Skip to content

[typemap] Classify JNI callback boundary ownership - #13155

Draft
simonrozsival wants to merge 4 commits into
mainfrom
simonrozsival-jni-callback-boundary-ownership
Draft

simonrozsival wants to merge 4 commits into
mainfrom
simonrozsival-jni-callback-boundary-ownership

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Managed-callable JNI callbacks do not all own the same exception boundary. A callback-format marker or package version cannot distinguish a complete modern inline boundary, a trusted marshaling-helper thunk, and an older raw callback. Wrapping every callback repeats transitions and policy; removing every wrapper leaves legacy callbacks unsafe.

Read implementation bodies with PEReader/System.Reflection.Metadata and classify exact trusted helper thunks, complete debugger-aware inline boundaries, native-only UCOs, and explicit raw/unrecognized/unavailable outcomes. Protected managed callbacks receive direct forwarding; legacy/unknown callbacks receive SafeInvoke with the actual managed function-pointer signature and JNI ABI conversions. Signatures beyond the helpers' finite overload set retain equivalent full guarded Begin/catch/runtime-policy/finally-End safety. Native-only UCOs remain direct native registrations. Connector factories are neither invoked nor rooted.

Include ownership and signatures in wrapper reuse, deterministic fingerprints, and legacy cross-RID consistency checks. Existing runtime-implementation resolution and generation inputs are exercised by reference-ordering, packaged-binding, multi-RID, and body-only build regressions. Debug-level logging explains classification outcomes. Generated managed-callback forwarders do not add redundant bridge waits or immediate legacy exception reporting. Constructor/export boundary attribute wiring and legacy API retirement are outside this PR.

Latest-main rebase

Rebased on 2026-10-30 onto main at f1bb0012f1917ebfa6121fbf8cd6f35be7506910; current head is 898df0016bb7143c5aa0b06bf100ee92add9280c. The emitter conflict preserves main's removal of Mono.Android.Runtime while retaining ownership-aware forwarding and the guarded full-safety fallback. Four cases in the constructor/registration test added on main still asserted the superseded catch-and-report implementation; update those assertions to verify SafeInvoke ownership and the callback function pointer, keeping their constructor/native-registration checks intact.

The runtime-policy prerequisite #13153 is merged and included in the base. This PR adds no duplicate JreRuntime override or constructor/export debugger attributes. #13154 is not a dependency. This remains an independent, main-based draft PR; no native stack or readiness change was requested.

Local validation of the current branch

All results below were rerun in this PR's owning worktree after the latest-main rebase. No temporary prerequisite patch or combined checkout was used. Exact TRX, build/binlog, logcat, emitted-IL, and packaged-native-library evidence is retained under:

validation=/Users/simon/.copilot/session-state/8174f939-3569-4f2b-88cf-d26fc23f6ea8/files/rebase-20261030

Release SDK build: passed. Preparation: zero warnings/errors. Full SDK build: 50 warnings, zero errors. Local SDK 12.0.100-alpha.1.26523.103.

make prepare CONFIGURATION=Release
# Passed.
make all CONFIGURATION=Release
# Passed: 50 warnings, zero errors.

Focused host suites: 106 passed, zero failed/skipped. Covers classifier adversarial fixtures, generated forwarding IL and managed/native ABI shape, fallback safety, constructor/registration compatibility, fingerprints, incremental behavior, reference/implementation ordering, manifest aliases, and cross-RID decisions. The initial post-rebase run exposed the four obsolete constructor-test assertions described above; the full selected suites passed after correcting them.

dotnet test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Release -v minimal --filter 'FullyQualifiedName~CallbackBoundaryOwnershipTests|FullyQualifiedName~GenerateTrimmableTypeMapTests|FullyQualifiedName~TrimmableTypeMapIncrementalTests|FullyQualifiedName~TrimmableTypeMapRidCallbackTests|FullyQualifiedName~TrimmableTypeMapManifestAliasTests' --results-directory "$validation/host-results" --logger 'trx;LogFileName=host-final.trx'
# Passed: 106.

Exact implementation corpus: passed. Rebuilt API37 Mono.Android: 29,967 protected helper callbacks and 9 protected inline callbacks. Ten cached pinned public NuGet implementation assets: 7,262 callbacks. Total: 37,238 classifications. The explicit test requires local inputs and does not download packages or add product dependencies.

JNI_CALLBACK_MONO_ANDROID="$PWD/bin/Release/lib/xamarin.android/xbuild-frameworks/Microsoft.Android/37/Mono.Android.dll" JNI_CALLBACK_CORPUS=/Users/simon/.copilot/session-state/5c836ffc-1c2b-4ed7-8c47-9ad43af99698/files/jni-boundary-prototype/samples dotnet test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Release --no-build -v minimal --filter 'FullyQualifiedName=Xamarin.Android.Build.Tests.CallbackBoundaryOwnershipTests.ProductionClassifierMatchesImplementationCorpus' --results-directory "$validation/host-results" --logger 'trx;LogFileName=corpus.trx'
# Passed: 1 exact inventory test.

Build integration: 3 passed, zero failed/skipped. Packaged ref/lib consumption, framework/RID implementation resolution and incrementality, and real body-only raw-to-helper regeneration with emitted-IL verification.

./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj -c Release -v minimal
# Passed: 30 warnings, zero errors.
./dotnet-local.sh test bin/TestRelease/net10.0/Xamarin.Android.Build.Tests.dll --filter 'FullyQualifiedName~TrimmableTypeMapBuildTests.Build_TrimmableTypeMap_UsesMonoAndroidImplementationMetadata|FullyQualifiedName~TrimmableTypeMapBuildTests.BindingCallbackFormatSupportsDefaultConsumer|FullyQualifiedName~TrimmableTypeMapBuildTests.BodyOnlyCallbackBoundaryChangeRegeneratesForwarder' --logger 'trx;LogFileName=integration.trx' --results-directory "$validation/integration-results"
# Passed: 3.

ARM64 CoreCLR: 12 passed, zero failed/skipped. Owned API35 AVD copilot_callback_ownership_8ed1dbeb, port5588, checked before reuse. Tests drive actual scanner-selected generated UCOs for raw, helper-protected, and inline-protected callbacks. Coverage includes success/default returns, exactly-once policy/event handling, Handled suppression, original exception identity, Java catch/finally/rethrow, and publication timing.

./dotnet-local.sh build -t:Rebuild,Install -c Release -m:1 -p:RuntimeIdentifier=android-arm64 '-p:AdbTarget=-s emulator-5588' -p:IncludeCategories=JniCallbackBoundaryOwnership tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v minimal -bl:"$validation/coreclr.binlog"
# Passed: 40 warnings, zero errors.
(cd tests/Mono.Android-Tests/Mono.Android-Tests && ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:RuntimeIdentifier=android-arm64 '-p:AdbTarget=-s emulator-5588' -p:IncludeCategories=JniCallbackBoundaryOwnership --device emulator-5588 --report-trx --results-directory "$validation/coreclr-results")
# Passed: 12.

Actual ARM64 NativeAOT: 12 passed, zero failed/skipped. PublishAot=true was supplied to both install and test. Logcat records NativeAotRuntimeProvider initialization. The installed signed APK's ARM aarch64 ELF ILC library lib/arm64-v8a/libMono.Android.NET-Tests.so was captured before test preparation could rewrite loose native output: SHA-256 9b0491015704584b78528cae6c296b93b72675e87f434c726ca894f3dbf1f237; signed APK SHA-256 b6690023096fe0f2913ff90e210b48c6f1b49c132b6753ff53e79a21dfde17f7. NativeAOT runtime package 11.0.0-preview.7.26381.103 is selected by the current base.

./dotnet-local.sh build -t:Rebuild,Install -c Release -m:1 -p:RuntimeIdentifier=android-arm64 -p:PublishAot=true '-p:AdbTarget=-s emulator-5588' -p:IncludeCategories=JniCallbackBoundaryOwnership tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v minimal -bl:"$validation/nativeaot.binlog"
# Passed: 12 warnings, zero errors.
(cd tests/Mono.Android-Tests/Mono.Android-Tests && ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:RuntimeIdentifier=android-arm64 -p:PublishAot=true '-p:AdbTarget=-s emulator-5588' -p:IncludeCategories=JniCallbackBoundaryOwnership --device emulator-5588 --report-trx --results-directory "$validation/nativeaot-results")
# Passed: 12.

Actual app forwarding IL: verified for both runtimes. Helper/inline forwarders contain only argument loads, a direct callback call, and return. Raw forwarders use the correctly typed managed function pointer and SafeInvokeFunc. No redundant catch/Begin/End/policy, bridge wait, legacy event call, or connector call occurs in these forwarders.

DOTNET_ROLL_FORWARD=LatestMajor DOTNET_ROLL_FORWARD_TO_PRERELEASE=1 ilspycmd -il tests/Mono.Android-Tests/Mono.Android-Tests/obj/Release/net11.0-android/android-arm64/linked/_Mono.Android.NET-Tests.TypeMap.dll
# Passed after CoreCLR run, before NativeAOT rebuild; verified all three ownership forwarders.
DOTNET_ROLL_FORWARD=LatestMajor DOTNET_ROLL_FORWARD_TO_PRERELEASE=1 ilspycmd -il tests/Mono.Android-Tests/Mono.Android-Tests/obj/Release/net11.0-android/android-arm64/typemap/_Mono.Android.NET-Tests.TypeMap.dll
# Passed after NativeAOT run; verified all three ownership forwarders.

Debugger evidence remains historical

Attached debugging was not rerun after this rebase. Historical pre-rebase head c4944e0185cc03ca670f883bbcac0c73488f8b06, supported VS Code coreclr_mobile, user-unhandled filtering, and Optimize=false produced 12/12 passing callback tests with 9 stops at the original callback throw and 9 successful Continues. Default optimized Release had 12/12 passing tests but zero stops. Logs remain in the original session artifact directory.

Stopped-frame Java evaluation failed with file-not-found in that callback run. A subsequent separate constructor/export debugger investigation corrected the assetsPath metadata lookup and demonstrated Java evaluation at a normal breakpoint, but evaluation at user-unhandled exception stops still did not complete. That is not new acceptance evidence for these callbacks. Java evaluation at callback exception stops and NativeAOT attached debugging remain unvalidated; no specific runtime/JNI cause is established. No new attached-debugger or CI success claim is made for this head.

No issue number was supplied. No merging is requested.

@simonrozsival simonrozsival changed the title [typemap] Classify JNI callback boundary ownership [Unsafe][typemap] Classify JNI callback boundary ownership Oct 15, 2026
@simonrozsival simonrozsival changed the title [Unsafe][typemap] Classify JNI callback boundary ownership [typemap] Classify JNI callback boundary ownership Oct 15, 2026
@simonrozsival
simonrozsival force-pushed the simonrozsival-jni-callback-boundary-ownership branch from c4944e0 to a082d71 Compare October 16, 2026 08:40
@simonrozsival
simonrozsival force-pushed the simonrozsival-jni-callback-boundary-ownership branch from a082d71 to 898df00 Compare October 30, 2026 07:36
simonrozsival and others added 4 commits November 21, 2026 08:03
Read implementation callback bodies and signatures instead of inferring
exception safety from assembly format or package versions.  Forward trusted
helper and complete debugger-aware inline boundaries directly; protect raw
or unavailable managed callbacks with SafeInvoke and retain equivalent full
policy for signatures outside its overload set.

Keep already-native UCO callbacks native-only, remove redundant legacy
bridge/report calls, and include ownership in reuse, fingerprints, and
cross-RID consistency checks.  Add adversarial metadata, emitted-IL,
body-only build invalidation, and generated-UCO device coverage.

NativeAOT event-policy equivalence requires the independent JreRuntime
policy fix in #13153; it is not duplicated here.

Co-authored-by: Copilot App <[email protected]>
Keep custom modifiers visible when classifying trusted helper calls and
reject generic or non-default-convention transition APIs.  A same-named
MemberRef with a nonexistent signature must not prove boundary ownership.

Add an adversarial modified-helper fixture.  All 93 targeted host tests and
the exact framework/public-package inventory still pass.

Co-authored-by: Copilot App <[email protected]>
Keep the constructor and native registration coverage added on main, but assert that unavailable managed callback bodies use SafeInvoke instead of the superseded catch-and-report forwarder. This resolves the semantic test conflict after rebasing the boundary-ownership implementation.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-jni-callback-boundary-ownership branch from 8e34a90 to c9d6a21 Compare November 21, 2026 07:03

This branch has not been deployed

No deployments
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.

1 participant