The Labs \ Source Viewer \ SSCLI \ System \ AppDomain

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. /*=============================================================================
  16. **
  17. ** Class: AppDomain
  18. **
  19. **
  20. ** Purpose: Domains represent an application within the runtime. Objects can
  21. **          not be shared between domains and each domain can be configured
  22. **          independently.
  23. **
  24. **
  25. =============================================================================*/
  26. namespace System
  27. {
  28.     using System;
  29.     using System.Reflection;
  30.     using System.Runtime;
  31.     using System.Runtime.Hosting;
  32.     using System.Runtime.CompilerServices;
  33.     using System.Runtime.Remoting.Channels;
  34.     using System.Runtime.Remoting.Contexts;
  35.     using System.Security;
  36.     using System.Security.Permissions;
  37.     using System.Security.Principal;
  38.     using System.Security.Policy;
  39.     using System.Security.Util;
  40.     using System.Collections;
  41.     using System.Collections.Generic;
  42.     using System.Threading;
  43.     using System.Runtime.InteropServices;
  44.     using System.Runtime.Remoting;
  45.     using Context = System.Runtime.Remoting.Contexts.Context;
  46.     using System.Reflection.Emit;
  47.     using Message = System.Runtime.Remoting.Messaging.Message;
  48.     using CultureInfo = System.Globalization.CultureInfo;
  49.     using System.IO;
  50.     using BinaryFormatter = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter;
  51.     using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
  52.     using System.Text;
  53.     using Microsoft.Win32;
  54.     using System.Runtime.ConstrainedExecution;
  55.     using System.Runtime.Versioning;
  56.    
  57.     [ComVisible(true)]
  58.     public class ResolveEventArgs : EventArgs
  59.     {
  60.         private string _Name;
  61.        
  62.         public string Name {
  63.             get { return _Name; }
  64.         }
  65.        
  66.         public ResolveEventArgs(string name)
  67.         {
  68.             _Name = name;
  69.         }
  70.     }
  71.    
  72.     [ComVisible(true)]
  73.     public class AssemblyLoadEventArgs : EventArgs
  74.     {
  75.         private Assembly _LoadedAssembly;
  76.        
  77.         public Assembly LoadedAssembly {
  78.             get { return _LoadedAssembly; }
  79.         }
  80.        
  81.         public AssemblyLoadEventArgs(Assembly loadedAssembly)
  82.         {
  83.             _LoadedAssembly = loadedAssembly;
  84.         }
  85.     }
  86.    
  87.    
  88.     [Serializable()]
  89.     [ComVisible(true)]
  90.     public delegate Assembly ResolveEventHandler(object sender, ResolveEventArgs args);
  91.    
  92.     [Serializable()]
  93.     [ComVisible(true)]
  94.     public delegate void AssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args);
  95.    
  96.     [Serializable()]
  97.     [ComVisible(true)]
  98.     public delegate void AppDomainInitializer(string[] args);
  99.    
  100.     internal class AppDomainInitializerInfo
  101.     {
  102.         internal class ItemInfo
  103.         {
  104.             public string TargetTypeAssembly;
  105.             public string TargetTypeName;
  106.             public string MethodName;
  107.         }
  108.        
  109.         internal ItemInfo[] Info;
  110.        
  111.         internal AppDomainInitializerInfo(AppDomainInitializer init)
  112.         {
  113.             Info = null;
  114.             if (init == null)
  115.                 return;
  116.             ArrayList itemInfo = new ArrayList();
  117.             ArrayList nestedDelegates = new ArrayList();
  118.             nestedDelegates.Add(init);
  119.             int idx = 0;
  120.            
  121.             while (nestedDelegates.Count > idx) {
  122.                 AppDomainInitializer curr = (AppDomainInitializer)nestedDelegates[idx++];
  123.                 Delegate[] list = curr.GetInvocationList();
  124.                 for (int i = 0; i < list.Length; i++) {
  125.                     if (!list[i].Method.IsStatic) {
  126.                         if (list[i].Target == null)
  127.                             continue;
  128.                        
  129.                         AppDomainInitializer nested = list[i].Target as AppDomainInitializer;
  130.                         if (nested != null)
  131.                             nestedDelegates.Add(nested);
  132.                         else
  133.                             throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"), list[i].Method.ReflectedType.FullName + "::" + list[i].Method.Name);
  134.                     }
  135.                     else {
  136.                         ItemInfo info = new ItemInfo();
  137.                         info.TargetTypeAssembly = list[i].Method.ReflectedType.Module.Assembly.FullName;
  138.                         info.TargetTypeName = list[i].Method.ReflectedType.FullName;
  139.                         info.MethodName = list[i].Method.Name;
  140.                         itemInfo.Add(info);
  141.                     }
  142.                    
  143.                 }
  144.             }
  145.            
  146.             Info = (ItemInfo[])itemInfo.ToArray(typeof(ItemInfo));
  147.         }
  148.        
  149.         internal AppDomainInitializer Unwrap()
  150.         {
  151.             if (Info == null)
  152.                 return null;
  153.             AppDomainInitializer retVal = null;
  154.             new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
  155.             for (int i = 0; i < Info.Length; i++) {
  156.                 Assembly assembly = Assembly.Load(Info[i].TargetTypeAssembly);
  157.                 AppDomainInitializer newVal = (AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer), assembly.GetType(Info[i].TargetTypeName), Info[i].MethodName);
  158.                 if (retVal == null)
  159.                     retVal = newVal;
  160.                 else
  161.                     retVal += newVal;
  162.             }
  163.             return retVal;
  164.         }
  165.     }
  166.    
  167.    
  168.     [ClassInterface(ClassInterfaceType.None)]
  169.     [ComDefaultInterface(typeof(System._AppDomain))]
  170.     [ComVisible(true)]
  171.     public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory
  172.     {
  173.         // Domain security information
  174.         // These fields initialized from the other side only. (NOTE: order
  175.         // of these fields cannot be changed without changing the layout in
  176.         // the EE)
  177.        
  178.         private AppDomainManager _domainManager;
  179.         private Hashtable _LocalStore;
  180.         private AppDomainSetup _FusionStore;
  181.         private Evidence _SecurityIdentity;
  182.         #pragma warning disable 169
  183.         private object[] _Policies;
  184.         // Called from the VM.
  185.         #pragma warning restore 169
  186.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  187.         public event AssemblyLoadEventHandler AssemblyLoad;
  188.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  189.         public event ResolveEventHandler TypeResolve;
  190.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  191.         public event ResolveEventHandler ResourceResolve;
  192.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  193.         public event ResolveEventHandler AssemblyResolve;
  194.        
  195.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  196.         public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
  197.        
  198.         private Context _DefaultContext;
  199.        
  200.        
  201.         private IPrincipal _DefaultPrincipal;
  202.         private DomainSpecificRemotingData _RemotingData;
  203.         private EventHandler _processExit;
  204.         private EventHandler _domainUnload;
  205.         private UnhandledExceptionEventHandler _unhandledException;
  206.        
  207.         #pragma warning disable 169
  208.         private IntPtr _dummyField;
  209.         // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
  210.         #pragma warning restore 169
  211.         private PrincipalPolicy _PrincipalPolicy;
  212.         // this is an enum
  213.         private bool _HasSetPolicy;
  214.        
  215.         // this method is required so Object.GetType is not made virtual by the compiler
  216.         public new Type GetType()
  217.         {
  218.             return base.GetType();
  219.         }
  220.        
  221.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  222.         private static extern string nGetDomainManagerAsm();
  223.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  224.         private static extern string nGetDomainManagerType();
  225.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  226.         private static extern void nSetHostSecurityManagerFlags(HostSecurityManagerOptions flags);
  227.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  228.         private static extern void nSetSecurityHomogeneousFlag();
  229.        
  230.         // Called from the VM during the default domain initialization phase.
  231.         private void SetDefaultDomainManager(string fullName, string[] manifestPaths, string[] activationData)
  232.         {
  233.             SetDomainManager(null, null, IntPtr.Zero, false);
  234.         }
  235.        
  236.         // Called for every AppDomain (including the default domain) to initialize
  237.         // the AppDomainManager instance and security of the AppDomain.
  238.         private void SetDomainManager(Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor, bool publishAppDomain)
  239.         {
  240.            
  241.             // Create the AppDomainManager for the AppDomain if specified.
  242.             string domainManagerAssemblyName = nGetDomainManagerAsm();
  243.             string domainManagerTypeName = nGetDomainManagerType();
  244.            
  245.             if (domainManagerAssemblyName != null && domainManagerTypeName != null)
  246.                 _domainManager = CreateDomainManager(domainManagerAssemblyName, domainManagerTypeName);
  247.            
  248.             AppDomainSetup adSetup = FusionStore;
  249.             // Call AppDomainManager initialization -- runs host custom code.
  250.             if (_domainManager != null) {
  251.                 // Call InitializeNewDomain and register the AppDomainManager with the host if needed.
  252.                 _domainManager.InitializeNewDomain(adSetup);
  253.                 AppDomainManagerInitializationOptions flags = _domainManager.InitializationFlags;
  254.                 if ((flags & AppDomainManagerInitializationOptions.RegisterWithHost) == AppDomainManagerInitializationOptions.RegisterWithHost)
  255.                     _domainManager.nRegisterWithHost();
  256.             }
  257.            
  258.            
  259.             // Set the new evidence to the default loader behavior.
  260.             Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo);
  261.             if (_domainManager != null) {
  262.                 // Give the host a chance to alter the AppDomain evidence
  263.                 HostSecurityManager securityManager = _domainManager.HostSecurityManager;
  264.                 if (securityManager != null) {
  265.                     nSetHostSecurityManagerFlags(securityManager.Flags);
  266.                     if ((securityManager.Flags & HostSecurityManagerOptions.HostAppDomainEvidence) == HostSecurityManagerOptions.HostAppDomainEvidence)
  267.                         newAppDomainEvidence = securityManager.ProvideAppDomainEvidence(newAppDomainEvidence);
  268.                 }
  269.             }
  270.            
  271.             // Set the evidence on the managed side
  272.             _SecurityIdentity = newAppDomainEvidence;
  273.            
  274.             // Set the evidence of the AppDomain in the VM.
  275.             // Also, now that the initialization is complete, signal that to the security system.
  276.             // Finish the AppDomain initialization and resolve the policy for the AppDomain evidence.
  277.             nSetupDomainSecurity(newAppDomainEvidence, parentSecurityDescriptor, publishAppDomain);
  278.            
  279.             // The AppDomain is now resolved. Go ahead and set the PolicyLevel
  280.             // from the HostSecurityManager if specified.
  281.             if (_domainManager != null)
  282.                 RunDomainManagerPostInitialization(_domainManager);
  283.         }
  284.        
  285.         private AppDomainManager CreateDomainManager(string domainManagerAssemblyName, string domainManagerTypeName)
  286.         {
  287.             AppDomainManager domainManager = null;
  288.             try {
  289.                 domainManager = CreateInstanceAndUnwrap(domainManagerAssemblyName, domainManagerTypeName) as AppDomainManager;
  290.             }
  291.             catch (FileNotFoundException) {
  292.             }
  293.             catch (TypeLoadException) {
  294.             }
  295.             finally {
  296.                 if (domainManager == null)
  297.                     throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"));
  298.             }
  299.             return domainManager;
  300.         }
  301.        
  302.         private void RunDomainManagerPostInitialization(AppDomainManager domainManager)
  303.         {
  304.             // force creation of the HostExecutionContextManager for the current AppDomain
  305.             HostExecutionContextManager contextManager = domainManager.HostExecutionContextManager;
  306.            
  307.             HostSecurityManager securityManager = domainManager.HostSecurityManager;
  308.             if (securityManager != null) {
  309.                 if ((securityManager.Flags & HostSecurityManagerOptions.HostPolicyLevel) == HostSecurityManagerOptions.HostPolicyLevel) {
  310.                     // set AppDomain policy if specified
  311.                     PolicyLevel level = securityManager.DomainPolicy;
  312.                     if (level != null)
  313.                         SetAppDomainPolicy(level);
  314.                 }
  315.             }
  316.         }
  317.        
  318.        
  319.         // This method is called from CorHost2::ExecuteApplication to activate a ClickOnce application in the default AppDomain.
  320.         private int ActivateApplication()
  321.         {
  322.             return 0;
  323.         }
  324.        
  325.         public AppDomainManager DomainManager {
  326.             [SecurityPermission(SecurityAction.LinkDemand, ControlDomainPolicy = true)]
  327.             get { return _domainManager; }
  328.         }
  329.        
  330.         internal HostSecurityManager HostSecurityManager {
  331.             get {
  332.                 HostSecurityManager securityManager = null;
  333.                 AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
  334.                 if (domainManager != null)
  335.                     securityManager = domainManager.HostSecurityManager;
  336.                
  337.                 if (securityManager == null)
  338.                     securityManager = new HostSecurityManager();
  339.                 return securityManager;
  340.             }
  341.         }
  342.        
  343.         private Assembly ResolveAssemblyForIntrospection(object sender, ResolveEventArgs args)
  344.         {
  345.             return Assembly.ReflectionOnlyLoad(ApplyPolicy(args.Name));
  346.         }
  347.        
  348.         private void EnableResolveAssembliesForIntrospection()
  349.         {
  350.             CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
  351.         }
  352.        
  353. /**********************************************
  354.         * If an AssemblyName has a public key specified, the assembly is assumed
  355.         * to have a strong name and a hash will be computed when the assembly
  356.         * is saved.
  357.         **********************************************/       
  358.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
  359.         {
  360.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  361.             return InternalDefineDynamicAssembly(name, access, null, null, null, null, null, ref stackMark);
  362.         }
  363.        
  364.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir)
  365.         {
  366.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  367.             return InternalDefineDynamicAssembly(name, access, dir, null, null, null, null, ref stackMark);
  368.         }
  369.        
  370.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)
  371.         {
  372.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  373.             return InternalDefineDynamicAssembly(name, access, null, evidence, null, null, null, ref stackMark);
  374.         }
  375.        
  376.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
  377.         {
  378.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  379.             return InternalDefineDynamicAssembly(name, access, null, null, requiredPermissions, optionalPermissions, refusedPermissions, ref stackMark);
  380.         }
  381.        
  382.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence)
  383.         {
  384.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  385.             return InternalDefineDynamicAssembly(name, access, dir, evidence, null, null, null, ref stackMark);
  386.         }
  387.        
  388.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
  389.         {
  390.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  391.             return InternalDefineDynamicAssembly(name, access, dir, null, requiredPermissions, optionalPermissions, refusedPermissions, ref stackMark);
  392.         }
  393.        
  394.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
  395.         {
  396.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  397.             return InternalDefineDynamicAssembly(name, access, null, evidence, requiredPermissions, optionalPermissions, refusedPermissions, ref stackMark);
  398.         }
  399.        
  400.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)
  401.         {
  402.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  403.             return InternalDefineDynamicAssembly(name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, ref stackMark);
  404.         }
  405.        
  406.        
  407.         public AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, bool isSynchronized)
  408.         {
  409.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  410.             AssemblyBuilder assemblyBuilder = InternalDefineDynamicAssembly(name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, ref stackMark);
  411.             assemblyBuilder.m_assemblyData.m_isSynchronized = isSynchronized;
  412.             return assemblyBuilder;
  413.         }
  414.        
  415.        
  416.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  417.         private extern string nApplyPolicy(AssemblyName an);
  418.        
  419.         // Return the assembly name that results from applying policy.
  420.         [ComVisible(false)]
  421.         public string ApplyPolicy(string assemblyName)
  422.         {
  423.             AssemblyName asmName = new AssemblyName(assemblyName);
  424.            
  425.             byte[] pk = asmName.GetPublicKeyToken();
  426.             if (pk == null)
  427.                 pk = asmName.GetPublicKey();
  428.            
  429.             // Simply-named assemblies cannot have policy, so for those,
  430.             // we simply return the passed-in assembly name.
  431.             if ((pk == null) || (pk.Length == 0))
  432.                 return assemblyName;
  433.             else
  434.                 return nApplyPolicy(asmName);
  435.         }
  436.        
  437.        
  438.        
  439.         public ObjectHandle CreateInstance(string assemblyName, string typeName)
  440.         {
  441.             // jit does not check for that, so we should do it ...
  442.             if (this == null)
  443.                 throw new NullReferenceException();
  444.            
  445.             if (assemblyName == null)
  446.                 throw new ArgumentNullException("assemblyName");
  447.            
  448.             return Activator.CreateInstance(assemblyName, typeName);
  449.         }
  450.        
  451.         internal ObjectHandle InternalCreateInstanceWithNoSecurity(string assemblyName, string typeName)
  452.         {
  453.             PermissionSet.s_fullTrust.Assert();
  454.             return CreateInstance(assemblyName, typeName);
  455.         }
  456.        
  457.        
  458.         public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName)
  459.         {
  460.             // jit does not check for that, so we should do it ...
  461.             if (this == null)
  462.                 throw new NullReferenceException();
  463.            
  464.             return Activator.CreateInstanceFrom(assemblyFile, typeName);
  465.         }
  466.        
  467.         internal ObjectHandle InternalCreateInstanceFromWithNoSecurity(string assemblyName, string typeName)
  468.         {
  469.             PermissionSet.s_fullTrust.Assert();
  470.             return CreateInstanceFrom(assemblyName, typeName);
  471.         }
  472.        
  473.        
  474.        
  475.         public ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes)
  476.         {
  477.             // jit does not check for that, so we should do it ...
  478.             if (this == null)
  479.                 throw new NullReferenceException();
  480.            
  481.             if (assemblyName == null)
  482.                 throw new ArgumentNullException("assemblyName");
  483.            
  484.             return Activator.CreateInstance(assemblyName, typeName, activationAttributes);
  485.         }
  486.        
  487.        
  488.         public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes)
  489.         {
  490.             // jit does not check for that, so we should do it ...
  491.             if (this == null)
  492.                 throw new NullReferenceException();
  493.            
  494.             return Activator.CreateInstanceFrom(assemblyFile, typeName, activationAttributes);
  495.         }
  496.        
  497.         public ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
  498.         {
  499.             // jit does not check for that, so we should do it ...
  500.             if (this == null)
  501.                 throw new NullReferenceException();
  502.            
  503.             if (assemblyName == null)
  504.                 throw new ArgumentNullException("assemblyName");
  505.            
  506.             return Activator.CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
  507.         }
  508.        
  509.         internal ObjectHandle InternalCreateInstanceWithNoSecurity(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
  510.         {
  511.             PermissionSet.s_fullTrust.Assert();
  512.             return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
  513.         }
  514.        
  515.        
  516.         public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
  517.         {
  518.             // jit does not check for that, so we should do it ...
  519.             if (this == null)
  520.                 throw new NullReferenceException();
  521.            
  522.             return Activator.CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
  523.         }
  524.        
  525.         internal ObjectHandle InternalCreateInstanceFromWithNoSecurity(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
  526.         {
  527.             PermissionSet.s_fullTrust.Assert();
  528.             return CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
  529.         }
  530.        
  531.         public Assembly Load(AssemblyName assemblyRef)
  532.         {
  533.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  534.             return Assembly.InternalLoad(assemblyRef, null, ref stackMark, false);
  535.         }
  536.        
  537.         public Assembly Load(string assemblyString)
  538.         {
  539.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  540.             return Assembly.InternalLoad(assemblyString, null, ref stackMark, false);
  541.         }
  542.        
  543.         public Assembly Load(byte[] rawAssembly)
  544.         {
  545.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  546.                 // symbol store
  547.                 // evidence
  548.             return Assembly.nLoadImage(rawAssembly, null, null, ref stackMark, false);
  549.            
  550.         }
  551.        
  552.         public Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore)
  553.         {
  554.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  555.                 // evidence
  556.                 // fIntrospection
  557.             return Assembly.nLoadImage(rawAssembly, rawSymbolStore, null, ref stackMark, false);
  558.         }
  559.        
  560.         [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
  561.         public Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)
  562.         {
  563.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  564.                 // fIntrospection
  565.             return Assembly.nLoadImage(rawAssembly, rawSymbolStore, securityEvidence, ref stackMark, false);
  566.         }
  567.        
  568.         public Assembly Load(AssemblyName assemblyRef, Evidence assemblySecurity)
  569.         {
  570.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  571.             return Assembly.InternalLoad(assemblyRef, assemblySecurity, ref stackMark, false);
  572.         }
  573.        
  574.         public Assembly Load(string assemblyString, Evidence assemblySecurity)
  575.         {
  576.             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
  577.             return Assembly.InternalLoad(assemblyString, assemblySecurity, ref stackMark, false);
  578.         }
  579.        
  580.         public int ExecuteAssembly(string assemblyFile)
  581.         {
  582.             return ExecuteAssembly(assemblyFile, null, null);
  583.         }
  584.        
  585.         public int ExecuteAssembly(string assemblyFile, Evidence assemblySecurity)
  586.         {
  587.             return ExecuteAssembly(assemblyFile, assemblySecurity, null);
  588.         }
  589.        
  590.         public int ExecuteAssembly(string assemblyFile, Evidence assemblySecurity, string[] args)
  591.         {
  592.             Assembly assembly = Assembly.LoadFrom(assemblyFile, assemblySecurity);
  593.            
  594.             if (args == null)
  595.                 args = new string[0];
  596.            
  597.             return nExecuteAssembly(assembly, args);
  598.         }
  599.        
  600.         public int ExecuteAssembly(string assemblyFile, Evidence assemblySecurity, string[] args, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
  601.         {
  602.             Assembly assembly = Assembly.LoadFrom(assemblyFile, assemblySecurity, hashValue, hashAlgorithm);
  603.             if (args == null)
  604.                 args = new string[0];
  605.            
  606.             return nExecuteAssembly(assembly, args);
  607.         }
  608.        
  609.         public int ExecuteAssemblyByName(string assemblyName)
  610.         {
  611.             return ExecuteAssemblyByName(assemblyName, null, null);
  612.         }
  613.        
  614.         public int ExecuteAssemblyByName(string assemblyName, Evidence assemblySecurity)
  615.         {
  616.             return ExecuteAssemblyByName(assemblyName, assemblySecurity, null);
  617.         }
  618.        
  619.         public int ExecuteAssemblyByName(string assemblyName, Evidence assemblySecurity, params string[] args)
  620.         {
  621.             Assembly assembly = Assembly.Load(assemblyName, assemblySecurity);
  622.            
  623.             if (args == null)
  624.                 args = new string[0];
  625.            
  626.             return nExecuteAssembly(assembly, args);
  627.         }
  628.        
  629.         public int ExecuteAssemblyByName(AssemblyName assemblyName, Evidence assemblySecurity, params string[] args)
  630.         {
  631.             Assembly assembly = Assembly.Load(assemblyName, assemblySecurity);
  632.            
  633.             if (args == null)
  634.                 args = new string[0];
  635.            
  636.             return nExecuteAssembly(assembly, args);
  637.         }
  638.        
  639.         public static AppDomain CurrentDomain {
  640.             get { return Thread.GetDomain(); }
  641.         }
  642.        
  643.         public Evidence Evidence {
  644.             [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
  645.             get {
  646.                 if (_SecurityIdentity == null) {
  647.                     if (IsDefaultAppDomain()) {
  648.                         //
  649.                         // V1.x compatibility: the evidence of the default
  650.                         // AppDomain is that of the entry assembly.
  651.                         //
  652.                         Assembly entryAsm = Assembly.GetEntryAssembly();
  653.                         if (entryAsm != null)
  654.                             return entryAsm.Evidence;
  655.                         else
  656.                             return new Evidence();
  657.                     }
  658.                     if (nIsDefaultAppDomainForSecurity()) {
  659.                         //
  660.                         // V1.x compatibility: If this is an AppDomain created
  661.                         // by the default appdomain without an explicit evidence
  662.                         // then reuse the evidence of the default AppDomain.
  663.                         //
  664.                         return GetDefaultDomain().Evidence;
  665.                     }
  666.                 }
  667.                
  668.                 Evidence ev = this.InternalEvidence;
  669.                 return (ev == null ? ev : ev.Copy());
  670.             }
  671.         }
  672.        
  673.         internal Evidence InternalEvidence {
  674.             get { return _SecurityIdentity; }
  675.         }
  676.        
  677.         // Should return a monotonically increasing appdomain ID that is unique for
  678.         // the lifetime of the process.
  679.         [MethodImpl(MethodImplOptions.InternalCall)]
  680.         internal extern uint GetAppDomainId();
  681.        
  682.         public string FriendlyName {
  683.             get { return nGetFriendlyName(); }
  684.         }
  685.        
  686.         public string BaseDirectory {
  687.             get { return FusionStore.ApplicationBase; }
  688.         }
  689.        
  690.         public string RelativeSearchPath {
  691.             get { return FusionStore.PrivateBinPath; }
  692.         }
  693.        
  694.         public bool ShadowCopyFiles {
  695.             get {
  696.                 string s = FusionStore.ShadowCopyFiles;
  697.                 if ((s != null) && (String.Compare(s, "true", StringComparison.OrdinalIgnoreCase) == 0))
  698.                     return true;
  699.                 else
  700.                     return false;
  701.             }
  702.         }
  703.        
  704.         public override string ToString()
  705.         {
  706.             StringBuilder sb = new StringBuilder();
  707.            
  708.             string fn = nGetFriendlyName();
  709.             if (fn != null) {
  710.                 sb.Append(Environment.GetResourceString("Loader_Name") + fn);
  711.                 sb.Append(Environment.NewLine);
  712.             }
  713.            
  714.             if (_Policies == null || _Policies.Length == 0)
  715.                 sb.Append(Environment.GetResourceString("Loader_NoContextPolicies") + Environment.NewLine);
  716.             else {
  717.                 sb.Append(Environment.GetResourceString("Loader_ContextPolicies") + Environment.NewLine);
  718.                 for (int i = 0; i < _Policies.Length; i++) {
  719.                     sb.Append(_Policies[i]);
  720.                     sb.Append(Environment.NewLine);
  721.                 }
  722.             }
  723.            
  724.             return sb.ToString();
  725.         }
  726.        
  727.         public Assembly[] GetAssemblies()
  728.         {
  729.                 /* forIntrospection */            return nGetAssemblies(false);
  730.         }
  731.        
  732.        
  733.         public Assembly[] ReflectionOnlyGetAssemblies()
  734.         {
  735.                 /* forIntrospection */            return nGetAssemblies(true);
  736.         }
  737.        
  738.        
  739.        
  740.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  741.         private extern Assembly[] nGetAssemblies(bool forIntrospection);
  742.        
  743.         // this is true when we've nuked the handles etc so really can't do anything
  744.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  745.         internal extern bool IsUnloadingForcedFinalize();
  746.        
  747.         // this is true when we've just started going through the finalizers and are forcing objects to finalize
  748.         // so must be aware that certain infrastructure may have gone away
  749.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  750.         public extern bool IsFinalizingForUnload();
  751.        
  752.         // Appends the following string to the private path. Valid paths
  753.         // are of the form "bin;util/i386" etc.
  754.         [Obsolete("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
  755.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  756.         public void AppendPrivatePath(string path)
  757.         {
  758.             if (path == null || path.Length == 0)
  759.                 return;
  760.            
  761.             string current = FusionStore.Value[(int)AppDomainSetup.LoaderInformation.PrivateBinPathValue];
  762.             StringBuilder appendPath = new StringBuilder();
  763.            
  764.             if (current != null && current.Length > 0) {
  765.                 // See if the last character is a separator
  766.                 appendPath.Append(current);
  767.                 if ((current[current.Length - 1] != Path.PathSeparator) && (path[0] != Path.PathSeparator))
  768.                     appendPath.Append(Path.PathSeparator);
  769.             }
  770.             appendPath.Append(path);
  771.            
  772.             string result = appendPath.ToString();
  773.             InternalSetPrivateBinPath(result);
  774.         }
  775.        
  776.        
  777.         [Obsolete("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
  778.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  779.         public void ClearPrivatePath()
  780.         {
  781.             InternalSetPrivateBinPath(String.Empty);
  782.         }
  783.        
  784.         [Obsolete("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
  785.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  786.         public void ClearShadowCopyPath()
  787.         {
  788.             InternalSetShadowCopyPath(String.Empty);
  789.         }
  790.        
  791.         [Obsolete("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
  792.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  793.         public void SetCachePath(string path)
  794.         {
  795.             InternalSetCachePath(path);
  796.         }
  797.        
  798.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  799.         [ResourceExposure(ResourceScope.AppDomain)]
  800.         [ResourceConsumption(ResourceScope.AppDomain)]
  801.         public void SetData(string name, object data)
  802.         {
  803.             SetDataHelper(name, data, null);
  804.         }
  805.        
  806.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  807.         [ResourceExposure(ResourceScope.AppDomain)]
  808.         [ResourceConsumption(ResourceScope.AppDomain)]
  809.         public void SetData(string name, object data, IPermission permission)
  810.         {
  811.             SetDataHelper(name, data, permission);
  812.         }
  813.        
  814.         [ResourceExposure(ResourceScope.AppDomain)]
  815.         [ResourceConsumption(ResourceScope.Machine, ResourceScope.AppDomain)]
  816.         private void SetDataHelper(string name, object data, IPermission permission)
  817.         {
  818.             if (name == null)
  819.                 throw new ArgumentNullException("name");
  820.            
  821.             //
  822.             // Synopsis:
  823.             // IgnoreSystemPolicy is provided as a legacy flag to allow callers to
  824.             // skip enterprise, machine and user policy levels. When this flag is set,
  825.             // any demands triggered in this AppDomain will be evaluated against the
  826.             // AppDomain CAS policy level that is set on the AppDomain.
  827.             // Security Requirements:
  828.             // The caller needs to be fully trusted in order to be able to set
  829.             // this legacy mode.
  830.             // Remarks:
  831.             // There needs to be an AppDomain policy level set before this compat
  832.             // switch can be set on the AppDomain.
  833.             //
  834.            
  835.             if (name.Equals("IgnoreSystemPolicy")) {
  836.                 lock (this) {
  837.                     if (!_HasSetPolicy)
  838.                         throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
  839.                 }
  840.                 new PermissionSet(PermissionState.Unrestricted).Demand();
  841.             }
  842.            
  843.             int key = AppDomainSetup.Locate(name);
  844.            
  845.             if (key == -1)
  846.                 LocalStore[name] = new object[] {data, permission};
  847.             else {
  848.                 if (permission != null)
  849.                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData"));
  850.                 // Be sure to call these properties, not Value, since
  851.                 // these do more than call Value.
  852.                 switch (key) {
  853.                     case (int)AppDomainSetup.LoaderInformation.DynamicBaseValue:
  854.                         FusionStore.DynamicBase = (string)data;
  855.                         break;
  856.                     case (int)AppDomainSetup.LoaderInformation.DevPathValue:
  857.                         FusionStore.DeveloperPath = (string)data;
  858.                         break;
  859.                     case (int)AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
  860.                         FusionStore.ShadowCopyDirectories = (string)data;
  861.                         break;
  862.                     case (int)AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
  863.                         if (data != null)
  864.                             FusionStore.DisallowPublisherPolicy = true;
  865.                         else
  866.                             FusionStore.DisallowPublisherPolicy = false;
  867.                         break;
  868.                     case (int)AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
  869.                         if (data != null)
  870.                             FusionStore.DisallowCodeDownload = true;
  871.                         else
  872.                             FusionStore.DisallowCodeDownload = false;
  873.                         break;
  874.                     case (int)AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
  875.                         if (data != null)
  876.                             FusionStore.DisallowBindingRedirects = true;
  877.                         else
  878.                             FusionStore.DisallowBindingRedirects = false;
  879.                         break;
  880.                     case (int)AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
  881.                         if (data != null)
  882.                             FusionStore.DisallowApplicationBaseProbing = true;
  883.                         else
  884.                             FusionStore.DisallowApplicationBaseProbing = false;
  885.                         break;
  886.                     case (int)AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
  887.                         FusionStore.SetConfigurationBytes((byte[])data);
  888.                         break;
  889.                     default:
  890.                         FusionStore.Value[key] = (string)data;
  891.                         break;
  892.                 }
  893.             }
  894.         }
  895.        
  896.         [ResourceExposure(ResourceScope.AppDomain)]
  897.         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  898.         public object GetData(string name)
  899.         {
  900.             if (name == null)
  901.                 throw new ArgumentNullException("name");
  902.            
  903.             int key = AppDomainSetup.Locate(name);
  904.             if (key == -1) {
  905.                 if (name.Equals(AppDomainSetup.LoaderOptimizationKey))
  906.                     return FusionStore.LoaderOptimization;
  907.                 else {
  908.                     object[] data = (object[])LocalStore[name];
  909.                     if (data == null)
  910.                         return null;
  911.                     if (data[1] != null) {
  912.                         IPermission permission = (IPermission)data[1];
  913.                         permission.Demand();
  914.                     }
  915.                     return data[0];
  916.                 }
  917.             }
  918.             else {
  919.                 // Be sure to call these properties, not Value, so
  920.                 // that the appropriate permission demand will be done
  921.                 switch (key) {
  922.                     case (int)AppDomainSetup.LoaderInformation.ApplicationBaseValue:
  923.                         return FusionStore.ApplicationBase;
  924.                     case (int)AppDomainSetup.LoaderInformation.ConfigurationFileValue:
  925.                         return FusionStore.ConfigurationFile;
  926.                     case (int)AppDomainSetup.LoaderInformation.DynamicBaseValue:
  927.                         return FusionStore.DynamicBase;
  928.                     case (int)AppDomainSetup.LoaderInformation.DevPathValue:
  929.                         return FusionStore.DeveloperPath;
  930.                     case (int)AppDomainSetup.LoaderInformation.ApplicationNameValue:
  931.                         return FusionStore.ApplicationName;
  932.                     case (int)AppDomainSetup.LoaderInformation.PrivateBinPathValue:
  933.                         return FusionStore.PrivateBinPath;
  934.                     case (int)AppDomainSetup.LoaderInformation.PrivateBinPathProbeValue:
  935.                         return FusionStore.PrivateBinPathProbe;
  936.                     case (int)AppDomainSetup.LoaderInformation.ShadowCopyDirectoriesValue:
  937.                         return FusionStore.ShadowCopyDirectories;
  938.                     case (int)AppDomainSetup.LoaderInformation.ShadowCopyFilesValue:
  939.                         return FusionStore.ShadowCopyFiles;
  940.                     case (int)AppDomainSetup.LoaderInformation.CachePathValue:
  941.                         return FusionStore.CachePath;
  942.                     case (int)AppDomainSetup.LoaderInformation.LicenseFileValue:
  943.                         return FusionStore.LicenseFile;
  944.                     case (int)AppDomainSetup.LoaderInformation.DisallowPublisherPolicyValue:
  945.                         return FusionStore.DisallowPublisherPolicy;
  946.                     case (int)AppDomainSetup.LoaderInformation.DisallowCodeDownloadValue:
  947.                         return FusionStore.DisallowCodeDownload;
  948.                     case (int)AppDomainSetup.LoaderInformation.DisallowBindingRedirectsValue:
  949.                         return FusionStore.DisallowBindingRedirects;
  950.                     case (int)AppDomainSetup.LoaderInformation.DisallowAppBaseProbingValue:
  951.                         return FusionStore.DisallowApplicationBaseProbing;
  952.                     case (int)AppDomainSetup.LoaderInformation.ConfigurationBytesValue:
  953.                         return FusionStore.GetConfigurationBytes();
  954.                     default:
  955.                         #if _DEBUG
  956.                         BCLDebug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
  957.                         #endif
  958.                         return null;
  959.                 }
  960.             }
  961.         }
  962.        
  963.         [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)]
  964.         [DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
  965.         public static extern int GetCurrentThreadId();
  966.        
  967.         [SecurityPermissionAttribute(SecurityAction.Demand, ControlAppDomain = true), ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]
  968.         public static void Unload(AppDomain domain)
  969.         {
  970.             if (domain == null)
  971.                 throw new ArgumentNullException("domain");
  972.            
  973.             try {
  974.                 Int32 domainID = AppDomain.GetIdForUnload(domain);
  975.                 if (domainID == 0)
  976.                     throw new CannotUnloadAppDomainException();
  977.                 AppDomain.nUnload(domainID);
  978.             }
  979.             catch (Exception e) {
  980.                 throw e;
  981.                 // throw it again to reset stack trace
  982.             }
  983.         }
  984.        
  985.         // Explicitly set policy for a domain (providing policy hasn't been set
  986.         // previously). Making this call will guarantee that previously loaded
  987.         // assemblies will be granted permissions based on the default machine
  988.         // policy that was in place prior to this call.
  989.         [SecurityPermission(SecurityAction.LinkDemand, ControlDomainPolicy = true)]
  990.         public void SetAppDomainPolicy(PolicyLevel domainPolicy)
  991.         {
  992.             if (domainPolicy == null)
  993.                 throw new ArgumentNullException("domainPolicy");
  994.            
  995.             // Check that policy has not been set previously.
  996.             lock (this) {
  997.                 if (_HasSetPolicy)
  998.                     throw new PolicyException(Environment.GetResourceString("Policy_PolicyAlreadySet"));
  999.                 _HasSetPolicy = true;
  1000.                
  1001.                 // Make sure that the loader allows us to change security policy
  1002.                 // at this time (this will throw if not.)
  1003.                 nChangeSecurityPolicy();
  1004.             }
  1005.            
  1006.             // Add the new policy level.
  1007.             SecurityManager.PolicyManager.AddLevel(domainPolicy);
  1008.         }
  1009.        
  1010.        
  1011.         // Set the default principal object to be attached to threads if they
  1012.         // attempt to bind to a principal while executing in this appdomain. The
  1013.         // default can only be set once.
  1014.         [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
  1015.         public void SetThreadPrincipal(IPrincipal principal)
  1016.         {
  1017.             if (principal == null)
  1018.                 throw new ArgumentNullException("principal");
  1019.            
  1020.             lock (this) {
  1021.                 // Check that principal has not been set previously.
  1022.                 if (_DefaultPrincipal != null)
  1023.                     throw new PolicyException(Environment.GetResourceString("Policy_PrincipalTwice"));
  1024.                
  1025.                 _DefaultPrincipal = principal;
  1026.             }
  1027.         }
  1028.        
  1029.         // Similar to the above, but sets the class of principal to be created
  1030.         // instead.
  1031.         [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
  1032.         public void SetPrincipalPolicy(PrincipalPolicy policy)
  1033.         {
  1034.             _PrincipalPolicy = policy;
  1035.         }
  1036.        
  1037.         // This method gives AppDomain an infinite life time by preventing a lease from being
  1038.         // created
  1039.         public override object InitializeLifetimeService()
  1040.         {
  1041.             return null;
  1042.         }
  1043.        
  1044.         // This is useful for requesting execution of some code
  1045.         // in another appDomain ... the delegate may be defined
  1046.         // on a marshal-by-value object or a marshal-by-ref or
  1047.         // contextBound object.
  1048.         public void DoCallBack(CrossAppDomainDelegate callBackDelegate)
  1049.         {
  1050.             if (callBackDelegate == null)
  1051.                 throw new ArgumentNullException("callBackDelegate");
  1052.            
  1053.             callBackDelegate();
  1054.         }
  1055.        
  1056.        
  1057.         public string DynamicDirectory {
  1058.             get {
  1059.                 string dyndir = GetDynamicDir();
  1060.                 if (dyndir != null)
  1061.                     new FileIOPermission(FileIOPermissionAccess.PathDiscovery, dyndir).Demand();
  1062.                
  1063.                 return dyndir;
  1064.             }
  1065.         }
  1066.        
  1067.         // Optional
  1068.         public static AppDomain CreateDomain(string friendlyName, Evidence securityInfo)
  1069.         {
  1070.             return CreateDomain(friendlyName, securityInfo, null);
  1071.         }
  1072.        
  1073.             // Optional
  1074.         public static AppDomain CreateDomain(string friendlyName, Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
  1075.         {
  1076.             AppDomainSetup info = new AppDomainSetup();
  1077.             info.ApplicationBase = appBasePath;
  1078.             info.PrivateBinPath = appRelativeSearchPath;
  1079.             if (shadowCopyFiles)
  1080.                 info.ShadowCopyFiles = "true";
  1081.            
  1082.             return CreateDomain(friendlyName, securityInfo, info);
  1083.         }
  1084.        
  1085.         public static AppDomain CreateDomain(string friendlyName)
  1086.         {
  1087.             return CreateDomain(friendlyName, null, null);
  1088.         }
  1089.        
  1090.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1091.         private extern string GetDynamicDir();
  1092.        
  1093.         // Private helpers called from unmanaged code.
  1094.        
  1095.         // Marshal a single object into a serialized blob.
  1096.         private static byte[] MarshalObject(object o)
  1097.         {
  1098.             CodeAccessPermission.AssertAllPossible();
  1099.            
  1100.             return Serialize(o);
  1101.         }
  1102.        
  1103.         // Marshal two objects into serialized blobs.
  1104.         private static byte[] MarshalObjects(object o1, object o2, out byte[] blob2)
  1105.         {
  1106.             CodeAccessPermission.AssertAllPossible();
  1107.            
  1108.             byte[] blob1 = Serialize(o1);
  1109.             blob2 = Serialize(o2);
  1110.             return blob1;
  1111.         }
  1112.        
  1113.         // Unmarshal a single object from a serialized blob.
  1114.         private static object UnmarshalObject(byte[] blob)
  1115.         {
  1116.             CodeAccessPermission.AssertAllPossible();
  1117.            
  1118.             return Deserialize(blob);
  1119.         }
  1120.        
  1121.         // Unmarshal two objects from serialized blobs.
  1122.         private static object UnmarshalObjects(byte[] blob1, byte[] blob2, out object o2)
  1123.         {
  1124.             CodeAccessPermission.AssertAllPossible();
  1125.            
  1126.             object o1 = Deserialize(blob1);
  1127.             o2 = Deserialize(blob2);
  1128.             return o1;
  1129.         }
  1130.        
  1131.         // Helper routines.
  1132.         private static byte[] Serialize(object o)
  1133.         {
  1134.             if (o == null) {
  1135.                 return null;
  1136.             }
  1137.             else if (o is ISecurityEncodable) {
  1138.                 SecurityElement element = ((ISecurityEncodable)o).ToXml();
  1139.                 MemoryStream ms = new MemoryStream(4096);
  1140.                 ms.WriteByte(0);
  1141.                 StreamWriter writer = new StreamWriter(ms, Encoding.UTF8);
  1142.                 element.ToWriter(writer);
  1143.                 writer.Flush();
  1144.                 return ms.ToArray();
  1145.             }
  1146.             else {
  1147.                 MemoryStream ms = new MemoryStream();
  1148.                 ms.WriteByte(1);
  1149.                 CrossAppDomainSerializer.SerializeObject(o, ms);
  1150.                 return ms.ToArray();
  1151.             }
  1152.         }
  1153.        
  1154.         private static object Deserialize(byte[] blob)
  1155.         {
  1156.             if (blob == null)
  1157.                 return null;
  1158.            
  1159.             if (blob[0] == 0) {
  1160.                 Parser parser = new Parser(blob, Tokenizer.ByteTokenEncoding.UTF8Tokens, 1);
  1161.                 SecurityElement root = parser.GetTopElement();
  1162.                 if (root.Tag.Equals("IPermission") || root.Tag.Equals("Permission")) {
  1163.                     IPermission ip = System.Security.Util.XMLUtil.CreatePermission(root, PermissionState.None, false);
  1164.                    
  1165.                     if (ip == null) {
  1166.                         BCLDebug.Assert(false, "Unable to create permission type");
  1167.                         return null;
  1168.                     }
  1169.                    
  1170.                     ip.FromXml(root);
  1171.                    
  1172.                     return ip;
  1173.                 }
  1174.                 else if (root.Tag.Equals("PermissionSet")) {
  1175.                     PermissionSet permissionSet = new PermissionSet();
  1176.                    
  1177.                     permissionSet.FromXml(root, false, false);
  1178.                    
  1179.                     return permissionSet;
  1180.                 }
  1181.                 else if (root.Tag.Equals("PermissionToken")) {
  1182.                     PermissionToken pToken = new PermissionToken();
  1183.                    
  1184.                     pToken.FromXml(root);
  1185.                    
  1186.                     return pToken;
  1187.                 }
  1188.                 else {
  1189.                     BCLDebug.Assert(false, "Unexpected type found");
  1190.                     return null;
  1191.                 }
  1192.                
  1193.             }
  1194.             else {
  1195.                 object obj = null;
  1196.                 using (MemoryStream stream = new MemoryStream(blob, 1, blob.Length - 1)) {
  1197.                     obj = CrossAppDomainSerializer.DeserializeObject(stream);
  1198.                 }
  1199.                
  1200.                 BCLDebug.Assert(!(obj is IPermission), "IPermission should be xml deserialized");
  1201.                 BCLDebug.Assert(!(obj is PermissionSet), "PermissionSet should be xml deserialized");
  1202.                
  1203.                 return obj;
  1204.             }
  1205.         }
  1206.        
  1207.         private AppDomain()
  1208.         {
  1209.             throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
  1210.         }
  1211.        
  1212.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1213.         private extern AssemblyBuilder nCreateDynamicAssembly(AssemblyName name, Evidence identity, ref StackCrawlMark stackMark, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, AssemblyBuilderAccess access);
  1214.        
  1215.         internal AssemblyBuilder InternalDefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, ref StackCrawlMark stackMark)
  1216.         {
  1217.             if (name == null)
  1218.                 throw new ArgumentNullException("name");
  1219.            
  1220.             if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.Save && access != AssemblyBuilderAccess.RunAndSave && access != AssemblyBuilderAccess.ReflectionOnly)
  1221.                 throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), "access");
  1222.            
  1223.             // Set the public key from the key pair if one has been provided.
  1224.             // (Overwite any public key in the Assembly name, since it's no
  1225.             // longer valid to have a disparity).
  1226.             if (name.KeyPair != null)
  1227.                 name.SetPublicKey(name.KeyPair.PublicKey);
  1228.            
  1229.             // If the caller is trusted they can supply identity
  1230.             // evidence for the new assembly. Otherwise we copy the
  1231.             // current grant and deny sets from the caller's assembly,
  1232.             // inject them into the new assembly and mark policy as
  1233.             // resolved. If/when the assembly is persisted and
  1234.             // reloaded, the normal rules for gathering evidence will
  1235.             // be used.
  1236.             if (evidence != null)
  1237.                 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
  1238.            
  1239.             AssemblyBuilder assemblyBuilder = nCreateDynamicAssembly(name, evidence, ref stackMark, requiredPermissions, optionalPermissions, refusedPermissions, access);
  1240.            
  1241.             assemblyBuilder.m_assemblyData = new AssemblyBuilderData(assemblyBuilder, name.Name, access, dir);
  1242.             assemblyBuilder.m_assemblyData.AddPermissionRequests(requiredPermissions, optionalPermissions, refusedPermissions);
  1243.             return assemblyBuilder;
  1244.         }
  1245.        
  1246.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1247.         internal extern int nExecuteAssembly(Assembly assembly, string[] args);
  1248.        
  1249.         internal void CreateRemotingData()
  1250.         {
  1251.             lock (this) {
  1252.                 if (_RemotingData == null)
  1253.                     _RemotingData = new DomainSpecificRemotingData();
  1254.             }
  1255.         }
  1256.        
  1257.         internal DomainSpecificRemotingData RemotingData {
  1258.             get {
  1259.                 if (_RemotingData == null)
  1260.                     CreateRemotingData();
  1261.                
  1262.                 return _RemotingData;
  1263.             }
  1264.         }
  1265.        
  1266.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1267.         private extern string nGetFriendlyName();
  1268.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1269.         private extern bool nIsDefaultAppDomainForSecurity();
  1270.        
  1271.         // support reliability for certain event handlers, if the target
  1272.         // methods also participate in this discipline. If caller passes
  1273.         // an existing MulticastDelegate, then we could use a MDA to indicate
  1274.         // that reliability is not guaranteed. But if it is a single cast
  1275.         // scenario, we can make it work.
  1276.        
  1277.         public event EventHandler ProcessExit {
  1278.             [SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1279.             add {
  1280.                 if (value != null) {
  1281.                     RuntimeHelpers.PrepareDelegate(value);
  1282.                     lock (this)
  1283.                         _processExit += value;
  1284.                 }
  1285.             }
  1286.             [SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1287.             remove {
  1288.                 lock (this)
  1289.                     _processExit -= value;
  1290.             }
  1291.         }
  1292.        
  1293.        
  1294.         public event EventHandler DomainUnload {
  1295.             [SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1296.             add {
  1297.                 if (value != null) {
  1298.                     RuntimeHelpers.PrepareDelegate(value);
  1299.                     lock (this)
  1300.                         _domainUnload += value;
  1301.                 }
  1302.             }
  1303.             [SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1304.             remove {
  1305.                 lock (this)
  1306.                     _domainUnload -= value;
  1307.             }
  1308.         }
  1309.        
  1310.        
  1311.         public event UnhandledExceptionEventHandler UnhandledException {
  1312.             [SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1313.             add {
  1314.                 if (value != null) {
  1315.                     RuntimeHelpers.PrepareDelegate(value);
  1316.                     lock (this)
  1317.                         _unhandledException += value;
  1318.                 }
  1319.             }
  1320.             [SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1321.             remove {
  1322.                 lock (this)
  1323.                     _unhandledException -= value;
  1324.             }
  1325.         }
  1326.        
  1327.        
  1328.         private void OnAssemblyLoadEvent(Assembly LoadedAssembly)
  1329.         {
  1330.             AssemblyLoadEventHandler eventHandler = AssemblyLoad;
  1331.             if (eventHandler != null) {
  1332.                 AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly);
  1333.                 eventHandler(this, ea);
  1334.             }
  1335.         }
  1336.        
  1337.         private Assembly OnResourceResolveEvent(string resourceName)
  1338.         {
  1339.             ResolveEventHandler eventHandler = ResourceResolve;
  1340.             if (eventHandler == null)
  1341.                 return null;
  1342.            
  1343.             Delegate[] ds = eventHandler.GetInvocationList();
  1344.             int len = ds.Length;
  1345.             for (int i = 0; i < len; i++) {
  1346.                 Assembly ret = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(resourceName));
  1347.                 if (ret != null)
  1348.                     return ret;
  1349.             }
  1350.            
  1351.             return null;
  1352.         }
  1353.        
  1354.         private Assembly OnTypeResolveEvent(string typeName)
  1355.         {
  1356.             ResolveEventHandler eventHandler = TypeResolve;
  1357.             if (eventHandler == null)
  1358.                 return null;
  1359.            
  1360.             Delegate[] ds = eventHandler.GetInvocationList();
  1361.             int len = ds.Length;
  1362.             for (int i = 0; i < len; i++) {
  1363.                 Assembly ret = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(typeName));
  1364.                 if (ret != null)
  1365.                     return ret;
  1366.             }
  1367.            
  1368.             return null;
  1369.         }
  1370.        
  1371.         private Assembly OnAssemblyResolveEvent(string assemblyFullName)
  1372.         {
  1373.             ResolveEventHandler eventHandler = AssemblyResolve;
  1374.             if (eventHandler == null)
  1375.                 return null;
  1376.            
  1377.             Delegate[] ds = eventHandler.GetInvocationList();
  1378.             int len = ds.Length;
  1379.             for (int i = 0; i < len; i++) {
  1380.                 Assembly ret = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName));
  1381.                 if (ret != null)
  1382.                     return ret;
  1383.             }
  1384.            
  1385.             return null;
  1386.         }
  1387.        
  1388.         private Assembly OnReflectionOnlyAssemblyResolveEvent(string assemblyFullName)
  1389.         {
  1390.             ResolveEventHandler eventHandler = ReflectionOnlyAssemblyResolve;
  1391.             if (eventHandler != null) {
  1392.                
  1393.                 Delegate[] ds = eventHandler.GetInvocationList();
  1394.                 int len = ds.Length;
  1395.                 for (int i = 0; i < len; i++) {
  1396.                     Assembly ret = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName));
  1397.                     if (ret != null)
  1398.                         return ret;
  1399.                 }
  1400.             }
  1401.            
  1402.             return null;
  1403.         }
  1404.        
  1405.         internal AppDomainSetup FusionStore {
  1406.             get {
  1407.                 #if _DEBUG
  1408.                 BCLDebug.Assert(_FusionStore != null, "Fusion store has not been correctly setup in this domain");
  1409.                 #endif
  1410.                 return _FusionStore;
  1411.             }
  1412.         }
  1413.        
  1414.         [ResourceExposure(ResourceScope.AppDomain)]
  1415.         private Hashtable LocalStore {
  1416.             get {
  1417.                 if (_LocalStore != null)
  1418.                     return _LocalStore;
  1419.                 else {
  1420.                     _LocalStore = Hashtable.Synchronized(new Hashtable());
  1421.                     return _LocalStore;
  1422.                 }
  1423.             }
  1424.         }
  1425.        
  1426.         private void TurnOnBindingRedirects()
  1427.         {
  1428.             _FusionStore.DisallowBindingRedirects = false;
  1429.         }
  1430.        
  1431.         // This will throw a CannotUnloadAppDomainException if the appdomain is
  1432.         // in another process.
  1433.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  1434.         static internal Int32 GetIdForUnload(AppDomain domain)
  1435.         {
  1436.             if (RemotingServices.IsTransparentProxy(domain)) {
  1437.                 return RemotingServices.GetServerDomainIdForProxy(domain);
  1438.             }
  1439.             else
  1440.                 return domain.Id;
  1441.         }
  1442.        
  1443.         // Used to determine if server object context is valid in
  1444.         // x-domain remoting scenarios.
  1445.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1446.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  1447.         static internal extern bool IsDomainIdValid(Int32 id);
  1448.        
  1449.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1450.         static internal extern AppDomain GetDefaultDomain();
  1451.        
  1452.         // Internal routine to retrieve the default principal object. If this is
  1453.         // called before the principal has been explicitly set, it will
  1454.         // automatically allocate a default principal based on the policy set by
  1455.         // SetPrincipalPolicy.
  1456.         internal IPrincipal GetThreadPrincipal()
  1457.         {
  1458.             IPrincipal principal = null;
  1459.            
  1460.             lock (this) {
  1461.                 if (_DefaultPrincipal == null) {
  1462.                     switch (_PrincipalPolicy) {
  1463.                         case PrincipalPolicy.NoPrincipal:
  1464.                             principal = null;
  1465.                             break;
  1466.                         case PrincipalPolicy.UnauthenticatedPrincipal:
  1467.                             principal = new GenericPrincipal(new GenericIdentity("", ""), new string[] {""});
  1468.                             break;
  1469.                         default:
  1470.                             principal = null;
  1471.                             break;
  1472.                     }
  1473.                 }
  1474.                 else
  1475.                     principal = _DefaultPrincipal;
  1476.                
  1477.                 return principal;
  1478.             }
  1479.         }
  1480.        
  1481.         internal void CreateDefaultContext()
  1482.         {
  1483.             lock (this) {
  1484.                 // if it has not been created we ask the Context class to
  1485.                 // create a new default context for this appdomain.
  1486.                 if (_DefaultContext == null)
  1487.                     _DefaultContext = Context.CreateDefaultContext();
  1488.             }
  1489.         }
  1490.        
  1491.         internal Context GetDefaultContext()
  1492.         {
  1493.             if (_DefaultContext == null)
  1494.                 CreateDefaultContext();
  1495.             return _DefaultContext;
  1496.         }
  1497.        
  1498.         [SecurityPermissionAttribute(SecurityAction.Demand, ControlAppDomain = true)]
  1499.         public static AppDomain CreateDomain(string friendlyName, Evidence securityInfo, AppDomainSetup info)
  1500.         {
  1501.             AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
  1502.             if (domainManager != null)
  1503.                 return domainManager.CreateDomain(friendlyName, securityInfo, info);
  1504.            
  1505.             // No AppDomainManager is set up for this domain
  1506.             if (friendlyName == null)
  1507.                 throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_String"));
  1508.            
  1509.             // If evidence is provided, we check to make sure that is allowed.
  1510.             if (securityInfo != null)
  1511.                 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
  1512.            
  1513.             return nCreateDomain(friendlyName, info, securityInfo, securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null, AppDomain.CurrentDomain.GetSecurityDescriptor());
  1514.         }
  1515.        
  1516.        
  1517.             // Optional
  1518.         public static AppDomain CreateDomain(string friendlyName, Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
  1519.         {
  1520.             AppDomainSetup info = new AppDomainSetup();
  1521.             info.ApplicationBase = appBasePath;
  1522.             info.PrivateBinPath = appRelativeSearchPath;
  1523.             info.AppDomainInitializer = adInit;
  1524.             info.AppDomainInitializerArguments = adInitArgs;
  1525.             if (shadowCopyFiles)
  1526.                 info.ShadowCopyFiles = "true";
  1527.            
  1528.             return CreateDomain(friendlyName, securityInfo, info);
  1529.         }
  1530.        
  1531.         private void SetupFusionStore(AppDomainSetup info)
  1532.         {
  1533.             // Create the application base and configuration file from the imagelocation
  1534.             // passed in or use the Win32 Image name.
  1535.             if (info.Value[(int)AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null || info.Value[(int)AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null) {
  1536.                 AppDomain defaultDomain = GetDefaultDomain();
  1537.                 if (this == defaultDomain) {
  1538.                     // The default domain gets its defaults from the main process.
  1539.                     info.SetupDefaultApplicationBase(RuntimeEnvironment.GetModuleFileName());
  1540.                 }
  1541.                 else {
  1542.                     // Other domains get their defaults from the default domain. This way, a host process
  1543.                     // can use AppDomainManager to set up the defaults for every domain created in the process.
  1544.                     if (info.Value[(int)AppDomainSetup.LoaderInformation.ConfigurationFileValue] == null)
  1545.                         info.ConfigurationFile = defaultDomain.FusionStore.Value[(int)AppDomainSetup.LoaderInformation.ConfigurationFileValue];
  1546.                     if (info.Value[(int)AppDomainSetup.LoaderInformation.ApplicationBaseValue] == null)
  1547.                         info.ApplicationBase = defaultDomain.FusionStore.Value[(int)AppDomainSetup.LoaderInformation.ApplicationBaseValue];
  1548.                     if (info.Value[(int)AppDomainSetup.LoaderInformation.ApplicationNameValue] == null)
  1549.                         info.ApplicationName = defaultDomain.FusionStore.Value[(int)AppDomainSetup.LoaderInformation.ApplicationNameValue];
  1550.                 }
  1551.             }
  1552.            
  1553.             // If there is no relative path then check the
  1554.             // environment
  1555.             if (info.Value[(int)AppDomainSetup.LoaderInformation.PrivateBinPathValue] == null)
  1556.                 info.PrivateBinPath = Environment.nativeGetEnvironmentVariable(AppDomainSetup.PrivateBinPathEnvironmentVariable);
  1557.            
  1558.             // Add the developer path if it exists on this
  1559.             // machine.
  1560.             if (info.DeveloperPath == null)
  1561.                 info.DeveloperPath = RuntimeEnvironment.GetDeveloperPath();
  1562.            
  1563.             // Set up the fusion context
  1564.             IntPtr fusionContext = GetFusionContext();
  1565.             info.SetupFusionContext(fusionContext);
  1566.            
  1567.             // Set loader optimization policy
  1568.             if (info.LoaderOptimization != LoaderOptimization.NotSpecified)
  1569.                 UpdateLoaderOptimization((int)info.LoaderOptimization);
  1570.            
  1571.             // This must be the last action taken
  1572.             _FusionStore = info;
  1573.         }
  1574.        
  1575.         // used to package up evidence, so it can be serialized
  1576.         // for the call to InternalRemotelySetupRemoteDomain
  1577.         [Serializable()]
  1578.         private class EvidenceCollection
  1579.         {
  1580.             public Evidence ProvidedSecurityInfo;
  1581.             public Evidence CreatorsSecurityInfo;
  1582.         }
  1583.        
  1584.         private static void RunInitializer(AppDomainSetup setup)
  1585.         {
  1586.             if (setup.AppDomainInitializer != null) {
  1587.                 string[] args = null;
  1588.                 if (setup.AppDomainInitializerArguments != null)
  1589.                     args = (string[])setup.AppDomainInitializerArguments.Clone();
  1590.                 setup.AppDomainInitializer(args);
  1591.             }
  1592.         }
  1593.        
  1594.         // Used to switch into other AppDomain and call SetupRemoteDomain.
  1595.         // We cannot simply call through the proxy, because if there
  1596.         // are any remoting sinks registered, they can add non-mscorlib
  1597.         // objects to the message (causing an assembly load exception when
  1598.         // we try to deserialize it on the other side)
  1599.         private static object RemotelySetupRemoteDomain(AppDomain appDomainProxy, string friendlyName, AppDomainSetup setup, Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor)
  1600.         {
  1601.             BCLDebug.Assert(RemotingServices.IsTransparentProxy(appDomainProxy), "Expected a proxy to the AppDomain.");
  1602.            
  1603.             // get context and appdomain id
  1604.             IntPtr contextId;
  1605.             int domainId;
  1606.             RemotingServices.GetServerContextAndDomainIdForProxy(appDomainProxy, out contextId, out domainId);
  1607.            
  1608.             if (contextId == IntPtr.Zero)
  1609.                 throw new AppDomainUnloadedException();
  1610.            
  1611.             // serialize evidence
  1612.             EvidenceCollection evidenceCollection = null;
  1613.             if ((providedSecurityInfo != null) || (creatorsSecurityInfo != null)) {
  1614.                 evidenceCollection = new EvidenceCollection();
  1615.                 evidenceCollection.ProvidedSecurityInfo = providedSecurityInfo;
  1616.                 evidenceCollection.CreatorsSecurityInfo = creatorsSecurityInfo;
  1617.             }
  1618.            
  1619.             bool bNeedGenericFormatter = false;
  1620.             char[] serProvidedEvidence = null;
  1621.             char[] serCreatorEvidence = null;
  1622.             byte[] serializedEvidence = null;
  1623.             AppDomainInitializerInfo initializerInfo = null;
  1624.            
  1625.             if (providedSecurityInfo != null) {
  1626.                 serProvidedEvidence = PolicyManager.MakeEvidenceArray(providedSecurityInfo, true);
  1627.                 if (serProvidedEvidence == null)
  1628.                     bNeedGenericFormatter = true;
  1629.             }
  1630.             if (creatorsSecurityInfo != null && !bNeedGenericFormatter) {
  1631.                 serCreatorEvidence = PolicyManager.MakeEvidenceArray(creatorsSecurityInfo, true);
  1632.                 if (serCreatorEvidence == null)
  1633.                     bNeedGenericFormatter = true;
  1634.             }
  1635.             if (evidenceCollection != null && bNeedGenericFormatter) {
  1636.                 serProvidedEvidence = serCreatorEvidence = null;
  1637.                 serializedEvidence = CrossAppDomainSerializer.SerializeObject(evidenceCollection).GetBuffer();
  1638.             }
  1639.            
  1640.             if (setup != null && setup.AppDomainInitializer != null)
  1641.                 initializerInfo = new AppDomainInitializerInfo(setup.AppDomainInitializer);
  1642.            
  1643.             return InternalRemotelySetupRemoteDomain(contextId, domainId, friendlyName, setup, parentSecurityDescriptor, serProvidedEvidence, serCreatorEvidence, serializedEvidence, initializerInfo);
  1644.         }
  1645.         // RemotelySetupRemoteDomain
  1646.         [MethodImplAttribute(MethodImplOptions.NoInlining)]
  1647.         private static object InternalRemotelySetupRemoteDomainHelper(object[] args)
  1648.         {
  1649.             string friendlyName = (string)args[0];
  1650.             AppDomainSetup setup = (AppDomainSetup)args[1];
  1651.             IntPtr parentSecurityDescriptor = (IntPtr)args[2];
  1652.             char[] serProvidedEvidence = (char[])args[3];
  1653.             char[] serCreatorEvidence = (char[])args[4];
  1654.             byte[] serializedEvidence = (byte[])args[5];
  1655.             AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[6];
  1656.            
  1657.             AppDomain ad = Thread.CurrentContext.AppDomain;
  1658.             AppDomainSetup newSetup = new AppDomainSetup(setup, false);
  1659.             ad.SetupFusionStore(newSetup);
  1660.            
  1661.             // extract evidence
  1662.             Evidence providedSecurityInfo = null;
  1663.             Evidence creatorsSecurityInfo = null;
  1664.            
  1665.             if (serializedEvidence == null) {
  1666.                 if (serProvidedEvidence != null)
  1667.                     providedSecurityInfo = new Evidence(serProvidedEvidence);
  1668.                 if (serCreatorEvidence != null)
  1669.                     creatorsSecurityInfo = new Evidence(serCreatorEvidence);
  1670.             }
  1671.             else {
  1672.                 EvidenceCollection evidenceCollection = (EvidenceCollection)CrossAppDomainSerializer.DeserializeObject(new MemoryStream(serializedEvidence));
  1673.                 providedSecurityInfo = evidenceCollection.ProvidedSecurityInfo;
  1674.                 creatorsSecurityInfo = evidenceCollection.CreatorsSecurityInfo;
  1675.             }
  1676.            
  1677.             // set up the friendly name
  1678.             ad.nSetupFriendlyName(friendlyName);
  1679.            
  1680.             // set up the AppDomainManager for this domain and initialize security.
  1681.             ad.SetDomainManager(providedSecurityInfo, creatorsSecurityInfo, parentSecurityDescriptor, true);
  1682.            
  1683.             // can load user code now
  1684.             if (initializerInfo != null)
  1685.                 newSetup.AppDomainInitializer = initializerInfo.Unwrap();
  1686.             RunInitializer(newSetup);
  1687.            
  1688.             // Activate the application if needed.
  1689.             ObjectHandle oh = null;
  1690.             return RemotingServices.MarshalInternal(oh, null, null);
  1691.         }
  1692.        
  1693.         [MethodImplAttribute(MethodImplOptions.NoInlining)]
  1694.         private static object InternalRemotelySetupRemoteDomain(IntPtr contextId, int domainId, string friendlyName, AppDomainSetup setup, IntPtr parentSecurityDescriptor, char[] serProvidedEvidence, char[] serCreatorEvidence, byte[] serializedEvidence, AppDomainInitializerInfo initializerInfo)
  1695.         {
  1696.             InternalCrossContextDelegate xctxDel = new InternalCrossContextDelegate(InternalRemotelySetupRemoteDomainHelper);
  1697.            
  1698.             object[] args = new object[] {friendlyName, setup, parentSecurityDescriptor, serProvidedEvidence, serCreatorEvidence, serializedEvidence, initializerInfo};
  1699.             return Thread.CurrentThread.InternalCrossContextCallback(null, contextId, domainId, xctxDel, args);
  1700.         }
  1701.         // InternalSetupRemoteDomain
  1702.         // This routine is called from unmanaged code to
  1703.         // set the default fusion context.
  1704.         private void SetupDomain(bool allowRedirects, string path, string configFile)
  1705.         {
  1706.             // It is possible that we could have multiple threads initializing
  1707.             // the default domain. We will just take the winner of these two.
  1708.             // (eg. one thread doing a com call and another doing attach for IJW)
  1709.             lock (this) {
  1710.                 if (_FusionStore == null) {
  1711.                     AppDomainSetup setup = new AppDomainSetup();
  1712.                     if (path != null)
  1713.                         setup.Value[(int)AppDomainSetup.LoaderInformation.ApplicationBaseValue] = path;
  1714.                     if (configFile != null)
  1715.                         setup.Value[(int)AppDomainSetup.LoaderInformation.ConfigurationFileValue] = configFile;
  1716.                    
  1717.                     // Default fusion context starts with binding redirects turned off.
  1718.                     if (!allowRedirects)
  1719.                         setup.DisallowBindingRedirects = true;
  1720.                    
  1721.                     SetupFusionStore(setup);
  1722.                 }
  1723.             }
  1724.         }
  1725.        
  1726.         private void SetupLoaderOptimization(LoaderOptimization policy)
  1727.         {
  1728.             if (policy != LoaderOptimization.NotSpecified) {
  1729.                 #if _DEBUG
  1730.                 BCLDebug.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified, "It is illegal to change the Loader optimization on a domain");
  1731.                 #endif
  1732.                 FusionStore.LoaderOptimization = policy;
  1733.                 UpdateLoaderOptimization((int)FusionStore.LoaderOptimization);
  1734.             }
  1735.         }
  1736.        
  1737.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1738.         internal extern IntPtr GetFusionContext();
  1739.        
  1740.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1741.         internal extern IntPtr GetSecurityDescriptor();
  1742.        
  1743.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1744.         static internal extern AppDomain nCreateDomain(string friendlyName, AppDomainSetup setup, Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor);
  1745.        
  1746.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1747.         static internal extern ObjRef nCreateInstance(string friendlyName, AppDomainSetup setup, Evidence providedSecurityInfo, Evidence creatorsSecurityInfo, IntPtr parentSecurityDescriptor);
  1748.        
  1749.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1750.         private extern void nSetupDomainSecurity(Evidence appDomainEvidence, IntPtr creatorsSecurityDescriptor, bool publishAppDomain);
  1751.        
  1752.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1753.         private extern void nSetupFriendlyName(string friendlyName);
  1754.        
  1755.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1756.         internal extern void UpdateLoaderOptimization(int optimization);
  1757.        
  1758.         //
  1759.         // This is just designed to prevent compiler warnings.
  1760.         // This field is used from native, but we need to prevent the compiler warnings.
  1761.         //
  1762.        
  1763.         [Obsolete("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
  1764.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1765.         public void SetShadowCopyPath(string path)
  1766.         {
  1767.             InternalSetShadowCopyPath(path);
  1768.         }
  1769.        
  1770.         [Obsolete("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. http://go.microsoft.com/fwlink/?linkid=14202")]
  1771.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1772.         public void SetShadowCopyFiles()
  1773.         {
  1774.             InternalSetShadowCopyFiles();
  1775.         }
  1776.        
  1777.         [Obsolete("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. http://go.microsoft.com/fwlink/?linkid=14202")]
  1778.         [method: SecurityPermissionAttribute(SecurityAction.LinkDemand, ControlAppDomain = true)]
  1779.         public void SetDynamicBase(string path)
  1780.         {
  1781.             InternalSetDynamicBase(path);
  1782.         }
  1783.        
  1784.         public AppDomainSetup SetupInformation {
  1785.             get { return new AppDomainSetup(FusionStore, true); }
  1786.         }
  1787.        
  1788.         internal void InternalSetShadowCopyPath(string path)
  1789.         {
  1790.             IntPtr fusionContext = GetFusionContext();
  1791.             AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyDirectoriesKey, path);
  1792.             FusionStore.ShadowCopyDirectories = path;
  1793.         }
  1794.        
  1795.         internal void InternalSetShadowCopyFiles()
  1796.         {
  1797.             IntPtr fusionContext = GetFusionContext();
  1798.             AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.ShadowCopyFilesKey, "true");
  1799.             FusionStore.ShadowCopyFiles = "true";
  1800.         }
  1801.        
  1802.         internal void InternalSetCachePath(string path)
  1803.         {
  1804.             IntPtr fusionContext = GetFusionContext();
  1805.             FusionStore.CachePath = path;
  1806.             AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.CachePathKey, FusionStore.Value[(int)AppDomainSetup.LoaderInformation.CachePathValue]);
  1807.         }
  1808.        
  1809.         internal void InternalSetPrivateBinPath(string path)
  1810.         {
  1811.             IntPtr fusionContext = GetFusionContext();
  1812.             AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.PrivateBinPathKey, path);
  1813.             FusionStore.PrivateBinPath = path;
  1814.         }
  1815.        
  1816.         internal void InternalSetDynamicBase(string path)
  1817.         {
  1818.             IntPtr fusionContext = GetFusionContext();
  1819.             FusionStore.DynamicBase = path;
  1820.            
  1821.             AppDomainSetup.UpdateContextProperty(fusionContext, AppDomainSetup.DynamicBaseKey, FusionStore.Value[(int)AppDomainSetup.LoaderInformation.DynamicBaseValue]);
  1822.         }
  1823.        
  1824.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1825.         internal extern string IsStringInterned(string str);
  1826.        
  1827.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1828.         internal extern string GetOrInternString(string str);
  1829.        
  1830.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1831.         internal extern void nGetGrantSet(out PermissionSet granted, out PermissionSet denied);
  1832.        
  1833.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1834.         private extern void nChangeSecurityPolicy();
  1835.        
  1836.         [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]
  1837.         static internal extern void nUnload(Int32 domainInternal);
  1838.        
  1839.         public object CreateInstanceAndUnwrap(string assemblyName, string typeName)
  1840.         {
  1841.             ObjectHandle oh = CreateInstance(assemblyName, typeName);
  1842.             if (oh == null)
  1843.                 return null;
  1844.            
  1845.             return oh.Unwrap();
  1846.         }
  1847.         // CreateInstanceAndUnwrap
  1848.        
  1849.         public object CreateInstanceAndUnwrap(string assemblyName, string typeName, object[] activationAttributes)
  1850.         {
  1851.             ObjectHandle oh = CreateInstance(assemblyName, typeName, activationAttributes);
  1852.             if (oh == null)
  1853.                 return null;
  1854.            
  1855.             return oh.Unwrap();
  1856.         }
  1857.         // CreateInstanceAndUnwrap
  1858.        
  1859.         public object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
  1860.         {
  1861.             ObjectHandle oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
  1862.             if (oh == null)
  1863.                 return null;
  1864.            
  1865.             return oh.Unwrap();
  1866.         }
  1867.         // CreateInstanceAndUnwrap
  1868.        
  1869.        
  1870.         // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
  1871.         // release, and the compatibility police won't let us change the name now.
  1872.         public object CreateInstanceFromAndUnwrap(string assemblyName, string typeName)
  1873.         {
  1874.             ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName);
  1875.             if (oh == null)
  1876.                 return null;
  1877.            
  1878.             return oh.Unwrap();
  1879.         }
  1880.         // CreateInstanceAndUnwrap
  1881.        
  1882.         // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
  1883.         // release, and the compatibility police won't let us change the name now.
  1884.         public object CreateInstanceFromAndUnwrap(string assemblyName, string typeName, object[] activationAttributes)
  1885.         {
  1886.             ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, activationAttributes);
  1887.             if (oh == null)
  1888.                 return null;
  1889.            
  1890.             return oh.Unwrap();
  1891.         }
  1892.         // CreateInstanceAndUnwrap
  1893.        
  1894.         // The first parameter should be named assemblyFile, but it was incorrectly named in a previous
  1895.         // release, and the compatibility police won't let us change the name now.
  1896.         public object CreateInstanceFromAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)
  1897.         {
  1898.             ObjectHandle oh = CreateInstanceFrom(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
  1899.             if (oh == null)
  1900.                 return null;
  1901.            
  1902.             return oh.Unwrap();
  1903.         }
  1904.         // CreateInstanceAndUnwrap
  1905.         public Int32 Id {
  1906.             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  1907.             get { return GetId(); }
  1908.         }
  1909.        
  1910.         [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1911.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  1912.         internal extern Int32 GetId();
  1913.        
  1914.         public bool IsDefaultAppDomain()
  1915.         {
  1916.             if (this == GetDefaultDomain())
  1917.                 return true;
  1918.             return false;
  1919.         }
  1920.        
  1921.         private static AppDomainSetup InternalCreateDomainSetup(string imageLocation)
  1922.         {
  1923.             int i = imageLocation.LastIndexOf('\\');
  1924.             #if PLATFORM_UNIX
  1925.             int j = imageLocation.LastIndexOf('/');
  1926.             i = i > j ? i : j;
  1927.             #endif
  1928.            
  1929.             BCLDebug.Assert(i != -1, "invalid image location");
  1930.            
  1931.             AppDomainSetup info = new AppDomainSetup();
  1932.             info.ApplicationBase = imageLocation.Substring(0, i + 1);
  1933.            
  1934.             StringBuilder config = new StringBuilder(imageLocation.Substring(i + 1));
  1935.             config.Append(AppDomainSetup.ConfigurationExtension);
  1936.             info.ConfigurationFile = config.ToString();
  1937.            
  1938.             return info;
  1939.         }
  1940.        
  1941.         // Used by the validator for testing but not executing an assembly
  1942.         private static AppDomain InternalCreateDomain(string imageLocation)
  1943.         {
  1944.             AppDomainSetup info = InternalCreateDomainSetup(imageLocation);
  1945.            
  1946.             return CreateDomain("Validator", null, info);
  1947.         }
  1948.        
  1949.         private void InternalSetDomainContext(string imageLocation)
  1950.         {
  1951.             SetupFusionStore(InternalCreateDomainSetup(imageLocation));
  1952.         }
  1953.        
  1954.         void _AppDomain.GetTypeInfoCount(out uint pcTInfo)
  1955.         {
  1956.             throw new NotImplementedException();
  1957.         }
  1958.        
  1959.         void _AppDomain.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
  1960.         {
  1961.             throw new NotImplementedException();
  1962.         }
  1963.        
  1964.         void _AppDomain.GetIDsOfNames(        [In()]
  1965. ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  1966.         {
  1967.             throw new NotImplementedException();
  1968.         }
  1969.        
  1970.         void _AppDomain.Invoke(uint dispIdMember,         [In()]
  1971. ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  1972.         {
  1973.             throw new NotImplementedException();
  1974.         }
  1975.     }
  1976.    
  1977.     // CallBacks provide a facility to request execution of some code
  1978.     // in another context/appDomain.
  1979.     // CrossAppDomainDelegate type is defined for appdomain call backs.
  1980.     // The delegate used to request a callbak through the DoCallBack method
  1981.     // must be of CrossContextDelegate type.
  1982.     [System.Runtime.InteropServices.ComVisible(true)]
  1983.     public delegate void CrossAppDomainDelegate();
  1984. }

Developer Fusion