881b64d99a9b640cab4661c177b8eee3ecc81b51
[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
227 #if NET_4_0
228                 public PermissionSet PermissionSet {
229                         get { return this.GrantedPermissionSet; }
230                 }
231 #endif
232
233                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
234                 private static extern AppDomain getCurDomain ();
235                 
236                 public static AppDomain CurrentDomain {
237                         get {
238                                 return getCurDomain ();
239                         }
240                 }
241
242                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
243                 private static extern AppDomain getRootDomain ();
244
245                 internal static AppDomain DefaultDomain {
246                         get {
247                                 if (default_domain == null) {
248                                         AppDomain rd = getRootDomain ();
249                                         if (rd == CurrentDomain)
250                                                 default_domain = rd;
251                                         else
252                                                 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
253                                 }
254                                 return default_domain;
255                         }
256                 }
257
258 #if !MOONLIGHT
259
260                 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
261                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
262                 public void AppendPrivatePath (string path)
263                 {
264                         if (path == null || path.Length == 0)
265                                 return;
266
267                         AppDomainSetup setup = SetupInformationNoCopy;
268
269                         string pp = setup.PrivateBinPath;
270                         if (pp == null || pp.Length == 0) {
271                                 setup.PrivateBinPath = path;
272                                 return;
273                         }
274
275                         pp = pp.Trim ();
276                         if (pp [pp.Length - 1] != Path.PathSeparator)
277                                 pp += Path.PathSeparator;
278
279                         setup.PrivateBinPath = pp + path;
280                 }
281
282                 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
283                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
284                 public void ClearPrivatePath ()
285                 {
286                         SetupInformationNoCopy.PrivateBinPath = String.Empty;
287                 }
288
289                 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
290                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
291                 public void ClearShadowCopyPath ()
292                 {
293                         SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
294                 }
295
296 #if !NET_2_1
297                 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
298                 {
299                         return Activator.CreateComInstanceFrom (assemblyName, typeName);
300                 }
301
302                 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
303                         byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
304                 {
305                         return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
306                 }
307 #endif
308
309                 public ObjectHandle CreateInstance (string assemblyName, string typeName)
310                 {
311                         if (assemblyName == null)
312                                 throw new ArgumentNullException ("assemblyName");
313
314                         return Activator.CreateInstance (assemblyName, typeName);
315                 }
316
317                 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
318                 {
319                         if (assemblyName == null)
320                                 throw new ArgumentNullException ("assemblyName");
321
322                         return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
323                 }
324
325 #if NET_4_0
326                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
327 #endif
328                 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
329                                                     Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
330                                                     Evidence securityAttributes)
331                 {
332                         if (assemblyName == null)
333                                 throw new ArgumentNullException ("assemblyName");
334
335                         return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
336                                 culture, activationAttributes, securityAttributes);
337                 }
338
339                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
340                 {
341                         ObjectHandle oh = CreateInstance (assemblyName, typeName);
342                         return (oh != null) ? oh.Unwrap () : null;
343                 }
344
345                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
346                 {
347                         ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
348                         return (oh != null) ? oh.Unwrap () : null;
349                 }
350
351 #if NET_4_0
352                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
353 #endif
354                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
355                                                        BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
356                                                        object[] activationAttributes, Evidence securityAttributes)
357                 {
358                         ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
359                                 culture, activationAttributes, securityAttributes);
360                         return (oh != null) ? oh.Unwrap () : null;
361                 }
362
363 #if NET_4_0
364                 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
365                                                     Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
366                 {
367                         if (assemblyName == null)
368                                 throw new ArgumentNullException ("assemblyName");
369
370                         return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
371                                 culture, activationAttributes, null);
372                 }
373                 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
374                                                        BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
375                                                        object[] activationAttributes)
376                 {
377                         ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
378                                 culture, activationAttributes);
379                         return (oh != null) ? oh.Unwrap () : null;
380                 }
381
382                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
383                                                         BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
384                                                         object[] activationAttributes)
385                 {
386                         if (assemblyFile == null)
387                                 throw new ArgumentNullException ("assemblyFile");
388
389                         return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
390                                                              culture, activationAttributes, null);
391                 }
392
393                 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
394                                                            BindingFlags bindingAttr, Binder binder, object[] args,
395                                                            CultureInfo culture, object[] activationAttributes)
396                 {
397                         ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
398                                 culture, activationAttributes);
399
400                         return (oh != null) ? oh.Unwrap () : null;
401                 }
402 #endif
403
404                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
405                 {
406                         if (assemblyFile == null)
407                                 throw new ArgumentNullException ("assemblyFile");
408
409                         return Activator.CreateInstanceFrom (assemblyFile, typeName);
410                 }
411
412                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
413                 {
414                         if (assemblyFile == null)
415                                 throw new ArgumentNullException ("assemblyFile");
416
417                         return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
418                 }
419
420 #if NET_4_0
421                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
422 #endif
423                 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
424                                                         BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
425                                                         object[] activationAttributes, Evidence securityAttributes)
426                 {
427                         if (assemblyFile == null)
428                                 throw new ArgumentNullException ("assemblyFile");
429
430                         return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
431                                                              culture, activationAttributes, securityAttributes);
432                 }
433
434                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
435                 {
436                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
437                         return (oh != null) ? oh.Unwrap () : null;
438                 }
439
440                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
441                 {
442                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
443                         return (oh != null) ? oh.Unwrap () : null;
444                 }
445
446 #if NET_4_0
447                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
448 #endif
449                 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
450                                                            BindingFlags bindingAttr, Binder binder, object[] args,
451                                                            CultureInfo culture, object[] activationAttributes,
452                                                            Evidence securityAttributes)
453                 {
454                         ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
455                                 culture, activationAttributes, securityAttributes);
456
457                         return (oh != null) ? oh.Unwrap () : null;
458                 }
459
460 #endif // !NET_2_1
461
462                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
463                 {
464                         return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
465                 }
466
467 #if NET_4_0
468                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
469 #endif
470                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
471                 {
472                         return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
473                 }
474
475                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
476                 {
477                         return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
478                 }
479
480 #if NET_4_0
481                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
482 #endif
483                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
484                                                               Evidence evidence)
485                 {
486                         return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
487                 }
488
489 #if NET_4_0
490                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
491 #endif
492                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
493                                                               PermissionSet requiredPermissions,
494                                                               PermissionSet optionalPermissions,
495                                                               PermissionSet refusedPermissions)
496                 {
497                         return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
498                                 refusedPermissions, false);
499                 }
500
501 #if NET_4_0
502                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
503 #endif
504                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
505                                                               PermissionSet requiredPermissions,
506                                                               PermissionSet optionalPermissions,
507                                                               PermissionSet refusedPermissions)
508                 {
509                         return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
510                                 refusedPermissions, false);
511                 }
512
513 #if NET_4_0
514                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
515 #endif
516                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
517                                                               PermissionSet requiredPermissions,
518                                                               PermissionSet optionalPermissions,
519                                                               PermissionSet refusedPermissions)
520                 {
521                         return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
522                                 refusedPermissions, false);
523                 }
524
525 #if NET_4_0
526                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
527 #endif
528                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
529                                                               Evidence evidence,
530                                                               PermissionSet requiredPermissions,
531                                                               PermissionSet optionalPermissions,
532                                                               PermissionSet refusedPermissions)
533                 {
534                         return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
535                                 refusedPermissions, false);
536                 }
537
538 #if NET_4_0
539                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
540 #endif
541                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
542                                                               Evidence evidence,
543                                                               PermissionSet requiredPermissions,
544                                                               PermissionSet optionalPermissions,
545                                                               PermissionSet refusedPermissions, bool isSynchronized)
546                 {
547                         if (name == null)
548                                 throw new ArgumentNullException ("name");
549                         ValidateAssemblyName (name.Name);
550
551                         // FIXME: examine all other parameters
552                         
553                         AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
554                         ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
555                         return ab;
556                 }
557
558                 // NET 3.5 method
559 #if NET_4_0
560                 [Obsolete ("Declarative security for assembly level is no longer enforced")]
561 #endif
562                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
563                                                               Evidence evidence,
564                                                               PermissionSet requiredPermissions,
565                                                               PermissionSet optionalPermissions,
566                                                               PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
567                 {
568                         AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
569                         if (assemblyAttributes != null)
570                                 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
571                                         ab.SetCustomAttribute (cb);
572                                 }
573                         return ab;
574                 }
575
576                 // NET 3.5 method
577                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
578                 {
579                         return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
580                 }
581
582 #if NET_4_0
583                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
584                 {
585                         return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
586                 }
587
588                 [MonoLimitation ("The argument securityContextSource is ignored")]
589                 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
590                 {
591                         return DefineDynamicAssembly (name, access, assemblyAttributes);
592                 }
593 #endif
594
595                 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
596                 {
597                         return new AssemblyBuilder (name, null, access, true);
598                 }
599
600                 //
601                 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
602                 // so, when you call AppDomain.DoCallBack, that's a remote call
603                 //
604                 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
605                 {
606                         if (callBackDelegate != null)
607                                 callBackDelegate ();
608                 }
609
610                 public int ExecuteAssembly (string assemblyFile)
611                 {
612                         return ExecuteAssembly (assemblyFile, (Evidence)null, null);
613                 }
614
615 #if NET_4_0
616                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
617 #endif
618                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
619                 {
620                         return ExecuteAssembly (assemblyFile, assemblySecurity, null);
621                 }
622
623 #if NET_4_0
624                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
625 #endif
626                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
627                 {
628                         Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
629                         return ExecuteAssemblyInternal (a, args);
630                 }
631
632 #if NET_4_0
633                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
634 #endif
635                 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
636                 {
637                         Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
638                         return ExecuteAssemblyInternal (a, args);
639                 }
640
641
642 #if NET_4_0
643                 public int ExecuteAssembly (string assemblyFile, string[] args)
644                 {
645                         Assembly a = Assembly.LoadFrom (assemblyFile, null);
646                         return ExecuteAssemblyInternal (a, args);
647                 }
648
649                 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
650                 {
651                         Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
652                         return ExecuteAssemblyInternal (a, args);
653                 }
654 #endif
655
656                 int ExecuteAssemblyInternal (Assembly a, string[] args)
657                 {
658                         if (a.EntryPoint == null)
659                                 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
660                         return ExecuteAssembly (a, args);
661                 }
662
663                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
664                 private extern int ExecuteAssembly (Assembly a, string[] args);
665                 
666                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667                 private extern Assembly [] GetAssemblies (bool refOnly);
668
669                 public Assembly [] GetAssemblies ()
670                 {
671                         return GetAssemblies (false);
672                 }
673
674                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
675                 public extern object GetData (string name);
676
677                 public new Type GetType()
678                 {
679                         return base.GetType ();
680                 }
681
682                 public override object InitializeLifetimeService ()
683                 {
684                         return null;
685                 }
686
687                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
688                 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
689
690                 public Assembly Load (AssemblyName assemblyRef)
691                 {
692                         return Load (assemblyRef, null);
693                 }
694
695                 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
696                 {
697                         if (assemblyRef == null)
698                                 throw new ArgumentNullException ("assemblyRef");
699
700                         Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
701                         if (result == null && throwOnError)
702                                 throw new FileNotFoundException (null, assemblyRef.Name);
703                         return result;
704                 }
705
706 #if NET_4_0
707                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
708 #endif
709                 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
710                 {
711                         if (assemblyRef == null)
712                                 throw new ArgumentNullException ("assemblyRef");
713
714                         if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
715                                 if (assemblyRef.CodeBase != null)
716                                         return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
717                                 else
718                                         throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
719                         }
720
721                         Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
722                         if (assembly != null)
723                                 return assembly;
724
725                         if (assemblyRef.CodeBase == null)
726                                 throw new FileNotFoundException (null, assemblyRef.Name);
727
728                         string cb = assemblyRef.CodeBase;
729                         if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
730                                 cb = new Mono.Security.Uri (cb).LocalPath;
731
732                         try {
733                                 assembly = Assembly.LoadFrom (cb, assemblySecurity);
734                         } catch {
735                                 throw new FileNotFoundException (null, assemblyRef.Name);
736                         }
737                         AssemblyName aname = assembly.GetName ();
738                         // Name, version, culture, publickeytoken. Anything else?
739                         if (assemblyRef.Name != aname.Name)
740                                 throw new FileNotFoundException (null, assemblyRef.Name);
741
742                         if (assemblyRef.Version != new Version () && assemblyRef.Version != aname.Version)
743                                 throw new FileNotFoundException (null, assemblyRef.Name);
744
745                         if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
746                                 throw new FileNotFoundException (null, assemblyRef.Name);
747
748                         byte [] pt = assemblyRef.GetPublicKeyToken ();
749                         if (pt != null) {
750                                 byte [] loaded_pt = aname.GetPublicKeyToken ();
751                                 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
752                                         throw new FileNotFoundException (null, assemblyRef.Name);
753                                 for (int i = pt.Length - 1; i >= 0; i--)
754                                         if (loaded_pt [i] != pt [i])
755                                                 throw new FileNotFoundException (null, assemblyRef.Name);
756                         }
757                         return assembly;
758                 }
759
760                 public Assembly Load (string assemblyString)
761                 {
762                         return Load (assemblyString, null, false);
763                 }
764
765 #if NET_4_0
766                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
767 #endif
768                 public Assembly Load (string assemblyString, Evidence assemblySecurity)
769                 {
770                         return Load (assemblyString, assemblySecurity, false);
771                 }
772                 
773                 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
774                 {
775                         if (assemblyString == null)
776                                 throw new ArgumentNullException ("assemblyString");
777                                 
778                         if (assemblyString.Length == 0)
779                                 throw new ArgumentException ("assemblyString cannot have zero length");
780
781                         Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
782                         if (assembly == null)
783                                 throw new FileNotFoundException (null, assemblyString);
784                         return assembly;
785                 }
786
787                 public Assembly Load (byte[] rawAssembly)
788                 {
789                         return Load (rawAssembly, null, null);
790                 }
791
792                 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
793                 {
794                         return Load (rawAssembly, rawSymbolStore, null);
795                 }
796
797                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
798                 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
799
800 #if NET_4_0
801                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
802 #endif
803                 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
804                 {
805                         return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
806                 }
807
808                 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
809                 {
810                         if (rawAssembly == null)
811                                 throw new ArgumentNullException ("rawAssembly");
812
813                         Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
814                         assembly.FromByteArray = true;
815                         return assembly;
816                 }
817 #if !MOONLIGHT
818 #if NET_4_0
819                 [Obsolete ("AppDomain policy levels are obsolete")]
820 #endif
821                 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
822                 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
823                 {
824                         if (domainPolicy == null)
825                                 throw new ArgumentNullException ("domainPolicy");
826                         if (_granted != null) {
827                                 throw new PolicyException (Locale.GetText (
828                                         "An AppDomain policy is already specified."));
829                         }
830                         if (IsFinalizingForUnload ())
831                                 throw new AppDomainUnloadedException ();
832
833                         PolicyStatement ps = domainPolicy.Resolve (_evidence);
834                         _granted = ps.PermissionSet;
835                 }
836
837                 [Obsolete ("Use AppDomainSetup.SetCachePath")]
838                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
839                 public void SetCachePath (string path)
840                 {
841                         SetupInformationNoCopy.CachePath = path;
842                 }
843
844                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
845                 public void SetPrincipalPolicy (PrincipalPolicy policy)
846                 {
847                         if (IsFinalizingForUnload ())
848                                 throw new AppDomainUnloadedException ();
849
850                         _principalPolicy = policy;
851                         _principal = null;
852                 }
853
854                 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
855                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
856                 public void SetShadowCopyFiles()
857                 {
858                         SetupInformationNoCopy.ShadowCopyFiles = "true";
859                 }
860
861                 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
862                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
863                 public void SetShadowCopyPath (string path)
864                 {
865                         SetupInformationNoCopy.ShadowCopyDirectories = path;
866                 }
867
868                 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
869                 public void SetThreadPrincipal (IPrincipal principal)
870                 {
871                         if (principal == null)
872                                 throw new ArgumentNullException ("principal");
873                         if (_principal != null)
874                                 throw new PolicyException (Locale.GetText ("principal already present."));
875                         if (IsFinalizingForUnload ())
876                                 throw new AppDomainUnloadedException ();
877
878                         _principal = principal;
879                 }
880 #endif
881                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
882                 private static extern AppDomain InternalSetDomainByID (int domain_id);
883  
884                 // Changes the active domain and returns the old domain
885                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
886                 private static extern AppDomain InternalSetDomain (AppDomain context);
887
888                 // Notifies the runtime that this thread references 'domain'.
889                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
890                 internal static extern void InternalPushDomainRef (AppDomain domain);
891
892                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
893                 internal static extern void InternalPushDomainRefByID (int domain_id);
894
895                 // Undoes the effect of the last PushDomainRef call
896                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
897                 internal static extern void InternalPopDomainRef ();
898
899                 // Changes the active context and returns the old context
900                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
901                 internal static extern Context InternalSetContext (Context context);
902
903                 // Returns the current context
904                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
905                 internal static extern Context InternalGetContext ();
906
907                 // Returns the current context
908                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
909                 internal static extern Context InternalGetDefaultContext ();
910
911                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
912                 internal static extern string InternalGetProcessGuid (string newguid);
913
914                 // This method is handled specially by the runtime
915                 // It is the only managed method which is allowed to set the current
916                 // appdomain
917                 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
918                 {
919                         AppDomain current = CurrentDomain;
920                         bool pushed = false;
921
922                         try {
923                                 Exception exc;
924                                 InternalPushDomainRef (domain);
925                                 pushed = true;
926                                 InternalSetDomain (domain);
927                                 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
928                                 if (exc != null)
929                                         throw exc;
930                                 return o;
931                         }
932                         finally {
933                                 InternalSetDomain (current);
934                                 if (pushed)
935                                         InternalPopDomainRef ();
936                         }
937                 }
938
939                 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
940                 {
941                         AppDomain current = CurrentDomain;
942                         bool pushed = false;
943
944                         try {
945                                 Exception exc;
946                                 InternalPushDomainRefByID (domain_id);
947                                 pushed = true;
948                                 InternalSetDomainByID (domain_id);
949                                 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
950                                 if (exc != null)
951                                         throw exc;
952                                 return o;
953                         }
954                         finally {
955                                 InternalSetDomain (current);
956                                 if (pushed)
957                                         InternalPopDomainRef ();
958                         }
959                 }
960
961                 internal static String GetProcessGuid ()
962                 {
963                         if (_process_guid == null) {
964                                 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
965                         }
966                         return _process_guid;
967                 }
968
969 #if !MOONLIGHT
970
971                 public static AppDomain CreateDomain (string friendlyName)
972                 {
973                         return CreateDomain (friendlyName, null, null);
974                 }
975                 
976                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
977                 {
978                         return CreateDomain (friendlyName, securityInfo, null);
979                 }
980
981                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
982                 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
983
984                 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
985                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
986                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
987                 {
988                         if (friendlyName == null)
989                                 throw new System.ArgumentNullException ("friendlyName");
990
991                         AppDomain def = AppDomain.DefaultDomain;
992                         if (info == null) {
993                                 // if null, get default domain's SetupInformation       
994                                 if (def == null)
995                                         info = new AppDomainSetup ();   // we're default!
996                                 else
997                                         info = def.SetupInformation;
998                         }
999                         else
1000                                 info = new AppDomainSetup (info);       // copy
1001
1002                         // todo: allow setup in the other domain
1003                         if (def != null) {
1004                                 if (!info.Equals (def.SetupInformation)) {
1005                                         // If not specified use default domain's app base.
1006                                         if (info.ApplicationBase == null)
1007                                                 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1008                                         if (info.ConfigurationFile == null)
1009                                                 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1010                                 }
1011                         } else if (info.ConfigurationFile == null)
1012                                 info.ConfigurationFile = "[I don't have a config file]";
1013
1014 #if !NET_2_1
1015                         if (info.AppDomainInitializer != null) {
1016                                 if (!info.AppDomainInitializer.Method.IsStatic)
1017                                         throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1018                         }
1019 #endif
1020
1021                         info.SerializeNonPrimitives ();
1022
1023                         AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1024                         if (securityInfo == null) {
1025                                 // get default domain's Evidence (unless we're are the default!)
1026                                 if (def == null)
1027                                         ad._evidence = null;            // we'll get them later (GetEntryAssembly)
1028                                 else
1029                                         ad._evidence = def.Evidence;    // new (shallow) copy
1030                         }
1031                         else
1032                                 ad._evidence = new Evidence (securityInfo);     // copy
1033
1034 #if !NET_2_1
1035                         if (info.AppDomainInitializer != null) {
1036                                 Loader loader = new Loader (
1037                                         info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1038                                 ad.DoCallBack (loader.Load);
1039
1040                                 Initializer initializer = new Initializer (
1041                                         info.AppDomainInitializer,
1042                                         info.AppDomainInitializerArguments);
1043                                 ad.DoCallBack (initializer.Initialize);
1044                         }
1045 #endif
1046
1047                         return ad;
1048                 }
1049
1050 #if !NET_2_1
1051                 [Serializable]
1052                 class Loader {
1053
1054                         string assembly;
1055
1056                         public Loader (string assembly)
1057                         {
1058                                 this.assembly = assembly;
1059                         }
1060
1061                         public void Load ()
1062                         {
1063                                 Assembly.LoadFrom (assembly);
1064                         }
1065                 }
1066
1067                 [Serializable]
1068                 class Initializer {
1069
1070                         AppDomainInitializer initializer;
1071                         string [] arguments;
1072
1073                         public Initializer (AppDomainInitializer initializer, string [] arguments)
1074                         {
1075                                 this.initializer = initializer;
1076                                 this.arguments = arguments;
1077                         }
1078
1079                         public void Initialize ()
1080                         {
1081                                 initializer (arguments);
1082                         }
1083                 }
1084 #endif
1085
1086                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1087                                                       string appRelativeSearchPath, bool shadowCopyFiles)
1088                 {
1089                         return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1090                 }
1091                 
1092 #if !NET_2_1
1093                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1094                                                       PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1095                 {
1096                         if (info == null)
1097                                 throw new ArgumentNullException ("info");
1098
1099                         info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
1100                         return CreateDomain (friendlyName, securityInfo, info);         
1101                 }
1102 #endif
1103
1104                 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1105                 {
1106                         AppDomainSetup info = new AppDomainSetup ();
1107
1108                         info.ApplicationBase = appBasePath;
1109                         info.PrivateBinPath = appRelativeSearchPath;
1110
1111                         if (shadowCopyFiles)
1112                                 info.ShadowCopyFiles = "true";
1113                         else
1114                                 info.ShadowCopyFiles = "false";
1115
1116                         return info;
1117                 }
1118 #endif // !NET_2_1
1119
1120                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1121                 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1122
1123                 public bool IsFinalizingForUnload()
1124                 {
1125                         return InternalIsFinalizingForUnload (getDomainID ());
1126                 }
1127
1128                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1129                 static extern void InternalUnload (int domain_id);
1130
1131                 // We do this because if the domain is a transparant proxy this
1132                 // will still return the correct domain id.
1133                 private int getDomainID ()
1134                 {
1135                         return Thread.GetDomainID ();
1136                 }
1137
1138                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1139                 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1140                 public static void Unload (AppDomain domain)
1141                 {
1142                         if (domain == null)
1143                                 throw new ArgumentNullException ("domain");
1144
1145                         InternalUnload (domain.getDomainID());
1146                 }
1147
1148                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1149                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1150                 public extern void SetData (string name, object data);
1151
1152                 [MonoLimitation ("The permission field is ignored")]
1153                 public void SetData (string name, object data, IPermission permission)
1154                 {
1155                         SetData (name, data);
1156                 }
1157
1158 #if !NET_2_1
1159                 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1160                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1161                 public void SetDynamicBase (string path)
1162                 {
1163                         SetupInformationNoCopy.DynamicBase = path;
1164                 }
1165 #endif // !NET_2_1
1166
1167                 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1168                         + " because it does not provide a stable Id when managed"
1169                         + " threads are running on fibers (aka lightweight"
1170                         + " threads). To get a stable identifier for a managed"
1171                         + " thread, use the ManagedThreadId property on Thread.'")]
1172                 public static int GetCurrentThreadId ()
1173                 {
1174                         return Thread.CurrentThreadId;
1175                 }
1176
1177                 public override string ToString ()
1178                 {
1179 #if !MOONLIGHT
1180                         return getFriendlyName ();
1181 #else
1182                         StringBuilder sb = new StringBuilder ("Name:");
1183                         sb.AppendLine (FriendlyName);
1184                         sb.AppendLine ("There are no context policies.");
1185                         return sb.ToString ();
1186 #endif
1187                 }
1188
1189                 private static void ValidateAssemblyName (string name)
1190                 {
1191                         if (name == null || name.Length == 0)
1192                                 throw new ArgumentException ("The Name of " +
1193                                         "AssemblyName cannot be null or a " +
1194                                         "zero-length string.");
1195
1196                         bool isValid = true;
1197
1198                         for (int i = 0; i < name.Length; i++) {
1199                                 char c = name [i];
1200
1201                                 // do not allow leading whitespace
1202                                 if (i == 0 && char.IsWhiteSpace (c)) {
1203                                         isValid = false;
1204                                         break;
1205                                 }
1206
1207                                 // do not allow /,\ or : in name
1208                                 if (c == '/' || c == '\\' || c == ':') {
1209                                         isValid = false;
1210                                         break;
1211                                 }
1212                         }
1213
1214                         if (!isValid)
1215                                 throw new ArgumentException ("The Name of " +
1216                                         "AssemblyName cannot start with " +
1217                                         "whitespace, or contain '/', '\\' " +
1218                                         " or ':'.");
1219                 }
1220
1221                 // The following methods are called from the runtime. Don't change signatures.
1222 #pragma warning disable 169             
1223                 private void DoAssemblyLoad (Assembly assembly)
1224                 {
1225                         if (AssemblyLoad == null)
1226                                 return;
1227
1228                         AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1229                 }
1230
1231                 private Assembly DoAssemblyResolve (string name, bool refonly)
1232                 {
1233                         ResolveEventHandler del;
1234 #if !NET_2_1
1235                         if (refonly)
1236                                 del = ReflectionOnlyAssemblyResolve;
1237                         else
1238                                 del = AssemblyResolve;
1239 #else
1240                         del = AssemblyResolve;
1241 #endif
1242                         if (del == null)
1243                                 return null;
1244                         
1245                         /* Prevent infinite recursion */
1246                         Hashtable ht;
1247                         if (refonly) {
1248                                 ht = assembly_resolve_in_progress_refonly;
1249                                 if (ht == null) {
1250                                         ht = new Hashtable ();
1251                                         assembly_resolve_in_progress_refonly = ht;
1252                                 }
1253                         } else {
1254                                 ht = assembly_resolve_in_progress;
1255                                 if (ht == null) {
1256                                         ht = new Hashtable ();
1257                                         assembly_resolve_in_progress = ht;
1258                                 }
1259                         }
1260
1261                         string s = (string) ht [name];
1262                         if (s != null)
1263                                 return null;
1264                         ht [name] = name;
1265                         try {
1266                                 Delegate[] invocation_list = del.GetInvocationList ();
1267
1268                                 foreach (Delegate eh in invocation_list) {
1269                                         ResolveEventHandler handler = (ResolveEventHandler) eh;
1270                                         Assembly assembly = handler (this, new ResolveEventArgs (name));
1271                                         if (assembly != null)
1272                                                 return assembly;
1273                                 }
1274                                 return null;
1275                         }
1276                         finally {
1277                                 ht.Remove (name);
1278                         }
1279                 }
1280
1281                 internal Assembly DoTypeResolve (Object name_or_tb)
1282                 {
1283                         if (TypeResolve == null)
1284                                 return null;
1285
1286                         string name;
1287
1288                         if (name_or_tb is TypeBuilder)
1289                                 name = ((TypeBuilder) name_or_tb).FullName;
1290                         else
1291                                 name = (string) name_or_tb;
1292
1293                         /* Prevent infinite recursion */
1294                         Hashtable ht = type_resolve_in_progress;
1295                         if (ht == null) {
1296                                 ht = new Hashtable ();
1297                                 type_resolve_in_progress = ht;
1298                         }
1299
1300                         if (ht.Contains (name))
1301                                 return null;
1302                         else
1303                                 ht [name] = name;
1304
1305                         try {
1306                                 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1307                                         ResolveEventHandler eh = (ResolveEventHandler) d;
1308                                         Assembly assembly = eh (this, new ResolveEventArgs (name));
1309                                         if (assembly != null)
1310                                                 return assembly;
1311                                 }
1312                                 return null;
1313                         }
1314                         finally {
1315                                 ht.Remove (name);
1316                         }
1317                 }
1318
1319                 private void DoDomainUnload ()
1320                 {
1321                         if (DomainUnload != null)
1322                                 DomainUnload(this, null);
1323                 }
1324
1325 #if !NET_2_1
1326                 internal byte[] GetMarshalledDomainObjRef ()
1327                 {
1328                         ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1329                         return CADSerializer.SerializeObject (oref).GetBuffer();
1330                 }
1331 #endif
1332                 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1333                                                       out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1334                 {
1335                         IMessage reqDomMsg;
1336
1337                         if (null != arrRequest)
1338                                 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1339                         else
1340                                 reqDomMsg = new MethodCall (cadMsg);
1341
1342                         IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1343
1344                         cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1345                         if (null == cadMrm) {
1346                                 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1347                         } 
1348                         else
1349                                 arrResponse = null;
1350                 }
1351
1352 #pragma warning restore 169
1353
1354                 // End of methods called from the runtime
1355                 
1356                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1357                 public event AssemblyLoadEventHandler AssemblyLoad;
1358
1359                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1360                 public event ResolveEventHandler AssemblyResolve;
1361
1362                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1363                 public event EventHandler DomainUnload;
1364
1365                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1366                 public event EventHandler ProcessExit;
1367
1368                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1369                 public event ResolveEventHandler ResourceResolve;
1370
1371                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1372                 public event ResolveEventHandler TypeResolve;
1373
1374                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1375                 public event UnhandledExceptionEventHandler UnhandledException;
1376
1377 #if NET_4_0 || BOOTSTRAP_NET_4_0
1378                 [MonoTODO]
1379                 public bool IsHomogenous {
1380                         get { return true; }
1381                 }
1382
1383                 [MonoTODO]
1384                 public bool IsFullyTrusted {
1385                         get { return true; }
1386                 }
1387 #endif
1388
1389         #pragma warning disable 649
1390                 private AppDomainManager _domain_manager;
1391         #pragma warning restore 649
1392
1393                 // default is null
1394                 public AppDomainManager DomainManager {
1395                         get { return _domain_manager; }
1396                 }
1397
1398 #if (!MOONLIGHT)
1399
1400                 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1401
1402         #pragma warning disable 649
1403                 private ActivationContext _activation;
1404                 private ApplicationIdentity _applicationIdentity;
1405         #pragma warning restore 649
1406
1407                 // properties
1408
1409                 public ActivationContext ActivationContext {
1410                         get { return _activation; }
1411                 }
1412
1413                 public ApplicationIdentity ApplicationIdentity {
1414                         get { return _applicationIdentity; }
1415                 }
1416
1417                 public int Id {
1418                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1419                         get { return getDomainID (); }
1420                 }
1421
1422                 // methods
1423
1424                 [MonoTODO ("This routine only returns the parameter currently")]
1425                 [ComVisible (false)]
1426                 public string ApplyPolicy (string assemblyName)
1427                 {
1428                         if (assemblyName == null)
1429                                 throw new ArgumentNullException ("assemblyName");
1430                         if (assemblyName.Length == 0) // String.Empty
1431                                 throw new ArgumentException ("assemblyName");
1432                         return assemblyName;
1433                 }
1434
1435                 // static methods
1436
1437                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1438                         string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1439                 {
1440                         AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1441
1442                         info.AppDomainInitializerArguments = adInitArgs;
1443                         info.AppDomainInitializer = adInit;
1444
1445                         return CreateDomain (friendlyName, securityInfo, info);
1446                 }
1447
1448                 public int ExecuteAssemblyByName (string assemblyName)
1449                 {
1450                         return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1451                 }
1452
1453 #if NET_4_0
1454                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1455 #endif
1456                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1457                 {
1458                         return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1459                 }
1460
1461 #if NET_4_0
1462                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1463 #endif
1464                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1465                 {
1466                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1467
1468                         return ExecuteAssemblyInternal (a, args);
1469                 }
1470
1471 #if NET_4_0
1472                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1473 #endif
1474                 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1475                 {
1476                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1477
1478                         return ExecuteAssemblyInternal (a, args);
1479                 }
1480
1481 #if NET_4_0
1482                 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1483                 {
1484                         Assembly a = Assembly.Load (assemblyName, null);
1485
1486                         return ExecuteAssemblyInternal (a, args);
1487                 }
1488
1489                 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1490                 {
1491                         Assembly a = Assembly.Load (assemblyName, null);
1492
1493                         return ExecuteAssemblyInternal (a, args);
1494                 }
1495 #endif
1496
1497                 public bool IsDefaultAppDomain ()
1498                 {
1499                         return Object.ReferenceEquals (this, DefaultDomain);
1500                 }
1501
1502                 public Assembly[] ReflectionOnlyGetAssemblies ()
1503                 {
1504                         return GetAssemblies (true);
1505                 }
1506
1507 #else // MOONLIGHT
1508
1509                 public int ExecuteAssemblyByName (string assemblyName)
1510                 {
1511                         // critical code in SL that we're not calling in ML
1512                         throw new NotImplementedException ();
1513                 }
1514 #endif
1515
1516 #if !NET_2_1
1517                 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1518                 {
1519                         throw new NotImplementedException ();
1520                 }
1521
1522                 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1523                 {
1524                         throw new NotImplementedException ();
1525                 }
1526
1527                 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1528                 {
1529                         throw new NotImplementedException ();
1530                 }
1531
1532                 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1533                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1534                 {
1535                         throw new NotImplementedException ();
1536                 }
1537 #endif
1538
1539 #if NET_4_0 || MOONLIGHT
1540                 List<string> compatibility_switch;
1541
1542                 public bool? IsCompatibilitySwitchSet (string value)
1543                 {
1544                         if (value == null)
1545                                 throw new ArgumentNullException ("value");
1546
1547                         // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1548                         return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1549                 }
1550
1551                 internal void SetCompatibilitySwitch (string value)
1552                 {
1553                         if (compatibility_switch == null)
1554                                 compatibility_switch = new List<string> ();
1555                         compatibility_switch.Add (value);
1556                 }
1557
1558                 [MonoTODO ("Currently always returns false")]
1559                 public static bool MonitoringIsEnabled { 
1560                         get { return false; }
1561                         set { throw new NotImplementedException (); }
1562                 }
1563
1564                 [MonoTODO]
1565                 public long MonitoringSurvivedMemorySize {
1566                         get { throw new NotImplementedException (); }
1567                 }
1568
1569                 [MonoTODO]
1570                 public static long MonitoringSurvivedProcessMemorySize {
1571                         get { throw new NotImplementedException (); }
1572                 }
1573
1574                 [MonoTODO]
1575                 public long MonitoringTotalAllocatedMemorySize {
1576                         get { throw new NotImplementedException (); }
1577                 }
1578
1579                 [MonoTODO]
1580                 public TimeSpan MonitoringTotalProcessorTime {
1581                         get { throw new NotImplementedException (); }
1582                 }
1583 #endif
1584         }
1585 }