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