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)
10 // Sebastien Pouliot (sebastien@ximian.com)
12 // (C) 2001, 2002 Ximian, Inc. http://www.ximian.com
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
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:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
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.
35 using System.Collections;
36 using System.Globalization;
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;
54 using System.Collections.Generic;
55 using System.Runtime.ConstrainedExecution;
63 [ClassInterface(ClassInterfaceType.None)]
64 public sealed class AppDomain : MarshalByRefObject , _AppDomain , IEvidenceFactory
66 IntPtr _mono_app_domain;
67 static string _process_guid;
70 static Hashtable type_resolve_in_progress;
73 static Hashtable assembly_resolve_in_progress;
76 private Evidence _evidence;
77 private PermissionSet _granted;
80 private PrincipalPolicy _principalPolicy;
83 private static IPrincipal _principal;
85 static AppDomain default_domain;
91 [MethodImplAttribute (MethodImplOptions.InternalCall)]
92 private extern AppDomainSetup getSetup ();
94 AppDomainSetup SetupInformationNoCopy {
95 get { return getSetup (); }
98 public AppDomainSetup SetupInformation {
100 AppDomainSetup setup = getSetup ();
101 return new AppDomainSetup (setup);
105 public string BaseDirectory {
107 string path = SetupInformationNoCopy.ApplicationBase;
108 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
109 // we cannot divulge local file informations
110 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
116 public string RelativeSearchPath {
118 string path = SetupInformationNoCopy.PrivateBinPath;
119 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
120 // we cannot divulge local file informations
121 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
127 public string DynamicDirectory {
129 AppDomainSetup setup = SetupInformationNoCopy;
130 if (setup.DynamicBase == null)
133 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
134 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
135 // we cannot divulge local file informations
136 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
142 public bool ShadowCopyFiles {
144 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
148 [MethodImplAttribute (MethodImplOptions.InternalCall)]
149 private extern string getFriendlyName ();
151 public string FriendlyName {
153 return getFriendlyName ();
157 public Evidence Evidence {
159 // if the host (runtime) hasn't provided it's own evidence...
160 if (_evidence == null) {
161 // ... we will provide our own
163 // the executed assembly from the "default" appdomain
164 // or null if we're not in the default appdomain
165 Assembly a = Assembly.GetEntryAssembly ();
167 _evidence = AppDomain.DefaultDomain.Evidence;
169 _evidence = Evidence.GetDefaultHostEvidence (a);
172 return new Evidence (_evidence); // return a copy
176 internal IPrincipal DefaultPrincipal {
178 if (_principal == null) {
179 switch (_principalPolicy) {
180 case PrincipalPolicy.UnauthenticatedPrincipal:
181 _principal = new GenericPrincipal (
182 new GenericIdentity (String.Empty, String.Empty), null);
184 case PrincipalPolicy.WindowsPrincipal:
185 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
193 // for AppDomain there is only an allowed (i.e. granted) set
194 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
195 internal PermissionSet GrantedPermissionSet {
196 get { return _granted; }
199 [MethodImplAttribute (MethodImplOptions.InternalCall)]
200 private static extern AppDomain getCurDomain ();
202 public static AppDomain CurrentDomain {
204 return getCurDomain ();
208 [MethodImplAttribute (MethodImplOptions.InternalCall)]
209 private static extern AppDomain getRootDomain ();
211 internal static AppDomain DefaultDomain {
213 if (default_domain == null) {
214 AppDomain rd = getRootDomain ();
215 if (rd == CurrentDomain)
218 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
220 return default_domain;
225 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
227 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
228 public void AppendPrivatePath (string path)
230 if (path == null || path.Length == 0)
233 AppDomainSetup setup = SetupInformationNoCopy;
235 string pp = setup.PrivateBinPath;
236 if (pp == null || pp.Length == 0) {
237 setup.PrivateBinPath = path;
242 if (pp [pp.Length - 1] != Path.PathSeparator)
243 pp += Path.PathSeparator;
245 setup.PrivateBinPath = pp + path;
249 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
251 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
252 public void ClearPrivatePath ()
254 SetupInformationNoCopy.PrivateBinPath = String.Empty;
257 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
258 public void ClearShadowCopyPath ()
260 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
263 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
265 return Activator.CreateComInstanceFrom (assemblyName, typeName);
269 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName,
270 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
272 return Activator.CreateComInstanceFrom (assemblyName, typeName, hashValue ,hashAlgorithm);
276 public ObjectHandle CreateInstance (string assemblyName, string typeName)
278 if (assemblyName == null)
279 throw new ArgumentNullException ("assemblyName");
281 return Activator.CreateInstance (assemblyName, typeName);
284 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
286 if (assemblyName == null)
287 throw new ArgumentNullException ("assemblyName");
289 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
292 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
293 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
294 Evidence securityAttributes)
296 if (assemblyName == null)
297 throw new ArgumentNullException ("assemblyName");
299 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
300 culture, activationAttributes, securityAttributes);
303 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
305 ObjectHandle oh = CreateInstance (assemblyName, typeName);
306 return (oh != null) ? oh.Unwrap () : null;
309 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
311 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
312 return (oh != null) ? oh.Unwrap () : null;
315 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
316 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
317 object[] activationAttributes, Evidence securityAttributes)
319 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
320 culture, activationAttributes, securityAttributes);
321 return (oh != null) ? oh.Unwrap () : null;
324 public ObjectHandle CreateInstanceFrom (string assemblyName, string typeName)
326 if (assemblyName == null)
327 throw new ArgumentNullException ("assemblyName");
329 return Activator.CreateInstanceFrom (assemblyName, typeName);
332 public ObjectHandle CreateInstanceFrom (string assemblyName, string typeName, object[] activationAttributes)
334 if (assemblyName == null)
335 throw new ArgumentNullException ("assemblyName");
337 return Activator.CreateInstanceFrom (assemblyName, typeName, activationAttributes);
340 public ObjectHandle CreateInstanceFrom (string assemblyName, string typeName, bool ignoreCase,
341 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
342 object[] activationAttributes, Evidence securityAttributes)
344 if (assemblyName == null)
345 throw new ArgumentNullException ("assemblyName");
347 return Activator.CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
348 culture, activationAttributes, securityAttributes);
351 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
353 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
354 return (oh != null) ? oh.Unwrap () : null;
357 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
359 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
360 return (oh != null) ? oh.Unwrap () : null;
363 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
364 BindingFlags bindingAttr, Binder binder, object[] args,
365 CultureInfo culture, object[] activationAttributes,
366 Evidence securityAttributes)
368 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
369 culture, activationAttributes, securityAttributes);
371 return (oh != null) ? oh.Unwrap () : null;
374 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
376 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
379 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
381 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
384 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
386 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
389 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
392 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
395 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
396 PermissionSet requiredPermissions,
397 PermissionSet optionalPermissions,
398 PermissionSet refusedPermissions)
400 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
401 refusedPermissions, false);
404 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
405 PermissionSet requiredPermissions,
406 PermissionSet optionalPermissions,
407 PermissionSet refusedPermissions)
409 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
410 refusedPermissions, false);
413 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
414 PermissionSet requiredPermissions,
415 PermissionSet optionalPermissions,
416 PermissionSet refusedPermissions)
418 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
419 refusedPermissions, false);
422 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
424 PermissionSet requiredPermissions,
425 PermissionSet optionalPermissions,
426 PermissionSet refusedPermissions)
428 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
429 refusedPermissions, false);
432 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
434 PermissionSet requiredPermissions,
435 PermissionSet optionalPermissions,
436 PermissionSet refusedPermissions, bool isSynchronized)
438 // FIXME: examine all other parameters
440 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
441 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
447 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
449 PermissionSet requiredPermissions,
450 PermissionSet optionalPermissions,
451 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
453 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
454 if (assemblyAttributes != null)
455 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
456 ab.SetCustomAttribute (cb);
462 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
463 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
467 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
469 return new AssemblyBuilder (name, null, access, true);
473 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
474 // so, when you call AppDomain.DoCallBack, that's a remote call
476 public void DoCallBack (CrossAppDomainDelegate theDelegate)
478 if (theDelegate != null)
482 public int ExecuteAssembly (string assemblyFile)
484 return ExecuteAssembly (assemblyFile, null, null);
487 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
489 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
492 [MethodImplAttribute (MethodImplOptions.InternalCall)]
493 public extern int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args);
495 [MonoTODO ("No support for ExecuteAssembly")]
496 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
498 throw new NotImplementedException ();
501 [MethodImplAttribute (MethodImplOptions.InternalCall)]
502 private extern Assembly [] GetAssemblies (bool refOnly);
504 public Assembly [] GetAssemblies ()
506 return GetAssemblies (false);
509 [MethodImplAttribute (MethodImplOptions.InternalCall)]
510 public extern object GetData (string name);
512 public new Type GetType()
514 return base.GetType ();
517 public override object InitializeLifetimeService ()
522 [MethodImplAttribute (MethodImplOptions.InternalCall)]
523 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
525 public Assembly Load (AssemblyName assemblyRef)
527 return Load (assemblyRef, null);
530 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
532 if (assemblyRef == null)
533 throw new ArgumentNullException ("assemblyRef");
535 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
536 if (assemblyRef.CodeBase != null)
537 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
539 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
542 return LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
545 public Assembly Load (string assemblyString)
547 if (assemblyString == null)
548 throw new ArgumentNullException ("assemblyString");
550 return LoadAssembly (assemblyString, null, false);
553 public Assembly Load (string assemblyString, Evidence assemblySecurity)
555 return Load (assemblyString, assemblySecurity, false);
558 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
560 if (assemblyString == null)
561 throw new ArgumentNullException ("assemblyString");
563 return LoadAssembly (assemblyString, assemblySecurity, refonly);
566 public Assembly Load (byte[] rawAssembly)
568 return Load (rawAssembly, null, null);
571 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
573 return Load (rawAssembly, rawSymbolStore, null);
576 [MethodImplAttribute (MethodImplOptions.InternalCall)]
577 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
579 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
581 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
584 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
586 if (rawAssembly == null)
587 throw new ArgumentNullException ("rawAssembly");
589 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
590 assembly.FromByteArray = true;
594 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
595 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
597 if (domainPolicy == null)
598 throw new ArgumentNullException ("domainPolicy");
599 if (_granted != null) {
600 throw new PolicyException (Locale.GetText (
601 "An AppDomain policy is already specified."));
603 if (IsFinalizingForUnload ())
604 throw new AppDomainUnloadedException ();
606 PolicyStatement ps = domainPolicy.Resolve (_evidence);
607 _granted = ps.PermissionSet;
610 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
611 public void SetCachePath (string path)
613 SetupInformationNoCopy.CachePath = path;
616 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
617 public void SetPrincipalPolicy (PrincipalPolicy policy)
619 if (IsFinalizingForUnload ())
620 throw new AppDomainUnloadedException ();
622 _principalPolicy = policy;
626 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
627 public void SetShadowCopyFiles()
629 SetupInformationNoCopy.ShadowCopyFiles = "true";
632 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
633 public void SetShadowCopyPath (string path)
635 SetupInformationNoCopy.ShadowCopyDirectories = path;
638 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
639 public void SetThreadPrincipal (IPrincipal principal)
641 if (principal == null)
642 throw new ArgumentNullException ("principal");
643 if (_principal != null)
644 throw new PolicyException (Locale.GetText ("principal already present."));
645 if (IsFinalizingForUnload ())
646 throw new AppDomainUnloadedException ();
648 _principal = principal;
651 [MethodImplAttribute (MethodImplOptions.InternalCall)]
652 private static extern AppDomain InternalSetDomainByID (int domain_id);
654 // Changes the active domain and returns the old domain
655 [MethodImplAttribute (MethodImplOptions.InternalCall)]
656 private static extern AppDomain InternalSetDomain (AppDomain context);
658 // Notifies the runtime that this thread references 'domain'.
659 [MethodImplAttribute (MethodImplOptions.InternalCall)]
660 internal static extern void InternalPushDomainRef (AppDomain domain);
662 [MethodImplAttribute (MethodImplOptions.InternalCall)]
663 internal static extern void InternalPushDomainRefByID (int domain_id);
665 // Undoes the effect of the last PushDomainRef call
666 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667 internal static extern void InternalPopDomainRef ();
669 // Changes the active context and returns the old context
670 [MethodImplAttribute (MethodImplOptions.InternalCall)]
671 internal static extern Context InternalSetContext (Context context);
673 // Returns the current context
674 [MethodImplAttribute (MethodImplOptions.InternalCall)]
675 internal static extern Context InternalGetContext ();
677 // Returns the current context
678 [MethodImplAttribute (MethodImplOptions.InternalCall)]
679 internal static extern Context InternalGetDefaultContext ();
681 [MethodImplAttribute (MethodImplOptions.InternalCall)]
682 internal static extern string InternalGetProcessGuid (string newguid);
684 // This method is handled specially by the runtime
685 // It is the only managed method which is allowed to set the current
687 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
689 AppDomain current = CurrentDomain;
693 InternalPushDomainRef (domain);
695 InternalSetDomain (domain);
696 return ((MonoMethod) method).InternalInvoke (obj, args);
699 InternalSetDomain (current);
701 InternalPopDomainRef ();
705 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
707 AppDomain current = CurrentDomain;
711 InternalPushDomainRefByID (domain_id);
713 InternalSetDomainByID (domain_id);
714 return ((MonoMethod) method).InternalInvoke (obj, args);
717 InternalSetDomain (current);
719 InternalPopDomainRef ();
723 internal static String GetProcessGuid ()
725 if (_process_guid == null) {
726 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
728 return _process_guid;
731 public static AppDomain CreateDomain (string friendlyName)
733 return CreateDomain (friendlyName, null, null);
736 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
738 return CreateDomain (friendlyName, securityInfo, null);
741 [MethodImplAttribute (MethodImplOptions.InternalCall)]
742 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
744 [MonoTODO ("Currently it does not allow the setup in the other domain")]
745 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
746 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
748 if (friendlyName == null)
749 throw new System.ArgumentNullException ("friendlyName");
751 AppDomain def = AppDomain.DefaultDomain;
753 // if null, get default domain's SetupInformation
755 info = new AppDomainSetup (); // we're default!
757 info = def.SetupInformation;
760 info = new AppDomainSetup (info); // copy
762 // todo: allow setup in the other domain
764 if (!info.Equals (def.SetupInformation)) {
765 // If not specified use default domain's app base.
766 if (info.ApplicationBase == null)
767 info.ApplicationBase = def.SetupInformation.ApplicationBase;
768 if (info.ConfigurationFile == null)
769 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
771 } else if (info.ConfigurationFile == null)
772 info.ConfigurationFile = "[I don't have a config file]";
774 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
775 if (securityInfo == null) {
776 // get default domain's Evidence (unless we're are the default!)
778 ad._evidence = null; // we'll get them later (GetEntryAssembly)
780 ad._evidence = def.Evidence; // new (shallow) copy
783 ad._evidence = new Evidence (securityInfo); // copy
786 if (info.AppDomainInitializer != null) {
787 if ((info.AppDomainInitializer.Method.Attributes & MethodAttributes.Static) == 0)
788 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
789 info.AppDomainInitializer (info.AppDomainInitializerArguments);
796 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
797 string appRelativeSearchPath, bool shadowCopyFiles)
799 AppDomainSetup info = new AppDomainSetup ();
801 info.ApplicationBase = appBasePath;
802 info.PrivateBinPath = appRelativeSearchPath;
805 info.ShadowCopyFiles = "true";
807 info.ShadowCopyFiles = "false";
809 return CreateDomain (friendlyName, securityInfo, info);
812 [MethodImplAttribute (MethodImplOptions.InternalCall)]
813 private static extern bool InternalIsFinalizingForUnload (int domain_id);
815 public bool IsFinalizingForUnload()
817 return InternalIsFinalizingForUnload (getDomainID ());
820 [MethodImplAttribute (MethodImplOptions.InternalCall)]
821 static extern void InternalUnload (int domain_id);
823 // We do this because if the domain is a transparant proxy this
824 // will still return the correct domain id.
825 private int getDomainID ()
827 return Thread.GetDomainID ();
830 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
832 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
834 public static void Unload (AppDomain domain)
837 throw new ArgumentNullException ("domain");
839 InternalUnload (domain.getDomainID());
842 [MethodImplAttribute (MethodImplOptions.InternalCall)]
843 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
844 public extern void SetData (string name, object data);
846 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
847 public void SetDynamicBase (string path)
849 SetupInformationNoCopy.DynamicBase = path;
853 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
854 + " because it does not provide a stable Id when managed"
855 + " threads are running on fibers (aka lightweight"
856 + " threads). To get a stable identifier for a managed"
857 + " thread, use the ManagedThreadId property on Thread.'")]
859 public static int GetCurrentThreadId ()
861 return Thread.CurrentThreadId;
864 public override string ToString ()
866 return getFriendlyName ();
869 // The following methods are called from the runtime. Don't change signatures.
870 private void DoAssemblyLoad (Assembly assembly)
872 if (AssemblyLoad == null)
875 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
878 private Assembly DoAssemblyResolve (string name, bool refonly)
881 if (refonly && ReflectionOnlyAssemblyResolve == null)
884 if (AssemblyResolve == null)
887 /* Prevent infinite recursion */
888 Hashtable ht = assembly_resolve_in_progress;
890 ht = new Hashtable ();
891 assembly_resolve_in_progress = ht;
894 Assembly ass = (Assembly) ht [name];
896 if (ass != null && (ass.ReflectionOnly == refonly))
906 Delegate [] invocation_list = refonly ? ReflectionOnlyAssemblyResolve.GetInvocationList () :
907 AssemblyResolve.GetInvocationList ();
909 Delegate [] invocation_list = AssemblyResolve.GetInvocationList ();
912 foreach (Delegate eh in invocation_list) {
913 ResolveEventHandler handler = (ResolveEventHandler) eh;
914 Assembly assembly = handler (this, new ResolveEventArgs (name));
915 if (assembly != null)
925 internal Assembly DoTypeResolve (Object name_or_tb)
927 if (TypeResolve == null)
932 if (name_or_tb is TypeBuilder)
933 name = ((TypeBuilder) name_or_tb).FullName;
935 name = (string) name_or_tb;
937 /* Prevent infinite recursion */
938 Hashtable ht = type_resolve_in_progress;
940 ht = new Hashtable ();
941 type_resolve_in_progress = ht;
944 if (ht.Contains (name))
950 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
951 ResolveEventHandler eh = (ResolveEventHandler) d;
952 Assembly assembly = eh (this, new ResolveEventArgs (name));
953 if (assembly != null)
963 private void DoDomainUnload ()
965 if (DomainUnload != null)
966 DomainUnload(this, null);
969 internal byte[] GetMarshalledDomainObjRef ()
971 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
972 return CADSerializer.SerializeObject (oref).GetBuffer();
975 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
976 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
980 if (null != arrRequest)
981 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
983 reqDomMsg = new MethodCall (cadMsg);
985 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
987 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
988 if (null == cadMrm) {
989 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
995 // End of methods called from the runtime
997 #if BOOTSTRAP_WITH_OLDLIB
998 // older MCS/corlib returns:
999 // _AppDomain.cs(138) error CS0592: Attribute 'SecurityPermission' is not valid on this declaration type.
1000 // It is valid on 'assembly' 'class' 'constructor' 'method' 'struct' declarations only.
1001 public event AssemblyLoadEventHandler AssemblyLoad;
1003 public event ResolveEventHandler AssemblyResolve;
1005 public event EventHandler DomainUnload;
1007 public event EventHandler ProcessExit;
1009 public event ResolveEventHandler ResourceResolve;
1011 public event ResolveEventHandler TypeResolve;
1013 public event UnhandledExceptionEventHandler UnhandledException;
1015 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1016 public event AssemblyLoadEventHandler AssemblyLoad;
1018 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1019 public event ResolveEventHandler AssemblyResolve;
1021 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1022 public event EventHandler DomainUnload;
1024 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1025 public event EventHandler ProcessExit;
1027 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1028 public event ResolveEventHandler ResourceResolve;
1030 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1031 public event ResolveEventHandler TypeResolve;
1033 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1034 public event UnhandledExceptionEventHandler UnhandledException;
1037 /* Avoid warnings for events used only by the runtime */
1038 private void DummyUse () {
1039 ProcessExit += (EventHandler)null;
1040 ResourceResolve += (ResolveEventHandler)null;
1041 UnhandledException += (UnhandledExceptionEventHandler)null;
1046 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1048 private ActivationContext _activation;
1049 private ApplicationIdentity _applicationIdentity;
1050 private AppDomainManager _domain_manager;
1054 public ActivationContext ActivationContext {
1055 get { return _activation; }
1058 public ApplicationIdentity ApplicationIdentity {
1059 get { return _applicationIdentity; }
1063 public AppDomainManager DomainManager {
1064 get { return _domain_manager; }
1068 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1069 get { return getDomainID (); }
1074 [MonoTODO ("This routine only returns the parameter currently")]
1075 [ComVisible (false)]
1076 public string ApplyPolicy (string assemblyName)
1078 if (assemblyName == null)
1079 throw new ArgumentNullException ("assemblyName");
1080 if (assemblyName.Length == 0) // String.Empty
1081 throw new ArgumentException ("assemblyName");
1082 return assemblyName;
1087 [MonoTODO ("add support for new delegate")]
1088 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1089 string appRelativeSearchPath, bool shadowCopy, AppDomainInitializer adInit, string[] adInitArgs)
1091 return CreateDomain (friendlyName, securityInfo, appBasePath, appRelativeSearchPath, shadowCopy);
1094 [MonoTODO ("resolve assemblyName to location")]
1095 public int ExecuteAssemblyByName (string assemblyName)
1097 return ExecuteAssemblyByName (assemblyName, null, null);
1100 [MonoTODO ("resolve assemblyName to location")]
1101 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1103 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1106 [MonoTODO ("resolve assemblyName to location")]
1107 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1109 if (assemblyName == null)
1110 throw new ArgumentNullException ("assemblyName");
1112 AssemblyName an = new AssemblyName (assemblyName);
1113 return ExecuteAssemblyByName (an, assemblySecurity, args);
1116 [MonoTODO ("assemblyName may not have a codebase")]
1117 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1119 if (assemblyName == null)
1120 throw new ArgumentNullException ("assemblyName");
1122 return ExecuteAssembly (assemblyName.CodeBase, assemblySecurity, args);
1125 public bool IsDefaultAppDomain ()
1127 return Object.ReferenceEquals (this, DefaultDomain);
1130 public Assembly[] ReflectionOnlyGetAssemblies ()
1132 return GetAssemblies (true);
1137 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1139 throw new NotImplementedException ();
1142 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1144 throw new NotImplementedException ();
1147 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1149 throw new NotImplementedException ();
1152 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1153 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1155 throw new NotImplementedException ();