-
Notifications
You must be signed in to change notification settings - Fork 388
/
InstrumentationHelper.cs
459 lines (377 loc) · 17.3 KB
/
InstrumentationHelper.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text.RegularExpressions;
using Coverlet.Core.Abstractions;
namespace Coverlet.Core.Helpers
{
internal class InstrumentationHelper : IInstrumentationHelper
{
private const int RetryAttempts = 12;
private readonly ConcurrentDictionary<string, string> _backupList = new();
private readonly IRetryHelper _retryHelper;
private readonly IFileSystem _fileSystem;
private readonly ISourceRootTranslator _sourceRootTranslator;
private ILogger _logger;
public InstrumentationHelper(IProcessExitHandler processExitHandler, IRetryHelper retryHelper, IFileSystem fileSystem, ILogger logger, ISourceRootTranslator sourceRootTranslator)
{
processExitHandler.Add((s, e) => RestoreOriginalModules());
_retryHelper = retryHelper;
_fileSystem = fileSystem;
_logger = logger;
_sourceRootTranslator = sourceRootTranslator;
}
public string[] GetCoverableModules(string moduleOrAppDirectory, string[] directories, bool includeTestAssembly)
{
Debug.Assert(directories != null);
Debug.Assert(moduleOrAppDirectory != null);
bool isAppDirectory = !File.Exists(moduleOrAppDirectory) && Directory.Exists(moduleOrAppDirectory);
string moduleDirectory = isAppDirectory ? moduleOrAppDirectory : Path.GetDirectoryName(moduleOrAppDirectory);
if (moduleDirectory == string.Empty)
{
moduleDirectory = Directory.GetCurrentDirectory();
}
var dirs = new List<string>()
{
// Add the test assembly's directory.
moduleDirectory
};
// Prepare all the directories we probe for modules.
foreach (string directory in directories)
{
if (string.IsNullOrWhiteSpace(directory)) continue;
string fullPath = (!Path.IsPathRooted(directory)
? Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), directory))
: directory).TrimEnd('*');
if (!Directory.Exists(fullPath)) continue;
if (directory.EndsWith("*", StringComparison.Ordinal))
dirs.AddRange(Directory.GetDirectories(fullPath));
else
dirs.Add(fullPath);
}
// The module's name must be unique.
var uniqueModules = new HashSet<string>();
if (!includeTestAssembly && !isAppDirectory)
uniqueModules.Add(Path.GetFileName(moduleOrAppDirectory));
return dirs.SelectMany(d => Directory.EnumerateFiles(d))
.Where(m => IsAssembly(m) && uniqueModules.Add(Path.GetFileName(m)))
.ToArray();
}
public bool HasPdb(string module, out bool embedded)
{
embedded = false;
using Stream moduleStream = _fileSystem.OpenRead(module);
using var peReader = new PEReader(moduleStream);
foreach (DebugDirectoryEntry entry in peReader.ReadDebugDirectory())
{
if (entry.Type == DebugDirectoryEntryType.CodeView)
{
CodeViewDebugDirectoryData codeViewData = peReader.ReadCodeViewDebugDirectoryData(entry);
if (_sourceRootTranslator.ResolveFilePath(codeViewData.Path) == $"{Path.GetFileNameWithoutExtension(module)}.pdb")
{
// PDB is embedded
embedded = true;
return true;
}
return _fileSystem.Exists(_sourceRootTranslator.ResolveFilePath(codeViewData.Path));
}
}
return false;
}
public bool EmbeddedPortablePdbHasLocalSource(string module, out string firstNotFoundDocument)
{
firstNotFoundDocument = "";
using (Stream moduleStream = _fileSystem.OpenRead(module))
using (var peReader = new PEReader(moduleStream))
{
foreach (DebugDirectoryEntry entry in peReader.ReadDebugDirectory())
{
if (entry.Type == DebugDirectoryEntryType.EmbeddedPortablePdb)
{
using MetadataReaderProvider embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry);
MetadataReader metadataReader = embeddedMetadataProvider.GetMetadataReader();
(bool allDocumentsMatch, string notFoundDocument) = MatchDocumentsWithSources(metadataReader);
if (!allDocumentsMatch)
{
firstNotFoundDocument = notFoundDocument;
return false;
}
}
}
}
// If we don't have EmbeddedPortablePdb entry return true, for instance empty dll
// We should call this method only on embedded pdb module
return true;
}
public bool PortablePdbHasLocalSource(string module, out string firstNotFoundDocument)
{
firstNotFoundDocument = "";
using (Stream moduleStream = _fileSystem.OpenRead(module))
using (var peReader = new PEReader(moduleStream))
{
foreach (DebugDirectoryEntry entry in peReader.ReadDebugDirectory())
{
if (entry.Type == DebugDirectoryEntryType.CodeView)
{
CodeViewDebugDirectoryData codeViewData = peReader.ReadCodeViewDebugDirectoryData(entry);
using Stream pdbStream = _fileSystem.OpenRead(_sourceRootTranslator.ResolveFilePath(codeViewData.Path));
using var metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream);
MetadataReader metadataReader = null;
try
{
metadataReader = metadataReaderProvider.GetMetadataReader();
}
catch (BadImageFormatException)
{
_logger.LogWarning($"{nameof(BadImageFormatException)} during MetadataReaderProvider.FromPortablePdbStream in InstrumentationHelper.PortablePdbHasLocalSource, unable to check if module has got local source.");
return true;
}
(bool allDocumentsMatch, string notFoundDocument) = MatchDocumentsWithSources(metadataReader);
if (!allDocumentsMatch)
{
firstNotFoundDocument = notFoundDocument;
return false;
}
}
}
}
return true;
}
private (bool allDocumentsMatch, string notFoundDocument) MatchDocumentsWithSources(MetadataReader metadataReader)
{
foreach (DocumentHandle docHandle in metadataReader.Documents)
{
Document document = metadataReader.GetDocument(docHandle);
string docName = _sourceRootTranslator.ResolveFilePath(metadataReader.GetString(document.Name));
Guid languageGuid = metadataReader.GetGuid(document.Language);
// We verify all docs and return false if not all are present in local
// We could have false negative if doc is not a source
// Btw check for all possible extension could be weak approach
// We exlude from the check the autogenerated source file(i.e. source generators)
// We exclude special F# construct https://github.com/coverlet-coverage/coverlet/issues/1145
if (!_fileSystem.Exists(docName) && !docName.EndsWith(".g.cs") &&
!IsUnknownModuleInFSharpAssembly(languageGuid, docName))
{
return (false, docName);
}
}
return (true, string.Empty);
}
public void BackupOriginalModule(string module, string identifier)
{
string backupPath = GetBackupPath(module, identifier);
string backupSymbolPath = Path.ChangeExtension(backupPath, ".pdb");
_fileSystem.Copy(module, backupPath, true);
if (!_backupList.TryAdd(module, backupPath))
{
throw new ArgumentException($"Key already added '{module}'");
}
string symbolFile = Path.ChangeExtension(module, ".pdb");
if (_fileSystem.Exists(symbolFile))
{
_fileSystem.Copy(symbolFile, backupSymbolPath, true);
if (!_backupList.TryAdd(symbolFile, backupSymbolPath))
{
throw new ArgumentException($"Key already added '{module}'");
}
}
}
public virtual void RestoreOriginalModule(string module, string identifier)
{
string backupPath = GetBackupPath(module, identifier);
string backupSymbolPath = Path.ChangeExtension(backupPath, ".pdb");
// Restore the original module - retry up to 10 times, since the destination file could be locked
// See: https://github.com/tonerdo/coverlet/issues/25
Func<TimeSpan> retryStrategy = CreateRetryStrategy();
_retryHelper.Retry(() =>
{
_fileSystem.Copy(backupPath, module, true);
_fileSystem.Delete(backupPath);
_backupList.TryRemove(module, out string _);
}, retryStrategy, RetryAttempts);
_retryHelper.Retry(() =>
{
if (_fileSystem.Exists(backupSymbolPath))
{
string symbolFile = Path.ChangeExtension(module, ".pdb");
_fileSystem.Copy(backupSymbolPath, symbolFile, true);
_fileSystem.Delete(backupSymbolPath);
_backupList.TryRemove(symbolFile, out string _);
}
}, retryStrategy, RetryAttempts);
}
public virtual void RestoreOriginalModules()
{
// Restore the original module - retry up to 10 times, since the destination file could be locked
// See: https://github.com/tonerdo/coverlet/issues/25
Func<TimeSpan> retryStrategy = CreateRetryStrategy();
foreach (string key in _backupList.Keys.ToList())
{
string backupPath = _backupList[key];
_retryHelper.Retry(() =>
{
_fileSystem.Copy(backupPath, key, true);
_fileSystem.Delete(backupPath);
_backupList.TryRemove(key, out string _);
}, retryStrategy, RetryAttempts);
}
}
public void DeleteHitsFile(string path)
{
Func<TimeSpan> retryStrategy = CreateRetryStrategy();
_retryHelper.Retry(() => _fileSystem.Delete(path), retryStrategy, RetryAttempts);
}
public bool IsValidFilterExpression(string filter)
{
if (filter == null)
return false;
if (!filter.StartsWith("["))
return false;
if (!filter.Contains("]"))
return false;
if (filter.Count(f => f == '[') > 1)
return false;
if (filter.Count(f => f == ']') > 1)
return false;
if (filter.IndexOf(']') < filter.IndexOf('['))
return false;
if (filter.IndexOf(']') - filter.IndexOf('[') == 1)
return false;
if (filter.EndsWith("]"))
return false;
if (new Regex(@"[^\w*]").IsMatch(filter.Replace(".", "").Replace("?", "").Replace("[", "").Replace("]", "")))
return false;
return true;
}
public bool IsModuleExcluded(string module, string[] excludeFilters)
{
if (excludeFilters == null || excludeFilters.Length == 0)
return false;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return false;
foreach (string filter in excludeFilters)
{
string typePattern = filter.Substring(filter.IndexOf(']') + 1);
if (typePattern != "*")
continue;
string modulePattern = filter.Substring(1, filter.IndexOf(']') - 1);
modulePattern = WildcardToRegex(modulePattern);
var regex = new Regex(modulePattern);
if (regex.IsMatch(module))
return true;
}
return false;
}
public bool IsModuleIncluded(string module, string[] includeFilters)
{
if (includeFilters == null || includeFilters.Length == 0)
return true;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return false;
foreach (string filter in includeFilters)
{
string modulePattern = filter.Substring(1, filter.IndexOf(']') - 1);
if (modulePattern == "*")
return true;
modulePattern = WildcardToRegex(modulePattern);
var regex = new Regex(modulePattern);
if (regex.IsMatch(module))
return true;
}
return false;
}
public bool IsTypeExcluded(string module, string type, string[] excludeFilters)
{
if (excludeFilters == null || excludeFilters.Length == 0)
return false;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return false;
return IsTypeFilterMatch(module, type, excludeFilters);
}
public bool IsTypeIncluded(string module, string type, string[] includeFilters)
{
if (includeFilters == null || includeFilters.Length == 0)
return true;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return true;
return IsTypeFilterMatch(module, type, includeFilters);
}
public bool IsLocalMethod(string method)
=> new Regex(WildcardToRegex("<*>*__*|*")).IsMatch(method);
public void SetLogger(ILogger logger)
{
_logger = logger;
}
private static bool IsTypeFilterMatch(string module, string type, string[] filters)
{
Debug.Assert(module != null);
Debug.Assert(filters != null);
foreach (string filter in filters)
{
string typePattern = filter.Substring(filter.IndexOf(']') + 1);
string modulePattern = filter.Substring(1, filter.IndexOf(']') - 1);
typePattern = WildcardToRegex(typePattern);
modulePattern = WildcardToRegex(modulePattern);
if (new Regex(typePattern).IsMatch(type) && new Regex(modulePattern).IsMatch(module))
return true;
}
return false;
}
private static string GetBackupPath(string module, string identifier)
{
return Path.Combine(
Path.GetTempPath(),
Path.GetFileNameWithoutExtension(module) + "_" + identifier + ".dll"
);
}
private Func<TimeSpan> CreateRetryStrategy(int initialSleepSeconds = 6)
{
TimeSpan retryStrategy()
{
var sleep = TimeSpan.FromMilliseconds(initialSleepSeconds);
initialSleepSeconds *= 2;
return sleep;
}
return retryStrategy;
}
private static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", "?") + "$";
}
private static bool IsAssembly(string filePath)
{
Debug.Assert(filePath != null);
if (!(filePath.EndsWith(".exe") || filePath.EndsWith(".dll")))
return false;
try
{
AssemblyName.GetAssemblyName(filePath);
return true;
}
catch
{
return false;
}
}
private static bool IsUnknownModuleInFSharpAssembly(Guid languageGuid, string docName)
{
// https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md#document-table-0x30
return languageGuid.Equals(new Guid("ab4f38c9-b6e6-43ba-be3b-58080b2ccce3"))
&& docName.EndsWith("unknown");
}
}
}