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.Runtime.ConstrainedExecution;
62 [ClassInterface(ClassInterfaceType.None)]
63 public sealed class AppDomain : MarshalByRefObject , _AppDomain , IEvidenceFactory
65 IntPtr _mono_app_domain;
66 static string _process_guid;
69 static Hashtable type_resolve_in_progress;
72 static Hashtable assembly_resolve_in_progress;
75 private Evidence _evidence;
76 private PermissionSet _granted;
79 private PrincipalPolicy _principalPolicy;
82 private static IPrincipal _principal;
88 [MethodImplAttribute (MethodImplOptions.InternalCall)]
89 private extern AppDomainSetup getSetup ();
91 AppDomainSetup SetupInformationNoCopy {
92 get { return getSetup (); }
95 public AppDomainSetup SetupInformation {
97 AppDomainSetup setup = getSetup ();
98 return new AppDomainSetup (setup);
102 public string BaseDirectory {
104 string path = SetupInformationNoCopy.ApplicationBase;
105 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
106 // we cannot divulge local file informations
107 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
113 public string RelativeSearchPath {
115 string path = SetupInformationNoCopy.PrivateBinPath;
116 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
117 // we cannot divulge local file informations
118 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
124 public string DynamicDirectory {
126 AppDomainSetup setup = SetupInformationNoCopy;
127 if (setup.DynamicBase == null)
130 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
131 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
132 // we cannot divulge local file informations
133 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
139 public bool ShadowCopyFiles {
141 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
145 [MethodImplAttribute (MethodImplOptions.InternalCall)]
146 private extern string getFriendlyName ();
148 public string FriendlyName {
150 return getFriendlyName ();
154 public Evidence Evidence {
156 // if the host (runtime) hasn't provided it's own evidence...
157 if (_evidence == null) {
158 // ... we will provide our own
160 // the executed assembly from the "default" appdomain
161 // or null if we're not in the default appdomain
162 Assembly a = Assembly.GetEntryAssembly ();
164 _evidence = AppDomain.DefaultDomain.Evidence;
166 _evidence = Evidence.GetDefaultHostEvidence (a);
169 return new Evidence (_evidence); // return a copy
173 internal IPrincipal DefaultPrincipal {
175 if (_principal == null) {
176 switch (_principalPolicy) {
177 case PrincipalPolicy.UnauthenticatedPrincipal:
178 _principal = new GenericPrincipal (
179 new GenericIdentity (String.Empty, String.Empty), null);
181 case PrincipalPolicy.WindowsPrincipal:
182 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
190 // for AppDomain there is only an allowed (i.e. granted) set
191 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
192 internal PermissionSet GrantedPermissionSet {
193 get { return _granted; }
196 [MethodImplAttribute (MethodImplOptions.InternalCall)]
197 private static extern AppDomain getCurDomain ();
199 public static AppDomain CurrentDomain {
201 return getCurDomain ();
205 [MethodImplAttribute (MethodImplOptions.InternalCall)]
206 private static extern AppDomain getRootDomain ();
208 internal static AppDomain DefaultDomain {
210 return getRootDomain ();
217 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
218 public void AppendPrivatePath (string path)
220 if (path == null || path.Length == 0)
223 AppDomainSetup setup = SetupInformationNoCopy;
225 string pp = setup.PrivateBinPath;
226 if (pp == null || pp.Length == 0) {
227 setup.PrivateBinPath = path;
232 if (pp [pp.Length - 1] != Path.PathSeparator)
233 pp += Path.PathSeparator;
235 setup.PrivateBinPath = pp + path;
241 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
242 public void ClearPrivatePath ()
244 SetupInformationNoCopy.PrivateBinPath = String.Empty;
247 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
248 public void ClearShadowCopyPath ()
250 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
253 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
255 return Activator.CreateComInstanceFrom (assemblyName, typeName);
259 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName,
260 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
262 return Activator.CreateComInstanceFrom (assemblyName, typeName, hashValue ,hashAlgorithm);
266 public ObjectHandle CreateInstance (string assemblyName, string typeName)
268 if (assemblyName == null)
269 throw new ArgumentNullException ("assemblyName");
271 return Activator.CreateInstance (assemblyName, typeName);
274 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
276 if (assemblyName == null)
277 throw new ArgumentNullException ("assemblyName");
279 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
282 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
283 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
284 Evidence securityAttributes)
286 if (assemblyName == null)
287 throw new ArgumentNullException ("assemblyName");
289 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
290 culture, activationAttributes, securityAttributes);
293 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
295 ObjectHandle oh = CreateInstance (assemblyName, typeName);
296 return (oh != null) ? oh.Unwrap () : null;
299 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
301 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
302 return (oh != null) ? oh.Unwrap () : null;
305 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
306 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
307 object[] activationAttributes, Evidence securityAttributes)
309 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
310 culture, activationAttributes, securityAttributes);
311 return (oh != null) ? oh.Unwrap () : null;
314 public ObjectHandle CreateInstanceFrom (string assemblyName, string typeName)
316 if (assemblyName == null)
317 throw new ArgumentNullException ("assemblyName");
319 return Activator.CreateInstanceFrom (assemblyName, typeName);
322 public ObjectHandle CreateInstanceFrom (string assemblyName, string typeName, object[] activationAttributes)
324 if (assemblyName == null)
325 throw new ArgumentNullException ("assemblyName");
327 return Activator.CreateInstanceFrom (assemblyName, typeName, activationAttributes);
330 public ObjectHandle CreateInstanceFrom (string assemblyName, string typeName, bool ignoreCase,
331 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
332 object[] activationAttributes, Evidence securityAttributes)
334 if (assemblyName == null)
335 throw new ArgumentNullException ("assemblyName");
337 return Activator.CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
338 culture, activationAttributes, securityAttributes);
341 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
343 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
344 return (oh != null) ? oh.Unwrap () : null;
347 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
349 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
350 return (oh != null) ? oh.Unwrap () : null;
353 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
354 BindingFlags bindingAttr, Binder binder, object[] args,
355 CultureInfo culture, object[] activationAttributes,
356 Evidence securityAttributes)
358 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
359 culture, activationAttributes, securityAttributes);
361 return (oh != null) ? oh.Unwrap () : null;
364 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
366 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
369 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
371 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
374 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
376 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
379 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
382 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
385 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
386 PermissionSet requiredPermissions,
387 PermissionSet optionalPermissions,
388 PermissionSet refusedPermissions)
390 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
391 refusedPermissions, false);
394 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
395 PermissionSet requiredPermissions,
396 PermissionSet optionalPermissions,
397 PermissionSet refusedPermissions)
399 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
400 refusedPermissions, false);
403 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
404 PermissionSet requiredPermissions,
405 PermissionSet optionalPermissions,
406 PermissionSet refusedPermissions)
408 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
409 refusedPermissions, false);
412 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
414 PermissionSet requiredPermissions,
415 PermissionSet optionalPermissions,
416 PermissionSet refusedPermissions)
418 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
419 refusedPermissions, false);
422 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
424 PermissionSet requiredPermissions,
425 PermissionSet optionalPermissions,
426 PermissionSet refusedPermissions, bool isSynchronized)
428 // FIXME: examine all other parameters
430 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
431 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
435 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
437 return new AssemblyBuilder (name, null, access, true);
441 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
442 // so, when you call AppDomain.DoCallBack, that's a remote call
444 public void DoCallBack (CrossAppDomainDelegate theDelegate)
446 if (theDelegate != null)
450 public int ExecuteAssembly (string assemblyFile)
452 return ExecuteAssembly (assemblyFile, null, null);
455 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
457 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
460 [MethodImplAttribute (MethodImplOptions.InternalCall)]
461 public extern int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args);
463 [MonoTODO ("No support for ExecuteAssembly")]
464 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
466 throw new NotImplementedException ();
469 [MethodImplAttribute (MethodImplOptions.InternalCall)]
470 private extern Assembly [] GetAssemblies (bool refOnly);
472 public Assembly [] GetAssemblies ()
474 return GetAssemblies (false);
477 [MethodImplAttribute (MethodImplOptions.InternalCall)]
478 public extern object GetData (string name);
480 public new Type GetType()
482 return base.GetType ();
485 public override object InitializeLifetimeService ()
490 [MethodImplAttribute (MethodImplOptions.InternalCall)]
491 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
493 public Assembly Load (AssemblyName assemblyRef)
495 return Load (assemblyRef, null);
498 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
500 if (assemblyRef == null)
501 throw new ArgumentNullException ("assemblyRef");
503 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
504 if (assemblyRef.CodeBase != null)
505 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
507 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
510 return LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
513 public Assembly Load (string assemblyString)
515 if (assemblyString == null)
516 throw new ArgumentNullException ("assemblyString");
518 return LoadAssembly (assemblyString, null, false);
521 public Assembly Load (string assemblyString, Evidence assemblySecurity)
523 return Load (assemblyString, assemblySecurity, false);
526 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
528 if (assemblyString == null)
529 throw new ArgumentNullException ("assemblyString");
531 return LoadAssembly (assemblyString, assemblySecurity, refonly);
534 public Assembly Load (byte[] rawAssembly)
536 return Load (rawAssembly, null, null);
539 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
541 return Load (rawAssembly, rawSymbolStore, null);
544 [MethodImplAttribute (MethodImplOptions.InternalCall)]
545 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
547 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
549 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
552 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
554 if (rawAssembly == null)
555 throw new ArgumentNullException ("rawAssembly");
557 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
558 assembly.FromByteArray = true;
562 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
563 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
565 if (domainPolicy == null)
566 throw new ArgumentNullException ("domainPolicy");
567 if (_granted != null) {
568 throw new PolicyException (Locale.GetText (
569 "An AppDomain policy is already specified."));
571 if (IsFinalizingForUnload ())
572 throw new AppDomainUnloadedException ();
574 PolicyStatement ps = domainPolicy.Resolve (_evidence);
575 _granted = ps.PermissionSet;
578 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
579 public void SetCachePath (string path)
581 SetupInformationNoCopy.CachePath = path;
584 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
585 public void SetPrincipalPolicy (PrincipalPolicy policy)
587 if (IsFinalizingForUnload ())
588 throw new AppDomainUnloadedException ();
590 _principalPolicy = policy;
594 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
595 public void SetShadowCopyFiles()
597 SetupInformationNoCopy.ShadowCopyFiles = "true";
600 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
601 public void SetShadowCopyPath (string path)
603 SetupInformationNoCopy.ShadowCopyDirectories = path;
606 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
607 public void SetThreadPrincipal (IPrincipal principal)
609 if (principal == null)
610 throw new ArgumentNullException ("principal");
611 if (_principal != null)
612 throw new PolicyException (Locale.GetText ("principal already present."));
613 if (IsFinalizingForUnload ())
614 throw new AppDomainUnloadedException ();
616 _principal = principal;
619 [MethodImplAttribute (MethodImplOptions.InternalCall)]
620 private static extern AppDomain InternalSetDomainByID (int domain_id);
622 // Changes the active domain and returns the old domain
623 [MethodImplAttribute (MethodImplOptions.InternalCall)]
624 private static extern AppDomain InternalSetDomain (AppDomain context);
626 // Notifies the runtime that this thread references 'domain'.
627 [MethodImplAttribute (MethodImplOptions.InternalCall)]
628 internal static extern void InternalPushDomainRef (AppDomain domain);
630 [MethodImplAttribute (MethodImplOptions.InternalCall)]
631 internal static extern void InternalPushDomainRefByID (int domain_id);
633 // Undoes the effect of the last PushDomainRef call
634 [MethodImplAttribute (MethodImplOptions.InternalCall)]
635 internal static extern void InternalPopDomainRef ();
637 // Changes the active context and returns the old context
638 [MethodImplAttribute (MethodImplOptions.InternalCall)]
639 internal static extern Context InternalSetContext (Context context);
641 // Returns the current context
642 [MethodImplAttribute (MethodImplOptions.InternalCall)]
643 internal static extern Context InternalGetContext ();
645 // Returns the current context
646 [MethodImplAttribute (MethodImplOptions.InternalCall)]
647 internal static extern Context InternalGetDefaultContext ();
649 [MethodImplAttribute (MethodImplOptions.InternalCall)]
650 internal static extern string InternalGetProcessGuid (string newguid);
652 // This method is handled specially by the runtime
653 // It is the only managed method which is allowed to set the current
655 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
657 AppDomain current = CurrentDomain;
661 InternalPushDomainRef (domain);
663 InternalSetDomain (domain);
664 return ((MonoMethod) method).InternalInvoke (obj, args);
667 InternalSetDomain (current);
669 InternalPopDomainRef ();
673 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
675 AppDomain current = CurrentDomain;
679 InternalPushDomainRefByID (domain_id);
681 InternalSetDomainByID (domain_id);
682 return ((MonoMethod) method).InternalInvoke (obj, args);
685 InternalSetDomain (current);
687 InternalPopDomainRef ();
691 internal static String GetProcessGuid ()
693 if (_process_guid == null) {
694 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
696 return _process_guid;
699 public static AppDomain CreateDomain (string friendlyName)
701 return CreateDomain (friendlyName, null, null);
704 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
706 return CreateDomain (friendlyName, securityInfo, null);
709 [MethodImplAttribute (MethodImplOptions.InternalCall)]
710 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
712 [MonoTODO ("Currently it does not allow the setup in the other domain")]
713 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
714 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
716 if (friendlyName == null)
717 throw new System.ArgumentNullException ("friendlyName");
719 AppDomain def = AppDomain.DefaultDomain;
721 // if null, get default domain's SetupInformation
723 info = new AppDomainSetup (); // we're default!
725 info = def.SetupInformation;
728 info = new AppDomainSetup (info); // copy
730 // todo: allow setup in the other domain
732 if (!info.Equals (def.SetupInformation)) {
733 // If not specified use default domain's app base.
734 if (info.ApplicationBase == null)
735 info.ApplicationBase = def.SetupInformation.ApplicationBase;
736 if (info.ConfigurationFile == null)
737 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
739 } else if (info.ConfigurationFile == null)
740 info.ConfigurationFile = "[I don't have a config file]";
742 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
743 if (securityInfo == null) {
744 // get default domain's Evidence (unless we're are the default!)
746 ad._evidence = null; // we'll get them later (GetEntryAssembly)
748 ad._evidence = def.Evidence; // new (shallow) copy
751 ad._evidence = new Evidence (securityInfo); // copy
754 if (info.AppDomainInitializer != null) {
755 if ((info.AppDomainInitializer.Method.Attributes & MethodAttributes.Static) == 0)
756 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
757 info.AppDomainInitializer (info.AppDomainInitializerArguments);
764 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
765 string appRelativeSearchPath, bool shadowCopyFiles)
767 AppDomainSetup info = new AppDomainSetup ();
769 info.ApplicationBase = appBasePath;
770 info.PrivateBinPath = appRelativeSearchPath;
773 info.ShadowCopyFiles = "true";
775 info.ShadowCopyFiles = "false";
777 return CreateDomain (friendlyName, securityInfo, info);
780 [MethodImplAttribute (MethodImplOptions.InternalCall)]
781 private static extern bool InternalIsFinalizingForUnload (int domain_id);
783 public bool IsFinalizingForUnload()
785 return InternalIsFinalizingForUnload (getDomainID ());
788 [MethodImplAttribute (MethodImplOptions.InternalCall)]
789 static extern void InternalUnload (int domain_id);
791 // We do this because if the domain is a transparant proxy this
792 // will still return the correct domain id.
793 private int getDomainID ()
795 return Thread.GetDomainID ();
798 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
800 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
802 public static void Unload (AppDomain domain)
805 throw new ArgumentNullException ("domain");
807 InternalUnload (domain.getDomainID());
810 [MethodImplAttribute (MethodImplOptions.InternalCall)]
811 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
812 public extern void SetData (string name, object data);
814 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
815 public void SetDynamicBase (string path)
817 SetupInformationNoCopy.DynamicBase = path;
823 public static int GetCurrentThreadId ()
825 return Thread.CurrentThreadId;
828 public override string ToString ()
830 return getFriendlyName ();
833 // The following methods are called from the runtime. Don't change signatures.
834 private void DoAssemblyLoad (Assembly assembly)
836 if (AssemblyLoad == null)
839 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
842 private Assembly DoAssemblyResolve (string name, bool refonly)
845 if (refonly && ReflectionOnlyAssemblyResolve == null)
848 if (AssemblyResolve == null)
851 /* Prevent infinite recursion */
852 Hashtable ht = assembly_resolve_in_progress;
854 ht = new Hashtable ();
855 assembly_resolve_in_progress = ht;
858 Assembly ass = (Assembly) ht [name];
860 if (ass != null && (ass.ReflectionOnly == refonly))
870 Delegate [] invocation_list = refonly ? ReflectionOnlyAssemblyResolve.GetInvocationList () :
871 AssemblyResolve.GetInvocationList ();
873 Delegate [] invocation_list = AssemblyResolve.GetInvocationList ();
876 foreach (Delegate eh in invocation_list) {
877 ResolveEventHandler handler = (ResolveEventHandler) eh;
878 Assembly assembly = handler (this, new ResolveEventArgs (name));
879 if (assembly != null)
889 internal Assembly DoTypeResolve (Object name_or_tb)
891 if (TypeResolve == null)
896 if (name_or_tb is TypeBuilder)
897 name = ((TypeBuilder) name_or_tb).FullName;
899 name = (string) name_or_tb;
901 /* Prevent infinite recursion */
902 Hashtable ht = type_resolve_in_progress;
904 ht = new Hashtable ();
905 type_resolve_in_progress = ht;
908 if (ht.Contains (name))
914 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
915 ResolveEventHandler eh = (ResolveEventHandler) d;
916 Assembly assembly = eh (this, new ResolveEventArgs (name));
917 if (assembly != null)
927 private void DoDomainUnload ()
929 if (DomainUnload != null)
930 DomainUnload(this, null);
933 internal byte[] GetMarshalledDomainObjRef ()
935 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
936 return CADSerializer.SerializeObject (oref).GetBuffer();
939 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
940 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
944 if (null != arrRequest)
945 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
947 reqDomMsg = new MethodCall (cadMsg);
949 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
951 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
952 if (null == cadMrm) {
953 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
959 // End of methods called from the runtime
961 #if BOOTSTRAP_WITH_OLDLIB
962 // older MCS/corlib returns:
963 // _AppDomain.cs(138) error CS0592: Attribute 'SecurityPermission' is not valid on this declaration type.
964 // It is valid on 'assembly' 'class' 'constructor' 'method' 'struct' declarations only.
965 public event AssemblyLoadEventHandler AssemblyLoad;
967 public event ResolveEventHandler AssemblyResolve;
969 public event EventHandler DomainUnload;
971 public event EventHandler ProcessExit;
973 public event ResolveEventHandler ResourceResolve;
975 public event ResolveEventHandler TypeResolve;
977 public event UnhandledExceptionEventHandler UnhandledException;
979 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
980 public event AssemblyLoadEventHandler AssemblyLoad;
982 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
983 public event ResolveEventHandler AssemblyResolve;
985 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
986 public event EventHandler DomainUnload;
988 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
989 public event EventHandler ProcessExit;
991 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
992 public event ResolveEventHandler ResourceResolve;
994 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
995 public event ResolveEventHandler TypeResolve;
997 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
998 public event UnhandledExceptionEventHandler UnhandledException;
1001 /* Avoid warnings for events used only by the runtime */
1002 private void DummyUse () {
1003 ProcessExit += (EventHandler)null;
1004 ResourceResolve += (ResolveEventHandler)null;
1005 UnhandledException += (UnhandledExceptionEventHandler)null;
1010 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1012 private ActivationContext _activation;
1013 private ApplicationIdentity _applicationIdentity;
1014 private AppDomainManager _domain_manager;
1018 public ActivationContext ActivationContext {
1019 get { return _activation; }
1022 public ApplicationIdentity ApplicationIdentity {
1023 get { return _applicationIdentity; }
1027 public AppDomainManager DomainManager {
1028 get { return _domain_manager; }
1032 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1033 get { return getDomainID (); }
1038 [MonoTODO ("This routine only returns the parameter currently")]
1039 [ComVisible (false)]
1040 public string ApplyPolicy (string assemblyName)
1042 if (assemblyName == null)
1043 throw new ArgumentNullException ("assemblyName");
1044 if (assemblyName.Length == 0) // String.Empty
1045 throw new ArgumentException ("assemblyName");
1046 return assemblyName;
1051 [MonoTODO ("add support for new delegate")]
1052 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1053 string appRelativeSearchPath, bool shadowCopy, AppDomainInitializer adInit, string[] adInitArgs)
1055 return CreateDomain (friendlyName, securityInfo, appBasePath, appRelativeSearchPath, shadowCopy);
1058 [MonoTODO ("resolve assemblyName to location")]
1059 public int ExecuteAssemblyByName (string assemblyName)
1061 return ExecuteAssemblyByName (assemblyName, null, null);
1064 [MonoTODO ("resolve assemblyName to location")]
1065 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1067 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1070 [MonoTODO ("resolve assemblyName to location")]
1071 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1073 if (assemblyName == null)
1074 throw new ArgumentNullException ("assemblyName");
1076 AssemblyName an = new AssemblyName (assemblyName);
1077 return ExecuteAssemblyByName (an, assemblySecurity, args);
1080 [MonoTODO ("assemblyName may not have a codebase")]
1081 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1083 if (assemblyName == null)
1084 throw new ArgumentNullException ("assemblyName");
1086 return ExecuteAssembly (assemblyName.CodeBase, assemblySecurity, args);
1089 public bool IsDefaultAppDomain ()
1091 return Object.ReferenceEquals (this, DefaultDomain);
1094 public Assembly[] ReflectionOnlyGetAssemblies ()
1096 return GetAssemblies (true);
1101 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1103 throw new NotImplementedException ();
1106 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1108 throw new NotImplementedException ();
1111 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1113 throw new NotImplementedException ();
1116 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1117 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1119 throw new NotImplementedException ();