Skip to content

[Mono.Android] Remove internal P/Invokes and simplify startup - #13116

Merged
simonrozsival merged 4 commits into
mainfrom
simonrozsival-coreclr-internal-pinvokes
Oct 14, 2026
Merged

simonrozsival merged 4 commits into
mainfrom
simonrozsival-coreclr-internal-pinvokes

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

The internal runtime P/Invokes duplicate existing managed/JNI functionality or perform work that belongs in startup. Remove that extra native surface and make GC-bridge initialization an explicit part of JNI runtime initialization.

  • Remove the obsolete CPU-detection reflection hook and native export.
  • Replace native logging wrappers with Android.Runtime.Logger, preserving logging tags and category gates.
  • Obtain threshold-class names through Java.Interop using the borrowed class reference. Keep the actual runtime Java name rather than reverse-remapping it.
  • Pass a typed GC-bridge initializer through JnienvInitializeArgs in both native hosts. Keep the callback handshake and one-shot initialization in Microsoft.Android.Runtime.JavaMarshalGCBridge.Initialize().
  • Extract NativeAOT's IGCUserPeer lookup/global-reference setup from Host::OnInit().
  • Wire PinvokeOverride::load_symbol directly into the CoreCLR host contract. Remove internal, liblog, and BCL special cases while retaining library-name normalization, packaged-DSO loading, diagnostics, and null-return fallback.
  • Track clr/pinvoke-override/*.cc in native build inputs so resolver edits rebuild the packaged runtime.
  • Update interop documentation and existing EventSource trimming assertions. No new test fixtures are added.

No issue is closed by this change. The logging-tag rename remains a separate follow-up: #13115.

Local validation

Release SDK build: passed (0 warnings, 0 errors).

make all CONFIGURATION=Release

CoreCLR ARM64 build/install: passed. Runtime initialization suite on the physical ARM64 device: 11 passed, 0 failed, 0 skipped.

./dotnet-local.sh build -t:Install -c Release \
  tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj \
  -p:AndroidRuntime=CoreCLR -p:RuntimeIdentifier=android-arm64 \
  -p:IncludeCategories=RuntimeInitialization '-p:AdbTarget=-s R58Y30HZ65V' -v:quiet
(
  cd tests/Mono.Android-Tests/Mono.Android-Tests
  ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release \
    -p:AndroidRuntime=CoreCLR -p:RuntimeIdentifier=android-arm64 \
    -p:IncludeCategories=RuntimeInitialization '-p:AdbTarget=-s R58Y30HZ65V' \
    --device R58Y30HZ65V --report-trx \
    --results-directory ../../../bin/TestRelease/TestResults/CoreCLRPinvokeNoFlatten
)

NativeAOT ARM64 build/install: passed. Runtime initialization suite on the same device: 11 passed, 0 failed, 0 skipped. NativeAOT is selected with $(PublishAot)=true.

./dotnet-local.sh build -t:Install -c Release \
  tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj \
  -p:PublishAot=true -p:RuntimeIdentifier=android-arm64 \
  -p:IncludeCategories=RuntimeInitialization '-p:AdbTarget=-s R58Y30HZ65V' -v:quiet
(
  cd tests/Mono.Android-Tests/Mono.Android-Tests
  ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release \
    -p:PublishAot=true -p:RuntimeIdentifier=android-arm64 \
    -p:IncludeCategories=RuntimeInitialization '-p:AdbTarget=-s R58Y30HZ65V' \
    --device R58Y30HZ65V --report-trx \
    --results-directory ../../../bin/TestRelease/TestResults/RuntimePrNativeAOTPublish
)

EventSource trimming with the feature switch enabled and disabled: 2 passed, 0 failed, 0 skipped.

./dotnet-local.sh test bin/TestRelease/net10.0/Xamarin.Android.Build.Tests.dll \
  --filter 'Name~RuntimeEventSourceFeatureSwitch'

Patch formatting: passed.

git diff --check

Pull Request
title and
description
should follow the
commit-messages.md workflow documentation, and in particular should include:

  • Useful description of why the change is necessary.
  • Links to issues fixed
  • Unit tests

Remove obsolete CPU detection, native logging, and class-name lookup
P/Invokes.  Use the existing managed logger and Java.Interop class-name
lookup instead of maintaining native wrappers and allocation helpers.

Pass the GC-bridge initializer through the shared JNI startup arguments
for CoreCLR and NativeAOT.  Keep the callback handshake in
JavaMarshalGCBridge and extract NativeAOT peer-class reference setup.

Wire the generic symbol loader directly into the CoreCLR host contract,
removing internal, liblog, and BCL special cases.  Track resolver sources
in native build inputs so changes reliably rebuild the packaged runtime.

Update interop documentation and existing EventSource trimming checks.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 13, 2026 12:51

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.

🔵 Needs a closer look

The cross-runtime startup and resolver changes need targeted coverage for CoreCLR P/Invoke resolution and remapped legacy dispatch.

2 open findings
What changed in this PR

Removes redundant runtime P/Invokes and moves GC-bridge initialization into the managed/native startup contract.

Changes:

  • Replaces internal native exports with managed/JNI implementations.
  • Connects GC-bridge and P/Invoke resolution directly to host contracts.
  • Updates startup, trimming tests, native inputs, and interop documentation.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​JavaMarshalGCBridgeTests.cs Adds runtime initialization coverage category.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​LinkerTests.cs Updates GC-bridge trimming assertions.
src/​native/​nativeaot/​include/​runtime-base/​internal-pinvokes.hh Removes obsolete NativeAOT exports.
src/​native/​nativeaot/​include/​host/​host-nativeaot.hh Declares peer-reference helper.
src/​native/​nativeaot/​host/​host.cc Supplies GC initializer and extracts peer setup.
src/​native/​nativeaot/​host/​CMakeLists.txt Removes obsolete source.
src/​native/​native.targets Tracks resolver sources incrementally.
src/​native/​common/​include/​managed-interface.hh Extends startup ABI with typed callback.
src/​native/​clr/​pinvoke-override/​precompiled.cc Uses consolidated resolver implementation.
src/​native/​clr/​include/​runtime-base/​monodroid-dl.hh Accepts C-string symbol names.
src/​native/​clr/​include/​runtime-base/​internal-pinvokes.hh Removes obsolete CoreCLR exports.
src/​native/​clr/​include/​host/​pinvoke-override.hh Simplifies resolver API.
src/​native/​clr/​include/​host/​pinvoke-override-impl.hh Implements generic symbol loading.
src/​native/​clr/​include/​host/​host.hh Wires resolver into CoreCLR contract.
src/​native/​clr/​include/​host/​host-common.hh Removes native class-name lookup state.
src/​native/​clr/​host/​internal-pinvokes-shared.cc Deletes redundant native wrappers.
src/​native/​clr/​host/​host.cc Supplies GC initializer during startup.
src/​native/​clr/​host/​host-shared.cc Removes class-name conversion helper.
src/​native/​clr/​host/​CMakeLists.txt Removes obsolete source.
src/​Mono.Android/​Mono.Android.csproj Stops compiling removed wrappers.
src/​Mono.Android/​Microsoft.Android.Runtime/​JavaMarshalRegisteredPeers.cs Relocates initialization responsibility.
src/​Mono.Android/​Microsoft.Android.Runtime/​JavaMarshalGCBridge.cs Owns one-shot bridge initialization.
src/​Mono.Android/​Java.Interop/​TypeManager.cs Removes native class-name wrapper.
src/​Mono.Android/​Android.Runtime/​XAPeerMembers.cs Uses Java.Interop class-name lookup.
src/​Mono.Android/​Android.Runtime/​RuntimeNativeMethods.cs Removes internal P/Invoke declarations.
src/​Mono.Android/​Android.Runtime/​JNINativeWrapper.cs Uses managed logging.
src/​Mono.Android/​Android.Runtime/​JNIEnvInit.cs Integrates GC initialization and logging.
src/​Mono.Android/​Android.Runtime/​JNIEnv.cs Replaces native logging calls.
src/​Mono.Android/​Android.Runtime/​AndroidEnvironment.cs Removes CPU-detection hook.
src/​Mono.Android.Runtime/​Mono.Android.Runtime.csproj Removes deleted wrapper source.
src/​Microsoft.Android.Runtime.NativeAOT/​Android.Runtime.NativeAOT/​JavaInteropRuntime.cs Passes startup arguments onward.
src/​java-runtime/​java/​mono/​android/​Runtime.java Removes unused class field.
Documentation/​guides/​internals/​JavaJNI_Interop.md Documents startup and naming behavior.

🧠 Review effort: Balanced

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • azcliprod.blob.core.windows.net

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "azcliprod.blob.core.windows.net"

See Network Configuration for more information.

Generated by Android PR Reviewer for #13116

Preserve the direct load_symbol callback and C-string arguments while
adopting upstream native Java.Interop removal.  Use dlsym and the
upstream RTLD_NOW | RTLD_LOCAL flags without restoring obsolete wrappers.

Validate the merged Release SDK, CoreCLR and NativeAOT startup suites
(11 tests each), and both EventSource trimming feature-switch cases.

Co-authored-by: Copilot App <[email protected]>
@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 13, 2026

@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.

⚠️ Review complete; CI pending — 0 errors, 0 warnings, 1 suggestion.

The managed/native startup handshake is consistent across CoreCLR and NativeAOT, the ABI layout assertions match the managed structure, and the JNI borrowed-reference usage is sound. I left one inline suggestion to add focused coverage for the newly unified P/Invoke resolver contract.

The available checks currently show two successes, four jobs in progress, and the aggregate dotnet-android check queued, so this is not yet a green-CI verdict.

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • azcliprod.blob.core.windows.net

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "azcliprod.blob.core.windows.net"

See Network Configuration for more information.

Generated by Android PR Reviewer for #13116 · copilot · gpt56 · 430.3 AIC · ⌖ 11.2 AIC · ⊞ 26.4K
Comment /review to run again

if (!Util::path_has_directory_components (library_name)) {
char stack_buffer [Util::LocalPathBufferSize];
char *short_library_name = Util::format_dso_name (stack_buffer, sizeof (stack_buffer), library_name, true);

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.

🤖 💡 Testing — Now that this implementation is wired directly into the CoreCLR host contract, could we add focused coverage for the resolver behavior that this refactor relies on: log/liblog name normalization, packaged-DSO lookup, and the nullptr fallback for a missing library or symbol? The runtime-initialization runs exercise successful startup, but they do not make these resolver contracts explicit, so a regression here would otherwise surface later as an unrelated DllNotFoundException/EntryPointNotFoundException.

Rule: Test behavior, not implementation

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@simonrozsival
simonrozsival enabled auto-merge (squash) October 13, 2026 15:43

@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.

The complete 32-file correctness and separate end-to-end reviews found no current high-confidence blocker. Both startup hosts preserve the typed GC-initialization ABI, callback handshake, one-shot initialization and peer setup; borrowed threshold references, logging gates/tags, generic resolver behavior and packaged-runtime rebuild inputs are consistent. The explicitly accepted existing-test boundary and separate logging-tag follow-up are not being relitigated.

The supplied failed wake-device test emitted its expected DOTNET marker from the fresh app PID in logcat, while captured dotnet-run output stopped at launch completion. The pinned runner and failing test are unchanged between base and head, and no causal defect in this PR was established. This source approval does not claim that CI is green or that the failure is definitively flaky/infrastructure, and no repository tests were executed by this review.

Preserve explicit GC bridge startup and the peer-class helper while adopting NativeAOT static ELF remapping data loading.

Co-authored-by: Copilot App <[email protected]>

@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.

The complete current 32-file revision was re-reviewed against the prior approved head, including the new-baseline NativeAOT bootstrap/reference-manager interactions. Both runtime startup paths preserve the typed initialization ABI, callback lifecycle and ordering; borrowed threshold references, logging, generic resolver/loading/fallback behavior and source-to-packaged-output wiring remain consistent. The separate integration pass, candidate dispositions and final independent search found no high-confidence blocker.

The accepted existing-test boundary and separate logging-tag follow-up remain accepted. This is source approval, not green CI, executed validation or retry-safety guidance: both investigated current macOS failures occur during CLI/NuGet first-use before MSBuild evaluation, compilation or tests. The underlying mutex cause remains unknown; no old wake-device inference was used and no current source path establishes PR attribution.

@dalexsoto

Copy link
Copy Markdown
Member

@simonrozsival Not reviewing this request in this iteration: The PR head changed while this iteration refreshed its review context, from 8112144 to 23c13fa. The newly observed revision has not received a complete current-head source review, so no review is being submitted for it in this iteration. It remains tracked for a fresh-context exhaustive review.

@simonrozsival
simonrozsival merged commit abf6073 into main Oct 14, 2026
41 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-coreclr-internal-pinvokes branch October 14, 2026 18:06
simonrozsival added a commit that referenced this pull request Oct 28, 2026
…3281)

Context: #13116

Context: #10461

### Simplify the host

After the internal P/Invoke removal, the NativeAOT-specific host still spreads a small amount of startup code across forwarding classes, JNI wrappers, environment helpers, and bootstrap files.  These layers no longer provide a useful separation: the host applies bootstrap environment data, supplies native JNI initialization, and connects the GC bridge.

Consolidate that glue into `host.cc`, remove the forwarding headers and unused CoreCLR source inputs, and use consistent `NativeAOT_*` entry-point names in the native definitions, managed imports, and linker arguments.  Keep the bootstrap property reader out of line in `app-system-properties.cc`.

The early environment callback remains hidden and selected through `DT_INIT`, so environment variables are applied before NativeAOT's constructors run.  Required bootstrap symbols remain strong, optional remapping symbols remain weak, and the JNI wrappers continue to duplicate borrowed string references before taking ownership.

### Remove the unused shared host

The NativeAOT host has built both static and shared libraries since its introduction in #10461, but applications have selected the static archive from the beginning.  The shared library's export map exposes no API, and no runtime consumer was found.  The NuGet pack project also explicitly selects only the host archives: the checked published ARM64 packages `36.0.0-rc.2.332`, `36.1.2`, `36.1.118`, and `37.2.0-rc.2.84` contain those archives, not `libnaot-android*.so`.  The shared libraries reach local SDK packs through the native output copy wildcard instead.

Build only the static host archives and remove the shared target, export map, and `DYNAMIC_RUNTIME_LINKING` branches.  Track both Debug and Release archives as native build outputs instead of using the unused shared library as an incremental-build sentinel.  Delete stale shared hosts from native output and local runtime packs before wildcard copying, so an existing checkout does not keep copying artifacts that are no longer built.

This removes an unused local-build artifact, not a shared host shipped by the checked published runtime NuGets.  The static host and its application-link contract remain in place.  No linked issue is being closed.
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 14, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

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