forked from coverlet-coverage/coverlet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCecilAssemblyResolver.cs
322 lines (278 loc) · 11.1 KB
/
CecilAssemblyResolver.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
// Copyright (c) Toni Solarin-Sodara
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using Coverlet.Core.Abstractions;
using Coverlet.Core.Exceptions;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.DependencyModel.Resolution;
using Mono.Cecil;
namespace Coverlet.Core.Instrumentation
{
/// <summary>
/// In case of testing different runtime i.e. netfx we could find netstandard.dll in folder.
/// netstandard.dll is a forward only lib, there is no IL but only forwards to "runtime" implementation.
/// For some classes implementation are in different assembly for different runtime for instance:
///
/// For NetFx 4.7
/// // Token: 0x2700072C RID: 1836
/// .class extern forwarder System.Security.Cryptography.X509Certificates.StoreName
/// {
/// .assembly extern System
/// }
///
/// For netcoreapp2.2
/// Token: 0x2700072C RID: 1836
/// .class extern forwarder System.Security.Cryptography.X509Certificates.StoreName
/// {
/// .assembly extern System.Security.Cryptography.X509Certificates
/// }
///
/// There is a concrete possibility that Cecil cannot find implementation and throws StackOverflow exception https://github.com/jbevain/cecil/issues/575
/// This custom resolver check if requested lib is a "official" netstandard.dll and load once of "current runtime" with
/// correct forwards.
/// Check compares 'assembly name' and 'public key token', because versions could differ between runtimes.
/// </summary>
internal class NetstandardAwareAssemblyResolver : DefaultAssemblyResolver
{
private static readonly System.Reflection.Assembly s_netStandardAssembly;
private static readonly string s_name;
private static readonly byte[] s_publicKeyToken;
private static readonly AssemblyDefinition s_assemblyDefinition;
private readonly string _modulePath;
private readonly Lazy<CompositeCompilationAssemblyResolver> _compositeResolver;
private readonly ILogger _logger;
static NetstandardAwareAssemblyResolver()
{
try
{
// To be sure to load information of "real" runtime netstandard implementation
s_netStandardAssembly = System.Reflection.Assembly.LoadFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "netstandard.dll"));
System.Reflection.AssemblyName name = s_netStandardAssembly.GetName();
s_name = name.Name;
s_publicKeyToken = name.GetPublicKeyToken();
s_assemblyDefinition = AssemblyDefinition.ReadAssembly(s_netStandardAssembly.Location);
}
catch (FileNotFoundException)
{
// netstandard not supported
}
}
public NetstandardAwareAssemblyResolver(string modulePath, ILogger logger)
{
_modulePath = modulePath;
_logger = logger;
// this is lazy because we cannot create NetCoreSharedFrameworkResolver if not on .NET Core runtime,
// runtime folders are different
_compositeResolver = new Lazy<CompositeCompilationAssemblyResolver>(() => new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
{
new AppBaseCompilationAssemblyResolver(),
new PackageCompilationAssemblyResolver(),
new NetCoreSharedFrameworkResolver(modulePath, _logger),
new ReferenceAssemblyPathResolver(),
}), true);
}
// Check name and public key but not version that could be different
private static bool CheckIfSearchingNetstandard(AssemblyNameReference name)
{
if (s_netStandardAssembly is null)
{
return false;
}
if (s_name != name.Name)
{
return false;
}
if (name.PublicKeyToken.Length != s_publicKeyToken.Length)
{
return false;
}
for (int i = 0; i < name.PublicKeyToken.Length; i++)
{
if (s_publicKeyToken[i] != name.PublicKeyToken[i])
{
return false;
}
}
return true;
}
public override AssemblyDefinition Resolve(AssemblyNameReference name)
{
if (CheckIfSearchingNetstandard(name))
{
return s_assemblyDefinition;
}
else
{
try
{
return base.Resolve(name);
}
catch (AssemblyResolutionException)
{
AssemblyDefinition asm = TryWithCustomResolverOnDotNetCore(name);
if (asm != null)
{
return asm;
}
throw;
}
}
}
private static bool IsDotNetCore()
{
// object for .NET Framework is inside mscorlib.dll
return Path.GetFileName(typeof(object).Assembly.Location) == "System.Private.CoreLib.dll";
}
/// <summary>
///
/// We try to manually load assembly.
/// To work test project needs to use
///
/// <PropertyGroup>
/// <PreserveCompilationContext>true</PreserveCompilationContext>
/// </PropertyGroup>
///
/// Runtime configuration file doc https://github.com/dotnet/cli/blob/master/Documentation/specs/runtime-configuration-file.md
///
/// </summary>
internal AssemblyDefinition TryWithCustomResolverOnDotNetCore(AssemblyNameReference name)
{
_logger.LogVerbose($"TryWithCustomResolverOnDotNetCore for {name}");
if (!IsDotNetCore())
{
_logger.LogVerbose($"Not a dotnet core app");
return null;
}
if (string.IsNullOrEmpty(_modulePath))
{
throw new AssemblyResolutionException(name);
}
using var contextJsonReader = new DependencyContextJsonReader();
var libraries = new Dictionary<string, Lazy<AssemblyDefinition>>();
foreach (string fileName in Directory.GetFiles(Path.GetDirectoryName(_modulePath), "*.deps.json"))
{
using FileStream depsFile = File.OpenRead(fileName);
_logger.LogVerbose($"Loading {fileName}");
DependencyContext dependencyContext = contextJsonReader.Read(depsFile);
foreach (CompilationLibrary library in dependencyContext.CompileLibraries)
{
// we're interested only on nuget package
if (library.Type == "project")
{
continue;
}
try
{
string path = library.ResolveReferencePaths(_compositeResolver.Value).FirstOrDefault();
if (string.IsNullOrEmpty(path))
{
continue;
}
// We could load more than one deps file, we need to check if lib is already found
if (!libraries.ContainsKey(library.Name))
{
libraries.Add(library.Name, new Lazy<AssemblyDefinition>(() => AssemblyDefinition.ReadAssembly(path, new ReaderParameters() { AssemblyResolver = this })));
}
}
catch (Exception ex)
{
// if we don't find a lib go on
_logger.LogVerbose($"TryWithCustomResolverOnDotNetCore exception: {ex}");
}
}
}
if (libraries.TryGetValue(name.Name, out Lazy<AssemblyDefinition> asm))
{
return asm.Value;
}
throw new CecilAssemblyResolutionException($"AssemblyResolutionException for '{name}'. Try to add <PreserveCompilationContext>true</PreserveCompilationContext> to test projects </PropertyGroup> or pass '/p:CopyLocalLockFileAssemblies=true' option to the 'dotnet test' command-line", new AssemblyResolutionException(name));
}
}
internal class NetCoreSharedFrameworkResolver : ICompilationAssemblyResolver
{
private readonly List<string> _aspNetSharedFrameworkDirs = new();
private readonly ILogger _logger;
public NetCoreSharedFrameworkResolver(string modulePath, ILogger logger)
{
_logger = logger;
string runtimeConfigFile = Path.Combine(
Path.GetDirectoryName(modulePath)!,
Path.GetFileNameWithoutExtension(modulePath) + ".runtimeconfig.json");
if (!File.Exists(runtimeConfigFile))
{
return;
}
var reader = new RuntimeConfigurationReader(runtimeConfigFile);
IEnumerable<(string Name, string Version)> referencedFrameworks = reader.GetFrameworks();
string runtimePath = Path.GetDirectoryName(typeof(object).Assembly.Location);
string runtimeRootPath = Path.Combine(runtimePath!, "../..");
foreach ((string frameworkName, string frameworkVersion) in referencedFrameworks)
{
var majorVersion = string.Join(".", frameworkVersion.Split('.').Take(2)) + ".";
var directory = new DirectoryInfo(Path.Combine(runtimeRootPath, frameworkName));
var latestVersion = directory.GetDirectories().Where(x => x.Name.StartsWith(majorVersion))
.Select(x => Convert.ToUInt32(x.Name.Substring(majorVersion.Length))).Max();
_aspNetSharedFrameworkDirs.Add(Path.Combine(directory.FullName, majorVersion + latestVersion));
}
_logger.LogVerbose("NetCoreSharedFrameworkResolver search paths:");
foreach (string searchPath in _aspNetSharedFrameworkDirs)
{
_logger.LogVerbose(searchPath);
}
}
public bool TryResolveAssemblyPaths(CompilationLibrary library, List<string> assemblies)
{
string dllName = $"{library.Name}.dll";
foreach (string sharedFrameworkPath in _aspNetSharedFrameworkDirs)
{
if (!Directory.Exists(sharedFrameworkPath))
{
continue;
}
string[] files = Directory.GetFiles(sharedFrameworkPath);
foreach (string file in files)
{
if (Path.GetFileName(file).Equals(dllName, StringComparison.OrdinalIgnoreCase))
{
_logger.LogVerbose($"'{dllName}' found in '{file}'");
assemblies.Add(file);
return true;
}
}
}
return false;
}
}
internal class RuntimeConfigurationReader
{
private readonly string _runtimeConfigFile;
public RuntimeConfigurationReader(string runtimeConfigFile)
{
_runtimeConfigFile = runtimeConfigFile;
}
public IEnumerable<(string Name, string Version)> GetFrameworks()
{
string jsonString = File.ReadAllText(_runtimeConfigFile);
var documentOptions = new JsonDocumentOptions
{
CommentHandling = JsonCommentHandling.Skip
};
using var configuration = JsonDocument.Parse(jsonString, documentOptions);
JsonElement rootElement = configuration.RootElement;
JsonElement runtimeOptionsElement = rootElement.GetProperty("runtimeOptions");
if (runtimeOptionsElement.TryGetProperty("framework", out JsonElement frameworkElement))
{
return new[] { (frameworkElement.GetProperty("name").GetString(), frameworkElement.GetProperty("version").GetString()) };
}
if (runtimeOptionsElement.TryGetProperty("frameworks", out JsonElement frameworksElement))
{
return frameworksElement.EnumerateArray().Select(x => (x.GetProperty("name").GetString(), x.GetProperty("version").GetString())).ToList();
}
throw new InvalidOperationException($"Unable to read runtime configuration from {_runtimeConfigFile}.");
}
}
}