-
Notifications
You must be signed in to change notification settings - Fork 416
/
AnalyzerAssemblyLoader.cs
325 lines (270 loc) · 12.5 KB
/
AnalyzerAssemblyLoader.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// This is simplified version from roslyn codebase, originated from https://github.com/dotnet/roslyn/blob/master/src/Compilers/Shared/ShadowCopyAnalyzerAssemblyLoader.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Utilities;
namespace OmniSharp.Host.Services
{
// This is shadow copying loader. Makes sure that analyzer assemblies are not locked
// on disk during analysis.
public class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader
{
private readonly string _baseDirectory;
private readonly Lazy<string> _shadowCopyDirectoryAndMutex;
private int _assemblyDirectoryId;
private readonly object _guard = new object();
private readonly Dictionary<string, Assembly> _loadedAssembliesByPath = new Dictionary<string, Assembly>();
private readonly Dictionary<string, AssemblyIdentity> _loadedAssemblyIdentitiesByPath = new Dictionary<string, AssemblyIdentity>();
private readonly Dictionary<AssemblyIdentity, Assembly> _loadedAssembliesByIdentity = new Dictionary<AssemblyIdentity, Assembly>();
private readonly Dictionary<string, HashSet<string>> _knownAssemblyPathsBySimpleName = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
private int _hookedAssemblyResolve;
public AnalyzerAssemblyLoader()
{
_baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies");
_shadowCopyDirectoryAndMutex = new Lazy<string>(
() => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication);
}
public void AddDependencyLocation(string fullPath)
{
string simpleName = Path.GetFileNameWithoutExtension(fullPath);
lock (_guard)
{
if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths))
{
paths = new HashSet<string>();
_knownAssemblyPathsBySimpleName.Add(simpleName, paths);
}
paths.Add(fullPath);
}
}
public Assembly LoadFromPath(string fullPath)
{
return LoadFromPathUncheckedCore(fullPath);
}
private Assembly LoadFromPathUncheckedCore(string fullPath, AssemblyIdentity identity = null)
{
// Check if we have already loaded an assembly with the same identity or from the given path.
Assembly loadedAssembly = null;
lock (_guard)
{
if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly))
{
loadedAssembly = existingAssembly;
}
else
{
identity = identity ?? GetOrAddAssemblyIdentity(fullPath);
if (identity != null && _loadedAssembliesByIdentity.TryGetValue(identity, out existingAssembly))
{
loadedAssembly = existingAssembly;
}
}
}
// Otherwise, load the assembly.
if (loadedAssembly == null)
{
loadedAssembly = LoadFromPathImpl(fullPath);
}
// Add the loaded assembly to both path and identity cache.
return AddToCache(loadedAssembly, fullPath, identity);
}
private AssemblyIdentity GetOrAddAssemblyIdentity(string fullPath)
{
lock (_guard)
{
if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity))
{
return existingIdentity;
}
}
var identity = TryGetAssemblyIdentity(fullPath);
return AddToCache(fullPath, identity);
}
private Assembly AddToCache(Assembly assembly, string fullPath, AssemblyIdentity identity)
{
identity = AddToCache(fullPath, identity ?? AssemblyIdentity.FromAssemblyDefinition(assembly));
lock (_guard)
{
// The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.),
// or another thread might have loaded the assembly after we checked above.
if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly))
{
assembly = existingAssembly;
}
else
{
_loadedAssembliesByIdentity.Add(identity, assembly);
}
// An assembly file might be replaced by another file with a different identity.
// Last one wins.
_loadedAssembliesByPath[fullPath] = assembly;
return assembly;
}
}
private AssemblyIdentity AddToCache(string fullPath, AssemblyIdentity identity)
{
lock (_guard)
{
if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null)
{
identity = existingIdentity;
}
else
{
_loadedAssemblyIdentitiesByPath[fullPath] = identity;
}
}
return identity;
}
private static string CopyFileAndResources(string fullPath, string assemblyDirectory)
{
string fileNameWithExtension = Path.GetFileName(fullPath);
string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension);
CopyFile(fullPath, shadowCopyPath);
string originalDirectory = Path.GetDirectoryName(fullPath);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension);
string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources";
string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll";
foreach (var directory in Directory.EnumerateDirectories(originalDirectory))
{
string directoryName = Path.GetFileName(directory);
string resourcesPath = Path.Combine(directory, resourcesNameWithExtension);
if (File.Exists(resourcesPath))
{
string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension);
CopyFile(resourcesPath, resourcesShadowCopyPath);
}
resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension);
if (File.Exists(resourcesPath))
{
string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension);
CopyFile(resourcesPath, resourcesShadowCopyPath);
}
}
return shadowCopyPath;
}
private static void CopyFile(string originalPath, string shadowCopyPath)
{
var directory = Path.GetDirectoryName(shadowCopyPath);
Directory.CreateDirectory(directory);
File.Copy(originalPath, shadowCopyPath);
ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath));
}
private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo)
{
try
{
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
}
catch
{
// There are many reasons this could fail. Ignore it and keep going.
}
}
private string CreateUniqueDirectoryForAssembly()
{
int directoryId = Interlocked.Increment(ref _assemblyDirectoryId);
string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value, directoryId.ToString());
Directory.CreateDirectory(directory);
return directory;
}
private string CreateUniqueDirectoryForProcess()
{
string guid = Guid.NewGuid().ToString("N").ToLowerInvariant();
string directory = Path.Combine(_baseDirectory, guid);
Directory.CreateDirectory(directory);
return directory;
}
private Assembly LoadFromPathImpl(string originalPath)
{
string assemblyDirectory = CreateUniqueDirectoryForAssembly();
string shadowCopyPath = CopyFileAndResources(originalPath, assemblyDirectory);
if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
return Assembly.LoadFrom(shadowCopyPath);
}
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
try
{
return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name));
}
catch
{
return null;
}
}
public Assembly Load(string displayName)
{
if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity))
{
return null;
}
ImmutableArray<string> candidatePaths;
lock (_guard)
{
// First, check if this loader already loaded the requested assembly:
if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly))
{
return existingAssembly;
}
// Second, check if an assembly file of the same simple name was registered with the loader:
if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedIdentity.Name, out var pathList))
{
return null;
}
candidatePaths = pathList.ToImmutableArray();
}
// Multiple assemblies of the same simple name but different identities might have been registered.
// Load the one that matches the requested identity (if any).
foreach (var candidatePath in candidatePaths)
{
var candidateIdentity = GetOrAddAssemblyIdentity(candidatePath);
if (requestedIdentity.Equals(candidateIdentity))
{
return LoadFromPathUncheckedCore(candidatePath, candidateIdentity);
}
}
return null;
}
private static AssemblyIdentity TryGetAssemblyIdentity(string filePath)
{
try
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var peReader = new PEReader(stream))
{
var metadataReader = peReader.GetMetadataReader();
AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();
string name = metadataReader.GetString(assemblyDefinition.Name);
Version version = assemblyDefinition.Version;
StringHandle cultureHandle = assemblyDefinition.Culture;
string cultureName = (!cultureHandle.IsNil) ? metadataReader.GetString(cultureHandle) : null;
AssemblyFlags flags = assemblyDefinition.Flags;
bool hasPublicKey = (flags & AssemblyFlags.PublicKey) != 0;
BlobHandle publicKeyHandle = assemblyDefinition.PublicKey;
ImmutableArray<byte> publicKeyOrToken = !publicKeyHandle.IsNil
? metadataReader.GetBlobBytes(publicKeyHandle).AsImmutableOrNull()
: default;
return new AssemblyIdentity(name, version, cultureName, publicKeyOrToken, hasPublicKey);
}
}
catch { }
return null;
}
}
}