Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
"reportgenerator"
],
"rollForward": false
},
"dotnet-ilverify": {
"version": "10.0.14",
"commands": [
"ilverify"
],
"rollForward": false
}
}
}
}
7 changes: 4 additions & 3 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ This is a .NET based repository that contains the coverlet projects for code cov
- Always ask for explicit approval before running any tests (`dotnet test`, integration tests, test scripts, coverage test runs, or equivalent). User prefers to run tests manually and does not want me to execute test runs unless explicitly requested.
- Create a single, well-organized proposal or resolution document per issue, located in `Documentation/Plans/`. This folder is Git-ignored and local-only; documents are NOT uploaded to GitHub.
- Stop deep analysis once effort/usage for a topic reaches about 60%, and keep investigation focused and efficient.
- Use ILVerify as a local dotnet tool for future IL investigations.

## Code Standards

Expand Down Expand Up @@ -181,8 +182,7 @@ When mocking interfaces, **reference actual adapter implementations** in the cod
- `src/coverlet.console/Logging/ConsoleLogger.cs` - Shows coverlet's internal `ILogger` implementation.
- `src/coverlet.core/Abstractions/ILogger.cs` - Coverlet's internal logger interface.

**Example from CoverletLoggerAdapter.cs:**
// Shows actual MTP ILogger usage - simple methods, no EventId
**Example from CoverletLoggerAdapter.cs:**// Shows actual MTP ILogger usage - simple methods, no EventId
public void LogInformation(string message, bool important = false)
{
if (important)
Expand All @@ -193,7 +193,8 @@ public void LogInformation(string message, bool important = false)
{
_logger.LogInformation(message);
}
}### Test Generation Verification (Critical Rule)
}
### Test Generation Verification (Critical Rule)

**Before generating any test, you MUST:**

Expand Down
6 changes: 4 additions & 2 deletions coverlet.slnx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<Solution>
<Folder Name="/Solution Items/">
<File Path=".config/dotnet-tools.json" />
<File Path=".editorconfig" />
<File Path=".github/copilot-instructions.md" />
<File Path=".gitignore" />
Expand All @@ -12,13 +13,14 @@
<File Path="eng/build-legacy.yml" />
<File Path="eng/build.yml" />
<File Path="global.json" />
<File Path="src/legacy/dotnet-tools-legacy.json" />
<File Path="src/legacy/global-legacy.json" />
</Folder>
<Folder Name="/src/">
<Project Path="src/coverlet.console/coverlet.console.csproj" />
<Project Path="src/coverlet.core/coverlet.core.csproj" />
<Project Path="src/coverlet.template/coverlet.template.csproj" />
<Project Path="src/coverlet.MTP/coverlet.MTP.csproj" />
<Project Path="src/coverlet.template/coverlet.template.csproj" />
<Project Path="src/legacy/coverlet.collector/coverlet.collector.csproj" />
<Project Path="src/legacy/coverlet.msbuild.tasks/coverlet.msbuild.tasks.csproj" />
</Folder>
Expand All @@ -35,8 +37,8 @@
<BuildDependency Project="src/legacy/coverlet.msbuild.tasks/coverlet.msbuild.tasks.csproj" />
</Project>
<Project Path="test/coverlet.integration.determisticbuild/coverlet.integration.determisticbuild.csproj" />
<Project Path="test/coverlet.integration.tests/coverlet.integration.tests.csproj" />
<Project Path="test/coverlet.integration.template/coverlet.integration.template.csproj" />
<Project Path="test/coverlet.integration.tests/coverlet.integration.tests.csproj" />
<Project Path="test/coverlet.msbuild.tasks.tests/coverlet.msbuild.tasks.tests.csproj" />
<Project Path="test/coverlet.MTP.tests/coverlet.MTP.tests.csproj" />
<Project Path="test/coverlet.MTP.validation.tests/coverlet.MTP.validation.tests.csproj" />
Expand Down
3 changes: 3 additions & 0 deletions eng/build-legacy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ steps:
- script: copy src\legacy\global-legacy.json global.json
displayName: copy global.json from src/legacy

- script: copy src\legacy\dotnet-tools-legacy.json .config\dotnet-tools.json
displayName: copy dotnet-tools.json from src/legacy

- task: UseDotNet@2
inputs:
version: 8.0.427
Expand Down
130 changes: 96 additions & 34 deletions src/coverlet.core/Instrumentation/Instrumenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,6 @@ 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>();
Expand Down Expand Up @@ -853,11 +852,27 @@ private void InstrumentIL(MethodDefinition method)
// for the first original instruction instead of its intended target.
List<Instruction> originalInstructions = [.. processor.Body.Instructions];

// Trampolines are appended at method end. If any exception-handler boundary is open-ended
// (null end marker), appending instructions extends that protected region and can pull the
// trampoline into a try/finally handler, yielding invalid IL in optimized loop shapes.
bool canUseBranchTrampolines = !method.Body.ExceptionHandlers.Any(h =>
(h.TryStart != null && h.TryEnd == null) ||
(h.HandlerStart != null && h.HandlerEnd == null));

// In optimized IL, the conditional branch for `if` can target a compiler-emitted NOP placed
// immediately before TryStart. Injecting a taken-branch counter before that NOP while we are
// forced to use inline fallback (no trampoline) can produce invalid IL in release loops.
// Track these offsets so we can skip only that unsafe taken-branch injection shape.
var offsetsImmediatelyBeforeTryStart = new HashSet<int>(
method.Body.ExceptionHandlers
.Where(h => h.TryStart?.Previous != null)
.Select(h => h.TryStart.Previous.Offset));

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];
Instruction currentInstruction = originalInstructions[n];
SequencePoint sequencePoint = method.DebugInformation.GetSequencePoint(currentInstruction);
IEnumerable<BranchPoint> targetedBranchPoints = branchPoints.Where(p => p.EndOffset == currentInstruction.Offset);

Expand All @@ -879,7 +894,6 @@ private void InstrumentIL(MethodDefinition method)
// Check is both reachable, _and_ coverable
if (isUnreachable || _cecilSymbolHelper.SkipNotCoverableInstruction(method, currentInstruction))
{
index++;
continue;
}

Expand All @@ -888,14 +902,11 @@ private void InstrumentIL(MethodDefinition method)
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)
Expand All @@ -916,8 +927,6 @@ private void InstrumentIL(MethodDefinition method)
Instruction firstInjectedInstrumentedOpCode = AddInstrumentationCode(method, processor, currentInstruction, branchTarget);
if (!targetsMap.ContainsKey(currentInstruction.Offset))
targetsMap.Add(currentInstruction.Offset, firstInjectedInstrumentedOpCode);

index += 2;
}
else
{
Expand All @@ -944,16 +953,38 @@ private void InstrumentIL(MethodDefinition method)
insideExceptionHandlerOffsets.Contains(branchTarget.Offset) ||
insideExceptionHandlerOffsets.Contains(branchTarget.EndOffset);

if (crossesExceptionBoundary || !targetReachableByFallThrough)
if (!canUseBranchTrampolines || crossesExceptionBoundary || !targetReachableByFallThrough)
{
// Inline fallback: preserves valid IL. Counter is inserted before the jump target so
// it fires on every arrival, which may produce false-positive counts for patterns like
// `if` without `else` inside exception-handler regions (e.g. async state machines).
// When the target is the instruction immediately before TryStart and trampolines are
// unavailable, use a branch-local trampoline so both branch paths are still registered
// without injecting a taken counter at the unsafe pre-TryStart location.
if (!canUseBranchTrampolines && offsetsImmediatelyBeforeTryStart.Contains(currentInstruction.Offset))
{
Instruction branchInstruction = originalInstructions.FirstOrDefault(i => i.Offset == branchTarget.Offset);
if (branchInstruction is not null &&
branchInstruction.Next is not null &&
branchInstruction.Operand is Instruction)
{
Instruction trampolineTarget = targetsMap.TryGetValue(currentInstruction.Offset, out Instruction firstCounter)
? firstCounter
: currentInstruction;
Instruction localTrampolineStart = AddLocalBranchTrampolineCode(method, processor, branchTarget, branchInstruction, trampolineTarget);
Comment thread
Bertk marked this conversation as resolved.
Resolved
#if NETSTANDARD2_0
if (!branchRedirectMap.ContainsKey((branchTarget.Offset, branchTarget.Path)))
branchRedirectMap.Add((branchTarget.Offset, branchTarget.Path), localTrampolineStart);
#else
branchRedirectMap.TryAdd((branchTarget.Offset, branchTarget.Path), localTrampolineStart);
#endif
continue;
}
}

Instruction firstInjectedInstrumentedOpCode = AddInstrumentationCode(method, processor, currentInstruction, branchTarget);
if (!targetsMap.ContainsKey(currentInstruction.Offset))
targetsMap.Add(currentInstruction.Offset, firstInjectedInstrumentedOpCode);

index += 2;
}
else
{
Expand All @@ -979,8 +1010,7 @@ private void InstrumentIL(MethodDefinition method)
}
}

index++;
}
}

foreach (Instruction bodyInstruction in originalInstructions)
ReplaceInstructionTarget(bodyInstruction, targetsMap, branchRedirectMap);
Expand Down Expand Up @@ -1089,7 +1119,55 @@ private void EnsureCustomTrackerRecordHitMethod(MethodDefinition method)

private Instruction AddBranchTrampolineCode(MethodDefinition method, ILProcessor processor, BranchPoint branchPoint, Instruction trampolineTarget)
{
if (!_result.Documents.TryGetValue(_sourceRootTranslator.ResolveFilePath(branchPoint.Document), out Document document))
RegisterBranchHitCandidate(method, branchPoint, out Document document);

_result.HitCandidates.Add(new HitCandidate(true, document.Index, branchPoint.StartLine, (int)branchPoint.Ordinal));

EnsureCustomTrackerRecordHitMethod(method);

// Append a self-contained trampoline block at the end of the method body:
// ldc.i4 <hitEntryIndex>
// call RecordHit
// br <trampolineTarget> ← jump to the normal entry point of the destination
// The trampoline is only reachable when the specific conditional jump is taken, so
// its counter does not fire on fall-through arrivals at the same destination.
var indxInstr = Instruction.Create(OpCodes.Ldc_I4, _result.HitCandidates.Count - 1);
var callInstr = Instruction.Create(OpCodes.Call, _customTrackerRecordHitMethod);
var brInstr = Instruction.Create(OpCodes.Br, trampolineTarget);

processor.Append(indxInstr);
processor.Append(callInstr);
processor.Append(brInstr);

return indxInstr;
}

private Instruction AddLocalBranchTrampolineCode(MethodDefinition method, ILProcessor processor, BranchPoint branchPoint,
Instruction branchInstruction, Instruction trampolineTarget)
{
RegisterBranchHitCandidate(method, branchPoint, out Document document);

_result.HitCandidates.Add(new HitCandidate(true, document.Index, branchPoint.StartLine, (int)branchPoint.Ordinal));

EnsureCustomTrackerRecordHitMethod(method);

Instruction fallThroughTarget = branchInstruction.Next;
var skipTrampolineInstr = Instruction.Create(OpCodes.Br, fallThroughTarget);
var indxInstr = Instruction.Create(OpCodes.Ldc_I4, _result.HitCandidates.Count - 1);
var callInstr = Instruction.Create(OpCodes.Call, _customTrackerRecordHitMethod);
var brInstr = Instruction.Create(OpCodes.Br, trampolineTarget);

processor.InsertBefore(fallThroughTarget, brInstr);
processor.InsertBefore(brInstr, callInstr);
processor.InsertBefore(callInstr, indxInstr);
processor.InsertBefore(indxInstr, skipTrampolineInstr);

return indxInstr;
}

private void RegisterBranchHitCandidate(MethodDefinition method, BranchPoint branchPoint, out Document document)
{
if (!_result.Documents.TryGetValue(_sourceRootTranslator.ResolveFilePath(branchPoint.Document), out document))
{
document = new Document
{
Expand Down Expand Up @@ -1130,26 +1208,6 @@ private Instruction AddBranchTrampolineCode(MethodDefinition method, ILProcessor
}
}
}

_result.HitCandidates.Add(new HitCandidate(true, document.Index, branchPoint.StartLine, (int)branchPoint.Ordinal));

EnsureCustomTrackerRecordHitMethod(method);

// Append a self-contained trampoline block at the end of the method body:
// ldc.i4 <hitEntryIndex>
// call RecordHit
// br <trampolineTarget> ← jump to the normal entry point of the destination
// The trampoline is only reachable when the specific conditional jump is taken, so
// its counter does not fire on fall-through arrivals at the same destination.
var indxInstr = Instruction.Create(OpCodes.Ldc_I4, _result.HitCandidates.Count - 1);
var callInstr = Instruction.Create(OpCodes.Call, _customTrackerRecordHitMethod);
var brInstr = Instruction.Create(OpCodes.Br, trampolineTarget);

processor.Append(indxInstr);
processor.Append(callInstr);
processor.Append(brInstr);

return indxInstr;
}

private Instruction AddInstrumentationInstructions(MethodDefinition method, ILProcessor processor, Instruction instruction, int hitEntryIndex)
Expand Down Expand Up @@ -1207,6 +1265,10 @@ private static void ReplaceExceptionHandlerBoundary(ExceptionHandler handler, ID
if (handler.TryEnd is not null && targetsMap.TryGetValue(handler.TryEnd.Offset, out Instruction newTryEnd))
handler.TryEnd = newTryEnd;

// Keep exception boundaries coordinated with branch-target rewriting.
// When a counter is inserted before TryStart and branch targets are rewritten to that
// counter, TryStart must move as well so intra-try back-edges remain inside the protected
// region (for example release-optimized do/while loops inside try/finally).
if (handler.TryStart is not null && targetsMap.TryGetValue(handler.TryStart.Offset, out Instruction newTryStart))
handler.TryStart = newTryStart;
}
Expand Down
20 changes: 20 additions & 0 deletions src/legacy/dotnet-tools-legacy.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-reportgenerator-globaltool": {
"version": "5.5.11",
"commands": [
"reportgenerator"
],
"rollForward": false
},
"dotnet-ilverify": {
"version": "9.0.22",
"commands": [
"ilverify"
],
"rollForward": false
}
}
}
Loading
Loading