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