Repository navigation
[Mono.Android] Remove the JNIEnv trimming suppression - #13721
Conversation
`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]>
There was a problem hiding this comment.
🟡 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
left a comment
There was a problem hiding this comment.
🤖 ✅ 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
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]>
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
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()returnstypeof(Def<>)with aPublicConstructors | NonPublicConstructorsreturn annotation, soGetConstructor()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 noMakeGenericType(), so no new IL3050. CreateClosedGenericInstance()returnsnullfor a missing definition, a mismatched definition or a missing constructor. Its only caller is gated byShouldActivateClosedGenericTarget(), so a non-generic type can't reachGetGenericTypeDefinition().- The base/derived proxy problem raised in the earlier review threads is fixed:
- The proxy is replaced only when the exact proxy's
TargetTypeequals 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. SingleUniverseTypeMapprefers the exact alias only for generic-definition lookups; other lookups are unchanged.
- The proxy is replaced only when the exact proxy's
- In the emitter, the override is
Family | Virtual | HideBySig. It has a sequence-0 return parameter carrying DAM value7, 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 publicGetObject<T>()keeps DAM onT. - 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.
) 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.
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.

Context: #8724
Context: #13656
JNIEnv.GetArray()converts Java object arrays through aDictionary<Type, Func<Type, IntPtr, int, object?>>. ItsIJavaObjectconverter passed the elementTypetoJava.Lang.Object.GetObject(), whosetypeparameter required[DynamicallyAccessedMembers(PublicConstructors | NonPublicConstructors)]. ATypetaken 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 asJavaList<string>, are the exception. Their proxy is generated for the open definition, so it can'tnewobjan arbitrary closed type. Until now,TrimmableTypeMap.CreateInstance()found the(IntPtr, JniHandleOwnership)constructor by callingGetConstructor()on the caller's closedType.That call needed DAM on the closed
Type. The requirement spread up throughTrimmableTypeMapValueManager.CreatePeer(), the publicJniValueManager.GetPeer()andCreatePeer(), andObject.GetObject(). It finally reached callers likeJNIEnv.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'sType.Mapping the constructor by metadata identity
Generated proxies for eligible open generic peers now override a new protected virtual method,
JavaPeerProxy.GetGenericTargetTypeDefinition(). The override returnstypeof(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:(IntPtr, JniHandleOwnership)constructor on the definition. The annotation keeps that lookup warning-free.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'sType. 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
NotSupportedExceptionbecause no compatible generic proxy could activate the requested type, andTryGetProxyType_GenericAlias_PrefersExactTargetselected 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
(IntPtr, JniHandleOwnership)constructor declared on the leaf type. This is the same condition that previously added[DynamicDependency]. Other proxies use the base method, which returnsnull, so activation returnsnullas it did when no constructor was found.protected virtual Type? JavaPeerProxy.GetGenericTargetTypeDefinition(). Removes[DynamicallyAccessedMembers]from thetargetTypeparameter ofJniRuntime.JniValueManager.GetPeer()andCreatePeer(). This is an intentional .NET 12 contract change. Custom value managers that overrideCreatePeer()should drop the annotation too, or they get IL2092 for the mismatch.CreateValue()/GetValue()andJavaConvertconversion 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.Mono.Android.NET-Testsbuild 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.Mono.Android.NET-Testsbuild and install with-p:TestsFlavor=NativeAOT -p:PublishAot=true -p:IncludeCategories=ConstructorParity -p:Device=emulator-5556: passed.$(_AndroidRuntime)wasNativeAOT, 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._AndroidRuntime=NativeAOTandOptimize=true, and the APK containedlibMono.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_DIRstands for the local TRX output directory):