[runtime] Fix Empty generic enumerator equality
[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 MOBILE
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 !MOBILE
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 !MOBILE
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 !MOBILE
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 !MOBILE
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 !MOBILE
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 !MOBILE
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 !MOBILE
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 !MOBILE
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 !MOBILE
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                 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1221                 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1222                 public void SetDynamicBase (string path)
1223                 {
1224 #if MOBILE
1225                         throw new PlatformNotSupportedException ();
1226 #else
1227                         SetupInformationNoCopy.DynamicBase = path;
1228 #endif // MOBILE
1229                 }
1230
1231                 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1232                         + " because it does not provide a stable Id when managed"
1233                         + " threads are running on fibers (aka lightweight"
1234                         + " threads). To get a stable identifier for a managed"
1235                         + " thread, use the ManagedThreadId property on Thread.'")]
1236                 public static int GetCurrentThreadId ()
1237                 {
1238                         return Thread.CurrentThreadId;
1239                 }
1240
1241                 public override string ToString ()
1242                 {
1243                         return getFriendlyName ();
1244                 }
1245
1246                 private static void ValidateAssemblyName (string name)
1247                 {
1248                         if (name == null || name.Length == 0)
1249                                 throw new ArgumentException ("The Name of " +
1250                                         "AssemblyName cannot be null or a " +
1251                                         "zero-length string.");
1252
1253                         bool isValid = true;
1254
1255                         for (int i = 0; i < name.Length; i++) {
1256                                 char c = name [i];
1257
1258                                 // do not allow leading whitespace
1259                                 if (i == 0 && char.IsWhiteSpace (c)) {
1260                                         isValid = false;
1261                                         break;
1262                                 }
1263
1264                                 // do not allow /,\ or : in name
1265                                 if (c == '/' || c == '\\' || c == ':') {
1266                                         isValid = false;
1267                                         break;
1268                                 }
1269                         }
1270
1271                         if (!isValid)
1272                                 throw new ArgumentException ("The Name of " +
1273                                         "AssemblyName cannot start with " +
1274                                         "whitespace, or contain '/', '\\' " +
1275                                         " or ':'.");
1276                 }
1277
1278                 // The following methods are called from the runtime. Don't change signatures.
1279 #pragma warning disable 169             
1280                 private void DoAssemblyLoad (Assembly assembly)
1281                 {
1282                         if (AssemblyLoad == null)
1283                                 return;
1284
1285                         AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1286                 }
1287
1288                 private Assembly DoAssemblyResolve (string name, Assembly requestingAssembly, bool refonly)
1289                 {
1290                         ResolveEventHandler del;
1291                         if (refonly)
1292                                 del = ReflectionOnlyAssemblyResolve;
1293                         else
1294                                 del = AssemblyResolve;
1295
1296                         if (del == null)
1297                                 return null;
1298                         
1299                         /* Prevent infinite recursion */
1300                         Dictionary<string, object> ht;
1301                         if (refonly) {
1302                                 ht = assembly_resolve_in_progress_refonly;
1303                                 if (ht == null) {
1304                                         ht = new Dictionary<string, object> ();
1305                                         assembly_resolve_in_progress_refonly = ht;
1306                                 }
1307                         } else {
1308                                 ht = assembly_resolve_in_progress;
1309                                 if (ht == null) {
1310                                         ht = new Dictionary<string, object> ();
1311                                         assembly_resolve_in_progress = ht;
1312                                 }
1313                         }
1314
1315                         if (ht.ContainsKey (name))
1316                                 return null;
1317
1318                         ht [name] = null;
1319                         try {
1320                                 Delegate[] invocation_list = del.GetInvocationList ();
1321
1322                                 foreach (Delegate eh in invocation_list) {
1323                                         ResolveEventHandler handler = (ResolveEventHandler) eh;
1324                                         Assembly assembly = handler (this, new ResolveEventArgs (name, requestingAssembly));
1325                                         if (assembly != null)
1326                                                 return assembly;
1327                                 }
1328                                 return null;
1329                         }
1330                         finally {
1331                                 ht.Remove (name);
1332                         }
1333                 }
1334
1335                 internal Assembly DoTypeResolve (Object name_or_tb)
1336                 {
1337                         if (TypeResolve == null)
1338                                 return null;
1339
1340                         string name;
1341
1342 #if !FULL_AOT_RUNTIME
1343                         if (name_or_tb is TypeBuilder)
1344                                 name = ((TypeBuilder) name_or_tb).FullName;
1345                         else
1346 #endif
1347                                 name = (string) name_or_tb;
1348
1349                         /* Prevent infinite recursion */
1350                         var ht = type_resolve_in_progress;
1351                         if (ht == null) {
1352                                 type_resolve_in_progress = ht = new Dictionary<string, object> ();
1353                         }
1354
1355                         if (ht.ContainsKey (name))
1356                                 return null;
1357
1358                         ht [name] = null;
1359
1360                         try {
1361                                 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1362                                         ResolveEventHandler eh = (ResolveEventHandler) d;
1363                                         Assembly assembly = eh (this, new ResolveEventArgs (name));
1364                                         if (assembly != null)
1365                                                 return assembly;
1366                                 }
1367                                 return null;
1368                         }
1369                         finally {
1370                                 ht.Remove (name);
1371                         }
1372                 }
1373
1374                 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1375                         if (ResourceResolve == null)
1376                                 return null;
1377
1378                         Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1379
1380                         foreach (Delegate eh in invocation_list) {
1381                                 ResolveEventHandler handler = (ResolveEventHandler) eh;
1382                                 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1383                                 if (assembly != null)
1384                                         return assembly;
1385                         }
1386                         return null;
1387                 }
1388
1389 #if MONO_FEATURE_MULTIPLE_APPDOMAINS
1390                 private void DoDomainUnload ()
1391                 {
1392                         if (DomainUnload != null)
1393                                 DomainUnload(this, null);
1394                 }
1395 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
1396
1397                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1398                 internal extern void DoUnhandledException (Exception e);
1399
1400                 internal void DoUnhandledException (UnhandledExceptionEventArgs args) {
1401                         if (UnhandledException != null)
1402                                 UnhandledException (this, args);
1403                 }
1404
1405                 internal byte[] GetMarshalledDomainObjRef ()
1406                 {
1407                         ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1408                         return CADSerializer.SerializeObject (oref).GetBuffer();
1409                 }
1410
1411                 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1412                                                       out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1413                 {
1414                         IMessage reqDomMsg;
1415
1416                         if (null != arrRequest)
1417                                 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1418                         else
1419                                 reqDomMsg = new MethodCall (cadMsg);
1420
1421                         IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1422
1423                         cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1424                         if (null == cadMrm) {
1425                                 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1426                         } 
1427                         else
1428                                 arrResponse = null;
1429                 }
1430
1431 #pragma warning restore 169
1432
1433                 // End of methods called from the runtime
1434                 
1435                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1436                 public event AssemblyLoadEventHandler AssemblyLoad;
1437
1438                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1439                 public event ResolveEventHandler AssemblyResolve;
1440
1441 #if MONO_FEATURE_MULTIPLE_APPDOMAINS
1442                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1443 #else
1444                 [Obsolete ("AppDomain.DomainUnload is not supported on the current platform.", true)]
1445 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
1446                 public event EventHandler DomainUnload;
1447
1448                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1449                 public event EventHandler ProcessExit;
1450
1451                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1452                 public event ResolveEventHandler ResourceResolve;
1453
1454                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1455                 public event ResolveEventHandler TypeResolve;
1456
1457                 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1458                 public event UnhandledExceptionEventHandler UnhandledException;
1459
1460                 public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException;
1461
1462                 [MonoTODO]
1463                 public bool IsHomogenous {
1464                         get { return true; }
1465                 }
1466
1467                 [MonoTODO]
1468                 public bool IsFullyTrusted {
1469                         get { return true; }
1470                 }
1471
1472         #pragma warning disable 649
1473 #if !MOBILE
1474                 private AppDomainManager _domain_manager;
1475 #else
1476                 object _domain_manager;
1477 #endif
1478         #pragma warning restore 649
1479
1480 #if MONO_FEATURE_MULTIPLE_APPDOMAINS
1481                 // default is null
1482                 public AppDomainManager DomainManager {
1483                         get { return (AppDomainManager)_domain_manager; }
1484                 }
1485 #else
1486                 [Obsolete ("AppDomain.DomainManager is not supported on this platform.", true)]
1487                 public AppDomainManager DomainManager {
1488                         get { throw new PlatformNotSupportedException ("AppDomain.DomainManager is not supported on this platform."); }
1489                 }
1490 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
1491
1492                 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1493
1494         #pragma warning disable 649
1495 #if MOBILE
1496                 private object _activation;
1497                 private object _applicationIdentity;
1498 #else
1499                 private ActivationContext _activation;
1500                 private ApplicationIdentity _applicationIdentity;
1501 #endif
1502         #pragma warning restore 649
1503
1504                 // properties
1505
1506                 public ActivationContext ActivationContext {
1507                         get { return (ActivationContext)_activation; }
1508                 }
1509
1510                 public ApplicationIdentity ApplicationIdentity {
1511                         get { return (ApplicationIdentity)_applicationIdentity; }
1512                 }
1513
1514                 public int Id {
1515                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1516                         get { return getDomainID (); }
1517                 }
1518
1519                 // methods
1520
1521                 [MonoTODO ("This routine only returns the parameter currently")]
1522                 [ComVisible (false)]
1523                 public string ApplyPolicy (string assemblyName)
1524                 {
1525                         if (assemblyName == null)
1526                                 throw new ArgumentNullException ("assemblyName");
1527                         if (assemblyName.Length == 0) // String.Empty
1528                                 throw new ArgumentException ("assemblyName");
1529                         return assemblyName;
1530                 }
1531
1532                 // static methods
1533
1534 #if MONO_FEATURE_MULTIPLE_APPDOMAINS
1535                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1536                         string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1537                 {
1538                         AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1539
1540                         info.AppDomainInitializerArguments = adInitArgs;
1541                         info.AppDomainInitializer = adInit;
1542
1543                         return CreateDomain (friendlyName, securityInfo, info);
1544                 }
1545 #else
1546                 [Obsolete ("AppDomain.CreateDomain is not supported on the current platform.", true)]
1547                 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1548                         string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1549                 {
1550                         throw new PlatformNotSupportedException ("AppDomain.CreateDomain is not supported on the current platform.");
1551                 }
1552 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
1553
1554                 public int ExecuteAssemblyByName (string assemblyName)
1555                 {
1556                         return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1557                 }
1558
1559                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1560                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1561                 {
1562                         return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1563                 }
1564
1565                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1566                 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1567                 {
1568                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1569
1570                         return ExecuteAssemblyInternal (a, args);
1571                 }
1572
1573                 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1574                 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1575                 {
1576                         Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1577
1578                         return ExecuteAssemblyInternal (a, args);
1579                 }
1580
1581                 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1582                 {
1583                         Assembly a = Assembly.Load (assemblyName, null);
1584
1585                         return ExecuteAssemblyInternal (a, args);
1586                 }
1587
1588                 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1589                 {
1590                         Assembly a = Assembly.Load (assemblyName, null);
1591
1592                         return ExecuteAssemblyInternal (a, args);
1593                 }
1594
1595                 public bool IsDefaultAppDomain ()
1596                 {
1597                         return Object.ReferenceEquals (this, DefaultDomain);
1598                 }
1599
1600                 public Assembly[] ReflectionOnlyGetAssemblies ()
1601                 {
1602                         return GetAssemblies (true);
1603                 }
1604
1605 #if !MOBILE
1606                 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1607                 {
1608                         throw new NotImplementedException ();
1609                 }
1610
1611                 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1612                 {
1613                         throw new NotImplementedException ();
1614                 }
1615
1616                 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1617                 {
1618                         throw new NotImplementedException ();
1619                 }
1620
1621                 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1622                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1623                 {
1624                         throw new NotImplementedException ();
1625                 }
1626 #endif
1627
1628                 List<string> compatibility_switch;
1629
1630                 public bool? IsCompatibilitySwitchSet (string value)
1631                 {
1632                         if (value == null)
1633                                 throw new ArgumentNullException ("value");
1634
1635                         // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1636                         return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1637                 }
1638
1639                 internal void SetCompatibilitySwitch (string value)
1640                 {
1641                         if (compatibility_switch == null)
1642                                 compatibility_switch = new List<string> ();
1643                         compatibility_switch.Add (value);
1644                 }
1645
1646                 [MonoTODO ("Currently always returns false")]
1647                 public static bool MonitoringIsEnabled { 
1648                         get { return false; }
1649                         set { throw new NotImplementedException (); }
1650                 }
1651
1652                 [MonoTODO]
1653                 public long MonitoringSurvivedMemorySize {
1654                         get { throw new NotImplementedException (); }
1655                 }
1656
1657                 [MonoTODO]
1658                 public static long MonitoringSurvivedProcessMemorySize {
1659                         get { throw new NotImplementedException (); }
1660                 }
1661
1662                 [MonoTODO]
1663                 public long MonitoringTotalAllocatedMemorySize {
1664                         get { throw new NotImplementedException (); }
1665                 }
1666
1667                 [MonoTODO]
1668                 public TimeSpan MonitoringTotalProcessorTime {
1669                         get { throw new NotImplementedException (); }
1670                 }
1671         }
1672 }