From b0b4190c995017d28c8b2cca5cad4f2d919591ff Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:40:01 +0100 Subject: [PATCH 01/14] Bump dotnet-reportgenerator-globaltool from 5.5.11 to 5.5.12 (#2062) --- updated-dependencies: - dependency-name: dotnet-reportgenerator-globaltool dependency-version: 5.5.12 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .config/dotnet-tools.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 074c30ebb..696628eb1 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "dotnet-reportgenerator-globaltool": { - "version": "5.5.11", + "version": "5.5.12", "commands": [ "reportgenerator" ], From 98d291d713dde46a58ee1dcf7ce832bdf6c2b781 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:41:26 +0100 Subject: [PATCH 02/14] Bump danielpalme/ReportGenerator-GitHub-Action from 5.5.11 to 5.5.12 (#2061) Bumps [danielpalme/ReportGenerator-GitHub-Action](https://github.com/danielpalme/reportgenerator-github-action) from 5.5.11 to 5.5.12. - [Release notes](https://github.com/danielpalme/reportgenerator-github-action/releases) - [Commits](https://github.com/danielpalme/reportgenerator-github-action/compare/5.5.11...5.5.12) --- updated-dependencies: - dependency-name: danielpalme/ReportGenerator-GitHub-Action dependency-version: 5.5.12 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/dotnet.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 1f596e77f..c94b3feb1 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -147,7 +147,7 @@ jobs: # MSBUILDDISABLENODEREUSE: 1 - name: ReportGenerator - uses: danielpalme/ReportGenerator-GitHub-Action@5.5.11 + uses: danielpalme/ReportGenerator-GitHub-Action@5.5.12 if: success() && matrix.os == 'windows-latest' with: reports: ./artifacts/reports/**/*.cobertura.xml From ea74a473c5c0f5ef7dffb425584da9a72a1769dd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:42:21 +0100 Subject: [PATCH 03/14] Bump github/codeql-action from 4.38.2 to 4.39.1 (#2060) Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.38.2 to 4.39.1. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/v4.38.2...v4.39.1) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: 4.39.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index a8747846a..ea8664ee6 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -49,7 +49,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v4.38.2 + uses: github/codeql-action/init@v4.39.1 with: languages: ${{ matrix.language }} build-mode: "manual" @@ -77,6 +77,6 @@ jobs: dotnet build coverlet.slnx --configuration Debug - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4.38.2 + uses: github/codeql-action/analyze@v4.39.1 with: category: "/language:${{matrix.language}}" From 1d9db3aacfbf61e1b2b4d9190715a13ba694d8c9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:20:11 +0100 Subject: [PATCH 04/14] Bump Microsoft.Testing.Extensions.AzureDevOpsReport from 2.5.1 to 2.5.2 (#2066) --- updated-dependencies: - dependency-name: Microsoft.Testing.Extensions.AzureDevOpsReport dependency-version: 2.5.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 42b941104..a0550461e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ 18.11.0 4.0.2 4.0.1 - 2.5.1 + 2.5.2 4.21.0 10.0.14 9.0.22 From 483ff5ac667a2d20fc4f3976251aa8f5335cc9ba Mon Sep 17 00:00:00 2001 From: Bert Date: Sun, 1 Nov 2026 15:56:57 +0100 Subject: [PATCH 05/14] Prevent invalid IL from branch trampolines (#2067) * Prevent invalid IL from branch trampolines Detect unsafe exception-handler boundaries and fall back to inline instrumentation. Preserve original `TryStart` boundaries to avoid invalid loop and `try/finally` IL. Add issue #2058 regression coverage, sample control-flow methods, and JIT-preparation validation with diagnostic IL output. * Fix EH boundaries for instrumented loop back-edges Update exception-handler boundary rewriting so `TryStart` follows inserted branch-target instructions, preserving intra-try back-edges in optimized `do/while` loops. Add Issue 2058 release-instrumentation coverage and a `try/finally` loop regression sample. * Prevent invalid IL near handler starts Add ILVerify 10.0.14 as a local tool and recommend it for IL investigations. Track instructions immediately preceding exception-handler `TryStart` offsets and skip unsafe taken-branch counter injection when trampolines are unavailable, preserving inline fallback for other cases. * use runtime specific dotnet tool versions * Fix path for dotnet-tools.json copy script * Fix branch instrumentation near EH boundaries Use local branch trampolines when standard trampolines are unavailable before exception-handler boundaries. Refactor branch candidate registration, track local trampoline redirections, and preserve branch hit tracking across netstandard2.0. Extend Issue 2058 coverage tests to verify both branch paths and filter recorded branch entries with LINQ. * Iterate instrumentation over original IL Process the pre-instrumentation instruction snapshot with a stable index instead of traversing the mutable instruction list. Remove manual index adjustments so injected instructions cannot alter iteration or cause original instructions to be skipped or processed incorrectly. Preserve target mapping and instruction-target replacement after instrumentation. --- .config/dotnet-tools.json | 9 +- .github/copilot-instructions.md | 7 +- coverlet.slnx | 6 +- eng/build-legacy.yml | 3 + .../Instrumentation/Instrumenter.cs | 130 ++++++++++++----- src/legacy/dotnet-tools-legacy.json | 20 +++ .../Coverage/CoverageTests.Issue2058.cs | 136 ++++++++++++++++++ .../Samples/Instrumentation.Issue2058.cs | 109 ++++++++++++++ 8 files changed, 380 insertions(+), 40 deletions(-) create mode 100644 src/legacy/dotnet-tools-legacy.json create mode 100644 test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs create mode 100644 test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 696628eb1..f3a920f15 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -8,6 +8,13 @@ "reportgenerator" ], "rollForward": false + }, + "dotnet-ilverify": { + "version": "10.0.14", + "commands": [ + "ilverify" + ], + "rollForward": false } } -} \ No newline at end of file +} diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index fc6e0d894..f8db1f6ad 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -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 @@ -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) @@ -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:** diff --git a/coverlet.slnx b/coverlet.slnx index fce99a3c9..f9e70dfd4 100644 --- a/coverlet.slnx +++ b/coverlet.slnx @@ -1,5 +1,6 @@ + @@ -12,13 +13,14 @@ + - + @@ -35,8 +37,8 @@ - + diff --git a/eng/build-legacy.yml b/eng/build-legacy.yml index 5723713d9..2d5d78b3f 100644 --- a/eng/build-legacy.yml +++ b/eng/build-legacy.yml @@ -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 diff --git a/src/coverlet.core/Instrumentation/Instrumenter.cs b/src/coverlet.core/Instrumentation/Instrumenter.cs index a51e62bb0..7a1ba6d19 100644 --- a/src/coverlet.core/Instrumentation/Instrumenter.cs +++ b/src/coverlet.core/Instrumentation/Instrumenter.cs @@ -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 branchPoints = _cecilSymbolHelper.GetBranchPoints(method); IDictionary targetsMap = new Dictionary(); @@ -853,11 +852,27 @@ private void InstrumentIL(MethodDefinition method) // for the first original instruction instead of its intended target. List 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( + method.Body.ExceptionHandlers + .Where(h => h.TryStart?.Previous != null) + .Select(h => h.TryStart.Previous.Offset)); + System.Collections.Immutable.ImmutableArray 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 targetedBranchPoints = branchPoints.Where(p => p.EndOffset == currentInstruction.Offset); @@ -879,7 +894,6 @@ private void InstrumentIL(MethodDefinition method) // Check is both reachable, _and_ coverable if (isUnreachable || _cecilSymbolHelper.SkipNotCoverableInstruction(method, currentInstruction)) { - index++; continue; } @@ -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) @@ -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 { @@ -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); +#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 { @@ -979,8 +1010,7 @@ private void InstrumentIL(MethodDefinition method) } } - index++; - } + } foreach (Instruction bodyInstruction in originalInstructions) ReplaceInstructionTarget(bodyInstruction, targetsMap, branchRedirectMap); @@ -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 + // call RecordHit + // br ← 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 { @@ -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 - // call RecordHit - // br ← 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) @@ -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; } diff --git a/src/legacy/dotnet-tools-legacy.json b/src/legacy/dotnet-tools-legacy.json new file mode 100644 index 000000000..6c2bf7b4f --- /dev/null +++ b/src/legacy/dotnet-tools-legacy.json @@ -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 + } + } +} diff --git a/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs b/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs new file mode 100644 index 000000000..d5d591e40 --- /dev/null +++ b/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs @@ -0,0 +1,136 @@ +// 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.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using Coverlet.Core; +using Coverlet.Core.CoverageSamples.Tests; +using Coverlet.Core.Tests; +using Coverlet.Tests.Utils; +using Xunit; + +namespace Coverlet.CoreCoverage.Tests +{ + public partial class CoverageTests + { + [Theory] + [InlineData(nameof(Issue2058.WhileTrue_IfThenTryFinally))] + [InlineData(nameof(Issue2058.WhileTrue_TryFinallyIfTryFinally))] + [InlineData(nameof(Issue2058.WhileTrue_LockIfLock))] + [InlineData(nameof(Issue2058.TryFinally_DoWhileBackEdge))] + public void Issue2058_ReleaseInstrumentation_PrepareMethod_DoesNotThrow(string methodName) + { + BuildConfiguration configuration = TestUtils.GetAssemblyBuildConfiguration(); + string path = Path.GetTempFileName(); + try + { + FunctionExecutor.Run(async (string[] pathSerialize) => + { + await TestInstrumentationHelper.Run(instance => + { + MethodInfo instrumentedMethod = instance.GetType().GetMethod(methodName); + Assert.NotNull(instrumentedMethod); + + MethodInfo originalMethod = typeof(Issue2058).GetMethod(methodName); + Assert.NotNull(originalMethod); + + string ilDumpPath = Path.Combine(Path.GetDirectoryName(pathSerialize[0]), + $"Issue2058.{configuration}.{methodName}.il.txt"); + File.WriteAllText(ilDumpPath, + BuildIlDiagnostic(methodName, configuration, originalMethod, instrumentedMethod)); + + Exception exception = Record.Exception(() => RuntimeHelpers.PrepareMethod(instrumentedMethod.MethodHandle)); + Assert.True(exception is null, + $"Expected JIT preparation to succeed for {methodName} in {configuration}. " + + $"IL dump written to '{ilDumpPath}'. Exception: {exception}"); + return Task.CompletedTask; + }, persistPrepareResultToFile: pathSerialize[0]); + + return 0; + + }, [path]); + + CoverageResult result = TestInstrumentationHelper.GetCoverageResult(path); + Assert.True(result.IsPresent("Instrumentation.Issue2058.cs")); + + AssertMethodHasBothBranchPaths(result, methodName); + } + finally + { + File.Delete(path); + } + } + + private static void AssertMethodHasBothBranchPaths(CoverageResult result, string methodName) + { + var branches = result.Document("Instrumentation.Issue2058.cs").Branches.Values + .Where(b => b.Method.Contains($"::{methodName}(", StringComparison.Ordinal)) + .ToList(); + + Assert.NotEmpty(branches); + Assert.Contains(branches, b => b.Path == 0); + Assert.Contains(branches, b => b.Path == 1); + } + + private static string BuildIlDiagnostic(string methodName, BuildConfiguration configuration, MethodInfo originalMethod, MethodInfo instrumentedMethod) + { + var builder = new StringBuilder(); + builder.AppendLine($"Method: {methodName}"); + builder.AppendLine($"Configuration: {configuration}"); + builder.AppendLine($"Original assembly: {originalMethod.Module.Assembly.Location}"); + builder.AppendLine($"Instrumented assembly: {instrumentedMethod.Module.Assembly.Location}"); + builder.AppendLine(); + builder.AppendLine("Original IL:"); + AppendMethodBody(builder, originalMethod); + builder.AppendLine(); + builder.AppendLine("Instrumented IL:"); + AppendMethodBody(builder, instrumentedMethod); + return builder.ToString(); + } + + private static void AppendMethodBody(StringBuilder builder, MethodInfo method) + { + MethodBody body = method.GetMethodBody(); + if (body is null) + { + builder.AppendLine(""); + return; + } + + byte[] il = body.GetILAsByteArray(); + builder.AppendLine($"MaxStack: {body.MaxStackSize}"); + builder.AppendLine($"InitLocals: {body.InitLocals}"); + builder.AppendLine($"LocalCount: {body.LocalVariables.Count}"); + builder.AppendLine($"ILBytesLength: {il.Length}"); + builder.AppendLine($"ILBytes: {BitConverter.ToString(il)}"); + + if (body.ExceptionHandlingClauses.Count == 0) + { + builder.AppendLine("EH: "); + } + else + { + builder.AppendLine("EH:"); + foreach (ExceptionHandlingClause clause in body.ExceptionHandlingClauses) + { + string filter = clause.Flags == ExceptionHandlingClauseOptions.Filter + ? clause.FilterOffset.ToString() + : "n/a"; + string catchType = clause.Flags == ExceptionHandlingClauseOptions.Clause + ? clause.CatchType?.FullName ?? "null" + : "n/a"; + + builder.AppendLine( + $" {clause.Flags} try[{clause.TryOffset}..{clause.TryOffset + clause.TryLength}) " + + $"handler[{clause.HandlerOffset}..{clause.HandlerOffset + clause.HandlerLength}) " + + $"filter[{filter}] catchType[{catchType}]"); + } + } + } + } +} diff --git a/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs b/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs new file mode 100644 index 000000000..8e93a8d3e --- /dev/null +++ b/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs @@ -0,0 +1,109 @@ +namespace Coverlet.Core.CoverageSamples.Tests +{ + public sealed class Issue2058 + { + private readonly object _gate = new object(); + private int _n; + + public void WhileTrue_IfThenTryFinally() + { + while (true) + { + if (_n > 0) + { + _n--; + } + + try + { + _n++; + } + finally + { + _n++; + } + } + } + + public void WhileTrue_TryFinallyIfTryFinally() + { + while (true) + { + try + { + _n++; + } + finally + { + _n++; + } + + if (_n > 0) + { + _n--; + } + + try + { + _n++; + } + finally + { + _n++; + } + } + } + + public void WhileTrue_LockIfLock() + { + while (true) + { + lock (_gate) + { + _n++; + } + + if (_n > 0) + { + _n--; + } + + lock (_gate) + { + _n++; + } + } + } + + public void TryFinally_DoWhileBackEdge() + { + try + { + do + { + Tick(); + } + while (Continue()); + } + finally + { + Cleanup(); + } + } + + private void Tick() + { + _n++; + } + + private bool Continue() + { + return _n >= 0; + } + + private void Cleanup() + { + _n++; + } + } +} From 345b63cc18abe9587e353e75f882b59cbf3e372f Mon Sep 17 00:00:00 2001 From: Bert Date: Mon, 2 Nov 2026 09:48:19 +0100 Subject: [PATCH 06/14] update CHANGELOG.md (#2068) --- Documentation/Changelog.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Documentation/Changelog.md b/Documentation/Changelog.md index 8df07eb86..6d77ee7f3 100644 --- a/Documentation/Changelog.md +++ b/Documentation/Changelog.md @@ -7,12 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +## Release date xxxx-xx-xx +### Packages +coverlet.msbuild 10.1.1 +coverlet.console 10.1.1 +coverlet.collector 10.1.1 +coverlet.MTP 10.1.1 + ### Improvements - Add `IsReachable` to branch points, computed from the method's control-flow graph, and exclude unreachable branches from branch-coverage totals and from branch details in Cobertura, LCOV and OpenCover reports [#2056](https://github.com/coverlet-coverage/coverlet/pull/2056) by ### Fixed +- Fix Regression Prevent invalid IL from branch trampolines [#2067](https://github.com/coverlet-coverage/coverlet/pull/2067) - Fix Regression coverlet.MTP does not instrument local functions [#2046](https://github.com/coverlet-coverage/coverlet/pull/2046) ## Maintenance From f37bf3d1ea8795cc1bdc57b29ad2ec81d10c9f1a Mon Sep 17 00:00:00 2001 From: Bert Date: Tue, 3 Nov 2026 12:38:05 +0100 Subject: [PATCH 07/14] Narrow Dynamic Exclude Filters for Loaded Assemblies (#2069) * Narrow Dynamic Exclude Filters for Loaded Assemblies * Allow hyphen for assembly names --- Documentation/Changelog.md | 1 + Documentation/Coverlet.MTP.Integration.md | 10 ++++--- .../Configuration/CoverageConfiguration.cs | 7 ++++- .../Helpers/InstrumentationHelper.cs | 2 +- .../Helpers/ProcessAssemblyHelper.cs | 8 +++++ ...overageConfigurationDynamicExcludeTests.cs | 29 ++++++++++++++++--- .../Helpers/InstrumentationHelperTests.cs | 14 ++++++++- .../Helpers/ProcessAssemblyHelperTests.cs | 13 +++++++++ 8 files changed, 73 insertions(+), 11 deletions(-) diff --git a/Documentation/Changelog.md b/Documentation/Changelog.md index 6d77ee7f3..3e6770253 100644 --- a/Documentation/Changelog.md +++ b/Documentation/Changelog.md @@ -17,6 +17,7 @@ coverlet.MTP 10.1.1 ### Improvements - Add `IsReachable` to branch points, computed from the method's control-flow graph, and exclude unreachable branches from branch-coverage totals and from branch details in Cobertura, LCOV and OpenCover reports [#2056](https://github.com/coverlet-coverage/coverlet/pull/2056) by +- coverlet.MTP: Narrow Dynamic Exclude Filters for Loaded Assemblies [#2069](https://github.com/coverlet-coverage/coverlet/pull/2069) ### Fixed diff --git a/Documentation/Coverlet.MTP.Integration.md b/Documentation/Coverlet.MTP.Integration.md index 4b03134ea..b049d6ea5 100644 --- a/Documentation/Coverlet.MTP.Integration.md +++ b/Documentation/Coverlet.MTP.Integration.md @@ -108,12 +108,14 @@ When using command line options **without** a configuration file, the following - **Default Exclude Filters:** `[coverlet.*]*`, `[Microsoft.VisualStudio.TestPlatform.*]*`, `[testhost*]*` - **Default Exclude by Attributes:** `ExcludeFromCodeCoverage`, `ExcludeFromCodeCoverageAttribute`, `GeneratedCodeAttribute`, `CompilerGeneratedAttribute` -**Dynamic Exclude Filters (Assembly Naming Convention):** +**Dynamic Exclude Filters (Runtime Discovery):** -Coverlet.MTP also applies **dynamic exclusions** derived from the test assembly name and its namespace conventions at runtime. These are intended to automatically exclude common test infrastructure assemblies that follow standard naming patterns. +Coverlet.MTP also applies **dynamic exclusions** discovered at runtime from two sources: -> [!WARNING] -> **Assembly Naming Limitation:** Dynamic exclusions rely on the assembly name following conventional naming schemas (e.g., `MyApp.Tests`, `MyApp.UnitTests`, `MyApp.IntegrationTests`). Assemblies that **do not follow these naming conventions** will **not** be automatically excluded by the dynamic filter. In such cases, you must add explicit `--coverlet-exclude` filters manually. +- Runtime package/library names from `*.deps.json` +- Assemblies already loaded in the controller process (for example build/test extensions that may lock files before instrumentation) + +`deps.json` entries continue to use wildcard normalization for resilient matching. Loaded-assembly entries use **exact assembly-name filters** to avoid broad prefix exclusions. For example, a loaded assembly `MSS.Tools.xUnit` is excluded as `[MSS.Tools.xUnit]*` (not `[MSS.Tools.*]*`), which prevents accidental exclusion of a SUT like `MSS.Tools.Markdown`. **Configuration File Behavior (Authoritative Mode):** diff --git a/src/coverlet.MTP/Configuration/CoverageConfiguration.cs b/src/coverlet.MTP/Configuration/CoverageConfiguration.cs index e5f18a0af..9eddae0bc 100644 --- a/src/coverlet.MTP/Configuration/CoverageConfiguration.cs +++ b/src/coverlet.MTP/Configuration/CoverageConfiguration.cs @@ -187,9 +187,14 @@ private string[] BuildDynamicExcludeFilters() // such as Microsoft.Testing.Extensions.MSBuild that are held open before instrumentation). IReadOnlyList loadedNames = _processAssemblyHelper.GetLoadedAssemblyNames(simpleTestName); - IEnumerable dynamicFilters = depsNames.Concat(loadedNames) + IEnumerable depsFilters = depsNames .Select(Coverlet.Core.Helpers.ProcessAssemblyHelper.ToExcludeFilter); + IEnumerable loadedFilters = loadedNames + .Select(Coverlet.Core.Helpers.ProcessAssemblyHelper.ToExactExcludeFilter); + + IEnumerable dynamicFilters = depsFilters.Concat(loadedFilters); + IEnumerable merged = s_baselineExcludeFilters .Concat(dynamicFilters) .Distinct(StringComparer.OrdinalIgnoreCase); diff --git a/src/coverlet.core/Helpers/InstrumentationHelper.cs b/src/coverlet.core/Helpers/InstrumentationHelper.cs index e44708033..6e85e845d 100644 --- a/src/coverlet.core/Helpers/InstrumentationHelper.cs +++ b/src/coverlet.core/Helpers/InstrumentationHelper.cs @@ -390,7 +390,7 @@ public bool IsValidFilterExpression(string filter) if (filter.EndsWith("]")) return false; - if (new Regex(@"[^\w*]", s_regexOptions, TimeSpan.FromSeconds(10)).IsMatch(filter.Replace(".", "").Replace("?", "").Replace("[", "").Replace("]", ""))) + if (new Regex(@"[^\w*\-]", s_regexOptions, TimeSpan.FromSeconds(10)).IsMatch(filter.Replace(".", "").Replace("?", "").Replace("[", "").Replace("]", ""))) return false; return true; diff --git a/src/coverlet.core/Helpers/ProcessAssemblyHelper.cs b/src/coverlet.core/Helpers/ProcessAssemblyHelper.cs index 559e6ea49..030e26d91 100644 --- a/src/coverlet.core/Helpers/ProcessAssemblyHelper.cs +++ b/src/coverlet.core/Helpers/ProcessAssemblyHelper.cs @@ -96,6 +96,14 @@ internal static string ToExcludeFilter(string assemblyName) return $"[{prefix}.*]*"; } + /// + /// Converts a simple assembly name to an exact coverlet exclude-filter pattern. + /// + internal static string ToExactExcludeFilter(string assemblyName) + { + return $"[{assemblyName}]*"; + } + /// /// Removes exact-name filters from that are already matched /// by a wildcard filter present in the same collection. diff --git a/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs index aa4a1e163..4d5adb59d 100644 --- a/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs +++ b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs @@ -222,8 +222,30 @@ public void WhenLoadedAssemblyReturnsEntryThenFilterApplied() string[] result = config.GetExcludeFilters(); - // Three-segment name → wildcarded to [Microsoft.Testing.*]* - Assert.Contains("[Microsoft.Testing.*]*", result); + Assert.Contains("[Microsoft.Testing.Extensions.MSBuild]*", result); + } + + [Fact] + public void WhenLoadedAssemblySharesSutPrefixThenLoadedAssemblyFilterIsExact() + { + _mockProcessAssemblyHelper + .Setup(x => x.GetDepsJsonAssemblyNames(s_fakeModuleDir, TestAssemblyName)) + .Returns([]); + _mockProcessAssemblyHelper + .Setup(x => x.GetLoadedAssemblyNames(TestAssemblyName)) + .Returns(["MSS.Tools.xUnit"]); + + var config = new CoverageConfiguration( + _mockCommandLineOptions.Object, + configFileSettings: null, + testModulePath: FakeModulePath, + logger: _mockLogger.Object, + processAssemblyHelper: _mockProcessAssemblyHelper.Object); + + string[] result = config.GetExcludeFilters(); + + Assert.Contains("[MSS.Tools.xUnit]*", result); + Assert.DoesNotContain("[MSS.Tools.*]*", result); } [Fact] @@ -246,10 +268,9 @@ public void WhenBothSourcesReturnEntriesThenAllFiltersApplied() string[] result = config.GetExcludeFilters(); - // Three-segment names are wildcarded to their two-segment prefix. Assert.Contains("[xunit.v3.*]*", result); Assert.Contains("[testhost]*", result); - Assert.Contains("[Microsoft.Testing.*]*", result); + Assert.Contains("[Microsoft.Testing.Extensions.MSBuild]*", result); } #endregion diff --git a/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs b/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs index b46188a94..23daf78c3 100644 --- a/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs +++ b/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs @@ -131,7 +131,6 @@ public void TestIsValidFilterExpression(string pattern) [Theory] [InlineData("[*]")] - [InlineData("[-]*")] [InlineData("*")] [InlineData("][")] [InlineData(null)] @@ -229,6 +228,19 @@ public void TestSelectModulesWithModuleFilterExcludesExpectedModules() Assert.Equal(["ModuleB.dll", "Module.B.Tests.dll"], result); } + [Fact] + public void TestSelectModulesWithGeneratedHyphenatedAssemblyFilterExcludesExactModule() + { + string generatedFilter = ProcessAssemblyHelper.ToExactExcludeFilter("MSS.Tools.xUnit-Runner"); + + Assert.True(_instrumentationHelper.IsValidFilterExpression(generatedFilter)); + + string[] modules = new[] { "MSS.Tools.Markdown.dll", "MSS.Tools.xUnit-Runner.dll" }; + IEnumerable result = _instrumentationHelper.SelectModules(modules, Array.Empty(), new[] { generatedFilter }); + + Assert.Equal(["MSS.Tools.Markdown.dll"], result); + } + [Fact] public void TestIsTypeExcludedWithoutFilter() { diff --git a/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs b/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs index d05271c9c..34b766335 100644 --- a/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs +++ b/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs @@ -89,6 +89,19 @@ public void WhenToExcludeFilterThenReturnsCorrectPattern(string assemblyName, st Assert.Equal(expectedFilter, result); } + [Theory] + [InlineData("xunit", "[xunit]*")] + [InlineData("coverlet.core", "[coverlet.core]*")] + [InlineData("Microsoft.Testing.Extensions.MSBuild", "[Microsoft.Testing.Extensions.MSBuild]*")] + [InlineData("MSS.Tools.xUnit", "[MSS.Tools.xUnit]*")] + [InlineData("MSS.Tools.xUnit-Runner", "[MSS.Tools.xUnit-Runner]*")] + public void WhenToExactExcludeFilterThenReturnsExactPattern(string assemblyName, string expectedFilter) + { + string result = ProcessAssemblyHelper.ToExactExcludeFilter(assemblyName); + + Assert.Equal(expectedFilter, result); + } + [Theory] // An exact filter that is already covered by a wildcard should be pruned. [InlineData(new[] { "[coverlet.*]*", "[coverlet.core]*" }, new[] { "[coverlet.*]*" })] From 922b11cd71fccd97ce3fc8e369beb71fad4bb81d Mon Sep 17 00:00:00 2001 From: gimlichael Date: Tue, 3 Nov 2026 17:09:22 +0100 Subject: [PATCH 08/14] =?UTF-8?q?=E2=9C=85=20verify=20windows=20release=20?= =?UTF-8?q?tests=20and=20update=20upstream=20documentation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UPSTREAM.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/UPSTREAM.md b/UPSTREAM.md index 73382679b..f3d2f6e7f 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -84,7 +84,9 @@ Reviewed `coverlet-coverage/coverlet:master` at [`1d9db3a`](https://github.com/c | [`98d291d`, #2061](https://github.com/coverlet-coverage/coverlet/commit/98d291d713dde46a58ee1dcf7ce832bdf6c2b781) | Omit the update to the removed upstream CI workflow. | | [`ea74a47`, #2060](https://github.com/coverlet-coverage/coverlet/commit/ea74a473c5c0f5ef7dffb425584da9a72a1769dd) | Omit the update to the removed upstream CodeQL workflow. | -The five centrally versioned Microsoft Testing Platform packages were verified at 2.5.2 via `dotnet package search`. On Windows with SDK `11.0.100-rc.3.26522.148`, solution restore and Release build with `PrepareValidationPackage=false` succeeded; the build had zero warnings and errors and compiled core and MTP for .NET Standard 2.0, .NET 10 and .NET 11. `dotnet pack` succeeded, and package inspection confirmed `Codebelt.Coverlet.MTP`, all three framework groups, their existing runtime pins and compatibility overrides, and Microsoft.Testing.Platform 2.5.2. MinVer calculated `10.1.2-alpha.0.3` before the merge commit. The release workflow guards were unchanged and were not executed locally. Tests and the Linux/Windows/macOS CI matrix have not been run for this change; they remain required before integration. No release or publication was performed. +The five centrally versioned Microsoft Testing Platform packages were verified at 2.5.2 via `dotnet package search`. On Windows with SDK `11.0.100-rc.3.26522.148`, solution restore and Release build with `PrepareValidationPackage=false` succeeded; the build had zero warnings and errors and compiled core and MTP for .NET Standard 2.0, .NET 10 and .NET 11. `dotnet pack` succeeded, and package inspection confirmed `Codebelt.Coverlet.MTP`, all three framework groups, their existing runtime pins and compatibility overrides, and Microsoft.Testing.Platform 2.5.2. MinVer calculated `10.1.2-alpha.0.3` before the merge commit. The release workflow guards were unchanged and were not executed locally. No release or publication was performed. + +With approval, Windows Release tests passed against the merged source `feef6ea0687684ecadc0bd147cc4d6a42f82f93f`. For each of .NET 10 and .NET 11: `coverlet.core.tests` passed 369 and skipped 9; `coverlet.core.coverage.tests` passed 98; `coverlet.MTP.tests` passed 433 and skipped 7; and `coverlet.MTP.validation.tests` passed 45. Skips were platform-specific tests for Linux or macOS. The validation projects were rebuilt with `PrepareValidationPackage=true`, creating isolated packages at version `10.1.2-alpha.0.4`; their framework runs were sequential. .NET Standard 2.0 was built and packed, not executed as a test target. The Linux/Windows/macOS CI matrix remains required before integration. ### 2026-11-01: retain reviewed upstream ancestry without runtime changes From 5c61491e7b5d578abcffe9dcad175c48b8cc4eb7 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Wed, 4 Nov 2026 15:23:26 +0100 Subject: [PATCH 09/14] =?UTF-8?q?=F0=9F=92=AC=20record=20PR=20#8=20reconci?= =?UTF-8?q?liation=20CI=20results?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Link the ancestry-preserving reconciliation merge and successful Windows/Ubuntu CI run in the upstream ledger. Record the verified regression coverage and package-validation outcomes while preserving the explicit macOS, CI skip, maintainer review, and release boundaries. --- UPSTREAM.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/UPSTREAM.md b/UPSTREAM.md index 615dbfbab..4806ed16d 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -14,7 +14,7 @@ The compatibility goal is to preserve upstream behavior within the retained surf | Codebelt baseline | [`feef6ea0687684ecadc0bd147cc4d6a42f82f93f`](https://github.com/codebeltnet/coverlet/commit/feef6ea0687684ecadc0bd147cc4d6a42f82f93f) | | Upstream ancestry merge | [`d66c8f1`](https://github.com/codebeltnet/coverlet/commit/d66c8f1ec9222faa23a0bc64ce3d568bf783ca73) records the baseline as first parent and the reviewed upstream tip as second parent; the 2026-11-04 reconciliation below also retains the released 10.1.2 ancestry. | | Destination integration | [PR #8](https://github.com/codebeltnet/coverlet/pull/8) remains subject to maintainer review. Master already contains 10.1.2 through [PR #10](https://github.com/codebeltnet/coverlet/pull/10); the later upstream snapshot is not yet integrated or released. | -| Validation | Windows Release solution build, package inspection, and all four retained test suites passed on .NET 10/11. Cross-platform CI remains pending. Earlier validation evidence is recorded in the previous history entries. | +| Validation | Windows Release solution build, package inspection, and all four retained test suites passed on .NET 10/11. Windows/Ubuntu reconciliation CI passed at `7a261c8`; macOS remains a manual opt-in. Exact outcomes and existing CI skips are recorded below. | ## Original marker and release tags @@ -53,7 +53,7 @@ The `netstandard2.0` embedded tracker in `src/coverlet.template` is retained fro ### 2026-11-04: reconcile PR #8 with the released 10.1.2 fixes -Operation date: 2026-11-04. This combines this fork's own branches, without reviewing a newer upstream snapshot. [PR #8](https://github.com/codebeltnet/coverlet/pull/8) starts at `922b11cd71fccd97ce3fc8e369beb71fad4bb81d`; the incoming master is `9f8983fd74153cca8e66d3317068fdea3e6d4266`, which integrated the released 10.1.2 fixes through [PR #10](https://github.com/codebeltnet/coverlet/pull/10). Their comparison base is `0e2e2fe394c2ea6343b9b228382f1dbd2ef165c3`. The normal reconciliation merge retains PR #8 as its first parent and master as its second parent, preserving both reviewed upstream snapshots and the `v10.1.2` release ancestry. Final integration into master remains subject to maintainer review through PR #8; no 11.0.0 release is performed. +Operation date: 2026-11-04. This combines this fork's own branches, without reviewing a newer upstream snapshot. [PR #8](https://github.com/codebeltnet/coverlet/pull/8) starts at `922b11cd71fccd97ce3fc8e369beb71fad4bb81d`; the incoming master is `9f8983fd74153cca8e66d3317068fdea3e6d4266`, which integrated the released 10.1.2 fixes through [PR #10](https://github.com/codebeltnet/coverlet/pull/10). Their comparison base is `0e2e2fe394c2ea6343b9b228382f1dbd2ef165c3`. The normal reconciliation merge [`7a261c8`](https://github.com/codebeltnet/coverlet/commit/7a261c816a57c7ab5c19ad10d6c4c0274170d38d) retains PR #8 as its first parent and master as its second parent, preserving both reviewed upstream snapshots and the `v10.1.2` release ancestry. Final integration into master remains subject to maintainer review through PR #8; no 11.0.0 release is performed. The six conflicts and all automatic merge results were reviewed individually. The resulting dependency discovery, generated filter path, filter validation, facade resolver, and real discovery/filter-application regressions are identical to master. In particular, upstream #2069's deps.json wildcard normalization is superseded by 10.1.2's exact managed runtime-asset discovery, including RID assets, project/reference precedence, and xUnit build assets. Its exact loaded-assembly behavior is retained through the same exact filter helper; the now-redundant `ToExactExcludeFilter` helper is removed, with its unique test cases moved to `ToExcludeFilter`. The loaded shared-prefix and hyphenated module-selection regressions remain. Explicit wildcard filters and authoritative configuration files retain their existing behavior. @@ -70,6 +70,8 @@ Local validation uses Windows x64 and SDK `11.0.100-rc.3.26522.148`. `dotnet bui The eight runs total 1,930 passed, 32 platform skips, and zero failures. Both package suites executed all 45 tests, including help/info checks skipped by the existing Release CI guard. All four Issue 2058 regressions passed on each runtime. Package inspection confirmed `Codebelt.Coverlet.MTP`, retained MTP/core assembly identities, all three framework/dependency groups, existing runtime pins/compatibility overrides, and MTP 2.5.2. Before committing the reconciliation merge, MinVer calculated `10.1.2-alpha.0.6` because the incoming release ancestry was not yet part of HEAD; no tag or version policy was changed. .NET Standard 2.0 was built and packed, not executed. These are local Windows results; PR #8 records destination CI outcomes, with macOS remaining a manual opt-in. No consumer repository-wide coverage rerun or 11.0.0 publication is claimed. +Cross-platform validation: [CI run 41845532478](https://github.com/codebeltnet/coverlet/actions/runs/41845532478) completed successfully for source `7a261c816a57c7ab5c19ad10d6c4c0274170d38d`. All 13 selected build, version-guard, Windows/Ubuntu test, pack, and .NET 10/11 package-validation jobs passed; publication was skipped for the PR. GitHub's proposed merge tree matched the locally validated tree. The 12 downloaded core/MTP/instrumentation TRX reports confirm that the real dependency-discovery, forwarded-enum resolver, loaded-prefix, hyphenated module-selection, and all four Issue 2058 regressions passed on both runtimes on both operating systems. Existing platform skips and the Release CI help/info skip guard remain; the full local package suites above cover those help/info checks. macOS was not selected under the approved opt-in workflow. PR #8 remains open for review with auto-merge disabled; this validation does not integrate it into master or publish 11.0.0. + ### 2026-11-04: integrate the 10.1.2 maintenance fixes into 11.0.0 Operation date: 2026-11-04, following preparation and local validation on 2026-11-03. This is a merge between this fork's own release lines, not a new upstream synchronization. The destination baseline is `master` at `0e2e2fe394c2ea6343b9b228382f1dbd2ef165c3`; the maintenance source is `releases/v10` at `373d6a26b8662fb83c9059a90a3d14bc331025aa`, the verified `v10.1.2` tag target produced by [PR #9](https://github.com/codebeltnet/coverlet/pull/9). The common base is Codebelt `v10.1.1`, `5bd86483a104328783255960116c1fb87ce2b35d`. The normal merge retains master as its first parent and that maintenance source as its second parent. From 93c6c6e84dbf5f058218494f221e1856e1989758 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Wed, 4 Nov 2026 15:45:40 +0100 Subject: [PATCH 10/14] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20update=20dependencie?= =?UTF-8?q?s=20and=20improve=20documentation=20for=20xunit=20and=20MTP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Documentation/Coverlet.MTP.Integration.md | 39 +++++++++++++++-------- README.md | 20 +++++++++--- 2 files changed, 41 insertions(+), 18 deletions(-) diff --git a/Documentation/Coverlet.MTP.Integration.md b/Documentation/Coverlet.MTP.Integration.md index cdd3653a3..d15be0700 100644 --- a/Documentation/Coverlet.MTP.Integration.md +++ b/Documentation/Coverlet.MTP.Integration.md @@ -32,22 +32,33 @@ A sample project file looks like: ```xml - - net10.0 - Exe - - true - true - - - - - - - + + net10.0 + Exe + true + + + + + + + + ``` +In xUnit v3 4.x, `xunit.v3` includes MTP v2, so this example does not need a direct `Microsoft.Testing.Platform` reference. The console and Visual Studio runner references are optional for MTP coverage. + +With .NET SDK 10 or later, select MTP in the repository's `global.json`, keeping any existing SDK settings: + +```json +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +} +``` + ### Basic Usage To collect code coverage, run your test executable with the `--coverlet` flag: @@ -62,7 +73,7 @@ Or using `dotnet test` with MTP enabled projects: dotnet test --coverlet ``` -After the test run, a `coverage.json` file containing the results will be generated in the current directory. +By default, JSON and Cobertura reports are written to the test results directory (normally `TestResults`), with timestamped filenames. ## Command Line Options diff --git a/README.md b/README.md index 11cc1328b..a0bc33450 100644 --- a/README.md +++ b/README.md @@ -46,17 +46,29 @@ Example test project: net10.0 Exe true - true - - - + + + + ``` +In xUnit v3 4.x, `xunit.v3` includes MTP v2, so this example does not need a direct `Microsoft.Testing.Platform` reference. The console and Visual Studio runner references are optional for MTP coverage. + +With .NET SDK 10 or later, select MTP in the repository's `global.json`, keeping any existing SDK settings: + +```json +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +} +``` + ## Usage Run the MTP test project with the normal Coverlet MTP argument: From 8e75c9071bcda75a4b873a52b8279defce3d33f2 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Wed, 4 Nov 2026 15:58:41 +0100 Subject: [PATCH 11/14] =?UTF-8?q?=E2=9C=A8=20add=20test=20for=20bounded=20?= =?UTF-8?q?execution=20in=20issue=202058=20instrumentation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Coverage/CoverageTests.Issue2058.cs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs b/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs index d5d591e40..e708fc635 100644 --- a/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs +++ b/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs @@ -66,6 +66,36 @@ await TestInstrumentationHelper.Run(instance => } } + [Fact] + public void Issue2058_ReleaseInstrumentation_BoundedExecution_RecordsBranchAndLineHits() + { + string path = Path.GetTempFileName(); + try + { + FunctionExecutor.Run(async (string[] pathSerialize) => + { + await TestInstrumentationHelper.Run(instance => + { + instance.TryFinally_DoWhileBackEdge_Bounded(); + return Task.CompletedTask; + }, persistPrepareResultToFile: pathSerialize[0]); + + return 0; + }, [path]); + + CoverageResult result = TestInstrumentationHelper.GetCoverageResult(path); + result.Document("Instrumentation.Issue2058.cs") + .Method("System.Void Coverlet.Core.CoverageSamples.Tests.Issue2058::TryFinally_DoWhileBackEdge_Bounded()") + .AssertLinesCovered((100, 2), (102, 2), (106, 1)) + .AssertBranchesCovered((102, 0, 1), (102, 1, 1)) + .ExpectedTotalNumberOfBranches(1); + } + finally + { + File.Delete(path); + } + } + private static void AssertMethodHasBothBranchPaths(CoverageResult result, string methodName) { var branches = result.Document("Instrumentation.Issue2058.cs").Branches.Values From d7c945a85127a012da677f7bfecb8e8f5fa76aa9 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Wed, 4 Nov 2026 15:58:47 +0100 Subject: [PATCH 12/14] =?UTF-8?q?=E2=9C=A8=20add=20bounded=20version=20of?= =?UTF-8?q?=20try-finally=20do-while=20back=20edge=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Samples/Instrumentation.Issue2058.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs b/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs index 8e93a8d3e..59e81a540 100644 --- a/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs +++ b/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs @@ -91,6 +91,22 @@ public void TryFinally_DoWhileBackEdge() } } + public void TryFinally_DoWhileBackEdge_Bounded() + { + try + { + do + { + _n++; + } + while (_n < 2); + } + finally + { + _n++; + } + } + private void Tick() { _n++; From d7f3c6b950c8841b7aeddd6e952ad9e8926d762b Mon Sep 17 00:00:00 2001 From: gimlichael Date: Wed, 4 Nov 2026 16:22:51 +0100 Subject: [PATCH 13/14] =?UTF-8?q?=E2=9C=A8=20add=20bounded=20version=20of?= =?UTF-8?q?=20while-true=20if-then=20try-finally=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Samples/Instrumentation.Issue2058.cs | 37 +++++++++++-------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs b/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs index 59e81a540..b91dee11b 100644 --- a/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs +++ b/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs @@ -25,6 +25,27 @@ public void WhileTrue_IfThenTryFinally() } } + public void WhileTrue_IfThenTryFinally_Bounded(System.Action onIteration) + { + while (true) + { + if (_n > 0) + { + _n--; + } + + try + { + _n++; + onIteration(); + } + finally + { + _n++; + } + } + } + public void WhileTrue_TryFinallyIfTryFinally() { while (true) @@ -91,22 +112,6 @@ public void TryFinally_DoWhileBackEdge() } } - public void TryFinally_DoWhileBackEdge_Bounded() - { - try - { - do - { - _n++; - } - while (_n < 2); - } - finally - { - _n++; - } - } - private void Tick() { _n++; From e1bf90bd995e83ed5030cc34399364a419474669 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Wed, 4 Nov 2026 16:22:56 +0100 Subject: [PATCH 14/14] =?UTF-8?q?=E2=9C=A8=20add=20bounded=20version=20of?= =?UTF-8?q?=20while-true=20if-then=20try-finally=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Coverage/CoverageTests.Issue2058.cs | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs b/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs index e708fc635..c88cacee8 100644 --- a/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs +++ b/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs @@ -76,7 +76,20 @@ public void Issue2058_ReleaseInstrumentation_BoundedExecution_RecordsBranchAndLi { await TestInstrumentationHelper.Run(instance => { - instance.TryFinally_DoWhileBackEdge_Bounded(); + int iterations = 0; + Action onIteration = () => + { + if (++iterations == 2) + { + throw new InvalidOperationException(); + } + }; + Action execute = () => + { + instance.WhileTrue_IfThenTryFinally_Bounded(onIteration); + }; + Exception exception = Record.Exception(execute); + Assert.True(exception is InvalidOperationException, $"Expected the callback to stop execution. Actual exception: {exception}"); return Task.CompletedTask; }, persistPrepareResultToFile: pathSerialize[0]); @@ -85,9 +98,9 @@ await TestInstrumentationHelper.Run(instance => CoverageResult result = TestInstrumentationHelper.GetCoverageResult(path); result.Document("Instrumentation.Issue2058.cs") - .Method("System.Void Coverlet.Core.CoverageSamples.Tests.Issue2058::TryFinally_DoWhileBackEdge_Bounded()") - .AssertLinesCovered((100, 2), (102, 2), (106, 1)) - .AssertBranchesCovered((102, 0, 1), (102, 1, 1)) + .Method("System.Void Coverlet.Core.CoverageSamples.Tests.Issue2058::WhileTrue_IfThenTryFinally_Bounded(System.Action)") + .AssertLinesCovered((32, 2), (34, 1), (39, 2), (44, 2)) + .AssertBranchesCovered((32, 0, 1), (32, 1, 1)) .ExpectedTotalNumberOfBranches(1); } finally