Confusing user's manual for Android developers

Source: Internet
Author: User

There is no doubt that obfuscation is one of the most important processes in the packaging process, and that all apps should turn on confusion for no particular reason.

First of all, the confusion here is in fact the optimization process including code compression, code obfuscation, and resource compression. By relying on Proguard, the obfuscation process removes the main project and the unused classes, class members, methods, and properties of the dependent libraries, which helps to circumvent the bottleneck of the 64K method number, and renaming classes, class members, and methods to meaningless short names adds to the difficulty of reverse engineering. and relying on Gradle Android plugin, we will remove unused resources, can effectively reduce the size of the APK installation package.

This article consists of two parts, the first part gives the best practice of confusion, and tries to make it possible for beginners of Zero Foundation to use confusion directly; the second chapter introduces the whole of confusion, the syntax and practice of custom obfuscation rules, the rules for customizing resource retention, and so on.

First, Android confusion best practices

    1. Confusing configuration

In general, the Build.gradle file of the app module will have the following structure by default:

Android {
Buildtypes {
Release {
Minifyenabled false
Proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '
}
}
}
The debug mode should not be turned on because confusion can cause the compilation to grow longer. What we need to do is:

Change the value of minifyenabled under release to true to open confusion;

Add shrinkresources True to turn on resource compression.

The contents of the modified file are as follows:

Android {
Buildtypes {
Release {
minifyenabled true
Shrinkresources true
Proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '
}
}
}

    1. Custom obfuscation Rules

A custom obfuscation rule file for the project is generated by default under App module Proguard-rules.pro, after multiple surveys, a best practice for confusing rules for most projects is as follows:

#指定压缩级别
-optimizationpasses 5

#不跳过非公共的库的类成员
-dontskipnonpubliclibraryclassmembers

#混淆时采用的算法
-optimizations!code/simplification/arithmetic,!field/,!class/merging/

#把混淆类中的方法名也混淆了
-useuniqueclassmembernames

#优化时允许访问并修改有修饰符的类和类的成员
-allowaccessmodification

#将文件来源重命名为 "SourceFile" string
-renamesourcefileattribute sourcefile
#保留行号
-keepattributes sourcefile,linenumbertable

Class member #保持所有实现 the Serializable interface
-keepclassmembers class * Implements Java.io.Serializable {
Static final long serialversionuid;
private static final java.io.objectstreamfield[] Serialpersistentfields;
private void WriteObject (Java.io.ObjectOutputStream);
private void ReadObject (Java.io.ObjectInputStream);
Java.lang.Object Writereplace ();
Java.lang.Object Readresolve ();
}

Registering in #Fragment不需要在AndroidManifest. XML requires additional protection
-keep public class extends Android.support.v4.app.Fragment
-keep public class
extends Android.app.Fragment

Keep test-related code

-dontnote Junit.framework.
-dontnote Junit.runner.

-dontwarn Android.test.
-dontwarn Android.support.test.

-dontwarn org.junit.**
What is really generic, what needs to be added is the above, but in addition, each project needs to add some confusion rules according to its own requirements:

The confusion rules required by the third party libraries. Regular third-party libraries generally write the required obfuscation rules in the access documentation, and use them with the added attention.

Code that dynamically changes at run time, such as reflection. A more typical example would be an entity class that would be converted to JSON with each other. If the project naming convention requires that entity classes be placed under the model package, you can add code like this to keep all entity classes:-keep public class . Model. {*;}

The class that is called in JNI.

Methods of JavaScript invocation in WebView

Layout layouts Use the view constructor, Android:onclick, and so on.

    1. Check for confusing results

The obfuscated package must be checked to avoid the bug introduced by the confusion.

On the one hand, it needs to be checked from the code level. The following files are output in the <module-name>/build/outputs/mapping/release/directory after the obfuscation is packaged using the configuration above:

Dump.txt
Describe the internal structure of all classes in the APK file

Mapping.txt
Provide a comparison table of classes, methods, class members, etc. before and after confusion

Seeds.txt
Lists classes and members that are not confused

Usage.txt
List the code that was removed

Depending on the Seeds.txt file, we can check that the classes and members that are not confused contain all the expected reservations, and then, depending on the usage.txt file, see if there is any code that was mistakenly removed.

On the other hand, it needs to be checked from test. Full-aspect testing of the obfuscated package to check for bugs.

    1. Solve the confusion stack

Confusing classes, method names, etc. are difficult to read, which will add to the difficulty of reverse engineering, but also hinder the tracking of crash on the line. We will find it difficult to locate when we get the stack information of crash, and we need to reverse the confusion.

There is an accompanying anti-solution tool under the <sdk-root>/tools/proguard/path (Window system is proguardgui.bat, MAC or Linux system is proguardgui.sh).

Here, take the Window platform as an example. After you double-click Run Proguardgui.bat, you can see a row of menus on the left. Click Retrace to select the mapping file corresponding to the obfuscation package (the Mapping.txt file will be generated under the <module-name>/build/outputs/mapping/release/path after confusion, Its role is to provide confusion before and after the class, method, class members, such as the comparison table, and then paste the crash stack trace into the input box, click on the bottom right corner of the retrace, confused stack information is displayed.

The above uses the GUI program to operate, another way is to use the path of the retrace tool through the command line to reverse the solution, the command is

retrace.bat|retrace.sh [-verbose] mapping.txt [<stacktrace_file>]
For example:

Retrace.bat-verbose Mapping.txt Obfuscated_trace.txt
Precautions:

1) All classes involved in Androidmanifest.xml have been automatically maintained, so there is no need to intentionally add this confusion rule. (a lot of old confusing files will add, it is not necessary now)

2) Proguard-android.txt already have some default obfuscation rules, there is no need to repeat the Proguard-rules.pro, the file specific rules see Appendix 1:

Ii. the introduction of confusion
"Confusion" in Android can be divided into two parts, the optimization and confusion of Java code, relying on the proguard obfuscation, and the other is resource compression, which will remove the unused resources in the project and dependent libraries (resource compression is strictly not related to confusion, But in general we all put together to talk about).

    1. Code compression

Code obfuscation is a process that includes code compression, optimization, obfuscation, and a series of behaviors. As shown, the obfuscation process will have several functions as follows:

Compression. Remove invalid classes, class members, methods, properties, and so on;

Optimization. Binary code for analysis and optimization methods; As described in Proguard-android-optimize.txt, optimizations can pose some potential risks and are not guaranteed to work correctly on all versions of Dalvik.

Confuse. Replace the class name, attribute name, method name with a short and meaningless name;

Pre-check. Add the pre-check information. This pre-check is on the Java platform, the Android platform does not need this feature, and then can be removed to speed up the confusion.

These four processes are turned on by default.

In the Android project we can choose to close the "optimize" and "pre-check", the corresponding command is-dontoptimize,-dontpreverify (of course, the default Proguard-android.txt file already contains these two confusing commands, No additional developer configuration required).

    1. Resource compression

Resource compression removes unused resources from the project and dependent libraries, which has a good effect on reducing the size of the APK package and is generally recommended. The practice is to set the Shrinkresources property to True in the Build.grade file. It is important to note that resource compression only takes effect when code compression is turned on with minifyenabled true.

Resource compression contains two processes for merge resources and remove resources.

In the merge resources process, a resource with the same name is considered a duplicate resource to be merged. It is important to note that this process is not controlled by the Shrinkresources attribute and cannot be banned, and Gradle will certainly do this because if a resource of the same name exists in a different project, it will result in an error. Gradle looking for duplicate resources around the place:

src/main/res/Path

Different build types (debug, release, etc.)

Different building channels

Third-party libraries that the project relies on

Merge resources in the following order of precedence:

Dependency--Main channel---Build type
For example, if duplicate resources exist in both the main folder and the different channels, Gradle will choose to keep the resources in the channel.

At the same time, if duplicate resources appear at the same level, such as src/main/res/and src/main/res/, Gradle cannot complete the resource merge, then the resource merge error is reported.

The "Remove resources" process is known as the name, and it is important to note that similar code, confusing resource removal, can also define which resources need to be retained, as given below.

Iii. Custom Obfuscation Rules
There is a line of code in the "Confusing Configuration" section above

Proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '
This line of code defines a two-part obfuscation rule: the contents of Proguard-android.txt in the tools/proguard/folder of the SDK and the contents of the Proguard-rules.pro that are placed in the module's root directory by default. The former is the default obfuscation file provided by the SDK (see Appendix 1), which is where developers customize the obfuscation rules.

    1. Common Obfuscation commands:

Optimizationpasses

Dontoptimize

Dontusemixedcaseclassnames

Dontskipnonpubliclibraryclasses

Dontpreverify

Dontwarn

Verbose

Optimizations

Keep

Keepnames

Keepclassmembers

Keepclassmembernames

Keepclasseswithmembers

Keepclasseswithmembernames

In the first part of the Android obfuscation best practices have introduced some of the confusing commands that need to be used, here are no more details, please check the official website. Specifically, there are several commands that are related to keeping the relevant elements out of the confusion rules:

Command function
-keep prevent classes and members from being removed or renamed
-keepnames prevent classes and members from being renamed
-keepclassmembers prevent members from being removed or renamed
-keepnames prevent members from being renamed
-keepclasseswithmembers prevents classes and members that own the member from being removed or renamed
-keepclasseswithmembernames prevents classes and members that have this member from being renamed

    1. Rules that keep elements from being confused

Shaped like:

[Hold command] [Class] {
Members
}
A class represents a class-related qualification, and it eventually navigates to certain classes that meet that qualification. Its contents can be used:

The specific class

Access modifiers (public, protected, private)

Wildcard *, matches any length character, but does not contain the package name delimiter (.)

Wildcard * *, matches any length character, and contains the package name delimiter (.)

Extends, that is, you can specify a class's base class

Implement, matching a class that implements an interface

$, Inner class

A member represents a qualifying condition related to a class member, and it eventually navigates to certain class members that meet that qualification. Its contents can be used:

Match all constructors
Match all domains
Match all methods
Wildcard *, matches any length character, but does not contain the package name delimiter (.)

Wildcard * *, matches any length character, and contains the package name delimiter (.)

Wildcard * * *, match any parameter type

... to match any type parameter of any length. such as void Test (...) can match any void test (string a) or void test (int A, string b).

Access modifiers (public, protected, private)

For example, if you need to keep all of the public classes and their constructors that inherit activity under the Name.huihui.test package, you can write:

-keep public class name.huihui.test.** extends Android.app.Activity {
<init>
}

    1. Common custom Obfuscation rules

Do not confuse a class

-keep public class Name.huihui.example.Test {*;}
Do not confuse all classes of a package

-keep class name.huihui.test.* { ;}
Do not confuse subclasses of a class

-keep public class extends Name.huihui.example.Test { ;}
Do not confuse classes with "model" in all class names and their members

-keep public class . Model. {*;}
Do not confuse an implementation of an interface

-keep class implements Name.huihui.example.TestInterface { ;}
Do not confuse a class's construction method

-keepclassmembers class Name.huihui.example.Test {
public <init> ();
}
Do not confuse a particular method of a class

-keepclassmembers class Name.huihui.example.Test {
public void test (java.lang.String);
}
Iv. Custom Resource Retention rules

    1. Keep.xml

When resource compression is turned on with shrinkresources true, all unused resources are removed by default. If you need to define which resources must be preserved, create an XML file under the res/raw/path, such as Keep.xml.

Some property settings enable you to define the requirements for resource retention, and the configurable properties are:

Tools:keep defines which resources need to be retained (separated by "," between resources)

Tools:discard defines which resources need to be removed (separated by "," between resources)

Tools:shrinkmode turn on Strict mode

Normal resource reference checking can be problematic when the code uses a dynamic string to fetch and use the resource through Resources.getidentifier (). For example, the following code causes all resources that begin with "img_" to be marked as used.

String name = String.Format ("img_%1d", angle + 1);
res = Getresources (). Getidentifier (Name, "Drawable", Getpackagename ());
We can set Tools:shrinkmode to strict to turn on strict mode so that only resources that are actually used are retained.

The above is a custom resource retention rule-related configuration, for example:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources xmlns:tools= "Http://schemas.android.com/tools" br/>tools:keep= "@layout/l_used*_c, @layout/l_used _a, @layout/l_used_b* "
tools:shrinkmode= "Strict"/>

    1. Remove an alternate resource

Some alternative resources, such as multi-language supported Strings.xml, multi-resolution supported Layout.xml, etc., can be removed using resource compression when we do not need to use them and do not want to delete them.

We use the Resconfig property to specify the properties that need to be supported, such as

Android {
Defaultconfig {
...
Resconfigs "en", "fr"
}
}
Other language resources that are not explicitly declared will be removed.

Resources
Shrink Your Code and Resources

Proguard

Android Security * * *, anti-compilation and obfuscation technology fully resolved (next)

Android obfuscation from getting started to mastering

Proguard of Android Code obfuscation

Appendix
Proguard-android.txt File Contents

#包名不混合大小写
-dontusemixedcaseclassnames

#不跳过非公共的库的类
-dontskipnonpubliclibraryclasses

#混淆时记录日志
-verbose

#关闭预校验
-dontpreverify

#不优化输入的类文件
-dontoptimize

#保护注解
-keepattributes Annotation

#保持所有拥有本地方法的类名及本地方法名
-keepclasseswithmembernames class * {
Native <methods>;
}

#保持自定义View的get和set相关方法
-keepclassmembers public class extends Android.view.View {
void set
();
Get* ();
}

#保持Activity中View及其子类入参的方法
-keepclassmembers class extends Android.app.Activity {
public void
(Android.view.View);
}

#枚举
-keepclassmembers enum * {
*[] $VALUES;
public;
}

#Parcelable
-keepclassmembers class * Implements Android.os.Parcelable {
public static final Android.os.parcelable$creator Creator;
}

#R文件的静态成员
-keepclassmembers class *. R $ {
public static <fields>;
}

-dontwarn android.support.**

#keep相关注解
-keep class Android.support.annotation.Keep

-keep @android. Support.annotation.Keep class {;}

-keepclasseswithmembers class * {
@android. Support.annotation.Keep <methods>;
}

-keepclasseswithmembers class * {
@android. Support.annotation.Keep <fields>;
}

-keepclasseswithmembers class * {
@android. Support.annotation.Keep <init> (...);
}

Confusing user's manual for Android developers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.