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