diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c8c8dd1c..45db06cae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ This major release adds .NET 11 support, removes the dedicated .NET 9 target, an - Target .NET 10 and .NET 11 alongside .NET Standard 2.0, with runtime dependency versions selected per target framework, - Preserve reviewed upstream history through merge ancestry while retaining selective Codebelt file integration; the 2026-11-01 synchronization through `2e0a852` changes no production code, dependencies, or package layout, - Exclude unreachable branches from branch coverage totals and from Cobertura, LCOV, and OpenCover branch details, -- Update Microsoft Testing Platform to 2.5.1, Microsoft.NET.Test.Sdk to 18.11.0, xunit.v3.mtp-v2 to 4.0.2, xunit.runner.visualstudio to 4.0.1, Moq to 4.21.0, and LinqKit.Microsoft.EntityFrameworkCore to 10.1.1, +- Update Microsoft Testing Platform to 2.5.2, Microsoft.NET.Test.Sdk to 18.11.0, xunit.v3.mtp-v2 to 4.0.2, xunit.runner.visualstudio to 4.0.1, Moq to 4.21.0, and LinqKit.Microsoft.EntityFrameworkCore to 10.1.1, - Update NuGet.Packaging and NuGet.Versioning to 7.9.0, retaining a NuGet.Versioning 6.14.3 override for .NET Standard 2.0, - Change the validation tests to read the package folder from MSBuild metadata instead of a hard-coded `artifacts/package/` path, with missing-package guidance that points to `-p:PrepareValidationPackage=true` or an existing package, - Disable automatic package preparation in GitHub Actions so validation consumes the downloaded release package, while allowing opt-out outside GitHub Actions with `-p:PrepareValidationPackage=false`, @@ -32,6 +32,7 @@ This major release adds .NET 11 support, removes the dedicated .NET 9 target, an ### Fixed +- Prevent invalid IL from branch trampolines near exception-handler boundaries and optimized loop back-edges, - Instrument local functions when CompilerGeneratedAttribute or GeneratedCodeAttribute is excluded, while continuing to honor other configured exclusion attributes, - Resolve shared-framework assemblies when runtime directory names contain version suffixes, - Align pattern-matching branch assertions with the selected SDK's compiled output. diff --git a/Directory.Packages.props b/Directory.Packages.props index dd604b66b..bd799ba2d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,7 +9,7 @@ $(MicrosoftNet10RuntimeVersion) $(MicrosoftNet11RuntimeVersion) 18.11.0 - 2.5.1 + 2.5.2 4.21.0 7.9.0 4.0.2 diff --git a/Documentation/Coverlet.MTP.Integration.md b/Documentation/Coverlet.MTP.Integration.md index c9e28b831..e9cbf71d2 100644 --- a/Documentation/Coverlet.MTP.Integration.md +++ b/Documentation/Coverlet.MTP.Integration.md @@ -35,22 +35,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: @@ -65,7 +76,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 ed3977e34..2530567b5 100644 --- a/README.md +++ b/README.md @@ -49,17 +49,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: diff --git a/UPSTREAM.md b/UPSTREAM.md index 4eca84269..4806ed16d 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -9,12 +9,12 @@ The compatibility goal is to preserve upstream behavior within the retained surf | Item | Recorded state | | --- | --- | | Upstream | [`coverlet-coverage/coverlet`, `master`](https://github.com/coverlet-coverage/coverlet/tree/master) | -| Latest reviewed upstream commit | [`2e0a852d3a0d9669d9c19445e366c69ccaaf6424`](https://github.com/coverlet-coverage/coverlet/commit/2e0a852d3a0d9669d9c19445e366c69ccaaf6424), dated 2026-10-27 | -| Latest sync operation | 2026-11-01; normal upstream merge preserving the existing Codebelt tree | -| Codebelt baseline | [`6e72c0c11523bf3d6baf3ca25c2a457ce547674e`](https://github.com/codebeltnet/coverlet/commit/6e72c0c11523bf3d6baf3ca25c2a457ce547674e), integrated by [PR #6](https://github.com/codebeltnet/coverlet/pull/6) on 2026-11-01 | -| Upstream ancestry merge | [`d587f8ca285f0bf147fb933e14ed48dfff8a7490`](https://github.com/codebeltnet/coverlet/commit/d587f8ca285f0bf147fb933e14ed48dfff8a7490); first parent is the Codebelt baseline, second parent is the reviewed upstream tip | -| Destination integration | [PR #7](https://github.com/codebeltnet/coverlet/pull/7) into `codebeltnet/coverlet:master` using a merge commit; its merge record supplies the authoritative destination commit and integration state. The 11.0.0 release entry remains a draft. | -| Validation | [CI run 41267824916](https://github.com/codebeltnet/coverlet/actions/runs/41267824916) at `1ddc5ab8bb25e437ebd3207769023e88c4a035e5` passed build, release-version guard, all nine test jobs, packing, and all six package-validation jobs across .NET 10/11 and Linux, Windows, and macOS. Publication was skipped. The final documentation follow-up is also gated by the checks on PR #7. | +| Latest reviewed upstream commit | [`f37bf3d1ea8795cc1bdc57b29ad2ec81d10c9f1a`](https://github.com/coverlet-coverage/coverlet/commit/f37bf3d1ea8795cc1bdc57b29ad2ec81d10c9f1a), dated 2026-11-03 | +| Latest sync operation | 2026-11-03; selective upstream merge on `v11.0.0/double-digits-chore` | +| 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. 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 @@ -51,6 +51,27 @@ The `netstandard2.0` embedded tracker in `src/coverlet.template` is retained fro ## Synchronization history +### 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 [`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. + +PR #8's exception-handler-aware instrumentation and four Issue 2058 JIT-preparation regressions are unchanged. Microsoft Testing Platform remains at 2.5.2. Master's .NET 11 SDK, `netstandard2.0;net10.0;net11.0` targets, remaining dependency pins, validation infrastructure, maintenance release workflow, and manual macOS opt-in are retained. The changelog keeps the 10.1.2 advisory and release history; exact filtering is no longer listed as a separate new 11.0.0 fix. The original synchronization entries below remain as historical records. + +Local validation uses Windows x64 and SDK `11.0.100-rc.3.26522.148`. `dotnet build coverlet.slnx -c Release -p:PrepareValidationPackage=false` passed with zero warnings/errors, including .NET Standard 2.0. Tests use `dotnet test --project test//.csproj --framework --configuration Release --report-trx --results-directory `, with `--no-build` for the core, MTP and instrumentation suites. Package-validation framework legs run sequentially and prepare isolated packages. Results: + +| Project | .NET 10 | .NET 11 | +| --- | --- | --- | +| `coverlet.core.tests` | 378 passed, 9 platform skips | 378 passed, 9 platform skips | +| `coverlet.MTP.tests` | 440 passed, 7 platform skips | 440 passed, 7 platform skips | +| `coverlet.core.coverage.tests` | 102 passed, no skips | 102 passed, no skips | +| `coverlet.MTP.validation.tests` | 45 passed, no skips | 45 passed, no skips | + +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. @@ -72,6 +93,50 @@ Local validation used Windows x64 and SDK `11.0.100-rc.3.26522.148`. The Release The total is 1,912 passed, 32 platform skips, and zero failures. These are local Windows results, not evidence of destination Linux/macOS execution. Read-only comparisons verified that master's SDK, dependencies, framework declarations, upstream instrumentation ports, and validation infrastructure are unchanged, while the maintenance discovery/resolver corrections and regression tests are present. Remote integration must preserve the merge ancestry; use a merge commit rather than squash or rebase. +Integration completed through [PR #10](https://github.com/codebeltnet/coverlet/pull/10) at `9f8983fd74153cca8e66d3317068fdea3e6d4266`, with a tree identical to the tested source `33c05e0092924dba510d0f0c558eb9d4aea30e08`. [CI run 41786504381](https://github.com/codebeltnet/coverlet/actions/runs/41786504381) passed the selected Windows/Ubuntu test, build, pack, and .NET 10/11 package-validation jobs; publication was skipped for the PR. macOS was not selected under the maintainer-approved opt-in workflow. These final outcomes supersede the preparation-state pending statements above. + +### 2026-11-03: exception-handler instrumentation and dynamic exclusion fixes + +Operation date: 2026-11-03. Reviewed `coverlet-coverage/coverlet:master` at [`f37bf3d1ea8795cc1bdc57b29ad2ec81d10c9f1a`](https://github.com/coverlet-coverage/coverlet/commit/f37bf3d1ea8795cc1bdc57b29ad2ec81d10c9f1a), fetched without tags. The shared comparison base is [`1d9db3aacfbf61e1b2b4d9190715a13ba694d8c9`](https://github.com/coverlet-coverage/coverlet/commit/1d9db3aacfbf61e1b2b4d9190715a13ba694d8c9); the requested branch baseline is `feef6ea0687684ecadc0bd147cc4d6a42f82f93f`. At the maintainer's explicit request this synchronization targets the existing `v11.0.0/double-digits-chore` branch, rather than starting a new branch from or integrating into `master`. + +| Upstream source | Disposition | +| --- | --- | +| [`483ff5a`, #2067](https://github.com/coverlet-coverage/coverlet/commit/483ff5ac667a2d20fc4f3976251aa8f5335cc9ba) | Adopt exception-handler-aware branch trampolines, local trampoline fallback, stable iteration over original IL, and Issue 2058 regression coverage/samples. Preserve the fork's solution layout. Exclude upstream-only ILVerify tool manifests, legacy pipeline/tool configuration, and Copilot instruction edits. | +| [`345b63c`, #2068](https://github.com/coverlet-coverage/coverlet/commit/345b63cc18abe9587e353e75f882b59cbf3e372f) | Translate the adopted instrumentation fix into the root changelog; omit upstream release headings and removed package identities. | +| [`f37bf3d`, #2069](https://github.com/coverlet-coverage/coverlet/commit/f37bf3d1ea8795cc1bdc57b29ad2ec81d10c9f1a) | Adopt exact assembly-name filters for loaded controller assemblies, retain wildcard normalization for deps.json entries, accept hyphens in filters, and adopt corresponding core/MTP tests and retained MTP usage documentation. Translate release notes into the root changelog. | + +The dependency-filter disposition above records the original 2026-11-03 merge. The 2026-11-04 reconciliation below supersedes its deps.json wildcard normalization with the released 10.1.2 exact runtime-asset discovery while retaining exact loaded-assembly behavior. + +All three incoming commits were reviewed; none was already present. Production and test changes match the reviewed upstream changes, including the .NET Standard trampoline compatibility path. The four modified/deleted or content-conflicted paths and all automatic merge results were reviewed individually. Removed tool manifests, legacy projects/pipelines, upstream changelog and versioning remain excluded. Codebelt package/assembly identities, `netstandard2.0;net10.0;net11.0`, runtime pins, MinVer `v*` tags, and release guards are preserved. + +Validation on Windows with SDK `11.0.100-rc.3.26522.148`: `dotnet build coverlet.slnx -c Release -p:PrepareValidationPackage=true` succeeded with zero warnings/errors. Core and MTP compiled for .NET Standard 2.0, .NET 10 and .NET 11; isolated validation packages were created for the .NET 10/11 consumer tests. Inspection of both packages confirmed `Codebelt.Coverlet.MTP`, `coverlet.MTP.dll`, all three framework/dependency groups, the existing runtime pins and compatibility overrides, and Microsoft.Testing.Platform 2.5.2. MinVer calculated `10.1.2-alpha.0.4` before this merge commit; its configuration and release guards are unchanged and the guards were not executed locally. + +With explicit approval, Release tests ran with `dotnet test test//.csproj -c Release -f --no-build -p:PrepareValidationPackage=false -- --report-trx --report-trx-filename ..sync-20261103.trx`. All eight runs passed; package-validation framework runs were sequential to avoid shared generated-project directories. + +| Project | .NET 10 | .NET 11 | +| --- | --- | --- | +| `coverlet.core.tests` | 374 passed, 9 skipped | 374 passed, 9 skipped | +| `coverlet.core.coverage.tests` | 102 passed, none skipped | 102 passed, none skipped | +| `coverlet.MTP.tests` | 434 passed, 7 skipped | 434 passed, 7 skipped | +| `coverlet.MTP.validation.tests` | 45 passed, none skipped | 45 passed, none skipped | + +Skips require Linux or macOS. The four Issue 2058 JIT-preparation regressions passed on each runtime. .NET Standard 2.0 was built and packed, not executed as a test target. The normal merge carrying this entry records the branch baseline first and the pinned upstream tip second; the reviewed tip is an ancestor of the resulting branch with zero commits on the upstream side of its comparison. Destination integration into `master` and Linux/Windows/macOS CI remain pending; this operation neither releases nor publishes a package. + +### 2026-11-01: Microsoft Testing Platform patch update + +Reviewed `coverlet-coverage/coverlet:master` at [`1d9db3a`](https://github.com/coverlet-coverage/coverlet/commit/1d9db3aacfbf61e1b2b4d9190715a13ba694d8c9), compared from shared base [`2e0a852`](https://github.com/coverlet-coverage/coverlet/commit/2e0a852d3a0d9669d9c19445e366c69ccaaf6424). The requested branch started at `0e2e2fe394c2ea6343b9b228382f1dbd2ef165c3`. This normal merge records the four reviewed commits in ancestry; that does not adopt their excluded files. + +| Upstream source | Disposition | +| --- | --- | +| [`1d9db3a`, #2066](https://github.com/coverlet-coverage/coverlet/commit/1d9db3aacfbf61e1b2b4d9190715a13ba694d8c9) | Adopt the shared Microsoft Testing Platform version update from 2.5.1 to 2.5.2 for the retained package and test dependencies, preserving the fork's central version layout. | +| [`b0b4190`, #2062](https://github.com/coverlet-coverage/coverlet/commit/b0b4190c995017d28c8b2cca5cad4f2d919591ff) | Omit the update to the removed upstream dotnet tool manifest. The separate `ReportGenerator.Core` test dependency was not changed upstream. | +| [`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. 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 Operation date: 2026-11-01. Source: `coverlet-coverage/coverlet`, `master`, pinned at [`2e0a852d3a0d9669d9c19445e366c69ccaaf6424`](https://github.com/coverlet-coverage/coverlet/commit/2e0a852d3a0d9669d9c19445e366c69ccaaf6424). Fetching without tags confirmed that this is still the previously reviewed upstream tip. The starting fork baseline is [`6e72c0c11523bf3d6baf3ca25c2a457ce547674e`](https://github.com/codebeltnet/coverlet/commit/6e72c0c11523bf3d6baf3ca25c2a457ce547674e), after integrating the green [PR #6](https://github.com/codebeltnet/coverlet/pull/6); its tree was verified identical to the tested head `0b04b05d6d996ac945869d0f9e5e96224246d309`. The pre-merge comparison base is `da5c649126c74985fc20c496bc898f143d18e21b`. diff --git a/src/coverlet.core/Instrumentation/Instrumenter.cs b/src/coverlet.core/Instrumentation/Instrumenter.cs index 813544abf..92850dc47 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/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs index 1cfd382a3..cf5d0a65b 100644 --- a/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs +++ b/test/coverlet.MTP.tests/Configuration/CoverageConfigurationDynamicExcludeTests.cs @@ -228,6 +228,29 @@ public void WhenLoadedAssemblyReturnsEntryThenFilterApplied() Assert.DoesNotContain("[Microsoft.Testing.*]*", 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] public void WhenBothSourcesReturnEntriesThenAllFiltersApplied() { 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..c88cacee8 --- /dev/null +++ b/test/coverlet.core.coverage.tests/Coverage/CoverageTests.Issue2058.cs @@ -0,0 +1,179 @@ +// 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); + } + } + + [Fact] + public void Issue2058_ReleaseInstrumentation_BoundedExecution_RecordsBranchAndLineHits() + { + string path = Path.GetTempFileName(); + try + { + FunctionExecutor.Run(async (string[] pathSerialize) => + { + await TestInstrumentationHelper.Run(instance => + { + 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]); + + return 0; + }, [path]); + + CoverageResult result = TestInstrumentationHelper.GetCoverageResult(path); + result.Document("Instrumentation.Issue2058.cs") + .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 + { + 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..b91dee11b --- /dev/null +++ b/test/coverlet.core.coverage.tests/Samples/Instrumentation.Issue2058.cs @@ -0,0 +1,130 @@ +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_IfThenTryFinally_Bounded(System.Action onIteration) + { + while (true) + { + if (_n > 0) + { + _n--; + } + + try + { + _n++; + onIteration(); + } + 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++; + } + } +} diff --git a/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs b/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs index bb57d8a52..d478b9033 100644 --- a/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs +++ b/test/coverlet.core.tests/Helpers/InstrumentationHelperTests.cs @@ -246,6 +246,19 @@ public void TestSelectModulesWithModuleFilterExcludesExpectedModules() Assert.Equal(["ModuleB.dll", "Module.B.Tests.dll"], result); } + [Fact] + public void TestSelectModulesWithGeneratedHyphenatedAssemblyFilterExcludesExactModule() + { + string generatedFilter = ProcessAssemblyHelper.ToExcludeFilter("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 ca951895c..97898f40a 100644 --- a/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs +++ b/test/coverlet.core.tests/Helpers/ProcessAssemblyHelperTests.cs @@ -82,6 +82,9 @@ public void WhenGetLoadedAssemblyNamesWithWhitespaceThenThrowsArgumentException( [InlineData("Microsoft.Testing.Platform", "[Microsoft.Testing.Platform]*")] [InlineData("Microsoft.Extensions.Configuration.Binder", "[Microsoft.Extensions.Configuration.Binder]*")] [InlineData("Codebelt.Extensions.Xunit", "[Codebelt.Extensions.Xunit]*")] + [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 WhenToExcludeFilterThenReturnsCorrectPattern(string assemblyName, string expectedFilter) { string result = ProcessAssemblyHelper.ToExcludeFilter(assemblyName);