-
Notifications
You must be signed in to change notification settings - Fork 386
/
Instrumenter.cs
943 lines (814 loc) · 39.5 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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
// 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using Coverlet.Core.Abstractions;
using Coverlet.Core.Attributes;
using Coverlet.Core.Enums;
using Coverlet.Core.Helpers;
using Coverlet.Core.Instrumentation.Reachability;
using Coverlet.Core.Symbols;
using Microsoft.Extensions.FileSystemGlobbing;
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 ExcludedFilesHelper _excludedFilesHelper;
private readonly CoverageParameters _parameters;
private readonly string[] _excludedAttributes;
private readonly bool _isCoreLibrary;
private readonly ILogger _logger;
private readonly IInstrumentationHelper _instrumentationHelper;
private readonly IFileSystem _fileSystem;
private readonly ISourceRootTranslator _sourceRootTranslator;
private readonly ICecilSymbolHelper _cecilSymbolHelper;
private readonly string[] _doesNotReturnAttributes;
private readonly AssemblySearchType _excludeAssembliesWithoutSources;
private InstrumenterResult _result;
private FieldDefinition _customTrackerHitsArray;
private FieldDefinition _customTrackerHitsFilePath;
private FieldDefinition _customTrackerSingleHit;
private FieldDefinition _customTrackerFlushHitFile;
private ILProcessor _customTrackerClassConstructorIl;
private TypeDefinition _customTrackerTypeDef;
private MethodReference _customTrackerRegisterUnloadEventsMethod;
private MethodReference _customTrackerRecordHitMethod;
private List<string> _excludedSourceFiles;
private List<string> _branchesInCompiledGeneratedClass;
private List<(SequencePoint firstSequencePoint, SequencePoint lastSequencePoint)> _excludedMethodSections;
private List<string> _excludedLambdaMethods;
private ReachabilityHelper _reachabilityHelper;
public bool SkipModule { get; set; }
public Instrumenter(
string module,
string identifier,
CoverageParameters parameters,
ILogger logger,
IInstrumentationHelper instrumentationHelper,
IFileSystem fileSystem,
ISourceRootTranslator sourceRootTranslator,
ICecilSymbolHelper cecilSymbolHelper)
{
_module = module;
_identifier = identifier;
_parameters = parameters;
_excludedFilesHelper = new ExcludedFilesHelper(parameters.ExcludedSourceFiles, logger);
_excludedAttributes = PrepareAttributes(parameters.ExcludeAttributes, nameof(ExcludeFromCoverageAttribute), nameof(ExcludeFromCodeCoverageAttribute));
_isCoreLibrary = Path.GetFileNameWithoutExtension(_module) == "System.Private.CoreLib";
_logger = logger;
_instrumentationHelper = instrumentationHelper;
_fileSystem = fileSystem;
_sourceRootTranslator = sourceRootTranslator;
_cecilSymbolHelper = cecilSymbolHelper;
_doesNotReturnAttributes = PrepareAttributes(parameters.DoesNotReturnAttributes);
_excludeAssembliesWithoutSources = DetermineHeuristics(parameters.ExcludeAssembliesWithoutSources);
}
private AssemblySearchType DetermineHeuristics(string parametersExcludeAssembliesWithoutSources)
{
if (Enum.TryParse(parametersExcludeAssembliesWithoutSources, true, out AssemblySearchType option))
{
return option;
}
return AssemblySearchType.MissingAll;
}
private static string[] PrepareAttributes(IEnumerable<string> providedAttrs, params string[] defaultAttrs)
{
return
(providedAttrs ?? Array.Empty<string>())
// In case the attribute class ends in "Attribute", but it wasn't specified.
// Both names are included (if it wasn't specified) because the attribute class might not actually end in the prefix.
.SelectMany(a => a.EndsWith("Attribute") ? new[] { a } : new[] { a, $"{a}Attribute" })
// The default custom attributes used to exclude from coverage.
.Union(defaultAttrs)
.ToArray();
}
public bool CanInstrument()
{
try
{
if (_instrumentationHelper.HasPdb(_module, out bool embeddedPdb))
{
if (_excludeAssembliesWithoutSources.Equals(AssemblySearchType.None))
{
return true;
}
if (embeddedPdb)
{
return _instrumentationHelper.EmbeddedPortablePdbHasLocalSource(_module, _excludeAssembliesWithoutSources);
}
else
{
return _instrumentationHelper.PortablePdbHasLocalSource(_module, _excludeAssembliesWithoutSources);
}
}
else
{
return false;
}
}
catch (Exception ex)
{
_logger.LogWarning($"Unable to instrument module: '{_module}'\n{ex}");
return false;
}
}
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();
if (_excludedSourceFiles != null)
{
foreach (string sourceFile in _excludedSourceFiles)
{
_logger.LogVerbose($"Excluded source file: '{FileSystem.EscapeFileName(sourceFile)}'");
}
}
_result.BranchesInCompiledGeneratedClass = _branchesInCompiledGeneratedClass == null ? Array.Empty<string>() : _branchesInCompiledGeneratedClass.ToArray();
return _result;
}
// If current type or one of his parent is excluded we'll exclude it
// If I'm out every my children and every children of my children will be out
private bool IsTypeExcluded(TypeDefinition type)
{
for (TypeDefinition current = type; current != null; current = current.DeclaringType)
{
// Check exclude attribute and filters
if (current.CustomAttributes.Any(IsExcludeAttribute) || _instrumentationHelper.IsTypeExcluded(_module, current.FullName, _parameters.ExcludeFilters))
{
return true;
}
}
return false;
}
// Instrumenting Interlocked which is used for recording hits would cause an infinite loop.
private bool Is_System_Threading_Interlocked_CoreLib_Type(TypeDefinition type)
{
return _isCoreLibrary && type.FullName == "System.Threading.Interlocked";
}
// Have to do this before we start writing to a module, as we'll get into file
// locking issues if we do it while writing.
private void CreateReachabilityHelper()
{
using Stream stream = _fileSystem.NewFileStream(_module, FileMode.Open, FileAccess.Read);
using var resolver = new NetstandardAwareAssemblyResolver(_module, _logger);
resolver.AddSearchDirectory(Path.GetDirectoryName(_module));
var parameters = new ReaderParameters { ReadSymbols = true, AssemblyResolver = resolver };
if (_isCoreLibrary)
{
parameters.MetadataImporterProvider = new CoreLibMetadataImporterProvider();
}
using var module = ModuleDefinition.ReadModule(stream, parameters);
_reachabilityHelper = ReachabilityHelper.CreateForModule(module, _doesNotReturnAttributes, _logger);
}
private void InstrumentModule()
{
CreateReachabilityHelper();
using Stream stream = _fileSystem.NewFileStream(_module, FileMode.Open, FileAccess.ReadWrite);
using var resolver = new NetstandardAwareAssemblyResolver(_module, _logger);
resolver.AddSearchDirectory(Path.GetDirectoryName(_module));
var parameters = new ReaderParameters { ReadSymbols = true, AssemblyResolver = resolver };
if (_isCoreLibrary)
{
parameters.MetadataImporterProvider = new CoreLibMetadataImporterProvider();
}
using var module = ModuleDefinition.ReadModule(stream, parameters);
foreach (CustomAttribute customAttribute in module.Assembly.CustomAttributes)
{
if (IsExcludeAttribute(customAttribute))
{
_logger.LogVerbose($"Excluded module: '{module}' for assembly level attribute {customAttribute.AttributeType.FullName}");
SkipModule = true;
return;
}
}
bool containsAppContext = module.GetType(nameof(System), nameof(AppContext)) != null;
IEnumerable<TypeDefinition> types = module.GetTypes();
AddCustomModuleTrackerToModule(module);
CustomDebugInformation sourceLinkDebugInfo = module.CustomDebugInformations.FirstOrDefault(c => c.Kind == CustomDebugInformationKind.SourceLink);
if (sourceLinkDebugInfo != null)
{
_result.SourceLink = ((SourceLinkDebugInformation)sourceLinkDebugInfo).Content;
}
foreach (TypeDefinition type in types)
{
if (
!Is_System_Threading_Interlocked_CoreLib_Type(type) &&
!IsTypeExcluded(type) &&
_instrumentationHelper.IsTypeIncluded(_module, type.FullName, _parameters.IncludeFilters)
)
{
InstrumentType(type);
}
}
// Fixup the custom tracker class constructor, according to all instrumented types
if (_customTrackerRegisterUnloadEventsMethod == null)
{
_customTrackerRegisterUnloadEventsMethod = new MethodReference(
nameof(ModuleTrackerTemplate.RegisterUnloadEvents), module.TypeSystem.Void, _customTrackerTypeDef);
}
Instruction lastInstr = _customTrackerClassConstructorIl.Body.Instructions.Last();
if (!containsAppContext)
{
// For "normal" cases, where the instrumented assembly is not the core library, we add a call to
// RegisterUnloadEvents to the static constructor of the generated custom tracker. Due to static
// initialization constraints, the core library is handled separately below.
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Call, _customTrackerRegisterUnloadEventsMethod));
}
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Ldc_I4, _result.HitCandidates.Count));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Newarr, module.TypeSystem.Int32));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Stsfld, _customTrackerHitsArray));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Ldstr, _result.HitsFilePath));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Stsfld, _customTrackerHitsFilePath));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(_parameters.SingleHit ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Stsfld, _customTrackerSingleHit));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Ldc_I4_1));
_customTrackerClassConstructorIl.InsertBefore(lastInstr, Instruction.Create(OpCodes.Stsfld, _customTrackerFlushHitFile));
if (containsAppContext)
{
// Handle the core library by instrumenting System.AppContext.OnProcessExit to directly call
// the UnloadModule method of the custom tracker type. This avoids loops between the static
// initialization of the custom tracker and the static initialization of the hosting AppDomain
// (which for the core library case will be instrumented code).
var eventArgsType = new TypeReference(nameof(System), nameof(EventArgs), module, module.TypeSystem.CoreLibrary);
var customTrackerUnloadModule = new MethodReference(nameof(ModuleTrackerTemplate.UnloadModule), module.TypeSystem.Void, _customTrackerTypeDef);
customTrackerUnloadModule.Parameters.Add(new ParameterDefinition(module.TypeSystem.Object));
customTrackerUnloadModule.Parameters.Add(new ParameterDefinition(eventArgsType));
var appContextType = new TypeReference(nameof(System), nameof(AppContext), module, module.TypeSystem.CoreLibrary);
MethodDefinition onProcessExitMethod = new MethodReference("OnProcessExit", module.TypeSystem.Void, appContextType).Resolve();
ILProcessor onProcessExitIl = onProcessExitMethod.Body.GetILProcessor();
// Put the OnProcessExit body inside try/finally to ensure the call to the UnloadModule.
Instruction lastInst = onProcessExitMethod.Body.Instructions.Last();
var firstNullParam = Instruction.Create(OpCodes.Ldnull);
var secondNullParam = Instruction.Create(OpCodes.Ldnull);
var callUnload = Instruction.Create(OpCodes.Call, customTrackerUnloadModule);
onProcessExitIl.InsertAfter(lastInst, firstNullParam);
onProcessExitIl.InsertAfter(firstNullParam, secondNullParam);
onProcessExitIl.InsertAfter(secondNullParam, callUnload);
var endFinally = Instruction.Create(OpCodes.Endfinally);
onProcessExitIl.InsertAfter(callUnload, endFinally);
Instruction ret = onProcessExitIl.Create(OpCodes.Ret);
Instruction leaveAfterFinally = onProcessExitIl.Create(OpCodes.Leave, ret);
onProcessExitIl.InsertAfter(endFinally, ret);
foreach (Instruction inst in onProcessExitMethod.Body.Instructions.ToArray())
{
// Patch ret to leave after the finally
if (inst.OpCode == OpCodes.Ret && inst != ret)
{
Instruction leaveBodyInstAfterFinally = onProcessExitIl.Create(OpCodes.Leave, ret);
Instruction prevInst = inst.Previous;
onProcessExitMethod.Body.Instructions.Remove(inst);
onProcessExitIl.InsertAfter(prevInst, leaveBodyInstAfterFinally);
}
}
var handler = new ExceptionHandler(ExceptionHandlerType.Finally)
{
TryStart = onProcessExitIl.Body.Instructions.First(),
TryEnd = firstNullParam,
HandlerStart = firstNullParam,
HandlerEnd = ret
};
onProcessExitMethod.Body.ExceptionHandlers.Add(handler);
}
module.Write(stream, new WriterParameters { WriteSymbols = true });
}
private void AddCustomModuleTrackerToModule(ModuleDefinition module)
{
using (var coverletInstrumentationAssembly = AssemblyDefinition.ReadAssembly(typeof(ModuleTrackerTemplate).Assembly.Location))
{
TypeDefinition moduleTrackerTemplate = coverletInstrumentationAssembly.MainModule.GetType(
"Coverlet.Core.Instrumentation", nameof(ModuleTrackerTemplate));
_customTrackerTypeDef = new TypeDefinition(
"Coverlet.Core.Instrumentation.Tracker", Path.GetFileNameWithoutExtension(module.Name) + "_" + _identifier, moduleTrackerTemplate.Attributes);
_customTrackerTypeDef.BaseType = module.TypeSystem.Object;
foreach (FieldDefinition fieldDef in moduleTrackerTemplate.Fields)
{
var fieldClone = new FieldDefinition(fieldDef.Name, fieldDef.Attributes, fieldDef.FieldType);
fieldClone.FieldType = module.ImportReference(fieldDef.FieldType);
_customTrackerTypeDef.Fields.Add(fieldClone);
if (fieldClone.Name == nameof(ModuleTrackerTemplate.HitsArray))
_customTrackerHitsArray = fieldClone;
else if (fieldClone.Name == nameof(ModuleTrackerTemplate.HitsFilePath))
_customTrackerHitsFilePath = fieldClone;
else if (fieldClone.Name == nameof(ModuleTrackerTemplate.SingleHit))
_customTrackerSingleHit = fieldClone;
else if (fieldClone.Name == nameof(ModuleTrackerTemplate.FlushHitFile))
_customTrackerFlushHitFile = fieldClone;
}
foreach (MethodDefinition methodDef in moduleTrackerTemplate.Methods)
{
var methodOnCustomType = new MethodDefinition(methodDef.Name, methodDef.Attributes, methodDef.ReturnType);
foreach (ParameterDefinition parameter in methodDef.Parameters)
{
methodOnCustomType.Parameters.Add(new ParameterDefinition(module.ImportReference(parameter.ParameterType)));
}
foreach (VariableDefinition variable in methodDef.Body.Variables)
{
methodOnCustomType.Body.Variables.Add(new VariableDefinition(module.ImportReference(variable.VariableType)));
}
methodOnCustomType.Body.InitLocals = methodDef.Body.InitLocals;
ILProcessor ilProcessor = methodOnCustomType.Body.GetILProcessor();
if (methodDef.Name == ".cctor")
_customTrackerClassConstructorIl = ilProcessor;
foreach (Instruction instr in methodDef.Body.Instructions)
{
if (instr.Operand is MethodReference methodReference)
{
if (!methodReference.FullName.Contains(moduleTrackerTemplate.Namespace))
{
// External method references, just import then
instr.Operand = module.ImportReference(methodReference);
}
else
{
// Move to the custom type
var updatedMethodReference = new MethodReference(methodReference.Name, methodReference.ReturnType, _customTrackerTypeDef);
foreach (ParameterDefinition parameter in methodReference.Parameters)
updatedMethodReference.Parameters.Add(new ParameterDefinition(parameter.Name, parameter.Attributes, module.ImportReference(parameter.ParameterType)));
instr.Operand = updatedMethodReference;
}
}
else if (instr.Operand is FieldReference fieldReference)
{
instr.Operand = _customTrackerTypeDef.Fields.Single(fd => fd.Name == fieldReference.Name);
}
else if (instr.Operand is TypeReference typeReference)
{
instr.Operand = module.ImportReference(typeReference);
}
ilProcessor.Append(instr);
}
foreach (ExceptionHandler handler in methodDef.Body.ExceptionHandlers)
{
if (handler.CatchType != null)
{
handler.CatchType = module.ImportReference(handler.CatchType);
}
methodOnCustomType.Body.ExceptionHandlers.Add(handler);
}
_customTrackerTypeDef.Methods.Add(methodOnCustomType);
}
module.Types.Add(_customTrackerTypeDef);
}
Debug.Assert(_customTrackerHitsArray != null);
Debug.Assert(_customTrackerClassConstructorIl != null);
}
private bool IsMethodOfCompilerGeneratedClassOfAsyncStateMachineToBeExcluded(MethodDefinition method)
{
// Type compiler generated, the async state machine
TypeDefinition typeDefinition = method.DeclaringType;
if (typeDefinition.DeclaringType is null)
{
return false;
}
// Search in type that contains async state machine, compiler generates async state machine in private nested class
foreach (MethodDefinition typeMethod in typeDefinition.DeclaringType.Methods)
{
// If we find the async state machine attribute on method
CustomAttribute attribute;
if ((attribute = typeMethod.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(AsyncStateMachineAttribute).FullName)) != null)
{
// If the async state machine generated by compiler is "associated" to this method we check for exclusions
// The associated type is specified on attribute constructor
// https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.asyncstatemachineattribute.-ctor?view=netcore-3.1
if (attribute.ConstructorArguments[0].Value == method.DeclaringType)
{
if (typeMethod.CustomAttributes.Any(IsExcludeAttribute))
{
return true;
}
}
}
}
return false;
}
private void InstrumentType(TypeDefinition type)
{
IEnumerable<MethodDefinition> methods = type.GetMethods();
foreach (MethodDefinition method in methods)
{
MethodDefinition actualMethod = method;
IEnumerable<CustomAttribute> customAttributes = method.CustomAttributes;
if (_instrumentationHelper.IsLocalMethod(method.Name))
#pragma warning disable IDE0057 // Use range operator
actualMethod = methods.FirstOrDefault(m => m.Name == method.Name.Split('>')[0].Substring(1)) ?? method;
#pragma warning restore IDE0057 // Use range operator
if (actualMethod.IsGetter || actualMethod.IsSetter)
{
if (_parameters.SkipAutoProps && IsCompilerGenerated(actualMethod))
{
continue;
}
PropertyDefinition prop = type.Properties.FirstOrDefault(p => p.GetMethod?.FullName.Equals(actualMethod.FullName) == true ||
p.SetMethod?.FullName.Equals(actualMethod.FullName) == true);
if (prop?.HasCustomAttributes == true)
customAttributes = customAttributes.Union(prop.CustomAttributes);
}
if (IsMethodOfCompilerGeneratedClassOfAsyncStateMachineToBeExcluded(method))
{
continue;
}
if (_excludedLambdaMethods != null && _excludedLambdaMethods.Contains(method.FullName))
{
continue;
}
if (!customAttributes.Any(IsExcludeAttribute))
{
InstrumentMethod(method);
}
else
{
(_excludedLambdaMethods ??= new List<string>()).AddRange(CollectLambdaMethodsInsideLocalFunction(method));
_excludedMethodSections ??= new List<(SequencePoint firstSequencePoint, SequencePoint lastSequencePoint)>();
AnalyzeCompileGeneratedTypesForExcludedMethod(method);
CacheExcludedMethodSection(method);
}
}
IEnumerable<MethodDefinition> ctors = type.GetConstructors();
foreach (MethodDefinition ctor in ctors)
{
if (!ctor.CustomAttributes.Any(IsExcludeAttribute) && !IsCompilerGenerated(ctor))
{
InstrumentMethod(ctor);
}
}
}
private static bool IsCompilerGenerated(IMemberDefinition member)
{
return member.CustomAttributes.Any(ca => ca.AttributeType.FullName == typeof(CompilerGeneratedAttribute).FullName);
}
private void InstrumentMethod(MethodDefinition method)
{
string sourceFile = method.DebugInformation.SequencePoints.Select(s => _sourceRootTranslator.ResolveFilePath(s.Document.Url)).FirstOrDefault();
if (string.IsNullOrEmpty(sourceFile)) return;
if (!string.IsNullOrEmpty(sourceFile) && _excludedFilesHelper.Exclude(sourceFile))
{
if (!(_excludedSourceFiles ??= new List<string>()).Contains(sourceFile))
{
_excludedSourceFiles.Add(sourceFile);
}
return;
}
MethodBody methodBody = GetMethodBody(method);
if (methodBody == null)
return;
if (method.IsNative)
return;
InstrumentIL(method);
}
/// <summary>
/// The base idea is to inject an int placeholder for every sequence point. We register source+placeholder+lines(from sequence point) for final accounting.
/// Instrumentation alg(current instruction: instruction we're analyzing):
/// 1) We get all branches for the method
/// 2) We get the sequence point of every instruction of method(start line/end line)
/// 3) We check if current instruction is reachable and coverable
/// 4) For every sequence point of an instruction we put load(int hint placeholder)+call opcode above current instruction
/// 5) We patch all jump to current instruction with first injected instruction(load)
/// 6) If current instruction is a target for a branch we inject again load(int hint placeholder)+call opcode above current instruction
/// 7) We patch all jump to current instruction with first injected instruction(load)
/// </summary>
private void InstrumentIL(MethodDefinition method)
{
method.Body.SimplifyMacros();
ILProcessor processor = method.Body.GetILProcessor();
int index = 0;
int count = processor.Body.Instructions.Count;
IReadOnlyList<BranchPoint> branchPoints = _cecilSymbolHelper.GetBranchPoints(method);
IDictionary<int, Instruction> targetsMap = new Dictionary<int, Instruction>();
System.Collections.Immutable.ImmutableArray<ReachabilityHelper.UnreachableRange> unreachableRanges = _reachabilityHelper.FindUnreachableIL(processor.Body.Instructions, processor.Body.ExceptionHandlers);
int currentUnreachableRangeIx = 0;
for (int n = 0; n < count; n++)
{
Instruction currentInstruction = processor.Body.Instructions[index];
SequencePoint sequencePoint = method.DebugInformation.GetSequencePoint(currentInstruction);
IEnumerable<BranchPoint> targetedBranchPoints = branchPoints.Where(p => p.EndOffset == currentInstruction.Offset);
// make sure we're looking at the correct unreachable range (if any)
int instrOffset = currentInstruction.Offset;
while (currentUnreachableRangeIx < unreachableRanges.Length && instrOffset > unreachableRanges[currentUnreachableRangeIx].EndOffset)
{
currentUnreachableRangeIx++;
}
// determine if the unreachable
bool isUnreachable = false;
if (currentUnreachableRangeIx < unreachableRanges.Length)
{
ReachabilityHelper.UnreachableRange range = unreachableRanges[currentUnreachableRangeIx];
isUnreachable = instrOffset >= range.StartOffset && instrOffset <= range.EndOffset;
}
// Check is both reachable, _and_ coverable
if (isUnreachable || _cecilSymbolHelper.SkipNotCoverableInstruction(method, currentInstruction))
{
index++;
continue;
}
if (sequencePoint != null && !sequencePoint.IsHidden)
{
if (_cecilSymbolHelper.SkipInlineAssignedAutoProperty(_parameters.SkipAutoProps, method,
currentInstruction) || IsInsideExcludedMethodSection(sequencePoint))
{
index++;
continue;
}
Instruction firstInjectedInstrumentedOpCode = AddInstrumentationCode(method, processor, currentInstruction, sequencePoint);
targetsMap.Add(currentInstruction.Offset, firstInjectedInstrumentedOpCode);
index += 2;
}
foreach (BranchPoint 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;
Instruction firstInjectedInstrumentedOpCode = AddInstrumentationCode(method, processor, currentInstruction, branchTarget);
if (!targetsMap.ContainsKey(currentInstruction.Offset))
targetsMap.Add(currentInstruction.Offset, firstInjectedInstrumentedOpCode);
index += 2;
}
index++;
}
foreach (Instruction bodyInstruction in processor.Body.Instructions)
ReplaceInstructionTarget(bodyInstruction, targetsMap);
foreach (ExceptionHandler handler in processor.Body.ExceptionHandlers)
ReplaceExceptionHandlerBoundary(handler, targetsMap);
method.Body.OptimizeMacros();
}
private Instruction AddInstrumentationCode(MethodDefinition method, ILProcessor processor, Instruction instruction, SequencePoint sequencePoint)
{
if (!_result.Documents.TryGetValue(_sourceRootTranslator.ResolveFilePath(sequencePoint.Document.Url), out Document document))
{
document = new Document { Path = _sourceRootTranslator.ResolveFilePath(sequencePoint.Document.Url) };
document.Index = _result.Documents.Count;
_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 });
}
_result.HitCandidates.Add(new HitCandidate(false, document.Index, sequencePoint.StartLine, sequencePoint.EndLine));
return AddInstrumentationInstructions(method, processor, instruction, _result.HitCandidates.Count - 1);
}
private Instruction AddInstrumentationCode(MethodDefinition method, ILProcessor processor, Instruction instruction, BranchPoint branchPoint)
{
if (!_result.Documents.TryGetValue(_sourceRootTranslator.ResolveFilePath(branchPoint.Document), out Document document))
{
document = new Document { Path = _sourceRootTranslator.ResolveFilePath(branchPoint.Document) };
document.Index = _result.Documents.Count;
_result.Documents.Add(document.Path, document);
}
var key = new BranchKey(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
}
);
if (IsCompilerGenerated(method.DeclaringType))
{
if (_branchesInCompiledGeneratedClass == null)
{
_branchesInCompiledGeneratedClass = new List<string>();
}
if (!_branchesInCompiledGeneratedClass.Contains(method.FullName))
{
_branchesInCompiledGeneratedClass.Add(method.FullName);
}
}
}
_result.HitCandidates.Add(new HitCandidate(true, document.Index, branchPoint.StartLine, (int)branchPoint.Ordinal));
return AddInstrumentationInstructions(method, processor, instruction, _result.HitCandidates.Count - 1);
}
private Instruction AddInstrumentationInstructions(MethodDefinition method, ILProcessor processor, Instruction instruction, int hitEntryIndex)
{
if (_customTrackerRecordHitMethod == null)
{
string recordHitMethodName;
if (_parameters.SingleHit)
{
recordHitMethodName = _isCoreLibrary
? nameof(ModuleTrackerTemplate.RecordSingleHitInCoreLibrary)
: nameof(ModuleTrackerTemplate.RecordSingleHit);
}
else
{
recordHitMethodName = _isCoreLibrary
? nameof(ModuleTrackerTemplate.RecordHitInCoreLibrary)
: nameof(ModuleTrackerTemplate.RecordHit);
}
_customTrackerRecordHitMethod = new MethodReference(
recordHitMethodName, method.Module.TypeSystem.Void, _customTrackerTypeDef);
_customTrackerRecordHitMethod.Parameters.Add(new ParameterDefinition("hitLocationIndex", ParameterAttributes.None, method.Module.TypeSystem.Int32));
}
var indxInstr = Instruction.Create(OpCodes.Ldc_I4, hitEntryIndex);
var callInstr = Instruction.Create(OpCodes.Call, _customTrackerRecordHitMethod);
processor.InsertBefore(instruction, callInstr);
processor.InsertBefore(callInstr, indxInstr);
return indxInstr;
}
private static void ReplaceInstructionTarget(Instruction instruction, IDictionary<int, Instruction> targetsMap)
{
if (instruction.Operand is Instruction operandInstruction)
{
if (targetsMap.TryGetValue(operandInstruction.Offset, out Instruction newTarget))
{
instruction.Operand = newTarget;
}
}
else if (instruction.Operand is Instruction[] operandInstructions)
{
for (int i = 0; i < operandInstructions.Length; i++)
{
if (targetsMap.TryGetValue(operandInstructions[i].Offset, out Instruction newTarget))
operandInstructions[i] = newTarget;
}
}
}
private static void ReplaceExceptionHandlerBoundary(ExceptionHandler handler, IDictionary<int, Instruction> targetsMap)
{
if (handler.FilterStart is not null && targetsMap.TryGetValue(handler.FilterStart.Offset, out Instruction newFilterStart))
handler.FilterStart = newFilterStart;
if (handler.HandlerEnd is not null && targetsMap.TryGetValue(handler.HandlerEnd.Offset, out Instruction newHandlerEnd))
handler.HandlerEnd = newHandlerEnd;
if (handler.HandlerStart is not null && targetsMap.TryGetValue(handler.HandlerStart.Offset, out Instruction newHandlerStart))
handler.HandlerStart = newHandlerStart;
if (handler.TryEnd is not null && targetsMap.TryGetValue(handler.TryEnd.Offset, out Instruction newTryEnd))
handler.TryEnd = newTryEnd;
if (handler.TryStart is not null && targetsMap.TryGetValue(handler.TryStart.Offset, out Instruction newTryStart))
handler.TryStart = newTryStart;
}
private bool IsExcludeAttribute(CustomAttribute customAttribute)
{
return Array.IndexOf(_excludedAttributes, customAttribute.AttributeType.Name) != -1 ||
Array.IndexOf(_excludedAttributes, customAttribute.AttributeType.FullName) != -1;
}
private static MethodBody GetMethodBody(MethodDefinition method)
{
try
{
return method.HasBody ? method.Body : null;
}
catch
{
return null;
}
}
private bool IsInsideExcludedMethodSection(SequencePoint sequencePoint)
{
if (_excludedMethodSections is null) return false;
bool IsInsideExcludedSection(SequencePoint firstSequencePoint, SequencePoint lastSequencePoint)
{
bool isInsideSameSourceFile = sequencePoint.Document.Url.Equals(firstSequencePoint.Document.Url);
bool isInsideExcludedMethod = sequencePoint.StartLine >= Math.Min(firstSequencePoint.StartLine, firstSequencePoint.EndLine) &&
sequencePoint.StartLine <= Math.Max(lastSequencePoint.StartLine, lastSequencePoint.EndLine);
return isInsideExcludedMethod && isInsideSameSourceFile;
}
return _excludedMethodSections
.Where(x => x is { firstSequencePoint: not null, lastSequencePoint: not null })
.Any(x => IsInsideExcludedSection(x.firstSequencePoint, x.lastSequencePoint));
}
private void AnalyzeCompileGeneratedTypesForExcludedMethod(MethodDefinition method)
{
IEnumerable<TypeDefinition> referencedTypes = method.CustomAttributes.Where(x => x.HasConstructorArguments)
.SelectMany(x => x.ConstructorArguments.Select(y => y.Value as TypeDefinition));
referencedTypes.ToList().ForEach(x =>
x?.Methods.Where(y => y.FullName.Contains("MoveNext")).ToList().ForEach(CacheExcludedMethodSection)
);
}
private void CacheExcludedMethodSection(MethodDefinition method)
{
_excludedMethodSections.Add((
method.DebugInformation.SequencePoints.FirstOrDefault(x => !x.IsHidden),
method.DebugInformation.SequencePoints.LastOrDefault(x => !x.IsHidden)));
}
private static IEnumerable<string> CollectLambdaMethodsInsideLocalFunction(MethodDefinition methodDefinition)
{
if (!methodDefinition.Name.Contains(">g__")) yield break;
foreach (Instruction instruction in methodDefinition.Body.Instructions.ToList())
{
if (instruction.OpCode == OpCodes.Ldftn && instruction.Operand is MethodReference mr &&
mr.Name.Contains(">b__"))
{
yield return mr.FullName;
}
}
}
/// <summary>
/// A custom importer created specifically to allow the instrumentation of System.Private.CoreLib by
/// removing the external references to netstandard that are generated when instrumenting a typical
/// assembly.
/// </summary>
private class CoreLibMetadataImporterProvider : IMetadataImporterProvider
{
public IMetadataImporter GetMetadataImporter(ModuleDefinition module)
{
return new CoreLibMetadataImporter(module);
}
private class CoreLibMetadataImporter : IMetadataImporter
{
private readonly ModuleDefinition _module;
private readonly DefaultMetadataImporter _defaultMetadataImporter;
public CoreLibMetadataImporter(ModuleDefinition module)
{
_module = module;
_defaultMetadataImporter = new DefaultMetadataImporter(module);
}
public AssemblyNameReference ImportReference(AssemblyNameReference reference)
{
return _defaultMetadataImporter.ImportReference(reference);
}
public TypeReference ImportReference(TypeReference type, IGenericParameterProvider context)
{
TypeReference importedRef = _defaultMetadataImporter.ImportReference(type, context);
importedRef.GetElementType().Scope = _module.TypeSystem.CoreLibrary;
return importedRef;
}
public FieldReference ImportReference(FieldReference field, IGenericParameterProvider context)
{
FieldReference importedRef = _defaultMetadataImporter.ImportReference(field, context);
importedRef.FieldType.GetElementType().Scope = _module.TypeSystem.CoreLibrary;
return importedRef;
}
public MethodReference ImportReference(MethodReference method, IGenericParameterProvider context)
{
MethodReference importedRef = _defaultMetadataImporter.ImportReference(method, context);
importedRef.DeclaringType.GetElementType().Scope = _module.TypeSystem.CoreLibrary;
foreach (ParameterDefinition parameter in importedRef.Parameters)
{
if (parameter.ParameterType.Scope == _module.TypeSystem.CoreLibrary)
{
continue;
}
parameter.ParameterType.GetElementType().Scope = _module.TypeSystem.CoreLibrary;
}
if (importedRef.ReturnType.Scope != _module.TypeSystem.CoreLibrary)
{
importedRef.ReturnType.GetElementType().Scope = _module.TypeSystem.CoreLibrary;
}
return importedRef;
}
}
}
}
// Exclude files helper https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.filesystemglobbing.matcher?view=aspnetcore-2.2
internal class ExcludedFilesHelper
{
readonly Matcher _matcher;
public ExcludedFilesHelper(string[] excludes, ILogger logger)
{
if (excludes != null && excludes.Length > 0)
{
_matcher = new Matcher();
foreach (string excludeRule in excludes)
{
if (excludeRule is null)
{
continue;
}
#pragma warning disable IDE0057 // Use range operator
_matcher.AddInclude(Path.IsPathRooted(excludeRule) ? excludeRule.Substring(Path.GetPathRoot(excludeRule).Length) : excludeRule);
#pragma warning restore IDE0057 // Use range operator
}
}
}
public bool Exclude(string sourceFile)
{
if (_matcher is null || sourceFile is null)
return false;
// We strip out drive because it doesn't work with globbing
#pragma warning disable IDE0057 // Use range operator
return _matcher.Match(Path.IsPathRooted(sourceFile) ? sourceFile.Substring(Path.GetPathRoot(sourceFile).Length) : sourceFile).HasMatches;
#pragma warning restore IDE0057 // Use range operator
}
}
}