Skip to content

[Java.Interop] Simplify local unsafe expression contexts - #13315

Merged
simonrozsival merged 4 commits into
mainfrom
simonrozsival-unsafe-expression-simplification
Oct 31, 2026
Merged

simonrozsival merged 4 commits into
mainfrom
simonrozsival-unsafe-expression-simplification

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Context: #13184, #13187, #13188, #13189.

The memory-safety audits separated caller obligations from unchecked operations inside an implementation. Some resulting unsafe blocks contain only a return or assignment, however. They add nesting and force locals to be declared separately from their initializers without making the unchecked operation any clearer.

Use unsafe (...) expressions for those single-value operations. This keeps the safety proof beside the operation while removing the surrounding block. The 122 compiled sites cover JNI lookup/invocation, pointer getters, borrowed-ref returns, value-returning callbacks, and embedded-resource reads.

  • Use expression-bodied properties/getters where the body is just that expression. Keep disposed/bounds checks and other multi-statement bodies intact.
  • Restore the object initializers and out var arguments that used var before the audits, as confirmed with git blame. Retain longstanding explicit scalar declarations.
  • Acquire resource streams directly in their using headers, preserving archive/stream disposal before the enclosing PEReader is disposed.
  • Update the canonical primitive-array, built-in marshaler, and callback T4 templates together with their generated outputs.

Caller contracts/modifiers, API metadata, evaluation order, ownership, and cleanup ordering are preserved. This does not enable the updated memory-safety model or change project settings, dependencies, language versions, or customer-generated binding code. Leave non-preview Mono.Android sources alone. Pinning, void calls, loops, and multi-statement operations retain blocks; so does PEMemoryBlock.Pointer, whose legacy pointer-signature getter still rejects the expression form with CS9363.

Validation

Built from pinned main source a78439a3a4817cd8c56c886f4312ec2feda55513 with SDK 12.0.100-alpha.1.26523.103 / Csc 5.13.0-1.26523.103. Results are attributed to the revision tested, rather than treating an earlier full build as validation of later edits:

Revision Coverage Result
9bff508212 Complete SDK/local workload; Java.Interop/net10.0, legacy tasks/netstandard2.0, modern tasks/net11.0; generator and host task cases Passed; 482 host tests passed
530a60ee1b Property/var follow-up: core and legacy-task Debug/Release builds; generator suite All four builds passed; 478/478 tests passed
7d29a95c5a Using-header follow-up: legacy-task Debug/Release builds; CoreCLR and NativeAOT resource-import host cases Both builds passed; 2/2 tests passed

Type/member metadata and public XML documentation are unchanged. At 530a60ee1b, Release IL matched the baseline; Debug IL was equivalent after conservatively normalizing verified single-use getter return spills and type-preserving local numbering. At 7d29a95c5a, only ResolveLibraryProjectImports.Extract changes IL in either configuration: three redundant stream-capture load/store pairs disappear, with the member-call sequence and exception-handler kinds/order preserved. These compiler-lowering differences are intentional; the final assemblies are not claimed to be byte-identical.

Canonical T4 regeneration is byte-stable, and original safety comments and BOMs are preserved. The full SDK, modern/net11 build, and compression-metadata cases were not rerun after 9bff508212; later results are limited to the focused coverage above. No device tests were run. This PR targets main independently of the memory-safety migration stack.

Validation commands and results

Initial change (9bff508212) — all commands passed. The three test commands passed 478, 2, and 2 tests respectively, matching the unmodified baseline. The SDK/workload build passed before and after the initial change.

make prepare MSBUILD_ARGS='-v:minimal'
make leeroy MSBUILD_ARGS='-v:minimal -m:2'
./dotnet-local.sh build external/Java.Interop/src/Java.Interop/Java.Interop.csproj -c Release -v minimal
./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj -c Release -v minimal
./dotnet-local.sh build src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj -c Release -v minimal
./dotnet-local.sh test external/Java.Interop/tests/generator-Tests/generator-Tests.csproj -c Release -v minimal --logger 'trx;LogFileName=head-generator.trx' --results-directory "$PWD/bin/validation/test-results"
./dotnet-local.sh test bin/TestDebug/net10.0/Xamarin.Android.Build.Tests.dll --filter 'FullyQualifiedName~IncrementalBuildTest.ResolveLibraryProjectImports' --logger 'trx;LogFileName=head-imports.trx' --results-directory "$PWD/bin/validation/test-results"
./dotnet-local.sh test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Release -v minimal --filter 'FullyQualifiedName~CompressionMetadataTests' --logger 'trx;LogFileName=head-metadata.trx' --results-directory "$PWD/bin/validation/test-results"

The initial change also passed value, ref-alias/write, out-variable, and callback execution probes with identical optimized IL in both legacy and updated-rules modes. Initial Debug/Release type/member metadata and normalized IL matched the baseline across all three affected assemblies.

Property/var follow-up (530a60ee1b) — all four library builds and the generator build passed; 478/478 generator tests passed.

for config in Release Debug; do
  ./dotnet-local.sh build external/Java.Interop/src/Java.Interop/Java.Interop.csproj -c "$config" -v minimal -m:2 -nr:false -p:UseSharedCompilation=false --disable-build-servers
  ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj -c "$config" -v minimal -m:2 -nr:false -p:UseSharedCompilation=false --disable-build-servers
done
./dotnet-local.sh build external/Java.Interop/tests/generator-Tests/generator-Tests.csproj -c Release -v minimal -m:2 -nr:false -p:UseSharedCompilation=false --disable-build-servers
./dotnet-local.sh test external/Java.Interop/bin/TestRelease-net10.0/generator-Tests.dll --logger 'trx;LogFileName=properties-var-generator.trx' --results-directory "$PWD/bin/validation/test-results"

Debug removes 18 single-use getter return spills, including the preceding IsDisposed follow-up; restored out var arguments also change local numbering. After the stated conservative normalization, all 38,348 core/legacy Debug/Release metadata/body records matched the baseline.

Using-header follow-up (7d29a95c5a) — both builds and both host cases passed. Builds used previously validated unchanged dependencies, without restoring or rebuilding them. Child app builds inherited the shared-compilation/build-server settings shown below.

for config in Release Debug; do
  ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj -c "$config" --no-restore -v minimal -m:2 -nr:false -p:BuildProjectReferences=false -p:UseSharedCompilation=false --disable-build-servers
done
UseSharedCompilation=false DOTNET_CLI_USE_MSBUILD_SERVER=0 MSBUILDUSESERVER=0 ./dotnet-local.sh test bin/TestDebug/net10.0/Xamarin.Android.Build.Tests.dll --filter 'FullyQualifiedName~IncrementalBuildTest.ResolveLibraryProjectImports' --logger 'trx;LogFileName=using-imports-isolated.trx' --results-directory "$PWD/bin/validation/test-results"

Stream-local counts decrease from four to three in Release and six to three in Debug. All 11 finally handlers remain, with the same member-call sequence and exception-handler kinds/order. Validation used isolated local SDK, toolchain, and package directories.

Copilot AI balanced review requested due to automatic review settings October 29, 2026 14:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported for the unsafe-expression refactor.

No open issues 🎉

What changed in this PR

Simplifies implementation-local unsafe contexts in Java.Interop and Android build tasks by replacing single-value unsafe blocks with unsafe (...) expressions, while preserving caller contracts, guards, ownership, and cleanup.

Changes:

  • Removes unnecessary nesting and split initialization across JNI calls, callbacks, pointer accessors, and embedded-resource reads.
  • Updates three canonical T4 templates and their checked-in generated outputs.
  • Documents expression-based unsafe contexts while retaining blocks where needed.
File Description
src/​Xamarin.Android.Build.Tasks/​Utilities/​MetadataExtensions.cs Simplifies embedded-resource length reads and stream creation.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ResolveLibraryProjectImports.cs Simplifies resource-stream initialization during extraction.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniType.cs Simplifies JNI type construction and member lookups.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniRuntime.JniTypeManager.cs Simplifies borrowed-pointer handling and remapping calls.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniRuntime.cs Simplifies VM calls and runtime initialization expressions.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniPeerMembers.JniStaticMethods.cs Converts value-returning static JNI calls to expressions.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniPeerMembers.cs Simplifies peer-type resolution and remapping lookups.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniMethodInfo.cs Simplifies lazy diagnostic string conversion.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniMarshal.SafeInvoke.tt Updates the value-returning callback template.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniMarshal.SafeInvoke.cs Synchronizes generated callback overloads.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniEnvironment.Types.cs Simplifies class lookups and native-method descriptor creation.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniEnvironment.Object.cs Simplifies object construction and string calls.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniEnvironment.cs Simplifies Java VM lookup result initialization.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniBuiltinMarshalers.tt Updates the primitive-value marshaling template.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JniBuiltinMarshalers.cs Synchronizes generated primitive marshalers.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaPrimitiveArrays.tt Updates pointer and borrowed-ref accessor templates.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaPrimitiveArrays.cs Synchronizes generated primitive-array accessors.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaObject.cs Simplifies Java method calls and control-block address access.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaException.cs Simplifies throwable calls and control-block address access.
external/​Java.Interop/​src/​Java.Interop/​Java.Interop/​JavaArray.cs Simplifies disposal checks and element-pointer accessors.
external/​Java.Interop/​Documentation/​Architecture.md Documents unsafe expressions and cases retaining blocks.

Review effort: Balanced

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Android PR Reviewer has started processing this issue comment

@jonathanpeppers jonathanpeppers left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to update copilot-instructions.md so future sessions know about the inline unsafe() expression?

@simonrozsival

Copy link
Copy Markdown
Member Author

Do we need to update copilot-instructions.md so future sessions know about the inline unsafe()expression?

I think once we're done iterating on the new memory safety rules, we need to update copilot instructions to give instructions + link to the blogpost/docs if build errors are encountered. I don't think things are already set in stone, so I would avoid updating the instructions just yet.

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Oct 30, 2026
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13315

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code assessment: no blocking findings. ⚠️ CI verification remains incomplete.

Reviewed all 21 changed files in full and checked the diff, relevant callers, linked-source project configuration, and canonical T4 templates. Findings: 0 errors, 0 warnings, 1 optional inline suggestion.

The conversions preserve the source-level invocation arguments, virtual/static dispatch, borrowed-ref returns, cache publication, and exception/finally structure. In particular, the resource streams remain disposed before their enclosing PEReader, and the three edited T4 templates match their generated counterparts. The existing preview settings cover the affected projects; the diff does not introduce customer-generated binding syntax or enable additional memory-safety features.

CI: GitHub reports 41 completed, successful checks, including dotnet-android build 1654437. The direct Azure DevOps build query required authentication, so I could not independently confirm its result/source revision or declare CI fully verified. This is a review-access limitation, not evidence of a PR regression.

No local builds or device tests were run during this review; the PR description's revision-specific build, test, metadata, and IL results were not independently reproduced.

Generated by Android PR Reviewer for #13315 · copilot · gpt61 · 91.4 AIC · ⌖ 7.97 AIC · ⊞ 19.3K
Comment /review to run again

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13315

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code assessment: no blocking findings. ⚠️ Latest CI is still running.

Reviewed all 21 changed files in full, the relevant callers/project configuration, and the additional ff62264458 commit pushed during this review. New findings: 0 errors, 0 warnings, 0 suggestions. The earlier inline suggestion about narrowing remapping pointer-expression scopes is addressed by that commit; no duplicate inline comment is needed.

The refactor preserves source-level invocation arguments, dispatch, borrowed-ref returns, cache publication, and cleanup ordering. Resource streams remain disposed before their enclosing PEReader; the three canonical T4 templates and generated changes are consistent. The follow-up preserves equality short-circuiting, hash inputs, and address-only diagnostic formatting while narrowing the unsafe contexts.

CI: The current head is ff62264458ad0e7a5cb0b18c100be7ffb624a872. Its new Azure pipeline 1655617 has five checks running and the aggregate check queued; CLA passed. The earlier 41 successful checks belong to the previous head and do not establish that the latest revision is green. Direct Azure DevOps verification was blocked by the CLI authentication requirement.

No local builds or device tests were run during this review, and the revision-specific validation claims were not independently reproduced. No additional code changes are requested; the final CI result remains outstanding.

Generated by Android PR Reviewer for #13315 · copilot · gpt61 · 95.5 AIC · ⌖ 4.67 AIC · ⊞ 20K
Comment /review to run again

@simonrozsival

Copy link
Copy Markdown
Member Author

@jonathanpeppers I started this: #13332

simonrozsival and others added 4 commits October 30, 2026 17:05
Use expression-local unsafe contexts for single-value JNI operations,
array refs, callbacks, and embedded resource reads.  Keep the existing
caller contracts, safety proofs, guards, and cleanup ordering unchanged.

Regenerate the affected T4 outputs together with their templates.  Keep
blocks for pinning, void calls, multi-statement operations, and legacy
pointer getters.  Leave non-preview projects and compiler settings alone.

Co-authored-by: Copilot App <[email protected]>
Keep the sentinel comparison and adjacent safety proof unchanged while
expressing the IsDisposed property with an expression body.

Validate the focused Release build with two nodes and no shared compiler
or build servers.  The 4,300 type/member metadata and normalized IL
records and public XML documentation match the baseline.

Co-authored-by: Copilot App <[email protected]>
Use expression bodies for trivial unsafe properties and get accessors,
including the canonical primitive-array template and generated output.
Preserve guarded bodies, caller modifiers, and adjacent safety proofs.

Follow git blame through the safety-block migration to restore object
var initializers and out-var arguments.  Keep longstanding explicit
scalar declarations instead of performing a broader typing sweep.

Build Java.Interop/net10.0 and legacy tasks/netstandard2.0 in Debug and
Release; all pass.  The 478 generator tests pass.  Release IL and member
metadata match the baseline; normalized Debug IL differs only by return
spills and local numbering.  Public XML documentation is identical.

Co-authored-by: Copilot App <[email protected]>
Keep managed string and scalar operations outside unsafe expressions in
ReplacementMethodInfo.  Scope equality to the three address comparisons
and hash/diagnostic operations to their individual pointer casts.

Preserve left-to-right short-circuiting, hash inputs, numeric-only address
formatting, and the adjacent safety proofs.  Debug and Release builds,
metadata/IL comparisons, and bounded host value-method checks pass.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-unsafe-expression-simplification branch from ff62264 to 61967c2 Compare October 30, 2026 16:09
@simonrozsival
simonrozsival enabled auto-merge (squash) October 30, 2026 16:19
@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 21 changed files against the merge-base, including the canonical templates and generated families, material JNI/callback consumers, task configuration, and actual-target integration differences. The separate final blocker search found no actionable issue.

No blocking issues found. This was a read-only static review.

@simonrozsival
simonrozsival merged commit d9811fc into main Oct 31, 2026
41 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-unsafe-expression-simplification branch October 31, 2026 22:08
simonrozsival added a commit that referenced this pull request Nov 2, 2026
Future Copilot sessions need guidance for inline unsafe expressions and
caller-unsafe contracts without widening unsafe scopes or changing APIs.
Add five compact rules and link the memory-safety overview, as requested
in review:
#13315 (review)

Documentation only; no build or runtime behavior changes.

Co-authored-by: Copilot App <[email protected]>
simonrozsival added a commit that referenced this pull request Nov 2, 2026
Context: #13315 (review)
Context: #13332 (comment)

Future sessions need to know about inline `unsafe (expression)` without loading a detailed unsafe-code checklist into every conversation.

Add a 107-word section to `.github/copilot-instructions.md`, primarily pointing to [Unsafe code best practices](https://learn.microsoft.com/dotnet/standard/unsafe-code/best-practices). Keep the preference for narrow unsafe expressions, the appropriate block contexts, safety documentation, and producer/consumer language compatibility. Link [Improving C# memory safety](https://devblogs.microsoft.com/dotnet/improving-csharp-memory-safety/) for caller contracts. Apply the guidance to affected code rather than requiring repository-wide scans.

Documentation only. After rebasing onto `main`, the exact 107-word section was preserved and all surrounding guide text was verified against `main`; `git diff origin/main HEAD --check` passed. Builds and unit/device tests were not run because no executable code changed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants