private static Assembly ResolveAssemblyAgain(AssemblyLoadContext sender, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; s_NumNonNullResolutions++; return sender.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyFilename)); }
/// <summary> /// /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public Task StartAsync(CancellationToken cancellationToken = default) { AssemblyLoadContext = new AssemblyLoadContext(Name, true); AssemblyLoadContext.Resolving += (_, name) => AssemblyLoadContext?.LoadFromAssemblyPath(Path.Combine(Directory, $"{name.Name}.dll")); return(Task.CompletedTask); }
private static Type LoadTestClassInALC(AssemblyLoadContext alc) { Assembly asm = alc.LoadFromAssemblyPath(Assembly.GetExecutingAssembly().Location); return(asm.GetType(typeof(BinderTracingTest).FullName)); }
/// <summary> /// The handler for the Resolving event /// </summary> private Assembly Resolve(AssemblyLoadContext loadContext, AssemblyName assemblyName) { // Probe the assembly cache Assembly asmLoaded; if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) { return(asmLoaded); } // Prepare to load the assembly lock (s_syncObj) { // Probe the cache again in case it's already loaded if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) { return(asmLoaded); } // Search the specified assembly in probing paths, and load it through 'LoadFromAssemblyPath' if the file exists and matches the requested AssemblyName. // If the CultureName of the requested assembly is not NullOrEmpty, then it's a resources.dll and we need to search corresponding culture sub-folder. bool isAssemblyFileFound = false, isAssemblyFileMatching = false; string asmCultureName = assemblyName.CultureName ?? string.Empty; string asmFilePath = null; for (int i = 0; i < _probingPaths.Length; i++) { string probingPath = _probingPaths[i]; string asmCulturePath = Path.Combine(probingPath, asmCultureName); for (int k = 0; k < _extensions.Length; k++) { string asmFileName = assemblyName.Name + _extensions[k]; asmFilePath = Path.Combine(asmCulturePath, asmFileName); if (File.Exists(asmFilePath)) { isAssemblyFileFound = true; AssemblyName asmNameFound = AssemblyLoadContext.GetAssemblyName(asmFilePath); if (IsAssemblyMatching(assemblyName, asmNameFound)) { isAssemblyFileMatching = true; break; } } } if (isAssemblyFileFound && isAssemblyFileMatching) { break; } } // We failed to find the assembly file; or we found the file, but the assembly file doesn't match the request. // In this case, return null so that other Resolving event handlers can kick in to resolve the request. if (!isAssemblyFileFound || !isAssemblyFileMatching) { #if !UNIX //Try loading from GAC if (!TryFindInGAC(assemblyName, out asmFilePath)) { return(null); } #else return(null); #endif } asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) ? loadContext.LoadFromNativeImagePath(asmFilePath, null) : loadContext.LoadFromAssemblyPath(asmFilePath); if (asmLoaded != null) { // Add the loaded assembly to the cache s_assemblyCache.TryAdd(assemblyName.Name, asmLoaded); } } return(asmLoaded); }
private static Assembly CustomResolving(AssemblyLoadContext arg1, AssemblyName arg2) { Console.WriteLine($"Try resolve: {arg2.FullName}"); //Maybe Load from different path e.g. Addon Path. return(arg1.LoadFromAssemblyPath(@"C:\Addons\" + arg2.Name + ".dll")); }
public virtual Assembly LoadFromAssemblyPath(string assemblyPath) => _loadContext.LoadFromAssemblyPath(assemblyPath);
private static Assembly DefaultOnResolving(AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName, string assemblyPath) { string dllName = assemblyName.Name.Split(new[] { ',' })[0] + ".dll"; return(assemblyLoadContext.LoadFromAssemblyPath(Path.Combine(Path.GetDirectoryName(assemblyPath), dllName))); }
/// <summary> /// Executes a LoadFrom in the app domain LoaderClass has been loaded into. Attempts to load a given assembly, looking in the /// given paths & the current directory. /// </summary> /// <param name="path">The assembly to load</param> /// <param name="paths">Paths to search for the given assembly</param> public void LoadFrom(string path, string[] paths #if !PROJECTK_BUILD , ReliabilityFramework rf #endif ) { #if !PROJECTK_BUILD myRf = rf; AssemblyName an = new AssemblyName(); an.CodeBase = assembly = path; //register AssemblyLoad and DomainUnload events AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(this.UnloadOnAssemblyLoad); AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadOnDomainUnload); #else AssemblyLoadContext alc = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); #endif try { #if !PROJECTK_BUILD assem = Assembly.Load(an); #else assembly = path; assem = alc.LoadFromAssemblyPath(assembly); #endif } catch { try { FileInfo fi = new FileInfo(path); assembly = fi.FullName; #if !PROJECTK_BUILD an = new AssemblyName(); an.CodeBase = assembly; assem = Assembly.Load(an); #else assem = alc.LoadFromAssemblyPath(assembly); #endif } catch { if (paths != null) { foreach (string basePath in paths) { try { assembly = ReliabilityConfig.ConvertPotentiallyRelativeFilenameToFullPath(basePath, path); #if !PROJECTK_BUILD an = new AssemblyName(); an.CodeBase = assembly; assem = Assembly.Load(an); #else assem = alc.LoadFromAssemblyPath(assembly); #endif break; } catch { } } } } } }
public bool Execute() { try { LogMessage("Executing IL2CPU on assembly"); LogTime("Engine execute started"); // Gen2 // Find the kernel's entry point. We are looking for a public class Kernel, with public static void Boot() MethodBase xKernelCtor = null; if (UseGen3Kernel) { LoadBootEntries(); } else { xKernelCtor = LoadAssemblies(); if (xKernelCtor == null) { return(false); } } var debugCom = mSettings.DebugCom; if (!mSettings.EnableDebug) { // Default of 1 is in Cosmos.Targets. Need to change to use proj props. debugCom = 0; } using (var xAsm = GetAppAssembler(debugCom)) { var xOutputFilenameWithoutExtension = Path.ChangeExtension(mSettings.OutputFilename, null); using (var xDebugInfo = new DebugInfo(xOutputFilenameWithoutExtension + ".cdb", true, false)) { xAsm.DebugInfo = xDebugInfo; xAsm.DebugEnabled = mSettings.EnableDebug; xAsm.StackCorruptionDetection = mSettings.EnableStackCorruptionDetection; xAsm.StackCorruptionDetectionLevel = mSettings.StackCorruptionDetectionLevel; xAsm.DebugMode = mSettings.DebugMode; xAsm.TraceAssemblies = mSettings.TraceAssemblies; xAsm.IgnoreDebugStubAttribute = mSettings.IgnoreDebugStubAttribute; if (!mSettings.EnableDebug) { xAsm.ShouldOptimize = true; } xAsm.Assembler.Initialize(); using (var xScanner = new ILScanner(xAsm, new TypeResolver(_assemblyLoadContext))) { xScanner.LogException = LogException; xScanner.LogWarning = LogWarning; CompilerHelpers.DebugEvent += LogMessage; if (mSettings.EnableLogging) { var xLogFile = xOutputFilenameWithoutExtension + ".log.html"; if (!xScanner.EnableLogging(xLogFile)) { // file creation not possible LogWarning("Could not create the file \"" + xLogFile + "\"! No log will be created!"); } } var plugsAssemblies = mSettings.PlugsReferences.Select( r => _assemblyLoadContext.LoadFromAssemblyPath(r)); if (UseGen3Kernel) { xScanner.Execute(mBootEntries.Keys.ToArray(), mForceIncludes, plugsAssemblies); } else { xScanner.QueueMethod(xKernelCtor.DeclaringType.BaseType.GetMethod(UseGen3Kernel ? "EntryPoint" : "Start")); xScanner.Execute(xKernelCtor, plugsAssemblies); } //AppAssemblerRingsCheck.Execute(xScanner, xKernelCtor.DeclaringType.Assembly); using (var xOut = new StreamWriter(File.Create(mSettings.OutputFilename), Encoding.ASCII, 128 * 1024)) { //if (EmitDebugSymbols) { xAsm.Assembler.FlushText(xOut); xAsm.FinalizeDebugInfo(); //// for now: write debug info to console //Console.WriteLine("Wrote {0} instructions and {1} datamembers", xAsm.Assembler.Instructions.Count, xAsm.Assembler.DataMembers.Count); //var dict = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase); //foreach (var instr in xAsm.Assembler.Instructions) //{ // var mn = instr.Mnemonic ?? ""; // if (dict.ContainsKey(mn)) // { // dict[mn] = dict[mn] + 1; // } // else // { // dict[mn] = 1; // } //} //foreach (var entry in dict) //{ // Console.WriteLine("{0}|{1}", entry.Key, entry.Value); //} } } // If you want to uncomment this line make sure to enable PERSISTANCE_PROFILING symbol in // DebugInfo.cs file. //LogMessage(string.Format("DebugInfo flatening {0} seconds, persistance : {1} seconds", // (int)xDebugInfo.FlateningDuration.TotalSeconds, // (int)xDebugInfo.PersistanceDuration.TotalSeconds)); } } LogTime("Engine execute finished"); return(true); } catch (Exception ex) { LogException(ex); return(false); } }
private Assembly Default_Resolving(AssemblyLoadContext arg1, AssemblyName arg2) { string fileName = Path.Combine(currentPluginFolder, $"{arg2.Name}.dll"); return(arg1.LoadFromAssemblyPath(fileName)); }
private static Assembly Default_Resolving(AssemblyLoadContext arg1, AssemblyName arg2) { Console.WriteLine($"Trying to resolve: {arg2.FullName}"); return(arg1.LoadFromAssemblyPath($"{_pluginsPath}\\{arg2.Name}.dll")); }
internal Type AddDynaClass(string fullyQualifiedClassName, string dllPath) { var loadedAssembly = context.LoadFromAssemblyPath(dllPath); return(loadedAssembly.GetType(fullyQualifiedClassName)); }
protected override Assembly LoadAssembly(string pluginAssemblyName) { return(_loadContext.LoadFromAssemblyPath(pluginAssemblyName)); }
public static Assembly LoadFrom(string assemblyPath) { return(LoadContext.LoadFromAssemblyPath(assemblyPath)); }
private Assembly ResolveAssembly(AssemblyLoadContext context, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; return(context.LoadFromAssemblyPath(Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), assemblyFilename))); }
private static Assembly LoadAssembly(AssemblyLoadContext context, string path) { path = Path.Combine(LoadPath, path); return(context.LoadFromAssemblyPath(path)); }
/// <summary> /// Loads the given type name from assemblies located in the given assembly path. /// </summary> /// <param name="typeName">The type name.</param> /// <exception cref="TypeLoadException">Thrown when type was not found.</exception> /// <returns>The type.</returns> public Type LoadType(string typeName) { if (_typeMap.ContainsKey(typeName)) { return(_typeMap[typeName]); } // Try to fetch the type from the already loaded assemblies, so we do not load duplicate assemblies in // app domain. var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies() .Where(a => !a.IsDynamic); foreach (var loadedAssembly in loadedAssemblies) { var contractType = loadedAssembly.GetType(typeName); if (contractType == null) { continue; } _typeMap.Add(typeName, contractType); return(contractType); } #if !NETFRAMEWORK foreach (var contractAssemblyPath in this._contractAssemblyPaths) { var assembly = _context.LoadFromAssemblyPath(contractAssemblyPath); var contractType = assembly.GetType(typeName); if (contractType == null) { continue; } _typeMap.Add(typeName, contractType); return(contractType); } #else // Load custom type from the given list of assemblies. foreach (var contractAssemblyPath in _contractAssemblyPaths) { var assembly = Assembly.LoadFrom(contractAssemblyPath); var contractType = assembly.GetType(typeName); if (contractType == null) { continue; } _typeMap.Add(typeName, contractType); return(contractType); } #endif var errorMessage = string.Format( SpecificationGenerationMessages.TypeNotFound, typeName, string.Join(" ", _contractAssemblyPaths.Select(Path.GetFileName))); throw new TypeLoadException(errorMessage); }
static public Func <AssemblyName, Assembly> collectibleAssemblyResolver(AssemblyLoadContext alc) => (asmName) => asmName.Name == asmNameString?alc.LoadFromAssemblyPath(asmPath) : null;
private Assembly ResolverForRoslyn(AssemblyLoadContext context, AssemblyName assemblyName) { return(LoadRoslyn(assemblyName, path => context.LoadFromAssemblyPath(path))); }
/// <summary> /// 使用文件流进行脚本编译,根据类名生成dll /// </summary> /// <param name="content">脚本内容</param> /// <param name="errorAction">发生错误执行委托</param> /// <returns></returns> public static Assembly FileComplier(string content, Action <Diagnostic> errorAction = null) { //类名获取 content = content.Trim(); var(Tree, ClassNames, formatter) = GetTreeAndClassNames(content); StringBuilder recoder = new StringBuilder(FormatLineCode(formatter)); //生成路径 string path = Path.Combine(LibPath, $"{ClassNames[0]}.dll"); if (DynamicDlls.ContainsKey(path)) { return(DynamicDlls[path]); } //创建语言编译 CSharpCompilation compilation = CSharpCompilation.Create( ClassNames[0], options: new CSharpCompilationOptions( outputKind: OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release), syntaxTrees: new[] { Tree }, references: References); EmitResult fileResult; //编译到文件 try { fileResult = compilation.Emit(path); if (fileResult.Success) { //为了实现动态中的动态,使用文件加载模式常驻内存 AssemblyLoadContext context = AssemblyLoadContext.Default; var result = context.LoadFromAssemblyPath(path); References.Add(MetadataReference.CreateFromFile(path)); for (int i = 0; i < ClassNames.Length; i += 1) { ClassMapping[ClassNames[i]] = result; } if (NScriptLog.UseLog) { recoder.AppendLine("\r\n\r\n------------------------------------------succeed-------------------------------------------"); recoder.AppendLine($"\r\n Time :\t\t{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); recoder.AppendLine($"\r\n Lauguage :\t{compilation.Language} & {compilation.LanguageVersion}"); recoder.AppendLine($"\r\n Target :\t\t{ClassNames[0]}"); recoder.AppendLine($"\r\n Path :\t\t{path}"); recoder.AppendLine($"\r\n Assembly : \t{result.FullName}"); recoder.AppendLine("\r\n----------------------------------------------------------------------------------------------"); NScriptLog.Succeed("Succeed : " + ClassNames[0], recoder.ToString()); } DynamicDlls[path] = result; return(result); } else { if (NScriptLog.UseLog) { recoder.AppendLine("\r\n\r\n------------------------------------------error----------------------------------------------"); recoder.AppendLine($"\r\n Time :\t\t{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); recoder.AppendLine($"\r\n Lauguage :\t{compilation.Language} & {compilation.LanguageVersion}"); recoder.AppendLine($"\r\n Target:\t\t{ClassNames[0]}"); recoder.AppendLine($"\r\n Error:\t\t共{fileResult.Diagnostics.Length}处错误!"); } foreach (var item in fileResult.Diagnostics) { if (NScriptLog.UseLog) { var temp = item.Location.GetLineSpan().StartLinePosition; var result = GetErrorString(formatter, item.Location.GetLineSpan()); recoder.AppendLine($"\t\t第{temp.Line + 1}行,第{temp.Character}个字符: 内容【{result}】 {item.GetMessage()}"); } errorAction?.Invoke(item); } recoder.AppendLine("\r\n---------------------------------------------------------------------------------------------"); NScriptLog.Error("Error : " + ClassNames[0], recoder.ToString()); } return(null); } catch (Exception ex) { if (ex is IOException) { int loop = 0; while (!DynamicDlls.ContainsKey(path)) { Thread.Sleep(200); loop += 1; } NScriptLog.Warning(ClassNames[0], $" I/O Delay :\t检测到争用,延迟{loop * 200}ms调用;\r\n"); return(DynamicDlls[path]); } return(null); } }
private static Assembly ResolveAssembly(AssemblyLoadContext sender, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; return sender.LoadFromAssemblyPath(Path.Combine(Path.GetTempPath(), assemblyFilename)); }
// Repeatedly execute a test case's Main method so that methods jitted // by the test can get rejitted at Tier1. // static int Main(string[] args) { string testAssemblyName = args[0]; // We'll stop iterating if total test time exceeds this value (in ms). // int timeout = 10_000; // Some tests return zero for success. // int expectedResult = 100; string[][] zeroReturnValuePatterns = { new string[] { "JIT", "jit64", "regress", "vsw", "102754", "test1" }, new string[] { "JIT", "Regression", "CLR-x86-JIT", "V1-M09", "b16102", "b16102" }, }; foreach (string[] pattern in zeroReturnValuePatterns) { if (testAssemblyName.IndexOf(Path.Join(pattern)) > 0) { expectedResult = 0; break; } } // Exclude tests that seem to be incompatible. // Todo: root cause these and fix tests if possible. // // With Full PGO: // RngchkStress2_o can hit a jit assert: '!m_failedToConverge' in 'SimpleArray_01.Test:Test1()' during 'Profile incorporation' // GitHub_25027 can hit a jit assert: 'verCurrentState.esStackDepth == 0' in 'X:Main():int' during 'Morph - Inlining' // string[][] exclusionPatterns = { new string[] { "JIT", "jit64", "opt", "cse", "VolatileTest_op" }, new string[] { "JIT", "jit64", "opt", "rngchk", "ArrayWithThread_o" }, new string[] { "baseservices", "threading", "threadstatic", "ThreadStatic01" }, new string[] { "GC", "Scenarios", "ReflectObj", "reflectobj" }, new string[] { "baseservices", "threading", "mutex", "openexisting", "openmutexpos4" }, new string[] { "GC", "Scenarios", "NDPin", "ndpinfinal" }, new string[] { "JIT", "Regression", "JitBlue", "GitHub_4044", "GitHub_4044" }, new string[] { "JIT", "HardwareIntrinsics", "X86", "Regression", "GitHub_21666", "GitHub_21666_ro"}, new string[] { "Interop", "NativeLibrary", "API", "NativeLibraryTests" }, new string[] { "baseservices", "compilerservices", "FixedAddressValueType", "FixedAddressValueType" }, new string[] { "GC", "LargeMemory", "API", "gc", "gettotalmemory" }, new string[] { "JIT", "jit64", "opt", "rngchk", "RngchkStress2_o" }, new string[] { "JIT", "Regression", "JitBlue", "GitHub_25027", "GitHub_25027" }, }; foreach (string[] pattern in exclusionPatterns) { if (testAssemblyName.IndexOf(Path.Join(pattern)) > 0) { if (verbose) { Console.WriteLine($"Test {Path.Join(pattern)} excluded; marked as incompatible"); } return(expectedResult); } } AssemblyLoadContext alc = AssemblyLoadContext.Default; Assembly testAssembly = alc.LoadFromAssemblyPath(testAssemblyName); MethodInfo main = testAssembly.EntryPoint; if (main == null) { Console.WriteLine($"Can't find entry point in {Path.GetFileName(args[0])}"); return(-1); } string[] mainArgs = new string[args.Length - 1]; Array.Copy(args, 1, mainArgs, 0, mainArgs.Length); // Console.WriteLine($"Found entry point {main.Name} in {Path.GetFileName(args[0])}"); // See if main wants any args. // var mainParams = main.GetParameters(); int result = 0; // Repeatedly invoke main to get things to pass through Tier0 and rejit at Tier1 // int warmup = 40; int final = 5; int total = warmup + final; int i = 0; int sleepInterval = 5; Stopwatch s = new Stopwatch(); s.Start(); // We might decide to give up on this test, for reasons. // // If the test fails at iteration 0, assume it's incompatible with the way we're running it // and don't report as a failure. // // If the test fails at iteration 1, assume it's got some bit of state that carries over // from one call to main to the next, and so don't report it as failure. // // If the test takes too long, just give up on iterating it. // bool giveUp = false; try { for (; i < warmup && !giveUp; i++) { if (mainParams.Length == 0) { result = (int)main.Invoke(null, new object[] { }); } else { result = (int)main.Invoke(null, new object[] { mainArgs }); } if (result != expectedResult) { if (i < 2) { Console.WriteLine($"[tieringtest] test failed at iteration {i} with result {result}. Test is likely incompatible."); result = expectedResult; } else { Console.WriteLine($"[tieringtest] test failed at iteration {i}: {result} (expected {expectedResult})"); } giveUp = true; break; } // Don't iterate if test is running long. // if (s.ElapsedMilliseconds > timeout) { Console.WriteLine($"[tieringtest] test running long ({s.ElapsedMilliseconds / (i + 1)} ms/iteration). Giving up at iteration {i}"); giveUp = true; break; } // Give TC a chance to jit some things. // Thread.Sleep(sleepInterval); } for (; i < total && !giveUp; i++) { if (mainParams.Length == 0) { result = (int)main.Invoke(null, new object[] { }); } else { result = (int)main.Invoke(null, new object[] { mainArgs }); } if (result != expectedResult) { Console.WriteLine($"[tieringtest] failed at iteration {i}: {result} (expected {expectedResult})"); giveUp = true; break; } // Don't iterate if test is running long. // if (s.ElapsedMilliseconds > timeout) { Console.WriteLine($"[tieringtest] test running long ({s.ElapsedMilliseconds / (i + 1)} ms/iteration). Giving up at iteration {i}"); giveUp = true; break; } } if (result == expectedResult) { if (verbose) { Console.WriteLine($"[tieringtest] ran {total} test iterations successfully"); } } } catch (Exception e) { if (i < 2) { if (verbose) { Console.WriteLine($"[tieringtest] test failed at iteration {i} with exception {e.Message}. Test is likely incompatible."); } result = expectedResult; } else { Console.WriteLine($"[tieringtest] test failed at iteration {i} with exception {e.Message}"); result = -1; } } return(result); }
private static AssemblyInfoItem GetAssemblyInfo(string fullFileName) { var assemblyItem = new AssemblyInfoItem { FullFileName = fullFileName, FileVersion = new Version(0, 0), referenceList = new List <FileItem>() }; AssemblyName[] references = null; try { var ctx = new AssemblyLoadContext(nameof(AssemblyLoader) + "", true); var asm = ctx.LoadFromAssemblyPath(fullFileName); try { assemblyItem.FileVersion = asm.GetName().Version; references = asm.GetReferencedAssemblies(); } catch (Exception e) { if (verbose) { Console.WriteLine("Can't get assembly info: " + fullFileName); Console.WriteLine("Exception: " + e.Message); } try { if (verbose) { Console.WriteLine("Re-trying to load assembly: " + fullFileName); } var newAsm = AssemblyName.GetAssemblyName(fullFileName); assemblyItem.FileVersion = newAsm.Version; } catch (Exception e2) { if (verbose) { Console.WriteLine("Still can't load assembly: " + fullFileName); Console.WriteLine("Exception: " + e2.Message); } } } finally { ctx.Unload(); } if (references != null) { foreach (var dllReference in references) { assemblyItem.referenceList.Add(new FileItem(dllReference.Name + ".dll", dllReference.Version)); } } } catch (Exception e) { // .NET Core 3.0 do not support ReflectionOnly load /*var loadedAssembly = Assembly.ReflectionOnlyLoadFrom(fullFileName); * assemblyItem.fileVersion = loadedAssembly.GetName().Version; * references = loadedAssembly.GetReferencedAssemblies();*/ if (verbose) { Console.WriteLine("Can't load assembly: " + fullFileName); Console.WriteLine("Exception: " + e.Message); } try { if (verbose) { Console.WriteLine("Re-trying to load assembly: " + fullFileName); } var newAsm = AssemblyName.GetAssemblyName(fullFileName); assemblyItem.FileVersion = newAsm.Version; } catch (Exception e2) { if (verbose) { Console.WriteLine("Still can't load assembly: " + fullFileName); Console.WriteLine("Exception: " + e2.Message); } } } return(assemblyItem); }
public Assembly LoadDefaultAssembly() { EnsureNotDisposed(); return(_context.LoadFromAssemblyPath(_config.MainAssemblyPath)); }
/// Called when an assembly could not be resolved private static Assembly OnAssemblyResolving(AssemblyLoadContext context, AssemblyName assembly) { return(context.LoadFromAssemblyPath(Path.Combine(lambdaTaskRoot, $"{assembly.Name}.dll"))); }
protected virtual Assembly LoadImpl(string fullPath) => _loadContext.LoadFromAssemblyPath(fullPath);
protected override Assembly LoadFromPathImpl(string fullPath) => _loadContext.LoadFromAssemblyPath(fullPath);
public Assembly LoadDefaultAssembly() => context.LoadFromAssemblyPath(mainAssembly);
public static void LoadRefEmitAssemblyInLoadContext(AssemblyLoadContext loadContext, AssemblyBuilderAccess builderType) { // Load this assembly in custom LoadContext var assemblyNameStr = "System.Runtime.Loader.Noop.Assembly.dll"; // Load the assembly in the specified load context var asmTargetAsm = loadContext.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyNameStr)); var loadedContext = AssemblyLoadContext.GetLoadContext(asmTargetAsm); // Get reference to the helper method that will RefEmit an assembly and return reference to it. Type type = asmTargetAsm.GetType("System.Runtime.Loader.Tests.TestClass"); var method = System.Reflection.TypeExtensions.GetMethod(type, "GetRefEmitAssembly"); // Use the helper to generate an assembly var assemblyNameRefEmit = "RefEmitTestAssembly"; var asmRefEmitLoaded = (Assembly)method.Invoke(null, new object[] {assemblyNameRefEmit, builderType}); Assert.NotNull(asmRefEmitLoaded); // Assert that Dynamically emitted assemblies do not have a load context associated with them. var loadContextRefEmitAssembly = AssemblyLoadContext.GetLoadContext(asmRefEmitLoaded); Assert.Equal(null, loadContextRefEmitAssembly); // Invoke the method that will trigger a static load in the dynamically generated assembly. Type typeRefEmit = asmRefEmitLoaded.GetType("RefEmitTestType"); method = System.Reflection.TypeExtensions.GetMethod(typeRefEmit, "LoadStaticAssembly"); Assert.NotNull(method); // Invoke the method to load the current assembly from the temp location var assemblyStaticToLoad = typeof(RefEmitLoadContext).GetTypeInfo().Assembly.GetName().Name; var asmRefEmitLoadedStatic = method.Invoke(null, new object[] {assemblyStaticToLoad}); Assert.NotNull(asmRefEmitLoadedStatic); // Load context of the statically loaded assembly is the custom load context in which dynamic assembly was created Assert.Equal(loadContext, AssemblyLoadContext.GetLoadContext((Assembly)asmRefEmitLoadedStatic)); }
public Assembly LoadFromAssemblyPath(string assemblyName) { return(ctx.LoadFromAssemblyPath(assemblyName)); }
private static Assembly ResolveAssembly(AssemblyLoadContext sender, AssemblyName assembly) { string assemblyFilename = assembly.Name + ".dll"; return(sender.LoadFromAssemblyPath(Path.Combine(Path.GetTempPath(), assemblyFilename))); }
public Assembly LoadFromPath(string path) => _context.LoadFromAssemblyPath(path);
public static void CreateEditorInstance() { lock (instanceCreateLocked) { if (instance == null) { instance = new ScriptEditor(); instance.FormClosing += (form, e) => { e.Cancel = true; ((Form)form).Visible = false; //if (editor.DialogResult == DialogResult.OK) //{ // try // { // string code = editor.Code; // //string code = editor.roslynHost.GetDocument(editor.docId).GetTextAsync().Result.ToString(); // //ret = codeFunc(code); // //var scrOpt = scriptOptions // // //.WithReferences(typeof(ScriptEditor).Assembly, typeof(MainController).Assembly) // // .WithReferences( // // editor.roslynHost.DefaultReferences // // .Concat(scriptOptions.MetadataReferences)) // // //.Concat( // // // scriptOptions.MetadataResolver)) // // //typeof(Enumerable).Assembly.GetReferencedAssemblies())) // // .WithImports(editor.roslynHost.DefaultImports); // var script = CSharpScript.Create( // code, // scriptOptions.WithImports(roslynHost.DefaultImports), // globalContext.GetType()); // var task = script.RunAsync(globalContext); // task.Wait(); // var ret = task.Result; // task.Dispose(); // File.WriteAllText("Code\\_last", editor.Code); // GC.Collect(); // } // catch (Exception ex) // { // if (exceptionHandler != null) // { // exceptionHandler(ex); // e.Cancel = true; // } // else throw; // } //} }; instance.button1.Click += (_, __) => { instance.button1.Enabled = false; cancellationTokenSource = new CancellationTokenSource(); Context.Reset(cancellationTokenSource); new Thread(() => { try { Guid guid = Guid.NewGuid(); string code = Code; File.WriteAllText("Code\\_last", code); //var script = CSharpScript.Create( // code, // scriptOptions // .WithImports(roslynHost.DefaultImports) // .WithEmitDebugInformation(true), // typeof(GlobalContext)); //var task = script.RunAsync(Context, Context.CancellationToken); //task.Wait(); //ScriptState scriptState = task.Result; //task.Dispose(); //GC.Collect(); //ScriptFinished?.Invoke(scriptState); //System.Diagnostics.Debug.WriteLine(scriptState.ReturnValue); InteractiveAssemblyLoader ial = new InteractiveAssemblyLoader(); //RoslynPad.Roslyn.Scripting.ScriptRunner scriptRunner = new RoslynPad.Roslyn.Scripting.ScriptRunner( // Code, // references: roslynHost.DefaultReferences, // usings: roslynHost.DefaultImports, // workingDirectory: $"{Environment.CurrentDirectory}\\Plugins", // assemblyLoader: ial // ); CSharpParseOptions parseOptions = CSharpParseOptions.Default .WithKind(SourceCodeKind.Script); //CSharpParseOptions parseOptions = new CSharpParseOptions( // documentationMode: DocumentationMode.Diagnose, // kind: SourceCodeKind.Script); string path = $"{Environment.CurrentDirectory}\\AsmTmp\\{guid.ToString().Substring(0, 8)}-{guid.GetHashCode()}"; string plugins = $"{Environment.CurrentDirectory}\\Plugins"; string className = "Submission"; string codePath = $"{path}\\{guid}.csx"; Directory.CreateDirectory(path); File.WriteAllText(codePath, Code); CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, mainTypeName: null, scriptClassName: className, usings: roslynHost.DefaultImports, allowUnsafe: true, sourceReferenceResolver: new SourceFileResolver(new[] { Environment.CurrentDirectory, plugins, path }, Environment.CurrentDirectory), metadataReferenceResolver: ScriptMetadataResolver .Default .WithBaseDirectory(Environment.CurrentDirectory) .WithSearchPaths(plugins, Environment.CurrentDirectory, path), assemblyIdentityComparer: AssemblyIdentityComparer.Default ); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText( Code, options: parseOptions, path: codePath, encoding: Encoding.Unicode, cancellationToken: cancellationTokenSource.Token); CSharpCompilation compilation = CSharpCompilation.CreateScriptCompilation( guid.ToString(), syntaxTree, roslynHost.DefaultReferences, options: compilationOptions, //previousScriptCompilation: previous, globalsType: typeof(GlobalContext)); //compilation = compilation.AddReferences(compilation.DirectiveReferences); foreach (MetadataReference item in compilation.DirectiveReferences) { string asmName = item.Display.Substring(item.Display.LastIndexOf('\\') + 1); asmName = asmName.Substring(0, asmName.Length - 4); //var asmid = // new AssemblyIdentity(asmName); //ial.RegisterDependency(asmid, item.Display); //Assembly.LoadFrom(item.Display); } Microsoft.CodeAnalysis.Emit.EmitResult emit = compilation.Emit($"{path}\\{guid}.dll", $"{path}\\{guid}.pdb", $"{path}\\{guid}.xml", cancellationToken: cancellationTokenSource.Token); previous = compilation; IMethodSymbol entryPoint = compilation.GetEntryPoint(cancellationTokenSource.Token); assemblyLoadContext?.Unload(); assemblyLoadContext = new AssemblyLoadContext(guid.ToString(), true); using FileStream fs = new FileStream($"{path}\\{guid}.dll", FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); assemblyLoadContext.LoadFromStream(fs); Assembly asm = assemblyLoadContext.LoadFromAssemblyPath($"{path}\\{guid}.dll"); assemblyLoadContext.Resolving += AssemblyLoadContext_Resolving; //Assembly asm = Assembly.LoadFrom($"{path}\\{guid}.dll"); //ial.RegisterDependency(asm); string BuildQualifiedName( string qualifier, string name) => !string.IsNullOrEmpty(qualifier) ? string.Concat(qualifier, ".", name) : name; var entryPointTypeName = BuildQualifiedName( entryPoint.ContainingNamespace.MetadataName, entryPoint.ContainingType.MetadataName); var entryPointMethodName = entryPoint.MetadataName; var entryPointType = asm.GetType(entryPointTypeName, throwOnError: true, ignoreCase: false); var runtimeEntryPoint = entryPointType.GetTypeInfo().GetDeclaredMethod(entryPointMethodName); var executor = (Func <object[], Task <object> >)runtimeEntryPoint.CreateDelegate(typeof(Func <object[], Task <object> >)); object[] vs = new object[3]; vs[0] = Context; var result = executor.Invoke(vs); if (result.IsFaulted) { SctiptException?.Invoke(result.Exception.InnerException); instance.Invoke((Action)(() => instance.propertyGrid.SelectedObject = new ScriptResult(Context, vs[1], result.Exception))); } else { System.Diagnostics.Debug.WriteLine(result.Result); instance.Invoke((Action)(() => instance.propertyGrid.SelectedObject = new ScriptResult(Context, vs[1], result.Result))); } //var compilation = script.GetCompilation() // .WithAssemblyName(guid.ToString()) // .WithOptions(compilation.Options.); //compilation.Options. //Directory.CreateDirectory("AsmTmp"); ////compilation.WithAssemblyName(); //var emit = compilation.Emit($"AsmTmp\\{guid}.dll", $"AsmTmp\\{guid}.pdb", $"AsmTmp\\{guid}.xml", cancellationToken: cancellationTokenSource.Token); } catch (Exception ex) { SctiptException?.Invoke(ex); } finally { // Выполнение в UI потоке instance.Invoke((Action)(() => instance.button1.Enabled = true)); GC.Collect(); } }) { Name = "ScriptThread" }.Start(); }; instance.button2.Click += (_, __) => { cancellationTokenSource?.Cancel(true); }; } }