AppDomain.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. #pragma warning disable CS0067 // events are declared but not used
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Runtime.ExceptionServices;
  8. using System.Runtime.Loader;
  9. using System.Runtime.Remoting;
  10. using System.Security;
  11. using System.Security.Permissions;
  12. using System.Security.Principal;
  13. using System.Threading;
  14. namespace System
  15. {
  16. public sealed partial class AppDomain : MarshalByRefObject
  17. {
  18. private static readonly AppDomain s_domain = new AppDomain();
  19. private readonly object _forLock = new object();
  20. private IPrincipal _defaultPrincipal;
  21. private PrincipalPolicy _principalPolicy = PrincipalPolicy.NoPrincipal;
  22. private Func<IPrincipal> s_getWindowsPrincipal;
  23. private Func<IPrincipal> s_getUnauthenticatedPrincipal;
  24. private AppDomain() { }
  25. public static AppDomain CurrentDomain => s_domain;
  26. public string BaseDirectory => AppContext.BaseDirectory;
  27. public string RelativeSearchPath => null;
  28. public AppDomainSetup SetupInformation => new AppDomainSetup();
  29. public PermissionSet PermissionSet => new PermissionSet(PermissionState.Unrestricted);
  30. public event UnhandledExceptionEventHandler UnhandledException
  31. {
  32. add { AppContext.UnhandledException += value; }
  33. remove { AppContext.UnhandledException -= value; }
  34. }
  35. public string DynamicDirectory => null;
  36. [ObsoleteAttribute("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. https://go.microsoft.com/fwlink/?linkid=14202")]
  37. public void SetDynamicBase(string path) { }
  38. public string FriendlyName
  39. {
  40. get
  41. {
  42. Assembly assembly = Assembly.GetEntryAssembly();
  43. return assembly != null ? assembly.GetName().Name : "DefaultDomain";
  44. }
  45. }
  46. public int Id => 1;
  47. public bool IsFullyTrusted => true;
  48. public bool IsHomogenous => true;
  49. public event EventHandler DomainUnload;
  50. public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
  51. {
  52. add { AppContext.FirstChanceException += value; }
  53. remove { AppContext.FirstChanceException -= value; }
  54. }
  55. public event EventHandler ProcessExit
  56. {
  57. add { AppContext.ProcessExit += value; }
  58. remove { AppContext.ProcessExit -= value; }
  59. }
  60. public string ApplyPolicy(string assemblyName)
  61. {
  62. if (assemblyName == null)
  63. {
  64. throw new ArgumentNullException(nameof(assemblyName));
  65. }
  66. if (assemblyName.Length == 0 || assemblyName[0] == '\0')
  67. {
  68. throw new ArgumentException(SR.ZeroLengthString);
  69. }
  70. return assemblyName;
  71. }
  72. public static AppDomain CreateDomain(string friendlyName)
  73. {
  74. if (friendlyName == null) throw new ArgumentNullException(nameof(friendlyName));
  75. throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomains);
  76. }
  77. public int ExecuteAssembly(string assemblyFile) => ExecuteAssembly(assemblyFile, null);
  78. public int ExecuteAssembly(string assemblyFile, string[] args)
  79. {
  80. if (assemblyFile == null)
  81. {
  82. throw new ArgumentNullException(nameof(assemblyFile));
  83. }
  84. string fullPath = Path.GetFullPath(assemblyFile);
  85. Assembly assembly = Assembly.LoadFile(fullPath);
  86. return ExecuteAssembly(assembly, args);
  87. }
  88. public int ExecuteAssembly(string assemblyFile, string[] args, byte[] hashValue, Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm)
  89. {
  90. throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // This api is only meaningful for very specific partial trust/CAS scenarios
  91. }
  92. private int ExecuteAssembly(Assembly assembly, string[] args)
  93. {
  94. MethodInfo entry = assembly.EntryPoint;
  95. if (entry == null)
  96. {
  97. throw new MissingMethodException(SR.EntryPointNotFound + assembly.FullName);
  98. }
  99. object result = entry.Invoke(
  100. obj: null,
  101. invokeAttr: BindingFlags.DoNotWrapExceptions,
  102. binder: null,
  103. parameters: entry.GetParameters().Length > 0 ? new object[] { args } : null,
  104. culture: null);
  105. return result != null ? (int)result : 0;
  106. }
  107. public int ExecuteAssemblyByName(AssemblyName assemblyName, params string[] args) =>
  108. ExecuteAssembly(Assembly.Load(assemblyName), args);
  109. public int ExecuteAssemblyByName(string assemblyName) =>
  110. ExecuteAssemblyByName(assemblyName, null);
  111. public int ExecuteAssemblyByName(string assemblyName, params string[] args) =>
  112. ExecuteAssembly(Assembly.Load(assemblyName), args);
  113. public object GetData(string name) => AppContext.GetData(name);
  114. public void SetData(string name, object data) => AppContext.SetData(name, data);
  115. public bool? IsCompatibilitySwitchSet(string value)
  116. {
  117. bool result;
  118. return AppContext.TryGetSwitch(value, out result) ? result : default(bool?);
  119. }
  120. public bool IsDefaultAppDomain() => true;
  121. public bool IsFinalizingForUnload() => false;
  122. public override string ToString() =>
  123. SR.AppDomain_Name + FriendlyName + Environment.NewLine + SR.AppDomain_NoContextPolicies;
  124. public static void Unload(AppDomain domain)
  125. {
  126. if (domain == null)
  127. {
  128. throw new ArgumentNullException(nameof(domain));
  129. }
  130. throw new CannotUnloadAppDomainException(SR.NotSupported_Platform);
  131. }
  132. public Assembly Load(byte[] rawAssembly) => Assembly.Load(rawAssembly);
  133. public Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) => Assembly.Load(rawAssembly, rawSymbolStore);
  134. public Assembly Load(AssemblyName assemblyRef) => Assembly.Load(assemblyRef);
  135. public Assembly Load(string assemblyString) => Assembly.Load(assemblyString);
  136. public Assembly[] ReflectionOnlyGetAssemblies() => Array.Empty<Assembly>();
  137. public static bool MonitoringIsEnabled
  138. {
  139. get { return false; }
  140. set
  141. {
  142. if (!value)
  143. {
  144. throw new ArgumentException(SR.Arg_MustBeTrue);
  145. }
  146. throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomain_ResMon);
  147. }
  148. }
  149. public long MonitoringSurvivedMemorySize { get { throw CreateResMonNotAvailException(); } }
  150. public static long MonitoringSurvivedProcessMemorySize { get { throw CreateResMonNotAvailException(); } }
  151. public long MonitoringTotalAllocatedMemorySize { get { throw CreateResMonNotAvailException(); } }
  152. public TimeSpan MonitoringTotalProcessorTime { get { throw CreateResMonNotAvailException(); } }
  153. private static Exception CreateResMonNotAvailException() => new InvalidOperationException(SR.PlatformNotSupported_AppDomain_ResMon);
  154. [ObsoleteAttribute("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. https://go.microsoft.com/fwlink/?linkid=14202", false)]
  155. public static int GetCurrentThreadId() => Environment.CurrentManagedThreadId;
  156. public bool ShadowCopyFiles => false;
  157. [ObsoleteAttribute("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")]
  158. public void AppendPrivatePath(string path) { }
  159. [ObsoleteAttribute("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")]
  160. public void ClearPrivatePath() { }
  161. [ObsoleteAttribute("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. https://go.microsoft.com/fwlink/?linkid=14202")]
  162. public void ClearShadowCopyPath() { }
  163. [ObsoleteAttribute("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. https://go.microsoft.com/fwlink/?linkid=14202")]
  164. public void SetCachePath(string path) { }
  165. [ObsoleteAttribute("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. https://go.microsoft.com/fwlink/?linkid=14202")]
  166. public void SetShadowCopyFiles() { }
  167. [ObsoleteAttribute("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. https://go.microsoft.com/fwlink/?linkid=14202")]
  168. public void SetShadowCopyPath(string path) { }
  169. public Assembly[] GetAssemblies() => AssemblyLoadContext.GetLoadedAssemblies();
  170. public event AssemblyLoadEventHandler AssemblyLoad
  171. {
  172. add { AssemblyLoadContext.AssemblyLoad += value; }
  173. remove { AssemblyLoadContext.AssemblyLoad -= value; }
  174. }
  175. public event ResolveEventHandler AssemblyResolve
  176. {
  177. add { AssemblyLoadContext.AssemblyResolve += value; }
  178. remove { AssemblyLoadContext.AssemblyResolve -= value; }
  179. }
  180. public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
  181. public event ResolveEventHandler TypeResolve
  182. {
  183. add { AssemblyLoadContext.TypeResolve += value; }
  184. remove { AssemblyLoadContext.TypeResolve -= value; }
  185. }
  186. public event ResolveEventHandler ResourceResolve
  187. {
  188. add { AssemblyLoadContext.ResourceResolve += value; }
  189. remove { AssemblyLoadContext.ResourceResolve -= value; }
  190. }
  191. public void SetPrincipalPolicy(PrincipalPolicy policy)
  192. {
  193. _principalPolicy = policy;
  194. }
  195. public void SetThreadPrincipal(IPrincipal principal)
  196. {
  197. if (principal == null)
  198. {
  199. throw new ArgumentNullException(nameof(principal));
  200. }
  201. lock (_forLock)
  202. {
  203. // Check that principal has not been set previously.
  204. if (_defaultPrincipal != null)
  205. {
  206. throw new SystemException(SR.AppDomain_Policy_PrincipalTwice);
  207. }
  208. _defaultPrincipal = principal;
  209. }
  210. }
  211. public ObjectHandle CreateInstance(string assemblyName, string typeName)
  212. {
  213. if (assemblyName == null)
  214. {
  215. throw new ArgumentNullException(nameof(assemblyName));
  216. }
  217. return Activator.CreateInstance(assemblyName, typeName);
  218. }
  219. public ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes)
  220. {
  221. if (assemblyName == null)
  222. {
  223. throw new ArgumentNullException(nameof(assemblyName));
  224. }
  225. return Activator.CreateInstance(assemblyName,
  226. typeName,
  227. ignoreCase,
  228. bindingAttr,
  229. binder,
  230. args,
  231. culture,
  232. activationAttributes);
  233. }
  234. public ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes)
  235. {
  236. if (assemblyName == null)
  237. {
  238. throw new ArgumentNullException(nameof(assemblyName));
  239. }
  240. return Activator.CreateInstance(assemblyName, typeName, activationAttributes);
  241. }
  242. public object CreateInstanceAndUnwrap(string assemblyName, string typeName)
  243. {
  244. ObjectHandle oh = CreateInstance(assemblyName, typeName);
  245. return oh?.Unwrap();
  246. }
  247. public object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes)
  248. {
  249. ObjectHandle oh = CreateInstance(assemblyName,
  250. typeName,
  251. ignoreCase,
  252. bindingAttr,
  253. binder,
  254. args,
  255. culture,
  256. activationAttributes);
  257. return oh?.Unwrap();
  258. }
  259. public object CreateInstanceAndUnwrap(string assemblyName, string typeName, object[] activationAttributes)
  260. {
  261. ObjectHandle oh = CreateInstance(assemblyName, typeName, activationAttributes);
  262. return oh?.Unwrap();
  263. }
  264. public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName)
  265. {
  266. return Activator.CreateInstanceFrom(assemblyFile, typeName);
  267. }
  268. public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes)
  269. {
  270. return Activator.CreateInstanceFrom(assemblyFile,
  271. typeName,
  272. ignoreCase,
  273. bindingAttr,
  274. binder,
  275. args,
  276. culture,
  277. activationAttributes);
  278. }
  279. public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes)
  280. {
  281. return Activator.CreateInstanceFrom(assemblyFile, typeName, activationAttributes);
  282. }
  283. public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName)
  284. {
  285. ObjectHandle oh = CreateInstanceFrom(assemblyFile, typeName);
  286. return oh?.Unwrap();
  287. }
  288. public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes)
  289. {
  290. ObjectHandle oh = CreateInstanceFrom(assemblyFile,
  291. typeName,
  292. ignoreCase,
  293. bindingAttr,
  294. binder,
  295. args,
  296. culture,
  297. activationAttributes);
  298. return oh?.Unwrap();
  299. }
  300. public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object[] activationAttributes)
  301. {
  302. ObjectHandle oh = CreateInstanceFrom(assemblyFile, typeName, activationAttributes);
  303. return oh?.Unwrap();
  304. }
  305. public IPrincipal GetThreadPrincipal()
  306. {
  307. IPrincipal principal = _defaultPrincipal;
  308. if (principal == null)
  309. {
  310. switch (_principalPolicy)
  311. {
  312. case PrincipalPolicy.UnauthenticatedPrincipal:
  313. if (s_getUnauthenticatedPrincipal == null)
  314. {
  315. Type type = Type.GetType("System.Security.Principal.GenericPrincipal, System.Security.Claims", throwOnError: true);
  316. // Don't throw PNSE if null like for WindowsPrincipal as UnauthenticatedPrincipal should
  317. // be available on all platforms.
  318. Volatile.Write(ref s_getUnauthenticatedPrincipal,
  319. (Func<IPrincipal>)Delegate.CreateDelegate(typeof(Func<IPrincipal>), type, "GetDefaultInstance"));
  320. }
  321. principal = s_getUnauthenticatedPrincipal();
  322. break;
  323. case PrincipalPolicy.WindowsPrincipal:
  324. if (s_getWindowsPrincipal == null)
  325. {
  326. Type type = Type.GetType("System.Security.Principal.WindowsPrincipal, System.Security.Principal.Windows", throwOnError: true);
  327. Volatile.Write(ref s_getWindowsPrincipal,
  328. (Func<IPrincipal>)Delegate.CreateDelegate(typeof(Func<IPrincipal>), type, "GetDefaultInstance", ignoreCase: false, throwOnBindFailure: false)
  329. ?? throw new PlatformNotSupportedException(SR.PlatformNotSupported_Principal));
  330. }
  331. principal = s_getWindowsPrincipal();
  332. break;
  333. }
  334. }
  335. return principal;
  336. }
  337. }
  338. }