Skip to content

[Microsoft.Android.Build.Tasks] Keep only JNI-reachable typemap members - #13849

Merged
jonathanpeppers merged 2 commits into
mainfrom
jonathanpeppers-r8-typemap-member-rules
Dec 2, 2026
Merged

jonathanpeppers merged 2 commits into
mainfrom
jonathanpeppers-r8-typemap-member-rules

Conversation

@jonathanpeppers

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 5a3745d7963e3cfd44c05b345482e6b53edf6714

Dimension Assessment Rationale
Change confidence 8.5/10 ↑ Mono.Android.NET-Tests Release with R8 on Pixel 10: 1154 passed, 0 failed.
↑ MAUI app starts and UI check passes; android template app starts.
↑ Task unit tests and focused full-build tests pass.
↓ MSBuildDeviceIntegration tests not run locally.
↓ Fields from non-public [ExportField] are no longer kept.

Context: #12827

On the CoreCLR + $(PublishTrimmed) + R8 path, <GenerateTypeMapMemberProguardConfiguration/> wrote this rule pair for each retained typemap key:

-keepclassmembers class K { *; }
-keepclassmembers interface K { *; }

This keeps every member of every bound Java type and Java callable wrapper, including private fields and methods that no managed code can reach. Examples are AccessibilityNodeInfoCompat, ViewCompat, and the Material date pickers. In a dotnet new maui app, proguard_typemap_members.cfg was the largest source of R8 keep restrictions. Google Play calculates its R8 obfuscation, optimization, and shrinking scores from these restrictions (BUNDLE-METADATA/com.android.tools/r8.json).

Now each key gets this rule instead:

-keepclassmembers class K { public protected *; native <methods>; }
-keepclassmembers interface K { public protected *; native <methods>; }

Bindings bind only public and protected Java members, and Java callable wrappers call managed code through native methods, including the private native nctor_N constructors. R8 treats public protected as either visibility.

One more rule is written at the top of the file:

-keepclassmembers class * implements mono.android.IGCUserPeer { private <methods>; }

A private [Export] method generates a private Java method, and JNI can call it by name (NonPublicExports_DispatchFromJava in TrimmableTypeMapExportTests). All Java callable wrappers implement IGCUserPeer. I tried { private *; } first, but R8 also applies field rules to superclass fields, so it restricted about 1400 private AppCompat and Material fields in the MAUI app. Thus the rule keeps only methods.

Limitations: fields generated for a non-public [ExportField], and private or package-private members that app code reads by JNI or reflection, are no longer kept. These need app ProGuard rules. Documentation/guides/D8andR8.md is updated.

Results

Release .aab, CoreCLR, $(AndroidLinkTool)=r8, net12.0-android, local SDK. The percentages come from r8.json (lower is better).

App noObfuscation % noOptimization % noShrinking % Live items DEX bytes
dotnet new maui (Microsoft.Maui.Controls 11.0.0) before 99.85 48.48 37.76 55,045 3,603,728
after 99.85 39.88 28.73 54,528 3,482,452
dotnet new android before 100.00 88.81 88.06 140 16,160
after 100.00 85.07 84.33 140 16,160

Obfuscation does not change because this path uses -dontobfuscate.

Validation

  • Pixel 10 (Android device): both apps install from the .aab and start, with no errors in logcat. A UI check of the MAUI app passed (button, picker, alert, navigation, CollectionView scroll).
  • Mono.Android.NET-Tests, -c Release (R8, $(TrimMode)=full, CoreCLR, new member rules), on Pixel 10: 1154 passed, 0 failed, 1 skipped (NativeAOT-only, inconclusive). All Export tests pass, including NonPublicExports_DispatchFromJava.
  • dotnet test --project src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests --filter FullyQualifiedName~TypeMapProguard: 122 passed, 4 skipped (need llvm-readobj).
  • Xamarin.Android.Build.Tests --filter "Name~RetainedTypeMapRulesDriveR8|Name~TrimmableTypeMap_PreservesJniOnlyConstructorThroughR8": 4 passed.
  • I updated the expected rule text in ScopedTypeMapR8Tests and R8RuntimeRemappingBuildTests. I also removed the JNI read of a private Java field from ScopedTypeMapR8Tests, because that member is now removed on purpose. I did not run these MSBuildDeviceIntegration tests locally, because their class cleanup runs adb kill-server on a shared machine.

jonathanpeppers and others added 2 commits November 30, 2026 15:33
proguard_typemap_members.cfg kept every member of each retained typemap
type with `{ *; }`, including private fields and methods that managed
bindings never use. In a `dotnet new maui` app this file was the largest
source of R8 keep restrictions.

Keep only `public protected *` and `native <methods>` for each retained
type. Managed bindings bind only public and protected Java members, and
Java callable wrappers call managed code through native methods.
Private [Export] methods of Java callable wrappers are still reachable
by JNI, so a single rule keeps private methods of IGCUserPeer types.

Release .aab, CoreCLR, R8 (obfuscation/optimization/shrinking scores):

  dotnet new maui:    0.15/51.52/62.24 -> 0.15/60.12/71.27,
                      DEX 3,603,728 -> 3,482,452 bytes
  dotnet new android: 0.00/11.19/11.94 -> 0.00/14.93/15.67,
                      DEX 16,160 -> 16,160 bytes

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 21:50

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 remain for the narrower retained-typemap R8 member rules.

No open issues 🎉

What changed in this PR

This PR narrows the retained-typemap R8 member rules used by trimmed CoreCLR Android apps, allowing more Java members to be optimized or removed while preserving members needed by bindings and Java callable wrappers.

Changes:

  • Keep public, protected, and native members instead of all members, with a separate rule preserving private [Export] methods.
  • Update test expectations and remove the private-field JNI check that no longer matches the retention policy.
  • Document the narrower rules and the non-public [ExportField] limitation.
File Description
tests/​MSBuildDeviceIntegration/​Tests/​ScopedTypeMapR8Tests.cs Updates rule assertions and removes the private-field JNI check.
tests/​MSBuildDeviceIntegration/​Tests/​R8RuntimeRemappingBuildTests.cs Updates the expected member rule.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​TrimmableTypeMapBuildTests.cs Updates build-test expectations for member and constructor retention.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​TypeMapProguardTargetsTests.cs Removes an unused member-rule helper.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​GenerateTypeMapProguardConfigurationTests.cs Updates expected generator output, including the private-export rule.
src/​Microsoft.Android.Build.Tasks/​Tasks/​GenerateTypeMapProguardConfiguration.cs Adds a header-writing hook for generated configurations.
src/​Microsoft.Android.Build.Tasks/​Tasks/​GenerateTypeMapMemberProguardConfiguration.cs Emits narrower member rules and preserves private wrapper methods.
Documentation/​guides/​D8andR8.md Explains the revised retention policy and its limitations.

Review effort: Balanced

@jonathanpeppers

Copy link
Copy Markdown
Member Author

/azp run Xamarin.Android-PR

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

@jonathanpeppers

Copy link
Copy Markdown
Member Author

Internal Xamarin.Android-PR build 16171893 failed. I reviewed the failures, and none of them appear to be caused by this PR. They can be ignored:

Failure Why it can be ignored
Task: PoliCheck English / Run PoliCheck Post Analysis Fails on every main build. #13838 fixes it.
Task: Windows > Build & Smoke Test / Ensure no modified/untracked files Untracked .sarif file left by the Guardian tools. Fails on every main build.
Test: BuildTest.SimilarAndroidXAssemblyNames (True,CoreCLR) Network error in the log: Failed to download package.
Test: BuildTest.AbiNameInIntermediateOutputPath (NativeAOT) Network error in the log: Failed to download package.
Test: BuildTest.NUnitLiteNugetWorks (CoreCLR) Network error in the log: Failed to download package.
Test: NuGetPackageVersionFinderTests.ShortTaskNameResolvesWithNuGetMetadataInFullMSBuild Fails on every main build.

The public CI (dnceng-public) is offline, so this internal build is the only CI result.

@jonathanpeppers jonathanpeppers added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Dec 1, 2026
@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto review

@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Android PR Reviewer has started processing this issue comment

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

⚠️ Needs Changes — CI is red; cause unverified.

No actionable code findings: 0 errors, 0 warnings, 0 suggestions. Reviewed all eight changed files and traced the generated rules through the CoreCLR R8 configuration and Java callable-wrapper generator. The narrower visibility rules retain public/protected members and native callbacks; the additional rule covers private export wrappers. Removal of non-public fields is an explicit, documented behavior change.

For head 5a3745d, license/cla passes, but Xamarin.Android-PR reports [build 16171893 failed]((devdiv.visualstudio.com/redacted) Its failure logs were inaccessible, and the public pipeline query returned no matching build. I cannot classify that failure as PR-related or infrastructure-related, or confirm CI is green. Local build/device tests were not rerun.

Generated by Android PR Reviewer for #13849 · copilot · gpt61 · ~64 AIC · ⌖ ~11 AIC · ⊞ 22.3K
Comment /review to run again

@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 all eight changed files at 5a3745d and the JCW scanner/generator, member-config target wiring, and relevant changes on the current target. Public/protected bound members and native callbacks remain kept; non-public [Export] methods become Java-private methods covered by the new IGCUserPeer rule. The documented [ExportField] and package-private limitations are accepted trade-offs. No blocking issues found. LGTM.

Static review only; I did not run builds or tests.

@jonathanpeppers
jonathanpeppers merged commit b156cf4 into main Dec 2, 2026
2 of 3 checks passed
@jonathanpeppers
jonathanpeppers deleted the jonathanpeppers-r8-typemap-member-rules branch December 2, 2026 13:20
jonathanpeppers added a commit that referenced this pull request Dec 2, 2026
Context: #13849

The `<R8/>` task writes `proguard_project_primary.cfg` from `acw-map.txt`. This is the default path for .NET 11 Release builds with R8. For every Java callable wrapper and bound Java type, it wrote:

```
-keep class crc64b5e713d400f589b7.MauiDrawable { *; }
```

`{ *; }` keeps every member, including private fields. R8 also applies member rules to superclass members, so private fields of library base classes are kept as well. In a `dotnet new maui` app, R8 `-whyareyoukeeping` shows that the private field `com.microsoft.maui.PlatformDrawable.strokeThickness` (in maui.aar) is kept by this file. The file also had each line about 3 times, because `acw-map.txt` has several keys for each Java name.

Google Play calculates R8 obfuscation, optimization, and shrinking scores from `BUNDLE-METADATA/com.android.tools/r8.json`. These rules are a large part of the restrictions in that file.

Now the file has one shared rule and one rule for each distinct Java type:

```
-keepclassmembers class * implements mono.android.IGCUserPeer { private <methods>; }
-keep class crc64b5e713d400f589b7.MauiDrawable { public protected *; native <methods>; }
```

This is the same design as #13849, which changes the CoreCLR trimmable-typemap path on main. Bindings use only public and protected Java members. Java callable wrappers call managed code through `native` methods, and their constructors, `__md_methods`, `monodroidAddReference ()`, and `monodroidClearReferences ()` are public. The first rule keeps private `[Export]` methods, which JNI can call by name. All Java callable wrappers implement `IGCUserPeer`. The rule keeps only methods, because R8 also applies field rules to superclass fields. User `@(AndroidJavaSource)` types still get `{ *; }`.

Limitations: fields generated for a non-public `[ExportField]`, and private or package-private members that app code reads by JNI or reflection, are no longer kept. These need app ProGuard rules.

### Results

`r8.json` stats are the percentage of items that R8 is not allowed to rename, optimize, or remove. Lower is better.

Release `.aab`, android-arm64, CoreCLR, `$(AndroidLinkTool)`=r8, local SDK from main with `$(_AndroidEnableTypemapR8Trimming)`=false (this uses the same acw-map code path as release/11.0.1xx), Microsoft.Maui.Controls 11.0.0, R8 9.5.33:

| App | | DEX bytes | noObfuscation % | noOptimization % | noShrinking % |
|---|---|---|---|---|---|
| `dotnet new maui` | before | 5,054,180 | 74.61 | 41.28 | 38.50 |
| | after | 4,905,740 (-148,440) | 69.43 | 35.19 | 32.34 |
| `dotnet new android` | before | 16,484 | 90.78 | 90.78 | 90.78 |
| | after | 16,484 | 89.36 | 89.36 | 89.36 |

The same MAUI app built with the shipped .NET 11 SDK 11.0.100 (Android workload 37.2.31, R8 9.5.26). I re-ran R8 with the same response file and only replaced `proguard_project_primary.cfg` with the new rules:

| | DEX bytes | noObfuscation % | noOptimization % | noShrinking % |
|---|---|---|---|---|
| before | 5,166,352 | 71.93 | 37.51 | 34.79 |
| after | 5,119,396 (-46,956) | 69.75 | 35.08 | 32.50 |

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants