Skip to content

[Mono.Android] Remove the JNIEnv trimming suppression - #13721

Merged
simonrozsival merged 3 commits into
mainfrom
simonrozsival-jnienv-trimming-suppression
Nov 23, 2026
Merged

simonrozsival merged 3 commits into
mainfrom
simonrozsival-jnienv-trimming-suppression

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Context: #8724
Context: #13656

JNIEnv.GetArray() converts Java object arrays through a Dictionary<Type, Func<Type, IntPtr, int, object?>>. Its IJavaObject converter passed the element Type to Java.Lang.Object.GetObject(), whose type parameter required [DynamicallyAccessedMembers(PublicConstructors | NonPublicConstructors)]. A Type taken from a dictionary of lambdas carries no annotation, so ILLink reported IL2067, and the converter silenced it with [UnconditionalSuppressMessage] and a FIXME.

The suppression hid a real question: would trimmed and NativeAOT apps keep the constructor that activation needs? If they didn't, a trimmed app would fail at run time with no build warning.

Where the DAM requirement came from

With the trimmable typemap, most peers are created by their generated proxy's CreateInstance(), which calls the constructor directly and needs no reflection. Closed instantiations of open generic peers, such as JavaList<string>, are the exception. Their proxy is generated for the open definition, so it can't newobj an arbitrary closed type. Until now, TrimmableTypeMap.CreateInstance() found the (IntPtr, JniHandleOwnership) constructor by calling GetConstructor() on the caller's closed Type.

That call needed DAM on the closed Type. The requirement spread up through TrimmableTypeMapValueManager.CreatePeer(), the public JniValueManager.GetPeer() and CreatePeer(), and Object.GetObject(). It finally reached callers like JNIEnv.GetArray() that can't satisfy it. The generated proxy added a [DynamicDependency] on the definition's constructor to keep it, but that didn't satisfy the data-flow requirement on the caller's Type.

Mapping the constructor by metadata identity

Generated proxies for eligible open generic peers now override a new protected virtual method, JavaPeerProxy.GetGenericTargetTypeDefinition(). The override returns typeof(Definition<>), and its return value is annotated with [DynamicallyAccessedMembers(PublicConstructors | NonPublicConstructors)]. That annotation replaces the old [DynamicDependency]. ILLink and ILC keep the definition's constructors whenever the proxy is kept.

At run time, JavaPeerProxy.CreateClosedGenericInstance() does the following:

  1. Checks that the requested closed type is an instantiation of the returned definition.
  2. Looks up the (IntPtr, JniHandleOwnership) constructor on the definition. The annotation keeps that lookup warning-free.
  3. Calls closedType.GetMemberWithSameMetadataDefinitionAs(definitionCtor) to get the matching constructor on the closed type, then invokes it.

GetMemberWithSameMetadataDefinitionAs() matches the constructor on the closed type by metadata definition, not by name and signature, so it never reflects over the caller's Type. Because the definition's constructor is kept, the matching constructor on each instantiation is kept too. The annotation is still needed: the mapping doesn't keep members by itself.

Selecting the requested generic proxy

The first compatible Java alias can be a base generic proxy even when the caller requests a derived generic peer. Mapping the base proxy's constructor to the derived type would fail. For that case, activation finds the exact requested generic definition in the Java object's class and interface hierarchy, with an assignability-checked managed lookup as a fallback. Managed alias lookup also prefers an exact generic definition over an earlier compatible base alias. This preserves the Java compatibility check and does not rely solely on FindClass, which may use another class loader.

The regression tests cover aliases on the same Java class, on a superclass, and on an interface, as well as an incompatible Java object. They also verify that a managed alias group prefers the exact proxy.

Regression proof

The new tests were run against the same final test assemblies twice: first with the proxy-selection fix removed, then with the fix restored. Without the fix, four tests failed: the same-class, superclass, and interface activation tests threw NotSupportedException because no compatible generic proxy could activate the requested type, and TryGetProxyType_GenericAlias_PrefersExactTarget selected the base proxy instead of the exact derived proxy. With the fix, those four tests passed, and the complete 53-test set passed on both trimmed CoreCLR and NativeAOT. This verifies that the tests reproduce the regression and that the implementation fixes it.

Scope and compatibility

  • The override is generated only when the activation constructor is a Xamarin.Android-style (IntPtr, JniHandleOwnership) constructor declared on the leaf type. This is the same condition that previously added [DynamicDependency]. Other proxies use the base method, which returns null, so activation returns null as it did when no constructor was found.
  • For a compatible closed generic peer, activation invokes the same constructor with the same handle and ownership arguments.
  • Public API: adds protected virtual Type? JavaPeerProxy.GetGenericTargetTypeDefinition(). Removes [DynamicallyAccessedMembers] from the targetType parameter of JniRuntime.JniValueManager.GetPeer() and CreatePeer(). This is an intentional .NET 12 contract change. Custom value managers that override CreatePeer() should drop the annotation too, or they get IL2092 for the mismatch.
  • The CreateValue()/GetValue() and JavaConvert conversion paths still need DAM and are left unchanged. Removing it there means auditing their public and custom value-manager contracts separately.

Validation

  • make prepare CONFIGURATION=Debug && make leeroy CONFIGURATION=Debug MSBUILD_ARGS='-p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false': passed.
  • ./dotnet-local.sh test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Debug --filter 'FullyQualifiedName~OpenGenericProxiesKeepTheReflectionActivationConstructor': passed, 8 tests. They check that the generated override exists, that its return value carries the DAM attribute, and that its return points to the target type.
  • Release trimmed CoreCLR Mono.Android.NET-Tests build and install with -p:IncludeCategories=ConstructorParity -p:Device=emulator-5556: passed, and the device run passed 4 tests. The build emitted no IL2067, IL2092 or IL2093 warnings for this path.
  • Release NativeAOT Mono.Android.NET-Tests build and install with -p:TestsFlavor=NativeAOT -p:PublishAot=true -p:IncludeCategories=ConstructorParity -p:Device=emulator-5556: passed. $(_AndroidRuntime) was NativeAOT, and the device run passed 4 tests. The build emitted the existing IL3050 warning for the XML serializer test, which is unrelated to this change.
  • MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0 make leeroy CONFIGURATION=Debug MSBUILD_ARGS='-nr:false -m:4 -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false': passed before and after restoring the proxy-selection fix.
  • MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0 ./dotnet-local.sh test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Debug --filter 'FullyQualifiedName~OpenGenericProxiesKeepTheReflectionActivationConstructor' -nr:false: passed, 8/8.
  • NativeAOT evaluation reported _AndroidRuntime=NativeAOT and Optimize=true, and the APK contained libMono.Android.NET-Tests.so. A detailed ILC/linker build passed with unrelated existing warnings and no warnings in the changed activation path.

Device commands (the environment variables above were set for each run; RESULTS_DIR stands for the local TRX output directory):

./dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -c Release -t:Install -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=true -p:TrimMode=full -p:PublishAot=false -p:PublishReadyToRun=false -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=false -p:PublishReadyToRun=false -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage -p:Device=emulator-5554 --report-trx --results-directory "$RESULTS_DIR")
# Before fix: build passed; test failed 4/53 as expected. After fix: build passed; test passed 53/53.

./dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -c Release -t:Install -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=true -p:TrimMode=full -p:PublishAot=true -p:PublishReadyToRun=false -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:PublishReadyToRun=false -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage -p:Device=emulator-5554 --report-trx --results-directory "$RESULTS_DIR")
# Passed; 53/53 tests.

./dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -c Debug -t:Install -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=false -p:PublishAot=false -p:PublishReadyToRun=false -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 Debug -p:RuntimeIdentifier=android-arm64 -p:PublishTrimmed=false -p:PublishAot=false -p:PublishReadyToRun=false -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage -p:Device=emulator-5554 --report-trx --results-directory "$RESULTS_DIR")
# Passed; 53/53 tests.

`JNIEnv.GetArray()` suppresses IL2067 because its `IJavaObject` converter
passes a runtime `Type` into peer activation.  Generated proxies now expose
the annotated open generic definition.  `System.Type.GetMemberWithSameMetadataDefinitionAs()`
maps its preserved activation constructor to the corresponding closed type,
without a name-based lookup.  The runtime conversion path therefore needs no
caller-propagated DAM requirements; only the generated return remains
annotated to root constructors.  The .NET 12 `JniValueManager` contract no
longer requires DAM annotations.

Context: #13656

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

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.

🟡 Changes recommended

Closed-generic activation can select a base-type proxy for a derived type sharing its JNI name, causing CreatePeer() to throw NotSupportedException instead of invoking the derived activation constructor.

1 open issue
What changed in this PR

This PR removes the JNIEnv.GetArray() trimming suppression by moving constructor preservation into generated peer proxies. It builds on #13656’s trimming work to support closed-generic activation without propagating constructor-preservation requirements through callers.

Changes:

  • Add an annotated generic-definition hook and map preserved constructors to closed types by metadata identity.
  • Remove constructor-preservation annotations from the activation call chain and the array converter’s suppression.
  • Update generator tests and the public API baseline.
File Description
src/​Mono.Android/​PublicAPI/​API-37/​PublicAPI.Unshipped.txt Records the new protected proxy hook.
src/​Mono.Android/​Microsoft.Android.Runtime/​TrimmableTypeMapValueManager.cs Removes caller-propagated constructor annotations.
src/​Mono.Android/​Microsoft.Android.Runtime/​TrimmableTypeMap.cs Delegates closed-generic activation to the proxy.
src/​Mono.Android/​Java.Lang/​Object.cs Removes the internal activation parameter annotation.
src/​Mono.Android/​Java.Interop/​JavaPeerProxy.cs Adds generic-definition lookup and constructor mapping.
src/​Mono.Android/​Android.Runtime/​JNIEnv.cs Removes the suppressed array-conversion helper.
src/​Microsoft.Android.Sdk.TrimmableTypeMap/​Generator/​TypeMapAssemblyEmitter.cs Emits annotated generic-definition overrides.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​GenerateTrimmableTypeMapTests.cs Verifies generated overrides and preservation annotations.
src/​Java.Interop/​Java.Interop/​JniRuntime.JniValueManager.cs Removes constructor requirements from peer-activation contracts.

Review effort: Balanced

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

🤖 ✅ LGTM — CI is green (38/38). This is a good change: it removes the IL2067 suppression and the FIXME, and it removes [DynamicallyAccessedMembers] from GetPeer/CreatePeer/GetObject instead of moving the problem somewhere else. GetMemberWithSameMetadataDefinitionAs is a clean way to map the constructor without DAM on the caller's Type.

The design is already close to minimal. 2 💡 suggestions make the diff smaller, and 1 ⚠️ asks about a possible behavior change when the proxy's definition is not the requested type's definition.

simonrozsival and others added 2 commits November 23, 2026 17:49
A Java alias can select a generic base proxy for a requested derived peer. The base proxy cannot map the derived activation constructor, so find the exact proxy in the Java hierarchy or through a Java-assignability-checked managed lookup.

Prefer exact generic aliases in managed lookups and cover same-class, superclass, interface, and incompatible-object cases.

Co-authored-by: Copilot App <[email protected]>
The generated override is limited to open generic peers that declare the Xamarin.Android-style activation constructor. Do not imply that every open generic peer overrides the method or that all other proxies can be constructed directly.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival simonrozsival added trimmable-type-map ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). labels Nov 23, 2026
@simonrozsival
simonrozsival enabled auto-merge (squash) November 23, 2026 19:36
@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.

Reviewed bc27c84e against main (merge-base c4fff063). This is a static, read-only review; I didn't build or run anything.

  • The DAM requirement is now met where it starts. GetGenericTargetTypeDefinition() returns typeof(Def<>) with a PublicConstructors | NonPublicConstructors return annotation, so GetConstructor() on the definition is warning-free. Type.GetMemberWithSameMetadataDefinitionAs() has no trimming or AOT annotations. dotnet/runtime suppresses IL2085 there on the basis that if the definition's member survives trimming, the instantiation's member does too. There's no MakeGenericType(), so no new IL3050.
  • CreateClosedGenericInstance() returns null for a missing definition, a mismatched definition or a missing constructor. Its only caller is gated by ShouldActivateClosedGenericTarget(), so a non-generic type can't reach GetGenericTypeDefinition().
  • The base/derived proxy problem raised in the earlier review threads is fixed:
    • The proxy is replaced only when the exact proxy's TargetType equals the requested definition.
    • The class/interface walk disposes every local reference and terminates.
    • The managed fallback checks IsAssignableFrom(objClass, targetClass), which is the right direction.
    • SingleUniverseTypeMap prefers the exact alias only for generic-definition lookups; other lookups are unchanged.
  • In the emitter, the override is Family | Virtual | HideBySig. It has a sequence-0 return parameter carrying DAM value 7, which matches the base method, so there's no IL2093. It's emitted under the same condition as the old [DynamicDependency], and all in-repo generic peers (JavaArray, JavaCollection, JavaDictionary, JavaList, JavaSet) declare the (IntPtr, JniHandleOwnership) constructor on the leaf type.
  • Dropping DAM from GetPeer()/CreatePeer() is safe in-repo. TrimmableTypeMapValueManager.CreatePeer() is the only override and was updated too, so there's no IL2092. The public GetObject<T>() keeps DAM on T.
  • The PublicAPI entry is correct. The new tests cover:
    • a same-class alias
    • a superclass alias
    • an interface alias
    • an incompatible object
    • preferring the exact proxy

Non-blocking: when no exact generic proxy is found in the Java hierarchy, activation now returns null (or CreatePeer() throws NotSupportedException). The old reflection path activated the requested type anyway. The new behavior is more correct, but it's worth a release note alongside the CreatePeer() contract change.

@simonrozsival
simonrozsival merged commit 7f830b3 into main Nov 23, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-jnienv-trimming-suppression branch November 23, 2026 20:39
simonrozsival added a commit that referenced this pull request Nov 23, 2026
)

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.
simonrozsival added a commit that referenced this pull request Nov 24, 2026
Context: #13721
Context: #13656

`Java.Interop.ValueTypeFactory<T>.CreateReferenceMixedDictionary()` requires an IL2072 suppression because `Activator.CreateInstance()` receives a runtime-constructed dictionary type whose constructors the trimmer cannot track.

Obtain the activation constructor from the statically rooted closed exemplar, map it onto the requested dictionary type with `GetMemberWithSameMetadataDefinitionAs()`, and invoke it. This applies the constructor-mapping approach from #13721 independently of that change and removes IL2072. Retain the closed exemplar roots: mapping preserves neither constructors nor the NativeAOT canonical templates for the exact value-type argument. The separate IL2055 and IL3050 suppressions for `MakeGenericType()` remain.

Add reference-key/value-type dictionary coverage alongside the existing value-key/reference-value test. A `string`/`bool?` case avoids the independently rooted `string`/`int` wrapper, allowing the reference-key exemplar to be tested in isolation.
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.

4 participants