public static AssemblyDomain GetDomain(this Assembly assembly) { var assemblyDomain = AssemblyLoadContext.GetLoadContext(assembly); if (assemblyDomain == AssemblyLoadContext.Default) { return((AssemblyDomain)DomainManagement.Default); } return((AssemblyDomain)assemblyDomain); }
/// <summary> /// Handles System.AppDomain.AssemblyResolve event of an System.AppDomain /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The event data.</param> /// <returns>The assembly that resolves the type, assembly, or resource; /// or null if theassembly cannot be resolved. /// </returns> public Assembly ResolveAssembly(object sender, ResolveEventArgs args) { var context = default(AssemblyLoadContext); #if NETCOREAPP context = AssemblyLoadContext.GetLoadContext(args.RequestingAssembly); #endif return(this.AssemblyLoadContextResolving(context, new AssemblyName(args.Name))); }
public void ScanWorks() { var context = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); var assembly = context.LoadFromAssemblyPath(Path.GetFullPath(assemblyPath)); var handlerType = assembly.GetTypes().Single(t => t.Name == "TestHandler"); var interfaceType = handlerType.GetInterface("IHandler"); var equal = interfaceType.Equals(typeof(IHandler)); //true }
public void Does_Not_Load_Assembly_Into_Default_AssemblyLoadContext() { var assemblyLoadResult = this.loader.Load((ContractByteCode)this.compilation.Compilation); Assert.True(assemblyLoadResult.IsSuccess); var loadContext = AssemblyLoadContext.GetLoadContext(assemblyLoadResult.Value.Assembly); Assert.NotEqual(AssemblyLoadContext.Default, loadContext); }
[InlineData("System.IO, Version=0.0.0.0")] // System.* public void RuntimeAssemblies_AreLoadedInDefaultContext(string assemblyName) { var functionContext = new FunctionAssemblyLoadContext(AppContext.BaseDirectory); var assembly = functionContext.LoadFromAssemblyName(new AssemblyName(assemblyName)); Assert.NotNull(assembly); Assert.NotSame(functionContext, AssemblyLoadContext.GetLoadContext(assembly)); Assert.Same(AssemblyLoadContext.Default, AssemblyLoadContext.GetLoadContext(assembly)); }
public static void GetLoadContextTest_SystemPrivateCorelibAssembly() { // System.Private.Corelib is a special case // `int` is defined in S.P.C var asm = typeof(int).Assembly; var context = AssemblyLoadContext.GetLoadContext(asm); Assert.NotNull(context); Assert.Same(AssemblyLoadContext.Default, context); }
protected void ReflectionRunTestAsync(string path, string typeName, string methodName) { var context = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); var assembly = context.LoadFromAssemblyPath(path); var type = assembly.GetType(typeName); var method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic); var obj = method.IsStatic ? null : Activator.CreateInstance(type); RunTestAsync(ToFuncOfTask(method, obj)); }
public static DomainBase GetDomain(Assembly assembly) { var assemblyDomain = AssemblyLoadContext.GetLoadContext(assembly); if (assemblyDomain == AssemblyLoadContext.Default) { return(DomainManagement.Default); } return((DomainBase)assemblyDomain); }
public static string GetOtherString() { var assemblyLocation = "/Users/rlander/git/dotnet-core-assembly-loading/src/addin-loadassemblybypath/lib2/bin/Debug/netstandard2.0/lib2.dll"; var context = AssemblyLoadContext.GetLoadContext(typeof(Class1).Assembly); var assembly = context.LoadFromAssemblyPath(assemblyLocation); var type = assembly.GetType("Class2"); var method = type.GetMethod("GetOtherString"); var returnValue = (string)method.Invoke(null, null); return(returnValue); }
public static void Main() { var typeInfo = typeof(EntryPoint).GetTypeInfo(); var assembly = typeInfo.Assembly; var alc = AssemblyLoadContext.GetLoadContext(assembly); var asmName = assembly.GetName(); alc.SetProfileOptimizationRoot(Directory.GetCurrentDirectory()); alc.StartProfileOptimization($"{asmName.Name},v{asmName.Version}.pgo"); BindingGenerator.Run(); }
/// <summary> /// Gets <see cref="Assembly"/> instances specified by <see cref="RelatedAssemblyAttribute"/>. /// </summary> /// <param name="assembly">The assembly containing <see cref="RelatedAssemblyAttribute"/> instances.</param> /// <param name="throwOnError">Determines if the method throws if a related assembly could not be located.</param> /// <returns>Related <see cref="Assembly"/> instances.</returns> public static IReadOnlyList <Assembly> GetRelatedAssemblies(Assembly assembly, bool throwOnError) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } var loadContext = AssemblyLoadContext.GetLoadContext(assembly) ?? AssemblyLoadContext.Default; return(GetRelatedAssemblies(assembly, throwOnError, File.Exists, new AssemblyLoadContextWrapper(loadContext))); }
public void Unload() { if (_instance != null) { _instance.Unload(); _instance = null; var assemblyLoadContext = AssemblyLoadContext.GetLoadContext(_rootAssembly); _rootAssembly = null; assemblyLoadContext.Unload(); } }
public DefaultExtensionAssemblyLoader() { _loadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultExtensionAssemblyLoader).GetTypeInfo().Assembly); _loadContext.Resolving += (context, name) => { Debug.Assert(ReferenceEquals(context, _loadContext)); return(Load(name.FullName)); }; }
#pragma warning disable S3963 // "static" fields should be initialized inline static ReindexerBinding() { #if NET472 AppDomain.CurrentDomain.DomainUnload += (_, _) => ReindexerBindingUnloading(); #else (AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()) ?? AssemblyLoadContext.Default).Unloading += (_) => ReindexerBindingUnloading(); #endif LoadAndBindNativeLibrary(); _bufferGc.Start(); }
static Helper() { GCHANDLE = GCHandle.Alloc(Console.Out); AssemblyLoadContext currentContext = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); if (currentContext != null) { currentContext.Unloading += Context_Unloading; } }
public bool TryLoadPluginsInCustomContext(AssemblyLoadContext?callingContext) { var currentContext = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); if (currentContext == callingContext) { throw new ArgumentException("The context of the caller is the context of this assembly. This invalidates the test."); } #if NETCOREAPP3_0 /* * Ensure the source calling context does not have our plugin's interfaces loaded. * This guarantees that the Assembly cannot possibly unify with the default load context. * * Note: * The code below this check would fail anyway if the assembly would unify with the default context. * This is more of a safety check to ensure "correctness" as opposed to anything else. */ var sayHelloAssembly = typeof(ISayHello).Assembly; if (callingContext?.Assemblies.Contains(sayHelloAssembly) == true) // .Assemblies API not available in Core 2.X { throw new ArgumentException("The context of the caller has this plugin's interface to interact with its own plugins loaded. Test is void."); } #endif // Load our own plugins: Remember, we are in an isolated, non-default ALC. var plugins = new List <ISayHello?>(); string[] assemblyNames = { "Plugins/WithOurPluginsPluginA.dll", "Plugins/WithOurPluginsPluginB.dll" }; foreach (var assemblyName in assemblyNames) { var currentAssemblyFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new Exception("Unable to get folder path for currently executing assembly."); var pluginPath = Path.Combine(currentAssemblyFolderPath, assemblyName); using var loader = PluginLoader.CreateFromAssemblyFile(pluginPath, new[] { typeof(ISayHello) }); var assembly = loader.LoadDefaultAssembly(); var configType = assembly.GetTypes().First(x => typeof(ISayHello).IsAssignableFrom(x) && !x.IsAbstract); var plugin = (ISayHello?)Activator.CreateInstance(configType); if (plugin == null) { throw new Exception($"Failed to load instance of {nameof(ISayHello)} from plugin."); } plugins.Add(plugin); } // Shouldn't need to check for this but just in case to absolutely make sure. if (plugins.Any(plugin => String.IsNullOrEmpty(plugin?.SayHello()))) { throw new Exception("No value returned from plugin."); } return(true); }
public HostContext(string hostType, string logFile = null) { // Validate args. ArgUtil.NotNullOrEmpty(hostType, nameof(hostType)); _loadContext = AssemblyLoadContext.GetLoadContext(typeof(HostContext).GetTypeInfo().Assembly); _loadContext.Unloading += LoadContext_Unloading; this.SecretMasker.AddValueEncoder(ValueEncoders.JsonStringEscape); this.SecretMasker.AddValueEncoder(ValueEncoders.UriDataEscape); // Create the trace manager. if (string.IsNullOrEmpty(logFile)) { int logPageSize; string logSizeEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGSIZE"); if (!string.IsNullOrEmpty(logSizeEnv) || !int.TryParse(logSizeEnv, out logPageSize)) { logPageSize = _defaultLogPageSize; } int logRetentionDays; string logRetentionDaysEnv = Environment.GetEnvironmentVariable($"{hostType.ToUpperInvariant()}_LOGRETENTION"); if (!string.IsNullOrEmpty(logRetentionDaysEnv) || !int.TryParse(logRetentionDaysEnv, out logRetentionDays)) { logRetentionDays = _defaultLogRetentionDays; } _traceManager = new TraceManager(new HostTraceListener(hostType, logPageSize, logRetentionDays), this.SecretMasker); } else { _traceManager = new TraceManager(new HostTraceListener(logFile), this.SecretMasker); } _trace = GetTrace(nameof(HostContext)); _vssTrace = GetTrace(nameof(VisualStudio) + nameof(VisualStudio.Services)); // VisualStudioService // Enable Http trace bool enableHttpTrace; if (bool.TryParse(Environment.GetEnvironmentVariable("VSTS_AGENT_HTTPTRACE"), out enableHttpTrace) && enableHttpTrace) { _trace.Warning("*****************************************************************************************"); _trace.Warning("** **"); _trace.Warning("** Http trace is enabled, all your http traffic will be dumped into agent diag log. **"); _trace.Warning("** DO NOT share the log in public place! The trace may contains secrets in plain text. **"); _trace.Warning("** **"); _trace.Warning("*****************************************************************************************"); _httpTrace = GetTrace("HttpTrace"); _diagListenerSubscription = DiagnosticListener.AllListeners.Subscribe(this); } }
private bool TryGetConfigurator(out IConfiguratorV1?configurator, out PluginLoader?loader) { var config = _modTuple !.Config; string dllPath = config.GetManagedDllPath(_modTuple.Path); configurator = null; loader = null; if (!File.Exists(dllPath)) { return(false); } loader = PluginLoader.CreateFromAssemblyFile(dllPath, true, _sharedTypes, config => { config.DefaultContext = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()) !; config.IsLazyLoaded = true; config.LoadInMemory = true; }); var assembly = loader.LoadDefaultAssembly(); var types = assembly.GetTypes(); var entryPoint = types.FirstOrDefault(t => typeof(IConfiguratorV1).IsAssignableFrom(t) && !t.IsAbstract); if (entryPoint == null) { return(false); } configurator = (IConfiguratorV1)Activator.CreateInstance(entryPoint) !; var modDirectory = Path.GetFullPath(Path.GetDirectoryName(_modTuple.Path) !); configurator.SetModDirectory(modDirectory); if (configurator is IConfiguratorV2 versionTwo && _modUserConfigTuple != null) { var configDirectory = Path.GetFullPath(Path.GetDirectoryName(_modUserConfigTuple.Path) !); versionTwo.Migrate(modDirectory, configDirectory); versionTwo.SetConfigDirectory(configDirectory); } if (configurator is IConfiguratorV3 versionThree) { versionThree.SetContext(new ConfiguratorContext() { Application = _applicationTuple.Config, ModConfigPath = _modTuple.Path, ApplicationConfigPath = _applicationTuple.Path }); } return(true); }
public static void GetLoadContextTest_ValidUserAssembly() { var asmName = new AssemblyName(TestAssembly); var expectedContext = new ResourceAssemblyLoadContext(); expectedContext.LoadBy = LoadBy.Stream; var asm = expectedContext.LoadFromAssemblyName(asmName); var actualContext = AssemblyLoadContext.GetLoadContext(asm); Assert.Equal(expectedContext, actualContext); }
private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args) { Assembly requestingAssembly = args.RequestingAssembly; // Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that // is the case. if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly)) { return(null); } // Get the path where requesting assembly lives and check if it is in the list // of assemblies for which LoadFrom was invoked. bool fRequestorLoadedViaLoadFrom = false; string requestorPath = Path.GetFullPath(requestingAssembly.Location); if (string.IsNullOrEmpty(requestorPath)) { return(null); } lock (s_syncLoadFromAssemblyList) { fRequestorLoadedViaLoadFrom = s_LoadFromAssemblyList.Contains(requestorPath); } // If the requestor assembly was not loaded using LoadFrom, exit. if (!fRequestorLoadedViaLoadFrom) { return(null); } // Requestor assembly was loaded using loadFrom, so look for its dependencies // in the same folder as it. // Form the name of the assembly using the path of the assembly that requested its load. AssemblyName requestedAssemblyName = new AssemblyName(args.Name); string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath), requestedAssemblyName.Name + ".dll"); // Load the dependency via LoadFrom so that it goes through the same path of being in the LoadFrom list. Assembly resolvedAssembly = null; try { resolvedAssembly = Assembly.LoadFrom(requestedAssemblyPath); } catch (FileNotFoundException) { // Catch FileNotFoundException when attempting to resolve assemblies via this handler to account for missing assemblies. resolvedAssembly = null; } return(resolvedAssembly); }
internal static unsafe void FixupModuleCell(ModuleFixupCell *pCell) { string moduleName = GetModuleName(pCell); uint dllImportSearchPath = 0; bool hasDllImportSearchPath = (pCell->DllImportSearchPathAndCookie & InteropDataConstants.HasDllImportSearchPath) != 0; if (hasDllImportSearchPath) { dllImportSearchPath = pCell->DllImportSearchPathAndCookie & ~InteropDataConstants.HasDllImportSearchPath; } Assembly callingAssembly = RuntimeAugments.Callbacks.GetAssemblyForHandle(new RuntimeTypeHandle(pCell->CallingAssemblyType)); // First check if there's a NativeLibrary callback and call it to attempt the resolution IntPtr hModule = NativeLibrary.LoadLibraryCallbackStub(moduleName, callingAssembly, hasDllImportSearchPath, dllImportSearchPath); if (hModule == IntPtr.Zero) { // NativeLibrary callback didn't resolve the library. Use built-in rules. NativeLibrary.LoadLibErrorTracker loadLibErrorTracker = default; hModule = NativeLibrary.LoadBySearch( callingAssembly, searchAssemblyDirectory: false, dllImportSearchPathFlags: 0, ref loadLibErrorTracker, moduleName); if (hModule == IntPtr.Zero) { // Built-in rules didn't resolve the library. Use AssemblyLoadContext as a last chance attempt. AssemblyLoadContext loadContext = AssemblyLoadContext.GetLoadContext(callingAssembly) !; hModule = loadContext.GetResolvedUnmanagedDll(callingAssembly, moduleName); } if (hModule == IntPtr.Zero) { // If the module is still unresolved, this is an error. loadLibErrorTracker.Throw(moduleName); } } Debug.Assert(hModule != IntPtr.Zero); var oldValue = Interlocked.CompareExchange(ref pCell->Handle, hModule, IntPtr.Zero); if (oldValue != IntPtr.Zero) { // Some other thread won the race to fix it up. FreeLibrary(hModule); } }
public static void LoadAssemblyByStream_ValidUserAssembly() { var asmName = new AssemblyName(TestAssembly); var loadContext = new ResourceAssemblyLoadContext(); loadContext.LoadBy = LoadBy.Stream; var asm = loadContext.LoadFromAssemblyName(asmName); Assert.NotNull(asm); Assert.Same(loadContext, AssemblyLoadContext.GetLoadContext(asm)); Assert.Contains(asm.DefinedTypes, t => t.Name == "TestClass"); }
/// <summary> /// Initializes a new instance of the <see cref="CompilationGenerator"/> class /// with default dependency resolution and loading. /// </summary> public CompilationGenerator() { this.assemblyResolver = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[] { new ReferenceAssemblyPathResolver(), new PackageCompilationAssemblyResolver(), }); this.dependencyContext = DependencyContext.Default; var loadContext = AssemblyLoadContext.GetLoadContext(this.GetType().GetTypeInfo().Assembly); loadContext.Resolving += this.ResolveAssembly; }
internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, Assembly?callingAssembly, AssemblyLoadContext?assemblyLoadContext, IEnumerable <CustomAttributeBuilder>?assemblyAttributes) { ArgumentNullException.ThrowIfNull(name); if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access)); } if (callingAssembly == null) { // Called either from interop or async delegate invocation. Rejecting because we don't // know how to set the correct context of the new dynamic assembly. throw new InvalidOperationException(); } if (assemblyLoadContext == null) { assemblyLoadContext = AssemblyLoadContext.GetLoadContext(callingAssembly); } // Clone the name in case the caller modifies it underneath us. name = (AssemblyName)name.Clone(); RuntimeAssembly?retAssembly = null; CreateDynamicAssembly(ObjectHandleOnStack.Create(ref name), (int)access, ObjectHandleOnStack.Create(ref assemblyLoadContext), ObjectHandleOnStack.Create(ref retAssembly)); _internalAssembly = retAssembly !; _access = access; // Make sure that ManifestModule is properly initialized // We need to do this before setting any CustomAttribute // Note that this ModuleBuilder cannot be used for RefEmit yet // because it hasn't been initialized. // However, it can be used to set the custom attribute on the Assembly _manifestModuleBuilder = new ModuleBuilder(this, (RuntimeModule)InternalAssembly.ManifestModule); if (assemblyAttributes != null) { foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes) { SetCustomAttribute(assemblyAttribute); } } }
private static ReadOnlySpan <byte> LoadAssembly(out GCHandle gchToAssembly) { var currentALC = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); var alc = new TestALC(currentALC); var a = alc.LoadFromAssemblyPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Unloaded.dll")); gchToAssembly = GCHandle.Alloc(a, GCHandleType.WeakTrackResurrection); var spanAccessor = (IReturnSpan)Activator.CreateInstance(a.GetType("SpanAccessor")); alc.Unload(); return(spanAccessor.GetSpan()); }
private AssemblyResolver(Assembly assembly) { this.Assembly = assembly; this.assemblyResolver = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[] { new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(assembly.Location)), new ReferenceAssemblyPathResolver(), new PackageCompilationAssemblyResolver() }); this.loadContext = AssemblyLoadContext.GetLoadContext(this.Assembly); this.loadContext.Resolving += OnResolving; }
bool TryLoadScannableAssembly(string assemblyPath, AssemblyScannerResults results, out Assembly assembly) { assembly = null; if (IsExcluded(Path.GetFileNameWithoutExtension(assemblyPath))) { var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning."); results.SkippedFiles.Add(skippedFile); return(false); } assemblyValidator.ValidateAssemblyFile(assemblyPath, out var shouldLoad, out var reason); if (!shouldLoad) { var skippedFile = new SkippedFile(assemblyPath, reason); results.SkippedFiles.Add(skippedFile); return(false); } try { #if NETCOREAPP var context = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); assembly = context.LoadFromAssemblyPath(assemblyPath); #else assembly = Assembly.LoadFrom(assemblyPath); #endif return(true); } catch (Exception ex) when(ex is BadImageFormatException || ex is FileLoadException) { results.ErrorsThrownDuringScanning = true; if (ThrowExceptions) { var errorMessage = $"Could not load '{assemblyPath}'. Consider excluding that assembly from the scanning."; throw new Exception(errorMessage, ex); } var skippedFile = new SkippedFile(assemblyPath, ex.Message); results.SkippedFiles.Add(skippedFile); return(false); } }
void TestDefineDynamicAssembly(bool collectibleContext, AssemblyBuilderAccess assemblyBuilderAccess) { AssemblyLoadContext assemblyLoadContext = collectibleContext ? new AssemblyLoadContext("DynamicAssembly Collectable context", true) : AssemblyLoadContext.Default; AssemblyBuilder assemblyBuilder; using (assemblyLoadContext.EnterContextualReflection()) { assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName($"DynamicAssembly_{Guid.NewGuid():N}"), assemblyBuilderAccess); } AssemblyLoadContext context = AssemblyLoadContext.GetLoadContext(assemblyBuilder); Assert.Equal(assemblyLoadContext, context); Assert.True(assemblyLoadContext.Assemblies.Any(a => AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyBuilder.GetName()))); }
public AssemblyResolver(string path) { this.Assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path); this.dependencyContext = DependencyContext.Load(this.Assembly); this.assemblyResolver = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[] { new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(path)), new ReferenceAssemblyPathResolver(), new PackageCompilationAssemblyResolver() }); this.loadContext = AssemblyLoadContext.GetLoadContext(this.Assembly); this.loadContext.Resolving += OnResolving; }
public static void LoadFromAssemblyName_ValidTrustedPlatformAssembly() { var asmName = AssemblyLoadContext.GetAssemblyName("System.Runtime.dll"); var loadContext = new CustomTPALoadContext(); // We should be able to override (and thus, load) assemblies that were // loaded in TPA load context. var asm = loadContext.LoadFromAssemblyName(asmName); Assert.NotNull(asm); var loadedContext = AssemblyLoadContext.GetLoadContext(asm); Assert.NotNull(loadedContext); Assert.Same(loadContext, loadedContext); }