Repository navigation
[Unsafe] Opt tooling into updated C# memory-safety rules - #13189
Merged
simonrozsival merged 2 commits intoOct 29, 2026
Merged
Conversation
Contributor
There was a problem hiding this comment.
🔵 Needs a closer look
Experimental compiler enforcement and borrowed-memory contracts warrant human confirmation beyond the supplied narrow current-head validation.
No open issues 🎉
What changed in this PR
Prepares host tooling for updated C# memory-safety rules as a scoped layer of the native-safety migration.
Changes:
- Enables preview memory-safety rules in three tooling projects.
- Moves implementation-owned unsafe operations into local blocks and classifies
renameas safe. - Documents borrowed resource-stream lifetimes and updates all three import callsites.
| File | Description |
|---|---|
| tools/tmt/tmt.csproj | Enables tooling-local compiler rules. |
| src/Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj | Enables tooling-local compiler rules. |
| src/Xamarin.Android.Build.Tasks/Utilities/TypeMapHelper.cs | Scopes unsafe encoding locally. |
| src/Xamarin.Android.Build.Tasks/Utilities/PathUtil.cs | Scopes unsafe path traversal locally. |
| src/Xamarin.Android.Build.Tasks/Utilities/MetadataExtensions.cs | Documents borrowing obligations and scopes unsafe operations. |
| src/Xamarin.Android.Build.Tasks/Utilities/FileUtil.cs | Classifies marshalled rename as safe. |
| src/Xamarin.Android.Build.Tasks/Tasks/ResolveLibraryProjectImports.cs | Explicitly acknowledges borrowed-stream contracts. |
| src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj | Enables tooling-local compiler rules. |
Review effort: Balanced
This was referenced Oct 19, 2026
Base automatically changed from
simonrozsival-jni-caller-contract-preparation
to
main
October 28, 2026 22:30
Enable the updated model locally in both build-task assemblies and the typemap tool. Keep pinned encoding and path traversal implementation-owned, and document the borrowed PE resource stream caller lifetime. Co-authored-by: Copilot App <[email protected]>
Document the borrowed PE resource stream lifetime, backing-storage bounds and alias/thread obligations. Record concrete safety proofs inside each audited block without changing executable code, caller classifications or project properties. Co-authored-by: Copilot App <[email protected]>
simonrozsival
force-pushed
the
simonrozsival-unsafe-tooling-contracts-stack
branch
from
October 29, 2026 10:05
bafafa0 to
fe23ca8
Compare
6 tasks
Member
Author
|
@dalexsoto review |
simonrozsival
enabled stacked auto-merge (squash)
October 29, 2026 12:36
jonathanpeppers
approved these changes
Oct 29, 2026
simonrozsival
deleted the
simonrozsival-unsafe-tooling-contracts-stack
branch
October 29, 2026 13:26
This was referenced Oct 29, 2026
simonrozsival
added a commit
that referenced
this pull request
Oct 30, 2026
Context: #11467 **Publication status:** the description below covers the prepared local revision at `181f2a5b3731`, rebased onto tooling [#13189](#13189). It has not been pushed: this PR still publishes `898022e97e31`. The prepared binding delta is six commits, 129 files, +6020/-2123. Generated bindings historically put `unsafe` on managed methods, properties and constructors because their implementations call JNI. Under the updated C# memory-safety rules, that modifier also imposes an obligation on callers. A managed override or interface implementation can therefore acquire an unsafe contract merely because it marshals an argument or invokes Java, even though its managed signature requires no such obligation. Separate the caller contract from the implementation context. Keep managed binding methods, accessors, ordinary constructors and typed callback targets safe, and place JNI argument storage, invocation and raw-reference conversion in local `unsafe` regions. Keep constants, guards and managed-only work outside those regions where practical; retain contiguous marshaling and cleanup where splitting them would complicate temporary lifetimes. Add concrete `// SAFETY:` explanations without changing JNI signatures, dispatch, allocations, copy-back or failure cleanup. Raw JNI callback entry points and marshal targets remain caller-unsafe, with documentation covering the registered ABI, attached thread, borrowed-reference lifetime and aliasing. ### Throwable construction and compatibility A safe managed Throwable constructor cannot initialize its base through a caller-unsafe raw-handle constructor. Add the approved None-only deferred-peer constructor and forwarding path instead. It accepts no JNI reference, creates no Java peer and has no Java-constructor registration; the normal binding constructor still performs JNI construction. Preserve peer-constructor partial hooks, and use an imported base's actual accessible capability rather than emitting an unavailable constructor call. The API baselines add 435, 435 and 437 constructor signatures for APIs 37, 37.1 and 37.2. Broader enforcement on non-Throwable raw class and invoker constructors is explicitly deferred to preserve existing safe zero/`DoNotTransfer` base initializers. Their handle type, thread, lifetime, aliasing and ownership obligations still apply, including on failure: these constructors construct peers, not opaque-address containers. Document that enforcement gap without adding a general initialization API or making managed derived constructors caller-unsafe. Preserve legacy compiler syntax and both default and direct-UCO callback formats. Regenerate 97 existing golden files from the canonical emitters; retain existing tests rather than adding annotation-only matrices. Remove the temporary audit-only compiler harness and its associated tests. This layer does not enable updated rules on Java.Interop, Mono.Android or customer projects, and does not close #11467. ### Validation The reduced preparation source, subsequently committed as `11eb8c228de9`, passed the existing full generator suite (**478 passed, 0 failed, 0 skipped**) and SourceWriter suite (**11 passed, 0 failed, 0 skipped**). Both ran normally, without update/bless mode or exclusions, using SDK `12.0.100-alpha.1.26509.101`, net10.0 test assemblies and the arm64 `12.0.0-alpha.1.26509.101` runtime. Existing test identities were unchanged. These are retained results from before the later parent rebases, **not validation of the current dependency chain**. All 97 golden files remain byte-identical; the latest overlap only incorporates upstream documentation/comment changes and removal of an obsolete test stub. Fresh combined SDK/runtime/device validation remains outstanding and was not run for this description update. Earlier integrated stack results are historical, not evidence for the current rebased composition.
simonrozsival
added a commit
that referenced
this pull request
Oct 31, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Context: #11467, revisiting
unsafein generated code and libraries; this PR does not close it.Context: #13085, removing temporary preview-language overrides when the compiler no longer needs them.
The updated C# memory-safety model separates obligations that callers must satisfy from unchecked operations owned by an implementation. Enable
$(Features);updated-memory-safety-ruleslocally inXamarin.Android.Build.TasksandMicrosoft.Android.Build.Tasks, preserving existing feature switches rather than changing customer-project compiler settings.Keep
Xamarin.Android.Tasks.MetadataExtensions.GetEmbeddedResourceStream()caller-unsafe. Its returned stream borrows thePEReaderimage without retaining or owning the reader. Document the resource bounds, backing-storage lifetime and stability, and prevention of alias/thread invalidation, including exceptional exits. Put unchecked operations in narrow implementation-local blocks with concrete// SAFETY:explanations, and audit the three resource-import calls so synchronous consumption and stream/archive disposal complete before reader disposal.Keep managed path traversal safe-callable: the implementation pins immutable strings and checks both bounds before dereferencing. Explicitly classify the marshalled
libcrename import as safe; the marshaller supplies the path buffers for the synchronous call and native code retains neither pointer. Preserve behavior, accepted calls, allocation choices, and cleanup ordering. No ownership redesign, buffer copies, new input restrictions, or annotation-only tests are introduced.Retain project-local
LangVersion=preview. With SDK12.0.100-alpha.1.26523.103, the feature flag alone still fails with CS8652 because the updated rules require the preview language version;LangVersion=16is rejected with CS1617. #13085 tracks removing these overrides as soon as the compiler supports doing so. Preservemain's removal ofTypeMapHelperand itstools/tmtsource link: neither the deleted helper nor the obsoletetmtcompiler opt-in is restored.Validation
Results apply to published revision
fe23ca8c07d76f1702c42ed8009d18dc1569a8a5, rebased onto608c74d49c0f449aa42b357191c94d0ada55cb9e, using repository SDK12.0.100-alpha.1.26523.103. The diff is six files, +66/-16. No repository tests are added or changed.DOTNET_PROCESSOR_COUNT=2 CMAKE_BUILD_PARALLEL_LEVEL=2 DOTNET_CLI_USE_MSBUILD_SERVER=0 MSBUILDDISABLENODEREUSE=1 make prepare CONFIGURATION=Debug MSBUILD_ARGS='-m:1 -p:UseSharedCompilation=false'— passed, 0 warnings/errors.DOTNET_PROCESSOR_COUNT=2 CMAKE_BUILD_PARALLEL_LEVEL=2 DOTNET_CLI_USE_MSBUILD_SERVER=0 MSBUILDDISABLENODEREUSE=1 UseSharedCompilation=false make leeroy CONFIGURATION=Debug _MSBUILD_ARGS='-m:1 -p:UseSharedCompilation=false'— passed the Debug SDK, APIs 37/37.1/37.2, packs, and local workload. Retained 29 primary-phase and 62 extra-API warnings; 0 errors. An initialmake allcompiled the solution but failed workload setup because it did not build the extra API references;make leeroycompleted those existing targets without build-system changes.Run each command below with
DOTNET_PROCESSOR_COUNT=2 DOTNET_CLI_USE_MSBUILD_SERVER=0:./dotnet-local.sh build src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj -c Debug --no-restore -p:BuildProjectReferences=false -p:UseSharedCompilation=false -m:1 -nr:false -v:minimal -nologo./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj -c Debug --no-restore -p:BuildProjectReferences=false -p:UseSharedCompilation=false -m:1 -nr:false -v:minimal -nologomain; 0 errorsFor each project above, plus
tools/tmt/tmt.csprojandexternal/Java.Interop/src/Java.Interop/Java.Interop.csproj,./dotnet-local.sh msbuild "$project" -getProperty:Features,LangVersion -m:1 -nr:false -p:UseSharedCompilation=false -nologopassed. Both task projects evaluate toFeatures=";updated-memory-safety-rules"andLangVersion="preview".tmtretains emptyFeaturesandLangVersion="latest"; Java.Interop retains emptyFeaturesand its existingLangVersion="preview".Existing resource-import tests used
DOTNET_PROCESSOR_COUNT=2 DOTNET_CLI_USE_MSBUILD_SERVER=0 DOTNET_ROLL_FORWARD=Major, withNUNIT_MSBUILD_ARGSset to newline-separated-m:1,-p:UseSharedCompilation=false, and-nr:false.$artifactsbelow denotes the retained session-evidence directory.Initial result: CoreCLR passed; NativeAOT failed the fourth-build assertion that
_CompileJavashould be skipped. Rebuilding the two task assemblies from unmodifiedmainand running the NativeAOT case passed. After restoring this revision and rebuilding both task assemblies, rerun without concurrent task builds:Repeat result: 1 passed, 0 failed/skipped; all five fixture builds completed. The initial failure is retained, not counted as a pass or claimed to have a proven root cause. These are host build/incremental tests, not on-device runtime execution. Release SDK and device tests were not run for this tooling-only change.