Android code compiled in user mode is Proguard optimized to cause class and variable loss

Source: Internet
Author: User
Tags modifiers

In the Android project to use the JNI, when the use of Proguard, found that the native method can not find many variables, the original was Produard optimized out. Therefore, it is prudent to use Progurad in JNI applications.

Workaround:
1. Add a line to the ANDROID.MK:
Local_proguard_flags: =-include $ (local_path)/proguard.flags
2. Create a Proguard.flag file that writes classes and methods that do not require proguard optimization. For example:

-keep class Oms.miracle.mobiletv.broadcast.ServiceContext {
*;
}

My class is related to JNI, do not want to let proguard to optimize and cause errors, write to the above can be achieved.

----------below are some of the Proguard information found online, posted to share:
Proguard is a free Java class file for compression, optimization, and obfuscation. It detects and removes unused classes, fields, methods, and properties. It removes useless instructions and uses bytecode to get maximum optimization. It uses meaningless names to rename classes, fields, and methods.

The use of Proguard is to:

1. Create compact code documents for faster network transfers, fast loading and smaller memory usage.
2. It is difficult to use reverse engineering to create programs and libraries.
3. So it can delete the code from the source file without calling it
4. Take advantage of JAVA6 's fast loading to detect and return class files that exist in Java6 in advance.

Parameters:

-include {filename} reads configuration parameters from a given file

-basedirectory {directoryname} specifies the base directory for later relative file names

-injars {Class_path} specifies the application jar,war,ear and directory to be processed

-outjars {Class_path} Specifies the name of the Jar,war,ear and directory to output after processing

-libraryjars {classpath} specifies the library files required for the application Jar,war,ear and directories to be processed

-dontskipnonpubliclibraryclasses specifies that non-public library classes are not ignored.

-dontskipnonpubliclibraryclassmembers specifies that the members of the Library class that the package is visible are not ignored.


Retention options
-keep {Modifier} {class_specification} protects the specified class file and members of the class

-keepclassmembers {modifier} {class_specification} Protects members of the specified class, and if this class is protected they will be better protected

-keepclasseswithmembers {class_specification} protects the specified class and members of the class, but the condition is that all specified classes and class members are to be present.

-keepnames {class_specification} protects the names of the specified classes and members of the class (if they are not removed in the compression step)

-keepclassmembernames {class_specification} protects the names of the members of the specified class (if they are not removed in the compression step)

-keepclasseswithmembernames {class_specification} protects the name of a member of the specified class and class if all the specified class members are present (after the compression step)

-printseeds {filename} lists the members of the class and class-keep options, standard output to the given file

Compression
-dontshrink does not compress the input class file

-printusage {filename}

-whyareyoukeeping {class_specification}

Optimization
-dontoptimize does not optimize the input class file

-assumenosideeffects {class_specification} Optimizations assume the specified method without any side effects

-allowaccessmodification allows access to and modification of members of classes and classes with modifiers when optimized

Confuse
-dontobfuscate does not confuse the input class file

-printmapping {filename}

-applymapping {filename} reuse mappings Add confusion

-obfuscationdictionary {filename} uses the keyword in the given file as the name of the method to be confused

-overloadaggressively obfuscation when applying intrusive overloads

-useuniqueclassmembernames determining the member names of a unified obfuscation class to increase confusion

-flattenpackagehierarchy {package_name} repack all renamed packages and place them in a given single package

-repackageclass {package_name} repack all renamed class files in a given single package

-dontusemixedcaseclassnames confusion does not produce 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


Because we are developing projects that are webwork+spring+hibernate architecture, all require very detailed configuration. (Summary after n failures)

Example:
-injars <project>.jar
-outjars <project>_out.jar

-libraryjars <java.home>/lib/rt.jar
-libraryjars <project.home>/webroot/web-inf/lib/webwork.jar
.......

# Preserve the public, friendly, private properties and public, friendly methods of implementing the Action interface class. All other compression, optimization, confusion.
# because the class name in the configuration file is a complete class name, this class may not be found if processed.
The # property is required for JSP pages and cannot get the data in the action if the JSP page is processed.
-keep public class * Implements com.opensymphony.xwork.action{
Public protected Private <fields>;
Public protected <methods>;
}

# preserves the public, friendly, private members (properties and methods) that implement the Serializable interface class
# This configuration is primarily the configuration of the corresponding entity class.
-keep public class * Implements java.io.serializable{
public protected Private *;
}

......




>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>


We do Java development generally encounter how to protect our development of code problems. Because the Java language is based on the JVM, it is very easy to decompile the class file. If we do a Web application and publish the Web program to the customer. In fact, the customer is very easy to decompile our source code out, including all the SRC files and JSP files and so on.

So, how to protect our source code, in fact, there should be several ways to use: 1, the use of code obfuscation 2, overloaded application server ClassLoader

For the first method, there are a lot of open source tools available outside now, and personally think it's best to use the genus Proguard. Proguard is mainly easy to use and easy to learn. And it offers a lot of features. Here is a personal point of use experience

(1), from the online download Proguard tool, the Proguard tool mainly consists of several jar files and some example,http://proguard.sourceforge.net/

(2), add several jar files inside the classpath. Of course, you can also not add, but the following in the confusion, you must specify the classpath, so that in the process of confusion, can access the class

(3), write a configuration file, mainly a number of parameters of the obfuscation. For example, here's an example
-injars Platform.jar
-outjars Platform_out.jar
-libraryjars <java.home>/lib/rt.jar
-libraryjars Ibatis-common-2.jar
-libraryjars Ibatis-dao-2.jar
-libraryjars Ibatis-sqlmap-2.jar
-libraryjars Junit-3.8.1.jar
-libraryjars D:/j2ee.jar
-libraryjars Struts.jar
-libraryjars Commons-lang.jar
-libraryjars D:/0working/coreproject/byislib/jasperreports-0.6.1.jar
-libraryjars Commons-beanutils.jar

-printmapping Proguard.map
-overloadaggressively
-defaultpackage "
-allowaccessmodification
-dontoptimize
-keep public class *
{
public protected *;
}
-keep public class org.**
-keep public class it.**

The meanings of each parameter refer to the Proguard documentation, which is very detailed and easy to get started with

OK, this completes the code confusion, open the resulting jar can be seen, a lot of a, B, C and other class files. Indicates that the result of the confusion has been successful. Delete the original jar, run the resulting obfuscation jar package, everything is OK!

FAQ: In the process of using the individual encountered a few problems, began to find a long time to solve
A. Memory overflow exception: mainly proguard in the confusion, eat a lot of memory, so when running the obfuscation, you can increase the memory, such as java-mx512m ...
B. Stack overflow exception: mainly proguard in the confusion, some code will be optimized, if you encounter some relatively complex methods, may throw this exception. The workaround is to increase the configuration parameter-dontoptimize, as shown in the configuration example above

For the second method, the principle of overloading the server's ClassLoader is this. First we encrypt the class file by a certain algorithm, then write our own classloader, replacing the server's ClassLoader. In this way, we can read the class file, encrypt it into the correct class using our own algorithm, and then load again. This approach has not yet been applied, and these days individuals are studying what new results will be done here to summarize.


Proguard is an open source project, home page: http://proguard.sourceforge.net/, the latest version of the current is 3.3.2. It is very easy to load the obfuscation, just unzip the proguard3.3.2.zip and select the Proguard installation directory in the J2me->packing->obfuscation tab. As shown here, you can configure the class names that need to be persisted during the obfuscation process, and the name of the MIDlet class must be preserved so that the device's Java Runtime Environment (JRE) can find the entry point for execution.
Http://images.csdn.net/20050726/image027.jpg,It ' s about the above pic.



Another document
Proguard is a free Java class file compressor, optimizer, and obfuscation. It can discover and delete useless classes, fields, methods, and property values (attribute). It can also optimize bytecode and remove useless instructions. Finally, it uses a simple, meaningless name to rename your class name, field name, and method name. The jar files that go through the above operations become smaller and can be difficult to reverse engineer. The main function of Proguard here is compression, optimization and obfuscation, so I'll start by introducing these concepts and then introducing the basic use of proguard.

L What is compression:

Java source code (. java files) is typically compiled into bytecode (. class files). The complete program or library is usually compressed and published as a Java document (. jar file). Bytecode is more concise than Java source files, but it still contains a lot of useless code, especially when it is a library. Proguard's compression program operation parses bytecode and removes useless classes, fields, and methods. The program retains only functional equivalence, including the information required by the exception stack description.

L What is confusing:

Typically, the compiled bytecode still contains a lot of debugging information: source file name, line number, field name, method name, parameter name, variable name, and so on. This information makes it easy to decompile and get a complete program through reverse engineering. Sometimes, this is disgusting. For example, a obfuscation like Proguard can remove these debug messages and replace all the names with meaningless sequences of characters, making it difficult to reverse engineer, and it further streamlines the code for free. In addition to the class name, method name, and line extra required for the exception stack information, the program retains only functional equivalence. Through the above understanding, you should understand why the need to confuse.

L Proguard supports those kinds of optimizations:

In addition to the useless classes, fields, and methods that are removed by the compression operation, Proguard also provides performance optimizations at the bytecode level, with internal methods:

² Constant Expression Evaluation

² Delete Unnecessary field access

² Remove Unnecessary method calls

² Remove Unnecessary branches

² Remove unnecessary comparisons and instanceof validation

² Remove Unused Code

² Delete Write-only segments

² to delete Unused method parameters

² A wide variety of peephole optimizations like Push/pop simplification

² Add static and final modifiers to the class where possible

² Add Private, Static, and final modifiers to the method where possible

² to make the Get/set method inline, where possible

² when the interface has only one implementation class, replace it

² Selective deletion of log codes

The actual optimization effect is dependent on your code and the virtual machine that executes the code. A simple virtual machine is more efficient than an advanced virtual machine with a complex JIT compiler. In any case, your bytecode will get smaller.

There are still a few technologies that are obviously needed to be optimized not supported:

² make a non-final constant field inline

² make other methods inline like the Get/set method

² move a constant expression outside the loop

²optimizations that require escape analysis



Proguard is a command-line tool and provides a graphical user interface that can also be used in conjunction with Ant or J2ME Wireless Toolkit. The more streamlined jar files obtained by proguard mean that only a smaller amount of storage space is needed, the network transport is more time-consuming, the loading speed is faster and the memory footprint is smaller. In addition, Proguard is very fast and efficient, it only takes a few seconds and a few megabytes of memory in the handler. The order in which it is processed is first compressed, then optimized, and finally confused. The results section presents actual figures for a number of applications. The main advantage of Proguard compared to other Java obfuscation is its simple configuration based on the template file. Some intuitive command-line options or a simple configuration file are sufficient. For example, the following configuration options protect all applets in the jar file:

-keep public class * extends Java.applet.Applet

The User Guide explains all the available options and demonstrates these powerful configuration options in a number of examples.



There are many benefits of Proguard, now let's look at how to use the Proguard in the program, and mentioned before Proguard can use the command line, graphical interface, ant, etc. to execute and process the program, but also mention the configuration file, let's look at how to use:

The command line executes Proguard commands as follows:

Java–jar Proguard.jar Options ...

Specific options can refer to the Proguard User Guide, you can also write these properties in the configuration file, we only need to specify this configuration file, for example:

Java–jar Proguard.jar @config. Pro

The format of the configuration file is also to be written in the format provided by Proguard, this can refer to the Proguard example configuration file to configure the appropriate Proguard configuration file for your application system. Proguard provides a graphical interface to configure and run the program, you can configure the interface to the parameters you want, and then run. The previously mentioned configuration files to be written manually can also be configured and generated using the graphical interface.

If you want to run Proguard in ant, you only need to add one by one of the following target:

<target name= "Proguard" depends= "init" >

<taskdef resource= "proguard/ant/task.properties" classpath= "${lib.dir}/proguard/proguard.jar"/>

<proguard configuration= "${src.dir}/config.pro"/>

</target>

You just have to make the Lib.dir and Src.dir attributes, and again, here's the Proguard configuration file, as mentioned above. We recommend that you use Proguardgui as a wizard to generate configuration files so that we only need to modify the configuration file without having to re-write a configuration file.

If you think Proguard is good, then get it into your project.





Third document
This is something that should not appear in the open source community, but it is indeed an open source project, just like its name, Proguard, program Guard, which represents the relative side of open source-code protection.
As a high-level language in Java, the product of the compilation is just a concept of relative source code, although the bytecode is not as easy to understand as the source code, but it is not impossible to decompile, anti-compilation products for Java many, such as Cavaj,jad and so on. Faced with the continuous emergence of anti-compilation products, the code as a wealth of those developers, and where to go.
The confusion is precisely in this context, since it is impossible to completely reject the anti-compilation, then let them go to decompile it, as long as the results of the anti-compilation can not be used directly by others? As long as the code to confuse, let others get the results of anti-compilation can not understand, and even can not compile.
There are many ways to confuse, mainly in the following aspects.
Renaming, renaming a private class, a private member, a variable name inside a method body, changing to a a,b,c, and so on, or even a three-to-one (not allowed in the code is not allowed in the result object)
Change the flow of logic, such as reverse the IF condition, If/else swap
Equivalent code, such as changing a loop to Goto
Invalid code, insertion of unusable code
Proguard is a very good open source Java obfuscation, can be downloaded to http://proguard.sourceforge.net/, now let me take a look at Proguard.
Take version 3.2 as an example, release the compressed package, we see that as an open source project there is a Docs,lib,src,sample folder, here is not introduced.
Enter the Lib directory, there are Proguard.jar, if you want to have the shell of the obfuscation, or as an ant plug-in, it will be used, detailed information can refer to the Proguard documentation.
What we want to see is Proguardgui.jar, this is Proguard's graphical interface, we use the JDK to open, note is the JDK, not the JRE.

Click the Input/output tab, select the Jar package to confuse (note the jar package), output the jar package, and all the class libraries used.
Click the Obfuscation tab and select the class that does not need to be confused (the class to be reflected must never be confused)
Click the Process tab, Process button, and wait to see the results.
Proguard also includes the function of code optimization and code collation, not the scope of this article, interested in self-study it)
Options for confusing aspects only



In this way, if A-Z is used, it turns to aa.class, such as the Configuration interface
1,4,6,9,10,11,12

Source
Package org.zwm.pub;

public class Bru {

/**
* @param args
*/

public static void Main (string[] args) {
TODO auto-generated Method Stub
System.out.println (ShowMsg ());
}
public static String ShowMsg () {
Return "You Are my Sun";
}
}
Post-compilation Code
Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
Jad Home page:http://www.kpdus.com/jad.html
Decompiler Options:packimports (3)

Package org.zwm.pub;

Import Java.io.PrintStream;

public class Bru
{

Public Bru ()
{
}

public static void Main (String args[])
{
System.out.println (PK0304140008000800FZ ());
}

public static String Pk0304140008000800fz ()
{
Return "You Are my Sun";
}
}




The class name does not change and the method name is confused.



Another example, I hope to help you:

Command line, run the proguard directive: Java-jar Proguard.jar @proguard. Pro where the Proguard.pro file is the specified obfuscation information.

Example: a swing application:

-injars Gimt.jar
-outjars Gimt_out.jar
-libraryjars Lib/rt.jar
-libraryjars Lib/antlr/antlr-2.7.5h3.jar
-libraryjars Lib/cglib/cglib-full-2.0.2.jar
-libraryjars Lib/db2-connector/db2jcc_license_cu.jar
-libraryjars Lib/dom4j/dom4j-1.5.2.jar
-libraryjars Lib/encache/ehcache-1.1.jar
-libraryjars Lib/hibernate/hibernate3.jar
-libraryjars Lib/jakarta-common/commons-beanutils.jar
-libraryjars Lib/log4j/log4j-1.2.9.jar
-libraryjars Lib/mysql-connector/mysql-connector-java-3.0.17-ga-bin.jar
-libraryjars Lib/spring/spring.jar
-libraryjars Lib/db2-connector/db2jcc.jar
-libraryjars Lib/jakarta-common/commons-collections-2.1.1.jar
-libraryjars Lib/jakarta-common/commons-dbcp-1.2.1.jar
-libraryjars Lib/jakarta-common/commons-lang-2.0.jar
-libraryjars Lib/jakarta-common/commons-logging-1.0.4.jar
-libraryjars Lib/jakarta-common/commons-pool-1.2.jar
-libraryjars Lib/spring/spring-mock.jar
-libraryjars Lib/j2ee/jta.jar
-libraryjars Lib/db2-connector/db2java.zip

-printmapping Proguard.map
-overloadaggressively
-defaultpackage "
-allowaccessmodification
-dontoptimize

-keep public class Com.wisdom.tool.MainFrame {
public static void Main (java.lang.string[]);
}

-keep class * extends Javax.swing.plaf.ComponentUI {
public static Javax.swing.plaf.ComponentUI Createui (javax.swing.JComponent);
}

-keep public class Com.wisdom.model.user.* {
*;
}

-keep public class Com.wisdom.service.* {
*;
}

-keep public class Com.wisdom.service.impl.MenuServiceImpl

A little note:
1. Start without the-dontoptimize option, which can sometimes be problematic, as mentioned above.
2. Lists all dependent. JAR packages.
3. The Keep option tells Proguard that there is no need to confuse.
A. For swing applications, the entry of the entire program cannot be confused.
B. For classes that inherit from Componentui, Createui cannot be confused.
C. Using Hibernate's Domain object Spring's service object, due to the use of the reflection mechanism.

Android code compiled in user mode is Proguard optimized to cause class and variable loss

Related Article

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.