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;
123 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
124 // we cannot divulge local file informations
125 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
131 public string RelativeSearchPath {
133 string path = SetupInformationNoCopy.PrivateBinPath;
134 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
135 // we cannot divulge local file informations
136 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
142 public string DynamicDirectory {
144 AppDomainSetup setup = SetupInformationNoCopy;
145 if (setup.DynamicBase == null)
148 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
149 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
150 // we cannot divulge local file informations
151 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
157 public bool ShadowCopyFiles {
159 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
163 [MethodImplAttribute (MethodImplOptions.InternalCall)]
164 private extern string getFriendlyName ();
166 public string FriendlyName {
168 return getFriendlyName ();
172 public Evidence Evidence {
174 // if the host (runtime) hasn't provided it's own evidence...
175 if (_evidence == null) {
176 // ... we will provide our own
178 // the executed assembly from the "default" appdomain
179 // or null if we're not in the default appdomain or
180 // if there is no entry assembly (embedded mono)
181 Assembly a = Assembly.GetEntryAssembly ();
183 if (this == DefaultDomain)
185 return new Evidence ();
187 _evidence = AppDomain.DefaultDomain.Evidence;
189 _evidence = Evidence.GetDefaultHostEvidence (a);
193 return new Evidence (_evidence); // return a copy
197 internal IPrincipal DefaultPrincipal {
199 if (_principal == null) {
200 switch (_principalPolicy) {
201 case PrincipalPolicy.UnauthenticatedPrincipal:
202 _principal = new GenericPrincipal (
203 new GenericIdentity (String.Empty, String.Empty), null);
205 case PrincipalPolicy.WindowsPrincipal:
206 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
214 // for AppDomain there is only an allowed (i.e. granted) set
215 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
216 internal PermissionSet GrantedPermissionSet {
217 get { return _granted; }
220 [MethodImplAttribute (MethodImplOptions.InternalCall)]
221 private static extern AppDomain getCurDomain ();
223 public static AppDomain CurrentDomain {
225 return getCurDomain ();
229 [MethodImplAttribute (MethodImplOptions.InternalCall)]
230 private static extern AppDomain getRootDomain ();
232 internal static AppDomain DefaultDomain {
234 if (default_domain == null) {
235 AppDomain rd = getRootDomain ();
236 if (rd == CurrentDomain)
239 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
241 return default_domain;
246 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
248 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
249 public void AppendPrivatePath (string path)
251 if (path == null || path.Length == 0)
254 AppDomainSetup setup = SetupInformationNoCopy;
256 string pp = setup.PrivateBinPath;
257 if (pp == null || pp.Length == 0) {
258 setup.PrivateBinPath = path;
263 if (pp [pp.Length - 1] != Path.PathSeparator)
264 pp += Path.PathSeparator;
266 setup.PrivateBinPath = pp + path;
270 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
272 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
273 public void ClearPrivatePath ()
275 SetupInformationNoCopy.PrivateBinPath = String.Empty;
279 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
281 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
282 public void ClearShadowCopyPath ()
284 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
287 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
289 return Activator.CreateComInstanceFrom (assemblyName, typeName);
293 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
294 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
296 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
300 public ObjectHandle CreateInstance (string assemblyName, string typeName)
302 if (assemblyName == null)
303 throw new ArgumentNullException ("assemblyName");
305 return Activator.CreateInstance (assemblyName, typeName);
308 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
310 if (assemblyName == null)
311 throw new ArgumentNullException ("assemblyName");
313 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
316 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
317 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
318 Evidence securityAttributes)
320 if (assemblyName == null)
321 throw new ArgumentNullException ("assemblyName");
323 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
324 culture, activationAttributes, securityAttributes);
327 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
329 ObjectHandle oh = CreateInstance (assemblyName, typeName);
330 return (oh != null) ? oh.Unwrap () : null;
333 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
335 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
336 return (oh != null) ? oh.Unwrap () : null;
339 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
340 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
341 object[] activationAttributes, Evidence securityAttributes)
343 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
344 culture, activationAttributes, securityAttributes);
345 return (oh != null) ? oh.Unwrap () : null;
348 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
350 if (assemblyFile == null)
351 throw new ArgumentNullException ("assemblyFile");
353 return Activator.CreateInstanceFrom (assemblyFile, typeName);
356 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
358 if (assemblyFile == null)
359 throw new ArgumentNullException ("assemblyFile");
361 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
364 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
365 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
366 object[] activationAttributes, Evidence securityAttributes)
368 if (assemblyFile == null)
369 throw new ArgumentNullException ("assemblyFile");
371 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
372 culture, activationAttributes, securityAttributes);
375 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
377 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
378 return (oh != null) ? oh.Unwrap () : null;
381 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
383 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
384 return (oh != null) ? oh.Unwrap () : null;
387 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
388 BindingFlags bindingAttr, Binder binder, object[] args,
389 CultureInfo culture, object[] activationAttributes,
390 Evidence securityAttributes)
392 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
393 culture, activationAttributes, securityAttributes);
395 return (oh != null) ? oh.Unwrap () : null;
398 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
400 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
403 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
405 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
408 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
410 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
413 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
416 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
419 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
420 PermissionSet requiredPermissions,
421 PermissionSet optionalPermissions,
422 PermissionSet refusedPermissions)
424 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
425 refusedPermissions, false);
428 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
429 PermissionSet requiredPermissions,
430 PermissionSet optionalPermissions,
431 PermissionSet refusedPermissions)
433 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
434 refusedPermissions, false);
437 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
438 PermissionSet requiredPermissions,
439 PermissionSet optionalPermissions,
440 PermissionSet refusedPermissions)
442 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
443 refusedPermissions, false);
446 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
448 PermissionSet requiredPermissions,
449 PermissionSet optionalPermissions,
450 PermissionSet refusedPermissions)
452 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
453 refusedPermissions, false);
456 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
458 PermissionSet requiredPermissions,
459 PermissionSet optionalPermissions,
460 PermissionSet refusedPermissions, bool isSynchronized)
463 throw new ArgumentNullException ("name");
464 ValidateAssemblyName (name.Name);
466 // FIXME: examine all other parameters
468 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
469 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
475 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
477 PermissionSet requiredPermissions,
478 PermissionSet optionalPermissions,
479 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
481 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
482 if (assemblyAttributes != null)
483 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
484 ab.SetCustomAttribute (cb);
490 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
491 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
496 // TODO: the last parameter is ignored for now
497 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, bool emitSymbolInfo)
499 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
503 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
505 return new AssemblyBuilder (name, null, access, true);
509 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
510 // so, when you call AppDomain.DoCallBack, that's a remote call
512 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
514 if (callBackDelegate != null)
518 public int ExecuteAssembly (string assemblyFile)
520 return ExecuteAssembly (assemblyFile, null, null);
523 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
525 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
528 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
530 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
531 return ExecuteAssemblyInternal (a, args);
534 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
536 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
537 return ExecuteAssemblyInternal (a, args);
540 int ExecuteAssemblyInternal (Assembly a, string[] args)
542 if (a.EntryPoint == null)
544 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
546 throw new COMException ("Unspecified error.", -2147467259);
548 return ExecuteAssembly (a, args);
551 [MethodImplAttribute (MethodImplOptions.InternalCall)]
552 private extern int ExecuteAssembly (Assembly a, string[] args);
554 [MethodImplAttribute (MethodImplOptions.InternalCall)]
555 private extern Assembly [] GetAssemblies (bool refOnly);
557 public Assembly [] GetAssemblies ()
559 return GetAssemblies (false);
562 [MethodImplAttribute (MethodImplOptions.InternalCall)]
563 public extern object GetData (string name);
565 public new Type GetType()
567 return base.GetType ();
570 public override object InitializeLifetimeService ()
575 [MethodImplAttribute (MethodImplOptions.InternalCall)]
576 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
578 public Assembly Load (AssemblyName assemblyRef)
580 return Load (assemblyRef, null);
583 internal Assembly LoadSatellite (AssemblyName assemblyRef)
585 if (assemblyRef == null)
586 throw new ArgumentNullException ("assemblyRef");
588 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
590 throw new FileNotFoundException (null, assemblyRef.Name);
594 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
596 if (assemblyRef == null)
597 throw new ArgumentNullException ("assemblyRef");
599 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
600 if (assemblyRef.CodeBase != null)
601 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
603 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
606 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
607 if (assembly != null)
610 if (assemblyRef.CodeBase == null)
611 throw new FileNotFoundException (null, assemblyRef.Name);
613 string cb = assemblyRef.CodeBase;
614 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
615 cb = new Mono.Security.Uri (cb).LocalPath;
618 assembly = Assembly.LoadFrom (cb, assemblySecurity);
620 throw new FileNotFoundException (null, assemblyRef.Name);
622 AssemblyName aname = assembly.GetName ();
623 // Name, version, culture, publickeytoken. Anything else?
624 if (assemblyRef.Name != aname.Name)
625 throw new FileNotFoundException (null, assemblyRef.Name);
627 if (assemblyRef.Version != new Version () && assemblyRef.Version != aname.Version)
628 throw new FileNotFoundException (null, assemblyRef.Name);
630 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
631 throw new FileNotFoundException (null, assemblyRef.Name);
633 byte [] pt = assemblyRef.GetPublicKeyToken ();
635 byte [] loaded_pt = aname.GetPublicKeyToken ();
636 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
637 throw new FileNotFoundException (null, assemblyRef.Name);
638 for (int i = pt.Length - 1; i >= 0; i--)
639 if (loaded_pt [i] != pt [i])
640 throw new FileNotFoundException (null, assemblyRef.Name);
645 public Assembly Load (string assemblyString)
647 return Load (assemblyString, null, false);
650 public Assembly Load (string assemblyString, Evidence assemblySecurity)
652 return Load (assemblyString, assemblySecurity, false);
655 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
657 if (assemblyString == null)
658 throw new ArgumentNullException ("assemblyString");
660 if (assemblyString.Length == 0)
661 throw new ArgumentException ("assemblyString cannot have zero length");
663 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
664 if (assembly == null)
665 throw new FileNotFoundException (null, assemblyString);
669 public Assembly Load (byte[] rawAssembly)
671 return Load (rawAssembly, null, null);
674 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
676 return Load (rawAssembly, rawSymbolStore, null);
679 [MethodImplAttribute (MethodImplOptions.InternalCall)]
680 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
682 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
684 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
687 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
689 if (rawAssembly == null)
690 throw new ArgumentNullException ("rawAssembly");
692 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
693 assembly.FromByteArray = true;
697 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
698 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
700 if (domainPolicy == null)
701 throw new ArgumentNullException ("domainPolicy");
702 if (_granted != null) {
703 throw new PolicyException (Locale.GetText (
704 "An AppDomain policy is already specified."));
706 if (IsFinalizingForUnload ())
707 throw new AppDomainUnloadedException ();
709 PolicyStatement ps = domainPolicy.Resolve (_evidence);
710 _granted = ps.PermissionSet;
714 [Obsolete ("Use AppDomainSetup.SetCachePath")]
716 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
717 public void SetCachePath (string path)
719 SetupInformationNoCopy.CachePath = path;
722 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
723 public void SetPrincipalPolicy (PrincipalPolicy policy)
725 if (IsFinalizingForUnload ())
726 throw new AppDomainUnloadedException ();
728 _principalPolicy = policy;
733 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
735 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
736 public void SetShadowCopyFiles()
738 SetupInformationNoCopy.ShadowCopyFiles = "true";
742 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
744 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
745 public void SetShadowCopyPath (string path)
747 SetupInformationNoCopy.ShadowCopyDirectories = path;
750 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
751 public void SetThreadPrincipal (IPrincipal principal)
753 if (principal == null)
754 throw new ArgumentNullException ("principal");
755 if (_principal != null)
756 throw new PolicyException (Locale.GetText ("principal already present."));
757 if (IsFinalizingForUnload ())
758 throw new AppDomainUnloadedException ();
760 _principal = principal;
763 [MethodImplAttribute (MethodImplOptions.InternalCall)]
764 private static extern AppDomain InternalSetDomainByID (int domain_id);
766 // Changes the active domain and returns the old domain
767 [MethodImplAttribute (MethodImplOptions.InternalCall)]
768 private static extern AppDomain InternalSetDomain (AppDomain context);
770 // Notifies the runtime that this thread references 'domain'.
771 [MethodImplAttribute (MethodImplOptions.InternalCall)]
772 internal static extern void InternalPushDomainRef (AppDomain domain);
774 [MethodImplAttribute (MethodImplOptions.InternalCall)]
775 internal static extern void InternalPushDomainRefByID (int domain_id);
777 // Undoes the effect of the last PushDomainRef call
778 [MethodImplAttribute (MethodImplOptions.InternalCall)]
779 internal static extern void InternalPopDomainRef ();
781 // Changes the active context and returns the old context
782 [MethodImplAttribute (MethodImplOptions.InternalCall)]
783 internal static extern Context InternalSetContext (Context context);
785 // Returns the current context
786 [MethodImplAttribute (MethodImplOptions.InternalCall)]
787 internal static extern Context InternalGetContext ();
789 // Returns the current context
790 [MethodImplAttribute (MethodImplOptions.InternalCall)]
791 internal static extern Context InternalGetDefaultContext ();
793 [MethodImplAttribute (MethodImplOptions.InternalCall)]
794 internal static extern string InternalGetProcessGuid (string newguid);
796 // This method is handled specially by the runtime
797 // It is the only managed method which is allowed to set the current
799 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
801 AppDomain current = CurrentDomain;
806 InternalPushDomainRef (domain);
808 InternalSetDomain (domain);
809 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
815 InternalSetDomain (current);
817 InternalPopDomainRef ();
821 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
823 AppDomain current = CurrentDomain;
828 InternalPushDomainRefByID (domain_id);
830 InternalSetDomainByID (domain_id);
831 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
837 InternalSetDomain (current);
839 InternalPopDomainRef ();
843 internal static String GetProcessGuid ()
845 if (_process_guid == null) {
846 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
848 return _process_guid;
851 public static AppDomain CreateDomain (string friendlyName)
853 return CreateDomain (friendlyName, null, null);
856 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
858 return CreateDomain (friendlyName, securityInfo, null);
861 [MethodImplAttribute (MethodImplOptions.InternalCall)]
862 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
864 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
865 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
866 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
868 if (friendlyName == null)
869 throw new System.ArgumentNullException ("friendlyName");
871 AppDomain def = AppDomain.DefaultDomain;
873 // if null, get default domain's SetupInformation
875 info = new AppDomainSetup (); // we're default!
877 info = def.SetupInformation;
880 info = new AppDomainSetup (info); // copy
882 // todo: allow setup in the other domain
884 if (!info.Equals (def.SetupInformation)) {
885 // If not specified use default domain's app base.
886 if (info.ApplicationBase == null)
887 info.ApplicationBase = def.SetupInformation.ApplicationBase;
888 if (info.ConfigurationFile == null)
889 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
891 } else if (info.ConfigurationFile == null)
892 info.ConfigurationFile = "[I don't have a config file]";
894 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
895 if (securityInfo == null) {
896 // get default domain's Evidence (unless we're are the default!)
898 ad._evidence = null; // we'll get them later (GetEntryAssembly)
900 ad._evidence = def.Evidence; // new (shallow) copy
903 ad._evidence = new Evidence (securityInfo); // copy
906 if (info.AppDomainInitializer != null) {
907 if (!info.AppDomainInitializer.Method.IsStatic)
908 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
910 Loader loader = new Loader (
911 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
912 ad.DoCallBack (loader.Load);
914 Initializer initializer = new Initializer (
915 info.AppDomainInitializer,
916 info.AppDomainInitializerArguments);
917 ad.DoCallBack (initializer.Initialize);
930 public Loader (string assembly)
932 this.assembly = assembly;
937 Assembly.LoadFrom (assembly);
944 AppDomainInitializer initializer;
947 public Initializer (AppDomainInitializer initializer, string [] arguments)
949 this.initializer = initializer;
950 this.arguments = arguments;
953 public void Initialize ()
955 initializer (arguments);
960 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
961 string appRelativeSearchPath, bool shadowCopyFiles)
963 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
966 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
968 AppDomainSetup info = new AppDomainSetup ();
970 info.ApplicationBase = appBasePath;
971 info.PrivateBinPath = appRelativeSearchPath;
974 info.ShadowCopyFiles = "true";
977 info.ShadowCopyFiles = "false";
979 info.ShadowCopyFiles = null;
988 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
989 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
991 throw new NotImplementedException ();
995 [MethodImplAttribute (MethodImplOptions.InternalCall)]
996 private static extern bool InternalIsFinalizingForUnload (int domain_id);
998 public bool IsFinalizingForUnload()
1000 return InternalIsFinalizingForUnload (getDomainID ());
1003 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1004 static extern void InternalUnload (int domain_id);
1006 // We do this because if the domain is a transparant proxy this
1007 // will still return the correct domain id.
1008 private int getDomainID ()
1010 return Thread.GetDomainID ();
1013 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1015 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1017 public static void Unload (AppDomain domain)
1020 throw new ArgumentNullException ("domain");
1022 InternalUnload (domain.getDomainID());
1025 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1026 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1027 public extern void SetData (string name, object data);
1031 public void SetData (string name, object data, IPermission permission)
1033 throw new NotImplementedException ();
1038 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1040 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1041 public void SetDynamicBase (string path)
1043 SetupInformationNoCopy.DynamicBase = path;
1047 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1048 + " because it does not provide a stable Id when managed"
1049 + " threads are running on fibers (aka lightweight"
1050 + " threads). To get a stable identifier for a managed"
1051 + " thread, use the ManagedThreadId property on Thread.'")]
1053 public static int GetCurrentThreadId ()
1055 return Thread.CurrentThreadId;
1058 public override string ToString ()
1060 return getFriendlyName ();
1063 private static void ValidateAssemblyName (string name)
1065 if (name == null || name.Length == 0)
1066 throw new ArgumentException ("The Name of " +
1067 "AssemblyName cannot be null or a " +
1068 "zero-length string.");
1070 bool isValid = true;
1072 for (int i = 0; i < name.Length; i++) {
1075 // do not allow leading whitespace
1076 if (i == 0 && char.IsWhiteSpace (c)) {
1081 // do not allow /,\ or : in name
1082 if (c == '/' || c == '\\' || c == ':') {
1089 throw new ArgumentException ("The Name of " +
1090 "AssemblyName cannot start with " +
1091 "whitespace, or contain '/', '\\' " +
1095 // The following methods are called from the runtime. Don't change signatures.
1096 #pragma warning disable 169
1097 private void DoAssemblyLoad (Assembly assembly)
1099 if (AssemblyLoad == null)
1102 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1105 private Assembly DoAssemblyResolve (string name, bool refonly)
1107 ResolveEventHandler del;
1110 del = ReflectionOnlyAssemblyResolve;
1112 del = AssemblyResolve;
1114 del = AssemblyResolve;
1119 /* Prevent infinite recursion */
1122 ht = assembly_resolve_in_progress_refonly;
1124 ht = new Hashtable ();
1125 assembly_resolve_in_progress_refonly = ht;
1128 ht = assembly_resolve_in_progress;
1130 ht = new Hashtable ();
1131 assembly_resolve_in_progress = ht;
1135 string s = (string) ht [name];
1140 Delegate[] invocation_list = del.GetInvocationList ();
1142 foreach (Delegate eh in invocation_list) {
1143 ResolveEventHandler handler = (ResolveEventHandler) eh;
1144 Assembly assembly = handler (this, new ResolveEventArgs (name));
1145 if (assembly != null)
1155 internal Assembly DoTypeResolve (Object name_or_tb)
1157 if (TypeResolve == null)
1162 if (name_or_tb is TypeBuilder)
1163 name = ((TypeBuilder) name_or_tb).FullName;
1165 name = (string) name_or_tb;
1167 /* Prevent infinite recursion */
1168 Hashtable ht = type_resolve_in_progress;
1170 ht = new Hashtable ();
1171 type_resolve_in_progress = ht;
1174 if (ht.Contains (name))
1180 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1181 ResolveEventHandler eh = (ResolveEventHandler) d;
1182 Assembly assembly = eh (this, new ResolveEventArgs (name));
1183 if (assembly != null)
1193 private void DoDomainUnload ()
1195 if (DomainUnload != null)
1196 DomainUnload(this, null);
1199 internal byte[] GetMarshalledDomainObjRef ()
1201 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1202 return CADSerializer.SerializeObject (oref).GetBuffer();
1205 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1206 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1210 if (null != arrRequest)
1211 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1213 reqDomMsg = new MethodCall (cadMsg);
1215 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1217 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1218 if (null == cadMrm) {
1219 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1224 #pragma warning restore 169
1226 // End of methods called from the runtime
1228 #if BOOTSTRAP_WITH_OLDLIB
1229 // older MCS/corlib returns:
1230 // _AppDomain.cs(138) error CS0592: Attribute 'SecurityPermission' is not valid on this declaration type.
1231 // It is valid on 'assembly' 'class' 'constructor' 'method' 'struct' declarations only.
1232 public event AssemblyLoadEventHandler AssemblyLoad;
1234 public event ResolveEventHandler AssemblyResolve;
1236 public event EventHandler DomainUnload;
1238 public event EventHandler ProcessExit;
1240 public event ResolveEventHandler ResourceResolve;
1242 public event ResolveEventHandler TypeResolve;
1244 public event UnhandledExceptionEventHandler UnhandledException;
1246 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1247 public event AssemblyLoadEventHandler AssemblyLoad;
1249 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1250 public event ResolveEventHandler AssemblyResolve;
1252 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1253 public event EventHandler DomainUnload;
1255 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1256 public event EventHandler ProcessExit;
1258 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1259 public event ResolveEventHandler ResourceResolve;
1261 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1262 public event ResolveEventHandler TypeResolve;
1264 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1265 public event UnhandledExceptionEventHandler UnhandledException;
1270 public bool IsHomogenous {
1271 get { return false; }
1277 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1279 #pragma warning disable 649
1280 private ActivationContext _activation;
1281 private ApplicationIdentity _applicationIdentity;
1282 private AppDomainManager _domain_manager;
1283 #pragma warning restore 649
1287 public ActivationContext ActivationContext {
1288 get { return _activation; }
1291 public ApplicationIdentity ApplicationIdentity {
1292 get { return _applicationIdentity; }
1296 public AppDomainManager DomainManager {
1297 get { return _domain_manager; }
1301 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1302 get { return getDomainID (); }
1307 [MonoTODO ("This routine only returns the parameter currently")]
1308 [ComVisible (false)]
1309 public string ApplyPolicy (string assemblyName)
1311 if (assemblyName == null)
1312 throw new ArgumentNullException ("assemblyName");
1313 if (assemblyName.Length == 0) // String.Empty
1314 throw new ArgumentException ("assemblyName");
1315 return assemblyName;
1320 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1321 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1323 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1325 info.AppDomainInitializerArguments = adInitArgs;
1326 info.AppDomainInitializer = adInit;
1328 return CreateDomain (friendlyName, securityInfo, info);
1331 public int ExecuteAssemblyByName (string assemblyName)
1333 return ExecuteAssemblyByName (assemblyName, null, null);
1336 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1338 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1341 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1343 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1345 return ExecuteAssemblyInternal (a, args);
1348 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1350 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1352 return ExecuteAssemblyInternal (a, args);
1355 public bool IsDefaultAppDomain ()
1357 return Object.ReferenceEquals (this, DefaultDomain);
1360 public Assembly[] ReflectionOnlyGetAssemblies ()
1362 return GetAssemblies (true);
1367 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1369 throw new NotImplementedException ();
1372 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1374 throw new NotImplementedException ();
1377 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1379 throw new NotImplementedException ();
1382 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1383 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1385 throw new NotImplementedException ();