Skip to content

Move CoreCLR reference accounting and logging to C# - #12860

Merged
jonathanpeppers merged 6 commits into
mainfrom
simonrozsival-csharp-reference-logging
Sep 23, 2026
Merged

jonathanpeppers merged 6 commits into
mainfrom
simonrozsival-csharp-reference-logging

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

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

  • Adds ManagedObjectReferenceManager for CoreCLR and NativeAOT.
  • Moves global, weak-global, and local reference accounting into managed code using thread-safe counters.
  • Moves +g+/-g-, +w+/-w-, and +l+/-l- message formatting, stack traces, file output, and logcat output into managed code.
  • Preserves the existing logging configuration and output contract:
    • gref, gref+, gref-, and gref=<path>
    • lref, lref+, lref-, and lref=<path>
    • default grefs.txt and lrefs.txt files
    • 0664 file permissions
    • established reference-line formats, including <null> for unnamed threads
  • Keeps logging-disabled reference operations and native callbacks on direct feature-switch-controlled counter-only paths. This avoids collecting reference types, thread metadata, stack traces, or callback strings and allows ILLink to remove the logging-only formatting/output graph from release apps.
  • Keeps native configuration parsing, but passes the parsed paths and mode flags to managed startup.
  • Adds a narrow callback boundary for references still created by native non-Mono bridge code. Native code reports structured transitions; managed code owns accounting and output.
  • Removes the obsolete CoreCLR/NativeAOT native counters, reference-log writers, formatting entry points, and resolver entries.
  • Updates Java.Interop.Runtime.GlobalReferenceCount to read the managed authoritative count for the non-Mono runtimes.
  • Adds a linked-output regression check that verifies disabled reference logging removes its formatting, file, thread, and stack-trace helpers.

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:

  1. Move CoreCLR reference accounting and logging to C# #12860: move non-Mono JNI reference accounting and logging to C#.
  2. Move non-Mono GC bridge processing to managed code #12861: move non-Mono GC bridge processing to C#, using the managed reference surface introduced here.

Validation

  • Built Mono.Android, Microsoft.Android.Runtime.NativeAOT, and Xamarin.Android.Build.Tests.
  • Built arm64 Debug and Release native runtimes for CoreCLR and NativeAOT.
  • Passed 10 focused reference-manager tests covering formatting, counting, configuration, file permissions, disabled-logging behavior, and disposal.
  • Replayed the failing CI app's exact ILLink argument graph and verified disabled builds retain counter/callback code but remove all logging-only methods.
  • Verified the effective diff contains no src/native/mono/** or profiled-AOT changes.
  • Verified Mono registers no new reference-logging callbacks.
  • Verified the final diff has no whitespace errors.

The full on-device runtime suite was not run because this workspace does not have a prepared local SDK/device.

Copilot AI lite review requested due to automatic review settings September 22, 2026 06:40

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.

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 Medium severity · 1 Low severity

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.

@simonrozsival simonrozsival added the do-not-merge PR should not be merged. label Sep 22, 2026
@simonrozsival simonrozsival added this to the .NET 12 milestone Sep 22, 2026
@simonrozsival simonrozsival changed the title Move JNI reference accounting and logging to C# Move CoreCLR reference accounting and logging to C# Sep 22, 2026
@simonrozsival simonrozsival added ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). and removed do-not-merge PR should not be merged. labels Sep 22, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #12860

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

✅ 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;

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.

🤖 💡 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

simonrozsival and others added 5 commits September 23, 2026 01:56
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]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-csharp-reference-logging branch from 08713a0 to 006182a Compare September 22, 2026 23:57
Keep managed reference accounting after MonoVM removal.

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

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Sep 23, 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 #12860

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

⚠️ Needs Changes — The migration is coherent across CoreCLR and NativeAOT, preserves the disabled-path trimming behavior, and all 44 GitHub/Azure checks are green. The remaining blocker is the native log-path ownership leak already identified in the unresolved 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"));

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 — 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

@jonathanpeppers
jonathanpeppers merged commit f999b5e into main Sep 23, 2026
44 checks passed
@jonathanpeppers
jonathanpeppers deleted the simonrozsival-csharp-reference-logging branch September 23, 2026 16:11
simonrozsival added a commit that referenced this pull request Sep 28, 2026
## 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.
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 24, 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.

3 participants