Android Proguard Detailed

Source: Internet
Author: User

Brief introduction

Java code is very easy to decompile. In order to protect the Java source code very well, we often confuse the compiled class file.

Proguard is an open source project that confuses code. Its main role is to confuse, of course, it can also reduce the size of bytecode, optimization, etc., but those for us is considered a secondary function. Website website is:

http://proguard.sourceforge.net/.


Explanation 1, principle
Java is a cross-platform, interpreted language in which Java source code is compiled into an intermediate "bytecode" stored in a class file. Because of the cross-platform requirements, Java bytecode contains a lot of source code information, such as variable name, method name, and through these names to access variables and methods, these symbols with a lot of semantic information, it is easy to decompile the Java source code. To prevent this, we can use Java obfuscation to confuse Java bytecode.

Confusion is the re-organization and processing of the published program, so that the processed code and the pre-processing code to complete the same function, and the confusing code is difficult to decompile, even if the anti-compilation success is difficult to derive the true semantics of the program. The obfuscated program code, still in accordance with the original file format and instruction set, the execution result is the same as before, but the confusion of all the variables, functions, classes in the code to the name of the short English letter code, in the absence of the corresponding function name and program comments, even if it is anti-compilation, it will be difficult to read. At the same time confusion is irreversible, in the process of confusion, some information that does not affect the normal operation will be lost permanently, the loss of this information makes the program more difficult to understand.

The role of the obfuscation is not only to protect the code, it also has the function of simplifying the size of the compiled program. Because of the shortened variables and function names described above, and the reasons for missing some information, the size of the jar file can be reduced by approximately 25%, which makes sense for the current cost of the wireless network transmission is more expensive. 2. Grammar

-include {filename} reads the configuration parameter from the given file-basedirectory {directoryname} specifies the underlying directory for the later relative file name-injars {Class_path} specifies the application to be processed Jar,war,ear and directory-outjars {Class_path} Specifies the name of the Jar,war,ear and directory to output after processing,-libraryjars {classpath} Specifies the applications to be processed jar,war,ear and directories required The library file-dontskipnonpubliclibraryclasses specifies that the non-public libraries class is not to be ignored. -dontskipnonpubliclibraryclassmembers specifies that the members of the Library class that the package is visible are not ignored. The Preserve option-keep {Modifier} {class_specification} protects the specified class file and the members of the class-keepclassmembers {Modifier} {class_specification} protects the specified class of If this class is protected they will protect it better-keepclasseswithmembers {class_specification} protects the specified class and members of the class, but the condition is that all the specified classes and class members are to be present. -keepnames {class_specification} protects the names of the members of the specified class and class (if they are not removed in the compression step)-keepclassmembernames {class_specification} protects the specified class from The name of the member (if they are not removed in the compression step)-keepclasseswithmembernames {class_specification} protects the name of the specified class and members of the class, if all the specified class members are present (after the compression step)- printseeds {filename} lists the members of the class and class-keep option, standard output to the given file compression-dontshrink does not compress the input class file-printusage {filename}-whyareyoukeepin The g {class_specification} optimization-dontoptimize does not optimize the input class file-assumenosideeffects {class_specification} optimizations assume that the specified method, without any side effects, is-allowaccessmodification optimized to allow access to and modify members of classes and classes that have modifiers to confuse-dontobfusca Te does not confuse the input class file-printmapping {filename}-applymapping {filename} reuse mappings Add confusion-obfuscationdictionary {filename} using the given file The keyword as the name of the method to be confused-overloadaggressively obfuscation when applying intrusive overloads-useuniqueclassmembernames to determine the uniform confusing class member names to increase confusion-flattenpackagehierar chy {package_name} repack all the renamed packages and place them in a given single package-repackageclass {package_name} repack all the renamed class files in a given single package-DONTUSEMIXEDCASECLA    Ssnames confusion does not result in a variety of class names-keepattributes {attribute_name,...} Protects the given optional attributes, such as linenumbertable, Localvariabletable, sourcefile, Deprecated, synthetic, Signature, and innerclasses. -renamesourcefileattribute {String} sets the given string constant in the source file

Demo instance

-ignorewarnings# ignores warnings and avoids packaging when certain warnings appear-optimizationpasses the compression level of the specified code-dontusemixedcaseclassnames#                            Whether to use case blending-dontskipnonpubliclibraryclasses# whether to confuse third-party jar-dontpreverify # When doing pre-calibration-verbose # when confusing the algorithm used when logging-optimizations!code/simplification/arithmetic,!field/*,!class/merging/* # is confused-libra Ryjars Libs/treecore.jar-dontwarn android.support.v4.** #缺省proguard will check that each reference is correct, but there are often some classes that are not used in third-party libraries and are not referenced correctly. If not configured, the system will error.  -dontwarn Android.os.**-keep class android.support.v4.** {*;} # Keep What classes are not confused-keep class com.baidu.** {*;} -keep class vi.com.gdi.bgl.android.**{*;} -keep class android.os.**{*;}  -keep interface android.support.v4.app.** {*;} -keep public class * Extends android.support.v4.**-keep public class * extends Android.app.fragment-keep public class * Extends Android.app.activity-keep public class * extends Android.app.application-keep public class * extends Android.app. Service-keep public class * extends Android.content.BroadcastReCeiver-keep public class * extends Android.content.contentprovider-keep public class * extends Android.support.v4.widget-keep public class * extends Com.sqlcrypt.database-keep public class * extends Com.sqlcrypt.database.sqlite-keep public class * extends Com.treecore.**-keep public class * extends de.greenrobot.dao.* *-keepclasseswithmembernames class * {# Keep Native method not to be confused native <methods>;} -keepclasseswithmembers class * {# Keep custom control classes from being confused with public <init> (Android.content.Context, Android.util.AttributeSe t);} -keepclasseswithmembers class * {# Keep custom control classes from being confused with public <init> (Android.content.Context, Android.util.AttributeSe t, int);} -keepclassmembers class * extends Android.app.Activity {//Keep class member public void * (Android.view.View);}    -keepclassmembers enum * {# keep Enum enum class not confused public static **[] values (); public static * * VALUEOF (java.lang.String);} -keep class * Implements android.os.Parcelable {# keep Parcelable not be confused public static final Android.os.parcelable$creatoR *;}                              -keep class MyClass; # Keep your defined classes from being confused

3. Documents

Proguard is automatically run when the APK is packaged in release mode, where the release mode refers to the ant release command or Eclipse Project->android Tools->export signed ( Unsigned
Application package generates APK.
In debug mode, Proguard is not called for faster debugging.

If the ant command is packaged apk,proguard information files will be saved in the <project_root>/bin/proguard folder;
If packaged with the Eclipse Export command, it is within the <project_root>/proguard folder. It contains the following files:

Mapping.txt
This file is very important for the comparison of the code before and after the confusion. If your code is confusing and generates a bug, the log hint is a confusing code, and if you want to locate the source code, you can reverse it by mapping.txt.
Keep it up every time you publish it to facilitate the issue of this version of the log for troubleshooting, it can be based on the version number or the name of the publication time to save or put into the code version control.


Dump.txt
Describes the internal structure of all class files within the APK.

Seeds.txt
Lists the classes and members that are not confused.

Usage.txt
Lists the code in the source code that is deleted in the APK without being present.

4. Code that cannot be confused

As the name implies, you cannot confuse the code, or it will go wrong.

1. Place of radiation

2. System interface

3. JNI interface

4.

Android.app.backup.BackupAgentHelper
Android.preference.Preference

Com.android.vending.licensing.ILicensingService

......

5, Bug (common error) 1, Proguard returned with error code 1. See console

1. Update Proguard version
2, android-support-v4 not to be confused

3, add the missing corresponding library

2. Missing type parameter exception occurs when parsing data using Gson package

1. Add in Proguard.cfg

-dontobfuscate-dontoptimize

2. Add in Proguard.cfg

# removes such information by default, so configure it to keep all of it.-keepattributes signature# Gson specific classes- Keep Class Sun.misc.Unsafe {*;} #-keep class com.google.gson.stream.** {*;} # application classes that'll be is serialized/deserialized over Gson-keep class com.google.gson.examples.android.model.* * { *; }
3. Type Conversion error-keepattributes Signature

4. Null pointer exception

Confusing and filtering out related classes and methods

5, Android code confusion and reflection conflict, map can not display and other problems and anti-compilation methods, Android anti-compilation

The previous code is confusing because it doesn't use reflection, so the usual code obfuscation can pass through, and some classes in this project use the reflection mechanism (I have instant messaging in this project, so there is an emoticon resource, so we need to find the expression resource ID by reflection by the file name). When the file name to find the resource ID when the null pointer exception, the beginning of the period I do not know what the reason, by anti-compilation has been confused apk, step by step to find the wrong place, only to realize that the reflection that step appeared the problem: Field field = R.drawable.class.getdeclaredfield (name); Go to this step and hang up, the program crashes directly.

Workaround:
1. In the proguard.cfg file, the variables in the class to which the reflection is used are not confused:
such as:-keep public class Com.byl.bean.Expressions {*;}, indicating that all variables and methods in Expressions class and class are not confused, note that the full path is to be written;
2. Filter generics:-keepattributes Signature
3. The most important point: keep R files from being confused, otherwise, your reflection is not getting the resource ID:-keep class * *. r$* {*;}


To add: After the last problem solved, and then encountered a problem is confused, the map can not be used normally, bloggers use Baidu map, Proguard.cfg also has written:
-keep class com.baidu.** {*;}
-keep class vi.com.** {*;}

6, Android.provider.settings$global

# Project Target.
Target=android-19

7, Java.lang.reflect.UndeclaredThrowableException

-keep Interface com.dev.impl.**

8. Memory overflow and cannot write to stack javaoptions in Proguard: = Seq (...)
Or
Javaoptions in (Proguard, proguard): = Seq (...)

9. error:unable to access Jarfile. \lib\proguard.jar

Path problem

10, Java.lang.NoSuchMethodError No related methods, methods are confused, confusing filter out the relevant methods can be.

11, professional website Bug Resolution method

Http://proguard.sourceforge.net/index.html#manual/troubleshooting.html

Summarize


With the obfuscation technology, the code no longer has to worry about being stolen ...

Android Proguard Detailed

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.