Merge pull request #2154 from BrennanConroy/bug_30018
[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                 public static AppDomain CreateDomain (string friendlyName)
987                 {
988                         return CreateDomain (friendlyName, null, null);
989                 }
990                 
991                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
992                 {
993                         return CreateDomain (friendlyName, securityInfo, null);
994                 }
995
996                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
997                 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
998
999                 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
1000                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1001                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
1002                 {
1003                         if (friendlyName == null)
1004                                 throw new System.ArgumentNullException ("friendlyName");
1005
1006                         AppDomain def = AppDomain.DefaultDomain;
1007                         if (info == null) {
1008                                 // if null, get default domain's SetupInformation       
1009                                 if (def == null)
1010                                         info = new AppDomainSetup ();   // we're default!
1011                                 else
1012                                         info = def.SetupInformation;
1013                         }
1014                         else
1015                                 info = new AppDomainSetup (info);       // copy
1016
1017                         // todo: allow setup in the other domain
1018                         if (def != null) {
1019                                 if (!info.Equals (def.SetupInformation)) {
1020                                         // If not specified use default domain's app base.
1021                                         if (info.ApplicationBase == null)
1022                                                 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1023                                         if (info.ConfigurationFile == null)
1024                                                 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1025                                 }
1026                         } else if (info.ConfigurationFile == null)
1027                                 info.ConfigurationFile = "[I don't have a config file]";
1028
1029 #if !NET_2_1
1030                         if (info.AppDomainInitializer != null) {
1031                                 if (!info.AppDomainInitializer.Method.IsStatic)
1032                                         throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1033                         }
1034 #endif
1035
1036                         info.SerializeNonPrimitives ();
1037
1038                         AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1039                         if (securityInfo == null) {
1040                                 // get default domain's Evidence (unless we're are the default!)
1041                                 if (def == null)
1042                                         ad._evidence = null;            // we'll get them later (GetEntryAssembly)
1043                                 else
1044                                         ad._evidence = def.Evidence;    // new (shallow) copy
1045                         }
1046                         else
1047                                 ad._evidence = new Evidence (securityInfo);     // copy
1048
1049 #if !NET_2_1
1050                         if (info.AppDomainInitializer != null) {
1051                                 Loader loader = new Loader (
1052                                         info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1053                                 ad.DoCallBack (loader.Load);
1054
1055                                 Initializer initializer = new Initializer (
1056                                         info.AppDomainInitializer,
1057                                         info.AppDomainInitializerArguments);
1058                                 ad.DoCallBack (initializer.Initialize);
1059                         }
1060 #endif
1061
1062                         return ad;
1063                 }
1064
1065 #if !NET_2_1
1066                 [Serializable]
1067                 class Loader {
1068
1069                         string assembly;
1070
1071                         public Loader (string assembly)
1072                         {
1073                                 this.assembly = assembly;
1074                         }
1075
1076                         public void Load ()
1077                         {
1078                                 Assembly.LoadFrom (assembly);
1079                         }
1080                 }
1081
1082                 [Serializable]
1083                 class Initializer {
1084
1085                         AppDomainInitializer initializer;
1086                         string [] arguments;
1087
1088                         public Initializer (AppDomainInitializer initializer, string [] arguments)
1089                         {
1090                                 this.initializer = initializer;
1091                                 this.arguments = arguments;
1092                         }
1093
1094                         public void Initialize ()
1095                         {
1096                                 initializer (arguments);
1097                         }
1098                 }
1099 #endif
1100
1101                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1102                                                       string appRelativeSearchPath, bool shadowCopyFiles)
1103                 {
1104                         return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1105                 }
1106                 
1107 #if !NET_2_1
1108                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1109                                                       PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1110                 {
1111                         if (info == null)
1112                                 throw new ArgumentNullException ("info");
1113
1114                         info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? EmptyArray<StrongName>.Value);
1115                         return CreateDomain (friendlyName, securityInfo, info);         
1116                 }
1117 #endif
1118
1119                 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1120                 {
1121                         AppDomainSetup info = new AppDomainSetup ();
1122
1123                         info.ApplicationBase = appBasePath;
1124                         info.PrivateBinPath = appRelativeSearchPath;
1125
1126                         if (shadowCopyFiles)
1127                                 info.ShadowCopyFiles = "true";
1128                         else
1129                                 info.ShadowCopyFiles = "false";
1130
1131                         return info;
1132                 }
1133                 
1134                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1135                 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1136
1137                 public bool IsFinalizingForUnload()
1138                 {
1139                         return InternalIsFinalizingForUnload (getDomainID ());
1140                 }
1141
1142                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1143                 static extern void InternalUnload (int domain_id);
1144
1145                 // We do this because if the domain is a transparant proxy this
1146                 // will still return the correct domain id.
1147                 private int getDomainID ()
1148                 {
1149                         return Thread.GetDomainID ();
1150                 }
1151
1152                 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1153                 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1154                 public static void Unload (AppDomain domain)
1155                 {
1156                         if (domain == null)
1157                                 throw new ArgumentNullException ("domain");
1158
1159                         InternalUnload (domain.getDomainID());
1160                 }
1161
1162                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1163                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1164                 public extern void SetData (string name, object data);
1165
1166                 [MonoLimitation ("The permission field is ignored")]
1167                 public void SetData (string name, object data, IPermission permission)
1168                 {
1169                         SetData (name, data);
1170                 }
1171
1172 #if !NET_2_1
1173                 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1174                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1175                 public void SetDynamicBase (string path)
1176                 {
1177                         SetupInformationNoCopy.DynamicBase = path;
1178                 }
1179 #endif // !NET_2_1
1180
1181                 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1182                         + " because it does not provide a stable Id when managed"
1183                         + " threads are running on fibers (aka lightweight"
1184                         + " threads). To get a stable identifier for a managed"
1185                         + " thread, use the ManagedThreadId property on Thread.'")]
1186                 public static int GetCurrentThreadId ()
1187                 {
1188                         return Thread.CurrentThreadId;
1189                 }
1190
1191                 public override string ToString ()
1192                 {
1193                         return getFriendlyName ();
1194                 }
1195
1196                 private static void ValidateAssemblyName (string name)
1197                 {
1198                         if (name == null || name.Length == 0)
1199                                 throw new ArgumentException ("The Name of " +
1200                                         "AssemblyName cannot be null or a " +
1201                                         "zero-length string.");
1202
1203                         bool isValid = true;
1204
1205                         for (int i = 0; i < name.Length; i++) {
1206                                 char c = name [i];
1207
1208                                 // do not allow leading whitespace
1209                                 if (i == 0 && char.IsWhiteSpace (c)) {
1210                                         isValid = false;
1211                                         break;
1212                                 }
1213
1214                                 // do not allow /,\ or : in name
1215                                 if (c == '/' || c == '\\' || c == ':') {
1216                                         isValid = false;
1217                                         break;
1218                                 }
1219                         }
1220
1221                         if (!isValid)
1222                                 throw new ArgumentException ("The Name of " +
1223                                         "AssemblyName cannot start with " +
1224                                         "whitespace, or contain '/', '\\' " +
1225                                         " or ':'.");
1226                 }
1227
1228                 // The following methods are called from the runtime. Don't change signatures.
1229 #pragma warning disable 169             
1230                 private void DoAssemblyLoad (Assembly assembly)
1231                 {
1232                         if (AssemblyLoad == null)
1233                                 return;
1234
1235                         AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1236                 }
1237
1238                 private Assembly DoAssemblyResolve (string name, Assembly requestingAssembly, bool refonly)
1239                 {
1240                         ResolveEventHandler del;
1241 #if !NET_2_1
1242                         if (refonly)
1243                                 del = ReflectionOnlyAssemblyResolve;
1244                         else
1245                                 del = AssemblyResolve;
1246 #else
1247                         del = AssemblyResolve;
1248 #endif
1249                         if (del == null)
1250                                 return null;
1251                         
1252                         /* Prevent infinite recursion */
1253                         Dictionary<string, object> ht;
1254                         if (refonly) {
1255                                 ht = assembly_resolve_in_progress_refonly;
1256                                 if (ht == null) {
1257                                         ht = new Dictionary<string, object> ();
1258                                         assembly_resolve_in_progress_refonly = ht;
1259                                 }
1260                         } else {
1261                                 ht = assembly_resolve_in_progress;
1262                                 if (ht == null) {
1263                                         ht = new Dictionary<string, object> ();
1264                                         assembly_resolve_in_progress = ht;
1265                                 }
1266                         }
1267
1268                         if (ht.ContainsKey (name))
1269                                 return null;
1270
1271                         ht [name] = null;
1272                         try {
1273                                 Delegate[] invocation_list = del.GetInvocationList ();
1274
1275                                 foreach (Delegate eh in invocation_list) {
1276                                         ResolveEventHandler handler = (ResolveEventHandler) eh;
1277                                         Assembly assembly = handler (this, new ResolveEventArgs (name, requestingAssembly));
1278                                         if (assembly != null)
1279                                                 return assembly;
1280                                 }
1281                                 return null;
1282                         }
1283                         finally {
1284                                 ht.Remove (name);
1285                         }
1286                 }
1287
1288                 internal Assembly DoTypeResolve (Object name_or_tb)
1289                 {
1290                         if (TypeResolve == null)
1291                                 return null;
1292
1293                         string name;
1294
1295 #if !FULL_AOT_RUNTIME
1296                         if (name_or_tb is TypeBuilder)
1297                                 name = ((TypeBuilder) name_or_tb).FullName;
1298                         else
1299 #endif
1300                                 name = (string) name_or_tb;
1301
1302                         /* Prevent infinite recursion */
1303                         var ht = type_resolve_in_progress;
1304                         if (ht == null) {
1305                                 type_resolve_in_progress = ht = new Dictionary<string, object> ();
1306                         }
1307
1308                         if (ht.ContainsKey (name))
1309                                 return null;
1310
1311                         ht [name] = null;
1312
1313                         try {
1314                                 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1315                                         ResolveEventHandler eh = (ResolveEventHandler) d;
1316                                         Assembly assembly = eh (this, new ResolveEventArgs (name));
1317                                         if (assembly != null)
1318                                                 return assembly;
1319                                 }
1320                                 return null;
1321                         }
1322                         finally {
1323                                 ht.Remove (name);
1324                         }
1325                 }
1326
1327                 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1328                         if (ResourceResolve == null)
1329                                 return null;
1330
1331                         Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1332
1333                         foreach (Delegate eh in invocation_list) {
1334                                 ResolveEventHandler handler = (ResolveEventHandler) eh;
1335                                 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1336                                 if (assembly != null)
1337                                         return assembly;
1338                         }
1339                         return null;
1340                 }
1341
1342                 private void DoDomainUnload ()
1343                 {
1344                         if (DomainUnload != null)
1345                                 DomainUnload(this, null);
1346                 }
1347
1348                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1349                 internal extern void DoUnhandledException (Exception e);
1350
1351                 internal void DoUnhandledException (UnhandledExceptionEventArgs args) {
1352                         if (UnhandledException != null)
1353                                 UnhandledException (this, args);
1354                 }
1355
1356                 internal byte[] GetMarshalledDomainObjRef ()
1357                 {
1358                         ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1359                         return CADSerializer.SerializeObject (oref).GetBuffer();
1360                 }
1361
1362                 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1363                                                       out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1364                 {
1365                         IMessage reqDomMsg;
1366
1367                         if (null != arrRequest)
1368                                 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1369                         else
1370                                 reqDomMsg = new MethodCall (cadMsg);
1371
1372                         IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1373
1374                         cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1375                         if (null == cadMrm) {
1376                                 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1377                         } 
1378                         else
1379                                 arrResponse = null;
1380                 }
1381
1382 #pragma warning restore 169
1383
1384                 // End of methods called from the runtime
1385                 
1386                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1387                 public event AssemblyLoadEventHandler AssemblyLoad;
1388
1389                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1390                 public event ResolveEventHandler AssemblyResolve;
1391
1392                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1393                 public event EventHandler DomainUnload;
1394
1395                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1396                 public event EventHandler ProcessExit;
1397
1398                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1399                 public event ResolveEventHandler ResourceResolve;
1400
1401                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1402                 public event ResolveEventHandler TypeResolve;
1403
1404                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1405                 public event UnhandledExceptionEventHandler UnhandledException;
1406
1407                 public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException;
1408
1409                 [MonoTODO]
1410                 public bool IsHomogenous {
1411                         get { return true; }
1412                 }
1413
1414                 [MonoTODO]
1415                 public bool IsFullyTrusted {
1416                         get { return true; }
1417                 }
1418
1419         #pragma warning disable 649
1420 #if !MOBILE
1421                 private AppDomainManager _domain_manager;
1422 #else
1423                 object _domain_manager;
1424 #endif
1425         #pragma warning restore 649
1426
1427                 // default is null
1428                 public AppDomainManager DomainManager {
1429                         get { return (AppDomainManager)_domain_manager; }
1430                 }
1431
1432 #if !MOBILE
1433                 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1434 #endif
1435
1436         #pragma warning disable 649
1437 #if MOBILE
1438                 private object _activation;
1439                 private object _applicationIdentity;
1440 #else
1441                 private ActivationContext _activation;
1442                 private ApplicationIdentity _applicationIdentity;
1443 #endif
1444         #pragma warning restore 649
1445
1446                 // properties
1447
1448                 public ActivationContext ActivationContext {
1449                         get { return (ActivationContext)_activation; }
1450                 }
1451
1452                 public ApplicationIdentity ApplicationIdentity {
1453                         get { return (ApplicationIdentity)_applicationIdentity; }
1454                 }
1455
1456                 public int Id {
1457                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1458                         get { return getDomainID (); }
1459                 }
1460
1461                 // methods
1462
1463                 [MonoTODO ("This routine only returns the parameter currently")]
1464                 [ComVisible (false)]
1465                 public string ApplyPolicy (string assemblyName)
1466                 {
1467                         if (assemblyName == null)
1468                                 throw new ArgumentNullException ("assemblyName");
1469                         if (assemblyName.Length == 0) // String.Empty
1470                                 throw new ArgumentException ("assemblyName");
1471                         return assemblyName;
1472                 }
1473
1474                 // static methods
1475
1476                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1477                         string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1478                 {
1479                         AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1480
1481                         info.AppDomainInitializerArguments = adInitArgs;
1482                         info.AppDomainInitializer = adInit;
1483
1484                         return CreateDomain (friendlyName, securityInfo, info);
1485                 }
1486
1487                 public int ExecuteAssemblyByName (string assemblyName)
1488                 {
1489                         return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1490                 }
1491
1492                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1493                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1494                 {
1495                         return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1496                 }
1497
1498                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1499                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1500                 {
1501                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1502
1503                         return ExecuteAssemblyInternal (a, args);
1504                 }
1505
1506                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1507                 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1508                 {
1509                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1510
1511                         return ExecuteAssemblyInternal (a, args);
1512                 }
1513
1514                 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1515                 {
1516                         Assembly a = Assembly.Load (assemblyName, null);
1517
1518                         return ExecuteAssemblyInternal (a, args);
1519                 }
1520
1521                 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1522                 {
1523                         Assembly a = Assembly.Load (assemblyName, null);
1524
1525                         return ExecuteAssemblyInternal (a, args);
1526                 }
1527
1528                 public bool IsDefaultAppDomain ()
1529                 {
1530                         return Object.ReferenceEquals (this, DefaultDomain);
1531                 }
1532
1533                 public Assembly[] ReflectionOnlyGetAssemblies ()
1534                 {
1535                         return GetAssemblies (true);
1536                 }
1537
1538 #if !MOBILE
1539                 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1540                 {
1541                         throw new NotImplementedException ();
1542                 }
1543
1544                 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1545                 {
1546                         throw new NotImplementedException ();
1547                 }
1548
1549                 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1550                 {
1551                         throw new NotImplementedException ();
1552                 }
1553
1554                 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1555                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1556                 {
1557                         throw new NotImplementedException ();
1558                 }
1559 #endif
1560
1561                 List<string> compatibility_switch;
1562
1563                 public bool? IsCompatibilitySwitchSet (string value)
1564                 {
1565                         if (value == null)
1566                                 throw new ArgumentNullException ("value");
1567
1568                         // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1569                         return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1570                 }
1571
1572                 internal void SetCompatibilitySwitch (string value)
1573                 {
1574                         if (compatibility_switch == null)
1575                                 compatibility_switch = new List<string> ();
1576                         compatibility_switch.Add (value);
1577                 }
1578
1579                 [MonoTODO ("Currently always returns false")]
1580                 public static bool MonitoringIsEnabled { 
1581                         get { return false; }
1582                         set { throw new NotImplementedException (); }
1583                 }
1584
1585                 [MonoTODO]
1586                 public long MonitoringSurvivedMemorySize {
1587                         get { throw new NotImplementedException (); }
1588                 }
1589
1590                 [MonoTODO]
1591                 public static long MonitoringSurvivedProcessMemorySize {
1592                         get { throw new NotImplementedException (); }
1593                 }
1594
1595                 [MonoTODO]
1596                 public long MonitoringTotalAllocatedMemorySize {
1597                         get { throw new NotImplementedException (); }
1598                 }
1599
1600                 [MonoTODO]
1601                 public TimeSpan MonitoringTotalProcessorTime {
1602                         get { throw new NotImplementedException (); }
1603                 }
1604         }
1605 }