From 72fba46e3225f25886e9e254afa9226a2fa5b5a8 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 30 Nov 2026 15:29:19 -0600 Subject: [PATCH 1/2] [r8] Scope the CoreCLR typemap interface rule to bound interfaces The CoreCLR typemap path kept every class that implements anything: -keep,allowshrinking class * implements ** R8 matches `implements` also against superclasses, so this rule restricted almost every live class (MAUI: 5,269 items, 4,134 of 4,910 classes) from optimization. Managed interface proxy selection only needs the interface edges of classes that implement a bound Java interface. On CoreCLR, GenerateTypeMapProguardConfiguration now writes for each retained typemap key: -if interface K -keep,allowshrinking,allowobfuscation class * implements K * `-if interface` applies the rule only when K is an interface, so class keys do not pin all their subclasses. * R8 matches `implements` transitively (super-interfaces and superclasses), so implementers of an unbound interface that extends K still match. * R8 never prunes library interfaces (they are always live), so these rules have effect only for program interfaces (AndroidX, Kotlin, ...). * `allowobfuscation`: proxy selection compares interface names, not the implementing class names. This has no effect today because the typemap path uses -dontobfuscate. NativeAOT output is unchanged. `dotnet new maui` (net12, Release .aab, Pixel 7 verified): obf/opt/shr 0.15/51.52/62.24 -> 0.02/57.06/58.02, DEX 3,603,728 -> 3,277,708 bytes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Documentation/guides/D8andR8.md | 23 +++++++++++++++++-- .../GenerateTypeMapProguardConfiguration.cs | 9 ++++++++ .../TypeMapProguardTargetsTests.cs | 7 +++++- ...osoft.Android.Sdk.TypeMap.Proguard.targets | 3 ++- .../Resources/proguard_typemap_coreclr.cfg | 4 ++-- .../Tasks/R8Tests.cs | 2 +- .../TrimmableTypeMapBuildTests.cs | 22 ++++++++++++++---- 7 files changed, 58 insertions(+), 12 deletions(-) diff --git a/Documentation/guides/D8andR8.md b/Documentation/guides/D8andR8.md index 1f29a479d27..a7facaf37c7 100644 --- a/Documentation/guides/D8andR8.md +++ b/Documentation/guides/D8andR8.md @@ -51,6 +51,26 @@ union of keys files and writes deterministic type-root rules to Each retained key emits both alternatives because the key format does not encode whether the Java type is a class or interface. The root generator never emits member rules or global R8 options. + +On CoreCLR, the root generator also writes these rules for each key: + +```text +-if interface example.Outer$Inner +-keep,allowshrinking,allowobfuscation class * implements example.Outer$Inner +``` + +Managed interface proxy selection calls `Class.getInterfaces ()` on the Java +class and on its superclasses and super-interfaces. R8 cannot see this use. +These rules stop R8 from optimizing away the interface edges of classes that +implement a bound interface. R8 matches `implements` transitively, so a class +that implements an unbound interface which extends a bound interface also +matches. R8 also matches `implements` against superclasses, so the `-if +interface` condition applies the rule only when the key is an interface. +R8 does not remove library interfaces, such as `android.*` interfaces, from +the classes that implement them, so these rules have effect only for +interfaces in the application's Java code (for example AndroidX or Kotlin). +The rules allow obfuscation because proxy selection compares interface names, +not the names of the implementing classes. CoreCLR uses a separate `GenerateTypeMapMemberProguardConfiguration` task to write `proguard/proguard_typemap_members.cfg` from the same retained keys: @@ -65,8 +85,7 @@ This preserves JNI-facing methods, constructors, and fields without also preserving every member of Java-only dependencies. R8's member matching includes inherited accessible methods and superclass fields. The separate `proguard_typemap_coreclr.cfg` configuration preserves runtime bootstrap -classes and their members, reflection-visible interface implementation -relationships used for managed proxy selection, plus framework-driven view +classes and their members, plus framework-driven view members. Dynamic JNI or reflection access to types or members not represented by retained managed bindings still needs application/library ProGuard rules. diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs index 62ecb544e6e..fdb541df15b 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs @@ -19,6 +19,8 @@ public class GenerateTypeMapProguardConfiguration : AndroidTask [Required] public string OutputFile { get; set; } = ""; + public bool KeepInterfaceImplementations { get; set; } + public override bool RunTask () { var classes = new SortedSet (StringComparer.Ordinal); @@ -76,6 +78,13 @@ protected virtual void WriteClassRule (TextWriter writer, string name) { writer.WriteLine ($"-keep class {name}"); writer.WriteLine ($"-keep interface {name}"); + if (KeepInterfaceImplementations) { + // Managed interface proxy selection observes Class.getInterfaces(), which R8 cannot see. + // R8 matches "implements" transitively, but also matches subclasses of a class, + // so apply the rule only when the key is an interface. + writer.WriteLine ($"-if interface {name}"); + writer.WriteLine ($"-keep,allowshrinking,allowobfuscation class * implements {name}"); + } } internal static bool IsClassName (string name) diff --git a/src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs b/src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs index d7d276c4685..6954c856a36 100644 --- a/src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs +++ b/src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TypeMapProguardTargetsTests.cs @@ -241,7 +241,7 @@ string EmitMap (string name, params string [] keys) string [] arguments = obsoleteImplementation == null ? [] : [$"-p:AndroidTypeMapImplementation={obsoleteImplementation}"]; Build (project, arguments); var rules = Path.Combine (directory, "obj", "proguard", "proguard_project_references.cfg"); - Assert.AreEqual (TypeRules ("test.Alias", "test.Live", "test.Second"), File.ReadAllText (rules)); + Assert.AreEqual (CoreClrTypeRules ("test.Alias", "test.Live", "test.Second"), File.ReadAllText (rules)); File.Delete (second); Assert.Contains ("XA4327", Build (project, false, arguments)); } @@ -691,6 +691,11 @@ public void InactivePathsNeedNoTypemapInputsOrModernTasks ( static string TypeRules (params string [] names) => string.Concat (names.Select (name => $"-keep class {name}\n-keep interface {name}\n")); + static string CoreClrTypeRules (params string [] names) => + string.Concat (names.Select (name => + $"-keep class {name}\n-keep interface {name}\n" + + $"-if interface {name}\n-keep,allowshrinking,allowobfuscation class * implements {name}\n")); + static string MemberRules (params string [] names) => string.Concat (names.Select (name => $"-keepclassmembers class {name} {{ *; }}\n-keepclassmembers interface {name} {{ *; }}\n")); diff --git a/src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Proguard.targets b/src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Proguard.targets index ade0d68ce99..bc49a3aeff0 100644 --- a/src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Proguard.targets +++ b/src/Xamarin.Android.Build.Tasks/Microsoft.Android.Sdk/targets/Microsoft.Android.Sdk.TypeMap.Proguard.targets @@ -152,7 +152,8 @@ Outputs="$(_ProguardProjectConfiguration)"> + OutputFile="$(_ProguardProjectConfiguration)" + KeepInterfaceImplementations="$(_AndroidUseScopedTypeMapMembers)" /> diff --git a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg index aeaafda0687..4bf7b9bd64b 100644 --- a/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg +++ b/src/Xamarin.Android.Build.Tasks/Resources/proguard_typemap_coreclr.cfg @@ -12,8 +12,8 @@ -keep class net.dot.android.ApplicationRegistration { *; } -keep class net.dot.android.crypto.** { *; (...); } -# Managed interface proxy selection observes Class.getInterfaces(). --keep,allowshrinking class * implements ** +# Managed interface proxy selection observes Class.getInterfaces(). The rules that +# keep implementers of bound interfaces are in proguard_project_references.cfg. # Framework-driven view inflation and property setters. -keepclassmembers class * extends android.view.View { 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 index 4af68dc605a..e18f3a49f5c 100644 --- 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 @@ -183,7 +183,7 @@ public void RetainedTypeMapRulesDoNotRootAllAcwsOrObfuscatePrivateMembers (bool Assert.DoesNotContain ("-keepclassmembers class * {", common); Assert.Contains ("-keep class mono.android.Runtime { *; }", common); Assert.Contains ("-keep interface mono.android.IGCUserPeer { *; }", common); - Assert.Contains ("-keep,allowshrinking class * implements **", common); + Assert.DoesNotContain ("implements", common); } else { Assert.Contains ("-keepclassmembers class * {", common); } diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs index dcdf54e763a..e91c1ff69cf 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs @@ -103,9 +103,19 @@ public void RetainedTypeMapRulesDriveR8 (AndroidRuntime runtime) CollectionAssert.DoesNotContain (keys, dead); var configuration = Path.Combine (intermediate, "proguard", "proguard_project_references.cfg"); CollectionAssert.AreEqual ( - keys.OrderBy (key => key, StringComparer.Ordinal).SelectMany (key => new [] { - "-keep class " + key.Replace ('/', '.'), - "-keep interface " + key.Replace ('/', '.'), + keys.OrderBy (key => key, StringComparer.Ordinal).SelectMany (key => { + var name = key.Replace ('/', '.'); + return runtime == AndroidRuntime.CoreCLR + ? new [] { + "-keep class " + name, + "-keep interface " + name, + "-if interface " + name, + "-keep,allowshrinking,allowobfuscation class * implements " + name, + } + : new [] { + "-keep class " + name, + "-keep interface " + name, + }; }).ToArray (), File.ReadAllLines (configuration)); var common = File.ReadAllText (Path.Combine (intermediate, "proguard", "proguard_xamarin.cfg")); @@ -4273,9 +4283,11 @@ void AssertPostTrimR8InputsExcludeDeadFrameworkImplementor (string dexFile, stri Assert.IsNotEmpty (rules, "Retained typemap keys should provide type roots."); Assert.IsTrue (rules.All (line => (line.StartsWith ("-keep class ", StringComparison.Ordinal) || - line.StartsWith ("-keep interface ", StringComparison.Ordinal)) && + line.StartsWith ("-keep interface ", StringComparison.Ordinal) || + line.StartsWith ("-if interface ", StringComparison.Ordinal) || + line.StartsWith ("-keep,allowshrinking,allowobfuscation class * implements ", StringComparison.Ordinal)) && !line.Contains ('{')), - "Typemap ProGuard rules must contain only class and interface roots, not member rules."); + "Typemap ProGuard rules must contain only class, interface, and interface-implementation roots, not member rules."); Assert.IsFalse (rules.Any (line => line.Contains (deadJavaDotName, StringComparison.Ordinal)), "Retained typemap type roots should exclude trimmed framework implementors."); var common = File.ReadAllText (Path.Combine (proguardDirectory, "proguard_xamarin.cfg")); From eb651debc77750178726757f29cd5f78706ad64b Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 30 Nov 2026 15:39:56 -0600 Subject: [PATCH 2/2] Simplify docs, comment, and test assertion Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Documentation/guides/D8andR8.md | 19 +++++++------------ .../GenerateTypeMapProguardConfiguration.cs | 3 +-- .../TrimmableTypeMapBuildTests.cs | 14 +++----------- 3 files changed, 11 insertions(+), 25 deletions(-) diff --git a/Documentation/guides/D8andR8.md b/Documentation/guides/D8andR8.md index a7facaf37c7..990b67c8c56 100644 --- a/Documentation/guides/D8andR8.md +++ b/Documentation/guides/D8andR8.md @@ -59,18 +59,13 @@ On CoreCLR, the root generator also writes these rules for each key: -keep,allowshrinking,allowobfuscation class * implements example.Outer$Inner ``` -Managed interface proxy selection calls `Class.getInterfaces ()` on the Java -class and on its superclasses and super-interfaces. R8 cannot see this use. -These rules stop R8 from optimizing away the interface edges of classes that -implement a bound interface. R8 matches `implements` transitively, so a class -that implements an unbound interface which extends a bound interface also -matches. R8 also matches `implements` against superclasses, so the `-if -interface` condition applies the rule only when the key is an interface. -R8 does not remove library interfaces, such as `android.*` interfaces, from -the classes that implement them, so these rules have effect only for -interfaces in the application's Java code (for example AndroidX or Kotlin). -The rules allow obfuscation because proxy selection compares interface names, -not the names of the implementing classes. +Managed interface proxy selection calls `Class.getInterfaces ()`, which R8 +cannot see, so implementers of bound interfaces keep their interface edges. +R8 also matches `implements` against superclasses; `-if interface` limits the +rule to keys that are interfaces. The rule matches indirect implementers too. +It only has an effect on interfaces in the app's Java code (AndroidX, Kotlin, +and so on), because R8 never removes library interfaces such as `android.*`. +Proxy selection compares interface names, so implementers can be renamed. CoreCLR uses a separate `GenerateTypeMapMemberProguardConfiguration` task to write `proguard/proguard_typemap_members.cfg` from the same retained keys: diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs index fdb541df15b..e57346ee83a 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs @@ -80,8 +80,7 @@ protected virtual void WriteClassRule (TextWriter writer, string name) writer.WriteLine ($"-keep interface {name}"); if (KeepInterfaceImplementations) { // Managed interface proxy selection observes Class.getInterfaces(), which R8 cannot see. - // R8 matches "implements" transitively, but also matches subclasses of a class, - // so apply the rule only when the key is an interface. + // R8 "implements" also matches subclasses, so limit the rule to interface keys. writer.WriteLine ($"-if interface {name}"); writer.WriteLine ($"-keep,allowshrinking,allowobfuscation class * implements {name}"); } diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs index e91c1ff69cf..35aa6a69e03 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/TrimmableTypeMapBuildTests.cs @@ -105,17 +105,9 @@ public void RetainedTypeMapRulesDriveR8 (AndroidRuntime runtime) CollectionAssert.AreEqual ( keys.OrderBy (key => key, StringComparer.Ordinal).SelectMany (key => { var name = key.Replace ('/', '.'); - return runtime == AndroidRuntime.CoreCLR - ? new [] { - "-keep class " + name, - "-keep interface " + name, - "-if interface " + name, - "-keep,allowshrinking,allowobfuscation class * implements " + name, - } - : new [] { - "-keep class " + name, - "-keep interface " + name, - }; + string [] rules = ["-keep class " + name, "-keep interface " + name]; + return runtime != AndroidRuntime.CoreCLR ? rules : + [.. rules, "-if interface " + name, "-keep,allowshrinking,allowobfuscation class * implements " + name]; }).ToArray (), File.ReadAllLines (configuration)); var common = File.ReadAllText (Path.Combine (intermediate, "proguard", "proguard_xamarin.cfg"));