3 // Copyright (c) Microsoft Corporation. All rights reserved.
6 /*=============================================================================
10 ** <OWNER>[....]</OWNER>
13 ** Purpose: Domains represent an application within the runtime. Objects can
14 ** not be shared between domains and each domain can be configured
18 =============================================================================*/
23 using System.Deployment.Internal.Isolation;
24 using System.Deployment.Internal.Isolation.Manifest;
25 using System.Runtime.Hosting;
27 using System.Reflection;
29 using System.Runtime.CompilerServices;
31 using System.Runtime.Remoting.Channels;
32 using System.Runtime.Remoting.Contexts;
34 using System.Security;
35 using System.Security.Permissions;
36 using System.Security.Principal;
37 using System.Security.Policy;
38 using System.Security.Util;
39 using System.Collections;
40 using System.Collections.Generic;
41 using System.Threading;
42 using System.Runtime.InteropServices;
43 using System.Runtime.Remoting;
45 using Context = System.Runtime.Remoting.Contexts.Context;
47 using System.Reflection.Emit;
48 using CultureInfo = System.Globalization.CultureInfo;
50 using System.Globalization;
53 using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
55 using Microsoft.Win32;
56 using System.Runtime.ConstrainedExecution;
57 using System.Runtime.Versioning;
58 using System.Diagnostics.Contracts;
59 #if FEATURE_EXCEPTION_NOTIFICATIONS
60 using System.Runtime.ExceptionServices;
61 #endif // FEATURE_EXCEPTION_NOTIFICATIONS
64 public class ResolveEventArgs : EventArgs
67 private Assembly _RequestingAssembly;
75 public Assembly RequestingAssembly
79 return _RequestingAssembly;
83 public ResolveEventArgs(String name)
88 public ResolveEventArgs(String name, Assembly requestingAssembly)
91 _RequestingAssembly = requestingAssembly;
96 public class AssemblyLoadEventArgs : EventArgs
98 private Assembly _LoadedAssembly;
100 public Assembly LoadedAssembly {
102 return _LoadedAssembly;
106 public AssemblyLoadEventArgs(Assembly loadedAssembly)
108 _LoadedAssembly = loadedAssembly;
114 [System.Security.SecurityCritical] // auto-generated
118 public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
122 public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args);
126 public delegate void AppDomainInitializer(string[] args);
128 internal class AppDomainInitializerInfo
130 internal class ItemInfo
132 public string TargetTypeAssembly;
133 public string TargetTypeName;
134 public string MethodName;
137 internal ItemInfo[] Info;
139 internal AppDomainInitializerInfo(AppDomainInitializer init)
144 List<ItemInfo> itemInfo = new List<ItemInfo>();
145 List<AppDomainInitializer> nestedDelegates = new List<AppDomainInitializer>();
146 nestedDelegates.Add(init);
149 while (nestedDelegates.Count>idx)
151 AppDomainInitializer curr = nestedDelegates[idx++];
152 Delegate[] list= curr.GetInvocationList();
153 for (int i=0;i<list.Length;i++)
155 if (!list[i].Method.IsStatic)
157 if(list[i].Target==null)
160 AppDomainInitializer nested = list[i].Target as AppDomainInitializer;
162 nestedDelegates.Add(nested);
164 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"),
165 list[i].Method.ReflectedType.FullName+"::"+list[i].Method.Name);
169 ItemInfo info=new ItemInfo();
170 info.TargetTypeAssembly=list[i].Method.ReflectedType.Module.Assembly.FullName;
171 info.TargetTypeName=list[i].Method.ReflectedType.FullName;
172 info.MethodName=list[i].Method.Name;
179 Info = itemInfo.ToArray();
182 [System.Security.SecuritySafeCritical] // auto-generated
183 internal AppDomainInitializer Unwrap()
187 AppDomainInitializer retVal=null;
188 new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
189 for (int i=0;i<Info.Length;i++)
191 Assembly assembly=Assembly.Load(Info[i].TargetTypeAssembly);
192 AppDomainInitializer newVal=(AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer),
193 assembly.GetType(Info[i].TargetTypeName),
205 [ClassInterface(ClassInterfaceType.None)]
206 [ComDefaultInterface(typeof(System._AppDomain))]
208 public sealed class AppDomain :
212 _AppDomain, IEvidenceFactory
214 // Domain security information
215 // These fields initialized from the other side only. (NOTE: order
216 // of these fields cannot be changed without changing the layout in
219 [System.Security.SecurityCritical] // auto-generated
220 private AppDomainManager _domainManager;
221 private Dictionary<String, Object[]> _LocalStore;
222 private AppDomainSetup _FusionStore;
223 private Evidence _SecurityIdentity;
224 #pragma warning disable 169
225 private Object[] _Policies; // Called from the VM.
226 #pragma warning restore 169
227 [method: System.Security.SecurityCritical]
228 public event AssemblyLoadEventHandler AssemblyLoad;
230 [System.Security.SecurityCritical]
231 private ResolveEventHandler _TypeResolve;
233 public event ResolveEventHandler TypeResolve
235 [System.Security.SecurityCritical]
240 _TypeResolve += value;
244 [System.Security.SecurityCritical]
249 _TypeResolve -= value;
254 [System.Security.SecurityCritical]
255 private ResolveEventHandler _ResourceResolve;
257 public event ResolveEventHandler ResourceResolve
259 [System.Security.SecurityCritical]
264 _ResourceResolve += value;
268 [System.Security.SecurityCritical]
273 _ResourceResolve -= value;
278 [System.Security.SecurityCritical]
279 private ResolveEventHandler _AssemblyResolve;
281 public event ResolveEventHandler AssemblyResolve
283 [System.Security.SecurityCritical]
288 _AssemblyResolve += value;
292 [System.Security.SecurityCritical]
297 _AssemblyResolve -= value;
302 #if FEATURE_REFLECTION_ONLY_LOAD
303 [method: System.Security.SecurityCritical]
304 public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
305 #endif // FEATURE_REFLECTION_ONLY
308 private Context _DefaultContext;
312 #if FEATURE_CLICKONCE
313 private ActivationContext _activationContext;
314 private ApplicationIdentity _applicationIdentity;
316 #endif // !FEATURE_PAL
317 private ApplicationTrust _applicationTrust;
319 #if FEATURE_IMPERSONATION
320 private IPrincipal _DefaultPrincipal;
321 #endif // FEATURE_IMPERSONATION
323 private DomainSpecificRemotingData _RemotingData;
325 private EventHandler _processExit;
328 [System.Security.SecurityCritical]
330 private EventHandler _domainUnload;
333 [System.Security.SecurityCritical] // auto-generated
335 private UnhandledExceptionEventHandler _unhandledException;
338 private String[] _aptcaVisibleAssemblies;
341 // The compat flags are set at domain creation time to indicate that the given breaking
342 // changes (named in the strings) should not be used in this domain. We only use the
343 // keys, the vhe values are ignored.
344 private Dictionary<String, object> _compatFlags;
346 #if FEATURE_EXCEPTION_NOTIFICATIONS
347 // Delegate that will hold references to FirstChance exception notifications
348 private EventHandler<FirstChanceExceptionEventArgs> _firstChanceException;
349 #endif // FEATURE_EXCEPTION_NOTIFICATIONS
351 private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
353 #if FEATURE_CAS_POLICY
354 private PrincipalPolicy _PrincipalPolicy; // this is an enum
356 private bool _HasSetPolicy;
357 private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous
358 private bool _compatFlagsInitialized;
360 internal const String TargetFrameworkNameAppCompatSetting = "TargetFrameworkName";
363 private static APPX_FLAGS s_flags;
366 // Keep in async with vm\appdomainnative.cpp
369 private enum APPX_FLAGS
371 APPX_FLAGS_INITIALIZED = 0x01,
373 APPX_FLAGS_APPX_MODEL = 0x02,
374 APPX_FLAGS_APPX_DESIGN_MODE = 0x04,
375 APPX_FLAGS_APPX_NGEN = 0x08,
376 APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL |
377 APPX_FLAGS_APPX_DESIGN_MODE |
378 APPX_FLAGS_APPX_NGEN,
380 APPX_FLAGS_API_CHECK = 0x10,
383 private static APPX_FLAGS Flags
385 [SecuritySafeCritical]
389 s_flags = nGetAppXFlags();
391 Contract.Assert(s_flags != 0);
396 internal static bool ProfileAPICheck
398 [SecuritySafeCritical]
401 return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0;
405 internal static bool IsAppXNGen
407 [SecuritySafeCritical]
410 return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0;
413 #endif // FEATURE_APPX
415 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
417 [ResourceExposure(ResourceScope.None)]
418 [SuppressUnmanagedCodeSecurity]
419 [return: MarshalAs(UnmanagedType.Bool)]
420 private static extern bool DisableFusionUpdatesFromADManager(AppDomainHandle domain);
423 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
425 [ResourceExposure(ResourceScope.None)]
426 [SuppressUnmanagedCodeSecurity]
427 [return: MarshalAs(UnmanagedType.I4)]
428 private static extern APPX_FLAGS nGetAppXFlags();
431 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
433 [ResourceExposure(ResourceScope.None)]
434 [SuppressUnmanagedCodeSecurity]
435 private static extern void GetAppDomainManagerType(AppDomainHandle domain,
436 StringHandleOnStack retAssembly,
437 StringHandleOnStack retType);
439 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
441 [ResourceExposure(ResourceScope.None)]
442 [SuppressUnmanagedCodeSecurity]
443 private static extern void SetAppDomainManagerType(AppDomainHandle domain,
447 [System.Security.SecurityCritical] // auto-generated
448 [ResourceExposure(ResourceScope.None)]
449 [MethodImplAttribute(MethodImplOptions.InternalCall)]
450 private static extern void nSetHostSecurityManagerFlags (HostSecurityManagerOptions flags);
453 [SuppressUnmanagedCodeSecurity]
454 [ResourceExposure(ResourceScope.None)]
455 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
456 private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain,
457 [MarshalAs(UnmanagedType.Bool)] bool runtimeSuppliedHomogenousGrantSet);
459 #if FEATURE_CAS_POLICY
461 [SuppressUnmanagedCodeSecurity]
462 [ResourceExposure(ResourceScope.None)]
463 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
464 private static extern void SetLegacyCasPolicyEnabled(AppDomainHandle domain);
467 private void SetLegacyCasPolicyEnabled()
469 SetLegacyCasPolicyEnabled(GetNativeHandle());
471 #endif // FEATURE_CAS_POLICY
474 /// Get a handle used to make a call into the VM pointing to this domain
476 internal AppDomainHandle GetNativeHandle()
478 // This should never happen under normal circumstances. However, there ar ways to create an
479 // uninitialized object through remoting, etc.
480 if (_pDomain.IsNull())
482 throw new InvalidOperationException(Environment.GetResourceString("Argument_InvalidHandle"));
486 BCLDebug.Assert(!RemotingServices.IsTransparentProxy(this), "QCalls should be made with the real AppDomain object rather than a transparent proxy");
487 #endif // FEATURE_REMOTING
488 return new AppDomainHandle(_pDomain);
492 /// If this AppDomain is configured to have an AppDomain manager then create the instance of it.
493 /// This method is also called from the VM to create the domain manager in the default domain.
495 [SecuritySafeCritical]
496 private void CreateAppDomainManager()
498 Contract.Assert(_domainManager == null, "_domainManager == null");
500 AppDomainSetup adSetup = FusionStore;
501 #if FEATURE_VERSIONING
502 String trustedPlatformAssemblies = (String)(GetData("TRUSTED_PLATFORM_ASSEMBLIES"));
503 if (trustedPlatformAssemblies != null)
505 String platformResourceRoots = (String)(GetData("PLATFORM_RESOURCE_ROOTS"));
506 if (platformResourceRoots == null)
508 platformResourceRoots = String.Empty;
511 String appPaths = (String)(GetData("APP_PATHS"));
512 if (appPaths == null)
514 appPaths = String.Empty;
517 String appNiPaths = (String)(GetData("APP_NI_PATHS"));
518 if (appNiPaths == null)
520 appNiPaths = String.Empty;
523 String appLocalWinMD = (String)(GetData("APP_LOCAL_WINMETADATA"));
524 if (appLocalWinMD == null)
526 appLocalWinMD = String.Empty;
528 SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD);
530 #endif // FEATURE_VERSIONING
532 string domainManagerAssembly;
533 string domainManagerType;
534 GetAppDomainManagerType(out domainManagerAssembly, out domainManagerType);
536 if (domainManagerAssembly != null && domainManagerType != null)
540 new PermissionSet(PermissionState.Unrestricted).Assert();
541 _domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager;
542 CodeAccessPermission.RevertAssert();
544 catch (FileNotFoundException e)
546 throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
548 catch (SecurityException e)
550 throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
552 catch (TypeLoadException e)
554 throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
557 if (_domainManager == null)
559 throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"));
562 // If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup
563 // will not have the correct values for the AppDomainManager set.
564 FusionStore.AppDomainManagerAssembly = domainManagerAssembly;
565 FusionStore.AppDomainManagerType = domainManagerType;
567 bool notifyFusion = _domainManager.GetType() != typeof(System.AppDomainManager) && !DisableFusionUpdatesFromADManager();
571 AppDomainSetup FusionStoreOld = null;
573 FusionStoreOld = new AppDomainSetup(FusionStore, true);
575 // Initialize the AppDomainMAnager and register the instance with the native host if requested
576 _domainManager.InitializeNewDomain(FusionStore);
579 SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object.
581 #if FEATURE_APPDOMAINMANAGER_INITOPTIONS
582 AppDomainManagerInitializationOptions flags = _domainManager.InitializationFlags;
583 if ((flags & AppDomainManagerInitializationOptions.RegisterWithHost) == AppDomainManagerInitializationOptions.RegisterWithHost)
585 _domainManager.RegisterWithHost();
587 #endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
590 InitializeCompatibilityFlags();
594 /// Initialize the compatibility flags to non-NULL values.
595 /// This method is also called from the VM when the default domain dosen't have a domain manager.
597 private void InitializeCompatibilityFlags()
599 AppDomainSetup adSetup = FusionStore;
601 // set up shim flags regardless of whether we create a DomainManager in this method.
602 if (adSetup.GetCompatibilityFlags() != null)
604 _compatFlags = new Dictionary<String, object>(adSetup.GetCompatibilityFlags(), StringComparer.OrdinalIgnoreCase);
607 // for perf, we don't intialize the _compatFlags dictionary when we don't need to. However, we do need to make a
608 // note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the
609 // case where the compat flags have been setup.
610 Contract.Assert(!_compatFlagsInitialized);
611 _compatFlagsInitialized = true;
613 CompatibilitySwitches.InitializeSwitches();
616 // Retrieves a possibly-cached target framework name for this appdomain. This could be set
617 // either by a host in native, a host in managed using an AppDomainSetup, or by the
618 // TargetFrameworkAttribute on the executable (VS emits its target framework moniker using this
619 // attribute starting in version 4).
620 [SecuritySafeCritical]
621 internal String GetTargetFrameworkName()
623 String targetFrameworkName = _FusionStore.TargetFrameworkName;
625 if (targetFrameworkName == null && IsDefaultAppDomain() && !_FusionStore.CheckedForTargetFrameworkName)
627 // This should only be run in the default appdomain. All other appdomains should have
628 // values copied from the default appdomain and/or specified by the host.
629 Assembly assembly = Assembly.GetEntryAssembly();
630 if (assembly != null)
632 TargetFrameworkAttribute[] attrs = (TargetFrameworkAttribute[])assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute));
633 if (attrs != null && attrs.Length > 0)
635 Contract.Assert(attrs.Length == 1);
636 targetFrameworkName = attrs[0].FrameworkName;
637 _FusionStore.TargetFrameworkName = targetFrameworkName;
640 _FusionStore.CheckedForTargetFrameworkName = true;
643 return targetFrameworkName;
647 /// Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact).
649 [SecuritySafeCritical]
650 internal bool DisableFusionUpdatesFromADManager()
652 return DisableFusionUpdatesFromADManager(GetNativeHandle());
656 /// Returns whether the current AppDomain follows the AppX rules.
658 [SecuritySafeCritical]
660 internal static bool IsAppXModel()
663 return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MODEL) != 0;
670 /// Returns the setting of the AppXDevMode config switch.
672 [SecuritySafeCritical]
674 internal static bool IsAppXDesignMode()
677 return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MASK) == (APPX_FLAGS.APPX_FLAGS_APPX_MODEL | APPX_FLAGS.APPX_FLAGS_APPX_DESIGN_MODE);
684 /// Checks (and throws on failure) if the domain supports Assembly.LoadFrom.
686 [SecuritySafeCritical]
688 internal static void CheckLoadFromSupported()
692 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFrom"));
697 /// Checks (and throws on failure) if the domain supports Assembly.LoadFile.
699 [SecuritySafeCritical]
701 internal static void CheckLoadFileSupported()
705 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFile"));
710 /// Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad.
712 [SecuritySafeCritical]
714 internal static void CheckReflectionOnlyLoadSupported()
718 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.ReflectionOnlyLoad"));
723 /// Checks (and throws on failure) if the domain supports Assembly.LoadWithPartialName.
725 [SecuritySafeCritical]
727 internal static void CheckLoadWithPartialNameSupported(StackCrawlMark stackMark)
732 RuntimeAssembly callingAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
733 bool callerIsFxAssembly = callingAssembly != null && callingAssembly.IsFrameworkAssembly();
734 if (!callerIsFxAssembly)
736 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadWithPartialName"));
743 /// Checks (and throws on failure) if the domain supports DefinePInvokeMethod.
745 [SecuritySafeCritical]
747 internal static void CheckDefinePInvokeSupported()
749 // We don't want users to use DefinePInvokeMethod in RefEmit to bypass app store validation on allowed native libraries.
752 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "DefinePInvokeMethod"));
757 /// Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...).
759 [SecuritySafeCritical]
761 internal static void CheckLoadByteArraySupported()
765 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.Load(byte[], ...)"));
770 /// Checks (and throws on failure) if the domain supports AppDomain.CreateDomain.
772 [SecuritySafeCritical]
774 internal static void CheckCreateDomainSupported()
777 // Can create a new domain in an AppX process only when DevMode is enabled and
778 // AssemblyLoadingCompat is not enabled (since there is no multi-domain support
779 // for LoadFrom and LoadFile in AppX.
782 if (!IsAppXDesignMode())
784 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "AppDomain.CreateDomain"));
791 /// Get the name of the assembly and type that act as the AppDomainManager for this domain
793 [SecuritySafeCritical]
794 internal void GetAppDomainManagerType(out string assembly, out string type)
796 // We can't just use our parameters because we need to ensure that the strings used for hte QCall
798 string localAssembly = null;
799 string localType = null;
801 GetAppDomainManagerType(GetNativeHandle(),
802 JitHelpers.GetStringHandleOnStack(ref localAssembly),
803 JitHelpers.GetStringHandleOnStack(ref localType));
805 assembly = localAssembly;
810 /// Set the assembly and type which act as the AppDomainManager for this domain
812 [SecuritySafeCritical]
813 private void SetAppDomainManagerType(string assembly, string type)
815 Contract.Assert(assembly != null, "assembly != null");
816 Contract.Assert(type != null, "type != null");
817 SetAppDomainManagerType(GetNativeHandle(), assembly, type);
821 internal String[] PartialTrustVisibleAssemblies
823 get { return _aptcaVisibleAssemblies; }
825 [SecuritySafeCritical]
828 _aptcaVisibleAssemblies = value;
830 // Build up the canonical representaiton of this list to allow the VM to do optimizations in
832 string canonicalConditionalAptcaList = null;
835 StringBuilder conditionalAptcaListBuilder = StringBuilderCache.Acquire();
836 for (int i = 0; i < value.Length; ++i)
838 if (value[i] != null)
840 conditionalAptcaListBuilder.Append(value[i].ToUpperInvariant());
841 if (i != value.Length - 1)
843 conditionalAptcaListBuilder.Append(';');
848 canonicalConditionalAptcaList = StringBuilderCache.GetStringAndRelease(conditionalAptcaListBuilder);
851 SetCanonicalConditionalAptcaList(canonicalConditionalAptcaList);
856 [ResourceExposure(ResourceScope.None)]
857 [SuppressUnmanagedCodeSecurity]
858 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
859 private static extern void SetCanonicalConditionalAptcaList(AppDomainHandle appDomain, string canonicalList);
862 private void SetCanonicalConditionalAptcaList(string canonicalList)
864 SetCanonicalConditionalAptcaList(GetNativeHandle(), canonicalList);
866 #endif // FEATURE_APTCA
868 #if FEATURE_CLICKONCE
870 /// If the CLR is being started up to run a ClickOnce applicaiton, setup the default AppDomain
871 /// with information about that application.
873 private void SetupDefaultClickOnceDomain(string fullName, string[] manifestPaths, string[] activationData)
875 Contract.Requires(fullName != null, "fullName != null");
876 FusionStore.ActivationArguments = new ActivationArguments(fullName, manifestPaths, activationData);
878 #endif // FEATURE_CLICKONCE
881 /// Called for every AppDomain (including the default domain) to initialize the security of the AppDomain)
884 private void InitializeDomainSecurity(Evidence providedSecurityInfo,
885 Evidence creatorsSecurityInfo,
886 bool generateDefaultEvidence,
887 IntPtr parentSecurityDescriptor,
888 bool publishAppDomain)
890 AppDomainSetup adSetup = FusionStore;
892 #if FEATURE_CAS_POLICY
893 // If the AppDomain is setup to use legacy CAS policy, then set that bit in the application
894 // security descriptor.
895 if (CompatibilitySwitches.IsNetFx40LegacySecurityPolicy)
897 SetLegacyCasPolicyEnabled();
899 #endif // FEATURE_CAS_POLICY
901 #if FEATURE_CLICKONCE
903 // Check if the domain manager set an ActivationContext (Debug-In-Zone for example)
904 // or if this is an AppDomain with an ApplicationTrust.
905 if (adSetup.ActivationArguments != null) {
906 // Merge the new evidence with the manifest's evidence if applicable
907 ActivationContext activationContext = null;
908 ApplicationIdentity appIdentity = null;
909 string[] activationData = null;
910 CmsUtils.CreateActivationContext(adSetup.ActivationArguments.ApplicationFullName,
911 adSetup.ActivationArguments.ApplicationManifestPaths,
912 adSetup.ActivationArguments.UseFusionActivationContext,
913 out appIdentity, out activationContext);
914 activationData = adSetup.ActivationArguments.ActivationData;
915 providedSecurityInfo = CmsUtils.MergeApplicationEvidence(providedSecurityInfo,
919 adSetup.ApplicationTrust);
920 SetupApplicationHelper(providedSecurityInfo, creatorsSecurityInfo, appIdentity, activationContext, activationData);
923 #endif // FEATURE_CLICKONCE
925 bool runtimeSuppliedHomogenousGrant = false;
926 ApplicationTrust appTrust = adSetup.ApplicationTrust;
928 #if FEATURE_CAS_POLICY
929 // In non-legacy CAS mode, domains should be homogenous. If the host has not specified a sandbox
930 // of their own, we'll set it up to be fully trusted. We must read the IsLegacyCasPolicy
931 // enabled property here rathern than just reading the switch from above because the entire
932 // process may also be opted into legacy CAS policy mode.
933 if (appTrust == null && !IsLegacyCasPolicyEnabled) {
934 _IsFastFullTrustDomain = true;
935 runtimeSuppliedHomogenousGrant = true;
937 #endif // FEATURE_CAS_POLICY
939 if (appTrust != null) {
940 SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant);
942 else if (_IsFastFullTrustDomain) {
943 SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant);
947 // Get the evidence supplied for the domain. If no evidence was supplied, it means that we want
948 // to use the default evidence creation strategy for this domain
949 Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo);
950 if (newAppDomainEvidence == null && generateDefaultEvidence) {
951 #if FEATURE_CAS_POLICY
952 newAppDomainEvidence = new Evidence(new AppDomainEvidenceFactory(this));
953 #else // !FEATURE_CAS_POLICY
954 newAppDomainEvidence = new Evidence();
955 #endif // FEATURE_CAS_POLICY
958 #if FEATURE_CAS_POLICY
959 if (_domainManager != null) {
960 // Give the host a chance to alter the AppDomain evidence
961 HostSecurityManager securityManager = _domainManager.HostSecurityManager;
962 if (securityManager != null) {
963 nSetHostSecurityManagerFlags (securityManager.Flags);
964 if ((securityManager.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence) {
965 newAppDomainEvidence = securityManager.ProvideAppDomainEvidence(newAppDomainEvidence);
966 // If this is a disconnected evidence collection, then attach it to the AppDomain,
967 // allowing the host security manager to get callbacks for delay generated evidence
968 if (newAppDomainEvidence != null && newAppDomainEvidence.Target == null) {
969 newAppDomainEvidence.Target = new AppDomainEvidenceFactory(this);
975 #endif // FEATURE_CAS_POLICY
977 // Set the evidence on the managed side
978 _SecurityIdentity = newAppDomainEvidence;
980 // Set the evidence of the AppDomain in the VM.
981 // Also, now that the initialization is complete, signal that to the security system.
982 // Finish the AppDomain initialization and resolve the policy for the AppDomain evidence.
983 SetupDomainSecurity(newAppDomainEvidence,
984 parentSecurityDescriptor,
987 #if FEATURE_CAS_POLICY
988 // The AppDomain is now resolved. Go ahead and set the PolicyLevel
989 // from the HostSecurityManager if specified.
990 if (_domainManager != null)
991 RunDomainManagerPostInitialization(_domainManager);
992 #endif // FEATURE_CAS_POLICY
995 #if FEATURE_CAS_POLICY
996 [System.Security.SecurityCritical] // auto-generated
997 private void RunDomainManagerPostInitialization (AppDomainManager domainManager)
999 // force creation of the HostExecutionContextManager for the current AppDomain
1000 HostExecutionContextManager contextManager = domainManager.HostExecutionContextManager;
1002 if (IsLegacyCasPolicyEnabled)
1004 #pragma warning disable 618
1005 HostSecurityManager securityManager = domainManager.HostSecurityManager;
1006 if (securityManager != null)
1008 if ((securityManager.Flags & HostSecurityManagerOptions.HostPolicyLevel) == HostSecurityManagerOptions.HostPolicyLevel)
1010 // set AppDomain policy if specified
1011 PolicyLevel level = securityManager.DomainPolicy;
1013 SetAppDomainPolicy(level);
1016 #pragma warning restore 618
1022 #if FEATURE_CLICKONCE
1024 [System.Security.SecurityCritical] // auto-generated
1025 private void SetupApplicationHelper (Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, ApplicationIdentity appIdentity, ActivationContext activationContext, string[] activationData) {
1026 Contract.Requires(providedSecurityInfo != null);
1027 HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager;
1028 ApplicationTrust appTrust = securityManager.DetermineApplicationTrust(providedSecurityInfo, creatorsSecurityInfo, new TrustManagerContext());
1029 if (appTrust == null || !appTrust.IsApplicationTrustedToRun)
1030 throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
1031 System.__HResults.CORSEC_E_NO_EXEC_PERM,
1034 // The application is trusted to run. Set up the AppDomain according to the manifests.
1035 if (activationContext != null)
1036 SetupDomainForApplication(activationContext, activationData);
1037 SetupDomainSecurityForApplication(appIdentity, appTrust);
1040 [System.Security.SecurityCritical] // auto-generated
1041 [ResourceExposure(ResourceScope.None)]
1042 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1043 private void SetupDomainForApplication(ActivationContext activationContext, string[] activationData) {
1044 Contract.Requires(activationContext != null);
1045 if (IsDefaultAppDomain()) {
1046 // make the ActivationArguments available off the AppDomain object.
1047 AppDomainSetup adSetup = this.FusionStore;
1048 adSetup.ActivationArguments = new ActivationArguments(activationContext, activationData);
1050 // set the application base to point at where the application resides
1051 string entryPointPath = CmsUtils.GetEntryPointFullPath(activationContext);
1052 if (!String.IsNullOrEmpty(entryPointPath))
1053 adSetup.SetupDefaults(entryPointPath);
1055 adSetup.ApplicationBase = activationContext.ApplicationDirectory;
1057 // update fusion context
1058 SetupFusionStore(adSetup, null);
1061 // perform app data directory migration.
1062 activationContext.PrepareForExecution();
1063 activationContext.SetApplicationState(ActivationContext.ApplicationState.Starting);
1064 // set current app data directory.
1065 activationContext.SetApplicationState(ActivationContext.ApplicationState.Running);
1067 // make data directory path available.
1068 IPermission permission = null;
1069 string dataDirectory = activationContext.DataDirectory;
1070 if (dataDirectory != null && dataDirectory.Length > 0)
1071 permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, dataDirectory);
1072 this.SetData("DataDirectory", dataDirectory, permission);
1074 _activationContext = activationContext;
1077 [System.Security.SecurityCritical] // auto-generated
1078 private void SetupDomainSecurityForApplication(ApplicationIdentity appIdentity,
1079 ApplicationTrust appTrust)
1081 // Set the Application trust on the managed side.
1082 _applicationIdentity = appIdentity;
1083 SetupDomainSecurityForHomogeneousDomain(appTrust, false);
1085 #endif // FEATURE_CLICKONCE
1087 [System.Security.SecurityCritical] // auto-generated
1088 private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust,
1089 bool runtimeSuppliedHomogenousGrantSet)
1091 // If the CLR has supplied the homogenous grant set (that is, this domain would have been
1092 // heterogenous in v2.0), then we need to strip the ApplicationTrust from the AppDomainSetup of
1093 // the current domain. This prevents code which does:
1094 // AppDomain.CreateDomain(..., AppDomain.CurrentDomain.SetupInformation);
1096 // From looking like it is trying to create a homogenous domain intentionally, and therefore
1097 // having its evidence check bypassed.
1098 if (runtimeSuppliedHomogenousGrantSet)
1100 BCLDebug.Assert(_FusionStore.ApplicationTrust != null, "Expected to find runtime supplied ApplicationTrust");
1101 #if FEATURE_CAS_POLICY
1102 _FusionStore.ApplicationTrust = null;
1103 #endif // FEATURE_CAS_POLICY
1106 _applicationTrust = appTrust;
1108 // Set the homogeneous bit in the VM's ApplicationSecurityDescriptor.
1109 SetSecurityHomogeneousFlag(GetNativeHandle(),
1110 runtimeSuppliedHomogenousGrantSet);
1113 // This method is called from CorHost2::ExecuteApplication to activate a ClickOnce application in the default AppDomain.
1114 #if FEATURE_CLICKONCE
1115 [System.Security.SecuritySafeCritical] // auto-generated
1116 private int ActivateApplication () {
1117 ObjectHandle oh = Activator.CreateInstance(AppDomain.CurrentDomain.ActivationContext);
1118 return (int) oh.Unwrap();
1120 #endif //FEATURE_CLICKONCE
1122 public AppDomainManager DomainManager {
1123 [System.Security.SecurityCritical] // auto-generated_required
1125 return _domainManager;
1129 #if FEATURE_CAS_POLICY
1130 internal HostSecurityManager HostSecurityManager {
1131 [System.Security.SecurityCritical] // auto-generated
1133 HostSecurityManager securityManager = null;
1134 AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
1135 if (domainManager != null)
1136 securityManager = domainManager.HostSecurityManager;
1138 if (securityManager == null)
1139 securityManager = new HostSecurityManager();
1140 return securityManager;
1143 #endif // FEATURE_CAS_POLICY
1144 #if FEATURE_REFLECTION_ONLY_LOAD
1145 private Assembly ResolveAssemblyForIntrospection(Object sender, ResolveEventArgs args)
1147 Contract.Requires(args != null);
1148 return Assembly.ReflectionOnlyLoad(ApplyPolicy(args.Name));
1151 // Helper class for method code:EnableResolveAssembliesForIntrospection
1152 private class NamespaceResolverForIntrospection
1154 private IEnumerable<string> _packageGraphFilePaths;
1155 public NamespaceResolverForIntrospection(IEnumerable<string> packageGraphFilePaths)
1157 _packageGraphFilePaths = packageGraphFilePaths;
1160 [System.Security.SecurityCritical]
1161 public void ResolveNamespace(
1163 System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args)
1165 Contract.Requires(args != null);
1167 IEnumerable<string> fileNames = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ResolveNamespace(
1169 null, // windowsSdkFilePath ... Use OS installed .winmd files
1170 _packageGraphFilePaths);
1171 foreach (string fileName in fileNames)
1173 args.ResolvedAssemblies.Add(Assembly.ReflectionOnlyLoadFrom(fileName));
1178 // Called only by native function code:ValidateWorker
1179 [System.Security.SecuritySafeCritical]
1180 private void EnableResolveAssembliesForIntrospection(string verifiedFileDirectory)
1182 CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
1184 string[] packageGraphFilePaths = null;
1185 if (verifiedFileDirectory != null)
1186 packageGraphFilePaths = new string[] { verifiedFileDirectory };
1187 NamespaceResolverForIntrospection namespaceResolver = new NamespaceResolverForIntrospection(packageGraphFilePaths);
1189 System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve +=
1190 new EventHandler<System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs>(namespaceResolver.ResolveNamespace);
1192 #endif // FEATURE_REFLECTION_ONLY_LOAD
1195 /**********************************************
1196 * If an AssemblyName has a public key specified, the assembly is assumed
1197 * to have a strong name and a hash will be computed when the assembly
1199 **********************************************/
1200 [System.Security.SecuritySafeCritical] // auto-generated
1201 [ResourceExposure(ResourceScope.None)]
1202 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1203 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1204 public AssemblyBuilder DefineDynamicAssembly(
1206 AssemblyBuilderAccess access)
1208 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1210 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1211 return InternalDefineDynamicAssembly(name, access, null,
1212 null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
1215 [System.Security.SecuritySafeCritical] // auto-generated
1216 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1217 public AssemblyBuilder DefineDynamicAssembly(
1219 AssemblyBuilderAccess access,
1220 IEnumerable<CustomAttributeBuilder> assemblyAttributes)
1222 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1224 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1225 return InternalDefineDynamicAssembly(name,
1227 null, null, null, null, null,
1229 assemblyAttributes, SecurityContextSource.CurrentAssembly);
1232 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Due to the stack crawl mark
1233 [SecuritySafeCritical]
1234 public AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
1235 AssemblyBuilderAccess access,
1236 IEnumerable<CustomAttributeBuilder> assemblyAttributes,
1237 SecurityContextSource securityContextSource)
1239 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1241 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1242 return InternalDefineDynamicAssembly(name,
1244 null, null, null, null, null,
1247 securityContextSource);
1250 [System.Security.SecuritySafeCritical] // auto-generated
1251 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1252 public AssemblyBuilder DefineDynamicAssembly(
1254 AssemblyBuilderAccess access,
1257 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1259 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1260 return InternalDefineDynamicAssembly(name, access, dir,
1261 null, null, null, null,
1264 SecurityContextSource.CurrentAssembly);
1267 [System.Security.SecuritySafeCritical] // auto-generated
1268 [ResourceExposure(ResourceScope.None)]
1269 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1270 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1271 [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1272 public AssemblyBuilder DefineDynamicAssembly(
1274 AssemblyBuilderAccess access,
1277 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1279 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1280 return InternalDefineDynamicAssembly(name, access, null,
1281 evidence, null, null, null,
1284 SecurityContextSource.CurrentAssembly);
1287 [System.Security.SecuritySafeCritical] // auto-generated
1288 [ResourceExposure(ResourceScope.None)]
1289 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1290 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1291 [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1292 public AssemblyBuilder DefineDynamicAssembly(
1294 AssemblyBuilderAccess access,
1295 PermissionSet requiredPermissions,
1296 PermissionSet optionalPermissions,
1297 PermissionSet refusedPermissions)
1299 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1301 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1302 return InternalDefineDynamicAssembly(name, access, null, null,
1303 requiredPermissions,
1304 optionalPermissions,
1308 SecurityContextSource.CurrentAssembly);
1311 [System.Security.SecuritySafeCritical] // auto-generated
1312 [ResourceExposure(ResourceScope.Machine)]
1313 [ResourceConsumption(ResourceScope.Machine)]
1314 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1315 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of DefineDynamicAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
1316 public AssemblyBuilder DefineDynamicAssembly(
1318 AssemblyBuilderAccess access,
1322 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1324 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1325 return InternalDefineDynamicAssembly(name, access, dir, evidence,
1326 null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
1329 [System.Security.SecuritySafeCritical] // auto-generated
1330 [ResourceExposure(ResourceScope.Machine)]
1331 [ResourceConsumption(ResourceScope.Machine)]
1332 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1333 [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1334 public AssemblyBuilder DefineDynamicAssembly(
1336 AssemblyBuilderAccess access,
1338 PermissionSet requiredPermissions,
1339 PermissionSet optionalPermissions,
1340 PermissionSet refusedPermissions)
1342 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1344 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1345 return InternalDefineDynamicAssembly(name, access, dir, null,
1346 requiredPermissions,
1347 optionalPermissions,
1351 SecurityContextSource.CurrentAssembly);
1354 [System.Security.SecuritySafeCritical] // auto-generated
1355 [ResourceExposure(ResourceScope.None)]
1356 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
1357 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1358 [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1359 public AssemblyBuilder DefineDynamicAssembly(
1361 AssemblyBuilderAccess access,
1363 PermissionSet requiredPermissions,
1364 PermissionSet optionalPermissions,
1365 PermissionSet refusedPermissions)
1367 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1369 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1370 return InternalDefineDynamicAssembly(name, access, null,
1372 requiredPermissions,
1373 optionalPermissions,
1377 SecurityContextSource.CurrentAssembly);
1380 [System.Security.SecuritySafeCritical] // auto-generated
1381 [ResourceExposure(ResourceScope.Machine)]
1382 [ResourceConsumption(ResourceScope.Machine)]
1383 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1384 [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. Please see http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
1385 public AssemblyBuilder DefineDynamicAssembly(
1387 AssemblyBuilderAccess access,
1390 PermissionSet requiredPermissions,
1391 PermissionSet optionalPermissions,
1392 PermissionSet refusedPermissions)
1394 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1396 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1397 return InternalDefineDynamicAssembly(name, access, dir,
1399 requiredPermissions,
1400 optionalPermissions,
1404 SecurityContextSource.CurrentAssembly);
1408 [System.Security.SecuritySafeCritical] // auto-generated
1409 [ResourceExposure(ResourceScope.Machine)]
1410 [ResourceConsumption(ResourceScope.Machine)]
1411 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1412 [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1413 public AssemblyBuilder DefineDynamicAssembly(
1415 AssemblyBuilderAccess access,
1418 PermissionSet requiredPermissions,
1419 PermissionSet optionalPermissions,
1420 PermissionSet refusedPermissions,
1421 bool isSynchronized)
1423 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1425 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1426 return InternalDefineDynamicAssembly(name,
1430 requiredPermissions,
1431 optionalPermissions,
1435 SecurityContextSource.CurrentAssembly);
1438 [System.Security.SecuritySafeCritical] // auto-generated
1439 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1440 [Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1441 public AssemblyBuilder DefineDynamicAssembly(
1443 AssemblyBuilderAccess access,
1446 PermissionSet requiredPermissions,
1447 PermissionSet optionalPermissions,
1448 PermissionSet refusedPermissions,
1449 bool isSynchronized,
1450 IEnumerable<CustomAttributeBuilder> assemblyAttributes)
1452 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1454 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1455 return InternalDefineDynamicAssembly(name,
1459 requiredPermissions,
1460 optionalPermissions,
1464 SecurityContextSource.CurrentAssembly);
1467 [System.Security.SecuritySafeCritical] // auto-generated
1468 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1469 public AssemblyBuilder DefineDynamicAssembly(
1471 AssemblyBuilderAccess access,
1473 bool isSynchronized,
1474 IEnumerable<CustomAttributeBuilder> assemblyAttributes)
1476 Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1478 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1479 return InternalDefineDynamicAssembly(name,
1488 SecurityContextSource.CurrentAssembly);
1491 [System.Security.SecurityCritical] // auto-generated
1492 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1493 private AssemblyBuilder InternalDefineDynamicAssembly(
1495 AssemblyBuilderAccess access,
1498 PermissionSet requiredPermissions,
1499 PermissionSet optionalPermissions,
1500 PermissionSet refusedPermissions,
1501 ref StackCrawlMark stackMark,
1502 IEnumerable<CustomAttributeBuilder> assemblyAttributes,
1503 SecurityContextSource securityContextSource)
1505 return AssemblyBuilder.InternalDefineDynamicAssembly(name,
1509 requiredPermissions,
1510 optionalPermissions,
1514 securityContextSource);
1517 [System.Security.SecuritySafeCritical] // auto-generated
1518 [ResourceExposure(ResourceScope.None)]
1519 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1520 private extern String nApplyPolicy(AssemblyName an);
1522 // Return the assembly name that results from applying policy.
1524 public String ApplyPolicy(String assemblyName)
1526 AssemblyName asmName = new AssemblyName(assemblyName);
1528 byte[] pk = asmName.GetPublicKeyToken();
1530 pk = asmName.GetPublicKey();
1532 // Simply-named assemblies cannot have policy, so for those,
1533 // we simply return the passed-in assembly name.
1534 if ((pk == null) || (pk.Length == 0))
1535 return assemblyName;
1537 return nApplyPolicy(asmName);
1541 public ObjectHandle CreateInstance(String assemblyName,
1545 // jit does not check for that, so we should do it ...
1547 throw new NullReferenceException();
1549 if (assemblyName == null)
1550 throw new ArgumentNullException("assemblyName");
1551 Contract.EndContractBlock();
1553 return Activator.CreateInstance(assemblyName,
1557 [System.Security.SecurityCritical] // auto-generated
1558 internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
1559 PermissionSet.s_fullTrust.Assert();
1560 return CreateInstance(assemblyName, typeName);
1563 [ResourceExposure(ResourceScope.Machine)]
1564 [ResourceConsumption(ResourceScope.Machine)]
1565 public ObjectHandle CreateInstanceFrom(String assemblyFile,
1569 // jit does not check for that, so we should do it ...
1571 throw new NullReferenceException();
1572 Contract.EndContractBlock();
1574 return Activator.CreateInstanceFrom(assemblyFile,
1578 [System.Security.SecurityCritical] // auto-generated
1579 [ResourceExposure(ResourceScope.Machine)]
1580 [ResourceConsumption(ResourceScope.Machine)]
1581 internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, string typeName) {
1582 PermissionSet.s_fullTrust.Assert();
1583 return CreateInstanceFrom(assemblyName, typeName);
1586 #if FEATURE_COMINTEROP
1587 // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
1588 // release, and the compatibility police won't let us change the name now.
1589 [ResourceExposure(ResourceScope.Machine)]
1590 [ResourceConsumption(ResourceScope.Machine)]
1591 public ObjectHandle CreateComInstanceFrom(String assemblyName,
1596 throw new NullReferenceException();
1597 Contract.EndContractBlock();
1599 return Activator.CreateComInstanceFrom(assemblyName,
1603 [ResourceExposure(ResourceScope.Machine)]
1604 [ResourceConsumption(ResourceScope.Machine)]
1605 public ObjectHandle CreateComInstanceFrom(String assemblyFile,
1608 AssemblyHashAlgorithm hashAlgorithm)
1612 throw new NullReferenceException();
1613 Contract.EndContractBlock();
1615 return Activator.CreateComInstanceFrom(assemblyFile,
1621 #endif // FEATURE_COMINTEROP
1623 public ObjectHandle CreateInstance(String assemblyName,
1625 Object[] activationAttributes)
1628 // jit does not check for that, so we should do it ...
1630 throw new NullReferenceException();
1632 if (assemblyName == null)
1633 throw new ArgumentNullException("assemblyName");
1634 Contract.EndContractBlock();
1636 return Activator.CreateInstance(assemblyName,
1638 activationAttributes);
1641 [ResourceExposure(ResourceScope.Machine)]
1642 [ResourceConsumption(ResourceScope.Machine)]
1643 public ObjectHandle CreateInstanceFrom(String assemblyFile,
1645 Object[] activationAttributes)
1648 // jit does not check for that, so we should do it ...
1650 throw new NullReferenceException();
1651 Contract.EndContractBlock();
1653 return Activator.CreateInstanceFrom(assemblyFile,
1655 activationAttributes);
1658 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1659 public ObjectHandle CreateInstance(String assemblyName,
1662 BindingFlags bindingAttr,
1665 CultureInfo culture,
1666 Object[] activationAttributes,
1667 Evidence securityAttributes)
1669 // jit does not check for that, so we should do it ...
1671 throw new NullReferenceException();
1673 if (assemblyName == null)
1674 throw new ArgumentNullException("assemblyName");
1675 Contract.EndContractBlock();
1677 #if FEATURE_CAS_POLICY
1678 if (securityAttributes != null && !IsLegacyCasPolicyEnabled)
1680 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1682 #endif // FEATURE_CAS_POLICY
1684 #pragma warning disable 618
1685 return Activator.CreateInstance(assemblyName,
1692 activationAttributes,
1693 securityAttributes);
1694 #pragma warning restore 618
1697 public ObjectHandle CreateInstance(string assemblyName,
1700 BindingFlags bindingAttr,
1703 CultureInfo culture,
1704 object[] activationAttributes)
1706 // jit does not check for that, so we should do it ...
1708 throw new NullReferenceException();
1710 if (assemblyName == null)
1711 throw new ArgumentNullException("assemblyName");
1712 Contract.EndContractBlock();
1714 return Activator.CreateInstance(assemblyName,
1721 activationAttributes);
1724 [System.Security.SecurityCritical] // auto-generated
1725 internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName,
1728 BindingFlags bindingAttr,
1731 CultureInfo culture,
1732 Object[] activationAttributes,
1733 Evidence securityAttributes)
1735 #if FEATURE_CAS_POLICY
1736 Contract.Assert(IsLegacyCasPolicyEnabled || securityAttributes == null);
1737 #endif // FEATURE_CAS_POLICY
1739 PermissionSet.s_fullTrust.Assert();
1740 #pragma warning disable 618
1741 return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
1742 #pragma warning restore 618
1745 [ResourceExposure(ResourceScope.Machine)]
1746 [ResourceConsumption(ResourceScope.Machine)]
1747 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1748 public ObjectHandle CreateInstanceFrom(String assemblyFile,
1751 BindingFlags bindingAttr,
1754 CultureInfo culture,
1755 Object[] activationAttributes,
1756 Evidence securityAttributes)
1759 // jit does not check for that, so we should do it ...
1761 throw new NullReferenceException();
1762 Contract.EndContractBlock();
1764 #if FEATURE_CAS_POLICY
1765 if (securityAttributes != null && !IsLegacyCasPolicyEnabled)
1767 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1769 #endif // FEATURE_CAS_POLICY
1771 return Activator.CreateInstanceFrom(assemblyFile,
1778 activationAttributes,
1779 securityAttributes);
1782 [ResourceExposure(ResourceScope.Machine)]
1783 [ResourceConsumption(ResourceScope.Machine)]
1784 public ObjectHandle CreateInstanceFrom(string assemblyFile,
1787 BindingFlags bindingAttr,
1790 CultureInfo culture,
1791 object[] activationAttributes)
1793 // jit does not check for that, so we should do it ...
1795 throw new NullReferenceException();
1796 Contract.EndContractBlock();
1798 return Activator.CreateInstanceFrom(assemblyFile,
1805 activationAttributes);
1808 [System.Security.SecurityCritical] // auto-generated
1809 [ResourceExposure(ResourceScope.Machine)]
1810 [ResourceConsumption(ResourceScope.Machine)]
1811 internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName,
1814 BindingFlags bindingAttr,
1817 CultureInfo culture,
1818 Object[] activationAttributes,
1819 Evidence securityAttributes)
1821 #if FEATURE_CAS_POLICY
1822 Contract.Assert(IsLegacyCasPolicyEnabled || securityAttributes == null);
1823 #endif // FEATURE_CAS_POLICY
1825 PermissionSet.s_fullTrust.Assert();
1826 #pragma warning disable 618
1827 return CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
1828 #pragma warning restore 618
1831 [System.Security.SecuritySafeCritical] // auto-generated
1832 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1833 public Assembly Load(AssemblyName assemblyRef)
1835 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1836 return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
1839 [System.Security.SecuritySafeCritical] // auto-generated
1840 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1841 public Assembly Load(String assemblyString)
1843 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1844 return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false);
1847 [System.Security.SecuritySafeCritical] // auto-generated
1848 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1849 public Assembly Load(byte[] rawAssembly)
1851 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1852 return RuntimeAssembly.nLoadImage(rawAssembly,
1853 null, // symbol store
1857 SecurityContextSource.CurrentAssembly);
1861 [System.Security.SecuritySafeCritical] // auto-generated
1862 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1863 public Assembly Load(byte[] rawAssembly,
1864 byte[] rawSymbolStore)
1866 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1867 return RuntimeAssembly.nLoadImage(rawAssembly,
1871 false, // fIntrospection
1872 SecurityContextSource.CurrentAssembly);
1875 [System.Security.SecuritySafeCritical] // auto-generated
1876 #pragma warning disable 618
1877 [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
1878 #pragma warning restore 618
1879 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1880 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
1881 public Assembly Load(byte[] rawAssembly,
1882 byte[] rawSymbolStore,
1883 Evidence securityEvidence)
1885 #if FEATURE_CAS_POLICY
1886 if (securityEvidence != null && !IsLegacyCasPolicyEnabled)
1888 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1890 #endif // FEATURE_CAS_POLICY
1892 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1893 return RuntimeAssembly.nLoadImage(rawAssembly,
1897 false, // fIntrospection
1898 SecurityContextSource.CurrentAssembly);
1901 [System.Security.SecuritySafeCritical] // auto-generated
1902 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1903 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1904 public Assembly Load(AssemblyName assemblyRef,
1905 Evidence assemblySecurity)
1907 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1908 return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
1911 [System.Security.SecuritySafeCritical] // auto-generated
1912 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
1913 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1914 public Assembly Load(String assemblyString,
1915 Evidence assemblySecurity)
1917 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1918 return RuntimeAssembly.InternalLoad(assemblyString, assemblySecurity, ref stackMark, false);
1921 [ResourceExposure(ResourceScope.Machine)]
1922 [ResourceConsumption(ResourceScope.Machine)]
1923 public int ExecuteAssembly(String assemblyFile)
1925 return ExecuteAssembly(assemblyFile, (string[])null);
1928 [ResourceExposure(ResourceScope.Machine)]
1929 [ResourceConsumption(ResourceScope.Machine)]
1930 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of ExecuteAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1931 public int ExecuteAssembly(String assemblyFile,
1932 Evidence assemblySecurity)
1934 return ExecuteAssembly(assemblyFile, assemblySecurity, null);
1937 [ResourceExposure(ResourceScope.Machine)]
1938 [ResourceConsumption(ResourceScope.Machine)]
1939 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of ExecuteAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1940 public int ExecuteAssembly(String assemblyFile,
1941 Evidence assemblySecurity,
1944 #if FEATURE_CAS_POLICY
1945 if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
1947 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1949 #endif // FEATURE_CAS_POLICY
1951 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile, assemblySecurity);
1954 args = new String[0];
1956 return nExecuteAssembly(assembly, args);
1959 [ResourceExposure(ResourceScope.Machine)]
1960 [ResourceConsumption(ResourceScope.Machine)]
1961 public int ExecuteAssembly(string assemblyFile, string[] args)
1963 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile);
1966 args = new String[0];
1968 return nExecuteAssembly(assembly, args);
1971 [ResourceExposure(ResourceScope.Machine)]
1972 [ResourceConsumption(ResourceScope.Machine)]
1973 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of ExecuteAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
1974 public int ExecuteAssembly(String assemblyFile,
1975 Evidence assemblySecurity,
1978 AssemblyHashAlgorithm hashAlgorithm)
1980 #if FEATURE_CAS_POLICY
1981 if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
1983 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1985 #endif // FEATURE_CAS_POLICY
1987 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile,
1992 args = new String[0];
1994 return nExecuteAssembly(assembly, args);
1997 [ResourceExposure(ResourceScope.Machine)]
1998 [ResourceConsumption(ResourceScope.Machine)]
1999 public int ExecuteAssembly(string assemblyFile,
2002 AssemblyHashAlgorithm hashAlgorithm)
2004 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile,
2008 args = new String[0];
2010 return nExecuteAssembly(assembly, args);
2014 [System.Security.SecurityCritical] // auto-generated
2016 public int ExecuteAssemblyByName(String assemblyName)
2018 return ExecuteAssemblyByName(assemblyName, (string[])null);
2021 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of ExecuteAssemblyByName which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
2022 public int ExecuteAssemblyByName(String assemblyName,
2023 Evidence assemblySecurity)
2025 #pragma warning disable 618
2026 return ExecuteAssemblyByName(assemblyName, assemblySecurity, null);
2027 #pragma warning restore 618
2030 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of ExecuteAssemblyByName which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
2031 public int ExecuteAssemblyByName(String assemblyName,
2032 Evidence assemblySecurity,
2033 params String[] args)
2035 #if FEATURE_CAS_POLICY
2036 if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
2038 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
2040 #endif // FEATURE_CAS_POLICY
2042 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
2045 args = new String[0];
2047 return nExecuteAssembly(assembly, args);
2050 public int ExecuteAssemblyByName(string assemblyName, params string[] args)
2052 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName);
2055 args = new String[0];
2057 return nExecuteAssembly(assembly, args);
2060 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of ExecuteAssemblyByName which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
2061 public int ExecuteAssemblyByName(AssemblyName assemblyName,
2062 Evidence assemblySecurity,
2063 params String[] args)
2065 #if FEATURE_CAS_POLICY
2066 if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
2068 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
2070 #endif // FEATURE_CAS_POLICY
2072 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
2075 args = new String[0];
2077 return nExecuteAssembly(assembly, args);
2080 public int ExecuteAssemblyByName(AssemblyName assemblyName, params string[] args)
2082 RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName);
2085 args = new String[0];
2087 return nExecuteAssembly(assembly, args);
2090 public static AppDomain CurrentDomain
2093 Contract.Ensures(Contract.Result<AppDomain>() != null);
2094 return Thread.GetDomain();
2098 #if FEATURE_CAS_POLICY
2099 public Evidence Evidence
2101 [System.Security.SecuritySafeCritical] // auto-generated
2102 [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
2104 return EvidenceNoDemand;
2108 internal Evidence EvidenceNoDemand {
2111 if (_SecurityIdentity == null) {
2112 if (!IsDefaultAppDomain() && nIsDefaultAppDomainForEvidence()) {
2113 #if !FEATURE_CORECLR
2115 // V1.x compatibility: If this is an AppDomain created
2116 // by the default appdomain without an explicit evidence
2117 // then reuse the evidence of the default AppDomain.
2119 return GetDefaultDomain().Evidence;
2121 Contract.Assert(false,"This code should not be called for core CLR");
2123 // This operation is not allowed
2124 throw new InvalidOperationException();
2128 // We can't cache this value, since the VM needs to differentiate between AppDomains
2129 // which have no user supplied evidence and those which do and it uses the presence
2130 // of Evidence on the domain to make that switch.
2131 return new Evidence(new AppDomainEvidenceFactory(this));
2135 return _SecurityIdentity.Clone();
2140 internal Evidence InternalEvidence
2143 return _SecurityIdentity;
2147 internal EvidenceBase GetHostEvidence(Type type)
2149 if (_SecurityIdentity != null)
2151 return _SecurityIdentity.GetHostEvidence(type);
2155 return new Evidence(new AppDomainEvidenceFactory(this)).GetHostEvidence(type);
2158 #endif // FEATURE_CAS_POLICY
2160 public String FriendlyName
2162 [System.Security.SecuritySafeCritical] // auto-generated
2163 get { return nGetFriendlyName(); }
2166 public String BaseDirectory
2169 [System.Security.SecurityCritical]
2171 [ResourceExposure(ResourceScope.Machine)]
2172 [ResourceConsumption(ResourceScope.Machine)]
2174 return FusionStore.ApplicationBase;
2179 public String RelativeSearchPath
2181 [ResourceExposure(ResourceScope.Machine)]
2182 [ResourceConsumption(ResourceScope.Machine)]
2183 get { return FusionStore.PrivateBinPath; }
2186 public bool ShadowCopyFiles
2189 String s = FusionStore.ShadowCopyFiles;
2191 (String.Compare(s, "true", StringComparison.OrdinalIgnoreCase) == 0))
2199 [System.Security.SecuritySafeCritical] // auto-generated
2200 public override String ToString()
2202 StringBuilder sb = StringBuilderCache.Acquire();
2204 String fn = nGetFriendlyName();
2206 sb.Append(Environment.GetResourceString("Loader_Name") + fn);
2207 sb.Append(Environment.NewLine);
2210 if(_Policies == null || _Policies.Length == 0)
2211 sb.Append(Environment.GetResourceString("Loader_NoContextPolicies")
2212 + Environment.NewLine);
2214 sb.Append(Environment.GetResourceString("Loader_ContextPolicies")
2215 + Environment.NewLine);
2216 for(int i = 0;i < _Policies.Length; i++) {
2217 sb.Append(_Policies[i]);
2218 sb.Append(Environment.NewLine);
2222 return StringBuilderCache.GetStringAndRelease(sb);
2225 public Assembly[] GetAssemblies()
2227 return nGetAssemblies(false /* forIntrospection */);
2231 public Assembly[] ReflectionOnlyGetAssemblies()
2233 return nGetAssemblies(true /* forIntrospection */);
2236 [System.Security.SecuritySafeCritical] // auto-generated
2237 [ResourceExposure(ResourceScope.None)]
2238 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2239 private extern Assembly[] nGetAssemblies(bool forIntrospection);
2241 // this is true when we've removed the handles etc so really can't do anything
2242 [System.Security.SecurityCritical] // auto-generated
2243 [ResourceExposure(ResourceScope.None)]
2244 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2245 internal extern bool IsUnloadingForcedFinalize();
2247 // this is true when we've just started going through the finalizers and are forcing objects to finalize
2248 // so must be aware that certain infrastructure may have gone away
2249 [System.Security.SecuritySafeCritical] // auto-generated
2250 [ResourceExposure(ResourceScope.None)]
2251 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2252 public extern bool IsFinalizingForUnload();
2254 [System.Security.SecurityCritical] // auto-generated
2255 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2256 internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
2259 // Appends the following string to the private path. Valid paths
2260 // are of the form "bin;util/i386" etc.
2261 [System.Security.SecurityCritical] // auto-generated_required
2262 [Obsolete("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
2263 [ResourceExposure(ResourceScope.Machine)]
2264 [ResourceConsumption(ResourceScope.Machine)]
2265 public void AppendPrivatePath(String path)
2267 if(path == null || path.Length == 0)
2270 String current = FusionStore.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue];
2271 StringBuilder appendPath = StringBuilderCache.Acquire();
2273 if(current != null && current.Length > 0) {
2274 // See if the last character is a separator
2275 appendPath.Append(current);
2276 if((current[current.Length-1] != Path.PathSeparator) &&
2277 (path[0] != Path.PathSeparator))
2278 appendPath.Append(Path.PathSeparator);
2280 appendPath.Append(path);
2282 String result = StringBuilderCache.GetStringAndRelease(appendPath);
2283 InternalSetPrivateBinPath(result);
2287 [System.Security.SecurityCritical] // auto-generated_required
2288 [Obsolete("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
2289 [ResourceExposure(ResourceScope.None)]
2290 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2291 public void ClearPrivatePath()
2293 InternalSetPrivateBinPath(String.Empty);
2296 [System.Security.SecurityCritical] // auto-generated_required
2297 [Obsolete("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
2298 [ResourceExposure(ResourceScope.None)]
2299 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2300 public void ClearShadowCopyPath()
2302 InternalSetShadowCopyPath(String.Empty);
2305 [System.Security.SecurityCritical] // auto-generated_required
2306 [Obsolete("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
2307 [ResourceExposure(ResourceScope.Machine)]
2308 [ResourceConsumption(ResourceScope.Machine)]
2309 public void SetCachePath(String path)
2311 InternalSetCachePath(path);
2313 #endif // FEATURE_FUSION
2315 [System.Security.SecurityCritical] // auto-generated_required
2316 [ResourceExposure(ResourceScope.AppDomain)]
2317 [ResourceConsumption(ResourceScope.AppDomain)]
2318 public void SetData (string name, object data) {
2320 if (!name.Equals("LOCATION_URI"))
2322 // Only LOCATION_URI can be set using AppDomain.SetData
2323 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyLocationURI", name));
2325 #endif // FEATURE_CORECLR
2326 SetDataHelper(name, data, null);
2329 [System.Security.SecurityCritical] // auto-generated_required
2330 [ResourceExposure(ResourceScope.AppDomain)]
2331 [ResourceConsumption(ResourceScope.AppDomain)]
2332 public void SetData (string name, object data, IPermission permission) {
2334 if (!name.Equals("LOCATION_URI"))
2336 // Only LOCATION_URI can be set using AppDomain.SetData
2337 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyLocationURI", name));
2339 #endif // FEATURE_CORECLR
2340 SetDataHelper(name, data, permission);
2343 [System.Security.SecurityCritical] // auto-generated
2344 [ResourceExposure(ResourceScope.AppDomain)]
2345 [ResourceConsumption(ResourceScope.Machine, ResourceScope.AppDomain)]
2346 private void SetDataHelper (string name, object data, IPermission permission) {
2348 throw new ArgumentNullException("name");
2349 Contract.EndContractBlock();
2353 // IgnoreSystemPolicy is provided as a legacy flag to allow callers to
2354 // skip enterprise, machine and user policy levels. When this flag is set,
2355 // any demands triggered in this AppDomain will be evaluated against the
2356 // AppDomain CAS policy level that is set on the AppDomain.
2357 // Security Requirements:
2358 // The caller needs to be fully trusted in order to be able to set
2359 // this legacy mode.
2361 // There needs to be an AppDomain policy level set before this compat
2362 // switch can be set on the AppDomain.
2365 if (name.Equals(TargetFrameworkNameAppCompatSetting)) {
2366 _FusionStore.TargetFrameworkName = (String) data;
2369 #if FEATURE_CAS_POLICY
2370 if (name.Equals("IgnoreSystemPolicy")) {
2373 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
2375 new PermissionSet(PermissionState.Unrestricted).Demand();
2378 int key = AppDomainSetup.Locate(name);
2381 lock (((ICollection)LocalStore).SyncRoot) {
2382 LocalStore[name] = new object[] {data, permission};
2386 if (permission != null)
2387 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
2388 // Be sure to call these properties, not Value, since
2389 // these do more than call Value.
2391 case (int) AppDomainSetup.LoaderInformation.DynamicBaseValue:
2392 FusionStore.DynamicBase = (string) data;
2394 case (int) AppDomainSetup.LoaderInformation.DevPathValue:
2395 FusionStore.DeveloperPath = (string) data;
2397 case (int) AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
2398 FusionStore.ShadowCopyDirectories = (string) data;
2400 case (int) AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
2402 FusionStore.DisallowPublisherPolicy = true;
2404 FusionStore.DisallowPublisherPolicy = false;
2406 case (int) AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
2408 FusionStore.DisallowCodeDownload = true;
2410 FusionStore.DisallowCodeDownload = false;
2412 case (int) AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
2414 FusionStore.DisallowBindingRedirects = true;
2416 FusionStore.DisallowBindingRedirects = false;
2418 case (int) AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
2420 FusionStore.DisallowApplicationBaseProbing = true;
2422 FusionStore.DisallowApplicationBaseProbing = false;
2424 case (int) AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
2425 FusionStore.SetConfigurationBytes((byte[]) data);
2428 FusionStore.Value[key] = (string) data;
2432 #else // FEATURE_FUSION
2434 // SetData should only be used to set values that don't already exist.
2436 object[] currentVal;
2437 lock (((ICollection)LocalStore).SyncRoot) {
2438 LocalStore.TryGetValue(name, out currentVal);
2440 if (currentVal != null && currentVal[0] != null)
2442 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
2446 #endif // FEATURE_CORECLR
2447 lock (((ICollection)LocalStore).SyncRoot) {
2448 LocalStore[name] = new object[] {data, permission};
2450 #endif // FEATURE_FUSION
2455 [System.Security.SecurityCritical] // auto-generated
2457 [System.Security.SecuritySafeCritical]
2459 [ResourceExposure(ResourceScope.AppDomain)]
2460 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2461 public Object GetData(string name)
2464 throw new ArgumentNullException("name");
2465 Contract.EndContractBlock();
2467 int key = AppDomainSetup.Locate(name);
2470 #if FEATURE_LOADER_OPTIMIZATION
2471 if(name.Equals(AppDomainSetup.LoaderOptimizationKey))
2472 return FusionStore.LoaderOptimization;
2474 #endif // FEATURE_LOADER_OPTIMIZATION
2477 lock (((ICollection)LocalStore).SyncRoot) {
2478 LocalStore.TryGetValue(name, out data);
2482 if (data[1] != null) {
2483 IPermission permission = (IPermission) data[1];
2484 permission.Demand();
2490 // Be sure to call these properties, not Value, so
2491 // that the appropriate permission demand will be done
2493 case (int) AppDomainSetup.LoaderInformation.ApplicationBaseValue:
2494 return FusionStore.ApplicationBase;
2495 case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
2496 return FusionStore.ApplicationName;
2498 case (int) AppDomainSetup.LoaderInformation.ConfigurationFileValue:
2499 return FusionStore.ConfigurationFile;
2500 case (int) AppDomainSetup.LoaderInformation.DynamicBaseValue:
2501 return FusionStore.DynamicBase;
2502 case (int) AppDomainSetup.LoaderInformation.DevPathValue:
2503 return FusionStore.DeveloperPath;
2504 case (int) AppDomainSetup.LoaderInformation.PrivateBinPathValue:
2505 return FusionStore.PrivateBinPath;
2506 case (int) AppDomainSetup.LoaderInformation.PrivateBinPathProbeValue:
2507 return FusionStore.PrivateBinPathProbe;
2508 case (int) AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
2509 return FusionStore.ShadowCopyDirectories;
2510 case (int) AppDomainSetup.LoaderInformation.ShadowCopyFilesValue:
2511 return FusionStore.ShadowCopyFiles;
2512 case (int) AppDomainSetup.LoaderInformation.CachePathValue:
2513 return FusionStore.CachePath;
2514 case (int) AppDomainSetup.LoaderInformation.LicenseFileValue:
2515 return FusionStore.LicenseFile;
2516 case (int) AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
2517 return FusionStore.DisallowPublisherPolicy;
2518 case (int) AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
2519 return FusionStore.DisallowCodeDownload;
2520 case (int) AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
2521 return FusionStore.DisallowBindingRedirects;
2522 case (int) AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
2523 return FusionStore.DisallowApplicationBaseProbing;
2524 case (int) AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
2525 return FusionStore.GetConfigurationBytes();
2526 #endif //FEATURE_FUSION
2529 Contract.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
2536 // The compat flags are set at domain creation time to indicate that the given breaking
2537 // change should not be used in this domain.
2539 // After the domain has been created, this Nullable boolean returned by this method should
2540 // always have a value. Code in the runtime uses this to know if it is safe to cache values
2541 // that might change if the compatibility switches have not been set yet.
2542 public Nullable<bool> IsCompatibilitySwitchSet(String value)
2544 Nullable<bool> fReturn;
2546 if (_compatFlagsInitialized == false)
2548 fReturn = new Nullable<bool>();
2552 fReturn = new Nullable<bool>(_compatFlags != null && _compatFlags.ContainsKey(value));
2558 [Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)]
2559 [DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
2560 [ResourceExposure(ResourceScope.Process)]
2561 public static extern int GetCurrentThreadId();
2563 #if FEATURE_REMOTING
2564 [System.Security.SecuritySafeCritical] // auto-generated
2565 [SecurityPermissionAttribute( SecurityAction.Demand, ControlAppDomain = true ),
2566 ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]
2567 public static void Unload(AppDomain domain)
2570 throw new ArgumentNullException("domain");
2571 Contract.EndContractBlock();
2574 Int32 domainID = AppDomain.GetIdForUnload(domain);
2576 throw new CannotUnloadAppDomainException();
2577 AppDomain.nUnload(domainID);
2579 catch(Exception e) {
2580 throw e; // throw it again to reset stack trace
2585 // Explicitly set policy for a domain (providing policy hasn't been set
2586 // previously). Making this call will guarantee that previously loaded
2587 // assemblies will be granted permissions based on the default machine
2588 // policy that was in place prior to this call.
2589 #if FEATURE_CAS_POLICY
2590 [System.Security.SecurityCritical] // auto-generated_required
2591 [Obsolete("AppDomain policy levels are obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
2592 public void SetAppDomainPolicy(PolicyLevel domainPolicy)
2594 if (domainPolicy == null)
2595 throw new ArgumentNullException("domainPolicy");
2596 Contract.EndContractBlock();
2598 if (!IsLegacyCasPolicyEnabled)
2600 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
2603 // Check that policy has not been set previously.
2606 throw new PolicyException(Environment.GetResourceString("Policy_PolicyAlreadySet"));
2607 _HasSetPolicy = true;
2609 // Make sure that the loader allows us to change security policy
2610 // at this time (this will throw if not.)
2611 nChangeSecurityPolicy();
2614 // Add the new policy level.
2615 SecurityManager.PolicyManager.AddLevel(domainPolicy);
2617 #endif //#if !FEATURE_CAS_POLICY
2618 #if FEATURE_CLICKONCE
2619 public ActivationContext ActivationContext {
2620 [System.Security.SecurityCritical] // auto-generated_required
2622 return _activationContext;
2626 public ApplicationIdentity ApplicationIdentity {
2627 [System.Security.SecurityCritical] // auto-generated_required
2629 return _applicationIdentity;
2632 #endif // FEATURE_CLICKONCE
2635 #if FEATURE_CLICKONCE
2636 public ApplicationTrust ApplicationTrust {
2637 [System.Security.SecurityCritical] // auto-generated_required
2638 #else // FEATURE_CLICKONCE
2639 internal ApplicationTrust ApplicationTrust {
2640 #endif // FEATURE_CLICKONCE
2642 if (_applicationTrust == null && _IsFastFullTrustDomain) {
2643 _applicationTrust = new ApplicationTrust(new PermissionSet(PermissionState.Unrestricted));
2646 return _applicationTrust;
2650 #if FEATURE_IMPERSONATION
2651 // Set the default principal object to be attached to threads if they
2652 // attempt to bind to a principal while executing in this appdomain. The
2653 // default can only be set once.
2654 [System.Security.SecuritySafeCritical] // auto-generated
2655 [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
2656 public void SetThreadPrincipal(IPrincipal principal)
2658 if (principal == null)
2659 throw new ArgumentNullException("principal");
2660 Contract.EndContractBlock();
2663 // Check that principal has not been set previously.
2664 if (_DefaultPrincipal != null)
2665 throw new PolicyException(Environment.GetResourceString("Policy_PrincipalTwice"));
2667 _DefaultPrincipal = principal;
2670 #endif // FEATURE_IMPERSONATION
2672 #if FEATURE_CAS_POLICY
2673 // Similar to the above, but sets the class of principal to be created
2675 [System.Security.SecuritySafeCritical] // auto-generated
2676 [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
2677 public void SetPrincipalPolicy(PrincipalPolicy policy)
2679 _PrincipalPolicy = policy;
2684 #if FEATURE_REMOTING
2685 // This method gives AppDomain an infinite life time by preventing a lease from being
2687 [System.Security.SecurityCritical] // auto-generated_required
2688 public override Object InitializeLifetimeService()
2692 // This is useful for requesting execution of some code
2693 // in another appDomain ... the delegate may be defined
2694 // on a marshal-by-value object or a marshal-by-ref or
2695 // contextBound object.
2696 public void DoCallBack(CrossAppDomainDelegate callBackDelegate)
2698 if (callBackDelegate == null)
2699 throw new ArgumentNullException("callBackDelegate");
2700 Contract.EndContractBlock();
2707 public String DynamicDirectory
2709 [System.Security.SecuritySafeCritical] // auto-generated
2710 [ResourceExposure(ResourceScope.Machine)]
2711 [ResourceConsumption(ResourceScope.Machine)]
2713 String dyndir = GetDynamicDir();
2715 FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, dyndir);
2721 #if FEATURE_CAS_POLICY
2722 [ResourceExposure(ResourceScope.None)]
2723 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2724 public static AppDomain CreateDomain(String friendlyName,
2725 Evidence securityInfo) // Optional
2727 return CreateDomain(friendlyName,
2732 [ResourceExposure(ResourceScope.Machine)]
2733 [ResourceConsumption(ResourceScope.Machine)]
2734 public static AppDomain CreateDomain(String friendlyName,
2735 Evidence securityInfo, // Optional
2737 String appRelativeSearchPath,
2738 bool shadowCopyFiles)
2740 AppDomainSetup info = new AppDomainSetup();
2741 info.ApplicationBase = appBasePath;
2742 info.PrivateBinPath = appRelativeSearchPath;
2744 info.ShadowCopyFiles = "true";
2746 return CreateDomain(friendlyName,
2750 #endif // #if FEATURE_CAS_POLICY (not exposed in core)
2753 [System.Security.SecurityCritical] // auto-generated
2754 [ResourceExposure(ResourceScope.Machine)]
2755 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2756 extern private String GetDynamicDir();
2758 // Private helpers called from unmanaged code.
2760 #if FEATURE_REMOTING
2762 [ResourceExposure(ResourceScope.None)]
2763 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2764 public static AppDomain CreateDomain(String friendlyName)
2766 return CreateDomain(friendlyName, null, null);
2770 // Marshal a single object into a serialized blob.
2771 [System.Security.SecurityCritical] // auto-generated
2772 private static byte[] MarshalObject(Object o)
2774 CodeAccessPermission.Assert(true);
2776 return Serialize(o);
2779 // Marshal two objects into serialized blobs.
2780 [System.Security.SecurityCritical] // auto-generated
2781 private static byte[] MarshalObjects(Object o1, Object o2, out byte[] blob2)
2783 CodeAccessPermission.Assert(true);
2785 byte[] blob1 = Serialize(o1);
2786 blob2 = Serialize(o2);
2790 // Unmarshal a single object from a serialized blob.
2791 [System.Security.SecurityCritical] // auto-generated
2792 private static Object UnmarshalObject(byte[] blob)
2794 CodeAccessPermission.Assert(true);
2796 return Deserialize(blob);
2799 // Unmarshal two objects from serialized blobs.
2800 [System.Security.SecurityCritical] // auto-generated
2801 private static Object UnmarshalObjects(byte[] blob1, byte[] blob2, out Object o2)
2803 CodeAccessPermission.Assert(true);
2805 Object o1 = Deserialize(blob1);
2806 o2 = Deserialize(blob2);
2811 [System.Security.SecurityCritical] // auto-generated
2812 private static byte[] Serialize(Object o)
2818 else if (o is ISecurityEncodable)
2820 SecurityElement element = ((ISecurityEncodable)o).ToXml();
2821 MemoryStream ms = new MemoryStream( 4096 );
2823 StreamWriter writer = new StreamWriter( ms, Encoding.UTF8 );
2824 element.ToWriter( writer );
2826 return ms.ToArray();
2830 MemoryStream ms = new MemoryStream();
2832 CrossAppDomainSerializer.SerializeObject(o, ms);
2833 return ms.ToArray();
2837 [System.Security.SecurityCritical] // auto-generated
2838 private static Object Deserialize(byte[] blob)
2845 Parser parser = new Parser( blob, Tokenizer.ByteTokenEncoding.UTF8Tokens, 1 );
2846 SecurityElement root = parser.GetTopElement();
2847 if (root.Tag.Equals( "IPermission" ) || root.Tag.Equals( "Permission" ))
2849 IPermission ip = System.Security.Util.XMLUtil.CreatePermission( root, PermissionState.None, false );
2860 else if (root.Tag.Equals( "PermissionSet" ))
2862 PermissionSet permissionSet = new PermissionSet();
2864 permissionSet.FromXml( root, false, false );
2866 return permissionSet;
2868 else if (root.Tag.Equals( "PermissionToken" ))
2870 PermissionToken pToken = new PermissionToken();
2872 pToken.FromXml( root );
2885 using(MemoryStream stream = new MemoryStream( blob, 1, blob.Length - 1 )) {
2886 obj = CrossAppDomainSerializer.DeserializeObject(stream);
2889 Contract.Assert( !(obj is IPermission), "IPermission should be xml deserialized" );
2890 Contract.Assert( !(obj is PermissionSet), "PermissionSet should be xml deserialized" );
2896 #endif // FEATURE_REMOTING
2898 #if FEATURE_LEGACYNETCFFAS
2899 public static IAppDomainPauseManager PauseManager
2901 [System.Security.SecurityCritical]
2904 return AppDomainPauseManager.Instance;
2907 #endif // FEATURE_LEGACYNETCFFAS
2909 #if !FEATURE_CORECLR
2911 // Called by the VM if ICLRExecutionManager::Pause is called with the PAUSE_APP_DOMAINS flag.
2912 // This mimics the behavior of the CoreCLR FAS (fast application switching) model, to ensure
2913 // that code that depends on things happening in a particular order will work.
2915 [System.Security.SecurityCritical]
2916 internal static void Pause()
2918 AppDomainPauseManager.Instance.Pausing();
2919 AppDomainPauseManager.Instance.Paused();
2923 // Called by the VM if ICLRExecutionManager::Resume is called after ICLRExecutionManager::Pause
2924 // was called with the PAUSE_APP_DOMAINS flag.
2925 // This mimics the behavior of the CoreCLR FAS (fast application switching) model, to ensure
2926 // that code that depends on things happening in a particular order will work.
2928 [System.Security.SecurityCritical]
2929 internal static void Resume()
2931 if (AppDomainPauseManager.IsPaused)
2933 AppDomainPauseManager.Instance.Resuming();
2934 AppDomainPauseManager.Instance.Resumed();
2939 private AppDomain() {
2940 throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
2943 [System.Security.SecuritySafeCritical] // auto-generated
2944 [ResourceExposure(ResourceScope.None)]
2945 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2946 private extern int _nExecuteAssembly(RuntimeAssembly assembly, String[] args);
2947 internal int nExecuteAssembly(RuntimeAssembly assembly, String[] args)
2949 return _nExecuteAssembly(assembly, args);
2952 #if FEATURE_VERSIONING
2953 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2954 internal extern void nCreateContext();
2956 [System.Security.SecurityCritical]
2957 [ResourceExposure(ResourceScope.None)]
2958 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2959 [SuppressUnmanagedCodeSecurity]
2960 private static extern void nSetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD);
2963 [System.Security.SecurityCritical] // auto-generated
2965 internal void SetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD)
2967 nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD);
2969 #endif // FEATURE_VERSIONING
2971 #if FEATURE_REMOTING
2972 internal void CreateRemotingData()
2975 if (_RemotingData == null)
2976 _RemotingData = new DomainSpecificRemotingData();
2980 internal DomainSpecificRemotingData RemotingData
2984 if (_RemotingData == null)
2985 CreateRemotingData();
2987 return _RemotingData;
2990 #endif // FEATURE_REMOTING
2992 [System.Security.SecurityCritical] // auto-generated
2993 [ResourceExposure(ResourceScope.None)]
2994 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2995 private extern String nGetFriendlyName();
2996 [System.Security.SecurityCritical] // auto-generated
2997 [ResourceExposure(ResourceScope.None)]
2998 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2999 private extern bool nIsDefaultAppDomainForEvidence();
3001 // support reliability for certain event handlers, if the target
3002 // methods also participate in this discipline. If caller passes
3003 // an existing MulticastDelegate, then we could use a MDA to indicate
3004 // that reliability is not guaranteed. But if it is a single cast
3005 // scenario, we can make it work.
3007 public event EventHandler ProcessExit
3009 [System.Security.SecuritySafeCritical] // auto-generated_required
3014 RuntimeHelpers.PrepareContractedDelegate(value);
3016 _processExit += value;
3022 _processExit -= value;
3027 public event EventHandler DomainUnload
3029 [System.Security.SecuritySafeCritical] // auto-generated_required
3034 RuntimeHelpers.PrepareContractedDelegate(value);
3036 _domainUnload += value;
3040 [System.Security.SecuritySafeCritical]
3045 _domainUnload -= value;
3050 public event UnhandledExceptionEventHandler UnhandledException
3052 [System.Security.SecurityCritical] // auto-generated_required
3057 RuntimeHelpers.PrepareContractedDelegate(value);
3059 _unhandledException += value;
3062 [System.Security.SecurityCritical] // auto-generated_required
3066 _unhandledException -= value;
3070 #if FEATURE_EXCEPTION_NOTIFICATIONS
3071 // This is the event managed code can wireup against to be notified
3072 // about first chance exceptions.
3074 // To register/unregister the callback, the code must be SecurityCritical.
3075 public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
3077 [System.Security.SecurityCritical] // auto-generated_required
3082 RuntimeHelpers.PrepareContractedDelegate(value);
3084 _firstChanceException += value;
3087 [System.Security.SecurityCritical] // auto-generated_required
3091 _firstChanceException -= value;
3094 #endif // FEATURE_EXCEPTION_NOTIFICATIONS
3096 private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
3098 AssemblyLoadEventHandler eventHandler = AssemblyLoad;
3099 if (eventHandler != null) {
3100 AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly);
3101 eventHandler(this, ea);
3105 // This method is called by the VM.
3106 [System.Security.SecurityCritical]
3107 private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName)
3109 ResolveEventHandler eventHandler = _ResourceResolve;
3110 if ( eventHandler == null)
3113 Delegate[] ds = eventHandler.GetInvocationList();
3114 int len = ds.Length;
3115 for (int i = 0; i < len; i++) {
3116 Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(resourceName, assembly));
3117 RuntimeAssembly ret = GetRuntimeAssembly(asm);
3125 // This method is called by the VM
3126 [System.Security.SecurityCritical]
3127 private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
3129 ResolveEventHandler eventHandler = _TypeResolve;
3130 if (eventHandler == null)
3133 Delegate[] ds = eventHandler.GetInvocationList();
3134 int len = ds.Length;
3135 for (int i = 0; i < len; i++) {
3136 Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(typeName, assembly));
3137 RuntimeAssembly ret = GetRuntimeAssembly(asm);
3145 // This method is called by the VM.
3146 [System.Security.SecurityCritical]
3147 private RuntimeAssembly OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
3149 ResolveEventHandler eventHandler = _AssemblyResolve;
3151 if (eventHandler == null)
3156 Delegate[] ds = eventHandler.GetInvocationList();
3157 int len = ds.Length;
3158 for (int i = 0; i < len; i++) {
3159 Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly));
3160 RuntimeAssembly ret = GetRuntimeAssembly(asm);
3168 #if FEATURE_REFLECTION_ONLY_LOAD
3170 private RuntimeAssembly OnReflectionOnlyAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
3172 ResolveEventHandler eventHandler = ReflectionOnlyAssemblyResolve;
3173 if (eventHandler != null) {
3175 Delegate[] ds = eventHandler.GetInvocationList();
3176 int len = ds.Length;
3177 for (int i = 0; i < len; i++) {
3178 Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly));
3179 RuntimeAssembly ret = GetRuntimeAssembly(asm);
3188 #if FEATURE_COMINTEROP
3189 // Called by VM - code:CLRPrivTypeCacheReflectionOnlyWinRT::RaiseNamespaceResolveEvent
3190 private RuntimeAssembly[] OnReflectionOnlyNamespaceResolveEvent(RuntimeAssembly assembly, string namespaceName)
3192 return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnReflectionOnlyNamespaceResolveEvent(this, assembly, namespaceName);
3194 #endif // FEATURE_COMINTEROP
3196 #endif // FEATURE_REFLECTION_ONLY_LOAD
3198 #if FEATURE_COMINTEROP
3199 // Called by VM - code:CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent
3200 private string[] OnDesignerNamespaceResolveEvent(string namespaceName)
3202 return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnDesignerNamespaceResolveEvent(this, namespaceName);
3204 #endif // FEATURE_COMINTEROP
3206 internal AppDomainSetup FusionStore
3209 Contract.Assert(_FusionStore != null,
3210 "Fusion store has not been correctly setup in this domain");
3211 return _FusionStore;
3215 internal static RuntimeAssembly GetRuntimeAssembly(Assembly asm)
3220 RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
3221 if (rtAssembly != null)
3224 AssemblyBuilder ab = asm as AssemblyBuilder;
3226 return ab.InternalAssembly;
3231 [ResourceExposure(ResourceScope.AppDomain)]
3232 private Dictionary<String, Object[]> LocalStore
3235 if (_LocalStore != null)
3238 _LocalStore = new Dictionary<String, Object[]>();
3245 private void TurnOnBindingRedirects()
3247 _FusionStore.DisallowBindingRedirects = false;
3251 // This will throw a CannotUnloadAppDomainException if the appdomain is
3252 // in another process.
3253 #if FEATURE_REMOTING
3254 [System.Security.SecurityCritical] // auto-generated
3255 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
3256 internal static Int32 GetIdForUnload(AppDomain domain)
3258 if (RemotingServices.IsTransparentProxy(domain))
3260 return RemotingServices.GetServerDomainIdForProxy(domain);
3267 // Used to determine if server object context is valid in
3268 // x-domain remoting scenarios.
3269 [System.Security.SecurityCritical] // auto-generated
3270 [ResourceExposure(ResourceScope.None)]
3271 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3272 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
3273 internal static extern bool IsDomainIdValid(Int32 id);
3275 #if FEATURE_REMOTING
3276 [System.Security.SecurityCritical] // auto-generated
3277 [ResourceExposure(ResourceScope.None)]
3278 [MethodImplAttribute(MethodImplOptions.InternalCall)]
3279 static internal extern AppDomain GetDefaultDomain();
3282 #if FEATURE_IMPERSONATION
3283 // Internal routine to retrieve the default principal object. If this is
3284 // called before the principal has been explicitly set, it will
3285 // automatically allocate a default principal based on the policy set by
3286 // SetPrincipalPolicy.
3287 internal IPrincipal GetThreadPrincipal()
3289 IPrincipal principal = null;
3290 if (_DefaultPrincipal == null) {
3291 #if FEATURE_CAS_POLICY
3292 switch (_PrincipalPolicy) {
3293 case PrincipalPolicy.NoPrincipal:
3296 case PrincipalPolicy.UnauthenticatedPrincipal:
3297 principal = new GenericPrincipal(new GenericIdentity("", ""),
3300 #if !FEATURE_PAL && FEATURE_IMPERSONATION
3301 case PrincipalPolicy.WindowsPrincipal:
3302 principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
3304 #endif // !FEATURE_PAL && FEATURE_IMPERSONATION
3310 principal = new GenericPrincipal(new GenericIdentity("", ""),
3316 principal = _DefaultPrincipal;
3320 #endif // FEATURE_IMPERSONATION
3322 #if FEATURE_REMOTING
3324 [System.Security.SecurityCritical] // auto-generated
3325 internal void CreateDefaultContext()
3328 // if it has not been created we ask the Context class to
3329 // create a new default context for this appdomain.
3330 if (_DefaultContext == null)
3331 _DefaultContext = Context.CreateDefaultContext();
3335 [System.Security.SecurityCritical] // auto-generated
3336 internal Context GetDefaultContext()
3338 if (_DefaultContext == null)
3339 CreateDefaultContext();
3340 return _DefaultContext;
3343 // Ensure that evidence provided when creating an AppDomain would not have been used to create a
3344 // sandbox in legacy CAS mode. If it could have been used to create a sandbox, and we're not in CAS
3345 // mode, then we throw an exception to prevent acciental creation of unsandboxed domains where a
3346 // sandbox would have been expected.
3347 [SecuritySafeCritical]
3348 internal static void CheckDomainCreationEvidence(AppDomainSetup creationDomainSetup,
3349 Evidence creationEvidence)
3351 if (creationEvidence != null && !CurrentDomain.IsLegacyCasPolicyEnabled)
3353 if (creationDomainSetup == null || creationDomainSetup.ApplicationTrust == null)
3355 // We allow non-null evidence in CAS mode to support the common pattern of passing in
3356 // AppDomain.CurrentDomain.Evidence. Since the zone evidence must have been changed
3357 // if the user has any expectation of sandboxing the domain under legacy CAS policy,
3358 // we use a zone comparison to check for this pattern. A strict comparison will not
3359 // work, since MSDN samples for creating a domain show using a modified version of the
3360 // current domain's evidence and we would capturce people who copied and pasted these
3361 // samples without intending to sandbox.
3362 Zone creatorsZone = CurrentDomain.EvidenceNoDemand.GetHostEvidence<Zone>();
3363 SecurityZone creatorsSecurityZone = creatorsZone != null ?
3364 creatorsZone.SecurityZone :
3365 SecurityZone.MyComputer;
3367 Zone suppliedZone = creationEvidence.GetHostEvidence<Zone>();
3368 if (suppliedZone != null)
3370 if (suppliedZone.SecurityZone != creatorsSecurityZone &&
3371 suppliedZone.SecurityZone != SecurityZone.MyComputer)
3373 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
3380 #if FEATURE_CAS_POLICY
3381 [System.Security.SecuritySafeCritical] // auto-generated
3382 [SecurityPermissionAttribute( SecurityAction.Demand, ControlAppDomain = true )]
3383 public static AppDomain CreateDomain(String friendlyName,
3384 Evidence securityInfo,
3385 AppDomainSetup info)
3387 return InternalCreateDomain(friendlyName, securityInfo, info);
3390 internal static AppDomain CreateDomain(String friendlyName,
3391 Evidence securityInfo,
3392 AppDomainSetup info)
3394 return InternalCreateDomain(friendlyName, securityInfo, info);
3398 [System.Security.SecurityCritical] // auto-generated
3399 internal static AppDomain InternalCreateDomain(String friendlyName,
3400 Evidence securityInfo,
3401 AppDomainSetup info)
3403 if (friendlyName == null)
3404 throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_String"));
3406 Contract.EndContractBlock();
3408 AppDomain.CheckCreateDomainSupported();
3411 info = new AppDomainSetup();
3412 if (info.TargetFrameworkName == null)
3413 info.TargetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName();
3415 AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
3416 if (domainManager != null)
3417 return domainManager.CreateDomain(friendlyName, securityInfo, info);
3419 // No AppDomainManager is set up for this domain
3421 // If evidence is provided, we check to make sure that is allowed.
3422 if (securityInfo != null)
3424 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
3426 // If we're potentially trying to sandbox without using a homogenous domain, we need to reject
3427 // the domain creation.
3428 CheckDomainCreationEvidence(info, securityInfo);
3431 return nCreateDomain(friendlyName,
3434 securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null,
3435 AppDomain.CurrentDomain.GetSecurityDescriptor());
3437 #endif // FEATURE_REMOTING
3439 #if FEATURE_CAS_POLICY
3442 [ResourceExposure(ResourceScope.Machine)]
3443 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
3444 public static AppDomain CreateDomain (string friendlyName,
3445 Evidence securityInfo,
3446 AppDomainSetup info,
3447 PermissionSet grantSet,
3448 params StrongName[] fullTrustAssemblies)
3451 throw new ArgumentNullException("info");
3452 if (info.ApplicationBase == null)
3453 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AppDomainSandboxAPINeedsExplicitAppBase"));
3454 Contract.EndContractBlock();
3456 if (fullTrustAssemblies == null)
3458 fullTrustAssemblies = new StrongName[0];
3461 info.ApplicationTrust = new ApplicationTrust(grantSet, fullTrustAssemblies);
3462 return CreateDomain(friendlyName, securityInfo, info);
3465 #endif // !FEATURE_PAL
3467 [ResourceExposure(ResourceScope.Machine)]
3468 [ResourceConsumption(ResourceScope.Machine)]
3469 public static AppDomain CreateDomain(String friendlyName,
3470 Evidence securityInfo, // Optional
3472 String appRelativeSearchPath,
3473 bool shadowCopyFiles,
3474 AppDomainInitializer adInit,
3475 string[] adInitArgs)
3477 AppDomainSetup info = new AppDomainSetup();
3478 info.ApplicationBase = appBasePath;
3479 info.PrivateBinPath = appRelativeSearchPath;
3480 info.AppDomainInitializer=adInit;
3481 info.AppDomainInitializerArguments=adInitArgs;
3483 info.ShadowCopyFiles = "true";
3485 return CreateDomain(friendlyName,
3489 #endif // FEATURE_CAS_POLICY
3492 [System.Security.SecurityCritical]
3493 [ResourceExposure(ResourceScope.None)]
3494 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
3495 [SuppressUnmanagedCodeSecurity]
3496 private static extern void nSetNativeDllSearchDirectories(string paths);
3499 [System.Security.SecurityCritical] // auto-generated
3500 [ResourceExposure(ResourceScope.None)]
3501 [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
3502 private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
3504 Contract.Requires(info != null);
3507 if (oldInfo == null) {
3509 // Create the application base and configuration file from the imagelocation
3510 // passed in or use the Win32 Image name.
3511 if(info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null ||
3512 info.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null )
3514 if (info.ApplicationBase == null)
3519 AppDomain defaultDomain = GetDefaultDomain();
3520 if (this == defaultDomain) {
3521 // The default domain gets its defaults from the main process.
3522 info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
3525 // Other domains get their defaults from the default domain. This way, a host process
3526 // can use AppDomainManager to set up the defaults for every domain created in the process.
3527 if (info.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null)
3528 info.ConfigurationFile = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue];
3529 if (info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null)
3530 info.ApplicationBase = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue];
3531 if (info.Value[(int) AppDomainSetup.LoaderInformation.ApplicationNameValue] == null)
3532 info.ApplicationName = defaultDomain.FusionStore.Value[(int) AppDomainSetup.LoaderInformation.ApplicationNameValue];
3535 info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
3541 // If there is no relative path then check the
3543 if(info.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue] == null)
3544 info.PrivateBinPath = Environment.nativeGetEnvironmentVariable(AppDomainSetup.PrivateBinPathEnvironmentVariable);
3546 // Add the developer path if it exists on this
3548 if(info.DeveloperPath == null)
3549 info.DeveloperPath = RuntimeEnvironment.GetDeveloperPath();
3553 // Set up the fusion context
3554 IntPtr fusionContext = GetFusionContext();
3555 info.SetupFusionContext(fusionContext, oldInfo);
3557 // Set loader optimization policy
3559 #if FEATURE_VERSIONING
3561 #endif // FEATURE_VERSIONING
3562 #endif // FEATURE_FUSION
3564 #if FEATURE_LOADER_OPTIMIZATION
3565 if (info.LoaderOptimization != LoaderOptimization.NotSpecified || (oldInfo != null && info.LoaderOptimization != oldInfo.LoaderOptimization))
3566 UpdateLoaderOptimization(info.LoaderOptimization);
3571 // This must be the last action taken
3572 _FusionStore = info;
3575 // used to package up evidence, so it can be serialized
3576 // for the call to InternalRemotelySetupRemoteDomain
3578 private class EvidenceCollection
3580 public Evidence ProvidedSecurityInfo;
3581 public Evidence CreatorsSecurityInfo;
3584 private static void RunInitializer(AppDomainSetup setup)
3586 if (setup.AppDomainInitializer!=null)
3589 if (setup.AppDomainInitializerArguments!=null)
3590 args=(string[])setup.AppDomainInitializerArguments.Clone();
3591 setup.AppDomainInitializer(args);
3595 // Used to switch into other AppDomain and call SetupRemoteDomain.
3596 // We cannot simply call through the proxy, because if there
3597 // are any remoting sinks registered, they can add non-mscorlib
3598 // objects to the message (causing an assembly load exception when
3599 // we try to deserialize it on the other side)
3600 [System.Security.SecurityCritical] // auto-generated
3601 private static object PrepareDataForSetup(String friendlyName,
3602 AppDomainSetup setup,
3603 Evidence providedSecurityInfo,
3604 Evidence creatorsSecurityInfo,
3605 IntPtr parentSecurityDescriptor,
3607 string[] propertyNames,
3608 string[] propertyValues)
3610 byte[] serializedEvidence = null;
3611 bool generateDefaultEvidence = false;
3613 #if FEATURE_CAS_POLICY
3614 // serialize evidence
3615 EvidenceCollection evidenceCollection = null;
3617 if (providedSecurityInfo != null || creatorsSecurityInfo != null)
3619 // If we're just passing through AppDomain.CurrentDomain.Evidence, and that evidence is just
3620 // using the standard runtime AppDomainEvidenceFactory, don't waste time serializing it and
3621 // deserializing it back -- instead, we can recreate a new AppDomainEvidenceFactory in the new
3622 // domain. We only want to do this if there is no HostSecurityManager, otherwise the
3623 // HostSecurityManager could have added additional evidence on top of our standard factory.
3624 HostSecurityManager hsm = CurrentDomain.DomainManager != null ? CurrentDomain.DomainManager.HostSecurityManager : null;
3625 bool hostMayContributeEvidence = hsm != null &&
3626 hsm.GetType() != typeof(HostSecurityManager) &&
3627 (hsm.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence;
3628 if (!hostMayContributeEvidence)
3630 if (providedSecurityInfo != null &&
3631 providedSecurityInfo.IsUnmodified &&
3632 providedSecurityInfo.Target != null &&
3633 providedSecurityInfo.Target is AppDomainEvidenceFactory)
3635 providedSecurityInfo = null;
3636 generateDefaultEvidence = true;
3638 if (creatorsSecurityInfo != null &&
3639 creatorsSecurityInfo.IsUnmodified &&
3640 creatorsSecurityInfo.Target != null &&
3641 creatorsSecurityInfo.Target is AppDomainEvidenceFactory)
3643 creatorsSecurityInfo = null;
3644 generateDefaultEvidence = true;
3648 if ((providedSecurityInfo != null) ||
3649 (creatorsSecurityInfo != null)) {
3650 evidenceCollection = new EvidenceCollection();
3651 evidenceCollection.ProvidedSecurityInfo = providedSecurityInfo;
3652 evidenceCollection.CreatorsSecurityInfo = creatorsSecurityInfo;
3655 if (evidenceCollection != null) {
3656 serializedEvidence =
3657 CrossAppDomainSerializer.SerializeObject(evidenceCollection).GetBuffer();
3659 #endif // FEATURE_CAS_POLICY
3661 AppDomainInitializerInfo initializerInfo = null;
3662 if (setup!=null && setup.AppDomainInitializer!=null)
3663 initializerInfo=new AppDomainInitializerInfo(setup.AppDomainInitializer);
3665 // will travel x-Ad, drop non-agile data
3666 AppDomainSetup newSetup = new AppDomainSetup(setup, false);
3669 // Remove the special AppDomainCompatSwitch entries from the set of name value pairs
3670 // And add them to the AppDomainSetup
3672 // This is only supported on CoreCLR through ICLRRuntimeHost2.CreateAppDomainWithManager
3673 // Desktop code should use System.AppDomain.CreateDomain() or
3674 // System.AppDomainManager.CreateDomain() and add the flags to the AppDomainSetup
3675 List<String> compatList = new List<String>();
3677 if(propertyNames!=null && propertyValues != null)
3679 for (int i=0; i<propertyNames.Length; i++)
3681 if(String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0)
3683 compatList.Add(propertyValues[i]);
3684 propertyNames[i] = null;
3685 propertyValues[i] = null;
3690 if (compatList.Count > 0)
3692 newSetup.SetCompatibilitySwitches(compatList);
3695 #endif // FEATURE_CORECLR
3702 parentSecurityDescriptor,
3703 generateDefaultEvidence,
3710 } // PrepareDataForSetup
3713 [System.Security.SecurityCritical] // auto-generated
3714 [MethodImplAttribute(MethodImplOptions.NoInlining)]
3715 private static Object Setup(Object arg)
3717 Contract.Requires(arg != null && arg is Object[]);
3718 Contract.Requires(((Object[])arg).Length >= 8);
3720 Object[] args=(Object[])arg;
3721 String friendlyName = (String)args[0];
3722 AppDomainSetup setup = (AppDomainSetup)args[1];
3723 IntPtr parentSecurityDescriptor = (IntPtr)args[2];
3724 bool generateDefaultEvidence = (bool)args[3];
3725 byte[] serializedEvidence = (byte[])args[4];
3726 AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
3727 string sandboxName = (string)args[6];
3728 string[] propertyNames = (string[])args[7]; // can contain null elements
3729 string[] propertyValues = (string[])args[8]; // can contain null elements
3731 Evidence providedSecurityInfo = null;
3732 Evidence creatorsSecurityInfo = null;
3735 AppDomain ad = AppDomain.CurrentDomain;
3736 AppDomainSetup newSetup=new AppDomainSetup(setup,false);
3738 if(propertyNames!=null && propertyValues != null)
3740 for (int i=0; i<propertyNames.Length; i++)
3743 if(propertyNames[i]=="APPBASE") // make sure in [....] with Fusion
3745 if(propertyValues[i]==null)
3746 throw new ArgumentNullException("APPBASE");
3748 if (Path.IsRelative(propertyValues[i]))
3749 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3751 newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
3753 #if FEATURE_CAS_POLICY
3754 else if(propertyNames[i]=="LOCATION_URI" && providedSecurityInfo==null)
3756 providedSecurityInfo=new Evidence();
3757 providedSecurityInfo.AddHostEvidence(new Url(propertyValues[i]));
3758 ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
3760 #endif // FEATURE_CAS_POLICY
3761 #if FEATURE_LOADER_OPTIMIZATION
3763 if(propertyNames[i]=="LOADER_OPTIMIZATION")
3765 if(propertyValues[i]==null)
3766 throw new ArgumentNullException("LOADER_OPTIMIZATION");
3768 switch(propertyValues[i])
3770 case "SingleDomain": newSetup.LoaderOptimization=LoaderOptimization.SingleDomain;break;
3771 case "MultiDomain": newSetup.LoaderOptimization=LoaderOptimization.MultiDomain;break;
3772 case "MultiDomainHost": newSetup.LoaderOptimization=LoaderOptimization.MultiDomainHost;break;
3773 case "NotSpecified": newSetup.LoaderOptimization=LoaderOptimization.NotSpecified;break;
3774 default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION");
3777 #endif // FEATURE_LOADER_OPTIMIZATION
3780 if(propertyNames[i]=="NATIVE_DLL_SEARCH_DIRECTORIES")
3782 if(propertyValues[i]==null)
3783 throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
3784 ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
3785 string paths = (string)propertyValues[i];
3786 if( paths.Length==0 )
3788 nSetNativeDllSearchDirectories(paths);
3791 if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES")
3793 if(propertyValues[i]==null)
3794 throw new ArgumentNullException("TRUSTED_PLATFORM_ASSEMBLIES");
3796 StringBuilder normalisedAppPathList = new StringBuilder();
3797 foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3800 if( path.Length==0 ) // skip empty dirs
3803 if (Path.IsRelative(path))
3804 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3806 string appPath = NormalizePath(path, fullCheck: true);
3808 normalisedAppPathList.Append(appPath);
3809 normalisedAppPathList.Append(Path.PathSeparator);
3811 // Strip the last separator
3812 if (normalisedAppPathList.Length > 0)
3814 normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3816 ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null); // not supported by fusion, so set explicitly
3819 if(propertyNames[i]=="PLATFORM_RESOURCE_ROOTS")
3821 if(propertyValues[i]==null)
3822 throw new ArgumentNullException("PLATFORM_RESOURCE_ROOTS");
3824 StringBuilder normalisedAppPathList = new StringBuilder();
3825 foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3828 if( path.Length==0 ) // skip empty dirs
3831 if (Path.IsRelative(path))
3832 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3834 string appPath = NormalizePath(path, fullCheck: true);
3836 normalisedAppPathList.Append(appPath);
3837 normalisedAppPathList.Append(Path.PathSeparator);
3839 // Strip the last separator
3840 if (normalisedAppPathList.Length > 0)
3842 normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3844 ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null); // not supported by fusion, so set explicitly
3847 if(propertyNames[i]=="APP_PATHS")
3849 if(propertyValues[i]==null)
3850 throw new ArgumentNullException("APP_PATHS");
3852 StringBuilder normalisedAppPathList = new StringBuilder();
3853 foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3856 if( path.Length==0 ) // skip empty dirs
3859 if (Path.IsRelative(path))
3860 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3862 string appPath = NormalizePath(path, fullCheck: true);
3864 normalisedAppPathList.Append(appPath);
3865 normalisedAppPathList.Append(Path.PathSeparator);
3867 // Strip the last separator
3868 if (normalisedAppPathList.Length > 0)
3870 normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3872 ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null); // not supported by fusion, so set explicitly
3875 if(propertyNames[i]=="APP_NI_PATHS")
3877 if(propertyValues[i]==null)
3878 throw new ArgumentNullException("APP_NI_PATHS");
3880 StringBuilder normalisedAppPathList = new StringBuilder();
3881 foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3884 if( path.Length==0 ) // skip empty dirs
3887 if (Path.IsRelative(path))
3888 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3890 string appPath = NormalizePath(path, fullCheck: true);
3892 normalisedAppPathList.Append(appPath);
3893 normalisedAppPathList.Append(Path.PathSeparator);
3895 // Strip the last separator
3896 if (normalisedAppPathList.Length > 0)
3898 normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3900 ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null); // not supported by fusion, so set explicitly
3903 if(propertyNames[i]!= null)
3905 ad.SetDataHelper(propertyNames[i],propertyValues[i],null); // just propagate
3912 #if !FEATURE_CORECLR
3913 AppDomainSortingSetupInfo sortingSetup = newSetup._AppDomainSortingSetupInfo;
3915 if(sortingSetup != null)
3917 if(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero || sortingSetup._pfnCompareStringEx == IntPtr.Zero || sortingSetup._pfnLCMapStringEx == IntPtr.Zero || sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
3918 || sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero || sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero)
3921 if(!(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero && sortingSetup._pfnCompareStringEx == IntPtr.Zero && sortingSetup._pfnLCMapStringEx == IntPtr.Zero && sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
3922 && sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero && sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero))
3924 // Some functions defined but not all of them.
3925 throw new ArgumentException(Environment.GetResourceString("ArgumentException_NotAllCustomSortingFuncsDefined"));
3932 ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup
3934 // technically, we don't need this, newSetup refers to the same object as FusionStore
3935 // but it's confusing since it isn't immediately obvious whether we have a ref or a copy
3936 AppDomainSetup adSetup = ad.FusionStore;
3940 #if !FEATURE_FT_CORECLR
3941 BCLDebug.Assert(sandboxName == "Internet", "Sandbox is not Internet");
3942 #endif // !FEATURE_FT_CORECLR
3944 adSetup.InternalSetApplicationTrust(sandboxName);
3945 #endif // FEATURE_CORECLR
3947 #if !FEATURE_CORECLR // not used by coreclr
3948 if (serializedEvidence != null) {
3949 EvidenceCollection evidenceCollection = (EvidenceCollection)
3950 CrossAppDomainSerializer.DeserializeObject(new MemoryStream(serializedEvidence));
3951 providedSecurityInfo = evidenceCollection.ProvidedSecurityInfo;
3952 creatorsSecurityInfo = evidenceCollection.CreatorsSecurityInfo;
3955 // set up the friendly name
3956 ad.nSetupFriendlyName(friendlyName);
3958 #if FEATURE_COMINTEROP
3959 if (setup != null && setup.SandboxInterop)
3961 ad.nSetDisableInterfaceCache();
3963 #endif // FEATURE_COMINTEROP
3965 // set up the AppDomainManager for this domain and initialize security.
3966 if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null)
3968 ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType);
3972 // set any conditial-aptca visible assemblies
3973 ad.PartialTrustVisibleAssemblies = adSetup.PartialTrustVisibleAssemblies;
3974 #endif // FEATURE_APTCA
3976 ad.CreateAppDomainManager(); // could modify FusionStore's object
3977 ad.InitializeDomainSecurity(providedSecurityInfo,
3978 creatorsSecurityInfo,
3979 generateDefaultEvidence,
3980 parentSecurityDescriptor,
3983 // can load user code now
3984 if(initializerInfo!=null)
3985 adSetup.AppDomainInitializer=initializerInfo.Unwrap();
3986 RunInitializer(adSetup);
3988 // Activate the application if needed.
3989 #if FEATURE_CLICKONCE
3990 ObjectHandle oh = null;
3991 if (adSetup.ActivationArguments != null && adSetup.ActivationArguments.ActivateInstance)
3992 oh = Activator.CreateInstance(ad.ActivationContext);
3993 return RemotingServices.MarshalInternal(oh, null, null);
3996 #endif // FEATURE_CLICKONCE
3999 [SecuritySafeCritical]
4000 internal static string NormalizePath(string path, bool fullCheck)
4002 // We have to directly hit LegacyNormalizePath to avoid loading quirks for
4003 // the AppDomain. (Once we have runtime support for long paths we can
4004 // use the new normalization in path, but we still need to go in directly
4005 // to avoid quirks.)
4006 return Path.LegacyNormalizePath(
4008 fullCheck: fullCheck,
4009 maxPathLength: PathInternal.MaxShortPath,
4010 expandShortPaths: true);
4014 // Called from DomainAssembly in Conditional APTCA cases
4015 [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
4016 [SecuritySafeCritical]
4017 private bool IsAssemblyOnAptcaVisibleList(RuntimeAssembly assembly)
4019 if (_aptcaVisibleAssemblies == null)
4022 AssemblyName assemblyName = assembly.GetName();
4023 String name = assemblyName.GetNameWithPublicKey();
4025 name = name.ToUpperInvariant();
4027 int index = Array.BinarySearch<string>(_aptcaVisibleAssemblies, name,
4028 StringComparer.OrdinalIgnoreCase);
4033 //Used to binary search the list of C-APTCA strings for an AssemblyName. It compares assembly name
4034 //and public key token.
4035 private class CAPTCASearcher : IComparer
4037 int IComparer.Compare(object /*string*/lhs, object /*AssemblyName*/rhs)
4039 AssemblyName captcaEntry = new AssemblyName((string)lhs);
4040 AssemblyName comparand = (AssemblyName)rhs;
4041 int nameComp = string.Compare(captcaEntry.Name,
4043 StringComparison.OrdinalIgnoreCase);
4049 //simple names match. Compare public key tokens.
4050 byte[] lhsKey = captcaEntry.GetPublicKeyToken();
4051 byte[] rhsKey = comparand.GetPublicKeyToken();
4053 // We require both sides have a public key token
4062 if (lhsKey.Length < rhsKey.Length)
4066 if (lhsKey.Length > rhsKey.Length)
4071 // Tokens seem valid - make sure the compare correctly
4072 for (int i = 0; i < lhsKey.Length; ++i)
4074 byte lhsByte = lhsKey[i];
4075 byte rhsByte = rhsKey[i];
4077 if (lhsByte < rhsByte)
4081 if (lhsByte > rhsByte)
4092 [System.Security.SecurityCritical]
4093 private unsafe bool IsAssemblyOnAptcaVisibleListRaw(char * namePtr, int nameLen, byte * keyTokenPtr,
4096 //This version is used for checking ngen dependencies against the C-APTCA list. It lets us
4097 //reject ngen images that depend on an assembly that has been disabled in the current domain.
4098 //Since we only have the public key token in the ngen image, we'll check against that. The
4099 //rationale is that if you have a public key token collision in your process you have many
4100 //problems. Since the source of this public key token is an ngen image for a full trust
4101 //assembly, there is essentially no risk to the reduced check.
4102 if (_aptcaVisibleAssemblies == null)
4105 string name = new string(namePtr, 0, nameLen);
4106 byte[] keyToken = new byte[keyTokenLen];
4107 for( int i = 0; i < keyToken.Length; ++i )
4108 keyToken[i] = keyTokenPtr[i];
4110 AssemblyName asmName = new AssemblyName();
4111 asmName.Name = name;
4112 asmName.SetPublicKeyToken(keyToken);
4115 int index = Array.BinarySearch(_aptcaVisibleAssemblies, asmName, new CAPTCASearcher());
4116 return (index >= 0);
4118 catch (InvalidOperationException) { /* Can happen for poorly formed assembly names */ return false; }
4123 // This routine is called from unmanaged code to
4124 // set the default fusion context.
4125 [System.Security.SecurityCritical] // auto-generated
4126 private void SetupDomain(bool allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)
4128 // It is possible that we could have multiple threads initializing
4129 // the default domain. We will just take the winner of these two.
4130 // (eg. one thread doing a com call and another doing attach for IJW)
4132 if(_FusionStore == null) {
4133 AppDomainSetup setup = new AppDomainSetup();
4135 // always use internet permission set
4136 setup.InternalSetApplicationTrust("Internet");
4137 #endif // FEATURE_CORECLR
4139 setup.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
4141 setup.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] = path;
4142 if(configFile != null)
4143 setup.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] = configFile;
4145 // Default fusion context starts with binding redirects turned off.
4146 if (!allowRedirects)
4147 setup.DisallowBindingRedirects = true;
4150 #if !FEATURE_CORECLR
4151 if (propertyNames != null) {
4152 BCLDebug.Assert(propertyValues != null, "propertyValues != null");
4153 BCLDebug.Assert(propertyNames.Length == propertyValues.Length, "propertyNames.Length == propertyValues.Length");
4155 for (int i = 0; i < propertyNames.Length; ++i) {
4156 if (String.Equals(propertyNames[i], "PARTIAL_TRUST_VISIBLE_ASSEMBLIES", StringComparison.Ordinal)) {
4157 // The value of the PARTIAL_TRUST_VISIBLE_ASSEMBLIES property is a semicolon
4158 // delimited list of assembly names to add to the
4159 // PartialTrustVisibleAssemblies setting of the domain setup
4160 if (propertyValues[i] != null) {
4161 if (propertyValues[i].Length > 0) {
4162 setup.PartialTrustVisibleAssemblies = propertyValues[i].Split(';');
4165 setup.PartialTrustVisibleAssemblies = new string[0];
4170 // In v4 we disallow anything but PARTIAL_TRUST_VISIBLE_ASSEMBLIES to come
4171 // in via the default domain properties. That restriction could be lifted
4172 // in a future release, at which point this assert should be removed.
4174 // This should be kept in [....] with the real externally facing filter code
4175 // in CorHost2::SetPropertiesForDefaultAppDomain
4176 BCLDebug.Assert(false, "Unexpected default domain property");
4180 #endif // !FEATURE_CORECLR
4183 // Propigate the set of conditional APTCA assemblies that will be used in the default
4184 // domain onto the domain itself and also into the VM
4185 PartialTrustVisibleAssemblies = setup.PartialTrustVisibleAssemblies;
4186 #endif // FEATURE_APTCA
4188 SetupFusionStore(setup, null);
4193 #if FEATURE_LOADER_OPTIMIZATION
4194 [System.Security.SecurityCritical] // auto-generated
4195 private void SetupLoaderOptimization(LoaderOptimization policy)
4197 if(policy != LoaderOptimization.NotSpecified) {
4198 Contract.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
4199 "It is illegal to change the Loader optimization on a domain");
4201 FusionStore.LoaderOptimization = policy;
4202 UpdateLoaderOptimization(FusionStore.LoaderOptimization);
4208 [System.Security.SecurityCritical] // auto-generated
4209 [ResourceExposure(ResourceScope.None)]
4210 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4211 internal extern IntPtr GetFusionContext();
4212 #endif // FEATURE_FUSION
4214 [System.Security.SecurityCritical] // auto-generated
4215 [ResourceExposure(ResourceScope.None)]
4216 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4217 internal extern IntPtr GetSecurityDescriptor();
4219 #if FEATURE_REMOTING
4220 [System.Security.SecurityCritical] // auto-generated
4221 [ResourceExposure(ResourceScope.None)]
4222 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4223 internal static extern AppDomain nCreateDomain(String friendlyName,
4224 AppDomainSetup setup,
4225 Evidence providedSecurityInfo,
4226 Evidence creatorsSecurityInfo,
4227 IntPtr parentSecurityDescriptor);
4229 [System.Security.SecurityCritical] // auto-generated
4230 [ResourceExposure(ResourceScope.None)]
4231 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4232 internal static extern ObjRef nCreateInstance(String friendlyName,
4233 AppDomainSetup setup,
4234 Evidence providedSecurityInfo,
4235 Evidence creatorsSecurityInfo,
4236 IntPtr parentSecurityDescriptor);
4240 private void SetupDomainSecurity(Evidence appDomainEvidence,
4241 IntPtr creatorsSecurityDescriptor,
4242 bool publishAppDomain)
4244 Evidence stackEvidence = appDomainEvidence;
4245 SetupDomainSecurity(GetNativeHandle(),
4246 JitHelpers.GetObjectHandleOnStack(ref stackEvidence),
4247 creatorsSecurityDescriptor,
4253 [ResourceExposure(ResourceScope.None)]
4254 [SuppressUnmanagedCodeSecurity]
4255 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
4256 private static extern void SetupDomainSecurity(AppDomainHandle appDomain,
4257 ObjectHandleOnStack appDomainEvidence,
4258 IntPtr creatorsSecurityDescriptor,
4259 [MarshalAs(UnmanagedType.Bool)] bool publishAppDomain);
4261 [System.Security.SecurityCritical] // auto-generated
4262 [ResourceExposure(ResourceScope.None)]
4263 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4264 private extern void nSetupFriendlyName(string friendlyName);
4266 #if FEATURE_COMINTEROP
4267 [ResourceExposure(ResourceScope.None)]
4268 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4269 private extern void nSetDisableInterfaceCache();
4270 #endif // FEATURE_COMINTEROP
4272 #if FEATURE_LOADER_OPTIMIZATION
4273 [System.Security.SecurityCritical] // auto-generated
4274 [ResourceExposure(ResourceScope.None)]
4275 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4276 internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
4281 // This is just designed to prevent compiler warnings.
4282 // This field is used from native, but we need to prevent the compiler warnings.
4285 [System.Security.SecurityCritical] // auto-generated_required
4286 [Obsolete("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
4287 [ResourceExposure(ResourceScope.Machine)]
4288 [ResourceConsumption(ResourceScope.Machine)]
4289 public void SetShadowCopyPath(String path)
4291 InternalSetShadowCopyPath(path);
4294 [System.Security.SecurityCritical] // auto-generated_required
4295 [Obsolete("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. http://go.microsoft.com/fwlink/?linkid=14202")]
4296 public void SetShadowCopyFiles()
4298 InternalSetShadowCopyFiles();
4301 [System.Security.SecurityCritical] // auto-generated_required
4302 [Obsolete("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. http://go.microsoft.com/fwlink/?linkid=14202")]
4303 [ResourceExposure(ResourceScope.Machine)]
4304 [ResourceConsumption(ResourceScope.Machine)]
4305 public void SetDynamicBase(String path)
4307 InternalSetDynamicBase(path);
4309 #endif // FEATURE_FUSION
4311 public AppDomainSetup SetupInformation
4314 return new AppDomainSetup(FusionStore,true);
4319 [System.Security.SecurityCritical] // auto-generated
4320 [ResourceExposure(ResourceScope.Machine)]
4321 [ResourceConsumption(ResourceScope.Machine)]
4322 internal void InternalSetShadowCopyPath(String path)
4326 IntPtr fusionContext = GetFusionContext();
4327 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyDirectoriesKey, path);
4329 FusionStore.ShadowCopyDirectories = path;
4332 [System.Security.SecurityCritical] // auto-generated
4333 internal void InternalSetShadowCopyFiles()
4335 IntPtr fusionContext = GetFusionContext();
4336 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyFilesKey, "true");
4337 FusionStore.ShadowCopyFiles = "true";
4340 [System.Security.SecurityCritical] // auto-generated
4341 [ResourceExposure(ResourceScope.Machine)]
4342 [ResourceConsumption(ResourceScope.Machine)]
4343 internal void InternalSetCachePath(String path)
4345 FusionStore.CachePath = path;
4346 if (FusionStore.Value[(int) AppDomainSetup.LoaderInformation.CachePathValue] != null)
4348 IntPtr fusionContext = GetFusionContext();
4349 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.CachePathKey,
4350 FusionStore.Value[(int) AppDomainSetup.LoaderInformation.CachePathValue]);
4354 [System.Security.SecurityCritical] // auto-generated
4355 [ResourceExposure(ResourceScope.Machine)]
4356 [ResourceConsumption(ResourceScope.Machine)]
4357 internal void InternalSetPrivateBinPath(String path)
4359 IntPtr fusionContext = GetFusionContext();
4360 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.PrivateBinPathKey, path);
4361 FusionStore.PrivateBinPath = path;
4364 [System.Security.SecurityCritical] // auto-generated
4365 [ResourceExposure(ResourceScope.Machine)]
4366 [ResourceConsumption(ResourceScope.Machine)]
4367 internal void InternalSetDynamicBase(String path)
4369 FusionStore.DynamicBase = path;
4370 if (FusionStore.Value[(int) AppDomainSetup.LoaderInformation.DynamicBaseValue] != null)
4372 IntPtr fusionContext = GetFusionContext();
4373 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.DynamicBaseKey,
4374 FusionStore.Value[(int) AppDomainSetup.LoaderInformation.DynamicBaseValue]);
4377 #endif // FEATURE_FUSION
4379 [System.Security.SecurityCritical] // auto-generated
4380 [ResourceExposure(ResourceScope.None)]
4381 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4382 internal extern String IsStringInterned(String str);
4384 [System.Security.SecurityCritical] // auto-generated
4385 [ResourceExposure(ResourceScope.None)]
4386 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4387 internal extern String GetOrInternString(String str);
4390 [ResourceExposure(ResourceScope.None)]
4391 [SuppressUnmanagedCodeSecurity]
4392 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
4393 private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
4395 #if FEATURE_CAS_POLICY
4397 [ResourceExposure(ResourceScope.None)]
4398 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
4399 [SuppressUnmanagedCodeSecurity]
4400 [return: MarshalAs(UnmanagedType.Bool)]
4401 private static extern bool GetIsLegacyCasPolicyEnabled(AppDomainHandle domain);
4402 #endif // FEATURE_CAS_POLICY
4404 public PermissionSet PermissionSet
4406 // SecurityCritical because permissions can contain sensitive information such as paths
4410 PermissionSet grantSet = null;
4411 GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref grantSet));
4413 if (grantSet != null)
4415 return grantSet.Copy();
4419 return new PermissionSet(PermissionState.Unrestricted);
4424 public bool IsFullyTrusted
4426 [SecuritySafeCritical]
4429 PermissionSet grantSet = null;
4430 GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref grantSet));
4432 return grantSet == null || grantSet.IsUnrestricted();
4436 public bool IsHomogenous
4440 // Homogenous AppDomains always have an ApplicationTrust associated with them
4441 return _IsFastFullTrustDomain || _applicationTrust != null;
4445 #if FEATURE_CAS_POLICY
4446 internal bool IsLegacyCasPolicyEnabled
4448 [SecuritySafeCritical]
4451 return GetIsLegacyCasPolicyEnabled(GetNativeHandle());
4455 // Determine what this homogenous domain thinks the grant set should be for a specific set of evidence
4456 [SecuritySafeCritical]
4457 internal PermissionSet GetHomogenousGrantSet(Evidence evidence)
4459 Contract.Assert(evidence != null);
4460 Contract.Assert(IsHomogenous);
4461 Contract.Assert(evidence.GetHostEvidence<GacInstalled>() == null);
4463 if (_IsFastFullTrustDomain)
4465 return new PermissionSet(PermissionState.Unrestricted);
4468 // If the ApplicationTrust's full trust list calls out the assembly, then it is fully trusted
4469 if (evidence.GetDelayEvaluatedHostEvidence<StrongName>() != null)
4471 foreach (StrongName fullTrustAssembly in ApplicationTrust.FullTrustAssemblies)
4473 StrongNameMembershipCondition sn = new StrongNameMembershipCondition(fullTrustAssembly.PublicKey,
4474 fullTrustAssembly.Name,
4475 fullTrustAssembly.Version);
4477 object usedEvidence = null;
4478 if ((sn as IReportMatchMembershipCondition).Check(evidence, out usedEvidence))
4480 IDelayEvaluatedEvidence delayEvidence = usedEvidence as IDelayEvaluatedEvidence;
4481 if (usedEvidence != null)
4483 delayEvidence.MarkUsed();
4486 return new PermissionSet(PermissionState.Unrestricted);
4491 // Otherwise, the grant set is just the default grant set
4492 return ApplicationTrust.DefaultGrantSet.PermissionSet.Copy();
4494 #endif // FEATURE_CAS_POLICY
4496 [System.Security.SecurityCritical] // auto-generated
4497 [ResourceExposure(ResourceScope.None)]
4498 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4499 private extern void nChangeSecurityPolicy();
4501 [System.Security.SecurityCritical] // auto-generated
4502 [MethodImplAttribute(MethodImplOptions.InternalCall),
4503 ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail),
4504 ResourceExposure(ResourceScope.None)]
4505 internal static extern void nUnload(Int32 domainInternal);
4507 public Object CreateInstanceAndUnwrap(String assemblyName,
4510 ObjectHandle oh = CreateInstance(assemblyName, typeName);
4515 } // CreateInstanceAndUnwrap
4518 public Object CreateInstanceAndUnwrap(String assemblyName,
4520 Object[] activationAttributes)
4522 ObjectHandle oh = CreateInstance(assemblyName, typeName, activationAttributes);
4527 } // CreateInstanceAndUnwrap
4530 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceAndUnwrap which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
4531 public Object CreateInstanceAndUnwrap(String assemblyName,
4534 BindingFlags bindingAttr,
4537 CultureInfo culture,
4538 Object[] activationAttributes,
4539 Evidence securityAttributes)
4541 #pragma warning disable 618
4542 ObjectHandle oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr,
4543 binder, args, culture, activationAttributes, securityAttributes);
4544 #pragma warning restore 618
4550 } // CreateInstanceAndUnwrap
4552 public object CreateInstanceAndUnwrap(string assemblyName,
4555 BindingFlags bindingAttr,
4558 CultureInfo culture,
4559 object[] activationAttributes)
4561 ObjectHandle oh = CreateInstance(assemblyName,
4568 activationAttributes);
4578 // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
4579 // release, and the compatibility police won't let us change the name now.
4580 [ResourceExposure(ResourceScope.Machine)]
4581 [ResourceConsumption(ResourceScope.Machine)]
4582 public Object CreateInstanceFromAndUnwrap(String assemblyName,
4585 ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName);
4590 } // CreateInstanceAndUnwrap
4593 // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
4594 // release, and the compatibility police won't let us change the name now.
4595 [ResourceExposure(ResourceScope.Machine)]
4596 [ResourceConsumption(ResourceScope.Machine)]
4597 public Object CreateInstanceFromAndUnwrap(String assemblyName,
4599 Object[] activationAttributes)
4601 ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, activationAttributes);
4606 } // CreateInstanceAndUnwrap
4609 // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
4610 // release, and the compatibility police won't let us change the name now.
4611 [ResourceExposure(ResourceScope.Machine)]
4612 [ResourceConsumption(ResourceScope.Machine)]
4613 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFromAndUnwrap which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
4614 public Object CreateInstanceFromAndUnwrap(String assemblyName,
4617 BindingFlags bindingAttr,
4620 CultureInfo culture,
4621 Object[] activationAttributes,
4622 Evidence securityAttributes)
4624 #pragma warning disable 618
4625 ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr,
4626 binder, args, culture, activationAttributes, securityAttributes);
4627 #pragma warning restore 618
4633 } // CreateInstanceAndUnwrap
4635 [ResourceExposure(ResourceScope.Machine)]
4636 [ResourceConsumption(ResourceScope.Machine)]
4637 public object CreateInstanceFromAndUnwrap(string assemblyFile,
4640 BindingFlags bindingAttr,
4643 CultureInfo culture,
4644 object[] activationAttributes)
4646 ObjectHandle oh = CreateInstanceFrom(assemblyFile,
4653 activationAttributes);
4664 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
4670 [System.Security.SecuritySafeCritical] // auto-generated
4671 [ResourceExposure(ResourceScope.None)]
4672 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4673 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
4674 internal extern Int32 GetId();
4676 internal const Int32 DefaultADID = 1;
4678 public bool IsDefaultAppDomain()
4680 if (GetId()==DefaultADID)
4685 [ResourceExposure(ResourceScope.Machine)]
4686 [ResourceConsumption(ResourceScope.Machine)]
4687 private static AppDomainSetup InternalCreateDomainSetup(String imageLocation)
4689 int i = imageLocation.LastIndexOf('\\');
4691 Contract.Assert(i != -1, "invalid image location");
4693 AppDomainSetup info = new AppDomainSetup();
4695 info.ApplicationBase = imageLocation.Substring(0, i+1);
4697 StringBuilder config = new StringBuilder(imageLocation.Substring(i+1));
4698 config.Append(AppDomainSetup.ConfigurationExtension);
4699 info.ConfigurationFile = config.ToString();
4704 // Used by the validator for testing but not executing an assembly
4705 #if FEATURE_REMOTING
4706 [ResourceExposure(ResourceScope.Machine)]
4707 [ResourceConsumption(ResourceScope.Machine)]
4708 private static AppDomain InternalCreateDomain(String imageLocation)
4710 AppDomainSetup info = InternalCreateDomainSetup(imageLocation);
4711 return CreateDomain("Validator",
4717 #if FEATURE_APPDOMAIN_RESOURCE_MONITORING
4718 [System.Security.SecurityCritical] // auto-generated
4719 [ResourceExposure(ResourceScope.None)]
4720 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4721 private static extern void nEnableMonitoring();
4723 [System.Security.SecurityCritical] // auto-generated
4724 [ResourceExposure(ResourceScope.None)]
4725 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4726 private static extern bool nMonitoringIsEnabled();
4728 // return -1 if ARM is not supported.
4729 [System.Security.SecurityCritical] // auto-generated
4730 [ResourceExposure(ResourceScope.None)]
4731 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4732 private extern Int64 nGetTotalProcessorTime();
4734 // return -1 if ARM is not supported.
4735 [System.Security.SecurityCritical] // auto-generated
4736 [ResourceExposure(ResourceScope.None)]
4737 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4738 private extern Int64 nGetTotalAllocatedMemorySize();
4740 // return -1 if ARM is not supported.
4741 [System.Security.SecurityCritical] // auto-generated
4742 [ResourceExposure(ResourceScope.None)]
4743 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4744 private extern Int64 nGetLastSurvivedMemorySize();
4746 // return -1 if ARM is not supported.
4747 [System.Security.SecurityCritical] // auto-generated
4748 [ResourceExposure(ResourceScope.None)]
4749 [MethodImplAttribute(MethodImplOptions.InternalCall)]
4750 private static extern Int64 nGetLastSurvivedProcessMemorySize();
4752 public static bool MonitoringIsEnabled
4754 [System.Security.SecurityCritical]
4756 return nMonitoringIsEnabled();
4759 [System.Security.SecurityCritical]
4763 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTrue"));
4767 nEnableMonitoring();
4772 // Gets the total processor time for this AppDomain.
4773 // Throws NotSupportedException if ARM is not enabled.
4774 public TimeSpan MonitoringTotalProcessorTime
4776 [System.Security.SecurityCritical]
4778 Int64 i64ProcessorTime = nGetTotalProcessorTime();
4779 if (i64ProcessorTime == -1)
4781 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4783 return new TimeSpan(i64ProcessorTime);
4787 // Gets the number of bytes allocated in this AppDomain since
4788 // the AppDomain was created.
4789 // Throws NotSupportedException if ARM is not enabled.
4790 public Int64 MonitoringTotalAllocatedMemorySize
4792 [System.Security.SecurityCritical]
4794 Int64 i64AllocatedMemory = nGetTotalAllocatedMemorySize();
4795 if (i64AllocatedMemory == -1)
4797 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4799 return i64AllocatedMemory;
4803 // Gets the number of bytes survived after the last collection
4804 // that are known to be held by this AppDomain. After a full
4805 // collection this number is accurate and complete. After an
4806 // ephemeral collection this number is potentially incomplete.
4807 // Throws NotSupportedException if ARM is not enabled.
4808 public Int64 MonitoringSurvivedMemorySize
4810 [System.Security.SecurityCritical]
4812 Int64 i64LastSurvivedMemory = nGetLastSurvivedMemorySize();
4813 if (i64LastSurvivedMemory == -1)
4815 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4817 return i64LastSurvivedMemory;
4821 // Gets the total bytes survived from the last collection. After
4822 // a full collection this number represents the number of the bytes
4823 // being held live in managed heaps. (This number should be close
4824 // to the number obtained from GC.GetTotalMemory for a full collection.)
4825 // After an ephemeral collection this number represents the number
4826 // of bytes being held live in ephemeral generations.
4827 // Throws NotSupportedException if ARM is not enabled.
4828 public static Int64 MonitoringSurvivedProcessMemorySize
4830 [System.Security.SecurityCritical]
4832 Int64 i64LastSurvivedProcessMemory = nGetLastSurvivedProcessMemorySize();
4833 if (i64LastSurvivedProcessMemory == -1)
4835 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4837 return i64LastSurvivedProcessMemory;
4843 [System.Security.SecurityCritical] // auto-generated
4844 [ResourceExposure(ResourceScope.Machine)]
4845 [ResourceConsumption(ResourceScope.Machine)]
4846 private void InternalSetDomainContext(String imageLocation)
4848 SetupFusionStore(InternalCreateDomainSetup(imageLocation), null);
4852 #if !FEATURE_CORECLR
4853 // this method is required so Object.GetType is not made virtual by the compiler
4854 // _AppDomain.GetType()
4855 public new Type GetType()
4857 return base.GetType();
4860 void _AppDomain.GetTypeInfoCount(out uint pcTInfo)
4862 throw new NotImplementedException();
4865 void _AppDomain.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
4867 throw new NotImplementedException();
4870 void _AppDomain.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
4872 throw new NotImplementedException();
4875 // If you implement this method, make sure to include _AppDomain.Invoke in VM\DangerousAPIs.h and
4876 // include _AppDomain in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
4877 void _AppDomain.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
4879 throw new NotImplementedException();
4884 // CallBacks provide a facility to request execution of some code
4885 // in another context/appDomain.
4886 // CrossAppDomainDelegate type is defined for appdomain call backs.
4887 // The delegate used to request a callbak through the DoCallBack method
4888 // must be of CrossContextDelegate type.
4889 #if FEATURE_REMOTING
4890 [System.Runtime.InteropServices.ComVisible(true)]
4891 public delegate void CrossAppDomainDelegate();
4895 /// Handle used to marshal an AppDomain to the VM (eg QCall). When marshaled via a QCall, the target
4896 /// method in the VM will recieve a QCall::AppDomainHandle parameter.
4898 internal struct AppDomainHandle
4900 private IntPtr m_appDomainHandle;
4902 // Note: generall an AppDomainHandle should not be directly constructed, instead the
4903 // code:System.AppDomain.GetNativeHandle method should be called to get the handle for a specific
4905 internal AppDomainHandle(IntPtr domainHandle)
4907 m_appDomainHandle = domainHandle;