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;
53 using System.Collections.Generic;
54 using System.Runtime.ConstrainedExecution;
61 [ComDefaultInterface (typeof (_AppDomain))]
63 [ClassInterface(ClassInterfaceType.None)]
65 public sealed class AppDomain : MarshalByRefObject {
67 public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory {
69 #pragma warning disable 169
70 #region Sync with object-internals.h
71 IntPtr _mono_app_domain;
73 #pragma warning restore 169
74 static string _process_guid;
77 static Hashtable type_resolve_in_progress;
80 static Hashtable assembly_resolve_in_progress;
83 static Hashtable assembly_resolve_in_progress_refonly;
86 private Evidence _evidence;
87 private PermissionSet _granted;
90 private PrincipalPolicy _principalPolicy;
93 private static IPrincipal _principal;
95 static AppDomain default_domain;
101 [MethodImplAttribute (MethodImplOptions.InternalCall)]
102 private extern AppDomainSetup getSetup ();
107 AppDomainSetup SetupInformationNoCopy {
108 get { return getSetup (); }
111 public AppDomainSetup SetupInformation {
113 AppDomainSetup setup = getSetup ();
114 return new AppDomainSetup (setup);
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;
253 [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;
275 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
276 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
277 public void ClearPrivatePath ()
279 SetupInformationNoCopy.PrivateBinPath = String.Empty;
282 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
283 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
284 public void ClearShadowCopyPath ()
286 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
290 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
292 return Activator.CreateComInstanceFrom (assemblyName, typeName);
295 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
296 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
298 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
302 public ObjectHandle CreateInstance (string assemblyName, string typeName)
304 if (assemblyName == null)
305 throw new ArgumentNullException ("assemblyName");
307 return Activator.CreateInstance (assemblyName, typeName);
310 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
312 if (assemblyName == null)
313 throw new ArgumentNullException ("assemblyName");
315 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
319 [Obsolete ("Use an overload that does not take an Evidence parameter")]
321 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
322 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
323 Evidence securityAttributes)
325 if (assemblyName == null)
326 throw new ArgumentNullException ("assemblyName");
328 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
329 culture, activationAttributes, securityAttributes);
332 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
334 ObjectHandle oh = CreateInstance (assemblyName, typeName);
335 return (oh != null) ? oh.Unwrap () : null;
338 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
340 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
341 return (oh != null) ? oh.Unwrap () : null;
345 [Obsolete ("Use an overload that does not take an Evidence parameter")]
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;
357 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
358 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
360 if (assemblyName == null)
361 throw new ArgumentNullException ("assemblyName");
363 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
364 culture, activationAttributes, null);
366 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
367 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
368 object[] activationAttributes)
370 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
371 culture, activationAttributes);
372 return (oh != null) ? oh.Unwrap () : null;
375 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
376 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
377 object[] activationAttributes)
379 if (assemblyFile == null)
380 throw new ArgumentNullException ("assemblyFile");
382 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
383 culture, activationAttributes, null);
386 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
387 BindingFlags bindingAttr, Binder binder, object[] args,
388 CultureInfo culture, object[] activationAttributes)
390 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
391 culture, activationAttributes);
393 return (oh != null) ? oh.Unwrap () : null;
397 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
399 if (assemblyFile == null)
400 throw new ArgumentNullException ("assemblyFile");
402 return Activator.CreateInstanceFrom (assemblyFile, typeName);
405 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
407 if (assemblyFile == null)
408 throw new ArgumentNullException ("assemblyFile");
410 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
414 [Obsolete ("Use an overload that does not take an Evidence parameter")]
416 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
417 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
418 object[] activationAttributes, Evidence securityAttributes)
420 if (assemblyFile == null)
421 throw new ArgumentNullException ("assemblyFile");
423 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
424 culture, activationAttributes, securityAttributes);
427 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
429 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
430 return (oh != null) ? oh.Unwrap () : null;
433 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
435 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
436 return (oh != null) ? oh.Unwrap () : null;
440 [Obsolete ("Use an overload that does not take an Evidence parameter")]
442 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
443 BindingFlags bindingAttr, Binder binder, object[] args,
444 CultureInfo culture, object[] activationAttributes,
445 Evidence securityAttributes)
447 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
448 culture, activationAttributes, securityAttributes);
450 return (oh != null) ? oh.Unwrap () : null;
455 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
457 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
461 [Obsolete ("Declarative security for assembly level is no longer enforced")]
463 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
465 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
468 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
470 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
474 [Obsolete ("Declarative security for assembly level is no longer enforced")]
476 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
479 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
483 [Obsolete ("Declarative security for assembly level is no longer enforced")]
485 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
486 PermissionSet requiredPermissions,
487 PermissionSet optionalPermissions,
488 PermissionSet refusedPermissions)
490 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
491 refusedPermissions, false);
495 [Obsolete ("Declarative security for assembly level is no longer enforced")]
497 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
498 PermissionSet requiredPermissions,
499 PermissionSet optionalPermissions,
500 PermissionSet refusedPermissions)
502 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
503 refusedPermissions, false);
507 [Obsolete ("Declarative security for assembly level is no longer enforced")]
509 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
510 PermissionSet requiredPermissions,
511 PermissionSet optionalPermissions,
512 PermissionSet refusedPermissions)
514 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
515 refusedPermissions, false);
519 [Obsolete ("Declarative security for assembly level is no longer enforced")]
521 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
523 PermissionSet requiredPermissions,
524 PermissionSet optionalPermissions,
525 PermissionSet refusedPermissions)
527 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
528 refusedPermissions, false);
532 [Obsolete ("Declarative security for assembly level is no longer enforced")]
534 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
536 PermissionSet requiredPermissions,
537 PermissionSet optionalPermissions,
538 PermissionSet refusedPermissions, bool isSynchronized)
541 throw new ArgumentNullException ("name");
542 ValidateAssemblyName (name.Name);
544 // FIXME: examine all other parameters
546 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
547 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
553 [Obsolete ("Declarative security for assembly level is no longer enforced")]
555 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
557 PermissionSet requiredPermissions,
558 PermissionSet optionalPermissions,
559 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
561 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
562 if (assemblyAttributes != null)
563 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
564 ab.SetCustomAttribute (cb);
570 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes) {
571 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
574 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
576 return new AssemblyBuilder (name, null, access, true);
580 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
581 // so, when you call AppDomain.DoCallBack, that's a remote call
583 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
585 if (callBackDelegate != null)
589 public int ExecuteAssembly (string assemblyFile)
591 return ExecuteAssembly (assemblyFile, (Evidence)null, null);
595 [Obsolete ("Use an overload that does not take an Evidence parameter")]
597 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
599 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
603 [Obsolete ("Use an overload that does not take an Evidence parameter")]
605 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
607 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
608 return ExecuteAssemblyInternal (a, args);
612 [Obsolete ("Use an overload that does not take an Evidence parameter")]
614 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
616 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
617 return ExecuteAssemblyInternal (a, args);
622 public int ExecuteAssembly (string assemblyFile, string[] args)
624 Assembly a = Assembly.LoadFrom (assemblyFile, null);
625 return ExecuteAssemblyInternal (a, args);
628 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
630 Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
631 return ExecuteAssemblyInternal (a, args);
635 int ExecuteAssemblyInternal (Assembly a, string[] args)
637 if (a.EntryPoint == null)
638 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
639 return ExecuteAssembly (a, args);
642 [MethodImplAttribute (MethodImplOptions.InternalCall)]
643 private extern int ExecuteAssembly (Assembly a, string[] args);
645 [MethodImplAttribute (MethodImplOptions.InternalCall)]
646 private extern Assembly [] GetAssemblies (bool refOnly);
648 public Assembly [] GetAssemblies ()
650 return GetAssemblies (false);
653 [MethodImplAttribute (MethodImplOptions.InternalCall)]
654 public extern object GetData (string name);
656 public new Type GetType()
658 return base.GetType ();
661 public override object InitializeLifetimeService ()
666 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
669 public Assembly Load (AssemblyName assemblyRef)
671 return Load (assemblyRef, null);
674 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
676 if (assemblyRef == null)
677 throw new ArgumentNullException ("assemblyRef");
679 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
680 if (result == null && throwOnError)
681 throw new FileNotFoundException (null, assemblyRef.Name);
686 [Obsolete ("Use an overload that does not take an Evidence parameter")]
688 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
690 if (assemblyRef == null)
691 throw new ArgumentNullException ("assemblyRef");
693 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
694 if (assemblyRef.CodeBase != null)
695 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
697 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
700 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
701 if (assembly != null)
704 if (assemblyRef.CodeBase == null)
705 throw new FileNotFoundException (null, assemblyRef.Name);
707 string cb = assemblyRef.CodeBase;
708 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
709 cb = new Mono.Security.Uri (cb).LocalPath;
712 assembly = Assembly.LoadFrom (cb, assemblySecurity);
714 throw new FileNotFoundException (null, assemblyRef.Name);
716 AssemblyName aname = assembly.GetName ();
717 // Name, version, culture, publickeytoken. Anything else?
718 if (assemblyRef.Name != aname.Name)
719 throw new FileNotFoundException (null, assemblyRef.Name);
721 if (assemblyRef.Version != new Version () && assemblyRef.Version != aname.Version)
722 throw new FileNotFoundException (null, assemblyRef.Name);
724 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
725 throw new FileNotFoundException (null, assemblyRef.Name);
727 byte [] pt = assemblyRef.GetPublicKeyToken ();
729 byte [] loaded_pt = aname.GetPublicKeyToken ();
730 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
731 throw new FileNotFoundException (null, assemblyRef.Name);
732 for (int i = pt.Length - 1; i >= 0; i--)
733 if (loaded_pt [i] != pt [i])
734 throw new FileNotFoundException (null, assemblyRef.Name);
739 public Assembly Load (string assemblyString)
741 return Load (assemblyString, null, false);
745 [Obsolete ("Use an overload that does not take an Evidence parameter")]
747 public Assembly Load (string assemblyString, Evidence assemblySecurity)
749 return Load (assemblyString, assemblySecurity, false);
752 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
754 if (assemblyString == null)
755 throw new ArgumentNullException ("assemblyString");
757 if (assemblyString.Length == 0)
758 throw new ArgumentException ("assemblyString cannot have zero length");
760 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
761 if (assembly == null)
762 throw new FileNotFoundException (null, assemblyString);
766 public Assembly Load (byte[] rawAssembly)
768 return Load (rawAssembly, null, null);
771 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
773 return Load (rawAssembly, rawSymbolStore, null);
776 [MethodImplAttribute (MethodImplOptions.InternalCall)]
777 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
780 [Obsolete ("Use an overload that does not take an Evidence parameter")]
782 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
784 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
787 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
789 if (rawAssembly == null)
790 throw new ArgumentNullException ("rawAssembly");
792 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
793 assembly.FromByteArray = true;
798 [Obsolete ("AppDomain policy levels are obsolete")]
800 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
801 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
803 if (domainPolicy == null)
804 throw new ArgumentNullException ("domainPolicy");
805 if (_granted != null) {
806 throw new PolicyException (Locale.GetText (
807 "An AppDomain policy is already specified."));
809 if (IsFinalizingForUnload ())
810 throw new AppDomainUnloadedException ();
812 PolicyStatement ps = domainPolicy.Resolve (_evidence);
813 _granted = ps.PermissionSet;
816 [Obsolete ("Use AppDomainSetup.SetCachePath")]
817 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
818 public void SetCachePath (string path)
820 SetupInformationNoCopy.CachePath = path;
823 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
824 public void SetPrincipalPolicy (PrincipalPolicy policy)
826 if (IsFinalizingForUnload ())
827 throw new AppDomainUnloadedException ();
829 _principalPolicy = policy;
833 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
834 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
835 public void SetShadowCopyFiles()
837 SetupInformationNoCopy.ShadowCopyFiles = "true";
840 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
841 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
842 public void SetShadowCopyPath (string path)
844 SetupInformationNoCopy.ShadowCopyDirectories = path;
847 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
848 public void SetThreadPrincipal (IPrincipal principal)
850 if (principal == null)
851 throw new ArgumentNullException ("principal");
852 if (_principal != null)
853 throw new PolicyException (Locale.GetText ("principal already present."));
854 if (IsFinalizingForUnload ())
855 throw new AppDomainUnloadedException ();
857 _principal = principal;
860 [MethodImplAttribute (MethodImplOptions.InternalCall)]
861 private static extern AppDomain InternalSetDomainByID (int domain_id);
863 // Changes the active domain and returns the old domain
864 [MethodImplAttribute (MethodImplOptions.InternalCall)]
865 private static extern AppDomain InternalSetDomain (AppDomain context);
867 // Notifies the runtime that this thread references 'domain'.
868 [MethodImplAttribute (MethodImplOptions.InternalCall)]
869 internal static extern void InternalPushDomainRef (AppDomain domain);
871 [MethodImplAttribute (MethodImplOptions.InternalCall)]
872 internal static extern void InternalPushDomainRefByID (int domain_id);
874 // Undoes the effect of the last PushDomainRef call
875 [MethodImplAttribute (MethodImplOptions.InternalCall)]
876 internal static extern void InternalPopDomainRef ();
878 // Changes the active context and returns the old context
879 [MethodImplAttribute (MethodImplOptions.InternalCall)]
880 internal static extern Context InternalSetContext (Context context);
882 // Returns the current context
883 [MethodImplAttribute (MethodImplOptions.InternalCall)]
884 internal static extern Context InternalGetContext ();
886 // Returns the current context
887 [MethodImplAttribute (MethodImplOptions.InternalCall)]
888 internal static extern Context InternalGetDefaultContext ();
890 [MethodImplAttribute (MethodImplOptions.InternalCall)]
891 internal static extern string InternalGetProcessGuid (string newguid);
893 // This method is handled specially by the runtime
894 // It is the only managed method which is allowed to set the current
896 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
898 AppDomain current = CurrentDomain;
903 InternalPushDomainRef (domain);
905 InternalSetDomain (domain);
906 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
912 InternalSetDomain (current);
914 InternalPopDomainRef ();
918 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
920 AppDomain current = CurrentDomain;
925 InternalPushDomainRefByID (domain_id);
927 InternalSetDomainByID (domain_id);
928 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
934 InternalSetDomain (current);
936 InternalPopDomainRef ();
940 internal static String GetProcessGuid ()
942 if (_process_guid == null) {
943 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
945 return _process_guid;
950 public static AppDomain CreateDomain (string friendlyName)
952 return CreateDomain (friendlyName, null, null);
955 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
957 return CreateDomain (friendlyName, securityInfo, null);
960 [MethodImplAttribute (MethodImplOptions.InternalCall)]
961 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
963 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
964 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
965 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
967 if (friendlyName == null)
968 throw new System.ArgumentNullException ("friendlyName");
970 AppDomain def = AppDomain.DefaultDomain;
972 // if null, get default domain's SetupInformation
974 info = new AppDomainSetup (); // we're default!
976 info = def.SetupInformation;
979 info = new AppDomainSetup (info); // copy
981 // todo: allow setup in the other domain
983 if (!info.Equals (def.SetupInformation)) {
984 // If not specified use default domain's app base.
985 if (info.ApplicationBase == null)
986 info.ApplicationBase = def.SetupInformation.ApplicationBase;
987 if (info.ConfigurationFile == null)
988 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
990 } else if (info.ConfigurationFile == null)
991 info.ConfigurationFile = "[I don't have a config file]";
994 if (info.AppDomainInitializer != null) {
995 if (!info.AppDomainInitializer.Method.IsStatic)
996 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1000 info.SerializeNonPrimitives ();
1002 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1003 if (securityInfo == null) {
1004 // get default domain's Evidence (unless we're are the default!)
1006 ad._evidence = null; // we'll get them later (GetEntryAssembly)
1008 ad._evidence = def.Evidence; // new (shallow) copy
1011 ad._evidence = new Evidence (securityInfo); // copy
1014 if (info.AppDomainInitializer != null) {
1015 Loader loader = new Loader (
1016 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1017 ad.DoCallBack (loader.Load);
1019 Initializer initializer = new Initializer (
1020 info.AppDomainInitializer,
1021 info.AppDomainInitializerArguments);
1022 ad.DoCallBack (initializer.Initialize);
1035 public Loader (string assembly)
1037 this.assembly = assembly;
1042 Assembly.LoadFrom (assembly);
1049 AppDomainInitializer initializer;
1050 string [] arguments;
1052 public Initializer (AppDomainInitializer initializer, string [] arguments)
1054 this.initializer = initializer;
1055 this.arguments = arguments;
1058 public void Initialize ()
1060 initializer (arguments);
1065 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1066 string appRelativeSearchPath, bool shadowCopyFiles)
1068 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1072 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1073 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1076 throw new ArgumentNullException ("info");
1078 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
1079 return CreateDomain (friendlyName, securityInfo, info);
1083 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1085 AppDomainSetup info = new AppDomainSetup ();
1087 info.ApplicationBase = appBasePath;
1088 info.PrivateBinPath = appRelativeSearchPath;
1090 if (shadowCopyFiles)
1091 info.ShadowCopyFiles = "true";
1093 info.ShadowCopyFiles = "false";
1099 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1100 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1102 public bool IsFinalizingForUnload()
1104 return InternalIsFinalizingForUnload (getDomainID ());
1107 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1108 static extern void InternalUnload (int domain_id);
1110 // We do this because if the domain is a transparant proxy this
1111 // will still return the correct domain id.
1112 private int getDomainID ()
1114 return Thread.GetDomainID ();
1117 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1118 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1119 public static void Unload (AppDomain domain)
1122 throw new ArgumentNullException ("domain");
1124 InternalUnload (domain.getDomainID());
1127 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1128 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1129 public extern void SetData (string name, object data);
1131 [MonoLimitation ("The permission field is ignored")]
1132 public void SetData (string name, object data, IPermission permission)
1134 SetData (name, data);
1138 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1139 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1140 public void SetDynamicBase (string path)
1142 SetupInformationNoCopy.DynamicBase = path;
1146 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1147 + " because it does not provide a stable Id when managed"
1148 + " threads are running on fibers (aka lightweight"
1149 + " threads). To get a stable identifier for a managed"
1150 + " thread, use the ManagedThreadId property on Thread.'")]
1151 public static int GetCurrentThreadId ()
1153 return Thread.CurrentThreadId;
1156 public override string ToString ()
1159 return getFriendlyName ();
1161 StringBuilder sb = new StringBuilder ("Name:");
1162 sb.AppendLine (FriendlyName);
1163 sb.AppendLine ("There are no context policies.");
1164 return sb.ToString ();
1168 private static void ValidateAssemblyName (string name)
1170 if (name == null || name.Length == 0)
1171 throw new ArgumentException ("The Name of " +
1172 "AssemblyName cannot be null or a " +
1173 "zero-length string.");
1175 bool isValid = true;
1177 for (int i = 0; i < name.Length; i++) {
1180 // do not allow leading whitespace
1181 if (i == 0 && char.IsWhiteSpace (c)) {
1186 // do not allow /,\ or : in name
1187 if (c == '/' || c == '\\' || c == ':') {
1194 throw new ArgumentException ("The Name of " +
1195 "AssemblyName cannot start with " +
1196 "whitespace, or contain '/', '\\' " +
1200 // The following methods are called from the runtime. Don't change signatures.
1201 #pragma warning disable 169
1202 private void DoAssemblyLoad (Assembly assembly)
1204 if (AssemblyLoad == null)
1207 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1210 private Assembly DoAssemblyResolve (string name, bool refonly)
1212 ResolveEventHandler del;
1215 del = ReflectionOnlyAssemblyResolve;
1217 del = AssemblyResolve;
1219 del = AssemblyResolve;
1224 /* Prevent infinite recursion */
1227 ht = assembly_resolve_in_progress_refonly;
1229 ht = new Hashtable ();
1230 assembly_resolve_in_progress_refonly = ht;
1233 ht = assembly_resolve_in_progress;
1235 ht = new Hashtable ();
1236 assembly_resolve_in_progress = ht;
1240 string s = (string) ht [name];
1245 Delegate[] invocation_list = del.GetInvocationList ();
1247 foreach (Delegate eh in invocation_list) {
1248 ResolveEventHandler handler = (ResolveEventHandler) eh;
1249 Assembly assembly = handler (this, new ResolveEventArgs (name));
1250 if (assembly != null)
1260 internal Assembly DoTypeResolve (Object name_or_tb)
1262 if (TypeResolve == null)
1267 if (name_or_tb is TypeBuilder)
1268 name = ((TypeBuilder) name_or_tb).FullName;
1270 name = (string) name_or_tb;
1272 /* Prevent infinite recursion */
1273 Hashtable ht = type_resolve_in_progress;
1275 ht = new Hashtable ();
1276 type_resolve_in_progress = ht;
1279 if (ht.Contains (name))
1285 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1286 ResolveEventHandler eh = (ResolveEventHandler) d;
1287 Assembly assembly = eh (this, new ResolveEventArgs (name));
1288 if (assembly != null)
1298 private void DoDomainUnload ()
1300 if (DomainUnload != null)
1301 DomainUnload(this, null);
1305 internal byte[] GetMarshalledDomainObjRef ()
1307 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1308 return CADSerializer.SerializeObject (oref).GetBuffer();
1311 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1312 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1316 if (null != arrRequest)
1317 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1319 reqDomMsg = new MethodCall (cadMsg);
1321 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1323 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1324 if (null == cadMrm) {
1325 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1331 #pragma warning restore 169
1333 // End of methods called from the runtime
1335 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1336 public event AssemblyLoadEventHandler AssemblyLoad;
1338 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1339 public event ResolveEventHandler AssemblyResolve;
1341 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1342 public event EventHandler DomainUnload;
1344 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1345 public event EventHandler ProcessExit;
1347 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1348 public event ResolveEventHandler ResourceResolve;
1350 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1351 public event ResolveEventHandler TypeResolve;
1353 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1354 public event UnhandledExceptionEventHandler UnhandledException;
1356 #if NET_4_0 || BOOTSTRAP_NET_4_0
1358 public bool IsHomogenous {
1359 get { return true; }
1363 #pragma warning disable 649
1364 private AppDomainManager _domain_manager;
1365 #pragma warning restore 649
1368 public AppDomainManager DomainManager {
1369 get { return _domain_manager; }
1374 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1376 #pragma warning disable 649
1377 private ActivationContext _activation;
1378 private ApplicationIdentity _applicationIdentity;
1379 #pragma warning restore 649
1383 public ActivationContext ActivationContext {
1384 get { return _activation; }
1387 public ApplicationIdentity ApplicationIdentity {
1388 get { return _applicationIdentity; }
1392 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1393 get { return getDomainID (); }
1398 [MonoTODO ("This routine only returns the parameter currently")]
1399 [ComVisible (false)]
1400 public string ApplyPolicy (string assemblyName)
1402 if (assemblyName == null)
1403 throw new ArgumentNullException ("assemblyName");
1404 if (assemblyName.Length == 0) // String.Empty
1405 throw new ArgumentException ("assemblyName");
1406 return assemblyName;
1411 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1412 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1414 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1416 info.AppDomainInitializerArguments = adInitArgs;
1417 info.AppDomainInitializer = adInit;
1419 return CreateDomain (friendlyName, securityInfo, info);
1422 public int ExecuteAssemblyByName (string assemblyName)
1424 return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1428 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1430 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1432 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1436 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1438 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1440 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1442 return ExecuteAssemblyInternal (a, args);
1446 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1448 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1450 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1452 return ExecuteAssemblyInternal (a, args);
1456 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1458 Assembly a = Assembly.Load (assemblyName, null);
1460 return ExecuteAssemblyInternal (a, args);
1463 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1465 Assembly a = Assembly.Load (assemblyName, null);
1467 return ExecuteAssemblyInternal (a, args);
1471 public bool IsDefaultAppDomain ()
1473 return Object.ReferenceEquals (this, DefaultDomain);
1476 public Assembly[] ReflectionOnlyGetAssemblies ()
1478 return GetAssemblies (true);
1483 public int ExecuteAssemblyByName (string assemblyName)
1485 // critical code in SL that we're not calling in ML
1486 throw new NotImplementedException ();
1491 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1493 throw new NotImplementedException ();
1496 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1498 throw new NotImplementedException ();
1501 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1503 throw new NotImplementedException ();
1506 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1507 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1509 throw new NotImplementedException ();
1513 #if NET_4_0 || (NET_2_1 && !MONOTOUCH)
1514 [MonoTODO ("Currently always returns null")]
1515 public bool? IsCompatibilitySwitchSet (string value)