Repository navigation
[Xamarin.Android.Build.Tasks] Let runtime-remapping rename classes - #13836
Conversation
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>
There was a problem hiding this comment.
🟡 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(...); }"); |
|
/azp run Xamarin.Android-PR |
|
No pipelines are associated with this pull request. |
PeppersMuse
left a comment
There was a problem hiding this comment.
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(...); }"); |
There was a problem hiding this comment.
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.
|
Internal
The public CI (dnceng-public) is offline, so this internal build is the only CI result. |
| ### 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. |
There was a problem hiding this comment.
I will probably do a PR to remove this folder, so AIs stop making these files!

Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
f84682e267ca7a218613fcfcdfcadc7297dfd732↓ Native/runtime binaries predate the main merge, and the MAUI sample reports trim warnings.
↓ 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-remappingallows 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:These rules preserve the names of public and nested classes, limiting obfuscation even when runtime remapping is enabled. Remove them for
runtime-remapping;private-membersanddisabledare 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-membersbehavior reported in #13603.Compatibility
Binding lookups,
[Register]metadata, and Java-to-managed activation use the remapping tables. Arbitrary strings passed to APIs such asJava.Lang.Class.ForName ("com.example.Foo")orJNIEnv.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:The build-property documentation and release note explain this distinction. Default behavior is unchanged because
runtime-remappingis opt-in.Measurements
On an Apple M5 Max, build the same MAUI sample twice in Release for
android-arm64with 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.The percentages are computed as 100 minus the corresponding
noObfuscationPercentage,noOptimizationPercentage, andnoShrinkingPercentagevalues in R8'sr8.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
6716a791b0also 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 at6716a791b0../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.dotnet new maui --sample-contenttemplate, retargeted tonet12.0-android, and built with locally built MAUI12.0.0-devpackages from dotnet/maui1344d164211e09569f56555998fd37fbdb851294; it is not an untouched .NET 12 template. The baseline build passed with the command below, with$rootdenoting the sample directory and$sessionthe artifact directory. The candidate passed with the same command after removing the two rules, using-bl:"$session/candidate.binlog". The sample emittedIL2026/IL2104CommunityToolkit trim warnings andNU1801for the unavailable nuget.org source; restore had succeeded using cached packages and other feeds.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.