Skip to content

[Xamarin.Android.Build.Tasks] Let runtime-remapping rename classes - #13836

Merged
jonathanpeppers merged 3 commits into
mainfrom
simonrozsival-vigilant-goggles
Dec 1, 2026
Merged

jonathanpeppers merged 3 commits into
mainfrom
simonrozsival-vigilant-goggles

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: f84682e267ca7a218613fcfcdfcadc7297dfd732

Dimension Assessment Rationale
Change confidence 8/10 ↑ 31 host tests, four CoreCLR/NativeAOT device cases, and a fully trimmed MAUI smoke test passed.
↓ Native/runtime binaries predate the main merge, and the MAUI sample reports trim warnings.
Diagnosis confidence 9.5/10 ↑ Restoring only the two blanket rules reduced the number of renamed classes in controlled builds.
Evidence fit 5/10 ↑ Main's runtime-remapping mode showed substantially more obfuscation after removing the rules.
↓ The linked production report concerns .NET 11 private-members and its Play metrics, which this main-only change does not address.

Context: #13603
Context: #12814
Context: 26a426d

$(AndroidR8ObfuscationMode)=runtime-remapping allows R8 to rename Java types and members while the generated tables translate binding and activation lookups. However, <R8/> still emitted two blanket rules in this mode:

-keepnames public class *
-keepnames class **$*

These rules preserve the names of public and nested classes, limiting obfuscation even when runtime remapping is enabled. Remove them for runtime-remapping; private-members and disabled are unchanged. The field-name and Kotlin interop rules remain in place.

This is a main-only improvement to the opt-in mode, not a .NET 11 backport or a fix for the private-members behavior reported in #13603.

Compatibility

Binding lookups, [Register] metadata, and Java-to-managed activation use the remapping tables. Arbitrary strings passed to APIs such as Java.Lang.Class.ForName ("com.example.Foo") or JNIEnv.FindClass ("com/example/Foo") do not. A lookup by the original name may therefore fail when R8 renames the class.

Apps that perform string-based lookups can add rules to a @(ProguardConfiguration) file:

# Preserve the name of a class that is otherwise retained.
-keepnames class com.example.Foo
# Also prevent shrinking of a class used only through reflection.
-keep class com.example.Foo { *; }

The build-property documentation and release note explain this distinction. Default behavior is unchanged because runtime-remapping is opt-in.

Measurements

On an Apple M5 Max, build the same MAUI sample twice in Release for android-arm64 with CoreCLR, full trimming, JDK 25, and R8 9.5.33. The baseline restores only the two removed rules through a @(ProguardConfiguration) item; the candidate omits them. Both clean rebuilds use the same SDK and optimizing Android defaults.

Metric Before After Change
R8 obfuscation 48.14% 55.69% +7.55 percentage points
R8 optimization 32.91% 38.80% +5.89 percentage points
R8 shrinking 67.00% 65.59% −1.41 percentage points
Renamed class targets in DEX 433 3,246 +2,813
DEX bytes 3,921,724 3,569,380 −352,344 (−8.98%)
Signed APK bytes 16,985,814 16,948,950 −36,864 (−0.22%)

The percentages are computed as 100 minus the corresponding noObfuscationPercentage, noOptimizationPercentage, and noShrinkingPercentage values in R8's r8.json; they are not measurements from a Play upload. Renamed classes count distinct mapping targets present in the final DEX; mapping entries without a DEX target are excluded.

An earlier controlled Material/AndroidX sample at main revision 6716a791b0 also increased renamed classes from 267 to 1,851, reduced DEX bytes from 2,144,544 to 1,962,780 (−8.48%), and reduced signed APK bytes from 9,176,943 to 9,144,175 (−0.36%).

Validation

  • make prepare CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false' && make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false': passed before the main merge at 6716a791b0.
  • ./dotnet-local.sh build src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj -c Release -m:2 -nr:false -v:minimal: passed after the merge; the affected Xamarin.Android tasks and host/device test assemblies were also rebuilt in Release.
  • DOTNET_PROCESSOR_COUNT=2 DOTNET_CLI_USE_MSBUILD_SERVER=0 MSBUILDDISABLENODEREUSE=1 ./dotnet-local.sh test --test-modules bin/TestRelease/net11.0/Xamarin.Android.Build.Tests.dll --filter 'FullyQualifiedName~R8Tests': 31 passed.
  • TEST_ANDROID_JDK_PATH="$HOME/android-toolchain/jdk-25" ANDROID_HOME="$HOME/Library/Android/sdk" ADB_TARGET='-s emulator-5558' DOTNET_PROCESSOR_COUNT=4 DOTNET_CLI_USE_MSBUILD_SERVER=0 MSBUILDDISABLENODEREUSE=1 ./dotnet-local.sh test --test-modules bin/TestRelease/MSBuildDeviceIntegration/net11.0/MSBuildDeviceIntegration.dll --filter 'Name~ObfuscatedMembersRun': four API 35 arm64 device cases passed, covering CoreCLR and NativeAOT with the compression opt-in on and off. NativeAOT remains uncompressed.
  • The MAUI sample was generated with the installed .NET 11 dotnet new maui --sample-content template, retargeted to net12.0-android, and built with locally built MAUI 12.0.0-dev packages from dotnet/maui 1344d164211e09569f56555998fd37fbdb851294; it is not an untouched .NET 12 template. The baseline build passed with the command below, with $root denoting the sample directory and $session the artifact directory. The candidate passed with the same command after removing the two rules, using -bl:"$session/candidate.binlog". The sample emitted IL2026/IL2104 CommunityToolkit trim warnings and NU1801 for the unavailable nuget.org source; restore had succeeded using cached packages and other feeds.
JAVA_HOME="$HOME/android-toolchain/jdk-25" ANDROID_HOME="$HOME/Library/Android/sdk" DOTNET_CLI_USE_MSBUILD_SERVER=0 MSBUILDDISABLENODEREUSE=1 DOTNET_PROCESSOR_COUNT=4 ./dotnet-local.sh build "$root/MauiR8.csproj" -t:Rebuild -c Release --no-restore -p:RuntimeIdentifier=android-arm64 -p:TrimMode=full -p:PublishTrimmed=true -p:AndroidLinkTool=r8 -p:AndroidR8ObfuscationMode=runtime-remapping -p:AndroidPackageFormat=apk -m:2 -nr:false -bl:"$session/baseline.binlog"

The measured candidate APK launched on the API 35 arm64 emulator; Dashboard, Projects, Manage Meta, and project detail loaded, and saving was exercised without observed app-process fatal or class-lookup errors. This is a smoke test, not exhaustive MAUI coverage.

A full SDK rebuild after the main merge was not run because the shared host had less than the requested 60 GiB free. The measured SDK combines rebuilt current task assemblies with native/runtime binaries from the earlier full build.

simonrozsival and others added 3 commits November 30, 2026 19:25
Remove blanket class-name preservation when JNI runtime remapping is enabled, and document the need for explicit rules for string-based lookups.

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

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

Removing the blanket keep rules allows Kotlin value classes to be renamed while generated JNI bindings still use original names and descriptors, risking runtime lookup failures during construction or boxed/nullable marshaling.

1 open issue
What changed in this PR

This PR enables broader Java class obfuscation in .NET for Android’s opt-in runtime-remapping mode. It leaves private-members and disabled unchanged and does not address the .NET 11 default-mode behavior reported in #13603.

Changes:

  • Removes blanket name-preservation rules for public and nested Java classes.
  • Extends host and device checks for class renaming, binding activation, reflection keep rules, and incremental remapping.
  • Documents string-based lookup limitations and explicit keep-rule options.
File Description
tests/​MSBuildDeviceIntegration/​Tests/​R8RuntimeRemappingTests.cs Exercises renamed public/nested classes and reflection keep rules.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​R8Tests.cs Verifies blanket class-name rules are absent.
src/​Xamarin.Android.Build.Tasks/​Tasks/​R8.cs Removes two blanket rules from runtime-remapping mode.
Documentation/​release-notes/​r8-runtime-remapping-class-names.md Announces class renaming and compatibility considerations.
Documentation/​docs-mobile/​building-apps/​build-properties.md Explains string-based lookups and required keep rules.

Review effort: Balanced

writer.WriteLine ("-keepnames public class *");
writer.WriteLine ("-keepnames class **$*");
// Kotlin value-class structs call these helpers by name over JNI.
writer.WriteLine ("-keepclassmembernames class * { *** box?impl(...); *** unbox?impl(...); *** constructor?impl(...); }");
@jonathanpeppers

Copy link
Copy Markdown
Member

/azp run Xamarin.Android-PR

@azure-pipelines

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

@PeppersMuse PeppersMuse left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the R8 rule removal and the new host/device tests. One issue below on Kotlin value classes; the rest of the change checks out — the removed -keepnames rules are asserted gone in R8Tests.WriteRuntimeRemappingRules, and the device test covers renamed public/nested classes through regular bindings.

writer.WriteLine ("-keepnames public class *");
writer.WriteLine ("-keepnames class **$*");
// Kotlin value-class structs call these helpers by name over JNI.
writer.WriteLine ("-keepclassmembernames class * { *** box?impl(...); *** unbox?impl(...); *** constructor?impl(...); }");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing the two blanket -keepnames rules also lets R8 rename Kotlin @JvmInline value classes, but the generated struct bindings in src/generator/SourceWriters/KotlinInlineClassStruct.cs still look them up by their original names: __GetJniType() calls JniType.GetCachedJniType with the original JNI name, and ToLocalJniHandle looks up box-impl with a descriptor containing the original class name ((J)L<original>;). That JniType path does no remapping — GetCachedStaticMethod goes straight to raw GetStaticMethodID and FindClass goes straight to raw JNI FindClass, unlike the JniPeerMembers path used by regular bindings. So constructing a value class with an init block or marshaling a boxed/nullable value will fail at runtime once the class is renamed. The device test here exercises renamed classes only through regular bindings, so this isn't covered. Until the generated lookups go through the remapping tables, consider keeping the names of classes that declare these helpers, e.g. -keepnames class * { *** box-impl(...); *** unbox-impl(...); *** constructor-impl(...); }, plus a device test with a Kotlin value class under runtime-remapping.

@jonathanpeppers

Copy link
Copy Markdown
Member

Internal Xamarin.Android-PR build 16171121 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 > Tests > MSBuild 6 / Guardian: Post Analysis BinSkim scans adb.exe that a test downloads into its temp folder. Not product code.
Task: Windows > Build & Smoke Test / Ensure no modified/untracked files Untracked .sarif file left by the Guardian tools. Fails on every main build.
Test: BuildTest2.Plugin_Maui_Audio (NativeAOT) 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.

Comment on lines +1 to +9
### Application publishing

- [GitHub Issue 13603](https://github.com/dotnet/android/issues/13603):
`AndroidR8ObfuscationMode=runtime-remapping` now allows R8 to rename public
and nested Java classes instead of keeping their names. Code that looks up
classes by their original names with `Class.ForName` or
`JNIEnv.FindClass(string)` needs appropriate R8 rules in
`ProguardConfiguration`. Classes accessed only through these APIs may also
need rules that prevent shrinking.

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.

I will probably do a PR to remove this folder, so AIs stop making these files!

@jonathanpeppers
jonathanpeppers merged commit a50bb10 into main Dec 1, 2026
2 of 3 checks passed
@jonathanpeppers
jonathanpeppers deleted the simonrozsival-vigilant-goggles branch December 1, 2026 16:50
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.

4 participants