Investigate JNI reference ownership leaks and GC-bridge leak-check reliability
Maintainer thường phản hồi trong vòng 1 ngày
Đánh giá
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức phù hợp với người mới
- 50/100
Hướng nghiên cứu
Start by examining finalization order in JavaMarshalRegisteredPeers.cs, JavaObject.cs, and JavaException.cs to ensure native control blocks are freed. Then review exception-path cleanup in Object.SetHandle(), Throwable.SetHandle(), and generated proxy activation to fix transferred-reference leaks. Add regression tests for each scenario and verify GC-bridge processing completion in TrimmableTypeMapValueManager.cs.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
Android framework version
net11.0-android (Preview)
Affected platform version
Source audit of dotnet/android main at commit 2a20d9989a (2026-10-06). Current Android initialization uses TrimmableTypeMapValueManager for CoreCLR/NativeAOT. Findings in the shared reflection implementation are listed separately and are not assumed to explain current Android failures.
Description
Intermittent JNI global-reference leak-check failures remain a concern following recent improvements. This issue tracks source-level ownership findings and measurement concerns, to be investigated and fixed in separate, non-stacked PRs.
Evidence level: This is a source audit, not a runtime reproduction of the intermittent failure. The findings below must not be treated as one established root cause. In particular, native control-block leakage is distinct from GREF leakage, and incomplete bridge processing is a possible measurement problem rather than proof that a failure is harmless.
1. Finalization does not free the native peer control block
JavaMarshalRegisteredPeers.FinalizePeer() clears the peer reference before calling value.Finalized() in both branches:
Finalized() sets the internal Disposed state. However, SetPeerReference(default) frees the NativeMemory.AllocZeroed control block only when that state is already set. The finalization sequence therefore leaves the block allocated, whereas explicit disposal marks the peer disposed before clearing it. The block is 16 bytes on 64-bit targets. An initially invalid peer can also allocate a block while its reference is cleared during finalization.
Classification: Source-backed unmanaged-memory lifetime defect; not itself an unreleased GREF and not visible in the GREF count. Validate actual finalization and callback ordering before changing it; blindly swapping calls could change Dispose(false) behavior.
2. Transferred-reference cleanup is skipped on exceptions
These APIs delete the transferred input handle only after fallible work, without a finally:
- Object.SetHandle(): peer construction/registration.
- Object.GetObject(): peer lookup/activation.
- Throwable.SetHandle(): construction and stack-trace extraction.
- Generated Java.Interop-style proxy activation: constructor invocation before
JNIEnv.DeleteRef().
An exception can strand an input passed with TransferGlobalRef; collection of a partially constructed wrapper releases its own reference, not necessarily that original input. GetPeer() calls CreatePeer() with Copy, so the latter's transfer cleanup does not consume the raw transferred input. Internal typemap creation normally passes DoNotTransfer | DoNotRegister; distinguish that path from explicitly transferring through the proxy API.
Classification: Source-backed exception-path ownership gaps; no evidence yet that successful intermittent activation loops take these paths. Fix ownership boundaries consistently and avoid double deletion through nested layers.
3. Leak checks do not establish completed GC-bridge processing
The baseline uses CollectPeers() while the post-batch sample uses only CollectGarbage(). The value manager's WaitForGCBridgeProcessing() is intentionally a no-op; CollectPeers() only drains already-collected contexts. Native bridge work runs on a separate thread and temporarily converts strong globals to weak globals before promoting survivors.
Classification: Credible collection/measurement timing concern, not a reproduced explanation. Existing JavaMarshalGCBridgeTests already wait for a changed BridgeProcessingGeneration and an expected outcome. Establish completed processing/eventual convergence without weakening the real-leak assertion or adding unbounded waits.
4. Reflection activation failure suppresses cleanup of a potentially constructed peer
ReflectionJniValueManager.TryCreatePeerInstance() suppresses finalization whenever construction does not complete. A derived activation constructor can throw after its base constructor has acquired a GREF, but that failure path does not dispose the peer before suppressing its finalizer.
Classification: Shared reflection/host-JVM exception-path leak candidate. Current Android initialization selects the trimmable value manager, so this is not assumed to cause current Android leak-test failures. Verify with a throwing activation constructor and host-JVM reference accounting.
Additional registration discrepancy: Throwable ignores DoNotRegister
Throwable.SetHandle() always uses Copy rather than preserving JniHandleOwnership.DoNotRegister, unlike Object.SetHandle(). The typemap's RegisterCreatedPeer() relies on withholding registration until the Replaceable state is set. This discrepancy needs Throwable alias/reentrant-activation coverage before its consequences can be attributed to leaks.
Classification: Source-backed registration-contract discrepancy; no demonstrated permanent GREF leak.
Additional test-only native reference retention
Both Android timing helper and Java.Interop timing helper overwrite static Object_class with NewGlobalRef() during foo_init() without releasing a previous value. Repeated initialization would lose the previous reference. These raw JNI calls bypass managed reference accounting and should not be confused with a failing managed GREF-count assertion.
Scope and related work
The first pass covered peer construction/disposal/finalization, registry reconciliation, generated proxy/UCO activation, direct runtime GREF acquisition, class/constructor/remapping caches, array marshaling, proxies, and native hosts. It is not a completed whole-codebase retention audit.
Normal constructor-cache publication disposes losing candidates, and normal existing-reference construction releases the old global when replacing it. Those paths were not identified as another unconditional duplicate-GREF acquisition.
Related context: #10989, #11101, #11201, #10973; recent activation/alias work #12772 and leak-test isolation #12716 and #12709. Historical fixes should not be taken as proof of the current failure mechanism.
Steps to Reproduce
No end-to-end reproduction of the intermittent failure was performed during this audit. Proposed focused regression scenarios:
- Exercise actual finalization of
JavaObjectandJavaExceptionpeers, including initially invalid/partially constructed peers; verify native control-block release independently of GREF deletion. - Warm caches, transfer a fresh global reference into a lookup or activation that throws, and verify the original acquisition is paired with deletion. Cover
Object,Throwable, and supported generated-proxy entry points. - Repeatedly run isolated Java-side activation/class-lookup leak checks while recording strong/weak reference counts, bridge generations, and matched acquisition/deletion logs. Distinguish sustained growth from delayed release and in-progress bridge transitions.
- On the reflection/host-JVM path, activate a peer whose constructor throws after base construction; verify GREF/registry cleanup after collection.
- Add Throwable registration-order coverage and determine whether repeated native timing initialization is reachable before treating the additional observations as runtime leak causes.
Each fix should have a regression that fails before the change, preserve successful-path ownership/activation semantics, and be validated on the relevant runtime. Follow-up PRs should reference this issue without automatically closing the broader investigation while unrelated findings remain unresolved.
Did you find any workaround?
No general workaround established. Explicit disposal normally releases peer references and control blocks, but it does not establish that exceptional transferred-input ownership is correct. Do not relax leak thresholds or assume all failures are GC timing noise.
Relevant log output
N/A — no new runtime reproduction or GREF logs collected during this source audit.
- Ngôn ngữ chính
- C#
- Star
- 2.1k
- Fork
- 579
- Merge trung bình
- 2 ngày 2 giờ
- Pull request đã merge (30 ngày)
- 205
Chuẩn bị môi trường
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Không có hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của dotnet/android
-
Area: App+Library Build
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày
-
EditText.getText() isn't boundĐang mởArea: Mono.Android
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 65/100
dotnet/android#9192 · 4 bình luận · 1 reaction ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Discuss disabling Dynamic PGO by default for CoreCLR Android apps while preserving developer opt-inĐang mởneeds-triage
Độ khó 5/5 Hơn một tuần Mức phù hợp với người mới 25/100
Maintainer thường phản hồi trong vòng 1 ngày
-
agentic-workflows needs-triage
Độ khó 4/5 3-5 ngày Mức phù hợp với người mới 35/100
Maintainer thường phản hồi trong vòng 1 ngày
-
needs-triage
Độ khó 4/5 Hơn một tuần Mức phù hợp với người mới 45/100
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của dotnet/android
Issue tương tự
-
[i18n] 安装实例完成后的成功提示未正确本地化Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 62/100
PCL-Community/PCL-CE#3658 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Deploy & Patch-issues opprettes ikke: create-pnd-issues.yml har feilet hver uke siden 2025-09-08Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 62/100
Altinn/altinn-auth#4359 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
アプリ: チャット 優先: 中 提案
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
yksr-melt/Meltype#243 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Workflows: a workflow stored with null conditions is skipped with an exception instead of runĐang mởbug core
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày
-
type/automation type/tech-debt
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày