Skip to content

[Xamarin.Android.Build.Tasks] Generate R8 rules without trimming - #13546

Merged
simonrozsival merged 1 commit into
mainfrom
simonrozsival-maui-40138-investigation
Nov 13, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
simonrozsival-maui-40138-investigation

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Context: dotnet/maui#40138

A Release MAUI app using R8 private-members and PublishTrimmed=false fails during startup with a TypeInitializationException for Microsoft.Maui.Controls.VisualElement. The build reports XA4304 because proguard_project_references.cfg is missing. Changing only PublishTrimmed to true avoids the failure.

PublishTrimmed controls managed trimming, not Java shrinking. Explicitly selecting AndroidLinkTool=r8 already enables Java shrinking independently of PublishTrimmed; this PR preserves that existing behavior rather than disabling Java shrinking when managed trimming is off. Disabling Java shrinking alone would also not protect JNI names and signatures from obfuscation or optimization, so managed bindings still need keep rules.

Reference-rule generation was restricted to trimmed builds and hooked to ILLink. Untrimmed builds therefore omitted the rules protecting Java members accessed through managed bindings. Generate these rules after ComputeFilesToPublish in untrimmed inner RID builds, preserving the existing trimmed/retained-typemap pipeline and incremental recovery behavior. With PublishTrimmed=true, the updated condition reduces to the same eligibility checks as before.

The reported scenario is a Release build with R8 explicitly enabled. Ordinary Debug builds still use D8: AndroidLinkTool and the generated reference-rule path remain empty, so this change neither enables R8 nor adds the reference-rule scan to those builds. A Debug build that explicitly opts into R8 can also use the corrected untrimmed path; the fix is not restricted to the configuration name.

Extend target and packaging regressions to cover untrimmed builds, unchanged inputs, and deleted-rule recovery. This targets current main; release backports will follow separately. The earlier UnsatisfiedLinkError in the issue remains unreproduced.

Build-time measurements on an M5 Max MacBook showed no significant adverse overall impact for the MAUI sample-content app with managed trimming disabled and R8 enabled. Across six alternating before/after rounds, clean-build medians were approximately 51 seconds in both variants; the added rule-generation task took about 80 ms, implementation-edit builds increased by about 0.15 seconds at the median, and steady no-change builds remained approximately 1.5 seconds with both rule generation and R8 skipped. These are warm-cache, restore-excluded measurements on a shared machine, so small differences are within observed noise; the pre-fix variant builds but omits the required JNI rules.

Validation

  • make prepare — passed.
  • make all — solution build passed after correcting test compilation errors; local workload setup initially failed on missing binding XML documentation. Completed prerequisites with the commands below.
  • ./dotnet-local.sh build src/Mono.Android/Mono.Android.csproj -p:GenerateDocumentationFile=true -p:NoWarn=CS1591 — passed, with existing binding warnings.
  • ./dotnet-local.sh build Microsoft.Android.slnx -t:BuildExtraApiLevels -p:GenerateDocumentationFile=true -p:NoWarn=CS1591 — passed, with existing binding warnings.
  • ./dotnet-local.sh build build-tools/create-packs/Microsoft.Android.Sdk.proj -t:ConfigureLocalWorkload — passed.
  • ./dotnet-local.sh test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj --no-restore -p:BuildProjectReferences=false -p:_NativeAotLlvmReadObjPath=/Users/simon/android-toolchain/ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin/llvm-readobj -v minimal --filter 'FullyQualifiedName~TypeMapProguardTargetsTests' — 99 passed, none failed or skipped. The three added untrimmed cases failed against the original targets.
  • ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj --no-restore -p:BuildProjectReferences=false — passed, zero warnings/errors.
  • ./dotnet-local.sh test bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter 'FullyQualifiedName~PackagingTest.R8PreservesInstanceIntFieldType' — 2 passed, covering trimmed/untrimmed packaging, incremental builds, and missing-rule recovery.
  • Reconstructed MAUI 10.0.120 sample adapted to net12.0-android, built using the local SDK with PublishTrimmed=false, R8 private-members, and PublishReadyToRun=false: dotnet-local.sh build Maui10R8Repro/Maui10R8Repro.csproj -c Release -p:RuntimeIdentifier=android-arm64 -p:AndroidSdkDirectory=/Users/simon/android-toolchain/sdk -p:JavaSdkDirectory=/Users/simon/android-toolchain/jdk-25 -bl:main-repro.binlog — clean and incremental builds passed, zero warnings/errors. APK startup and button interaction passed on Android 16 arm64 with 16 KB pages, without additional keep rules.
  • Evaluated the sample's Debug properties with dotnet-local.sh msbuild Maui10R8Repro/Maui10R8Repro.csproj -p:TargetFramework=net12.0-android -p:Configuration=Debug -getProperty:PublishTrimmed,AndroidLinkTool,AndroidEnableMultiDex,_ProguardProjectConfiguration,_GenerateProguardAfterTargets — confirmed AndroidLinkTool and _ProguardProjectConfiguration are empty and AndroidEnableMultiDex=False; ordinary Debug builds do not select R8 or generate reference rules.
  • git diff --check — passed.

Context: dotnet/maui#40138

A Release MAUI application using R8 private-member obfuscation and PublishTrimmed=false fails during startup with a TypeInitializationException for Microsoft.Maui.Controls.VisualElement.  The build also reports XA4304 because proguard_project_references.cfg is missing.  Enabling managed trimming alone avoids the failure.

Reference-rule generation was restricted to trimmed builds and ran after ILLink.  Untrimmed builds never generated the rules protecting Java members accessed only through managed bindings, allowing R8 to remove or optimize required members.

Generate these rules after ComputeFilesToPublish in untrimmed inner RID builds, using the resolved publish assemblies.  Preserve the existing ILLink hook and retained-typemap policy for trimmed builds, and reuse the existing incremental stamp and missing-output recovery.

Extend target and packaging regressions to cover untrimmed builds, unchanged inputs, and deleted-rule recovery.  All 99 target tests and both packaging cases pass.  The reconstructed MAUI application also launches and handles button interaction with managed trimming disabled on an Android 16 arm64 emulator with 16 KB pages, using the locally built main SDK.

Co-authored-by: Copilot App <[email protected]>

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

There are no active review issues requiring changes.

No open issues 🎉

What changed in this PR

Fixes missing R8 reference rules in untrimmed CoreCLR builds, addressing startup failures when Java members accessed through managed bindings are removed or optimized.

Changes:

  • Generates reference rules after ComputeFilesToPublish in untrimmed inner RID builds while preserving the trimmed pipeline.
  • Extends target and packaging tests to cover untrimmed builds, unchanged-input skipping, and deleted-rule recovery.
  • Documents why R8 still needs keep rules when managed trimming is disabled.
File Description
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​PackagingTest.cs Adds untrimmed packaging and incremental recovery coverage.
src/​Xamarin.Android.Build.Tasks/​Microsoft.Android.Sdk/​targets/​Microsoft.Android.Sdk.TypeMap.Trimmable.CoreCLR.targets Enables reference-rule generation for untrimmed builds.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​TypeMapProguardTargetsTests.cs Tests generation hooks, eligibility, and missing-rule recovery.
Documentation/​guides/​D8andR8.md Explains R8 rule generation without managed trimming.

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 13, 2026
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13546

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

✅ LGTM on code — 0 errors, 0 warnings, 1 non-blocking inline testing suggestion.

Reviewed all four changed files in full and traced the keep-rule producer, outer-build consumption, R8 fallback policy, and missing-output stamp invalidation. The untrimmed path now runs after publish-item computation, while the trimmed path retains its existing eligibility checks. The DEX field assertion and incremental/deleted-rule regressions are useful end-to-end coverage; no merge-blocking correctness issues found.

CI: All 41 GitHub checks report success, including the aggregate dotnet-android check for Azure build 1679379. Direct Azure build/timeline verification was blocked because az devops invoke requires login in this environment, so I could not independently confirm Azure's final result beyond the published GitHub checks. Local tests were not run during this review.

Generated by Android PR Reviewer for #13546 · copilot · gpt61 · 43.5 AIC · ⌖ 7.5 AIC · ⊞ 20.2K
Comment /review to run again

"Lexample/PlaybackError;", "type", "I", DexUtils.GetDexDump (dexFile, AndroidSdkPath))),
"R8 must preserve the instance field as int, not narrow it to byte, for managed JNI access.");

if (!publishTrimmed) {

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 — Consider adding a PublishTrimmed=true → false → true round trip using the same project/intermediate directory, checking the generated rules and DEX field after each switch. The separate test cases cover clean builds in each mode, plus unchanged inputs and deleted-output recovery, but not switching between the retained-typemap producer and the legacy inner-RID producer with existing outputs. That would strengthen coverage of the hook selection and stale-rule handling without requiring another fixture.

{Rule: Test edge cases}

@simonrozsival
simonrozsival merged commit 1013d2e into main Nov 13, 2026
41 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-maui-40138-investigation branch November 13, 2026 14:36
@jonathanpeppers

Copy link
Copy Markdown
Member

/backport to release/11.0.1xx

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0.1xx (link to workflow run)

@github-actions

Copy link
Copy Markdown
Contributor

@jonathanpeppers backporting to release/11.0.1xx failed, the patch most likely resulted in conflicts. Please backport manually!

git am output
$ git cherry-pick 1013d2ea90e4de40fbdc3891086d61c80a9ea3e6

Auto-merging Documentation/guides/D8andR8.md
CONFLICT (content): Merge conflict in Documentation/guides/D8andR8.md
CONFLICT (modify/delete): src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs deleted in HEAD and modified in 1013d2ea9 ([Xamarin.Android.Build.Tasks] Generate R8 rules without trimming (#13546)).  Version 1013d2ea9 ([Xamarin.Android.Build.Tasks] Generate R8 rules without trimming (#13546)) of src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs left in tree.
Auto-merging src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Trimmable.CoreCLR.targets
CONFLICT (content): Merge conflict in src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Trimmable.CoreCLR.targets
Auto-merging src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs
CONFLICT (content): Merge conflict in src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs
error: could not apply 1013d2ea9... [Xamarin.Android.Build.Tasks] Generate R8 rules without trimming (#13546)
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git cherry-pick --continue".
hint: You can instead skip this commit with "git cherry-pick --skip".
hint: To abort and get back to the state before "git cherry-pick",
hint: run "git cherry-pick --abort".
hint: Disable this message with "git config set advice.mergeConflict false"


$ git am --3way --empty=keep --ignore-whitespace --keep-non-patch changes.patch

Applying: [Xamarin.Android.Build.Tasks] Generate R8 rules without trimming
Using index info to reconstruct a base tree...
M	Documentation/guides/D8andR8.md
A	src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs
M	src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Trimmable.CoreCLR.targets
M	src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs
Falling back to patching base and 3-way merge...
Auto-merging Documentation/guides/D8andR8.md
CONFLICT (content): Merge conflict in Documentation/guides/D8andR8.md
CONFLICT (modify/delete): src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs deleted in HEAD and modified in [Xamarin.Android.Build.Tasks] Generate R8 rules without trimming.  Version [Xamarin.Android.Build.Tasks] Generate R8 rules without trimming of src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs left in tree.
Auto-merging src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Trimmable.CoreCLR.targets
CONFLICT (content): Merge conflict in src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Trimmable.CoreCLR.targets
Auto-merging src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs
CONFLICT (content): Merge conflict in src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0001 [Xamarin.Android.Build.Tasks] Generate R8 rules without trimming
Error: The process '/usr/bin/git' failed with exit code 128

Link to workflow output

jonathanpeppers added a commit that referenced this pull request Nov 17, 2026
…thout trimming (#13546) (#13558)

Context: dotnet/maui#40138

A Release MAUI app using R8 `private-members` and `PublishTrimmed=false` fails during startup with a `TypeInitializationException` for `Microsoft.Maui.Controls.VisualElement`. The build reports XA4304 because `proguard_project_references.cfg` is missing. Changing only `PublishTrimmed` to `true` avoids the failure.

`PublishTrimmed` controls managed trimming, not Java shrinking. Explicitly selecting `AndroidLinkTool=r8` already enables Java shrinking independently of `PublishTrimmed`; this PR preserves that existing behavior rather than disabling Java shrinking when managed trimming is off. Disabling Java shrinking alone would also not protect JNI names and signatures from obfuscation or optimization, so managed bindings still need keep rules.

Reference-rule generation was restricted to trimmed builds and hooked to ILLink. Untrimmed builds therefore omitted the rules protecting Java members accessed through managed bindings. Generate these rules after `ComputeFilesToPublish` in untrimmed inner RID builds, preserving the existing trimmed/retained-typemap pipeline and incremental recovery behavior. With `PublishTrimmed=true`, the updated condition reduces to the same eligibility checks as before.

The reported scenario is a Release build with R8 explicitly enabled. Ordinary Debug builds still use D8: `AndroidLinkTool` and the generated reference-rule path remain empty, so this change neither enables R8 nor adds the reference-rule scan to those builds. A Debug build that explicitly opts into R8 can also use the corrected untrimmed path; the fix is not restricted to the configuration name.

Extend target and packaging regressions to cover untrimmed builds, unchanged inputs, and deleted-rule recovery. This targets current `main`; release backports will follow separately. The earlier `UnsatisfiedLinkError` in the issue remains unreproduced.

Build-time measurements on an M5 Max MacBook showed no significant adverse overall impact for the MAUI sample-content app with managed trimming disabled and R8 enabled. Across six alternating before/after rounds, clean-build medians were approximately 51 seconds in both variants; the added rule-generation task took about 80 ms, implementation-edit builds increased by about 0.15 seconds at the median, and steady no-change builds remained approximately 1.5 seconds with both rule generation and R8 skipped. These are warm-cache, restore-excluded measurements on a shared machine, so small differences are within observed noise; the pre-fix variant builds but omits the required JNI rules.

Backport of #13546 to release/11.0.1xx.

release/11.0.1xx uses the LLVM IR typemap by default, and only sets
`_ProguardProjectConfiguration` in `_PrepareLinking` for trimmed builds.
This backport applies the fix to `Microsoft.Android.Sdk.TypeMap.LlvmIr.targets`:
untrimmed inner RID builds set the rules path and generate the rules after
`ComputeFilesToPublish`. Trimmed builds are unchanged. The test uses the
rules file timestamp because this branch has no `.stamp` file.

(cherry picked from commit 1013d2e)

Co-authored-by: Šimon Rozsíval <[email protected]>
Co-authored-by: Copilot App <[email protected]>
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