-
Notifications
You must be signed in to change notification settings - Fork 387
/
Copy pathInstrumentationHelper.cs
388 lines (312 loc) · 13.2 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
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.PortableExecutable;
using System.Text.RegularExpressions;
using Microsoft.Extensions.FileSystemGlobbing;
using Microsoft.Extensions.FileSystemGlobbing.Abstractions;
namespace Coverlet.Core.Helpers
{
internal static class InstrumentationHelper
{
private static readonly ConcurrentDictionary<string, string> _backupList = new ConcurrentDictionary<string, string>();
static InstrumentationHelper()
{
AppDomain.CurrentDomain.ProcessExit += (s, e) => RestoreOriginalModules();
}
public static string[] GetCoverableModules(string module, string[] directories, bool includeTestAssembly)
{
Debug.Assert(directories != null);
string moduleDirectory = Path.GetDirectoryName(module);
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)
uniqueModules.Add(Path.GetFileName(module));
return dirs.SelectMany(d => Directory.EnumerateFiles(d))
.Where(m => IsAssembly(m) && uniqueModules.Add(Path.GetFileName(m)))
.ToArray();
}
public static bool HasPdb(string module)
{
using (var moduleStream = File.OpenRead(module))
using (var peReader = new PEReader(moduleStream))
{
foreach (var entry in peReader.ReadDebugDirectory())
{
if (entry.Type == DebugDirectoryEntryType.CodeView)
{
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(entry);
if (codeViewData.Path == $"{Path.GetFileNameWithoutExtension(module)}.pdb")
{
// PDB is embedded
return true;
}
return File.Exists(codeViewData.Path);
}
}
return false;
}
}
public static void BackupOriginalModule(string module, string identifier)
{
var backupPath = GetBackupPath(module, identifier);
var backupSymbolPath = Path.ChangeExtension(backupPath, ".pdb");
File.Copy(module, backupPath, true);
if (!_backupList.TryAdd(module, backupPath))
{
throw new ArgumentException($"Key already added '{module}'");
}
var symbolFile = Path.ChangeExtension(module, ".pdb");
if (File.Exists(symbolFile))
{
File.Copy(symbolFile, backupSymbolPath, true);
if (!_backupList.TryAdd(symbolFile, backupSymbolPath))
{
throw new ArgumentException($"Key already added '{module}'");
}
}
}
public static void RestoreOriginalModule(string module, string identifier)
{
var backupPath = GetBackupPath(module, identifier);
var 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
var retryStrategy = CreateRetryStrategy();
RetryHelper.Retry(() =>
{
File.Copy(backupPath, module, true);
File.Delete(backupPath);
_backupList.TryRemove(module, out string _);
}, retryStrategy, 10);
RetryHelper.Retry(() =>
{
if (File.Exists(backupSymbolPath))
{
string symbolFile = Path.ChangeExtension(module, ".pdb");
File.Copy(backupSymbolPath, symbolFile, true);
File.Delete(backupSymbolPath);
_backupList.TryRemove(symbolFile, out string _);
}
}, retryStrategy, 10);
}
public static 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
var retryStrategy = CreateRetryStrategy();
foreach (string key in _backupList.Keys.ToList())
{
string backupPath = _backupList[key];
RetryHelper.Retry(() =>
{
File.Copy(backupPath, key, true);
File.Delete(backupPath);
_backupList.TryRemove(key, out string _);
}, retryStrategy, 10);
}
}
public static void DeleteHitsFile(string path)
{
// Retry hitting the hits file - retry up to 10 times, since the file could be locked
// See: https://github.com/tonerdo/coverlet/issues/25
var retryStrategy = CreateRetryStrategy();
RetryHelper.Retry(() => File.Delete(path), retryStrategy, 10);
}
public static 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 static bool IsModuleExcluded(string module, string[] excludeFilters)
{
if (excludeFilters == null || excludeFilters.Length == 0)
return false;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return false;
foreach (var 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 static bool IsModuleIncluded(string module, string[] includeFilters)
{
if (includeFilters == null || includeFilters.Length == 0)
return true;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return false;
foreach (var 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 static 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 static 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 static bool IsLocalMethod(string method)
=> new Regex(WildcardToRegex("<*>*__*|*")).IsMatch(method);
public static string[] GetExcludedFiles(string[] excludes)
{
const string RELATIVE_KEY = nameof(RELATIVE_KEY);
string parentDir = Directory.GetCurrentDirectory();
if (excludes == null || !excludes.Any()) return Array.Empty<string>();
var matcherDict = new Dictionary<string, Matcher>() { { RELATIVE_KEY, new Matcher() } };
foreach (var excludeRule in excludes)
{
if (Path.IsPathRooted(excludeRule))
{
var root = Path.GetPathRoot(excludeRule);
if (!matcherDict.ContainsKey(root))
{
matcherDict.Add(root, new Matcher());
}
matcherDict[root].AddInclude(Path.GetFullPath(excludeRule).Substring(root.Length));
}
else
{
matcherDict[RELATIVE_KEY].AddInclude(excludeRule);
}
}
var files = new List<string>();
foreach (var entry in matcherDict)
{
var root = entry.Key;
var matcher = entry.Value;
var directoryInfo = new DirectoryInfo(root.Equals(RELATIVE_KEY) ? parentDir : root);
var fileMatchResult = matcher.Execute(new DirectoryInfoWrapper(directoryInfo));
var currentFiles = fileMatchResult.Files
.Select(f => Path.GetFullPath(Path.Combine(directoryInfo.ToString(), f.Path)));
files.AddRange(currentFiles);
}
return files.Distinct().ToArray();
}
private static bool IsTypeFilterMatch(string module, string type, string[] filters)
{
Debug.Assert(module != null);
Debug.Assert(filters != null);
foreach (var 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 static 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;
}
}
}
}