After understanding the basics of how ProGuard works, it’s hard not to want to know how it’s designed behind the scenes, so that it can process and analyze code of all kinds of styles, without even worrying that the whole flow fails to run because the target program is too large.
At least, that’s how I feel, so the remaining chapters focus on the flow of its code. As for whether we can find any patterns in it that we can borrow for our daily projects, we’ll only know after reading through.
Covering everything takes a lot of space, so Part3 is only a beginning. I also suggest reading Part1 first to understand some of the terms used in the following chapters.
Where to start
Source code
A craftsman must first sharpen his tools. First, download the source code from the official site. Everything below is based on version 6.0.3.
Start point
Since we want to look at the flow related to Android, let’s go straight to ProGuardTask under the gradle directory.
To design a Gradle Task, besides extending DefaultTask, you also need to add @TaskAction to the method that serves as the entry point; similar to Java’s main(), the Task starts by calling execute(). For details, see the introduction on the Gradle website.
So the entry point of ProGuardTask is proguard():
// In ProGuardTask |
As we mentioned in Part1, the first step of ProGuard is reading the ProGuard configuration.
Read Configuration
First, look at getConfiguration():
// In ProGuardTask |
The omitted first half adds the jar files of the Program and Library classes into configuration, but it’s not important here, so we skip it. What’s left is that every configuration file goes through ConfigurationParser.parse() in turn, which stores the settings in the file into configuration.
So the key is ConfigurationParser:
// In ConfigurationParser |
ConfigurationParser uses FileWordReader to read the file:
// In FileWordReader |
We won’t go into its details here; in short, it’s used to read the file content line by line.
Back to readNextWord():
// In ConfigurationParser |
So right after ConfigurationParser is created, it reads the file through the passed-in Reader. FileWordReader here doesn’t implement nextWord(), so the parent WordReader’s nextWord() is used.
To avoid interrupting the analysis, this method is explained in the Appendix. In short, its purpose is: read the configuration content line by line and return it, split by whitespace, brackets, commas or colons. So the current nextWord is -keep.
At this point, ConfigurationParser has been created successfully. Then parse() is called, with configuration passed in to hold the result. To have something concrete for the explanation, here we use a common keep rule as the example:
-keep class * extends com.example.classname { *; } |
Here are the parts of parse() that the example uses; the other parts are much the same:
// In ConfigurationConstants |
Since nextWord is -keep at this point, after entering the loop it goes to the KEEP_OPTION branch, which uses configuration.keep to store the classes, methods and variables that need to be kept:
// In Configuration |
Here we simply assume configuration.keep isn’t null, and look at parseKeepClassSpecificationArguments():
// In ConfigurationParser |
Based on the input above, note that only markClasses is true, and the others are either false or null. It then calls another parseKeepClassSpecificationArguments() with the same name:
// In ConfigurationConstants |
At the beginning, this method checks whether there are settings modifying keep, such as allowshrinking. If there are, the variables at the beginning of the method are changed.
However, according to the example, the string readNextWord() gets here is class, so the next check breaks out of the loop directly and goes to the part that reads the class: parseClassSpecificationArguments(). This method runs through more code for this example, so it’s explained in sections below:
// In ConfigurationParser |
Now the value of nextWord is class, so it skips the while loop and goes to parseCommaSeparatedList.
This method is also fairly complex; see the Appendix for details. In short, its purpose is:
- Reassemble a comma-separated string into a List until no more commas are seen, and read the next word before returning.
After getting the List, commaSeparatedString is called to reassemble the List back into a string. This round trip removes unnecessary characters between the strings, such as comments.
// For backward compatibility, allow a single "*" wildcard to match any |
With the example, parseCommaSeparatedList() only gets the asterisk, so className is set to null, and nextWord is the word after the asterisk, extends.
// Clear the annotation type and the class name of the extends part. |
nextWord is extends, so configurationEnd() is false. readNextWord() is called again to get the next string in the example: com.example.classname.
Then, as before, parseCommaSeparatedList is used to take out the comma-separated strings, but it only gets the same result. So at this point externalExtendsClassName is com.example.classname, and nextWord is {.
Finally, ClassUtil.internalClassName() replaces the . separating the class name with /:
// In ClassUtil |
At this point we have the complete class name, and next is creating a ClassSpecification. ClassSpecification is a model that stores class information; besides the class name, it records methods, variables and other class-related information:
// Create the basic class specification. |
Back in parseClassSpecificationArguments(), there’s still:
// Now add any class members to this class specification. |
Last of all, configurationEnd() is still false, and nextWord is {, which equals OPEN_KEYWORD, so it goes straight down to the while loop.
|
readNextWord() inside the loop gets the asterisk, which is further analyzed by parseMemberSpecificationArguments(), and the result is put back into classSpecification.
When }, i.e. CLOSE_KEYWORD, is read, readNextWord() runs one last time. At this point nextWord becomes null because it reaches the end of the file, the loop exits, and the parsing of one keep rule is complete.
The classSpecification produced here is returned to parseKeepClassSpecificationArguments() and added to the List keepClassSpecifications, which is the configuration.keep passed in from outside.
Returning further, we’re back in parse ready for the next iteration. At this point nextWord is null, which ends the loop and exits parse(), completing the configuration analysis of the whole file.
Appendix
This part introduces the methods with more content, to keep the analysis above from getting too scattered. To connect with the analysis above, the same example is used.
readNextWord()
Since this method contains a lot of operations, the parts not used in the analysis above are omitted or left as comments to save space:
// In WordReader |
This method works in three phases: first call, subsequent calls, and end of file.
First call
At first, currentLine is empty, so it jumps straight to the second section and gets the first line through nextLine().
nextLine() here is implemented by each Reader; let’s look at FileWordReader directly. FileWordReader actually extends LineNumberReader, which reads one line of the file as a string without the line break.
Back in nextWord, after getting the string, its length is stored first. This is the termination condition used to tell whether the line has been fully analyzed. Then it looks for the starting position of the configuration content, so whitespace and comments are skipped.
Once found, it takes out the first word and enters the series of checks in the third section. Generally it goes into the last else, and reads until a whitespace or a hash sign appears, which is taken as the end position.
With the start and end positions, part of the string can be taken out of the current line.
Subsequent calls
Since the Reader exists throughout the whole analysis, the previously set currentLine, currentLineLength and the resulting currentWord aren’t cleared; the next time this method is entered, it goes into the first section, again skipping whitespace and comments to find the start of the next piece of configuration, and then goes into the third section to get the next piece.
End of file
If currentIndex has been incremented to equal currentLineLength in the first section, the line has been fully processed. It then goes into the second section and first reads the next line into currentLine. This is a reset, so later calls don’t loop in the terminated state. If there’s no next line to read (nextLine() returns null), it returns null directly to let the caller know the end of the file has been reached.
In summary, this method:
- Reads the configuration content line by line and returns it, split by whitespace, brackets, commas or colons.
parseCommaSeparatedList()
Same as readNextWord(), only the parts used in the analysis above are kept here:
// In ConfigurationParser |
This is a general-purpose method dedicated to reassembling a comma-separated string into a List. In this post’s example, it’s used to get the class name.
if (list == null) { |
This method first calls readNextWord(). In this post’s example, when the analysis reaches this method, the nextWord obtained is the asterisk.
while (true) { |
Whatever it gets is then added to the List, and readNextWord() is used again to read the next string, which in the example is extends.
if (!ConfigurationConstants.ARGUMENT_SEPARATOR_KEYWORD.equals(nextWord)) { |
Since nextWord is extends, not a comma, the List containing the asterisk is returned directly. If it were a comma, the next string would be taken out and the next iteration would start.
In short, this method:
- Reassembles a comma-separated string into a List until no more commas are seen, and reads the next word before returning.