Skip to content

[Mono.Android] Map collection constructors from open definitions - #13724

Merged
simonrozsival merged 1 commit into
mainfrom
simonrozsival-safe-java-collection-constructors
Nov 23, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
simonrozsival-safe-java-collection-constructors

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Context: #13721
Context: #13656

SafeJavaCollectionFactory uses Activator.CreateInstance on runtime-constructed collection wrappers, so the trimmer cannot identify their activation constructors and requires three IL2072 suppressions.

Find each (IntPtr, JniHandleOwnership) constructor on the statically known open JavaList<>, JavaCollection<>, or JavaDictionary<,> definition, then map it to the closed wrapper with GetMemberWithSameMetadataDefinitionAs and invoke it. This removes all three IL2072 suppressions without adding new ones. Keep the separate MakeGenericType IL2071/IL3050 waivers and the concrete NativeAOT canonical-template roots: mapping a preserved member does not itself root a generic native template.

Include the existing three-row reference-argument canonical-template test in NativeAOTTrimmable, so focused device runs exercise these paths while keeping expected wrapper types open.

Size

Measured the same android-arm64 Release test application before and after the change on macOS arm64, using SDK 12.0.100-alpha.1.26556.115 and identical category filters. The signed CoreCLR APK changed from 35,666,702 to 35,658,510 bytes (-8,192); the signed NativeAOT APK changed from 13,215,861 to 13,211,765 bytes (-4,096). The NativeAOT application library changed from 33,337,216 to 33,336,224 bytes (-992). These are test-app measurements, not a general size guarantee.

Validation

All commands used MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0. Per-run log, binlog, and result destination arguments are omitted below.

Release SDK preparation and baseline/modified SDK builds: passed.

make prepare CONFIGURATION=Release MSBUILD_ARGS='-nr:false -m:4'
make leeroy CONFIGURATION=Release MSBUILD_ARGS='-nr:false -m:4'

Explicit Mono.Android trim/AOT analyzer rebuild: passed, no IL warnings; 12 existing nullable C# warnings. Confirmed ILLink.RoslynAnalyzer was an actual compiler input.

bin/Release/dotnet/dotnet build src/Mono.Android/Mono.Android.csproj \
    -c Release -t:Rebuild -p:BuildProjectReferences=false \
    -p:RunAnalyzers=true -p:RunAnalyzersDuringBuild=true \
    -p:EnableTrimAnalyzer=true -nr:false -m:2

Trimmed CoreCLR build/install and device tests: passed before and after, 51/51 tests per run on emulator-5554.

./dotnet-local.sh build -t:Install -c Release \
    tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj \
    -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=true -p:TrimMode=full \
    -p:PublishReadyToRun=false -p:PublishAot=true -p:_AndroidRuntime=CoreCLR \
    -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage \
    -p:Device=emulator-5554 -nr:false -m:4
(
    cd tests/Mono.Android-Tests/Mono.Android-Tests
    ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release \
        -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=true -p:TrimMode=full \
        -p:PublishReadyToRun=false -p:PublishAot=true -p:_AndroidRuntime=CoreCLR \
        -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage \
        -p:Device=emulator-5554 --report-trx
)

The explicit CoreCLR runtime override keeps the application on CoreCLR while PublishAot=true enables the safe collection-factory feature switch. Verified _AndroidRuntime=CoreCLR, Optimize=true, PublishTrimmed=true, NativeCompilationDuringPublish=false, the safe-factory switch, and packaged libcoreclr.so. PublishReadyToRun=false was necessary because the unmodified baseline fails R2R packaging with missing R2R/shrunk/_Java.Interop-Tests.TypeMap.dll; it was applied consistently to both CoreCLR measurements and runs.

NativeAOT build/install and device tests: passed before and after, 51/51 tests per run on the same device.

./dotnet-local.sh build -t:Install -c Release \
    tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj \
    -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=true -p:TrimMode=full \
    -p:PublishAot=true \
    -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage \
    -p:Device=emulator-5554 -nr:false -m:4
(
    cd tests/Mono.Android-Tests/Mono.Android-Tests
    ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release \
        -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=true -p:TrimMode=full \
        -p:PublishAot=true \
        -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage \
        -p:Device=emulator-5554 --report-trx
)

Verified _AndroidRuntime=NativeAOT, Optimize=true, PublishTrimmed=true, and the packaged native application library without libcoreclr.so. All four TRX files contain passing results for the three reference-wrapper canonical-template rows. Modified app linker/ILC logs contain no SafeJavaCollectionFactory diagnostics or IL2072 warnings; existing unrelated test warnings remain.

Activator.CreateInstance on runtime-closed collection wrappers needs IL2072 suppressions because the trimmer cannot identify their constructors. Get each activation constructor from the known open generic definition, then map its metadata identity to the closed wrapper before invocation. Remove the three IL2072 suppressions while retaining the MakeGenericType waivers and NativeAOT canonical-template roots.

Include the existing reference-argument canonical-template test in NativeAOTTrimmable so focused device runs exercise all three wrappers without rooting closed wrapper types in test expectations.

Validation: make prepare CONFIGURATION=Release and make leeroy CONFIGURATION=Release passed. A forced Mono.Android Rebuild with RunAnalyzers=true, RunAnalyzersDuringBuild=true and EnableTrimAnalyzer=true passed without IL warnings. Baseline and modified android-arm64 Release device runs each passed 51/51 tests on trimmed CoreCLR (safe-factory switch enabled, PublishReadyToRun=false) and NativeAOT; app linker/ILC emitted no SafeJavaCollectionFactory or IL2072 diagnostics. The signed test APK shrank 8192 bytes on CoreCLR and 4096 bytes on NativeAOT; the NativeAOT app library shrank 992 bytes.

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

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.

🟢 Approval recommended

No active review issues were identified for the trimming-safe constructor-mapping change.

No open issues 🎉

What changed in this PR

Updates SafeJavaCollectionFactory to map activation constructors from known open generic definitions, extending the trimming-safe reflection approach used in related interop changes.

Changes:

  • Replaces Activator.CreateInstance for list, collection, and dictionary wrappers, removing three IL2072 suppressions.
  • Preserves the separate generic-construction waivers and NativeAOT template roots.
  • Adds the existing three-row reference-wrapper test to NativeAOTTrimmable coverage.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​JavaConvertTest.cs Includes canonical-template tests in focused NativeAOT runs.
src/​Mono.Android/​Java.Interop/​SafeJavaCollectionFactory.cs Maps and invokes preserved constructors on closed wrappers instead of using Activator.

Review effort: Balanced

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 23, 2026
@simonrozsival
simonrozsival enabled auto-merge (squash) November 23, 2026 19:38
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13724

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

Code assessment: no blocking findings. Reviewed both changed files in full, the factory's caller and mixed-value sibling implementation, wrapper constructors, target frameworks, and test-rooting configuration. Findings: 0 errors, 0 warnings, 1 optional suggestion (posted inline).

The constructor lookup is now anchored to statically known open definitions, with metadata-definition mapping selecting the corresponding closed constructor. The separate native canonical-template roots and MakeGenericType suppressions remain intact; the null-handle, value-type, and JNI ownership paths are unchanged. Adding the existing three reference-wrapper rows to NativeAOTTrimmable is appropriate. The description reports before/after analyzer, trimmed CoreCLR, and NativeAOT device validation and appropriately limits its size claims to the measured test app; I did not independently rerun those builds or device tests.

CI: All 39 head-commit GitHub checks report success, including the aggregate dotnet-android check for Azure build 1694997. Direct Azure build/timeline verification was unavailable: the CLI required authentication and the public HTTP request was denied by the execution environment. Consequently, I cannot independently confirm Azure's underlying build result or non-gating device-test outcomes, and am not giving an unqualified CI/merge-readiness verdict.

Generated by Android PR Reviewer for #13724 · copilot · gpt61 · 25.6 AIC · ⌖ 8.15 AIC · ⊞ 21K
Comment /review to run again

// Keep the expected wrapper types open so NativeAOT must construct the closed reference-type
// wrappers through SafeJavaCollectionFactory's rooted canonical templates.
[TestMethod]
[TestCategory ("NativeAOTTrimmable")]

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 — Including these rows in the focused NativeAOT lane is useful. Could we also populate the non-generic source with a string item (or string key/value pair) and assert the converted contents through IList<string>, ICollection<string>, and IDictionary<string, string>? Currently these rows verify only an empty wrapper's type and assignability. A non-empty case would also exercise element conversion through the dynamically closed wrapper, without introducing a closed JavaList<string>/JavaCollection<string>/JavaDictionary<string, string> reference that could mask canonical-template rooting problems.

{Rule: Specific assertions and runtime-path coverage}

@simonrozsival
simonrozsival merged commit 499981f into main Nov 23, 2026
39 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-safe-java-collection-constructors branch November 23, 2026 21:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). trimmable-type-map

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants