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