[coop] Temporarily restore MonoThreadInfo when TLS destructor runs. Fixes #43099
[mono.git] / mcs / class / referencesource / mscorlib / system / appdomain.cs
1 // ==++==
2 // 
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 // 
5 // ==--==
6 /*=============================================================================
7 **
8 ** Class: AppDomain
9 **
10 ** <OWNER>[....]</OWNER>
11 **
12 **
13 ** Purpose: Domains represent an application within the runtime. Objects can 
14 **          not be shared between domains and each domain can be configured
15 **          independently. 
16 **
17 **
18 =============================================================================*/
19
20 namespace System {
21     using System;
22 #if FEATURE_CLICKONCE    
23     using System.Deployment.Internal.Isolation;
24     using System.Deployment.Internal.Isolation.Manifest;
25     using System.Runtime.Hosting;    
26 #endif    
27     using System.Reflection;
28     using System.Runtime;
29     using System.Runtime.CompilerServices;
30 #if FEATURE_REMOTING    
31     using System.Runtime.Remoting.Channels;
32     using System.Runtime.Remoting.Contexts;
33 #endif    
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;   
44 #if FEATURE_REMOTING        
45     using Context = System.Runtime.Remoting.Contexts.Context;
46 #endif
47     using System.Reflection.Emit;
48     using CultureInfo = System.Globalization.CultureInfo;
49 #if !FEATURE_CORECLR
50     using System.Globalization;
51 #endif
52     using System.IO;
53     using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
54     using System.Text;
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
62
63     [ComVisible(true)]
64     public class ResolveEventArgs : EventArgs
65     {
66         private String _Name;
67         private Assembly _RequestingAssembly;
68
69         public String Name {
70             get {
71                 return _Name;
72             }
73         }
74
75         public Assembly RequestingAssembly 
76         {
77             get
78             {
79                 return _RequestingAssembly;
80             }
81         }
82
83         public ResolveEventArgs(String name)
84         {
85             _Name = name;
86         }
87
88         public ResolveEventArgs(String name, Assembly requestingAssembly)
89         {
90             _Name = name;
91             _RequestingAssembly = requestingAssembly;
92         }
93     }
94
95     [ComVisible(true)]
96     public class AssemblyLoadEventArgs : EventArgs
97     {
98         private Assembly _LoadedAssembly;
99
100         public Assembly LoadedAssembly {
101             get {
102                 return _LoadedAssembly;
103             }
104         }
105
106         public AssemblyLoadEventArgs(Assembly loadedAssembly)
107         {
108             _LoadedAssembly = loadedAssembly;
109         }
110     }
111
112
113     #if FEATURE_CORECLR
114     [System.Security.SecurityCritical] // auto-generated
115     #endif
116     [Serializable]
117     [ComVisible(true)]
118     public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
119
120     [Serializable]
121     [ComVisible(true)]
122     public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args);
123
124     [Serializable]
125     [ComVisible(true)]
126     public delegate void AppDomainInitializer(string[] args);
127
128     internal class AppDomainInitializerInfo
129     {
130         internal class ItemInfo
131         {
132             public string TargetTypeAssembly;
133             public string TargetTypeName;
134             public string MethodName;
135         }
136
137         internal ItemInfo[] Info;
138
139         internal AppDomainInitializerInfo(AppDomainInitializer init)
140         {
141             Info=null;
142             if (init==null)
143                 return;
144             List<ItemInfo> itemInfo = new List<ItemInfo>();
145             List<AppDomainInitializer> nestedDelegates = new List<AppDomainInitializer>();
146             nestedDelegates.Add(init);
147             int idx=0;
148  
149             while (nestedDelegates.Count>idx)
150             {
151                 AppDomainInitializer curr = nestedDelegates[idx++];
152                 Delegate[] list= curr.GetInvocationList();
153                 for (int i=0;i<list.Length;i++)
154                 {
155                     if (!list[i].Method.IsStatic) 
156                     {
157                         if(list[i].Target==null)
158                             continue;
159                     
160                         AppDomainInitializer nested = list[i].Target as AppDomainInitializer;
161                         if (nested!=null)
162                             nestedDelegates.Add(nested);
163                         else
164                             throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"),
165                                list[i].Method.ReflectedType.FullName+"::"+list[i].Method.Name);
166                     }
167                     else
168                     {
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;
173                         itemInfo.Add(info);
174                     }
175                     
176                 }
177             }
178
179             Info = itemInfo.ToArray();            
180         }
181         
182         [System.Security.SecuritySafeCritical]  // auto-generated
183         internal AppDomainInitializer Unwrap()
184         {
185             if (Info==null)
186                 return null;
187             AppDomainInitializer retVal=null;
188             new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
189             for (int i=0;i<Info.Length;i++)
190             {
191                 Assembly assembly=Assembly.Load(Info[i].TargetTypeAssembly);
192                 AppDomainInitializer newVal=(AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer),
193                         assembly.GetType(Info[i].TargetTypeName),
194                         Info[i].MethodName);
195                 if(retVal==null)
196                     retVal=newVal;
197                 else
198                     retVal+=newVal;
199             }
200             return retVal;
201         }
202     }
203
204
205     [ClassInterface(ClassInterfaceType.None)]
206     [ComDefaultInterface(typeof(System._AppDomain))]
207     [ComVisible(true)]
208     public sealed class AppDomain :
209 #if FEATURE_REMOTING
210         MarshalByRefObject,
211 #endif
212         _AppDomain, IEvidenceFactory
213     {
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 
217         // the EE)
218
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;
229
230         [System.Security.SecurityCritical]
231         private ResolveEventHandler _TypeResolve;
232
233         public event ResolveEventHandler TypeResolve
234         {
235             [System.Security.SecurityCritical]
236             add
237             {
238                 lock (this)
239                 {
240                     _TypeResolve += value;
241                 }
242             }
243
244             [System.Security.SecurityCritical]
245             remove
246             {
247                 lock (this)
248                 {
249                     _TypeResolve -= value;
250                 }
251             }
252         }
253
254         [System.Security.SecurityCritical]
255         private ResolveEventHandler _ResourceResolve;
256
257         public event ResolveEventHandler ResourceResolve
258         {
259             [System.Security.SecurityCritical]
260             add
261             {
262                 lock (this)
263                 {
264                     _ResourceResolve += value;
265                 }
266             }
267
268             [System.Security.SecurityCritical]
269             remove
270             {
271                 lock (this)
272                 {
273                     _ResourceResolve -= value;
274                 }
275             }
276         }
277
278         [System.Security.SecurityCritical]
279         private ResolveEventHandler _AssemblyResolve;
280
281         public event ResolveEventHandler AssemblyResolve
282         {
283             [System.Security.SecurityCritical]
284             add
285             {
286                 lock (this)
287                 {
288                     _AssemblyResolve += value;
289                 }
290             }
291
292             [System.Security.SecurityCritical]
293             remove
294             {
295                 lock (this)
296                 {
297                     _AssemblyResolve -= value;
298                 }
299             }
300         }
301
302 #if FEATURE_REFLECTION_ONLY_LOAD
303         [method: System.Security.SecurityCritical]
304         public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
305 #endif // FEATURE_REFLECTION_ONLY
306
307 #if FEATURE_REMOTING        
308         private Context          _DefaultContext;
309 #endif
310
311 #if !FEATURE_PAL
312 #if FEATURE_CLICKONCE
313         private ActivationContext _activationContext;        
314         private ApplicationIdentity _applicationIdentity;        
315 #endif
316 #endif // !FEATURE_PAL
317         private ApplicationTrust _applicationTrust;
318
319 #if FEATURE_IMPERSONATION
320         private IPrincipal       _DefaultPrincipal;
321 #endif // FEATURE_IMPERSONATION
322 #if FEATURE_REMOTING
323         private DomainSpecificRemotingData _RemotingData;
324 #endif
325         private EventHandler     _processExit;
326
327         #if FEATURE_CORECLR
328         [System.Security.SecurityCritical] 
329         #endif
330         private EventHandler     _domainUnload;
331
332         #if FEATURE_CORECLR
333         [System.Security.SecurityCritical] // auto-generated
334         #endif
335         private UnhandledExceptionEventHandler _unhandledException;
336
337 #if FEATURE_APTCA
338         private String[]         _aptcaVisibleAssemblies;
339 #endif
340
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;
345
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
350
351         private IntPtr           _pDomain;                      // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
352
353 #if FEATURE_CAS_POLICY
354         private PrincipalPolicy  _PrincipalPolicy;              // this is an enum
355 #endif        
356         private bool             _HasSetPolicy;
357         private bool             _IsFastFullTrustDomain;        // quick check to see if the AppDomain is fully trusted and homogenous
358         private bool             _compatFlagsInitialized;
359
360         internal const String TargetFrameworkNameAppCompatSetting = "TargetFrameworkName";
361
362 #if FEATURE_APPX
363         private static APPX_FLAGS s_flags;
364
365         //
366         // Keep in async with vm\appdomainnative.cpp
367         //
368         [Flags]
369         private enum APPX_FLAGS
370         {
371             APPX_FLAGS_INITIALIZED =        0x01,
372
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,
379
380             APPX_FLAGS_API_CHECK =          0x10,
381         }
382
383         private static APPX_FLAGS Flags
384         {
385             [SecuritySafeCritical]
386             get
387             {
388                 if (s_flags == 0)
389                     s_flags = nGetAppXFlags();
390
391                 Contract.Assert(s_flags != 0);
392                 return s_flags;
393             }
394         }
395
396         internal static bool ProfileAPICheck
397         {
398             [SecuritySafeCritical]
399             get
400             {
401                 return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0;
402             }
403         }
404
405         internal static bool IsAppXNGen
406         {
407             [SecuritySafeCritical]
408             get
409             {
410                 return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0;
411             }
412         }
413 #endif // FEATURE_APPX
414
415         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
416         [SecurityCritical]
417         [ResourceExposure(ResourceScope.None)]
418         [SuppressUnmanagedCodeSecurity]
419         [return: MarshalAs(UnmanagedType.Bool)]
420         private static extern bool DisableFusionUpdatesFromADManager(AppDomainHandle domain);
421
422 #if FEATURE_APPX
423         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
424         [SecurityCritical]
425         [ResourceExposure(ResourceScope.None)]
426         [SuppressUnmanagedCodeSecurity]
427         [return: MarshalAs(UnmanagedType.I4)]
428         private static extern APPX_FLAGS nGetAppXFlags();
429 #endif
430
431         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
432         [SecurityCritical]
433         [ResourceExposure(ResourceScope.None)]
434         [SuppressUnmanagedCodeSecurity]
435         private static extern void GetAppDomainManagerType(AppDomainHandle domain,
436                                                            StringHandleOnStack retAssembly,
437                                                            StringHandleOnStack retType);
438
439         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
440         [SecurityCritical]
441         [ResourceExposure(ResourceScope.None)]
442         [SuppressUnmanagedCodeSecurity]
443         private static extern void SetAppDomainManagerType(AppDomainHandle domain,
444                                                            string assembly,
445                                                            string type);
446
447         [System.Security.SecurityCritical]  // auto-generated
448         [ResourceExposure(ResourceScope.None)]
449         [MethodImplAttribute(MethodImplOptions.InternalCall)]
450         private static extern void nSetHostSecurityManagerFlags (HostSecurityManagerOptions flags);
451
452         [SecurityCritical]
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);
458
459 #if FEATURE_CAS_POLICY
460         [SecurityCritical]
461         [SuppressUnmanagedCodeSecurity]
462         [ResourceExposure(ResourceScope.None)]
463         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
464         private static extern void SetLegacyCasPolicyEnabled(AppDomainHandle domain);
465
466         [SecurityCritical]
467         private void SetLegacyCasPolicyEnabled()
468         {
469             SetLegacyCasPolicyEnabled(GetNativeHandle());
470         }
471 #endif // FEATURE_CAS_POLICY
472
473         /// <summary>
474         ///     Get a handle used to make a call into the VM pointing to this domain
475         /// </summary>
476         internal AppDomainHandle GetNativeHandle()
477         {
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())
481             {
482                 throw new InvalidOperationException(Environment.GetResourceString("Argument_InvalidHandle"));
483             }
484
485 #if FEATURE_REMOTING
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);
489         }
490
491         /// <summary>
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.
494         /// </summary>
495         [SecuritySafeCritical]
496         private void CreateAppDomainManager()
497         {
498             Contract.Assert(_domainManager == null, "_domainManager == null");
499
500             AppDomainSetup adSetup = FusionStore;
501 #if FEATURE_VERSIONING
502             String trustedPlatformAssemblies = (String)(GetData("TRUSTED_PLATFORM_ASSEMBLIES"));
503             if (trustedPlatformAssemblies != null)
504             {
505                 String platformResourceRoots = (String)(GetData("PLATFORM_RESOURCE_ROOTS"));
506                 if (platformResourceRoots == null)
507                 {
508                     platformResourceRoots = String.Empty;
509                 }
510
511                 String appPaths = (String)(GetData("APP_PATHS"));
512                 if (appPaths == null)
513                 {
514                     appPaths = String.Empty;
515                 }
516
517                 String appNiPaths = (String)(GetData("APP_NI_PATHS"));
518                 if (appNiPaths == null)
519                 {
520                     appNiPaths = String.Empty;
521                 }
522
523                 String appLocalWinMD = (String)(GetData("APP_LOCAL_WINMETADATA"));
524                 if (appLocalWinMD == null)
525                 {
526                     appLocalWinMD = String.Empty;
527                 }
528                 SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD);
529             }
530 #endif // FEATURE_VERSIONING
531
532             string domainManagerAssembly;
533             string domainManagerType;
534             GetAppDomainManagerType(out domainManagerAssembly, out domainManagerType);
535
536             if (domainManagerAssembly != null && domainManagerType != null)
537             {
538                 try
539                 {
540                     new PermissionSet(PermissionState.Unrestricted).Assert();
541                     _domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager;
542                     CodeAccessPermission.RevertAssert();
543                 }
544                 catch (FileNotFoundException e)
545                 {
546                     throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
547                 }
548                 catch (SecurityException e)
549                 {
550                     throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
551                 }
552                 catch (TypeLoadException e)
553                 {
554                     throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
555                 }
556
557                 if (_domainManager == null)
558                 {
559                     throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"));
560                 }
561
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;
566
567                 bool notifyFusion = _domainManager.GetType() != typeof(System.AppDomainManager) && !DisableFusionUpdatesFromADManager();
568
569
570
571                 AppDomainSetup FusionStoreOld = null;
572                 if (notifyFusion)
573                     FusionStoreOld = new AppDomainSetup(FusionStore, true);
574
575                 // Initialize the AppDomainMAnager and register the instance with the native host if requested
576                 _domainManager.InitializeNewDomain(FusionStore);
577
578                 if (notifyFusion)
579                     SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object.
580                                 
581 #if FEATURE_APPDOMAINMANAGER_INITOPTIONS                
582                 AppDomainManagerInitializationOptions flags = _domainManager.InitializationFlags;
583                 if ((flags & AppDomainManagerInitializationOptions.RegisterWithHost) == AppDomainManagerInitializationOptions.RegisterWithHost)
584                 {
585                     _domainManager.RegisterWithHost();
586                 }
587 #endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS
588             }
589
590             InitializeCompatibilityFlags();       
591         }
592
593         /// <summary>
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.
596         /// </summary>
597         private void InitializeCompatibilityFlags()
598         {
599             AppDomainSetup adSetup = FusionStore;
600             
601             // set up shim flags regardless of whether we create a DomainManager in this method.
602             if (adSetup.GetCompatibilityFlags() != null)
603             {
604                 _compatFlags = new Dictionary<String, object>(adSetup.GetCompatibilityFlags(), StringComparer.OrdinalIgnoreCase);
605             }
606
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;
612
613             CompatibilitySwitches.InitializeSwitches();
614         }
615
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()
622         {
623             String targetFrameworkName = _FusionStore.TargetFrameworkName;
624
625             if (targetFrameworkName == null && IsDefaultAppDomain() && !_FusionStore.CheckedForTargetFrameworkName)
626             {
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)
631                 {
632                     TargetFrameworkAttribute[] attrs = (TargetFrameworkAttribute[])assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute));
633                     if (attrs != null && attrs.Length > 0)
634                     {
635                         Contract.Assert(attrs.Length == 1);
636                         targetFrameworkName = attrs[0].FrameworkName;
637                         _FusionStore.TargetFrameworkName = targetFrameworkName;
638                     }
639                 }
640                 _FusionStore.CheckedForTargetFrameworkName = true;
641             }
642
643             return targetFrameworkName;
644         }
645
646         /// <summary>
647         ///     Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact).
648         /// </summary>
649         [SecuritySafeCritical]
650         internal bool DisableFusionUpdatesFromADManager()
651         {
652             return DisableFusionUpdatesFromADManager(GetNativeHandle());
653         }
654
655         /// <summary>
656         ///     Returns whether the current AppDomain follows the AppX rules.
657         /// </summary>
658         [SecuritySafeCritical]
659         [Pure]
660         internal static bool IsAppXModel()
661         {
662 #if FEATURE_APPX
663             return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MODEL) != 0;
664 #else
665             return false;
666 #endif
667         }
668
669         /// <summary>
670         ///     Returns the setting of the AppXDevMode config switch.
671         /// </summary>
672         [SecuritySafeCritical]
673         [Pure]
674         internal static bool IsAppXDesignMode()
675         {
676 #if FEATURE_APPX
677             return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MASK) == (APPX_FLAGS.APPX_FLAGS_APPX_MODEL | APPX_FLAGS.APPX_FLAGS_APPX_DESIGN_MODE);
678 #else
679             return false;
680 #endif
681         }
682
683         /// <summary>
684         ///     Checks (and throws on failure) if the domain supports Assembly.LoadFrom.
685         /// </summary>
686         [SecuritySafeCritical]
687         [Pure]
688         internal static void CheckLoadFromSupported()
689         {
690 #if FEATURE_APPX
691             if (IsAppXModel())
692                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFrom"));
693 #endif
694         }
695
696         /// <summary>
697         ///     Checks (and throws on failure) if the domain supports Assembly.LoadFile.
698         /// </summary>
699         [SecuritySafeCritical]
700         [Pure]
701         internal static void CheckLoadFileSupported()
702         {
703 #if FEATURE_APPX
704             if (IsAppXModel())
705                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFile"));
706 #endif
707         }
708
709         /// <summary>
710         ///     Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad.
711         /// </summary>
712         [SecuritySafeCritical]
713         [Pure]
714         internal static void CheckReflectionOnlyLoadSupported()
715         {
716 #if FEATURE_APPX
717             if (IsAppXModel())
718                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.ReflectionOnlyLoad"));
719 #endif
720         }
721
722         /// <summary>
723         ///     Checks (and throws on failure) if the domain supports Assembly.LoadWithPartialName.
724         /// </summary>
725         [SecuritySafeCritical]
726         [Pure]
727         internal static void CheckLoadWithPartialNameSupported(StackCrawlMark stackMark)
728         {
729 #if FEATURE_APPX
730             if (IsAppXModel())
731             {
732                 RuntimeAssembly callingAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
733                 bool callerIsFxAssembly = callingAssembly != null && callingAssembly.IsFrameworkAssembly();
734                 if (!callerIsFxAssembly)
735                 {
736                     throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadWithPartialName"));
737                 }
738             }
739 #endif
740         }
741
742         /// <summary>
743         ///     Checks (and throws on failure) if the domain supports DefinePInvokeMethod.
744         /// </summary>
745         [SecuritySafeCritical]
746         [Pure]
747         internal static void CheckDefinePInvokeSupported()
748         {
749             // We don't want users to use DefinePInvokeMethod in RefEmit to bypass app store validation on allowed native libraries.
750 #if FEATURE_APPX
751             if (IsAppXModel())
752                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "DefinePInvokeMethod"));
753 #endif
754         }
755
756         /// <summary>
757         ///     Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...).
758         /// </summary>
759         [SecuritySafeCritical]
760         [Pure]
761         internal static void CheckLoadByteArraySupported()
762         {
763 #if FEATURE_APPX
764             if (IsAppXModel())
765                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.Load(byte[], ...)"));
766 #endif
767         }
768
769         /// <summary>
770         ///     Checks (and throws on failure) if the domain supports AppDomain.CreateDomain.
771         /// </summary>
772         [SecuritySafeCritical]
773         [Pure]
774         internal static void CheckCreateDomainSupported()
775         {
776 #if FEATURE_APPX
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.
780             if(IsAppXModel())
781             {
782                 if (!IsAppXDesignMode())
783                 {
784                     throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "AppDomain.CreateDomain"));
785                 }
786             }
787 #endif
788         }
789
790         /// <summary>
791         ///     Get the name of the assembly and type that act as the AppDomainManager for this domain
792         /// </summary>
793         [SecuritySafeCritical]
794         internal void GetAppDomainManagerType(out string assembly, out string type)
795         {
796             // We can't just use our parameters because we need to ensure that the strings used for hte QCall
797             // are on the stack.
798             string localAssembly = null;
799             string localType = null;
800
801             GetAppDomainManagerType(GetNativeHandle(),
802                                     JitHelpers.GetStringHandleOnStack(ref localAssembly),
803                                     JitHelpers.GetStringHandleOnStack(ref localType));
804
805             assembly = localAssembly;
806             type = localType;
807         }
808
809         /// <summary>
810         ///     Set the assembly and type which act as the AppDomainManager for this domain
811         /// </summary>
812         [SecuritySafeCritical]
813         private void SetAppDomainManagerType(string assembly, string type)
814         {
815             Contract.Assert(assembly != null, "assembly != null");
816             Contract.Assert(type != null, "type != null");
817             SetAppDomainManagerType(GetNativeHandle(), assembly, type);
818         }
819
820 #if FEATURE_APTCA
821         internal String[] PartialTrustVisibleAssemblies
822         {
823             get { return _aptcaVisibleAssemblies; }
824
825             [SecuritySafeCritical]
826             set
827             {
828                 _aptcaVisibleAssemblies = value;
829
830                 // Build up the canonical representaiton of this list to allow the VM to do optimizations in
831                 // common cases
832                 string canonicalConditionalAptcaList = null;
833                 if (value != null)
834                 {
835                     StringBuilder conditionalAptcaListBuilder = StringBuilderCache.Acquire();
836                     for (int i = 0; i < value.Length; ++i)
837                     {
838                         if (value[i] != null)
839                         {
840                             conditionalAptcaListBuilder.Append(value[i].ToUpperInvariant());
841                             if (i != value.Length - 1)
842                             {
843                                 conditionalAptcaListBuilder.Append(';');
844                             }
845                         }
846                     }
847
848                     canonicalConditionalAptcaList = StringBuilderCache.GetStringAndRelease(conditionalAptcaListBuilder);
849                 }
850
851                 SetCanonicalConditionalAptcaList(canonicalConditionalAptcaList);
852             }
853         }
854
855         [SecurityCritical]
856         [ResourceExposure(ResourceScope.None)]
857         [SuppressUnmanagedCodeSecurity]
858         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
859         private static extern void SetCanonicalConditionalAptcaList(AppDomainHandle appDomain, string canonicalList);
860
861         [SecurityCritical]
862         private void SetCanonicalConditionalAptcaList(string canonicalList)
863         {
864             SetCanonicalConditionalAptcaList(GetNativeHandle(), canonicalList);
865         }
866 #endif // FEATURE_APTCA
867
868 #if FEATURE_CLICKONCE
869         /// <summary>
870         ///    If the CLR is being started up to run a ClickOnce applicaiton, setup the default AppDomain
871         ///    with information about that application.
872         /// </summary>
873         private void SetupDefaultClickOnceDomain(string fullName, string[] manifestPaths, string[] activationData)
874         {
875             Contract.Requires(fullName != null, "fullName != null");
876             FusionStore.ActivationArguments = new ActivationArguments(fullName, manifestPaths, activationData);
877         }
878 #endif // FEATURE_CLICKONCE
879
880         /// <summary>
881         ///     Called for every AppDomain (including the default domain) to initialize the security of the AppDomain)
882         /// </summary>
883         [SecurityCritical]
884         private void InitializeDomainSecurity(Evidence providedSecurityInfo,
885                                               Evidence creatorsSecurityInfo,
886                                               bool generateDefaultEvidence,
887                                               IntPtr parentSecurityDescriptor,
888                                               bool publishAppDomain)
889         {
890             AppDomainSetup adSetup = FusionStore;
891
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)
896             {
897                 SetLegacyCasPolicyEnabled();
898             }
899 #endif // FEATURE_CAS_POLICY
900
901 #if FEATURE_CLICKONCE
902
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,
916                                                                          appIdentity,
917                                                                          activationContext,
918                                                                          activationData,
919                                                                          adSetup.ApplicationTrust);
920                 SetupApplicationHelper(providedSecurityInfo, creatorsSecurityInfo, appIdentity, activationContext, activationData);
921             }
922             else 
923 #endif // FEATURE_CLICKONCE
924             {
925                 bool runtimeSuppliedHomogenousGrant = false;
926                 ApplicationTrust appTrust = adSetup.ApplicationTrust;
927                 
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;
936                 }
937 #endif // FEATURE_CAS_POLICY
938
939                 if (appTrust != null) {
940                     SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant);
941                 }
942                 else if (_IsFastFullTrustDomain) {
943                     SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant);
944                 }
945             }
946
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
956             }
957
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);
970                         }
971                     }
972                 }
973             }
974
975 #endif // FEATURE_CAS_POLICY
976
977             // Set the evidence on the managed side
978             _SecurityIdentity = newAppDomainEvidence;
979
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,
985                                 publishAppDomain);
986
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
993         }
994
995 #if FEATURE_CAS_POLICY
996         [System.Security.SecurityCritical]  // auto-generated
997         private void RunDomainManagerPostInitialization (AppDomainManager domainManager)
998         {
999             // force creation of the HostExecutionContextManager for the current AppDomain
1000             HostExecutionContextManager contextManager = domainManager.HostExecutionContextManager;
1001
1002             if (IsLegacyCasPolicyEnabled)
1003             {
1004 #pragma warning disable 618
1005                 HostSecurityManager securityManager = domainManager.HostSecurityManager;
1006                 if (securityManager != null)
1007                 {
1008                     if ((securityManager.Flags & HostSecurityManagerOptions.HostPolicyLevel) == HostSecurityManagerOptions.HostPolicyLevel)
1009                     {
1010                         // set AppDomain policy if specified
1011                         PolicyLevel level = securityManager.DomainPolicy;
1012                         if (level != null)
1013                             SetAppDomainPolicy(level);
1014                     }
1015                 }
1016 #pragma warning restore 618
1017             }
1018         }
1019 #endif 
1020
1021
1022 #if FEATURE_CLICKONCE
1023
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,
1032                                           null);
1033
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);
1038         }
1039
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);
1049
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);
1054                 else
1055                     adSetup.ApplicationBase = activationContext.ApplicationDirectory;
1056
1057                 // update fusion context
1058                 SetupFusionStore(adSetup, null);
1059             }
1060
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);
1066
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);
1073
1074             _activationContext = activationContext;
1075         }
1076
1077         [System.Security.SecurityCritical]  // auto-generated
1078         private void SetupDomainSecurityForApplication(ApplicationIdentity appIdentity,
1079                                                        ApplicationTrust appTrust)
1080         {
1081             // Set the Application trust on the managed side.
1082             _applicationIdentity = appIdentity;
1083             SetupDomainSecurityForHomogeneousDomain(appTrust, false);
1084         }
1085 #endif // FEATURE_CLICKONCE
1086
1087         [System.Security.SecurityCritical]  // auto-generated
1088         private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust,
1089                                                              bool runtimeSuppliedHomogenousGrantSet)
1090         {
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);
1095             // 
1096             // From looking like it is trying to create a homogenous domain intentionally, and therefore
1097             // having its evidence check bypassed.
1098             if (runtimeSuppliedHomogenousGrantSet)
1099             {
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
1104             }
1105
1106             _applicationTrust = appTrust;
1107
1108             // Set the homogeneous bit in the VM's ApplicationSecurityDescriptor.
1109             SetSecurityHomogeneousFlag(GetNativeHandle(),
1110                                        runtimeSuppliedHomogenousGrantSet);
1111         }
1112
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();
1119         }
1120 #endif //FEATURE_CLICKONCE
1121
1122         public AppDomainManager DomainManager {
1123             [System.Security.SecurityCritical]  // auto-generated_required
1124             get {
1125                 return _domainManager;
1126             }
1127         }
1128
1129 #if FEATURE_CAS_POLICY
1130         internal HostSecurityManager HostSecurityManager {
1131             [System.Security.SecurityCritical]  // auto-generated
1132             get {
1133                 HostSecurityManager securityManager = null;
1134                 AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
1135                 if (domainManager != null)
1136                     securityManager = domainManager.HostSecurityManager;
1137
1138                 if (securityManager == null)
1139                     securityManager = new HostSecurityManager();
1140                 return securityManager;
1141             }
1142         }
1143 #endif // FEATURE_CAS_POLICY
1144 #if FEATURE_REFLECTION_ONLY_LOAD        
1145         private Assembly ResolveAssemblyForIntrospection(Object sender, ResolveEventArgs args)
1146         {
1147             Contract.Requires(args != null);
1148             return Assembly.ReflectionOnlyLoad(ApplyPolicy(args.Name));
1149         }
1150         
1151         // Helper class for method code:EnableResolveAssembliesForIntrospection
1152         private class NamespaceResolverForIntrospection
1153         {
1154             private IEnumerable<string> _packageGraphFilePaths;
1155             public NamespaceResolverForIntrospection(IEnumerable<string> packageGraphFilePaths)
1156             {
1157                 _packageGraphFilePaths = packageGraphFilePaths;
1158             }
1159             
1160             [System.Security.SecurityCritical]
1161             public void ResolveNamespace(
1162                 object sender, 
1163                 System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args)
1164             {
1165                 Contract.Requires(args != null);
1166                 
1167                 IEnumerable<string> fileNames = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ResolveNamespace(
1168                     args.NamespaceName,
1169                     null,   // windowsSdkFilePath ... Use OS installed .winmd files
1170                     _packageGraphFilePaths);
1171                 foreach (string fileName in fileNames)
1172                 {
1173                     args.ResolvedAssemblies.Add(Assembly.ReflectionOnlyLoadFrom(fileName));
1174                 }
1175             }
1176         }
1177         
1178         // Called only by native function code:ValidateWorker
1179         [System.Security.SecuritySafeCritical]
1180         private void EnableResolveAssembliesForIntrospection(string verifiedFileDirectory)
1181         {
1182             CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
1183             
1184             string[] packageGraphFilePaths = null;
1185             if (verifiedFileDirectory != null)
1186                 packageGraphFilePaths = new string[] { verifiedFileDirectory };
1187             NamespaceResolverForIntrospection namespaceResolver = new NamespaceResolverForIntrospection(packageGraphFilePaths);
1188             
1189             System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve += 
1190                 new EventHandler<System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs>(namespaceResolver.ResolveNamespace);
1191         }
1192 #endif // FEATURE_REFLECTION_ONLY_LOAD
1193
1194
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
1198         * is saved.
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(
1205             AssemblyName            name,
1206             AssemblyBuilderAccess   access)
1207         {
1208             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1209
1210             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1211             return InternalDefineDynamicAssembly(name, access, null,
1212                                                  null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
1213         }
1214
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(
1218             AssemblyName            name,
1219             AssemblyBuilderAccess   access,
1220             IEnumerable<CustomAttributeBuilder> assemblyAttributes)
1221         {
1222             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1223
1224             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1225             return InternalDefineDynamicAssembly(name,
1226                                                  access,
1227                                                  null, null, null, null, null,
1228                                                  ref stackMark,
1229                                                  assemblyAttributes, SecurityContextSource.CurrentAssembly);
1230         }
1231
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)
1238         {
1239             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1240
1241             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1242             return InternalDefineDynamicAssembly(name,
1243                                                  access,
1244                                                  null, null, null, null, null,
1245                                                  ref stackMark,
1246                                                  assemblyAttributes,
1247                                                  securityContextSource);
1248         }
1249
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(
1253             AssemblyName            name,
1254             AssemblyBuilderAccess   access,
1255             String                  dir)
1256         {
1257             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1258
1259             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1260             return InternalDefineDynamicAssembly(name, access, dir,
1261                                                  null, null, null, null,
1262                                                  ref stackMark,
1263                                                  null,
1264                                                  SecurityContextSource.CurrentAssembly);
1265         }
1266     
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(
1273             AssemblyName            name,
1274             AssemblyBuilderAccess   access,
1275             Evidence                evidence)
1276         {
1277             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1278
1279             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1280             return InternalDefineDynamicAssembly(name, access, null,
1281                                                  evidence, null, null, null,
1282                                                  ref stackMark,
1283                                                  null,
1284                                                  SecurityContextSource.CurrentAssembly);
1285         }
1286     
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(
1293             AssemblyName            name,
1294             AssemblyBuilderAccess   access,
1295             PermissionSet           requiredPermissions,
1296             PermissionSet           optionalPermissions,
1297             PermissionSet           refusedPermissions)
1298         {
1299             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1300
1301             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1302             return InternalDefineDynamicAssembly(name, access, null, null,
1303                                                  requiredPermissions,
1304                                                  optionalPermissions,
1305                                                  refusedPermissions,
1306                                                  ref stackMark,
1307                                                  null,
1308                                                  SecurityContextSource.CurrentAssembly);
1309         }
1310     
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(
1317             AssemblyName            name,
1318             AssemblyBuilderAccess   access,
1319             String                  dir,
1320             Evidence                evidence)
1321         {
1322             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1323
1324             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1325             return InternalDefineDynamicAssembly(name, access, dir, evidence,
1326                                                  null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
1327         }
1328     
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(
1335             AssemblyName            name,
1336             AssemblyBuilderAccess   access,
1337             String                  dir,
1338             PermissionSet           requiredPermissions,
1339             PermissionSet           optionalPermissions,
1340             PermissionSet           refusedPermissions)
1341         {
1342             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1343
1344             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1345             return InternalDefineDynamicAssembly(name, access, dir, null,
1346                                                  requiredPermissions,
1347                                                  optionalPermissions,
1348                                                  refusedPermissions,
1349                                                  ref stackMark,
1350                                                  null,
1351                                                  SecurityContextSource.CurrentAssembly);
1352         }
1353     
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(
1360             AssemblyName            name,
1361             AssemblyBuilderAccess   access,
1362             Evidence                evidence,
1363             PermissionSet           requiredPermissions,
1364             PermissionSet           optionalPermissions,
1365             PermissionSet           refusedPermissions)
1366         {
1367             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1368
1369             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1370             return InternalDefineDynamicAssembly(name, access, null,
1371                                                  evidence,
1372                                                  requiredPermissions,
1373                                                  optionalPermissions,
1374                                                  refusedPermissions,
1375                                                  ref stackMark,
1376                                                  null,
1377                                                  SecurityContextSource.CurrentAssembly);
1378         }
1379     
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(
1386             AssemblyName            name,
1387             AssemblyBuilderAccess   access,
1388             String                  dir,
1389             Evidence                evidence,
1390             PermissionSet           requiredPermissions,
1391             PermissionSet           optionalPermissions,
1392             PermissionSet           refusedPermissions)
1393         {
1394             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1395
1396             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1397             return InternalDefineDynamicAssembly(name, access, dir,
1398                                                  evidence,
1399                                                  requiredPermissions,
1400                                                  optionalPermissions,
1401                                                  refusedPermissions,
1402                                                  ref stackMark,
1403                                                  null,
1404                                                  SecurityContextSource.CurrentAssembly);
1405         }
1406
1407
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(
1414             AssemblyName            name,
1415             AssemblyBuilderAccess   access,
1416             String                  dir,
1417             Evidence                evidence,
1418             PermissionSet           requiredPermissions,
1419             PermissionSet           optionalPermissions,
1420             PermissionSet           refusedPermissions,
1421             bool                    isSynchronized)
1422         {
1423             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1424
1425             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1426             return InternalDefineDynamicAssembly(name,
1427                                                  access,
1428                                                  dir,
1429                                                  evidence,
1430                                                  requiredPermissions,
1431                                                  optionalPermissions,
1432                                                  refusedPermissions,
1433                                                  ref stackMark,
1434                                                  null,
1435                                                  SecurityContextSource.CurrentAssembly);
1436         }
1437
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(
1442                     AssemblyName name,
1443                     AssemblyBuilderAccess access,
1444                     String dir,
1445                     Evidence evidence,
1446                     PermissionSet requiredPermissions,
1447                     PermissionSet optionalPermissions,
1448                     PermissionSet refusedPermissions,
1449                     bool isSynchronized,
1450                     IEnumerable<CustomAttributeBuilder> assemblyAttributes)
1451         {
1452             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1453
1454             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1455             return InternalDefineDynamicAssembly(name,
1456                                                  access,
1457                                                  dir,
1458                                                  evidence,
1459                                                  requiredPermissions,
1460                                                  optionalPermissions,
1461                                                  refusedPermissions,
1462                                                  ref stackMark,
1463                                                  assemblyAttributes,
1464                                                  SecurityContextSource.CurrentAssembly);
1465         }
1466
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(
1470                     AssemblyName name,
1471                     AssemblyBuilderAccess access,
1472                     String dir,
1473                     bool isSynchronized,
1474                     IEnumerable<CustomAttributeBuilder> assemblyAttributes)
1475         {
1476             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
1477
1478             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1479             return InternalDefineDynamicAssembly(name,
1480                                                  access,
1481                                                  dir,
1482                                                  null,
1483                                                  null,
1484                                                  null,
1485                                                  null,
1486                                                  ref stackMark,
1487                                                  assemblyAttributes,
1488                                                  SecurityContextSource.CurrentAssembly);
1489         }
1490
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(
1494             AssemblyName name,
1495             AssemblyBuilderAccess access,
1496             String dir,
1497             Evidence evidence,
1498             PermissionSet requiredPermissions,
1499             PermissionSet optionalPermissions,
1500             PermissionSet refusedPermissions,
1501             ref StackCrawlMark stackMark,
1502             IEnumerable<CustomAttributeBuilder> assemblyAttributes,
1503             SecurityContextSource securityContextSource)
1504         {
1505             return AssemblyBuilder.InternalDefineDynamicAssembly(name,
1506                                                                  access,
1507                                                                  dir,
1508                                                                  evidence,
1509                                                                  requiredPermissions,
1510                                                                  optionalPermissions,
1511                                                                  refusedPermissions,
1512                                                                  ref stackMark,
1513                                                                  assemblyAttributes,
1514                                                                  securityContextSource);
1515         }
1516
1517         [System.Security.SecuritySafeCritical]  // auto-generated
1518         [ResourceExposure(ResourceScope.None)]
1519         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1520         private extern String nApplyPolicy(AssemblyName an);
1521        
1522         // Return the assembly name that results from applying policy.
1523         [ComVisible(false)]
1524         public String ApplyPolicy(String assemblyName)
1525         {
1526             AssemblyName asmName = new AssemblyName(assemblyName);  
1527
1528             byte[] pk = asmName.GetPublicKeyToken();
1529             if (pk == null)
1530                 pk = asmName.GetPublicKey();
1531
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;
1536             else
1537                 return nApplyPolicy(asmName);
1538         }
1539
1540
1541         public ObjectHandle CreateInstance(String assemblyName,
1542                                            String typeName)
1543                                          
1544         {
1545             // jit does not check for that, so we should do it ...
1546             if (this == null)
1547                 throw new NullReferenceException();
1548
1549             if (assemblyName == null)
1550                 throw new ArgumentNullException("assemblyName");
1551             Contract.EndContractBlock();
1552
1553             return Activator.CreateInstance(assemblyName,
1554                                             typeName);
1555         }
1556
1557         [System.Security.SecurityCritical]  // auto-generated
1558         internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
1559             PermissionSet.s_fullTrust.Assert();
1560             return CreateInstance(assemblyName, typeName);
1561         }
1562
1563         [ResourceExposure(ResourceScope.Machine)]
1564         [ResourceConsumption(ResourceScope.Machine)]
1565         public ObjectHandle CreateInstanceFrom(String assemblyFile,
1566                                                String typeName)
1567                                          
1568         {
1569             // jit does not check for that, so we should do it ...
1570             if (this == null)
1571                 throw new NullReferenceException();
1572             Contract.EndContractBlock();
1573
1574             return Activator.CreateInstanceFrom(assemblyFile,
1575                                                 typeName);
1576         }
1577
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);
1584         }
1585
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,
1592                                                   String typeName)
1593                                          
1594         {
1595             if (this == null)
1596                 throw new NullReferenceException();
1597             Contract.EndContractBlock();
1598
1599             return Activator.CreateComInstanceFrom(assemblyName,
1600                                                    typeName);
1601         }
1602
1603         [ResourceExposure(ResourceScope.Machine)]
1604         [ResourceConsumption(ResourceScope.Machine)]
1605         public ObjectHandle CreateComInstanceFrom(String assemblyFile,
1606                                                   String typeName,
1607                                                   byte[] hashValue, 
1608                                                   AssemblyHashAlgorithm hashAlgorithm)
1609                                          
1610         {
1611             if (this == null)
1612                 throw new NullReferenceException();
1613             Contract.EndContractBlock();
1614
1615             return Activator.CreateComInstanceFrom(assemblyFile,
1616                                                    typeName,
1617                                                    hashValue, 
1618                                                    hashAlgorithm);
1619         }
1620
1621 #endif // FEATURE_COMINTEROP
1622
1623         public ObjectHandle CreateInstance(String assemblyName,
1624                                            String typeName,
1625                                            Object[] activationAttributes)
1626                                          
1627         {
1628             // jit does not check for that, so we should do it ...
1629             if (this == null)
1630                 throw new NullReferenceException();
1631
1632             if (assemblyName == null)
1633                 throw new ArgumentNullException("assemblyName");
1634             Contract.EndContractBlock();
1635
1636             return Activator.CreateInstance(assemblyName,
1637                                             typeName,
1638                                             activationAttributes);
1639         }
1640                                   
1641         [ResourceExposure(ResourceScope.Machine)]
1642         [ResourceConsumption(ResourceScope.Machine)]
1643         public ObjectHandle CreateInstanceFrom(String assemblyFile,
1644                                                String typeName,
1645                                                Object[] activationAttributes)
1646                                                
1647         {
1648             // jit does not check for that, so we should do it ...
1649             if (this == null)
1650                 throw new NullReferenceException();
1651             Contract.EndContractBlock();
1652
1653             return Activator.CreateInstanceFrom(assemblyFile,
1654                                                 typeName,
1655                                                 activationAttributes);
1656         }
1657                                          
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, 
1660                                            String typeName, 
1661                                            bool ignoreCase,
1662                                            BindingFlags bindingAttr, 
1663                                            Binder binder,
1664                                            Object[] args,
1665                                            CultureInfo culture,
1666                                            Object[] activationAttributes,
1667                                            Evidence securityAttributes)
1668         {
1669             // jit does not check for that, so we should do it ...
1670             if (this == null)
1671                 throw new NullReferenceException();
1672             
1673             if (assemblyName == null)
1674                 throw new ArgumentNullException("assemblyName");
1675             Contract.EndContractBlock();
1676
1677 #if FEATURE_CAS_POLICY
1678             if (securityAttributes != null && !IsLegacyCasPolicyEnabled)
1679             {
1680                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));   
1681             }
1682 #endif // FEATURE_CAS_POLICY
1683
1684 #pragma warning disable 618
1685             return Activator.CreateInstance(assemblyName,
1686                                             typeName,
1687                                             ignoreCase,
1688                                             bindingAttr,
1689                                             binder,
1690                                             args,
1691                                             culture,
1692                                             activationAttributes,
1693                                             securityAttributes);
1694 #pragma warning restore 618
1695         }
1696
1697         public ObjectHandle CreateInstance(string assemblyName,
1698                                            string typeName,
1699                                            bool ignoreCase,
1700                                            BindingFlags bindingAttr,
1701                                            Binder binder,
1702                                            object[] args,
1703                                            CultureInfo culture,
1704                                            object[] activationAttributes)
1705         {
1706             // jit does not check for that, so we should do it ...
1707             if (this == null)
1708                 throw new NullReferenceException();
1709
1710             if (assemblyName == null)
1711                 throw new ArgumentNullException("assemblyName");
1712             Contract.EndContractBlock();
1713
1714             return Activator.CreateInstance(assemblyName,
1715                                             typeName,
1716                                             ignoreCase,
1717                                             bindingAttr,
1718                                             binder,
1719                                             args,
1720                                             culture,
1721                                             activationAttributes);
1722         }
1723
1724         [System.Security.SecurityCritical]  // auto-generated
1725         internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, 
1726                                                                     string typeName,
1727                                                                     bool ignoreCase,
1728                                                                     BindingFlags bindingAttr,
1729                                                                     Binder binder,
1730                                                                     Object[] args,
1731                                                                     CultureInfo culture,
1732                                                                     Object[] activationAttributes,
1733                                                                     Evidence securityAttributes)
1734         {
1735 #if FEATURE_CAS_POLICY
1736             Contract.Assert(IsLegacyCasPolicyEnabled || securityAttributes == null);
1737 #endif // FEATURE_CAS_POLICY
1738
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
1743         }
1744
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,
1749                                                String typeName, 
1750                                                bool ignoreCase,
1751                                                BindingFlags bindingAttr, 
1752                                                Binder binder,
1753                                                Object[] args,
1754                                                CultureInfo culture,
1755                                                Object[] activationAttributes,
1756                                                Evidence securityAttributes)
1757
1758         {
1759             // jit does not check for that, so we should do it ...
1760             if (this == null)
1761                 throw new NullReferenceException();
1762             Contract.EndContractBlock();
1763
1764 #if FEATURE_CAS_POLICY
1765             if (securityAttributes != null && !IsLegacyCasPolicyEnabled)
1766             {
1767                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1768             }
1769 #endif // FEATURE_CAS_POLICY
1770
1771             return Activator.CreateInstanceFrom(assemblyFile,
1772                                                 typeName,
1773                                                 ignoreCase,
1774                                                 bindingAttr,
1775                                                 binder,
1776                                                 args,
1777                                                 culture,
1778                                                 activationAttributes,
1779                                                 securityAttributes);
1780         }
1781
1782         [ResourceExposure(ResourceScope.Machine)]
1783         [ResourceConsumption(ResourceScope.Machine)]
1784         public ObjectHandle CreateInstanceFrom(string assemblyFile,
1785                                                string typeName,
1786                                                bool ignoreCase,
1787                                                BindingFlags bindingAttr,
1788                                                Binder binder,
1789                                                object[] args,
1790                                                CultureInfo culture,
1791                                                object[] activationAttributes)
1792         {
1793             // jit does not check for that, so we should do it ...
1794             if (this == null)
1795                 throw new NullReferenceException();
1796             Contract.EndContractBlock();
1797
1798             return Activator.CreateInstanceFrom(assemblyFile,
1799                                                 typeName,
1800                                                 ignoreCase,
1801                                                 bindingAttr,
1802                                                 binder,
1803                                                 args,
1804                                                 culture,
1805                                                 activationAttributes);
1806         }
1807
1808         [System.Security.SecurityCritical]  // auto-generated
1809         [ResourceExposure(ResourceScope.Machine)]
1810         [ResourceConsumption(ResourceScope.Machine)]
1811         internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, 
1812                                                                         string typeName,
1813                                                                         bool ignoreCase,
1814                                                                         BindingFlags bindingAttr,
1815                                                                         Binder binder,
1816                                                                         Object[] args,
1817                                                                         CultureInfo culture,
1818                                                                         Object[] activationAttributes,
1819                                                                         Evidence securityAttributes)
1820         {
1821 #if FEATURE_CAS_POLICY
1822             Contract.Assert(IsLegacyCasPolicyEnabled || securityAttributes == null);
1823 #endif // FEATURE_CAS_POLICY
1824
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
1829         }
1830
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)
1834         {
1835             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1836             return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
1837         }
1838         
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)
1842         {
1843             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1844             return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false);
1845         }
1846
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)
1850         {
1851             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1852             return RuntimeAssembly.nLoadImage(rawAssembly,
1853                                        null, // symbol store
1854                                        null, // evidence
1855                                        ref stackMark,
1856                                        false,
1857                                        SecurityContextSource.CurrentAssembly);
1858
1859         }
1860
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)
1865         {
1866             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1867             return RuntimeAssembly.nLoadImage(rawAssembly,
1868                                        rawSymbolStore,
1869                                        null, // evidence
1870                                        ref stackMark,
1871                                        false, // fIntrospection
1872                                        SecurityContextSource.CurrentAssembly);
1873         }
1874
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)
1884         {
1885 #if FEATURE_CAS_POLICY
1886             if (securityEvidence != null && !IsLegacyCasPolicyEnabled)
1887             {
1888                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1889             }
1890 #endif // FEATURE_CAS_POLICY
1891
1892             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1893             return RuntimeAssembly.nLoadImage(rawAssembly,
1894                                        rawSymbolStore,
1895                                        securityEvidence,
1896                                        ref stackMark,
1897                                        false, // fIntrospection
1898                                        SecurityContextSource.CurrentAssembly);
1899         }
1900
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)
1906         {
1907             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1908             return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
1909         }
1910
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)
1916         {
1917             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1918             return RuntimeAssembly.InternalLoad(assemblyString, assemblySecurity, ref stackMark, false);
1919         }
1920
1921         [ResourceExposure(ResourceScope.Machine)]
1922         [ResourceConsumption(ResourceScope.Machine)]
1923         public int ExecuteAssembly(String assemblyFile)
1924         {
1925             return ExecuteAssembly(assemblyFile, (string[])null);
1926         }
1927
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)
1933         {
1934             return ExecuteAssembly(assemblyFile, assemblySecurity, null);
1935         }
1936     
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,
1942                                    String[] args)
1943         {
1944 #if FEATURE_CAS_POLICY
1945             if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
1946             {
1947                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1948             }
1949 #endif // FEATURE_CAS_POLICY
1950
1951             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile, assemblySecurity);
1952     
1953             if (args == null)
1954                 args = new String[0];
1955
1956             return nExecuteAssembly(assembly, args);
1957         }
1958
1959         [ResourceExposure(ResourceScope.Machine)]
1960         [ResourceConsumption(ResourceScope.Machine)]
1961         public int ExecuteAssembly(string assemblyFile, string[] args)
1962         {
1963             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile);
1964
1965             if (args == null)
1966                 args = new String[0];
1967
1968             return nExecuteAssembly(assembly, args);
1969         }
1970
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,
1976                                    String[] args,
1977                                    byte[] hashValue, 
1978                                    AssemblyHashAlgorithm hashAlgorithm)
1979         {
1980 #if FEATURE_CAS_POLICY
1981             if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
1982             {
1983                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
1984             }
1985 #endif // FEATURE_CAS_POLICY
1986
1987             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile, 
1988                                                                           assemblySecurity,
1989                                                                           hashValue,
1990                                                                           hashAlgorithm);
1991             if (args == null)
1992                 args = new String[0];
1993
1994             return nExecuteAssembly(assembly, args);
1995         }
1996
1997         [ResourceExposure(ResourceScope.Machine)]
1998         [ResourceConsumption(ResourceScope.Machine)]
1999         public int ExecuteAssembly(string assemblyFile,
2000                                    string[] args,
2001                                    byte[] hashValue,
2002                                    AssemblyHashAlgorithm hashAlgorithm)
2003         {
2004             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.LoadFrom(assemblyFile,
2005                                                                           hashValue,
2006                                                                           hashAlgorithm);
2007             if (args == null)
2008                 args = new String[0];
2009
2010             return nExecuteAssembly(assembly, args);
2011         }
2012
2013         #if FEATURE_CORECLR
2014         [System.Security.SecurityCritical] // auto-generated
2015         #endif
2016         public int ExecuteAssemblyByName(String assemblyName)
2017         {
2018             return ExecuteAssemblyByName(assemblyName, (string[])null);
2019         }
2020
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)
2024         {
2025 #pragma warning disable 618
2026             return ExecuteAssemblyByName(assemblyName, assemblySecurity, null);
2027 #pragma warning restore 618
2028         }
2029
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)
2034         {
2035 #if FEATURE_CAS_POLICY
2036             if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
2037             {
2038                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
2039             }
2040 #endif // FEATURE_CAS_POLICY
2041
2042             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
2043     
2044             if (args == null)
2045                 args = new String[0];
2046
2047             return nExecuteAssembly(assembly, args);
2048         }
2049
2050         public int ExecuteAssemblyByName(string assemblyName, params string[] args)
2051         {
2052             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName);
2053
2054             if (args == null)
2055                 args = new String[0];
2056
2057             return nExecuteAssembly(assembly, args);
2058         }
2059
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)
2064         {
2065 #if FEATURE_CAS_POLICY
2066             if (assemblySecurity != null && !IsLegacyCasPolicyEnabled)
2067             {
2068                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
2069             }
2070 #endif // FEATURE_CAS_POLICY
2071
2072             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName, assemblySecurity);
2073     
2074             if (args == null)
2075                 args = new String[0];
2076
2077             return nExecuteAssembly(assembly, args);
2078         }
2079
2080         public int ExecuteAssemblyByName(AssemblyName assemblyName, params string[] args)
2081         {
2082             RuntimeAssembly assembly = (RuntimeAssembly)Assembly.Load(assemblyName);
2083
2084             if (args == null)
2085                 args = new String[0];
2086
2087             return nExecuteAssembly(assembly, args);
2088         }
2089
2090         public static AppDomain CurrentDomain
2091         {
2092             get {
2093                 Contract.Ensures(Contract.Result<AppDomain>() != null);
2094                 return Thread.GetDomain();
2095             }
2096         }
2097
2098 #if FEATURE_CAS_POLICY
2099         public Evidence Evidence
2100         {
2101             [System.Security.SecuritySafeCritical]  // auto-generated
2102             [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
2103             get {
2104                 return EvidenceNoDemand;
2105             }
2106         }
2107
2108         internal Evidence EvidenceNoDemand {
2109             [SecurityCritical]
2110             get {
2111                 if (_SecurityIdentity == null) {
2112                     if (!IsDefaultAppDomain() && nIsDefaultAppDomainForEvidence()) {
2113 #if !FEATURE_CORECLR                         
2114                         //
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.
2118                         //
2119                         return GetDefaultDomain().Evidence;
2120 #else
2121                        Contract.Assert(false,"This code should not be called for core CLR");
2122                         
2123                         // This operation is not allowed
2124                         throw new InvalidOperationException();
2125 #endif
2126                     }
2127                     else {
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));
2132                     }
2133                 }
2134                 else {
2135                     return _SecurityIdentity.Clone();
2136                 }
2137             }
2138         }
2139
2140         internal Evidence InternalEvidence
2141         {
2142             get {
2143                     return _SecurityIdentity;
2144             }
2145         }
2146
2147         internal EvidenceBase GetHostEvidence(Type type)
2148         {
2149             if (_SecurityIdentity != null)
2150             {
2151                 return _SecurityIdentity.GetHostEvidence(type);
2152             }
2153             else
2154             {
2155                 return new Evidence(new AppDomainEvidenceFactory(this)).GetHostEvidence(type);
2156             }
2157         }
2158 #endif // FEATURE_CAS_POLICY
2159
2160         public String FriendlyName
2161         {
2162             [System.Security.SecuritySafeCritical]  // auto-generated
2163             get { return nGetFriendlyName(); }
2164         } 
2165
2166         public String BaseDirectory
2167         {
2168 #if FEATURE_CORECLR
2169             [System.Security.SecurityCritical]
2170 #endif        
2171             [ResourceExposure(ResourceScope.Machine)]
2172             [ResourceConsumption(ResourceScope.Machine)]
2173             get {
2174                 return FusionStore.ApplicationBase;
2175             }
2176         }
2177
2178 #if FEATURE_FUSION
2179         public String RelativeSearchPath
2180         {
2181             [ResourceExposure(ResourceScope.Machine)]
2182             [ResourceConsumption(ResourceScope.Machine)]
2183             get { return FusionStore.PrivateBinPath; }
2184         }
2185
2186         public bool ShadowCopyFiles
2187         {
2188             get {
2189                 String s = FusionStore.ShadowCopyFiles;
2190                 if((s != null) && 
2191                    (String.Compare(s, "true", StringComparison.OrdinalIgnoreCase) == 0))
2192                     return true;
2193                 else
2194                     return false;
2195             }
2196         }
2197 #endif
2198
2199         [System.Security.SecuritySafeCritical]  // auto-generated
2200         public override String ToString()
2201         {
2202             StringBuilder sb = StringBuilderCache.Acquire();
2203             
2204             String fn = nGetFriendlyName();
2205             if (fn != null) {
2206                 sb.Append(Environment.GetResourceString("Loader_Name") + fn);
2207                 sb.Append(Environment.NewLine);
2208             }
2209     
2210             if(_Policies == null || _Policies.Length == 0) 
2211                 sb.Append(Environment.GetResourceString("Loader_NoContextPolicies")
2212                           + Environment.NewLine);
2213             else {
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);
2219                 }
2220             }
2221     
2222             return StringBuilderCache.GetStringAndRelease(sb);
2223         }
2224         
2225         public Assembly[] GetAssemblies()
2226         {
2227             return nGetAssemblies(false /* forIntrospection */);
2228         }
2229
2230
2231         public Assembly[] ReflectionOnlyGetAssemblies()
2232         {
2233             return nGetAssemblies(true /* forIntrospection */);
2234         }
2235
2236         [System.Security.SecuritySafeCritical]  // auto-generated
2237         [ResourceExposure(ResourceScope.None)]
2238         [MethodImplAttribute(MethodImplOptions.InternalCall)]
2239         private extern Assembly[] nGetAssemblies(bool forIntrospection);
2240
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();
2246
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();
2253
2254         [System.Security.SecurityCritical]  // auto-generated
2255         [MethodImplAttribute(MethodImplOptions.InternalCall)]
2256         internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
2257
2258 #if  FEATURE_FUSION
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)
2266         {
2267             if(path == null || path.Length == 0)
2268                 return;
2269
2270             String current = FusionStore.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue];
2271             StringBuilder appendPath = StringBuilderCache.Acquire();
2272
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);
2279             }
2280             appendPath.Append(path);
2281
2282             String result = StringBuilderCache.GetStringAndRelease(appendPath);
2283             InternalSetPrivateBinPath(result);
2284         }
2285
2286         
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()
2292         {
2293             InternalSetPrivateBinPath(String.Empty);
2294         }
2295
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()
2301         {
2302             InternalSetShadowCopyPath(String.Empty);
2303         }
2304
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)
2310         {
2311             InternalSetCachePath(path);
2312         }
2313 #endif // FEATURE_FUSION
2314
2315         [System.Security.SecurityCritical]  // auto-generated_required
2316         [ResourceExposure(ResourceScope.AppDomain)]
2317         [ResourceConsumption(ResourceScope.AppDomain)]
2318         public void SetData (string name, object data) {
2319 #if FEATURE_CORECLR        
2320             if (!name.Equals("LOCATION_URI"))
2321             {
2322                 // Only LOCATION_URI can be set using AppDomain.SetData
2323                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyLocationURI", name));
2324             }
2325 #endif // FEATURE_CORECLR            
2326             SetDataHelper(name, data, null);
2327         }
2328
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) {
2333 #if FEATURE_CORECLR        
2334             if (!name.Equals("LOCATION_URI"))
2335             {
2336                 // Only LOCATION_URI can be set using AppDomain.SetData
2337                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyLocationURI", name));
2338             }
2339 #endif // FEATURE_CORECLR                    
2340             SetDataHelper(name, data, permission);
2341         }
2342
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) {
2347             if (name == null)
2348                 throw new ArgumentNullException("name");
2349             Contract.EndContractBlock();
2350
2351             //
2352             // Synopsis:
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.
2360             // Remarks:
2361             //   There needs to be an AppDomain policy level set before this compat
2362             //   switch can be set on the AppDomain.
2363             //
2364 #if FEATURE_FUSION
2365             if (name.Equals(TargetFrameworkNameAppCompatSetting)) {
2366                 _FusionStore.TargetFrameworkName = (String) data;
2367                 return;
2368             }
2369 #if FEATURE_CAS_POLICY
2370             if (name.Equals("IgnoreSystemPolicy")) {
2371                 lock (this) {
2372                     if (!_HasSetPolicy)
2373                         throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
2374                 }
2375                 new PermissionSet(PermissionState.Unrestricted).Demand();
2376             }
2377 #endif
2378             int key = AppDomainSetup.Locate(name);
2379
2380             if(key == -1) {
2381                 lock (((ICollection)LocalStore).SyncRoot) {
2382                     LocalStore[name] = new object[] {data, permission};
2383                 }
2384             }
2385             else {
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.
2390                 switch(key) {
2391                 case (int) AppDomainSetup.LoaderInformation.DynamicBaseValue:
2392                     FusionStore.DynamicBase = (string) data;
2393                     break;
2394                 case (int) AppDomainSetup.LoaderInformation.DevPathValue:
2395                     FusionStore.DeveloperPath = (string) data;
2396                     break;
2397                 case (int) AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
2398                     FusionStore.ShadowCopyDirectories = (string) data;
2399                     break;
2400                 case (int) AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
2401                     if(data != null)
2402                         FusionStore.DisallowPublisherPolicy = true;
2403                     else
2404                         FusionStore.DisallowPublisherPolicy = false;
2405                     break;
2406                 case (int) AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
2407                     if (data != null)
2408                          FusionStore.DisallowCodeDownload = true;
2409                     else
2410                         FusionStore.DisallowCodeDownload = false;
2411                     break;
2412                 case (int) AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
2413                     if(data != null)
2414                         FusionStore.DisallowBindingRedirects = true;
2415                     else
2416                         FusionStore.DisallowBindingRedirects = false;
2417                     break;
2418                 case (int) AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
2419                     if(data != null)
2420                         FusionStore.DisallowApplicationBaseProbing = true;
2421                     else
2422                         FusionStore.DisallowApplicationBaseProbing = false;
2423                     break;
2424                 case (int) AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
2425                     FusionStore.SetConfigurationBytes((byte[]) data);
2426                     break;
2427                 default:
2428                     FusionStore.Value[key] = (string) data;
2429                     break;
2430                 }
2431             }
2432 #else // FEATURE_FUSION
2433 #if FEATURE_CORECLR
2434             // SetData should only be used to set values that don't already exist.
2435             {
2436                 object[] currentVal;
2437                 lock (((ICollection)LocalStore).SyncRoot) {
2438                     LocalStore.TryGetValue(name, out currentVal);
2439                 }
2440                 if (currentVal != null && currentVal[0] != null)
2441                 {
2442                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
2443                 }
2444             }
2445
2446 #endif // FEATURE_CORECLR
2447             lock (((ICollection)LocalStore).SyncRoot) {
2448                 LocalStore[name] = new object[] {data, permission};
2449             }
2450 #endif // FEATURE_FUSION
2451         }
2452
2453         [Pure]
2454         #if FEATURE_CORECLR
2455         [System.Security.SecurityCritical] // auto-generated
2456         #else
2457         [System.Security.SecuritySafeCritical]
2458         #endif
2459         [ResourceExposure(ResourceScope.AppDomain)]
2460         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2461         public Object GetData(string name)
2462         {
2463             if(name == null)
2464                 throw new ArgumentNullException("name");
2465             Contract.EndContractBlock();
2466
2467             int key = AppDomainSetup.Locate(name);
2468             if(key == -1) 
2469             {
2470 #if FEATURE_LOADER_OPTIMIZATION
2471                 if(name.Equals(AppDomainSetup.LoaderOptimizationKey))
2472                     return FusionStore.LoaderOptimization;
2473                 else 
2474 #endif // FEATURE_LOADER_OPTIMIZATION                    
2475                 {
2476                     object[] data;
2477                     lock (((ICollection)LocalStore).SyncRoot) {
2478                         LocalStore.TryGetValue(name, out data);
2479                     }
2480                     if (data == null)
2481                         return null;
2482                     if (data[1] != null) {
2483                         IPermission permission = (IPermission) data[1];
2484                         permission.Demand();
2485                     }
2486                     return data[0];
2487                 }
2488             }
2489            else {
2490                 // Be sure to call these properties, not Value, so
2491                 // that the appropriate permission demand will be done
2492                 switch(key) {
2493                 case (int) AppDomainSetup.LoaderInformation.ApplicationBaseValue:
2494                     return FusionStore.ApplicationBase;
2495                 case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
2496                     return FusionStore.ApplicationName;
2497 #if FEATURE_FUSION
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
2527                     
2528                 default:
2529                     Contract.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
2530                     return null;
2531                 }
2532             }
2533                    
2534         }
2535
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.
2538         //
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)
2543         {
2544             Nullable<bool> fReturn;
2545
2546             if (_compatFlagsInitialized == false) 
2547             {
2548                 fReturn = new Nullable<bool>();
2549             } 
2550             else
2551             {
2552                 fReturn  = new Nullable<bool>(_compatFlags != null && _compatFlags.ContainsKey(value));
2553             }
2554
2555             return fReturn;
2556         }
2557         
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();
2562
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)
2568         {
2569             if (domain == null)
2570                 throw new ArgumentNullException("domain");
2571             Contract.EndContractBlock();
2572
2573             try {
2574                 Int32 domainID = AppDomain.GetIdForUnload(domain);
2575                 if (domainID==0)
2576                     throw new CannotUnloadAppDomainException();
2577                 AppDomain.nUnload(domainID);
2578             }
2579             catch(Exception e) {
2580                 throw e;    // throw it again to reset stack trace
2581             }
2582         }
2583 #endif
2584
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)
2593         {
2594             if (domainPolicy == null)
2595                 throw new ArgumentNullException("domainPolicy");
2596             Contract.EndContractBlock();
2597
2598             if (!IsLegacyCasPolicyEnabled)
2599             {
2600                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
2601             }
2602
2603             // Check that policy has not been set previously.
2604             lock (this) {
2605                 if (_HasSetPolicy)
2606                     throw new PolicyException(Environment.GetResourceString("Policy_PolicyAlreadySet"));
2607                 _HasSetPolicy = true;
2608
2609                 // Make sure that the loader allows us to change security policy
2610                 // at this time (this will throw if not.)
2611                 nChangeSecurityPolicy();
2612             }
2613
2614             // Add the new policy level.
2615             SecurityManager.PolicyManager.AddLevel(domainPolicy);
2616         }
2617 #endif //#if !FEATURE_CAS_POLICY
2618 #if FEATURE_CLICKONCE
2619         public ActivationContext ActivationContext {
2620             [System.Security.SecurityCritical]  // auto-generated_required
2621             get {
2622                 return _activationContext;
2623             }
2624         }
2625
2626         public ApplicationIdentity ApplicationIdentity {
2627             [System.Security.SecurityCritical]  // auto-generated_required
2628             get {
2629                 return _applicationIdentity;
2630             }
2631         }
2632 #endif // FEATURE_CLICKONCE
2633
2634
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
2641             get {
2642                 if (_applicationTrust == null && _IsFastFullTrustDomain) {
2643                     _applicationTrust = new ApplicationTrust(new PermissionSet(PermissionState.Unrestricted));
2644                 }
2645
2646                 return _applicationTrust;
2647             }
2648         }
2649
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)
2657         {
2658             if (principal == null)
2659                 throw new ArgumentNullException("principal");
2660             Contract.EndContractBlock();
2661
2662             lock (this) {
2663                 // Check that principal has not been set previously.
2664                 if (_DefaultPrincipal != null)
2665                     throw new PolicyException(Environment.GetResourceString("Policy_PrincipalTwice"));
2666
2667                 _DefaultPrincipal = principal;
2668             }
2669         }
2670 #endif // FEATURE_IMPERSONATION
2671
2672 #if FEATURE_CAS_POLICY
2673         // Similar to the above, but sets the class of principal to be created
2674         // instead.
2675         [System.Security.SecuritySafeCritical]  // auto-generated
2676         [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlPrincipal)]
2677         public void SetPrincipalPolicy(PrincipalPolicy policy)
2678         {
2679             _PrincipalPolicy = policy;
2680         }
2681 #endif
2682
2683
2684 #if FEATURE_REMOTING        
2685         // This method gives AppDomain an infinite life time by preventing a lease from being
2686         // created
2687         [System.Security.SecurityCritical]  // auto-generated_required
2688         public override Object InitializeLifetimeService()
2689         {
2690             return null;
2691         }
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)
2697         {
2698             if (callBackDelegate == null)
2699                 throw new ArgumentNullException("callBackDelegate");
2700             Contract.EndContractBlock();
2701
2702             callBackDelegate();        
2703         }
2704 #endif
2705
2706
2707         public String DynamicDirectory
2708         {
2709             [System.Security.SecuritySafeCritical]  // auto-generated
2710             [ResourceExposure(ResourceScope.Machine)]
2711             [ResourceConsumption(ResourceScope.Machine)]
2712             get {
2713                 String dyndir = GetDynamicDir();
2714                 if (dyndir != null)
2715                     new FileIOPermission( FileIOPermissionAccess.PathDiscovery, dyndir ).Demand();
2716
2717                 return dyndir;
2718             }
2719         }
2720
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
2726         {
2727             return CreateDomain(friendlyName,
2728                                 securityInfo,
2729                                 null);
2730         }
2731     
2732         [ResourceExposure(ResourceScope.Machine)]
2733         [ResourceConsumption(ResourceScope.Machine)]
2734         public static AppDomain CreateDomain(String friendlyName,
2735                                              Evidence securityInfo, // Optional
2736                                              String appBasePath,
2737                                              String appRelativeSearchPath,
2738                                              bool shadowCopyFiles)
2739         {            
2740             AppDomainSetup info = new AppDomainSetup();
2741             info.ApplicationBase = appBasePath;
2742             info.PrivateBinPath = appRelativeSearchPath;
2743             if(shadowCopyFiles)
2744                 info.ShadowCopyFiles = "true";
2745
2746             return CreateDomain(friendlyName,
2747                                 securityInfo,
2748                                 info);
2749         }
2750 #endif // #if FEATURE_CAS_POLICY    (not exposed in core)
2751
2752
2753         [System.Security.SecurityCritical]  // auto-generated
2754         [ResourceExposure(ResourceScope.Machine)]
2755         [MethodImplAttribute(MethodImplOptions.InternalCall)]
2756         extern private String GetDynamicDir();
2757
2758         // Private helpers called from unmanaged code.
2759
2760 #if FEATURE_REMOTING        
2761
2762         [ResourceExposure(ResourceScope.None)]
2763         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
2764         public static AppDomain CreateDomain(String friendlyName)
2765         {
2766             return CreateDomain(friendlyName, null, null);
2767         }
2768
2769
2770         // Marshal a single object into a serialized blob.
2771         [System.Security.SecurityCritical]  // auto-generated
2772         private static byte[] MarshalObject(Object o)
2773         {
2774             CodeAccessPermission.Assert(true);
2775
2776             return Serialize(o);
2777         }
2778
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)
2782         {
2783             CodeAccessPermission.Assert(true);
2784
2785             byte[] blob1 = Serialize(o1);
2786             blob2 = Serialize(o2);
2787             return blob1;
2788         }
2789
2790         // Unmarshal a single object from a serialized blob.
2791         [System.Security.SecurityCritical]  // auto-generated
2792         private static Object UnmarshalObject(byte[] blob)
2793         {
2794             CodeAccessPermission.Assert(true);
2795
2796             return Deserialize(blob);
2797         }
2798
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)
2802         {
2803             CodeAccessPermission.Assert(true);
2804
2805             Object o1 = Deserialize(blob1);
2806             o2 = Deserialize(blob2);
2807             return o1;
2808         }
2809
2810         // Helper routines.
2811         [System.Security.SecurityCritical]  // auto-generated
2812         private static byte[] Serialize(Object o)
2813         {
2814             if (o == null)
2815             {
2816                 return null;
2817             }
2818             else if (o is ISecurityEncodable)
2819             {
2820                 SecurityElement element = ((ISecurityEncodable)o).ToXml();
2821                 MemoryStream ms = new MemoryStream( 4096 );
2822                 ms.WriteByte( 0 );
2823                 StreamWriter writer = new StreamWriter( ms, Encoding.UTF8 );
2824                 element.ToWriter( writer );
2825                 writer.Flush();
2826                 return ms.ToArray();
2827             }
2828             else
2829             {
2830                 MemoryStream ms = new MemoryStream();
2831                 ms.WriteByte( 1 );
2832                 CrossAppDomainSerializer.SerializeObject(o, ms);
2833                 return ms.ToArray();
2834             }
2835         }
2836
2837         [System.Security.SecurityCritical]  // auto-generated
2838         private static Object Deserialize(byte[] blob)
2839         {
2840             if (blob == null)
2841                 return null;
2842
2843             if (blob[0] == 0)
2844             {
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" ))
2848                 {
2849                     IPermission ip = System.Security.Util.XMLUtil.CreatePermission( root, PermissionState.None, false );
2850
2851                     if (ip == null)
2852                     {
2853                         return null;
2854                     }
2855
2856                     ip.FromXml( root );
2857
2858                     return ip;
2859                 }
2860                 else if (root.Tag.Equals( "PermissionSet" ))
2861                 {
2862                     PermissionSet permissionSet = new PermissionSet();
2863
2864                     permissionSet.FromXml( root, false, false );
2865
2866                     return permissionSet;
2867                 }
2868                 else if (root.Tag.Equals( "PermissionToken" ))
2869                 {
2870                     PermissionToken pToken = new PermissionToken();
2871
2872                     pToken.FromXml( root );
2873
2874                     return pToken;
2875                 }
2876                 else
2877                 {
2878                     return null;
2879                 }
2880
2881             }
2882             else
2883             {
2884                 Object obj = null;
2885                 using(MemoryStream stream = new MemoryStream( blob, 1, blob.Length - 1 )) {
2886                     obj = CrossAppDomainSerializer.DeserializeObject(stream);
2887                 }
2888
2889                 Contract.Assert( !(obj is IPermission), "IPermission should be xml deserialized" );
2890                 Contract.Assert( !(obj is PermissionSet), "PermissionSet should be xml deserialized" );
2891
2892                 return obj;
2893             }
2894         }
2895
2896 #endif // FEATURE_REMOTING        
2897
2898 #if FEATURE_LEGACYNETCFFAS
2899         public static IAppDomainPauseManager PauseManager
2900         {
2901             [System.Security.SecurityCritical]
2902             get
2903             {
2904                 return AppDomainPauseManager.Instance;
2905             }
2906         }
2907 #endif // FEATURE_LEGACYNETCFFAS
2908
2909 #if !FEATURE_CORECLR
2910         //
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.
2914         //
2915         [System.Security.SecurityCritical]
2916         internal static void Pause()
2917         {
2918             AppDomainPauseManager.Instance.Pausing();
2919             AppDomainPauseManager.Instance.Paused();
2920         }
2921
2922         //
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.
2927         //
2928         [System.Security.SecurityCritical]
2929         internal static void Resume()
2930         {
2931             if (AppDomainPauseManager.IsPaused)
2932             {
2933                 AppDomainPauseManager.Instance.Resuming();
2934                 AppDomainPauseManager.Instance.Resumed();
2935             }
2936         }
2937 #endif
2938
2939         private AppDomain() {
2940             throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
2941         }
2942
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)
2948         {
2949             return _nExecuteAssembly(assembly, args);
2950         }
2951
2952 #if FEATURE_VERSIONING
2953         [MethodImplAttribute(MethodImplOptions.InternalCall)]
2954         internal extern void nCreateContext();
2955
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);
2961
2962         #if FEATURE_CORECLR
2963         [System.Security.SecurityCritical] // auto-generated
2964         #endif
2965         internal void SetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD)
2966         {
2967             nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD);
2968         }
2969 #endif // FEATURE_VERSIONING
2970
2971 #if FEATURE_REMOTING
2972         internal void CreateRemotingData()
2973         {
2974                     lock(this) {
2975                         if (_RemotingData == null)
2976                             _RemotingData = new DomainSpecificRemotingData();
2977                     }
2978         }
2979         
2980         internal DomainSpecificRemotingData RemotingData
2981         {
2982             get 
2983             { 
2984                 if (_RemotingData == null) 
2985                     CreateRemotingData();
2986
2987                 return _RemotingData;
2988             }
2989         }
2990 #endif // FEATURE_REMOTING
2991
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();
3000
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.
3006
3007         public event EventHandler ProcessExit
3008         {
3009             [System.Security.SecuritySafeCritical]  // auto-generated_required
3010             add
3011             {
3012                 if (value != null)
3013                 {
3014                     RuntimeHelpers.PrepareContractedDelegate(value);
3015                     lock(this)
3016                         _processExit += value;
3017                 }
3018             }
3019             remove
3020             {
3021                 lock(this)
3022                     _processExit -= value;
3023             }
3024         }
3025
3026
3027         public event EventHandler DomainUnload
3028         {
3029             [System.Security.SecuritySafeCritical]  // auto-generated_required
3030             add
3031             {
3032                 if (value != null)
3033                 {
3034                     RuntimeHelpers.PrepareContractedDelegate(value);
3035                     lock(this)
3036                         _domainUnload += value;
3037                 }
3038             }
3039 #if FEATURE_CORECLR
3040             [System.Security.SecuritySafeCritical] 
3041 #endif
3042             remove
3043             {
3044                 lock(this)
3045                     _domainUnload -= value;
3046             }
3047         }
3048
3049
3050         public event UnhandledExceptionEventHandler UnhandledException
3051         {
3052             [System.Security.SecurityCritical]  // auto-generated_required
3053             add
3054             {
3055                 if (value != null)
3056                 {
3057                     RuntimeHelpers.PrepareContractedDelegate(value);
3058                     lock(this)
3059                         _unhandledException += value;
3060                 }
3061             }
3062             [System.Security.SecurityCritical]  // auto-generated_required
3063             remove
3064             {
3065                 lock(this)
3066                     _unhandledException -= value;
3067             }
3068         }
3069
3070 #if FEATURE_EXCEPTION_NOTIFICATIONS
3071         // This is the event managed code can wireup against to be notified
3072         // about first chance exceptions. 
3073         //
3074         // To register/unregister the callback, the code must be SecurityCritical.
3075         public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
3076         {
3077             [System.Security.SecurityCritical]  // auto-generated_required
3078             add
3079             {
3080                 if (value != null)
3081                 {
3082                     RuntimeHelpers.PrepareContractedDelegate(value);
3083                     lock(this)
3084                         _firstChanceException += value;
3085                 }
3086             }
3087             [System.Security.SecurityCritical]  // auto-generated_required
3088             remove
3089             {
3090                 lock(this)
3091                     _firstChanceException -= value;
3092             }
3093         }
3094 #endif // FEATURE_EXCEPTION_NOTIFICATIONS
3095
3096         private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
3097         {
3098             AssemblyLoadEventHandler eventHandler = AssemblyLoad;
3099             if (eventHandler != null) {
3100                 AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly);
3101                 eventHandler(this, ea);
3102             }
3103         }
3104     
3105         // This method is called by the VM.
3106         [System.Security.SecurityCritical]
3107         private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName)
3108         {
3109             ResolveEventHandler eventHandler = _ResourceResolve;
3110             if ( eventHandler == null)
3111                 return null;
3112
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);
3118                 if (ret != null)
3119                     return ret;
3120             }
3121
3122             return null;
3123         }
3124         
3125         // This method is called by the VM
3126         [System.Security.SecurityCritical]
3127         private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
3128         {
3129             ResolveEventHandler eventHandler = _TypeResolve;
3130             if (eventHandler == null)
3131                 return null;
3132
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);
3138                 if (ret != null)
3139                     return ret;
3140             }
3141
3142             return null;
3143         }
3144
3145         // This method is called by the VM.
3146         [System.Security.SecurityCritical]
3147         private RuntimeAssembly OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
3148         {
3149             ResolveEventHandler eventHandler = _AssemblyResolve;
3150
3151             if (eventHandler == null)
3152             {
3153                 return null;
3154             }
3155
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);
3161                 if (ret != null)
3162                     return ret;
3163             }
3164             
3165             return null;
3166         }
3167
3168 #if FEATURE_REFLECTION_ONLY_LOAD
3169         
3170         private RuntimeAssembly OnReflectionOnlyAssemblyResolveEvent(RuntimeAssembly  assembly, String assemblyFullName)
3171         {
3172             ResolveEventHandler eventHandler = ReflectionOnlyAssemblyResolve;
3173             if (eventHandler != null) {
3174
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);
3180                     if (ret != null)
3181                         return ret;
3182                 }
3183             }
3184
3185             return null;
3186         }
3187         
3188 #if FEATURE_COMINTEROP
3189         // Called by VM - code:CLRPrivTypeCacheReflectionOnlyWinRT::RaiseNamespaceResolveEvent
3190         private RuntimeAssembly[] OnReflectionOnlyNamespaceResolveEvent(RuntimeAssembly assembly, string namespaceName)
3191         {
3192             return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnReflectionOnlyNamespaceResolveEvent(this, assembly, namespaceName);
3193         }
3194 #endif // FEATURE_COMINTEROP
3195
3196 #endif // FEATURE_REFLECTION_ONLY_LOAD
3197
3198 #if FEATURE_COMINTEROP
3199         // Called by VM - code:CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent
3200         private string[] OnDesignerNamespaceResolveEvent(string namespaceName)
3201         {
3202             return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnDesignerNamespaceResolveEvent(this, namespaceName);
3203         }
3204 #endif // FEATURE_COMINTEROP
3205
3206         internal AppDomainSetup FusionStore
3207         {
3208             get {
3209                 Contract.Assert(_FusionStore != null, 
3210                                 "Fusion store has not been correctly setup in this domain");
3211                 return _FusionStore;
3212             }
3213         }
3214
3215         internal static RuntimeAssembly GetRuntimeAssembly(Assembly asm)
3216         {
3217             if (asm == null)
3218                 return null;
3219
3220             RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
3221             if (rtAssembly != null)
3222                 return rtAssembly;
3223
3224             AssemblyBuilder ab = asm as AssemblyBuilder;
3225             if (ab != null)
3226                 return ab.InternalAssembly;
3227
3228             return null;
3229         }
3230
3231         [ResourceExposure(ResourceScope.AppDomain)]
3232         private Dictionary<String, Object[]> LocalStore
3233         {
3234             get { 
3235                 if (_LocalStore != null)
3236                     return _LocalStore;
3237                 else {
3238                     _LocalStore = new Dictionary<String, Object[]>();
3239                     return _LocalStore;
3240                 }
3241             }
3242         }
3243
3244 #if FEATURE_FUSION
3245         private void TurnOnBindingRedirects()
3246         {
3247             _FusionStore.DisallowBindingRedirects = false;
3248         }
3249 #endif
3250
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)
3257         {
3258             if (RemotingServices.IsTransparentProxy(domain))
3259             {
3260                 return RemotingServices.GetServerDomainIdForProxy(domain);
3261             }
3262             else
3263                 return domain.Id;
3264         }
3265 #endif
3266
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);
3274         
3275 #if FEATURE_REMOTING        
3276         [System.Security.SecurityCritical]  // auto-generated
3277         [ResourceExposure(ResourceScope.None)]
3278         [MethodImplAttribute(MethodImplOptions.InternalCall)]
3279         static internal extern AppDomain GetDefaultDomain();
3280 #endif
3281
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()
3288         {
3289             IPrincipal principal = null;
3290             if (_DefaultPrincipal == null) {
3291 #if FEATURE_CAS_POLICY                    
3292                 switch (_PrincipalPolicy) {
3293                 case PrincipalPolicy.NoPrincipal:
3294                     principal = null;
3295                     break;
3296                 case PrincipalPolicy.UnauthenticatedPrincipal:
3297                     principal = new GenericPrincipal(new GenericIdentity("", ""),
3298                                                      new String[] {""});
3299                     break;
3300 #if !FEATURE_PAL && FEATURE_IMPERSONATION
3301                 case PrincipalPolicy.WindowsPrincipal:
3302                     principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
3303                     break;
3304 #endif // !FEATURE_PAL && FEATURE_IMPERSONATION
3305                 default:
3306                     principal = null;
3307                     break;
3308                     }
3309 #else
3310                 principal = new GenericPrincipal(new GenericIdentity("", ""),
3311                                                  new String[] {""});
3312
3313 #endif
3314             }
3315             else
3316                 principal = _DefaultPrincipal;
3317
3318             return principal;
3319         }
3320 #endif // FEATURE_IMPERSONATION
3321
3322 #if FEATURE_REMOTING        
3323
3324         [System.Security.SecurityCritical]  // auto-generated
3325         internal void CreateDefaultContext()
3326         {
3327                 lock(this) {
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();
3332                 }            
3333         }
3334
3335         [System.Security.SecurityCritical]  // auto-generated
3336         internal Context GetDefaultContext()
3337         {
3338             if (_DefaultContext == null)
3339                 CreateDefaultContext();
3340             return _DefaultContext;
3341         }
3342
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)
3350         {
3351             if (creationEvidence != null && !CurrentDomain.IsLegacyCasPolicyEnabled)
3352             {
3353                 if (creationDomainSetup == null || creationDomainSetup.ApplicationTrust == null)
3354                 {
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;
3366
3367                     Zone suppliedZone = creationEvidence.GetHostEvidence<Zone>();
3368                     if (suppliedZone != null)
3369                     {
3370                         if (suppliedZone.SecurityZone != creatorsSecurityZone &&
3371                             suppliedZone.SecurityZone != SecurityZone.MyComputer)
3372                         {
3373                             throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
3374                         }
3375                     }
3376                 }
3377             }
3378         }
3379
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)
3386         {
3387             return InternalCreateDomain(friendlyName, securityInfo, info);
3388         }
3389 #else
3390         internal static AppDomain CreateDomain(String friendlyName,
3391                                       Evidence securityInfo,
3392                                       AppDomainSetup info)
3393         {
3394             return InternalCreateDomain(friendlyName, securityInfo, info);
3395         }
3396 #endif
3397
3398         [System.Security.SecurityCritical]  // auto-generated
3399         internal static AppDomain InternalCreateDomain(String friendlyName,
3400                                       Evidence securityInfo,
3401                                       AppDomainSetup info)
3402         {
3403             if (friendlyName == null)
3404                 throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_String"));
3405
3406             Contract.EndContractBlock();
3407
3408             AppDomain.CheckCreateDomainSupported();
3409
3410             if (info == null)
3411                 info = new AppDomainSetup();
3412             if (info.TargetFrameworkName == null)
3413                 info.TargetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName();
3414
3415             AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
3416             if (domainManager != null)
3417                 return domainManager.CreateDomain(friendlyName, securityInfo, info);
3418
3419             // No AppDomainManager is set up for this domain
3420
3421             // If evidence is provided, we check to make sure that is allowed.    
3422             if (securityInfo != null)
3423             {
3424                 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
3425
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);
3429             }
3430
3431             return nCreateDomain(friendlyName,
3432                                  info,
3433                                  securityInfo,
3434                                  securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null,
3435                                  AppDomain.CurrentDomain.GetSecurityDescriptor());
3436         }
3437 #endif // FEATURE_REMOTING
3438
3439 #if FEATURE_CAS_POLICY   
3440
3441 #if !FEATURE_PAL
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)
3449         {
3450             if (info == null)
3451                 throw new ArgumentNullException("info");
3452             if (info.ApplicationBase == null)
3453                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AppDomainSandboxAPINeedsExplicitAppBase"));
3454             Contract.EndContractBlock();
3455
3456             if (fullTrustAssemblies == null)
3457             {
3458                 fullTrustAssemblies = new StrongName[0];
3459             }
3460
3461             info.ApplicationTrust = new ApplicationTrust(grantSet, fullTrustAssemblies);
3462             return CreateDomain(friendlyName, securityInfo, info);
3463         }
3464
3465 #endif // !FEATURE_PAL
3466
3467         [ResourceExposure(ResourceScope.Machine)]
3468         [ResourceConsumption(ResourceScope.Machine)]
3469         public static AppDomain CreateDomain(String friendlyName,
3470                                              Evidence securityInfo, // Optional
3471                                              String appBasePath,
3472                                              String appRelativeSearchPath,
3473                                              bool shadowCopyFiles,
3474                                              AppDomainInitializer adInit, 
3475                                              string[] adInitArgs) 
3476         {
3477             AppDomainSetup info = new AppDomainSetup();
3478             info.ApplicationBase = appBasePath;
3479             info.PrivateBinPath = appRelativeSearchPath;
3480             info.AppDomainInitializer=adInit;
3481             info.AppDomainInitializerArguments=adInitArgs;
3482             if(shadowCopyFiles)
3483                 info.ShadowCopyFiles = "true";
3484
3485             return CreateDomain(friendlyName,
3486                                 securityInfo,
3487                                 info);
3488         }
3489 #endif // FEATURE_CAS_POLICY
3490
3491 #if FEATURE_CORECLR
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);
3497 #endif
3498
3499         [System.Security.SecurityCritical]  // auto-generated
3500         [ResourceExposure(ResourceScope.None)]
3501         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
3502         private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
3503         {
3504             Contract.Requires(info != null);
3505
3506 #if FEATURE_FUSION
3507             if (oldInfo == null) {
3508                         
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 ) 
3513 #else        
3514             if (info.ApplicationBase == null)
3515 #endif                
3516
3517             {
3518 #if FEATURE_FUSION
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);
3523                 }
3524                 else {
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];
3533                 }
3534 #else
3535                 info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
3536 #endif
3537                 
3538             }
3539
3540 #if FEATURE_FUSION
3541             // If there is no relative path then check the
3542             // environment
3543             if(info.Value[(int) AppDomainSetup.LoaderInformation.PrivateBinPathValue] == null)
3544                 info.PrivateBinPath = Environment.nativeGetEnvironmentVariable(AppDomainSetup.PrivateBinPathEnvironmentVariable);
3545
3546             // Add the developer path if it exists on this
3547             // machine.
3548             if(info.DeveloperPath == null)
3549                 info.DeveloperPath = RuntimeEnvironment.GetDeveloperPath();
3550
3551             }
3552                         
3553             // Set up the fusion context
3554             IntPtr fusionContext = GetFusionContext();
3555             info.SetupFusionContext(fusionContext, oldInfo);
3556
3557             // Set loader optimization policy
3558 #else
3559 #if FEATURE_VERSIONING
3560             nCreateContext();
3561 #endif // FEATURE_VERSIONING
3562 #endif // FEATURE_FUSION
3563
3564 #if FEATURE_LOADER_OPTIMIZATION
3565             if (info.LoaderOptimization != LoaderOptimization.NotSpecified || (oldInfo != null && info.LoaderOptimization != oldInfo.LoaderOptimization))
3566                 UpdateLoaderOptimization(info.LoaderOptimization);
3567 #endif                        
3568
3569
3570
3571             // This must be the last action taken
3572             _FusionStore = info;
3573         }
3574
3575         // used to package up evidence, so it can be serialized
3576         //   for the call to InternalRemotelySetupRemoteDomain
3577         [Serializable]
3578         private class EvidenceCollection
3579         {
3580             public Evidence ProvidedSecurityInfo;
3581             public Evidence CreatorsSecurityInfo;
3582         }
3583
3584         private static void RunInitializer(AppDomainSetup setup)
3585         {
3586             if (setup.AppDomainInitializer!=null)
3587             {
3588                 string[] args=null;
3589                 if (setup.AppDomainInitializerArguments!=null)
3590                     args=(string[])setup.AppDomainInitializerArguments.Clone();
3591                 setup.AppDomainInitializer(args);
3592             }
3593         }
3594
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,
3606                                                         string sandboxName,
3607                                                         string[] propertyNames,
3608                                                         string[] propertyValues)
3609         {
3610             byte[] serializedEvidence = null;
3611             bool generateDefaultEvidence = false;
3612
3613 #if FEATURE_CAS_POLICY
3614             // serialize evidence
3615             EvidenceCollection evidenceCollection = null;
3616
3617             if (providedSecurityInfo != null || creatorsSecurityInfo != null)
3618             {
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)
3629                 {
3630                     if (providedSecurityInfo != null &&
3631                         providedSecurityInfo.IsUnmodified &&
3632                         providedSecurityInfo.Target != null &&
3633                         providedSecurityInfo.Target is AppDomainEvidenceFactory)
3634                     {
3635                         providedSecurityInfo = null;
3636                         generateDefaultEvidence = true;
3637                     }
3638                     if (creatorsSecurityInfo != null &&
3639                         creatorsSecurityInfo.IsUnmodified &&
3640                         creatorsSecurityInfo.Target != null &&
3641                         creatorsSecurityInfo.Target is AppDomainEvidenceFactory)
3642                     {
3643                         creatorsSecurityInfo = null;
3644                         generateDefaultEvidence = true;
3645                     }
3646                 }
3647             }
3648             if ((providedSecurityInfo != null) ||
3649                 (creatorsSecurityInfo != null)) {
3650                 evidenceCollection = new EvidenceCollection();
3651                 evidenceCollection.ProvidedSecurityInfo = providedSecurityInfo;
3652                 evidenceCollection.CreatorsSecurityInfo = creatorsSecurityInfo;
3653             }
3654
3655             if (evidenceCollection != null) {
3656                 serializedEvidence =
3657                     CrossAppDomainSerializer.SerializeObject(evidenceCollection).GetBuffer();                
3658             }
3659 #endif // FEATURE_CAS_POLICY
3660
3661             AppDomainInitializerInfo initializerInfo = null;
3662             if (setup!=null && setup.AppDomainInitializer!=null)
3663                 initializerInfo=new AppDomainInitializerInfo(setup.AppDomainInitializer);
3664
3665             // will travel x-Ad, drop non-agile data 
3666             AppDomainSetup newSetup = new AppDomainSetup(setup, false);
3667
3668 #if FEATURE_CORECLR
3669             // Remove the special AppDomainCompatSwitch entries from the set of name value pairs
3670             // And add them to the AppDomainSetup
3671             //
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>();
3676                         
3677             if(propertyNames!=null && propertyValues != null)
3678             {
3679                 for (int i=0; i<propertyNames.Length; i++)
3680                 {
3681                     if(String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0) 
3682                     {
3683                         compatList.Add(propertyValues[i]);
3684                         propertyNames[i] = null;                        
3685                         propertyValues[i] = null;
3686                     }
3687
3688                 }
3689                 
3690                 if (compatList.Count > 0)
3691                 {
3692                     newSetup.SetCompatibilitySwitches(compatList);
3693                 }            
3694             }
3695 #endif // FEATURE_CORECLR
3696
3697
3698             return new Object[] 
3699             {
3700                 friendlyName, 
3701                 newSetup, 
3702                 parentSecurityDescriptor, 
3703                 generateDefaultEvidence,
3704                 serializedEvidence,
3705                 initializerInfo,
3706                 sandboxName,
3707                 propertyNames,
3708                 propertyValues
3709             };  
3710         } // PrepareDataForSetup
3711
3712
3713         [System.Security.SecurityCritical]  // auto-generated
3714         [MethodImplAttribute(MethodImplOptions.NoInlining)]
3715         private static Object Setup(Object arg)
3716         {
3717             Contract.Requires(arg != null && arg is Object[]);
3718             Contract.Requires(((Object[])arg).Length >= 8);
3719
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           
3730             // extract evidence
3731             Evidence providedSecurityInfo = null;
3732             Evidence creatorsSecurityInfo = null;
3733
3734
3735             AppDomain ad = AppDomain.CurrentDomain;
3736             AppDomainSetup newSetup=new AppDomainSetup(setup,false);
3737
3738             if(propertyNames!=null && propertyValues != null)
3739             {
3740                 for (int i=0; i<propertyNames.Length; i++)
3741                 {
3742                     
3743                     if(propertyNames[i]=="APPBASE") // make sure in [....] with Fusion
3744                     {
3745                         if(propertyValues[i]==null)
3746                             throw new ArgumentNullException("APPBASE");
3747                             
3748                         if (Path.IsRelative(propertyValues[i]))
3749                             throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3750
3751                         newSetup.ApplicationBase=Path.NormalizePath(propertyValues[i],true);
3752
3753                     }
3754 #if FEATURE_CAS_POLICY
3755                     else if(propertyNames[i]=="LOCATION_URI" && providedSecurityInfo==null)
3756                     {
3757                         providedSecurityInfo=new Evidence();
3758                         providedSecurityInfo.AddHostEvidence(new Url(propertyValues[i]));
3759                         ad.SetDataHelper(propertyNames[i],propertyValues[i],null);                        
3760                     }
3761 #endif // FEATURE_CAS_POLICY
3762 #if FEATURE_LOADER_OPTIMIZATION                    
3763                     else
3764                     if(propertyNames[i]=="LOADER_OPTIMIZATION")
3765                     {
3766                         if(propertyValues[i]==null)
3767                             throw new ArgumentNullException("LOADER_OPTIMIZATION");
3768
3769                         switch(propertyValues[i])
3770                         {
3771                             case "SingleDomain": newSetup.LoaderOptimization=LoaderOptimization.SingleDomain;break;
3772                             case "MultiDomain": newSetup.LoaderOptimization=LoaderOptimization.MultiDomain;break;
3773                             case "MultiDomainHost": newSetup.LoaderOptimization=LoaderOptimization.MultiDomainHost;break;
3774                             case "NotSpecified": newSetup.LoaderOptimization=LoaderOptimization.NotSpecified;break;
3775                             default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION");
3776                         }
3777                     }
3778 #endif // FEATURE_LOADER_OPTIMIZATION                    
3779 #if FEATURE_CORECLR      
3780                     else
3781                     if(propertyNames[i]=="NATIVE_DLL_SEARCH_DIRECTORIES")
3782                     {
3783                         if(propertyValues[i]==null)
3784                             throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
3785                         ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
3786                         string paths = (string)propertyValues[i];
3787                         if( paths.Length==0 )
3788                             continue;
3789                         nSetNativeDllSearchDirectories(paths);
3790                     }
3791                     else
3792                     if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES")
3793                     {
3794                         if(propertyValues[i]==null)
3795                             throw new ArgumentNullException("TRUSTED_PLATFORM_ASSEMBLIES");
3796
3797                         StringBuilder normalisedAppPathList = new StringBuilder();
3798                         foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3799                         {
3800
3801                             if( path.Length==0 )                  // skip empty dirs
3802                                 continue;
3803                                
3804                             if (Path.IsRelative(path))
3805                                 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3806
3807                             string appPath=Path.NormalizePath(path,true);
3808                             normalisedAppPathList.Append(appPath);
3809                             normalisedAppPathList.Append(Path.PathSeparator);
3810                         }
3811                         // Strip the last separator
3812                         if (normalisedAppPathList.Length > 0)
3813                         {
3814                             normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3815                         }
3816                         ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null);        // not supported by fusion, so set explicitly                
3817                     }
3818                     else
3819                     if(propertyNames[i]=="PLATFORM_RESOURCE_ROOTS")
3820                     {
3821                         if(propertyValues[i]==null)
3822                             throw new ArgumentNullException("PLATFORM_RESOURCE_ROOTS");
3823
3824                         StringBuilder normalisedAppPathList = new StringBuilder();
3825                         foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3826                         {
3827
3828                             if( path.Length==0 )                  // skip empty dirs
3829                                 continue;
3830                                
3831                             if (Path.IsRelative(path))
3832                                 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3833
3834                             string appPath=Path.NormalizePath(path,true);
3835                             normalisedAppPathList.Append(appPath);
3836                             normalisedAppPathList.Append(Path.PathSeparator);
3837                         }
3838                         // Strip the last separator
3839                         if (normalisedAppPathList.Length > 0)
3840                         {
3841                             normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3842                         }
3843                         ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null);        // not supported by fusion, so set explicitly                
3844                     }
3845                     else
3846                     if(propertyNames[i]=="APP_PATHS")
3847                     {
3848                         if(propertyValues[i]==null)
3849                             throw new ArgumentNullException("APP_PATHS");
3850
3851                         StringBuilder normalisedAppPathList = new StringBuilder();
3852                         foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3853                         {
3854
3855                             if( path.Length==0 )                  // skip empty dirs
3856                                 continue;
3857                                
3858                             if (Path.IsRelative(path))
3859                                 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3860
3861                             string appPath=Path.NormalizePath(path,true);
3862                             normalisedAppPathList.Append(appPath);
3863                             normalisedAppPathList.Append(Path.PathSeparator);
3864                         }
3865                         // Strip the last separator
3866                         if (normalisedAppPathList.Length > 0)
3867                         {
3868                             normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3869                         }
3870                         ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null);        // not supported by fusion, so set explicitly                
3871                     }
3872                     else
3873                     if(propertyNames[i]=="APP_NI_PATHS")
3874                     {
3875                         if(propertyValues[i]==null)
3876                             throw new ArgumentNullException("APP_NI_PATHS");
3877
3878                         StringBuilder normalisedAppPathList = new StringBuilder();
3879                         foreach(string path in propertyValues[i].Split(Path.PathSeparator))
3880                         {
3881
3882                             if( path.Length==0 )                  // skip empty dirs
3883                                 continue;
3884                                
3885                             if (Path.IsRelative(path))
3886                                 throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
3887
3888                             string appPath=Path.NormalizePath(path,true);
3889                             normalisedAppPathList.Append(appPath);
3890                             normalisedAppPathList.Append(Path.PathSeparator);
3891                         }
3892                         // Strip the last separator
3893                         if (normalisedAppPathList.Length > 0)
3894                         {
3895                             normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
3896                         }
3897                         ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null);        // not supported by fusion, so set explicitly                
3898                     }
3899                     else
3900                     if(propertyNames[i]!= null)
3901                     {
3902                         ad.SetDataHelper(propertyNames[i],propertyValues[i],null);     // just propagate                   
3903                     }
3904 #endif
3905
3906                 }
3907             }
3908
3909 #if !FEATURE_CORECLR
3910             AppDomainSortingSetupInfo sortingSetup = newSetup._AppDomainSortingSetupInfo;
3911
3912             if(sortingSetup != null)
3913             {          
3914                 if(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero || sortingSetup._pfnCompareStringEx == IntPtr.Zero || sortingSetup._pfnLCMapStringEx == IntPtr.Zero || sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
3915                     || sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero || sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero) 
3916                 {
3917              
3918                     if(!(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero && sortingSetup._pfnCompareStringEx == IntPtr.Zero && sortingSetup._pfnLCMapStringEx == IntPtr.Zero && sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
3919                         && sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero && sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero)) 
3920                     {
3921                         // Some functions defined but not all of them.
3922                         throw new ArgumentException(Environment.GetResourceString("ArgumentException_NotAllCustomSortingFuncsDefined"));
3923                     }
3924
3925                 }
3926             }
3927 #endif
3928
3929             ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup
3930             
3931             // technically, we don't need this, newSetup refers to the same object as FusionStore 
3932             // but it's confusing since it isn't immediately obvious whether we have a ref or a copy
3933             AppDomainSetup adSetup = ad.FusionStore; 
3934
3935 #if FEATURE_CORECLR
3936
3937 #if !FEATURE_FT_CORECLR
3938             BCLDebug.Assert(sandboxName == "Internet", "Sandbox is not Internet");
3939 #endif // !FEATURE_FT_CORECLR
3940
3941             adSetup.InternalSetApplicationTrust(sandboxName);
3942 #endif // FEATURE_CORECLR
3943
3944 #if !FEATURE_CORECLR  // not used by coreclr
3945             if (serializedEvidence != null) {
3946                 EvidenceCollection evidenceCollection = (EvidenceCollection)
3947                     CrossAppDomainSerializer.DeserializeObject(new MemoryStream(serializedEvidence));
3948                 providedSecurityInfo  = evidenceCollection.ProvidedSecurityInfo;
3949                 creatorsSecurityInfo  = evidenceCollection.CreatorsSecurityInfo;
3950             }
3951 #endif
3952             // set up the friendly name
3953             ad.nSetupFriendlyName(friendlyName);
3954
3955 #if FEATURE_COMINTEROP
3956             if (setup != null && setup.SandboxInterop)
3957             {
3958                 ad.nSetDisableInterfaceCache();
3959             }
3960 #endif // FEATURE_COMINTEROP
3961
3962             // set up the AppDomainManager for this domain and initialize security.
3963             if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null)
3964             {
3965                 ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType);
3966             }
3967
3968 #if FEATURE_APTCA
3969             // set any conditial-aptca visible assemblies
3970             ad.PartialTrustVisibleAssemblies = adSetup.PartialTrustVisibleAssemblies;
3971 #endif // FEATURE_APTCA
3972
3973             ad.CreateAppDomainManager(); // could modify FusionStore's object
3974             ad.InitializeDomainSecurity(providedSecurityInfo,
3975                                         creatorsSecurityInfo,
3976                                         generateDefaultEvidence,
3977                                         parentSecurityDescriptor,
3978                                         true);
3979             
3980             // can load user code now
3981             if(initializerInfo!=null)
3982                 adSetup.AppDomainInitializer=initializerInfo.Unwrap();
3983             RunInitializer(adSetup);
3984
3985             // Activate the application if needed.
3986 #if FEATURE_CLICKONCE 
3987             ObjectHandle oh = null;
3988             if (adSetup.ActivationArguments != null && adSetup.ActivationArguments.ActivateInstance)
3989                 oh = Activator.CreateInstance(ad.ActivationContext);
3990             return RemotingServices.MarshalInternal(oh, null, null);
3991 #else
3992             return null;
3993 #endif // FEATURE_CLICKONCE
3994         }
3995
3996
3997 #if FEATURE_APTCA
3998         // Called from DomainAssembly in Conditional APTCA cases
3999         [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
4000         [SecuritySafeCritical]
4001         private bool IsAssemblyOnAptcaVisibleList(RuntimeAssembly assembly)
4002         {
4003             if (_aptcaVisibleAssemblies == null)
4004                 return false;
4005
4006             AssemblyName assemblyName = assembly.GetName();
4007             String name = assemblyName.GetNameWithPublicKey();
4008
4009             name = name.ToUpperInvariant();
4010
4011             int index = Array.BinarySearch<string>(_aptcaVisibleAssemblies, name,
4012                                                    StringComparer.OrdinalIgnoreCase);
4013             return (index >=0);
4014
4015         }
4016
4017         //Used to binary search the list of C-APTCA strings for an AssemblyName.  It compares assembly name
4018         //and public key token.
4019         private class CAPTCASearcher : IComparer
4020         {
4021             int IComparer.Compare(object /*string*/lhs, object /*AssemblyName*/rhs)
4022             {
4023                 AssemblyName captcaEntry = new AssemblyName((string)lhs);
4024                 AssemblyName comparand = (AssemblyName)rhs;
4025                 int nameComp = string.Compare(captcaEntry.Name,
4026                                               comparand.Name,
4027                                               StringComparison.OrdinalIgnoreCase);
4028                 if (nameComp != 0)
4029                 {
4030                     return nameComp;
4031                 }
4032
4033                 //simple names match.  Compare public key tokens.
4034                 byte[] lhsKey = captcaEntry.GetPublicKeyToken();
4035                 byte[] rhsKey = comparand.GetPublicKeyToken();
4036
4037                 // We require both sides have a public key token
4038                 if (lhsKey == null)
4039                 {
4040                     return -1;
4041                 }
4042                 if (rhsKey == null)
4043                 {
4044                     return 1;
4045                 }
4046                 if (lhsKey.Length < rhsKey.Length)
4047                 {
4048                     return -1;
4049                 }
4050                 if (lhsKey.Length > rhsKey.Length)
4051                 {
4052                     return 1;
4053                 }
4054
4055                 // Tokens seem valid - make sure the compare correctly
4056                 for (int i = 0; i < lhsKey.Length; ++i)
4057                 {
4058                     byte lhsByte = lhsKey[i];
4059                     byte rhsByte = rhsKey[i];
4060
4061                     if (lhsByte < rhsByte)
4062                     {
4063                         return -1;
4064                     }
4065                     if (lhsByte > rhsByte)
4066                     {
4067                         return 1;
4068                     }
4069                 }
4070
4071                 //They match.
4072                 return 0;
4073             }
4074         }
4075
4076         [System.Security.SecurityCritical]
4077         private unsafe bool IsAssemblyOnAptcaVisibleListRaw(char * namePtr, int nameLen, byte * keyTokenPtr,
4078                                                             int keyTokenLen)
4079         {
4080             //This version is used for checking ngen dependencies against the C-APTCA list.  It lets us
4081             //reject ngen images that depend on an assembly that has been disabled in the current domain.
4082             //Since we only have the public key token in the ngen image, we'll check against that.  The
4083             //rationale is that if you have a public key token collision in your process you have many
4084             //problems.  Since the source of this public key token is an ngen image for a full trust
4085             //assembly, there is essentially no risk to the reduced check.
4086             if (_aptcaVisibleAssemblies == null)
4087                 return false;
4088
4089             string name = new string(namePtr, 0, nameLen);
4090             byte[] keyToken = new byte[keyTokenLen];
4091             for( int i = 0; i < keyToken.Length; ++i )
4092                 keyToken[i] = keyTokenPtr[i];
4093
4094             AssemblyName asmName = new AssemblyName();
4095             asmName.Name = name;
4096             asmName.SetPublicKeyToken(keyToken);
4097             try
4098             {
4099                 int index = Array.BinarySearch(_aptcaVisibleAssemblies, asmName, new CAPTCASearcher());
4100                 return (index >= 0);
4101             }
4102             catch (InvalidOperationException) { /* Can happen for poorly formed assembly names */ return false; }
4103         }
4104
4105 #endif
4106
4107         // This routine is called from unmanaged code to
4108         // set the default fusion context.
4109         [System.Security.SecurityCritical]  // auto-generated
4110         private void SetupDomain(bool allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)
4111         {
4112             // It is possible that we could have multiple threads initializing
4113             // the default domain. We will just take the winner of these two.
4114             // (eg. one thread doing a com call and another doing attach for IJW)
4115             lock (this) {
4116                 if(_FusionStore == null) {
4117                     AppDomainSetup setup = new AppDomainSetup();
4118 #if FEATURE_CORECLR
4119                     // always use internet permission set
4120                     setup.InternalSetApplicationTrust("Internet");
4121 #endif // FEATURE_CORECLR
4122 #if FEATURE_FUSION
4123                     setup.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
4124                     if(path != null)
4125                         setup.Value[(int) AppDomainSetup.LoaderInformation.ApplicationBaseValue] = path;
4126                     if(configFile != null)
4127                         setup.Value[(int) AppDomainSetup.LoaderInformation.ConfigurationFileValue] = configFile;
4128
4129                     // Default fusion context starts with binding redirects turned off.
4130                     if (!allowRedirects)
4131                         setup.DisallowBindingRedirects = true;
4132 #endif
4133
4134 #if !FEATURE_CORECLR
4135                     if (propertyNames != null) {
4136                         BCLDebug.Assert(propertyValues != null, "propertyValues != null");
4137                         BCLDebug.Assert(propertyNames.Length == propertyValues.Length, "propertyNames.Length == propertyValues.Length");
4138
4139                         for (int i = 0; i < propertyNames.Length; ++i) {
4140                             if (String.Equals(propertyNames[i], "PARTIAL_TRUST_VISIBLE_ASSEMBLIES", StringComparison.Ordinal)) {
4141                                 // The value of the PARTIAL_TRUST_VISIBLE_ASSEMBLIES property is a semicolon
4142                                 // delimited list of assembly names to add to the
4143                                 // PartialTrustVisibleAssemblies setting of the domain setup
4144                                 if (propertyValues[i] != null) {
4145                                     if (propertyValues[i].Length > 0) {
4146                                         setup.PartialTrustVisibleAssemblies = propertyValues[i].Split(';');
4147                                     }
4148                                     else {
4149                                         setup.PartialTrustVisibleAssemblies = new string[0];
4150                                     }
4151                                 }
4152                             }
4153                             else {
4154                                 // In v4 we disallow anything but PARTIAL_TRUST_VISIBLE_ASSEMBLIES to come
4155                                 // in via the default domain properties.  That restriction could be lifted
4156                                 // in a future release, at which point this assert should be removed.
4157                                 // 
4158                                 // This should be kept in [....] with the real externally facing filter code
4159                                 // in CorHost2::SetPropertiesForDefaultAppDomain
4160                                 BCLDebug.Assert(false, "Unexpected default domain property");
4161                             }
4162                         }
4163                     }
4164 #endif // !FEATURE_CORECLR
4165
4166 #if FEATURE_APTCA
4167                     // Propigate the set of conditional APTCA assemblies that will be used in the default
4168                     // domain onto the domain itself and also into the VM
4169                     PartialTrustVisibleAssemblies = setup.PartialTrustVisibleAssemblies;
4170 #endif // FEATURE_APTCA
4171
4172                     SetupFusionStore(setup, null);
4173                 }
4174             }
4175         }
4176
4177 #if FEATURE_LOADER_OPTIMIZATION
4178        [System.Security.SecurityCritical]  // auto-generated
4179        private void SetupLoaderOptimization(LoaderOptimization policy)
4180         {
4181             if(policy != LoaderOptimization.NotSpecified) {
4182                 Contract.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
4183                                 "It is illegal to change the Loader optimization on a domain");
4184
4185                 FusionStore.LoaderOptimization = policy;
4186                 UpdateLoaderOptimization(FusionStore.LoaderOptimization);
4187             }
4188         }
4189 #endif
4190            
4191 #if FEATURE_FUSION
4192         [System.Security.SecurityCritical]  // auto-generated
4193         [ResourceExposure(ResourceScope.None)]
4194         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4195         internal extern IntPtr GetFusionContext();
4196 #endif // FEATURE_FUSION
4197
4198         [System.Security.SecurityCritical]  // auto-generated
4199         [ResourceExposure(ResourceScope.None)]
4200         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4201         internal extern IntPtr GetSecurityDescriptor();
4202
4203 #if FEATURE_REMOTING        
4204         [System.Security.SecurityCritical]  // auto-generated
4205         [ResourceExposure(ResourceScope.None)]
4206         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4207         internal static extern AppDomain nCreateDomain(String friendlyName,
4208                                                       AppDomainSetup setup,
4209                                                       Evidence providedSecurityInfo,
4210                                                       Evidence creatorsSecurityInfo,
4211                                                       IntPtr parentSecurityDescriptor);
4212
4213         [System.Security.SecurityCritical]  // auto-generated
4214         [ResourceExposure(ResourceScope.None)]
4215         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4216         internal static extern ObjRef nCreateInstance(String friendlyName,
4217                                                       AppDomainSetup setup,
4218                                                       Evidence providedSecurityInfo,
4219                                                       Evidence creatorsSecurityInfo,
4220                                                       IntPtr parentSecurityDescriptor);
4221 #endif
4222
4223         [SecurityCritical]
4224         private void SetupDomainSecurity(Evidence appDomainEvidence,
4225                                          IntPtr creatorsSecurityDescriptor,
4226                                          bool publishAppDomain)
4227         {
4228             Evidence stackEvidence = appDomainEvidence;
4229             SetupDomainSecurity(GetNativeHandle(),
4230                                 JitHelpers.GetObjectHandleOnStack(ref stackEvidence),
4231                                 creatorsSecurityDescriptor,
4232                                 publishAppDomain);
4233
4234         }
4235
4236         [SecurityCritical]
4237         [ResourceExposure(ResourceScope.None)]
4238         [SuppressUnmanagedCodeSecurity]
4239         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
4240         private static extern void SetupDomainSecurity(AppDomainHandle appDomain,
4241                                                        ObjectHandleOnStack appDomainEvidence,
4242                                                        IntPtr creatorsSecurityDescriptor,
4243                                                        [MarshalAs(UnmanagedType.Bool)] bool publishAppDomain);
4244
4245         [System.Security.SecurityCritical]  // auto-generated
4246         [ResourceExposure(ResourceScope.None)]
4247         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4248         private extern void nSetupFriendlyName(string friendlyName);
4249
4250 #if FEATURE_COMINTEROP
4251         [ResourceExposure(ResourceScope.None)]
4252         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4253         private extern void nSetDisableInterfaceCache();
4254 #endif // FEATURE_COMINTEROP
4255
4256 #if FEATURE_LOADER_OPTIMIZATION
4257         [System.Security.SecurityCritical]  // auto-generated
4258         [ResourceExposure(ResourceScope.None)]
4259         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4260         internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
4261 #endif
4262
4263 #if FEATURE_FUSION       
4264         //
4265         // This is just designed to prevent compiler warnings.
4266         // This field is used from native, but we need to prevent the compiler warnings.
4267         //
4268
4269         [System.Security.SecurityCritical]  // auto-generated_required
4270         [Obsolete("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
4271         [ResourceExposure(ResourceScope.Machine)]
4272         [ResourceConsumption(ResourceScope.Machine)]
4273         public void SetShadowCopyPath(String path)
4274         {
4275             InternalSetShadowCopyPath(path);
4276         }
4277
4278         [System.Security.SecurityCritical]  // auto-generated_required
4279         [Obsolete("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. http://go.microsoft.com/fwlink/?linkid=14202")]
4280         public void SetShadowCopyFiles()
4281         {
4282             InternalSetShadowCopyFiles();
4283         }
4284
4285         [System.Security.SecurityCritical]  // auto-generated_required
4286         [Obsolete("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. http://go.microsoft.com/fwlink/?linkid=14202")]
4287         [ResourceExposure(ResourceScope.Machine)]
4288         [ResourceConsumption(ResourceScope.Machine)]
4289         public void SetDynamicBase(String path)
4290         {
4291             InternalSetDynamicBase(path);
4292         }
4293 #endif // FEATURE_FUSION
4294
4295         public AppDomainSetup SetupInformation
4296         {
4297             get {
4298                 return new AppDomainSetup(FusionStore,true);
4299             }
4300         }
4301
4302 #if FEATURE_FUSION
4303         [System.Security.SecurityCritical]  // auto-generated
4304         [ResourceExposure(ResourceScope.Machine)]
4305         [ResourceConsumption(ResourceScope.Machine)]
4306         internal void InternalSetShadowCopyPath(String path)
4307         {
4308             if (path != null)
4309             {
4310                 IntPtr fusionContext = GetFusionContext();
4311                 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyDirectoriesKey, path);
4312             }
4313             FusionStore.ShadowCopyDirectories = path;
4314         }
4315
4316         [System.Security.SecurityCritical]  // auto-generated
4317         internal void InternalSetShadowCopyFiles()
4318         {
4319             IntPtr fusionContext = GetFusionContext();
4320             AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyFilesKey, "true");
4321             FusionStore.ShadowCopyFiles = "true";
4322         }
4323
4324         [System.Security.SecurityCritical]  // auto-generated
4325         [ResourceExposure(ResourceScope.Machine)]
4326         [ResourceConsumption(ResourceScope.Machine)]
4327         internal void InternalSetCachePath(String path)
4328         {
4329             FusionStore.CachePath = path;
4330             if (FusionStore.Value[(int) AppDomainSetup.LoaderInformation.CachePathValue] != null)
4331             {
4332                 IntPtr fusionContext = GetFusionContext();
4333                 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.CachePathKey,
4334                                                      FusionStore.Value[(int) AppDomainSetup.LoaderInformation.CachePathValue]);
4335             }
4336         }
4337
4338         [System.Security.SecurityCritical]  // auto-generated
4339         [ResourceExposure(ResourceScope.Machine)]
4340         [ResourceConsumption(ResourceScope.Machine)]
4341         internal void InternalSetPrivateBinPath(String path)
4342         {
4343             IntPtr fusionContext = GetFusionContext();
4344             AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.PrivateBinPathKey, path);
4345             FusionStore.PrivateBinPath = path;
4346         }
4347
4348         [System.Security.SecurityCritical]  // auto-generated
4349         [ResourceExposure(ResourceScope.Machine)]
4350         [ResourceConsumption(ResourceScope.Machine)]
4351         internal void InternalSetDynamicBase(String path)
4352         {
4353             FusionStore.DynamicBase = path;
4354             if (FusionStore.Value[(int) AppDomainSetup.LoaderInformation.DynamicBaseValue] != null)
4355             {
4356                 IntPtr fusionContext = GetFusionContext();
4357                 AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.DynamicBaseKey,
4358                                                      FusionStore.Value[(int) AppDomainSetup.LoaderInformation.DynamicBaseValue]);
4359             }
4360         }
4361 #endif // FEATURE_FUSION
4362
4363         [System.Security.SecurityCritical]  // auto-generated
4364         [ResourceExposure(ResourceScope.None)]
4365         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4366         internal extern String IsStringInterned(String str);
4367
4368         [System.Security.SecurityCritical]  // auto-generated
4369         [ResourceExposure(ResourceScope.None)]
4370         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4371         internal extern String GetOrInternString(String str);
4372         
4373         [SecurityCritical]
4374         [ResourceExposure(ResourceScope.None)]
4375         [SuppressUnmanagedCodeSecurity]
4376         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
4377         private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
4378
4379 #if FEATURE_CAS_POLICY
4380         [SecurityCritical]
4381         [ResourceExposure(ResourceScope.None)]
4382         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
4383         [SuppressUnmanagedCodeSecurity]
4384         [return: MarshalAs(UnmanagedType.Bool)]
4385         private static extern bool GetIsLegacyCasPolicyEnabled(AppDomainHandle domain);
4386 #endif // FEATURE_CAS_POLICY
4387
4388         public PermissionSet PermissionSet
4389         {
4390             // SecurityCritical because permissions can contain sensitive information such as paths
4391             [SecurityCritical]
4392             get
4393             {
4394                 PermissionSet grantSet = null;
4395                 GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref grantSet));
4396
4397                 if (grantSet != null)
4398                 {
4399                     return grantSet.Copy();
4400                 }
4401                 else
4402                 {
4403                     return new PermissionSet(PermissionState.Unrestricted);
4404                 }
4405             }
4406         }
4407
4408         public bool IsFullyTrusted
4409         {
4410             [SecuritySafeCritical]
4411             get
4412             {
4413                 PermissionSet grantSet = null;
4414                 GetGrantSet(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref grantSet));
4415
4416                 return grantSet == null || grantSet.IsUnrestricted();
4417             }
4418         }
4419
4420         public bool IsHomogenous
4421         {
4422             get
4423             {
4424                 // Homogenous AppDomains always have an ApplicationTrust associated with them
4425                 return _IsFastFullTrustDomain || _applicationTrust != null;
4426             }
4427         }
4428
4429 #if FEATURE_CAS_POLICY
4430         internal bool IsLegacyCasPolicyEnabled
4431         {
4432             [SecuritySafeCritical]
4433             get
4434             {
4435                 return GetIsLegacyCasPolicyEnabled(GetNativeHandle());
4436             }
4437         }
4438
4439         // Determine what this homogenous domain thinks the grant set should be for a specific set of evidence
4440         [SecuritySafeCritical]
4441         internal PermissionSet GetHomogenousGrantSet(Evidence evidence)
4442         {
4443             Contract.Assert(evidence != null);
4444             Contract.Assert(IsHomogenous);
4445             Contract.Assert(evidence.GetHostEvidence<GacInstalled>() == null);
4446
4447             if (_IsFastFullTrustDomain)
4448             {
4449                 return new PermissionSet(PermissionState.Unrestricted);
4450             }
4451
4452             // If the ApplicationTrust's full trust list calls out the assembly, then it is fully trusted
4453             if (evidence.GetDelayEvaluatedHostEvidence<StrongName>() != null)
4454             {
4455                 foreach (StrongName fullTrustAssembly in ApplicationTrust.FullTrustAssemblies)
4456                 {
4457                     StrongNameMembershipCondition sn = new StrongNameMembershipCondition(fullTrustAssembly.PublicKey,
4458                                                                                          fullTrustAssembly.Name,
4459                                                                                          fullTrustAssembly.Version);
4460
4461                     object usedEvidence = null;
4462                     if ((sn as IReportMatchMembershipCondition).Check(evidence, out usedEvidence))
4463                     {
4464                         IDelayEvaluatedEvidence delayEvidence = usedEvidence as IDelayEvaluatedEvidence;
4465                         if (usedEvidence != null)
4466                         {
4467                             delayEvidence.MarkUsed();
4468                         }
4469
4470                         return new PermissionSet(PermissionState.Unrestricted);
4471                     }
4472                 }
4473             }
4474
4475             // Otherwise, the grant set is just the default grant set
4476             return ApplicationTrust.DefaultGrantSet.PermissionSet.Copy();
4477         }
4478 #endif // FEATURE_CAS_POLICY
4479
4480         [System.Security.SecurityCritical]  // auto-generated
4481         [ResourceExposure(ResourceScope.None)]
4482         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4483         private extern void nChangeSecurityPolicy();
4484
4485         [System.Security.SecurityCritical]  // auto-generated
4486         [MethodImplAttribute(MethodImplOptions.InternalCall),
4487          ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail),
4488          ResourceExposure(ResourceScope.None)]
4489         internal static extern void nUnload(Int32 domainInternal);
4490            
4491         public Object CreateInstanceAndUnwrap(String assemblyName,
4492                                               String typeName)
4493         {
4494             ObjectHandle oh = CreateInstance(assemblyName, typeName);
4495             if (oh == null)
4496                 return null;
4497
4498             return oh.Unwrap();
4499         } // CreateInstanceAndUnwrap
4500
4501
4502         public Object CreateInstanceAndUnwrap(String assemblyName, 
4503                                               String typeName,
4504                                               Object[] activationAttributes)
4505         {
4506             ObjectHandle oh = CreateInstance(assemblyName, typeName, activationAttributes);
4507             if (oh == null)
4508                 return null; 
4509
4510             return oh.Unwrap();
4511         } // CreateInstanceAndUnwrap
4512
4513
4514         [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.")]
4515         public Object CreateInstanceAndUnwrap(String assemblyName, 
4516                                               String typeName, 
4517                                               bool ignoreCase,
4518                                               BindingFlags bindingAttr, 
4519                                               Binder binder,
4520                                               Object[] args,
4521                                               CultureInfo culture,
4522                                               Object[] activationAttributes,
4523                                               Evidence securityAttributes)
4524         {
4525 #pragma warning disable 618
4526             ObjectHandle oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr,
4527                 binder, args, culture, activationAttributes, securityAttributes);
4528 #pragma warning restore 618
4529
4530             if (oh == null)
4531                 return null; 
4532             
4533             return oh.Unwrap();
4534         } // CreateInstanceAndUnwrap
4535
4536         public object CreateInstanceAndUnwrap(string assemblyName,
4537                                               string typeName,
4538                                               bool ignoreCase,
4539                                               BindingFlags bindingAttr,
4540                                               Binder binder,
4541                                               object[] args,
4542                                               CultureInfo culture,
4543                                               object[] activationAttributes)
4544         {
4545             ObjectHandle oh = CreateInstance(assemblyName,
4546                                              typeName,
4547                                              ignoreCase,
4548                                              bindingAttr,
4549                                              binder,
4550                                              args,
4551                                              culture,
4552                                              activationAttributes);
4553
4554             if (oh == null)
4555             {
4556                 return null;
4557             }
4558
4559             return oh.Unwrap();
4560         }
4561
4562         // The first parameter should be named assemblyFile, but it was incorrectly named in a previous 
4563         //  release, and the compatibility police won't let us change the name now.
4564         [ResourceExposure(ResourceScope.Machine)]
4565         [ResourceConsumption(ResourceScope.Machine)]
4566         public Object CreateInstanceFromAndUnwrap(String assemblyName,
4567                                                   String typeName)
4568         {
4569             ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName);
4570             if (oh == null)
4571                 return null;  
4572
4573             return oh.Unwrap();                
4574         } // CreateInstanceAndUnwrap
4575
4576
4577         // The first parameter should be named assemblyFile, but it was incorrectly named in a previous 
4578         //  release, and the compatibility police won't let us change the name now.
4579         [ResourceExposure(ResourceScope.Machine)]
4580         [ResourceConsumption(ResourceScope.Machine)]
4581         public Object CreateInstanceFromAndUnwrap(String assemblyName,
4582                                                   String typeName,
4583                                                   Object[] activationAttributes)
4584         {
4585             ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, activationAttributes);
4586             if (oh == null)
4587                 return null; 
4588
4589             return oh.Unwrap();
4590         } // CreateInstanceAndUnwrap
4591
4592
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         [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.")]
4598         public Object CreateInstanceFromAndUnwrap(String assemblyName, 
4599                                                   String typeName, 
4600                                                   bool ignoreCase,
4601                                                   BindingFlags bindingAttr, 
4602                                                   Binder binder,
4603                                                   Object[] args,
4604                                                   CultureInfo culture,
4605                                                   Object[] activationAttributes,
4606                                                   Evidence securityAttributes)
4607         {
4608 #pragma warning disable 618
4609             ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr,
4610                 binder, args, culture, activationAttributes, securityAttributes);
4611 #pragma warning restore 618
4612
4613             if (oh == null)
4614                 return null; 
4615
4616             return oh.Unwrap();
4617         } // CreateInstanceAndUnwrap
4618
4619         [ResourceExposure(ResourceScope.Machine)]
4620         [ResourceConsumption(ResourceScope.Machine)]
4621         public object CreateInstanceFromAndUnwrap(string assemblyFile,
4622                                                   string typeName,
4623                                                   bool ignoreCase,
4624                                                   BindingFlags bindingAttr,
4625                                                   Binder binder,
4626                                                   object[] args,
4627                                                   CultureInfo culture,
4628                                                   object[] activationAttributes)
4629         {
4630             ObjectHandle oh = CreateInstanceFrom(assemblyFile,
4631                                                  typeName,
4632                                                  ignoreCase,
4633                                                  bindingAttr,
4634                                                  binder,
4635                                                  args,
4636                                                  culture,
4637                                                  activationAttributes);
4638             if (oh == null)
4639             {
4640                 return null;
4641             }
4642             
4643             return oh.Unwrap();
4644         }
4645
4646         public Int32 Id
4647         {
4648             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]  
4649             get {
4650                 return GetId();
4651             }
4652         }
4653
4654         [System.Security.SecuritySafeCritical]  // auto-generated
4655         [ResourceExposure(ResourceScope.None)]
4656         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4657         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]              
4658         internal extern Int32 GetId();
4659         
4660         internal const Int32 DefaultADID = 1;
4661         
4662         public bool IsDefaultAppDomain()
4663         {
4664             if (GetId()==DefaultADID)
4665                 return true;
4666             return false;
4667         }
4668
4669         [ResourceExposure(ResourceScope.Machine)]
4670         [ResourceConsumption(ResourceScope.Machine)]
4671         private static AppDomainSetup InternalCreateDomainSetup(String imageLocation)
4672         {
4673             int i = imageLocation.LastIndexOf('\\');
4674  
4675             Contract.Assert(i != -1, "invalid image location");
4676
4677             AppDomainSetup info = new AppDomainSetup();
4678             info.ApplicationBase = imageLocation.Substring(0, i+1);
4679
4680             StringBuilder config = new StringBuilder(imageLocation.Substring(i+1));
4681             config.Append(AppDomainSetup.ConfigurationExtension);
4682             info.ConfigurationFile = config.ToString();
4683
4684             return info;
4685         }
4686
4687         // Used by the validator for testing but not executing an assembly
4688 #if FEATURE_REMOTING        
4689         [ResourceExposure(ResourceScope.Machine)]
4690         [ResourceConsumption(ResourceScope.Machine)]
4691         private static AppDomain InternalCreateDomain(String imageLocation)
4692         {
4693             AppDomainSetup info = InternalCreateDomainSetup(imageLocation);
4694             return CreateDomain("Validator",
4695                                 null,
4696                                 info);
4697         }
4698 #endif
4699
4700 #if FEATURE_APPDOMAIN_RESOURCE_MONITORING
4701         [System.Security.SecurityCritical]  // auto-generated
4702         [ResourceExposure(ResourceScope.None)]
4703         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4704         private static extern void nEnableMonitoring();
4705
4706         [System.Security.SecurityCritical]  // auto-generated
4707         [ResourceExposure(ResourceScope.None)]
4708         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4709         private static extern bool nMonitoringIsEnabled();
4710
4711         // return -1 if ARM is not supported.
4712         [System.Security.SecurityCritical]  // auto-generated
4713         [ResourceExposure(ResourceScope.None)]
4714         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4715         private extern Int64 nGetTotalProcessorTime();
4716
4717         // return -1 if ARM is not supported.
4718         [System.Security.SecurityCritical]  // auto-generated
4719         [ResourceExposure(ResourceScope.None)]
4720         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4721         private extern Int64 nGetTotalAllocatedMemorySize();
4722
4723         // return -1 if ARM is not supported.
4724         [System.Security.SecurityCritical]  // auto-generated
4725         [ResourceExposure(ResourceScope.None)]
4726         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4727         private extern Int64 nGetLastSurvivedMemorySize();
4728
4729         // return -1 if ARM is not supported.
4730         [System.Security.SecurityCritical]  // auto-generated
4731         [ResourceExposure(ResourceScope.None)]
4732         [MethodImplAttribute(MethodImplOptions.InternalCall)]
4733         private static extern Int64 nGetLastSurvivedProcessMemorySize();
4734
4735         public static bool MonitoringIsEnabled
4736         {
4737             [System.Security.SecurityCritical]
4738             get {
4739                 return nMonitoringIsEnabled();
4740             }
4741             
4742             [System.Security.SecurityCritical]
4743             set {
4744                 if (value == false)
4745                 {
4746                     throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTrue"));
4747                 }
4748                 else
4749                 {
4750                     nEnableMonitoring();
4751                 }
4752             }
4753         }
4754
4755         // Gets the total processor time for this AppDomain.
4756         // Throws NotSupportedException if ARM is not enabled.
4757         public TimeSpan MonitoringTotalProcessorTime 
4758         {
4759             [System.Security.SecurityCritical]
4760             get {
4761                 Int64 i64ProcessorTime = nGetTotalProcessorTime();
4762                 if (i64ProcessorTime == -1)
4763                 {
4764                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4765                 }
4766                 return new TimeSpan(i64ProcessorTime);
4767             }
4768         }
4769
4770         // Gets the number of bytes allocated in this AppDomain since
4771         // the AppDomain was created.
4772         // Throws NotSupportedException if ARM is not enabled.
4773         public Int64 MonitoringTotalAllocatedMemorySize 
4774         {
4775             [System.Security.SecurityCritical]
4776             get {
4777                 Int64 i64AllocatedMemory = nGetTotalAllocatedMemorySize();
4778                 if (i64AllocatedMemory == -1)
4779                 {
4780                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4781                 }
4782                 return i64AllocatedMemory;
4783             }
4784         }
4785
4786         // Gets the number of bytes survived after the last collection
4787         // that are known to be held by this AppDomain. After a full 
4788         // collection this number is accurate and complete. After an 
4789         // ephemeral collection this number is potentially incomplete.
4790         // Throws NotSupportedException if ARM is not enabled.
4791         public Int64 MonitoringSurvivedMemorySize
4792         {
4793             [System.Security.SecurityCritical]
4794             get {
4795                 Int64 i64LastSurvivedMemory = nGetLastSurvivedMemorySize();
4796                 if (i64LastSurvivedMemory == -1)
4797                 {
4798                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4799                 }
4800                 return i64LastSurvivedMemory;
4801             }
4802         }
4803
4804         // Gets the total bytes survived from the last collection. After 
4805         // a full collection this number represents the number of the bytes 
4806         // being held live in managed heaps. (This number should be close 
4807         // to the number obtained from GC.GetTotalMemory for a full collection.)
4808         // After an ephemeral collection this number represents the number 
4809         // of bytes being held live in ephemeral generations.
4810         // Throws NotSupportedException if ARM is not enabled.
4811         public static Int64 MonitoringSurvivedProcessMemorySize
4812         {
4813             [System.Security.SecurityCritical]
4814             get {
4815                 Int64 i64LastSurvivedProcessMemory = nGetLastSurvivedProcessMemorySize();
4816                 if (i64LastSurvivedProcessMemory == -1)
4817                 {
4818                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WithoutARM"));
4819                 }
4820                 return i64LastSurvivedProcessMemory;
4821             }
4822         }
4823 #endif
4824
4825 #if FEATURE_FUSION
4826         [System.Security.SecurityCritical]  // auto-generated
4827         [ResourceExposure(ResourceScope.Machine)]
4828         [ResourceConsumption(ResourceScope.Machine)]
4829         private void InternalSetDomainContext(String imageLocation)
4830         {
4831             SetupFusionStore(InternalCreateDomainSetup(imageLocation), null);
4832         }
4833 #endif
4834
4835 #if !FEATURE_CORECLR
4836         // this method is required so Object.GetType is not made virtual by the compiler
4837         // _AppDomain.GetType()
4838         public new Type GetType()
4839         {
4840             return base.GetType();
4841         }
4842
4843         void _AppDomain.GetTypeInfoCount(out uint pcTInfo)
4844         {
4845             throw new NotImplementedException();
4846         }
4847
4848         void _AppDomain.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
4849         {
4850             throw new NotImplementedException();
4851         }
4852
4853         void _AppDomain.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
4854         {
4855             throw new NotImplementedException();
4856         }
4857
4858         // If you implement this method, make sure to include _AppDomain.Invoke in VM\DangerousAPIs.h and 
4859         // include _AppDomain in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
4860         void _AppDomain.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
4861         {
4862             throw new NotImplementedException();
4863         }
4864 #endif
4865     }
4866
4867     //  CallBacks provide a facility to request execution of some code
4868     //  in another context/appDomain.
4869     //  CrossAppDomainDelegate type is defined for appdomain call backs. 
4870     //  The delegate used to request a callbak through the DoCallBack method
4871     //  must be of CrossContextDelegate type.
4872 #if FEATURE_REMOTING    
4873 [System.Runtime.InteropServices.ComVisible(true)]
4874     public delegate void CrossAppDomainDelegate();
4875 #endif
4876
4877     /// <summary>
4878     ///     Handle used to marshal an AppDomain to the VM (eg QCall). When marshaled via a QCall, the target
4879     ///     method in the VM will recieve a QCall::AppDomainHandle parameter.
4880     /// </summary>
4881     internal struct AppDomainHandle
4882     {
4883         private IntPtr m_appDomainHandle;
4884
4885         // Note: generall an AppDomainHandle should not be directly constructed, instead the
4886         // code:System.AppDomain.GetNativeHandle method should be called to get the handle for a specific
4887         // AppDomain.
4888         internal AppDomainHandle(IntPtr domainHandle)
4889         {
4890             m_appDomainHandle = domainHandle;
4891         }
4892     }
4893 }