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, _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 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;
88 private Evidence _evidence;
89 private PermissionSet _granted;
92 private PrincipalPolicy _principalPolicy;
95 private static IPrincipal _principal;
97 static AppDomain default_domain;
103 [MethodImplAttribute (MethodImplOptions.InternalCall)]
104 private extern AppDomainSetup getSetup ();
109 AppDomainSetup SetupInformationNoCopy {
110 get { return getSetup (); }
113 public AppDomainSetup SetupInformation {
115 AppDomainSetup setup = getSetup ();
116 return new AppDomainSetup (setup);
122 public ApplicationTrust ApplicationTrust {
123 get { throw new NotImplementedException (); }
126 public string BaseDirectory {
128 string path = SetupInformationNoCopy.ApplicationBase;
130 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
131 // we cannot divulge local file informations
132 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
139 public string RelativeSearchPath {
141 string path = SetupInformationNoCopy.PrivateBinPath;
143 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
144 // we cannot divulge local file informations
145 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
152 public string DynamicDirectory {
154 AppDomainSetup setup = SetupInformationNoCopy;
155 if (setup.DynamicBase == null)
158 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
160 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
161 // we cannot divulge local file informations
162 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
169 public bool ShadowCopyFiles {
171 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
175 [MethodImplAttribute (MethodImplOptions.InternalCall)]
176 private extern string getFriendlyName ();
178 public string FriendlyName {
180 return getFriendlyName ();
184 public Evidence Evidence {
186 // if the host (runtime) hasn't provided it's own evidence...
187 if (_evidence == null) {
188 // ... we will provide our own
190 // the executed assembly from the "default" appdomain
191 // or null if we're not in the default appdomain or
192 // if there is no entry assembly (embedded mono)
193 Assembly a = Assembly.GetEntryAssembly ();
195 if (this == DefaultDomain)
197 return new Evidence ();
199 _evidence = AppDomain.DefaultDomain.Evidence;
201 _evidence = Evidence.GetDefaultHostEvidence (a);
205 return new Evidence (_evidence); // return a copy
209 internal IPrincipal DefaultPrincipal {
211 if (_principal == null) {
212 switch (_principalPolicy) {
213 case PrincipalPolicy.UnauthenticatedPrincipal:
214 _principal = new GenericPrincipal (
215 new GenericIdentity (String.Empty, String.Empty), null);
217 case PrincipalPolicy.WindowsPrincipal:
218 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
226 // for AppDomain there is only an allowed (i.e. granted) set
227 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
228 internal PermissionSet GrantedPermissionSet {
229 get { return _granted; }
233 public PermissionSet PermissionSet {
234 get { return _granted ?? (_granted = new PermissionSet (PermissionState.Unrestricted)); }
238 [MethodImplAttribute (MethodImplOptions.InternalCall)]
239 private static extern AppDomain getCurDomain ();
241 public static AppDomain CurrentDomain {
243 return getCurDomain ();
247 [MethodImplAttribute (MethodImplOptions.InternalCall)]
248 private static extern AppDomain getRootDomain ();
250 internal static AppDomain DefaultDomain {
252 if (default_domain == null) {
253 AppDomain rd = getRootDomain ();
254 if (rd == CurrentDomain)
257 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
259 return default_domain;
263 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
264 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
265 public void AppendPrivatePath (string path)
267 if (path == null || path.Length == 0)
270 AppDomainSetup setup = SetupInformationNoCopy;
272 string pp = setup.PrivateBinPath;
273 if (pp == null || pp.Length == 0) {
274 setup.PrivateBinPath = path;
279 if (pp [pp.Length - 1] != Path.PathSeparator)
280 pp += Path.PathSeparator;
282 setup.PrivateBinPath = pp + path;
285 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
286 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
287 public void ClearPrivatePath ()
289 SetupInformationNoCopy.PrivateBinPath = String.Empty;
292 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
293 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
294 public void ClearShadowCopyPath ()
296 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
300 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
302 return Activator.CreateComInstanceFrom (assemblyName, typeName);
305 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
306 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
308 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
312 public ObjectHandle CreateInstance (string assemblyName, string typeName)
314 if (assemblyName == null)
315 throw new ArgumentNullException ("assemblyName");
317 return Activator.CreateInstance (assemblyName, typeName);
320 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
322 if (assemblyName == null)
323 throw new ArgumentNullException ("assemblyName");
325 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
329 [Obsolete ("Use an overload that does not take an Evidence parameter")]
331 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
332 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
333 Evidence securityAttributes)
335 if (assemblyName == null)
336 throw new ArgumentNullException ("assemblyName");
338 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
339 culture, activationAttributes, securityAttributes);
342 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
344 ObjectHandle oh = CreateInstance (assemblyName, typeName);
345 return (oh != null) ? oh.Unwrap () : null;
348 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
350 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
351 return (oh != null) ? oh.Unwrap () : null;
355 [Obsolete ("Use an overload that does not take an Evidence parameter")]
357 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
358 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
359 object[] activationAttributes, Evidence securityAttributes)
361 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
362 culture, activationAttributes, securityAttributes);
363 return (oh != null) ? oh.Unwrap () : null;
367 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
368 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
370 if (assemblyName == null)
371 throw new ArgumentNullException ("assemblyName");
373 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
374 culture, activationAttributes, null);
376 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
377 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
378 object[] activationAttributes)
380 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
381 culture, activationAttributes);
382 return (oh != null) ? oh.Unwrap () : null;
385 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
386 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
387 object[] activationAttributes)
389 if (assemblyFile == null)
390 throw new ArgumentNullException ("assemblyFile");
392 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
393 culture, activationAttributes, null);
396 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
397 BindingFlags bindingAttr, Binder binder, object[] args,
398 CultureInfo culture, object[] activationAttributes)
400 ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
401 culture, activationAttributes);
403 return (oh != null) ? oh.Unwrap () : null;
407 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
409 if (assemblyFile == null)
410 throw new ArgumentNullException ("assemblyFile");
412 return Activator.CreateInstanceFrom (assemblyFile, typeName);
415 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
417 if (assemblyFile == null)
418 throw new ArgumentNullException ("assemblyFile");
420 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
424 [Obsolete ("Use an overload that does not take an Evidence parameter")]
426 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
427 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
428 object[] activationAttributes, Evidence securityAttributes)
430 if (assemblyFile == null)
431 throw new ArgumentNullException ("assemblyFile");
433 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
434 culture, activationAttributes, securityAttributes);
437 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
439 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
440 return (oh != null) ? oh.Unwrap () : null;
443 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
445 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
446 return (oh != null) ? oh.Unwrap () : null;
450 [Obsolete ("Use an overload that does not take an Evidence parameter")]
452 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
453 BindingFlags bindingAttr, Binder binder, object[] args,
454 CultureInfo culture, object[] activationAttributes,
455 Evidence securityAttributes)
457 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
458 culture, activationAttributes, securityAttributes);
460 return (oh != null) ? oh.Unwrap () : null;
463 #if !FULL_AOT_RUNTIME
464 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
466 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
470 [Obsolete ("Declarative security for assembly level is no longer enforced")]
472 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
474 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
477 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
479 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
483 [Obsolete ("Declarative security for assembly level is no longer enforced")]
485 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
488 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
492 [Obsolete ("Declarative security for assembly level is no longer enforced")]
494 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
495 PermissionSet requiredPermissions,
496 PermissionSet optionalPermissions,
497 PermissionSet refusedPermissions)
499 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
500 refusedPermissions, false);
504 [Obsolete ("Declarative security for assembly level is no longer enforced")]
506 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
507 PermissionSet requiredPermissions,
508 PermissionSet optionalPermissions,
509 PermissionSet refusedPermissions)
511 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
512 refusedPermissions, false);
516 [Obsolete ("Declarative security for assembly level is no longer enforced")]
518 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
519 PermissionSet requiredPermissions,
520 PermissionSet optionalPermissions,
521 PermissionSet refusedPermissions)
523 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
524 refusedPermissions, false);
528 [Obsolete ("Declarative security for assembly level is no longer enforced")]
530 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
532 PermissionSet requiredPermissions,
533 PermissionSet optionalPermissions,
534 PermissionSet refusedPermissions)
536 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
537 refusedPermissions, false);
541 [Obsolete ("Declarative security for assembly level is no longer enforced")]
543 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
545 PermissionSet requiredPermissions,
546 PermissionSet optionalPermissions,
547 PermissionSet refusedPermissions, bool isSynchronized)
550 throw new ArgumentNullException ("name");
551 ValidateAssemblyName (name.Name);
553 // FIXME: examine all other parameters
555 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
556 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
562 [Obsolete ("Declarative security for assembly level is no longer enforced")]
564 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
566 PermissionSet requiredPermissions,
567 PermissionSet optionalPermissions,
568 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
570 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
571 if (assemblyAttributes != null)
572 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
573 ab.SetCustomAttribute (cb);
579 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
581 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
585 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
587 return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
590 [MonoLimitation ("The argument securityContextSource is ignored")]
591 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
593 return DefineDynamicAssembly (name, access, assemblyAttributes);
597 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
599 return new AssemblyBuilder (name, null, access, true);
604 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
605 // so, when you call AppDomain.DoCallBack, that's a remote call
607 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
609 if (callBackDelegate != null)
613 public int ExecuteAssembly (string assemblyFile)
615 return ExecuteAssembly (assemblyFile, (Evidence)null, null);
619 [Obsolete ("Use an overload that does not take an Evidence parameter")]
621 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
623 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
627 [Obsolete ("Use an overload that does not take an Evidence parameter")]
629 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
631 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
632 return ExecuteAssemblyInternal (a, args);
636 [Obsolete ("Use an overload that does not take an Evidence parameter")]
638 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
640 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
641 return ExecuteAssemblyInternal (a, args);
646 public int ExecuteAssembly (string assemblyFile, string[] args)
648 Assembly a = Assembly.LoadFrom (assemblyFile, null);
649 return ExecuteAssemblyInternal (a, args);
652 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
654 Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
655 return ExecuteAssemblyInternal (a, args);
659 int ExecuteAssemblyInternal (Assembly a, string[] args)
661 if (a.EntryPoint == null)
662 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
663 return ExecuteAssembly (a, args);
666 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667 private extern int ExecuteAssembly (Assembly a, string[] args);
669 [MethodImplAttribute (MethodImplOptions.InternalCall)]
670 private extern Assembly [] GetAssemblies (bool refOnly);
672 public Assembly [] GetAssemblies ()
674 return GetAssemblies (false);
677 [MethodImplAttribute (MethodImplOptions.InternalCall)]
678 public extern object GetData (string name);
680 public new Type GetType()
682 return base.GetType ();
685 public override object InitializeLifetimeService ()
690 [MethodImplAttribute (MethodImplOptions.InternalCall)]
691 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
693 public Assembly Load (AssemblyName assemblyRef)
695 return Load (assemblyRef, null);
698 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
700 if (assemblyRef == null)
701 throw new ArgumentNullException ("assemblyRef");
703 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
704 if (result == null && throwOnError)
705 throw new FileNotFoundException (null, assemblyRef.Name);
710 [Obsolete ("Use an overload that does not take an Evidence parameter")]
712 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
714 if (assemblyRef == null)
715 throw new ArgumentNullException ("assemblyRef");
717 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
718 if (assemblyRef.CodeBase != null)
719 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
721 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
724 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
725 if (assembly != null)
728 if (assemblyRef.CodeBase == null)
729 throw new FileNotFoundException (null, assemblyRef.Name);
731 string cb = assemblyRef.CodeBase;
732 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
733 cb = new Mono.Security.Uri (cb).LocalPath;
736 assembly = Assembly.LoadFrom (cb, assemblySecurity);
738 throw new FileNotFoundException (null, assemblyRef.Name);
740 AssemblyName aname = assembly.GetName ();
741 // Name, version, culture, publickeytoken. Anything else?
742 if (assemblyRef.Name != aname.Name)
743 throw new FileNotFoundException (null, assemblyRef.Name);
745 if (assemblyRef.Version != null && assemblyRef.Version != new Version (0, 0, 0, 0) && assemblyRef.Version != aname.Version)
746 throw new FileNotFoundException (null, assemblyRef.Name);
748 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
749 throw new FileNotFoundException (null, assemblyRef.Name);
751 byte [] pt = assemblyRef.GetPublicKeyToken ();
752 if (pt != null && pt.Length != 0) {
753 byte [] loaded_pt = aname.GetPublicKeyToken ();
754 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
755 throw new FileNotFoundException (null, assemblyRef.Name);
756 for (int i = pt.Length - 1; i >= 0; i--)
757 if (loaded_pt [i] != pt [i])
758 throw new FileNotFoundException (null, assemblyRef.Name);
763 public Assembly Load (string assemblyString)
765 return Load (assemblyString, null, false);
769 [Obsolete ("Use an overload that does not take an Evidence parameter")]
771 public Assembly Load (string assemblyString, Evidence assemblySecurity)
773 return Load (assemblyString, assemblySecurity, false);
776 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
778 if (assemblyString == null)
779 throw new ArgumentNullException ("assemblyString");
781 if (assemblyString.Length == 0)
782 throw new ArgumentException ("assemblyString cannot have zero length");
784 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
785 if (assembly == null)
786 throw new FileNotFoundException (null, assemblyString);
790 public Assembly Load (byte[] rawAssembly)
792 return Load (rawAssembly, null, null);
795 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
797 return Load (rawAssembly, rawSymbolStore, null);
800 [MethodImplAttribute (MethodImplOptions.InternalCall)]
801 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
804 [Obsolete ("Use an overload that does not take an Evidence parameter")]
806 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
808 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
811 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
813 if (rawAssembly == null)
814 throw new ArgumentNullException ("rawAssembly");
816 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
817 assembly.FromByteArray = true;
821 [Obsolete ("AppDomain policy levels are obsolete")]
823 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
824 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
826 if (domainPolicy == null)
827 throw new ArgumentNullException ("domainPolicy");
828 if (_granted != null) {
829 throw new PolicyException (Locale.GetText (
830 "An AppDomain policy is already specified."));
832 if (IsFinalizingForUnload ())
833 throw new AppDomainUnloadedException ();
835 PolicyStatement ps = domainPolicy.Resolve (_evidence);
836 _granted = ps.PermissionSet;
839 [Obsolete ("Use AppDomainSetup.SetCachePath")]
840 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
841 public void SetCachePath (string path)
843 SetupInformationNoCopy.CachePath = path;
846 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
847 public void SetPrincipalPolicy (PrincipalPolicy policy)
849 if (IsFinalizingForUnload ())
850 throw new AppDomainUnloadedException ();
852 _principalPolicy = policy;
856 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
857 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
858 public void SetShadowCopyFiles()
860 SetupInformationNoCopy.ShadowCopyFiles = "true";
863 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
864 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
865 public void SetShadowCopyPath (string path)
867 SetupInformationNoCopy.ShadowCopyDirectories = path;
870 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
871 public void SetThreadPrincipal (IPrincipal principal)
873 if (principal == null)
874 throw new ArgumentNullException ("principal");
875 if (_principal != null)
876 throw new PolicyException (Locale.GetText ("principal already present."));
877 if (IsFinalizingForUnload ())
878 throw new AppDomainUnloadedException ();
880 _principal = principal;
883 [MethodImplAttribute (MethodImplOptions.InternalCall)]
884 private static extern AppDomain InternalSetDomainByID (int domain_id);
886 // Changes the active domain and returns the old domain
887 [MethodImplAttribute (MethodImplOptions.InternalCall)]
888 private static extern AppDomain InternalSetDomain (AppDomain context);
890 // Notifies the runtime that this thread references 'domain'.
891 [MethodImplAttribute (MethodImplOptions.InternalCall)]
892 internal static extern void InternalPushDomainRef (AppDomain domain);
894 [MethodImplAttribute (MethodImplOptions.InternalCall)]
895 internal static extern void InternalPushDomainRefByID (int domain_id);
897 // Undoes the effect of the last PushDomainRef call
898 [MethodImplAttribute (MethodImplOptions.InternalCall)]
899 internal static extern void InternalPopDomainRef ();
901 // Changes the active context and returns the old context
902 [MethodImplAttribute (MethodImplOptions.InternalCall)]
903 internal static extern Context InternalSetContext (Context context);
905 // Returns the current context
906 [MethodImplAttribute (MethodImplOptions.InternalCall)]
907 internal static extern Context InternalGetContext ();
909 // Returns the current context
910 [MethodImplAttribute (MethodImplOptions.InternalCall)]
911 internal static extern Context InternalGetDefaultContext ();
913 [MethodImplAttribute (MethodImplOptions.InternalCall)]
914 internal static extern string InternalGetProcessGuid (string newguid);
916 // This method is handled specially by the runtime
917 // It is the only managed method which is allowed to set the current
919 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
921 AppDomain current = CurrentDomain;
926 InternalPushDomainRef (domain);
928 InternalSetDomain (domain);
929 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
935 InternalSetDomain (current);
937 InternalPopDomainRef ();
941 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
943 AppDomain current = CurrentDomain;
948 InternalPushDomainRefByID (domain_id);
950 InternalSetDomainByID (domain_id);
951 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
957 InternalSetDomain (current);
959 InternalPopDomainRef ();
963 internal static String GetProcessGuid ()
965 if (_process_guid == null) {
966 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
968 return _process_guid;
971 public static AppDomain CreateDomain (string friendlyName)
973 return CreateDomain (friendlyName, null, null);
976 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
978 return CreateDomain (friendlyName, securityInfo, null);
981 [MethodImplAttribute (MethodImplOptions.InternalCall)]
982 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
984 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
985 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
986 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
988 if (friendlyName == null)
989 throw new System.ArgumentNullException ("friendlyName");
991 AppDomain def = AppDomain.DefaultDomain;
993 // if null, get default domain's SetupInformation
995 info = new AppDomainSetup (); // we're default!
997 info = def.SetupInformation;
1000 info = new AppDomainSetup (info); // copy
1002 // todo: allow setup in the other domain
1004 if (!info.Equals (def.SetupInformation)) {
1005 // If not specified use default domain's app base.
1006 if (info.ApplicationBase == null)
1007 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1008 if (info.ConfigurationFile == null)
1009 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1011 } else if (info.ConfigurationFile == null)
1012 info.ConfigurationFile = "[I don't have a config file]";
1015 if (info.AppDomainInitializer != null) {
1016 if (!info.AppDomainInitializer.Method.IsStatic)
1017 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1021 info.SerializeNonPrimitives ();
1023 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1024 if (securityInfo == null) {
1025 // get default domain's Evidence (unless we're are the default!)
1027 ad._evidence = null; // we'll get them later (GetEntryAssembly)
1029 ad._evidence = def.Evidence; // new (shallow) copy
1032 ad._evidence = new Evidence (securityInfo); // copy
1035 if (info.AppDomainInitializer != null) {
1036 Loader loader = new Loader (
1037 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1038 ad.DoCallBack (loader.Load);
1040 Initializer initializer = new Initializer (
1041 info.AppDomainInitializer,
1042 info.AppDomainInitializerArguments);
1043 ad.DoCallBack (initializer.Initialize);
1056 public Loader (string assembly)
1058 this.assembly = assembly;
1063 Assembly.LoadFrom (assembly);
1070 AppDomainInitializer initializer;
1071 string [] arguments;
1073 public Initializer (AppDomainInitializer initializer, string [] arguments)
1075 this.initializer = initializer;
1076 this.arguments = arguments;
1079 public void Initialize ()
1081 initializer (arguments);
1086 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1087 string appRelativeSearchPath, bool shadowCopyFiles)
1089 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1093 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1094 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1097 throw new ArgumentNullException ("info");
1099 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? EmptyArray<StrongName>.Value);
1100 return CreateDomain (friendlyName, securityInfo, info);
1104 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1106 AppDomainSetup info = new AppDomainSetup ();
1108 info.ApplicationBase = appBasePath;
1109 info.PrivateBinPath = appRelativeSearchPath;
1111 if (shadowCopyFiles)
1112 info.ShadowCopyFiles = "true";
1114 info.ShadowCopyFiles = "false";
1119 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1120 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1122 public bool IsFinalizingForUnload()
1124 return InternalIsFinalizingForUnload (getDomainID ());
1127 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1128 static extern void InternalUnload (int domain_id);
1130 // We do this because if the domain is a transparant proxy this
1131 // will still return the correct domain id.
1132 private int getDomainID ()
1134 return Thread.GetDomainID ();
1137 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1138 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1139 public static void Unload (AppDomain domain)
1142 throw new ArgumentNullException ("domain");
1144 InternalUnload (domain.getDomainID());
1147 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1148 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1149 public extern void SetData (string name, object data);
1151 [MonoLimitation ("The permission field is ignored")]
1152 public void SetData (string name, object data, IPermission permission)
1154 SetData (name, data);
1158 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1159 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1160 public void SetDynamicBase (string path)
1162 SetupInformationNoCopy.DynamicBase = path;
1166 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1167 + " because it does not provide a stable Id when managed"
1168 + " threads are running on fibers (aka lightweight"
1169 + " threads). To get a stable identifier for a managed"
1170 + " thread, use the ManagedThreadId property on Thread.'")]
1171 public static int GetCurrentThreadId ()
1173 return Thread.CurrentThreadId;
1176 public override string ToString ()
1178 return getFriendlyName ();
1181 private static void ValidateAssemblyName (string name)
1183 if (name == null || name.Length == 0)
1184 throw new ArgumentException ("The Name of " +
1185 "AssemblyName cannot be null or a " +
1186 "zero-length string.");
1188 bool isValid = true;
1190 for (int i = 0; i < name.Length; i++) {
1193 // do not allow leading whitespace
1194 if (i == 0 && char.IsWhiteSpace (c)) {
1199 // do not allow /,\ or : in name
1200 if (c == '/' || c == '\\' || c == ':') {
1207 throw new ArgumentException ("The Name of " +
1208 "AssemblyName cannot start with " +
1209 "whitespace, or contain '/', '\\' " +
1213 // The following methods are called from the runtime. Don't change signatures.
1214 #pragma warning disable 169
1215 private void DoAssemblyLoad (Assembly assembly)
1217 if (AssemblyLoad == null)
1220 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1223 private Assembly DoAssemblyResolve (string name, bool refonly)
1225 ResolveEventHandler del;
1228 del = ReflectionOnlyAssemblyResolve;
1230 del = AssemblyResolve;
1232 del = AssemblyResolve;
1237 /* Prevent infinite recursion */
1238 Dictionary<string, object> ht;
1240 ht = assembly_resolve_in_progress_refonly;
1242 ht = new Dictionary<string, object> ();
1243 assembly_resolve_in_progress_refonly = ht;
1246 ht = assembly_resolve_in_progress;
1248 ht = new Dictionary<string, object> ();
1249 assembly_resolve_in_progress = ht;
1253 if (ht.ContainsKey (name))
1258 Delegate[] invocation_list = del.GetInvocationList ();
1260 foreach (Delegate eh in invocation_list) {
1261 ResolveEventHandler handler = (ResolveEventHandler) eh;
1262 Assembly assembly = handler (this, new ResolveEventArgs (name));
1263 if (assembly != null)
1273 internal Assembly DoTypeResolve (Object name_or_tb)
1275 if (TypeResolve == null)
1280 #if !FULL_AOT_RUNTIME
1281 if (name_or_tb is TypeBuilder)
1282 name = ((TypeBuilder) name_or_tb).FullName;
1285 name = (string) name_or_tb;
1287 /* Prevent infinite recursion */
1288 var ht = type_resolve_in_progress;
1290 type_resolve_in_progress = ht = new Dictionary<string, object> ();
1293 if (ht.ContainsKey (name))
1299 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1300 ResolveEventHandler eh = (ResolveEventHandler) d;
1301 Assembly assembly = eh (this, new ResolveEventArgs (name));
1302 if (assembly != null)
1312 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1313 if (ResourceResolve == null)
1316 Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1318 foreach (Delegate eh in invocation_list) {
1319 ResolveEventHandler handler = (ResolveEventHandler) eh;
1321 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1323 Assembly assembly = handler (this, new ResolveEventArgs (name));
1325 if (assembly != null)
1331 private void DoDomainUnload ()
1333 if (DomainUnload != null)
1334 DomainUnload(this, null);
1337 internal byte[] GetMarshalledDomainObjRef ()
1339 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1340 return CADSerializer.SerializeObject (oref).GetBuffer();
1343 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1344 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1348 if (null != arrRequest)
1349 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1351 reqDomMsg = new MethodCall (cadMsg);
1353 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1355 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1356 if (null == cadMrm) {
1357 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1363 #pragma warning restore 169
1365 // End of methods called from the runtime
1367 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1368 public event AssemblyLoadEventHandler AssemblyLoad;
1370 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1371 public event ResolveEventHandler AssemblyResolve;
1373 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1374 public event EventHandler DomainUnload;
1376 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1377 public event EventHandler ProcessExit;
1379 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1380 public event ResolveEventHandler ResourceResolve;
1382 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1383 public event ResolveEventHandler TypeResolve;
1385 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1386 public event UnhandledExceptionEventHandler UnhandledException;
1390 public bool IsHomogenous {
1391 get { return true; }
1395 public bool IsFullyTrusted {
1396 get { return true; }
1400 #pragma warning disable 649
1401 private AppDomainManager _domain_manager;
1402 #pragma warning restore 649
1405 public AppDomainManager DomainManager {
1406 get { return _domain_manager; }
1410 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1413 #pragma warning disable 649
1415 private object _activation;
1416 private object _applicationIdentity;
1418 private ActivationContext _activation;
1419 private ApplicationIdentity _applicationIdentity;
1421 #pragma warning restore 649
1425 public ActivationContext ActivationContext {
1426 get { return (ActivationContext)_activation; }
1429 public ApplicationIdentity ApplicationIdentity {
1430 get { return (ApplicationIdentity)_applicationIdentity; }
1434 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1435 get { return getDomainID (); }
1440 [MonoTODO ("This routine only returns the parameter currently")]
1441 [ComVisible (false)]
1442 public string ApplyPolicy (string assemblyName)
1444 if (assemblyName == null)
1445 throw new ArgumentNullException ("assemblyName");
1446 if (assemblyName.Length == 0) // String.Empty
1447 throw new ArgumentException ("assemblyName");
1448 return assemblyName;
1453 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1454 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1456 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1458 info.AppDomainInitializerArguments = adInitArgs;
1459 info.AppDomainInitializer = adInit;
1461 return CreateDomain (friendlyName, securityInfo, info);
1464 public int ExecuteAssemblyByName (string assemblyName)
1466 return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1470 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1472 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1474 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1478 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1480 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1482 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1484 return ExecuteAssemblyInternal (a, args);
1488 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1490 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1492 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1494 return ExecuteAssemblyInternal (a, args);
1498 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1500 Assembly a = Assembly.Load (assemblyName, null);
1502 return ExecuteAssemblyInternal (a, args);
1505 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1507 Assembly a = Assembly.Load (assemblyName, null);
1509 return ExecuteAssemblyInternal (a, args);
1513 public bool IsDefaultAppDomain ()
1515 return Object.ReferenceEquals (this, DefaultDomain);
1518 public Assembly[] ReflectionOnlyGetAssemblies ()
1520 return GetAssemblies (true);
1524 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1526 throw new NotImplementedException ();
1529 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1531 throw new NotImplementedException ();
1534 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1536 throw new NotImplementedException ();
1539 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1540 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1542 throw new NotImplementedException ();
1547 List<string> compatibility_switch;
1549 public bool? IsCompatibilitySwitchSet (string value)
1552 throw new ArgumentNullException ("value");
1554 // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1555 return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1558 internal void SetCompatibilitySwitch (string value)
1560 if (compatibility_switch == null)
1561 compatibility_switch = new List<string> ();
1562 compatibility_switch.Add (value);
1565 [MonoTODO ("Currently always returns false")]
1566 public static bool MonitoringIsEnabled {
1567 get { return false; }
1568 set { throw new NotImplementedException (); }
1572 public long MonitoringSurvivedMemorySize {
1573 get { throw new NotImplementedException (); }
1577 public static long MonitoringSurvivedProcessMemorySize {
1578 get { throw new NotImplementedException (); }
1582 public long MonitoringTotalAllocatedMemorySize {
1583 get { throw new NotImplementedException (); }
1587 public TimeSpan MonitoringTotalProcessorTime {
1588 get { throw new NotImplementedException (); }