5 // Paolo Molaro (lupus@ximian.com)
6 // Dietmar Maurer (dietmar@ximian.com)
7 // Miguel de Icaza (miguel@ximian.com)
8 // Gonzalo Paniagua (gonzalo@ximian.com)
10 // Sebastien Pouliot (sebastien@ximian.com)
12 // (C) 2001, 2002 Ximian, Inc. http://www.ximian.com
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
14 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Globalization;
39 using System.Reflection;
40 using System.Reflection.Emit;
41 using System.Threading;
42 using System.Runtime.CompilerServices;
43 using System.Runtime.InteropServices;
44 using System.Runtime.Remoting;
45 using System.Runtime.Remoting.Contexts;
46 using System.Runtime.Remoting.Channels;
47 using System.Runtime.Remoting.Messaging;
48 using System.Security;
49 using System.Security.Permissions;
50 using System.Security.Policy;
51 using System.Security.Principal;
52 using System.Configuration.Assemblies;
54 using System.Collections.Generic;
55 using System.Runtime.ConstrainedExecution;
61 #if !NET_2_1 || MOONLIGHT
62 [ComDefaultInterface (typeof (_AppDomain))]
64 [ClassInterface(ClassInterfaceType.None)]
65 [StructLayout (LayoutKind.Sequential)]
67 public sealed class AppDomain : _AppDomain {
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;
90 private Evidence _evidence;
91 private PermissionSet _granted;
94 private PrincipalPolicy _principalPolicy;
97 private static IPrincipal _principal;
99 static AppDomain default_domain;
105 [MethodImplAttribute (MethodImplOptions.InternalCall)]
106 private extern AppDomainSetup getSetup ();
111 AppDomainSetup SetupInformationNoCopy {
112 get { return getSetup (); }
115 public AppDomainSetup SetupInformation {
117 AppDomainSetup setup = getSetup ();
118 return new AppDomainSetup (setup);
124 public ApplicationTrust ApplicationTrust {
125 get { throw new NotImplementedException (); }
129 public string BaseDirectory {
131 string path = SetupInformationNoCopy.ApplicationBase;
133 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
134 // we cannot divulge local file informations
135 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
142 public string RelativeSearchPath {
144 string path = SetupInformationNoCopy.PrivateBinPath;
146 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
147 // we cannot divulge local file informations
148 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
155 public string DynamicDirectory {
157 AppDomainSetup setup = SetupInformationNoCopy;
158 if (setup.DynamicBase == null)
161 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
163 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
164 // we cannot divulge local file informations
165 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
172 public bool ShadowCopyFiles {
174 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
179 [MethodImplAttribute (MethodImplOptions.InternalCall)]
180 private extern string getFriendlyName ();
182 public string FriendlyName {
184 return getFriendlyName ();
188 public Evidence Evidence {
190 // if the host (runtime) hasn't provided it's own evidence...
191 if (_evidence == null) {
192 // ... we will provide our own
194 // the executed assembly from the "default" appdomain
195 // or null if we're not in the default appdomain or
196 // if there is no entry assembly (embedded mono)
197 Assembly a = Assembly.GetEntryAssembly ();
199 if (this == DefaultDomain)
201 return new Evidence ();
203 _evidence = AppDomain.DefaultDomain.Evidence;
205 _evidence = Evidence.GetDefaultHostEvidence (a);
209 return new Evidence (_evidence); // return a copy
213 internal IPrincipal DefaultPrincipal {
215 if (_principal == null) {
216 switch (_principalPolicy) {
217 case PrincipalPolicy.UnauthenticatedPrincipal:
218 _principal = new GenericPrincipal (
219 new GenericIdentity (String.Empty, String.Empty), null);
221 case PrincipalPolicy.WindowsPrincipal:
222 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
230 // for AppDomain there is only an allowed (i.e. granted) set
231 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
232 internal PermissionSet GrantedPermissionSet {
233 get { return _granted; }
238 public PermissionSet PermissionSet {
239 get { return _granted ?? (_granted = new PermissionSet (PermissionState.Unrestricted)); }
243 [MethodImplAttribute (MethodImplOptions.InternalCall)]
244 private static extern AppDomain getCurDomain ();
246 public static AppDomain CurrentDomain {
248 return getCurDomain ();
252 [MethodImplAttribute (MethodImplOptions.InternalCall)]
253 private static extern AppDomain getRootDomain ();
255 internal static AppDomain DefaultDomain {
257 if (default_domain == null) {
258 AppDomain rd = getRootDomain ();
259 if (rd == CurrentDomain)
262 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
264 return default_domain;
270 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
271 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
272 public void AppendPrivatePath (string path)
274 if (path == null || path.Length == 0)
277 AppDomainSetup setup = SetupInformationNoCopy;
279 string pp = setup.PrivateBinPath;
280 if (pp == null || pp.Length == 0) {
281 setup.PrivateBinPath = path;
286 if (pp [pp.Length - 1] != Path.PathSeparator)
287 pp += Path.PathSeparator;
289 setup.PrivateBinPath = pp + path;
292 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
293 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
294 public void ClearPrivatePath ()
296 SetupInformationNoCopy.PrivateBinPath = String.Empty;
299 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
300 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
301 public void ClearShadowCopyPath ()
303 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
307 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
309 return Activator.CreateComInstanceFrom (assemblyName, typeName);
312 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
313 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
315 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
319 public ObjectHandle CreateInstance (string assemblyName, string typeName)
321 if (assemblyName == null)
322 throw new ArgumentNullException ("assemblyName");
324 return Activator.CreateInstance (assemblyName, typeName);
327 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
329 if (assemblyName == null)
330 throw new ArgumentNullException ("assemblyName");
332 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
336 [Obsolete ("Use an overload that does not take an Evidence parameter")]
338 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
339 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
340 Evidence securityAttributes)
342 if (assemblyName == null)
343 throw new ArgumentNullException ("assemblyName");
345 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
346 culture, activationAttributes, securityAttributes);
349 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
351 ObjectHandle oh = CreateInstance (assemblyName, typeName);
352 return (oh != null) ? oh.Unwrap () : null;
355 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
357 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
358 return (oh != null) ? oh.Unwrap () : null;
362 [Obsolete ("Use an overload that does not take an Evidence parameter")]
364 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
365 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
366 object[] activationAttributes, Evidence securityAttributes)
368 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
369 culture, activationAttributes, securityAttributes);
370 return (oh != null) ? oh.Unwrap () : null;
374 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
375 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
377 if (assemblyName == null)
378 throw new ArgumentNullException ("assemblyName");
380 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
381 culture, activationAttributes, null);
383 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
384 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
385 object[] activationAttributes)
387 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
388 culture, activationAttributes);
389 return (oh != null) ? oh.Unwrap () : null;
392 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
393 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
394 object[] activationAttributes)
396 if (assemblyFile == null)
397 throw new ArgumentNullException ("assemblyFile");
399 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
400 culture, activationAttributes, null);
403 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
404 BindingFlags bindingAttr, Binder binder, object[] args,
405 CultureInfo culture, object[] activationAttributes)
407 ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
408 culture, activationAttributes);
410 return (oh != null) ? oh.Unwrap () : null;
414 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
416 if (assemblyFile == null)
417 throw new ArgumentNullException ("assemblyFile");
419 return Activator.CreateInstanceFrom (assemblyFile, typeName);
422 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
424 if (assemblyFile == null)
425 throw new ArgumentNullException ("assemblyFile");
427 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
431 [Obsolete ("Use an overload that does not take an Evidence parameter")]
433 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
434 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
435 object[] activationAttributes, Evidence securityAttributes)
437 if (assemblyFile == null)
438 throw new ArgumentNullException ("assemblyFile");
440 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
441 culture, activationAttributes, securityAttributes);
444 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
446 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
447 return (oh != null) ? oh.Unwrap () : null;
450 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
452 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
453 return (oh != null) ? oh.Unwrap () : null;
457 [Obsolete ("Use an overload that does not take an Evidence parameter")]
459 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
460 BindingFlags bindingAttr, Binder binder, object[] args,
461 CultureInfo culture, object[] activationAttributes,
462 Evidence securityAttributes)
464 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
465 culture, activationAttributes, securityAttributes);
467 return (oh != null) ? oh.Unwrap () : null;
472 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
474 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
478 [Obsolete ("Declarative security for assembly level is no longer enforced")]
480 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
482 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
485 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
487 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
491 [Obsolete ("Declarative security for assembly level is no longer enforced")]
493 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
496 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
500 [Obsolete ("Declarative security for assembly level is no longer enforced")]
502 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
503 PermissionSet requiredPermissions,
504 PermissionSet optionalPermissions,
505 PermissionSet refusedPermissions)
507 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
508 refusedPermissions, false);
512 [Obsolete ("Declarative security for assembly level is no longer enforced")]
514 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
515 PermissionSet requiredPermissions,
516 PermissionSet optionalPermissions,
517 PermissionSet refusedPermissions)
519 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
520 refusedPermissions, false);
524 [Obsolete ("Declarative security for assembly level is no longer enforced")]
526 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
527 PermissionSet requiredPermissions,
528 PermissionSet optionalPermissions,
529 PermissionSet refusedPermissions)
531 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
532 refusedPermissions, false);
536 [Obsolete ("Declarative security for assembly level is no longer enforced")]
538 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
540 PermissionSet requiredPermissions,
541 PermissionSet optionalPermissions,
542 PermissionSet refusedPermissions)
544 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
545 refusedPermissions, false);
549 [Obsolete ("Declarative security for assembly level is no longer enforced")]
551 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
553 PermissionSet requiredPermissions,
554 PermissionSet optionalPermissions,
555 PermissionSet refusedPermissions, bool isSynchronized)
558 throw new ArgumentNullException ("name");
559 ValidateAssemblyName (name.Name);
561 // FIXME: examine all other parameters
563 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
564 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
570 [Obsolete ("Declarative security for assembly level is no longer enforced")]
572 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
574 PermissionSet requiredPermissions,
575 PermissionSet optionalPermissions,
576 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
578 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
579 if (assemblyAttributes != null)
580 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
581 ab.SetCustomAttribute (cb);
587 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
589 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
593 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
595 return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
598 [MonoLimitation ("The argument securityContextSource is ignored")]
599 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
601 return DefineDynamicAssembly (name, access, assemblyAttributes);
605 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
607 return new AssemblyBuilder (name, null, access, true);
611 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
612 // so, when you call AppDomain.DoCallBack, that's a remote call
614 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
616 if (callBackDelegate != null)
620 public int ExecuteAssembly (string assemblyFile)
622 return ExecuteAssembly (assemblyFile, (Evidence)null, null);
626 [Obsolete ("Use an overload that does not take an Evidence parameter")]
628 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
630 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
634 [Obsolete ("Use an overload that does not take an Evidence parameter")]
636 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
638 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
639 return ExecuteAssemblyInternal (a, args);
643 [Obsolete ("Use an overload that does not take an Evidence parameter")]
645 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
647 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
648 return ExecuteAssemblyInternal (a, args);
653 public int ExecuteAssembly (string assemblyFile, string[] args)
655 Assembly a = Assembly.LoadFrom (assemblyFile, null);
656 return ExecuteAssemblyInternal (a, args);
659 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
661 Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
662 return ExecuteAssemblyInternal (a, args);
666 int ExecuteAssemblyInternal (Assembly a, string[] args)
668 if (a.EntryPoint == null)
669 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
670 return ExecuteAssembly (a, args);
673 [MethodImplAttribute (MethodImplOptions.InternalCall)]
674 private extern int ExecuteAssembly (Assembly a, string[] args);
676 [MethodImplAttribute (MethodImplOptions.InternalCall)]
677 private extern Assembly [] GetAssemblies (bool refOnly);
679 public Assembly [] GetAssemblies ()
681 return GetAssemblies (false);
684 [MethodImplAttribute (MethodImplOptions.InternalCall)]
685 public extern object GetData (string name);
687 public new Type GetType()
689 return base.GetType ();
693 public override object InitializeLifetimeService ()
699 [MethodImplAttribute (MethodImplOptions.InternalCall)]
700 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
702 public Assembly Load (AssemblyName assemblyRef)
704 return Load (assemblyRef, null);
707 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
709 if (assemblyRef == null)
710 throw new ArgumentNullException ("assemblyRef");
712 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
713 if (result == null && throwOnError)
714 throw new FileNotFoundException (null, assemblyRef.Name);
719 [Obsolete ("Use an overload that does not take an Evidence parameter")]
721 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
723 if (assemblyRef == null)
724 throw new ArgumentNullException ("assemblyRef");
726 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
727 if (assemblyRef.CodeBase != null)
728 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
730 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
733 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
734 if (assembly != null)
737 if (assemblyRef.CodeBase == null)
738 throw new FileNotFoundException (null, assemblyRef.Name);
740 string cb = assemblyRef.CodeBase;
741 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
742 cb = new Mono.Security.Uri (cb).LocalPath;
745 assembly = Assembly.LoadFrom (cb, assemblySecurity);
747 throw new FileNotFoundException (null, assemblyRef.Name);
749 AssemblyName aname = assembly.GetName ();
750 // Name, version, culture, publickeytoken. Anything else?
751 if (assemblyRef.Name != aname.Name)
752 throw new FileNotFoundException (null, assemblyRef.Name);
754 if (assemblyRef.Version != null && assemblyRef.Version != new Version (0, 0, 0, 0) && assemblyRef.Version != aname.Version)
755 throw new FileNotFoundException (null, assemblyRef.Name);
757 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
758 throw new FileNotFoundException (null, assemblyRef.Name);
760 byte [] pt = assemblyRef.GetPublicKeyToken ();
761 if (pt != null && pt.Length != 0) {
762 byte [] loaded_pt = aname.GetPublicKeyToken ();
763 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
764 throw new FileNotFoundException (null, assemblyRef.Name);
765 for (int i = pt.Length - 1; i >= 0; i--)
766 if (loaded_pt [i] != pt [i])
767 throw new FileNotFoundException (null, assemblyRef.Name);
772 public Assembly Load (string assemblyString)
774 return Load (assemblyString, null, false);
778 [Obsolete ("Use an overload that does not take an Evidence parameter")]
780 public Assembly Load (string assemblyString, Evidence assemblySecurity)
782 return Load (assemblyString, assemblySecurity, false);
785 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
787 if (assemblyString == null)
788 throw new ArgumentNullException ("assemblyString");
790 if (assemblyString.Length == 0)
791 throw new ArgumentException ("assemblyString cannot have zero length");
793 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
794 if (assembly == null)
795 throw new FileNotFoundException (null, assemblyString);
799 public Assembly Load (byte[] rawAssembly)
801 return Load (rawAssembly, null, null);
804 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
806 return Load (rawAssembly, rawSymbolStore, null);
809 [MethodImplAttribute (MethodImplOptions.InternalCall)]
810 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
813 [Obsolete ("Use an overload that does not take an Evidence parameter")]
815 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
817 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
820 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
822 if (rawAssembly == null)
823 throw new ArgumentNullException ("rawAssembly");
825 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
826 assembly.FromByteArray = true;
831 [Obsolete ("AppDomain policy levels are obsolete")]
833 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
834 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
836 if (domainPolicy == null)
837 throw new ArgumentNullException ("domainPolicy");
838 if (_granted != null) {
839 throw new PolicyException (Locale.GetText (
840 "An AppDomain policy is already specified."));
842 if (IsFinalizingForUnload ())
843 throw new AppDomainUnloadedException ();
845 PolicyStatement ps = domainPolicy.Resolve (_evidence);
846 _granted = ps.PermissionSet;
849 [Obsolete ("Use AppDomainSetup.SetCachePath")]
850 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
851 public void SetCachePath (string path)
853 SetupInformationNoCopy.CachePath = path;
856 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
857 public void SetPrincipalPolicy (PrincipalPolicy policy)
859 if (IsFinalizingForUnload ())
860 throw new AppDomainUnloadedException ();
862 _principalPolicy = policy;
866 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
867 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
868 public void SetShadowCopyFiles()
870 SetupInformationNoCopy.ShadowCopyFiles = "true";
873 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
874 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
875 public void SetShadowCopyPath (string path)
877 SetupInformationNoCopy.ShadowCopyDirectories = path;
880 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
881 public void SetThreadPrincipal (IPrincipal principal)
883 if (principal == null)
884 throw new ArgumentNullException ("principal");
885 if (_principal != null)
886 throw new PolicyException (Locale.GetText ("principal already present."));
887 if (IsFinalizingForUnload ())
888 throw new AppDomainUnloadedException ();
890 _principal = principal;
893 [MethodImplAttribute (MethodImplOptions.InternalCall)]
894 private static extern AppDomain InternalSetDomainByID (int domain_id);
896 // Changes the active domain and returns the old domain
897 [MethodImplAttribute (MethodImplOptions.InternalCall)]
898 private static extern AppDomain InternalSetDomain (AppDomain context);
900 // Notifies the runtime that this thread references 'domain'.
901 [MethodImplAttribute (MethodImplOptions.InternalCall)]
902 internal static extern void InternalPushDomainRef (AppDomain domain);
904 [MethodImplAttribute (MethodImplOptions.InternalCall)]
905 internal static extern void InternalPushDomainRefByID (int domain_id);
907 // Undoes the effect of the last PushDomainRef call
908 [MethodImplAttribute (MethodImplOptions.InternalCall)]
909 internal static extern void InternalPopDomainRef ();
911 // Changes the active context and returns the old context
912 [MethodImplAttribute (MethodImplOptions.InternalCall)]
913 internal static extern Context InternalSetContext (Context context);
915 // Returns the current context
916 [MethodImplAttribute (MethodImplOptions.InternalCall)]
917 internal static extern Context InternalGetContext ();
919 // Returns the current context
920 [MethodImplAttribute (MethodImplOptions.InternalCall)]
921 internal static extern Context InternalGetDefaultContext ();
923 [MethodImplAttribute (MethodImplOptions.InternalCall)]
924 internal static extern string InternalGetProcessGuid (string newguid);
926 // This method is handled specially by the runtime
927 // It is the only managed method which is allowed to set the current
929 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
931 AppDomain current = CurrentDomain;
936 InternalPushDomainRef (domain);
938 InternalSetDomain (domain);
939 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
945 InternalSetDomain (current);
947 InternalPopDomainRef ();
951 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
953 AppDomain current = CurrentDomain;
958 InternalPushDomainRefByID (domain_id);
960 InternalSetDomainByID (domain_id);
961 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
967 InternalSetDomain (current);
969 InternalPopDomainRef ();
973 internal static String GetProcessGuid ()
975 if (_process_guid == null) {
976 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
978 return _process_guid;
983 public static AppDomain CreateDomain (string friendlyName)
985 return CreateDomain (friendlyName, null, null);
988 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo)
990 return CreateDomain (friendlyName, securityInfo, null);
993 [MethodImplAttribute (MethodImplOptions.InternalCall)]
994 private static extern AppDomain createDomain (string friendlyName, AppDomainSetup info);
996 [MonoLimitationAttribute ("Currently it does not allow the setup in the other domain")]
997 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
998 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
1000 if (friendlyName == null)
1001 throw new System.ArgumentNullException ("friendlyName");
1003 AppDomain def = AppDomain.DefaultDomain;
1005 // if null, get default domain's SetupInformation
1007 info = new AppDomainSetup (); // we're default!
1009 info = def.SetupInformation;
1012 info = new AppDomainSetup (info); // copy
1014 // todo: allow setup in the other domain
1016 if (!info.Equals (def.SetupInformation)) {
1017 // If not specified use default domain's app base.
1018 if (info.ApplicationBase == null)
1019 info.ApplicationBase = def.SetupInformation.ApplicationBase;
1020 if (info.ConfigurationFile == null)
1021 info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
1023 } else if (info.ConfigurationFile == null)
1024 info.ConfigurationFile = "[I don't have a config file]";
1027 if (info.AppDomainInitializer != null) {
1028 if (!info.AppDomainInitializer.Method.IsStatic)
1029 throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
1033 info.SerializeNonPrimitives ();
1035 AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
1036 if (securityInfo == null) {
1037 // get default domain's Evidence (unless we're are the default!)
1039 ad._evidence = null; // we'll get them later (GetEntryAssembly)
1041 ad._evidence = def.Evidence; // new (shallow) copy
1044 ad._evidence = new Evidence (securityInfo); // copy
1047 if (info.AppDomainInitializer != null) {
1048 Loader loader = new Loader (
1049 info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
1050 ad.DoCallBack (loader.Load);
1052 Initializer initializer = new Initializer (
1053 info.AppDomainInitializer,
1054 info.AppDomainInitializerArguments);
1055 ad.DoCallBack (initializer.Initialize);
1068 public Loader (string assembly)
1070 this.assembly = assembly;
1075 Assembly.LoadFrom (assembly);
1082 AppDomainInitializer initializer;
1083 string [] arguments;
1085 public Initializer (AppDomainInitializer initializer, string [] arguments)
1087 this.initializer = initializer;
1088 this.arguments = arguments;
1091 public void Initialize ()
1093 initializer (arguments);
1098 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo,string appBasePath,
1099 string appRelativeSearchPath, bool shadowCopyFiles)
1101 return CreateDomain (friendlyName, securityInfo, CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles));
1105 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info,
1106 PermissionSet grantSet, params StrongName [] fullTrustAssemblies)
1109 throw new ArgumentNullException ("info");
1111 info.ApplicationTrust = new ApplicationTrust (grantSet, fullTrustAssemblies ?? new StrongName [0]);
1112 return CreateDomain (friendlyName, securityInfo, info);
1116 static AppDomainSetup CreateDomainSetup (string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
1118 AppDomainSetup info = new AppDomainSetup ();
1120 info.ApplicationBase = appBasePath;
1121 info.PrivateBinPath = appRelativeSearchPath;
1123 if (shadowCopyFiles)
1124 info.ShadowCopyFiles = "true";
1126 info.ShadowCopyFiles = "false";
1132 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1133 private static extern bool InternalIsFinalizingForUnload (int domain_id);
1135 public bool IsFinalizingForUnload()
1137 return InternalIsFinalizingForUnload (getDomainID ());
1140 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1141 static extern void InternalUnload (int domain_id);
1143 // We do this because if the domain is a transparant proxy this
1144 // will still return the correct domain id.
1145 private int getDomainID ()
1147 return Thread.GetDomainID ();
1150 [SecurityPermission (SecurityAction.Demand, ControlAppDomain = true)]
1151 [ReliabilityContractAttribute (Consistency.MayCorruptAppDomain, Cer.MayFail)]
1152 public static void Unload (AppDomain domain)
1155 throw new ArgumentNullException ("domain");
1157 InternalUnload (domain.getDomainID());
1160 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1161 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1162 public extern void SetData (string name, object data);
1164 [MonoLimitation ("The permission field is ignored")]
1165 public void SetData (string name, object data, IPermission permission)
1167 SetData (name, data);
1171 [Obsolete ("Use AppDomainSetup.DynamicBase")]
1172 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1173 public void SetDynamicBase (string path)
1175 SetupInformationNoCopy.DynamicBase = path;
1179 [Obsolete ("AppDomain.GetCurrentThreadId has been deprecated"
1180 + " because it does not provide a stable Id when managed"
1181 + " threads are running on fibers (aka lightweight"
1182 + " threads). To get a stable identifier for a managed"
1183 + " thread, use the ManagedThreadId property on Thread.'")]
1184 public static int GetCurrentThreadId ()
1186 return Thread.CurrentThreadId;
1189 public override string ToString ()
1192 return getFriendlyName ();
1194 StringBuilder sb = new StringBuilder ("Name:");
1195 sb.AppendLine (FriendlyName);
1196 sb.AppendLine ("There are no context policies.");
1197 return sb.ToString ();
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 */
1260 ht = assembly_resolve_in_progress_refonly;
1262 ht = new Hashtable ();
1263 assembly_resolve_in_progress_refonly = ht;
1266 ht = assembly_resolve_in_progress;
1268 ht = new Hashtable ();
1269 assembly_resolve_in_progress = ht;
1273 string s = (string) ht [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 (name_or_tb is TypeBuilder)
1301 name = ((TypeBuilder) name_or_tb).FullName;
1303 name = (string) name_or_tb;
1305 /* Prevent infinite recursion */
1306 Hashtable ht = type_resolve_in_progress;
1308 ht = new Hashtable ();
1309 type_resolve_in_progress = ht;
1312 if (ht.Contains (name))
1318 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1319 ResolveEventHandler eh = (ResolveEventHandler) d;
1320 Assembly assembly = eh (this, new ResolveEventArgs (name));
1321 if (assembly != null)
1331 internal Assembly DoResourceResolve (string name, Assembly requesting) {
1332 if (ResourceResolve == null)
1335 Delegate[] invocation_list = ResourceResolve.GetInvocationList ();
1337 foreach (Delegate eh in invocation_list) {
1338 ResolveEventHandler handler = (ResolveEventHandler) eh;
1340 Assembly assembly = handler (this, new ResolveEventArgs (name, requesting));
1342 Assembly assembly = handler (this, new ResolveEventArgs (name));
1344 if (assembly != null)
1350 private void DoDomainUnload ()
1352 if (DomainUnload != null)
1353 DomainUnload(this, null);
1356 internal byte[] GetMarshalledDomainObjRef ()
1358 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1359 return CADSerializer.SerializeObject (oref).GetBuffer();
1362 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1363 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1367 if (null != arrRequest)
1368 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1370 reqDomMsg = new MethodCall (cadMsg);
1372 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1374 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1375 if (null == cadMrm) {
1376 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1382 #pragma warning restore 169
1384 // End of methods called from the runtime
1386 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1387 public event AssemblyLoadEventHandler AssemblyLoad;
1389 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1390 public event ResolveEventHandler AssemblyResolve;
1392 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1393 public event EventHandler DomainUnload;
1395 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1396 public event EventHandler ProcessExit;
1398 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1399 public event ResolveEventHandler ResourceResolve;
1401 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1402 public event ResolveEventHandler TypeResolve;
1404 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1405 public event UnhandledExceptionEventHandler UnhandledException;
1409 public bool IsHomogenous {
1410 get { return true; }
1414 public bool IsFullyTrusted {
1415 get { return true; }
1419 #pragma warning disable 649
1420 private AppDomainManager _domain_manager;
1421 #pragma warning restore 649
1424 public AppDomainManager DomainManager {
1425 get { return _domain_manager; }
1430 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1432 #pragma warning disable 649
1433 private ActivationContext _activation;
1434 private ApplicationIdentity _applicationIdentity;
1435 #pragma warning restore 649
1439 public ActivationContext ActivationContext {
1440 get { return _activation; }
1443 public ApplicationIdentity ApplicationIdentity {
1444 get { return _applicationIdentity; }
1448 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1449 get { return getDomainID (); }
1454 [MonoTODO ("This routine only returns the parameter currently")]
1455 [ComVisible (false)]
1456 public string ApplyPolicy (string assemblyName)
1458 if (assemblyName == null)
1459 throw new ArgumentNullException ("assemblyName");
1460 if (assemblyName.Length == 0) // String.Empty
1461 throw new ArgumentException ("assemblyName");
1462 return assemblyName;
1467 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1468 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1470 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1472 info.AppDomainInitializerArguments = adInitArgs;
1473 info.AppDomainInitializer = adInit;
1475 return CreateDomain (friendlyName, securityInfo, info);
1478 public int ExecuteAssemblyByName (string assemblyName)
1480 return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1484 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1486 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1488 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1492 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1494 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1496 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1498 return ExecuteAssemblyInternal (a, args);
1502 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1504 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1506 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1508 return ExecuteAssemblyInternal (a, args);
1512 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1514 Assembly a = Assembly.Load (assemblyName, null);
1516 return ExecuteAssemblyInternal (a, args);
1519 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1521 Assembly a = Assembly.Load (assemblyName, null);
1523 return ExecuteAssemblyInternal (a, args);
1527 public bool IsDefaultAppDomain ()
1529 return Object.ReferenceEquals (this, DefaultDomain);
1532 public Assembly[] ReflectionOnlyGetAssemblies ()
1534 return GetAssemblies (true);
1539 public int ExecuteAssemblyByName (string assemblyName)
1541 // critical code in SL that we're not calling in ML
1542 throw new NotImplementedException ();
1547 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1549 throw new NotImplementedException ();
1552 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1554 throw new NotImplementedException ();
1557 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1559 throw new NotImplementedException ();
1562 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1563 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1565 throw new NotImplementedException ();
1569 #if NET_4_0 || MOONLIGHT || MOBILE
1570 List<string> compatibility_switch;
1572 public bool? IsCompatibilitySwitchSet (string value)
1575 throw new ArgumentNullException ("value");
1577 // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1578 return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1581 internal void SetCompatibilitySwitch (string value)
1583 if (compatibility_switch == null)
1584 compatibility_switch = new List<string> ();
1585 compatibility_switch.Add (value);
1588 [MonoTODO ("Currently always returns false")]
1589 public static bool MonitoringIsEnabled {
1590 get { return false; }
1591 set { throw new NotImplementedException (); }
1595 public long MonitoringSurvivedMemorySize {
1596 get { throw new NotImplementedException (); }
1600 public static long MonitoringSurvivedProcessMemorySize {
1601 get { throw new NotImplementedException (); }
1605 public long MonitoringTotalAllocatedMemorySize {
1606 get { throw new NotImplementedException (); }
1610 public TimeSpan MonitoringTotalProcessorTime {
1611 get { throw new NotImplementedException (); }