From b9bd72b1f3d39c09c9497653517376b48a4b787c Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Thu, 10 Sep 2026 13:16:07 -0500 Subject: [PATCH] Backport selective R8 obfuscation Keep R8 obfuscation disabled by default on .NET 10 while allowing private Java members to be obfuscated and optimized when explicitly requested. Validate mode values only when R8 is enabled. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Documentation/docs-mobile/TOC.yml | 2 + .../building-apps/build-properties.md | 16 ++ Documentation/docs-mobile/messages/index.md | 1 + Documentation/docs-mobile/messages/xa1050.md | 34 ++++ .../installers/create-installers.targets | 1 + .../Properties/Resources.Designer.cs | 9 + .../Properties/Resources.resx | 5 + .../Resources/proguard_xamarin.cfg | 4 +- src/Xamarin.Android.Build.Tasks/Tasks/R8.cs | 25 +++ .../PackagingTest.cs | 55 +++++- .../Tasks/R8Tests.cs | 48 ++++++ .../Android/KnownProperties.cs | 1 + .../Xamarin.Android.Common.targets | 14 +- .../Xamarin.Android.D8.targets | 1 + src/proguard-android/proguard-android.targets | 16 +- .../Tests/R8ObfuscationTests.cs | 162 ++++++++++++++++++ 16 files changed, 384 insertions(+), 10 deletions(-) create mode 100644 Documentation/docs-mobile/messages/xa1050.md create mode 100644 src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Tasks/R8Tests.cs create mode 100644 tests/MSBuildDeviceIntegration/Tests/R8ObfuscationTests.cs diff --git a/Documentation/docs-mobile/TOC.yml b/Documentation/docs-mobile/TOC.yml index bdb778ad713..5c0e8c892f7 100644 --- a/Documentation/docs-mobile/TOC.yml +++ b/Documentation/docs-mobile/TOC.yml @@ -274,6 +274,8 @@ href: messages/xa1037.md - name: XA1038 href: messages/xa1038.md + - name: XA1050 + href: messages/xa1050.md - name: "XA2xxx: Linker" items: - name: "XA2xxx: Linker" diff --git a/Documentation/docs-mobile/building-apps/build-properties.md b/Documentation/docs-mobile/building-apps/build-properties.md index c261eccd0b9..964d0d7a4db 100644 --- a/Documentation/docs-mobile/building-apps/build-properties.md +++ b/Documentation/docs-mobile/building-apps/build-properties.md @@ -1119,6 +1119,22 @@ r8 dex-compiler and shrinker. The default value is a path into the .NET for Android workload installation. For further information see our documentation on [D8 and R8][d8-r8]. +## AndroidR8ObfuscationMode + +An enum-style property that specifies how `r8` obfuscates Java names when +[`$(AndroidLinkTool)`](#androidlinktool) is `r8`. Supported values are: + +- `private-members` preserves Java class and interface names and public or + protected member names. Private and package-private members can be + obfuscated, and R8 optimization is enabled. +- `disabled` disables obfuscation, preserves all Java names, and uses the + non-optimizing Android R8 defaults. + +This property does not disable R8 code shrinking. + +This property was introduced in a .NET 10 servicing release and defaults to +`disabled` in .NET 10. + ## AndroidResgenExtraArgs Specifies diff --git a/Documentation/docs-mobile/messages/index.md b/Documentation/docs-mobile/messages/index.md index 4ed408a0899..48a3517dbc9 100644 --- a/Documentation/docs-mobile/messages/index.md +++ b/Documentation/docs-mobile/messages/index.md @@ -150,6 +150,7 @@ Either change the value in the AndroidManifest.xml to match the $(SupportedOSPla + [XA1039](xa1039.md): The Android Support libraries are not supported in .NET 9 and later, please migrate to AndroidX. See https://aka.ms/xamarin/androidx for more details. + [XA1040](xa1040.md): The CoreCLR runtime on Android is an experimental feature and not yet suitable for production use. File issues at: https://github.com/dotnet/android/issues + [XA1041](xa1041.md): The MSBuild property 'MonoAndroidAssetPrefix' has an invalid value of 'c:\Foo\Assets'. The value is expected to be a directory path representing the relative location of your Assets or Resources ++ [XA1050](xa1050.md): The 'AndroidR8ObfuscationMode' MSBuild property has an invalid value. ## XA2xxx: Linker diff --git a/Documentation/docs-mobile/messages/xa1050.md b/Documentation/docs-mobile/messages/xa1050.md new file mode 100644 index 00000000000..1f984daa7ba --- /dev/null +++ b/Documentation/docs-mobile/messages/xa1050.md @@ -0,0 +1,34 @@ +--- +title: .NET for Android error XA1050 +description: XA1050 error code +ms.date: 09/10/2026 +f1_keywords: + - "XA1050" +--- + +# .NET for Android error XA1050 + +## Example messages + +```dotnetcli +error XA1050: The 'AndroidR8ObfuscationMode' MSBuild property has an invalid value of 'private-member'. Valid values are 'disabled' and 'private-members'. +``` + +## Issue + +The [`$(AndroidR8ObfuscationMode)`](../building-apps/build-properties.md#androidr8obfuscationmode) +MSBuild property contains an unsupported value. This property is validated when +R8 runs. + +## Solution + +Set `$(AndroidR8ObfuscationMode)` to one of the supported values: + +```xml + + private-members + +``` + +Use `disabled` to preserve all Java names and use the legacy non-optimizing +Android R8 configuration. diff --git a/build-tools/installers/create-installers.targets b/build-tools/installers/create-installers.targets index 6eea7e7fe9c..bdf7ac5f34f 100644 --- a/build-tools/installers/create-installers.targets +++ b/build-tools/installers/create-installers.targets @@ -136,6 +136,7 @@ <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)java_runtime_clr.dex" ExcludeFromLegacy="true" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)java_runtime_fastdev_clr.dex" ExcludeFromLegacy="true" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)manifestmerger.jar" /> + <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)proguard-android-optimize.txt" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)proguard-android.txt" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)protobuf-net.dll" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)System.CodeDom.dll" /> diff --git a/src/Xamarin.Android.Build.Tasks/Properties/Resources.Designer.cs b/src/Xamarin.Android.Build.Tasks/Properties/Resources.Designer.cs index c301a8d6dd6..6a9e06b74e1 100644 --- a/src/Xamarin.Android.Build.Tasks/Properties/Resources.Designer.cs +++ b/src/Xamarin.Android.Build.Tasks/Properties/Resources.Designer.cs @@ -902,6 +902,15 @@ public static string XA1041 { } } + /// + /// Looks up a localized string similar to The 'AndroidR8ObfuscationMode' MSBuild property has an invalid value of '{0}'. Valid values are 'disabled' and 'private-members'.. + /// + public static string XA1050 { + get { + return ResourceManager.GetString("XA1050", resourceCulture); + } + } + /// /// Looks up a localized string similar to Use of AppDomain.CreateDomain() detected in assembly: {0}. .NET 6 and higher will only support a single AppDomain, so this API will no longer be available in .NET for Android once .NET 6 is released.. /// diff --git a/src/Xamarin.Android.Build.Tasks/Properties/Resources.resx b/src/Xamarin.Android.Build.Tasks/Properties/Resources.resx index 756007eea2a..b669a9ae8e1 100644 --- a/src/Xamarin.Android.Build.Tasks/Properties/Resources.resx +++ b/src/Xamarin.Android.Build.Tasks/Properties/Resources.resx @@ -1008,6 +1008,11 @@ To use a custom JDK path for a command line build, set the 'JavaSdkDirectory' MS {0} - The MSBuild property that has the incorrect value. {1} - The current value of the property + + + The 'AndroidR8ObfuscationMode' MSBuild property has an invalid value of '{0}'. Valid values are 'disabled' and 'private-members'. + The following are literal names and should not be translated: AndroidR8ObfuscationMode, MSBuild, disabled, private-members. +{0} - The invalid value of the AndroidR8ObfuscationMode MSBuild property. Java dependency '{0}' is not satisfied. diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg index 9b16fefd6cf..f5e0e1e128a 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_xamarin.cfg @@ -1,7 +1,5 @@ # This is Xamarin-specific (and enhanced) configuration. --dontobfuscate - -keep class android.support.multidex.MultiDexApplication { (); } -keep class net.dot.jni.** { *; (); } -keep class mono.MonoRuntimeProvider* { *; (...); } @@ -22,6 +20,8 @@ -keepclassmembers class md52ce486a14f4bcd95899665e9d932190b.** { *; (...); } # .NET runtime +# Loaded by name from managed code. +-keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } # Android's template misses fluent setters... diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/R8.cs b/src/Xamarin.Android.Build.Tasks/Tasks/R8.cs index b11d504734f..88cbe90c547 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/R8.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/R8.cs @@ -36,6 +36,7 @@ public class R8 : D8 public string? ProguardMappingFileOutput { get; set; } public string? BuildMetadataFileOutput { get; set; } public string []? ProguardConfigurationFiles { get; set; } + public string ObfuscationMode { get; set; } = "disabled"; protected override string MainClass => "com.android.tools.r8.R8"; @@ -116,6 +117,9 @@ protected override string CreateResponseFile () } if (!ProguardCommonXamarinConfiguration.IsNullOrWhiteSpace ()) { using (var xamcfg = File.CreateText (ProguardCommonXamarinConfiguration)) { + WriteObfuscationRules (xamcfg, ObfuscationMode); + xamcfg.WriteLine (); + xamcfg.Flush (); GetType ().Assembly.GetManifestResourceStream ("proguard_xamarin.cfg").CopyTo (xamcfg.BaseStream); if (IgnoreWarnings) { xamcfg.WriteLine ("-ignorewarnings"); @@ -165,6 +169,27 @@ protected override string CreateResponseFile () return responseFile; } + internal static void WriteObfuscationRules (TextWriter writer, string obfuscationMode) + { + if (string.Equals (obfuscationMode, "disabled", StringComparison.OrdinalIgnoreCase)) { + writer.WriteLine ("-dontobfuscate"); + return; + } + if (!string.Equals (obfuscationMode, "private-members", StringComparison.OrdinalIgnoreCase)) { + throw new ArgumentException ($"Unsupported R8 obfuscation mode '{obfuscationMode}'.", nameof (obfuscationMode)); + } + + writer.WriteLine ("-keep,allowshrinking,allowoptimization class **"); + writer.WriteLine ("-keepclassmembers,allowshrinking,allowoptimization class ** {"); + writer.WriteLine (" public protected *;"); + writer.WriteLine ("}"); + // Managed interface proxy selection observes Class.getInterfaces(), which R8 cannot infer. + writer.WriteLine ("-keep,allowoptimization interface ** {"); + writer.WriteLine (" public protected *;"); + writer.WriteLine ("}"); + writer.WriteLine ("-keep,allowshrinking class * implements **"); + } + // Note: We do not want to call the base.LogEventsFromTextOutput as it will incorrectly identify // Warnings and Info messages as errors. protected override void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance) diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs index 617ef224248..307629c9d25 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/PackagingTest.cs @@ -4,6 +4,7 @@ using Xamarin.ProjectTools; using System.Linq; using System.Text; +using System.Text.Json; using System.Collections.Generic; using System.Xml.Linq; using Xamarin.Tools.Zip; @@ -17,12 +18,18 @@ namespace Xamarin.Android.Build.Tests public class PackagingTest : BaseTest { [Test] - public void CheckR8MetadataFilesExist () + [TestCase (null, false)] + [TestCase ("disabled", false)] + [TestCase ("private-members", true)] + public void CheckR8MetadataFilesExist (string obfuscationMode, bool optimizationsEnabled) { var proj = new XamarinAndroidApplicationProject { IsRelease = true, }; proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, "r8"); + if (obfuscationMode != null) { + proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidR8ObfuscationMode, obfuscationMode); + } // Projects must set $(AndroidCreateProguardMappingFile) to true to opt in proj.SetProperty (proj.ReleaseProperties, "AndroidCreateProguardMappingFile", true); proj.SetProperty ("AndroidPackageFormat", "aab"); @@ -35,7 +42,14 @@ public void CheckR8MetadataFilesExist () FileAssert.Exists (aab, $"'{aab}' should have been generated."); using (var zip = ZipHelper.OpenZip (aab)) { Assert.IsTrue (zip.Any (e => e.FullName == "BUNDLE-METADATA/com.android.tools.build.obfuscation/proguard.map"), $"AAB file `{aab}` should contain the ProGuard mapping."); - Assert.IsTrue (zip.Any (e => e.FullName == "BUNDLE-METADATA/com.android.tools/r8.json"), $"AAB file `{aab}` should contain the R8 build metadata."); + var metadata = zip.SingleOrDefault (e => e.FullName == "BUNDLE-METADATA/com.android.tools/r8.json"); + Assert.IsNotNull (metadata, $"AAB file `{aab}` should contain the R8 build metadata."); + using var stream = new MemoryStream (); + metadata.Extract (stream); + stream.Position = 0; + using var document = JsonDocument.Parse (stream); + var options = document.RootElement.GetProperty ("options"); + Assert.AreEqual (optimizationsEnabled, options.GetProperty ("isOptimizationsEnabled").GetBoolean ()); } Assert.IsTrue (b.Build (proj), "second build should have succeeded."); @@ -45,6 +59,43 @@ public void CheckR8MetadataFilesExist () } } + [Test] + public void InvalidR8ObfuscationModeFailsBuild () + { + var proj = new XamarinAndroidApplicationProject { + IsRelease = true, + }; + proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, "r8"); + proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidR8ObfuscationMode, "private-member"); + + using var builder = CreateApkBuilder (); + builder.ThrowOnBuildFailure = false; + Assert.IsFalse (builder.Build (proj), "Build should reject an invalid AndroidR8ObfuscationMode."); + StringAssertEx.Contains ("error XA1050", builder.LastBuildOutput); + StringAssertEx.Contains ("'private-member'", builder.LastBuildOutput); + } + + [TestCase ("", true)] + [TestCase ("r8", false)] + public void InvalidR8ObfuscationModeIsValidatedOnlyForR8 (string linkTool, bool expectedResult) + { + var proj = new XamarinAndroidApplicationProject { + IsRelease = true, + }; + proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, linkTool); + proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidR8ObfuscationMode, "private-member"); + + using var builder = CreateApkBuilder (); + builder.Target = "_ValidateAndroidR8ObfuscationMode"; + builder.ThrowOnBuildFailure = false; + builder.AutomaticNuGetRestore = false; + Assert.AreEqual (expectedResult, builder.Build (proj), "Validation result should depend on whether R8 is enabled."); + if (!expectedResult) { + StringAssertEx.Contains ("error XA1050", builder.LastBuildOutput); + StringAssertEx.Contains ("'private-member'", builder.LastBuildOutput); + } + } + [Test] public void CheckR8InfoMessagesToNotBreakTheBuild () { diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Tasks/R8Tests.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Tasks/R8Tests.cs new file mode 100644 index 00000000000..6e9ff979952 --- /dev/null +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Tasks/R8Tests.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using NUnit.Framework; +using Xamarin.Android.Tasks; + +namespace Xamarin.Android.Build.Tests +{ + [TestFixture] + public class R8Tests + { + [Test] + public void WritePrivateMemberObfuscationRules () + { + using var writer = new StringWriter (); + R8.WriteObfuscationRules (writer, "private-members"); + + var expected = """ + -keep,allowshrinking,allowoptimization class ** + -keepclassmembers,allowshrinking,allowoptimization class ** { + public protected *; + } + -keep,allowoptimization interface ** { + public protected *; + } + -keep,allowshrinking class * implements ** + + """; + Assert.AreEqual (expected.ReplaceLineEndings (Environment.NewLine), writer.ToString ()); + } + + [Test] + public void WriteDisabledObfuscationRules () + { + using var writer = new StringWriter (); + R8.WriteObfuscationRules (writer, "disabled"); + + Assert.AreEqual ("-dontobfuscate" + Environment.NewLine, writer.ToString ()); + } + + [Test] + public void WriteInvalidObfuscationModeThrows () + { + using var writer = new StringWriter (); + + Assert.Throws (() => R8.WriteObfuscationRules (writer, "private-member")); + } + } +} diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Android/KnownProperties.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Android/KnownProperties.cs index d6f5a732054..2175b2b6f05 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Android/KnownProperties.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Android/KnownProperties.cs @@ -25,6 +25,7 @@ public static class KnownProperties public const string AndroidEnableDesugar = "AndroidEnableDesugar"; public const string AndroidManifestMerger = "AndroidManifestMerger"; public const string AndroidLinkTool = "AndroidLinkTool"; + public const string AndroidR8ObfuscationMode = "AndroidR8ObfuscationMode"; public const string UseJackAndJill = "UseJackAndJill"; public const string AotAssemblies = "AotAssemblies"; public const string AndroidEnableProfiledAot = "AndroidEnableProfiledAot"; diff --git a/src/Xamarin.Android.Build.Tasks/Xamarin.Android.Common.targets b/src/Xamarin.Android.Build.Tasks/Xamarin.Android.Common.targets index eafdb06f3aa..81294786733 100644 --- a/src/Xamarin.Android.Build.Tasks/Xamarin.Android.Common.targets +++ b/src/Xamarin.Android.Build.Tasks/Xamarin.Android.Common.targets @@ -252,6 +252,7 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved. False True True + disabled True @@ -968,6 +969,7 @@ because xbuild doesn't support framework reference assemblies. <_PropertyCacheItems Include="AndroidEnableProfiledAot=$(AndroidEnableProfiledAot)" /> <_PropertyCacheItems Include="AndroidDexTool=$(AndroidDexTool)" /> <_PropertyCacheItems Include="AndroidLinkTool=$(AndroidLinkTool)" /> + <_PropertyCacheItems Include="AndroidR8ObfuscationMode=$(AndroidR8ObfuscationMode)" /> <_PropertyCacheItems Include="AndroidLinkResources=$(AndroidLinkResources)" /> <_PropertyCacheItems Include="AndroidPackageFormat=$(AndroidPackageFormat)" /> <_PropertyCacheItems Include="EmbedAssembliesIntoApk=$(EmbedAssembliesIntoApk)" /> @@ -2115,7 +2117,8 @@ because xbuild doesn't support framework reference assemblies. <_ProguardConfiguration Include="$(ProguardConfigFiles)" /> - <_ProguardConfiguration Include="$(MSBuildThisFileDirectory)proguard-android.txt" /> + <_ProguardConfiguration Include="$(MSBuildThisFileDirectory)proguard-android.txt" Condition=" '$(AndroidR8ObfuscationMode)' == 'disabled' " /> + <_ProguardConfiguration Include="$(MSBuildThisFileDirectory)proguard-android-optimize.txt" Condition=" '$(AndroidR8ObfuscationMode)' == 'private-members' " /> <_ProguardConfiguration Include="$(IntermediateOutputPath)proguard\proguard_xamarin.cfg" Condition=" '$(AndroidLinkTool)' != '' " /> <_ProguardConfiguration Include="$(_ProguardProjectConfiguration)" Condition=" '$(AndroidLinkTool)' != '' " /> <_ProguardConfiguration Include="$(IntermediateOutputPath)proguard\proguard_project_primary.cfg" Condition=" '$(AndroidLinkTool)' != '' " /> @@ -3080,6 +3083,15 @@ because xbuild doesn't support framework reference assemblies. + + + + diff --git a/src/Xamarin.Android.Build.Tasks/Xamarin.Android.D8.targets b/src/Xamarin.Android.Build.Tasks/Xamarin.Android.D8.targets index 5f197b76ffa..7897212fe5e 100644 --- a/src/Xamarin.Android.Build.Tasks/Xamarin.Android.D8.targets +++ b/src/Xamarin.Android.Build.Tasks/Xamarin.Android.D8.targets @@ -75,6 +75,7 @@ Copyright (C) 2018 Xamarin. All rights reserved. ProguardMappingFileOutput="$(AndroidProguardMappingFile)" BuildMetadataFileOutput="$(_AndroidR8BuildMetadataFile)" ProguardConfigurationFiles="@(_ProguardConfiguration)" + ObfuscationMode="$(AndroidR8ObfuscationMode)" EnableShrinking="$(_R8EnableShrinking)" EnableMultiDex="$(AndroidEnableMultiDex)" MultiDexMainDexListFile="$(_AndroidMainDexListFile)" diff --git a/src/proguard-android/proguard-android.targets b/src/proguard-android/proguard-android.targets index c2664819ae0..40a28ec9c68 100644 --- a/src/proguard-android/proguard-android.targets +++ b/src/proguard-android/proguard-android.targets @@ -1,29 +1,35 @@ <_Destination>$(MicrosoftAndroidSdkOutDir)proguard-android.txt + <_OptimizeDestination>$(MicrosoftAndroidSdkOutDir)proguard-android-optimize.txt + Outputs="$(_Destination);$(_OptimizeDestination)"> - <_ProguardRules Include="$(MSBuildThisFileDirectory)build\intermediates\default_proguard_files\global\proguard-android.txt-*" /> + <_ProguardRules Include="$(MSBuildThisFileDirectory)build\intermediates\default_proguard_files\global\proguard-android.txt-*"> + $(_Destination) + + <_ProguardRules Include="$(MSBuildThisFileDirectory)build\intermediates\default_proguard_files\global\proguard-android-optimize.txt-*"> + $(_OptimizeDestination) + - + - + """ + package example; + + public class ObfuscationProbe { + public static int publicEntry (int value) { + return protectedEntry (value) + packagePrivateEntry (value) + privateEntry (value); + } + + protected static int protectedEntry (int value) { + return value + 1; + } + + static int packagePrivateEntry (int value) { + return value + 2; + } + + private static int privateEntry (int value) { + return value + 3; + } + } + """, + Metadata = { + { "Bind", "False" }, + }, + }, + new BuildItem (AndroidBuildActions.ProguardConfiguration, "proguard.cfg") { + TextContent = () => """ + -keep,allowobfuscation class example.ObfuscationProbe { + ; + ; + } + """, + }, + }, + }; + proj.SetRuntime (runtime); + proj.SetRuntimeIdentifiers (new [] { DeviceAbi }); + proj.SetProperty ("AndroidLinkTool", "r8"); + proj.SetProperty ("AndroidR8ObfuscationMode", "private-members"); + proj.SetProperty ("AndroidCreateProguardMappingFile", "true"); + proj.SetDefaultTargetDevice (); + proj.MainActivity = proj.DefaultMainActivity.Replace ( + "//${AFTER_ONCREATE}", + """ + using var probeClass = Java.Lang.Class.ForName ( + "example.ObfuscationProbe", + initialize: true, + Android.App.Application.Context.ClassLoader); + IntPtr publicEntry = Android.Runtime.JNIEnv.GetStaticMethodID (probeClass.Handle, "publicEntry", "(I)I"); + int result = Android.Runtime.JNIEnv.CallStaticIntMethod (probeClass.Handle, publicEntry, new Android.Runtime.JValue (5)); + Console.WriteLine ($"# R8_SELECTIVE_OBFUSCATION_RESULT {result}"); + if (result != 21) { + throw new InvalidOperationException ($"Unexpected R8 obfuscation probe result: {result}"); + } + """); + + using var builder = CreateApkBuilder (); + bool installed = false; + try { + installed = builder.Install (proj); + Assert.IsTrue (installed, "Project should have installed."); + + var projectDirectory = Path.Combine (Root, builder.ProjectDirectory); + var mappingFiles = Directory.GetFiles ( + Path.Combine (projectDirectory, proj.OutputPath), + "mapping.txt", + SearchOption.AllDirectories); + Assert.AreEqual (1, mappingFiles.Length, "The R8 build should produce one mapping file."); + string mapping = File.ReadAllText (mappingFiles [0]); + + StringAssert.Contains ($"{JavaMappingClassName} -> {JavaMappingClassName}:", mapping, + "Java class names should remain unchanged."); + string mappedPackagePrivateMethod = GetRenamedMethod (mapping, "packagePrivateEntry"); + string mappedPrivateMethod = GetRenamedMethod (mapping, "privateEntry"); + + var dexFiles = Directory.GetFiles ( + Path.Combine (projectDirectory, proj.IntermediateOutputPath), + "classes*.dex", + SearchOption.AllDirectories); + Assert.IsNotEmpty (dexFiles, "R8 should produce at least one DEX file."); + AssertDexContainsMethod (dexFiles, "publicEntry"); + AssertDexContainsMethod (dexFiles, "protectedEntry"); + AssertDexContainsMethod (dexFiles, mappedPackagePrivateMethod); + AssertDexContainsMethod (dexFiles, mappedPrivateMethod); + AssertDexDoesNotContainMethod (dexFiles, "packagePrivateEntry"); + AssertDexDoesNotContainMethod (dexFiles, "privateEntry"); + + ClearAdbLogcat (); + RunProjectAndAssert (proj, builder, doNotCleanupOnUpdate: true); + Assert.IsTrue (WaitForActivityToStart (proj.PackageName, "MainActivity", + Path.Combine (projectDirectory, "logcat.log"), 30), "Activity should have started."); + Assert.IsTrue (MonitorAdbLogcat (line => line.Contains (SuccessMarker), + Path.Combine (projectDirectory, "startup-logcat.log"), 45), $"Output did not contain {SuccessMarker}."); + } finally { + if (installed) { + try { + builder.ThrowOnBuildFailure = false; + if (!builder.Uninstall (proj)) { + TestContext.Error.WriteLine ($"Failed to uninstall '{proj.PackageName}' during test cleanup."); + } + } catch (Exception ex) { + TestContext.Error.WriteLine ($"Failed to uninstall '{proj.PackageName}' during test cleanup: {ex}"); + } + } + } + } + + static string GetRenamedMethod (string mapping, string methodName) + { + var match = Regex.Match ( + mapping, + $@"(?m)^\s*(?:\d+:\d+:)?int {Regex.Escape (methodName)}\(int\)(?::\d+:\d+)?\s+->\s+(?\S+)\s*$"); + Assert.IsTrue (match.Success, $"R8 mapping should contain {methodName}(int)."); + string mappedMethodName = match.Groups ["name"].Value; + Assert.AreNotEqual (methodName, mappedMethodName, $"{methodName}(int) should be renamed."); + return mappedMethodName; + } + + void AssertDexContainsMethod (string [] dexFiles, string methodName) + { + Assert.IsTrue (dexFiles.Any (dex => DexUtils.ContainsClassWithMethod ( + $"L{JavaClassName};", methodName, "(I)I", dex, AndroidSdkPath)), + $"DEX should contain {JavaClassName}.{methodName}(int)."); + } + + void AssertDexDoesNotContainMethod (string [] dexFiles, string methodName) + { + Assert.IsFalse (dexFiles.Any (dex => DexUtils.ContainsClassWithMethod ( + $"L{JavaClassName};", methodName, "(I)I", dex, AndroidSdkPath)), + $"DEX should not contain {JavaClassName}.{methodName}(int)."); + } + } +}