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)
14 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Globalization;
39 using System.Reflection;
40 using System.Reflection.Emit;
41 using System.Threading;
42 using System.Runtime.CompilerServices;
43 using System.Runtime.InteropServices;
44 using System.Runtime.Remoting;
45 using System.Runtime.Remoting.Contexts;
46 using System.Runtime.Remoting.Channels;
47 using System.Runtime.Remoting.Messaging;
48 using System.Security;
49 using System.Security.Permissions;
50 using System.Security.Policy;
51 using System.Security.Principal;
52 using System.Configuration.Assemblies;
54 using System.Collections.Generic;
55 using System.Runtime.ConstrainedExecution;
61 #if !NET_2_1 || MOONLIGHT
62 [ComDefaultInterface (typeof (_AppDomain))]
64 [ClassInterface(ClassInterfaceType.None)]
66 public sealed class AppDomain : _AppDomain {
68 public sealed class AppDomain : MarshalByRefObject, _AppDomain {
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 ();
110 AppDomainSetup SetupInformationNoCopy {
111 get { return getSetup (); }
114 public AppDomainSetup SetupInformation {
116 AppDomainSetup setup = getSetup ();
117 return new AppDomainSetup (setup);
123 public ApplicationTrust ApplicationTrust {
124 get { throw new NotImplementedException (); }
128 public string BaseDirectory {
130 string path = SetupInformationNoCopy.ApplicationBase;
132 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
133 // we cannot divulge local file informations
134 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
141 public string RelativeSearchPath {
143 string path = SetupInformationNoCopy.PrivateBinPath;
145 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
146 // we cannot divulge local file informations
147 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
154 public string DynamicDirectory {
156 AppDomainSetup setup = SetupInformationNoCopy;
157 if (setup.DynamicBase == null)
160 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
162 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
163 // we cannot divulge local file informations
164 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
171 public bool ShadowCopyFiles {
173 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
178 [MethodImplAttribute (MethodImplOptions.InternalCall)]
179 private extern string getFriendlyName ();
181 public string FriendlyName {
183 return getFriendlyName ();
187 public Evidence Evidence {
189 // if the host (runtime) hasn't provided it's own evidence...
190 if (_evidence == null) {
191 // ... we will provide our own
193 // the executed assembly from the "default" appdomain
194 // or null if we're not in the default appdomain or
195 // if there is no entry assembly (embedded mono)
196 Assembly a = Assembly.GetEntryAssembly ();
198 if (this == DefaultDomain)
200 return new Evidence ();
202 _evidence = AppDomain.DefaultDomain.Evidence;
204 _evidence = Evidence.GetDefaultHostEvidence (a);
208 return new Evidence (_evidence); // return a copy
212 internal IPrincipal DefaultPrincipal {
214 if (_principal == null) {
215 switch (_principalPolicy) {
216 case PrincipalPolicy.UnauthenticatedPrincipal:
217 _principal = new GenericPrincipal (
218 new GenericIdentity (String.Empty, String.Empty), null);
220 case PrincipalPolicy.WindowsPrincipal:
221 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
229 // for AppDomain there is only an allowed (i.e. granted) set
230 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
231 internal PermissionSet GrantedPermissionSet {
232 get { return _granted; }
237 public PermissionSet PermissionSet {
238 get { return _granted ?? (_granted = new PermissionSet (PermissionState.Unrestricted)); }
242 [MethodImplAttribute (MethodImplOptions.InternalCall)]
243 private static extern AppDomain getCurDomain ();
245 public static AppDomain CurrentDomain {
247 return getCurDomain ();
251 [MethodImplAttribute (MethodImplOptions.InternalCall)]
252 private static extern AppDomain getRootDomain ();
254 internal static AppDomain DefaultDomain {
256 if (default_domain == null) {
257 AppDomain rd = getRootDomain ();
258 if (rd == CurrentDomain)
261 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
263 return default_domain;
269 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
270 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
271 public void AppendPrivatePath (string path)
273 if (path == null || path.Length == 0)
276 AppDomainSetup setup = SetupInformationNoCopy;
278 string pp = setup.PrivateBinPath;
279 if (pp == null || pp.Length == 0) {
280 setup.PrivateBinPath = path;
285 if (pp [pp.Length - 1] != Path.PathSeparator)
286 pp += Path.PathSeparator;
288 setup.PrivateBinPath = pp + path;
291 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
292 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
293 public void ClearPrivatePath ()
295 SetupInformationNoCopy.PrivateBinPath = String.Empty;
298 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
299 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
300 public void ClearShadowCopyPath ()
302 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
306 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
308 return Activator.CreateComInstanceFrom (assemblyName, typeName);
311 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
312 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
314 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
318 public ObjectHandle CreateInstance (string assemblyName, string typeName)
320 if (assemblyName == null)
321 throw new ArgumentNullException ("assemblyName");
323 return Activator.CreateInstance (assemblyName, typeName);
326 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
328 if (assemblyName == null)
329 throw new ArgumentNullException ("assemblyName");
331 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
335 [Obsolete ("Use an overload that does not take an Evidence parameter")]
337 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
338 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
339 Evidence securityAttributes)
341 if (assemblyName == null)
342 throw new ArgumentNullException ("assemblyName");
344 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
345 culture, activationAttributes, securityAttributes);
348 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
350 ObjectHandle oh = CreateInstance (assemblyName, typeName);
351 return (oh != null) ? oh.Unwrap () : null;
354 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
356 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
357 return (oh != null) ? oh.Unwrap () : null;
361 [Obsolete ("Use an overload that does not take an Evidence parameter")]
363 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
364 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
365 object[] activationAttributes, Evidence securityAttributes)
367 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
368 culture, activationAttributes, securityAttributes);
369 return (oh != null) ? oh.Unwrap () : null;
373 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
374 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
376 if (assemblyName == null)
377 throw new ArgumentNullException ("assemblyName");
379 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
380 culture, activationAttributes, null);
382 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
383 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
384 object[] activationAttributes)
386 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
387 culture, activationAttributes);
388 return (oh != null) ? oh.Unwrap () : null;
391 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
392 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
393 object[] activationAttributes)
395 if (assemblyFile == null)
396 throw new ArgumentNullException ("assemblyFile");
398 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
399 culture, activationAttributes, null);
402 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
403 BindingFlags bindingAttr, Binder binder, object[] args,
404 CultureInfo culture, object[] activationAttributes)
406 ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
407 culture, activationAttributes);
409 return (oh != null) ? oh.Unwrap () : null;
413 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
415 if (assemblyFile == null)
416 throw new ArgumentNullException ("assemblyFile");
418 return Activator.CreateInstanceFrom (assemblyFile, typeName);
421 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
423 if (assemblyFile == null)
424 throw new ArgumentNullException ("assemblyFile");
426 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
430 [Obsolete ("Use an overload that does not take an Evidence parameter")]
432 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
433 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
434 object[] activationAttributes, Evidence securityAttributes)
436 if (assemblyFile == null)
437 throw new ArgumentNullException ("assemblyFile");
439 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
440 culture, activationAttributes, securityAttributes);
443 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
445 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
446 return (oh != null) ? oh.Unwrap () : null;
449 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
451 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
452 return (oh != null) ? oh.Unwrap () : null;
456 [Obsolete ("Use an overload that does not take an Evidence parameter")]
458 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
459 BindingFlags bindingAttr, Binder binder, object[] args,
460 CultureInfo culture, object[] activationAttributes,
461 Evidence securityAttributes)
463 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
464 culture, activationAttributes, securityAttributes);
466 return (oh != null) ? oh.Unwrap () : null;
471 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
473 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
477 [Obsolete ("Declarative security for assembly level is no longer enforced")]
479 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
481 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
484 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
486 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
490 [Obsolete ("Declarative security for assembly level is no longer enforced")]
492 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
495 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
499 [Obsolete ("Declarative security for assembly level is no longer enforced")]
501 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
502 PermissionSet requiredPermissions,
503 PermissionSet optionalPermissions,
504 PermissionSet refusedPermissions)
506 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
507 refusedPermissions, false);
511 [Obsolete ("Declarative security for assembly level is no longer enforced")]
513 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
514 PermissionSet requiredPermissions,
515 PermissionSet optionalPermissions,
516 PermissionSet refusedPermissions)
518 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
519 refusedPermissions, false);
523 [Obsolete ("Declarative security for assembly level is no longer enforced")]
525 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
526 PermissionSet requiredPermissions,
527 PermissionSet optionalPermissions,
528 PermissionSet refusedPermissions)
530 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
531 refusedPermissions, false);
535 [Obsolete ("Declarative security for assembly level is no longer enforced")]
537 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
539 PermissionSet requiredPermissions,
540 PermissionSet optionalPermissions,
541 PermissionSet refusedPermissions)
543 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
544 refusedPermissions, false);
548 [Obsolete ("Declarative security for assembly level is no longer enforced")]
550 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
552 PermissionSet requiredPermissions,
553 PermissionSet optionalPermissions,
554 PermissionSet refusedPermissions, bool isSynchronized)
557 throw new ArgumentNullException ("name");
558 ValidateAssemblyName (name.Name);
560 // FIXME: examine all other parameters
562 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
563 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
569 [Obsolete ("Declarative security for assembly level is no longer enforced")]
571 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
573 PermissionSet requiredPermissions,
574 PermissionSet optionalPermissions,
575 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
577 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
578 if (assemblyAttributes != null)
579 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
580 ab.SetCustomAttribute (cb);
586 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
588 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
592 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
594 return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
597 [MonoLimitation ("The argument securityContextSource is ignored")]
598 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
600 return DefineDynamicAssembly (name, access, assemblyAttributes);
604 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
606 return new AssemblyBuilder (name, null, access, true);
610 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
611 // so, when you call AppDomain.DoCallBack, that's a remote call
613 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
615 if (callBackDelegate != null)
619 public int ExecuteAssembly (string assemblyFile)
621 return ExecuteAssembly (assemblyFile, (Evidence)null, null);
625 [Obsolete ("Use an overload that does not take an Evidence parameter")]
627 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
629 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
633 [Obsolete ("Use an overload that does not take an Evidence parameter")]
635 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
637 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
638 return ExecuteAssemblyInternal (a, args);
642 [Obsolete ("Use an overload that does not take an Evidence parameter")]
644 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
646 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
647 return ExecuteAssemblyInternal (a, args);
652 public int ExecuteAssembly (string assemblyFile, string[] args)
654 Assembly a = Assembly.LoadFrom (assemblyFile, null);
655 return ExecuteAssemblyInternal (a, args);
658 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
660 Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
661 return ExecuteAssemblyInternal (a, args);
665 int ExecuteAssemblyInternal (Assembly a, string[] args)
667 if (a.EntryPoint == null)
668 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
669 return ExecuteAssembly (a, args);
672 [MethodImplAttribute (MethodImplOptions.InternalCall)]
673 private extern int ExecuteAssembly (Assembly a, string[] args);
675 [MethodImplAttribute (MethodImplOptions.InternalCall)]
676 private extern Assembly [] GetAssemblies (bool refOnly);
678 public Assembly [] GetAssemblies ()
680 return GetAssemblies (false);
683 [MethodImplAttribute (MethodImplOptions.InternalCall)]
684 public extern object GetData (string name);
686 public new Type GetType()
688 return base.GetType ();
692 public override object InitializeLifetimeService ()
698 [MethodImplAttribute (MethodImplOptions.InternalCall)]
699 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
701 public Assembly Load (AssemblyName assemblyRef)
703 return Load (assemblyRef, null);
706 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
708 if (assemblyRef == null)
709 throw new ArgumentNullException ("assemblyRef");
711 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
712 if (result == null && throwOnError)
713 throw new FileNotFoundException (null, assemblyRef.Name);
718 [Obsolete ("Use an overload that does not take an Evidence parameter")]
720 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
722 if (assemblyRef == null)
723 throw new ArgumentNullException ("assemblyRef");
725 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
726 if (assemblyRef.CodeBase != null)
727 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
729 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
732 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
733 if (assembly != null)
736 if (assemblyRef.CodeBase == null)
737 throw new FileNotFoundException (null, assemblyRef.Name);
739 string cb = assemblyRef.CodeBase;
740 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
741 cb = new Mono.Security.Uri (cb).LocalPath;
744 assembly = Assembly.LoadFrom (cb, assemblySecurity);
746 throw new FileNotFoundException (null, assemblyRef.Name);
748 AssemblyName aname = assembly.GetName ();
749 // Name, version, culture, publickeytoken. Anything else?
750 if (assemblyRef.Name != aname.Name)
751 throw new FileNotFoundException (null, assemblyRef.Name);
753 if (assemblyRef.Version != null && assemblyRef.Version != new Version (0, 0, 0, 0) && assemblyRef.Version != aname.Version)
754 throw new FileNotFoundException (null, assemblyRef.Name);
756 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
757 throw new FileNotFoundException (null, assemblyRef.Name);
759 byte [] pt = assemblyRef.GetPublicKeyToken ();
760 if (pt != null && pt.Length != 0) {
761 byte [] loaded_pt = aname.GetPublicKeyToken ();
762 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
763 throw new FileNotFoundException (null, assemblyRef.Name);
764 for (int i = pt.Length - 1; i >= 0; i--)
765 if (loaded_pt [i] != pt [i])
766 throw new FileNotFoundException (null, assemblyRef.Name);
771 public Assembly Load (string assemblyString)
773 return Load (assemblyString, null, false);
777 [Obsolete ("Use an overload that does not take an Evidence parameter")]
779 public Assembly Load (string assemblyString, Evidence assemblySecurity)
781 return Load (assemblyString, assemblySecurity, false);
784 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
786 if (assemblyString == null)
787 throw new ArgumentNullException ("assemblyString");
789 if (assemblyString.Length == 0)
790 throw new ArgumentException ("assemblyString cannot have zero length");
792 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
793 if (assembly == null)
794 throw new FileNotFoundException (null, assemblyString);
798 public Assembly Load (byte[] rawAssembly)
800 return Load (rawAssembly, null, null);
803 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
805 return Load (rawAssembly, rawSymbolStore, null);
808 [MethodImplAttribute (MethodImplOptions.InternalCall)]
809 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
812 [Obsolete ("Use an overload that does not take an Evidence parameter")]
814 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
816 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
819 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
821 if (rawAssembly == null)
822 throw new ArgumentNullException ("rawAssembly");
824 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
825 assembly.FromByteArray = true;
830 [Obsolete ("AppDomain policy levels are obsolete")]
832 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
833 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
835 if (domainPolicy == null)
836 throw new ArgumentNullException ("domainPolicy");
837 if (_granted != null) {
838 throw new PolicyException (Locale.GetText (
839 "An AppDomain policy is already specified."));
841 if (IsFinalizingForUnload ())
842 throw new AppDomainUnloadedException ();
844 PolicyStatement ps = domainPolicy.Resolve (_evidence);
845 _granted = ps.PermissionSet;
848 [Obsolete ("Use AppDomainSetup.SetCachePath")]
849 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
850 public void SetCachePath (string path)
852 SetupInformationNoCopy.CachePath = path;
855 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
856 public void SetPrincipalPolicy (PrincipalPolicy policy)
858 if (IsFinalizingForUnload ())
859 throw new AppDomainUnloadedException ();
861 _principalPolicy = policy;
865 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
866 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
867 public void SetShadowCopyFiles()
869 SetupInformationNoCopy.ShadowCopyFiles = "true";
872 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
873 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
874 public void SetShadowCopyPath (string path)
876 SetupInformationNoCopy.ShadowCopyDirectories = path;
879 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
880 public void SetThreadPrincipal (IPrincipal principal)
882 if (principal == null)
883 throw new ArgumentNullException ("principal");
884 if (_principal != null)
885 throw new PolicyException (Locale.GetText ("principal already present."));
886 if (IsFinalizingForUnload ())
887 throw new AppDomainUnloadedException ();
889 _principal = principal;
892 [MethodImplAttribute (MethodImplOptions.InternalCall)]
893 private static extern AppDomain InternalSetDomainByID (int domain_id);
895 // Changes the active domain and returns the old domain
896 [MethodImplAttribute (MethodImplOptions.InternalCall)]
897 private static extern AppDomain InternalSetDomain (AppDomain context);
899 // Notifies the runtime that this thread references 'domain'.
900 [MethodImplAttribute (MethodImplOptions.InternalCall)]
901 internal static extern void InternalPushDomainRef (AppDomain domain);
903 [MethodImplAttribute (MethodImplOptions.InternalCall)]
904 internal static extern void InternalPushDomainRefByID (int domain_id);
906 // Undoes the effect of the last PushDomainRef call
907 [MethodImplAttribute (MethodImplOptions.InternalCall)]
908 internal static extern void InternalPopDomainRef ();
910 // Changes the active context and returns the old context
911 [MethodImplAttribute (MethodImplOptions.InternalCall)]
912 internal static extern Context InternalSetContext (Context context);
914 // Returns the current context
915 [MethodImplAttribute (MethodImplOptions.InternalCall)]
916 internal static extern Context InternalGetContext ();
918 // Returns the current context
919 [MethodImplAttribute (MethodImplOptions.InternalCall)]
920 internal static extern Context InternalGetDefaultContext ();
922 [MethodImplAttribute (MethodImplOptions.InternalCall)]
923 internal static extern string InternalGetProcessGuid (string newguid);
925 // This method is handled specially by the runtime
926 // It is the only managed method which is allowed to set the current
928 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
930 AppDomain current = CurrentDomain;
935 InternalPushDomainRef (domain);
937 InternalSetDomain (domain);
938 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
944 InternalSetDomain (current);
946 InternalPopDomainRef ();
950 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
952 AppDomain current = CurrentDomain;
957 InternalPushDomainRefByID (domain_id);
959 InternalSetDomainByID (domain_id);
960 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
966 InternalSetDomain (current);
968 InternalPopDomainRef ();
972 internal static String GetProcessGuid ()
974 if (_process_guid == null) {
975 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
977 return _process_guid;
982 public static AppDomain CreateDomain (string friendlyName)
984 return CreateDomain (friendlyName, null, null);
987 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
989 return CreateDomain (friendlyName, securityInfo, null);
992 [MethodImplAttribute (MethodImplOptions.InternalCall)]
993 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
995 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
996 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
997 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
999 if (friendlyName == null)
1000 throw new System.ArgumentNullException ("friendlyName");
1002 AppDomain def = AppDomain.DefaultDomain;
1004 // if null, get default domain's SetupInformation
1006 info = new AppDomainSetup (); // we're default!
1008 info = def.SetupInformation;
1011 info = new AppDomainSetup (info); // copy
1013 // todo: allow setup in the other domain
1015 if (!info.Equals (def.SetupInformation)) {
1016 // If not specified use default domain's app base.
1017 if (info.ApplicationBase == null)
1018 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1019 if (info.ConfigurationFile == null)
1020 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1022 } else if (info.ConfigurationFile == null)
1023 info.ConfigurationFile = "[I don't have a config file]";
1026 if (info.AppDomainInitializer != null) {
1027 if (!info.AppDomainInitializer.Method.IsStatic)
1028 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1032 info.SerializeNonPrimitives ();
1034 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1035 if (securityInfo == null) {
1036 // get default domain's Evidence (unless we're are the default!)
1038 ad._evidence = null; // we'll get them later (GetEntryAssembly)
1040 ad._evidence = def.Evidence; // new (shallow) copy
1043 ad._evidence = new Evidence (securityInfo); // copy
1046 if (info.AppDomainInitializer != null) {
1047 Loader loader = new Loader (
1048 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1049 ad.DoCallBack (loader.Load);
1051 Initializer initializer = new Initializer (
1052 info.AppDomainInitializer,
1053 info.AppDomainInitializerArguments);
1054 ad.DoCallBack (initializer.Initialize);
1067 public Loader (string assembly)
1069 this.assembly = assembly;
1074 Assembly.LoadFrom (assembly);
1081 AppDomainInitializer initializer;
1082 string [] arguments;
1084 public Initializer (AppDomainInitializer initializer, string [] arguments)
1086 this.initializer = initializer;
1087 this.arguments = arguments;
1090 public void Initialize ()
1092 initializer (arguments);
1097 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1098 string appRelativeSearchPath, bool shadowCopyFiles)
1100 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1104 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1105 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1108 throw new ArgumentNullException ("info");
1110 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
1111 return CreateDomain (friendlyName, securityInfo, info);
1115 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1117 AppDomainSetup info = new AppDomainSetup ();
1119 info.ApplicationBase = appBasePath;
1120 info.PrivateBinPath = appRelativeSearchPath;
1122 if (shadowCopyFiles)
1123 info.ShadowCopyFiles = "true";
1125 info.ShadowCopyFiles = "false";
1131 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1132 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1134 public bool IsFinalizingForUnload()
1136 return InternalIsFinalizingForUnload (getDomainID ());
1139 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1140 static extern void InternalUnload (int domain_id);
1142 // We do this because if the domain is a transparant proxy this
1143 // will still return the correct domain id.
1144 private int getDomainID ()
1146 return Thread.GetDomainID ();
1149 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1150 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1151 public static void Unload (AppDomain domain)
1154 throw new ArgumentNullException ("domain");
1156 InternalUnload (domain.getDomainID());
1159 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1160 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1161 public extern void SetData (string name, object data);
1163 [MonoLimitation ("The permission field is ignored")]
1164 public void SetData (string name, object data, IPermission permission)
1166 SetData (name, data);
1170 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1171 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1172 public void SetDynamicBase (string path)
1174 SetupInformationNoCopy.DynamicBase = path;
1178 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1179 + " because it does not provide a stable Id when managed"
1180 + " threads are running on fibers (aka lightweight"
1181 + " threads). To get a stable identifier for a managed"
1182 + " thread, use the ManagedThreadId property on Thread.'")]
1183 public static int GetCurrentThreadId ()
1185 return Thread.CurrentThreadId;
1188 public override string ToString ()
1191 return getFriendlyName ();
1193 StringBuilder sb = new StringBuilder ("Name:");
1194 sb.AppendLine (FriendlyName);
1195 sb.AppendLine ("There are no context policies.");
1196 return sb.ToString ();
1200 private static void ValidateAssemblyName (string name)
1202 if (name == null || name.Length == 0)
1203 throw new ArgumentException ("The Name of " +
1204 "AssemblyName cannot be null or a " +
1205 "zero-length string.");
1207 bool isValid = true;
1209 for (int i = 0; i < name.Length; i++) {
1212 // do not allow leading whitespace
1213 if (i == 0 && char.IsWhiteSpace (c)) {
1218 // do not allow /,\ or : in name
1219 if (c == '/' || c == '\\' || c == ':') {
1226 throw new ArgumentException ("The Name of " +
1227 "AssemblyName cannot start with " +
1228 "whitespace, or contain '/', '\\' " +
1232 // The following methods are called from the runtime. Don't change signatures.
1233 #pragma warning disable 169
1234 private void DoAssemblyLoad (Assembly assembly)
1236 if (AssemblyLoad == null)
1239 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1242 private Assembly DoAssemblyResolve (string name, bool refonly)
1244 ResolveEventHandler del;
1247 del = ReflectionOnlyAssemblyResolve;
1249 del = AssemblyResolve;
1251 del = AssemblyResolve;
1256 /* Prevent infinite recursion */
1259 ht = assembly_resolve_in_progress_refonly;
1261 ht = new Hashtable ();
1262 assembly_resolve_in_progress_refonly = ht;
1265 ht = assembly_resolve_in_progress;
1267 ht = new Hashtable ();
1268 assembly_resolve_in_progress = ht;
1272 string s = (string) ht [name];
1277 Delegate[] invocation_list = del.GetInvocationList ();
1279 foreach (Delegate eh in invocation_list) {
1280 ResolveEventHandler handler = (ResolveEventHandler) eh;
1281 Assembly assembly = handler (this, new ResolveEventArgs (name));
1282 if (assembly != null)
1292 internal Assembly DoTypeResolve (Object name_or_tb)
1294 if (TypeResolve == null)
1299 if (name_or_tb is TypeBuilder)
1300 name = ((TypeBuilder) name_or_tb).FullName;
1302 name = (string) name_or_tb;
1304 /* Prevent infinite recursion */
1305 Hashtable ht = type_resolve_in_progress;
1307 ht = new Hashtable ();
1308 type_resolve_in_progress = ht;
1311 if (ht.Contains (name))
1317 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1318 ResolveEventHandler eh = (ResolveEventHandler) d;
1319 Assembly assembly = eh (this, new ResolveEventArgs (name));
1320 if (assembly != null)
1330 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1331 if (ResourceResolve == null)
1334 Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1336 foreach (Delegate eh in invocation_list) {
1337 ResolveEventHandler handler = (ResolveEventHandler) eh;
1339 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1341 Assembly assembly = handler (this, new ResolveEventArgs (name));
1343 if (assembly != null)
1349 private void DoDomainUnload ()
1351 if (DomainUnload != null)
1352 DomainUnload(this, null);
1355 internal byte[] GetMarshalledDomainObjRef ()
1357 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1358 return CADSerializer.SerializeObject (oref).GetBuffer();
1361 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1362 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1366 if (null != arrRequest)
1367 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1369 reqDomMsg = new MethodCall (cadMsg);
1371 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1373 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1374 if (null == cadMrm) {
1375 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1381 #pragma warning restore 169
1383 // End of methods called from the runtime
1385 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1386 public event AssemblyLoadEventHandler AssemblyLoad;
1388 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1389 public event ResolveEventHandler AssemblyResolve;
1391 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1392 public event EventHandler DomainUnload;
1394 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1395 public event EventHandler ProcessExit;
1397 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1398 public event ResolveEventHandler ResourceResolve;
1400 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1401 public event ResolveEventHandler TypeResolve;
1403 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1404 public event UnhandledExceptionEventHandler UnhandledException;
1408 public bool IsHomogenous {
1409 get { return true; }
1413 public bool IsFullyTrusted {
1414 get { return true; }
1418 #pragma warning disable 649
1419 private AppDomainManager _domain_manager;
1420 #pragma warning restore 649
1423 public AppDomainManager DomainManager {
1424 get { return _domain_manager; }
1429 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1431 #pragma warning disable 649
1432 private ActivationContext _activation;
1433 private ApplicationIdentity _applicationIdentity;
1434 #pragma warning restore 649
1438 public ActivationContext ActivationContext {
1439 get { return _activation; }
1442 public ApplicationIdentity ApplicationIdentity {
1443 get { return _applicationIdentity; }
1447 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1448 get { return getDomainID (); }
1453 [MonoTODO ("This routine only returns the parameter currently")]
1454 [ComVisible (false)]
1455 public string ApplyPolicy (string assemblyName)
1457 if (assemblyName == null)
1458 throw new ArgumentNullException ("assemblyName");
1459 if (assemblyName.Length == 0) // String.Empty
1460 throw new ArgumentException ("assemblyName");
1461 return assemblyName;
1466 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1467 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1469 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1471 info.AppDomainInitializerArguments = adInitArgs;
1472 info.AppDomainInitializer = adInit;
1474 return CreateDomain (friendlyName, securityInfo, info);
1477 public int ExecuteAssemblyByName (string assemblyName)
1479 return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1483 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1485 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1487 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1491 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1493 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1495 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1497 return ExecuteAssemblyInternal (a, args);
1501 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1503 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1505 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1507 return ExecuteAssemblyInternal (a, args);
1511 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1513 Assembly a = Assembly.Load (assemblyName, null);
1515 return ExecuteAssemblyInternal (a, args);
1518 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1520 Assembly a = Assembly.Load (assemblyName, null);
1522 return ExecuteAssemblyInternal (a, args);
1526 public bool IsDefaultAppDomain ()
1528 return Object.ReferenceEquals (this, DefaultDomain);
1531 public Assembly[] ReflectionOnlyGetAssemblies ()
1533 return GetAssemblies (true);
1538 public int ExecuteAssemblyByName (string assemblyName)
1540 // critical code in SL that we're not calling in ML
1541 throw new NotImplementedException ();
1546 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1548 throw new NotImplementedException ();
1551 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1553 throw new NotImplementedException ();
1556 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1558 throw new NotImplementedException ();
1561 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1562 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1564 throw new NotImplementedException ();
1568 #if NET_4_0 || MOONLIGHT || MOBILE
1569 List<string> compatibility_switch;
1571 public bool? IsCompatibilitySwitchSet (string value)
1574 throw new ArgumentNullException ("value");
1576 // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1577 return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1580 internal void SetCompatibilitySwitch (string value)
1582 if (compatibility_switch == null)
1583 compatibility_switch = new List<string> ();
1584 compatibility_switch.Add (value);
1587 [MonoTODO ("Currently always returns false")]
1588 public static bool MonitoringIsEnabled {
1589 get { return false; }
1590 set { throw new NotImplementedException (); }
1594 public long MonitoringSurvivedMemorySize {
1595 get { throw new NotImplementedException (); }
1599 public static long MonitoringSurvivedProcessMemorySize {
1600 get { throw new NotImplementedException (); }
1604 public long MonitoringTotalAllocatedMemorySize {
1605 get { throw new NotImplementedException (); }
1609 public TimeSpan MonitoringTotalProcessorTime {
1610 get { throw new NotImplementedException (); }