In the previous chapters, we understood how ProGuard prepares the configuration files it needs and the code to be processed at the early stage of its execution.
Next comes the Shrink part. As before, let’s go back to ProGuard.execute():
// In ProGuard |
Skipping the operations that aren’t the main ones here, let’s go straight to shrink():
// In ProGuard |
From experience, the main operations happen inside execute(), and Shrinker is divided into two major parts: marking the code that is used, and removing the code that isn’t. Below, we go in reverse and start with the removing part.
Removing
First, only the part about removing is listed:
// In Shrinker |
Look at classesAccept():
// In ClassPool |
Here the ProgramClasses in the ProgramClassPool are taken out one by one to call accept().
Here we need to restate the concept mentioned in Part4, to make the following analysis easier to understand:
- Executing
clazz.accept(visitor)can be read directly asvisitor.visitXXXClass(). Whetherclazzis a ProgramClass or a LibraryClass decides whatXXXis.
Following this concept, classesAccept() leads to UsedClassFilter’s visitProgramClass():
// In UsedClassFilter |
Here UsageMarker is used first to check whether the passed-in ProgramClass is marked as used, which means it’s referenced in the code:
// In UsageMarker |
If it is, visitProgramClass() is called again. Combined with the arguments passed in at the beginning, we know this is the MultiClassVisitor:
// In MultiClassVisitor |
Here it calls visitProgramClass through the ClassVisitors it holds, in order: ClassShrinker and ClassPoolFiller.
ClassShrinker
What ClassShrinker’s visitProgramClass() does is mostly the same throughout, so let’s take shrinkArray() as the example:
// In ClassShrinker |
The first loop takes out the ProgramFields in the array one by one and checks through usageMarker whether each is used; if it is, it’s written back over the original array from the start. Then, if the new array should be shorter, the remaining part is cleared.
Overall, ClassShrinker’s visitProgramClass() has many shrinkXXX() methods, used to strip the classes, methods or variables that usageMarker decides are unused, which achieves the removal.
Marking
Create ClassVisitor
From the removing part, we can see that whether a class, method or variable stays depends on whether calling getVisitorInfo() on it returns USED.
Next, go back to the first half of execute(), which is the part that sets up the marking:
// In Shrinker |
At the very beginning of the method, usageMarker is created. Here we assume -whyareyoukeeping isn’t set, so UsageMarker is chosen.
// Automatically mark the parameterless constructors of seed classes, |
Then it’s wrapped with a NamedMethodVisitor and passed into a MultiClassVisitor. Here, let’s sum up the structure of classUsageMarker first:
ClassVisitor { |
usageMarker and classUsageMarker are then passed together into KeepClassSpecificationVisitorFactory’s createClassPoolVisitor(), along with ProGuard’s keep configuration:
ClassPoolVisitor classPoolvisitor = |
Let’s pause Shrinker.execute() here, and first go deeper from the part that gets the ClassPoolVisitor.
// In KeepClassSpecificationVisitorFactory |
Here a loop takes out each keep configuration in order, gets an individual ClassVisitor for each through createClassPoolVisitor(), and adds it to the MultiClassPoolVisitor that’s returned. From the content above, apart from classVisitor being classUsageMarker, all the arguments here are usageMarker:
// In KeepClassSpecificationVisitorFactory |
Next, we bring in the example from Part3, but drop the description at the end to focus on the class:
-keep class * extends com.example.classname |
The keepClassSpecification obtained from the example makes createClassPoolVisitor() skip all the operations in between and go straight to the parent class ClassSpecificationVisitorFactory:
// In ClassSpecificationVisitorFactory |
According to the analysis in Part3, extendsClassName is com.example.classname; className is null, and is set to ** here.
... |
We won’t go into detail here; just note that classNameMatcher is a VariableStringMatcher, and it’s recorded in variableStringMatchers.
// Combine both visitors. |
Then createCombinedClassVisitor() is called, which we won’t go deeper into. With this post’s example, this method returns the passed-in classVisitor directly.
Let’s keep reading:
// If the class name has wildcards, only visit classes with matching names. |
Everything obtained above is wrapped into a ClassNameFilter, and className is set back to null at this point.
// If it's specified, start visiting from the extended class. |
Since extendsClassName isn’t null, combinedClassVisitor is wrapped again into a ClassHierarchyTraveler, and the value is assigned to className, so className is now com.example.classname.
// If specified, visit a single named class, otherwise visit all classes. |
Finally, className isn’t null, so it’s wrapped in one more NamedClassVisitor and returned.
Here’s a summary of the structure of the ClassPoolVisitor obtained, combined with the ClassVisitor passed in from Shrinker:
MultiClassPoolVisitor { |
Accept ClassVisitor
Back in Shrinker, after getting the ClassVisitor, it’s passed in through accept to start the static analysis:
// Mark the seeds. |
Below we use programClassPool as the example.
Seeing accept(), we can directly associate it with MultiClassPoolVisitor’s visitClassPool():
// In MultiClassPoolVisitor |
A loop takes out the ClassPoolVisitors in order, which, compared with the structure above, is the NamedClassVisitor, and passes the ProgramClassPool in:
// In NamedClassVisitor |
It doesn’t do much: it passes com.example.classname and the ClassHierarchyTraveler into the ProgramClassPool through classAccept():
// In ClassPool |
Here it tries to use the passed-in class name to take the corresponding Clazz out of the ProgramClassPool. ProGuard hasn’t done any Shrink yet, so the Clazz for the class com.example.classname should be there.
Likewise, seeing accept() tells us it goes into ClassHierarchyTraveler:
// In ClassHierarchyTraveler |
Then it goes back to ProgramClass, which is the Clazz just mentioned:
// In ProgramClass |
From the content above, we know only visitSubclasses is true, so the parts that won’t run are omitted.
Here the subclasses of com.example.classname are taken out in order. Since what’s obtained is also a Clazz, hierarchyAccept() can be called again to recurse, so all the subclasses can be analyzed one by one. This way of execution also matches the rule * extends com.example.classname in the example.
Next, look at the part where a subclass runs hierarchyAccept(); at this point visitThisClass is also true:
// In ProgramClass |
Seeing accept(), it automatically goes to ClassNameFilter:
// In ClassNameFilter |
Here regularExpressionMatcher is used to check whether what’s passed in matches a specific rule. It’s the VariableStringMatcher generated from the string ** mentioned earlier, so any string passed to it matches, which also matches the * rule in the example.
After confirming the rule matches, it calls visitProgramClass with the classVisitor it holds. Following the structure above, the classVisitor here is the MultiClassVisitor created in Shrinker.execute().
MultiClassVisitor was introduced earlier, so let’s go straight to the UsageMarker inside it:
// In UsageMarker |
At this point the ProgramClass is marked as USED, which ties back to the check before removal earlier.
Next, look at the other one inside MultiClassVisitor, the NamedMethodVisitor:
// In NamedMethodVisitor |
Following the structure above, name and descriptor combined are <init>()V, which refers to Java’s default constructor. The memberVisitor passed in here is usageMarker, so let’s go straight to visitProgramMethod:
// In UsageMarker |
The comments make it clear: it first checks whether the ProgramClass is marked. If it is, the passed-in ProgramMethod, i.e. the class’s default constructor, is kept; if it isn’t kept, the method is first marked as POSSIBLY_USED, and then markMethodHierarchy looks again through the class’s parent or subclasses for whether it’s referenced.
This small section also brings out a concept:
- If a class is kept, its default constructor is always kept too
With that, we’ve finished analyzing the steps of Shrink from marking to removing. It’s more complex than the previous chapters, and it pushes the Visitor Pattern and the Decorator Pattern to the limit.
However, if you’ve read along from Part1, you should feel that the implementation is actually very uniform:
- Visitors are wrapped layer by layer through the Decorator Pattern, with the decision logic each layer needs included; then the Visitors are unwrapped layer by layer through the Visitor Pattern, passing the content to be processed down layer by layer.
To put it plainly, the layers of Visitor wrapping are just like the block layers of Java code:
ClassPool { |
So when reading the ProGuard source code, keeping Java’s structural rules in mind helps you understand the processing logic of each layer and the order of the wrapping.