/
Instrumenter.cs
305 lines (251 loc) · 11.6 KB
/
Instrumenter.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
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using Coverlet.Core.Attributes;
using Coverlet.Core.Helpers;
using Coverlet.Core.Symbols;
using Coverlet.Tracker;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
namespace Coverlet.Core.Instrumentation
{
internal class Instrumenter
{
private readonly string _module;
private readonly string _identifier;
private readonly string[] _filters;
private readonly string[] _excludedFiles;
private readonly static Lazy<MethodInfo> _markExecutedMethodLoader = new Lazy<MethodInfo>(GetMarkExecutedMethod);
private InstrumenterResult _result;
public Instrumenter(string module, string identifier, string[] filters, string[] excludedFiles)
{
_module = module;
_identifier = identifier;
_filters = filters;
_excludedFiles = excludedFiles ?? Array.Empty<string>();
}
public bool CanInstrument() => InstrumentationHelper.HasPdb(_module);
public InstrumenterResult Instrument()
{
string hitsFilePath = Path.Combine(
Path.GetTempPath(),
Path.GetFileNameWithoutExtension(_module) + "_" + _identifier
);
_result = new InstrumenterResult
{
Module = Path.GetFileNameWithoutExtension(_module),
HitsFilePath = hitsFilePath,
ModulePath = _module
};
InstrumentModule();
InstrumentationHelper.CopyCoverletDependency(_module);
return _result;
}
private void InstrumentModule()
{
using (var stream = new FileStream(_module, FileMode.Open, FileAccess.ReadWrite))
using (var resolver = new DefaultAssemblyResolver())
{
resolver.AddSearchDirectory(Path.GetDirectoryName(_module));
var parameters = new ReaderParameters { ReadSymbols = true, AssemblyResolver = resolver };
using (var module = ModuleDefinition.ReadModule(stream, parameters))
{
var types = module.GetTypes();
foreach (TypeDefinition type in types)
{
var actualType = type.DeclaringType ?? type;
if (!actualType.CustomAttributes.Any(IsExcludeAttribute)
&& !InstrumentationHelper.IsTypeExcluded(_module, actualType.FullName, _filters))
InstrumentType(type);
}
module.Write(stream);
}
}
}
private void InstrumentType(TypeDefinition type)
{
var methods = type.GetMethods();
foreach (var method in methods)
{
MethodDefinition actualMethod = method;
if (InstrumentationHelper.IsLocalMethod(method.Name))
actualMethod = methods.FirstOrDefault(m => m.Name == method.Name.Split('>')[0].Substring(1)) ?? method;
if (!actualMethod.CustomAttributes.Any(IsExcludeAttribute))
InstrumentMethod(method);
}
var ctors = type.GetConstructors();
foreach (var ctor in ctors)
{
if (!ctor.CustomAttributes.Any(IsExcludeAttribute))
InstrumentMethod(ctor);
}
}
private void InstrumentMethod(MethodDefinition method)
{
var sourceFile = method.DebugInformation.SequencePoints.Select(s => s.Document.Url).FirstOrDefault();
if (!string.IsNullOrEmpty(sourceFile) && _excludedFiles.Contains(sourceFile))
return;
var methodBody = GetMethodBody(method);
if (methodBody == null)
return;
if (method.IsNative)
return;
InstrumentIL(method);
}
private void InstrumentIL(MethodDefinition method)
{
method.Body.SimplifyMacros();
ILProcessor processor = method.Body.GetILProcessor();
var index = 0;
var count = processor.Body.Instructions.Count;
var branchPoints = CecilSymbolHelper.GetBranchPoints(method);
for (int n = 0; n < count; n++)
{
var instruction = processor.Body.Instructions[index];
var sequencePoint = method.DebugInformation.GetSequencePoint(instruction);
var targetedBranchPoints = branchPoints.Where(p => p.EndOffset == instruction.Offset);
if (sequencePoint != null && !sequencePoint.IsHidden)
{
var target = AddInstrumentationCode(method, processor, instruction, sequencePoint);
foreach (var _instruction in processor.Body.Instructions)
ReplaceInstructionTarget(_instruction, instruction, target);
foreach (ExceptionHandler handler in processor.Body.ExceptionHandlers)
ReplaceExceptionHandlerBoundary(handler, instruction, target);
index += 3;
}
foreach (var _branchTarget in targetedBranchPoints)
{
/*
* Skip branches with no sequence point reference for now.
* In this case for an anonymous class the compiler will dynamically create an Equals 'utility' method.
* The CecilSymbolHelper will create branch points with a start line of -1 and no document, which
* I am currently not sure how to handle.
*/
if (_branchTarget.StartLine == -1 || _branchTarget.Document == null)
continue;
var target = AddInstrumentationCode(method, processor, instruction, _branchTarget);
foreach (var _instruction in processor.Body.Instructions)
ReplaceInstructionTarget(_instruction, instruction, target);
foreach (ExceptionHandler handler in processor.Body.ExceptionHandlers)
ReplaceExceptionHandlerBoundary(handler, instruction, target);
index += 3;
}
index++;
}
method.Body.OptimizeMacros();
}
private Instruction AddInstrumentationCode(MethodDefinition method, ILProcessor processor, Instruction instruction, SequencePoint sequencePoint)
{
if (!_result.Documents.TryGetValue(sequencePoint.Document.Url, out var document))
{
document = new Document { Path = sequencePoint.Document.Url };
_result.Documents.Add(document.Path, document);
}
for (int i = sequencePoint.StartLine; i <= sequencePoint.EndLine; i++)
{
if (!document.Lines.ContainsKey(i))
document.Lines.Add(i, new Line { Number = i, Class = method.DeclaringType.FullName, Method = method.FullName });
}
string marker = $"L,{document.Path},{sequencePoint.StartLine},{sequencePoint.EndLine}";
var pathInstr = Instruction.Create(OpCodes.Ldstr, _result.HitsFilePath);
var markInstr = Instruction.Create(OpCodes.Ldstr, marker);
var callInstr = Instruction.Create(OpCodes.Call, processor.Body.Method.Module.ImportReference(_markExecutedMethodLoader.Value));
processor.InsertBefore(instruction, callInstr);
processor.InsertBefore(callInstr, markInstr);
processor.InsertBefore(markInstr, pathInstr);
return pathInstr;
}
private Instruction AddInstrumentationCode(MethodDefinition method, ILProcessor processor, Instruction instruction, BranchPoint branchPoint)
{
if (!_result.Documents.TryGetValue(branchPoint.Document, out var document))
{
document = new Document { Path = branchPoint.Document };
_result.Documents.Add(document.Path, document);
}
var key = (branchPoint.StartLine, (int)branchPoint.Ordinal);
if (!document.Branches.ContainsKey(key))
document.Branches.Add(key,
new Branch
{
Number = branchPoint.StartLine,
Class = method.DeclaringType.FullName,
Method = method.FullName,
Offset = branchPoint.Offset,
EndOffset = branchPoint.EndOffset,
Path = branchPoint.Path,
Ordinal = branchPoint.Ordinal
}
);
string marker = $"B,{document.Path},{branchPoint.StartLine},{branchPoint.Ordinal}";
var pathInstr = Instruction.Create(OpCodes.Ldstr, _result.HitsFilePath);
var markInstr = Instruction.Create(OpCodes.Ldstr, marker);
var callInstr = Instruction.Create(OpCodes.Call, processor.Body.Method.Module.ImportReference(_markExecutedMethodLoader.Value));
processor.InsertBefore(instruction, callInstr);
processor.InsertBefore(callInstr, markInstr);
processor.InsertBefore(markInstr, pathInstr);
return pathInstr;
}
private static void ReplaceInstructionTarget(Instruction instruction, Instruction oldTarget, Instruction newTarget)
{
if (instruction.Operand is Instruction _instruction)
{
if (_instruction == oldTarget)
{
instruction.Operand = newTarget;
return;
}
}
else if (instruction.Operand is Instruction[] _instructions)
{
for (int i = 0; i < _instructions.Length; i++)
{
if (_instructions[i] == oldTarget)
_instructions[i] = newTarget;
}
}
}
private static void ReplaceExceptionHandlerBoundary(ExceptionHandler handler, Instruction oldTarget, Instruction newTarget)
{
if (handler.FilterStart == oldTarget)
handler.FilterStart = newTarget;
if (handler.HandlerEnd == oldTarget)
handler.HandlerEnd = newTarget;
if (handler.HandlerStart == oldTarget)
handler.HandlerStart = newTarget;
if (handler.TryEnd == oldTarget)
handler.TryEnd = newTarget;
if (handler.TryStart == oldTarget)
handler.TryStart = newTarget;
}
private static bool IsExcludeAttribute(CustomAttribute customAttribute)
{
var excludeAttributeNames = new[]
{
nameof(ExcludeFromCoverageAttribute),
"ExcludeFromCoverage",
nameof(ExcludeFromCodeCoverageAttribute),
"ExcludeFromCodeCoverage"
};
var attributeName = customAttribute.AttributeType.Name;
return excludeAttributeNames.Any(a => a.Equals(attributeName));
}
private static Mono.Cecil.Cil.MethodBody GetMethodBody(MethodDefinition method)
{
try
{
return method.HasBody ? method.Body : null;
}
catch
{
return null;
}
}
private static MethodInfo GetMarkExecutedMethod()
{
return typeof(CoverageTracker).GetMethod(nameof(CoverageTracker.MarkExecuted));
}
}
}