TExcelTAD
Home › Mobile Build Pipelines: Gradle/AGP, Xcode, SwiftPM & Fastlane › Keep Rules, Mapping Files & Retrace

Keep Rules, Mapping Files & Retrace

R8 only sees code that is referenced. Anything reached another way (by reflection, from native code, from a class name in a string or an XML file, by a serialization library) looks dead and gets removed or renamed. The app builds fine and crashes on the user's phone. Keep rules tell R8 about those hidden entry points.

The anatomy of a rule

proguard
-keep class com.example.hello.ShoutPlugin { <init>(); }
#  ^      ^                                  ^
#  |      class specification               members to keep (here: the no-arg constructor)
#  keep option
Option Keeps from removal Keeps from renaming
-keep the class and the listed members yes
-keepclassmembers listed members, if the class survives anyway yes
-keepclasseswithmembers classes that have all listed members yes
-keepnames (= ,allowshrinking) nothing (may be removed if unused) yes
-keepattributes Signature,*Annotation* generic signatures / annotations (attributes)
-keepattributes SourceFile,LineNumberTable file names and line numbers in stack traces (attributes)

Write them as narrowly as possible: -keep class com.example.** { *; } keeps your whole app un-shrunk and un-obfuscated, which defeats the point.

A reflection bug, then the fix

MainActivity loads a plugin by class name, the way plugin systems, dependency injection containers and serialization libraries do. Nothing references ShoutPlugin directly:

bash · try it yourself
mkdir -p hello/app/src/main/java/com/example/hello && cd hello
cat > settings.gradle.kts <<'KTS'
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositories { google(); mavenCentral() } }
rootProject.name = "hello"
include(":app")
KTS
echo 'plugins { id("com.android.application") version "9.4.1" apply false }' > build.gradle.kts
cat > app/src/main/AndroidManifest.xml <<'XML'
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:label="Hello">
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
XML
cat > app/src/main/java/com/example/hello/Plugin.java <<'JAVA'
package com.example.hello;

public interface Plugin { String name(); }
JAVA
cat > app/src/main/java/com/example/hello/ShoutPlugin.java <<'JAVA'
package com.example.hello;

public class ShoutPlugin implements Plugin {
    public String name() { return "SHOUT"; }
}
JAVA
cat > app/src/main/java/com/example/hello/MainActivity.java <<'JAVA'
package com.example.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
    static Plugin load(String className) throws Exception {
        return (Plugin) Class.forName(className).getDeclaredConstructor().newInstance();
    }

    @Override protected void onCreate(Bundle state) {
        super.onCreate(state);
        String label;
        try { label = load("com.example.hello.ShoutPlugin").name(); }
        catch (Exception e) { label = "no plugin: " + e; }
        TextView view = new TextView(this);
        view.setText(label);
        setContentView(view);
    }
}
JAVA
cat > app/build.gradle.kts <<'KTS'
plugins { id("com.android.application") }
android {
    namespace = "com.example.hello"
    compileSdk = 36
    defaultConfig { applicationId = "com.example.hello"; minSdk = 24; targetSdk = 36; versionCode = 1; versionName = "1.0" }
    buildTypes {
        release {
            isMinifyEnabled = true
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
        }
    }
}
KTS
touch app/proguard-rules.pro
gradle wrapper > /dev/null
./gradlew -q assembleRelease
echo "=== without a keep rule"
grep '^com.example' app/build/outputs/mapping/release/mapping.txt
echo "removed: $(grep -E '^com.example.hello.[A-Za-z]+
  

 app/build/outputs/mapping/release/usage.txt | sort | tr '\n' ' ')"
cat > app/proguard-rules.pro <<'PRO'
# Loaded by name in MainActivity.load()
-keep class com.example.hello.ShoutPlugin { <init>(); }
PRO
./gradlew -q assembleRelease
echo "=== with the keep rule"
grep '^com.example' app/build/outputs/mapping/release/mapping.txt
echo "--- seeds.txt (what keep rules matched)"
sort app/build/outputs/mapping/release/seeds.txt
=== without a keep rule
com.example.hello.MainActivity -> com.example.hello.MainActivity:
removed: com.example.hello.Plugin com.example.hello.R com.example.hello.ShoutPlugin
=== with the keep rule
com.example.hello.MainActivity -> com.example.hello.MainActivity:
com.example.hello.ShoutPlugin -> com.example.hello.ShoutPlugin:
--- seeds.txt (what keep rules matched)
com.example.hello.MainActivity
com.example.hello.MainActivity: MainActivity()
com.example.hello.ShoutPlugin
com.example.hello.ShoutPlugin: ShoutPlugin()

Without the rule, ShoutPlugin was removed as dead code, and the release build would show no plugin: java.lang.ClassNotFoundException while the debug build works perfectly. That asymmetry is why R8 problems slip through testing: always test the minified build. With the rule, the class survives under its own name. Note that the Plugin interface is still gone: full-mode R8 noticed only one implementation exists and merged the interface away, which is fine because name() is still called on ShoutPlugin.

Where rules come from

configuration.txt shows every rule R8 applied, in sections named after their source:

bash
grep '^# The proguard configuration file for the following section is' app/build/outputs/mapping/release/configuration.txt
Source Example
AGP's default file proguard-android-optimize.txt, extracted into build/intermediates/default_proguard_files/
your files proguard-rules.pro listed in proguardFiles(...)
AAPT2-generated one -keep class … { <init>(); } per activity, service, receiver, provider and custom view in layouts
libraries an AAR's proguard.txt or a JAR's META-INF/proguard/*.pro (consumer rules)

If you publish a library, ship its rules as consumer rules (consumerProguardFiles("consumer-rules.pro") in a library module), so apps that use it don't have to discover them by crashing. AndroidX's @Keep annotation does the same job for single classes, with a rule shipped in the annotation library.

Reading obfuscated crashes: retrace

A production stack trace from a minified build names obfuscated classes and synthetic line numbers. retrace (in the SDK's command-line tools; R8 also ships it) maps it back using mapping.txt from the same build:

bash · try it yourself
mkdir -p hello/app/src/main/java/com/example/hello && cd hello
cat > settings.gradle.kts <<'KTS'
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositories { google(); mavenCentral() } }
rootProject.name = "hello"
include(":app")
KTS
echo 'plugins { id("com.android.application") version "9.4.1" apply false }' > build.gradle.kts
cat > app/src/main/AndroidManifest.xml <<'XML'
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:label="Hello">
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
XML
cat > app/src/main/java/com/example/hello/Scoreboard.java <<'JAVA'
package com.example.hello;

import java.util.ArrayList;
import java.util.List;

public final class Scoreboard {
    private final List<Integer> scores = new ArrayList<>();
    public void add(int s) {
        if (s <= 0) throw new IllegalArgumentException("bad score " + s);
        scores.add(s);
    }
    public String describe() { return scores.size() + " scores"; }
}
JAVA
cat > app/src/main/java/com/example/hello/MainActivity.java <<'JAVA'
package com.example.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
    @Override protected void onCreate(Bundle state) {
        super.onCreate(state);
        Scoreboard a = new Scoreboard();
        a.add(getIntent().getIntExtra("score", 1));
        Scoreboard b = new Scoreboard();
        b.add(getTaskId());
        TextView view = new TextView(this);
        view.setText(a.describe() + b.describe());
        setContentView(view);
    }
}
JAVA
cat > app/build.gradle.kts <<'KTS'
plugins { id("com.android.application") }
android {
    namespace = "com.example.hello"
    compileSdk = 36
    defaultConfig { applicationId = "com.example.hello"; minSdk = 24; targetSdk = 36; versionCode = 1; versionName = "1.0" }
    buildTypes { release { isMinifyEnabled = true; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) } }
}
KTS
gradle wrapper > /dev/null
./gradlew -q assembleRelease
grep -E '^com.example|^    4:5:' app/build/outputs/mapping/release/mapping.txt
# What a crash reporter receives from a user's phone:
cat > crash.txt <<'TXT'
java.lang.IllegalArgumentException: bad score 0
	at com.example.hello.MainActivity.onCreate(SourceFile:4)
TXT
retrace app/build/outputs/mapping/release/mapping.txt crash.txt
com.example.hello.MainActivity -> com.example.hello.MainActivity:
    4:5:void com.example.hello.Scoreboard.add(int):9:10 -> onCreate
    4:5:void onCreate(android.os.Bundle):11 -> onCreate
com.example.hello.Scoreboard -> R8$REMOVED$CLASS$0:
java.lang.IllegalArgumentException: bad score 0
	at com.example.hello.Scoreboard.add(Scoreboard.java:9)
	at com.example.hello.MainActivity.onCreate(MainActivity.java:11)

R8 went further than renaming here: Scoreboard was inlined completely into onCreate (the mapping says R8$REMOVED$CLASS$0), so the phone reports a single frame at line 4 of an optimized method. The mapping's line ranges record which original lines that line came from, and retrace expands it back into two frames: Scoreboard.add at line 9, called from onCreate at line 11. Back to real class names, methods, files and line numbers. That's why release pipelines upload mapping.txt to wherever crashes are read: the Play Console does it automatically when the mapping file is inside the App Bundle (AGP puts it in BUNDLE-METADATA), Firebase Crashlytics has a Gradle plugin task for it, and Sentry and others have CLI uploaders. Also archive it with the build artifacts, keyed by versionCode.

Test yourself

A class is only instantiated with Class.forName("…").newInstance(). What happens in a minified release build without a keep rule?

  1. R8 detects the reflection and keeps it
  2. R8 removes or renames it, and the call fails at runtime with ClassNotFoundException
  3. The build fails
  4. Only the debug build is affected

You publish an Android library that uses reflection. Where should its keep rules go?

  1. In the README for app developers
  2. Consumer rules (consumerProguardFiles) shipped inside the AAR
  3. In every app's proguard-rules.pro
  4. Nowhere; libraries aren't minified

Why must the mapping file be archived per build?

  1. It contains the signing key
  2. Obfuscated names differ between builds, so only the matching mapping.txt can retrace that build's crashes
  3. Play requires it for installation
  4. It speeds up the next build