Skip to content

[Mono.Android] Move JNI reference logging to EventSource - #13002

Merged
simonrozsival merged 3 commits into
mainfrom
simonrozsival-jni-reference-tracing
Oct 6, 2026
Merged

simonrozsival merged 3 commits into
mainfrom
simonrozsival-jni-reference-tracing

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

JNI global/local/weak-global reference diagnostics still use bespoke text formatting, files, per-operation flushing, and logcat routing even though reference accounting and GC bridge processing now run in managed code. Replace those sinks with structured events from the existing Microsoft.Android.Runtime EventSource.

Fixes #6822.

  • Add independently selectable verbose reference events with numeric handles, reference kinds, counter snapshots, managed thread IDs, and explicit bridge context. Distinguish releasing local-reference ownership from JNI deletion.
  • Preserve counting and GREF-pressure GC behavior regardless of diagnostic enablement, including the bridge guard against recursive collection.
  • Remove unused reference managers, legacy P/Invokes, reference-log options and initialization ABI fields, and associated dead state. Keep native parsing for remaining non-reference categories and early startup logging; relocating that parser out of the residual Logger wrapper is the upper layer, [native] Move logging category parsing into shared host startup #13003.
  • Use CoreCLR EventPipe stacks. NativeAOT traces did not supply stacks in the local experiment, so expose a separately enabled managed-stack keyword without stack-string allocation during ordinary reference collection.
  • Cover real JNI lifecycles/event contracts, ownership transfer, disabled-path allocation, GREF initialization limits, and stack opt-in. The existing peer-cycle test also checks bridge transitions. Remove redundant keyword permutations and handle-history reconstruction; cover collected-weak-reference serialization/filtering and stack correlation within existing cases.
  • Update documentation and defer host-side trace interpretation to the skill tracked separately; do not add a permanent trace-reader tool or dependency.
  • Merge current main, preserving its removal of legacy native typemap paths and keeping the native/managed initialization layouts aligned without the retired logging fields.

Validation after review and merge-conflict resolution (2026-10-05):

The local preview SDK requests unavailable .NET 10 targeting packs. Repository builds used the validation-only CustomBeforeMicrosoftCommonTargets override stored in session artifacts; no repository override is committed.

  • ./dotnet-local.sh build Microsoft.Android.slnx -v:quiet — passed; includes native and managed runtime builds.
  • ./dotnet-local.sh build Microsoft.Android.slnx -t:BuildExtraApiLevels -v:quiet — passed.
  • ./dotnet-local.sh build -t:ConfigureLocalWorkload build-tools/create-packs/Microsoft.Android.Sdk.proj -v:quiet — passed.
  • ./dotnet-local.sh build -t:Install -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:IncludeCategories=ReferenceTracing -p:Device=emulator-5554 -v:quiet — passed.
  • From tests/Mono.Android-Tests/Mono.Android-Tests: ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:IncludeCategories=ReferenceTracing --device emulator-5554 --report-trx --results-directory ../../../bin/TestDebug/TestResults — passed, all 10 focused CoreCLR cases.
  • ./dotnet-local.sh publish -c Release tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:PublishAot=true -p:IncludeCategories=ReferenceTracing -p:RuntimeIdentifier=android-arm64 -v:quiet — passed. The initial build-only attempt failed with missing NativeAOT DGML inputs (XA4319); publishing produced the required native compilation outputs.
  • ./dotnet-local.sh build -t:Install -c Release tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:PublishAot=true -p:IncludeCategories=ReferenceTracing -p:RuntimeIdentifier=android-arm64 -p:Device=emulator-5554 -v:quiet — passed after publishing.
  • From the test project directory: ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release -p:PublishAot=true -p:IncludeCategories=ReferenceTracing -p:RuntimeIdentifier=android-arm64 --device emulator-5554 --report-trx --results-directory ../../../bin/TestRelease/TestResults — passed, all 10 focused NativeAOT cases, including event 20 stack correlation.
  • ./dotnet-local.sh test bin/TestDebug/net10.0/Xamarin.Android.Build.Tests.dll --filter 'Name~RuntimeEventSourceFeatureSwitch' — passed, both enabled/disabled cases; linked-assembly inspection confirms instrumentation removal when disabled.
  • Earlier real CoreCLR and NativeAOT emulator traces contained reference creation/deletion/release, peer diagnostics, and bridge transitions. CoreCLR yielded application frames through EventPipe. NativeAOT opt-in stack collection produced 148 correlated stack events including application frames; ordinary 0x30 collection produced no stack-string events.
  • git diff --check — passed. Full runtime test suites and hardware-device tests were not run.

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

Copilot AI balanced review requested due to automatic review settings October 5, 2026 08:09

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

Existing GREF initialization coverage was removed, and the new weak-reference-collected event contract remains untested.

Review effort: Balanced
Findings: 2 Medium severity

Open (2)
What changed in this PR

Moves JNI reference diagnostics from legacy files/logcat and native plumbing to structured Microsoft.Android.Runtime EventSource events.

Changes:

  • Adds global, weak-global, local, bridge-context, and NativeAOT stack events.
  • Removes legacy logging options, ABI fields, P/Invokes, and reference managers.
  • Expands lifecycle/trimming tests and updates tracing documentation.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Mono.Android.NET-Tests.csproj Removes obsolete logging switch.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​JavaMarshalGCBridgeTests.cs Validates bridge reference events.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Android.Runtime/​ManagedObjectReferenceManagerTests.cs Adds reference lifecycle and allocation tests.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​LinkerTests.cs Verifies instrumentation trimming.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​BuildTest2.cs Updates release trimming assertions.
src/​Xamarin.Android.Build.Tasks/​Microsoft.Android.Sdk/​targets/​Microsoft.Android.Sdk.RuntimeConfig.targets Removes obsolete feature switch.
src/​native/​nativeaot/​host/​host.cc Removes legacy logging initialization.
src/​native/​common/​include/​managed-interface.hh Removes obsolete ABI fields.
src/​native/​clr/​shared/​log_functions.cc Reserves retired logging bits.
src/​native/​clr/​runtime-base/​logger.cc Simplifies category parsing.
src/​native/​clr/​include/​runtime-base/​logger.hh Removes reference-logging APIs.
src/​native/​clr/​include/​constants.hh Removes retired category names.
src/​native/​clr/​host/​host.cc Stops passing logging configuration.
src/​Mono.Android/​Microsoft.Android.Runtime/​RuntimeFeature.cs Removes the old feature switch.
src/​Mono.Android/​Microsoft.Android.Runtime/​RuntimeEventSource.cs Defines structured reference events.
src/​Mono.Android/​Microsoft.Android.Runtime/​JavaMarshalGCBridge.cs Adds explicit bridge event context.
src/​Mono.Android/​Java.Interop/​TypeManager.cs Routes diagnostics through the manager.
src/​Mono.Android/​Android.Runtime/​RuntimeNativeMethods.cs Removes legacy logging P/Invokes.
src/​Mono.Android/​Android.Runtime/​ManagedObjectReferenceManager.cs Implements accounting and EventSource emission.
src/​Mono.Android/​Android.Runtime/​Logger.cs Removes retired category accessors.
src/​Mono.Android/​Android.Runtime/​LogCategories.cs Removes managed reference categories.
src/​Mono.Android/​Android.Runtime/​JNIEnvInit.cs Removes logging initialization state.
src/​Mono.Android/​Android.Runtime/​AndroidRuntime.cs Deletes the obsolete native-backed manager.
src/​Microsoft.Android.Runtime.NativeAOT/​Java.Interop/​ManagedObjectReferenceManager.cs Deletes duplicate NativeAOT manager.
src/​Microsoft.Android.Runtime.NativeAOT/​Java.Interop/​JreRuntime.cs Removes writer options.
src/​Microsoft.Android.Runtime.NativeAOT/​Android.Runtime.NativeAOT/​DiagnosticSettings.cs Deletes legacy diagnostic settings.
Documentation/​workflow/​SystemProperties.md Documents removal of system-property logging.
Documentation/​guides/​tracing.md Documents EventSource collection and schema.
Documentation/​guides/​internals/​debug-jni-objrefs.md Rewrites JNI reference debugging guidance.

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@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 103-file JNI diagnostics migration, including the native/managed initialization contract and updated documentation gitlink, has no remaining blocking issue. Reference accounting and GC/bridge protection remain independent of diagnostics; payload/filtering/stack contracts, feature-switch trimming, and restored event-20/GREF-limit coverage are consistent. The retired sinks and deferred parser/trace-reader work match the accepted scope.

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto stamp

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

Stamping as requested by @simonrozsival; no code review performed.

@simonrozsival
simonrozsival removed this pull request from stack #13004 October 6, 2026 11:32
@simonrozsival
simonrozsival added this pull request to stack #13021 October 6, 2026 11:33
simonrozsival and others added 3 commits October 6, 2026 13:41
Replace JNI reference-specific file and logcat sinks with typed events
from the existing Microsoft.Android.Runtime provider.  Keep reference
accounting and GREF-pressure GC independent of diagnostic collection.

Remove obsolete reference managers, native logging configuration and
initialization fields, and unused P/Invokes.  Retain early native category
selection for non-reference logging; its remaining wrapper cleanup is a
separate stacked change.

CoreCLR supplies EventPipe call stacks.  Add explicitly enabled NativeAOT
stack events because its reference traces do not provide those stacks.
Keep that fallback off during ordinary reference collection.

Cover real JNI lifetimes, ownership transfer, event wire contracts,
disabled-path allocations, optional stacks, and provider trimming.
Update reference-debugging and tracing documentation.

Fixes #6822.

Co-authored-by: Copilot App <[email protected]>
Cover the collected-weak-reference event payload and filtering in the
existing lifecycle cases, and verify its NativeAOT stack correlation in
the existing opt-in test.  Retain the small GREF initialization regression
check requested in review and surface EventSource error events.

Remove redundant keyword combinations and the bridge test handle-history
reconstruction.  Keep the actual peer-cycle survival/collection checks
and correlated bridge transition assertions.

Co-authored-by: Copilot App <[email protected]>
Capture reference stacks in a non-inlineable helper and skip only its
known frame. A fixed two-frame skip could discard the application caller
when NativeAOT inlined the runtime wrappers. Keep caller-name coverage
and verify that the capture helper is excluded.

Validated the Release SDK build, 10 NativeAOT and 10 CoreCLR reference
tracing tests on Android ARM64, Android x64 NativeAOT publishing, and an
x64 NativeAOT source probe that fails before this fix and passes after.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-jni-reference-tracing branch from 839ec3d to dd94f74 Compare October 6, 2026 11:51
simonrozsival added a commit that referenced this pull request Oct 6, 2026
The JNI reference logging migration leaves Logger as a wrapper around
startup category parsing.  Move the unchanged debug.dotnet.log parser
to HostCommon with a file-local helper instead of keeping a separate
configuration class.

Keep both hosts calling it before environment setup and runtime startup
so native assembly discovery and library loading retain their early
diagnostics.  Remove obsolete headers and CMake sources, replace direct
logging dependencies, and track the shared initializer in NativeAOT
incremental-build inputs.

Context: #13002

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

Copy link
Copy Markdown
Member Author

@dalexsoto review

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13002

@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 — no blocking issues found.

The managed/native initialization layouts remain aligned, reference counts and JNI ownership behavior are preserved, and the EventSource disabled paths avoid payload allocation. The added lifecycle, GC bridge, trimming, and NativeAOT stack tests provide solid coverage. All reported CI checks are green.

Findings: 0 errors · 0 warnings · 1 suggestion

Generated by Android PR Reviewer for #13002 · copilot · gpt56 · 367.5 AIC · ⌖ 11.1 AIC · ⊞ 26.4K
Comment /review to run again

}

[Event (GlobalReferenceCreatedEventId, Level = EventLevel.Verbose, Keywords = Keywords.GlobalReference)]
public void GlobalReferenceCreated (ulong sourceHandle, ulong handle, int sourceType, int referenceType, int globalCount, int weakCount, int managedThreadId, int bridgeOperation)

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.

🤖 💡 API design — Could these manifest-facing parameters use enums (or event-specific enum types) instead of raw int values? EventSource can then publish the symbolic mappings in its metadata, so PerfView/TraceEvent users see names such as Global and WeakToGlobal rather than having to consult the documentation for magic values. The low-level WriteEventCore helper can still cast them to their int representation.

Rule: Prefer self-describing diagnostic contracts

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto stamp

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

Stamping as requested by @simonrozsival; no code review performed.

@simonrozsival
simonrozsival merged commit e2230e9 into main Oct 6, 2026
42 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-jni-reference-tracing branch October 6, 2026 21:55
simonrozsival added a commit that referenced this pull request Oct 6, 2026
The JNI reference logging migration leaves Logger as a wrapper around
startup category parsing.  Move the unchanged debug.dotnet.log parser
to HostCommon with a file-local helper instead of keeping a separate
configuration class.

Keep both hosts calling it before environment setup and runtime startup
so native assembly discovery and library loading retain their early
diagnostics.  Remove obsolete headers and CMake sources, replace direct
logging dependencies, and track the shared initializer in NativeAOT
incremental-build inputs.

Context: #13002

Co-authored-by: Copilot App <[email protected]>
simonrozsival added a commit that referenced this pull request Oct 7, 2026
The JNI reference logging migration in [#13002](#13002) leaves the native `Logger` class wrapping only startup category parsing. Move that C++ parsing into `HostCommon::init_logging_categories()` in the existing shared host source, inline exact token comparisons directly in initialization, and delete the obsolete wrapper header/source and category helper.

Keep category selection before environment setup and early native diagnostics in both hosts. CoreCLR retains the original call position before assembly-store discovery and `coreclr_initialize`. NativeAOT preserves the current bootstrap: validate the Java VM, obtain the JNI environment and initialize `AppSystemProperties` first, then select logging categories and initialize the host environment. String-view comparisons preserve exact matching, unknown/empty-token behavior and `all` without allocations or modifying property data. No managed parser is introduced.

Replace stale header dependencies with the declarations actually used, remove obsolete CMake source entries, and update NativeAOT MSBuild incremental inputs to track the shared initializer and header while retaining the new NativeAOT runtime-base input glob.

This is the upper layer of native stack 13021, with complete ordered membership [#13002](#13002), [#13003](#13003), targeting `simonrozsival-jni-reference-tracing`, not `main`. No issue is closed. Stack metadata and the lower branch were not modified.

Rebased only the upper cleanup commits from their verified historical lower fork `a125f69b6b52c9bf25128cb1c7094c029a0dbde8` onto the verified new lower head `dd94f74548437df80c6e2291b9b5db4a94a5dde0`, based on current `main` at `1089999735d3565e96cb9b443fdf04387e165350`. Old lower merge history is not retained in the upper-only range. Preserve `main`'s legacy typemap deletions and the now-merged unused debugger/netlink/bundle cleanup from [#13001](#13001): the relocated parser does not reintroduce removed tokens or category declarations. The upper-only diff contains 18 native files (62 insertions, 79 deletions) and no managed/test changes relative to the updated lower layer.
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 6, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Port GREF logging to .NET 6+ EventSource infrastructure

4 participants