Repository navigation
Move CoreCLR reference accounting and logging to C# - #12860
Conversation
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Unresolved moderate correctness, permission, and performance findings remain.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 2
Open (3)
What changed in this PR
Moves JNI reference accounting and logging from native code into AndroidObjectReferenceManager, while preserving configuration parsing and runtime callback plumbing.
Changes:
- Adds managed counters, formatting, output, thresholds, callbacks, and focused tests.
- Updates MonoVM, CoreCLR, and NativeAOT startup and P/Invoke wiring.
- Removes obsolete native counters, writers, P/Invokes, and resolver entries.
| File | Summary |
|---|---|
tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj |
Registers reference-manager tests. |
tests/Mono.Android-Tests/Mono.Android-Tests/Android.Runtime/AndroidObjectReferenceManagerTests.cs |
Tests formatting, counting, files, and disposal. |
src/profiled-aot/dotnet.aotprofile.txt |
Removes obsolete P/Invoke profile entries. |
src/native/nativeaot/include/runtime-base/internal-pinvokes.hh |
Updates NativeAOT callback declarations. |
src/native/nativeaot/host/host.cc |
Passes logging configuration to managed startup. |
src/native/mono/runtime-base/logger.hh |
Exposes logging configuration accessors. |
src/native/mono/runtime-base/logger.cc |
Retains parsing and removes native output. |
src/native/mono/runtime-base/internal-pinvokes.hh |
Updates callback declarations. |
src/native/mono/runtime-base/android-system.hh |
Removes obsolete logging globals. |
src/native/mono/runtime-base/android-system.cc |
Removes obsolete logging definitions. |
src/native/mono/pinvoke-override/pinvoke-tables.include |
Regenerates Mono P/Invoke mappings. |
src/native/mono/pinvoke-override/generate-pinvoke-tables.cc |
Updates P/Invoke generation inputs. |
src/native/mono/monodroid/osbridge.hh |
Defines the managed logging callback API. |
src/native/mono/monodroid/osbridge.cc |
Delegates reference events to managed code. Moderate performance finding, 1 vote: avoid JNI and thread metadata queries when logging is disabled. |
src/native/mono/monodroid/monodroid-glue.hh |
Removes obsolete logging globals. |
src/native/mono/monodroid/monodroid-glue.cc |
Passes logging configuration during initialization. |
src/native/mono/monodroid/internal-pinvokes.cc |
Implements callback registration. |
src/native/common/include/managed-interface.hh |
Adds shared callback and configuration ABI. |
src/native/clr/runtime-base/logger.cc |
Retains CoreCLR configuration parsing. |
src/native/clr/pinvoke-override/precompiled.cc |
Adds callback resolver support. |
src/native/clr/include/runtime-base/logger.hh |
Updates the logger API. |
src/native/clr/include/runtime-base/internal-pinvokes.hh |
Updates callback declarations. |
src/native/clr/include/host/os-bridge.hh |
Defines CoreCLR callback methods. |
src/native/clr/host/os-bridge.cc |
Delegates CoreCLR events to managed code. |
src/native/clr/host/internal-pinvokes-shared.cc |
Implements callback registration. |
src/native/clr/host/host.cc |
Passes logging configuration to managed startup. |
src/native/clr/host/bridge-processing.cc |
Emits managed GC-bridge events. Moderate performance finding, 1 vote: avoid JNI and thread metadata queries when logging is disabled. |
src/Mono.Android/Mono.Android.csproj |
Includes the new manager. |
src/Mono.Android/Java.Interop/Runtime.cs |
Reads the managed global-reference count. |
src/Mono.Android/Android.Runtime/RuntimeNativeMethods.cs |
Replaces obsolete P/Invokes with callback registration. |
src/Mono.Android/Android.Runtime/JNIEnvInit.cs |
Receives logging configuration. |
src/Mono.Android/Android.Runtime/AndroidRuntime.cs |
Removes the embedded manager and routes diagnostics. |
src/Mono.Android/Android.Runtime/AndroidObjectReferenceManager.cs |
Implements managed accounting and logging. Moderate findings: preserve invalid-reference accounting behavior, apply file permissions, gate diagnostic metadata and stack traces, and preserve <null> log formatting. Nit findings: update documentation source references. Votes: 2, 2, 1, 1, 1, 1, and 2 respectively. |
src/Microsoft.Android.Runtime.NativeAOT/Android.Runtime.NativeAOT/JavaInteropRuntime.cs |
Uses the shared managed manager. Nit maintainability finding, 1 vote: remove or document obsolete duplicate diagnostic implementations. |
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
✅ LGTM
Findings: 0 errors · 0 warnings · 1 suggestion
The managed/native ABI remains aligned, reference transitions preserve the existing accounting paths, callback failures are contained at the unmanaged boundary, and the focused tests cover formatting, counters, file behavior, and writer ownership. The linked-output regression check is also a strong guard for the logging-disabled path. All 44 checks are green.
I left one non-blocking inline suggestion about releasing the native path allocations after managed startup copies them.
Generated by Android PR Reviewer for #12860 · copilot · gpt56 · 378.7 AIC · ⌖ 11.1 AIC · ⊞ 26K
Comment /review to run again
| Util::create_public_directory (override_dir); | ||
| char stack_buffer [Util::LocalPathBufferSize]; | ||
| char *path_buffer = Util::join_paths (stack_buffer, sizeof (stack_buffer), override_dir, fallback_filename); | ||
| return gref_file; |
There was a problem hiding this comment.
🤖 💡 Native memory — gref_file and lref_file are heap allocations populated by set_category(). Before this change, init_reference_logging() freed both after opening the logs; now the getters hand them to managed startup, where the strings are copied, but the native allocations are never released. Could the handoff include an explicit cleanup after InitializeCommonState() has marshaled the paths (or otherwise make their process-lifetime ownership explicit)?
Rule: Release native allocations when ownership ends
Make AndroidObjectReferenceManager own gref, weak-gref, and lref accounting and output while retaining callbacks for native GC bridge transitions. Co-authored-by: Copilot App <[email protected]>
Restore MonoVM reference accounting, logging, P/Invokes, and GC bridge integration while selecting the managed implementation for CoreCLR and NativeAOT. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
08713a0 to
006182a
Compare
Keep managed reference accounting after MonoVM removal. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully! Warning Firewall blocked 1 domainThe following domain was blocked by the firewall during workflow execution:
To allow these domains, add them to the network:
allowed:
- defaults
- "azcliprod.blob.core.windows.net"See Network Configuration for more information.
|
There was a problem hiding this comment.
logger.cc thread; I did not duplicate that inline feedback.
New findings: 0 errors, 0 warnings, 1 suggestion. The added tests cover formatting, accounting, permissions, and disposal well; I left one inline suggestion for the custom-path failure/fallback path.
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 #12860 · copilot · gpt56 · 181.4 AIC · ⌖ 11.1 AIC · ⊞ 25.9K
Comment /review to run again
| Assert.AreEqual ("default" + Environment.NewLine, File.ReadAllText (fallbackPath)); | ||
| AssertReferenceLogFileMode (fallbackPath); | ||
|
|
||
| Assert.IsNull (global::Android.Runtime.ManagedObjectReferenceManager.CreateLogWriter (true, true, explicitPath, directory, "fallback.txt", "test")); |
There was a problem hiding this comment.
🤖 💡 Testing — Could this also cover the failure-and-fallback path by supplying an unusable explicit path and verifying that fallback.txt is created? That behavior is important to this migration (TryCreateLogWriter(customPath) must fail without preventing the override-directory fallback), while the current cases exercise only successful opens and light logging.
Rule: Test error paths
## Motivation The CoreCLR/NativeAOT GC bridge previously split SCC traversal, JNI reference transitions, temporary Java peers, and Java GC between managed peer tracking and a large native processor. Now that #12860 moved reference accounting and logging to managed code, the bridge algorithm can live beside the peer state it operates on. ## Processing flow 1. The runtime's stopped-GC callback publishes its `MarkCrossReferencesArgs*` to a single-slot native mailbox and posts a semaphore without entering managed code. 2. A process-lifetime native worker takes the arguments and invokes one `[UnmanagedCallersOnly]` callback in `JavaMarshalGCBridge`. 3. Managed code processes SCCs and cross-references, creates temporary peers, swaps strong/weak JNI references, invokes Java GC, collects dead contexts, and calls `JavaMarshal.FinishCrossReferenceProcessing` before returning to the worker. The original `GCBridge` class and `gc-bridge.cc/.hh` filenames remain; its old C++ algorithm has been removed. Bridge registration occurs **after** `JniRuntime.SetCurrent` in both CoreCLR and NativeAOT, so the worker cannot use the JNI reference manager before it is published. The upstream EventSource GC-bridge start/stop events are retained around each managed round. ## Behavior and scope - Reference creation and deletion pass through `ManagedObjectReferenceManager`; a worker-thread marker suppresses threshold-triggered managed GC during bridge reference operations and initial JNI cache setup. - Reference diagnostics are guarded at their call sites, including when global-reference logging is off. Verbose GC-bridge logging is disabled by default in trimmed apps, with `_AndroidEnableGCBridgeLogging=true` as an opt-in. - Native callbacks and logging code rendered unused by the move are removed. MonoVM's GC bridge is unchanged. - Exceptions cannot unwind through the unmanaged callback: a failed bridge round terminates via `Environment.FailFast`. - #12860 is already merged into `main`; this PR targets `main` directly. ## Size and trimming analysis Compared **identical minimal arm64 Release apps** using the same repository-local .NET SDK and build properties against this PR and its pinned `main` parent (`7a170b185a`). NativeAOT builds emitted both DGML dependency graphs and mstat files; Sizoscope compared the mstat snapshots. The CoreCLR app used the trimmable typemap. | Output | `main` | This PR | Change | | --- | ---: | ---: | ---: | | NativeAOT mstat accounted size | — | — | +13.0 kB | | NativeAOT stripped app `.so` | 3,936,392 B | 3,924,728 B | **−11,664 B** | | NativeAOT APK | 1,726,272 B | 1,726,272 B | unchanged | | CoreCLR linked `Mono.Android.dll` | 231,424 B | 240,640 B | +9,216 B | | CoreCLR `libassembly-store.so` | 2,399,312 B | 2,409,800 B | +10,488 B | | CoreCLR `libmonodroid.so` | 187,400 B | 152,408 B | **−34,992 B** | | CoreCLR APK | 6,543,839 B | 6,547,935 B | +4,096 B | The DGML graph roots the new managed SCC processor and its JNI helper through the bridge callback; these are the functional code replacing the native implementation. Sizoscope attributes approximately +6.1 kB net to `Mono.Android` and +3.0 kB to `Java.Interop`. The native-code reduction offsets the managed growth in NativeAOT; APK compression and alignment obscure the smaller component changes. The earlier large *Simple* `.apkdesc` delta is not a matched-main measurement: those references predate the rebased parent and should not be attributed entirely to this PR. **Default logging is already trimmed.** The default NativeAOT map contains none of `LogArguments`, `LogSummary`, `WriteReferenceDiagnostic`, or the logging-only stack-trace field; stack-trace method size is unchanged from `main`. As controls, opting into GC-bridge logging adds 4.5 kB to mstat-accounted size, and opting into object-reference logging adds 21.4 kB. Further substantial savings would require changing the functional JNI bridge path rather than adding another logging switch. These measurements are from a minimal app and are not promised byte deltas for other apps. ## Validation - The managed runtime and CoreCLR/NativeAOT native hosts built after rebasing onto `main`. - The new fixture covers ABI layout, temporary-peer cross-references, and a real bridge round with a managed peer cycle that survives while Java-rooted and is collectible after release. - Azure build [#1613442](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1613442) tested the rebased bridge commit: 38/42 jobs passed, including the device tests. Its four failures were XForms CoreCLR size-reference tests; both `.apkdesc` files were updated from the macOS test attachments in `b049149b1f` (Windows packages matched; assembly-store entries differed by 32–56 B). Build [#1613543](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1613543) is in progress for that updated head.


Motivation
For CoreCLR and NativeAOT, JNI references are created and released through managed
Java.Interop, but their accounting and diagnostic logging were still owned by the native runtime. Every reference operation crossed into C++ to update counters or format a log entry, splitting one responsibility across two runtimes and making the behavior difficult to test in isolation.The split also made the GC bridge harder to migrate: bridge-created references needed to participate in the same counters and logs, but the only reusable implementation was embedded in native runtime code.
This PR makes managed code the source of truth for reference accounting and logging in the non-Mono runtime family. It establishes the shared surface used by the follow-up GC-bridge migration in #12861.
What changes
ManagedObjectReferenceManagerfor CoreCLR and NativeAOT.+g+/-g-,+w+/-w-, and+l+/-l-message formatting, stack traces, file output, and logcat output into managed code.gref,gref+,gref-, andgref=<path>lref,lref+,lref-, andlref=<path>grefs.txtandlrefs.txtfiles0664file permissions<null>for unnamed threadsJava.Interop.Runtime.GlobalReferenceCountto read the managed authoritative count for the non-Mono runtimes.Runtime boundary
MonoVM is intentionally unchanged. It continues to use its existing
AndroidObjectReferenceManager, C++ gref/lref/wref counters and logging, internal P/Invokes, and native Mono GC bridge.CoreCLR and NativeAOT are treated as one runtime family and use the new managed implementation.
Stack
This is layer 1 of 2:
Validation
Mono.Android,Microsoft.Android.Runtime.NativeAOT, andXamarin.Android.Build.Tests.src/native/mono/**or profiled-AOT changes.The full on-device runtime suite was not run because this workspace does not have a prepared local SDK/device.