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;
62 [ComDefaultInterface (typeof (_AppDomain))]
64 [ClassInterface(ClassInterfaceType.None)]
65 public sealed class AppDomain : MarshalByRefObject , _AppDomain , IEvidenceFactory
67 IntPtr _mono_app_domain;
68 static string _process_guid;
71 static Hashtable type_resolve_in_progress;
74 static Hashtable assembly_resolve_in_progress;
77 private Evidence _evidence;
78 private PermissionSet _granted;
81 private PrincipalPolicy _principalPolicy;
84 private static IPrincipal _principal;
86 static AppDomain default_domain;
92 [MethodImplAttribute (MethodImplOptions.InternalCall)]
93 private extern AppDomainSetup getSetup ();
95 AppDomainSetup SetupInformationNoCopy {
96 get { return getSetup (); }
99 public AppDomainSetup SetupInformation {
101 AppDomainSetup setup = getSetup ();
102 return new AppDomainSetup (setup);
108 public ApplicationTrust ApplicationTrust {
109 get { throw new NotImplementedException (); }
113 public string BaseDirectory {
115 string path = SetupInformationNoCopy.ApplicationBase;
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 RelativeSearchPath {
126 string path = SetupInformationNoCopy.PrivateBinPath;
127 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
128 // we cannot divulge local file informations
129 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
135 public string DynamicDirectory {
137 AppDomainSetup setup = SetupInformationNoCopy;
138 if (setup.DynamicBase == null)
141 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
142 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
143 // we cannot divulge local file informations
144 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
150 public bool ShadowCopyFiles {
152 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
156 [MethodImplAttribute (MethodImplOptions.InternalCall)]
157 private extern string getFriendlyName ();
159 public string FriendlyName {
161 return getFriendlyName ();
165 public Evidence Evidence {
167 // if the host (runtime) hasn't provided it's own evidence...
168 if (_evidence == null) {
169 // ... we will provide our own
171 // the executed assembly from the "default" appdomain
172 // or null if we're not in the default appdomain or
173 // if there is no entry assembly (embedded mono)
174 Assembly a = Assembly.GetEntryAssembly ();
176 if (this == DefaultDomain)
178 return new Evidence ();
180 _evidence = AppDomain.DefaultDomain.Evidence;
182 _evidence = Evidence.GetDefaultHostEvidence (a);
186 return new Evidence (_evidence); // return a copy
190 internal IPrincipal DefaultPrincipal {
192 if (_principal == null) {
193 switch (_principalPolicy) {
194 case PrincipalPolicy.UnauthenticatedPrincipal:
195 _principal = new GenericPrincipal (
196 new GenericIdentity (String.Empty, String.Empty), null);
198 case PrincipalPolicy.WindowsPrincipal:
199 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
207 // for AppDomain there is only an allowed (i.e. granted) set
208 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
209 internal PermissionSet GrantedPermissionSet {
210 get { return _granted; }
213 [MethodImplAttribute (MethodImplOptions.InternalCall)]
214 private static extern AppDomain getCurDomain ();
216 public static AppDomain CurrentDomain {
218 return getCurDomain ();
222 [MethodImplAttribute (MethodImplOptions.InternalCall)]
223 private static extern AppDomain getRootDomain ();
225 internal static AppDomain DefaultDomain {
227 if (default_domain == null) {
228 AppDomain rd = getRootDomain ();
229 if (rd == CurrentDomain)
232 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
234 return default_domain;
239 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
241 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
242 public void AppendPrivatePath (string path)
244 if (path == null || path.Length == 0)
247 AppDomainSetup setup = SetupInformationNoCopy;
249 string pp = setup.PrivateBinPath;
250 if (pp == null || pp.Length == 0) {
251 setup.PrivateBinPath = path;
256 if (pp [pp.Length - 1] != Path.PathSeparator)
257 pp += Path.PathSeparator;
259 setup.PrivateBinPath = pp + path;
263 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
265 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
266 public void ClearPrivatePath ()
268 SetupInformationNoCopy.PrivateBinPath = String.Empty;
272 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
274 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
275 public void ClearShadowCopyPath ()
277 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
280 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
282 return Activator.CreateComInstanceFrom (assemblyName, typeName);
286 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
287 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
289 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
293 public ObjectHandle CreateInstance (string assemblyName, string typeName)
295 if (assemblyName == null)
296 throw new ArgumentNullException ("assemblyName");
298 return Activator.CreateInstance (assemblyName, typeName);
301 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
303 if (assemblyName == null)
304 throw new ArgumentNullException ("assemblyName");
306 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
309 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
310 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
311 Evidence securityAttributes)
313 if (assemblyName == null)
314 throw new ArgumentNullException ("assemblyName");
316 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
317 culture, activationAttributes, securityAttributes);
320 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
322 ObjectHandle oh = CreateInstance (assemblyName, typeName);
323 return (oh != null) ? oh.Unwrap () : null;
326 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
328 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
329 return (oh != null) ? oh.Unwrap () : null;
332 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
333 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
334 object[] activationAttributes, Evidence securityAttributes)
336 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
337 culture, activationAttributes, securityAttributes);
338 return (oh != null) ? oh.Unwrap () : null;
341 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
343 if (assemblyFile == null)
344 throw new ArgumentNullException ("assemblyFile");
346 return Activator.CreateInstanceFrom (assemblyFile, typeName);
349 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
351 if (assemblyFile == null)
352 throw new ArgumentNullException ("assemblyFile");
354 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
357 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
358 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
359 object[] activationAttributes, Evidence securityAttributes)
361 if (assemblyFile == null)
362 throw new ArgumentNullException ("assemblyFile");
364 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
365 culture, activationAttributes, securityAttributes);
368 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
370 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
371 return (oh != null) ? oh.Unwrap () : null;
374 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
376 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
377 return (oh != null) ? oh.Unwrap () : null;
380 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
381 BindingFlags bindingAttr, Binder binder, object[] args,
382 CultureInfo culture, object[] activationAttributes,
383 Evidence securityAttributes)
385 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
386 culture, activationAttributes, securityAttributes);
388 return (oh != null) ? oh.Unwrap () : null;
391 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
393 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
396 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
398 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
401 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
403 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
406 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
409 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
412 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
413 PermissionSet requiredPermissions,
414 PermissionSet optionalPermissions,
415 PermissionSet refusedPermissions)
417 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
418 refusedPermissions, false);
421 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
422 PermissionSet requiredPermissions,
423 PermissionSet optionalPermissions,
424 PermissionSet refusedPermissions)
426 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
427 refusedPermissions, false);
430 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
431 PermissionSet requiredPermissions,
432 PermissionSet optionalPermissions,
433 PermissionSet refusedPermissions)
435 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
436 refusedPermissions, false);
439 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
441 PermissionSet requiredPermissions,
442 PermissionSet optionalPermissions,
443 PermissionSet refusedPermissions)
445 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
446 refusedPermissions, false);
449 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
451 PermissionSet requiredPermissions,
452 PermissionSet optionalPermissions,
453 PermissionSet refusedPermissions, bool isSynchronized)
456 throw new ArgumentNullException ("name");
457 ValidateAssemblyName (name.Name);
459 // FIXME: examine all other parameters
461 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
462 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
468 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
470 PermissionSet requiredPermissions,
471 PermissionSet optionalPermissions,
472 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
474 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
475 if (assemblyAttributes != null)
476 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
477 ab.SetCustomAttribute (cb);
483 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
484 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
489 // TODO: the last parameter is ignored for now
490 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, bool emitSymbolInfo)
492 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
496 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
498 return new AssemblyBuilder (name, null, access, true);
502 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
503 // so, when you call AppDomain.DoCallBack, that's a remote call
505 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
507 if (callBackDelegate != null)
511 public int ExecuteAssembly (string assemblyFile)
513 return ExecuteAssembly (assemblyFile, null, null);
516 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
518 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
521 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
523 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
524 return ExecuteAssemblyInternal (a, args);
527 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
529 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
530 return ExecuteAssemblyInternal (a, args);
533 int ExecuteAssemblyInternal (Assembly a, string[] args)
535 if (a.EntryPoint == null)
537 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
539 throw new COMException ("Unspecified error.", -2147467259);
541 return ExecuteAssembly (a, args);
544 [MethodImplAttribute (MethodImplOptions.InternalCall)]
545 private extern int ExecuteAssembly (Assembly a, string[] args);
547 [MethodImplAttribute (MethodImplOptions.InternalCall)]
548 private extern Assembly [] GetAssemblies (bool refOnly);
550 public Assembly [] GetAssemblies ()
552 return GetAssemblies (false);
555 [MethodImplAttribute (MethodImplOptions.InternalCall)]
556 public extern object GetData (string name);
558 public new Type GetType()
560 return base.GetType ();
563 public override object InitializeLifetimeService ()
568 [MethodImplAttribute (MethodImplOptions.InternalCall)]
569 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
571 public Assembly Load (AssemblyName assemblyRef)
573 return Load (assemblyRef, null);
576 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
578 if (assemblyRef == null)
579 throw new ArgumentNullException ("assemblyRef");
581 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
582 if (assemblyRef.CodeBase != null)
583 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
585 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
588 return LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
591 public Assembly Load (string assemblyString)
593 return Load (assemblyString, null, false);
596 public Assembly Load (string assemblyString, Evidence assemblySecurity)
598 return Load (assemblyString, assemblySecurity, false);
601 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
603 if (assemblyString == null)
604 throw new ArgumentNullException ("assemblyString");
606 if (assemblyString.Length == 0)
607 throw new ArgumentException ("assemblyString cannot have zero length");
609 return LoadAssembly (assemblyString, assemblySecurity, refonly);
612 public Assembly Load (byte[] rawAssembly)
614 return Load (rawAssembly, null, null);
617 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
619 return Load (rawAssembly, rawSymbolStore, null);
622 [MethodImplAttribute (MethodImplOptions.InternalCall)]
623 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
625 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
627 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
630 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
632 if (rawAssembly == null)
633 throw new ArgumentNullException ("rawAssembly");
635 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
636 assembly.FromByteArray = true;
640 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
641 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
643 if (domainPolicy == null)
644 throw new ArgumentNullException ("domainPolicy");
645 if (_granted != null) {
646 throw new PolicyException (Locale.GetText (
647 "An AppDomain policy is already specified."));
649 if (IsFinalizingForUnload ())
650 throw new AppDomainUnloadedException ();
652 PolicyStatement ps = domainPolicy.Resolve (_evidence);
653 _granted = ps.PermissionSet;
657 [Obsolete ("Use AppDomainSetup.SetCachePath")]
659 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
660 public void SetCachePath (string path)
662 SetupInformationNoCopy.CachePath = path;
665 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
666 public void SetPrincipalPolicy (PrincipalPolicy policy)
668 if (IsFinalizingForUnload ())
669 throw new AppDomainUnloadedException ();
671 _principalPolicy = policy;
676 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
678 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
679 public void SetShadowCopyFiles()
681 SetupInformationNoCopy.ShadowCopyFiles = "true";
685 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
687 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
688 public void SetShadowCopyPath (string path)
690 SetupInformationNoCopy.ShadowCopyDirectories = path;
693 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
694 public void SetThreadPrincipal (IPrincipal principal)
696 if (principal == null)
697 throw new ArgumentNullException ("principal");
698 if (_principal != null)
699 throw new PolicyException (Locale.GetText ("principal already present."));
700 if (IsFinalizingForUnload ())
701 throw new AppDomainUnloadedException ();
703 _principal = principal;
706 [MethodImplAttribute (MethodImplOptions.InternalCall)]
707 private static extern AppDomain InternalSetDomainByID (int domain_id);
709 // Changes the active domain and returns the old domain
710 [MethodImplAttribute (MethodImplOptions.InternalCall)]
711 private static extern AppDomain InternalSetDomain (AppDomain context);
713 // Notifies the runtime that this thread references 'domain'.
714 [MethodImplAttribute (MethodImplOptions.InternalCall)]
715 internal static extern void InternalPushDomainRef (AppDomain domain);
717 [MethodImplAttribute (MethodImplOptions.InternalCall)]
718 internal static extern void InternalPushDomainRefByID (int domain_id);
720 // Undoes the effect of the last PushDomainRef call
721 [MethodImplAttribute (MethodImplOptions.InternalCall)]
722 internal static extern void InternalPopDomainRef ();
724 // Changes the active context and returns the old context
725 [MethodImplAttribute (MethodImplOptions.InternalCall)]
726 internal static extern Context InternalSetContext (Context context);
728 // Returns the current context
729 [MethodImplAttribute (MethodImplOptions.InternalCall)]
730 internal static extern Context InternalGetContext ();
732 // Returns the current context
733 [MethodImplAttribute (MethodImplOptions.InternalCall)]
734 internal static extern Context InternalGetDefaultContext ();
736 [MethodImplAttribute (MethodImplOptions.InternalCall)]
737 internal static extern string InternalGetProcessGuid (string newguid);
739 // This method is handled specially by the runtime
740 // It is the only managed method which is allowed to set the current
742 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
744 AppDomain current = CurrentDomain;
749 InternalPushDomainRef (domain);
751 InternalSetDomain (domain);
752 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
758 InternalSetDomain (current);
760 InternalPopDomainRef ();
764 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
766 AppDomain current = CurrentDomain;
771 InternalPushDomainRefByID (domain_id);
773 InternalSetDomainByID (domain_id);
774 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
780 InternalSetDomain (current);
782 InternalPopDomainRef ();
786 internal static String GetProcessGuid ()
788 if (_process_guid == null) {
789 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
791 return _process_guid;
794 public static AppDomain CreateDomain (string friendlyName)
796 return CreateDomain (friendlyName, null, null);
799 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
801 return CreateDomain (friendlyName, securityInfo, null);
804 [MethodImplAttribute (MethodImplOptions.InternalCall)]
805 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
807 [MonoTODO ("Currently it does not allow the setup in the other domain")]
808 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
809 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
811 if (friendlyName == null)
812 throw new System.ArgumentNullException ("friendlyName");
814 AppDomain def = AppDomain.DefaultDomain;
816 // if null, get default domain's SetupInformation
818 info = new AppDomainSetup (); // we're default!
820 info = def.SetupInformation;
823 info = new AppDomainSetup (info); // copy
825 // todo: allow setup in the other domain
827 if (!info.Equals (def.SetupInformation)) {
828 // If not specified use default domain's app base.
829 if (info.ApplicationBase == null)
830 info.ApplicationBase = def.SetupInformation.ApplicationBase;
831 if (info.ConfigurationFile == null)
832 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
834 } else if (info.ConfigurationFile == null)
835 info.ConfigurationFile = "[I don't have a config file]";
837 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
838 if (securityInfo == null) {
839 // get default domain's Evidence (unless we're are the default!)
841 ad._evidence = null; // we'll get them later (GetEntryAssembly)
843 ad._evidence = def.Evidence; // new (shallow) copy
846 ad._evidence = new Evidence (securityInfo); // copy
849 if (info.AppDomainInitializer != null) {
850 if ((info.AppDomainInitializer.Method.Attributes & MethodAttributes.Static) == 0)
851 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
852 info.AppDomainInitializer (info.AppDomainInitializerArguments);
859 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
860 string appRelativeSearchPath, bool shadowCopyFiles)
862 AppDomainSetup info = new AppDomainSetup ();
864 info.ApplicationBase = appBasePath;
865 info.PrivateBinPath = appRelativeSearchPath;
868 info.ShadowCopyFiles = "true";
870 info.ShadowCopyFiles = "false";
872 return CreateDomain (friendlyName, securityInfo, info);
877 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
878 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
880 throw new NotImplementedException ();
884 [MethodImplAttribute (MethodImplOptions.InternalCall)]
885 private static extern bool InternalIsFinalizingForUnload (int domain_id);
887 public bool IsFinalizingForUnload()
889 return InternalIsFinalizingForUnload (getDomainID ());
892 [MethodImplAttribute (MethodImplOptions.InternalCall)]
893 static extern void InternalUnload (int domain_id);
895 // We do this because if the domain is a transparant proxy this
896 // will still return the correct domain id.
897 private int getDomainID ()
899 return Thread.GetDomainID ();
902 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
904 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
906 public static void Unload (AppDomain domain)
909 throw new ArgumentNullException ("domain");
911 InternalUnload (domain.getDomainID());
914 [MethodImplAttribute (MethodImplOptions.InternalCall)]
915 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
916 public extern void SetData (string name, object data);
920 public void SetData (string name, object data, IPermission permission)
922 throw new NotImplementedException ();
927 [Obsolete ("Use AppDomainSetup.DynamicBase")]
929 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
930 public void SetDynamicBase (string path)
932 SetupInformationNoCopy.DynamicBase = path;
936 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
937 + " because it does not provide a stable Id when managed"
938 + " threads are running on fibers (aka lightweight"
939 + " threads). To get a stable identifier for a managed"
940 + " thread, use the ManagedThreadId property on Thread.'")]
942 public static int GetCurrentThreadId ()
944 return Thread.CurrentThreadId;
947 public override string ToString ()
949 return getFriendlyName ();
952 private static void ValidateAssemblyName (string name)
954 if (name == null || name.Length == 0)
955 throw new ArgumentException ("The Name of " +
956 "AssemblyName cannot be null or a " +
957 "zero-length string.");
961 for (int i = 0; i < name.Length; i++) {
964 // do not allow leading whitespace
965 if (i == 0 && char.IsWhiteSpace (c)) {
970 // do not allow /,\ or : in name
971 if (c == '/' || c == '\\' || c == ':') {
978 throw new ArgumentException ("The Name of " +
979 "AssemblyName cannot start with " +
980 "whitespace, or contain '/', '\\' " +
984 // The following methods are called from the runtime. Don't change signatures.
985 private void DoAssemblyLoad (Assembly assembly)
987 if (AssemblyLoad == null)
990 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
993 private Assembly DoAssemblyResolve (string name, bool refonly)
995 ResolveEventHandler del;
998 del = ReflectionOnlyAssemblyResolve;
1000 del = AssemblyResolve;
1002 del = AssemblyResolve;
1007 /* Prevent infinite recursion */
1008 Hashtable ht = assembly_resolve_in_progress;
1010 ht = new Hashtable ();
1011 assembly_resolve_in_progress = ht;
1014 Assembly ass = (Assembly) ht [name];
1016 if (ass != null && (ass.ReflectionOnly == refonly))
1024 Delegate[] invocation_list = del.GetInvocationList ();
1026 foreach (Delegate eh in invocation_list) {
1027 ResolveEventHandler handler = (ResolveEventHandler) eh;
1028 Assembly assembly = handler (this, new ResolveEventArgs (name));
1029 if (assembly != null)
1039 internal Assembly DoTypeResolve (Object name_or_tb)
1041 if (TypeResolve == null)
1046 if (name_or_tb is TypeBuilder)
1047 name = ((TypeBuilder) name_or_tb).FullName;
1049 name = (string) name_or_tb;
1051 /* Prevent infinite recursion */
1052 Hashtable ht = type_resolve_in_progress;
1054 ht = new Hashtable ();
1055 type_resolve_in_progress = ht;
1058 if (ht.Contains (name))
1064 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1065 ResolveEventHandler eh = (ResolveEventHandler) d;
1066 Assembly assembly = eh (this, new ResolveEventArgs (name));
1067 if (assembly != null)
1077 private void DoDomainUnload ()
1079 if (DomainUnload != null)
1080 DomainUnload(this, null);
1083 internal byte[] GetMarshalledDomainObjRef ()
1085 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1086 return CADSerializer.SerializeObject (oref).GetBuffer();
1089 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1090 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1094 if (null != arrRequest)
1095 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1097 reqDomMsg = new MethodCall (cadMsg);
1099 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1101 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1102 if (null == cadMrm) {
1103 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1109 // End of methods called from the runtime
1111 #if BOOTSTRAP_WITH_OLDLIB
1112 // older MCS/corlib returns:
1113 // _AppDomain.cs(138) error CS0592: Attribute 'SecurityPermission' is not valid on this declaration type.
1114 // It is valid on 'assembly' 'class' 'constructor' 'method' 'struct' declarations only.
1115 public event AssemblyLoadEventHandler AssemblyLoad;
1117 public event ResolveEventHandler AssemblyResolve;
1119 public event EventHandler DomainUnload;
1121 public event EventHandler ProcessExit;
1123 public event ResolveEventHandler ResourceResolve;
1125 public event ResolveEventHandler TypeResolve;
1127 public event UnhandledExceptionEventHandler UnhandledException;
1129 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1130 public event AssemblyLoadEventHandler AssemblyLoad;
1132 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1133 public event ResolveEventHandler AssemblyResolve;
1135 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1136 public event EventHandler DomainUnload;
1138 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1139 public event EventHandler ProcessExit;
1141 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1142 public event ResolveEventHandler ResourceResolve;
1144 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1145 public event ResolveEventHandler TypeResolve;
1147 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1148 public event UnhandledExceptionEventHandler UnhandledException;
1151 /* Avoid warnings for events used only by the runtime */
1152 private void DummyUse () {
1153 ProcessExit += (EventHandler)null;
1154 ResourceResolve += (ResolveEventHandler)null;
1155 UnhandledException += (UnhandledExceptionEventHandler)null;
1160 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1162 private ActivationContext _activation;
1163 private ApplicationIdentity _applicationIdentity;
1164 private AppDomainManager _domain_manager;
1168 public ActivationContext ActivationContext {
1169 get { return _activation; }
1172 public ApplicationIdentity ApplicationIdentity {
1173 get { return _applicationIdentity; }
1177 public AppDomainManager DomainManager {
1178 get { return _domain_manager; }
1182 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1183 get { return getDomainID (); }
1188 [MonoTODO ("This routine only returns the parameter currently")]
1189 [ComVisible (false)]
1190 public string ApplyPolicy (string assemblyName)
1192 if (assemblyName == null)
1193 throw new ArgumentNullException ("assemblyName");
1194 if (assemblyName.Length == 0) // String.Empty
1195 throw new ArgumentException ("assemblyName");
1196 return assemblyName;
1201 [MonoTODO ("add support for new delegate")]
1202 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1203 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1205 return CreateDomain (friendlyName, securityInfo, appBasePath, appRelativeSearchPath, shadowCopyFiles);
1208 public int ExecuteAssemblyByName (string assemblyName)
1210 return ExecuteAssemblyByName (assemblyName, null, null);
1213 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1215 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1218 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1220 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1222 return ExecuteAssemblyInternal (a, args);
1225 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1227 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1229 return ExecuteAssemblyInternal (a, args);
1232 public bool IsDefaultAppDomain ()
1234 return Object.ReferenceEquals (this, DefaultDomain);
1237 public Assembly[] ReflectionOnlyGetAssemblies ()
1239 return GetAssemblies (true);
1244 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1246 throw new NotImplementedException ();
1249 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1251 throw new NotImplementedException ();
1254 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1256 throw new NotImplementedException ();
1259 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1260 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1262 throw new NotImplementedException ();