5 // Paolo Molaro (lupus@ximian.com)
6 // Dietmar Maurer (dietmar@ximian.com)
7 // Miguel de Icaza (miguel@ximian.com)
8 // Gonzalo Paniagua (gonzalo@ximian.com)
10 // Sebastien Pouliot (sebastien@ximian.com)
12 // (C) 2001, 2002 Ximian, Inc. http://www.ximian.com
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections;
36 using System.Globalization;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Threading;
41 using System.Runtime.CompilerServices;
42 using System.Runtime.InteropServices;
43 using System.Runtime.Remoting;
44 using System.Runtime.Remoting.Contexts;
45 using System.Runtime.Remoting.Channels;
46 using System.Runtime.Remoting.Messaging;
47 using System.Security;
48 using System.Security.Permissions;
49 using System.Security.Policy;
50 using System.Security.Principal;
51 using System.Configuration.Assemblies;
54 using System.Collections.Generic;
55 using System.Runtime.ConstrainedExecution;
63 [ComDefaultInterface (typeof (_AppDomain))]
66 [ClassInterface(ClassInterfaceType.None)]
68 public sealed class AppDomain : MarshalByRefObject {
70 public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory {
72 #pragma warning disable 169
73 #region Sync with object-internals.h
74 IntPtr _mono_app_domain;
76 #pragma warning restore 169
77 static string _process_guid;
80 static Hashtable type_resolve_in_progress;
83 static Hashtable assembly_resolve_in_progress;
86 static Hashtable assembly_resolve_in_progress_refonly;
89 private Evidence _evidence;
90 private PermissionSet _granted;
93 private PrincipalPolicy _principalPolicy;
96 private static IPrincipal _principal;
98 static AppDomain default_domain;
104 [MethodImplAttribute (MethodImplOptions.InternalCall)]
105 private extern AppDomainSetup getSetup ();
107 AppDomainSetup SetupInformationNoCopy {
108 get { return getSetup (); }
111 public AppDomainSetup SetupInformation {
113 AppDomainSetup setup = getSetup ();
114 return new AppDomainSetup (setup);
118 #if NET_2_0 && !NET_2_1
120 public ApplicationTrust ApplicationTrust {
121 get { throw new NotImplementedException (); }
125 public string BaseDirectory {
127 string path = SetupInformationNoCopy.ApplicationBase;
128 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
129 // we cannot divulge local file informations
130 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
136 public string RelativeSearchPath {
138 string path = SetupInformationNoCopy.PrivateBinPath;
139 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
140 // we cannot divulge local file informations
141 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
147 public string DynamicDirectory {
149 AppDomainSetup setup = SetupInformationNoCopy;
150 if (setup.DynamicBase == null)
153 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 ();
162 public bool ShadowCopyFiles {
164 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;
254 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
256 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
257 public void AppendPrivatePath (string path)
259 if (path == null || path.Length == 0)
262 AppDomainSetup setup = SetupInformationNoCopy;
264 string pp = setup.PrivateBinPath;
265 if (pp == null || pp.Length == 0) {
266 setup.PrivateBinPath = path;
271 if (pp [pp.Length - 1] != Path.PathSeparator)
272 pp += Path.PathSeparator;
274 setup.PrivateBinPath = pp + path;
278 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
280 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
281 public void ClearPrivatePath ()
283 SetupInformationNoCopy.PrivateBinPath = String.Empty;
287 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
289 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
290 public void ClearShadowCopyPath ()
292 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
295 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
297 return Activator.CreateComInstanceFrom (assemblyName, typeName);
301 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
302 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
304 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
308 public ObjectHandle CreateInstance (string assemblyName, string typeName)
310 if (assemblyName == null)
311 throw new ArgumentNullException ("assemblyName");
313 return Activator.CreateInstance (assemblyName, typeName);
316 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
318 if (assemblyName == null)
319 throw new ArgumentNullException ("assemblyName");
321 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
324 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
325 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
326 Evidence securityAttributes)
328 if (assemblyName == null)
329 throw new ArgumentNullException ("assemblyName");
331 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
332 culture, activationAttributes, securityAttributes);
335 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
337 ObjectHandle oh = CreateInstance (assemblyName, typeName);
338 return (oh != null) ? oh.Unwrap () : null;
341 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
343 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
344 return (oh != null) ? oh.Unwrap () : null;
347 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
348 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
349 object[] activationAttributes, Evidence securityAttributes)
351 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
352 culture, activationAttributes, securityAttributes);
353 return (oh != null) ? oh.Unwrap () : null;
356 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
358 if (assemblyFile == null)
359 throw new ArgumentNullException ("assemblyFile");
361 return Activator.CreateInstanceFrom (assemblyFile, typeName);
364 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
366 if (assemblyFile == null)
367 throw new ArgumentNullException ("assemblyFile");
369 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
372 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
373 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
374 object[] activationAttributes, Evidence securityAttributes)
376 if (assemblyFile == null)
377 throw new ArgumentNullException ("assemblyFile");
379 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
380 culture, activationAttributes, securityAttributes);
383 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
385 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
386 return (oh != null) ? oh.Unwrap () : null;
389 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
391 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
392 return (oh != null) ? oh.Unwrap () : null;
395 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
396 BindingFlags bindingAttr, Binder binder, object[] args,
397 CultureInfo culture, object[] activationAttributes,
398 Evidence securityAttributes)
400 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
401 culture, activationAttributes, securityAttributes);
403 return (oh != null) ? oh.Unwrap () : null;
408 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
410 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
413 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
415 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
418 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
420 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
423 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
426 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
429 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
430 PermissionSet requiredPermissions,
431 PermissionSet optionalPermissions,
432 PermissionSet refusedPermissions)
434 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
435 refusedPermissions, false);
438 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
439 PermissionSet requiredPermissions,
440 PermissionSet optionalPermissions,
441 PermissionSet refusedPermissions)
443 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
444 refusedPermissions, false);
447 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
448 PermissionSet requiredPermissions,
449 PermissionSet optionalPermissions,
450 PermissionSet refusedPermissions)
452 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
453 refusedPermissions, false);
456 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
458 PermissionSet requiredPermissions,
459 PermissionSet optionalPermissions,
460 PermissionSet refusedPermissions)
462 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
463 refusedPermissions, false);
466 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
468 PermissionSet requiredPermissions,
469 PermissionSet optionalPermissions,
470 PermissionSet refusedPermissions, bool isSynchronized)
473 throw new ArgumentNullException ("name");
474 ValidateAssemblyName (name.Name);
476 // FIXME: examine all other parameters
478 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
479 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
485 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
487 PermissionSet requiredPermissions,
488 PermissionSet optionalPermissions,
489 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
491 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
492 if (assemblyAttributes != null)
493 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
494 ab.SetCustomAttribute (cb);
500 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
501 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
506 // TODO: the last parameter is ignored for now
507 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, bool emitSymbolInfo)
509 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
513 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
515 return new AssemblyBuilder (name, null, access, true);
519 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
520 // so, when you call AppDomain.DoCallBack, that's a remote call
522 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
524 if (callBackDelegate != null)
528 public int ExecuteAssembly (string assemblyFile)
530 return ExecuteAssembly (assemblyFile, null, null);
533 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
535 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
538 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
540 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
541 return ExecuteAssemblyInternal (a, args);
544 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
546 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
547 return ExecuteAssemblyInternal (a, args);
550 int ExecuteAssemblyInternal (Assembly a, string[] args)
552 if (a.EntryPoint == null)
554 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
556 throw new COMException ("Unspecified error.", -2147467259);
558 return ExecuteAssembly (a, args);
561 [MethodImplAttribute (MethodImplOptions.InternalCall)]
562 private extern int ExecuteAssembly (Assembly a, string[] args);
564 [MethodImplAttribute (MethodImplOptions.InternalCall)]
565 private extern Assembly [] GetAssemblies (bool refOnly);
567 public Assembly [] GetAssemblies ()
569 return GetAssemblies (false);
572 [MethodImplAttribute (MethodImplOptions.InternalCall)]
573 public extern object GetData (string name);
575 public new Type GetType()
577 return base.GetType ();
580 public override object InitializeLifetimeService ()
585 [MethodImplAttribute (MethodImplOptions.InternalCall)]
586 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
588 public Assembly Load (AssemblyName assemblyRef)
590 return Load (assemblyRef, null);
593 internal Assembly LoadSatellite (AssemblyName assemblyRef)
595 if (assemblyRef == null)
596 throw new ArgumentNullException ("assemblyRef");
598 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
600 throw new FileNotFoundException (null, assemblyRef.Name);
604 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
606 if (assemblyRef == null)
607 throw new ArgumentNullException ("assemblyRef");
609 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
610 if (assemblyRef.CodeBase != null)
611 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
613 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
616 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
617 if (assembly != null)
620 if (assemblyRef.CodeBase == null)
621 throw new FileNotFoundException (null, assemblyRef.Name);
623 string cb = assemblyRef.CodeBase;
624 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
625 cb = new Mono.Security.Uri (cb).LocalPath;
628 assembly = Assembly.LoadFrom (cb, assemblySecurity);
630 throw new FileNotFoundException (null, assemblyRef.Name);
632 AssemblyName aname = assembly.GetName ();
633 // Name, version, culture, publickeytoken. Anything else?
634 if (assemblyRef.Name != aname.Name)
635 throw new FileNotFoundException (null, assemblyRef.Name);
637 if (assemblyRef.Version != new Version () && assemblyRef.Version != aname.Version)
638 throw new FileNotFoundException (null, assemblyRef.Name);
640 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
641 throw new FileNotFoundException (null, assemblyRef.Name);
643 byte [] pt = assemblyRef.GetPublicKeyToken ();
645 byte [] loaded_pt = aname.GetPublicKeyToken ();
646 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
647 throw new FileNotFoundException (null, assemblyRef.Name);
648 for (int i = pt.Length - 1; i >= 0; i--)
649 if (loaded_pt [i] != pt [i])
650 throw new FileNotFoundException (null, assemblyRef.Name);
655 public Assembly Load (string assemblyString)
657 return Load (assemblyString, null, false);
660 public Assembly Load (string assemblyString, Evidence assemblySecurity)
662 return Load (assemblyString, assemblySecurity, false);
665 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
667 if (assemblyString == null)
668 throw new ArgumentNullException ("assemblyString");
670 if (assemblyString.Length == 0)
671 throw new ArgumentException ("assemblyString cannot have zero length");
673 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
674 if (assembly == null)
675 throw new FileNotFoundException (null, assemblyString);
679 public Assembly Load (byte[] rawAssembly)
681 return Load (rawAssembly, null, null);
684 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
686 return Load (rawAssembly, rawSymbolStore, null);
689 [MethodImplAttribute (MethodImplOptions.InternalCall)]
690 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
692 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
694 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
697 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
699 if (rawAssembly == null)
700 throw new ArgumentNullException ("rawAssembly");
702 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
703 assembly.FromByteArray = true;
707 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
708 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
710 if (domainPolicy == null)
711 throw new ArgumentNullException ("domainPolicy");
712 if (_granted != null) {
713 throw new PolicyException (Locale.GetText (
714 "An AppDomain policy is already specified."));
716 if (IsFinalizingForUnload ())
717 throw new AppDomainUnloadedException ();
719 PolicyStatement ps = domainPolicy.Resolve (_evidence);
720 _granted = ps.PermissionSet;
724 [Obsolete ("Use AppDomainSetup.SetCachePath")]
726 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
727 public void SetCachePath (string path)
729 SetupInformationNoCopy.CachePath = path;
732 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
733 public void SetPrincipalPolicy (PrincipalPolicy policy)
735 if (IsFinalizingForUnload ())
736 throw new AppDomainUnloadedException ();
738 _principalPolicy = policy;
743 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
745 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
746 public void SetShadowCopyFiles()
748 SetupInformationNoCopy.ShadowCopyFiles = "true";
752 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
754 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
755 public void SetShadowCopyPath (string path)
757 SetupInformationNoCopy.ShadowCopyDirectories = path;
760 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
761 public void SetThreadPrincipal (IPrincipal principal)
763 if (principal == null)
764 throw new ArgumentNullException ("principal");
765 if (_principal != null)
766 throw new PolicyException (Locale.GetText ("principal already present."));
767 if (IsFinalizingForUnload ())
768 throw new AppDomainUnloadedException ();
770 _principal = principal;
773 [MethodImplAttribute (MethodImplOptions.InternalCall)]
774 private static extern AppDomain InternalSetDomainByID (int domain_id);
776 // Changes the active domain and returns the old domain
777 [MethodImplAttribute (MethodImplOptions.InternalCall)]
778 private static extern AppDomain InternalSetDomain (AppDomain context);
780 // Notifies the runtime that this thread references 'domain'.
781 [MethodImplAttribute (MethodImplOptions.InternalCall)]
782 internal static extern void InternalPushDomainRef (AppDomain domain);
784 [MethodImplAttribute (MethodImplOptions.InternalCall)]
785 internal static extern void InternalPushDomainRefByID (int domain_id);
787 // Undoes the effect of the last PushDomainRef call
788 [MethodImplAttribute (MethodImplOptions.InternalCall)]
789 internal static extern void InternalPopDomainRef ();
791 // Changes the active context and returns the old context
792 [MethodImplAttribute (MethodImplOptions.InternalCall)]
793 internal static extern Context InternalSetContext (Context context);
795 // Returns the current context
796 [MethodImplAttribute (MethodImplOptions.InternalCall)]
797 internal static extern Context InternalGetContext ();
799 // Returns the current context
800 [MethodImplAttribute (MethodImplOptions.InternalCall)]
801 internal static extern Context InternalGetDefaultContext ();
803 [MethodImplAttribute (MethodImplOptions.InternalCall)]
804 internal static extern string InternalGetProcessGuid (string newguid);
806 // This method is handled specially by the runtime
807 // It is the only managed method which is allowed to set the current
809 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
811 AppDomain current = CurrentDomain;
816 InternalPushDomainRef (domain);
818 InternalSetDomain (domain);
819 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
825 InternalSetDomain (current);
827 InternalPopDomainRef ();
831 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
833 AppDomain current = CurrentDomain;
838 InternalPushDomainRefByID (domain_id);
840 InternalSetDomainByID (domain_id);
841 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
847 InternalSetDomain (current);
849 InternalPopDomainRef ();
853 internal static String GetProcessGuid ()
855 if (_process_guid == null) {
856 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
858 return _process_guid;
863 public static AppDomain CreateDomain (string friendlyName)
865 return CreateDomain (friendlyName, null, null);
868 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
870 return CreateDomain (friendlyName, securityInfo, null);
873 [MethodImplAttribute (MethodImplOptions.InternalCall)]
874 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
876 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
877 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
878 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
880 if (friendlyName == null)
881 throw new System.ArgumentNullException ("friendlyName");
883 AppDomain def = AppDomain.DefaultDomain;
885 // if null, get default domain's SetupInformation
887 info = new AppDomainSetup (); // we're default!
889 info = def.SetupInformation;
892 info = new AppDomainSetup (info); // copy
894 // todo: allow setup in the other domain
896 if (!info.Equals (def.SetupInformation)) {
897 // If not specified use default domain's app base.
898 if (info.ApplicationBase == null)
899 info.ApplicationBase = def.SetupInformation.ApplicationBase;
900 if (info.ConfigurationFile == null)
901 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
903 } else if (info.ConfigurationFile == null)
904 info.ConfigurationFile = "[I don't have a config file]";
906 info.SerializeNonPrimitives ();
908 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
909 if (securityInfo == null) {
910 // get default domain's Evidence (unless we're are the default!)
912 ad._evidence = null; // we'll get them later (GetEntryAssembly)
914 ad._evidence = def.Evidence; // new (shallow) copy
917 ad._evidence = new Evidence (securityInfo); // copy
919 #if NET_2_0 && !NET_2_1
920 if (info.AppDomainInitializer != null) {
921 if (!info.AppDomainInitializer.Method.IsStatic)
922 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
924 Loader loader = new Loader (
925 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
926 ad.DoCallBack (loader.Load);
928 Initializer initializer = new Initializer (
929 info.AppDomainInitializer,
930 info.AppDomainInitializerArguments);
931 ad.DoCallBack (initializer.Initialize);
938 #if NET_2_0 && !NET_2_1
944 public Loader (string assembly)
946 this.assembly = assembly;
951 Assembly.LoadFrom (assembly);
958 AppDomainInitializer initializer;
961 public Initializer (AppDomainInitializer initializer, string [] arguments)
963 this.initializer = initializer;
964 this.arguments = arguments;
967 public void Initialize ()
969 initializer (arguments);
974 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
975 string appRelativeSearchPath, bool shadowCopyFiles)
977 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
980 #if NET_2_0 && !NET_2_1
981 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
982 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
985 throw new ArgumentNullException ("info");
987 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
988 return CreateDomain (friendlyName, securityInfo, info);
992 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
994 AppDomainSetup info = new AppDomainSetup ();
996 info.ApplicationBase = appBasePath;
997 info.PrivateBinPath = appRelativeSearchPath;
1000 info.ShadowCopyFiles = "true";
1003 info.ShadowCopyFiles = "false";
1005 info.ShadowCopyFiles = null;
1013 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1014 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1016 public bool IsFinalizingForUnload()
1018 return InternalIsFinalizingForUnload (getDomainID ());
1021 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1022 static extern void InternalUnload (int domain_id);
1024 // We do this because if the domain is a transparant proxy this
1025 // will still return the correct domain id.
1026 private int getDomainID ()
1028 return Thread.GetDomainID ();
1031 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1033 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1035 public static void Unload (AppDomain domain)
1038 throw new ArgumentNullException ("domain");
1040 InternalUnload (domain.getDomainID());
1043 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1044 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1045 public extern void SetData (string name, object data);
1049 public void SetData (string name, object data, IPermission permission)
1051 throw new NotImplementedException ();
1057 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1059 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1060 public void SetDynamicBase (string path)
1062 SetupInformationNoCopy.DynamicBase = path;
1067 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1068 + " because it does not provide a stable Id when managed"
1069 + " threads are running on fibers (aka lightweight"
1070 + " threads). To get a stable identifier for a managed"
1071 + " thread, use the ManagedThreadId property on Thread.'")]
1073 public static int GetCurrentThreadId ()
1075 return Thread.CurrentThreadId;
1078 public override string ToString ()
1080 return getFriendlyName ();
1083 private static void ValidateAssemblyName (string name)
1085 if (name == null || name.Length == 0)
1086 throw new ArgumentException ("The Name of " +
1087 "AssemblyName cannot be null or a " +
1088 "zero-length string.");
1090 bool isValid = true;
1092 for (int i = 0; i < name.Length; i++) {
1095 // do not allow leading whitespace
1096 if (i == 0 && char.IsWhiteSpace (c)) {
1101 // do not allow /,\ or : in name
1102 if (c == '/' || c == '\\' || c == ':') {
1109 throw new ArgumentException ("The Name of " +
1110 "AssemblyName cannot start with " +
1111 "whitespace, or contain '/', '\\' " +
1115 // The following methods are called from the runtime. Don't change signatures.
1116 #pragma warning disable 169
1117 private void DoAssemblyLoad (Assembly assembly)
1119 if (AssemblyLoad == null)
1122 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1125 private Assembly DoAssemblyResolve (string name, bool refonly)
1127 ResolveEventHandler del;
1128 #if NET_2_0 && !NET_2_1
1130 del = ReflectionOnlyAssemblyResolve;
1132 del = AssemblyResolve;
1134 del = AssemblyResolve;
1139 /* Prevent infinite recursion */
1142 ht = assembly_resolve_in_progress_refonly;
1144 ht = new Hashtable ();
1145 assembly_resolve_in_progress_refonly = ht;
1148 ht = assembly_resolve_in_progress;
1150 ht = new Hashtable ();
1151 assembly_resolve_in_progress = ht;
1155 string s = (string) ht [name];
1160 Delegate[] invocation_list = del.GetInvocationList ();
1162 foreach (Delegate eh in invocation_list) {
1163 ResolveEventHandler handler = (ResolveEventHandler) eh;
1164 Assembly assembly = handler (this, new ResolveEventArgs (name));
1165 if (assembly != null)
1175 internal Assembly DoTypeResolve (Object name_or_tb)
1177 if (TypeResolve == null)
1182 if (name_or_tb is TypeBuilder)
1183 name = ((TypeBuilder) name_or_tb).FullName;
1185 name = (string) name_or_tb;
1187 /* Prevent infinite recursion */
1188 Hashtable ht = type_resolve_in_progress;
1190 ht = new Hashtable ();
1191 type_resolve_in_progress = ht;
1194 if (ht.Contains (name))
1200 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1201 ResolveEventHandler eh = (ResolveEventHandler) d;
1202 Assembly assembly = eh (this, new ResolveEventArgs (name));
1203 if (assembly != null)
1213 private void DoDomainUnload ()
1215 if (DomainUnload != null)
1216 DomainUnload(this, null);
1220 internal byte[] GetMarshalledDomainObjRef ()
1222 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1223 return CADSerializer.SerializeObject (oref).GetBuffer();
1226 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1227 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1231 if (null != arrRequest)
1232 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1234 reqDomMsg = new MethodCall (cadMsg);
1236 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1238 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1239 if (null == cadMrm) {
1240 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1246 #pragma warning restore 169
1248 // End of methods called from the runtime
1250 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1251 public event AssemblyLoadEventHandler AssemblyLoad;
1253 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1254 public event ResolveEventHandler AssemblyResolve;
1256 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1257 public event EventHandler DomainUnload;
1259 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1260 public event EventHandler ProcessExit;
1262 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1263 public event ResolveEventHandler ResourceResolve;
1265 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1266 public event ResolveEventHandler TypeResolve;
1268 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1269 public event UnhandledExceptionEventHandler UnhandledException;
1271 #if NET_4_0 || BOOTSTRAP_NET_4_0
1273 public bool IsHomogenous {
1274 get { return true; }
1279 #pragma warning disable 649
1280 private AppDomainManager _domain_manager;
1281 #pragma warning restore 649
1284 public AppDomainManager DomainManager {
1285 get { return _domain_manager; }
1289 #if NET_2_0 && !NET_2_1
1291 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1293 #pragma warning disable 649
1294 private ActivationContext _activation;
1295 private ApplicationIdentity _applicationIdentity;
1296 #pragma warning restore 649
1300 public ActivationContext ActivationContext {
1301 get { return _activation; }
1304 public ApplicationIdentity ApplicationIdentity {
1305 get { return _applicationIdentity; }
1309 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1310 get { return getDomainID (); }
1315 [MonoTODO ("This routine only returns the parameter currently")]
1316 [ComVisible (false)]
1317 public string ApplyPolicy (string assemblyName)
1319 if (assemblyName == null)
1320 throw new ArgumentNullException ("assemblyName");
1321 if (assemblyName.Length == 0) // String.Empty
1322 throw new ArgumentException ("assemblyName");
1323 return assemblyName;
1328 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1329 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1331 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1333 info.AppDomainInitializerArguments = adInitArgs;
1334 info.AppDomainInitializer = adInit;
1336 return CreateDomain (friendlyName, securityInfo, info);
1339 public int ExecuteAssemblyByName (string assemblyName)
1341 return ExecuteAssemblyByName (assemblyName, null, null);
1344 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1346 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1349 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1351 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1353 return ExecuteAssemblyInternal (a, args);
1356 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1358 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1360 return ExecuteAssemblyInternal (a, args);
1363 public bool IsDefaultAppDomain ()
1365 return Object.ReferenceEquals (this, DefaultDomain);
1368 public Assembly[] ReflectionOnlyGetAssemblies ()
1370 return GetAssemblies (true);
1375 public int ExecuteAssemblyByName (string assemblyName)
1377 // critical code in SL that we're not calling in ML
1378 throw new NotImplementedException ();
1382 #if NET_1_1 && !NET_2_1
1383 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1385 throw new NotImplementedException ();
1388 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1390 throw new NotImplementedException ();
1393 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1395 throw new NotImplementedException ();
1398 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1399 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1401 throw new NotImplementedException ();