Skip to content

[release/11.0.1xx] Preserve generic peers during collection CopyTo - #13803

Open
simonrozsival wants to merge 1 commit into
release/11.0.1xxfrom
simonrozsival-backport-13795-net11
Open

simonrozsival wants to merge 1 commit into
release/11.0.1xxfrom
simonrozsival-backport-13795-net11

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Context: #13795
Context: #13655

Backport of #13795 to .NET 11, without its new tests (the TrimmingTests project does not exist on this branch, and the AndroidX regression build test is dropped as requested).

Closed-generic collection CopyTo

Non-generic JavaCollection.CopyTo and JavaList.CopyTo receive the destination's runtime element type. With the trimmable type map, closed-generic Java peer element types were rejected with NotSupportedException. Activate them through TrimmableTypeMap.CreateInstance, and release the temporary JNI array reference if conversion fails.

On this branch, CreateInstance reflects over the closed type's (IntPtr, JniHandleOwnership) constructor and requires a DAM-annotated type. The array element type carries no annotation, so the call goes through a helper with an IL2067 suppression. The suppression relies on the emitter change from #13655, also backported here without its tests: the generated CreateInstance of an open generic definition's proxy carries [DynamicDependency] on that constructor, so ILLink and ILC keep it for as long as the proxy is kept. Without it, the constructor is trimmed and activation returns null, which surfaces as the existing NotSupportedException.

AndroidX layout-binding fragments

The AndroidX FindFragment<T> overload uses a generic JavaCast<T> result but did not propagate the constructor-preservation requirement to T, producing IL2091 for layout bindings. Propagate the public and non-public constructor annotation.

Validation

  • dotnet build src/Microsoft.Android.Sdk.TrimmableTypeMap/Microsoft.Android.Sdk.TrimmableTypeMap.csproj: succeeded, 0 warnings.
  • dotnet test tests/Microsoft.Android.Sdk.TrimmableTypeMap.Tests/Microsoft.Android.Sdk.TrimmableTypeMap.Tests.csproj: 1080 passed.
  • Not yet run locally: full SDK build (Mono.Android) and device tests, pending shared build/emulator admission. On main, the same runtime change passed the closed-generic CopyTo case on CoreCLR full trimming, CoreCLR partial trimming, and NativeAOT ([Mono.Android] Preserve generic peers during collection CopyTo #13795).

Backport of #13795 without its new tests. Includes the emitter change
from #13655, which keeps the activation constructor of open generic
peers so closed-generic activation survives trimming.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@simonrozsival
simonrozsival marked this pull request as ready for review November 26, 2026 18:19
Copilot AI balanced review requested due to automatic review settings November 26, 2026 18:20

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.

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

4 open issues
What changed in this PR

This PR updates Android runtime/type-map activation to better support trimming and generic peer activation, while improving JNI local reference safety.

Changes:

  • Add trimming annotations/suppressions to enable creating peers for closed generic element types via TrimmableTypeMap.CreateInstance()
  • Ensure JNI local references are always released in JavaCollection.CopyTo()
  • Update the trimmable type-map generator to preserve activation constructors for generic definitions via DynamicDependency
File Description
src/​Xamarin.Android.Build.Tasks/​Resources/​LayoutBinding.cs Adds DynamicallyAccessedMembers annotations to fragment lookup to improve trimming correctness.
src/​Mono.Android/​Microsoft.Android.Runtime/​TrimmableTypeMap.cs Removes a specialized CreateInstance path that avoided reflection fallback.
src/​Mono.Android/​Java.Interop/​JavaConvert.cs Switches array element activation to TrimmableTypeMap.CreateInstance() with a trimming-warning suppression.
src/​Mono.Android/​Android.Runtime/​JavaCollection.cs Wraps JNI array handling in try/finally to always delete the local ref.
src/​Microsoft.Android.Sdk.TrimmableTypeMap/​Generator/​TypeMapAssemblyEmitter.cs Emits DynamicDependency to keep activation constructors for generic definitions and refactors CreateInstance body emission to return a handle.

Review effort: Lite

if (proxy.ActivationCtor is { IsOnLeafType: true, Style: ActivationCtorStyle.XamarinAndroid }) {
_pe.Metadata.AddCustomAttribute (createInstance, GetDynamicDependencyAttrCtorRef (),
_pe.BuildAttributeBlob (
"#ctor(System.IntPtr,Android.Runtime.JniHandleOwnership)",
Comment on lines +873 to +876
_pe.Metadata.AddCustomAttribute (createInstance, GetDynamicDependencyAttrCtorRef (),
_pe.BuildAttributeBlob (
"#ctor(System.IntPtr,Android.Runtime.JniHandleOwnership)",
$"{proxy.TargetType.ManagedTypeName}, {proxy.TargetType.AssemblyName}"));
Comment on lines +880 to 895
MemberReferenceHandle GetDynamicDependencyAttrCtorRef ()
{
if (_dynamicDependencyAttrCtorRef.IsNil) {
var metadata = _pe.Metadata;
var attrRef = metadata.AddTypeReference (_pe.SystemRuntimeRef,
metadata.GetOrAddString ("System.Diagnostics.CodeAnalysis"), metadata.GetOrAddString ("DynamicDependencyAttribute"));
_dynamicDependencyAttrCtorRef = _pe.AddMemberRef (attrRef, ".ctor",
sig => sig.MethodSignature (isInstanceMethod: true).Parameters (2,
rt => rt.Void (),
p => {
p.AddParameter ().Type ().String ();
p.AddParameter ().Type ().Type (_systemTypeRef, false);
}));
}
return _dynamicDependencyAttrCtorRef;
}
Comment on lines +111 to +114
protected T FindFragment<
[DynamicallyAccessedMembers (Constructors)]
T
> (int resourceId, global::AndroidX.Fragment.App.Fragment? __ignoreMe, ref T? cachedField)
@PeppersMuse

Copy link
Copy Markdown

Reviewed as PeppersMuse. No issues found in the change itself.

What I checked:

  • src/Mono.Android/Android.Runtime/JavaCollection.cs: the CopyTo loop is now wrapped in try/finally so the temporary JNI array local ref is released even if element conversion throws — previously it leaked on that path.
  • src/Mono.Android/Java.Interop/JavaConvert.cs: ArrayElementConverter now activates closed-generic peers via TrimmableTypeMap.CreateInstance instead of throwing NotSupportedException for generic element types, through a helper carrying the IL2067 suppression with a justification that matches the emitter change below. JavaList.CopyTo does not need the same treatment — its element-by-element conversion already goes through the peer path without the array-local-ref pattern.
  • src/Mono.Android/Microsoft.Android.Runtime/TrimmableTypeMap.cs: CreateInstanceWithoutReflectionFallback is removed, and it had no other callers besides the one updated here.
  • src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/TypeMapAssemblyEmitter.cs: the generated CreateInstance of an open generic definition's proxy now carries [DynamicDependency] on the leaf (IntPtr, JniHandleOwnership) constructor, gated on ActivationCtorStyle.XamarinAndroid on the leaf type, and EmitCreateInstanceBody returns the method handle so the attribute lands on the right method.
  • src/Xamarin.Android.Build.Tasks/Resources/LayoutBinding.cs: the AndroidX FindFragment<T> overload now carries [DynamicallyAccessedMembers (Constructors)] on T. The Constructors constant is defined in the same class and the same annotation is already used on the other three overloads, so this completes the set.
  • On Copilot's open points, I checked each one and do not agree they are defects: the #ctor(...) member-signature format is the one ILLink's own test suite uses (e.g. [DynamicDependency("#ctor()", typeof(C))] in dotnet/runtime's DynamicDependencyMethod.cs); the attribute blob encodes its two arguments as serialized strings, matching the DynamicDependencyAttribute(string, Type) fixed-argument layout; and the same emitter + runtime change already passed the closed-generic CopyTo case under full trimming, partial trimming, and NativeAOT on main ([Mono.Android] Preserve generic peers during collection CopyTo #13795, [TrimmableTypeMap] Keep the activation constructor of open generic peers #13655).
  • Validation as described: TrimmableTypeMap project builds clean and its 1080 tests pass; the full SDK build and device tests are noted as not yet run, same as on main.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants