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 #pragma warning disable 169
68 #region Sync with object-internals.h
69 IntPtr _mono_app_domain;
71 #pragma warning restore 169
72 static string _process_guid;
75 static Hashtable type_resolve_in_progress;
78 static Hashtable assembly_resolve_in_progress;
81 static Hashtable assembly_resolve_in_progress_refonly;
84 private Evidence _evidence;
85 private PermissionSet _granted;
88 private PrincipalPolicy _principalPolicy;
91 private static IPrincipal _principal;
93 static AppDomain default_domain;
99 [MethodImplAttribute (MethodImplOptions.InternalCall)]
100 private extern AppDomainSetup getSetup ();
102 AppDomainSetup SetupInformationNoCopy {
103 get { return getSetup (); }
106 public AppDomainSetup SetupInformation {
108 AppDomainSetup setup = getSetup ();
109 return new AppDomainSetup (setup);
115 public ApplicationTrust ApplicationTrust {
116 get { throw new NotImplementedException (); }
120 public string BaseDirectory {
122 string path = SetupInformationNoCopy.ApplicationBase;
124 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
125 // we cannot divulge local file informations
126 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
133 public string RelativeSearchPath {
135 string path = SetupInformationNoCopy.PrivateBinPath;
137 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
138 // we cannot divulge local file informations
139 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
146 public string DynamicDirectory {
148 AppDomainSetup setup = SetupInformationNoCopy;
149 if (setup.DynamicBase == null)
152 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
154 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
155 // we cannot divulge local file informations
156 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
163 public bool ShadowCopyFiles {
165 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
169 [MethodImplAttribute (MethodImplOptions.InternalCall)]
170 private extern string getFriendlyName ();
172 public string FriendlyName {
174 return getFriendlyName ();
178 public Evidence Evidence {
180 // if the host (runtime) hasn't provided it's own evidence...
181 if (_evidence == null) {
182 // ... we will provide our own
184 // the executed assembly from the "default" appdomain
185 // or null if we're not in the default appdomain or
186 // if there is no entry assembly (embedded mono)
187 Assembly a = Assembly.GetEntryAssembly ();
189 if (this == DefaultDomain)
191 return new Evidence ();
193 _evidence = AppDomain.DefaultDomain.Evidence;
195 _evidence = Evidence.GetDefaultHostEvidence (a);
199 return new Evidence (_evidence); // return a copy
203 internal IPrincipal DefaultPrincipal {
205 if (_principal == null) {
206 switch (_principalPolicy) {
207 case PrincipalPolicy.UnauthenticatedPrincipal:
208 _principal = new GenericPrincipal (
209 new GenericIdentity (String.Empty, String.Empty), null);
211 case PrincipalPolicy.WindowsPrincipal:
212 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
220 // for AppDomain there is only an allowed (i.e. granted) set
221 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
222 internal PermissionSet GrantedPermissionSet {
223 get { return _granted; }
226 [MethodImplAttribute (MethodImplOptions.InternalCall)]
227 private static extern AppDomain getCurDomain ();
229 public static AppDomain CurrentDomain {
231 return getCurDomain ();
235 [MethodImplAttribute (MethodImplOptions.InternalCall)]
236 private static extern AppDomain getRootDomain ();
238 internal static AppDomain DefaultDomain {
240 if (default_domain == null) {
241 AppDomain rd = getRootDomain ();
242 if (rd == CurrentDomain)
245 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
247 return default_domain;
252 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
254 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
255 public void AppendPrivatePath (string path)
257 if (path == null || path.Length == 0)
260 AppDomainSetup setup = SetupInformationNoCopy;
262 string pp = setup.PrivateBinPath;
263 if (pp == null || pp.Length == 0) {
264 setup.PrivateBinPath = path;
269 if (pp [pp.Length - 1] != Path.PathSeparator)
270 pp += Path.PathSeparator;
272 setup.PrivateBinPath = pp + path;
276 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
278 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
279 public void ClearPrivatePath ()
281 SetupInformationNoCopy.PrivateBinPath = String.Empty;
285 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
287 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
288 public void ClearShadowCopyPath ()
290 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
293 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
295 return Activator.CreateComInstanceFrom (assemblyName, typeName);
299 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
300 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
302 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
306 public ObjectHandle CreateInstance (string assemblyName, string typeName)
308 if (assemblyName == null)
309 throw new ArgumentNullException ("assemblyName");
311 return Activator.CreateInstance (assemblyName, typeName);
314 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
316 if (assemblyName == null)
317 throw new ArgumentNullException ("assemblyName");
319 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
322 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
323 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
324 Evidence securityAttributes)
326 if (assemblyName == null)
327 throw new ArgumentNullException ("assemblyName");
329 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
330 culture, activationAttributes, securityAttributes);
333 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
335 ObjectHandle oh = CreateInstance (assemblyName, typeName);
336 return (oh != null) ? oh.Unwrap () : null;
339 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
341 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
342 return (oh != null) ? oh.Unwrap () : null;
345 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
346 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
347 object[] activationAttributes, Evidence securityAttributes)
349 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
350 culture, activationAttributes, securityAttributes);
351 return (oh != null) ? oh.Unwrap () : null;
354 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
356 if (assemblyFile == null)
357 throw new ArgumentNullException ("assemblyFile");
359 return Activator.CreateInstanceFrom (assemblyFile, typeName);
362 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
364 if (assemblyFile == null)
365 throw new ArgumentNullException ("assemblyFile");
367 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
370 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
371 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
372 object[] activationAttributes, Evidence securityAttributes)
374 if (assemblyFile == null)
375 throw new ArgumentNullException ("assemblyFile");
377 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
378 culture, activationAttributes, securityAttributes);
381 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
383 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
384 return (oh != null) ? oh.Unwrap () : null;
387 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
389 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
390 return (oh != null) ? oh.Unwrap () : null;
393 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
394 BindingFlags bindingAttr, Binder binder, object[] args,
395 CultureInfo culture, object[] activationAttributes,
396 Evidence securityAttributes)
398 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
399 culture, activationAttributes, securityAttributes);
401 return (oh != null) ? oh.Unwrap () : null;
404 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
406 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
409 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
411 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
414 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
416 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
419 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
422 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
425 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
426 PermissionSet requiredPermissions,
427 PermissionSet optionalPermissions,
428 PermissionSet refusedPermissions)
430 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
431 refusedPermissions, false);
434 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
435 PermissionSet requiredPermissions,
436 PermissionSet optionalPermissions,
437 PermissionSet refusedPermissions)
439 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
440 refusedPermissions, false);
443 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
444 PermissionSet requiredPermissions,
445 PermissionSet optionalPermissions,
446 PermissionSet refusedPermissions)
448 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
449 refusedPermissions, false);
452 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
454 PermissionSet requiredPermissions,
455 PermissionSet optionalPermissions,
456 PermissionSet refusedPermissions)
458 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
459 refusedPermissions, false);
462 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
464 PermissionSet requiredPermissions,
465 PermissionSet optionalPermissions,
466 PermissionSet refusedPermissions, bool isSynchronized)
469 throw new ArgumentNullException ("name");
470 ValidateAssemblyName (name.Name);
472 // FIXME: examine all other parameters
474 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
475 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
481 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
483 PermissionSet requiredPermissions,
484 PermissionSet optionalPermissions,
485 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
487 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
488 if (assemblyAttributes != null)
489 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
490 ab.SetCustomAttribute (cb);
496 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
497 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
502 // TODO: the last parameter is ignored for now
503 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, bool emitSymbolInfo)
505 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
509 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
511 return new AssemblyBuilder (name, null, access, true);
515 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
516 // so, when you call AppDomain.DoCallBack, that's a remote call
518 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
520 if (callBackDelegate != null)
524 public int ExecuteAssembly (string assemblyFile)
526 return ExecuteAssembly (assemblyFile, null, null);
529 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
531 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
534 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
536 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
537 return ExecuteAssemblyInternal (a, args);
540 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
542 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
543 return ExecuteAssemblyInternal (a, args);
546 int ExecuteAssemblyInternal (Assembly a, string[] args)
548 if (a.EntryPoint == null)
550 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
552 throw new COMException ("Unspecified error.", -2147467259);
554 return ExecuteAssembly (a, args);
557 [MethodImplAttribute (MethodImplOptions.InternalCall)]
558 private extern int ExecuteAssembly (Assembly a, string[] args);
560 [MethodImplAttribute (MethodImplOptions.InternalCall)]
561 private extern Assembly [] GetAssemblies (bool refOnly);
563 public Assembly [] GetAssemblies ()
565 return GetAssemblies (false);
568 [MethodImplAttribute (MethodImplOptions.InternalCall)]
569 public extern object GetData (string name);
571 public new Type GetType()
573 return base.GetType ();
576 public override object InitializeLifetimeService ()
581 [MethodImplAttribute (MethodImplOptions.InternalCall)]
582 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
584 public Assembly Load (AssemblyName assemblyRef)
586 return Load (assemblyRef, null);
589 internal Assembly LoadSatellite (AssemblyName assemblyRef)
591 if (assemblyRef == null)
592 throw new ArgumentNullException ("assemblyRef");
594 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
596 throw new FileNotFoundException (null, assemblyRef.Name);
600 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
602 if (assemblyRef == null)
603 throw new ArgumentNullException ("assemblyRef");
605 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
606 if (assemblyRef.CodeBase != null)
607 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
609 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
612 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
613 if (assembly != null)
616 if (assemblyRef.CodeBase == null)
617 throw new FileNotFoundException (null, assemblyRef.Name);
619 string cb = assemblyRef.CodeBase;
620 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
621 cb = new Mono.Security.Uri (cb).LocalPath;
624 assembly = Assembly.LoadFrom (cb, assemblySecurity);
626 throw new FileNotFoundException (null, assemblyRef.Name);
628 AssemblyName aname = assembly.GetName ();
629 // Name, version, culture, publickeytoken. Anything else?
630 if (assemblyRef.Name != aname.Name)
631 throw new FileNotFoundException (null, assemblyRef.Name);
633 if (assemblyRef.Version != new Version () && assemblyRef.Version != aname.Version)
634 throw new FileNotFoundException (null, assemblyRef.Name);
636 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
637 throw new FileNotFoundException (null, assemblyRef.Name);
639 byte [] pt = assemblyRef.GetPublicKeyToken ();
641 byte [] loaded_pt = aname.GetPublicKeyToken ();
642 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
643 throw new FileNotFoundException (null, assemblyRef.Name);
644 for (int i = pt.Length - 1; i >= 0; i--)
645 if (loaded_pt [i] != pt [i])
646 throw new FileNotFoundException (null, assemblyRef.Name);
651 public Assembly Load (string assemblyString)
653 return Load (assemblyString, null, false);
656 public Assembly Load (string assemblyString, Evidence assemblySecurity)
658 return Load (assemblyString, assemblySecurity, false);
661 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
663 if (assemblyString == null)
664 throw new ArgumentNullException ("assemblyString");
666 if (assemblyString.Length == 0)
667 throw new ArgumentException ("assemblyString cannot have zero length");
669 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
670 if (assembly == null)
671 throw new FileNotFoundException (null, assemblyString);
675 public Assembly Load (byte[] rawAssembly)
677 return Load (rawAssembly, null, null);
680 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
682 return Load (rawAssembly, rawSymbolStore, null);
685 [MethodImplAttribute (MethodImplOptions.InternalCall)]
686 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
688 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
690 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
693 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
695 if (rawAssembly == null)
696 throw new ArgumentNullException ("rawAssembly");
698 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
699 assembly.FromByteArray = true;
703 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
704 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
706 if (domainPolicy == null)
707 throw new ArgumentNullException ("domainPolicy");
708 if (_granted != null) {
709 throw new PolicyException (Locale.GetText (
710 "An AppDomain policy is already specified."));
712 if (IsFinalizingForUnload ())
713 throw new AppDomainUnloadedException ();
715 PolicyStatement ps = domainPolicy.Resolve (_evidence);
716 _granted = ps.PermissionSet;
720 [Obsolete ("Use AppDomainSetup.SetCachePath")]
722 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
723 public void SetCachePath (string path)
725 SetupInformationNoCopy.CachePath = path;
728 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
729 public void SetPrincipalPolicy (PrincipalPolicy policy)
731 if (IsFinalizingForUnload ())
732 throw new AppDomainUnloadedException ();
734 _principalPolicy = policy;
739 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
741 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
742 public void SetShadowCopyFiles()
744 SetupInformationNoCopy.ShadowCopyFiles = "true";
748 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
750 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
751 public void SetShadowCopyPath (string path)
753 SetupInformationNoCopy.ShadowCopyDirectories = path;
756 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
757 public void SetThreadPrincipal (IPrincipal principal)
759 if (principal == null)
760 throw new ArgumentNullException ("principal");
761 if (_principal != null)
762 throw new PolicyException (Locale.GetText ("principal already present."));
763 if (IsFinalizingForUnload ())
764 throw new AppDomainUnloadedException ();
766 _principal = principal;
769 [MethodImplAttribute (MethodImplOptions.InternalCall)]
770 private static extern AppDomain InternalSetDomainByID (int domain_id);
772 // Changes the active domain and returns the old domain
773 [MethodImplAttribute (MethodImplOptions.InternalCall)]
774 private static extern AppDomain InternalSetDomain (AppDomain context);
776 // Notifies the runtime that this thread references 'domain'.
777 [MethodImplAttribute (MethodImplOptions.InternalCall)]
778 internal static extern void InternalPushDomainRef (AppDomain domain);
780 [MethodImplAttribute (MethodImplOptions.InternalCall)]
781 internal static extern void InternalPushDomainRefByID (int domain_id);
783 // Undoes the effect of the last PushDomainRef call
784 [MethodImplAttribute (MethodImplOptions.InternalCall)]
785 internal static extern void InternalPopDomainRef ();
787 // Changes the active context and returns the old context
788 [MethodImplAttribute (MethodImplOptions.InternalCall)]
789 internal static extern Context InternalSetContext (Context context);
791 // Returns the current context
792 [MethodImplAttribute (MethodImplOptions.InternalCall)]
793 internal static extern Context InternalGetContext ();
795 // Returns the current context
796 [MethodImplAttribute (MethodImplOptions.InternalCall)]
797 internal static extern Context InternalGetDefaultContext ();
799 [MethodImplAttribute (MethodImplOptions.InternalCall)]
800 internal static extern string InternalGetProcessGuid (string newguid);
802 // This method is handled specially by the runtime
803 // It is the only managed method which is allowed to set the current
805 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
807 AppDomain current = CurrentDomain;
812 InternalPushDomainRef (domain);
814 InternalSetDomain (domain);
815 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
821 InternalSetDomain (current);
823 InternalPopDomainRef ();
827 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
829 AppDomain current = CurrentDomain;
834 InternalPushDomainRefByID (domain_id);
836 InternalSetDomainByID (domain_id);
837 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
843 InternalSetDomain (current);
845 InternalPopDomainRef ();
849 internal static String GetProcessGuid ()
851 if (_process_guid == null) {
852 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
854 return _process_guid;
857 public static AppDomain CreateDomain (string friendlyName)
859 return CreateDomain (friendlyName, null, null);
862 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
864 return CreateDomain (friendlyName, securityInfo, null);
867 [MethodImplAttribute (MethodImplOptions.InternalCall)]
868 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
870 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
871 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
872 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
874 if (friendlyName == null)
875 throw new System.ArgumentNullException ("friendlyName");
877 AppDomain def = AppDomain.DefaultDomain;
879 // if null, get default domain's SetupInformation
881 info = new AppDomainSetup (); // we're default!
883 info = def.SetupInformation;
886 info = new AppDomainSetup (info); // copy
888 // todo: allow setup in the other domain
890 if (!info.Equals (def.SetupInformation)) {
891 // If not specified use default domain's app base.
892 if (info.ApplicationBase == null)
893 info.ApplicationBase = def.SetupInformation.ApplicationBase;
894 if (info.ConfigurationFile == null)
895 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
897 } else if (info.ConfigurationFile == null)
898 info.ConfigurationFile = "[I don't have a config file]";
900 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
901 if (securityInfo == null) {
902 // get default domain's Evidence (unless we're are the default!)
904 ad._evidence = null; // we'll get them later (GetEntryAssembly)
906 ad._evidence = def.Evidence; // new (shallow) copy
909 ad._evidence = new Evidence (securityInfo); // copy
912 if (info.AppDomainInitializer != null) {
913 if (!info.AppDomainInitializer.Method.IsStatic)
914 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
916 Loader loader = new Loader (
917 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
918 ad.DoCallBack (loader.Load);
920 Initializer initializer = new Initializer (
921 info.AppDomainInitializer,
922 info.AppDomainInitializerArguments);
923 ad.DoCallBack (initializer.Initialize);
936 public Loader (string assembly)
938 this.assembly = assembly;
943 Assembly.LoadFrom (assembly);
950 AppDomainInitializer initializer;
953 public Initializer (AppDomainInitializer initializer, string [] arguments)
955 this.initializer = initializer;
956 this.arguments = arguments;
959 public void Initialize ()
961 initializer (arguments);
966 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
967 string appRelativeSearchPath, bool shadowCopyFiles)
969 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
973 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
974 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
977 throw new ArgumentNullException ("info");
979 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
980 return CreateDomain (friendlyName, securityInfo, info);
984 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
986 AppDomainSetup info = new AppDomainSetup ();
988 info.ApplicationBase = appBasePath;
989 info.PrivateBinPath = appRelativeSearchPath;
992 info.ShadowCopyFiles = "true";
995 info.ShadowCopyFiles = "false";
997 info.ShadowCopyFiles = null;
1004 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1005 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1007 public bool IsFinalizingForUnload()
1009 return InternalIsFinalizingForUnload (getDomainID ());
1012 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1013 static extern void InternalUnload (int domain_id);
1015 // We do this because if the domain is a transparant proxy this
1016 // will still return the correct domain id.
1017 private int getDomainID ()
1019 return Thread.GetDomainID ();
1022 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1024 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1026 public static void Unload (AppDomain domain)
1029 throw new ArgumentNullException ("domain");
1031 InternalUnload (domain.getDomainID());
1034 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1035 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1036 public extern void SetData (string name, object data);
1040 public void SetData (string name, object data, IPermission permission)
1042 throw new NotImplementedException ();
1047 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1049 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1050 public void SetDynamicBase (string path)
1052 SetupInformationNoCopy.DynamicBase = path;
1056 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1057 + " because it does not provide a stable Id when managed"
1058 + " threads are running on fibers (aka lightweight"
1059 + " threads). To get a stable identifier for a managed"
1060 + " thread, use the ManagedThreadId property on Thread.'")]
1062 public static int GetCurrentThreadId ()
1064 return Thread.CurrentThreadId;
1067 public override string ToString ()
1069 return getFriendlyName ();
1072 private static void ValidateAssemblyName (string name)
1074 if (name == null || name.Length == 0)
1075 throw new ArgumentException ("The Name of " +
1076 "AssemblyName cannot be null or a " +
1077 "zero-length string.");
1079 bool isValid = true;
1081 for (int i = 0; i < name.Length; i++) {
1084 // do not allow leading whitespace
1085 if (i == 0 && char.IsWhiteSpace (c)) {
1090 // do not allow /,\ or : in name
1091 if (c == '/' || c == '\\' || c == ':') {
1098 throw new ArgumentException ("The Name of " +
1099 "AssemblyName cannot start with " +
1100 "whitespace, or contain '/', '\\' " +
1104 // The following methods are called from the runtime. Don't change signatures.
1105 #pragma warning disable 169
1106 private void DoAssemblyLoad (Assembly assembly)
1108 if (AssemblyLoad == null)
1111 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1114 private Assembly DoAssemblyResolve (string name, bool refonly)
1116 ResolveEventHandler del;
1119 del = ReflectionOnlyAssemblyResolve;
1121 del = AssemblyResolve;
1123 del = AssemblyResolve;
1128 /* Prevent infinite recursion */
1131 ht = assembly_resolve_in_progress_refonly;
1133 ht = new Hashtable ();
1134 assembly_resolve_in_progress_refonly = ht;
1137 ht = assembly_resolve_in_progress;
1139 ht = new Hashtable ();
1140 assembly_resolve_in_progress = ht;
1144 string s = (string) ht [name];
1149 Delegate[] invocation_list = del.GetInvocationList ();
1151 foreach (Delegate eh in invocation_list) {
1152 ResolveEventHandler handler = (ResolveEventHandler) eh;
1153 Assembly assembly = handler (this, new ResolveEventArgs (name));
1154 if (assembly != null)
1164 internal Assembly DoTypeResolve (Object name_or_tb)
1166 if (TypeResolve == null)
1171 if (name_or_tb is TypeBuilder)
1172 name = ((TypeBuilder) name_or_tb).FullName;
1174 name = (string) name_or_tb;
1176 /* Prevent infinite recursion */
1177 Hashtable ht = type_resolve_in_progress;
1179 ht = new Hashtable ();
1180 type_resolve_in_progress = ht;
1183 if (ht.Contains (name))
1189 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1190 ResolveEventHandler eh = (ResolveEventHandler) d;
1191 Assembly assembly = eh (this, new ResolveEventArgs (name));
1192 if (assembly != null)
1202 private void DoDomainUnload ()
1204 if (DomainUnload != null)
1205 DomainUnload(this, null);
1208 internal byte[] GetMarshalledDomainObjRef ()
1210 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1211 return CADSerializer.SerializeObject (oref).GetBuffer();
1214 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1215 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1219 if (null != arrRequest)
1220 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1222 reqDomMsg = new MethodCall (cadMsg);
1224 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1226 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1227 if (null == cadMrm) {
1228 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1233 #pragma warning restore 169
1235 // End of methods called from the runtime
1237 #if BOOTSTRAP_WITH_OLDLIB
1238 // older MCS/corlib returns:
1239 // _AppDomain.cs(138) error CS0592: Attribute 'SecurityPermission' is not valid on this declaration type.
1240 // It is valid on 'assembly' 'class' 'constructor' 'method' 'struct' declarations only.
1241 public event AssemblyLoadEventHandler AssemblyLoad;
1243 public event ResolveEventHandler AssemblyResolve;
1245 public event EventHandler DomainUnload;
1247 public event EventHandler ProcessExit;
1249 public event ResolveEventHandler ResourceResolve;
1251 public event ResolveEventHandler TypeResolve;
1253 public event UnhandledExceptionEventHandler UnhandledException;
1255 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1256 public event AssemblyLoadEventHandler AssemblyLoad;
1258 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1259 public event ResolveEventHandler AssemblyResolve;
1261 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1262 public event EventHandler DomainUnload;
1264 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1265 public event EventHandler ProcessExit;
1267 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1268 public event ResolveEventHandler ResourceResolve;
1270 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1271 public event ResolveEventHandler TypeResolve;
1273 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1274 public event UnhandledExceptionEventHandler UnhandledException;
1277 #if NET_4_0 || BOOTSTRAP_NET_4_0
1279 public bool IsHomogenous {
1280 get { return true; }
1286 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1288 #pragma warning disable 649
1289 private ActivationContext _activation;
1290 private ApplicationIdentity _applicationIdentity;
1291 private AppDomainManager _domain_manager;
1292 #pragma warning restore 649
1296 public ActivationContext ActivationContext {
1297 get { return _activation; }
1300 public ApplicationIdentity ApplicationIdentity {
1301 get { return _applicationIdentity; }
1305 public AppDomainManager DomainManager {
1306 get { return _domain_manager; }
1310 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1311 get { return getDomainID (); }
1316 [MonoTODO ("This routine only returns the parameter currently")]
1317 [ComVisible (false)]
1318 public string ApplyPolicy (string assemblyName)
1320 if (assemblyName == null)
1321 throw new ArgumentNullException ("assemblyName");
1322 if (assemblyName.Length == 0) // String.Empty
1323 throw new ArgumentException ("assemblyName");
1324 return assemblyName;
1329 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1330 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1332 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1334 info.AppDomainInitializerArguments = adInitArgs;
1335 info.AppDomainInitializer = adInit;
1337 return CreateDomain (friendlyName, securityInfo, info);
1340 public int ExecuteAssemblyByName (string assemblyName)
1342 return ExecuteAssemblyByName (assemblyName, null, null);
1345 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1347 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1350 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1352 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1354 return ExecuteAssemblyInternal (a, args);
1357 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1359 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1361 return ExecuteAssemblyInternal (a, args);
1364 public bool IsDefaultAppDomain ()
1366 return Object.ReferenceEquals (this, DefaultDomain);
1369 public Assembly[] ReflectionOnlyGetAssemblies ()
1371 return GetAssemblies (true);
1376 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1378 throw new NotImplementedException ();
1381 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1383 throw new NotImplementedException ();
1386 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1388 throw new NotImplementedException ();
1391 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1392 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1394 throw new NotImplementedException ();