2010-03-17 Rolf Bjarne Kvinge <RKvinge@novell.com>
[mono.git] / mcs / class / corlib / System / AppDomain.cs
1 //
2 // System.AppDomain.cs
3 //
4 // Authors:
5 //   Paolo Molaro (lupus@ximian.com)
6 //   Dietmar Maurer (dietmar@ximian.com)
7 //   Miguel de Icaza (miguel@ximian.com)
8 //   Gonzalo Paniagua (gonzalo@ximian.com)
9 //   Patrik Torstensson
10 //   Sebastien Pouliot (sebastien@ximian.com)
11 //
12 // (C) 2001, 2002 Ximian, Inc.  http://www.ximian.com
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 using System.Collections;
36 using System.Globalization;
37 using System.IO;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Threading;
41 using System.Runtime.CompilerServices;
42 using System.Runtime.InteropServices;
43 using System.Runtime.Remoting;
44 using System.Runtime.Remoting.Contexts;
45 using System.Runtime.Remoting.Channels;
46 using System.Runtime.Remoting.Messaging;
47 using System.Security;
48 using System.Security.Permissions;
49 using System.Security.Policy;
50 using System.Security.Principal;
51 using System.Configuration.Assemblies;
52
53 using System.Collections.Generic;
54 using System.Runtime.ConstrainedExecution;
55 using System.Text;
56
57 namespace System {
58
59         [ComVisible (true)]
60 #if !NET_2_1
61         [ComDefaultInterface (typeof (_AppDomain))]
62 #endif
63         [ClassInterface(ClassInterfaceType.None)]
64 #if NET_2_1
65         public sealed class AppDomain : MarshalByRefObject {
66 #else
67         public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory {
68 #endif
69         #pragma warning disable 169
70         #region Sync with object-internals.h
71                 IntPtr _mono_app_domain;
72                 #endregion
73         #pragma warning restore 169
74                 static string _process_guid;
75
76                 [ThreadStatic]
77                 static Hashtable type_resolve_in_progress;
78
79                 [ThreadStatic]
80                 static Hashtable assembly_resolve_in_progress;
81
82                 [ThreadStatic]
83                 static Hashtable assembly_resolve_in_progress_refonly;
84 #if !MOONLIGHT
85                 // CAS
86                 private Evidence _evidence;
87                 private PermissionSet _granted;
88
89                 // non-CAS
90                 private PrincipalPolicy _principalPolicy;
91
92                 [ThreadStatic]
93                 private static IPrincipal _principal;
94 #endif
95                 static AppDomain default_domain;
96
97                 private AppDomain ()
98                 {
99                 }
100
101                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
102                 private extern AppDomainSetup getSetup ();
103
104 #if NET_2_1
105                 internal
106 #endif
107                 AppDomainSetup SetupInformationNoCopy {
108                         get { return getSetup (); }
109                 }
110
111                 public AppDomainSetup SetupInformation {
112                         get {
113                                 AppDomainSetup setup = getSetup ();
114                                 return new AppDomainSetup (setup);
115                         }
116                 }
117
118 #if !NET_2_1
119                 [MonoTODO]
120                 public ApplicationTrust ApplicationTrust {
121                         get { throw new NotImplementedException (); }
122                 }
123 #endif
124 #if !MOONLIGHT
125                 public string BaseDirectory {
126                         get {
127                                 string path = SetupInformationNoCopy.ApplicationBase;
128                                 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
129                                         // we cannot divulge local file informations
130                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
131                                 }
132                                 return path;
133                         }
134                 }
135
136                 public string RelativeSearchPath {
137                         get {
138                                 string path = SetupInformationNoCopy.PrivateBinPath;
139                                 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
140                                         // we cannot divulge local file informations
141                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
142                                 }
143                                 return path;
144                         }
145                 }
146
147                 public string DynamicDirectory {
148                         get {
149                                 AppDomainSetup setup = SetupInformationNoCopy;
150                                 if (setup.DynamicBase == null)
151                                         return null;
152
153                                 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
154                                 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
155                                         // we cannot divulge local file informations
156                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
157                                 }
158                                 return path;
159                         }
160                 }
161
162                 public bool ShadowCopyFiles {
163                         get {
164                                 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
165                         }
166                 }
167 #endif
168
169                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
170                 private extern string getFriendlyName ();
171
172                 public string FriendlyName {
173                         get {
174                                 return getFriendlyName ();
175                         }
176                 }
177 #if !MOONLIGHT
178                 public Evidence Evidence {
179                         get {
180                                 // if the host (runtime) hasn't provided it's own evidence...
181                                 if (_evidence == null) {
182                                         // ... we will provide our own
183                                         lock (this) {
184                                                 // the executed assembly from the "default" appdomain
185                                                 // or null if we're not in the default appdomain or
186                                                 // if there is no entry assembly (embedded mono)
187                                                 Assembly a = Assembly.GetEntryAssembly ();
188                                                 if (a == null) {
189                                                         if (this == DefaultDomain)
190                                                                 // mono is embedded
191                                                                 return new Evidence ();
192                                                         else
193                                                                 _evidence = AppDomain.DefaultDomain.Evidence;
194                                                 } else {
195                                                         _evidence = Evidence.GetDefaultHostEvidence (a);
196                                                 }
197                                         }
198                                 }
199                                 return new Evidence (_evidence);        // return a copy
200                         }
201                 }
202
203                 internal IPrincipal DefaultPrincipal {
204                         get {
205                                 if (_principal == null) {
206                                         switch (_principalPolicy) {
207                                                 case PrincipalPolicy.UnauthenticatedPrincipal:
208                                                         _principal = new GenericPrincipal (
209                                                                 new GenericIdentity (String.Empty, String.Empty), null);
210                                                         break;
211                                                 case PrincipalPolicy.WindowsPrincipal:
212                                                         _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
213                                                         break;
214                                         }
215                                 }
216                                 return _principal; 
217                         }
218                 }
219
220                 // for AppDomain there is only an allowed (i.e. granted) set
221                 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
222                 internal PermissionSet GrantedPermissionSet {
223                         get { return _granted; }
224                 }
225 #endif
226                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
227                 private static extern AppDomain getCurDomain ();
228                 
229                 public static AppDomain CurrentDomain {
230                         get {
231                                 return getCurDomain ();
232                         }
233                 }
234
235                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
236                 private static extern AppDomain getRootDomain ();
237
238                 internal static AppDomain DefaultDomain {
239                         get {
240                                 if (default_domain == null) {
241                                         AppDomain rd = getRootDomain ();
242                                         if (rd == CurrentDomain)
243                                                 default_domain = rd;
244                                         else
245                                                 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
246                                 }
247                                 return default_domain;
248                         }
249                 }
250
251 #if !MOONLIGHT
252
253                 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
254                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
255                 public void AppendPrivatePath (string path)
256                 {
257                         if (path == null || path.Length == 0)
258                                 return;
259
260                         AppDomainSetup setup = SetupInformationNoCopy;
261
262                         string pp = setup.PrivateBinPath;
263                         if (pp == null || pp.Length == 0) {
264                                 setup.PrivateBinPath = path;
265                                 return;
266                         }
267
268                         pp = pp.Trim ();
269                         if (pp [pp.Length - 1] != Path.PathSeparator)
270                                 pp += Path.PathSeparator;
271
272                         setup.PrivateBinPath = pp + path;
273                 }
274
275                 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
276                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
277                 public void ClearPrivatePath ()
278                 {
279                         SetupInformationNoCopy.PrivateBinPath = String.Empty;
280                 }
281
282                 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
283                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
284                 public void ClearShadowCopyPath ()
285                 {
286                         SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
287                 }
288
289 #if !NET_2_1
290                 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
291                 {
292                         return Activator.CreateComInstanceFrom (assemblyName, typeName);
293                 }
294
295                 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
296                         byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
297                 {
298                         return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
299                 }
300 #endif
301
302                 public ObjectHandle CreateInstance (string assemblyName, string typeName)
303                 {
304                         if (assemblyName == null)
305                                 throw new ArgumentNullException ("assemblyName");
306
307                         return Activator.CreateInstance (assemblyName, typeName);
308                 }
309
310                 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
311                 {
312                         if (assemblyName == null)
313                                 throw new ArgumentNullException ("assemblyName");
314
315                         return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
316                 }
317
318 #if NET_4_0
319                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
320 #endif
321                 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
322                                                     Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
323                                                     Evidence securityAttributes)
324                 {
325                         if (assemblyName == null)
326                                 throw new ArgumentNullException ("assemblyName");
327
328                         return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
329                                 culture, activationAttributes, securityAttributes);
330                 }
331
332                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
333                 {
334                         ObjectHandle oh = CreateInstance (assemblyName, typeName);
335                         return (oh != null) ? oh.Unwrap () : null;
336                 }
337
338                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
339                 {
340                         ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
341                         return (oh != null) ? oh.Unwrap () : null;
342                 }
343
344 #if NET_4_0
345                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
346 #endif
347                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
348                                                        BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
349                                                        object[] activationAttributes, Evidence securityAttributes)
350                 {
351                         ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
352                                 culture, activationAttributes, securityAttributes);
353                         return (oh != null) ? oh.Unwrap () : null;
354                 }
355
356 #if NET_4_0
357                 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
358                                                     Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
359                 {
360                         if (assemblyName == null)
361                                 throw new ArgumentNullException ("assemblyName");
362
363                         return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
364                                 culture, activationAttributes, null);
365                 }
366                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
367                                                        BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
368                                                        object[] activationAttributes)
369                 {
370                         ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
371                                 culture, activationAttributes);
372                         return (oh != null) ? oh.Unwrap () : null;
373                 }
374
375                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
376                                                         BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
377                                                         object[] activationAttributes)
378                 {
379                         if (assemblyFile == null)
380                                 throw new ArgumentNullException ("assemblyFile");
381
382                         return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
383                                                              culture, activationAttributes, null);
384                 }
385
386                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
387                                                            BindingFlags bindingAttr, Binder binder, object[] args,
388                                                            CultureInfo culture, object[] activationAttributes)
389                 {
390                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
391                                 culture, activationAttributes);
392
393                         return (oh != null) ? oh.Unwrap () : null;
394                 }
395 #endif
396
397                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
398                 {
399                         if (assemblyFile == null)
400                                 throw new ArgumentNullException ("assemblyFile");
401
402                         return Activator.CreateInstanceFrom (assemblyFile, typeName);
403                 }
404
405                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
406                 {
407                         if (assemblyFile == null)
408                                 throw new ArgumentNullException ("assemblyFile");
409
410                         return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
411                 }
412
413 #if NET_4_0
414                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
415 #endif
416                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
417                                                         BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
418                                                         object[] activationAttributes, Evidence securityAttributes)
419                 {
420                         if (assemblyFile == null)
421                                 throw new ArgumentNullException ("assemblyFile");
422
423                         return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
424                                                              culture, activationAttributes, securityAttributes);
425                 }
426
427                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
428                 {
429                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
430                         return (oh != null) ? oh.Unwrap () : null;
431                 }
432
433                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
434                 {
435                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
436                         return (oh != null) ? oh.Unwrap () : null;
437                 }
438
439 #if NET_4_0
440                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
441 #endif
442                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
443                                                            BindingFlags bindingAttr, Binder binder, object[] args,
444                                                            CultureInfo culture, object[] activationAttributes,
445                                                            Evidence securityAttributes)
446                 {
447                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
448                                 culture, activationAttributes, securityAttributes);
449
450                         return (oh != null) ? oh.Unwrap () : null;
451                 }
452
453 #endif // !NET_2_1
454
455                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
456                 {
457                         return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
458                 }
459
460 #if NET_4_0
461                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
462 #endif
463                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
464                 {
465                         return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
466                 }
467
468                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
469                 {
470                         return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
471                 }
472
473 #if NET_4_0
474                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
475 #endif
476                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
477                                                               Evidence evidence)
478                 {
479                         return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
480                 }
481
482 #if NET_4_0
483                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
484 #endif
485                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
486                                                               PermissionSet requiredPermissions,
487                                                               PermissionSet optionalPermissions,
488                                                               PermissionSet refusedPermissions)
489                 {
490                         return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
491                                 refusedPermissions, false);
492                 }
493
494 #if NET_4_0
495                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
496 #endif
497                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
498                                                               PermissionSet requiredPermissions,
499                                                               PermissionSet optionalPermissions,
500                                                               PermissionSet refusedPermissions)
501                 {
502                         return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
503                                 refusedPermissions, false);
504                 }
505
506 #if NET_4_0
507                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
508 #endif
509                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
510                                                               PermissionSet requiredPermissions,
511                                                               PermissionSet optionalPermissions,
512                                                               PermissionSet refusedPermissions)
513                 {
514                         return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
515                                 refusedPermissions, false);
516                 }
517
518 #if NET_4_0
519                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
520 #endif
521                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
522                                                               Evidence evidence,
523                                                               PermissionSet requiredPermissions,
524                                                               PermissionSet optionalPermissions,
525                                                               PermissionSet refusedPermissions)
526                 {
527                         return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
528                                 refusedPermissions, false);
529                 }
530
531 #if NET_4_0
532                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
533 #endif
534                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
535                                                               Evidence evidence,
536                                                               PermissionSet requiredPermissions,
537                                                               PermissionSet optionalPermissions,
538                                                               PermissionSet refusedPermissions, bool isSynchronized)
539                 {
540                         if (name == null)
541                                 throw new ArgumentNullException ("name");
542                         ValidateAssemblyName (name.Name);
543
544                         // FIXME: examine all other parameters
545                         
546                         AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
547                         ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
548                         return ab;
549                 }
550
551                 // NET 3.5 method
552 #if NET_4_0
553                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
554 #endif
555                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
556                                                               Evidence evidence,
557                                                               PermissionSet requiredPermissions,
558                                                               PermissionSet optionalPermissions,
559                                                               PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
560                 {
561                         AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
562                         if (assemblyAttributes != null)
563                                 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
564                                         ab.SetCustomAttribute (cb);
565                                 }
566                         return ab;
567                 }
568
569                 // NET 3.5 method
570                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
571                         return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
572                 }
573
574                 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
575                 {
576                         return new AssemblyBuilder (name, null, access, true);
577                 }
578
579                 //
580                 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
581                 // so, when you call AppDomain.DoCallBack, that's a remote call
582                 //
583                 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
584                 {
585                         if (callBackDelegate != null)
586                                 callBackDelegate ();
587                 }
588
589                 public int ExecuteAssembly (string assemblyFile)
590                 {
591                         return ExecuteAssembly (assemblyFile, (Evidence)null, null);
592                 }
593
594 #if NET_4_0
595                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
596 #endif
597                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
598                 {
599                         return ExecuteAssembly (assemblyFile, assemblySecurity, null);
600                 }
601
602 #if NET_4_0
603                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
604 #endif
605                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
606                 {
607                         Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
608                         return ExecuteAssemblyInternal (a, args);
609                 }
610
611 #if NET_4_0
612                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
613 #endif
614                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
615                 {
616                         Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
617                         return ExecuteAssemblyInternal (a, args);
618                 }
619
620
621 #if NET_4_0
622                 public int ExecuteAssembly (string assemblyFile, string[] args)
623                 {
624                         Assembly a = Assembly.LoadFrom (assemblyFile, null);
625                         return ExecuteAssemblyInternal (a, args);
626                 }
627
628                 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
629                 {
630                         Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
631                         return ExecuteAssemblyInternal (a, args);
632                 }
633 #endif
634
635                 int ExecuteAssemblyInternal (Assembly a, string[] args)
636                 {
637                         if (a.EntryPoint == null)
638                                 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
639                         return ExecuteAssembly (a, args);
640                 }
641
642                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
643                 private extern int ExecuteAssembly (Assembly a, string[] args);
644                 
645                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
646                 private extern Assembly [] GetAssemblies (bool refOnly);
647
648                 public Assembly [] GetAssemblies ()
649                 {
650                         return GetAssemblies (false);
651                 }
652
653                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
654                 public extern object GetData (string name);
655
656                 public new Type GetType()
657                 {
658                         return base.GetType ();
659                 }
660
661                 public override object InitializeLifetimeService ()
662                 {
663                         return null;
664                 }
665
666                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667                 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
668
669                 public Assembly Load (AssemblyName assemblyRef)
670                 {
671                         return Load (assemblyRef, null);
672                 }
673
674                 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
675                 {
676                         if (assemblyRef == null)
677                                 throw new ArgumentNullException ("assemblyRef");
678
679                         Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
680                         if (result == null && throwOnError)
681                                 throw new FileNotFoundException (null, assemblyRef.Name);
682                         return result;
683                 }
684
685 #if NET_4_0
686                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
687 #endif
688                 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
689                 {
690                         if (assemblyRef == null)
691                                 throw new ArgumentNullException ("assemblyRef");
692
693                         if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
694                                 if (assemblyRef.CodeBase != null)
695                                         return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
696                                 else
697                                         throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
698                         }
699
700                         Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
701                         if (assembly != null)
702                                 return assembly;
703
704                         if (assemblyRef.CodeBase == null)
705                                 throw new FileNotFoundException (null, assemblyRef.Name);
706
707                         string cb = assemblyRef.CodeBase;
708                         if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
709                                 cb = new Mono.Security.Uri (cb).LocalPath;
710
711                         try {
712                                 assembly = Assembly.LoadFrom (cb, assemblySecurity);
713                         } catch {
714                                 throw new FileNotFoundException (null, assemblyRef.Name);
715                         }
716                         AssemblyName aname = assembly.GetName ();
717                         // Name, version, culture, publickeytoken. Anything else?
718                         if (assemblyRef.Name != aname.Name)
719                                 throw new FileNotFoundException (null, assemblyRef.Name);
720
721                         if (assemblyRef.Version != new Version () && assemblyRef.Version != aname.Version)
722                                 throw new FileNotFoundException (null, assemblyRef.Name);
723
724                         if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
725                                 throw new FileNotFoundException (null, assemblyRef.Name);
726
727                         byte [] pt = assemblyRef.GetPublicKeyToken ();
728                         if (pt != null) {
729                                 byte [] loaded_pt = aname.GetPublicKeyToken ();
730                                 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
731                                         throw new FileNotFoundException (null, assemblyRef.Name);
732                                 for (int i = pt.Length - 1; i >= 0; i--)
733                                         if (loaded_pt [i] != pt [i])
734                                                 throw new FileNotFoundException (null, assemblyRef.Name);
735                         }
736                         return assembly;
737                 }
738
739                 public Assembly Load (string assemblyString)
740                 {
741                         return Load (assemblyString, null, false);
742                 }
743
744 #if NET_4_0
745                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
746 #endif
747                 public Assembly Load (string assemblyString, Evidence assemblySecurity)
748                 {
749                         return Load (assemblyString, assemblySecurity, false);
750                 }
751                 
752                 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
753                 {
754                         if (assemblyString == null)
755                                 throw new ArgumentNullException ("assemblyString");
756                                 
757                         if (assemblyString.Length == 0)
758                                 throw new ArgumentException ("assemblyString cannot have zero length");
759
760                         Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
761                         if (assembly == null)
762                                 throw new FileNotFoundException (null, assemblyString);
763                         return assembly;
764                 }
765
766                 public Assembly Load (byte[] rawAssembly)
767                 {
768                         return Load (rawAssembly, null, null);
769                 }
770
771                 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
772                 {
773                         return Load (rawAssembly, rawSymbolStore, null);
774                 }
775
776                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
777                 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
778
779 #if NET_4_0
780                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
781 #endif
782                 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
783                 {
784                         return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
785                 }
786
787                 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
788                 {
789                         if (rawAssembly == null)
790                                 throw new ArgumentNullException ("rawAssembly");
791
792                         Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
793                         assembly.FromByteArray = true;
794                         return assembly;
795                 }
796 #if !MOONLIGHT
797 #if NET_4_0
798                 [Obsolete ("AppDomain policy levels are obsolete")]
799 #endif
800                 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
801                 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
802                 {
803                         if (domainPolicy == null)
804                                 throw new ArgumentNullException ("domainPolicy");
805                         if (_granted != null) {
806                                 throw new PolicyException (Locale.GetText (
807                                         "An AppDomain policy is already specified."));
808                         }
809                         if (IsFinalizingForUnload ())
810                                 throw new AppDomainUnloadedException ();
811
812                         PolicyStatement ps = domainPolicy.Resolve (_evidence);
813                         _granted = ps.PermissionSet;
814                 }
815
816                 [Obsolete ("Use AppDomainSetup.SetCachePath")]
817                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
818                 public void SetCachePath (string path)
819                 {
820                         SetupInformationNoCopy.CachePath = path;
821                 }
822
823                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
824                 public void SetPrincipalPolicy (PrincipalPolicy policy)
825                 {
826                         if (IsFinalizingForUnload ())
827                                 throw new AppDomainUnloadedException ();
828
829                         _principalPolicy = policy;
830                         _principal = null;
831                 }
832
833                 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
834                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
835                 public void SetShadowCopyFiles()
836                 {
837                         SetupInformationNoCopy.ShadowCopyFiles = "true";
838                 }
839
840                 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
841                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
842                 public void SetShadowCopyPath (string path)
843                 {
844                         SetupInformationNoCopy.ShadowCopyDirectories = path;
845                 }
846
847                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
848                 public void SetThreadPrincipal (IPrincipal principal)
849                 {
850                         if (principal == null)
851                                 throw new ArgumentNullException ("principal");
852                         if (_principal != null)
853                                 throw new PolicyException (Locale.GetText ("principal already present."));
854                         if (IsFinalizingForUnload ())
855                                 throw new AppDomainUnloadedException ();
856
857                         _principal = principal;
858                 }
859 #endif
860                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
861                 private static extern AppDomain InternalSetDomainByID (int domain_id);
862  
863                 // Changes the active domain and returns the old domain
864                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
865                 private static extern AppDomain InternalSetDomain (AppDomain context);
866
867                 // Notifies the runtime that this thread references 'domain'.
868                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
869                 internal static extern void InternalPushDomainRef (AppDomain domain);
870
871                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
872                 internal static extern void InternalPushDomainRefByID (int domain_id);
873
874                 // Undoes the effect of the last PushDomainRef call
875                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
876                 internal static extern void InternalPopDomainRef ();
877
878                 // Changes the active context and returns the old context
879                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
880                 internal static extern Context InternalSetContext (Context context);
881
882                 // Returns the current context
883                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
884                 internal static extern Context InternalGetContext ();
885
886                 // Returns the current context
887                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
888                 internal static extern Context InternalGetDefaultContext ();
889
890                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
891                 internal static extern string InternalGetProcessGuid (string newguid);
892
893                 // This method is handled specially by the runtime
894                 // It is the only managed method which is allowed to set the current
895                 // appdomain
896                 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
897                 {
898                         AppDomain current = CurrentDomain;
899                         bool pushed = false;
900
901                         try {
902                                 Exception exc;
903                                 InternalPushDomainRef (domain);
904                                 pushed = true;
905                                 InternalSetDomain (domain);
906                                 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
907                                 if (exc != null)
908                                         throw exc;
909                                 return o;
910                         }
911                         finally {
912                                 InternalSetDomain (current);
913                                 if (pushed)
914                                         InternalPopDomainRef ();
915                         }
916                 }
917
918                 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
919                 {
920                         AppDomain current = CurrentDomain;
921                         bool pushed = false;
922
923                         try {
924                                 Exception exc;
925                                 InternalPushDomainRefByID (domain_id);
926                                 pushed = true;
927                                 InternalSetDomainByID (domain_id);
928                                 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
929                                 if (exc != null)
930                                         throw exc;
931                                 return o;
932                         }
933                         finally {
934                                 InternalSetDomain (current);
935                                 if (pushed)
936                                         InternalPopDomainRef ();
937                         }
938                 }
939
940                 internal static String GetProcessGuid ()
941                 {
942                         if (_process_guid == null) {
943                                 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
944                         }
945                         return _process_guid;
946                 }
947
948 #if !MOONLIGHT
949
950                 public static AppDomain CreateDomain (string friendlyName)
951                 {
952                         return CreateDomain (friendlyName, null, null);
953                 }
954                 
955                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
956                 {
957                         return CreateDomain (friendlyName, securityInfo, null);
958                 }
959
960                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
961                 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
962
963                 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
964                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
965                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
966                 {
967                         if (friendlyName == null)
968                                 throw new System.ArgumentNullException ("friendlyName");
969
970                         AppDomain def = AppDomain.DefaultDomain;
971                         if (info == null) {
972                                 // if null, get default domain's SetupInformation       
973                                 if (def == null)
974                                         info = new AppDomainSetup ();   // we're default!
975                                 else
976                                         info = def.SetupInformation;
977                         }
978                         else
979                                 info = new AppDomainSetup (info);       // copy
980
981                         // todo: allow setup in the other domain
982                         if (def != null) {
983                                 if (!info.Equals (def.SetupInformation)) {
984                                         // If not specified use default domain's app base.
985                                         if (info.ApplicationBase == null)
986                                                 info.ApplicationBase = def.SetupInformation.ApplicationBase;
987                                         if (info.ConfigurationFile == null)
988                                                 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
989                                 }
990                         } else if (info.ConfigurationFile == null)
991                                 info.ConfigurationFile = "[I don't have a config file]";
992
993 #if !NET_2_1
994                         if (info.AppDomainInitializer != null) {
995                                 if (!info.AppDomainInitializer.Method.IsStatic)
996                                         throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
997                         }
998 #endif
999
1000                         info.SerializeNonPrimitives ();
1001
1002                         AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1003                         if (securityInfo == null) {
1004                                 // get default domain's Evidence (unless we're are the default!)
1005                                 if (def == null)
1006                                         ad._evidence = null;            // we'll get them later (GetEntryAssembly)
1007                                 else
1008                                         ad._evidence = def.Evidence;    // new (shallow) copy
1009                         }
1010                         else
1011                                 ad._evidence = new Evidence (securityInfo);     // copy
1012
1013 #if !NET_2_1
1014                         if (info.AppDomainInitializer != null) {
1015                                 Loader loader = new Loader (
1016                                         info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1017                                 ad.DoCallBack (loader.Load);
1018
1019                                 Initializer initializer = new Initializer (
1020                                         info.AppDomainInitializer,
1021                                         info.AppDomainInitializerArguments);
1022                                 ad.DoCallBack (initializer.Initialize);
1023                         }
1024 #endif
1025
1026                         return ad;
1027                 }
1028
1029 #if !NET_2_1
1030                 [Serializable]
1031                 class Loader {
1032
1033                         string assembly;
1034
1035                         public Loader (string assembly)
1036                         {
1037                                 this.assembly = assembly;
1038                         }
1039
1040                         public void Load ()
1041                         {
1042                                 Assembly.LoadFrom (assembly);
1043                         }
1044                 }
1045
1046                 [Serializable]
1047                 class Initializer {
1048
1049                         AppDomainInitializer initializer;
1050                         string [] arguments;
1051
1052                         public Initializer (AppDomainInitializer initializer, string [] arguments)
1053                         {
1054                                 this.initializer = initializer;
1055                                 this.arguments = arguments;
1056                         }
1057
1058                         public void Initialize ()
1059                         {
1060                                 initializer (arguments);
1061                         }
1062                 }
1063 #endif
1064
1065                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1066                                                       string appRelativeSearchPath, bool shadowCopyFiles)
1067                 {
1068                         return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1069                 }
1070                 
1071 #if !NET_2_1
1072                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1073                                                       PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1074                 {
1075                         if (info == null)
1076                                 throw new ArgumentNullException ("info");
1077
1078                         info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
1079                         return CreateDomain (friendlyName, securityInfo, info);         
1080                 }
1081 #endif
1082
1083                 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1084                 {
1085                         AppDomainSetup info = new AppDomainSetup ();
1086
1087                         info.ApplicationBase = appBasePath;
1088                         info.PrivateBinPath = appRelativeSearchPath;
1089
1090                         if (shadowCopyFiles)
1091                                 info.ShadowCopyFiles = "true";
1092                         else
1093                                 info.ShadowCopyFiles = "false";
1094
1095                         return info;
1096                 }
1097 #endif // !NET_2_1
1098
1099                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1100                 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1101
1102                 public bool IsFinalizingForUnload()
1103                 {
1104                         return InternalIsFinalizingForUnload (getDomainID ());
1105                 }
1106
1107                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1108                 static extern void InternalUnload (int domain_id);
1109
1110                 // We do this because if the domain is a transparant proxy this
1111                 // will still return the correct domain id.
1112                 private int getDomainID ()
1113                 {
1114                         return Thread.GetDomainID ();
1115                 }
1116
1117                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1118                 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1119                 public static void Unload (AppDomain domain)
1120                 {
1121                         if (domain == null)
1122                                 throw new ArgumentNullException ("domain");
1123
1124                         InternalUnload (domain.getDomainID());
1125                 }
1126
1127                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1128                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1129                 public extern void SetData (string name, object data);
1130
1131                 [MonoLimitation ("The permission field is ignored")]
1132                 public void SetData (string name, object data, IPermission permission)
1133                 {
1134                         SetData (name, data);
1135                 }
1136
1137 #if !NET_2_1
1138                 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1139                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1140                 public void SetDynamicBase (string path)
1141                 {
1142                         SetupInformationNoCopy.DynamicBase = path;
1143                 }
1144 #endif // !NET_2_1
1145
1146                 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1147                         + " because it does not provide a stable Id when managed"
1148                         + " threads are running on fibers (aka lightweight"
1149                         + " threads). To get a stable identifier for a managed"
1150                         + " thread, use the ManagedThreadId property on Thread.'")]
1151                 public static int GetCurrentThreadId ()
1152                 {
1153                         return Thread.CurrentThreadId;
1154                 }
1155
1156                 public override string ToString ()
1157                 {
1158 #if !MOONLIGHT
1159                         return getFriendlyName ();
1160 #else
1161                         StringBuilder sb = new StringBuilder ("Name:");
1162                         sb.AppendLine (FriendlyName);
1163                         sb.AppendLine ("There are no context policies.");
1164                         return sb.ToString ();
1165 #endif
1166                 }
1167
1168                 private static void ValidateAssemblyName (string name)
1169                 {
1170                         if (name == null || name.Length == 0)
1171                                 throw new ArgumentException ("The Name of " +
1172                                         "AssemblyName cannot be null or a " +
1173                                         "zero-length string.");
1174
1175                         bool isValid = true;
1176
1177                         for (int i = 0; i < name.Length; i++) {
1178                                 char c = name [i];
1179
1180                                 // do not allow leading whitespace
1181                                 if (i == 0 && char.IsWhiteSpace (c)) {
1182                                         isValid = false;
1183                                         break;
1184                                 }
1185
1186                                 // do not allow /,\ or : in name
1187                                 if (c == '/' || c == '\\' || c == ':') {
1188                                         isValid = false;
1189                                         break;
1190                                 }
1191                         }
1192
1193                         if (!isValid)
1194                                 throw new ArgumentException ("The Name of " +
1195                                         "AssemblyName cannot start with " +
1196                                         "whitespace, or contain '/', '\\' " +
1197                                         " or ':'.");
1198                 }
1199
1200                 // The following methods are called from the runtime. Don't change signatures.
1201 #pragma warning disable 169             
1202                 private void DoAssemblyLoad (Assembly assembly)
1203                 {
1204                         if (AssemblyLoad == null)
1205                                 return;
1206
1207                         AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1208                 }
1209
1210                 private Assembly DoAssemblyResolve (string name, bool refonly)
1211                 {
1212                         ResolveEventHandler del;
1213 #if !NET_2_1
1214                         if (refonly)
1215                                 del = ReflectionOnlyAssemblyResolve;
1216                         else
1217                                 del = AssemblyResolve;
1218 #else
1219                         del = AssemblyResolve;
1220 #endif
1221                         if (del == null)
1222                                 return null;
1223                         
1224                         /* Prevent infinite recursion */
1225                         Hashtable ht;
1226                         if (refonly) {
1227                                 ht = assembly_resolve_in_progress_refonly;
1228                                 if (ht == null) {
1229                                         ht = new Hashtable ();
1230                                         assembly_resolve_in_progress_refonly = ht;
1231                                 }
1232                         } else {
1233                                 ht = assembly_resolve_in_progress;
1234                                 if (ht == null) {
1235                                         ht = new Hashtable ();
1236                                         assembly_resolve_in_progress = ht;
1237                                 }
1238                         }
1239
1240                         string s = (string) ht [name];
1241                         if (s != null)
1242                                 return null;
1243                         ht [name] = name;
1244                         try {
1245                                 Delegate[] invocation_list = del.GetInvocationList ();
1246
1247                                 foreach (Delegate eh in invocation_list) {
1248                                         ResolveEventHandler handler = (ResolveEventHandler) eh;
1249                                         Assembly assembly = handler (this, new ResolveEventArgs (name));
1250                                         if (assembly != null)
1251                                                 return assembly;
1252                                 }
1253                                 return null;
1254                         }
1255                         finally {
1256                                 ht.Remove (name);
1257                         }
1258                 }
1259
1260                 internal Assembly DoTypeResolve (Object name_or_tb)
1261                 {
1262                         if (TypeResolve == null)
1263                                 return null;
1264
1265                         string name;
1266
1267                         if (name_or_tb is TypeBuilder)
1268                                 name = ((TypeBuilder) name_or_tb).FullName;
1269                         else
1270                                 name = (string) name_or_tb;
1271
1272                         /* Prevent infinite recursion */
1273                         Hashtable ht = type_resolve_in_progress;
1274                         if (ht == null) {
1275                                 ht = new Hashtable ();
1276                                 type_resolve_in_progress = ht;
1277                         }
1278
1279                         if (ht.Contains (name))
1280                                 return null;
1281                         else
1282                                 ht [name] = name;
1283
1284                         try {
1285                                 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1286                                         ResolveEventHandler eh = (ResolveEventHandler) d;
1287                                         Assembly assembly = eh (this, new ResolveEventArgs (name));
1288                                         if (assembly != null)
1289                                                 return assembly;
1290                                 }
1291                                 return null;
1292                         }
1293                         finally {
1294                                 ht.Remove (name);
1295                         }
1296                 }
1297
1298                 private void DoDomainUnload ()
1299                 {
1300                         if (DomainUnload != null)
1301                                 DomainUnload(this, null);
1302                 }
1303
1304 #if !NET_2_1
1305                 internal byte[] GetMarshalledDomainObjRef ()
1306                 {
1307                         ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1308                         return CADSerializer.SerializeObject (oref).GetBuffer();
1309                 }
1310 #endif
1311                 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1312                                                       out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1313                 {
1314                         IMessage reqDomMsg;
1315
1316                         if (null != arrRequest)
1317                                 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1318                         else
1319                                 reqDomMsg = new MethodCall (cadMsg);
1320
1321                         IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1322
1323                         cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1324                         if (null == cadMrm) {
1325                                 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1326                         } 
1327                         else
1328                                 arrResponse = null;
1329                 }
1330
1331 #pragma warning restore 169
1332
1333                 // End of methods called from the runtime
1334                 
1335                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1336                 public event AssemblyLoadEventHandler AssemblyLoad;
1337
1338                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1339                 public event ResolveEventHandler AssemblyResolve;
1340
1341                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1342                 public event EventHandler DomainUnload;
1343
1344                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1345                 public event EventHandler ProcessExit;
1346
1347                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1348                 public event ResolveEventHandler ResourceResolve;
1349
1350                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1351                 public event ResolveEventHandler TypeResolve;
1352
1353                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1354                 public event UnhandledExceptionEventHandler UnhandledException;
1355
1356 #if NET_4_0 || BOOTSTRAP_NET_4_0
1357                 [MonoTODO]
1358                 public bool IsHomogenous {
1359                         get { return true; }
1360                 }
1361 #endif
1362
1363         #pragma warning disable 649
1364                 private AppDomainManager _domain_manager;
1365         #pragma warning restore 649
1366
1367                 // default is null
1368                 public AppDomainManager DomainManager {
1369                         get { return _domain_manager; }
1370                 }
1371
1372 #if (!MOONLIGHT)
1373
1374                 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1375
1376         #pragma warning disable 649
1377                 private ActivationContext _activation;
1378                 private ApplicationIdentity _applicationIdentity;
1379         #pragma warning restore 649
1380
1381                 // properties
1382
1383                 public ActivationContext ActivationContext {
1384                         get { return _activation; }
1385                 }
1386
1387                 public ApplicationIdentity ApplicationIdentity {
1388                         get { return _applicationIdentity; }
1389                 }
1390
1391                 public int Id {
1392                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1393                         get { return getDomainID (); }
1394                 }
1395
1396                 // methods
1397
1398                 [MonoTODO ("This routine only returns the parameter currently")]
1399                 [ComVisible (false)]
1400                 public string ApplyPolicy (string assemblyName)
1401                 {
1402                         if (assemblyName == null)
1403                                 throw new ArgumentNullException ("assemblyName");
1404                         if (assemblyName.Length == 0) // String.Empty
1405                                 throw new ArgumentException ("assemblyName");
1406                         return assemblyName;
1407                 }
1408
1409                 // static methods
1410
1411                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1412                         string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1413                 {
1414                         AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1415
1416                         info.AppDomainInitializerArguments = adInitArgs;
1417                         info.AppDomainInitializer = adInit;
1418
1419                         return CreateDomain (friendlyName, securityInfo, info);
1420                 }
1421
1422                 public int ExecuteAssemblyByName (string assemblyName)
1423                 {
1424                         return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1425                 }
1426
1427 #if NET_4_0
1428                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1429 #endif
1430                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1431                 {
1432                         return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1433                 }
1434
1435 #if NET_4_0
1436                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1437 #endif
1438                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1439                 {
1440                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1441
1442                         return ExecuteAssemblyInternal (a, args);
1443                 }
1444
1445 #if NET_4_0
1446                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1447 #endif
1448                 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1449                 {
1450                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1451
1452                         return ExecuteAssemblyInternal (a, args);
1453                 }
1454
1455 #if NET_4_0
1456                 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1457                 {
1458                         Assembly a = Assembly.Load (assemblyName, null);
1459
1460                         return ExecuteAssemblyInternal (a, args);
1461                 }
1462
1463                 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1464                 {
1465                         Assembly a = Assembly.Load (assemblyName, null);
1466
1467                         return ExecuteAssemblyInternal (a, args);
1468                 }
1469 #endif
1470
1471                 public bool IsDefaultAppDomain ()
1472                 {
1473                         return Object.ReferenceEquals (this, DefaultDomain);
1474                 }
1475
1476                 public Assembly[] ReflectionOnlyGetAssemblies ()
1477                 {
1478                         return GetAssemblies (true);
1479                 }
1480 #endif
1481
1482 #if MOONLIGHT
1483                 public int ExecuteAssemblyByName (string assemblyName)
1484                 {
1485                         // critical code in SL that we're not calling in ML
1486                         throw new NotImplementedException ();
1487                 }
1488 #endif
1489
1490 #if !NET_2_1
1491                 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1492                 {
1493                         throw new NotImplementedException ();
1494                 }
1495
1496                 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1497                 {
1498                         throw new NotImplementedException ();
1499                 }
1500
1501                 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1502                 {
1503                         throw new NotImplementedException ();
1504                 }
1505
1506                 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1507                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1508                 {
1509                         throw new NotImplementedException ();
1510                 }
1511 #endif
1512
1513 #if NET_4_0 || (NET_2_1 && !MONOTOUCH)
1514                 [MonoTODO ("Currently always returns null")]
1515                 public bool? IsCompatibilitySwitchSet (string value)
1516                 {
1517                         return null;
1518                 }
1519 #endif
1520         }
1521 }