This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 169
/
LoadContext.cs
236 lines (208 loc) · 9.19 KB
/
LoadContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// This unfortunately needs to live in this project since the functionality is not available in netstandard2.1.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
namespace Microsoft.Quantum.QsCompiler
{
/// <summary>
/// Context with some basic handling for loading dependencies.
/// Each assembly loaded via LoadAssembly is loaded into its own context.
/// For more details, see https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/assemblyloadcontext.md
/// </summary>
public class LoadContext : AssemblyLoadContext
{
internal static HashSet<string> ManagedDllPaths { get; private set; } = new HashSet<string>();
internal static HashSet<string> UnmanagedDllPaths { get; private set; } = new HashSet<string>();
public string PathToParentAssembly { get; }
private readonly AssemblyDependencyResolver resolver;
private readonly HashSet<string> fallbackPaths;
/// <summary>
/// Adds the given path(s) to the list of paths the loader will search for a suitable .dll when an assembly could not be loaded.
/// </summary>
public void AddToPath(params string[] paths) =>
this.fallbackPaths.UnionWith(paths);
/// <summary>
/// Removes the given path(s) from the list of paths the loader will search for a suitable .dll when an assembly could not be loaded.
/// </summary>
public void RemoveFromPath(params string[] paths) =>
this.fallbackPaths.RemoveWhere(paths.Contains);
private LoadContext(string parentAssembly)
{
this.PathToParentAssembly = parentAssembly;
this.resolver = new AssemblyDependencyResolver(this.PathToParentAssembly);
this.fallbackPaths = new HashSet<string>();
this.Resolving += this.OnResolving;
}
/// <inheritdoc/>
protected override IntPtr LoadUnmanagedDll(string name)
{
var path = this.resolver.ResolveUnmanagedDllToPath(name);
path ??= ResolveFromPaths(name, this.fallbackPaths);
return path == null ? IntPtr.Zero : this.LoadUnmanagedDllFromPath(path);
}
/// <summary>
/// Search all fallback paths for a suitable .dll, .dylib, or .so file, ignoring all exceptions.
/// Returns the full path to the file if such a file was found.
/// </summary>
internal static string? ResolveFromPaths(string name, IEnumerable<string> paths)
{
bool MatchByName(string file) =>
Path.GetFileNameWithoutExtension(file)
.Equals(name, StringComparison.InvariantCultureIgnoreCase);
var found = new List<string>();
foreach (var dir in paths)
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
found.AddRange(Directory.GetFiles(dir, "*.dylib", SearchOption.AllDirectories).Where(MatchByName));
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
found.AddRange(Directory.GetFiles(dir, "*.so", SearchOption.AllDirectories).Where(MatchByName));
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
found.AddRange(Directory.GetFiles(dir, "*.dll", SearchOption.AllDirectories).Where(MatchByName));
}
else
{
found.AddRange(Directory.GetFiles(dir, "*.dll", SearchOption.AllDirectories).Where(MatchByName));
found.AddRange(Directory.GetFiles(dir, "*.dylib", SearchOption.AllDirectories).Where(MatchByName));
found.AddRange(Directory.GetFiles(dir, "*.so", SearchOption.AllDirectories).Where(MatchByName));
}
}
catch
{
continue;
}
}
return found.FirstOrDefault();
}
/// <inheritdoc/>
protected override Assembly? Load(AssemblyName name)
{
var path = this.resolver.ResolveAssemblyToPath(name);
return path == null ? null : this.LoadFromAssemblyPath(path);
}
/// <summary>
/// Search all fallback paths for a suitable .dll ignoring all exceptions.
/// Returns the full path to the dll if a suitable assembly was found.
/// </summary>
internal static string? ResolveFromPaths(AssemblyName name, string pathToParentAssembly, IEnumerable<string> paths)
{
bool MatchByName(string file) =>
Path.GetFileNameWithoutExtension(file)
.Equals(name.Name, StringComparison.InvariantCultureIgnoreCase);
var found = new List<string>();
foreach (var dir in paths)
{
try
{
found.AddRange(Directory.GetFiles(dir, "*.dll", SearchOption.AllDirectories).Where(MatchByName));
}
catch
{
continue;
}
}
if (found.Count <= 1 || name.Version == null)
{
return found.FirstOrDefault();
}
var tempContext = new LoadContext(pathToParentAssembly);
var versions = new List<(string, Version?)>();
foreach (var file in found)
{
try
{
var asm = tempContext.LoadFromAssemblyPath(file);
var asmVersion = asm.GetName()?.Version;
versions.Add((file, asmVersion));
if (name.Version.Equals(asmVersion))
{
if (tempContext.IsCollectible)
{
tempContext.Unload();
}
return file;
}
}
catch
{
continue;
}
}
if (tempContext.IsCollectible)
{
tempContext.Unload();
}
var matchesMajor = versions.Where(asm => name.Version.Major == asm.Item2?.Major);
var matchesMinor = matchesMajor.Where(asm => name.Version.Minor == asm.Item2?.Minor);
var matchesMajRev = matchesMinor.Where(asm => name.Version.MajorRevision == asm.Item2?.MajorRevision);
return matchesMajRev.Concat(matchesMinor).Concat(matchesMajor).Select(asm => asm.Item1).FirstOrDefault();
}
/// <summary>
/// Last effort to find a suitable dll for an assembly that could otherwise not be loaded.
/// Search for a suitable .dll in the specified fallback locations.
/// Does not load any dependencies.
/// </summary>
private Assembly? OnResolving(AssemblyLoadContext context, AssemblyName name)
{
var path = ResolveFromPaths(name, this.PathToParentAssembly, this.fallbackPaths);
return path == null ? null : this.LoadFromAssemblyPath(path);
}
private static readonly ConcurrentBag<LoadContext> Loaded =
new ConcurrentBag<LoadContext>();
/// <summary>
/// Unloads all created contexts that can be unloaded.
/// </summary>
public static void UnloadAll()
{
while (Loaded.TryTake(out var context))
{
if (context.IsCollectible)
{
context.Unload();
}
}
}
/// <summary>
/// Loads an assembly at the given location into a new context.
/// Adds the specified fallback locations, if any,
/// to the list of paths where the context will try to look for assemblies that could otherwise not be loaded.
/// </summary>
/// <exception cref="FileNotFoundException">File at <paramref name="path"/> does not exist.</exception>
public static Assembly LoadAssembly(string path, string[]? fallbackPaths = null)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("Failed to create contex for \"path\". No such file exists.");
}
var context = new LoadContext(path);
if (fallbackPaths != null)
{
context.AddToPath(fallbackPaths);
}
foreach (var preload in UnmanagedDllPaths)
{
context.LoadUnmanagedDllFromPath(preload);
}
foreach (var preload in ManagedDllPaths)
{
context.LoadFromAssemblyPath(preload);
}
Loaded.Add(context);
var assemblyName = new AssemblyName(Path.GetFileNameWithoutExtension(path));
return context.LoadFromAssemblyName(assemblyName);
}
}
}