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