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)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections;
36 using System.Globalization;
38 using System.Reflection;
39 using System.Reflection.Emit;
40 using System.Threading;
41 using System.Runtime.CompilerServices;
42 using System.Runtime.InteropServices;
43 using System.Runtime.Remoting;
44 using System.Runtime.Remoting.Contexts;
45 using System.Runtime.Remoting.Channels;
46 using System.Runtime.Remoting.Messaging;
47 using System.Security;
48 using System.Security.Permissions;
49 using System.Security.Policy;
50 using System.Security.Principal;
51 using System.Configuration.Assemblies;
53 using System.Collections.Generic;
54 using System.Runtime.ConstrainedExecution;
61 [ComDefaultInterface (typeof (_AppDomain))]
63 [ClassInterface(ClassInterfaceType.None)]
65 public sealed class AppDomain : MarshalByRefObject {
67 public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory {
69 #pragma warning disable 169
70 #region Sync with object-internals.h
71 IntPtr _mono_app_domain;
73 #pragma warning restore 169
74 static string _process_guid;
77 static Hashtable type_resolve_in_progress;
80 static Hashtable assembly_resolve_in_progress;
83 static Hashtable assembly_resolve_in_progress_refonly;
86 private Evidence _evidence;
87 private PermissionSet _granted;
90 private PrincipalPolicy _principalPolicy;
93 private static IPrincipal _principal;
95 static AppDomain default_domain;
101 [MethodImplAttribute (MethodImplOptions.InternalCall)]
102 private extern AppDomainSetup getSetup ();
107 AppDomainSetup SetupInformationNoCopy {
108 get { return getSetup (); }
111 public AppDomainSetup SetupInformation {
113 AppDomainSetup setup = getSetup ();
114 return new AppDomainSetup (setup);
120 public ApplicationTrust ApplicationTrust {
121 get { throw new NotImplementedException (); }
125 public string BaseDirectory {
127 string path = SetupInformationNoCopy.ApplicationBase;
128 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
129 // we cannot divulge local file informations
130 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
136 public string RelativeSearchPath {
138 string path = SetupInformationNoCopy.PrivateBinPath;
139 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
140 // we cannot divulge local file informations
141 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
147 public string DynamicDirectory {
149 AppDomainSetup setup = SetupInformationNoCopy;
150 if (setup.DynamicBase == null)
153 string path = Path.Combine (setup.DynamicBase, setup.ApplicationName);
154 if (SecurityManager.SecurityEnabled && (path != null) && (path.Length > 0)) {
155 // we cannot divulge local file informations
156 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, path).Demand ();
162 public bool ShadowCopyFiles {
164 return (SetupInformationNoCopy.ShadowCopyFiles == "true");
169 [MethodImplAttribute (MethodImplOptions.InternalCall)]
170 private extern string getFriendlyName ();
172 public string FriendlyName {
174 return getFriendlyName ();
178 public Evidence Evidence {
180 // if the host (runtime) hasn't provided it's own evidence...
181 if (_evidence == null) {
182 // ... we will provide our own
184 // the executed assembly from the "default" appdomain
185 // or null if we're not in the default appdomain or
186 // if there is no entry assembly (embedded mono)
187 Assembly a = Assembly.GetEntryAssembly ();
189 if (this == DefaultDomain)
191 return new Evidence ();
193 _evidence = AppDomain.DefaultDomain.Evidence;
195 _evidence = Evidence.GetDefaultHostEvidence (a);
199 return new Evidence (_evidence); // return a copy
203 internal IPrincipal DefaultPrincipal {
205 if (_principal == null) {
206 switch (_principalPolicy) {
207 case PrincipalPolicy.UnauthenticatedPrincipal:
208 _principal = new GenericPrincipal (
209 new GenericIdentity (String.Empty, String.Empty), null);
211 case PrincipalPolicy.WindowsPrincipal:
212 _principal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
220 // for AppDomain there is only an allowed (i.e. granted) set
221 // http://msdn.microsoft.com/library/en-us/cpguide/html/cpcondetermininggrantedpermissions.asp
222 internal PermissionSet GrantedPermissionSet {
223 get { return _granted; }
228 public PermissionSet PermissionSet {
229 get { return this.GrantedPermissionSet; }
233 [MethodImplAttribute (MethodImplOptions.InternalCall)]
234 private static extern AppDomain getCurDomain ();
236 public static AppDomain CurrentDomain {
238 return getCurDomain ();
242 [MethodImplAttribute (MethodImplOptions.InternalCall)]
243 private static extern AppDomain getRootDomain ();
245 internal static AppDomain DefaultDomain {
247 if (default_domain == null) {
248 AppDomain rd = getRootDomain ();
249 if (rd == CurrentDomain)
252 default_domain = (AppDomain) RemotingServices.GetDomainProxy (rd);
254 return default_domain;
260 [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
261 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
262 public void AppendPrivatePath (string path)
264 if (path == null || path.Length == 0)
267 AppDomainSetup setup = SetupInformationNoCopy;
269 string pp = setup.PrivateBinPath;
270 if (pp == null || pp.Length == 0) {
271 setup.PrivateBinPath = path;
276 if (pp [pp.Length - 1] != Path.PathSeparator)
277 pp += Path.PathSeparator;
279 setup.PrivateBinPath = pp + path;
282 [Obsolete ("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
283 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
284 public void ClearPrivatePath ()
286 SetupInformationNoCopy.PrivateBinPath = String.Empty;
289 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
290 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
291 public void ClearShadowCopyPath ()
293 SetupInformationNoCopy.ShadowCopyDirectories = String.Empty;
297 public ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
299 return Activator.CreateComInstanceFrom (assemblyName, typeName);
302 public ObjectHandle CreateComInstanceFrom (string assemblyFile, string typeName,
303 byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
305 return Activator.CreateComInstanceFrom (assemblyFile, typeName, hashValue ,hashAlgorithm);
309 public ObjectHandle CreateInstance (string assemblyName, string typeName)
311 if (assemblyName == null)
312 throw new ArgumentNullException ("assemblyName");
314 return Activator.CreateInstance (assemblyName, typeName);
317 public ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes)
319 if (assemblyName == null)
320 throw new ArgumentNullException ("assemblyName");
322 return Activator.CreateInstance (assemblyName, typeName, activationAttributes);
326 [Obsolete ("Use an overload that does not take an Evidence parameter")]
328 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
329 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes,
330 Evidence securityAttributes)
332 if (assemblyName == null)
333 throw new ArgumentNullException ("assemblyName");
335 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
336 culture, activationAttributes, securityAttributes);
339 public object CreateInstanceAndUnwrap (string assemblyName, string typeName)
341 ObjectHandle oh = CreateInstance (assemblyName, typeName);
342 return (oh != null) ? oh.Unwrap () : null;
345 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
347 ObjectHandle oh = CreateInstance (assemblyName, typeName, activationAttributes);
348 return (oh != null) ? oh.Unwrap () : null;
352 [Obsolete ("Use an overload that does not take an Evidence parameter")]
354 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
355 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
356 object[] activationAttributes, Evidence securityAttributes)
358 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
359 culture, activationAttributes, securityAttributes);
360 return (oh != null) ? oh.Unwrap () : null;
364 public ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr,
365 Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
367 if (assemblyName == null)
368 throw new ArgumentNullException ("assemblyName");
370 return Activator.CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
371 culture, activationAttributes, null);
373 public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
374 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
375 object[] activationAttributes)
377 ObjectHandle oh = CreateInstance (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
378 culture, activationAttributes);
379 return (oh != null) ? oh.Unwrap () : null;
382 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
383 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
384 object[] activationAttributes)
386 if (assemblyFile == null)
387 throw new ArgumentNullException ("assemblyFile");
389 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
390 culture, activationAttributes, null);
393 public object CreateInstanceFromAndUnwrap (string assemblyFile, string typeName, bool ignoreCase,
394 BindingFlags bindingAttr, Binder binder, object[] args,
395 CultureInfo culture, object[] activationAttributes)
397 ObjectHandle oh = CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
398 culture, activationAttributes);
400 return (oh != null) ? oh.Unwrap () : null;
404 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName)
406 if (assemblyFile == null)
407 throw new ArgumentNullException ("assemblyFile");
409 return Activator.CreateInstanceFrom (assemblyFile, typeName);
412 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, object[] activationAttributes)
414 if (assemblyFile == null)
415 throw new ArgumentNullException ("assemblyFile");
417 return Activator.CreateInstanceFrom (assemblyFile, typeName, activationAttributes);
421 [Obsolete ("Use an overload that does not take an Evidence parameter")]
423 public ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase,
424 BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture,
425 object[] activationAttributes, Evidence securityAttributes)
427 if (assemblyFile == null)
428 throw new ArgumentNullException ("assemblyFile");
430 return Activator.CreateInstanceFrom (assemblyFile, typeName, ignoreCase, bindingAttr, binder, args,
431 culture, activationAttributes, securityAttributes);
434 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName)
436 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName);
437 return (oh != null) ? oh.Unwrap () : null;
440 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, object [] activationAttributes)
442 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, activationAttributes);
443 return (oh != null) ? oh.Unwrap () : null;
447 [Obsolete ("Use an overload that does not take an Evidence parameter")]
449 public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase,
450 BindingFlags bindingAttr, Binder binder, object[] args,
451 CultureInfo culture, object[] activationAttributes,
452 Evidence securityAttributes)
454 ObjectHandle oh = CreateInstanceFrom (assemblyName, typeName, ignoreCase, bindingAttr, binder, args,
455 culture, activationAttributes, securityAttributes);
457 return (oh != null) ? oh.Unwrap () : null;
462 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
464 return DefineDynamicAssembly (name, access, null, null, null, null, null, false);
468 [Obsolete ("Declarative security for assembly level is no longer enforced")]
470 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
472 return DefineDynamicAssembly (name, access, null, evidence, null, null, null, false);
475 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir)
477 return DefineDynamicAssembly (name, access, dir, null, null, null, null, false);
481 [Obsolete ("Declarative security for assembly level is no longer enforced")]
483 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
486 return DefineDynamicAssembly (name, access, dir, evidence, null, null, null, false);
490 [Obsolete ("Declarative security for assembly level is no longer enforced")]
492 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access,
493 PermissionSet requiredPermissions,
494 PermissionSet optionalPermissions,
495 PermissionSet refusedPermissions)
497 return DefineDynamicAssembly (name, access, null, null, requiredPermissions, optionalPermissions,
498 refusedPermissions, false);
502 [Obsolete ("Declarative security for assembly level is no longer enforced")]
504 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, Evidence evidence,
505 PermissionSet requiredPermissions,
506 PermissionSet optionalPermissions,
507 PermissionSet refusedPermissions)
509 return DefineDynamicAssembly (name, access, null, evidence, requiredPermissions, optionalPermissions,
510 refusedPermissions, false);
514 [Obsolete ("Declarative security for assembly level is no longer enforced")]
516 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
517 PermissionSet requiredPermissions,
518 PermissionSet optionalPermissions,
519 PermissionSet refusedPermissions)
521 return DefineDynamicAssembly (name, access, dir, null, requiredPermissions, optionalPermissions,
522 refusedPermissions, false);
526 [Obsolete ("Declarative security for assembly level is no longer enforced")]
528 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
530 PermissionSet requiredPermissions,
531 PermissionSet optionalPermissions,
532 PermissionSet refusedPermissions)
534 return DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions,
535 refusedPermissions, false);
539 [Obsolete ("Declarative security for assembly level is no longer enforced")]
541 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
543 PermissionSet requiredPermissions,
544 PermissionSet optionalPermissions,
545 PermissionSet refusedPermissions, bool isSynchronized)
548 throw new ArgumentNullException ("name");
549 ValidateAssemblyName (name.Name);
551 // FIXME: examine all other parameters
553 AssemblyBuilder ab = new AssemblyBuilder (name, dir, access, false);
554 ab.AddPermissionRequests (requiredPermissions, optionalPermissions, refusedPermissions);
560 [Obsolete ("Declarative security for assembly level is no longer enforced")]
562 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir,
564 PermissionSet requiredPermissions,
565 PermissionSet optionalPermissions,
566 PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
568 AssemblyBuilder ab = DefineDynamicAssembly (name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, isSynchronized);
569 if (assemblyAttributes != null)
570 foreach (CustomAttributeBuilder cb in assemblyAttributes) {
571 ab.SetCustomAttribute (cb);
577 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
579 return DefineDynamicAssembly (name, access, null, null, null, null, null, false, assemblyAttributes);
583 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<CustomAttributeBuilder> assemblyAttributes)
585 return DefineDynamicAssembly (name, access, dir, null, null, null, null, isSynchronized, assemblyAttributes);
588 [MonoLimitation ("The argument securityContextSource is ignored")]
589 public AssemblyBuilder DefineDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes, SecurityContextSource securityContextSource)
591 return DefineDynamicAssembly (name, access, assemblyAttributes);
595 internal AssemblyBuilder DefineInternalDynamicAssembly (AssemblyName name, AssemblyBuilderAccess access)
597 return new AssemblyBuilder (name, null, access, true);
601 // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject
602 // so, when you call AppDomain.DoCallBack, that's a remote call
604 public void DoCallBack (CrossAppDomainDelegate callBackDelegate)
606 if (callBackDelegate != null)
610 public int ExecuteAssembly (string assemblyFile)
612 return ExecuteAssembly (assemblyFile, (Evidence)null, null);
616 [Obsolete ("Use an overload that does not take an Evidence parameter")]
618 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity)
620 return ExecuteAssembly (assemblyFile, assemblySecurity, null);
624 [Obsolete ("Use an overload that does not take an Evidence parameter")]
626 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args)
628 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity);
629 return ExecuteAssemblyInternal (a, args);
633 [Obsolete ("Use an overload that does not take an Evidence parameter")]
635 public int ExecuteAssembly (string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
637 Assembly a = Assembly.LoadFrom (assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
638 return ExecuteAssemblyInternal (a, args);
643 public int ExecuteAssembly (string assemblyFile, string[] args)
645 Assembly a = Assembly.LoadFrom (assemblyFile, null);
646 return ExecuteAssemblyInternal (a, args);
649 public int ExecuteAssembly (string assemblyFile, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
651 Assembly a = Assembly.LoadFrom (assemblyFile, null, hashValue, hashAlgorithm);
652 return ExecuteAssemblyInternal (a, args);
656 int ExecuteAssemblyInternal (Assembly a, string[] args)
658 if (a.EntryPoint == null)
659 throw new MissingMethodException ("Entry point not found in assembly '" + a.FullName + "'.");
660 return ExecuteAssembly (a, args);
663 [MethodImplAttribute (MethodImplOptions.InternalCall)]
664 private extern int ExecuteAssembly (Assembly a, string[] args);
666 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667 private extern Assembly [] GetAssemblies (bool refOnly);
669 public Assembly [] GetAssemblies ()
671 return GetAssemblies (false);
674 [MethodImplAttribute (MethodImplOptions.InternalCall)]
675 public extern object GetData (string name);
677 public new Type GetType()
679 return base.GetType ();
682 public override object InitializeLifetimeService ()
687 [MethodImplAttribute (MethodImplOptions.InternalCall)]
688 internal extern Assembly LoadAssembly (string assemblyRef, Evidence securityEvidence, bool refOnly);
690 public Assembly Load (AssemblyName assemblyRef)
692 return Load (assemblyRef, null);
695 internal Assembly LoadSatellite (AssemblyName assemblyRef, bool throwOnError)
697 if (assemblyRef == null)
698 throw new ArgumentNullException ("assemblyRef");
700 Assembly result = LoadAssembly (assemblyRef.FullName, null, false);
701 if (result == null && throwOnError)
702 throw new FileNotFoundException (null, assemblyRef.Name);
707 [Obsolete ("Use an overload that does not take an Evidence parameter")]
709 public Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
711 if (assemblyRef == null)
712 throw new ArgumentNullException ("assemblyRef");
714 if (assemblyRef.Name == null || assemblyRef.Name.Length == 0) {
715 if (assemblyRef.CodeBase != null)
716 return Assembly.LoadFrom (assemblyRef.CodeBase, assemblySecurity);
718 throw new ArgumentException (Locale.GetText ("assemblyRef.Name cannot be empty."), "assemblyRef");
721 Assembly assembly = LoadAssembly (assemblyRef.FullName, assemblySecurity, false);
722 if (assembly != null)
725 if (assemblyRef.CodeBase == null)
726 throw new FileNotFoundException (null, assemblyRef.Name);
728 string cb = assemblyRef.CodeBase;
729 if (cb.ToLower (CultureInfo.InvariantCulture).StartsWith ("file://"))
730 cb = new Mono.Security.Uri (cb).LocalPath;
733 assembly = Assembly.LoadFrom (cb, assemblySecurity);
735 throw new FileNotFoundException (null, assemblyRef.Name);
737 AssemblyName aname = assembly.GetName ();
738 // Name, version, culture, publickeytoken. Anything else?
739 if (assemblyRef.Name != aname.Name)
740 throw new FileNotFoundException (null, assemblyRef.Name);
742 if (assemblyRef.Version != new Version () && assemblyRef.Version != aname.Version)
743 throw new FileNotFoundException (null, assemblyRef.Name);
745 if (assemblyRef.CultureInfo != null && assemblyRef.CultureInfo.Equals (aname))
746 throw new FileNotFoundException (null, assemblyRef.Name);
748 byte [] pt = assemblyRef.GetPublicKeyToken ();
750 byte [] loaded_pt = aname.GetPublicKeyToken ();
751 if (loaded_pt == null || (pt.Length != loaded_pt.Length))
752 throw new FileNotFoundException (null, assemblyRef.Name);
753 for (int i = pt.Length - 1; i >= 0; i--)
754 if (loaded_pt [i] != pt [i])
755 throw new FileNotFoundException (null, assemblyRef.Name);
760 public Assembly Load (string assemblyString)
762 return Load (assemblyString, null, false);
766 [Obsolete ("Use an overload that does not take an Evidence parameter")]
768 public Assembly Load (string assemblyString, Evidence assemblySecurity)
770 return Load (assemblyString, assemblySecurity, false);
773 internal Assembly Load (string assemblyString, Evidence assemblySecurity, bool refonly)
775 if (assemblyString == null)
776 throw new ArgumentNullException ("assemblyString");
778 if (assemblyString.Length == 0)
779 throw new ArgumentException ("assemblyString cannot have zero length");
781 Assembly assembly = LoadAssembly (assemblyString, assemblySecurity, refonly);
782 if (assembly == null)
783 throw new FileNotFoundException (null, assemblyString);
787 public Assembly Load (byte[] rawAssembly)
789 return Load (rawAssembly, null, null);
792 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
794 return Load (rawAssembly, rawSymbolStore, null);
797 [MethodImplAttribute (MethodImplOptions.InternalCall)]
798 internal extern Assembly LoadAssemblyRaw (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence, bool refonly);
801 [Obsolete ("Use an overload that does not take an Evidence parameter")]
803 public Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
805 return Load (rawAssembly, rawSymbolStore, securityEvidence, false);
808 internal Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, Evidence securityEvidence, bool refonly)
810 if (rawAssembly == null)
811 throw new ArgumentNullException ("rawAssembly");
813 Assembly assembly = LoadAssemblyRaw (rawAssembly, rawSymbolStore, securityEvidence, refonly);
814 assembly.FromByteArray = true;
819 [Obsolete ("AppDomain policy levels are obsolete")]
821 [SecurityPermission (SecurityAction.Demand, ControlPolicy = true)]
822 public void SetAppDomainPolicy (PolicyLevel domainPolicy)
824 if (domainPolicy == null)
825 throw new ArgumentNullException ("domainPolicy");
826 if (_granted != null) {
827 throw new PolicyException (Locale.GetText (
828 "An AppDomain policy is already specified."));
830 if (IsFinalizingForUnload ())
831 throw new AppDomainUnloadedException ();
833 PolicyStatement ps = domainPolicy.Resolve (_evidence);
834 _granted = ps.PermissionSet;
837 [Obsolete ("Use AppDomainSetup.SetCachePath")]
838 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
839 public void SetCachePath (string path)
841 SetupInformationNoCopy.CachePath = path;
844 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
845 public void SetPrincipalPolicy (PrincipalPolicy policy)
847 if (IsFinalizingForUnload ())
848 throw new AppDomainUnloadedException ();
850 _principalPolicy = policy;
854 [Obsolete ("Use AppDomainSetup.ShadowCopyFiles")]
855 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
856 public void SetShadowCopyFiles()
858 SetupInformationNoCopy.ShadowCopyFiles = "true";
861 [Obsolete ("Use AppDomainSetup.ShadowCopyDirectories")]
862 [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
863 public void SetShadowCopyPath (string path)
865 SetupInformationNoCopy.ShadowCopyDirectories = path;
868 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
869 public void SetThreadPrincipal (IPrincipal principal)
871 if (principal == null)
872 throw new ArgumentNullException ("principal");
873 if (_principal != null)
874 throw new PolicyException (Locale.GetText ("principal already present."));
875 if (IsFinalizingForUnload ())
876 throw new AppDomainUnloadedException ();
878 _principal = principal;
881 [MethodImplAttribute (MethodImplOptions.InternalCall)]
882 private static extern AppDomain InternalSetDomainByID (int domain_id);
884 // Changes the active domain and returns the old domain
885 [MethodImplAttribute (MethodImplOptions.InternalCall)]
886 private static extern AppDomain InternalSetDomain (AppDomain context);
888 // Notifies the runtime that this thread references 'domain'.
889 [MethodImplAttribute (MethodImplOptions.InternalCall)]
890 internal static extern void InternalPushDomainRef (AppDomain domain);
892 [MethodImplAttribute (MethodImplOptions.InternalCall)]
893 internal static extern void InternalPushDomainRefByID (int domain_id);
895 // Undoes the effect of the last PushDomainRef call
896 [MethodImplAttribute (MethodImplOptions.InternalCall)]
897 internal static extern void InternalPopDomainRef ();
899 // Changes the active context and returns the old context
900 [MethodImplAttribute (MethodImplOptions.InternalCall)]
901 internal static extern Context InternalSetContext (Context context);
903 // Returns the current context
904 [MethodImplAttribute (MethodImplOptions.InternalCall)]
905 internal static extern Context InternalGetContext ();
907 // Returns the current context
908 [MethodImplAttribute (MethodImplOptions.InternalCall)]
909 internal static extern Context InternalGetDefaultContext ();
911 [MethodImplAttribute (MethodImplOptions.InternalCall)]
912 internal static extern string InternalGetProcessGuid (string newguid);
914 // This method is handled specially by the runtime
915 // It is the only managed method which is allowed to set the current
917 internal static object InvokeInDomain (AppDomain domain, MethodInfo method, object obj, object [] args)
919 AppDomain current = CurrentDomain;
924 InternalPushDomainRef (domain);
926 InternalSetDomain (domain);
927 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
933 InternalSetDomain (current);
935 InternalPopDomainRef ();
939 internal static object InvokeInDomainByID (int domain_id, MethodInfo method, object obj, object [] args)
941 AppDomain current = CurrentDomain;
946 InternalPushDomainRefByID (domain_id);
948 InternalSetDomainByID (domain_id);
949 object o = ((MonoMethod) method).InternalInvoke (obj, args, out exc);
955 InternalSetDomain (current);
957 InternalPopDomainRef ();
961 internal static String GetProcessGuid ()
963 if (_process_guid == null) {
964 _process_guid = InternalGetProcessGuid (Guid.NewGuid().ToString ());
966 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 ?? new StrongName [0]);
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";
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 ()
1180 return getFriendlyName ();
1182 StringBuilder sb = new StringBuilder ("Name:");
1183 sb.AppendLine (FriendlyName);
1184 sb.AppendLine ("There are no context policies.");
1185 return sb.ToString ();
1189 private static void ValidateAssemblyName (string name)
1191 if (name == null || name.Length == 0)
1192 throw new ArgumentException ("The Name of " +
1193 "AssemblyName cannot be null or a " +
1194 "zero-length string.");
1196 bool isValid = true;
1198 for (int i = 0; i < name.Length; i++) {
1201 // do not allow leading whitespace
1202 if (i == 0 && char.IsWhiteSpace (c)) {
1207 // do not allow /,\ or : in name
1208 if (c == '/' || c == '\\' || c == ':') {
1215 throw new ArgumentException ("The Name of " +
1216 "AssemblyName cannot start with " +
1217 "whitespace, or contain '/', '\\' " +
1221 // The following methods are called from the runtime. Don't change signatures.
1222 #pragma warning disable 169
1223 private void DoAssemblyLoad (Assembly assembly)
1225 if (AssemblyLoad == null)
1228 AssemblyLoad (this, new AssemblyLoadEventArgs (assembly));
1231 private Assembly DoAssemblyResolve (string name, bool refonly)
1233 ResolveEventHandler del;
1236 del = ReflectionOnlyAssemblyResolve;
1238 del = AssemblyResolve;
1240 del = AssemblyResolve;
1245 /* Prevent infinite recursion */
1248 ht = assembly_resolve_in_progress_refonly;
1250 ht = new Hashtable ();
1251 assembly_resolve_in_progress_refonly = ht;
1254 ht = assembly_resolve_in_progress;
1256 ht = new Hashtable ();
1257 assembly_resolve_in_progress = ht;
1261 string s = (string) ht [name];
1266 Delegate[] invocation_list = del.GetInvocationList ();
1268 foreach (Delegate eh in invocation_list) {
1269 ResolveEventHandler handler = (ResolveEventHandler) eh;
1270 Assembly assembly = handler (this, new ResolveEventArgs (name));
1271 if (assembly != null)
1281 internal Assembly DoTypeResolve (Object name_or_tb)
1283 if (TypeResolve == null)
1288 if (name_or_tb is TypeBuilder)
1289 name = ((TypeBuilder) name_or_tb).FullName;
1291 name = (string) name_or_tb;
1293 /* Prevent infinite recursion */
1294 Hashtable ht = type_resolve_in_progress;
1296 ht = new Hashtable ();
1297 type_resolve_in_progress = ht;
1300 if (ht.Contains (name))
1306 foreach (Delegate d in TypeResolve.GetInvocationList ()) {
1307 ResolveEventHandler eh = (ResolveEventHandler) d;
1308 Assembly assembly = eh (this, new ResolveEventArgs (name));
1309 if (assembly != null)
1319 private void DoDomainUnload ()
1321 if (DomainUnload != null)
1322 DomainUnload(this, null);
1326 internal byte[] GetMarshalledDomainObjRef ()
1328 ObjRef oref = RemotingServices.Marshal (AppDomain.CurrentDomain, null, typeof (AppDomain));
1329 return CADSerializer.SerializeObject (oref).GetBuffer();
1332 internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg,
1333 out byte[] arrResponse, out CADMethodReturnMessage cadMrm)
1337 if (null != arrRequest)
1338 reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null);
1340 reqDomMsg = new MethodCall (cadMsg);
1342 IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg);
1344 cadMrm = CADMethodReturnMessage.Create (retDomMsg);
1345 if (null == cadMrm) {
1346 arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer();
1352 #pragma warning restore 169
1354 // End of methods called from the runtime
1356 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1357 public event AssemblyLoadEventHandler AssemblyLoad;
1359 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1360 public event ResolveEventHandler AssemblyResolve;
1362 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1363 public event EventHandler DomainUnload;
1365 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1366 public event EventHandler ProcessExit;
1368 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1369 public event ResolveEventHandler ResourceResolve;
1371 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1372 public event ResolveEventHandler TypeResolve;
1374 [method: SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
1375 public event UnhandledExceptionEventHandler UnhandledException;
1377 #if NET_4_0 || BOOTSTRAP_NET_4_0
1379 public bool IsHomogenous {
1380 get { return true; }
1384 public bool IsFullyTrusted {
1385 get { return true; }
1389 #pragma warning disable 649
1390 private AppDomainManager _domain_manager;
1391 #pragma warning restore 649
1394 public AppDomainManager DomainManager {
1395 get { return _domain_manager; }
1400 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
1402 #pragma warning disable 649
1403 private ActivationContext _activation;
1404 private ApplicationIdentity _applicationIdentity;
1405 #pragma warning restore 649
1409 public ActivationContext ActivationContext {
1410 get { return _activation; }
1413 public ApplicationIdentity ApplicationIdentity {
1414 get { return _applicationIdentity; }
1418 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1419 get { return getDomainID (); }
1424 [MonoTODO ("This routine only returns the parameter currently")]
1425 [ComVisible (false)]
1426 public string ApplyPolicy (string assemblyName)
1428 if (assemblyName == null)
1429 throw new ArgumentNullException ("assemblyName");
1430 if (assemblyName.Length == 0) // String.Empty
1431 throw new ArgumentException ("assemblyName");
1432 return assemblyName;
1437 public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, string appBasePath,
1438 string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
1440 AppDomainSetup info = CreateDomainSetup (appBasePath, appRelativeSearchPath, shadowCopyFiles);
1442 info.AppDomainInitializerArguments = adInitArgs;
1443 info.AppDomainInitializer = adInit;
1445 return CreateDomain (friendlyName, securityInfo, info);
1448 public int ExecuteAssemblyByName (string assemblyName)
1450 return ExecuteAssemblyByName (assemblyName, (Evidence)null, null);
1454 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1456 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity)
1458 return ExecuteAssemblyByName (assemblyName, assemblySecurity, null);
1462 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1464 public int ExecuteAssemblyByName (string assemblyName, Evidence assemblySecurity, params string[] args)
1466 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1468 return ExecuteAssemblyInternal (a, args);
1472 [Obsolete ("Use an overload that does not take an Evidence parameter")]
1474 public int ExecuteAssemblyByName (AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
1476 Assembly a = Assembly.Load (assemblyName, assemblySecurity);
1478 return ExecuteAssemblyInternal (a, args);
1482 public int ExecuteAssemblyByName (string assemblyName, params string[] args)
1484 Assembly a = Assembly.Load (assemblyName, null);
1486 return ExecuteAssemblyInternal (a, args);
1489 public int ExecuteAssemblyByName (AssemblyName assemblyName, params string[] args)
1491 Assembly a = Assembly.Load (assemblyName, null);
1493 return ExecuteAssemblyInternal (a, args);
1497 public bool IsDefaultAppDomain ()
1499 return Object.ReferenceEquals (this, DefaultDomain);
1502 public Assembly[] ReflectionOnlyGetAssemblies ()
1504 return GetAssemblies (true);
1509 public int ExecuteAssemblyByName (string assemblyName)
1511 // critical code in SL that we're not calling in ML
1512 throw new NotImplementedException ();
1517 void _AppDomain.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1519 throw new NotImplementedException ();
1522 void _AppDomain.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1524 throw new NotImplementedException ();
1527 void _AppDomain.GetTypeInfoCount (out uint pcTInfo)
1529 throw new NotImplementedException ();
1532 void _AppDomain.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1533 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1535 throw new NotImplementedException ();
1539 #if NET_4_0 || MOONLIGHT
1540 List<string> compatibility_switch;
1542 public bool? IsCompatibilitySwitchSet (string value)
1545 throw new ArgumentNullException ("value");
1547 // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
1548 return ((compatibility_switch != null) && compatibility_switch.Contains (value));
1551 internal void SetCompatibilitySwitch (string value)
1553 if (compatibility_switch == null)
1554 compatibility_switch = new List<string> ();
1555 compatibility_switch.Add (value);
1558 [MonoTODO ("Currently always returns false")]
1559 public static bool MonitoringIsEnabled {
1560 get { return false; }
1561 set { throw new NotImplementedException (); }
1565 public long MonitoringSurvivedMemorySize {
1566 get { throw new NotImplementedException (); }
1570 public static long MonitoringSurvivedProcessMemorySize {
1571 get { throw new NotImplementedException (); }
1575 public long MonitoringTotalAllocatedMemorySize {
1576 get { throw new NotImplementedException (); }
1580 public TimeSpan MonitoringTotalProcessorTime {
1581 get { throw new NotImplementedException (); }