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;
41 using System.Reflection.Emit;
43 using System.Threading;
44 using System.Runtime.CompilerServices;
45 using System.Runtime.InteropServices;
46 using System.Runtime.Remoting;
47 using System.Runtime.Remoting.Contexts;
48 using System.Runtime.Remoting.Channels;
49 using System.Runtime.Remoting.Messaging;
50 using System.Security;
51 using System.Security.Permissions;
52 using System.Security.Policy;
53 using System.Security.Principal;
54 using System.Configuration.Assemblies;
56 using System.Collections.Generic;
57 using System.Runtime.ConstrainedExecution;
64 [ComDefaultInterface (typeof (_AppDomain))]
66 [ClassInterface(ClassInterfaceType.None)]
67 [StructLayout (LayoutKind.Sequential)]
69 public sealed class AppDomain : MarshalByRefObject, _AppDomain {
71 public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory {
73 #pragma warning disable 169
74 #region Sync with object-internals.h
75 IntPtr _mono_app_domain;
77 #pragma warning restore 169
78 static string _process_guid;
81 static Hashtable type_resolve_in_progress;
84 static Hashtable assembly_resolve_in_progress;
87 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 (); }
127 public string BaseDirectory {
129 string path = SetupInformationNoCopy.ApplicationBase;
131 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
132 // we cannot divulge local file informations
133 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
140 public string RelativeSearchPath {
142 string path = SetupInformationNoCopy.PrivateBinPath;
144 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
145 // we cannot divulge local file informations
146 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
153 public string DynamicDirectory {
155 AppDomainSetup setup = SetupInformationNoCopy;
156 if (setup.DynamicBase == null)
159 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
161 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
162 // we cannot divulge local file informations
163 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
170 public bool ShadowCopyFiles {
172 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
176 [MethodImplAttribute (MethodImplOptions.InternalCall)]
177 private extern string getFriendlyName ();
179 public string FriendlyName {
181 return getFriendlyName ();
185 public Evidence Evidence {
187 // if the host (runtime) hasn't provided it's own evidence...
188 if (_evidence == null) {
189 // ... we will provide our own
191 // the executed assembly from the "default" appdomain
192 // or null if we're not in the default appdomain or
193 // if there is no entry assembly (embedded mono)
194 Assembly a = Assembly.GetEntryAssembly ();
196 if (this == DefaultDomain)
198 return new Evidence ();
200 _evidence = AppDomain.DefaultDomain.Evidence;
202 _evidence = Evidence.GetDefaultHostEvidence (a);
206 return new Evidence (_evidence); // return a copy
210 internal IPrincipal DefaultPrincipal {
212 if (_principal == null) {
213 switch (_principalPolicy) {
214 case PrincipalPolicy.UnauthenticatedPrincipal:
215 _principal = new GenericPrincipal (
216 new GenericIdentity (String.Empty, String.Empty), null);
218 case PrincipalPolicy.WindowsPrincipal:
219 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
227 // for AppDomain there is only an allowed (i.e. granted) set
228 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
229 internal PermissionSet GrantedPermissionSet {
230 get { return _granted; }
234 public PermissionSet PermissionSet {
235 get { return _granted ?? (_granted = new PermissionSet (PermissionState.Unrestricted)); }
239 [MethodImplAttribute (MethodImplOptions.InternalCall)]
240 private static extern AppDomain getCurDomain ();
242 public static AppDomain CurrentDomain {
244 return getCurDomain ();
248 [MethodImplAttribute (MethodImplOptions.InternalCall)]
249 private static extern AppDomain getRootDomain ();
251 internal static AppDomain DefaultDomain {
253 if (default_domain == null) {
254 AppDomain rd = getRootDomain ();
255 if (rd == CurrentDomain)
258 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
260 return default_domain;
264 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
265 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
266 public void AppendPrivatePath (string path)
268 if (path == null || path.Length == 0)
271 AppDomainSetup setup = SetupInformationNoCopy;
273 string pp = setup.PrivateBinPath;
274 if (pp == null || pp.Length == 0) {
275 setup.PrivateBinPath = path;
280 if (pp [pp.Length - 1] != Path.PathSeparator)
281 pp += Path.PathSeparator;
283 setup.PrivateBinPath = pp + path;
286 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
287 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
288 public void ClearPrivatePath ()
290 SetupInformationNoCopy.PrivateBinPath = String.Empty;
293 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
294 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
295 public void ClearShadowCopyPath ()
297 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
301 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
303 return Activator.CreateComInstanceFrom (assemblyName, typeName);
306 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
307 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
309 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
313 public ObjectHandle CreateInstance (string assemblyName, string typeName)
315 if (assemblyName == null)
316 throw new ArgumentNullException ("assemblyName");
318 return Activator.CreateInstance (assemblyName, typeName);
321 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
323 if (assemblyName == null)
324 throw new ArgumentNullException ("assemblyName");
326 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
330 [Obsolete ("Use an overload that does not take an Evidence parameter")]
332 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
333 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
334 Evidence securityAttributes)
336 if (assemblyName == null)
337 throw new ArgumentNullException ("assemblyName");
339 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
340 culture, activationAttributes, securityAttributes);
343 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
345 ObjectHandle oh = CreateInstance (assemblyName, typeName);
346 return (oh != null) ? oh.Unwrap () : null;
349 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
351 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
352 return (oh != null) ? oh.Unwrap () : null;
356 [Obsolete ("Use an overload that does not take an Evidence parameter")]
358 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
359 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
360 object[] activationAttributes, Evidence securityAttributes)
362 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
363 culture, activationAttributes, securityAttributes);
364 return (oh != null) ? oh.Unwrap () : null;
368 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
369 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
371 if (assemblyName == null)
372 throw new ArgumentNullException ("assemblyName");
374 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
375 culture, activationAttributes, null);
377 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
378 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
379 object[] activationAttributes)
381 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
382 culture, activationAttributes);
383 return (oh != null) ? oh.Unwrap () : null;
386 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
387 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
388 object[] activationAttributes)
390 if (assemblyFile == null)
391 throw new ArgumentNullException ("assemblyFile");
393 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
394 culture, activationAttributes, null);
397 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
398 BindingFlags bindingAttr, Binder binder, object[] args,
399 CultureInfo culture, object[] activationAttributes)
401 ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
402 culture, activationAttributes);
404 return (oh != null) ? oh.Unwrap () : null;
408 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
410 if (assemblyFile == null)
411 throw new ArgumentNullException ("assemblyFile");
413 return Activator.CreateInstanceFrom (assemblyFile, typeName);
416 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
418 if (assemblyFile == null)
419 throw new ArgumentNullException ("assemblyFile");
421 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
425 [Obsolete ("Use an overload that does not take an Evidence parameter")]
427 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
428 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
429 object[] activationAttributes, Evidence securityAttributes)
431 if (assemblyFile == null)
432 throw new ArgumentNullException ("assemblyFile");
434 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
435 culture, activationAttributes, securityAttributes);
438 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
440 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
441 return (oh != null) ? oh.Unwrap () : null;
444 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
446 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
447 return (oh != null) ? oh.Unwrap () : null;
451 [Obsolete ("Use an overload that does not take an Evidence parameter")]
453 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
454 BindingFlags bindingAttr, Binder binder, object[] args,
455 CultureInfo culture, object[] activationAttributes,
456 Evidence securityAttributes)
458 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
459 culture, activationAttributes, securityAttributes);
461 return (oh != null) ? oh.Unwrap () : null;
464 #if !FULL_AOT_RUNTIME
465 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
467 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
471 [Obsolete ("Declarative security for assembly level is no longer enforced")]
473 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
475 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
478 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
480 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
484 [Obsolete ("Declarative security for assembly level is no longer enforced")]
486 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
489 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
493 [Obsolete ("Declarative security for assembly level is no longer enforced")]
495 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
496 PermissionSet requiredPermissions,
497 PermissionSet optionalPermissions,
498 PermissionSet refusedPermissions)
500 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
501 refusedPermissions, false);
505 [Obsolete ("Declarative security for assembly level is no longer enforced")]
507 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
508 PermissionSet requiredPermissions,
509 PermissionSet optionalPermissions,
510 PermissionSet refusedPermissions)
512 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
513 refusedPermissions, false);
517 [Obsolete ("Declarative security for assembly level is no longer enforced")]
519 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
520 PermissionSet requiredPermissions,
521 PermissionSet optionalPermissions,
522 PermissionSet refusedPermissions)
524 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
525 refusedPermissions, false);
529 [Obsolete ("Declarative security for assembly level is no longer enforced")]
531 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
533 PermissionSet requiredPermissions,
534 PermissionSet optionalPermissions,
535 PermissionSet refusedPermissions)
537 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
538 refusedPermissions, false);
542 [Obsolete ("Declarative security for assembly level is no longer enforced")]
544 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
546 PermissionSet requiredPermissions,
547 PermissionSet optionalPermissions,
548 PermissionSet refusedPermissions, bool isSynchronized)
551 throw new ArgumentNullException ("name");
552 ValidateAssemblyName (name.Name);
554 // FIXME: examine all other parameters
556 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
557 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
563 [Obsolete ("Declarative security for assembly level is no longer enforced")]
565 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
567 PermissionSet requiredPermissions,
568 PermissionSet optionalPermissions,
569 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
571 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
572 if (assemblyAttributes != null)
573 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
574 ab.SetCustomAttribute (cb);
580 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
582 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
586 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
588 return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
591 [MonoLimitation ("The argument securityContextSource is ignored")]
592 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
594 return DefineDynamicAssembly (name, access, assemblyAttributes);
598 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
600 return new AssemblyBuilder (name, null, access, true);
605 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
606 // so, when you call AppDomain.DoCallBack, that's a remote call
608 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
610 if (callBackDelegate != null)
614 public int ExecuteAssembly (string assemblyFile)
616 return ExecuteAssembly (assemblyFile, (Evidence)null, null);
620 [Obsolete ("Use an overload that does not take an Evidence parameter")]
622 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
624 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
628 [Obsolete ("Use an overload that does not take an Evidence parameter")]
630 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
632 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
633 return ExecuteAssemblyInternal (a, args);
637 [Obsolete ("Use an overload that does not take an Evidence parameter")]
639 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
641 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
642 return ExecuteAssemblyInternal (a, args);
647 public int ExecuteAssembly (string assemblyFile, string[] args)
649 Assembly a = Assembly.LoadFrom (assemblyFile, null);
650 return ExecuteAssemblyInternal (a, args);
653 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
655 Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
656 return ExecuteAssemblyInternal (a, args);
660 int ExecuteAssemblyInternal (Assembly a, string[] args)
662 if (a.EntryPoint == null)
663 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
664 return ExecuteAssembly (a, args);
667 [MethodImplAttribute (MethodImplOptions.InternalCall)]
668 private extern int ExecuteAssembly (Assembly a, string[] args);
670 [MethodImplAttribute (MethodImplOptions.InternalCall)]
671 private extern Assembly [] GetAssemblies (bool refOnly);
673 public Assembly [] GetAssemblies ()
675 return GetAssemblies (false);
678 [MethodImplAttribute (MethodImplOptions.InternalCall)]
679 public extern object GetData (string name);
681 public new Type GetType()
683 return base.GetType ();
686 public override object InitializeLifetimeService ()
691 [MethodImplAttribute (MethodImplOptions.InternalCall)]
692 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
694 public Assembly Load (AssemblyName assemblyRef)
696 return Load (assemblyRef, null);
699 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
701 if (assemblyRef == null)
702 throw new ArgumentNullException ("assemblyRef");
704 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
705 if (result == null && throwOnError)
706 throw new FileNotFoundException (null, assemblyRef.Name);
711 [Obsolete ("Use an overload that does not take an Evidence parameter")]
713 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
715 if (assemblyRef == null)
716 throw new ArgumentNullException ("assemblyRef");
718 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
719 if (assemblyRef.CodeBase != null)
720 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
722 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
725 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
726 if (assembly != null)
729 if (assemblyRef.CodeBase == null)
730 throw new FileNotFoundException (null, assemblyRef.Name);
732 string cb = assemblyRef.CodeBase;
733 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
734 cb = new Mono.Security.Uri (cb).LocalPath;
737 assembly = Assembly.LoadFrom (cb, assemblySecurity);
739 throw new FileNotFoundException (null, assemblyRef.Name);
741 AssemblyName aname = assembly.GetName ();
742 // Name, version, culture, publickeytoken. Anything else?
743 if (assemblyRef.Name != aname.Name)
744 throw new FileNotFoundException (null, assemblyRef.Name);
746 if (assemblyRef.Version != null && assemblyRef.Version != new Version (0, 0, 0, 0) && assemblyRef.Version != aname.Version)
747 throw new FileNotFoundException (null, assemblyRef.Name);
749 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
750 throw new FileNotFoundException (null, assemblyRef.Name);
752 byte [] pt = assemblyRef.GetPublicKeyToken ();
753 if (pt != null && pt.Length != 0) {
754 byte [] loaded_pt = aname.GetPublicKeyToken ();
755 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
756 throw new FileNotFoundException (null, assemblyRef.Name);
757 for (int i = pt.Length - 1; i >= 0; i--)
758 if (loaded_pt [i] != pt [i])
759 throw new FileNotFoundException (null, assemblyRef.Name);
764 public Assembly Load (string assemblyString)
766 return Load (assemblyString, null, false);
770 [Obsolete ("Use an overload that does not take an Evidence parameter")]
772 public Assembly Load (string assemblyString, Evidence assemblySecurity)
774 return Load (assemblyString, assemblySecurity, false);
777 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
779 if (assemblyString == null)
780 throw new ArgumentNullException ("assemblyString");
782 if (assemblyString.Length == 0)
783 throw new ArgumentException ("assemblyString cannot have zero length");
785 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
786 if (assembly == null)
787 throw new FileNotFoundException (null, assemblyString);
791 public Assembly Load (byte[] rawAssembly)
793 return Load (rawAssembly, null, null);
796 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
798 return Load (rawAssembly, rawSymbolStore, null);
801 [MethodImplAttribute (MethodImplOptions.InternalCall)]
802 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
805 [Obsolete ("Use an overload that does not take an Evidence parameter")]
807 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
809 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
812 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
814 if (rawAssembly == null)
815 throw new ArgumentNullException ("rawAssembly");
817 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
818 assembly.FromByteArray = true;
822 [Obsolete ("AppDomain policy levels are obsolete")]
824 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
825 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
827 if (domainPolicy == null)
828 throw new ArgumentNullException ("domainPolicy");
829 if (_granted != null) {
830 throw new PolicyException (Locale.GetText (
831 "An AppDomain policy is already specified."));
833 if (IsFinalizingForUnload ())
834 throw new AppDomainUnloadedException ();
836 PolicyStatement ps = domainPolicy.Resolve (_evidence);
837 _granted = ps.PermissionSet;
840 [Obsolete ("Use AppDomainSetup.SetCachePath")]
841 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
842 public void SetCachePath (string path)
844 SetupInformationNoCopy.CachePath = path;
847 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
848 public void SetPrincipalPolicy (PrincipalPolicy policy)
850 if (IsFinalizingForUnload ())
851 throw new AppDomainUnloadedException ();
853 _principalPolicy = policy;
857 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
858 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
859 public void SetShadowCopyFiles()
861 SetupInformationNoCopy.ShadowCopyFiles = "true";
864 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
865 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
866 public void SetShadowCopyPath (string path)
868 SetupInformationNoCopy.ShadowCopyDirectories = path;
871 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
872 public void SetThreadPrincipal (IPrincipal principal)
874 if (principal == null)
875 throw new ArgumentNullException ("principal");
876 if (_principal != null)
877 throw new PolicyException (Locale.GetText ("principal already present."));
878 if (IsFinalizingForUnload ())
879 throw new AppDomainUnloadedException ();
881 _principal = principal;
884 [MethodImplAttribute (MethodImplOptions.InternalCall)]
885 private static extern AppDomain InternalSetDomainByID (int domain_id);
887 // Changes the active domain and returns the old domain
888 [MethodImplAttribute (MethodImplOptions.InternalCall)]
889 private static extern AppDomain InternalSetDomain (AppDomain context);
891 // Notifies the runtime that this thread references 'domain'.
892 [MethodImplAttribute (MethodImplOptions.InternalCall)]
893 internal static extern void InternalPushDomainRef (AppDomain domain);
895 [MethodImplAttribute (MethodImplOptions.InternalCall)]
896 internal static extern void InternalPushDomainRefByID (int domain_id);
898 // Undoes the effect of the last PushDomainRef call
899 [MethodImplAttribute (MethodImplOptions.InternalCall)]
900 internal static extern void InternalPopDomainRef ();
902 // Changes the active context and returns the old context
903 [MethodImplAttribute (MethodImplOptions.InternalCall)]
904 internal static extern Context InternalSetContext (Context context);
906 // Returns the current context
907 [MethodImplAttribute (MethodImplOptions.InternalCall)]
908 internal static extern Context InternalGetContext ();
910 // Returns the current context
911 [MethodImplAttribute (MethodImplOptions.InternalCall)]
912 internal static extern Context InternalGetDefaultContext ();
914 [MethodImplAttribute (MethodImplOptions.InternalCall)]
915 internal static extern string InternalGetProcessGuid (string newguid);
917 // This method is handled specially by the runtime
918 // It is the only managed method which is allowed to set the current
920 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
922 AppDomain current = CurrentDomain;
927 InternalPushDomainRef (domain);
929 InternalSetDomain (domain);
930 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
936 InternalSetDomain (current);
938 InternalPopDomainRef ();
942 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
944 AppDomain current = CurrentDomain;
949 InternalPushDomainRefByID (domain_id);
951 InternalSetDomainByID (domain_id);
952 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
958 InternalSetDomain (current);
960 InternalPopDomainRef ();
964 internal static String GetProcessGuid ()
966 if (_process_guid == null) {
967 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
969 return _process_guid;
972 public static AppDomain CreateDomain (string friendlyName)
974 return CreateDomain (friendlyName, null, null);
977 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
979 return CreateDomain (friendlyName, securityInfo, null);
982 [MethodImplAttribute (MethodImplOptions.InternalCall)]
983 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
985 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
986 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
987 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
989 if (friendlyName == null)
990 throw new System.ArgumentNullException ("friendlyName");
992 AppDomain def = AppDomain.DefaultDomain;
994 // if null, get default domain's SetupInformation
996 info = new AppDomainSetup (); // we're default!
998 info = def.SetupInformation;
1001 info = new AppDomainSetup (info); // copy
1003 // todo: allow setup in the other domain
1005 if (!info.Equals (def.SetupInformation)) {
1006 // If not specified use default domain's app base.
1007 if (info.ApplicationBase == null)
1008 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1009 if (info.ConfigurationFile == null)
1010 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1012 } else if (info.ConfigurationFile == null)
1013 info.ConfigurationFile = "[I don't have a config file]";
1016 if (info.AppDomainInitializer != null) {
1017 if (!info.AppDomainInitializer.Method.IsStatic)
1018 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1022 info.SerializeNonPrimitives ();
1024 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1025 if (securityInfo == null) {
1026 // get default domain's Evidence (unless we're are the default!)
1028 ad._evidence = null; // we'll get them later (GetEntryAssembly)
1030 ad._evidence = def.Evidence; // new (shallow) copy
1033 ad._evidence = new Evidence (securityInfo); // copy
1036 if (info.AppDomainInitializer != null) {
1037 Loader loader = new Loader (
1038 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1039 ad.DoCallBack (loader.Load);
1041 Initializer initializer = new Initializer (
1042 info.AppDomainInitializer,
1043 info.AppDomainInitializerArguments);
1044 ad.DoCallBack (initializer.Initialize);
1057 public Loader (string assembly)
1059 this.assembly = assembly;
1064 Assembly.LoadFrom (assembly);
1071 AppDomainInitializer initializer;
1072 string [] arguments;
1074 public Initializer (AppDomainInitializer initializer, string [] arguments)
1076 this.initializer = initializer;
1077 this.arguments = arguments;
1080 public void Initialize ()
1082 initializer (arguments);
1087 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1088 string appRelativeSearchPath, bool shadowCopyFiles)
1090 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1094 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1095 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1098 throw new ArgumentNullException ("info");
1100 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
1101 return CreateDomain (friendlyName, securityInfo, info);
1105 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1107 AppDomainSetup info = new AppDomainSetup ();
1109 info.ApplicationBase = appBasePath;
1110 info.PrivateBinPath = appRelativeSearchPath;
1112 if (shadowCopyFiles)
1113 info.ShadowCopyFiles = "true";
1115 info.ShadowCopyFiles = "false";
1120 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1121 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1123 public bool IsFinalizingForUnload()
1125 return InternalIsFinalizingForUnload (getDomainID ());
1128 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1129 static extern void InternalUnload (int domain_id);
1131 // We do this because if the domain is a transparant proxy this
1132 // will still return the correct domain id.
1133 private int getDomainID ()
1135 return Thread.GetDomainID ();
1138 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1139 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1140 public static void Unload (AppDomain domain)
1143 throw new ArgumentNullException ("domain");
1145 InternalUnload (domain.getDomainID());
1148 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1149 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1150 public extern void SetData (string name, object data);
1152 [MonoLimitation ("The permission field is ignored")]
1153 public void SetData (string name, object data, IPermission permission)
1155 SetData (name, data);
1159 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1160 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1161 public void SetDynamicBase (string path)
1163 SetupInformationNoCopy.DynamicBase = path;
1167 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1168 + " because it does not provide a stable Id when managed"
1169 + " threads are running on fibers (aka lightweight"
1170 + " threads). To get a stable identifier for a managed"
1171 + " thread, use the ManagedThreadId property on Thread.'")]
1172 public static int GetCurrentThreadId ()
1174 return Thread.CurrentThreadId;
1177 public override string ToString ()
1179 return getFriendlyName ();
1182 private static void ValidateAssemblyName (string name)
1184 if (name == null || name.Length == 0)
1185 throw new ArgumentException ("The Name of " +
1186 "AssemblyName cannot be null or a " +
1187 "zero-length string.");
1189 bool isValid = true;
1191 for (int i = 0; i < name.Length; i++) {
1194 // do not allow leading whitespace
1195 if (i == 0 && char.IsWhiteSpace (c)) {
1200 // do not allow /,\ or : in name
1201 if (c == '/' || c == '\\' || c == ':') {
1208 throw new ArgumentException ("The Name of " +
1209 "AssemblyName cannot start with " +
1210 "whitespace, or contain '/', '\\' " +
1214 // The following methods are called from the runtime. Don't change signatures.
1215 #pragma warning disable 169
1216 private void DoAssemblyLoad (Assembly assembly)
1218 if (AssemblyLoad == null)
1221 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1224 private Assembly DoAssemblyResolve (string name, bool refonly)
1226 ResolveEventHandler del;
1229 del = ReflectionOnlyAssemblyResolve;
1231 del = AssemblyResolve;
1233 del = AssemblyResolve;
1238 /* Prevent infinite recursion */
1241 ht = assembly_resolve_in_progress_refonly;
1243 ht = new Hashtable ();
1244 assembly_resolve_in_progress_refonly = ht;
1247 ht = assembly_resolve_in_progress;
1249 ht = new Hashtable ();
1250 assembly_resolve_in_progress = ht;
1254 string s = (string) ht [name];
1259 Delegate[] invocation_list = del.GetInvocationList ();
1261 foreach (Delegate eh in invocation_list) {
1262 ResolveEventHandler handler = (ResolveEventHandler) eh;
1263 Assembly assembly = handler (this, new ResolveEventArgs (name));
1264 if (assembly != null)
1274 internal Assembly DoTypeResolve (Object name_or_tb)
1276 if (TypeResolve == null)
1281 #if !FULL_AOT_RUNTIME
1282 if (name_or_tb is TypeBuilder)
1283 name = ((TypeBuilder) name_or_tb).FullName;
1286 name = (string) name_or_tb;
1288 /* Prevent infinite recursion */
1289 Hashtable ht = type_resolve_in_progress;
1291 ht = new Hashtable ();
1292 type_resolve_in_progress = ht;
1295 if (ht.Contains (name))
1301 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1302 ResolveEventHandler eh = (ResolveEventHandler) d;
1303 Assembly assembly = eh (this, new ResolveEventArgs (name));
1304 if (assembly != null)
1314 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1315 if (ResourceResolve == null)
1318 Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1320 foreach (Delegate eh in invocation_list) {
1321 ResolveEventHandler handler = (ResolveEventHandler) eh;
1323 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1325 Assembly assembly = handler (this, new ResolveEventArgs (name));
1327 if (assembly != null)
1333 private void DoDomainUnload ()
1335 if (DomainUnload != null)
1336 DomainUnload(this, null);
1339 internal byte[] GetMarshalledDomainObjRef ()
1341 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1342 return CADSerializer.SerializeObject (oref).GetBuffer();
1345 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1346 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1350 if (null != arrRequest)
1351 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1353 reqDomMsg = new MethodCall (cadMsg);
1355 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1357 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1358 if (null == cadMrm) {
1359 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1365 #pragma warning restore 169
1367 // End of methods called from the runtime
1369 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1370 public event AssemblyLoadEventHandler AssemblyLoad;
1372 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1373 public event ResolveEventHandler AssemblyResolve;
1375 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1376 public event EventHandler DomainUnload;
1378 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1379 public event EventHandler ProcessExit;
1381 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1382 public event ResolveEventHandler ResourceResolve;
1384 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1385 public event ResolveEventHandler TypeResolve;
1387 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1388 public event UnhandledExceptionEventHandler UnhandledException;
1392 public bool IsHomogenous {
1393 get { return true; }
1397 public bool IsFullyTrusted {
1398 get { return true; }
1402 #pragma warning disable 649
1403 private AppDomainManager _domain_manager;
1404 #pragma warning restore 649
1407 public AppDomainManager DomainManager {
1408 get { return _domain_manager; }
1411 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1413 #pragma warning disable 649
1414 private ActivationContext _activation;
1415 private ApplicationIdentity _applicationIdentity;
1416 #pragma warning restore 649
1420 public ActivationContext ActivationContext {
1421 get { return _activation; }
1424 public ApplicationIdentity ApplicationIdentity {
1425 get { return _applicationIdentity; }
1429 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1430 get { return getDomainID (); }
1435 [MonoTODO ("This routine only returns the parameter currently")]
1436 [ComVisible (false)]
1437 public string ApplyPolicy (string assemblyName)
1439 if (assemblyName == null)
1440 throw new ArgumentNullException ("assemblyName");
1441 if (assemblyName.Length == 0) // String.Empty
1442 throw new ArgumentException ("assemblyName");
1443 return assemblyName;
1448 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1449 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1451 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1453 info.AppDomainInitializerArguments = adInitArgs;
1454 info.AppDomainInitializer = adInit;
1456 return CreateDomain (friendlyName, securityInfo, info);
1459 public int ExecuteAssemblyByName (string assemblyName)
1461 return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1465 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1467 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1469 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1473 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1475 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1477 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1479 return ExecuteAssemblyInternal (a, args);
1483 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1485 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1487 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1489 return ExecuteAssemblyInternal (a, args);
1493 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1495 Assembly a = Assembly.Load (assemblyName, null);
1497 return ExecuteAssemblyInternal (a, args);
1500 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1502 Assembly a = Assembly.Load (assemblyName, null);
1504 return ExecuteAssemblyInternal (a, args);
1508 public bool IsDefaultAppDomain ()
1510 return Object.ReferenceEquals (this, DefaultDomain);
1513 public Assembly[] ReflectionOnlyGetAssemblies ()
1515 return GetAssemblies (true);
1519 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1521 throw new NotImplementedException ();
1524 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1526 throw new NotImplementedException ();
1529 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1531 throw new NotImplementedException ();
1534 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1535 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1537 throw new NotImplementedException ();
1541 #if NET_4_0 || MOBILE
1542 List<string> compatibility_switch;
1544 public bool? IsCompatibilitySwitchSet (string value)
1547 throw new ArgumentNullException ("value");
1549 // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1550 return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1553 internal void SetCompatibilitySwitch (string value)
1555 if (compatibility_switch == null)
1556 compatibility_switch = new List<string> ();
1557 compatibility_switch.Add (value);
1560 [MonoTODO ("Currently always returns false")]
1561 public static bool MonitoringIsEnabled {
1562 get { return false; }
1563 set { throw new NotImplementedException (); }
1567 public long MonitoringSurvivedMemorySize {
1568 get { throw new NotImplementedException (); }
1572 public static long MonitoringSurvivedProcessMemorySize {
1573 get { throw new NotImplementedException (); }
1577 public long MonitoringTotalAllocatedMemorySize {
1578 get { throw new NotImplementedException (); }
1582 public TimeSpan MonitoringTotalProcessorTime {
1583 get { throw new NotImplementedException (); }