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.Globalization;
38 using System.Reflection;
40 using System.Reflection.Emit;
42 using System.Threading;
43 using System.Runtime.CompilerServices;
44 using System.Runtime.InteropServices;
45 using System.Runtime.Remoting;
46 using System.Runtime.Remoting.Contexts;
47 using System.Runtime.Remoting.Channels;
48 using System.Runtime.Remoting.Messaging;
49 using System.Security;
50 using System.Security.Permissions;
51 using System.Security.Policy;
52 using System.Security.Principal;
53 using System.Configuration.Assemblies;
55 using System.Collections.Generic;
56 using System.Runtime.ConstrainedExecution;
63 [ComDefaultInterface (typeof (_AppDomain))]
65 [ClassInterface(ClassInterfaceType.None)]
66 [StructLayout (LayoutKind.Sequential)]
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 Dictionary<string, object> type_resolve_in_progress;
83 static Dictionary<string, object> assembly_resolve_in_progress;
86 static Dictionary<string, object> assembly_resolve_in_progress_refonly;
89 private Evidence _evidence;
90 private PermissionSet _granted;
93 private PrincipalPolicy _principalPolicy;
96 private static IPrincipal _principal;
102 int _principalPolicy;
105 static object _principal;
109 static AppDomain default_domain;
115 [MethodImplAttribute (MethodImplOptions.InternalCall)]
116 private extern AppDomainSetup getSetup ();
121 AppDomainSetup SetupInformationNoCopy {
122 get { return getSetup (); }
125 public AppDomainSetup SetupInformation {
127 AppDomainSetup setup = getSetup ();
128 return new AppDomainSetup (setup);
134 public ApplicationTrust ApplicationTrust {
135 get { throw new NotImplementedException (); }
138 public string BaseDirectory {
140 string path = SetupInformationNoCopy.ApplicationBase;
142 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
143 // we cannot divulge local file informations
144 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
151 public string RelativeSearchPath {
153 string path = SetupInformationNoCopy.PrivateBinPath;
155 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
156 // we cannot divulge local file informations
157 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
164 public string DynamicDirectory {
166 AppDomainSetup setup = SetupInformationNoCopy;
167 if (setup.DynamicBase == null)
170 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
172 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
173 // we cannot divulge local file informations
174 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
181 public bool ShadowCopyFiles {
183 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
187 [MethodImplAttribute (MethodImplOptions.InternalCall)]
188 private extern string getFriendlyName ();
190 public string FriendlyName {
192 return getFriendlyName ();
196 public Evidence Evidence {
201 // if the host (runtime) hasn't provided it's own evidence...
202 if (_evidence == null) {
203 // ... we will provide our own
205 // the executed assembly from the "default" appdomain
206 // or null if we're not in the default appdomain or
207 // if there is no entry assembly (embedded mono)
208 Assembly a = Assembly.GetEntryAssembly ();
210 if (this == DefaultDomain)
212 return new Evidence ();
214 _evidence = AppDomain.DefaultDomain.Evidence;
216 _evidence = Evidence.GetDefaultHostEvidence (a);
220 return new Evidence ((Evidence)_evidence); // return a copy
225 internal IPrincipal DefaultPrincipal {
227 if (_principal == null) {
228 switch ((PrincipalPolicy)_principalPolicy) {
229 case PrincipalPolicy.UnauthenticatedPrincipal:
230 _principal = new GenericPrincipal (
231 new GenericIdentity (String.Empty, String.Empty), null);
233 case PrincipalPolicy.WindowsPrincipal:
234 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
238 return (IPrincipal)_principal;
242 // for AppDomain there is only an allowed (i.e. granted) set
243 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
244 internal PermissionSet GrantedPermissionSet {
245 get { return (PermissionSet)_granted; }
249 public PermissionSet PermissionSet {
250 get { return (PermissionSet)_granted ?? (PermissionSet)(_granted = new PermissionSet (PermissionState.Unrestricted)); }
254 [MethodImplAttribute (MethodImplOptions.InternalCall)]
255 private static extern AppDomain getCurDomain ();
257 public static AppDomain CurrentDomain {
259 return getCurDomain ();
263 [MethodImplAttribute (MethodImplOptions.InternalCall)]
264 private static extern AppDomain getRootDomain ();
266 internal static AppDomain DefaultDomain {
268 if (default_domain == null) {
269 AppDomain rd = getRootDomain ();
270 if (rd == CurrentDomain)
273 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
275 return default_domain;
279 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
280 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
281 public void AppendPrivatePath (string path)
283 if (path == null || path.Length == 0)
286 AppDomainSetup setup = SetupInformationNoCopy;
288 string pp = setup.PrivateBinPath;
289 if (pp == null || pp.Length == 0) {
290 setup.PrivateBinPath = path;
295 if (pp [pp.Length - 1] != Path.PathSeparator)
296 pp += Path.PathSeparator;
298 setup.PrivateBinPath = pp + path;
301 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
302 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
303 public void ClearPrivatePath ()
305 SetupInformationNoCopy.PrivateBinPath = String.Empty;
308 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
309 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
310 public void ClearShadowCopyPath ()
312 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
316 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
318 return Activator.CreateComInstanceFrom (assemblyName, typeName);
321 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
322 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
324 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
328 public ObjectHandle CreateInstance (string assemblyName, string typeName)
330 if (assemblyName == null)
331 throw new ArgumentNullException ("assemblyName");
333 return Activator.CreateInstance (assemblyName, typeName);
336 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
338 if (assemblyName == null)
339 throw new ArgumentNullException ("assemblyName");
341 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
345 [Obsolete ("Use an overload that does not take an Evidence parameter")]
347 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
348 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
349 Evidence securityAttributes)
351 if (assemblyName == null)
352 throw new ArgumentNullException ("assemblyName");
354 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
355 culture, activationAttributes, securityAttributes);
358 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
360 ObjectHandle oh = CreateInstance (assemblyName, typeName);
361 return (oh != null) ? oh.Unwrap () : null;
364 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
366 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
367 return (oh != null) ? oh.Unwrap () : null;
371 [Obsolete ("Use an overload that does not take an Evidence parameter")]
373 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
374 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
375 object[] activationAttributes, Evidence securityAttributes)
377 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
378 culture, activationAttributes, securityAttributes);
379 return (oh != null) ? oh.Unwrap () : null;
383 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
384 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
386 if (assemblyName == null)
387 throw new ArgumentNullException ("assemblyName");
389 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
390 culture, activationAttributes, null);
392 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
393 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
394 object[] activationAttributes)
396 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
397 culture, activationAttributes);
398 return (oh != null) ? oh.Unwrap () : null;
401 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
402 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
403 object[] activationAttributes)
405 if (assemblyFile == null)
406 throw new ArgumentNullException ("assemblyFile");
408 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
409 culture, activationAttributes, null);
412 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
413 BindingFlags bindingAttr, Binder binder, object[] args,
414 CultureInfo culture, object[] activationAttributes)
416 ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
417 culture, activationAttributes);
419 return (oh != null) ? oh.Unwrap () : null;
423 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
425 if (assemblyFile == null)
426 throw new ArgumentNullException ("assemblyFile");
428 return Activator.CreateInstanceFrom (assemblyFile, typeName);
431 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
433 if (assemblyFile == null)
434 throw new ArgumentNullException ("assemblyFile");
436 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
440 [Obsolete ("Use an overload that does not take an Evidence parameter")]
442 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
443 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
444 object[] activationAttributes, Evidence securityAttributes)
446 if (assemblyFile == null)
447 throw new ArgumentNullException ("assemblyFile");
449 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
450 culture, activationAttributes, securityAttributes);
453 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
455 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
456 return (oh != null) ? oh.Unwrap () : null;
459 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
461 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
462 return (oh != null) ? oh.Unwrap () : null;
466 [Obsolete ("Use an overload that does not take an Evidence parameter")]
468 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
469 BindingFlags bindingAttr, Binder binder, object[] args,
470 CultureInfo culture, object[] activationAttributes,
471 Evidence securityAttributes)
473 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
474 culture, activationAttributes, securityAttributes);
476 return (oh != null) ? oh.Unwrap () : null;
479 #if !FULL_AOT_RUNTIME
480 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
482 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
486 [Obsolete ("Declarative security for assembly level is no longer enforced")]
488 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
490 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
493 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
495 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
499 [Obsolete ("Declarative security for assembly level is no longer enforced")]
501 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
504 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
508 [Obsolete ("Declarative security for assembly level is no longer enforced")]
510 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
511 PermissionSet requiredPermissions,
512 PermissionSet optionalPermissions,
513 PermissionSet refusedPermissions)
515 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
516 refusedPermissions, false);
520 [Obsolete ("Declarative security for assembly level is no longer enforced")]
522 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
523 PermissionSet requiredPermissions,
524 PermissionSet optionalPermissions,
525 PermissionSet refusedPermissions)
527 return DefineDynamicAssembly (name, access, null, 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,
535 PermissionSet requiredPermissions,
536 PermissionSet optionalPermissions,
537 PermissionSet refusedPermissions)
539 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
540 refusedPermissions, false);
544 [Obsolete ("Declarative security for assembly level is no longer enforced")]
546 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
548 PermissionSet requiredPermissions,
549 PermissionSet optionalPermissions,
550 PermissionSet refusedPermissions)
552 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
553 refusedPermissions, false);
557 [Obsolete ("Declarative security for assembly level is no longer enforced")]
559 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
561 PermissionSet requiredPermissions,
562 PermissionSet optionalPermissions,
563 PermissionSet refusedPermissions, bool isSynchronized)
566 throw new ArgumentNullException ("name");
567 ValidateAssemblyName (name.Name);
569 // FIXME: examine all other parameters
571 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
572 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
578 [Obsolete ("Declarative security for assembly level is no longer enforced")]
580 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
582 PermissionSet requiredPermissions,
583 PermissionSet optionalPermissions,
584 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
586 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
587 if (assemblyAttributes != null)
588 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
589 ab.SetCustomAttribute (cb);
595 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
597 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
601 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
603 return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
606 [MonoLimitation ("The argument securityContextSource is ignored")]
607 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
609 return DefineDynamicAssembly (name, access, assemblyAttributes);
613 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
615 return new AssemblyBuilder (name, null, access, true);
620 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
621 // so, when you call AppDomain.DoCallBack, that's a remote call
623 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
625 if (callBackDelegate != null)
629 public int ExecuteAssembly (string assemblyFile)
631 return ExecuteAssembly (assemblyFile, (Evidence)null, null);
635 [Obsolete ("Use an overload that does not take an Evidence parameter")]
637 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
639 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
643 [Obsolete ("Use an overload that does not take an Evidence parameter")]
645 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
647 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
648 return ExecuteAssemblyInternal (a, args);
652 [Obsolete ("Use an overload that does not take an Evidence parameter")]
654 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
656 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
657 return ExecuteAssemblyInternal (a, args);
662 public int ExecuteAssembly (string assemblyFile, string[] args)
664 Assembly a = Assembly.LoadFrom (assemblyFile, null);
665 return ExecuteAssemblyInternal (a, args);
668 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
670 Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
671 return ExecuteAssemblyInternal (a, args);
675 int ExecuteAssemblyInternal (Assembly a, string[] args)
677 if (a.EntryPoint == null)
678 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
679 return ExecuteAssembly (a, args);
682 [MethodImplAttribute (MethodImplOptions.InternalCall)]
683 private extern int ExecuteAssembly (Assembly a, string[] args);
685 [MethodImplAttribute (MethodImplOptions.InternalCall)]
686 private extern Assembly [] GetAssemblies (bool refOnly);
688 public Assembly [] GetAssemblies ()
690 return GetAssemblies (false);
693 [MethodImplAttribute (MethodImplOptions.InternalCall)]
694 public extern object GetData (string name);
696 public new Type GetType()
698 return base.GetType ();
701 public override object InitializeLifetimeService ()
706 [MethodImplAttribute (MethodImplOptions.InternalCall)]
707 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
709 public Assembly Load (AssemblyName assemblyRef)
711 return Load (assemblyRef, null);
714 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
716 if (assemblyRef == null)
717 throw new ArgumentNullException ("assemblyRef");
719 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
720 if (result == null && throwOnError)
721 throw new FileNotFoundException (null, assemblyRef.Name);
726 [Obsolete ("Use an overload that does not take an Evidence parameter")]
728 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
730 if (assemblyRef == null)
731 throw new ArgumentNullException ("assemblyRef");
733 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
734 if (assemblyRef.CodeBase != null)
735 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
737 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
740 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
741 if (assembly != null)
744 if (assemblyRef.CodeBase == null)
745 throw new FileNotFoundException (null, assemblyRef.Name);
747 string cb = assemblyRef.CodeBase;
748 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
749 cb = new Mono.Security.Uri (cb).LocalPath;
752 assembly = Assembly.LoadFrom (cb, assemblySecurity);
754 throw new FileNotFoundException (null, assemblyRef.Name);
756 AssemblyName aname = assembly.GetName ();
757 // Name, version, culture, publickeytoken. Anything else?
758 if (assemblyRef.Name != aname.Name)
759 throw new FileNotFoundException (null, assemblyRef.Name);
761 if (assemblyRef.Version != null && assemblyRef.Version != new Version (0, 0, 0, 0) && assemblyRef.Version != aname.Version)
762 throw new FileNotFoundException (null, assemblyRef.Name);
764 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
765 throw new FileNotFoundException (null, assemblyRef.Name);
767 byte [] pt = assemblyRef.GetPublicKeyToken ();
768 if (pt != null && pt.Length != 0) {
769 byte [] loaded_pt = aname.GetPublicKeyToken ();
770 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
771 throw new FileNotFoundException (null, assemblyRef.Name);
772 for (int i = pt.Length - 1; i >= 0; i--)
773 if (loaded_pt [i] != pt [i])
774 throw new FileNotFoundException (null, assemblyRef.Name);
779 public Assembly Load (string assemblyString)
781 return Load (assemblyString, null, false);
785 [Obsolete ("Use an overload that does not take an Evidence parameter")]
787 public Assembly Load (string assemblyString, Evidence assemblySecurity)
789 return Load (assemblyString, assemblySecurity, false);
792 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
794 if (assemblyString == null)
795 throw new ArgumentNullException ("assemblyString");
797 if (assemblyString.Length == 0)
798 throw new ArgumentException ("assemblyString cannot have zero length");
800 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
801 if (assembly == null)
802 throw new FileNotFoundException (null, assemblyString);
806 public Assembly Load (byte[] rawAssembly)
808 return Load (rawAssembly, null, null);
811 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
813 return Load (rawAssembly, rawSymbolStore, null);
816 [MethodImplAttribute (MethodImplOptions.InternalCall)]
817 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
820 [Obsolete ("Use an overload that does not take an Evidence parameter")]
822 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
824 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
827 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
829 if (rawAssembly == null)
830 throw new ArgumentNullException ("rawAssembly");
832 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
833 assembly.FromByteArray = true;
837 [Obsolete ("AppDomain policy levels are obsolete")]
839 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
840 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
842 if (domainPolicy == null)
843 throw new ArgumentNullException ("domainPolicy");
844 if (_granted != null) {
845 throw new PolicyException (Locale.GetText (
846 "An AppDomain policy is already specified."));
848 if (IsFinalizingForUnload ())
849 throw new AppDomainUnloadedException ();
851 PolicyStatement ps = domainPolicy.Resolve ((Evidence)_evidence);
852 _granted = ps.PermissionSet;
855 [Obsolete ("Use AppDomainSetup.SetCachePath")]
856 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
857 public void SetCachePath (string path)
859 SetupInformationNoCopy.CachePath = path;
862 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
863 public void SetPrincipalPolicy (PrincipalPolicy policy)
865 if (IsFinalizingForUnload ())
866 throw new AppDomainUnloadedException ();
869 _principalPolicy = (int)policy;
871 _principalPolicy = policy;
876 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
877 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
878 public void SetShadowCopyFiles()
880 SetupInformationNoCopy.ShadowCopyFiles = "true";
883 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
884 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
885 public void SetShadowCopyPath (string path)
887 SetupInformationNoCopy.ShadowCopyDirectories = path;
890 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
891 public void SetThreadPrincipal (IPrincipal principal)
893 if (principal == null)
894 throw new ArgumentNullException ("principal");
895 if (_principal != null)
896 throw new PolicyException (Locale.GetText ("principal already present."));
897 if (IsFinalizingForUnload ())
898 throw new AppDomainUnloadedException ();
900 _principal = principal;
903 [MethodImplAttribute (MethodImplOptions.InternalCall)]
904 private static extern AppDomain InternalSetDomainByID (int domain_id);
906 // Changes the active domain and returns the old domain
907 [MethodImplAttribute (MethodImplOptions.InternalCall)]
908 private static extern AppDomain InternalSetDomain (AppDomain context);
910 // Notifies the runtime that this thread references 'domain'.
911 [MethodImplAttribute (MethodImplOptions.InternalCall)]
912 internal static extern void InternalPushDomainRef (AppDomain domain);
914 [MethodImplAttribute (MethodImplOptions.InternalCall)]
915 internal static extern void InternalPushDomainRefByID (int domain_id);
917 // Undoes the effect of the last PushDomainRef call
918 [MethodImplAttribute (MethodImplOptions.InternalCall)]
919 internal static extern void InternalPopDomainRef ();
921 // Changes the active context and returns the old context
922 [MethodImplAttribute (MethodImplOptions.InternalCall)]
923 internal static extern Context InternalSetContext (Context context);
925 // Returns the current context
926 [MethodImplAttribute (MethodImplOptions.InternalCall)]
927 internal static extern Context InternalGetContext ();
929 // Returns the current context
930 [MethodImplAttribute (MethodImplOptions.InternalCall)]
931 internal static extern Context InternalGetDefaultContext ();
933 [MethodImplAttribute (MethodImplOptions.InternalCall)]
934 internal static extern string InternalGetProcessGuid (string newguid);
936 // This method is handled specially by the runtime
937 // It is the only managed method which is allowed to set the current
939 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
941 AppDomain current = CurrentDomain;
946 InternalPushDomainRef (domain);
948 InternalSetDomain (domain);
949 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
955 InternalSetDomain (current);
957 InternalPopDomainRef ();
961 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
963 AppDomain current = CurrentDomain;
968 InternalPushDomainRefByID (domain_id);
970 InternalSetDomainByID (domain_id);
971 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
977 InternalSetDomain (current);
979 InternalPopDomainRef ();
983 internal static String GetProcessGuid ()
985 if (_process_guid == null) {
986 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
988 return _process_guid;
991 public static AppDomain CreateDomain (string friendlyName)
993 return CreateDomain (friendlyName, null, null);
996 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
998 return CreateDomain (friendlyName, securityInfo, null);
1001 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1002 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
1004 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
1005 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1006 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
1008 if (friendlyName == null)
1009 throw new System.ArgumentNullException ("friendlyName");
1011 AppDomain def = AppDomain.DefaultDomain;
1013 // if null, get default domain's SetupInformation
1015 info = new AppDomainSetup (); // we're default!
1017 info = def.SetupInformation;
1020 info = new AppDomainSetup (info); // copy
1022 // todo: allow setup in the other domain
1024 if (!info.Equals (def.SetupInformation)) {
1025 // If not specified use default domain's app base.
1026 if (info.ApplicationBase == null)
1027 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1028 if (info.ConfigurationFile == null)
1029 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1031 } else if (info.ConfigurationFile == null)
1032 info.ConfigurationFile = "[I don't have a config file]";
1035 if (info.AppDomainInitializer != null) {
1036 if (!info.AppDomainInitializer.Method.IsStatic)
1037 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1041 info.SerializeNonPrimitives ();
1043 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1044 if (securityInfo == null) {
1045 // get default domain's Evidence (unless we're are the default!)
1047 ad._evidence = null; // we'll get them later (GetEntryAssembly)
1049 ad._evidence = def.Evidence; // new (shallow) copy
1052 ad._evidence = new Evidence (securityInfo); // copy
1055 if (info.AppDomainInitializer != null) {
1056 Loader loader = new Loader (
1057 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1058 ad.DoCallBack (loader.Load);
1060 Initializer initializer = new Initializer (
1061 info.AppDomainInitializer,
1062 info.AppDomainInitializerArguments);
1063 ad.DoCallBack (initializer.Initialize);
1076 public Loader (string assembly)
1078 this.assembly = assembly;
1083 Assembly.LoadFrom (assembly);
1090 AppDomainInitializer initializer;
1091 string [] arguments;
1093 public Initializer (AppDomainInitializer initializer, string [] arguments)
1095 this.initializer = initializer;
1096 this.arguments = arguments;
1099 public void Initialize ()
1101 initializer (arguments);
1106 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1107 string appRelativeSearchPath, bool shadowCopyFiles)
1109 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1113 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1114 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1117 throw new ArgumentNullException ("info");
1119 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? EmptyArray<StrongName>.Value);
1120 return CreateDomain (friendlyName, securityInfo, info);
1124 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1126 AppDomainSetup info = new AppDomainSetup ();
1128 info.ApplicationBase = appBasePath;
1129 info.PrivateBinPath = appRelativeSearchPath;
1131 if (shadowCopyFiles)
1132 info.ShadowCopyFiles = "true";
1134 info.ShadowCopyFiles = "false";
1139 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1140 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1142 public bool IsFinalizingForUnload()
1144 return InternalIsFinalizingForUnload (getDomainID ());
1147 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1148 static extern void InternalUnload (int domain_id);
1150 // We do this because if the domain is a transparant proxy this
1151 // will still return the correct domain id.
1152 private int getDomainID ()
1154 return Thread.GetDomainID ();
1157 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1158 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1159 public static void Unload (AppDomain domain)
1162 throw new ArgumentNullException ("domain");
1164 InternalUnload (domain.getDomainID());
1167 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1168 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1169 public extern void SetData (string name, object data);
1171 [MonoLimitation ("The permission field is ignored")]
1172 public void SetData (string name, object data, IPermission permission)
1174 SetData (name, data);
1178 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1179 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1180 public void SetDynamicBase (string path)
1182 SetupInformationNoCopy.DynamicBase = path;
1186 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1187 + " because it does not provide a stable Id when managed"
1188 + " threads are running on fibers (aka lightweight"
1189 + " threads). To get a stable identifier for a managed"
1190 + " thread, use the ManagedThreadId property on Thread.'")]
1191 public static int GetCurrentThreadId ()
1193 return Thread.CurrentThreadId;
1196 public override string ToString ()
1198 return getFriendlyName ();
1201 private static void ValidateAssemblyName (string name)
1203 if (name == null || name.Length == 0)
1204 throw new ArgumentException ("The Name of " +
1205 "AssemblyName cannot be null or a " +
1206 "zero-length string.");
1208 bool isValid = true;
1210 for (int i = 0; i < name.Length; i++) {
1213 // do not allow leading whitespace
1214 if (i == 0 && char.IsWhiteSpace (c)) {
1219 // do not allow /,\ or : in name
1220 if (c == '/' || c == '\\' || c == ':') {
1227 throw new ArgumentException ("The Name of " +
1228 "AssemblyName cannot start with " +
1229 "whitespace, or contain '/', '\\' " +
1233 // The following methods are called from the runtime. Don't change signatures.
1234 #pragma warning disable 169
1235 private void DoAssemblyLoad (Assembly assembly)
1237 if (AssemblyLoad == null)
1240 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1243 private Assembly DoAssemblyResolve (string name, bool refonly)
1245 ResolveEventHandler del;
1248 del = ReflectionOnlyAssemblyResolve;
1250 del = AssemblyResolve;
1252 del = AssemblyResolve;
1257 /* Prevent infinite recursion */
1258 Dictionary<string, object> ht;
1260 ht = assembly_resolve_in_progress_refonly;
1262 ht = new Dictionary<string, object> ();
1263 assembly_resolve_in_progress_refonly = ht;
1266 ht = assembly_resolve_in_progress;
1268 ht = new Dictionary<string, object> ();
1269 assembly_resolve_in_progress = ht;
1273 if (ht.ContainsKey (name))
1278 Delegate[] invocation_list = del.GetInvocationList ();
1280 foreach (Delegate eh in invocation_list) {
1281 ResolveEventHandler handler = (ResolveEventHandler) eh;
1282 Assembly assembly = handler (this, new ResolveEventArgs (name));
1283 if (assembly != null)
1293 internal Assembly DoTypeResolve (Object name_or_tb)
1295 if (TypeResolve == null)
1300 #if !FULL_AOT_RUNTIME
1301 if (name_or_tb is TypeBuilder)
1302 name = ((TypeBuilder) name_or_tb).FullName;
1305 name = (string) name_or_tb;
1307 /* Prevent infinite recursion */
1308 var ht = type_resolve_in_progress;
1310 type_resolve_in_progress = ht = new Dictionary<string, object> ();
1313 if (ht.ContainsKey (name))
1319 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1320 ResolveEventHandler eh = (ResolveEventHandler) d;
1321 Assembly assembly = eh (this, new ResolveEventArgs (name));
1322 if (assembly != null)
1332 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1333 if (ResourceResolve == null)
1336 Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1338 foreach (Delegate eh in invocation_list) {
1339 ResolveEventHandler handler = (ResolveEventHandler) eh;
1341 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1343 Assembly assembly = handler (this, new ResolveEventArgs (name));
1345 if (assembly != null)
1351 private void DoDomainUnload ()
1353 if (DomainUnload != null)
1354 DomainUnload(this, null);
1357 internal byte[] GetMarshalledDomainObjRef ()
1359 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1360 return CADSerializer.SerializeObject (oref).GetBuffer();
1363 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1364 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1368 if (null != arrRequest)
1369 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1371 reqDomMsg = new MethodCall (cadMsg);
1373 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1375 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1376 if (null == cadMrm) {
1377 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1383 #pragma warning restore 169
1385 // End of methods called from the runtime
1387 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1388 public event AssemblyLoadEventHandler AssemblyLoad;
1390 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1391 public event ResolveEventHandler AssemblyResolve;
1393 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1394 public event EventHandler DomainUnload;
1396 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1397 public event EventHandler ProcessExit;
1399 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1400 public event ResolveEventHandler ResourceResolve;
1402 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1403 public event ResolveEventHandler TypeResolve;
1405 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1406 public event UnhandledExceptionEventHandler UnhandledException;
1410 public bool IsHomogenous {
1411 get { return true; }
1415 public bool IsFullyTrusted {
1416 get { return true; }
1420 #pragma warning disable 649
1422 private AppDomainManager _domain_manager;
1424 object _domain_manager;
1426 #pragma warning restore 649
1429 public AppDomainManager DomainManager {
1430 get { return (AppDomainManager)_domain_manager; }
1434 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1437 #pragma warning disable 649
1439 private object _activation;
1440 private object _applicationIdentity;
1442 private ActivationContext _activation;
1443 private ApplicationIdentity _applicationIdentity;
1445 #pragma warning restore 649
1449 public ActivationContext ActivationContext {
1450 get { return (ActivationContext)_activation; }
1453 public ApplicationIdentity ApplicationIdentity {
1454 get { return (ApplicationIdentity)_applicationIdentity; }
1458 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1459 get { return getDomainID (); }
1464 [MonoTODO ("This routine only returns the parameter currently")]
1465 [ComVisible (false)]
1466 public string ApplyPolicy (string assemblyName)
1468 if (assemblyName == null)
1469 throw new ArgumentNullException ("assemblyName");
1470 if (assemblyName.Length == 0) // String.Empty
1471 throw new ArgumentException ("assemblyName");
1472 return assemblyName;
1477 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1478 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1480 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1482 info.AppDomainInitializerArguments = adInitArgs;
1483 info.AppDomainInitializer = adInit;
1485 return CreateDomain (friendlyName, securityInfo, info);
1488 public int ExecuteAssemblyByName (string assemblyName)
1490 return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1494 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1496 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1498 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1502 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1504 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1506 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1508 return ExecuteAssemblyInternal (a, args);
1512 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1514 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1516 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1518 return ExecuteAssemblyInternal (a, args);
1522 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1524 Assembly a = Assembly.Load (assemblyName, null);
1526 return ExecuteAssemblyInternal (a, args);
1529 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1531 Assembly a = Assembly.Load (assemblyName, null);
1533 return ExecuteAssemblyInternal (a, args);
1537 public bool IsDefaultAppDomain ()
1539 return Object.ReferenceEquals (this, DefaultDomain);
1542 public Assembly[] ReflectionOnlyGetAssemblies ()
1544 return GetAssemblies (true);
1548 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1550 throw new NotImplementedException ();
1553 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1555 throw new NotImplementedException ();
1558 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1560 throw new NotImplementedException ();
1563 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1564 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1566 throw new NotImplementedException ();
1571 List<string> compatibility_switch;
1573 public bool? IsCompatibilitySwitchSet (string value)
1576 throw new ArgumentNullException ("value");
1578 // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1579 return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1582 internal void SetCompatibilitySwitch (string value)
1584 if (compatibility_switch == null)
1585 compatibility_switch = new List<string> ();
1586 compatibility_switch.Add (value);
1589 [MonoTODO ("Currently always returns false")]
1590 public static bool MonitoringIsEnabled {
1591 get { return false; }
1592 set { throw new NotImplementedException (); }
1596 public long MonitoringSurvivedMemorySize {
1597 get { throw new NotImplementedException (); }
1601 public static long MonitoringSurvivedProcessMemorySize {
1602 get { throw new NotImplementedException (); }
1606 public long MonitoringTotalAllocatedMemorySize {
1607 get { throw new NotImplementedException (); }
1611 public TimeSpan MonitoringTotalProcessorTime {
1612 get { throw new NotImplementedException (); }