Skip to content

Fix PInvoke017 for span-based string copies in using scopes - #1875

Merged
Jevan Saks (jevansaks) merged 2 commits into
mainfrom
jevansaks-dangerous-value-using-guard
Nov 9, 2026
Merged

Jevan Saks (jevansaks) merged 2 commits into
mainfrom
jevansaks-dangerous-value-using-guard

Conversation

@jevansaks

@jevansaks Jevan Saks (jevansaks) commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

The lifetime analyzer reports PInvoke017 for this valid pattern:

using var pPath = pRawPath;
string filePath = Path.Combine(pPath.DangerousValue.AsSpan().ToString(), ".earlystart");

The owner's using scope is already recognized. The false positive comes from stopping at AsSpan() instead of following the expression to ToString(), which copies the native contents into a managed string.

Follow instance calls that return Span<T> or ReadOnlySpan<T> so chained copies, including Slice(...).ToString(), are evaluated at their final use. The same behavior applies to a lease's Value. Saving or returning a native-backed span still reports PInvoke017, and accessing the resource without a visible lifetime scope still reports PInvoke016.

Adds regression coverage for the reported pattern, owners and leases, mutable and read-only spans, and rejected lifetime escapes on .NET Framework 4.7.2 and .NET 8.

@jevansaks
Jevan Saks (jevansaks) marked this pull request as ready for review November 6, 2026 19:56
@jevansaks
Jevan Saks (jevansaks) merged commit 66d53ce into main Nov 9, 2026
20 checks passed
@jevansaks
Jevan Saks (jevansaks) deleted the jevansaks-dangerous-value-using-guard branch November 9, 2026 18:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants