diff --git a/README b/README
new file mode 100644
index 000000000..2be677723
--- /dev/null
+++ b/README
@@ -0,0 +1,33 @@
+ProGuard, Java class file shrinker, optimizer, obfuscator, and preverifier
+==========================================================================
+
+This distribution contains the following directories:
+
+- bin : simple wrapper scripts to run ProGuard, its GUI, and ReTrace
+- lib : the main jars, compiled and ready to use with "java -jar ...."
+- docs : the complete documentation, licenses, etc. in html format
+- examples : some example configuration files
+- src : the source code
+- build : various alternative build scripts
+
+
+The best place to start is docs/index.html
+
+
+Example
+=======
+
+If you want to give ProGuard a spin right away, try processing the ProGuard
+jar itself:
+
+ cd examples
+ java -jar ../lib/proguard.jar @proguard.pro
+
+The resulting proguard_out.jar contains the same application, but it's a lot
+smaller.
+
+Enjoy!
+
+http://proguard.sourceforge.net/
+
+Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
diff --git a/bin/proguard.bat b/bin/proguard.bat
new file mode 100644
index 000000000..793e7196e
--- /dev/null
+++ b/bin/proguard.bat
@@ -0,0 +1,14 @@
+@ECHO OFF
+
+REM Start-up script for ProGuard -- free class file shrinker, optimizer,
+REM obfuscator, and preverifier for Java bytecode.
+REM
+REM Note: when passing file names containing spaces to this script,
+REM you'll have to add escaped quotes around them, e.g.
+REM "\"C:/My Directory/My File.txt\""
+
+IF EXIST "%PROGUARD_HOME%" GOTO home
+SET PROGUARD_HOME=..
+:home
+
+java -jar "%PROGUARD_HOME%\lib\proguard.jar" %*
diff --git a/bin/proguard.sh b/bin/proguard.sh
new file mode 100755
index 000000000..5adc0472e
--- /dev/null
+++ b/bin/proguard.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+#
+# Start-up script for ProGuard -- free class file shrinker, optimizer,
+# obfuscator, and preverifier for Java bytecode.
+#
+# Note: when passing file names containing spaces to this script,
+# you'll have to add escaped quotes around them, e.g.
+# "\"/My Directory/My File.txt\""
+
+PROGUARD_HOME=`dirname "$0"`/..
+
+java -jar $PROGUARD_HOME/lib/proguard.jar "$@"
diff --git a/bin/proguardgui.bat b/bin/proguardgui.bat
new file mode 100644
index 000000000..4575aaaff
--- /dev/null
+++ b/bin/proguardgui.bat
@@ -0,0 +1,14 @@
+@ECHO OFF
+
+REM Start-up script for the GUI of ProGuard -- free class file shrinker,
+REM optimizer, obfuscator, and preverifier for Java bytecode.
+REM
+REM Note: when passing file names containing spaces to this script,
+REM you'll have to add escaped quotes around them, e.g.
+REM "\"C:/My Directory/My File.txt\""
+
+IF EXIST "%PROGUARD_HOME%" GOTO home
+SET PROGUARD_HOME=..
+:home
+
+java -jar "%PROGUARD_HOME%\lib\proguardgui.jar" %*
diff --git a/bin/proguardgui.sh b/bin/proguardgui.sh
new file mode 100755
index 000000000..c7349067f
--- /dev/null
+++ b/bin/proguardgui.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+#
+# Start-up script for the GUI of ProGuard -- free class file shrinker,
+# optimizer, obfuscator, and preverifier for Java bytecode.
+#
+# Note: when passing file names containing spaces to this script,
+# you'll have to add escaped quotes around them, e.g.
+# "\"/My Directory/My File.txt\""
+
+PROGUARD_HOME=`dirname "$0"`/..
+
+# On Linux, Java 1.6.0_24 and higher hang when starting the GUI:
+# http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7027598
+# We're using the -D option as a workaround.
+java -DsuppressSwingDropSupport=true -jar $PROGUARD_HOME/lib/proguardgui.jar "$@"
diff --git a/bin/retrace.bat b/bin/retrace.bat
new file mode 100644
index 000000000..7201fb67f
--- /dev/null
+++ b/bin/retrace.bat
@@ -0,0 +1,14 @@
+@ECHO OFF
+
+REM Start-up script for Retrace -- companion tool for ProGuard, free class file
+REM shrinker, optimizer, obfuscator, and preverifier for Java bytecode.
+REM
+REM Note: when passing file names containing spaces to this script,
+REM you'll have to add escaped quotes around them, e.g.
+REM "\"C:/My Directory/My File.txt\""
+
+IF EXIST "%PROGUARD_HOME%" GOTO home
+SET PROGUARD_HOME=..
+:home
+
+java -jar "%PROGUARD_HOME%\lib\retrace.jar" %*
diff --git a/bin/retrace.sh b/bin/retrace.sh
new file mode 100755
index 000000000..85fd3149b
--- /dev/null
+++ b/bin/retrace.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+#
+# Start-up script for Retrace -- companion tool for ProGuard, free class file
+# shrinker, optimizer, obfuscator, and preverifier for Java bytecode.
+#
+# Note: when passing file names containing spaces to this script,
+# you'll have to add escaped quotes around them, e.g.
+# "\"/My Directory/My File.txt\""
+
+PROGUARD_HOME=`dirname "$0"`/..
+
+java -jar $PROGUARD_HOME/lib/retrace.jar "$@"
diff --git a/build/README b/build/README
new file mode 100644
index 000000000..36a235b64
--- /dev/null
+++ b/build/README
@@ -0,0 +1,40 @@
+ProGuard, Java class file shrinker, optimizer, obfuscator, and preverifier
+==========================================================================
+
+This directory contains a number of alternative ways to build ProGuard:
+
+- build.sh : a shell script for GNU/Linux
+- makefile : a makefile for GNU/Linux
+- build.xml : an Ant build file for all platforms
+- maven/pom.xml : a Maven POM for building the Maven artifacts
+
+- As a final alternative, you can also easily compile the code from the
+ command line:
+
+ mkdir classes
+ javac -sourcepath src -d classes src/proguard/ProGuard.java
+ javac -sourcepath src -d classes src/proguard/gui/ProGuardGUI.java
+ javac -sourcepath src -d classes src/proguard/retrace/ReTrace.java
+
+ For the ProGuard Ant task:
+
+ javac -sourcepath src -d classes -classpath lib/ant.jar \
+ src/proguard/ant/ProGuardTask.java
+
+ For the ProGuard Gradle task:
+
+ javac -sourcepath src -d classes -classpath ..... \
+ src/proguard/gradle/ProGuardTask.java
+
+ For the Java Micro Edition Wireless Tool Kit (JME WTK) obfuscator plug-in:
+
+ javac -sourcepath src -d classes -classpath wtklib/kenv.zip \
+ src/proguard/wtk/ProGuardObfuscator.java
+
+Note that you'll have to install Ant and the JME WTK yourself.
+
+Enjoy!
+
+http://proguard.sourceforge.net/
+
+Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
diff --git a/build/build.properties b/build/build.properties
new file mode 100644
index 000000000..a6d2bbf5b
--- /dev/null
+++ b/build/build.properties
@@ -0,0 +1,4 @@
+# Ant build properties for ProGuard.
+
+gradle.home = /usr/local/java/gradle
+wtk.home = /usr/local/java/wtk
diff --git a/build/build.sh b/build/build.sh
new file mode 100755
index 000000000..adb2ee75a
--- /dev/null
+++ b/build/build.sh
@@ -0,0 +1,110 @@
+#!/bin/bash
+#
+# GNU/Linux build script for ProGuard.
+
+#
+# Configuration.
+#
+
+ANT_HOME=${ANT_HOME:-/usr/local/java/ant}
+GRADLE_HOME=${GRADLE_HOME:-/usr/local/java/gradle}
+WTK_HOME=${WTK_HOME:-/usr/local/java/wtk}
+
+if [ -z $PROGUARD_HOME ]; then
+ PROGUARD_HOME=$(which "$0")
+ PROGUARD_HOME=$(dirname "$0")/..
+fi
+
+cd "$PROGUARD_HOME"
+
+SRC=src
+CLASSES=classes
+LIB=lib
+
+PROGUARD=proguard/ProGuard
+PROGUARD_GUI=proguard/gui/ProGuardGUI
+RETRACE=proguard/retrace/ReTrace
+ANT_TASK=proguard/ant/ProGuardTask
+GRADLE_TASK=proguard/gradle/ProGuardTask
+WTK_PLUGIN=proguard/wtk/ProGuardObfuscator
+
+ANT_JAR=$ANT_HOME/lib/ant.jar
+GRADLE_PATH=\
+$GRADLE_HOME/lib/plugins/gradle-plugins-1.3.jar:\
+$GRADLE_HOME/lib/gradle-base-services-1.3.jar:\
+$GRADLE_HOME/lib/gradle-core-1.3.jar:\
+$GRADLE_HOME/lib/groovy-all-1.8.6.jar
+WTK_JAR=$WTK_HOME/wtklib/kenv.zip
+
+PROGUARD_JAR=$LIB/proguard.jar
+PROGUARD_GUI_JAR=$LIB/proguardgui.jar
+RETRACE_JAR=$LIB/retrace.jar
+
+#
+# Function definitions.
+#
+
+function compile {
+ # Compile java source files.
+ echo "Compiling ${1//\//.} ..."
+ javac -nowarn -Xlint:none -sourcepath "$SRC" -d "$CLASSES" \
+ "$SRC/$1.java" 2>&1 \
+ | sed -e 's|^| |'
+
+ # Copy resource files.
+ (cd "$SRC"; find $(dirname $1) -maxdepth 1 \
+ \( -name \*.properties -o -name \*.png -o -name \*.gif -o -name \*.pro \) \
+ -exec cp --parents {} "../$CLASSES" \; )
+}
+
+function createjar {
+ echo "Creating $2..."
+ jar -cfm "$2" "$SRC/$(dirname $1)/MANIFEST.MF" -C "$CLASSES" $(dirname $1)
+}
+
+function updatejar {
+ echo "Updating $PROGUARD_JAR..."
+ jar -uf "$PROGUARD_JAR" -C "$CLASSES" $(dirname $1)
+}
+
+#
+# Main script body.
+#
+
+mkdir -p "$CLASSES"
+
+compile $PROGUARD
+createjar $PROGUARD "$PROGUARD_JAR"
+
+compile $PROGUARD_GUI
+createjar $PROGUARD_GUI "$PROGUARD_GUI_JAR"
+
+compile $RETRACE
+createjar $RETRACE "$RETRACE_JAR"
+
+if [ -f "$ANT_JAR" ]; then
+ export CLASSPATH=$ANT_JAR
+ compile $ANT_TASK
+ updatejar $ANT_TASK
+else
+ echo "Please make sure the environment variable ANT_HOME is set correctly,"
+ echo "if you want to compile the optional ProGuard Ant task."
+fi
+
+if [ -f "${GRADLE_PATH%%:*}" ]; then
+ export CLASSPATH=$GRADLE_PATH
+ compile $GRADLE_TASK
+ updatejar $GRADLE_TASK
+else
+ echo "Please make sure the environment variable GRADLE_HOME is set correctly,"
+ echo "if you want to compile the optional ProGuard Gradle task."
+fi
+
+if [ -f "$WTK_JAR" ]; then
+ export CLASSPATH=$WTK_JAR
+ compile $WTK_PLUGIN
+ updatejar $WTK_PLUGIN
+else
+ echo "Please make sure the environment variable WTK_HOME is set correctly,"
+ echo "if you want to compile the optional ProGuard WTK plugin."
+fi
diff --git a/build/build.xml b/build/build.xml
new file mode 100644
index 000000000..9544a41a5
--- /dev/null
+++ b/build/build.xml
@@ -0,0 +1,214 @@
+
+
+
Class.forName
+ calls?+Some notable optimizations that aren't supported yet: +
+ProGuard also comes with an obfuscator plug-in for the JME Wireless +Toolkit. + +
dx
compiler converts ordinary jar files into files
+that run on Android devices. By preprocessing the original jar files,
+ProGuard can significantly reduce the file sizes and boost the run-time
+performance of the code. It is distributed as part of the Android SDK.
+DexGuard,
+ProGuard's closed-source sibling for Android, offers additional
+optimizations and more application protection.
+
+rapc
compiler converts ordinary JME
+jar files into cod files that run on Blackberry devices. The compiler performs
+quite a few optimizations, but preprocessing the jar files with
+ProGuard can generally still reduce the final code size by a few
+percent. However, the rapc
compiler also seems to contain some
+bugs. It sometimes fails on obfuscated code that is valid and accepted by other
+JME tools and VMs. Your mileage may therefore vary.
+
+Class.forName
calls?Class.forName("SomeClass")
and SomeClass.class
. The
+referenced classes are preserved in the shrinking phase, and the string
+arguments are properly replaced in the obfuscation phase.
+
+With variable string arguments, it's generally not possible to determine their
+possible values. They might be read from a configuration file, for instance.
+However, ProGuard will note a number of constructs like
+"(SomeClass)Class.forName(variable).newInstance()
". These might
+be an indication that the class or interface SomeClass
and/or its
+implementations may need to be preserved. The developer can adapt his
+configuration accordingly.
+
+
+ +
+ + + +
+Version 2, June 1991 + +
+ ++Copyright (C) 1989, 1991 Free Software Foundation, Inc. +59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. ++ + + +
+ The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + +
++ When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + +
++ To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + +
++ For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + +
++ We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + +
++ Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + +
++ Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + +
++ The precise terms and conditions for copying, distribution and +modification follow. + +
+ + ++ +0. + This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". +
+ +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + +
+ +1. + You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. +
+ +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. +
+ +2. + You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: +
+ +
+
+
+ +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. +
+ +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + +
+ +3. + You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + + + +
+
+
+ +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. +
+ +4. + You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + +
+ +5. + You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + +
+ +6. + Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + +
+ +7. + If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. +
+ +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. +
+ +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. +
+ +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + +
+ +8. + If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + +
+ +9. + The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. +
+ +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + +
+ + +10. + If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + + +
NO WARRANTY
+ ++ +11. + BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + +
+ +12. + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +
+ + +
+Copyright © 2002-2013 Eric Lafortune +
+ ++This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 2 of the License, or (at your option) any later +version. +
+ ++This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +
+ ++You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place, Suite 330, Boston, MA 02111-1307 USA +
+ ++In addition, as a special exception, Eric Lafortune gives permission to link +the code of this program with the following stand-alone applications: +
+ +Dirk Schnelle has contributed and maintained the first versions of the Ant +task. I have rewritten the implementation for version 3.0, but the XML schema +is still based on his work. +
+ +Marcel Patzlaff has initiated a series of artifacts in the Maven Central +repository. I am now maintaining them as part of the official builds. +
+ +Many other people have expressed their enthusiasm and have chimed in with +interesting ideas, bug reports, and bug fixes: Thorsten Heit, Oliver Retzl, +Jonathan Knudsen, Tarcisio Camara, Bob Drury, Dave Jarvis, Marc Chapman, Dave +Morehouse, Richard Osbaldeston, Peter Hawkins, Mark Sherington, David Sitsky, +James Manning, Ptolemy Oberin, Frank-Michael Moser, QZ Shines, Thomas Singer, +Michele Puccini, Roman Bednarek, Natalia Pujol, Daniel Sjöblom, Jan +Filipsky, Charles Smith, Gerrit Telkamp, Noel Grandin, Torbjörn +Söderstedt, Clemens Eisserer, Clark Bassett, Eduard Welch, Dawid Weiss, +Andrew Wilson, Sean Owen, Niels Gron, Ishan Mehta, Steven Adams, Xavier Kral, +Stefan Martin, Toby Reyelts, Bernhard Eder, Manfred Moser, Marco Blümel, +David Reiss, +and many more. Thanks! Your feedback has been invaluable. +
+ +Saikoa is providing the +financial resources for this project. At Saikoa, we're also developing +ProGuard's sibling for Android, +DexGuard. +
+ +SourceForge is providing the resources for hosting this +project and many other projects. +
+ +Sonatype and +the Maven Central repository are hosting the Maven artifacts. +
+ +The code and these web pages were written using Oracle/Sun's JDKs, Linux, +IntelliJ IDEA, GNU emacs, bash, sed, awk, and a whole host of other tools that +continue to make programming interesting. +
+ +And finally, I'm a great fan of Sanaware's Java Docking Library. + +
+This is a list of the programs of which I'm aware. Obviously, I've never +personally tested all of them. Many programs, even commercial ones, have been +abandoned. Please drop me a note if you know of any other shrinkers, +optimizers, obfuscators, or preverifiers, or if some information provided +below is incorrect. +
+ +
Author/Company | +Program | +Shrink. | +Optim. | +Obfusc. | +Preverif. | +License | +
---|---|---|---|---|---|---|
Eric Lafortune | +ProGuard | +![]() |
+![]() |
+![]() |
+![]() |
+Free (GPL) | +
Jochen Hoenicke | +Jode | +![]() |
+![]() |
+![]() |
+Free (GPL) | +|
Nate Nystrom | +Bloat | +![]() |
+![]() |
+Free | +||
Hidetoshi Ohuchi | +Jarg | +![]() |
+![]() |
+Free (BSD) | +||
yWorks | +yGuard | +![]() |
+![]() |
+Free (no source) | +||
Mojo | +Minijar | +![]() |
+Free (Apache) | +|||
RiggsHill Software | +GenJar | +![]() |
+Free (Apache) | +|||
Apache | +Ant Classfileset | +![]() |
+Free (Apache) | +|||
Carsten Elton Sørensen | +Treeshaker | +![]() |
+Free (Apache) | +|||
Jörg Spieler | +UCDetector | +![]() |
+Free (EPL) | +|||
Romain Guy | +Harvester | +![]() |
+Free (BSD) | +|||
Emeric Vernat | +DCD | +![]() |
+Free (LGPL) | +|||
Cristiano Sadun | +Pack | +![]() |
+Free (LGPL) | +|||
Sable | +Soot | +![]() |
+Free (LGPL) | +|||
Konstantin Knizhnik | +JavaGO | +![]() |
+Free | +|||
Sable | +JBCO | +![]() |
+Free (LGPL) | +|||
Jeffrey Wheaton | +ClassEncrypt | +![]() |
+Free (GPL) | +|||
Thorsten Heit | +JavaGuard | +![]() |
+Free (LGPL) | +|||
Patrick Mueller | +Mwobfu | +![]() |
+Free (GPL) | +|||
BebboSoft | +Bb_mug | +![]() |
+Free (no source) | +|||
Vít Šesták | +Preverifier | +![]() |
+Free (EPL) | +|||
Saikoa | +DexGuard | +![]() |
+![]() |
+![]() |
+Commercial | +|
PreEmptive | +DashOPro | +![]() |
+![]() |
+![]() |
+Commercial | +|
Zelix | +KlassMaster | +![]() |
+![]() |
+![]() |
+Commercial | +|
Sophia Cradle | +SophiaCompress | +![]() |
+![]() |
+![]() |
+Commercial | +|
Eastridge Technology | +Jshrink | +![]() |
+![]() |
+Commercial | +||
LeeSoftware | +Smokescreen Obfuscator | +![]() |
+![]() |
+Commercial | +||
Innaworks | +mBooster | +![]() |
+![]() |
+![]() |
+Commercial | +|
Sergey Sverdlov | +J.Class Optimizer | +![]() |
+![]() |
+Commercial | +||
Smardec | +Allatori | +![]() |
+![]() |
+Commercial | +||
U. of Arizona | +SandMark | +![]() |
+![]() |
+Commercial | +||
Zenofx | +ClassGuard | +![]() |
+Commercial | +|||
BIS Guard & Co. | +Java Antidecompiler | +![]() |
+Commercial | +|||
Force 5 | +JCloak | +![]() |
+Commercial | +|||
Semantic Designs | +Obfuscator | +![]() |
+Commercial | +|||
Duckware | +Jobfuscate | +![]() |
+Commercial | +|||
Arxan | +GuardIT | +![]() |
+Commercial | +|||
Vasile Calmatui | +VasObfuLite | +![]() |
+Free | +|||
IBM AlphaWorks | +JAX | +![]() |
+![]() |
+![]() |
+(discontinued) | +|
NQ4 | +Joga | +![]() |
+![]() |
+![]() |
+(discontinued?) | +|
Markus Jansen | +Jopt | +![]() |
+![]() |
+![]() |
+(disappeared?) | +|
Alexander Shvets | +CafeBabe | +![]() |
+![]() |
+(disappeared?) | +||
Brian Alliet | +Gcclass | +![]() |
+(disappeared?) | +|||
Christian Grothoff | +Jamit | +![]() |
+(disappeared?) | +|||
Haruaki Tamada | +DonQuixote | +![]() |
+![]() |
+(disappeared?) | +||
Bajie | +JCMP | +![]() |
+![]() |
+(disappeared?) | +||
Elegant Software | +JMangle | +![]() |
+(disappeared?) | +|||
Eron Jokipii | +Jobe | +![]() |
+(disappeared?) | +|||
JRC | +DeCaf | +![]() |
+(disappeared?) | +|||
Dr. Java | +Marvin Obfuscator | +![]() |
+(disappeared?) | +|||
IBM | +WSDD | +![]() |
+![]() |
+![]() |
+Commercial (discontinued?) | +|
S5 Systems | +jPresto | +![]() |
+![]() |
+![]() |
+Commercial (discontinued?) | +|
Plumb Design | +Condensity | +![]() |
+![]() |
+Commercial (discontinued) | +||
4th Pass | +SourceGuard | +![]() |
+![]() |
+Commercial (discontinued?) | +||
CodingArt | +CodeShield | +![]() |
+![]() |
+Commercial (discontinued?) | +||
Software4j | +Obfuscate4j | +![]() |
+Commercial (discontinued?) | +|||
JAMM Consulting | +ObfuscatePro | +![]() |
+Commercial (discontinued?) | +|||
JDevelop | +JSCO | +![]() |
+Commercial (discontinued?) | +|||
4Fang | +JMix | +![]() |
+Commercial (discontinued?) | +|||
RetroLogic | +RetroGuard | +![]() |
+![]() |
+Commercial (disappeared?) | +||
Helseth | +JObfuscator | +![]() |
+![]() |
+Commercial (disappeared?) | +||
Vega Technologies | +JZipper | +![]() |
+![]() |
+Commercial (disappeared?) | +||
JProof | +JProof | +![]() |
+Commercial (disappeared?) | +|||
ChainKey | +Java Code Protector | +![]() |
+Commercial (disappeared?) | +|||
2LKit | +2LKit Obfuscator | +![]() |
+Commercial (disappeared?) | +|||
WingSoft | +WingGuard | +![]() |
+Commercial (disappeared?) | +|||
HashJava | +HashJava | +![]() |
+Commercial (disappeared?) | +|||
GITS | +Blurfuscator | +![]() |
+Commercial (disappeared?) | +
+All trademarks are property of their respective holders. + +
+ProGuard is written in Java, so it requires a Java Runtime Environment + (JRE 1.5 or higher). +
+You can download the latest release (containing the program jars, the +documentation that you're reading now, examples, and the source code) from this +location: +
+
+ +The proguard section contains major releases and updates with +sub-minor version numbers, for applying emergency fixes. The +proguard beta section contains beta releases. These include +new features and any less urgent bug fixes collected since the previous +release. +
+If you're still working with an older version of ProGuard, check out +the summary of changes below, to see if you're missing something essential. +Better look at the up-to-date on-line version if +you're reading a local copy of this page. Unless noted otherwise, +ProGuard remains compatible across versions, so don't be afraid to +update. +
+If you're only interested in individual jar files for your build process, you +can also download them from the Maven Central repository, with GroupId +net.sf.proguard and ArtifactIds +proguard-parent, +proguard-base, +proguard-gui, +proguard-anttask, +proguard-gradle, +proguard-wtk-plugin, and +proguard-retrace. + +
optimize.conservatively
to allow
+ for instructions intentionally throwing NullPointerException
,
+ ArrayIndexOutOfBoundsException
, or
+ ClassCastException
without other useful effects.
+-keepparameternames
or -keepattributes
.
+-keepclassmembers
+ without specific class or class members.
+-keep
options.
+-keepparameternames
.
+-dontskipnonpubliclibraryclasses
is now set by default. Added
+ -skipnonpubliclibraryclasses
as an option.
+-optimizations
for fine-grained configuration of
+ optimizations.
+-adaptclassstrings
for adapting string constants
+ that correspond to obfuscated classes.
+-keeppackagenames
for keeping specified package
+ names from being obfuscated.
+-keepdirectories
for keeping specified directory
+ entries in output jars.
+-dontnote
and -dontwarn
for
+ fine-grained configuration of notes and warnings.
+-regex
in ReTrace, for specifying alternative
+ regular expressions to parse stack traces.
+EnclosingMethod
+ attributes are being kept.
+-keepclassmembers
options.
+-classobfuscationdictionary
and
+ -packageobfuscationdictionary
.
+maximum.inlined.code.length
(default is 8) and
+ maximum.resulting.code.length
(defaults are 8000 for JSE and
+ 2000 for JME), for expert users who read release notes.
+<injars>
and
+ <libraryjars>
elements.
+-microedition
and -dontpreverify
.
+-target
to modify java version of processed
+ class files.
+-keep
options more orthogonal and flexible, with option
+ modifiers allowshrinking
, allowoptimization
, and
+ allowobfuscation
.
+***
",
+ matching any type, and "...
", matching any number of
+ arguments.
+-forceprocessing
.
+-flattenpackagehierarchy
and
+ -repackageclasses
(replacing -defaultpackage
) to
+ control obfuscation of package names.
+-adaptresourcefilenames
and
+ -adaptresourcefilecontents
, with file filters, to update
+ resource files corresponding to obfuscated class names.
+Exceptions
attributes as optional.
+EnclosingClass$InnerClass
) in obfuscation step, if
+ InnerClasses
attributes or EnclosingMethod
+ attributes are being kept.
+Exceptions
attribute as
+ optional, you may have to specify -keepattributes Exceptions
,
+ notably when processing code that is to be used as a library.
+
+-microedition
. You then no longer need to process the
+ code with an external preverifier.
+
+-repackageclasses
instead of the
+ old option name -defaultpackage
.
+-dontusemixedcaseclassnames
is specified.
+-useuniqueclassmembernames
.
+Class.forName
detection.
+-basedirectory
option.
+-whyareyoukeeping
option to get details on why given
+ classes and class members are being kept.
+Class.forName
constructs.
+assumenosideeffects
' nested element in Ant task.
+-resourcejars
option. Resources should now be read
+ using regular -injars
options, using filters if necessary.
+outjars
' now nested element instead of attribute.
+ type
' attribute of <method>
element no
+ longer defaults to 'void
'.
+ <
and >
characters now have to be
+ encoded in embedded configurations.
+ <proguardconfiguration>
task no longer accepts
+ attributes.
+ -applymapping
option for incremental obfuscation.
+SourceDir
attribute.
+.class
constructs.
+-defaultpackage
bug for protected classes and class
+ members.
+-defaultpackage
option.
+.class
constructs in internal classes
+ targeted at JRE1.2 (the default in JDK1.4).
+-dump
option when -outjar
option is not
+ present.
+.class
detection for classes compiled with
+ Jikes.
+Class.forName("MyClass")
,
+ MyClass.class
, and
+ (MyClass)Class.forName(variable).newInstance()
constructs.
+ This greatly simplifies configuration.
++
+I can't promise a swift answer, or any answer at all, for that matter, but it's +always great to see constructive comments. +
+ +ProGuard isn't a typical open source project, in the sense that I am +not looking for code contributions. Developing on my own allows me to +do things my way, without the overhead and compromises associated with larger +projects. + +
+ProGuard is a free Java class file shrinker, optimizer, obfuscator, and +preverifier. It detects and removes unused classes, fields, methods, and +attributes. It optimizes bytecode and removes unused instructions. It renames +the remaining classes, fields, and methods using short meaningless names. +Finally, it preverifies the processed code for Java 6 or for Java Micro +Edition. +
++Your browser doesn't support frames, but that's cool. +
+You can go straight to the main page. + +
+ +ProGuard itself is copyrighted, but its distribution license provides +you with some rights for modifying and redistributing its code and its +documentation. More specifically, ProGuard is distributed under the +terms of the GNU General Public License (GPL), version +2, as published by the Free +Software Foundation (FSF). In short, this means that you may freely +redistribute the program, modified or as is, on the condition that you make +the complete source code available as well. If you develop a program that is +linked with +ProGuard, the program as a whole has to be distributed at no charge +under the GPL. I am granting a special +exception to the latter clause (in wording suggested by +the FSF), for combinations with the following stand-alone +applications: Apache Ant, Apache Maven, the Google Android SDK, the Eclipse +ProGuardDT GUI, the EclipseME JME IDE, the Oracle NetBeans Java IDE, the +Oracle JME Wireless Toolkit, the Intel TXE SDK, the Simple Build Tool for +Scala, the NeoMAD Tools by Neomades, the Javaground Tools, and the Sanaware +Tools. + +
+The ProGuard user documentation represents an important part of this +work. It may only be redistributed without changes, along with the unmodified +version of the code. + +
+ProGuard is a free Java class file shrinker, optimizer, obfuscator, and +preverifier. It detects and removes unused classes, fields, methods, and +attributes. It optimizes bytecode and removes unused instructions. It renames +the remaining classes, fields, and methods using short meaningless names. +Finally, it preverifies the processed code for Java 6 or higher, or for Java +Micro Edition. +
+Some uses of ProGuard are: ++ProGuard's main advantage compared to other Java obfuscators is +probably its compact template-based configuration. A few intuitive command +line options or a simple configuration file are usually sufficient. +The user manual explains all available options and shows examples of this +powerful configuration style. +
+ProGuard is fast. It only takes seconds to process programs and +libraries of several megabytes. The results section presents actual figures +for a number of applications. +
+ProGuard is a command-line tool with an optional graphical user +interface. It also comes with plugins for Ant, for Gradle, and for the JME +Wireless Toolkit. +
+
+
+
+ProGuard now has a sibling optimizer and obfuscator for Android:
+DexGuard. It
+focuses on code protection, with additional features like string encryption
+and class encryption. It directly targets Dalvik bytecode and streamlines the
+Android build process.
+
+
+Before you can use the proguard
task, you have to tell Ant about
+this new task. The easiest way is to add the following line to your
+build.xml
file:
+
+ +
+<taskdef resource="proguard/ant/task.properties" + classpath="/usr/local/java/proguard/lib/proguard.jar" /> ++
+ +Please make sure the class path is set correctly for your system. +
+ +There are three ways to configure the ProGuard task: +
+ +
configuration
+attribute of your
+proguard
task. Your ant build file will then look like this:
++ +
+<taskdef resource="proguard/ant/task.properties" + classpath="/usr/local/java/proguard/lib/proguard.jar" /> +<proguard configuration="myconfigfile.pro"/> ++
+ +This is a convenient option if you prefer ProGuard's configuration style over +XML, if you want to keep your build file small, or if you have to share your +configuration with developers who don't use Ant. +
+ +
proguard
task
+(the PCDATA area). Your Ant build file will then look like this:
++ +
+<taskdef resource="proguard/ant/task.properties" + classpath="/usr/local/java/proguard/lib/proguard.jar" /> +<proguard> + -libraryjars ${java.home}/lib/rt.jar + -injars in.jar + -outjars out.jar + + -keepclasseswithmembers public class * { + public static void main(java.lang.String[]); + } +</proguard> ++
+ +Some minor syntactical changes are required in order to conform with the XML +standard. +
+
+Firstly, the #
character cannot be used for comments in an XML
+file. Comments must be enclosed by an opening <!--
and a
+closing -->
. All occurrences of the #
character
+can be removed.
+
+
+Secondly, the use of <
and >
characters would
+upset the structure of the XML build file. Environment variables can be
+specified with the usual Ant style ${...}
, instead of the ProGuard
+style <...>
. Other occurrences of <
and
+>
have to be encoded as <
and
+>
respectively.
+
+ +
examples/ant
directory of the ProGuard distribution.
++ +
<proguard>
task and the
+<proguardconfiguration>
task can have the following
+attributes (only for <proguard>
) and nested
+elements:
+
+configuration
+ = "filename"configuration
+ element.skipnonpubliclibraryclasses
+ = "boolean"
+ (default = false)skipnonpubliclibraryclassmembers
+ = "boolean"
+ (default = true)target
+ = "version"
+ (default = none)forceprocessing
+ = "boolean"
+ (default = false)printseeds
+ = "boolean or filename"
+ (default = false)keep
+ commands, to the standard output or to the given file.shrink
+ = "boolean"
+ (default = true)printusage
+ = "boolean or filename"
+ (default = false)optimize
+ = "boolean"
+ (default = true)optimizationpasses
+ = "n"
+ (default = 1)allowaccessmodification
+ = "boolean"
+ (default = false)mergeinterfacesaggressively
+ = "boolean"
+ (default = false)obfuscate
+ = "boolean"
+ (default = true)printmapping
+ = "boolean or filename"
+ (default = false)applymapping
+ = "filename"
+ (default = none)obfuscationdictionary
+ = "filename"
+ (default = none)classobfuscationdictionary
+ = "filename"
+ (default = none)packageobfuscationdictionary
+ = "filename"
+ (default = none)overloadaggressively
+ = "boolean"
+ (default = false)useuniqueclassmembernames
+ = "boolean"
+ (default = false)usemixedcaseclassnames
+ = "boolean"
+ (default = true)flattenpackagehierarchy
+ = "package_name"
+ (default = none)repackageclasses
+ = "package_name"
+ (default = none)keepparameternames
+ = "boolean"
+ (default = false)renamesourcefileattribute
+ = "string"
+ (default = none)SourceFile
+ attributes.preverify
+ = "boolean"
+ (default = true)microedition
+ = "boolean"
+ (default = false)verbose
+ = "boolean"
+ (default = false)note
+ = "boolean"
+ (default = true)warn
+ = "boolean"
+ (default = true)ignorewarnings
+ = "boolean"
+ (default = false)printconfiguration
+ = "boolean or filename"
+ (default = false)dump
+ = "boolean or filename"
+ (default = false)<injar
+ class_path
+ />
<outjar
+ class_path
+ />
<libraryjar
+ class_path
+ />
<keepdirectory name =
"directory_name"
+ />
<keepdirectories filter =
"directory_filter"
+ />
<keep
+ modifiers
+ class_specification
+ >
+ class_member_specifications
+ </keep>
<keepclassmembers
+ modifiers
+ class_specification
+ >
+ class_member_specifications
+ </keepclassmembers>
<keepclasseswithmembers
+ modifiers
+ class_specification
+ >
+ class_member_specifications
+ </keepclasseswithmembers>
<keepnames
+ class_specification
+ >
+ class_member_specifications
+ </keepnames>
<keepclassmembernames
+ class_specification
+ >
+ class_member_specifications
+ </keepclassmembernames>
<keepclasseswithmembernames
+ class_specification
+ >
+ class_member_specifications
+ </keepclasseswithmembernames>
<whyareyoukeeping
+ class_specification
+ >
+ class_member_specifications
+ </whyareyoukeeping>
<assumenosideeffects
+ class_specification
+ >
+ class_member_specifications
+ </assumenosideeffects>
<optimization name =
"optimization_name"
+ />
<optimizations filter =
""optimization_filter"
+ />
<keeppackagename name =
"package_name"
+ />
<keeppackagenames filter =
"package_filter"
+ />
<keepattribute name =
"attribute_name"
+ />
<keepattributes filter =
"attribute_filter"
+ />
<adaptclassstrings filter =
"class_filter"
+ />
<adaptresourcefilenames filter =
"file_filter"
+ />
<adaptresourcefilecontents filter =
"file_filter"
+ />
<dontnote filter =
"class_filter"
+ />
<dontwarn filter =
"class_filter"
+ />
<configuration refid =
"ref_id"
+ />
<configuration file =
"name"
+ />
<proguardconfiguration>
task (or
+ <proguard>
task) with attribute id
=
+ "ref_id". Only the nested elements of this configuration are
+ considered, not the attributes.
+
+ The second form includes the ProGuard-style configuration from the specified
+ file. The element is actually a fileset
element and supports
+ all of its attributes and nested elements, including multiple files.
+
path
elements, so they can have any of the
+standard path
attributes and nested elements. The most common
+attributes are:
+
+path
= "path"location
= "name" (or file
+ = "name", or dir
= "name", or
+ name
= "name")refid
= "ref_id"id
= "ref_id".filter
=
+ "file_filter"jarfilter
=
+ "file_filter"warfilter
=
+ "file_filter"earfilter
=
+ "file_filter"zipfilter
=
+ "file_filter"allowshrinking
+ = "boolean"
+ (default = false)allowoptimization
+ = "boolean"
+ (default = false)allowobfuscation
+ = "boolean"
+ (default = false)access
= "access_modifiers"annotation
= "annotation_name"type
= "type"name
= "class_name"extendsannotation
= "annotation_name"extends
= "class_name"implements
= "class_name"<field
+ class_member_specification
+ />
<method
+ class_member_specification
+ />
<constructor
+ class_member_specification
+ />
access
= "access_modifiers"annotation
= "annotation_name"type
= "type"parameters
attribute is specified.name
= "name"parameters
= "parameters"type
attribute is
+ specified.examples
+directory of the ProGuard distribution.
+
+myconfig.pro
, which can be used
+with
++bin/proguard @myconfig.pro ++
+The configuration file specifies the input, the output, and the entry points +of the application: +
+-injars myapplication.jar +-outjars myapplication_out.jar +-libraryjars <java.home>/lib/rt.jar +-printmapping myapplication.map + +-keep public class mypackage.MyMain { + public static void main(java.lang.String[]); +} ++
+Note the use of the <java.home>
system property. ProGuard
+automatically replaces it when parsing the file.
+
+The -keep
option specifies the
+entry point of the application that has to be preserved.
+The access modifiers public
and static
are not
+really required in this case, since we know a priori that the specified class
+and method have the proper access flags. It just looks more familiar this way.
+
+Note that all type names are fully specified:
+mypackage.MyMain
and java.lang.String[]
.
+
+We're writing out an obfuscation mapping file with -printmapping
, for
+de-obfuscating any stack traces later on, or for incremental obfuscation of
+extensions.
+
+We can further improve the results with a few additional options: +
+-optimizationpasses 3 +-overloadaggressively +-repackageclasses '' +-allowaccessmodification ++These options are not required; they just shave off some extra bytes from the +output jar, by performing up to 3 optimization passes, and by aggressively +obfuscating class members and package names. +
+In general, you might need a few additional options for processing native methods, callback methods, +enumerations, serializable +classes, bean classes, annotations, and resource +files. + +
mypackage.MyApplet
:
++-injars in.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar + +-keep public class mypackage.MyApplet ++
+The typical applet methods will be preserved automatically, since
+mypackage.MyApplet
is an extension of the Applet
+class in the library rt.jar
.
+
+If applicable, you should add options for processing native +methods, callback methods, enumerations, serializable +classes, bean classes, annotations, and resource +files. + +
mypackage.MyMIDlet
:
++-injars in.jar +-outjars out.jar +-libraryjars /usr/local/java/wtk2.5.2/lib/midpapi20.jar +-libraryjars /usr/local/java/wtk2.5.2/lib/cldcapi11.jar +-overloadaggressively +-repackageclasses '' +-allowaccessmodification +-microedition + +-keep public class mypackage.MyMIDlet ++
+Note how we're now targeting the Java Micro Edition run-time environment of
+midpapi20.jar
and cldcapi11.jar
, instead of the Java
+Standard Edition run-time environment rt.jar
. You can target
+other JME environments by picking the appropriate jars.
+
+The typical midlet methods will be preserved automatically, since
+mypackage.MyMIDlet
is an extension of the MIDlet
+class in the library midpapi20.jar
.
+
+The -microedition
option
+makes sure the class files are preverified for Java Micro Edition, producing
+compact StackMap
attributes. It is no longer necessary to run an
+external preverifier.
+
+Be careful if you do use the external preverify
tool on a platform
+with a case-insensitive filing system, such as Windows. Because this tool
+unpacks your processed jars, you should then use ProGuard's -dontusemixedcaseclassnames
+option.
+
+If applicable, you should add options for processing native +methods and resource files. +
+Note that you will still have to adapt the midlet jar size in the +corresponding jad file; ProGuard doesn't do that for you. + +
mypackage.MyApplet
:
++-injars in.jar +-outjars out.jar +-libraryjars /usr/local/java/javacard2.2.2/lib/api.jar +-dontwarn java.lang.Class +-overloadaggressively +-repackageclasses '' +-allowaccessmodification + +-keep public class mypackage.MyApplet ++
+The configuration is very similar to the configuration for midlets, except that +it now targets the Java Card run-time environment. This environment doesn't +have java.lang.Class, so we're telling ProGuard not to worry about it. + +
mypackage.MyXlet
:
++-injars in.jar +-outjars out.jar +-libraryjars /usr/local/java/jtv1.1/javatv.jar +-libraryjars /usr/local/java/cdc1.1/lib/cdc.jar +-libraryjars /usr/local/java/cdc1.1/lib/btclasses.zip +-overloadaggressively +-repackageclasses '' +-allowaccessmodification + +-keep public class mypackage.MyXlet ++
+The configuration is very similar to the configuration for midlets, except that +it now targets the CDC run-time environment with the Java TV API. + +
mypackage.MyActivity
:
++-injars bin/classes +-outjars bin/classes-processed.jar +-libraryjars /usr/local/java/android-sdk/platforms/android-9/android.jar + +-dontpreverify +-repackageclasses '' +-allowaccessmodification +-optimizations !code/simplification/arithmetic + +-keep public class mypackage.MyActivity ++
+We're targeting the Android run-time and keeping the activity as an entry +point. +
+Preverification is irrelevant for the dex compiler and the Dalvik VM, so we
+can switch it off with the
+-dontpreverify
option.
+
+The -optimizations
option
+disables some arithmetic simplifications that Dalvik 1.0 and 1.5 can't handle.
+Note that the Dalvik VM also can't
+handle aggressive overloading
+(of static fields).
+
+If applicable, you should add options for processing native +methods, callback methods, +enumerations, +annotations, and +resource files. + +
proguard.config=.....
" in the file
+project.properties
(created or updated by Android SDK revision 17
+or higher). Notes:
+proguard-project.txt
,...) contain
+ the necessary settings for your application.${sdk.dir}/tools/proguard/proguard-android-optimize.txt
+ instead of the default
+ ${sdk.dir}/tools/proguard/proguard-android.txt
.+For more information, you can consult the official Developer +Guide in the Android SDK. +
+If you're constructing a build process from scratch: these options shrink, +optimize, and obfuscate all public activities, services, broadcast receivers, +and content providers from the compiled classes and external libraries: +
+-injars bin/classes +-injars libs +-outjars bin/classes-processed.jar +-libraryjars /usr/local/java/android-sdk/platforms/android-9/android.jar + +-dontpreverify +-repackageclasses '' +-allowaccessmodification +-optimizations !code/simplification/arithmetic +-keepattributes *Annotation* + +-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.view.View { + public <init>(android.content.Context); + public <init>(android.content.Context, android.util.AttributeSet); + public <init>(android.content.Context, android.util.AttributeSet, int); + public void set*(...); +} + +-keepclasseswithmembers class * { + public <init>(android.content.Context, android.util.AttributeSet); +} + +-keepclasseswithmembers class * { + public <init>(android.content.Context, android.util.AttributeSet, int); +} + +-keepclassmembers class * extends android.content.Context { + public void *(android.view.View); + public void *(android.view.MenuItem); +} + +-keepclassmembers class * implements android.os.Parcelable { + static android.os.Parcelable$Creator CREATOR; +} + +-keepclassmembers class **.R$* { + public static <fields>; +} ++
+Most importantly, we're keeping all fundamental classes that may be referenced
+by the AndroidManifest.xml
file of the application. If your
+manifest file contains other classes and methods, you may have to specify
+those as well.
+
+We're keeping annotations, since they might be used by custom
+RemoteViews
.
+
+We're keeping any custom View
extensions and other classes with
+typical constructors, since they might be referenced from XML layout files.
+
+We're also keeping possible onClick
handlers in
+custom Context
extensions, since they might be referenced from
+XML layout files.
+
+We're also keeping the required static fields in Parcelable
+implementations, since they are accessed by introspection.
+
+Finally, we're keeping the static fields of referenced inner classes of
+auto-generated R
classes, just in case your code is accessing
+those fields by introspection. Note that the compiler already inlines
+primitive fields, so ProGuard can generally remove all these classes entirely
+anyway (because the classes are not referenced and therefore not required).
+
+If you're using additional Google APIs, you'll have to specify +those as well, for instance: +
+-libraryjars /usr/local/android-sdk/add-ons/google_apis-7_r01/libs/maps.jar ++
+If you're using Google's optional License Verification Library, you can
+obfuscate its code along with your own code. You do have to preserve
+its ILicensingService
interface for the library to work:
+
+-keep public interface com.android.vending.licensing.ILicensingService ++
+If you're using the Android Compatibility library, you should add the +following line, to let ProGuard know it's ok that the library references some +classes that are not available in all versions of the API: +
+-dontwarn android.support.** ++
+If applicable, you should add options for processing native
+methods, callback methods,
+enumerations,
+and resource files. You may also want to add
+options for producing useful stack traces and
+to remove logging. You can find a complete sample
+configuration in examples/android.pro
in the ProGuard
+distribution.
+
+
+-injars in.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar +-printmapping out.map + +-keepparameternames +-renamesourcefileattribute SourceFile +-keepattributes Exceptions,InnerClasses,Signature,Deprecated, + SourceFile,LineNumberTable,*Annotation*,EnclosingMethod + +-keep public class * { + public protected *; +} + +-keepclassmembernames class * { + java.lang.Class class$(java.lang.String); + java.lang.Class class$(java.lang.String, boolean); +} + +-keepclasseswithmembernames class * { + native <methods>; +} + +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +-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(); +} ++
+This configuration should preserve everything we'll ever want to access in the
+library. Only if there are any other non-public classes or methods that are
+invoked dynamically, they should be specified using additional -keep
options.
+
+The -keepclassmembernames
+option for the class$
methods is not strictly necessary. These
+methods are inserted by the javac
compiler and the
+jikes
compiler respectively, in JDK 1.2 and older, to implement
+the .class
construct. ProGuard will automatically detect them and
+deal with them, even when their names have been obfuscated. However, other
+obfuscators may rely on the original method names. It may therefore be helpful
+to preserve them, in case these other obfuscators are ever used for further
+obfuscation of the library.
+
+The "Exceptions" attribute has to be preserved, so the compiler knows which +exceptions methods may throw. +
+The "InnerClasses" attribute (or more precisely, its source name part) has to
+be preserved too, for any inner classes that can be referenced from outside the
+library. The javac
compiler would be unable to find the inner
+classes otherwise.
+
+The "Signature" attribute is required to be able to access generic types when +compiling in JDK 5.0 and higher. +
+The -keepparameternames
+option keeps the parameter names in the "LocalVariableTable" and
+"LocalVariableTypeTable" attributes of public library methods. Some IDEs can
+present these names to the developers who use the library.
+
+Finally, we're keeping the "Deprecated" attribute and the attributes for +producing useful stack traces. +
+We've also added some options for for processing native +methods, enumerations, serializable classes, and annotations, which are all discussed in their +respective examples. + +
in.jar
:
++-injars in.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar +-printseeds + +-keepclasseswithmembers public class * { + public static void main(java.lang.String[]); +} ++
+Note the use of -keepclasseswithmembers
.
+We don't want to preserve all classes, just all classes that have main
+methods, and those methods.
+
+The -printseeds
option prints
+out which classes exactly will be preserved, so we know for sure we're getting
+what we want.
+
+If applicable, you should add options for processing native +methods, callback methods, enumerations, serializable +classes, bean classes, annotations, and resource +files. + +
in.jar
:
++-injars in.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar +-printseeds + +-keep public class * extends java.applet.Applet ++
+We're simply keeping all classes that extend the Applet
class.
+
+Again, the -printseeds
option
+prints out which applets exactly will be preserved.
+
+If applicable, you should add options for processing native +methods, callback methods, enumerations, serializable +classes, bean classes, annotations, and resource +files. + +
in.jar
:
++-injars in.jar +-outjars out.jar +-libraryjars /usr/local/java/wtk2.5.2/lib/midpapi20.jar +-libraryjars /usr/local/java/wtk2.5.2/lib/cldcapi11.jar +-overloadaggressively +-repackageclasses '' +-allowaccessmodification +-microedition +-printseeds + +-keep public class * extends javax.microedition.midlet.MIDlet ++
+We're simply keeping all classes that extend the MIDlet
class.
+
+The -microedition
option
+makes sure the class files are preverified for Java Micro Edition, producing
+compact StackMap
attributes. It is no longer necessary to run an
+external preverifier.
+
+Be careful if you do use the external preverify
tool on a platform
+with a case-insensitive filing system, such as Windows. Because this tool
+unpacks your processed jars, you should then use ProGuard's -dontusemixedcaseclassnames
+option.
+
+The -printseeds
option prints
+out which midlets exactly will be preserved.
+
+If applicable, you should add options for processing native +methods and resource files. +
+Note that you will still have to adapt the midlet jar size in the +corresponding jad file; ProGuard doesn't do that for you. + +
in.jar
:
++-injars in.jar +-outjars out.jar +-libraryjars /usr/local/java/javacard2.2.2/lib/api.jar +-dontwarn java.lang.Class +-overloadaggressively +-repackageclasses '' +-allowaccessmodification +-printseeds + +-keep public class * implements javacard.framework.Applet ++
+We're simply keeping all classes that implement the Applet
+interface.
+
+The -printseeds
option prints
+out which applets exactly will be preserved.
+
+
in.jar
:
++-injars in.jar +-outjars out.jar +-libraryjars /usr/local/java/jtv1.1/javatv.jar +-libraryjars /usr/local/java/cdc1.1/lib/cdc.jar +-libraryjars /usr/local/java/cdc1.1/lib/btclasses.zip +-overloadaggressively +-repackageclasses '' +-allowaccessmodification +-printseeds + +-keep public class * implements javax.tv.xlet.Xlet ++
+We're simply keeping all classes that implement the Xlet
interface.
+
+The -printseeds
option prints
+out which xlets exactly will be preserved.
+
+
in.jar
:
++-injars in.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar +-libraryjars /usr/local/java/servlet/servlet.jar +-printseeds + +-keep public class * implements javax.servlet.Servlet ++
+Keeping all servlets is very similar to keeping all applets. The servlet API +is not part of the standard run-time jar, so we're specifying it as a library. +Don't forget to use the right path name. +
+We're then keeping all classes that implement the Servlet
+interface. We're using the implements
keyword because it looks
+more familiar in this context, but it is equivalent to extends
,
+as far as ProGuard is concerned.
+
+The -printseeds
option prints
+out which servlets exactly will be preserved.
+
+If applicable, you should add options for processing native +methods, callback methods, enumerations, serializable +classes, bean classes, annotations, and resource +files. + +
in.jar
:
++-injars in.jar +-injars /usr/local/java/scala-2.9.1/lib/scala-library.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar + +-dontwarn scala.** + +-keepclasseswithmembers public class * { + public static void main(java.lang.String[]); +} + +-keep class * implements org.xml.sax.EntityResolver + +-keepclassmembers class * { + ** MODULE$; +} + +-keepclassmembernames class scala.concurrent.forkjoin.ForkJoinPool { + long eventCount; + int workerCounts; + int runControl; + scala.concurrent.forkjoin.ForkJoinPool$WaitQueueNode syncStack; + scala.concurrent.forkjoin.ForkJoinPool$WaitQueueNode spareStack; +} + +-keepclassmembernames class scala.concurrent.forkjoin.ForkJoinWorkerThread { + int base; + int sp; + int runState; +} + +-keepclassmembernames class scala.concurrent.forkjoin.ForkJoinTask { + int status; +} + +-keepclassmembernames class scala.concurrent.forkjoin.LinkedTransferQueue { + scala.concurrent.forkjoin.LinkedTransferQueue$PaddedAtomicReference head; + scala.concurrent.forkjoin.LinkedTransferQueue$PaddedAtomicReference tail; + scala.concurrent.forkjoin.LinkedTransferQueue$PaddedAtomicReference cleanMe; +} ++
+The configuration is essentially the same as +for processing applications, because Scala is +compiled to ordinary Java bytecode. However, the example processes the Scala +runtime library as well. The processed jar can be an order of magnitude +smaller and a few times faster than the original code (for the Scala code +examples, for instance). +
+The -dontwarn
option tells
+ProGuard not to complain about some artefacts in the Scala runtime, the way it
+is compiled by the scalac
compiler (at least in Scala 2.9.1 and
+older). Note that this option should always be used with care.
+
+The additional -keep
+options make sure that some classes and some fields that are accessed by means
+of introspection are not removed or renamed.
+
+If applicable, you should add options for processing native +methods, callback methods, enumerations, serializable +classes, bean classes, annotations, and resource +files. +
+-keepclasseswithmembernames class * { + native <methods>; +} ++
+Note the use of -keepclasseswithmembernames
.
+We don't want to preserve all classes or all native methods; we just want to
+keep the relevant names from being obfuscated.
+
+ProGuard doesn't look at your native code, so it won't automatically preserve +the classes or class members that are invoked by the native code. These are +entry points, which you'll have to specify explicitly. Callback methods are discussed below as a typical example. + +
-keep
options, something like
+the following option will keep the callback class and method:
++-keep class mypackage.MyCallbackClass { + void myCallbackMethod(java.lang.String); +} ++
+This will preserve the given class and method from being removed or renamed. + +
+-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} ++ +
+-keepclassmembers class * implements java.io.Serializable { + 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(); +} ++
+
+ The -keepclassmembers
+ option makes sure that any serialization methods are kept. By using this
+ option instead of the basic -keep
option, we're not
+ forcing preservation of all serializable classes, just preservation
+ of the listed members of classes that are actually used.
serialVersionUID
fields. The following options should
+ then be sufficient to ensure compatibility over time:
+
++-keepnames class * implements java.io.Serializable + +-keepclassmembers class * implements java.io.Serializable { + static final long serialVersionUID; + private static final java.io.ObjectStreamField[] serialPersistentFields; + !static !transient <fields>; + private void writeObject(java.io.ObjectOutputStream); + private void readObject(java.io.ObjectInputStream); + java.lang.Object writeReplace(); + java.lang.Object readResolve(); +} ++
+
+ The serialVersionUID
and serialPersistentFields
+ lines makes sure those fields are preserved, if they are present.
+ The <fields>
line preserves all non-static,
+ non-transient fields, with their original names. The introspection of the
+ serialization process and the de-serialization process will then find
+ consistent names.
serialVersionUID
fields. I imagine the
+ original code will then be hard to maintain, since the serial version UID
+ is then computed from a list of features the serializable class. Changing
+ the class ever so slightly may change the computed serial version UID. The
+ list of features is specified in the section on Stream
+ Unique Identifiers of Sun's Java
+ Object Serialization Specification. The following directives should at
+ least partially ensure compatibility with the original classes:
+
++-keepnames class * implements java.io.Serializable + +-keepclassmembers class * implements java.io.Serializable { + static final long serialVersionUID; + private static final java.io.ObjectStreamField[] serialPersistentFields; + !static !transient <fields>; + !private <fields>; + !private <methods>; + private void writeObject(java.io.ObjectOutputStream); + private void readObject(java.io.ObjectInputStream); + java.lang.Object writeReplace(); + java.lang.Object readResolve(); +} ++
+
+ The new options force preservation of the elements involved in the UID
+ computation. In addition, the user will have to manually specify all
+ interfaces of the serializable classes (using something like "-keep
+ interface MyInterface
"), since these names are also used when
+ computing the UID. A fast but sub-optimal alternative would be simply
+ keeping all interfaces with "-keep interface *
".
+
+Note that the above options may preserve more classes and class members
+than strictly necessary. For instance, a large number of classes may implement
+the Serialization
interface, yet only a small number may actually
+ever be serialized. Knowing your application and tuning the configuration
+often produces more compact results.
+
+
+-keep public class mypackage.MyBean { + public void setMyProperty(int); + public int getMyProperty(); +} + +-keep public class mypackage.MyBeanEditor ++
+If there are too many elements to list explicitly, wildcards in class names
+and method signatures might be helpful. This example preserves all possible
+setters and getters in classes in the package mybeans
:
+
+-keep class mybeans.** { + void set*(***); + void set*(int, ***); + + boolean is*(); + boolean is*(int); + + *** get*(); + *** get*(int); +} ++
+The '***
' wildcard matches any type (primitive or non-primitive,
+array or non-array). The methods with the 'int
' arguments matches
+properties that are lists.
+
+
+-keepattributes *Annotation* ++
+For brevity, we're specifying a wildcarded attribute name, which will match
+RuntimeVisibleAnnotations
,
+RuntimeInvisibleAnnotations
,
+RuntimeVisibleParameterAnnotations
,
+RuntimeInvisibleParameterAnnotations
, and
+AnnotationDefault
. Depending on the purpose of the processed
+code, you could refine this selection, for instance not keeping the run-time
+invisible annotations (which are only used at compile-time).
+
+Some code may make further use of introspection to figure out the enclosing +methods of anonymous inner classes. In that case, the corresponding attribute +has to be preserved as well: +
+-keepattributes EnclosingMethod ++ +
Driver
interface.
+Since they are often created dynamically, you may want to preserve any
+implementations that you are processing as entry points:
++-keep class * implements java.sql.Driver ++
+This option also gets rid of the note that ProGuard prints out about
+(java.sql.Driver)Class.forName
constructs, if you are
+instantiating a driver in your code (without necessarily implementing any
+drivers yourself).
+
+
ComponentUI
class. For some reason, these have to contain a
+static method createUI
, which the Swing API invokes using
+introspection. You should therefore always preserve the method as an entry
+point, for instance like this:
++-keep class * extends javax.swing.plaf.ComponentUI { + public static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent); +} ++
+This option also keeps the classes themselves. + +
rmic
tool. If that is not
+possible, you may want to try something like this:
++-keepattributes Exceptions + +-keep interface * extends java.rmi.Remote { + <methods>; +} + +-keep class * implements java.rmi.Remote { + <init>(java.rmi.activation.ActivationID, java.rmi.MarshalledObject); +} ++
+The first -keep
option keeps all your Remote interfaces and their
+methods. The second one keeps all the implementations, along with their
+particular RMI constructors, if any.
+
+The Exceptions
attribute has to be kept too, because the RMI
+handling code performs introspection to check whether the method signatures
+are compatible.
+
+
@Resource
. The container applies
+introspection, even accessing private class members directly. It typically
+constructs a resource name based on the type name and the class member name.
+We then have to avoid that such class members are removed or renamed:
++-keepclassmembers class * { + @javax.annotation.Resource *; +} ++
+The Spring framework has another similar annotation @Autowired
:
+
+-keepclassmembers class * { + @org.springframework.beans.factory.annotation.Autowired *; +} ++ +
+-adaptresourcefilenames **.properties,**.gif,**.jpg +-adaptresourcefilecontents **.properties,META-INF/MANIFEST.MF ++
+The -adaptresourcefilenames +option in this case renames properties files and image files in the processed +output, based on the obfuscated names of their corresponding class files (if +any). The -adaptresourcefilecontents +option looks for class names in properties files and in the manifest file, and +replaces these names by the obfuscated names (if any). You'll probably want to +adapt the filters to suit your application. + +
+If you're merging several input jars into a single output jar, you'll have to +pick one, typically by specifying filters: +
+-injars in1.jar +-injars in2.jar(!META-INF/MANIFEST.MF) +-injars in3.jar(!META-INF/MANIFEST.MF) +-outjars out.jar ++
+The filters will let ProGuard copy the manifest file from the first jar and +ignore any manifest files in the second and third input jars. Note that +ProGuard will leave the order of the files in the jars unchanged; manifest +files are not necessarily put first. + +
+-printmapping out.map + +-renamesourcefileattribute SourceFile +-keepattributes SourceFile,LineNumberTable ++
+We're keeping all source file attributes, but we're replacing their values by +the string "SourceFile". We could use any string. This string is already +present in all class files, so it doesn't take up any extra space. If you're +working with J++, you'll want to keep the "SourceDir" attribute as well. +
+We're also keeping the line number tables of all methods. +
+Whenever both of these attributes are present, the Java run-time environment +will include line number information when printing out exception stack traces. +
+The information will only be useful if we can map the obfuscated names back to
+their original names, so we're saving the mapping to a file
+out.map
. The information can then be used by the ReTrace tool to restore the original stack trace.
+
+
+mycompany.myapplication.MyMain +mycompany.myapplication.Foo +mycompany.myapplication.Bar +mycompany.myapplication.extra.FirstExtra +mycompany.myapplication.extra.SecondExtra +mycompany.util.FirstUtil +mycompany.util.SecondUtil ++
+Let's assume the class name mycompany.myapplication.MyMain
is the
+main application class that is kept by the configuration. All other class names
+can be obfuscated.
+
+By default, packages that contain classes that can't be renamed aren't renamed +either, and the package hierarchy is preserved. This results in obfuscated +class names like these: +
+mycompany.myapplication.MyMain +mycompany.myapplication.a +mycompany.myapplication.b +mycompany.myapplication.a.a +mycompany.myapplication.a.b +mycompany.a.a +mycompany.a.b ++
+The -flattenpackagehierarchy
+option obfuscates the package names further, by flattening the package
+hierarchy of obfuscated packages:
+
+-flattenpackagehierarchy 'myobfuscated' ++
+The obfuscated class names then look as follows: +
+mycompany.myapplication.MyMain +mycompany.myapplication.a +mycompany.myapplication.b +myobfuscated.a.a +myobfuscated.a.b +myobfuscated.b.a +myobfuscated.b.b ++
+Alternatively, the -repackageclasses
option
+obfuscates the entire packaging, by combining obfuscated classes into a single
+package:
+
+-repackageclasses 'myobfuscated' ++The obfuscated class names then look as follows: +
+mycompany.myapplication.MyMain +mycompany.myapplication.a +mycompany.myapplication.b +myobfuscated.a +myobfuscated.b +myobfuscated.c +myobfuscated.d ++
+Additionally specifying the -allowaccessmodification
+option allows access permissions of classes and class members to
+be broadened, opening up the opportunity to repackage all obfuscated classes:
+
+-repackageclasses 'myobfuscated' +-allowaccessmodification ++The obfuscated class names then look as follows: +
+mycompany.myapplication.MyMain +myobfuscated.a +myobfuscated.b +myobfuscated.c +myobfuscated.d +myobfuscated.e +myobfuscated.f ++
+The specified target package can always be the root package. For instance: +
+-repackageclasses '' +-allowaccessmodification ++The obfuscated class names are then the shortest possible names: +
+mycompany.myapplication.MyMain +a +b +c +d +e +f ++
+Note that not all levels of obfuscation of package names may be acceptable for +all code. Notably, you may have to take into account that your application may +contain resource files that have to be adapted. + +
+For example, this configuration removes invocations of the Android logging +methods: +
+-assumenosideeffects class android.util.Log { + public static boolean isLoggable(java.lang.String, int); + public static int v(...); + public static int i(...); + public static int w(...); + public static int d(...); + public static int e(...); +} ++
+The wildcards are a shortcut to match all versions of the methods. +
+Note that you generally can't remove logging code that uses
+System.out.println
, since you would be removing all invocations
+of java.io.PrintStream#println
, which could break your
+application. You can work around it by creating your own logging methods and
+let ProGuard remove those.
+
+
+-injars classes +-injars in1.jar +-injars in2.jar +-injars in3.jar +-outjars out.jar ++
+This configuration merges the processed versions of the files in the
+classes
directory and the three jars into a single output jar
+out.jar
.
+
+If you want to preserve the structure of your input jars (and/or wars, ears, +zips, or directories), you can specify an output directory (or a war, an ear, +or a zip). For example: +
+-injars in1.jar +-injars in2.jar +-injars in3.jar +-outjars out ++
+The input jars will then be reconstructed in the directory out
,
+with their original names.
+
+You can also combine archives into higher level archives. For example: +
+-injars in1.jar +-injars in2.jar +-injars in3.jar +-outjars out.war ++
+The other way around, you can flatten the archives inside higher level +archives into simple archives: +
+-injars in.war +-outjars out.jar ++
+This configuration puts the processed contents of all jars inside
+in.war
(plus any other contents of in.war
) into
+out.jar
.
+
+If you want to combine input jars (and/or wars, ears, zips, or directories)
+into output jars (and/or wars, ears, zips, or directories), you can group the
+-injars
and -outjars
options. For example:
+
+-injars base_in1.jar +-injars base_in2.jar +-injars base_in3.jar +-outjars base_out.jar + +-injars extra_in.jar +-outjars extra_out.jar ++
+This configuration puts the processed results of all base_in*.jar
+jars into base_out.jar
, and the processed results of the
+extra_in.jar
into extra_out.jar
. Note that only the
+order of the options matters; the additional whitespace is just for clarity.
+
+This grouping, archiving, and flattening can be arbitrarily complex. ProGuard +always tries to package output archives in a sensible way, reconstructing the +input entries as much as required. + +
+-injars in.jar(!images/**) +-outjars out.jar ++
+This configuration removes any files in the images
directory and
+its subdirectories.
+
+Such filters can be convenient for avoiding warnings about duplicate files in +the output. For example, only keeping the manifest file from a first input jar: +
+-injars in1.jar +-injars in2.jar(!META-INF/MANIFEST.MF) +-injars in3.jar(!META-INF/MANIFEST.MF) +-outjars out.jar ++
+Another useful application is speeding up the processing by ProGuard, by +disregarding a large number of irrelevant classes in the runtime library jar: +
+-libraryjars <java.home>/lib/rt.jar(java/**,javax/**) ++
+The filter makes ProGuard disregard com.sun.**
classes, for
+instance , which don't affect the processing of ordinary applications.
+
+It is also possible to filter the jars (and/or wars, ears, zips) themselves, +based on their names. For example: +
+-injars in(**/acme_*.jar;) +-outjars out.jar ++
+Note the semi-colon in the filter; the filter in front of it applies to jar
+names. In this case, only acme_*.jar
jars are read from the
+directory in
and its subdirectories. Filters for war names, ear
+names, and zip names can be prefixed with additional semi-colons. All types of
+filters can be combined. They are orthogonal.
+
+On the other hand, you can also filter the output, in order to control what +content goes where. For example: +
+-injars in.jar +-outjars code_out.jar(**.class) +-outjars resources_out.jar ++
+This configuration splits the processed output, sending **.class
+files to code_out.jar
, and all remaining files to
+resources_out.jar
.
+
+Again, the filtering can be arbitrarily complex, especially when combined with +grouping input and output. + +
+The easiest way is to specify your input jars (and/or wars, ears, zips, and +directories) and a single output directory. ProGuard will then reconstruct the +input in this directory, using the original jar names. For example, showing +just the input and output options: +
+-injars application1.jar +-injars application2.jar +-injars application3.jar +-outjars processed_applications ++
+After processing, the directory processed_applications
will
+contain processed versions of application jars, with their original names.
+
+
+-injars proguardgui.jar +-outjars proguardgui_out.jar +-injars proguard.jar +-outjars proguard_out.jar +-libraryjars <java.home>/lib/rt.jar +-applymapping proguard.map + +-keep public class proguard.gui.ProGuardGUI { + public static void main(java.lang.String[]); +} ++
+We're reading both unprocessed jars as input. Their processed contents will go
+to the respective output jars. The -applymapping
option then
+makes sure the ProGuard part of the code gets the previously produced
+obfuscation mapping. The final application will consist of the obfuscated
+ProGuard jar and the additional obfuscated GUI jar.
+
+The added code in this example is straightforward; it doesn't affect the
+original code. The proguard_out.jar
will be identical to the one
+produced in the initial processing step. If you foresee adding more complex
+extensions to your code, you should specify the options -useuniqueclassmembernames
,
+-dontshrink
, and -dontoptimize
in the
+original processing step. These options ensure that the obfuscated base
+jar will always remain usable without changes. You can then specify the base
+jar as a library jar:
+
+-injars proguardgui.jar +-outjars proguardgui_out.jar +-libraryjars proguard.jar +-libraryjars <java.home>/lib/rt.jar +-applymapping proguard.map + +-keep public class proguard.gui.ProGuardGUI { + public static void main(java.lang.String[]); +} ++ +
+-injars in.jar +-outjars out.jar +-libraryjars /usr/local/java/wtk2.5.2/lib/midpapi20.jar +-libraryjars /usr/local/java/wtk2.5.2/lib/cldcapi11.jar + +-dontshrink +-dontoptimize +-dontobfuscate + +-microedition ++
+We're not processing the input, just making sure the class files are
+preverified by targeting them at Java Micro Edition with the -microedition
option. Note
+that we don't need any -keep
options to specify entry points; all
+class files are simply preverified.
+
+
+-injars in.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar + +-dontshrink +-dontoptimize +-dontobfuscate + +-target 1.6 ++
+We're not processing the input, just retargeting the class files with the -target
option. They will
+automatically be preverified for Java 6 as a result. Note that we don't need
+any -keep
options to specify entry points; all class files are
+simply updated and preverified.
+
+
mypackage.MyApplication
:
++-injars in.jar +-libraryjars <java.home>/lib/rt.jar + +-dontoptimize +-dontobfuscate +-dontpreverify +-printusage + +-keep public class mypackage.MyApplication { + public static void main(java.lang.String[]); +} ++
+We're not specifying an output jar, just printing out some results. We're +saving some processing time by skipping the other processing steps. +
+The java compiler inlines primitive constants and String constants
+(static final
fields). ProGuard would therefore list such fields
+as not being used in the class files that it analyzes, even if they are
+used in the source files. We can add a -keepclassmembers
option
+that keeps those fields a priori, in order to avoid having them listed:
+
+-keepclassmembers class * { + static final % *; + static final java.lang.String *; +} ++ +
+-injars in.jar + +-dontshrink +-dontoptimize +-dontobfuscate +-dontpreverify + +-dump ++
+Note how we don't need to specify the Java run-time jar, because we're not +processing the input jar at all. + +
+You can find a set of such predefined annotations in the directory
+examples/annotations/lib
in the ProGuard distribution.
+The annotation classes are defined in annotations.jar
. The
+corresponding ProGuard configuration (or meta-configuration, if you prefer)
+is specified in annotations.pro
. With these files, you can start
+annotating your code. For instance, a java source file
+Application.java
can be annotated as follows:
+
+@KeepApplication +public class Application { + .... +} ++
+The ProGuard configuration file for the application can then be simplified by +leveraging off these annotations: +
+-injars in.jar +-outjars out.jar +-libraryjars <java.home>/lib/rt.jar + +-include lib/annotations.pro ++
+The annotations are effectively replacing the application-dependent
+-keep
options. You may still wish to add traditional
+-keep
options for processing native
+methods, enumerations, serializable classes, and annotations.
+
+The directory examples/annotations
contains more examples that
+illustrate some of the possibilities.
+
+
+
+Before you can use the proguard
task, you have to make sure
+Gradle can find it in its class path at build time. One way is to add the
+following line to your build.gradle
file:
+
+ +
+buildscript { + repositories { + flatDir dirs: '/usr/local/java/proguard/lib' + } + dependencies { + classpath ':proguard' + } +} ++
+ +Please make sure the class path is set correctly for your system. +
+ +You can then define a task: +
+
+task myProguardTask(type: proguard.gradle.ProGuardTask) { + ..... +} ++
+ +The embedded configuration is much like a standard ProGuard configuration. +Notable similarities and differences: +
+You can find some sample build files in the examples/gradle
+directory of the ProGuard distribution.
+
+If you prefer a more verbose configuration derived from the Ant task, you can +import the Ant task as a Gradle task. + +
configuration
+ fileinjars
+ class_pathoutjars
+ class_pathlibraryjars
+ class_pathskipnonpubliclibraryclasses
dontskipnonpubliclibraryclassmembers
keepdirectories
+ ['directory_filter']target
+ 'version'forceprocessing
keep
+ [modifier,...]
+ class_specificationkeepclassmembers
+ [modifier,...]
+ class_specificationkeepclasseswithmembers
+ [modifier,...]
+ class_specificationkeepnames
+ class_specificationkeepclassmembernames
+ class_specificationkeepclasseswithmembernames
+ class_specificationprintseeds
+ [file]keep
+ commands, to the standard output or to the given file.dontshrink
printusage
+ [file]whyareyoukeeping
+ class_specificationdontoptimize
optimizations
'optimization_filter'optimizationpasses
+ nassumenosideeffects
+ class_specificationallowaccessmodification
mergeinterfacesaggressively
dontobfuscate
printmapping
+ [file]applymapping
+ fileobfuscationdictionary
+ fileclassobfuscationdictionary
+ filepackageobfuscationdictionary
+ fileoverloadaggressively
useuniqueclassmembernames
dontusemixedcaseclassnames
keeppackagenames
['package_filter']flattenpackagehierarchy
+ 'package_name'repackageclasses
+ ['package_name']keepattributes
['attribute_filter']keepparameternames
renamesourcefileattribute
+ ['string']SourceFile
+ attributes.adaptclassstrings
+ ['class_filter']adaptresourcefilenames
+ ['file_filter']adaptresourcefilecontents
+ ['file_filter']dontpreverify
microedition
verbose
dontnote
'class_filter'dontwarn
'class_filter'ignorewarnings
printconfiguration
+ [file]dump
+ [file]files(Object)
, etc.
++In addition, they can have ProGuard-style filters, specified as +comma-separated named arguments after the file: + +
filter:
+ 'file_filter'jarfilter:
+ 'file_filter'warfilter:
+ 'file_filter'earfilter:
+ 'file_filter'zipfilter:
+ 'file_filter'file(Object)
, etc.
+
+In Gradle, file names (any strings really) in double quotes can contain
+properties or code inside ${...}
. These are automatically
+expanded.
+
+Like in ProGuard-style configurations, the names can also contain Java system +properties, delimited by angular brackets, '<' and '>'. +These properties are automatically replaced by their corresponding values. +
+For example, <java.home>/lib/rt.jar
is automatically
+expanded to something like /usr/local/java/jdk/jre/lib/rt.jar
.
+Similarly, <user.home>
is expanded to the user's home
+directory, and <user.dir>
is expanded to the current
+working directory.
+
+
allowshrinking:
+ boolean
+ (default = false)allowoptimization:
+ boolean
+ (default = false)allowobfuscation:
+ boolean
+ (default = false)+keep 'public class mypackage.MyMainClass { \ + public static void main(java.lang.String[]); \ +}' +
+keep access: 'public', + name: 'mypackage.MyMainClass', { + method access: 'public static', + type: 'void', + name: 'main', + parameters: 'java.lang.String[]' +} +
+ +The ProGuard-style class +specification is described on the traditional Usage page. +
+A Gradle-style class specification can have the following named arguments: + +
access:
'access_modifiers'annotation:
'annotation_name'type:
'type'name:
'class_name'extendsannotation:
'annotation_name''extends':
'class_name''implements':
'class_name'+ +
field
field_constraintsmethod
method_constraintsconstructor
constructor_constraintsaccess:
'access_modifiers''annotation':
'annotation_name'type:
'type'parameters
argument is specified.name:
'name'parameters:
'parameters'type
argument is
+ specified.+A class member setting doesn't have a closure. + +
+
+ant.project.basedir = '../..' + +ant.taskdef(resource: 'proguard/ant/task.properties', + classpath: '/usr/local/java/proguard/lib/proguard.jar') ++
+ +Gradle automatically converts the elements and attributes to Groovy methods, +so converting the configuration is essentially mechanical. The one-on-one +mapping can be useful, but the resulting configuration is more verbose. For +instance: +
+task proguard << { + ant.proguard(printmapping: 'proguard.map', + overloadaggressively: 'on', + repackageclasses: '', + renamesourcefileattribute: 'SourceFile') { + + injar(file: 'application.jar') + injar(file: 'gui.jar', filter: '!META-INF/**') + + ..... + } +} ++
+ +
lib
directory of the
+ProGuard distribution. To run the ProGuard graphical user interface, just type:
+
+java -jar proguardgui.jar [-nosplash]
[configuration_file]
+
bin
directory contains some short Linux and
+Windows scripts containing this command. The GUI will pop up in a window. With
+the -nosplash
option, you can switch off the short opening
+animation. If you have specified a ProGuard configuration file, it will be
+loaded. The GUI works like a wizard. You can edit the configuration and
+execute ProGuard through a few tabs:
++ +
ProGuard | +Optionally load an existing configuration file. |
Input/Output | +Specify the program jars and library jars. |
Shrinking | +Specify the shrinking options. |
Obfuscation | +Specify the obfuscation options. |
Optimization | +Specify the optimization options. |
Information | +Specify some options to get information. |
Process | +View and save the resulting configuration, and run ProGuard. |
+ +In addition, there is a tab to execute ReTrace interactively: +
+ +
ReTrace | +Set up and run ReTrace, to de-obfuscate stack traces. |
+ +You can freely toggle between the tabs by means of the buttons on the +left-hand side of the window, or by means of the Previous and +Next buttons at the bottom of the tabs. Tool tips briefly explain the +purpose of the numerous options and text fields, although a basic +understanding of the shrinking/optimization/obfuscation/preverification +process is assumed. Please refer to the Introduction of this manual. +
+ +
+ +
Load configuration... | +opens a file chooser to load an existing ProGuard configuration + file. |
+ +If you don't want to load an existing configuration, you can just continue +creating a new configuration from scratch. +
+ +
+ +Each of these lists can be edited by means of a couple of buttons on the +right-hand side: +
+ +
Add input... | opens a file chooser to add an + input entry to the list of program jars. |
Add output... | opens a file chooser to add an + output entry to the list of program jars. |
Add... | +opens a file chooser to add an entry to the list of library + jars. |
Edit... | +opens a file chooser to edit the selected entry in the list. |
Filter... | +opens a text entry field to add or edit the filters of the selected + entries in the list. |
Remove | +removes the selected entries from the list. |
Move up | +moves the selected entries one position up the list. |
Move down | +moves the selected entries one position down the list. |
Move to libraries | +moves the selected entries in the list of program jars to the list of + library jars. |
Move to program | +moves the selected entries in the list of library jars to the list of + program jars. |
+ +Filters allow to filter files based on their names. One can specify filters +for class file names and resource file names, for jar file names, for war file +names, for ear file names, and for zip file names. Multiple entries in the +program list only make sense when combined with filters; each output file is +written to the first entry with a matching filter. +
+ +Input entries that are currently not readable are colored red. +
+ +The order of the entries in each list may matter, as the first occurrence of +any duplicate entries gets precedence, just as in conventional class paths. +
+ +Corresponding configuration options: +
+ +
+ +The fixed lists contain predefined entries that are typically useful for many +applications. Each of these entries can be toggled by means of a check box. +The text field following each entry allows to constrain the applicable classes +by means of a comma-separated list of wildcarded, fully-qualified class +names. The default is "*", which means that all input classes of the +corresponding type are considered. +
+ +For example, checking the Applications entry and filling in +"myapplications.**" after it would mean: keep all classes that have main +methods in the "myapplications" package and all of its subpackages. +
+ +The variable list at the bottom allows to define additional entries +yourself. The list can be edited by means of a couple of buttons on the +right-hand side: +
+ +
Add... | +opens a window to add a new entry to the list. |
Edit... | +opens a window to edit the selected entry in the list. |
Remove | +removes the selected entries from the list. |
Move up | +moves the selected entries one position up the list. |
Move down | +moves the selected entries one position down the list. |
+ +The interface windows allow to specify classes, fields, and methods. They +contain text fields and check boxes to constrain these items. They have +Ok and Cancel buttons to apply or to cancel the operation. +
+
+For example, your application may be creating some classes dynamically using
+Class.forName
. You should then specify them here, so they are kept
+by their original names. Press the Add... button to open the class
+window. Fill out the fully-qualified class name in the Code text field,
+and press the Ok button. Repeat this for all required classes. Wildcards
+can be helpful to specify a large number of related classes in one go. If you
+want to specify all implementations of a certain interface, fill out the
+fully qualified interface name in the Extends/implements class instead.
+
+ +For more advanced settings, it is advisable to become familiar with ProGuard's +configuration options through the Usage section and +the Examples section. We'll suffice with a brief +overview of the three dialogs provided by the GUI. +
+ +The keep class dialog appears when adding or editing new special keep +entries. It has text fields and selections for specifying and constraining +classes and class members to keep. The Advanced options / Basic +options button at the bottom of the dialog allows to toggle showing the +advanced options. + +
+ +The keep field dialog appears when adding or editing fields within the +above dialog. It has text fields and selections for specifying and +constraining fields to keep. Again, the Advanced options / Basic +options button at the bottom of the dialog allows to toggle showing the +advanced options. + +
+ +Similarly, the keep method dialog appears when adding or editing +methods within the keep class dialog. It has text fields and selections for +specifying and constraining methods to keep. Again, the Advanced +options / Basic options button at the bottom of the dialog allows +to toggle showing the advanced options. + +
+ +Corresponding configuration options: +
+ +
+ +The lists are manipulated in the same way as in the Shrinking Tab. +
+ +Corresponding configuration options: +
+ +
+ +The lists are manipulated in much the same way as in the Shrinking Tab. +
+ +Corresponding configuration options: +
+ +
+ +Corresponding configuration options: +
+ +
+ +
View configuration | +displays the current ProGuard configuration in the console. |
Save configuration... | +opens a file chooser to save the current ProGuard + configuration. |
Process! | +executes ProGuard with the current configuration. |
+ +
+ +
Load stack trace... | +opens a file chooser to load an obfuscated stack trace. |
ReTrace! | +executes ReTrace with the current settings. |
+Each of these steps is optional. For instance, ProGuard can also be used to +just list dead code in an application, or to preverify class files for +efficient use in Java 6. +
+ +
Input jars | ++ | |||||||
+ | Shrunk code | ++ | ||||||
+ | Optim. code | ++ | Output jars | +|||||
- shrink → | +- optimize → | +- obfuscate → | +Obfusc. code | +- preverify → | +||||
Library jars | +------------------------------- (unchanged) -------------------------------→ | +Library jars | +
+ +ProGuard first reads the input jars (or wars, ears, zips, or +directories). It then subsequently shrinks, optimizes, obfuscates, and +preverifies them. You can optionally let ProGuard perform multiple +optimization passes. ProGuard writes the processed results to one or +more output jars (or wars, ears, zips, or directories). The input may +contain resource files, whose names and contents can optionally be updated to +reflect the obfuscated class names. +
+ProGuard requires the library jars (or wars, ears, zips, or +directories) of the input jars to be specified. These are essentially the +libraries that you would need for compiling the code. ProGuard uses them to +reconstruct the class dependencies that are necessary for proper processing. +The library jars themselves always remain unchanged. You should still put them +in the class path of your final application. + +
+The Usage section of this manual describes the
+necessary -keep
options and
+the Examples section provides plenty of examples.
+
+
Class.forName()
constructs may
+refer to any class at run-time. It is generally impossible to compute which
+classes have to be preserved (with their original names), since the class
+names might be read from a configuration file, for instance. You therefore
+have to specify them in your ProGuard configuration, with the same
+simple -keep
options.
++However, ProGuard will already detect and handle the following cases for you: + +
Class.forName("SomeClass")
SomeClass.class
SomeClass.class.getField("someField")
SomeClass.class.getDeclaredField("someField")
SomeClass.class.getMethod("someMethod", new Class[] {})
SomeClass.class.getMethod("someMethod", new Class[] { A.class })
SomeClass.class.getMethod("someMethod", new Class[] { A.class, B.class })
SomeClass.class.getDeclaredMethod("someMethod", new Class[] {})
SomeClass.class.getDeclaredMethod("someMethod", new Class[] { A.class })
SomeClass.class.getDeclaredMethod("someMethod", new Class[] { A.class, B.class })
AtomicIntegerFieldUpdater.newUpdater(SomeClass.class, "someField")
AtomicLongFieldUpdater.newUpdater(SomeClass.class, "someField")
AtomicReferenceFieldUpdater.newUpdater(SomeClass.class, SomeType.class, "someField")
+Furthermore, ProGuard will offer some suggestions if keeping some classes or
+class members appears necessary. For example, ProGuard will note constructs
+like "(SomeClass)Class.forName(variable).newInstance()
". These
+might be an indication that the class or interface SomeClass
+and/or its implementations may need to be preserved. You can then adapt your
+configuration accordingly.
+
+For proper results, you should at least be somewhat familiar with the code +that you are processing. Obfuscating code that performs a lot of reflection +may require trial and error, especially without the necessary information +about the internals of the code. + +
+
myObject.myMethod()
if that call
+ wouldn't have any effect. It ignores the possibility that
+ myObject
might be null, causing a NullPointerException. In
+ some way this is a good thing: optimized code may throw fewer exceptions.
+ Should this entire assumption be false, you'll have to switch off
+ optimization using the -dontoptimize
option.-dontoptimize
option.a.class
", "b.class
", etc. If a package contains
+ a large number of classes, ProGuard may also write out
+ "aux.class
". Inconveniently, Windows refuses to create
+ files with this reserved name (among a few other names). It's generally
+ better to write the output to a jar, in order to avoid such problems.-dontoptimize
option. For
+more fine-grained control over individual optimizations, experts can use the
+-optimizations
option,
+with a filter based on the optimization names listed below. The filter works
+like any filter in ProGuard.
++ +The following wildcards are supported: + +
? |
+ matches any single character in an optimization name. |
* |
+ matches any part of an optimization name. |
+
+For example,
+"code/simplification/variable,code/simplification/arithmetic
"
+only performs the two specified peephole optimizations.
+
+
+For example, "!method/propagation/*
" performs all optimizations,
+except the ones that propagate values between methods.
+
+
+For example,
+"!code/simplification/advanced,code/simplification/*
" only
+performs all peephole optimizations.
+
+Some optimizations necessarily imply other optimizations. These are then +indicated. Note that the list is likely to change over time, as optimizations +are added and reorganized. +
+ +
class/marking/final
class/merging/vertical
class/merging/horizontal
code/removal/advanced
)field/removal/writeonly
field/marking/private
code/simplification/advanced
)field/propagation/value
method/marking/private
code/removal/advanced
)method/marking/static
method/marking/final
code/removal/advanced
)method/removal/parameter
code/simplification/advanced
)method/propagation/parameter
code/simplification/advanced
)method/propagation/returnvalue
method/inlining/short
method/inlining/unique
method/inlining/tailrecursion
code/merging
code/simplification/variable
code/simplification/arithmetic
code/simplification/cast
code/simplification/field
code/removal/simple
)code/simplification/branch
code/simplification/string
code/removal/advanced
)code/simplification/advanced
code/removal/exception
)code/removal/advanced
code/removal/exception
)code/removal/simple
code/removal/variable
code/removal/exception
code/allocation/variable
+
+ProGuard also provides some unofficial settings to control optimizations, that
+may disappear in future versions. These are Java system properties, which
+can be set as JVM arguments (with -D.....)
:
+
maximum.inlined.code.length
(default = 8 bytes)maximum.resulting.code.length
(default = 8000 bytes
+ for JSE, 2000 bytes for JME)optimize.conservatively
(default = unset)NullPointerException
,
+ ArrayIndexOutOfBoundsException
, or
+ ClassCastException
, without any other useful purposes. By
+ default, ProGuard may just discard such seemingly useless instructions,
+ resulting in better optimization of most common code.java -jar proguard.jar
options ...
++ Typically: +
+java -jar proguard.jar @myconfig.pro
+
+ +
@ filename |
+
+Short for '-include filename'. |
+
-include
+ filename |
+
+Read configuration options from the given file. | +
-basedirectory
+ directoryname |
+
+Specifies the base directory for subsequent relative file names. | +
-injars
+ class_path |
+Specifies the program jars (or wars, ears, zips, or directories). | +
-outjars
+ class_path |
+Specifies the names of the output jars (or wars, ears, zips, or + directories). | +
-libraryjars
+ class_path |
+Specifies the library jars (or wars, ears, zips, or directories). | +
-skipnonpubliclibraryclasses |
+Ignore non-public library classes. | +
-dontskipnonpubliclibraryclasses |
+Don't ignore non-public library classes (the default). | +
-dontskipnonpubliclibraryclassmembers |
+Don't ignore package visible library class members. | +
-keepdirectories
+ [directory_filter] |
+Keep the specified directories in the output jars (or wars, ears, zips, or + directories). | +
-target
+ version |
+Set the given version number in the processed classes. | +
-forceprocessing |
+Process the input, even if the output seems up to date. | +
-keep
+ [,modifier,...]
+ class_specification |
+Preserve the specified classes and class members. | + +
-keepclassmembers
+ [,modifier,...]
+ class_specification |
+Preserve the specified class members, if their classes are preserved as + well. | +
-keepclasseswithmembers
+ [,modifier,...]
+ class_specification |
+Preserve the specified classes and class members, if all of the + specified class members are present. | +
-keepnames
+ class_specification |
+Preserve the names of the specified classes and class members (if + they aren't removed in the shrinking step). | +
-keepclassmembernames
+ class_specification |
+Preserve the names of the specified class members (if they aren't removed + in the shrinking step). | +
-keepclasseswithmembernames
+ class_specification |
+Preserve the names of the specified classes and class members, if + all of the specified class members are present (after the shrinking + step). | +
-printseeds
+ [filename] |
+List classes and class members matched by the various -keep
+ options, to the standard output or to the given file. |
+
-dontshrink |
+Don't shrink the input class files. | +
-printusage
+ [filename] |
+List dead code of the input class files, to the standard output or to the + given file. | +
-whyareyoukeeping
+ class_specification |
+Print details on why the given classes and class members are being kept in + the shrinking step. | +
-dontoptimize |
+Don't optimize the input class files. | +
-optimizations
+ optimization_filter |
+The optimizations to be enabled and disabled. | +
-optimizationpasses
+ n |
+The number of optimization passes to be performed. | +
-assumenosideeffects
+ class_specification |
+Assume that the specified methods don't have any side effects, while + optimizing. | +
-allowaccessmodification |
+Allow the access modifiers of classes and class members to be modified, + while optimizing. | +
-mergeinterfacesaggressively |
+Allow any interfaces to be merged, while optimizing. | +
-dontobfuscate |
+Don't obfuscate the input class files. | +
-printmapping
+ [filename] |
+Print the mapping from old names to new names for classes and class members + that have been renamed, to the standard output or to the given file. | +
-applymapping
+ filename |
+Reuse the given mapping, for incremental obfuscation. | +
-obfuscationdictionary
+ filename |
+Use the words in the given text file as obfuscated field names and method names. | +
-classobfuscationdictionary
+ filename |
+Use the words in the given text file as obfuscated class names. | +
-packageobfuscationdictionary
+ filename |
+Use the words in the given text file as obfuscated package names. | +
-overloadaggressively |
+Apply aggressive overloading while obfuscating. | +
-useuniqueclassmembernames |
+Ensure uniform obfuscated class member names for subsequent incremental + obfuscation. |
-dontusemixedcaseclassnames |
+Don't generate mixed-case class names while obfuscating. | +
-keeppackagenames
+ [package_filter] |
+Keep the specified package names from being obfuscated. | +
-flattenpackagehierarchy
+ [package_name] |
+Repackage all packages that are renamed into the single given parent + package. | +
-repackageclasses
+ [package_name] |
+Repackage all class files that are renamed into the single given + package. | +
-keepattributes
+ [attribute_filter] |
+Preserve the given optional attributes; typically
+ Exceptions , InnerClasses ,
+ Signature , Deprecated ,
+ SourceFile , SourceDir ,
+ LineNumberTable ,
+ LocalVariableTable , LocalVariableTypeTable ,
+ Synthetic , EnclosingMethod , and
+ *Annotation* . |
+
-keepparameternames |
+Keep the parameter names and types of methods that are kept. | +
-renamesourcefileattribute
+ [string] |
+Put the given constant string in the SourceFile
+ attributes. |
+
-adaptclassstrings
+ [class_filter] |
+Adapt string constants in the specified classes, based on the obfuscated + names of any corresponding classes. | +
-adaptresourcefilenames
+ [file_filter] |
+Rename the specified resource files, based on the obfuscated names of the + corresponding class files. | +
-adaptresourcefilecontents
+ [file_filter] |
+Update the contents of the specified resource files, based on the + obfuscated names of the processed classes. | +
-dontpreverify |
+Don't preverify the processed class files. | +
-microedition |
+Target the processed class files at Java Micro Edition. | +
-verbose |
+Write out some more information during processing. | +
-dontnote
+ [class_filter] |
+Don't print notes about potential mistakes or omissions in the + configuration. | +
-dontwarn
+ [class_filter] |
+Don't warn about unresolved references at all. | +
-ignorewarnings |
+Print warnings about unresolved references, but continue processing + anyhow. | +
-printconfiguration
+ [filename] |
+Write out the entire configuration in traditional ProGuard style, to the + standard output or to the given file. | +
-dump
+ [filename] |
+Write out the internal structure of the processed class files, to the + standard output or to the given file. | +
+Notes: +
+ +
Keep
OptionsKeep | +From being removed or renamed | +From being renamed | +
---|---|---|
Classes and class members | +-keep |
+-keepnames |
+
Class members only | +-keepclassmembers |
+-keepclassmembernames |
+
Classes and class members, if class members present | +-keepclasseswithmembers |
+-keepclasseswithmembernames |
+
+ +
allowshrinking |
+The entry points specified in the keep tag may be shrunk. | +
allowoptimization |
+The entry points specified in the keep tag may be optimized. | +
allowobfuscation |
+The entry points specified in the keep tag may be obfuscated. | +
+ +
+[@annotationtype] [[!]public|final|abstract ...] [!]interface|class classname + [extends|implements [@annotationtype] classname] +[{ + [@annotationtype] [[!]public|private|protected|static|volatile|transient ...] <fields> | + (fieldtype fieldname); + [@annotationtype] [[!]public|private|protected|static|synchronized|native|abstract|strictfp ...] <methods> | + <init>(argumenttype,...) | + classname(argumenttype,...) | + (returntype methodname(argumenttype,...)); + [@annotationtype] [[!]public|private|protected|static ... ] *; + ... +}] ++
+Notes: +
?
' for a
+ single character, '*
' for any number of characters
+ (but not the package separator), '**
' for any number
+ of (any) characters, '%
' for any primitive type,
+ '***
' for any type, and '...
' for any number of arguments.?
' for a single character and '*
'
+ for any number of characters.+-printmapping proguard.map + +-renamesourcefileattribute ProGuard +-keepattributes SourceFile,LineNumberTable ++
+
+Now assume the processed application throws an exception, and we have saved the
+stack trace in proguard.trace
, shown below. Of course, in real
+life ProGuard rarely throws exceptions, so this is a purposely generated
+exception. :)
+
+
+Exception in thread "main" java.lang.Error: Random exception + at pro.bY.a(ProGuard:576) + at pro.bO.a(ProGuard:431) + at pro.bj.a(ProGuard:145) + at pro.bY.a(ProGuard:522) + at pro.bj.a(ProGuard:129) + at pro.bN.a(ProGuard:125) + at pro.bY.a(ProGuard:251) + at pro.bY.a(ProGuard:229) + at pro.l.a(ProGuard:55) + at pro.bo.b(ProGuard:405) + at pro.ci.a(ProGuard:51) + at pro.bo.a(ProGuard:356) + at pro.be.a(ProGuard:109) + at pro.bo.a(ProGuard:356) + at pro.be.a(ProGuard:186) + at pro.bg.a(ProGuard:369) + at pro.bY.a(ProGuard:286) + at pro.bh.a(ProGuard:55) + at pro.bg.b(ProGuard:408) + at pro.bY.a(ProGuard:190) + at pro.bg.a(ProGuard:369) + at pro.M.a(ProGuard:110) + at pro.bY.a(ProGuard:449) + at pro.M.a(ProGuard:99) + at pro.bo.a(ProGuard:372) + at pro.bY.a(ProGuard:649) + at pro.bY.a(ProGuard:112) + at pro.P.a(ProGuard:66) + at pro.p.a(ProGuard:83) + at pro.bU.a(ProGuard:69) + at pro.bo.a(ProGuard:356) + at pro.J.a(ProGuard:149) + at pro.I.a(ProGuard:49) + at pro.J.a(ProGuard:105) + at pro.cf.c(ProGuard:370) + at pro.cf.a(ProGuard:317) + at pro.bc.a(ProGuard:55) + at proguard.ProGuard.a(ProGuard:363) + at proguard.ProGuard.c(ProGuard:187) + at proguard.ProGuard.b(ProGuard:385) + at proguard.ProGuard.main(ProGuard:429) ++
+ +We can then use the following command to recover the stack trace: +
+java -jar retrace.jar proguard.map proguard.trace ++
+ +The output will look as follows: +
+Exception in thread "main" java.lang.Error: Random exception + at proguard.shrink.UsageMarker.visitInstruction(ProGuard:576) + at proguard.classfile.instruction.GenericInstruction.accept(ProGuard:431) + at proguard.classfile.CodeAttrInfo.instructionsAccept(ProGuard:145) + at proguard.shrink.UsageMarker.visitCodeAttrInfo(ProGuard:522) + at proguard.classfile.CodeAttrInfo.accept(ProGuard:129) + at proguard.classfile.ProgramMemberInfo.attributesAccept(ProGuard:125) + at proguard.shrink.UsageMarker.visitMemberInfo(ProGuard:251) + at proguard.shrink.UsageMarker.visitProgramMethodInfo(ProGuard:229) + at proguard.classfile.ProgramMethodInfo.accept(ProGuard:55) + at proguard.classfile.ProgramClassFile.methodAccept(ProGuard:405) + at proguard.classfile.visitor.NamedMethodVisitor.visitProgramClassFile(ProGuard:51) + at proguard.classfile.ProgramClassFile.accept(ProGuard:356) + at proguard.classfile.visitor.ClassFileUpDownTraveler.visitProgramClassFile(ProGuard:109) + at proguard.classfile.ProgramClassFile.accept(ProGuard:356) + at proguard.classfile.visitor.ClassFileUpDownTraveler.visitLibraryClassFile(ProGuard:186) + at proguard.classfile.LibraryClassFile.accept(ProGuard:369) + at proguard.shrink.UsageMarker.visitLibraryMethodInfo(ProGuard:286) + at proguard.classfile.LibraryMethodInfo.accept(ProGuard:55) + at proguard.classfile.LibraryClassFile.methodsAccept(ProGuard:408) + at proguard.shrink.UsageMarker.visitLibraryClassFile(ProGuard:190) + at proguard.classfile.LibraryClassFile.accept(ProGuard:369) + at proguard.classfile.ClassCpInfo.referencedClassAccept(ProGuard:110) + at proguard.shrink.UsageMarker.visitClassCpInfo(ProGuard:449) + at proguard.classfile.ClassCpInfo.accept(ProGuard:99) + at proguard.classfile.ProgramClassFile.constantPoolEntryAccept(ProGuard:372) + at proguard.shrink.UsageMarker.markCpEntry(ProGuard:649) + at proguard.shrink.UsageMarker.visitProgramClassFile(ProGuard:112) + at proguard.classfile.visitor.VariableClassFileVisitor.visitProgramClassFile(ProGuard:66) + at proguard.classfile.visitor.MultiClassFileVisitor.visitProgramClassFile(ProGuard:83) + at proguard.classfile.visitor.FilteredClassFileVisitor.visitProgramClassFile(ProGuard:69) + at proguard.classfile.ProgramClassFile.accept(ProGuard:356) + at proguard.classfile.ClassPool.classFileAccept(ProGuard:149) + at proguard.classfile.visitor.NamedClassFileVisitor.visitClassPool(ProGuard:49) + at proguard.classfile.ClassPool.accept(ProGuard:105) + at proguard.KeepCommand.executeShrinkingPhase(ProGuard:370) + at proguard.KeepCommand.execute(ProGuard:317) + at proguard.CompoundCommand.execute(ProGuard:55) + at proguard.ProGuard.executeCommands(ProGuard:363) + at proguard.ProGuard.shrink(ProGuard:187) + at proguard.ProGuard.execute(ProGuard:385) + at proguard.ProGuard.main(ProGuard:429) ++ +
+java -jar retrace.jar -verbose proguard.map proguard.trace ++
+ +The output will then look as follows: +
+Exception in thread "main" java.lang.Error: Random exception + at proguard.shrink.UsageMarker.void visitInstruction(proguard.classfile.ClassFile,proguard.classfile.instruction.Instruction)(ProGuard:576) + at proguard.classfile.instruction.GenericInstruction.void accept(proguard.classfile.ClassFile,proguard.classfile.instruction.InstructionVisitor)(ProGuard:431) + at proguard.classfile.CodeAttrInfo.void instructionsAccept(proguard.classfile.ClassFile,proguard.classfile.instruction.InstructionVisitor)(ProGuard:145) + at proguard.shrink.UsageMarker.void visitCodeAttrInfo(proguard.classfile.ClassFile,proguard.classfile.CodeAttrInfo)(ProGuard:522) + at proguard.classfile.CodeAttrInfo.void accept(proguard.classfile.ClassFile,proguard.classfile.visitor.AttrInfoVisitor)(ProGuard:129) + at proguard.classfile.ProgramMemberInfo.void attributesAccept(proguard.classfile.ProgramClassFile,proguard.classfile.visitor.AttrInfoVisitor)(ProGuard:125) + at proguard.shrink.UsageMarker.void visitMemberInfo(proguard.classfile.ProgramClassFile,proguard.classfile.ProgramMemberInfo)(ProGuard:251) + at proguard.shrink.UsageMarker.void visitProgramMethodInfo(proguard.classfile.ProgramClassFile,proguard.classfile.ProgramMethodInfo)(ProGuard:229) + at proguard.classfile.ProgramMethodInfo.void accept(proguard.classfile.ProgramClassFile,proguard.classfile.visitor.MemberInfoVisitor)(ProGuard:55) + at proguard.classfile.ProgramClassFile.void methodAccept(proguard.classfile.visitor.MemberInfoVisitor,java.lang.String,java.lang.String)(ProGuard:405) + at proguard.classfile.visitor.NamedMethodVisitor.void visitProgramClassFile(proguard.classfile.ProgramClassFile)(ProGuard:51) + at proguard.classfile.ProgramClassFile.void accept(proguard.classfile.visitor.ClassFileVisitor)(ProGuard:356) + at proguard.classfile.visitor.ClassFileUpDownTraveler.void visitProgramClassFile(proguard.classfile.ProgramClassFile)(ProGuard:109) + at proguard.classfile.ProgramClassFile.void accept(proguard.classfile.visitor.ClassFileVisitor)(ProGuard:356) + at proguard.classfile.visitor.ClassFileUpDownTraveler.void visitLibraryClassFile(proguard.classfile.LibraryClassFile)(ProGuard:186) + at proguard.classfile.LibraryClassFile.void accept(proguard.classfile.visitor.ClassFileVisitor)(ProGuard:369) + at proguard.shrink.UsageMarker.void visitLibraryMethodInfo(proguard.classfile.LibraryClassFile,proguard.classfile.LibraryMethodInfo)(ProGuard:286) + at proguard.classfile.LibraryMethodInfo.void accept(proguard.classfile.LibraryClassFile,proguard.classfile.visitor.MemberInfoVisitor)(ProGuard:55) + at proguard.classfile.LibraryClassFile.void methodsAccept(proguard.classfile.visitor.MemberInfoVisitor)(ProGuard:408) + at proguard.shrink.UsageMarker.void visitLibraryClassFile(proguard.classfile.LibraryClassFile)(ProGuard:190) + at proguard.classfile.LibraryClassFile.void accept(proguard.classfile.visitor.ClassFileVisitor)(ProGuard:369) + at proguard.classfile.ClassCpInfo.void referencedClassAccept(proguard.classfile.visitor.ClassFileVisitor)(ProGuard:110) + at proguard.shrink.UsageMarker.void visitClassCpInfo(proguard.classfile.ClassFile,proguard.classfile.ClassCpInfo)(ProGuard:449) + at proguard.classfile.ClassCpInfo.void accept(proguard.classfile.ClassFile,proguard.classfile.visitor.CpInfoVisitor)(ProGuard:99) + at proguard.classfile.ProgramClassFile.void constantPoolEntryAccept(proguard.classfile.visitor.CpInfoVisitor,int)(ProGuard:372) + at proguard.shrink.UsageMarker.void markCpEntry(proguard.classfile.ClassFile,int)(ProGuard:649) + at proguard.shrink.UsageMarker.void visitProgramClassFile(proguard.classfile.ProgramClassFile)(ProGuard:112) + at proguard.classfile.visitor.VariableClassFileVisitor.void visitProgramClassFile(proguard.classfile.ProgramClassFile)(ProGuard:66) + at proguard.classfile.visitor.MultiClassFileVisitor.void visitProgramClassFile(proguard.classfile.ProgramClassFile)(ProGuard:83) + at proguard.classfile.visitor.FilteredClassFileVisitor.void visitProgramClassFile(proguard.classfile.ProgramClassFile)(ProGuard:69) + at proguard.classfile.ProgramClassFile.void accept(proguard.classfile.visitor.ClassFileVisitor)(ProGuard:356) + at proguard.classfile.ClassPool.void classFileAccept(proguard.classfile.visitor.ClassFileVisitor,java.lang.String)(ProGuard:149) + at proguard.classfile.visitor.NamedClassFileVisitor.void visitClassPool(proguard.classfile.ClassPool)(ProGuard:49) + at proguard.classfile.ClassPool.void accept(proguard.classfile.visitor.ClassPoolVisitor)(ProGuard:105) + at proguard.KeepCommand.void executeShrinkingPhase(proguard.classfile.ClassPool,proguard.classfile.ClassPool)(ProGuard:370) + at proguard.KeepCommand.void execute(int,proguard.classfile.ClassPool,proguard.classfile.ClassPool)(ProGuard:317) + at proguard.CompoundCommand.void execute(int,proguard.classfile.ClassPool,proguard.classfile.ClassPool)(ProGuard:55) + at proguard.ProGuard.void executeCommands(int)(ProGuard:363) + at proguard.ProGuard.void shrink()(ProGuard:187) + at proguard.ProGuard.void execute(java.lang.String[])(ProGuard:385) + at proguard.ProGuard.void main(java.lang.String[])(ProGuard:429) ++ + +
+-printmapping proguard.map ++
+
+A stack trace proguard.trace
will then lack line number
+information:
+
+Exception in thread "main" java.lang.Error: Random exception + at pro.bY.a(Unknown Source) + at pro.bO.a(Unknown Source) + at pro.bj.a(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.bj.a(Unknown Source) + at pro.bN.a(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.l.a(Unknown Source) + at pro.bo.b(Unknown Source) + at pro.ci.a(Unknown Source) + at pro.bo.a(Unknown Source) + at pro.be.a(Unknown Source) + at pro.bo.a(Unknown Source) + at pro.be.a(Unknown Source) + at pro.bg.a(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.bh.a(Unknown Source) + at pro.bg.b(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.bg.a(Unknown Source) + at pro.M.a(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.M.a(Unknown Source) + at pro.bo.a(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.bY.a(Unknown Source) + at pro.P.a(Unknown Source) + at pro.p.a(Unknown Source) + at pro.bU.a(Unknown Source) + at pro.bo.a(Unknown Source) + at pro.J.a(Unknown Source) + at pro.I.a(Unknown Source) + at pro.J.a(Unknown Source) + at pro.cf.c(Unknown Source) + at pro.cf.a(Unknown Source) + at pro.bc.a(Unknown Source) + at proguard.ProGuard.a(Unknown Source) + at proguard.ProGuard.c(Unknown Source) + at proguard.ProGuard.b(Unknown Source) + at proguard.ProGuard.main(Unknown Source) ++
+ +We can still use the same command to recover the stack trace: +
+java -jar retrace.jar proguard.map proguard.trace ++
+ +The output will now give a list of alternative original method names for each +ambiguous obfuscated method name: +
+Exception in thread "main" java.lang.Error: Random exception + at proguard.shrink.UsageMarker.visitProgramClassFile(Unknown Source) + visitLibraryClassFile + visitProgramFieldInfo + visitProgramMethodInfo + visitMemberInfo + visitLibraryFieldInfo + visitLibraryMethodInfo + visitIntegerCpInfo + visitLongCpInfo + visitFloatCpInfo + visitDoubleCpInfo + visitStringCpInfo + visitUtf8CpInfo + visitFieldrefCpInfo + visitInterfaceMethodrefCpInfo + visitMethodrefCpInfo + visitClassCpInfo + visitNameAndTypeCpInfo + visitUnknownAttrInfo + visitInnerClassesAttrInfo + visitConstantValueAttrInfo + visitExceptionsAttrInfo + visitCodeAttrInfo + visitLineNumberTableAttrInfo + visitLocalVariableTableAttrInfo + visitSourceFileAttrInfo + visitDeprecatedAttrInfo + visitSyntheticAttrInfo + visitInstruction + visitCpInstruction + visitExceptionInfo + visitInnerClassesInfo + visitLocalVariableInfo + markCpEntry + markAsUnused + isUsed + at proguard.classfile.instruction.GenericInstruction.create(Unknown Source) + isWide + getLength + accept + at proguard.classfile.CodeAttrInfo.getAttribute(Unknown Source) + getAttrInfoLength + readInfo + accept + instructionsAccept + exceptionsAccept + [...] + at proguard.KeepCommand.executeShrinkingPhase(Unknown Source) + access$100 + at proguard.KeepCommand.keepField(Unknown Source) + ensureMultiClassFileVisitorForMembers + execute + executeObfuscationPhase + access$002 + access$000 + access$102 + access$108 + at proguard.CompoundCommand.addCommand(Unknown Source) + execute + at proguard.ProGuard.readCommands(Unknown Source) + obfuscate + executeCommands + at proguard.ProGuard.shrink(Unknown Source) + at proguard.ProGuard.check(Unknown Source) + execute + at proguard.ProGuard.main(Unknown Source) ++ +
+When an obfuscated program throws an exception, the resulting stack trace +typically isn't very informative. Class names and method names have been +replaced by short meaningless strings. Source file names and line numbers are +missing altogether. While this may be intentional, it can also be inconvenient +when debugging problems. +
+ +
Original code | +- ProGuard → | +Obfuscated code | +
+ | ↓ | +↓ | +
Mapping file | +↓ | +|
↓ | +↓ | +|
Readable stack trace | +← ReTrace - | +Obfuscated stack trace | +
+ReTrace can read an obfuscated stack trace and restore it to what it would +look like without obfuscation. The restoration is based on the mapping file +that ProGuard can write out during obfuscation. The mapping file links the +original class names and class member names to their obfuscated names. + +
lib
directory of the
+ProGuard distribution. To run ReTrace, just type:
++
+java -jar retrace.jar
[options...]
+ mapping_file [stacktrace_file]
+
bin
directory contains some short Linux and
+Windows scripts containing this command. These are the arguments:
+
+-printmapping
mapping_file",
+ while obfuscating the application that produced the stack trace.-verbose
-regex
regular_expression+ (?:.*?\bat\s+%c.%m\s*\(.*?(?::%l)?\)\s*)|(?:(?:.*?[:"]\s+)?%c(?::.*)?) ++ The regular expression is a Java regular expression (cfr. the documentation + of
java.util.regex.Pattern
), with a few additional wildcards:
+ %c |
+ matches a class name (e.g.
+ "myapplication.MyClass "). |
%C |
+ matches a class name with slashes (e.g.
+ "myapplication/MyClass "). |
%t |
+ matches a field type or method return type (e.g.
+ "myapplication.MyClass[] "). |
%f |
+ matches a field name (e.g.
+ "myField "). |
%m |
+ matches a method name (e.g.
+ "myMethod "). |
%a |
+ matches a list of method arguments (e.g.
+ "boolean,int "). |
%l |
+ matches a line number inside a method (e.g.
+ "123 "). |
(?:
...)
+ + +Preserving line number tables is explained in detail in this example in the ProGuard User Manual. +
+ +Unobfuscated elements and obfuscated elements for which no mapping is available +will be left unchanged. + +
+
+
+
+
+
+With support of +
+
+
+
+
+
+
+
+
+
(MyClass)Class.forName(variable).newInstance()
".
+ Depending on your application, you may need to keep the mentioned classes
+ with an option like "-keep class MyClass
", or their
+ implementations with an option like "-keep class * implements
+ MyClass
". You can switch off these notes by specifying the
+ -dontnote
option..getField("myField")
". Depending on your application, you
+ may need to figure out where the mentioned class members are defined and
+ keep them with an option like "-keep class MyClass { MyFieldType
+ myField; }
". Otherwise, ProGuard might remove or obfuscate the
+ class members, since it can't know which ones they are exactly. It does
+ list possible candidates, for your information. You can switch off these
+ notes by specifying the -dontnote
option.-keep
option to preserve the
+ given method (or field), but no -keep
option for the given
+ class that is an argument type or return type in the method's descriptor.
+ You may then want to keep the class too. Otherwise, ProGuard will
+ obfuscate its name, thus changing the method's signature. The method might
+ then become unfindable as an entry point, e.g. if it is part of a public
+ API. You can switch off these notes by specifying the -dontnote
option.-keepclassmembers/-keepclasseswithmembers
option to
+ preserve fields or methods in the given class, but it doesn't specify
+ which fields or methods. This way, the option simply won't have any
+ effect. You probably want to specify one or more fields or methods, as
+ usual between curly braces. You can specify all fields or methods with a
+ wildcard "*;
". You can switch off these notes by specifying
+ the -dontnote
option.-dontnote
option.+ +ProGuard may terminate when it encounters parsing errors or I/O errors, or +some more serious warnings: + +
+
-injars
, otherwise you
+ should specify it with
+ -libraryjars
.
+
+ For example, if ProGuard complains that it can't find a
+ java.lang
class, you have to make sure that you are
+ specifying the run-time library of your platform. For JSE, these are
+ typically packaged in lib/rt.jar
(vm.jar
for
+ IBM's JVM, and classes.jar
in MacOS X). Other platforms
+ like JME and Android have their own run-time libraries.
+ The examples section provides more details
+ for the various platforms.
+
+ If ProGuard still complains that it can't find a
+ javax.crypto
class, you probably still have to specify
+ jce.jar
, next to the more common rt.jar
.
-injars
+ myapplication.jar(!somepackage/SomeUnusedReferencingClass.class)
".
+ ProGuard will then skip this class entirely in the input, and it will
+ not bump into the problem of its missing reference. However, you may
+ then have to filter out other classes that are in turn referencing the
+ removed class. In practice, this works best if you can filter out
+ entire unused packages at once, with a wildcard filter like
+ "-injars
+ myapplication.jar(!someunusedpackage/**)
".-ignorewarnings
+ option, or even
+ the -dontwarn
option.
+ Only use these options if you really know what you're doing though.
+ This last solution is commonly necessary in the standard Android build
+ process. The standard build script automatically passes the libraries that
+ it can find in the libs
directory to ProGuard. Unfortunately,
+ many third-party libraries refer to other libraries that are not actually
+ used and not present. This works fine in debug builds, but in release
+ builds, ProGuard expects all libraries, so it can perform a proper static
+ analysis. For example, if ProGuard complains that it can't find
+ a java.awt
class, then some library that you are using is
+ referring to java.awt
. This is a bit shady, since Android
+ doesn't have this package at all, but if your application works anyway,
+ you can let ProGuard accept it with "-dontwarn
+ java.awt.**
".
-ignorewarnings
+ or -dontwarn
, but it didn't
+ work out. ProGuard's optimization step and preverification step really
+ need the missing classes to make sense of the code. Preferably, you would
+ solve the problem by adding the missing library, as discussed. If you're
+ sure the class that references the missing class isn't used either, you
+ could also try filtering it out from the input, by adding a filter to the
+ corresponding -injars
option:
+ "-injars
+ myapplication.jar(!somepackage/SomeUnusedClass.class)
". As a final
+ solution, you could switch off optimization
+ (-dontoptimize
) and
+ preverification
+ (-dontpreverify
).+
+ For example, if you're developing for Android, and ProGuard complains
+ that it can't find a run-time method that is only available in recent
+ versions of Android, you should change the target in
+ project.properties
to that recent version.
+
+ Alternatively, you may get away with ignoring the inconsistency with
+ the options
+ -ignorewarnings
+ or even
+ -dontwarn
. For
+ instance if the code contains a class to optionally support recent
+ versions of Android, you can specify "-dontwarn
+ mypackage.MySupportClass
".
-dontskipnonpubliclibraryclassmembers
+ option.-injars
) and library code
+ (specified with -libraryjars
), and try
+ again.
+
+ On Android, it is not uncommon that sloppy libraries contain duplicates of
+ classes that are already present in the Android run-time
+ (e.g. org.json
, org.xml
, org.xmlpull
,
+ org.w3c.dom
, or org.apache.http
). You must remove
+ these classes from your libraries, since they are possibly inconsistent,
+ and the run-time libraries would get precedence anyway.
WEB-INF/classes
directory in a war should be packaged
+ in a jar and put in the WEB-INF/lib
directory. If you don't
+ mind these classes not being written to the output, you can specify the -ignorewarnings
option,
+ or even the -dontwarn
+ option.-keep
option in the
+ configuration, and the mapping file, in the obfuscation step. The given
+ class name or class member name can't be kept by its original name, as
+ specified in the configuration, but it has to be mapped to the other given
+ name, as specified in the mapping file. You should adapt your
+ configuration or your mapping file to remove the conflict. Alternatively,
+ if you're sure the renaming won't hurt, you can specify the -ignorewarnings
option,
+ or even the -dontwarn
+ option.-ignorewarnings
option,
+ or even the -dontwarn
+ option. Note that you should always use the -useuniqueclassmembernames
+ option in the initial obfuscation step, in order to reduce the risk of
+ conflicts.-keep
options, or you mistyped the
+ class names. ProGuard has to know exactly what you want to keep: an
+ application, an applet, a servlet, a midlet,..., or any combination of
+ these. Without the proper seed specifications, ProGuard would shrink,
+ optimize, or obfuscate all class files away.<java.home>/lib/rt.jar
by
+ <java.home>/../Classes/classes.jar
.-DsuppressSwingDropSupport=true
when running the
+ GUI.+ +Should ProGuard crash while processing your application: + +
-Xms
and -Xmx
options). You can also
+ reduce the amount of memory that ProGuard needs by removing unnecessary
+ library jars from your configuration, or by filtering out unused library
+ packages and classes. Remember that only classes or interfaces that are
+ extended or implemented by classes in your input jars are required.-Xss
option)
+ should help too. In practice however, the -Xss
setting
+ doesn't have any effect on the main thread, due to Sun Bug
+ #4362291. As a result, this solution will only work when running
+ ProGuard in a different thread, e.g. from its GUI.-dontoptimize
option. In
+ any case, please report the problem, preferably with the simplest example
+ that causes ProGuard to crash.+ +
-dontusemixedcaseclassnames
+ option.
+
+ Also, you should make sure your class files are in directories that
+ correspond to their package names. ProGuard will read misplaced class
+ files, but it will currently not write their processed versions. Notably,
+ class files that are in the WEB-INF/classes
directory in a
+ war should be packaged in a jar and put in the WEB-INF/lib
+ directory.
-printseeds
option to see
+ which elements are being kept exactly.
+
+ If you are using marker interfaces to keep other classes, the marker
+ interfaces themselves are probably being removed in the shrinking step.
+ You should therefore always explicitly keep any marker interfaces, with
+ an option like "-keep interface MyMarkerInterface
".
+
+ Similarly, if you are keeping classes based on annotations, you may have
+ to avoid that the annotation classes themselves are removed in the
+ shrinking step. You should package the annotation classes as a library, or
+ explicitly keep them in your program code with an option like "-keep
+ @interface *
".
LocalVariableTable
or LocalVariableTypeTable
+ attributes.-g:none
), or let
+ ProGuard's obfuscation step remove the debug information again
+ (by not keeping the attributes LocalVariableTable
+ and LocalVariableTypeTable
+ with -keepattributes
),
+ or otherwise just disable optimization
+ (-dontoptimize
).android-sdk/tools/proguard/lib
. If that doesn't help,
+ please report the problem, preferably with the simplest example that still
+ brings out the error.preverify
tool always unpacks the jars, so class files with
+ similar lower-case and upper-case names overwrite each other. You can use
+ ProGuard's -dontusemixedcaseclassnames
+ option to work around this problem.
+
+ If the above doesn't help, there is probably a bug in the optimization
+ step of ProGuard. Make sure you are using the latest version. You should
+ be able to work around the problem by using the -dontoptimize
option. You
+ can check the bug database to see if it is a known problem (often with a
+ fix). Otherwise, please report it, preferably with the simplest example on
+ which you can find ProGuard to fail.
-microedition
option,
+ProGuard will preverify the class files for Java Micro Edition.
++ +
Class.forName
, trying to create
+ the missing class dynamically. ProGuard can only detect constant name
+ arguments, like Class.forName("mypackage.MyClass")
. For
+ variable name arguments like Class.forName(someClass)
, you
+ have to keep all possible classes using the appropriate -keep
option, e.g. "-keep
+ class mypackage.MyClass
" or "-keep class * implements
+ mypackage.MyInterface
".myClass.getField
, trying to find some field dynamically.
+ Since ProGuard can't always detect this automatically, you have to keep
+ the missing field in using the
+ appropriate -keep
option, e.g.
+ "-keepclassmembers class mypackage.MyClass { int myField;
+ }
".myClass.getMethod
, trying to find some method dynamically.
+ Since ProGuard can't always detect this automatically, you have to keep
+ the missing method in using the
+ appropriate -keep
option, e.g.
+ "-keepclassmembers class mypackage.MyClass { void myMethod();
+ }
".
+
+ More specifically, if the method reported as missing is
+ values
or valueOf
, you probably have to keep
+ some methods related to enumerations.
-adaptresourcefilenames
+ and/or -adaptresourcefilecontents
.
+
+ Furthermore, directory entries in jar files aren't copied, unless you
+ specify the option -keepdirectories
.
+ Note that Sun advises against calling Class.getResource()
for
+ directories (Sun
+ Bug #4761949).
-keepattributes
+ *Annotation*
.-jar
instead of the option -classpath
. The java
+ virtual machine returns with this error message if your jar doesn't
+ contain a manifest file (META-INF/MANIFEST.MF
), if the
+ manifest file doesn't specify a main class (Main-Class:
...),
+ or if the jar doesn't contain this main class. You should then make sure
+ that the input jar contains a valid manifest file to start with, that this
+ manifest file is the one that is copied (the first manifest file that is
+ encountered), and that the main class is kept in your configuration,META-INF/INDEX.LIST
, listing all class files in the jar.
+ ProGuard by default copies files like these unchanged. ProGuard may however
+ remove or rename classes, thus invalidating the file. You should filter the
+ index file out of the input
+ (-injars in.jar(!META-INF/INDEX.LIST)
) or update the file
+ after having applied ProGuard (jar -i out.jar
).
+ -microedition
option, so
+ the processed class files are preverified properly.-repackageclasses
+ ''
and -overloadaggressively
.
+ If you're using the JME WTK plugin, you can adapt the configuration
+ proguard/wtk/default.pro
that's inside the
+ proguard.jar
.-useuniqueclassmembernames
+ option. It avoids overloading class member names, which triggers a bug in
+ their java virtual machine.
+
+ You might also try using the -dontusemixedcaseclassnames
+ option. Even if the midlet has been properly processed and then
+ preverified on a case-sensitive file system, the device itself might not
+ like the mixed-case class names. Notably, the Nokia N-Gage emulator works
+ fine, but the actual device seems to exhibit this problem.
volatile
. If this is not
+ possible for some reason, you'll have to switch off optimization using the
+ -dontoptimize
+ option.-overloadaggressively
+ option. This option triggers a bug in
+ sun.tools.java.MethodSet.add
in Sun's JDK 1.2.2, which is
+ used for (dynamic) compilation. You should then avoid this option.-overloadaggressively
+ option. You should then use the same option again in the second processing
+ round.LocalVariableTable
or
+ LocalVariableTypeTable
attributes, ProGuard's optimizing step
+ is sometimes unable to update them consistently. You should then let the
+ obfuscation step remove these attributes or disable the optimization
+ step.+ Furthermore, you should check whether you have specified your program jars + and library jars properly. Program classes can refer to library classes, + but not the other way around. +
+ If all of this seems ok, perhaps there's a bug in ProGuard (gasp!). If so, + please report it, preferably with the simplest example on which you can + find ProGuard to fail.
-dontoptimize
+ option. You can check the bug database to see if it is a known problem
+ (often with a fix). Otherwise, please report it, preferably with the
+ simplest example on which ProGuard fails.
+java -jar proguard.jar
options ...
+
lib
directory of the
+ProGuard distribution. Alternatively, the bin
directory contains
+some short Linux and Windows scripts containing this command. Typically, you'll
+put most options in a configuration file (say, myconfig.pro
), and
+just call:
+
+java -jar proguard.jar @myconfig.pro
+
+java -jar proguard.jar @myconfig.pro -verbose
+
+You can add comments in a configuration file, starting with a
+#
character and continuing until the end of the line.
+
+Extra whitespace between words and delimiters is ignored. File names with +spaces or special characters should be quoted with single or double quotes. +
+Options can be grouped arbitrarily in arguments on the command line and in +lines in configuration files. This means that you can quote arbitrary sections +of command line options, to avoid shell expansion of special characters, for +instance. +
+The order of the options is generally irrelevant. For quick experiments, you +can abbreviate them to their first unique characters. +
+ +The sections below provide more details: +
Keep
Options@
filename-include
+ filename'.-include
+ filename-basedirectory
+ directoryname-injars
+ class_path-injars
options.-outjars
+ class_path-injars
+ options will be written to the named jars. This allows you to collect the
+ contents of groups of input jars into corresponding groups of output jars.
+ In addition, the output entries can be filtered, as explained in
+ the filters section. Each processed class file
+ or resource file is then written to the first output entry with a matching
+ filter, within the group of output jars.
+
+ You must avoid letting the output files overwrite any input files. For
+ better readability, class path entries can be specified using multiple
+ -outjars
options. Without any -outjars
options,
+ no jars will be written.
-libraryjars
+ class_path-libraryjars
options.
+ + Please note that the boot path and the class path set for running ProGuard + are not considered when looking for library classes. This means that you + explicitly have to specify the run-time jar that your code will use. + Although this may seem cumbersome, it allows you to process applications + targeted at different run-time environments. For example, you can process + J2SE applications as well as JME midlets or Android apps, just by + specifying the appropriate run-time jar.
-skipnonpubliclibraryclasses
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-keepdirectories
+ [directory_filter]mypackage.MyClass.class.getResource("")
". You'll then want to
+ keep the directory corresponding to the package, "-keepdirectories
+ mypackage
". If the option is specified without a filter, all
+ directories are kept. With a filter, only matching directories are
+ kept.-target
version1.0
, 1.1
,
+ 1.2
, 1.3
, 1.4
, 1.5
(or
+ just 5
), 1.6
(or just 6
), or
+ 1.7
(or just 7
). By default, the version numbers
+ of the class files are left unchanged. For example, you may want to
+ upgrade class files to Java 6, by
+ changing their version numbers and having them preverified.-forceprocessing
+ +
-keep
+ [,modifier,...]
+ class_specification-keepclassmembers
+ [,modifier,...]
+ class_specificationSerializable
+ interface.-keepclasseswithmembers
+ [,modifier,...]
+ class_specification-keepnames
+ class_specification-keep
,allowshrinking
+ class_specification
+
+ Specifies classes and class members whose names are to be preserved, if
+ they aren't removed in the shrinking phase. For example, you may want to
+ keep all class names of classes
+ that implement the Serializable
interface, so that the
+ processed code remains compatible with any originally serialized classes.
+ Classes that aren't used at all can still be removed. Only applicable when
+ obfuscating.
-keepclassmembernames
+ class_specification-keepclassmembers
,allowshrinking
+ class_specification
+
+ Specifies class members whose names are to be preserved, if they aren't
+ removed in the shrinking phase. For example, you may want to preserve the
+ name of the synthetic class$
methods
+ when processing a library compiled by
+ JDK 1.2 or older, so obfuscators can detect it again when processing an
+ application that uses the processed library (although ProGuard itself
+ doesn't need this). Only applicable when obfuscating.
-keepclasseswithmembernames
+ class_specification-keepclasseswithmembers
,allowshrinking
+ class_specification
+ + Specifies classes and class members whose names are to be preserved, on + the condition that all of the specified class members are present after + the shrinking phase. For example, you may want to keep all native method names and the names + of their classes, so that the processed code can still link with the + native library code. Native methods that aren't used at all can still be + removed. If a class file is used, but none of its native methods are, its + name will still be obfuscated. Only applicable when obfuscating.
-printseeds
+ [filename]-keep
options. The list is printed to the standard
+ output or to the given file. The list can be useful to verify if the
+ intended class members are really found, especially if you're using
+ wildcards. For example, you may want to list all the applications or all the applets that you are keeping.+ +
-dontshrink
-keep
options, and the ones on which
+ they depend, directly or indirectly. A shrinking step is also applied
+ after each optimization step, since some optimizations may open the
+ possibility to remove more classes and class members.-printusage
+ [filename]-whyareyoukeeping
+ class_specification-verbose
option if specified, the traces
+ include full field and method signatures. Only applicable when
+ shrinking.+ +
-dontoptimize
-optimizations
+ optimization_filter-optimizationpasses
n-assumenosideeffects
+ class_specificationSystem.currentTimeMillis()
, so that any idle calls to it will
+ be removed. With some care, you can also use the option to
+ remove logging code. Note that
+ ProGuard applies the option to the entire hierarchy of the specified
+ methods. Only applicable when optimizing. In general, making assumptions
+ can be dangerous; you can easily break the processed code. Only use
+ this option if you know what you're doing!-allowaccessmodification
-repackageclasses
option).
+ + Counter-indication: you probably shouldn't use this option when + processing code that is to be used as a library, since classes and class + members that weren't designed to be public in the API may become + public.
-mergeinterfacesaggressively
+ Counter-indication: setting this option can reduce the performance + of the processed code on some JVMs, since advanced just-in-time + compilation tends to favor more interfaces with fewer implementing + classes. Worse, some JVMs may not be able to handle the resulting code. + Notably: +
InternalError
when
+ encountering more than 256 Miranda methods (interface methods
+ without implementations) in a class.+ +
-dontobfuscate
-keep
options.
+ Internal attributes that are useful for debugging, such as source files
+ names, variable names, and line numbers are removed.-printmapping
+ [filename]-applymapping
+ filename-useuniqueclassmembernames
+ in both obfuscation runs. Only a single mapping file is allowed. Only
+ applicable when obfuscating.-obfuscationdictionary
+ filename#
sign are ignored. Note that an
+ obfuscation dictionary hardly improves the obfuscation. Decent compilers
+ can automatically replace them, and the effect can fairly simply be undone
+ by obfuscating again with simpler names. The most useful application is
+ specifying strings that are typically already present in class files (such
+ as 'Code'), thus reducing the class file sizes just a little bit more.
+ Only applicable when obfuscating.-classobfuscationdictionary
+ filename-obfuscationdictionary
.
+ Only applicable when obfuscating.-packageobfuscationdictionary
+ filename-obfuscationdictionary
.
+ Only applicable when obfuscating.-overloadaggressively
+ Counter-indication: the resulting class files fall within the Java + bytecode specification (cfr. The Java Virtual Machine Specification, Second Edition, first + paragraphs of Section 4.5 and Section 4.6), even though this kind of overloading is not allowed in + the Java language (cfr. The Java Language Specification, Second Edition, Section 8.3 and Section 8.4.7). Still, some tools have problems with it. Notably: +
javac
compiler produces an exception when
+ compiling with such a library (cfr. Bug #4216736).
+ You probably shouldn't use this option for processing libraries.pack200
tool reportedly has problems with
+ overloaded class members.-useuniqueclassmembernames
+ For instance, consider two distinct interfaces containing methods with the + same name and signature. Without this option, these methods may get + different obfuscated names in a first obfuscation step. If a patch is then + added containing a class that implements both interfaces, ProGuard will + have to enforce the same method name for both methods in an incremental + obfuscation step. The original obfuscated code is changed, in order to + keep the resulting code consistent. With this option in the initial + obfuscation step, such renaming will never be necessary. +
+ This option is only applicable when obfuscating. In fact, if you are + planning on performing incremental obfuscation, you probably want to avoid + shrinking and optimization altogether, since these steps could remove or + modify parts of your code that are essential for later additions.
-dontusemixedcaseclassnames
-keeppackagenames
+ [package_filter]-flattenpackagehierarchy
+ [package_name]-repackageclasses
+ [package_name]-flattenpackagehierarchy
+ option. It is another example of further obfuscating package names. It can
+ make the processed code even smaller and less comprehensible. Its
+ deprecated name is -defaultpackage
. Only applicable when
+ obfuscating.
+ + Counter-indication: classes that look for resource files in their + package directories will no longer work properly if they are moved + elsewhere. When in doubt, just leave the packaging untouched by not using + this option.
-keepattributes
+ [attribute_filter]-keepattributes
directives. The
+ optional filter is a comma-separated list of attribute names. Attribute
+ names can contain ?, *, and ** wildcards, and they
+ can be preceded by the ! negator. Typical optional attributes are
+ Exceptions
, Signature
, Deprecated
,
+ SourceFile
, SourceDir
,
+ LineNumberTable
, LocalVariableTable
,
+ LocalVariableTypeTable
, Synthetic
,
+ EnclosingMethod
, RuntimeVisibleAnnotations
,
+ RuntimeInvisibleAnnotations
,
+ RuntimeVisibleParameterAnnotations
,
+ RuntimeInvisibleParameterAnnotations
, and
+ AnnotationDefault
. The InnerClasses
attribute
+ name can be specified as well, referring to the source name part of this
+ attribute. For example, you should at least keep the
+ Exceptions
, InnerClasses
, and
+ Signature
attributes
+ when processing a library. You should
+ also keep the SourceFile
and
+ LineNumberTable
attributes
+ for producing useful obfuscated stack
+ traces. Finally, you may want
+ to keep annotations if your code
+ depends on them. Only applicable when obfuscating.-keepparameternames
LocalVariableTable
and
+ LocalVariableTypeTable
. It can be useful when
+ processing a library. Some IDEs can
+ use the information to assist developers who use the library, for example
+ with tool tips or autocompletion. Only applicable when obfuscating.-renamesourcefileattribute
+ [string]SourceFile
+ attributes (and SourceDir
attributes) of the class files.
+ Note that the attribute has to be present to start with, so it also has to
+ be preserved explicitly using the -keepattributes
directive.
+ For example, you may want to have your processed libraries and
+ applications produce useful obfuscated
+ stack traces. Only applicable when obfuscating.-adaptclassstrings
+ [class_filter]-adaptresourcefilenames
+ [file_filter]-adaptresourcefilecontents
+ [file_filter]LANG
or the Java system
+ property file.encoding
. For an example,
+ see processing resource files.
+ Only applicable when obfuscating.+ +
-dontpreverify
-microedition
+ +
-verbose
-dontnote
+ [class_filter]-dontwarn
+ [class_filter]-ignorewarnings
-printconfiguration
+ [filename]-dump
+ [filename]+ +
+Each input entry can be: +
+The paths of directly specified class files and resource files is ignored, so +class files should generally be part of a jar file, a war file, an ear file, a +zip file, or a directory. In addition, the paths of class files should not have +any additional directory prefixes inside the archives or directories. + +
+Each output entry can be: +
+When writing output entries, ProGuard will generally package the results in a +sensible way, reconstructing the input entries as much as required. Writing +everything to an output directory is the most straightforward option: the +output directory will contain a complete reconstruction of the input entries. +The packaging can be almost arbitrarily complex though: you could process an +entire application, packaged in a zip file along with its documentation, +writing it out as a zip file again. The Examples section shows a few ways +to restructure output archives. +
+Files and directories can be specified as discussed in the section on file names below. +
+In addition, ProGuard provides the possibility to filter the class path +entries and their contents, based on their full relative file names. Each +class path entry can be followed by up to 5 types of file filters between parentheses, separated by +semi-colons: +
+If fewer than 5 filters are specified, they are assumed to be the latter +filters. Any empty filters are ignored. More formally, a filtered class path +entry looks like this: +
+classpathentry([[[[zipfilter;]earfilter;]warfilter;]jarfilter;]filefilter) ++
+Square brackets "[]" mean that their contents are optional. +
+For example, "rt.jar(java/**.class,javax/**.class)
" matches all
+class files in the java
and javax
directories inside
+the rt
jar.
+
+For example, "input.jar(!**.gif,images/**)
" matches all files in
+the images
directory inside the input
jar, except
+gif files.
+
+The different filters are applied to all corresponding file types, irrespective +of their nesting levels in the input; they are orthogonal. +
+For example,
+"input.war(lib/**.jar,support/**.jar;**.class,**.gif)
" only
+considers jar files in the lib
and support
+directories in the input
war, not any other jar files. It then
+matches all class files and gif files that are encountered.
+
+The filters allow for an almost infinite number of packaging and repackaging +possibilities. The Examples section provides a few more examples +for filtering input and output. +
+ +
+The names can contain Java system properties (or Ant properties, when using +Ant), delimited by angular brackets, '<' and '>'. The +properties are automatically replaced by their corresponding values. +
+For example, <java.home>/lib/rt.jar
is automatically
+expanded to something like /usr/local/java/jdk/jre/lib/rt.jar
.
+Similarly, <user.home>
is expanded to the user's home
+directory, and <user.dir>
is expanded to the current
+working directory.
+
+Names with special characters like spaces and parentheses must be quoted with +single or double quotes. Each file name in a list of names has to be quoted +individually. Note that the quotes themselves may need to be escaped when used +on the command line, to avoid them being gobbled by the shell. +
+For example, on the command line, you could use an option like '-injars
+"my program.jar":"/your directory/your program.jar"'
.
+
+ +
? |
+ matches any single character in a file name. |
* |
+ matches any part of a filename not containing the directory + separator. |
** |
+ matches any part of a filename, possibly containing any number of + directory separators. |
java/**.class,javax/**.class
" matches all
+class files in the java
and javax
.
++ +Furthermore, a file name can be preceded by an exclamation mark '!' to +exclude the file name from further attempts to match with +subsequent file names. +
+For example, "!**.gif,images/**
" matches all files in the
+images
directory, except gif files.
+
+The Examples section provides a few more examples for filtering input and output. + +
+A filter is a list of comma-separated names that can contain wildcards. Only +names that match an item on the list pass the filter. The supported wildcards +depend on the type of names for which the filter is being used, but the +following wildcards are typical: + +
? |
+ matches any single character in a name. |
* |
+ matches any part of a name not containing the package separator or + directory separator. |
** |
+ matches any part of a name, possibly containing any number of + package separators or directory separators. |
foo,*bar
" matches the name foo
and
+all names ending with bar
.
++ +Furthermore, a name can be preceded by a negating exclamation mark '!' +to exclude the name from further attempts to match +with subsequent names. So, if a name matches an item in the filter, it +is accepted or rejected right away, depending on whether the item has a +negator. If the name doesn't match the item, it is tested against the next +item, and so on. It if doesn't match any items, it is accepted or rejected, +depending on the whether the last item has a negator or not. +
+For example, "!foobar,*bar
" matches all names ending with
+bar
, except foobar
.
+
+ +
Keep
Options-keep
options for shrinking and obfuscation may seem
+a bit confusing at first, but there's actually a pattern behind them. The
+following table summarizes how they are related:
++ +
Keep | +From being removed or renamed | +From being renamed | +
---|---|---|
Classes and class members | +-keep |
+-keepnames |
+
Class members only | +-keepclassmembers |
+-keepclassmembernames |
+
Classes and class members, if class members present | +-keepclasseswithmembers |
+-keepclasseswithmembernames |
+
+
+Each of these -keep
options is of course followed by a
+specification of the classes and class
+members (fields and methods) to which it should be applied.
+
+If you're not sure which option you need, you should probably simply use
+-keep
. It will make sure the specified classes and class members
+are not removed in the shrinking step, and not renamed in the obfuscation step.
+
+
+
+ +
allowshrinking
allowoptimization
allowobfuscation
+ +
-keep
options and in the
+-assumenosideeffects
option. The corresponding option is only
+applied to classes and class members that match the template.
++The template was designed to look very Java-like, with some extensions for +wildcards. To get a feel for the syntax, you should probably look at the examples, but this is an attempt at a complete formal +definition: +
+ +
+[@annotationtype] [[!]public|final|abstract|@ ...] [!]interface|class|enum classname + [extends|implements [@annotationtype] classname] +[{ + [@annotationtype] [[!]public|private|protected|static|volatile|transient ...] <fields> | + (fieldtype fieldname); + [@annotationtype] [[!]public|private|protected|static|synchronized|native|abstract|strictfp ...] <methods> | + <init>(argumenttype,...) | + classname(argumenttype,...) | + (returntype methodname(argumenttype,...)); + [@annotationtype] [[!]public|private|protected|static ... ] *; + ... +}] ++
+Square brackets "[]" mean that their contents are optional. Ellipsis dots +"..." mean that any number of the preceding items may be specified. A vertical +bar "|" delimits two alternatives. Non-bold parentheses "()" just group parts +of the specification that belong together. The indentation tries to clarify +the intended meaning, but white-space is irrelevant in actual configuration +files. +
+
class
keyword refers to any interface or class.
+ The interface
keyword restricts matches to interface
+ classes. The enum
keyword restricts matches to
+ enumeration classes. Preceding the interface
or
+ enum
keywords by a !
restricts
+ matches to classes that are not interfaces or enumerations,
+ respectively.java.lang.String
. Inner classes are separated by a dollar sign
+ "$
", e.g. java.lang.Thread$State
. Class names
+ may be specified as regular
+ expressions containing the following wildcards:
+
+? |
+
+matches any single character in a class name, but not the package
+ separator. For example, "mypackage.Test? " matches
+ "mypackage.Test1 " and "mypackage.Test2 ", but not
+ "mypackage.Test12 ". |
* |
+
+matches any part of a class name not containing the package separator. For
+ example, "mypackage.*Test* " matches
+ "mypackage.Test " and
+ "mypackage.YourTestApplication ", but not
+ "mypackage.mysubpackage.MyTest ". Or, more generally,
+ "mypackage.* " matches all classes in
+ "mypackage ", but not in its subpackages. |
** |
+
+matches any part of a class name, possibly containing any number of
+ package separators. For example, "**.Test " matches all
+ Test classes in all packages except the root package. Or,
+ "mypackage.** " matches all classes in
+ "mypackage " and in its subpackages. |
!
negators, just
+ like file name filters. This notation doesn't look very Java-like, so it
+ should be used with moderation.
+
+ For convenience and for backward compatibility, the class name
+ *
refers to any class, irrespective of its package.
extends
and implements
+ specifications are typically used to restrict classes with wildcards. They
+ are currently equivalent, specifying that only classes extending or
+ implementing the given class qualify. Note that the given class itself is
+ not included in this set. If required, it should be specified in a
+ separate option.@
specifications can be used to restrict classes
+ and class members to the ones that are annotated with the specified
+ annotation types. An annotationtype is specified just like a
+ classname.javadoc
and javap
). The specifications can
+ also contain the following catch-all wildcards:
+
+<init> |
+matches any constructor. |
<fields> |
+matches any field. |
<methods> |
+matches any method. |
* |
+matches any field or method. |
<init>
wildcard has an argument list.
+ + + Fields and methods may also be specified using regular expressions. Names + can contain the following wildcards: + +
? |
+ matches any single character in a method name. |
* |
+ matches any part of a method name. |
% |
+ matches any primitive type ("boolean ", "int ",
+ etc, but not "void "). |
? |
+ matches any single character in a class name. |
* |
+ matches any part of a class name not containing the package separator. |
** |
+ matches any part of a class name, possibly containing any number of + package separators. |
*** |
+ matches any type (primitive or non-primitive, array or + non-array). |
... |
+ matches any number of arguments of any type. |
?
, *
, and **
+ wildcards will never match primitive types. Furthermore, only the
+ ***
wildcards will match array types of any dimension. For
+ example, "** get*()
" matches "java.lang.Object
+ getObject()
", but not "float getFloat()
", nor
+ "java.lang.Object[] getObjects()
".!
specifies that the corresponding access
+ flag should be unset.
+
+ Combining multiple flags is allowed (e.g. public static
). It
+ means that both access flags have to be set (e.g. public
+ and static
), except when they are conflicting, in
+ which case at least one of them has to be set (e.g. at least
+ public
+ or protected
).
+
+ ProGuard supports the additional modifiers synthetic
,
+ bridge
, and varargs
, which may be
+ set by compilers.
+ +The WTK already comes with a plug-in for ProGuard. Alternatively, ProGuard +offers its own plug-in. This latter implementation is recommended, as it more +up to date and it solves some problems. It is also somewhat more efficient, +invoking the ProGuard engine directly, instead of writing out a configuration +file and running ProGuard in a separate virtual machine. +
+
+In order to integrate this plug-in in the toolkit, you'll have to put the
+following lines in the file
+{j2mewtk.dir}/wtklib/Linux/ktools.properties
or
+{j2mewtk.dir}\wtklib\Windows\ktools.properties
(whichever is
+applicable).
+
+ +
+obfuscator.runner.class.name: proguard.wtk.ProGuardObfuscator +obfuscator.runner.classpath: /usr/local/java/proguard/lib/proguard.jar ++
+ +Please make sure the class path is set correctly for your system. +
+ +Once ProGuard has been set up, you can apply it to your projects as part of +the build process. The build process is started from the WTK menu bar: +
+
+This option will compile, shrink, obfuscate, verify, and install your midlets +for testing. +
+Should you ever need to customize your ProGuard configuration for the JME WTK,
+you can adapt the configuration file proguard/wtk/default.pro
+that's inside the proguard.jar
.
+
+
+
+The pages will appear in a new window, which you probably want to view at +full-screen size. +
+ +In addition, ProGuard is tested against a constantly growing test suite +(more than 1500 tests at this time of writing). These small programs contain a +wide range of common and uncommon constructs, in order to detect any regression +problems as soon as possible. + +
+ +
Input Program | +Original size | +After shrinking | +After optim. | +After obfusc. | +Total reduction | +Time | +Memory usage | +
---|---|---|---|---|---|---|---|
Worm, a sample midlet from Oracle's JME | +10.3 K | +9.8 K | +9.6 K | +8.5 K | +18 % | +2 s | +19 M | +
Javadocking, a docking library | +290 K | +281 K | +270 K | +201 K | +30 % | +12 s | +32 M | +
ProGuard itself | +648 K | +579 K | +557 K | +348 K | +46 % | +28 s | +66 M | +
JDepend, a Java quality metrics tool | +57 K | +36 K | +33 K | +28 K | +51 % | +6 s | +24 M | +
the run-time classes from Oracle's Java 6 | +53 M | +23 M | +22 M | +18 M | +66 % | +16 min | +270 M | +
Tomcat, the Apache servlet container | +1.1 M | +466 K | +426 K | +295 K | +74 % | +17 s | +44 M | +
JavaNCSS, a Java source metrics tool | +632 K | +242 K | +212 K | +152 K | +75 % | +20 s | +36 M | +
Ant, the Apache build tool | +2.4 M | +401 K | +325 K | +242 K | +90 % | +23 s | +61 M | +
+Results were measured with ProGuard 4.0 on a 2.6 GHz Pentium 4 with 512 MB +of memory, using Sun JDK 1.5.0 in Fedora Core 3 Linux. All of this technology +and software has evolved since, but the gist of the results remains the same. +
+The program sizes include companion libraries. The shrinking step produces the +best results for programs that use only small parts of their libraries. The +obfuscation step can significantly shrink large programs even further, since +the identifiers of their many internal references can be replaced by short +identifiers. +
+The Java 6 run-time classes are the most complex example. The classes perform +a lot of introspection, interacting with the native code of the virtual +machine. The 1500+ lines of configuration were largely composed by automated +analysis, complemented by a great deal of trial and error. The configuration +is probably not complete, but the resulting library successfully serves as a +run-time environment for running applications like ProGuard and the ProGuard +GUI. +
+For small inputs, timings are governed by the reading and parsing of the jars. +For large inputs, the optimization step becomes more important. For instance, +processing the Java 6 run-time classes without optimization only takes 2 +minutes. +
+Memory usage (the amount of physical memory used by ProGuard while processing) +is governed by the basic java virtual machine and by the total size of the +library jars and program jars. + +
+
+![]() +You can click on the small tab buttons to see the full-size versions of the +tabs. + + |
+
+![]() +You can click on the image to see the full-size version. + + |
+
+
+
+
+
+With support of + +
+
+
+
+
+
+
+
+
+ProGuard is probably the most popular java shrinker, optimizer, and +obfuscator world-wide. It is being used by developers at companies and +organizations like IBM, HP, Siemens, Nokia, Google, Intel, and NATO. It is the +default tool in many development environments like Oracle's Wireless Toolkit, +Netbeans, EclipseME, Google's Android SDK, and more. Although the quotes below +probably don't represent official views of any kind, encouragements like these +do keep me happy. +
+ +
+ProGuard is the ultimate java obfuscator! + + |
+![]() |
![]() |
+![]() |
+
+ +Also: +
+ProGuard is pure quality - powerful and trouble-free. + + |
+![]() |
![]() |
+![]() |
+
+ +And: +
+It is the simplest and most robust obfuscator we have ever used. + + |
+![]() |
![]() |
+![]() |
+
+ +And indeed: +
+ProGuard rules. Much easier to use than the commercial alternatives. + + |
+![]() |
![]() |
+![]() |
+
+ +Straight from ProGuard's open discussion forum: +
+
+After searching for, trying to trial, and futzing with numerous other +obfuscators and shrinkers, ProGuard stands out as the simplest, most robust, +and accurate shrinker of them all. + + |
+![]() |
![]() |
+![]() |
+
+ +From the article "Obfuscating MIDlet Suites with ProGuard" at developers.sun.com: +
+
+Its friendly license, attractive price tag, compelling performance, and +powerful configuration options make it an excellent addition to your MIDlet +development toolbox. + + |
+![]() |
![]() |
+![]() |
+
+ +And, of course, the price is stunning: +
+
+You could've been rich. + + |
+![]() |
![]() |
+![]() |
+
WordReader
that returns words from an argument list.
+ * Single arguments are split into individual words if necessary.
+ *
+ * @author Eric Lafortune
+ */
+public class ArgumentWordReader extends WordReader
+{
+ private final String[] arguments;
+
+ private int index = 0;
+
+
+// /**
+// * Creates a new ArgumentWordReader for the given arguments.
+// */
+// public ArgumentWordReader(String[] arguments)
+// {
+// this(arguments, null);
+// }
+//
+//
+ /**
+ * Creates a new ArgumentWordReader for the given arguments, with the
+ * given base directory.
+ */
+ public ArgumentWordReader(String[] arguments, File baseDir)
+ {
+ super(baseDir);
+
+ this.arguments = arguments;
+ }
+
+
+ // Implementations for WordReader.
+
+ protected String nextLine() throws IOException
+ {
+ return index < arguments.length ?
+ arguments[index++] :
+ null;
+ }
+
+
+ protected String lineLocationDescription()
+ {
+ return "argument number " + index;
+ }
+
+
+ /**
+ * Test application that prints out the individual words of
+ * the argument list.
+ */
+ public static void main(String[] args) {
+
+ try
+ {
+ WordReader reader = new ArgumentWordReader(args, null);
+
+ try
+ {
+ while (true)
+ {
+ String word = reader.nextWord(false);
+ if (word == null)
+ System.exit(-1);
+
+ System.err.println("["+word+"]");
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ finally
+ {
+ reader.close();
+ }
+ }
+ catch (IOException ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/ClassPath.java b/src/proguard/ClassPath.java
new file mode 100644
index 000000000..3d7d1195e
--- /dev/null
+++ b/src/proguard/ClassPath.java
@@ -0,0 +1,94 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import java.util.*;
+
+
+/**
+ * This class represents a class path, as a list of ClassPathEntry objects.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassPath
+{
+ private final List classPathEntries = new ArrayList();
+
+
+ /**
+ * Returns whether the class path contains any output entries.
+ */
+ public boolean hasOutput()
+ {
+ for (int index = 0; index < classPathEntries.size(); index++)
+ {
+ if (((ClassPathEntry)classPathEntries.get(index)).isOutput())
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ // Delegates to List.
+
+ public void clear()
+ {
+ classPathEntries.clear();
+ }
+
+ public void add(int index, ClassPathEntry classPathEntry)
+ {
+ classPathEntries.add(index, classPathEntry);
+ }
+
+ public boolean add(ClassPathEntry classPathEntry)
+ {
+ return classPathEntries.add(classPathEntry);
+ }
+
+ public boolean addAll(ClassPath classPath)
+ {
+ return classPathEntries.addAll(classPath.classPathEntries);
+ }
+
+ public ClassPathEntry get(int index)
+ {
+ return (ClassPathEntry)classPathEntries.get(index);
+ }
+
+ public ClassPathEntry remove(int index)
+ {
+ return (ClassPathEntry)classPathEntries.remove(index);
+ }
+
+ public boolean isEmpty()
+ {
+ return classPathEntries.isEmpty();
+ }
+
+ public int size()
+ {
+ return classPathEntries.size();
+ }
+}
diff --git a/src/proguard/ClassPathEntry.java b/src/proguard/ClassPathEntry.java
new file mode 100644
index 000000000..705195528
--- /dev/null
+++ b/src/proguard/ClassPathEntry.java
@@ -0,0 +1,282 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.util.ListUtil;
+
+import java.io.*;
+import java.util.List;
+
+
+/**
+ * This class represents an entry from a class path: a jar, a war, a zip, an
+ * ear, or a directory, with a name and a flag to indicates whether the entry is
+ * an input entry or an output entry. Optional filters can be specified for the
+ * names of the contained resource/classes, jars, wars, ears, and zips.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassPathEntry
+{
+ private File file;
+ private boolean output;
+ private List filter;
+ private List jarFilter;
+ private List warFilter;
+ private List earFilter;
+ private List zipFilter;
+
+
+ /**
+ * Creates a new ClassPathEntry with the given file and output flag.
+ */
+ public ClassPathEntry(File file, boolean isOutput)
+ {
+ this.file = file;
+ this.output = isOutput;
+ }
+
+
+ /**
+ * Returns the path name of the entry.
+ */
+ public String getName()
+ {
+ try
+ {
+ return file.getCanonicalPath();
+ }
+ catch (IOException ex)
+ {
+ return file.getPath();
+ }
+ }
+
+
+ /**
+ * Returns the file.
+ */
+ public File getFile()
+ {
+ return file;
+ }
+
+
+ /**
+ * Sets the file.
+ */
+ public void setFile(File file)
+ {
+ this.file = file;
+ }
+
+
+ /**
+ * Returns whether this data entry is an output entry.
+ */
+ public boolean isOutput()
+ {
+ return output;
+ }
+
+
+ /**
+ * Specifies whether this data entry is an output entry.
+ */
+ public void setOutput(boolean output)
+ {
+ this.output = output;
+ }
+
+
+ /**
+ * Returns whether this data entry is a jar file.
+ */
+ public boolean isJar()
+ {
+ return hasExtension(".jar");
+ }
+
+
+ /**
+ * Returns whether this data entry is a war file.
+ */
+ public boolean isWar()
+ {
+ return hasExtension(".war");
+ }
+
+
+ /**
+ * Returns whether this data entry is a ear file.
+ */
+ public boolean isEar()
+ {
+ return hasExtension(".ear");
+ }
+
+
+ /**
+ * Returns whether this data entry is a zip file.
+ */
+ public boolean isZip()
+ {
+ return hasExtension(".zip");
+ }
+
+
+ /**
+ * Returns whether this data entry has the given extension.
+ */
+ private boolean hasExtension(String extension)
+ {
+ return endsWithIgnoreCase(file.getPath(), extension);
+ }
+
+
+ /**
+ * Returns whether the given string ends with the given suffix, ignoring
+ * its case.
+ */
+ private static boolean endsWithIgnoreCase(String string, String suffix)
+ {
+ int stringLength = string.length();
+ int suffixLength = suffix.length();
+
+ return string.regionMatches(true, stringLength -
+ suffixLength, suffix, 0, suffixLength);
+ }
+
+
+ /**
+ * Returns the name filter that is applied to bottom-level files in this entry.
+ */
+ public List getFilter()
+ {
+ return filter;
+ }
+
+ /**
+ * Sets the name filter that is applied to bottom-level files in this entry.
+ */
+ public void setFilter(List filter)
+ {
+ this.filter = filter == null || filter.size() == 0 ? null : filter;
+ }
+
+
+ /**
+ * Returns the name filter that is applied to jar files in this entry, if any.
+ */
+ public List getJarFilter()
+ {
+ return jarFilter;
+ }
+
+ /**
+ * Sets the name filter that is applied to jar files in this entry, if any.
+ */
+ public void setJarFilter(List filter)
+ {
+ this.jarFilter = filter == null || filter.size() == 0 ? null : filter;
+ }
+
+
+ /**
+ * Returns the name filter that is applied to war files in this entry, if any.
+ */
+ public List getWarFilter()
+ {
+ return warFilter;
+ }
+
+ /**
+ * Sets the name filter that is applied to war files in this entry, if any.
+ */
+ public void setWarFilter(List filter)
+ {
+ this.warFilter = filter == null || filter.size() == 0 ? null : filter;
+ }
+
+
+ /**
+ * Returns the name filter that is applied to ear files in this entry, if any.
+ */
+ public List getEarFilter()
+ {
+ return earFilter;
+ }
+
+ /**
+ * Sets the name filter that is applied to ear files in this entry, if any.
+ */
+ public void setEarFilter(List filter)
+ {
+ this.earFilter = filter == null || filter.size() == 0 ? null : filter;
+ }
+
+
+ /**
+ * Returns the name filter that is applied to zip files in this entry, if any.
+ */
+ public List getZipFilter()
+ {
+ return zipFilter;
+ }
+
+ /**
+ * Sets the name filter that is applied to zip files in this entry, if any.
+ */
+ public void setZipFilter(List filter)
+ {
+ this.zipFilter = filter == null || filter.size() == 0 ? null : filter;
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ String string = getName();
+
+ if (filter != null ||
+ jarFilter != null ||
+ warFilter != null ||
+ earFilter != null ||
+ zipFilter != null)
+ {
+ string +=
+ ConfigurationConstants.OPEN_ARGUMENTS_KEYWORD +
+ (zipFilter != null ? ListUtil.commaSeparatedString(zipFilter, true) : "") +
+ ConfigurationConstants.SEPARATOR_KEYWORD +
+ (earFilter != null ? ListUtil.commaSeparatedString(earFilter, true) : "") +
+ ConfigurationConstants.SEPARATOR_KEYWORD +
+ (warFilter != null ? ListUtil.commaSeparatedString(warFilter, true) : "") +
+ ConfigurationConstants.SEPARATOR_KEYWORD +
+ (jarFilter != null ? ListUtil.commaSeparatedString(jarFilter, true) : "") +
+ ConfigurationConstants.SEPARATOR_KEYWORD +
+ (filter != null ? ListUtil.commaSeparatedString(filter, true) : "") +
+ ConfigurationConstants.CLOSE_ARGUMENTS_KEYWORD;
+ }
+
+ return string;
+ }
+}
diff --git a/src/proguard/ClassSpecification.java b/src/proguard/ClassSpecification.java
new file mode 100644
index 000000000..485c0b033
--- /dev/null
+++ b/src/proguard/ClassSpecification.java
@@ -0,0 +1,259 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import java.util.*;
+
+/**
+ * This class stores a specification of classes and possibly class members.
+ * The specification is template-based: the class names and class member names
+ * and descriptors can contain wildcards. Classes can be specified explicitly,
+ * or as extensions or implementations in the class hierarchy.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassSpecification implements Cloneable
+{
+ public final String comments;
+ public int requiredSetAccessFlags;
+ public int requiredUnsetAccessFlags;
+ public final String annotationType;
+ public String className;
+ public final String extendsAnnotationType;
+ public final String extendsClassName;
+
+ public List fieldSpecifications;
+ public List methodSpecifications;
+
+
+ /**
+ * Creates a new ClassSpecification for all possible classes, without
+ * comments or class members.
+ */
+ public ClassSpecification()
+ {
+ this(null,
+ 0,
+ 0,
+ null,
+ null,
+ null,
+ null);
+ }
+
+
+ /**
+ * Creates a new ClassSpecification that is a copy of the given specification.
+ */
+ public ClassSpecification(ClassSpecification classSpecification)
+ {
+ this(classSpecification.comments,
+ classSpecification.requiredSetAccessFlags,
+ classSpecification.requiredUnsetAccessFlags,
+ classSpecification.annotationType,
+ classSpecification.className,
+ classSpecification.extendsAnnotationType,
+ classSpecification.extendsClassName,
+ classSpecification.fieldSpecifications,
+ classSpecification.methodSpecifications);
+ }
+
+
+ /**
+ * Creates a new ClassSpecification for the specified class(es), without
+ * class members.
+ *
+ * @param comments provides optional comments on this
+ * specification.
+ * @param requiredSetAccessFlags the class access flags that must be set
+ * in order for the class to apply.
+ * @param requiredUnsetAccessFlags the class access flags that must be
+ * unset in order for the class to apply.
+ * @param annotationType the name of the class that must be an
+ * annotation of the class in order for it
+ * to apply. The name may be null to
+ * specify that no annotation is required.
+ * @param className the class name. The name may be null to
+ * specify any class, or it may contain
+ * "**", "*", or "?" wildcards.
+ * @param extendsAnnotationType the name of the class of that must be
+ * an annotation of the class that the
+ * class must extend or implement in order
+ * to apply. The name may be null to
+ * specify that no annotation is required.
+ * @param extendsClassName the name of the class that the class
+ * must extend or implement in order to
+ * apply. The name may be null to specify
+ * any class.
+ */
+ public ClassSpecification(String comments,
+ int requiredSetAccessFlags,
+ int requiredUnsetAccessFlags,
+ String annotationType,
+ String className,
+ String extendsAnnotationType,
+ String extendsClassName)
+ {
+ this(comments,
+ requiredSetAccessFlags,
+ requiredUnsetAccessFlags,
+ annotationType,
+ className,
+ extendsAnnotationType,
+ extendsClassName,
+ null,
+ null);
+ }
+
+
+ /**
+ * Creates a new ClassSpecification for the specified classes and class
+ * members.
+ *
+ * @param comments provides optional comments on this
+ * specification.
+ * @param requiredSetAccessFlags the class access flags that must be set
+ * in order for the class to apply.
+ * @param requiredUnsetAccessFlags the class access flags that must be
+ * unset in order for the class to apply.
+ * @param annotationType the name of the class that must be an
+ * annotation of the class in order for it
+ * to apply. The name may be null to
+ * specify that no annotation is required.
+ * @param className the class name. The name may be null to
+ * specify any class, or it may contain
+ * "**", "*", or "?" wildcards.
+ * @param extendsAnnotationType the name of the class of that must be
+ * an annotation of the class that the
+ * class must extend or implement in order
+ * to apply. The name may be null to
+ * specify that no annotation is required.
+ * @param extendsClassName the name of the class that the class
+ * must extend or implement in order to
+ * apply. The name may be null to specify
+ * any class.
+ * @param fieldSpecifications the field specifications.
+ * @param methodSpecifications the method specifications.
+ */
+ public ClassSpecification(String comments,
+ int requiredSetAccessFlags,
+ int requiredUnsetAccessFlags,
+ String annotationType,
+ String className,
+ String extendsAnnotationType,
+ String extendsClassName,
+ List fieldSpecifications,
+ List methodSpecifications)
+ {
+ this.comments = comments;
+ this.requiredSetAccessFlags = requiredSetAccessFlags;
+ this.requiredUnsetAccessFlags = requiredUnsetAccessFlags;
+ this.annotationType = annotationType;
+ this.className = className;
+ this.extendsAnnotationType = extendsAnnotationType;
+ this.extendsClassName = extendsClassName;
+ this.fieldSpecifications = fieldSpecifications;
+ this.methodSpecifications = methodSpecifications;
+ }
+
+
+ /**
+ * Specifies to keep the specified field(s) of this option's class(es).
+ *
+ * @param fieldSpecification the field specification.
+ */
+ public void addField(MemberSpecification fieldSpecification)
+ {
+ if (fieldSpecifications == null)
+ {
+ fieldSpecifications = new ArrayList();
+ }
+
+ fieldSpecifications.add(fieldSpecification);
+ }
+
+
+ /**
+ * Specifies to keep the specified method(s) of this option's class(es).
+ *
+ * @param methodSpecification the method specification.
+ */
+ public void addMethod(MemberSpecification methodSpecification)
+ {
+ if (methodSpecifications == null)
+ {
+ methodSpecifications = new ArrayList();
+ }
+
+ methodSpecifications.add(methodSpecification);
+ }
+
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ ClassSpecification other = (ClassSpecification)object;
+ return
+// (this.comments == null ? other.comments == null : this.comments.equals(other.comments) ) &&
+ (this.requiredSetAccessFlags == other.requiredSetAccessFlags ) &&
+ (this.requiredUnsetAccessFlags == other.requiredUnsetAccessFlags ) &&
+ (this.annotationType == null ? other.annotationType == null : this.annotationType.equals(other.annotationType) ) &&
+ (this.className == null ? other.className == null : this.className.equals(other.className) ) &&
+ (this.extendsAnnotationType == null ? other.extendsAnnotationType == null : this.extendsAnnotationType.equals(other.extendsAnnotationType)) &&
+ (this.extendsClassName == null ? other.extendsClassName == null : this.extendsClassName.equals(other.extendsClassName) ) &&
+ (this.fieldSpecifications == null ? other.fieldSpecifications == null : this.fieldSpecifications.equals(other.fieldSpecifications) ) &&
+ (this.methodSpecifications == null ? other.methodSpecifications == null : this.methodSpecifications.equals(other.methodSpecifications) );
+ }
+
+ public int hashCode()
+ {
+ return
+// (comments == null ? 0 : comments.hashCode() ) ^
+ (requiredSetAccessFlags ) ^
+ (requiredUnsetAccessFlags ) ^
+ (annotationType == null ? 0 : annotationType.hashCode() ) ^
+ (className == null ? 0 : className.hashCode() ) ^
+ (extendsAnnotationType == null ? 0 : extendsAnnotationType.hashCode()) ^
+ (extendsClassName == null ? 0 : extendsClassName.hashCode() ) ^
+ (fieldSpecifications == null ? 0 : fieldSpecifications.hashCode() ) ^
+ (methodSpecifications == null ? 0 : methodSpecifications.hashCode() );
+ }
+
+ public Object clone()
+ {
+ try
+ {
+ return super.clone();
+ }
+ catch (CloneNotSupportedException e)
+ {
+ return null;
+ }
+ }
+}
diff --git a/src/proguard/ClassSpecificationVisitorFactory.java b/src/proguard/ClassSpecificationVisitorFactory.java
new file mode 100644
index 000000000..dc5d71f65
--- /dev/null
+++ b/src/proguard/ClassSpecificationVisitorFactory.java
@@ -0,0 +1,503 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.visitor.AllAttributeVisitor;
+import proguard.classfile.visitor.*;
+
+import java.util.List;
+
+/**
+ * This factory creates visitors to efficiently travel to specified classes and
+ * class members.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassSpecificationVisitorFactory
+{
+ /**
+ * Constructs a ClassPoolVisitor to efficiently travel to the specified
+ * classes and class members.
+ *
+ * @param keepClassSpecifications the list of KeepClassSpecification
+ * instances, defining of the classes and
+ * class members to visit.
+ * @param classVisitor the ClassVisitor to be applied to matching
+ * classes.
+ * @param memberVisitor the MemberVisitor to be applied to matching
+ * class members.
+ */
+ public static ClassPoolVisitor createClassPoolVisitor(List keepClassSpecifications,
+ ClassVisitor classVisitor,
+ MemberVisitor memberVisitor,
+ boolean shrinking,
+ boolean optimizing,
+ boolean obfuscating)
+ {
+ MultiClassPoolVisitor multiClassPoolVisitor = new MultiClassPoolVisitor();
+
+ if (keepClassSpecifications != null)
+ {
+ for (int index = 0; index < keepClassSpecifications.size(); index++)
+ {
+ KeepClassSpecification keepClassSpecification =
+ (KeepClassSpecification)keepClassSpecifications.get(index);
+
+ if ((shrinking && !keepClassSpecification.allowShrinking) ||
+ (optimizing && !keepClassSpecification.allowOptimization) ||
+ (obfuscating && !keepClassSpecification.allowObfuscation))
+ {
+ multiClassPoolVisitor.addClassPoolVisitor(
+ createClassPoolVisitor(keepClassSpecification,
+ classVisitor,
+ memberVisitor));
+ }
+ }
+ }
+
+ return multiClassPoolVisitor;
+ }
+
+
+ /**
+ * Constructs a ClassPoolVisitor to efficiently travel to the specified
+ * classes and class members.
+ *
+ * @param classSpecifications the list of ClassSpecification instances,
+ * defining of the classes and class members to
+ * visit.
+ * @param classVisitor the ClassVisitor to be applied to matching
+ * classes.
+ * @param memberVisitor the MemberVisitor to be applied to matching
+ * class members.
+ */
+ public static ClassPoolVisitor createClassPoolVisitor(List classSpecifications,
+ ClassVisitor classVisitor,
+ MemberVisitor memberVisitor)
+ {
+ MultiClassPoolVisitor multiClassPoolVisitor = new MultiClassPoolVisitor();
+
+ if (classSpecifications != null)
+ {
+ for (int index = 0; index < classSpecifications.size(); index++)
+ {
+ ClassSpecification classSpecification =
+ (ClassSpecification)classSpecifications.get(index);
+
+ multiClassPoolVisitor.addClassPoolVisitor(
+ createClassPoolVisitor(classSpecification,
+ classVisitor,
+ memberVisitor));
+ }
+ }
+
+ return multiClassPoolVisitor;
+ }
+
+
+ /**
+ * Constructs a ClassPoolVisitor to efficiently travel to the specified
+ * classes and class members.
+ *
+ * @param keepClassSpecification the specifications of the class(es) and class
+ * members to visit.
+ * @param classVisitor the ClassVisitor to be applied to matching
+ * classes.
+ * @param memberVisitor the MemberVisitor to be applied to matching
+ * class members.
+ */
+ private static ClassPoolVisitor createClassPoolVisitor(KeepClassSpecification keepClassSpecification,
+ ClassVisitor classVisitor,
+ MemberVisitor memberVisitor)
+ {
+ // Don't visit the classes if not specified.
+ if (!keepClassSpecification.markClasses &&
+ !keepClassSpecification.markConditionally)
+ {
+ classVisitor = null;
+ }
+
+ // If specified, let the marker visit the class and its class
+ // members conditionally.
+ if (keepClassSpecification.markConditionally)
+ {
+ // Combine both visitors.
+ ClassVisitor composedClassVisitor =
+ createCombinedClassVisitor(keepClassSpecification,
+ classVisitor,
+ memberVisitor);
+
+ // Replace the class visitor.
+ classVisitor =
+ createClassMemberTester(keepClassSpecification,
+ composedClassVisitor);
+
+ // Discard the member visitor, because it has already been included.
+ memberVisitor = null;
+ }
+
+ return createClassPoolVisitor((ClassSpecification)keepClassSpecification,
+ classVisitor,
+ memberVisitor);
+ }
+
+
+ /**
+ * Constructs a ClassPoolVisitor to efficiently travel to the specified
+ * classes and class members.
+ *
+ * @param classSpecification the specifications of the class(es) and class
+ * members to visit.
+ * @param classVisitor the ClassVisitor to be applied to matching
+ * classes.
+ * @param memberVisitor the MemberVisitor to be applied to matching
+ * class members.
+ */
+ private static ClassPoolVisitor createClassPoolVisitor(ClassSpecification classSpecification,
+ ClassVisitor classVisitor,
+ MemberVisitor memberVisitor)
+ {
+ // Combine both visitors.
+ ClassVisitor composedClassVisitor =
+ createCombinedClassVisitor(classSpecification,
+ classVisitor,
+ memberVisitor);
+
+ // By default, start visiting from the named class name, if specified.
+ String className = classSpecification.className;
+
+ // Although we may have to start from the extended class.
+ String extendsAnnotationType = classSpecification.extendsAnnotationType;
+ String extendsClassName = classSpecification.extendsClassName;
+
+ // If wildcarded, only visit classes with matching names.
+ if (className != null &&
+ (extendsAnnotationType != null ||
+ extendsClassName != null ||
+ containsWildCards(className)))
+ {
+ composedClassVisitor =
+ new ClassNameFilter(className, composedClassVisitor);
+
+ // We'll have to visit all classes now.
+ className = null;
+ }
+
+ // If specified, only visit classes with the right annotation.
+ String annotationType = classSpecification.annotationType;
+
+ if (annotationType != null)
+ {
+ composedClassVisitor =
+ new AllAttributeVisitor(
+ new AllAnnotationVisitor(
+ new AnnotationTypeFilter(annotationType,
+ new AnnotatedClassVisitor(composedClassVisitor))));
+ }
+
+ // If specified, only visit classes with the right access flags.
+ if (classSpecification.requiredSetAccessFlags != 0 ||
+ classSpecification.requiredUnsetAccessFlags != 0)
+ {
+ composedClassVisitor =
+ new ClassAccessFilter(classSpecification.requiredSetAccessFlags,
+ classSpecification.requiredUnsetAccessFlags,
+ composedClassVisitor);
+ }
+
+ // If it's specified, start visiting from the extended class.
+ if (extendsAnnotationType != null ||
+ extendsClassName != null)
+ {
+ // Start visiting from the extended class.
+ composedClassVisitor =
+ new ClassHierarchyTraveler(false, false, false, true,
+ composedClassVisitor);
+
+ // If specified, only visit extended classes with the right annotation.
+ if (extendsAnnotationType != null)
+ {
+ composedClassVisitor =
+ new AllAttributeVisitor(
+ new AllAnnotationVisitor(
+ new AnnotationTypeFilter(extendsAnnotationType,
+ new AnnotatedClassVisitor(composedClassVisitor))));
+ }
+
+ // If specified, only visit extended classes with matching names.
+ if (extendsClassName != null)
+ {
+ // If wildcarded, only visit extended classes with matching names.
+ if (containsWildCards(extendsClassName))
+ {
+ composedClassVisitor =
+ new ClassNameFilter(extendsClassName,
+ composedClassVisitor);
+ }
+ else
+ {
+ // Start visiting from the named extended class.
+ className = extendsClassName;
+ }
+ }
+ }
+
+ // If specified, visit a single named class, otherwise visit all classes.
+ return className != null ?
+ (ClassPoolVisitor)new NamedClassVisitor(composedClassVisitor, className) :
+ (ClassPoolVisitor)new AllClassVisitor(composedClassVisitor);
+ }
+
+
+ /**
+ * Constructs a ClassVisitor to efficiently travel to the specified
+ * classes and class members.
+ *
+ * @param classSpecification the specifications of the class(es) and class
+ * members to visit.
+ * @param classVisitor the ClassVisitor to be applied to matching
+ * classes.
+ * @param memberVisitor the MemberVisitor to be applied to matching
+ * class members.
+ */
+ private static ClassVisitor createCombinedClassVisitor(ClassSpecification classSpecification,
+ ClassVisitor classVisitor,
+ MemberVisitor memberVisitor)
+ {
+ // Don't visit any members if there aren't any member specifications.
+ if (classSpecification.fieldSpecifications == null &&
+ classSpecification.methodSpecifications == null)
+ {
+ memberVisitor = null;
+ }
+
+ // The class visitor for classes and their members.
+ MultiClassVisitor multiClassVisitor = new MultiClassVisitor();
+
+ // If specified, let the class visitor visit the class itself.
+ if (classVisitor != null)
+ {
+ // This class visitor may be the only one.
+ if (memberVisitor == null)
+ {
+ return classVisitor;
+ }
+
+ multiClassVisitor.addClassVisitor(classVisitor);
+ }
+
+ // If specified, let the member info visitor visit the class members.
+ if (memberVisitor != null)
+ {
+ ClassVisitor memberClassVisitor =
+ createClassVisitor(classSpecification, memberVisitor);
+
+ // This class visitor may be the only one.
+ if (classVisitor == null)
+ {
+ return memberClassVisitor;
+ }
+
+ multiClassVisitor.addClassVisitor(memberClassVisitor);
+ }
+
+ return multiClassVisitor;
+ }
+
+
+ /**
+ * Constructs a ClassVisitor to efficiently travel to the specified class
+ * members.
+ *
+ * @param classSpecification the specifications of the class members to visit.
+ * @param memberVisitor the MemberVisitor to be applied to matching
+ * class members.
+ */
+ private static ClassVisitor createClassVisitor(ClassSpecification classSpecification,
+ MemberVisitor memberVisitor)
+ {
+ MultiClassVisitor multiClassVisitor = new MultiClassVisitor();
+
+ addMemberVisitors(classSpecification.fieldSpecifications, true, multiClassVisitor, memberVisitor);
+ addMemberVisitors(classSpecification.methodSpecifications, false, multiClassVisitor, memberVisitor);
+
+ // Mark the class member in this class and in super classes.
+ return new ClassHierarchyTraveler(true, true, false, false,
+ multiClassVisitor);
+ }
+
+
+ /**
+ * Adds elements to the given MultiClassVisitor, to apply the given
+ * MemberVisitor to all class members that match the given List
+ * of options (of the given type).
+ */
+ private static void addMemberVisitors(List memberSpecifications,
+ boolean isField,
+ MultiClassVisitor multiClassVisitor,
+ MemberVisitor memberVisitor)
+ {
+ if (memberSpecifications != null)
+ {
+ for (int index = 0; index < memberSpecifications.size(); index++)
+ {
+ MemberSpecification memberSpecification =
+ (MemberSpecification)memberSpecifications.get(index);
+
+ multiClassVisitor.addClassVisitor(
+ createClassVisitor(memberSpecification,
+ isField,
+ memberVisitor));
+ }
+ }
+ }
+
+
+ /**
+ * Constructs a ClassVisitor that conditionally applies the given
+ * ClassVisitor to all classes that contain the given class members.
+ */
+ private static ClassVisitor createClassMemberTester(ClassSpecification classSpecification,
+ ClassVisitor classVisitor)
+ {
+ // Create a linked list of conditional visitors, for fields and for
+ // methods.
+ return createClassMemberTester(classSpecification.fieldSpecifications,
+ true,
+ createClassMemberTester(classSpecification.methodSpecifications,
+ false,
+ classVisitor));
+ }
+
+
+ /**
+ * Constructs a ClassVisitor that conditionally applies the given
+ * ClassVisitor to all classes that contain the given List of class
+ * members (of the given type).
+ */
+ private static ClassVisitor createClassMemberTester(List memberSpecifications,
+ boolean isField,
+ ClassVisitor classVisitor)
+ {
+ // Create a linked list of conditional visitors.
+ if (memberSpecifications != null)
+ {
+ for (int index = 0; index < memberSpecifications.size(); index++)
+ {
+ MemberSpecification memberSpecification =
+ (MemberSpecification)memberSpecifications.get(index);
+
+ classVisitor =
+ createClassVisitor(memberSpecification,
+ isField,
+ new MemberToClassVisitor(classVisitor));
+ }
+ }
+
+ return classVisitor;
+ }
+
+
+ /**
+ * Creates a new ClassVisitor to efficiently travel to the specified class
+ * members.
+ *
+ * @param memberSpecification the specification of the class member(s) to
+ * visit.
+ * @param memberVisitor the MemberVisitor to be applied to matching
+ * class member(s).
+ */
+ private static ClassVisitor createClassVisitor(MemberSpecification memberSpecification,
+ boolean isField,
+ MemberVisitor memberVisitor)
+ {
+ String name = memberSpecification.name;
+ String descriptor = memberSpecification.descriptor;
+
+ // If name or descriptor are not fully specified, only visit matching
+ // class members.
+ boolean fullySpecified =
+ name != null &&
+ descriptor != null &&
+ !containsWildCards(name) &&
+ !containsWildCards(descriptor);
+
+ if (!fullySpecified)
+ {
+ if (descriptor != null)
+ {
+ memberVisitor =
+ new MemberDescriptorFilter(descriptor, memberVisitor);
+ }
+
+ if (name != null)
+ {
+ memberVisitor =
+ new MemberNameFilter(name, memberVisitor);
+ }
+ }
+
+ // If specified, only visit class members with the right annotation.
+ if (memberSpecification.annotationType != null)
+ {
+ memberVisitor =
+ new AllAttributeVisitor(
+ new AllAnnotationVisitor(
+ new AnnotationTypeFilter(memberSpecification.annotationType,
+ new AnnotationToMemberVisitor(memberVisitor))));
+ }
+
+ // If any access flags are specified, only visit matching class members.
+ if (memberSpecification.requiredSetAccessFlags != 0 ||
+ memberSpecification.requiredUnsetAccessFlags != 0)
+ {
+ memberVisitor =
+ new MemberAccessFilter(memberSpecification.requiredSetAccessFlags,
+ memberSpecification.requiredUnsetAccessFlags,
+ memberVisitor);
+ }
+
+ // Depending on what's specified, visit a single named class member,
+ // or all class members, filtering the matching ones.
+ return isField ?
+ fullySpecified ?
+ (ClassVisitor)new NamedFieldVisitor(name, descriptor, memberVisitor) :
+ (ClassVisitor)new AllFieldVisitor(memberVisitor) :
+ fullySpecified ?
+ (ClassVisitor)new NamedMethodVisitor(name, descriptor, memberVisitor) :
+ (ClassVisitor)new AllMethodVisitor(memberVisitor);
+ }
+
+
+ // Small utility methods.
+
+ private static boolean containsWildCards(String string)
+ {
+ return string != null &&
+ (string.indexOf('!') >= 0 ||
+ string.indexOf('*') >= 0 ||
+ string.indexOf('?') >= 0 ||
+ string.indexOf('%') >= 0 ||
+ string.indexOf(',') >= 0 ||
+ string.indexOf("///") >= 0);
+ }
+}
diff --git a/src/proguard/Configuration.java b/src/proguard/Configuration.java
new file mode 100644
index 000000000..471126054
--- /dev/null
+++ b/src/proguard/Configuration.java
@@ -0,0 +1,331 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import java.io.File;
+import java.util.List;
+
+/**
+ * The ProGuard configuration.
+ *
+ * @see ProGuard
+ *
+ * @author Eric Lafortune
+ */
+public class Configuration
+{
+ public static final File STD_OUT = new File("");
+
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Input and output options.
+ ///////////////////////////////////////////////////////////////////////////
+
+ /**
+ * A list of input and output entries (jars, wars, ears, zips, and directories).
+ */
+ public ClassPath programJars;
+
+ /**
+ * A list of library entries (jars, wars, ears, zips, and directories).
+ */
+ public ClassPath libraryJars;
+
+ /**
+ * Specifies whether to skip non-public library classes while reading
+ * library jars.
+ */
+ public boolean skipNonPublicLibraryClasses = false;
+
+ /**
+ * Specifies whether to skip non-public library class members while reading
+ * library classes.
+ */
+ public boolean skipNonPublicLibraryClassMembers = true;
+
+ /**
+ * A list of String
s specifying directories to be kept in
+ * the output directories or the output jars. A null
list
+ * means no directories. An empty list means all directories. The directory
+ * names may contain "**", "*", or "?" wildcards, and they may be preceded
+ * by the "!" negator.
+ */
+ public List keepDirectories;
+
+ /**
+ * Specifies the version number of the output classes, or 0 if the version
+ * number can be left unchanged.
+ */
+ public int targetClassVersion;
+
+ /**
+ * Specifies the last modification time of this configuration. This time
+ * is necessary to check whether the input has to be processed. Setting it
+ * to Long.MAX_VALUE forces processing, even if the modification times
+ * of the output appear more recent than the modification times of the
+ * input.
+ */
+ public long lastModified = 0L;
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Keep options.
+ ///////////////////////////////////////////////////////////////////////////
+
+ /**
+ * A list of {@link KeepClassSpecification} instances, whose class names and
+ * class member names are to be kept from shrinking, optimization, and/or
+ * obfuscation.
+ */
+ public List keep;
+
+ /**
+ * An optional output file for listing the kept seeds.
+ * An empty file name means the standard output.
+ */
+ public File printSeeds;
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Shrinking options.
+ ///////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Specifies whether the code should be shrunk.
+ */
+ public boolean shrink = true;
+
+ /**
+ * An optional output file for listing the unused classes and class
+ * members. An empty file name means the standard output.
+ */
+ public File printUsage;
+
+ /**
+ * A list of {@link ClassSpecification} instances, for which an explanation
+ * is to be printed, why they are kept in the shrinking step.
+ */
+ public List whyAreYouKeeping;
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Optimization options.
+ ///////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Specifies whether the code should be optimized.
+ */
+ public boolean optimize = true;
+
+ /**
+ * A list of String
s specifying the optimizations to be
+ * performed. A null
list means all optimizations. The
+ * optimization names may contain "*" or "?" wildcards, and they may
+ * be preceded by the "!" negator.
+ */
+ public List optimizations;
+
+ /**
+ * Specifies the number of optimization passes.
+ */
+ public int optimizationPasses = 1;
+
+ /**
+ * A list of {@link ClassSpecification} instances, whose methods are
+ * assumed to have no side effects.
+ */
+ public List assumeNoSideEffects;
+
+ /**
+ * Specifies whether the access of class members can be modified.
+ */
+ public boolean allowAccessModification = false;
+
+ /**
+ * Specifies whether interfaces may be merged aggressively.
+ */
+ public boolean mergeInterfacesAggressively = false;
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Obfuscation options.
+ ///////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Specifies whether the code should be obfuscated.
+ */
+ public boolean obfuscate = true;
+
+ /**
+ * An optional output file for listing the obfuscation mapping.
+ * An empty file name means the standard output.
+ */
+ public File printMapping;
+
+ /**
+ * An optional input file for reading an obfuscation mapping.
+ */
+ public File applyMapping;
+
+ /**
+ * An optional name of a file containing obfuscated class member names.
+ */
+ public File obfuscationDictionary;
+
+ /**
+ * An optional name of a file containing obfuscated class names.
+ */
+ public File classObfuscationDictionary;
+
+ /**
+ * An optional name of a file containing obfuscated package names.
+ */
+ public File packageObfuscationDictionary;
+
+ /**
+ * Specifies whether to apply aggressive name overloading on class members.
+ */
+ public boolean overloadAggressively = false;
+
+ /**
+ * Specifies whether to generate globally unique class member names.
+ */
+ public boolean useUniqueClassMemberNames = false;
+
+ /**
+ * Specifies whether obfuscated packages and classes can get mixed-case names.
+ */
+ public boolean useMixedCaseClassNames = true;
+
+ /**
+ * A list of String
s specifying package names to be kept.
+ * A null
list means no names. An empty list means all
+ * names. The package names may contain "**", "*", or "?" wildcards, and
+ * they may be preceded by the "!" negator.
+ */
+ public List keepPackageNames;
+
+ /**
+ * An optional base package if the obfuscated package hierarchy is to be
+ * flattened, null
otherwise.
+ */
+ public String flattenPackageHierarchy;
+
+ /**
+ * An optional base package if the obfuscated classes are to be repackaged
+ * into a single package, null
otherwise.
+ */
+ public String repackageClasses;
+
+ /**
+ * A list of String
s specifying optional attributes to be kept.
+ * A null
list means no attributes. An empty list means all
+ * attributes. The attribute names may contain "*" or "?" wildcards, and
+ * they may be preceded by the "!" negator.
+ */
+ public List keepAttributes;
+
+ /**
+ * Specifies whether method parameter names and types should be kept for
+ * methods that are not obfuscated. This is achieved by keeping partial
+ * "LocalVariableTable" and "LocalVariableTypeTable" attributes.
+ */
+ public boolean keepParameterNames = false;
+
+ /**
+ * An optional replacement for all SourceFile attributes.
+ */
+ public String newSourceFileAttribute;
+
+ /**
+ * A list of String
s specifying a filter for classes whose
+ * string constants are to be adapted, based on corresponding obfuscated
+ * class names.
+ */
+ public List adaptClassStrings;
+
+ /**
+ * A list of String
s specifying a filter for files whose
+ * names are to be adapted, based on corresponding obfuscated class names.
+ */
+ public List adaptResourceFileNames;
+
+ /**
+ * A list of String
s specifying a filter for files whose
+ * contents are to be adapted, based on obfuscated class names.
+ */
+ public List adaptResourceFileContents;
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Preverification options.
+ ///////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Specifies whether the code should be preverified.
+ */
+ public boolean preverify = true;
+
+ /**
+ * Specifies whether the code should be preverified for Java Micro Edition
+ * (creating StackMap attributes) instead of for Java Standard Edition
+ * (creating StackMapTable attributes).
+ */
+ public boolean microEdition = false;
+
+ ///////////////////////////////////////////////////////////////////////////
+ // General options.
+ ///////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Specifies whether to print verbose messages.
+ */
+ public boolean verbose = false;
+
+ /**
+ * A list of String
s specifying a filter for the classes for
+ * which not to print notes, if there are noteworthy potential problems.
+ * A null
list means all classes. The class names may contain
+ * "**", "*", or "?" wildcards, and they may be preceded by the "!" negator.
+ */
+ public List note = null;
+
+ /**
+ * A list of String
s specifying a filter for the classes for
+ * which not to print warnings, if there are any problems.
+ * A null
list means all classes. The class names may contain
+ * "**", "*", or "?" wildcards, and they may be preceded by the "!" negator.
+ */
+ public List warn = null;
+
+ /**
+ * Specifies whether to ignore any warnings.
+ */
+ public boolean ignoreWarnings = false;
+
+ /**
+ * An optional output file for printing out the configuration that ProGuard
+ * is using (with included files and replaced variables).
+ * An empty file name means the standard output.
+ */
+ public File printConfiguration;
+
+ /**
+ * An optional output file for printing out the processed code in a more
+ * or less readable form. An empty file name means the standard output.
+ */
+ public File dump;
+}
diff --git a/src/proguard/ConfigurationConstants.java b/src/proguard/ConfigurationConstants.java
new file mode 100644
index 000000000..14c565475
--- /dev/null
+++ b/src/proguard/ConfigurationConstants.java
@@ -0,0 +1,123 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+/**
+ * This class provides constants for parsing and writing ProGuard configurations.
+ *
+ * @author Eric Lafortune
+ */
+class ConfigurationConstants
+{
+ public static final String OPTION_PREFIX = "-";
+ public static final String AT_DIRECTIVE = "@";
+ public static final String INCLUDE_DIRECTIVE = "-include";
+ public static final String BASE_DIRECTORY_DIRECTIVE = "-basedirectory";
+
+ public static final String INJARS_OPTION = "-injars";
+ public static final String OUTJARS_OPTION = "-outjars";
+ public static final String LIBRARYJARS_OPTION = "-libraryjars";
+ public static final String RESOURCEJARS_OPTION = "-resourcejars";
+
+ public static final String KEEP_OPTION = "-keep";
+ public static final String KEEP_CLASS_MEMBERS_OPTION = "-keepclassmembers";
+ public static final String KEEP_CLASSES_WITH_MEMBERS_OPTION = "-keepclasseswithmembers";
+ public static final String KEEP_NAMES_OPTION = "-keepnames";
+ public static final String KEEP_CLASS_MEMBER_NAMES_OPTION = "-keepclassmembernames";
+ public static final String KEEP_CLASSES_WITH_MEMBER_NAMES_OPTION = "-keepclasseswithmembernames";
+ public static final String ALLOW_SHRINKING_SUBOPTION = "allowshrinking";
+ public static final String ALLOW_OPTIMIZATION_SUBOPTION = "allowoptimization";
+ public static final String ALLOW_OBFUSCATION_SUBOPTION = "allowobfuscation";
+ public static final String PRINT_SEEDS_OPTION = "-printseeds";
+
+ public static final String DONT_SHRINK_OPTION = "-dontshrink";
+ public static final String PRINT_USAGE_OPTION = "-printusage";
+ public static final String WHY_ARE_YOU_KEEPING_OPTION = "-whyareyoukeeping";
+
+ public static final String DONT_OPTIMIZE_OPTION = "-dontoptimize";
+ public static final String OPTIMIZATIONS = "-optimizations";
+ public static final String OPTIMIZATION_PASSES = "-optimizationpasses";
+ public static final String ASSUME_NO_SIDE_EFFECTS_OPTION = "-assumenosideeffects";
+ public static final String ALLOW_ACCESS_MODIFICATION_OPTION = "-allowaccessmodification";
+ public static final String MERGE_INTERFACES_AGGRESSIVELY_OPTION = "-mergeinterfacesaggressively";
+
+ public static final String DONT_OBFUSCATE_OPTION = "-dontobfuscate";
+ public static final String PRINT_MAPPING_OPTION = "-printmapping";
+ public static final String APPLY_MAPPING_OPTION = "-applymapping";
+ public static final String OBFUSCATION_DICTIONARY_OPTION = "-obfuscationdictionary";
+ public static final String CLASS_OBFUSCATION_DICTIONARY_OPTION = "-classobfuscationdictionary";
+ public static final String PACKAGE_OBFUSCATION_DICTIONARY_OPTION = "-packageobfuscationdictionary";
+ public static final String OVERLOAD_AGGRESSIVELY_OPTION = "-overloadaggressively";
+ public static final String USE_UNIQUE_CLASS_MEMBER_NAMES_OPTION = "-useuniqueclassmembernames";
+ public static final String DONT_USE_MIXED_CASE_CLASS_NAMES_OPTION = "-dontusemixedcaseclassnames";
+ public static final String KEEP_PACKAGE_NAMES_OPTION = "-keeppackagenames";
+ public static final String FLATTEN_PACKAGE_HIERARCHY_OPTION = "-flattenpackagehierarchy";
+ public static final String REPACKAGE_CLASSES_OPTION = "-repackageclasses";
+ public static final String DEFAULT_PACKAGE_OPTION = "-defaultpackage";
+ public static final String KEEP_ATTRIBUTES_OPTION = "-keepattributes";
+ public static final String KEEP_PARAMETER_NAMES_OPTION = "-keepparameternames";
+ public static final String RENAME_SOURCE_FILE_ATTRIBUTE_OPTION = "-renamesourcefileattribute";
+ public static final String ADAPT_CLASS_STRINGS_OPTION = "-adaptclassstrings";
+ public static final String ADAPT_RESOURCE_FILE_NAMES_OPTION = "-adaptresourcefilenames";
+ public static final String ADAPT_RESOURCE_FILE_CONTENTS_OPTION = "-adaptresourcefilecontents";
+
+ public static final String DONT_PREVERIFY_OPTION = "-dontpreverify";
+ public static final String MICRO_EDITION_OPTION = "-microedition";
+
+ public static final String VERBOSE_OPTION = "-verbose";
+ public static final String DONT_NOTE_OPTION = "-dontnote";
+ public static final String DONT_WARN_OPTION = "-dontwarn";
+ public static final String IGNORE_WARNINGS_OPTION = "-ignorewarnings";
+ public static final String PRINT_CONFIGURATION_OPTION = "-printconfiguration";
+ public static final String DUMP_OPTION = "-dump";
+ public static final String SKIP_NON_PUBLIC_LIBRARY_CLASSES_OPTION = "-skipnonpubliclibraryclasses";
+ public static final String DONT_SKIP_NON_PUBLIC_LIBRARY_CLASSES_OPTION = "-dontskipnonpubliclibraryclasses";
+ public static final String DONT_SKIP_NON_PUBLIC_LIBRARY_CLASS_MEMBERS_OPTION = "-dontskipnonpubliclibraryclassmembers";
+ public static final String TARGET_OPTION = "-target";
+ public static final String KEEP_DIRECTORIES_OPTION = "-keepdirectories";
+ public static final String FORCE_PROCESSING_OPTION = "-forceprocessing";
+
+ public static final String ANY_ATTRIBUTE_KEYWORD = "*";
+ public static final String ATTRIBUTE_SEPARATOR_KEYWORD = ",";
+
+ public static final String JAR_SEPARATOR_KEYWORD = System.getProperty("path.separator");
+
+ public static final char OPEN_SYSTEM_PROPERTY = '<';
+ public static final char CLOSE_SYSTEM_PROPERTY = '>';
+
+ public static final String ANNOTATION_KEYWORD = "@";
+ public static final String NEGATOR_KEYWORD = "!";
+ public static final String CLASS_KEYWORD = "class";
+ public static final String ANY_CLASS_KEYWORD = "*";
+ public static final String ANY_TYPE_KEYWORD = "***";
+ public static final String IMPLEMENTS_KEYWORD = "implements";
+ public static final String EXTENDS_KEYWORD = "extends";
+ public static final String OPEN_KEYWORD = "{";
+ public static final String ANY_CLASS_MEMBER_KEYWORD = "*";
+ public static final String ANY_FIELD_KEYWORD = "WordReader
that returns words from a file or a URL.
+ *
+ * @author Eric Lafortune
+ */
+public class FileWordReader extends LineWordReader
+{
+ /**
+ * Creates a new FileWordReader for the given file.
+ */
+ public FileWordReader(File file) throws IOException
+ {
+ super(new LineNumberReader(new BufferedReader(new FileReader(file))),
+ "file '" + file.getPath() + "'",
+ file.getParentFile()
+ );
+ }
+
+
+ /**
+ * Creates a new FileWordReader for the given URL.
+ */
+ public FileWordReader(URL url) throws IOException
+ {
+ super(new LineNumberReader(new BufferedReader(new InputStreamReader(url.openStream()))),
+ "file '" + url.toString() + "'",
+ null);
+ }
+}
diff --git a/src/proguard/FullyQualifiedClassNameChecker.java b/src/proguard/FullyQualifiedClassNameChecker.java
new file mode 100644
index 000000000..eb1865a9d
--- /dev/null
+++ b/src/proguard/FullyQualifiedClassNameChecker.java
@@ -0,0 +1,191 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+import java.util.List;
+
+/**
+ * This class checks if the user has forgotten to fully qualify any classes
+ * in the configuration.
+ *
+ * @author Eric Lafortune
+ */
+public class FullyQualifiedClassNameChecker
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final ClassPool programClassPool;
+ private final ClassPool libraryClassPool;
+ private final WarningPrinter notePrinter;
+
+
+ /**
+ * Creates a new FullyQualifiedClassNameChecker.
+ */
+ public FullyQualifiedClassNameChecker(ClassPool programClassPool,
+ ClassPool libraryClassPool,
+ WarningPrinter notePrinter)
+ {
+ this.programClassPool = programClassPool;
+ this.libraryClassPool = libraryClassPool;
+ this.notePrinter = notePrinter;
+ }
+
+
+ /**
+ * Checks the classes mentioned in the given class specifications, printing
+ * notes if necessary.
+ */
+ public void checkClassSpecifications(List classSpecifications)
+ {
+ if (classSpecifications != null)
+ {
+ for (int index = 0; index < classSpecifications.size(); index++)
+ {
+ ClassSpecification classSpecification =
+ (ClassSpecification)classSpecifications.get(index);
+
+ checkType(classSpecification.annotationType);
+ checkClassName(classSpecification.className);
+ checkType(classSpecification.extendsAnnotationType);
+ checkClassName(classSpecification.extendsClassName);
+
+ checkMemberSpecifications(classSpecification.fieldSpecifications, true);
+ checkMemberSpecifications(classSpecification.methodSpecifications, false);
+ }
+ }
+ }
+
+
+ /**
+ * Checks the classes mentioned in the given class member specifications,
+ * printing notes if necessary.
+ */
+ private void checkMemberSpecifications(List memberSpecifications, boolean isField)
+ {
+ if (memberSpecifications != null)
+ {
+ for (int index = 0; index < memberSpecifications.size(); index++)
+ {
+ MemberSpecification memberSpecification =
+ (MemberSpecification)memberSpecifications.get(index);
+
+ checkType(memberSpecification.annotationType);
+
+ if (isField)
+ {
+ checkType(memberSpecification.descriptor);
+ }
+ else
+ {
+ checkDescriptor(memberSpecification.descriptor);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Checks the classes mentioned in the given class member descriptor,
+ * printing notes if necessary.
+ */
+ private void checkDescriptor(String descriptor)
+ {
+ if (descriptor != null)
+ {
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(descriptor);
+
+ checkType(internalTypeEnumeration.returnType());
+
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ checkType(internalTypeEnumeration.nextType());
+ }
+ }
+ }
+
+
+ /**
+ * Checks the class mentioned in the given type (if any),
+ * printing notes if necessary.
+ */
+ private void checkType(String type)
+ {
+ if (type != null)
+ {
+ checkClassName(ClassUtil.internalClassNameFromType(type));
+ }
+ }
+
+
+ /**
+ * Checks the specified class (if any),
+ * printing notes if necessary.
+ */
+ private void checkClassName(String className)
+ {
+ if (className != null &&
+ !containsWildCards(className) &&
+ programClassPool.getClass(className) == null &&
+ libraryClassPool.getClass(className) == null &&
+ notePrinter.accepts(className))
+ {
+ notePrinter.print(className,
+ "Note: the configuration refers to the unknown class '" +
+ ClassUtil.externalClassName(className) + "'");
+
+ String fullyQualifiedClassName =
+ "**" + ClassConstants.INTERNAL_PACKAGE_SEPARATOR +
+ className.substring(className.lastIndexOf(ClassConstants.INTERNAL_PACKAGE_SEPARATOR)+1);
+
+ ClassNameFilter classNameFilter =
+ new ClassNameFilter(fullyQualifiedClassName, this);
+
+ programClassPool.classesAccept(classNameFilter);
+ libraryClassPool.classesAccept(classNameFilter);
+ }
+ }
+
+
+ private static boolean containsWildCards(String string)
+ {
+ return string != null &&
+ (string.indexOf('!') >= 0 ||
+ string.indexOf('*') >= 0 ||
+ string.indexOf('?') >= 0 ||
+ string.indexOf(',') >= 0 ||
+ string.indexOf("///") >= 0);
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitAnyClass(Clazz clazz)
+ {
+ System.out.println(" Maybe you meant the fully qualified name '" +
+ ClassUtil.externalClassName(clazz.getName()) + "'?");
+ }
+}
diff --git a/src/proguard/GPL.java b/src/proguard/GPL.java
new file mode 100644
index 000000000..51220b86b
--- /dev/null
+++ b/src/proguard/GPL.java
@@ -0,0 +1,201 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * This class checks and prints out information about the GPL.
+ *
+ * @author Eric Lafortune
+ */
+public class GPL
+{
+ /**
+ * Prints out a note about the GPL if ProGuard is linked against unknown
+ * code.
+ */
+ public static void check()
+ {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ new Exception().printStackTrace(new PrintStream(out));
+ LineNumberReader reader = new LineNumberReader(
+ new InputStreamReader(
+ new ByteArrayInputStream(out.toByteArray())));
+
+ Set unknownPackageNames = unknownPackageNames(reader);
+
+ if (unknownPackageNames.size() > 0)
+ {
+ String uniquePackageNames = uniquePackageNames(unknownPackageNames);
+
+ System.out.println("ProGuard is released under the GNU General Public License. You therefore");
+ System.out.println("must ensure that programs that link to it ("+uniquePackageNames+"...)");
+ System.out.println("carry the GNU General Public License as well. Alternatively, you can");
+ System.out.println("apply for an exception with the author of ProGuard.");
+ }
+ }
+
+
+ /**
+ * Returns a set of package names from the given stack trace.
+ */
+ private static Set unknownPackageNames(LineNumberReader reader)
+ {
+ Set packageNames = new HashSet();
+
+ try
+ {
+ while (true)
+ {
+ String line = reader.readLine();
+ if (line == null)
+ {
+ break;
+ }
+
+ line = line.trim();
+ if (line.startsWith("at "))
+ {
+ line = line.substring(2).trim();
+ line = trimSuffix(line, '(');
+ line = trimSuffix(line, '.');
+ line = trimSuffix(line, '.');
+
+ if (line.length() > 0 && !isKnown(line))
+ {
+ packageNames.add(line);
+ }
+ }
+ }
+ }
+ catch (IOException ex)
+ {
+ // We'll just stop looking for more names.
+ }
+
+ return packageNames;
+ }
+
+
+ /**
+ * Returns a comma-separated list of package names from the set, excluding
+ * any subpackages of packages in the set.
+ */
+ private static String uniquePackageNames(Set packageNames)
+ {
+ StringBuffer buffer = new StringBuffer();
+
+ Iterator iterator = packageNames.iterator();
+ while (iterator.hasNext())
+ {
+ String packageName = (String)iterator.next();
+ if (!containsPrefix(packageNames, packageName))
+ {
+ buffer.append(packageName).append(", ");
+ }
+ }
+
+ return buffer.toString();
+ }
+
+
+ /**
+ * Returns a given string without the suffix, as defined by the given
+ * separator.
+ */
+ private static String trimSuffix(String string, char separator)
+ {
+ int index = string.lastIndexOf(separator);
+ return index < 0 ? "" : string.substring(0, index);
+ }
+
+
+ /**
+ * Returns whether the given set contains a prefix of the given name.
+ */
+ private static boolean containsPrefix(Set set, String name)
+ {
+ int index = 0;
+
+ while (!set.contains(name.substring(0, index)))
+ {
+ index = name.indexOf('.', index + 1);
+ if (index < 0)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Returns whether the given package name has been granted an exception
+ * against the GPL linking clause, by the copyright holder of ProGuard.
+ * This method is not legally binding, but of course the actual license is.
+ * Please contact the copyright holder if you would like an exception for
+ * your code as well.
+ */
+ private static boolean isKnown(String packageName)
+ {
+ return packageName.startsWith("java") ||
+ packageName.startsWith("sun.reflect") ||
+ packageName.startsWith("proguard") ||
+ packageName.startsWith("org.apache.tools.ant") ||
+ packageName.startsWith("org.apache.tools.maven") ||
+ packageName.startsWith("org.gradle") ||
+ packageName.startsWith("org.codehaus.groovy") ||
+ packageName.startsWith("org.eclipse") ||
+ packageName.startsWith("org.netbeans") ||
+ packageName.startsWith("com.android") ||
+ packageName.startsWith("com.sun.kvem") ||
+ packageName.startsWith("com.intel") ||
+ packageName.startsWith("net.certiv.proguarddt") ||
+ packageName.startsWith("groovy") ||
+ packageName.startsWith("scala") ||
+ packageName.startsWith("sbt") ||
+ packageName.startsWith("xsbt") ||
+ packageName.startsWith("eclipseme") ||
+ packageName.startsWith("com.neomades") ||
+ packageName.startsWith("jg.j2me") ||
+ packageName.startsWith("jg.common") ||
+ packageName.startsWith("jg.buildengine");
+ }
+
+
+ public static void main(String[] args)
+ {
+ LineNumberReader reader = new LineNumberReader(
+ new InputStreamReader(System.in));
+
+ Set unknownPackageNames = unknownPackageNames(reader);
+
+ if (unknownPackageNames.size() > 0)
+ {
+ String uniquePackageNames = uniquePackageNames(unknownPackageNames);
+
+ System.out.println(uniquePackageNames);
+ }
+ }
+}
diff --git a/src/proguard/Initializer.java b/src/proguard/Initializer.java
new file mode 100644
index 000000000..c56daa732
--- /dev/null
+++ b/src/proguard/Initializer.java
@@ -0,0 +1,433 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.ClassPool;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.visitor.AllAttributeVisitor;
+import proguard.classfile.constant.visitor.*;
+import proguard.classfile.instruction.visitor.AllInstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.util.*;
+
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * This class initializes class pools.
+ *
+ * @author Eric Lafortune
+ */
+public class Initializer
+{
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new Initializer to initialize classes according to the given
+ * configuration.
+ */
+ public Initializer(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Initializes the classes in the given program class pool and library class
+ * pool, performs some basic checks, and shrinks the library class pool.
+ */
+ public void execute(ClassPool programClassPool,
+ ClassPool libraryClassPool) throws IOException
+ {
+ int originalLibraryClassPoolSize = libraryClassPool.size();
+
+ // Perform a basic check on the keep options in the configuration.
+ WarningPrinter keepClassMemberNotePrinter = new WarningPrinter(System.out, configuration.note);
+
+ new KeepClassMemberChecker(keepClassMemberNotePrinter).checkClassSpecifications(configuration.keep);
+
+ // Construct a reduced library class pool with only those library
+ // classes whose hierarchies are referenced by the program classes.
+ // We can't do this if we later have to come up with the obfuscated
+ // class member names that are globally unique.
+ ClassPool reducedLibraryClassPool = configuration.useUniqueClassMemberNames ?
+ null : new ClassPool();
+
+ WarningPrinter classReferenceWarningPrinter = new WarningPrinter(System.err, configuration.warn);
+ WarningPrinter dependencyWarningPrinter = new WarningPrinter(System.err, configuration.warn);
+
+ // Initialize the superclass hierarchies for program classes.
+ programClassPool.classesAccept(
+ new ClassSuperHierarchyInitializer(programClassPool,
+ libraryClassPool,
+ classReferenceWarningPrinter,
+ null));
+
+ // Initialize the superclass hierarchy of all library classes, without
+ // warnings.
+ libraryClassPool.classesAccept(
+ new ClassSuperHierarchyInitializer(programClassPool,
+ libraryClassPool,
+ null,
+ dependencyWarningPrinter));
+
+ // Initialize the class references of program class members and
+ // attributes. Note that all superclass hierarchies have to be
+ // initialized for this purpose.
+ WarningPrinter memberReferenceWarningPrinter = new WarningPrinter(System.err, configuration.warn);
+
+ programClassPool.classesAccept(
+ new ClassReferenceInitializer(programClassPool,
+ libraryClassPool,
+ classReferenceWarningPrinter,
+ memberReferenceWarningPrinter,
+ null));
+
+ if (reducedLibraryClassPool != null)
+ {
+ // Collect the library classes that are directly referenced by
+ // program classes, without introspection.
+ programClassPool.classesAccept(
+ new ReferencedClassVisitor(
+ new LibraryClassFilter(
+ new ClassPoolFiller(reducedLibraryClassPool))));
+
+ // Reinitialize the superclass hierarchies of referenced library
+ // classes, this time with warnings.
+ reducedLibraryClassPool.classesAccept(
+ new ClassSuperHierarchyInitializer(programClassPool,
+ libraryClassPool,
+ classReferenceWarningPrinter,
+ null));
+ }
+
+ // Initialize the enum annotation references.
+ programClassPool.classesAccept(
+ new AllAttributeVisitor(true,
+ new AllElementValueVisitor(true,
+ new EnumFieldReferenceInitializer())));
+
+ // Initialize the Class.forName references.
+ WarningPrinter dynamicClassReferenceNotePrinter = new WarningPrinter(System.out, configuration.note);
+ WarningPrinter classForNameNotePrinter = new WarningPrinter(System.out, configuration.note);
+
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new AllInstructionVisitor(
+ new DynamicClassReferenceInitializer(programClassPool,
+ libraryClassPool,
+ dynamicClassReferenceNotePrinter,
+ null,
+ classForNameNotePrinter,
+ createClassNoteExceptionMatcher(configuration.keep))))));
+
+ // Initialize the Class.get[Declared]{Field,Method} references.
+ WarningPrinter getMemberNotePrinter = new WarningPrinter(System.out, configuration.note);
+
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new AllInstructionVisitor(
+ new DynamicMemberReferenceInitializer(programClassPool,
+ libraryClassPool,
+ getMemberNotePrinter,
+ createClassMemberNoteExceptionMatcher(configuration.keep, true),
+ createClassMemberNoteExceptionMatcher(configuration.keep, false))))));
+
+ // Initialize other string constant references, if requested.
+ if (configuration.adaptClassStrings != null)
+ {
+ programClassPool.classesAccept(
+ new ClassNameFilter(configuration.adaptClassStrings,
+ new AllConstantVisitor(
+ new StringReferenceInitializer(programClassPool,
+ libraryClassPool))));
+ }
+
+ // Print various notes, if specified.
+ WarningPrinter fullyQualifiedClassNameNotePrinter = new WarningPrinter(System.out, configuration.note);
+ WarningPrinter descriptorKeepNotePrinter = new WarningPrinter(System.out, configuration.note);
+
+ new FullyQualifiedClassNameChecker(programClassPool,
+ libraryClassPool,
+ fullyQualifiedClassNameNotePrinter).checkClassSpecifications(configuration.keep);
+
+ new DescriptorKeepChecker(programClassPool,
+ libraryClassPool,
+ descriptorKeepNotePrinter).checkClassSpecifications(configuration.keep);
+
+ // Initialize the class references of library class members.
+ if (reducedLibraryClassPool != null)
+ {
+ // Collect the library classes that are referenced by program
+ // classes, directly or indirectly, with or without introspection.
+ programClassPool.classesAccept(
+ new ReferencedClassVisitor(
+ new LibraryClassFilter(
+ new ClassHierarchyTraveler(true, true, true, false,
+ new LibraryClassFilter(
+ new ClassPoolFiller(reducedLibraryClassPool))))));
+
+ // Initialize the class references of referenced library
+ // classes, without warnings.
+ reducedLibraryClassPool.classesAccept(
+ new ClassReferenceInitializer(programClassPool,
+ libraryClassPool,
+ null,
+ null,
+ dependencyWarningPrinter));
+
+ // Reset the library class pool.
+ libraryClassPool.clear();
+
+ // Copy the library classes that are referenced directly by program
+ // classes and the library classes that are referenced by referenced
+ // library classes.
+ reducedLibraryClassPool.classesAccept(
+ new MultiClassVisitor(new ClassVisitor[]
+ {
+ new ClassHierarchyTraveler(true, true, true, false,
+ new LibraryClassFilter(
+ new ClassPoolFiller(libraryClassPool))),
+
+ new ReferencedClassVisitor(
+ new LibraryClassFilter(
+ new ClassHierarchyTraveler(true, true, true, false,
+ new LibraryClassFilter(
+ new ClassPoolFiller(libraryClassPool)))))
+ }));
+ }
+ else
+ {
+ // Initialize the class references of all library class members.
+ libraryClassPool.classesAccept(
+ new ClassReferenceInitializer(programClassPool,
+ libraryClassPool,
+ null,
+ null,
+ dependencyWarningPrinter));
+ }
+
+ // Initialize the subclass hierarchies.
+ programClassPool.classesAccept(new ClassSubHierarchyInitializer());
+ libraryClassPool.classesAccept(new ClassSubHierarchyInitializer());
+
+ // Share strings between the classes, to reduce heap memory usage.
+ programClassPool.classesAccept(new StringSharer());
+ libraryClassPool.classesAccept(new StringSharer());
+
+ // Print out a summary of the notes, if necessary.
+ int fullyQualifiedNoteCount = fullyQualifiedClassNameNotePrinter.getWarningCount();
+ if (fullyQualifiedNoteCount > 0)
+ {
+ System.out.println("Note: there were " + fullyQualifiedNoteCount +
+ " references to unknown classes.");
+ System.out.println(" You should check your configuration for typos.");
+ }
+
+ int descriptorNoteCount = descriptorKeepNotePrinter.getWarningCount();
+ if (descriptorNoteCount > 0)
+ {
+ System.out.println("Note: there were " + descriptorNoteCount +
+ " unkept descriptor classes in kept class members.");
+ System.out.println(" You should consider explicitly keeping the mentioned classes");
+ System.out.println(" (using '-keep').");
+ }
+
+ int dynamicClassReferenceNoteCount = dynamicClassReferenceNotePrinter.getWarningCount();
+ if (dynamicClassReferenceNoteCount > 0)
+ {
+ System.out.println("Note: there were " + dynamicClassReferenceNoteCount +
+ " unresolved dynamic references to classes or interfaces.");
+ System.out.println(" You should check if you need to specify additional program jars.");
+ }
+
+ int classForNameNoteCount = classForNameNotePrinter.getWarningCount();
+ if (classForNameNoteCount > 0)
+ {
+ System.out.println("Note: there were " + classForNameNoteCount +
+ " class casts of dynamically created class instances.");
+ System.out.println(" You might consider explicitly keeping the mentioned classes and/or");
+ System.out.println(" their implementations (using '-keep').");
+ }
+
+ int getmemberNoteCount = getMemberNotePrinter.getWarningCount();
+ if (getmemberNoteCount > 0)
+ {
+ System.out.println("Note: there were " + getmemberNoteCount +
+ " accesses to class members by means of introspection.");
+ System.out.println(" You should consider explicitly keeping the mentioned class members");
+ System.out.println(" (using '-keep' or '-keepclassmembers').");
+ }
+
+ // Print out a summary of the warnings, if necessary.
+ int classReferenceWarningCount = classReferenceWarningPrinter.getWarningCount();
+ if (classReferenceWarningCount > 0)
+ {
+ System.err.println("Warning: there were " + classReferenceWarningCount +
+ " unresolved references to classes or interfaces.");
+ System.err.println(" You may need to add missing library jars or update their versions.");
+ System.err.println(" If your code works fine without the missing classes, you can suppress");
+ System.err.println(" the warnings with '-dontwarn' options.");
+
+ if (configuration.skipNonPublicLibraryClasses)
+ {
+ System.err.println(" You may also have to remove the option '-skipnonpubliclibraryclasses'.");
+ }
+ }
+
+ int dependencyWarningCount = dependencyWarningPrinter.getWarningCount();
+ if (dependencyWarningCount > 0)
+ {
+ System.err.println("Warning: there were " + dependencyWarningCount +
+ " instances of library classes depending on program classes.");
+ System.err.println(" You must avoid such dependencies, since the program classes will");
+ System.err.println(" be processed, while the library classes will remain unchanged.");
+ }
+
+ int memberReferenceWarningCount = memberReferenceWarningPrinter.getWarningCount();
+ if (memberReferenceWarningCount > 0)
+ {
+ System.err.println("Warning: there were " + memberReferenceWarningCount +
+ " unresolved references to program class members.");
+ System.err.println(" Your input classes appear to be inconsistent.");
+ System.err.println(" You may need to recompile the code or update the library versions.");
+ System.err.println(" Alternatively, you may have to specify the option ");
+ System.err.println(" '-dontskipnonpubliclibraryclassmembers'.");
+
+ if (configuration.skipNonPublicLibraryClasses)
+ {
+ System.err.println(" You may also have to remove the option '-skipnonpubliclibraryclasses'.");
+ }
+ }
+
+ if ((classReferenceWarningCount > 0 ||
+ dependencyWarningCount > 0 ||
+ memberReferenceWarningCount > 0) &&
+ !configuration.ignoreWarnings)
+ {
+ throw new IOException("Please correct the above warnings first.");
+ }
+
+ if ((configuration.note == null ||
+ !configuration.note.isEmpty()) &&
+ (configuration.warn != null &&
+ configuration.warn.isEmpty() ||
+ configuration.ignoreWarnings))
+ {
+ System.out.println("Note: You're ignoring all warnings!");
+ }
+
+ // Discard unused library classes.
+ if (configuration.verbose)
+ {
+ System.out.println("Ignoring unused library classes...");
+ System.out.println(" Original number of library classes: " + originalLibraryClassPoolSize);
+ System.out.println(" Final number of library classes: " + libraryClassPool.size());
+ }
+ }
+
+
+ /**
+ * Extracts a list of exceptions of classes for which not to print notes,
+ * from the keep configuration.
+ */
+ private StringMatcher createClassNoteExceptionMatcher(List noteExceptions)
+ {
+ if (noteExceptions != null)
+ {
+ List noteExceptionNames = new ArrayList(noteExceptions.size());
+ for (int index = 0; index < noteExceptions.size(); index++)
+ {
+ KeepClassSpecification keepClassSpecification = (KeepClassSpecification)noteExceptions.get(index);
+ if (keepClassSpecification.markClasses)
+ {
+ // If the class itself is being kept, it's ok.
+ String className = keepClassSpecification.className;
+ if (className != null)
+ {
+ noteExceptionNames.add(className);
+ }
+
+ // If all of its extensions are being kept, it's ok too.
+ String extendsClassName = keepClassSpecification.extendsClassName;
+ if (extendsClassName != null)
+ {
+ noteExceptionNames.add(extendsClassName);
+ }
+ }
+ }
+
+ if (noteExceptionNames.size() > 0)
+ {
+ return new ListParser(new ClassNameParser()).parse(noteExceptionNames);
+ }
+ }
+
+ return null;
+ }
+
+
+ /**
+ * Extracts a list of exceptions of field or method names for which not to
+ * print notes, from the keep configuration.
+ */
+ private StringMatcher createClassMemberNoteExceptionMatcher(List noteExceptions,
+ boolean isField)
+ {
+ if (noteExceptions != null)
+ {
+ List noteExceptionNames = new ArrayList();
+ for (int index = 0; index < noteExceptions.size(); index++)
+ {
+ KeepClassSpecification keepClassSpecification = (KeepClassSpecification)noteExceptions.get(index);
+ List memberSpecifications = isField ?
+ keepClassSpecification.fieldSpecifications :
+ keepClassSpecification.methodSpecifications;
+
+ if (memberSpecifications != null)
+ {
+ for (int index2 = 0; index2 < memberSpecifications.size(); index2++)
+ {
+ MemberSpecification memberSpecification =
+ (MemberSpecification)memberSpecifications.get(index2);
+
+ String memberName = memberSpecification.name;
+ if (memberName != null)
+ {
+ noteExceptionNames.add(memberName);
+ }
+ }
+ }
+ }
+
+ if (noteExceptionNames.size() > 0)
+ {
+ return new ListParser(new ClassNameParser()).parse(noteExceptionNames);
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/src/proguard/InputReader.java b/src/proguard/InputReader.java
new file mode 100644
index 000000000..8478c8ffe
--- /dev/null
+++ b/src/proguard/InputReader.java
@@ -0,0 +1,233 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.ClassPool;
+import proguard.classfile.util.WarningPrinter;
+import proguard.classfile.visitor.*;
+import proguard.io.*;
+
+import java.io.IOException;
+
+/**
+ * This class reads the input class files.
+ *
+ * @author Eric Lafortune
+ */
+public class InputReader
+{
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new InputReader to read input class files as specified by the
+ * given configuration.
+ */
+ public InputReader(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Fills the given program class pool and library class pool by reading
+ * class files, based on the current configuration.
+ */
+ public void execute(ClassPool programClassPool,
+ ClassPool libraryClassPool) throws IOException
+ {
+ // Check if we have at least some input classes.
+ if (configuration.programJars == null)
+ {
+ throw new IOException("The input is empty. You have to specify one or more '-injars' options");
+ }
+
+ // Perform some sanity checks on the class paths.
+ checkInputOutput(configuration.libraryJars,
+ configuration.programJars);
+ checkInputOutput(configuration.programJars,
+ configuration.programJars);
+
+ WarningPrinter warningPrinter = new WarningPrinter(System.err, configuration.warn);
+ WarningPrinter notePrinter = new WarningPrinter(System.out, configuration.note);
+
+ DuplicateClassPrinter duplicateClassPrinter = new DuplicateClassPrinter(notePrinter);
+
+ // Read the program class files.
+ // Prepare a data entry reader to filter all classes,
+ // which are then decoded to classes by a class reader,
+ // which are then put in the class pool by a class pool filler.
+ readInput("Reading program ",
+ configuration.programJars,
+ new ClassFilter(
+ new ClassReader(false,
+ configuration.skipNonPublicLibraryClasses,
+ configuration.skipNonPublicLibraryClassMembers,
+ warningPrinter,
+ new ClassPresenceFilter(programClassPool, duplicateClassPrinter,
+ new ClassPoolFiller(programClassPool)))));
+
+ // Check if we have at least some input classes.
+ if (programClassPool.size() == 0)
+ {
+ throw new IOException("The input doesn't contain any classes. Did you specify the proper '-injars' options?");
+ }
+
+ // Read the library class files, if any.
+ if (configuration.libraryJars != null)
+ {
+ // Prepare a data entry reader to filter all classes,
+ // which are then decoded to classes by a class reader,
+ // which are then put in the class pool by a class pool filler.
+ readInput("Reading library ",
+ configuration.libraryJars,
+ new ClassFilter(
+ new ClassReader(true,
+ configuration.skipNonPublicLibraryClasses,
+ configuration.skipNonPublicLibraryClassMembers,
+ warningPrinter,
+ new ClassPresenceFilter(programClassPool, duplicateClassPrinter,
+ new ClassPresenceFilter(libraryClassPool, duplicateClassPrinter,
+ new ClassPoolFiller(libraryClassPool))))));
+ }
+
+ // Print out a summary of the notes, if necessary.
+ int noteCount = notePrinter.getWarningCount();
+ if (noteCount > 0)
+ {
+ System.err.println("Note: there were " + noteCount +
+ " duplicate class definitions.");
+ }
+
+ // Print out a summary of the warnings, if necessary.
+ int warningCount = warningPrinter.getWarningCount();
+ if (warningCount > 0)
+ {
+ System.err.println("Warning: there were " + warningCount +
+ " classes in incorrectly named files.");
+ System.err.println(" You should make sure all file names correspond to their class names.");
+ System.err.println(" The directory hierarchies must correspond to the package hierarchies.");
+
+ if (!configuration.ignoreWarnings)
+ {
+ System.err.println(" If you don't mind the mentioned classes not being written out,");
+ System.err.println(" you could try your luck using the '-ignorewarnings' option.");
+ throw new IOException("Please correct the above warnings first.");
+ }
+ }
+ }
+
+
+ /**
+ * Performs some sanity checks on the class paths.
+ */
+ private void checkInputOutput(ClassPath inputClassPath,
+ ClassPath outputClassPath)
+ throws IOException
+ {
+ if (inputClassPath == null ||
+ outputClassPath == null)
+ {
+ return;
+ }
+
+ for (int index1 = 0; index1 < inputClassPath.size(); index1++)
+ {
+ ClassPathEntry entry1 = inputClassPath.get(index1);
+ if (!entry1.isOutput())
+ {
+ for (int index2 = 0; index2 < outputClassPath.size(); index2++)
+ {
+ ClassPathEntry entry2 = outputClassPath.get(index2);
+ if (entry2.isOutput() &&
+ entry2.getName().equals(entry1.getName()))
+ {
+ throw new IOException("Input jars and output jars must be different ["+entry1.getName()+"]");
+ }
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Reads all input entries from the given class path.
+ */
+ private void readInput(String messagePrefix,
+ ClassPath classPath,
+ DataEntryReader reader) throws IOException
+ {
+ readInput(messagePrefix,
+ classPath,
+ 0,
+ classPath.size(),
+ reader);
+ }
+
+
+ /**
+ * Reads all input entries from the given section of the given class path.
+ */
+ public void readInput(String messagePrefix,
+ ClassPath classPath,
+ int fromIndex,
+ int toIndex,
+ DataEntryReader reader) throws IOException
+ {
+ for (int index = fromIndex; index < toIndex; index++)
+ {
+ ClassPathEntry entry = classPath.get(index);
+ if (!entry.isOutput())
+ {
+ readInput(messagePrefix, entry, reader);
+ }
+ }
+ }
+
+
+ /**
+ * Reads the given input class path entry.
+ */
+ private void readInput(String messagePrefix,
+ ClassPathEntry classPathEntry,
+ DataEntryReader dataEntryReader) throws IOException
+ {
+ try
+ {
+ // Create a reader that can unwrap jars, wars, ears, and zips.
+ DataEntryReader reader =
+ DataEntryReaderFactory.createDataEntryReader(messagePrefix,
+ classPathEntry,
+ dataEntryReader);
+
+ // Create the data entry pump.
+ DirectoryPump directoryPump =
+ new DirectoryPump(classPathEntry.getFile());
+
+ // Pump the data entries into the reader.
+ directoryPump.pumpDataEntries(reader);
+ }
+ catch (IOException ex)
+ {
+ throw (IOException)new IOException("Can't read [" + classPathEntry + "] (" + ex.getMessage() + ")").initCause(ex);
+ }
+ }
+}
diff --git a/src/proguard/KeepClassMemberChecker.java b/src/proguard/KeepClassMemberChecker.java
new file mode 100644
index 000000000..3a375da59
--- /dev/null
+++ b/src/proguard/KeepClassMemberChecker.java
@@ -0,0 +1,87 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+import java.util.List;
+
+/**
+ * This class checks if the user has forgotten to specify class members in
+ * some keep options in the configuration.
+ *
+ * @author Eric Lafortune
+ */
+public class KeepClassMemberChecker
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final WarningPrinter notePrinter;
+
+
+ /**
+ * Creates a new KeepClassMemberChecker.
+ */
+ public KeepClassMemberChecker(WarningPrinter notePrinter)
+ {
+ this.notePrinter = notePrinter;
+ }
+
+
+ /**
+ * Checks if the given class specifications try to keep class members
+ * without actually specifying any, printing notes if necessary. Returns
+ * the number of notes printed.
+ */
+ public void checkClassSpecifications(List keepClassSpecifications)
+ {
+ if (keepClassSpecifications != null)
+ {
+ for (int index = 0; index < keepClassSpecifications.size(); index++)
+ {
+ KeepClassSpecification keepClassSpecification =
+ (KeepClassSpecification)keepClassSpecifications.get(index);
+
+ if (!keepClassSpecification.markClasses &&
+ (keepClassSpecification.fieldSpecifications == null ||
+ keepClassSpecification.fieldSpecifications.size() == 0) &&
+ (keepClassSpecification.methodSpecifications == null ||
+ keepClassSpecification.methodSpecifications.size() == 0))
+ {
+ String className = keepClassSpecification.className;
+ if (className == null)
+ {
+ className = keepClassSpecification.extendsClassName;
+ }
+
+ if (className != null &&
+ notePrinter.accepts(className))
+ {
+ notePrinter.print(className,
+ "Note: the configuration doesn't specify which class members to keep for class '" +
+ ClassUtil.externalClassName(className) + "'");
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/proguard/KeepClassSpecification.java b/src/proguard/KeepClassSpecification.java
new file mode 100644
index 000000000..a6215c5ce
--- /dev/null
+++ b/src/proguard/KeepClassSpecification.java
@@ -0,0 +1,137 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+/**
+ * This class represents a keep option with class specification.
+ *
+ * @author Eric Lafortune
+ */
+public class KeepClassSpecification extends ClassSpecification
+{
+ public final boolean markClasses;
+ public final boolean markConditionally;
+ public final boolean allowShrinking;
+ public final boolean allowOptimization;
+ public final boolean allowObfuscation;
+
+
+ /**
+ * Creates a new KeepClassSpecification for all possible classes.
+ * @param markClasses specifies whether to mark the classes.
+ * If false, only class members are marked.
+ * If true, the classes are marked as well.
+ * @param markConditionally specifies whether to mark the classes and
+ * class members conditionally. If true, classes
+ * and class members are marked, on the condition
+ * that all specified class members are present.
+ * @param allowShrinking specifies whether shrinking is allowed.
+ * @param allowOptimization specifies whether optimization is allowed.
+ * @param allowObfuscation specifies whether obfuscation is allowed.
+ */
+ public KeepClassSpecification(boolean markClasses,
+ boolean markConditionally,
+ boolean allowShrinking,
+ boolean allowOptimization,
+ boolean allowObfuscation)
+ {
+ this.markClasses = markClasses;
+ this.markConditionally = markConditionally;
+ this.allowShrinking = allowShrinking;
+ this.allowOptimization = allowOptimization;
+ this.allowObfuscation = allowObfuscation;
+ }
+
+
+ /**
+ * Creates a new KeepClassSpecification.
+ * @param markClasses specifies whether to mark the classes.
+ * If false, only class members are marked.
+ * If true, the classes are marked as well.
+ * @param markConditionally specifies whether to mark the classes and
+ * class members conditionally. If true, classes
+ * and class members are marked, on the condition
+ * that all specified class members are present.
+ * @param allowShrinking specifies whether shrinking is allowed.
+ * @param allowOptimization specifies whether optimization is allowed.
+ * @param allowObfuscation specifies whether obfuscation is allowed.
+ * @param classSpecification the specification of classes and class members.
+ */
+ public KeepClassSpecification(boolean markClasses,
+ boolean markConditionally,
+ boolean allowShrinking,
+ boolean allowOptimization,
+ boolean allowObfuscation,
+ ClassSpecification classSpecification)
+ {
+ super(classSpecification);
+
+ this.markClasses = markClasses;
+ this.markConditionally = markConditionally;
+ this.allowShrinking = allowShrinking;
+ this.allowOptimization = allowOptimization;
+ this.allowObfuscation = allowObfuscation;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ KeepClassSpecification other = (KeepClassSpecification)object;
+ return
+ this.markClasses == other.markClasses &&
+ this.markConditionally == other.markConditionally &&
+ this.allowShrinking == other.allowShrinking &&
+ this.allowOptimization == other.allowOptimization &&
+ this.allowObfuscation == other.allowObfuscation &&
+ super.equals(other);
+ }
+
+ public int hashCode()
+ {
+ return
+ (markClasses ? 0 : 1) ^
+ (markConditionally ? 0 : 2) ^
+ (allowShrinking ? 0 : 4) ^
+ (allowOptimization ? 0 : 8) ^
+ (allowObfuscation ? 0 : 16) ^
+ super.hashCode();
+ }
+
+ public Object clone()
+ {
+// try
+// {
+ return super.clone();
+// }
+// catch (CloneNotSupportedException e)
+// {
+// return null;
+// }
+ }
+}
diff --git a/src/proguard/LineWordReader.java b/src/proguard/LineWordReader.java
new file mode 100644
index 000000000..64a228c30
--- /dev/null
+++ b/src/proguard/LineWordReader.java
@@ -0,0 +1,74 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import java.io.*;
+
+
+/**
+ * A WordReader
that returns words from a line number reader.
+ *
+ * @author Eric Lafortune
+ */
+public class LineWordReader extends WordReader
+{
+ private final LineNumberReader reader;
+ private final String description;
+
+
+ /**
+ * Creates a new LineWordReader for the given input.
+ */
+ public LineWordReader(LineNumberReader lineNumberReader,
+ String description,
+ File baseDir) throws IOException
+ {
+ super(baseDir);
+
+ this.reader = lineNumberReader;
+ this.description = description;
+ }
+
+
+ // Implementations for WordReader.
+
+ protected String nextLine() throws IOException
+ {
+ return reader.readLine();
+ }
+
+
+ protected String lineLocationDescription()
+ {
+ return "line " + reader.getLineNumber() + " of " + description;
+ }
+
+
+ public void close() throws IOException
+ {
+ super.close();
+
+ if (reader != null)
+ {
+ reader.close();
+ }
+ }
+}
diff --git a/src/proguard/MANIFEST.MF b/src/proguard/MANIFEST.MF
new file mode 100644
index 000000000..3bad15ec1
--- /dev/null
+++ b/src/proguard/MANIFEST.MF
@@ -0,0 +1,2 @@
+Manifest-Version: 1.0
+Main-Class: proguard.ProGuard
diff --git a/src/proguard/MemberSpecification.java b/src/proguard/MemberSpecification.java
new file mode 100644
index 000000000..e771fdea3
--- /dev/null
+++ b/src/proguard/MemberSpecification.java
@@ -0,0 +1,114 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+
+/**
+ * This class stores a specification of class members. The specification is
+ * template-based: the class member names and descriptors can contain wildcards.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberSpecification
+{
+ public int requiredSetAccessFlags;
+ public int requiredUnsetAccessFlags;
+ public final String annotationType;
+ public final String name;
+ public final String descriptor;
+
+
+ /**
+ * Creates a new option to keep all possible class members.
+ */
+ public MemberSpecification()
+ {
+ this(0,
+ 0,
+ null,
+ null,
+ null);
+ }
+
+
+ /**
+ * Creates a new option to keep the specified class member(s).
+ *
+ * @param requiredSetAccessFlags the class access flags that must be set
+ * in order for the class to apply.
+ * @param requiredUnsetAccessFlags the class access flags that must be unset
+ * in order for the class to apply.
+ * @param annotationType the name of the class that must be an
+ * annotation in order for the class member
+ * to apply. The name may be null to specify
+ * that no annotation is required.
+ * @param name the class member name. The name may be
+ * null to specify any class member or it
+ * may contain "*" or "?" wildcards.
+ * @param descriptor the class member descriptor. The
+ * descriptor may be null to specify any
+ * class member or it may contain
+ * "**", "*", or "?" wildcards.
+ */
+ public MemberSpecification(int requiredSetAccessFlags,
+ int requiredUnsetAccessFlags,
+ String annotationType,
+ String name,
+ String descriptor)
+ {
+ this.requiredSetAccessFlags = requiredSetAccessFlags;
+ this.requiredUnsetAccessFlags = requiredUnsetAccessFlags;
+ this.annotationType = annotationType;
+ this.name = name;
+ this.descriptor = descriptor;
+ }
+
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ MemberSpecification other = (MemberSpecification)object;
+ return
+ (this.requiredSetAccessFlags == other.requiredSetAccessFlags ) &&
+ (this.requiredUnsetAccessFlags == other.requiredUnsetAccessFlags ) &&
+ (this.annotationType == null ? other.annotationType == null : this.annotationType.equals(other.annotationType)) &&
+ (this.name == null ? other.name == null : this.name.equals(other.name) ) &&
+ (this.descriptor == null ? other.descriptor == null : this.descriptor.equals(other.descriptor) );
+ }
+
+ public int hashCode()
+ {
+ return
+ (requiredSetAccessFlags ) ^
+ (requiredUnsetAccessFlags ) ^
+ (annotationType == null ? 0 : annotationType.hashCode()) ^
+ (name == null ? 0 : name.hashCode() ) ^
+ (descriptor == null ? 0 : descriptor.hashCode() );
+ }
+}
diff --git a/src/proguard/OutputWriter.java b/src/proguard/OutputWriter.java
new file mode 100644
index 000000000..c4467cf25
--- /dev/null
+++ b/src/proguard/OutputWriter.java
@@ -0,0 +1,296 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.ClassPool;
+import proguard.classfile.util.ClassUtil;
+import proguard.io.*;
+
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * This class writes the output class files.
+ *
+ * @author Eric Lafortune
+ */
+public class OutputWriter
+{
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new OutputWriter to write output class files as specified by
+ * the given configuration.
+ */
+ public OutputWriter(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Writes the given class pool to class files, based on the current
+ * configuration.
+ */
+ public void execute(ClassPool programClassPool) throws IOException
+ {
+ ClassPath programJars = configuration.programJars;
+
+ // Perform a check on the first jar.
+ ClassPathEntry firstEntry = programJars.get(0);
+ if (firstEntry.isOutput())
+ {
+ throw new IOException("The output jar [" + firstEntry.getName() +
+ "] must be specified after an input jar, or it will be empty.");
+ }
+
+ // Check if the first of two subsequent the output jars has a filter.
+ for (int index = 0; index < programJars.size() - 1; index++)
+ {
+ ClassPathEntry entry = programJars.get(index);
+ if (entry.isOutput())
+ {
+ if (entry.getFilter() == null &&
+ entry.getJarFilter() == null &&
+ entry.getWarFilter() == null &&
+ entry.getEarFilter() == null &&
+ entry.getZipFilter() == null &&
+ programJars.get(index + 1).isOutput())
+ {
+ throw new IOException("The output jar [" + entry.getName() +
+ "] must have a filter, or all subsequent output jars will be empty.");
+ }
+ }
+ }
+
+ // Check if the output jar names are different from the input jar names.
+ for (int outIndex = 0; outIndex < programJars.size() - 1; outIndex++)
+ {
+ ClassPathEntry entry = programJars.get(outIndex);
+ if (entry.isOutput())
+ {
+ for (int inIndex = 0; inIndex < programJars.size(); inIndex++)
+ {
+ ClassPathEntry otherEntry = programJars.get(inIndex);
+
+ if (!otherEntry.isOutput() &&
+ entry.getFile().equals(otherEntry.getFile()))
+ {
+ throw new IOException("The output jar [" + entry.getName() +
+ "] must be different from all input jars.");
+ }
+ }
+ }
+ }
+
+ // Check for potential problems with mixed-case class names on
+ // case-insensitive file systems.
+ if (configuration.obfuscate &&
+ configuration.useMixedCaseClassNames &&
+ configuration.classObfuscationDictionary == null &&
+ (configuration.note == null ||
+ !configuration.note.isEmpty()))
+ {
+ String os = System.getProperty("os.name").toLowerCase();
+ if (os.startsWith("windows") ||
+ os.startsWith("mac os"))
+ {
+ // Go over all program class path entries.
+ for (int index = 0; index < programJars.size(); index++)
+ {
+ // Is it an output directory?
+ ClassPathEntry entry = programJars.get(index);
+ if (entry.isOutput() &&
+ !entry.isJar() &&
+ !entry.isWar() &&
+ !entry.isEar() &&
+ !entry.isZip())
+ {
+ System.out.println("Note: you're writing the processed class files to a directory [" + entry.getName() +"].");
+ System.out.println(" This will likely cause problems with obfuscated mixed-case class names.");
+ System.out.println(" You should consider writing the output to a jar file, or otherwise");
+ System.out.println(" specify '-dontusemixedcaseclassnames'.");
+
+ break;
+ }
+ }
+ }
+ }
+
+ int firstInputIndex = 0;
+ int lastInputIndex = 0;
+
+ // Go over all program class path entries.
+ for (int index = 0; index < programJars.size(); index++)
+ {
+ // Is it an input entry?
+ ClassPathEntry entry = programJars.get(index);
+ if (!entry.isOutput())
+ {
+ // Remember the index of the last input entry.
+ lastInputIndex = index;
+ }
+ else
+ {
+ // Check if this the last output entry in a series.
+ int nextIndex = index + 1;
+ if (nextIndex == programJars.size() ||
+ !programJars.get(nextIndex).isOutput())
+ {
+ // Write the processed input entries to the output entries.
+ writeOutput(programClassPool,
+ programJars,
+ firstInputIndex,
+ lastInputIndex + 1,
+ nextIndex);
+
+ // Start with the next series of input entries.
+ firstInputIndex = nextIndex;
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Transfers the specified input jars to the specified output jars.
+ */
+ private void writeOutput(ClassPool programClassPool,
+ ClassPath classPath,
+ int fromInputIndex,
+ int fromOutputIndex,
+ int toOutputIndex)
+ throws IOException
+ {
+ try
+ {
+ // Construct the writer that can write jars, wars, ears, zips, and
+ // directories, cascading over the specified output entries.
+ DataEntryWriter writer =
+ DataEntryWriterFactory.createDataEntryWriter(classPath,
+ fromOutputIndex,
+ toOutputIndex);
+
+ // The writer will be used to write possibly obfuscated class files.
+ DataEntryReader classRewriter =
+ new ClassRewriter(programClassPool, writer);
+
+ // The writer will also be used to write resource files.
+ DataEntryReader resourceCopier =
+ new DataEntryCopier(writer);
+
+ DataEntryReader resourceRewriter = resourceCopier;
+
+ // Wrap the resource writer with a filter and a data entry rewriter,
+ // if required.
+ if (configuration.adaptResourceFileContents != null)
+ {
+ resourceRewriter =
+ new NameFilter(configuration.adaptResourceFileContents,
+ new NameFilter("META-INF/MANIFEST.MF,META-INF/*.SF",
+ new ManifestRewriter(programClassPool, writer),
+ new DataEntryRewriter(programClassPool, writer)),
+ resourceRewriter);
+ }
+
+ // Wrap the resource writer with a filter and a data entry renamer,
+ // if required.
+ if (configuration.adaptResourceFileNames != null)
+ {
+ Map packagePrefixMap = createPackagePrefixMap(programClassPool);
+
+ resourceRewriter =
+ new NameFilter(configuration.adaptResourceFileNames,
+ new DataEntryObfuscator(programClassPool,
+ packagePrefixMap,
+ resourceRewriter),
+ resourceRewriter);
+ }
+
+ DataEntryReader directoryRewriter = null;
+
+ // Wrap the directory writer with a filter and a data entry renamer,
+ // if required.
+ if (configuration.keepDirectories != null)
+ {
+ Map packagePrefixMap = createPackagePrefixMap(programClassPool);
+
+ directoryRewriter =
+ new NameFilter(configuration.keepDirectories,
+ new DataEntryRenamer(packagePrefixMap,
+ resourceCopier,
+ resourceCopier));
+ }
+
+ // Create the reader that can write class files and copy directories
+ // and resource files to the main writer.
+ DataEntryReader reader =
+ new ClassFilter( classRewriter,
+ new DirectoryFilter(directoryRewriter,
+ resourceRewriter));
+
+ // Go over the specified input entries and write their processed
+ // versions.
+ new InputReader(configuration).readInput(" Copying resources from program ",
+ classPath,
+ fromInputIndex,
+ fromOutputIndex,
+ reader);
+
+ // Close all output entries.
+ writer.close();
+ }
+ catch (IOException ex)
+ {
+ throw (IOException)new IOException("Can't write [" + classPath.get(fromOutputIndex).getName() + "] (" + ex.getMessage() + ")").initCause(ex);
+ }
+ }
+
+
+ /**
+ * Creates a map of old package prefixes to new package prefixes, based on
+ * the given class pool.
+ */
+ private static Map createPackagePrefixMap(ClassPool classPool)
+ {
+ Map packagePrefixMap = new HashMap();
+
+ Iterator iterator = classPool.classNames();
+ while (iterator.hasNext())
+ {
+ String className = (String)iterator.next();
+ String packagePrefix = ClassUtil.internalPackagePrefix(className);
+
+ String mappedNewPackagePrefix = (String)packagePrefixMap.get(packagePrefix);
+ if (mappedNewPackagePrefix == null ||
+ !mappedNewPackagePrefix.equals(packagePrefix))
+ {
+ String newClassName = classPool.getClass(className).getName();
+ String newPackagePrefix = ClassUtil.internalPackagePrefix(newClassName);
+
+ packagePrefixMap.put(packagePrefix, newPackagePrefix);
+ }
+ }
+
+ return packagePrefixMap;
+ }
+}
diff --git a/src/proguard/ParseException.java b/src/proguard/ParseException.java
new file mode 100644
index 000000000..b4af6c27b
--- /dev/null
+++ b/src/proguard/ParseException.java
@@ -0,0 +1,51 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+
+/**
+ * This Exception
signals that a parse exception of some
+ * sort has occurred.
+ *
+ * @author Eric Lafortune
+ */
+public class ParseException extends Exception {
+
+ /**
+ * Constructs a ParseException
with null
+ * as its error detail message.
+ */
+ public ParseException() {
+ super();
+ }
+
+ /**
+ * Constructs a ParseException
with the specified detail
+ * message. The error message string s
can later be
+ * retrieved by the {@link Throwable#getMessage}
+ * method of class Throwable
.
+ *
+ * @param s the detail message.
+ */
+ public ParseException(String s) {
+ super(s);
+ }
+}
diff --git a/src/proguard/ProGuard.java b/src/proguard/ProGuard.java
new file mode 100644
index 000000000..4410174bb
--- /dev/null
+++ b/src/proguard/ProGuard.java
@@ -0,0 +1,504 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.ClassPool;
+import proguard.classfile.editor.ClassElementSorter;
+import proguard.classfile.visitor.*;
+import proguard.obfuscate.Obfuscator;
+import proguard.optimize.*;
+import proguard.preverify.*;
+import proguard.shrink.Shrinker;
+
+import java.io.*;
+import java.util.Properties;
+
+/**
+ * Tool for shrinking, optimizing, obfuscating, and preverifying Java classes.
+ *
+ * @author Eric Lafortune
+ */
+public class ProGuard
+{
+ public static final String VERSION = "ProGuard, version 4.9";
+
+ private final Configuration configuration;
+ private ClassPool programClassPool = new ClassPool();
+ private final ClassPool libraryClassPool = new ClassPool();
+
+
+ /**
+ * Creates a new ProGuard object to process jars as specified by the given
+ * configuration.
+ */
+ public ProGuard(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Performs all subsequent ProGuard operations.
+ */
+ public void execute() throws IOException
+ {
+ System.out.println(VERSION);
+
+ GPL.check();
+
+ if (configuration.printConfiguration != null)
+ {
+ printConfiguration();
+ }
+
+ if (configuration.programJars != null &&
+ configuration.programJars.hasOutput() &&
+ new UpToDateChecker(configuration).check())
+ {
+ return;
+ }
+
+ readInput();
+
+ if (configuration.printSeeds != null ||
+ configuration.shrink ||
+ configuration.optimize ||
+ configuration.obfuscate ||
+ configuration.preverify)
+ {
+ initialize();
+ }
+
+ if (configuration.targetClassVersion != 0)
+ {
+ target();
+ }
+
+ if (configuration.printSeeds != null)
+ {
+ printSeeds();
+ }
+
+ if (configuration.shrink)
+ {
+ shrink();
+ }
+
+ if (configuration.preverify)
+ {
+ inlineSubroutines();
+ }
+
+ if (configuration.optimize)
+ {
+ for (int optimizationPass = 0;
+ optimizationPass < configuration.optimizationPasses;
+ optimizationPass++)
+ {
+ if (!optimize())
+ {
+ // Stop optimizing if the code doesn't improve any further.
+ break;
+ }
+
+ // Shrink again, if we may.
+ if (configuration.shrink)
+ {
+ // Don't print any usage this time around.
+ configuration.printUsage = null;
+ configuration.whyAreYouKeeping = null;
+
+ shrink();
+ }
+ }
+ }
+
+ if (configuration.obfuscate)
+ {
+ obfuscate();
+ }
+
+ if (configuration.preverify)
+ {
+ preverify();
+ }
+
+ if (configuration.shrink ||
+ configuration.optimize ||
+ configuration.obfuscate ||
+ configuration.preverify)
+ {
+ sortClassElements();
+ }
+
+ if (configuration.programJars.hasOutput())
+ {
+ writeOutput();
+ }
+
+ if (configuration.dump != null)
+ {
+ dump();
+ }
+ }
+
+
+ /**
+ * Prints out the configuration that ProGuard is using.
+ */
+ private void printConfiguration() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Printing configuration to [" + fileName(configuration.printConfiguration) + "]...");
+ }
+
+ PrintStream ps = createPrintStream(configuration.printConfiguration);
+ try
+ {
+ new ConfigurationWriter(ps).write(configuration);
+ }
+ finally
+ {
+ closePrintStream(ps);
+ }
+ }
+
+
+ /**
+ * Reads the input class files.
+ */
+ private void readInput() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Reading input...");
+ }
+
+ // Fill the program class pool and the library class pool.
+ new InputReader(configuration).execute(programClassPool, libraryClassPool);
+ }
+
+
+ /**
+ * Initializes the cross-references between all classes, performs some
+ * basic checks, and shrinks the library class pool.
+ */
+ private void initialize() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Initializing...");
+ }
+
+ new Initializer(configuration).execute(programClassPool, libraryClassPool);
+ }
+
+
+ /**
+ * Sets that target versions of the program classes.
+ */
+ private void target() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Setting target versions...");
+ }
+
+ new Targeter(configuration).execute(programClassPool);
+ }
+
+
+ /**
+ * Prints out classes and class members that are used as seeds in the
+ * shrinking and obfuscation steps.
+ */
+ private void printSeeds() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Printing kept classes, fields, and methods...");
+ }
+
+ PrintStream ps = createPrintStream(configuration.printSeeds);
+ try
+ {
+ new SeedPrinter(ps).write(configuration, programClassPool, libraryClassPool);
+ }
+ finally
+ {
+ closePrintStream(ps);
+ }
+ }
+
+
+ /**
+ * Performs the shrinking step.
+ */
+ private void shrink() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Shrinking...");
+
+ // We'll print out some explanation, if requested.
+ if (configuration.whyAreYouKeeping != null)
+ {
+ System.out.println("Explaining why classes and class members are being kept...");
+ }
+
+ // We'll print out the usage, if requested.
+ if (configuration.printUsage != null)
+ {
+ System.out.println("Printing usage to [" + fileName(configuration.printUsage) + "]...");
+ }
+ }
+
+ // Perform the actual shrinking.
+ programClassPool =
+ new Shrinker(configuration).execute(programClassPool, libraryClassPool);
+ }
+
+
+ /**
+ * Performs the subroutine inlining step.
+ */
+ private void inlineSubroutines()
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Inlining subroutines...");
+ }
+
+ // Perform the actual inlining.
+ new SubroutineInliner(configuration).execute(programClassPool);
+ }
+
+
+ /**
+ * Performs the optimization step.
+ */
+ private boolean optimize() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Optimizing...");
+ }
+
+ // Perform the actual optimization.
+ return new Optimizer(configuration).execute(programClassPool, libraryClassPool);
+ }
+
+
+ /**
+ * Performs the obfuscation step.
+ */
+ private void obfuscate() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Obfuscating...");
+
+ // We'll apply a mapping, if requested.
+ if (configuration.applyMapping != null)
+ {
+ System.out.println("Applying mapping [" + fileName(configuration.applyMapping) + "]");
+ }
+
+ // We'll print out the mapping, if requested.
+ if (configuration.printMapping != null)
+ {
+ System.out.println("Printing mapping to [" + fileName(configuration.printMapping) + "]...");
+ }
+ }
+
+ // Perform the actual obfuscation.
+ new Obfuscator(configuration).execute(programClassPool, libraryClassPool);
+ }
+
+
+ /**
+ * Performs the preverification step.
+ */
+ private void preverify()
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Preverifying...");
+ }
+
+ // Perform the actual preverification.
+ new Preverifier(configuration).execute(programClassPool);
+ }
+
+
+ /**
+ * Sorts the elements of all program classes.
+ */
+ private void sortClassElements()
+ {
+ programClassPool.classesAccept(new ClassElementSorter());
+ }
+
+
+ /**
+ * Writes the output class files.
+ */
+ private void writeOutput() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Writing output...");
+ }
+
+ // Write out the program class pool.
+ new OutputWriter(configuration).execute(programClassPool);
+ }
+
+
+ /**
+ * Prints out the contents of the program classes.
+ */
+ private void dump() throws IOException
+ {
+ if (configuration.verbose)
+ {
+ System.out.println("Printing classes to [" + fileName(configuration.dump) + "]...");
+ }
+
+ PrintStream ps = createPrintStream(configuration.dump);
+ try
+ {
+ programClassPool.classesAccept(new ClassPrinter(ps));
+ }
+ finally
+ {
+ closePrintStream(ps);
+ }
+ }
+
+
+ /**
+ * Returns a print stream for the given file, or the standard output if
+ * the file name is empty.
+ */
+ private PrintStream createPrintStream(File file)
+ throws FileNotFoundException
+ {
+ return file == Configuration.STD_OUT ? System.out :
+ new PrintStream(
+ new BufferedOutputStream(
+ new FileOutputStream(file)));
+ }
+
+
+ /**
+ * Closes the given print stream, or closes it if is the standard output.
+ * @param printStream
+ */
+ private void closePrintStream(PrintStream printStream)
+ {
+ if (printStream == System.out)
+ {
+ printStream.flush();
+ }
+ else
+ {
+ printStream.close();
+ }
+ }
+
+
+ /**
+ * Returns the canonical file name for the given file, or "standard output"
+ * if the file name is empty.
+ */
+ private String fileName(File file)
+ {
+ if (file == Configuration.STD_OUT)
+ {
+ return "standard output";
+ }
+ else
+ {
+ try
+ {
+ return file.getCanonicalPath();
+ }
+ catch (IOException ex)
+ {
+ return file.getPath();
+ }
+ }
+ }
+
+
+ /**
+ * The main method for ProGuard.
+ */
+ public static void main(String[] args)
+ {
+ if (args.length == 0)
+ {
+ System.out.println(VERSION);
+ System.out.println("Usage: java proguard.ProGuard [options ...]");
+ System.exit(1);
+ }
+
+ // Create the default options.
+ Configuration configuration = new Configuration();
+
+ try
+ {
+ // Parse the options specified in the command line arguments.
+ ConfigurationParser parser = new ConfigurationParser(args,
+ System.getProperties());
+ try
+ {
+ parser.parse(configuration);
+ }
+ finally
+ {
+ parser.close();
+ }
+
+ // Execute ProGuard with these options.
+ new ProGuard(configuration).execute();
+ }
+ catch (Exception ex)
+ {
+ if (configuration.verbose)
+ {
+ // Print a verbose stack trace.
+ ex.printStackTrace();
+ }
+ else
+ {
+ // Print just the stack trace message.
+ System.err.println("Error: "+ex.getMessage());
+ }
+
+ System.exit(1);
+ }
+
+ System.exit(0);
+ }
+}
diff --git a/src/proguard/SeedPrinter.java b/src/proguard/SeedPrinter.java
new file mode 100644
index 000000000..8ed74b610
--- /dev/null
+++ b/src/proguard/SeedPrinter.java
@@ -0,0 +1,97 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.ClassPool;
+import proguard.classfile.attribute.visitor.AllAttributeVisitor;
+import proguard.classfile.constant.visitor.AllConstantVisitor;
+import proguard.classfile.instruction.visitor.AllInstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.optimize.*;
+import proguard.util.*;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * This class prints out the seeds specified by keep options.
+ *
+ * @author Eric Lafortune
+ */
+public class SeedPrinter
+{
+ private final PrintStream ps;
+
+
+ /**
+ * Creates a new ConfigurationWriter for the given PrintStream.
+ */
+ public SeedPrinter(PrintStream ps) throws IOException
+ {
+ this.ps = ps;
+ }
+
+
+ /**
+ * Prints out the seeds for the classes in the given program class pool.
+ * @param configuration the configuration containing the keep options.
+ * @throws IOException if an IO error occurs while writing the configuration.
+ */
+ public void write(Configuration configuration,
+ ClassPool programClassPool,
+ ClassPool libraryClassPool) throws IOException
+ {
+ // Check if we have at least some keep commands.
+ if (configuration.keep == null)
+ {
+ throw new IOException("You have to specify '-keep' options for the shrinking step.");
+ }
+
+ // Clean up any old visitor info.
+ programClassPool.classesAccept(new ClassCleaner());
+ libraryClassPool.classesAccept(new ClassCleaner());
+
+ // Create a visitor for printing out the seeds. We're printing out
+ // the program elements that are preserved against shrinking,
+ // optimization, or obfuscation.
+ KeepMarker keepMarker = new KeepMarker();
+ ClassPoolVisitor classPoolvisitor =
+ ClassSpecificationVisitorFactory.createClassPoolVisitor(configuration.keep,
+ keepMarker,
+ keepMarker,
+ true,
+ true,
+ true);
+ // Mark the seeds.
+ programClassPool.accept(classPoolvisitor);
+ libraryClassPool.accept(classPoolvisitor);
+
+ // Print out the seeds.
+ SimpleClassPrinter printer = new SimpleClassPrinter(false, ps);
+ programClassPool.classesAcceptAlphabetically(new MultiClassVisitor(
+ new ClassVisitor[]
+ {
+ new KeptClassFilter(printer),
+ new AllMemberVisitor(new KeptMemberFilter(printer))
+ }));
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/SubclassedClassFilter.java b/src/proguard/SubclassedClassFilter.java
new file mode 100644
index 000000000..1b9c1fee9
--- /dev/null
+++ b/src/proguard/SubclassedClassFilter.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor delegates all its method calls to another ClassVisitor,
+ * but only for Clazz objects that are being subclassed.
+ *
+ * @author Eric Lafortune
+ */
+final class SubclassedClassFilter
+implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ public SubclassedClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (programClass.subClasses != null)
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (libraryClass.subClasses != null)
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
diff --git a/src/proguard/Targeter.java b/src/proguard/Targeter.java
new file mode 100644
index 000000000..675f0df78
--- /dev/null
+++ b/src/proguard/Targeter.java
@@ -0,0 +1,88 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import proguard.classfile.ClassPool;
+import proguard.classfile.util.ClassUtil;
+import proguard.classfile.visitor.ClassVersionSetter;
+
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * This class sets the target version on program classes.
+ *
+ * @author Eric Lafortune
+ */
+public class Targeter
+{
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new Targeter to set the target version on program classes
+ * according to the given configuration.
+ */
+ public Targeter(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Sets the target version on classes in the given program class pool.
+ */
+ public void execute(ClassPool programClassPool) throws IOException
+ {
+ Set newerClassVersions = configuration.warn != null ? null : new HashSet();
+
+ programClassPool.classesAccept(new ClassVersionSetter(configuration.targetClassVersion,
+ newerClassVersions));
+
+ if (newerClassVersions != null &&
+ newerClassVersions.size() > 0)
+ {
+ System.err.print("Warning: some classes have more recent versions (");
+
+ Iterator iterator = newerClassVersions.iterator();
+ while (iterator.hasNext())
+ {
+ Integer classVersion = (Integer)iterator.next();
+ System.err.print(ClassUtil.externalClassVersion(classVersion.intValue()));
+
+ if (iterator.hasNext())
+ {
+ System.err.print(",");
+ }
+ }
+
+ System.err.println(")");
+ System.err.println(" than the target version ("+ClassUtil.externalClassVersion(configuration.targetClassVersion)+").");
+
+ if (!configuration.ignoreWarnings)
+ {
+ System.err.println(" If you are sure this is not a problem,");
+ System.err.println(" you could try your luck using the '-ignorewarnings' option.");
+ throw new IOException("Please correct the above warnings first.");
+ }
+ }
+ }
+}
diff --git a/src/proguard/UpToDateChecker.java b/src/proguard/UpToDateChecker.java
new file mode 100644
index 000000000..7f5e7a66b
--- /dev/null
+++ b/src/proguard/UpToDateChecker.java
@@ -0,0 +1,232 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import java.io.File;
+
+/**
+ * This class checks whether the output is up to date.
+ *
+ * @author Eric Lafortune
+ */
+public class UpToDateChecker
+{
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new UpToDateChecker with the given configuration.
+ */
+ public UpToDateChecker(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Returns whether the output is up to date, based on the modification times
+ * of the input jars, output jars, and library jars (or directories).
+ */
+ public boolean check()
+ {
+ try
+ {
+ ModificationTimeChecker checker = new ModificationTimeChecker();
+
+ checker.updateInputModificationTime(configuration.lastModified);
+
+ ClassPath programJars = configuration.programJars;
+ ClassPath libraryJars = configuration.libraryJars;
+
+ // Check the dates of the program jars, if any.
+ if (programJars != null)
+ {
+ for (int index = 0; index < programJars.size(); index++)
+ {
+ // Update the input and output modification times.
+ ClassPathEntry classPathEntry = programJars.get(index);
+
+ checker.updateModificationTime(classPathEntry.getFile(),
+ classPathEntry.isOutput());
+ }
+ }
+
+ // Check the dates of the library jars, if any.
+ if (libraryJars != null)
+ {
+ for (int index = 0; index < libraryJars.size(); index++)
+ {
+ // Update the input modification time.
+ ClassPathEntry classPathEntry = libraryJars.get(index);
+
+ checker.updateModificationTime(classPathEntry.getFile(),
+ false);
+ }
+ }
+
+ // Check the dates of the auxiliary input files.
+ checker.updateInputModificationTime(configuration.applyMapping);
+ checker.updateInputModificationTime(configuration.obfuscationDictionary);
+ checker.updateInputModificationTime(configuration.classObfuscationDictionary);
+ checker.updateInputModificationTime(configuration.packageObfuscationDictionary);
+
+ // Check the dates of the auxiliary output files.
+ checker.updateOutputModificationTime(configuration.printSeeds);
+ checker.updateOutputModificationTime(configuration.printUsage);
+ checker.updateOutputModificationTime(configuration.printMapping);
+ checker.updateOutputModificationTime(configuration.printConfiguration);
+ checker.updateOutputModificationTime(configuration.dump);
+ }
+ catch (IllegalStateException e)
+ {
+ // The output is outdated.
+ return false;
+ }
+
+ System.out.println("The output seems up to date");
+
+ return true;
+ }
+
+
+ /**
+ * This class maintains the modification times of input and output.
+ * The methods throw an IllegalStateException if the output appears
+ * outdated.
+ */
+ private static class ModificationTimeChecker {
+
+ private long inputModificationTime = Long.MIN_VALUE;
+ private long outputModificationTime = Long.MAX_VALUE;
+
+
+ /**
+ * Updates the input modification time based on the given file or
+ * directory (recursively).
+ */
+ public void updateInputModificationTime(File file)
+ {
+ if (file != null)
+ {
+ updateModificationTime(file, false);
+ }
+ }
+
+
+ /**
+ * Updates the input modification time based on the given file or
+ * directory (recursively).
+ */
+ public void updateOutputModificationTime(File file)
+ {
+ if (file != null && file.getName().length() > 0)
+ {
+ updateModificationTime(file, true);
+ }
+ }
+
+
+ /**
+ * Updates the specified modification time based on the given file or
+ * directory (recursively).
+ */
+ public void updateModificationTime(File file, boolean isOutput)
+ {
+ // Is it a directory?
+ if (file.isDirectory())
+ {
+ // Ignore the directory's modification time; just recurse on
+ // its files.
+ File[] files = file.listFiles();
+
+ // Still, an empty output directory is probably a sign that it
+ // is not up to date.
+ if (files.length == 0 && isOutput)
+ {
+ updateOutputModificationTime(Long.MIN_VALUE);
+ }
+
+ for (int index = 0; index < files.length; index++)
+ {
+ updateModificationTime(files[index], isOutput);
+ }
+ }
+ else
+ {
+ // Update with the file's modification time.
+ updateModificationTime(file.lastModified(), isOutput);
+ }
+ }
+
+
+ /**
+ * Updates the specified modification time.
+ */
+ public void updateModificationTime(long time, boolean isOutput)
+ {
+ if (isOutput)
+ {
+ updateOutputModificationTime(time);
+ }
+ else
+ {
+ updateInputModificationTime(time);
+ }
+ }
+
+
+ /**
+ * Updates the input modification time.
+ */
+ public void updateInputModificationTime(long time)
+ {
+ if (inputModificationTime < time)
+ {
+ inputModificationTime = time;
+
+ checkModificationTimes();
+ }
+ }
+
+
+ /**
+ * Updates the output modification time.
+ */
+ public void updateOutputModificationTime(long time)
+ {
+ if (outputModificationTime > time)
+ {
+ outputModificationTime = time;
+
+ checkModificationTimes();
+ }
+ }
+
+
+ private void checkModificationTimes()
+ {
+ if (inputModificationTime > outputModificationTime)
+ {
+ throw new IllegalStateException("The output is outdated");
+ }
+ }
+ }
+}
diff --git a/src/proguard/WordReader.java b/src/proguard/WordReader.java
new file mode 100644
index 000000000..110fce3b3
--- /dev/null
+++ b/src/proguard/WordReader.java
@@ -0,0 +1,387 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard;
+
+import java.io.*;
+
+
+/**
+ * An abstract reader of words, with the possibility to include other readers.
+ * Words are separated by spaces or broken off at delimiters. Words containing
+ * spaces or delimiters can be quoted with single or double quotes.
+ * Comments (everything starting with '#' on a single line) are ignored.
+ *
+ * @author Eric Lafortune
+ * @noinspection TailRecursion
+ */
+public abstract class WordReader
+{
+ private static final char COMMENT_CHARACTER = '#';
+
+
+ private File baseDir;
+ private WordReader includeWordReader;
+ private String currentLine;
+ private int currentLineLength;
+ private int currentIndex;
+ private String currentWord;
+ private String currentComments;
+
+
+ /**
+ * Creates a new WordReader with the given base directory.
+ */
+ protected WordReader(File baseDir)
+ {
+ this.baseDir = baseDir;
+ }
+
+
+ /**
+ * Sets the base directory of this reader.
+ */
+ public void setBaseDir(File baseDir)
+ {
+ if (includeWordReader != null)
+ {
+ includeWordReader.setBaseDir(baseDir);
+ }
+ else
+ {
+ this.baseDir = baseDir;
+ }
+ }
+
+
+ /**
+ * Returns the base directory of this reader, if any.
+ */
+ public File getBaseDir()
+ {
+ return includeWordReader != null ?
+ includeWordReader.getBaseDir() :
+ baseDir;
+ }
+
+
+ /**
+ * Specifies to start reading words from the given WordReader. When it is
+ * exhausted, this WordReader will continue to provide its own words.
+ *
+ * @param newIncludeWordReader the WordReader that will start reading words.
+ */
+ public void includeWordReader(WordReader newIncludeWordReader)
+ {
+ if (includeWordReader == null)
+ {
+ includeWordReader = newIncludeWordReader;
+ }
+ else
+ {
+ includeWordReader.includeWordReader(newIncludeWordReader);
+ }
+ }
+
+
+ /**
+ * Reads a word from this WordReader, or from one of its active included
+ * WordReader objects.
+ *
+ * @param isFileName return a complete line (or argument), if the word
+ * isn't an option (it doesn't start with '-').
+ * @return the read word.
+ */
+ public String nextWord(boolean isFileName) throws IOException
+ {
+ currentWord = null;
+
+ // See if we have an included reader to produce a word.
+ if (includeWordReader != null)
+ {
+ // Does the included word reader still produce a word?
+ currentWord = includeWordReader.nextWord(isFileName);
+ if (currentWord != null)
+ {
+ // Return it if so.
+ return currentWord;
+ }
+
+ // Otherwise close and ditch the word reader.
+ includeWordReader.close();
+ includeWordReader = null;
+ }
+
+ // Get a word from this reader.
+
+ // Skip any whitespace and comments left on the current line.
+ if (currentLine != null)
+ {
+ // Skip any leading whitespace.
+ while (currentIndex < currentLineLength &&
+ Character.isWhitespace(currentLine.charAt(currentIndex)))
+ {
+ currentIndex++;
+ }
+
+ // Skip any comments.
+ if (currentIndex < currentLineLength &&
+ isComment(currentLine.charAt(currentIndex)))
+ {
+ currentIndex = currentLineLength;
+ }
+ }
+
+ // Make sure we have a non-blank line.
+ while (currentLine == null || currentIndex == currentLineLength)
+ {
+ currentLine = nextLine();
+ if (currentLine == null)
+ {
+ return null;
+ }
+
+ currentLineLength = currentLine.length();
+
+ // Skip any leading whitespace.
+ currentIndex = 0;
+ while (currentIndex < currentLineLength &&
+ Character.isWhitespace(currentLine.charAt(currentIndex)))
+ {
+ currentIndex++;
+ }
+
+ // Remember any leading comments.
+ if (currentIndex < currentLineLength &&
+ isComment(currentLine.charAt(currentIndex)))
+ {
+ // Remember the comments.
+ String comment = currentLine.substring(currentIndex + 1);
+ currentComments = currentComments == null ?
+ comment :
+ currentComments + '\n' + comment;
+
+ // Skip the comments.
+ currentIndex = currentLineLength;
+ }
+ }
+
+ // Find the word starting at the current index.
+ int startIndex = currentIndex;
+ int endIndex;
+
+ char startChar = currentLine.charAt(startIndex);
+
+ if (isQuote(startChar))
+ {
+ // The next word is starting with a quote character.
+ // Skip the opening quote.
+ startIndex++;
+
+ // The next word is a quoted character string.
+ // Find the closing quote.
+ do
+ {
+ currentIndex++;
+
+ if (currentIndex == currentLineLength)
+ {
+ currentWord = currentLine.substring(startIndex-1, currentIndex);
+ throw new IOException("Missing closing quote for "+locationDescription());
+ }
+ }
+ while (currentLine.charAt(currentIndex) != startChar);
+
+ endIndex = currentIndex++;
+ }
+ else if (isFileName &&
+ !isOption(startChar))
+ {
+ // The next word is a (possibly optional) file name.
+ // Find the end of the line, the first path separator, the first
+ // option, or the first comment.
+ while (currentIndex < currentLineLength)
+ {
+ char currentCharacter = currentLine.charAt(currentIndex);
+ if (isFileDelimiter(currentCharacter) ||
+ ((isOption(currentCharacter) ||
+ isComment(currentCharacter)) &&
+ Character.isWhitespace(currentLine.charAt(currentIndex-1)))) {
+ break;
+ }
+
+ currentIndex++;
+ }
+
+ endIndex = currentIndex;
+
+ // Trim any trailing whitespace.
+ while (endIndex > startIndex &&
+ Character.isWhitespace(currentLine.charAt(endIndex-1)))
+ {
+ endIndex--;
+ }
+ }
+ else if (isDelimiter(startChar))
+ {
+ // The next word is a single delimiting character.
+ endIndex = ++currentIndex;
+ }
+ else
+ {
+ // The next word is a simple character string.
+ // Find the end of the line, the first delimiter, or the first
+ // white space.
+ while (currentIndex < currentLineLength)
+ {
+ char currentCharacter = currentLine.charAt(currentIndex);
+ if (isDelimiter(currentCharacter) ||
+ Character.isWhitespace(currentCharacter) ||
+ isComment(currentCharacter)) {
+ break;
+ }
+
+ currentIndex++;
+ }
+
+ endIndex = currentIndex;
+ }
+
+ // Remember and return the parsed word.
+ currentWord = currentLine.substring(startIndex, endIndex);
+
+ return currentWord;
+ }
+
+
+ /**
+ * Returns the comments collected before returning the last word.
+ * Starts collecting new comments.
+ *
+ * @return the collected comments, or null
if there weren't any.
+ */
+ public String lastComments() throws IOException
+ {
+ if (includeWordReader == null)
+ {
+ String comments = currentComments;
+ currentComments = null;
+ return comments;
+ }
+ else
+ {
+ return includeWordReader.lastComments();
+ }
+ }
+
+
+ /**
+ * Constructs a readable description of the current position in this
+ * WordReader and its included WordReader objects.
+ *
+ * @return the description.
+ */
+ public String locationDescription()
+ {
+ return
+ (includeWordReader == null ?
+ (currentWord == null ?
+ "end of " :
+ "'" + currentWord + "' in " ) :
+ (includeWordReader.locationDescription() + ",\n" +
+ " included from ")) +
+ lineLocationDescription();
+ }
+
+
+ /**
+ * Reads a line from this WordReader, or from one of its active included
+ * WordReader objects.
+ *
+ * @return the read line.
+ */
+ protected abstract String nextLine() throws IOException;
+
+
+ /**
+ * Returns a readable description of the current WordReader position.
+ *
+ * @return the description.
+ */
+ protected abstract String lineLocationDescription();
+
+
+ /**
+ * Closes the FileWordReader.
+ */
+ public void close() throws IOException
+ {
+ // Close and ditch the included word reader, if any.
+ if (includeWordReader != null)
+ {
+ includeWordReader.close();
+ includeWordReader = null;
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean isOption(char character)
+ {
+ return character == '-';
+ }
+
+
+ private boolean isComment(char character)
+ {
+ return character == COMMENT_CHARACTER;
+ }
+
+
+ private boolean isDelimiter(char character)
+ {
+ return character == '@' ||
+ character == '{' ||
+ character == '}' ||
+ character == '(' ||
+ character == ')' ||
+ character == ',' ||
+ character == ';' ||
+ character == File.pathSeparatorChar;
+ }
+
+
+ private boolean isFileDelimiter(char character)
+ {
+ return character == '(' ||
+ character == ')' ||
+ character == ',' ||
+ character == ';' ||
+ character == File.pathSeparatorChar;
+ }
+
+
+ private boolean isQuote(char character)
+ {
+ return character == '\'' ||
+ character == '"';
+ }
+}
diff --git a/src/proguard/ant/ClassPathElement.java b/src/proguard/ant/ClassPathElement.java
new file mode 100644
index 000000000..b49612315
--- /dev/null
+++ b/src/proguard/ant/ClassPathElement.java
@@ -0,0 +1,191 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.ant;
+
+import org.apache.tools.ant.*;
+import org.apache.tools.ant.types.*;
+import proguard.*;
+import proguard.util.ListUtil;
+
+import java.io.File;
+
+/**
+ * This FileSet represents a class path entry (or a set of class path entries)
+ * in Ant.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassPathElement extends Path
+{
+ private String filter;
+ private String jarFilter;
+ private String warFilter;
+ private String earFilter;
+ private String zipFilter;
+
+
+ /**
+ * @see Path#Path(Project)
+ */
+ public ClassPathElement(Project project)
+ {
+ super(project);
+ }
+
+
+ /**
+ * Adds the contents of this class path element to the given class path.
+ * @param classPath the class path to be extended.
+ * @param output specifies whether this is an output entry or not.
+ */
+ public void appendClassPathEntriesTo(ClassPath classPath, boolean output)
+ {
+ File baseDir = getProject().getBaseDir();
+ String[] fileNames;
+
+ if (isReference())
+ {
+ // Get the referenced path or file set.
+ Object referencedObject = getCheckedRef(DataType.class,
+ DataType.class.getName());
+
+ if (referencedObject instanceof Path)
+ {
+ Path path = (Path)referencedObject;
+
+ // Get the names of the files in the referenced path.
+ fileNames = path.list();
+ }
+ else if (referencedObject instanceof AbstractFileSet)
+ {
+ AbstractFileSet fileSet = (AbstractFileSet)referencedObject;
+
+ // Get the names of the existing input files in the referenced file set.
+ DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject());
+ baseDir = scanner.getBasedir();
+ fileNames = scanner.getIncludedFiles();
+ }
+ else
+ {
+ throw new BuildException("The refid attribute doesn't point to a null
or empty if its name is actually a
+ * boolean flag.
+ */
+ private File optionalFile(File file)
+ {
+ String fileName = file.getName();
+
+ return
+ fileName.equalsIgnoreCase("false") ||
+ fileName.equalsIgnoreCase("no") ||
+ fileName.equalsIgnoreCase("off") ? null :
+ fileName.equalsIgnoreCase("true") ||
+ fileName.equalsIgnoreCase("yes") ||
+ fileName.equalsIgnoreCase("on") ? Configuration.STD_OUT :
+ resolvedFile(file);
+ }
+
+
+ /**
+ * Returns a file that is properly resolved with respect to the project
+ * directory.
+ */
+ private File resolvedFile(File file)
+ {
+ return file.isAbsolute() ? file :
+ new File(getProject().getBaseDir(),
+ file.getName());
+ }
+}
diff --git a/src/proguard/ant/package.html b/src/proguard/ant/package.html
new file mode 100644
index 000000000..75e0466df
--- /dev/null
+++ b/src/proguard/ant/package.html
@@ -0,0 +1,3 @@
+
+This package contains the Ant task for ProGuard.
+
diff --git a/src/proguard/ant/task.properties b/src/proguard/ant/task.properties
new file mode 100644
index 000000000..82d0f3f41
--- /dev/null
+++ b/src/proguard/ant/task.properties
@@ -0,0 +1,2 @@
+proguard = proguard.ant.ProGuardTask
+proguardconfiguration = proguard.ant.ConfigurationTask
diff --git a/src/proguard/classfile/ClassConstants.java b/src/proguard/classfile/ClassConstants.java
new file mode 100644
index 000000000..59580c543
--- /dev/null
+++ b/src/proguard/classfile/ClassConstants.java
@@ -0,0 +1,329 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+/**
+ * Constants used in representing a Java class (*.class).
+ *
+ * @author Eric Lafortune
+ */
+public interface ClassConstants
+{
+ public static final String CLASS_FILE_EXTENSION = ".class";
+
+ public static final int MAGIC = 0xCAFEBABE;
+
+ public static final int INTERNAL_CLASS_VERSION_1_0_MAJOR = 45;
+ public static final int INTERNAL_CLASS_VERSION_1_0_MINOR = 3;
+ public static final int INTERNAL_CLASS_VERSION_1_2_MAJOR = 46;
+ public static final int INTERNAL_CLASS_VERSION_1_2_MINOR = 0;
+ public static final int INTERNAL_CLASS_VERSION_1_3_MAJOR = 47;
+ public static final int INTERNAL_CLASS_VERSION_1_3_MINOR = 0;
+ public static final int INTERNAL_CLASS_VERSION_1_4_MAJOR = 48;
+ public static final int INTERNAL_CLASS_VERSION_1_4_MINOR = 0;
+ public static final int INTERNAL_CLASS_VERSION_1_5_MAJOR = 49;
+ public static final int INTERNAL_CLASS_VERSION_1_5_MINOR = 0;
+ public static final int INTERNAL_CLASS_VERSION_1_6_MAJOR = 50;
+ public static final int INTERNAL_CLASS_VERSION_1_6_MINOR = 0;
+ public static final int INTERNAL_CLASS_VERSION_1_7_MAJOR = 51;
+ public static final int INTERNAL_CLASS_VERSION_1_7_MINOR = 0;
+
+ public static final int INTERNAL_CLASS_VERSION_1_0 = (INTERNAL_CLASS_VERSION_1_0_MAJOR << 16) | INTERNAL_CLASS_VERSION_1_0_MINOR;
+ public static final int INTERNAL_CLASS_VERSION_1_2 = (INTERNAL_CLASS_VERSION_1_2_MAJOR << 16) | INTERNAL_CLASS_VERSION_1_2_MINOR;
+ public static final int INTERNAL_CLASS_VERSION_1_3 = (INTERNAL_CLASS_VERSION_1_3_MAJOR << 16) | INTERNAL_CLASS_VERSION_1_3_MINOR;
+ public static final int INTERNAL_CLASS_VERSION_1_4 = (INTERNAL_CLASS_VERSION_1_4_MAJOR << 16) | INTERNAL_CLASS_VERSION_1_4_MINOR;
+ public static final int INTERNAL_CLASS_VERSION_1_5 = (INTERNAL_CLASS_VERSION_1_5_MAJOR << 16) | INTERNAL_CLASS_VERSION_1_5_MINOR;
+ public static final int INTERNAL_CLASS_VERSION_1_6 = (INTERNAL_CLASS_VERSION_1_6_MAJOR << 16) | INTERNAL_CLASS_VERSION_1_6_MINOR;
+ public static final int INTERNAL_CLASS_VERSION_1_7 = (INTERNAL_CLASS_VERSION_1_7_MAJOR << 16) | INTERNAL_CLASS_VERSION_1_7_MINOR;
+
+ public static final String EXTERNAL_CLASS_VERSION_1_0 = "1.0";
+ public static final String EXTERNAL_CLASS_VERSION_1_1 = "1.1";
+ public static final String EXTERNAL_CLASS_VERSION_1_2 = "1.2";
+ public static final String EXTERNAL_CLASS_VERSION_1_3 = "1.3";
+ public static final String EXTERNAL_CLASS_VERSION_1_4 = "1.4";
+ public static final String EXTERNAL_CLASS_VERSION_1_5 = "1.5";
+ public static final String EXTERNAL_CLASS_VERSION_1_6 = "1.6";
+ public static final String EXTERNAL_CLASS_VERSION_1_7 = "1.7";
+ public static final String EXTERNAL_CLASS_VERSION_1_5_ALIAS = "5";
+ public static final String EXTERNAL_CLASS_VERSION_1_6_ALIAS = "6";
+ public static final String EXTERNAL_CLASS_VERSION_1_7_ALIAS = "7";
+
+ public static final int INTERNAL_ACC_PUBLIC = 0x0001;
+ public static final int INTERNAL_ACC_PRIVATE = 0x0002;
+ public static final int INTERNAL_ACC_PROTECTED = 0x0004;
+ public static final int INTERNAL_ACC_STATIC = 0x0008;
+ public static final int INTERNAL_ACC_FINAL = 0x0010;
+ public static final int INTERNAL_ACC_SUPER = 0x0020;
+ public static final int INTERNAL_ACC_SYNCHRONIZED = 0x0020;
+ public static final int INTERNAL_ACC_VOLATILE = 0x0040;
+ public static final int INTERNAL_ACC_TRANSIENT = 0x0080;
+ public static final int INTERNAL_ACC_BRIDGE = 0x0040;
+ public static final int INTERNAL_ACC_VARARGS = 0x0080;
+ public static final int INTERNAL_ACC_NATIVE = 0x0100;
+ public static final int INTERNAL_ACC_INTERFACE = 0x0200;
+ public static final int INTERNAL_ACC_ABSTRACT = 0x0400;
+ public static final int INTERNAL_ACC_STRICT = 0x0800;
+ public static final int INTERNAL_ACC_SYNTHETIC = 0x1000;
+ public static final int INTERNAL_ACC_ANNOTATTION = 0x2000;
+ public static final int INTERNAL_ACC_ENUM = 0x4000;
+
+ public static final int VALID_INTERNAL_ACC_CLASS = INTERNAL_ACC_PUBLIC |
+ INTERNAL_ACC_FINAL |
+ INTERNAL_ACC_SUPER |
+ INTERNAL_ACC_INTERFACE |
+ INTERNAL_ACC_ABSTRACT |
+ INTERNAL_ACC_SYNTHETIC |
+ INTERNAL_ACC_ANNOTATTION |
+ INTERNAL_ACC_ENUM;
+ public static final int VALID_INTERNAL_ACC_FIELD = INTERNAL_ACC_PUBLIC |
+ INTERNAL_ACC_PRIVATE |
+ INTERNAL_ACC_PROTECTED |
+ INTERNAL_ACC_STATIC |
+ INTERNAL_ACC_FINAL |
+ INTERNAL_ACC_VOLATILE |
+ INTERNAL_ACC_TRANSIENT |
+ INTERNAL_ACC_SYNTHETIC |
+ INTERNAL_ACC_ENUM;
+ public static final int VALID_INTERNAL_ACC_METHOD = INTERNAL_ACC_PUBLIC |
+ INTERNAL_ACC_PRIVATE |
+ INTERNAL_ACC_PROTECTED |
+ INTERNAL_ACC_STATIC |
+ INTERNAL_ACC_FINAL |
+ INTERNAL_ACC_SYNCHRONIZED |
+ INTERNAL_ACC_BRIDGE |
+ INTERNAL_ACC_VARARGS |
+ INTERNAL_ACC_NATIVE |
+ INTERNAL_ACC_ABSTRACT |
+ INTERNAL_ACC_STRICT |
+ INTERNAL_ACC_SYNTHETIC;
+
+ public static final String EXTERNAL_ACC_PUBLIC = "public";
+ public static final String EXTERNAL_ACC_PRIVATE = "private";
+ public static final String EXTERNAL_ACC_PROTECTED = "protected";
+ public static final String EXTERNAL_ACC_STATIC = "static";
+ public static final String EXTERNAL_ACC_FINAL = "final";
+ public static final String EXTERNAL_ACC_SUPER = "super";
+ public static final String EXTERNAL_ACC_SYNCHRONIZED = "synchronized";
+ public static final String EXTERNAL_ACC_VOLATILE = "volatile";
+ public static final String EXTERNAL_ACC_TRANSIENT = "transient";
+ public static final String EXTERNAL_ACC_BRIDGE = "bridge";
+ public static final String EXTERNAL_ACC_VARARGS = "varargs";
+ public static final String EXTERNAL_ACC_NATIVE = "native";
+ public static final String EXTERNAL_ACC_INTERFACE = "interface";
+ public static final String EXTERNAL_ACC_ABSTRACT = "abstract";
+ public static final String EXTERNAL_ACC_STRICT = "strictfp";
+ public static final String EXTERNAL_ACC_SYNTHETIC = "synthetic";
+ public static final String EXTERNAL_ACC_ANNOTATION = "@";
+ public static final String EXTERNAL_ACC_ENUM = "enum";
+
+ public static final int CONSTANT_Utf8 = 1;
+ public static final int CONSTANT_Integer = 3;
+ public static final int CONSTANT_Float = 4;
+ public static final int CONSTANT_Long = 5;
+ public static final int CONSTANT_Double = 6;
+ public static final int CONSTANT_Class = 7;
+ public static final int CONSTANT_String = 8;
+ public static final int CONSTANT_Fieldref = 9;
+ public static final int CONSTANT_Methodref = 10;
+ public static final int CONSTANT_InterfaceMethodref = 11;
+ public static final int CONSTANT_NameAndType = 12;
+ public static final int CONSTANT_MethodHandle = 15;
+ public static final int CONSTANT_MethodType = 16;
+ public static final int CONSTANT_InvokeDynamic = 18;
+
+ public static final int REF_getField = 1;
+ public static final int REF_getStatic = 2;
+ public static final int REF_putField = 3;
+ public static final int REF_putStatic = 4;
+ public static final int REF_invokeVirtual = 5;
+ public static final int REF_invokeStatic = 6;
+ public static final int REF_invokeSpecial = 7;
+ public static final int REF_newInvokeSpecial = 8;
+ public static final int REF_invokeInterface = 9;
+
+ public static final String ATTR_BootstrapMethods = "BootstrapMethods";
+ public static final String ATTR_SourceFile = "SourceFile";
+ public static final String ATTR_SourceDir = "SourceDir";
+ public static final String ATTR_InnerClasses = "InnerClasses";
+ public static final String ATTR_EnclosingMethod = "EnclosingMethod";
+ public static final String ATTR_Deprecated = "Deprecated";
+ public static final String ATTR_Synthetic = "Synthetic";
+ public static final String ATTR_Signature = "Signature";
+ public static final String ATTR_ConstantValue = "ConstantValue";
+ public static final String ATTR_Exceptions = "Exceptions";
+ public static final String ATTR_Code = "Code";
+ public static final String ATTR_StackMap = "StackMap";
+ public static final String ATTR_StackMapTable = "StackMapTable";
+ public static final String ATTR_LineNumberTable = "LineNumberTable";
+ public static final String ATTR_LocalVariableTable = "LocalVariableTable";
+ public static final String ATTR_LocalVariableTypeTable = "LocalVariableTypeTable";
+ public static final String ATTR_RuntimeVisibleAnnotations = "RuntimeVisibleAnnotations";
+ public static final String ATTR_RuntimeInvisibleAnnotations = "RuntimeInvisibleAnnotations";
+ public static final String ATTR_RuntimeVisibleParameterAnnotations = "RuntimeVisibleParameterAnnotations";
+ public static final String ATTR_RuntimeInvisibleParameterAnnotations = "RuntimeInvisibleParameterAnnotations";
+ public static final String ATTR_AnnotationDefault = "AnnotationDefault";
+
+ public static final char ELEMENT_VALUE_STRING_CONSTANT = 's';
+ public static final char ELEMENT_VALUE_ENUM_CONSTANT = 'e';
+ public static final char ELEMENT_VALUE_CLASS = 'c';
+ public static final char ELEMENT_VALUE_ANNOTATION = '@';
+ public static final char ELEMENT_VALUE_ARRAY = '[';
+
+ public static final char EXTERNAL_PACKAGE_SEPARATOR = '.';
+ public static final char EXTERNAL_INNER_CLASS_SEPARATOR = '.';
+ public static final char INTERNAL_PACKAGE_SEPARATOR = '/';
+ public static final char INTERNAL_INNER_CLASS_SEPARATOR = '$';
+ public static final char SPECIAL_CLASS_CHARACTER = '-';
+ public static final char SPECIAL_MEMBER_SEPARATOR = '$';
+
+ public static final char EXTERNAL_METHOD_ARGUMENTS_OPEN = '(';
+ public static final char EXTERNAL_METHOD_ARGUMENTS_CLOSE = ')';
+ public static final char EXTERNAL_METHOD_ARGUMENTS_SEPARATOR = ',';
+
+ public static final char INTERNAL_METHOD_ARGUMENTS_OPEN = '(';
+ public static final char INTERNAL_METHOD_ARGUMENTS_CLOSE = ')';
+
+ public static final String INTERNAL_PACKAGE_JAVA_LANG = "java/lang/";
+ public static final String INTERNAL_NAME_JAVA_LANG_OBJECT = "java/lang/Object";
+ public static final String INTERNAL_TYPE_JAVA_LANG_OBJECT = "Ljava/lang/Object;";
+ public static final String INTERNAL_NAME_JAVA_LANG_CLONEABLE = "java/lang/Cloneable";
+ public static final String INTERNAL_NAME_JAVA_LANG_THROWABLE = "java/lang/Throwable";
+ public static final String INTERNAL_NAME_JAVA_LANG_CLASS = "java/lang/Class";
+ public static final String INTERNAL_NAME_JAVA_LANG_STRING = "java/lang/String";
+ public static final String INTERNAL_NAME_JAVA_LANG_STRING_BUFFER = "java/lang/StringBuffer";
+ public static final String INTERNAL_NAME_JAVA_LANG_STRING_BUILDER = "java/lang/StringBuilder";
+ public static final String INTERNAL_NAME_JAVA_LANG_INVOKE_METHOD_HANDLE = "java/lang/invoke/MethodHandle";
+ public static final String INTERNAL_NAME_JAVA_LANG_INVOKE_METHOD_TYPE = "java/lang/invoke/MethodType";
+ public static final String INTERNAL_NAME_JAVA_IO_SERIALIZABLE = "java/io/Serializable";
+
+ public static final String INTERNAL_NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_INTEGER_FIELD_UPDATER = "java/util/concurrent/atomic/AtomicIntegerFieldUpdater";
+ public static final String INTERNAL_NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_LONG_FIELD_UPDATER = "java/util/concurrent/atomic/AtomicLongFieldUpdater";
+ public static final String INTERNAL_NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_REFERENCE_FIELD_UPDATER = "java/util/concurrent/atomic/AtomicReferenceFieldUpdater";
+
+ public static final String INTERNAL_METHOD_NAME_INIT = "null
if the class with the given name is not in the class
+ * pool.
+ */
+ public Clazz getClass(String className)
+ {
+ return (Clazz)classes.get(className);
+ }
+
+
+ /**
+ * Returns an Iterator of all class names in the class pool.
+ */
+ public Iterator classNames()
+ {
+ return classes.keySet().iterator();
+ }
+
+
+ /**
+ * Returns the number of classes in the class pool.
+ */
+ public int size()
+ {
+ return classes.size();
+ }
+
+
+ /**
+ * Applies the given ClassPoolVisitor to the class pool.
+ */
+ public void accept(ClassPoolVisitor classPoolVisitor)
+ {
+ classPoolVisitor.visitClassPool(this);
+ }
+
+
+ /**
+ * Applies the given ClassVisitor to all classes in the class pool,
+ * in random order.
+ */
+ public void classesAccept(ClassVisitor classVisitor)
+ {
+ Iterator iterator = classes.values().iterator();
+ while (iterator.hasNext())
+ {
+ Clazz clazz = (Clazz)iterator.next();
+ clazz.accept(classVisitor);
+ }
+ }
+
+
+ /**
+ * Applies the given ClassVisitor to all classes in the class pool,
+ * in sorted order.
+ */
+ public void classesAcceptAlphabetically(ClassVisitor classVisitor)
+ {
+ // We're already using a tree map.
+ //TreeMap sortedClasses = new TreeMap(classes);
+ //Iterator iterator = sortedClasses.values().iterator();
+
+ Iterator iterator = classes.values().iterator();
+ while (iterator.hasNext())
+ {
+ Clazz clazz = (Clazz)iterator.next();
+ clazz.accept(classVisitor);
+ }
+ }
+
+
+ /**
+ * Applies the given ClassVisitor to the class with the given name,
+ * if it is present in the class pool.
+ */
+ public void classAccept(String className, ClassVisitor classVisitor)
+ {
+ Clazz clazz = getClass(className);
+ if (clazz != null)
+ {
+ clazz.accept(classVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/Clazz.java b/src/proguard/classfile/Clazz.java
new file mode 100644
index 000000000..35f8a1c2d
--- /dev/null
+++ b/src/proguard/classfile/Clazz.java
@@ -0,0 +1,261 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.visitor.*;
+
+
+/**
+ * This interface provides access to the representation of a Java class.
+ *
+ * @author Eric Lafortune
+ */
+public interface Clazz extends VisitorAccepter
+{
+ /**
+ * Returns the access flags of this class.
+ * @see ClassConstants
+ */
+ public int getAccessFlags();
+
+ /**
+ * Returns the full internal name of this class.
+ */
+ public String getName();
+
+ /**
+ * Returns the full internal name of the super class of this class, or
+ * null if this class represents java.lang.Object.
+ */
+ public String getSuperName();
+
+ /**
+ * Returns the number of interfaces that this class implements.
+ */
+ public int getInterfaceCount();
+
+ /**
+ * Returns the full internal name of the interface at the given index of
+ * this class.
+ */
+ public String getInterfaceName(int index);
+
+ /**
+ * Returns the tag value of the Constant at the specified index.
+ */
+ public int getTag(int constantIndex);
+
+ /**
+ * Returns the String value of the Utf8Constant at the specified index.
+ */
+ public String getString(int constantIndex);
+
+ /**
+ * Returns the String value of the StringConstant at the specified index.
+ */
+ public String getStringString(int constantIndex);
+
+ /**
+ * Returns the class name of ClassConstant at the specified index.
+ */
+ public String getClassName(int constantIndex);
+
+ /**
+ * Returns the name of the NameAndTypeConstant at the specified index.
+ */
+ public String getName(int constantIndex);
+
+ /**
+ * Returns the type of the NameAndTypeConstant at the specified index.
+ */
+ public String getType(int constantIndex);
+
+ /**
+ * Returns the name of the RefConstant at the specified index.
+ */
+ public String getRefName(int constantIndex);
+
+ /**
+ * Returns the type of the RefConstant at the specified index.
+ */
+ public String getRefType(int constantIndex);
+
+
+ // Methods pertaining to related classes.
+
+ /**
+ * Notifies this Clazz that it is being subclassed by another class.
+ */
+ public void addSubClass(Clazz clazz);
+
+ /**
+ * Returns the super class of this class.
+ */
+ public Clazz getSuperClass();
+
+ /**
+ * Returns the interface at the given index.
+ */
+ public Clazz getInterface(int index);
+
+ /**
+ * Returns whether this class extends the given class.
+ * A class is always considered to extend itself.
+ * Interfaces are considered to only extend the root Object class.
+ */
+ public boolean extends_(Clazz clazz);
+
+ /**
+ * Returns whether this class extends the specified class.
+ * A class is always considered to extend itself.
+ * Interfaces are considered to only extend the root Object class.
+ */
+ public boolean extends_(String className);
+
+ /**
+ * Returns whether this class implements the given class.
+ * A class is always considered to implement itself.
+ * Interfaces are considered to implement all their superinterfaces.
+ */
+ public boolean extendsOrImplements(Clazz clazz);
+
+ /**
+ * Returns whether this class implements the specified class.
+ * A class is always considered to implement itself.
+ * Interfaces are considered to implement all their superinterfaces.
+ */
+ public boolean extendsOrImplements(String className);
+
+
+ // Methods for getting specific class members.
+
+ /**
+ * Returns the field with the given name and descriptor.
+ */
+ Field findField(String name, String descriptor);
+
+ /**
+ * Returns the method with the given name and descriptor.
+ */
+ Method findMethod(String name, String descriptor);
+
+
+ // Methods for accepting various types of visitors.
+
+ /**
+ * Accepts the given class visitor.
+ */
+ public void accept(ClassVisitor classVisitor);
+
+ /**
+ * Accepts the given class visitor in the class hierarchy.
+ * @param visitThisClass specifies whether to visit this class.
+ * @param visitSuperClass specifies whether to visit the super classes.
+ * @param visitInterfaces specifies whether to visit the interfaces.
+ * @param visitSubclasses specifies whether to visit the subclasses.
+ * @param classVisitor the ClassVisitor
that will
+ * visit the class hierarchy.
+ */
+ public void hierarchyAccept(boolean visitThisClass,
+ boolean visitSuperClass,
+ boolean visitInterfaces,
+ boolean visitSubclasses,
+ ClassVisitor classVisitor);
+
+ /**
+ * Lets the given class visitor visit all known subclasses.
+ * @param classVisitor the ClassVisitor
that will visit the
+ * subclasses.
+ */
+ public void subclassesAccept(ClassVisitor classVisitor);
+
+ /**
+ * Lets the given constant pool entry visitor visit all constant pool entries
+ * of this class.
+ */
+ public void constantPoolEntriesAccept(ConstantVisitor constantVisitor);
+
+ /**
+ * Lets the given constant pool entry visitor visit the constant pool entry
+ * at the specified index.
+ */
+ public void constantPoolEntryAccept(int index, ConstantVisitor constantVisitor);
+
+ /**
+ * Lets the given constant pool entry visitor visit the class constant pool
+ * entry of this class.
+ */
+ public void thisClassConstantAccept(ConstantVisitor constantVisitor);
+
+ /**
+ * Lets the given constant pool entry visitor visit the class constant pool
+ * entry of the super class of this class, if there is one.
+ */
+ public void superClassConstantAccept(ConstantVisitor constantVisitor);
+
+ /**
+ * Lets the given constant pool entry visitor visit the class constant pool
+ * entries for all interfaces of this class.
+ */
+ public void interfaceConstantsAccept(ConstantVisitor constantVisitor);
+
+ /**
+ * Lets the given member info visitor visit all fields of this class.
+ */
+ public void fieldsAccept(MemberVisitor memberVisitor);
+
+ /**
+ * Lets the given member info visitor visit the specified field.
+ */
+ public void fieldAccept(String name, String descriptor, MemberVisitor memberVisitor);
+
+ /**
+ * Lets the given member info visitor visit all methods of this class.
+ */
+ public void methodsAccept(MemberVisitor memberVisitor);
+
+ /**
+ * Lets the given member info visitor visit the specified method.
+ */
+ public void methodAccept(String name, String descriptor, MemberVisitor memberVisitor);
+
+ /**
+ * Returns whether the given method may possibly have implementing or
+ * overriding methods down the class hierarchy. This can only be true
+ * if the class is not final, and the method is not private, static, or
+ * final, or a constructor.
+ * @param method the method that may have implementations.
+ * @return whether it may have implementations.
+ */
+ public boolean mayHaveImplementations(Method method);
+
+ /**
+ * Lets the given attribute info visitor visit all attributes of this class.
+ */
+ public void attributesAccept(AttributeVisitor attributeVisitor);
+
+ /**
+ * Lets the given attribute info visitor visit the specified attribute.
+ */
+ public void attributeAccept(String name, AttributeVisitor attributeVisitor);
+}
diff --git a/src/proguard/classfile/Field.java b/src/proguard/classfile/Field.java
new file mode 100644
index 000000000..61bf2daee
--- /dev/null
+++ b/src/proguard/classfile/Field.java
@@ -0,0 +1,32 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+
+
+/**
+ * Representation of a field from a class.
+ *
+ * @author Eric Lafortune
+ */
+public interface Field extends Member
+{
+}
diff --git a/src/proguard/classfile/LibraryClass.java b/src/proguard/classfile/LibraryClass.java
new file mode 100644
index 000000000..151a32a09
--- /dev/null
+++ b/src/proguard/classfile/LibraryClass.java
@@ -0,0 +1,548 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This Clazz is a compact representation of the essential data in a Java class.
+ *
+ * @author Eric Lafortune
+ */
+public class LibraryClass implements Clazz
+{
+ public int u2accessFlags;
+ public String thisClassName;
+ public String superClassName;
+ public String[] interfaceNames;
+ public LibraryField[] fields;
+ public LibraryMethod[] methods;
+
+ /**
+ * An extra field pointing to the superclass of this class.
+ * This field is filled out by the {@link ClassSuperHierarchyInitializer}.
+ */
+ public Clazz superClass;
+
+ /**
+ * An extra field pointing to the interfaces of this class.
+ * This field is filled out by the {@link ClassSuperHierarchyInitializer}.
+ */
+ public Clazz[] interfaceClasses;
+
+ /**
+ * An extra field pointing to the subclasses of this class.
+ * This field is filled out by the {@link ClassSubHierarchyInitializer}.
+ */
+ public Clazz[] subClasses;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an empty LibraryClass.
+ */
+ public LibraryClass() {}
+
+
+ /**
+ * Returns whether this library class is visible to the outside world.
+ */
+ boolean isVisible()
+ {
+ return (u2accessFlags & ClassConstants.INTERNAL_ACC_PUBLIC) != 0;
+ }
+
+
+ // Implementations for Clazz.
+
+ public int getAccessFlags()
+ {
+ return u2accessFlags;
+ }
+
+ public String getName()
+ {
+ return thisClassName;
+ }
+
+ public String getSuperName()
+ {
+ // This may be java/lang/Object, in which case there is no super.
+ return superClassName;
+ }
+
+ public int getInterfaceCount()
+ {
+ return interfaceClasses.length;
+ }
+
+ public String getInterfaceName(int index)
+ {
+ return interfaceNames[index];
+ }
+
+ public int getTag(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+ public String getString(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+ public String getStringString(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+ public String getClassName(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+ public String getName(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+ public String getType(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+
+ public String getRefName(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+ public String getRefType(int constantIndex)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store constant pool");
+ }
+
+
+ public void addSubClass(Clazz clazz)
+ {
+ if (subClasses == null)
+ {
+ subClasses = new Clazz[1];
+ }
+ else
+ {
+ // Copy the old elements into new larger array.
+ Clazz[] temp = new Clazz[subClasses.length+1];
+ System.arraycopy(subClasses, 0, temp, 0, subClasses.length);
+ subClasses = temp;
+ }
+
+ subClasses[subClasses.length-1] = clazz;
+ }
+
+
+ public Clazz getSuperClass()
+ {
+ return superClass;
+ }
+
+
+ public Clazz getInterface(int index)
+ {
+ return interfaceClasses[index];
+ }
+
+
+ public boolean extends_(Clazz clazz)
+ {
+ if (this.equals(clazz))
+ {
+ return true;
+ }
+
+ return superClass != null &&
+ superClass.extends_(clazz);
+ }
+
+
+ public boolean extends_(String className)
+ {
+ if (getName().equals(className))
+ {
+ return true;
+ }
+
+ return superClass != null &&
+ superClass.extends_(className);
+ }
+
+
+ public boolean extendsOrImplements(Clazz clazz)
+ {
+ if (this.equals(clazz))
+ {
+ return true;
+ }
+
+ if (superClass != null &&
+ superClass.extendsOrImplements(clazz))
+ {
+ return true;
+ }
+
+ if (interfaceClasses != null)
+ {
+ for (int index = 0; index < interfaceClasses.length; index++)
+ {
+ Clazz interfaceClass = interfaceClasses[index];
+ if (interfaceClass != null &&
+ interfaceClass.extendsOrImplements(clazz))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+
+ public boolean extendsOrImplements(String className)
+ {
+ if (getName().equals(className))
+ {
+ return true;
+ }
+
+ if (superClass != null &&
+ superClass.extendsOrImplements(className))
+ {
+ return true;
+ }
+
+ if (interfaceClasses != null)
+ {
+ for (int index = 0; index < interfaceClasses.length; index++)
+ {
+ Clazz interfaceClass = interfaceClasses[index];
+ if (interfaceClass != null &&
+ interfaceClass.extendsOrImplements(className))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+
+ public Field findField(String name, String descriptor)
+ {
+ for (int index = 0; index < fields.length; index++)
+ {
+ Field field = fields[index];
+ if (field != null &&
+ (name == null || field.getName(this).equals(name)) &&
+ (descriptor == null || field.getDescriptor(this).equals(descriptor)))
+ {
+ return field;
+ }
+ }
+
+ return null;
+ }
+
+
+ public Method findMethod(String name, String descriptor)
+ {
+ for (int index = 0; index < methods.length; index++)
+ {
+ Method method = methods[index];
+ if (method != null &&
+ (name == null || method.getName(this).equals(name)) &&
+ (descriptor == null || method.getDescriptor(this).equals(descriptor)))
+ {
+ return method;
+ }
+ }
+
+ return null;
+ }
+
+
+ public void accept(ClassVisitor classVisitor)
+ {
+ classVisitor.visitLibraryClass(this);
+ }
+
+
+ public void hierarchyAccept(boolean visitThisClass,
+ boolean visitSuperClass,
+ boolean visitInterfaces,
+ boolean visitSubclasses,
+ ClassVisitor classVisitor)
+ {
+ // First visit the current classfile.
+ if (visitThisClass)
+ {
+ accept(classVisitor);
+ }
+
+ // Then visit its superclass, recursively.
+ if (visitSuperClass)
+ {
+ if (superClass != null)
+ {
+ superClass.hierarchyAccept(true,
+ true,
+ visitInterfaces,
+ false,
+ classVisitor);
+ }
+ }
+
+ // Then visit its interfaces, recursively.
+ if (visitInterfaces)
+ {
+ // Visit the interfaces of the superclasses, if we haven't done so yet.
+ if (!visitSuperClass)
+ {
+ if (superClass != null)
+ {
+ superClass.hierarchyAccept(false,
+ false,
+ true,
+ false,
+ classVisitor);
+ }
+ }
+
+ // Visit the interfaces.
+ if (interfaceClasses != null)
+ {
+ for (int index = 0; index < interfaceClasses.length; index++)
+ {
+ Clazz interfaceClass = interfaceClasses[index];
+ if (interfaceClass != null)
+ {
+ interfaceClass.hierarchyAccept(true,
+ false,
+ true,
+ false,
+ classVisitor);
+ }
+ }
+ }
+ }
+
+ // Then visit its subclasses, recursively.
+ if (visitSubclasses)
+ {
+ if (subClasses != null)
+ {
+ for (int index = 0; index < subClasses.length; index++)
+ {
+ subClasses[index].hierarchyAccept(true,
+ false,
+ false,
+ true,
+ classVisitor);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Lets the given class visitor visit the superclass, if it is known.
+ * @param classVisitor the ClassVisitor
that will visit the
+ * superclass.
+ */
+ public void superClassAccept(ClassVisitor classVisitor)
+ {
+ if (superClass != null)
+ {
+ superClass.accept(classVisitor);
+ }
+ }
+
+
+ /**
+ * Lets the given class visitor visit all known direct interfaces.
+ * @param classVisitor the ClassVisitor
that will visit the
+ * interfaces.
+ */
+ public void interfacesAccept(ClassVisitor classVisitor)
+ {
+ if (interfaceClasses != null)
+ {
+ for (int index = 0; index < interfaceClasses.length; index++)
+ {
+ Clazz interfaceClass = interfaceClasses[index];
+ if (interfaceClass != null)
+ {
+ interfaceClass.accept(classVisitor);
+ }
+ }
+ }
+ }
+
+
+ public void subclassesAccept(ClassVisitor classVisitor)
+ {
+ if (subClasses != null)
+ {
+ for (int index = 0; index < subClasses.length; index++)
+ {
+ subClasses[index].accept(classVisitor);
+ }
+ }
+ }
+
+
+ public void constantPoolEntriesAccept(ConstantVisitor constantVisitor)
+ {
+ // This class doesn't keep references to its constant pool entries.
+ }
+
+
+ public void constantPoolEntryAccept(int index, ConstantVisitor constantVisitor)
+ {
+ // This class doesn't keep references to its constant pool entries.
+ }
+
+
+ public void thisClassConstantAccept(ConstantVisitor constantVisitor)
+ {
+ // This class doesn't keep references to its constant pool entries.
+ }
+
+
+ public void superClassConstantAccept(ConstantVisitor constantVisitor)
+ {
+ // This class doesn't keep references to its constant pool entries.
+ }
+
+
+ public void interfaceConstantsAccept(ConstantVisitor constantVisitor)
+ {
+ // This class doesn't keep references to its constant pool entries.
+ }
+
+
+ public void fieldsAccept(MemberVisitor memberVisitor)
+ {
+ for (int index = 0; index < fields.length; index++)
+ {
+ Field field = fields[index];
+ if (field != null)
+ {
+ field.accept(this, memberVisitor);
+ }
+ }
+ }
+
+
+ public void fieldAccept(String name, String descriptor, MemberVisitor memberVisitor)
+ {
+ Field field = findField(name, descriptor);
+ if (field != null)
+ {
+ field.accept(this, memberVisitor);
+ }
+ }
+
+
+ public void methodsAccept(MemberVisitor memberVisitor)
+ {
+ for (int index = 0; index < methods.length; index++)
+ {
+ Method method = methods[index];
+ if (method != null)
+ {
+ method.accept(this, memberVisitor);
+ }
+ }
+ }
+
+
+ public void methodAccept(String name, String descriptor, MemberVisitor memberVisitor)
+ {
+ Method method = findMethod(name, descriptor);
+ if (method != null)
+ {
+ method.accept(this, memberVisitor);
+ }
+ }
+
+
+ public boolean mayHaveImplementations(Method method)
+ {
+ return
+ (u2accessFlags & ClassConstants.INTERNAL_ACC_FINAL) == 0 &&
+ (method == null ||
+ ((method.getAccessFlags() & (ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC |
+ ClassConstants.INTERNAL_ACC_FINAL)) == 0 &&
+ !method.getName(this).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT)));
+ }
+
+
+ public void attributesAccept(AttributeVisitor attributeVisitor)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store attributes");
+ }
+
+
+ public void attributeAccept(String name, AttributeVisitor attributeVisitor)
+ {
+ throw new UnsupportedOperationException("Library class ["+thisClassName+"] doesn't store attributes");
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "LibraryClass("+getName()+")";
+ }
+}
diff --git a/src/proguard/classfile/LibraryField.java b/src/proguard/classfile/LibraryField.java
new file mode 100644
index 000000000..1c1c427dd
--- /dev/null
+++ b/src/proguard/classfile/LibraryField.java
@@ -0,0 +1,77 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.visitor.*;
+
+/**
+ * Representation of a field from a class-file.
+ *
+ * @author Eric Lafortune
+ */
+public class LibraryField extends LibraryMember implements Field
+{
+ /**
+ * An extra field pointing to the Clazz object referenced in the
+ * descriptor string. This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz referencedClass;
+
+
+ /**
+ * Creates an uninitialized LibraryField.
+ */
+ public LibraryField()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LibraryField.
+ */
+ public LibraryField(int u2accessFlags,
+ String name,
+ String descriptor)
+ {
+ super(u2accessFlags, name, descriptor);
+ }
+
+
+ // Implementations for LibraryMember.
+
+ public void accept(LibraryClass libraryClass, MemberVisitor memberVisitor)
+ {
+ memberVisitor.visitLibraryField(libraryClass, this);
+ }
+
+
+ // Implementations for Member.
+
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/LibraryMember.java b/src/proguard/classfile/LibraryMember.java
new file mode 100644
index 000000000..8d8d00e08
--- /dev/null
+++ b/src/proguard/classfile/LibraryMember.java
@@ -0,0 +1,108 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * Representation of a field or method from a library class.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class LibraryMember implements Member
+{
+ private static final int ACC_VISIBLE = ClassConstants.INTERNAL_ACC_PUBLIC |
+ ClassConstants.INTERNAL_ACC_PROTECTED;
+
+
+ public int u2accessFlags;
+ public String name;
+ public String descriptor;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized LibraryMember.
+ */
+ protected LibraryMember()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LibraryMember.
+ */
+ protected LibraryMember(int u2accessFlags,
+ String name,
+ String descriptor)
+ {
+ this.u2accessFlags = u2accessFlags;
+ this.name = name;
+ this.descriptor = descriptor;
+ }
+
+
+ /**
+ * Accepts the given member info visitor.
+ */
+ public abstract void accept(LibraryClass libraryClass,
+ MemberVisitor memberVisitor);
+
+
+ // Implementations for Member.
+
+ public int getAccessFlags()
+ {
+ return u2accessFlags;
+ }
+
+ public String getName(Clazz clazz)
+ {
+ return name;
+ }
+
+ public String getDescriptor(Clazz clazz)
+ {
+ return descriptor;
+ }
+
+ public void accept(Clazz clazz, MemberVisitor memberVisitor)
+ {
+ accept((LibraryClass)clazz, memberVisitor);
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/LibraryMethod.java b/src/proguard/classfile/LibraryMethod.java
new file mode 100644
index 000000000..ac0785753
--- /dev/null
+++ b/src/proguard/classfile/LibraryMethod.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.visitor.*;
+
+/**
+ * Representation of a method from a class-file.
+ *
+ * @author Eric Lafortune
+ */
+public class LibraryMethod extends LibraryMember implements Method
+{
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * descriptor string. This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+
+ /**
+ * Creates an uninitialized LibraryMethod.
+ */
+ public LibraryMethod()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LibraryMethod.
+ */
+ public LibraryMethod(int u2accessFlags,
+ String name,
+ String descriptor)
+ {
+ super(u2accessFlags, name, descriptor);
+ }
+
+
+ // Implementations for LibraryMember.
+
+ public void accept(LibraryClass libraryClass, MemberVisitor memberVisitor)
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, this);
+ }
+
+
+ // Implementations for Member.
+
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ if (referencedClasses[index] != null)
+ {
+ referencedClasses[index].accept(classVisitor);
+ }
+ }
+ }
+ }
+}
diff --git a/src/proguard/classfile/Member.java b/src/proguard/classfile/Member.java
new file mode 100644
index 000000000..ee2cf1949
--- /dev/null
+++ b/src/proguard/classfile/Member.java
@@ -0,0 +1,57 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.visitor.*;
+
+/**
+ * Representation of a field or method from a class.
+ *
+ * @author Eric Lafortune
+ */
+public interface Member extends VisitorAccepter
+{
+ /**
+ * Returns the access flags.
+ */
+ public int getAccessFlags();
+
+ /**
+ * Returns the class member name.
+ */
+ public String getName(Clazz clazz);
+
+ /**
+ * Returns the class member's descriptor.
+ */
+ public String getDescriptor(Clazz clazz);
+
+ /**
+ * Accepts the given class visitor.
+ */
+ public void accept(Clazz clazz, MemberVisitor memberVisitor);
+
+ /**
+ * Lets the Clazz objects referenced in the descriptor string
+ * accept the given visitor.
+ */
+ public void referencedClassesAccept(ClassVisitor classVisitor);
+}
diff --git a/src/proguard/classfile/Method.java b/src/proguard/classfile/Method.java
new file mode 100644
index 000000000..64ff50a73
--- /dev/null
+++ b/src/proguard/classfile/Method.java
@@ -0,0 +1,32 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+
+
+/**
+ * Representation of a method from a class.
+ *
+ * @author Eric Lafortune
+ */
+public interface Method extends Member
+{
+}
diff --git a/src/proguard/classfile/ProgramClass.java b/src/proguard/classfile/ProgramClass.java
new file mode 100644
index 000000000..54bb8b1de
--- /dev/null
+++ b/src/proguard/classfile/ProgramClass.java
@@ -0,0 +1,572 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.ClassSubHierarchyInitializer;
+import proguard.classfile.visitor.*;
+
+/**
+ * This Clazz is a complete representation of the data in a Java class.
+ *
+ * @author Eric Lafortune
+ */
+public class ProgramClass implements Clazz
+{
+ public int u4magic;
+ public int u4version;
+ public int u2constantPoolCount;
+ public Constant[] constantPool;
+ public int u2accessFlags;
+ public int u2thisClass;
+ public int u2superClass;
+ public int u2interfacesCount;
+ public int[] u2interfaces;
+ public int u2fieldsCount;
+ public ProgramField[] fields;
+ public int u2methodsCount;
+ public ProgramMethod[] methods;
+ public int u2attributesCount;
+ public Attribute[] attributes;
+
+ /**
+ * An extra field pointing to the subclasses of this class.
+ * This field is filled out by the {@link ClassSubHierarchyInitializer}.
+ */
+ public Clazz[] subClasses;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized ProgramClass.
+ */
+ public ProgramClass() {}
+
+
+ /**
+ * Returns the Constant at the given index in the constant pool.
+ */
+ public Constant getConstant(int constantIndex)
+ {
+ return constantPool[constantIndex];
+ }
+
+
+ // Implementations for Clazz.
+
+ public int getAccessFlags()
+ {
+ return u2accessFlags;
+ }
+
+ public String getName()
+ {
+ return getClassName(u2thisClass);
+ }
+
+ public String getSuperName()
+ {
+ return u2superClass == 0 ? null : getClassName(u2superClass);
+ }
+
+ public int getInterfaceCount()
+ {
+ return u2interfacesCount;
+ }
+
+ public String getInterfaceName(int index)
+ {
+ return getClassName(u2interfaces[index]);
+ }
+
+ public int getTag(int constantIndex)
+ {
+ return constantPool[constantIndex].getTag();
+ }
+
+ public String getString(int constantIndex)
+ {
+ try
+ {
+ return ((Utf8Constant)constantPool[constantIndex]).getString();
+ }
+ catch (ClassCastException ex)
+ {
+ throw ((IllegalStateException)new IllegalStateException("Expected Utf8Constant at index ["+constantIndex+"] in class ["+getName()+"]").initCause(ex));
+ }
+ }
+
+ public String getStringString(int constantIndex)
+ {
+ try
+ {
+ return ((StringConstant)constantPool[constantIndex]).getString(this);
+ }
+ catch (ClassCastException ex)
+ {
+ throw ((IllegalStateException)new IllegalStateException("Expected StringConstant at index ["+constantIndex+"] in class ["+getName()+"]").initCause(ex));
+ }
+ }
+
+ public String getClassName(int constantIndex)
+ {
+ try
+ {
+ return ((ClassConstant)constantPool[constantIndex]).getName(this);
+ }
+ catch (ClassCastException ex)
+ {
+ throw ((IllegalStateException)new IllegalStateException("Expected ClassConstant at index ["+constantIndex+"] in class ["+getName()+"]").initCause(ex));
+ }
+ }
+
+ public String getName(int constantIndex)
+ {
+ try
+ {
+ return ((NameAndTypeConstant)constantPool[constantIndex]).getName(this);
+ }
+ catch (ClassCastException ex)
+ {
+ throw ((IllegalStateException)new IllegalStateException("Expected NameAndTypeConstant at index ["+constantIndex+"] in class ["+getName()+"]").initCause(ex));
+ }
+ }
+
+ public String getType(int constantIndex)
+ {
+ try
+ {
+ return ((NameAndTypeConstant)constantPool[constantIndex]).getType(this);
+ }
+ catch (ClassCastException ex)
+ {
+ throw ((IllegalStateException)new IllegalStateException("Expected NameAndTypeConstant at index ["+constantIndex+"] in class ["+getName()+"]").initCause(ex));
+ }
+ }
+
+
+ public String getRefName(int constantIndex)
+ {
+ try
+ {
+ return ((RefConstant)constantPool[constantIndex]).getName(this);
+ }
+ catch (ClassCastException ex)
+ {
+ throw ((IllegalStateException)new IllegalStateException("Expected RefConstant at index ["+constantIndex+"] in class ["+getName()+"]").initCause(ex));
+ }
+ }
+
+ public String getRefType(int constantIndex)
+ {
+ try
+ {
+ return ((RefConstant)constantPool[constantIndex]).getType(this);
+ }
+ catch (ClassCastException ex)
+ {
+ throw ((IllegalStateException)new IllegalStateException("Expected RefConstant at index ["+constantIndex+"] in class ["+getName()+"]").initCause(ex));
+ }
+ }
+
+
+ public void addSubClass(Clazz clazz)
+ {
+ if (subClasses == null)
+ {
+ subClasses = new Clazz[1];
+ }
+ else
+ {
+ // Copy the old elements into new larger array.
+ Clazz[] temp = new Clazz[subClasses.length+1];
+ System.arraycopy(subClasses, 0, temp, 0, subClasses.length);
+ subClasses = temp;
+ }
+
+ subClasses[subClasses.length-1] = clazz;
+ }
+
+
+ public Clazz getSuperClass()
+ {
+ return u2superClass != 0 ?
+ ((ClassConstant)constantPool[u2superClass]).referencedClass :
+ null;
+ }
+
+
+ public Clazz getInterface(int index)
+ {
+ return ((ClassConstant)constantPool[u2interfaces[index]]).referencedClass;
+ }
+
+
+ public boolean extends_(Clazz clazz)
+ {
+ if (this.equals(clazz))
+ {
+ return true;
+ }
+
+ Clazz superClass = getSuperClass();
+ return superClass != null &&
+ superClass.extends_(clazz);
+ }
+
+
+ public boolean extends_(String className)
+ {
+ if (getName().equals(className))
+ {
+ return true;
+ }
+
+ Clazz superClass = getSuperClass();
+ return superClass != null &&
+ superClass.extends_(className);
+ }
+
+
+ public boolean extendsOrImplements(Clazz clazz)
+ {
+ if (this.equals(clazz))
+ {
+ return true;
+ }
+
+ Clazz superClass = getSuperClass();
+ if (superClass != null &&
+ superClass.extendsOrImplements(clazz))
+ {
+ return true;
+ }
+
+ for (int index = 0; index < u2interfacesCount; index++)
+ {
+ Clazz interfaceClass = getInterface(index);
+ if (interfaceClass != null &&
+ interfaceClass.extendsOrImplements(clazz))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ public boolean extendsOrImplements(String className)
+ {
+ if (getName().equals(className))
+ {
+ return true;
+ }
+
+ Clazz superClass = getSuperClass();
+ if (superClass != null &&
+ superClass.extendsOrImplements(className))
+ {
+ return true;
+ }
+
+ for (int index = 0; index < u2interfacesCount; index++)
+ {
+ Clazz interfaceClass = getInterface(index);
+ if (interfaceClass != null &&
+ interfaceClass.extendsOrImplements(className))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ public Field findField(String name, String descriptor)
+ {
+ for (int index = 0; index < u2fieldsCount; index++)
+ {
+ Field field = fields[index];
+ if ((name == null || field.getName(this).equals(name)) &&
+ (descriptor == null || field.getDescriptor(this).equals(descriptor)))
+ {
+ return field;
+ }
+ }
+
+ return null;
+ }
+
+
+ public Method findMethod(String name, String descriptor)
+ {
+ for (int index = 0; index < u2methodsCount; index++)
+ {
+ Method method = methods[index];
+ if ((name == null || method.getName(this).equals(name)) &&
+ (descriptor == null || method.getDescriptor(this).equals(descriptor)))
+ {
+ return method;
+ }
+ }
+
+ return null;
+ }
+
+
+ public void accept(ClassVisitor classVisitor)
+ {
+ classVisitor.visitProgramClass(this);
+ }
+
+
+ public void hierarchyAccept(boolean visitThisClass,
+ boolean visitSuperClass,
+ boolean visitInterfaces,
+ boolean visitSubclasses,
+ ClassVisitor classVisitor)
+ {
+ // First visit the current classfile.
+ if (visitThisClass)
+ {
+ accept(classVisitor);
+ }
+
+ // Then visit its superclass, recursively.
+ if (visitSuperClass)
+ {
+ Clazz superClass = getSuperClass();
+ if (superClass != null)
+ {
+ superClass.hierarchyAccept(true,
+ true,
+ visitInterfaces,
+ false,
+ classVisitor);
+ }
+ }
+
+ // Then visit its interfaces, recursively.
+ if (visitInterfaces)
+ {
+ // Visit the interfaces of the superclasses, if we haven't done so yet.
+ if (!visitSuperClass)
+ {
+ Clazz superClass = getSuperClass();
+ if (superClass != null)
+ {
+ superClass.hierarchyAccept(false,
+ false,
+ true,
+ false,
+ classVisitor);
+ }
+ }
+
+ // Visit the interfaces.
+ for (int index = 0; index < u2interfacesCount; index++)
+ {
+ Clazz interfaceClass = getInterface(index);
+ if (interfaceClass != null)
+ {
+ interfaceClass.hierarchyAccept(true,
+ false,
+ true,
+ false,
+ classVisitor);
+ }
+ }
+ }
+
+ // Then visit its subclasses, recursively.
+ if (visitSubclasses)
+ {
+ if (subClasses != null)
+ {
+ for (int index = 0; index < subClasses.length; index++)
+ {
+ Clazz subClass = subClasses[index];
+ subClass.hierarchyAccept(true,
+ false,
+ false,
+ true,
+ classVisitor);
+ }
+ }
+ }
+ }
+
+
+ public void subclassesAccept(ClassVisitor classVisitor)
+ {
+ if (subClasses != null)
+ {
+ for (int index = 0; index < subClasses.length; index++)
+ {
+ subClasses[index].accept(classVisitor);
+ }
+ }
+ }
+
+
+ public void constantPoolEntriesAccept(ConstantVisitor constantVisitor)
+ {
+ for (int index = 1; index < u2constantPoolCount; index++)
+ {
+ if (constantPool[index] != null)
+ {
+ constantPool[index].accept(this, constantVisitor);
+ }
+ }
+ }
+
+
+ public void constantPoolEntryAccept(int index, ConstantVisitor constantVisitor)
+ {
+ constantPool[index].accept(this, constantVisitor);
+ }
+
+
+ public void thisClassConstantAccept(ConstantVisitor constantVisitor)
+ {
+ constantPool[u2thisClass].accept(this, constantVisitor);
+ }
+
+
+ public void superClassConstantAccept(ConstantVisitor constantVisitor)
+ {
+ if (u2superClass != 0)
+ {
+ constantPool[u2superClass].accept(this, constantVisitor);
+ }
+ }
+
+
+ public void interfaceConstantsAccept(ConstantVisitor constantVisitor)
+ {
+ for (int index = 0; index < u2interfacesCount; index++)
+ {
+ constantPool[u2interfaces[index]].accept(this, constantVisitor);
+ }
+ }
+
+
+ public void fieldsAccept(MemberVisitor memberVisitor)
+ {
+ for (int index = 0; index < u2fieldsCount; index++)
+ {
+ fields[index].accept(this, memberVisitor);
+ }
+ }
+
+
+ public void fieldAccept(String name, String descriptor, MemberVisitor memberVisitor)
+ {
+ Field field = findField(name, descriptor);
+ if (field != null)
+ {
+ field.accept(this, memberVisitor);
+ }
+ }
+
+
+ public void methodsAccept(MemberVisitor memberVisitor)
+ {
+ for (int index = 0; index < u2methodsCount; index++)
+ {
+ methods[index].accept(this, memberVisitor);
+ }
+ }
+
+
+ public void methodAccept(String name, String descriptor, MemberVisitor memberVisitor)
+ {
+ Method method = findMethod(name, descriptor);
+ if (method != null)
+ {
+ method.accept(this, memberVisitor);
+ }
+ }
+
+
+ public boolean mayHaveImplementations(Method method)
+ {
+ return
+ (u2accessFlags & ClassConstants.INTERNAL_ACC_FINAL) == 0 &&
+ (method == null ||
+ ((method.getAccessFlags() & (ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC |
+ ClassConstants.INTERNAL_ACC_FINAL)) == 0 &&
+ !method.getName(this).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT)));
+ }
+
+
+ public void attributesAccept(AttributeVisitor attributeVisitor)
+ {
+ for (int index = 0; index < u2attributesCount; index++)
+ {
+ attributes[index].accept(this, attributeVisitor);
+ }
+ }
+
+
+ public void attributeAccept(String name, AttributeVisitor attributeVisitor)
+ {
+ for (int index = 0; index < u2attributesCount; index++)
+ {
+ Attribute attribute = attributes[index];
+ if (attribute.getAttributeName(this).equals(name))
+ {
+ attribute.accept(this, attributeVisitor);
+ }
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "ProgramClass("+getName()+")";
+ }
+}
diff --git a/src/proguard/classfile/ProgramField.java b/src/proguard/classfile/ProgramField.java
new file mode 100644
index 000000000..3bdfd85ec
--- /dev/null
+++ b/src/proguard/classfile/ProgramField.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.visitor.*;
+
+/**
+ * Representation of a field from a program class.
+ *
+ * @author Eric Lafortune
+ */
+public class ProgramField extends ProgramMember implements Field
+{
+ /**
+ * An extra field pointing to the Clazz object referenced in the
+ * descriptor string. This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz referencedClass;
+
+
+ /**
+ * Creates an uninitialized ProgramField.
+ */
+ public ProgramField()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ProgramField.
+ */
+ public ProgramField(int u2accessFlags,
+ int u2nameIndex,
+ int u2descriptorIndex,
+ int u2attributesCount,
+ Attribute[] attributes,
+ Clazz referencedClass)
+ {
+ super(u2accessFlags, u2nameIndex, u2descriptorIndex, u2attributesCount, attributes);
+
+ this.referencedClass = referencedClass;
+ }
+
+
+ // Implementations for ProgramMember.
+
+ public void accept(ProgramClass programClass, MemberVisitor memberVisitor)
+ {
+ memberVisitor.visitProgramField(programClass, this);
+ }
+
+
+ public void attributesAccept(ProgramClass programClass, AttributeVisitor attributeVisitor)
+ {
+ for (int index = 0; index < u2attributesCount; index++)
+ {
+ attributes[index].accept(programClass, this, attributeVisitor);
+ }
+ }
+
+
+ // Implementations for Member.
+
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/ProgramMember.java b/src/proguard/classfile/ProgramMember.java
new file mode 100644
index 000000000..240d3440f
--- /dev/null
+++ b/src/proguard/classfile/ProgramMember.java
@@ -0,0 +1,140 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * Representation of a field or method from a program class.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class ProgramMember implements Member
+{
+ public int u2accessFlags;
+ public int u2nameIndex;
+ public int u2descriptorIndex;
+ public int u2attributesCount;
+ public Attribute[] attributes;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized ProgramMember.
+ */
+ protected ProgramMember()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ProgramMember.
+ */
+ protected ProgramMember(int u2accessFlags,
+ int u2nameIndex,
+ int u2descriptorIndex,
+ int u2attributesCount,
+ Attribute[] attributes)
+ {
+ this.u2accessFlags = u2accessFlags;
+ this.u2nameIndex = u2nameIndex;
+ this.u2descriptorIndex = u2descriptorIndex;
+ this.u2attributesCount = u2attributesCount;
+ this.attributes = attributes;
+ }
+
+
+ /**
+ * Returns the (first) attribute with the given name.
+ */
+ private Attribute getAttribute(Clazz clazz, String name)
+ {
+ for (int index = 0; index < u2attributesCount; index++)
+ {
+ Attribute attribute = attributes[index];
+ if (attribute.getAttributeName(clazz).equals(name))
+ {
+ return attribute;
+ }
+ }
+
+ return null;
+ }
+
+
+ /**
+ * Accepts the given member info visitor.
+ */
+ public abstract void accept(ProgramClass programClass,
+ MemberVisitor memberVisitor);
+
+
+
+ /**
+ * Lets the given attribute info visitor visit all the attributes of
+ * this member info.
+ */
+ public abstract void attributesAccept(ProgramClass programClass,
+ AttributeVisitor attributeVisitor);
+
+
+ // Implementations for Member.
+
+ public int getAccessFlags()
+ {
+ return u2accessFlags;
+ }
+
+ public String getName(Clazz clazz)
+ {
+ return clazz.getString(u2nameIndex);
+ }
+
+ public String getDescriptor(Clazz clazz)
+ {
+ return clazz.getString(u2descriptorIndex);
+ }
+
+ public void accept(Clazz clazz, MemberVisitor memberVisitor)
+ {
+ accept((ProgramClass)clazz, memberVisitor);
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/ProgramMethod.java b/src/proguard/classfile/ProgramMethod.java
new file mode 100644
index 000000000..26f793fb4
--- /dev/null
+++ b/src/proguard/classfile/ProgramMethod.java
@@ -0,0 +1,99 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.visitor.*;
+
+/**
+ * Representation of a method from a program class.
+ *
+ * @author Eric Lafortune
+ */
+public class ProgramMethod extends ProgramMember implements Method
+{
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * descriptor string. This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+
+ /**
+ * Creates an uninitialized ProgramMethod.
+ */
+ public ProgramMethod()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ProgramMethod.
+ */
+ public ProgramMethod(int u2accessFlags,
+ int u2nameIndex,
+ int u2descriptorIndex,
+ int u2attributesCount,
+ Attribute[] attributes,
+ Clazz[] referencedClasses)
+ {
+ super(u2accessFlags, u2nameIndex, u2descriptorIndex, u2attributesCount, attributes);
+
+ this.referencedClasses = referencedClasses;
+ }
+
+
+ // Implementations for ProgramMember.
+
+ public void accept(ProgramClass programClass, MemberVisitor memberVisitor)
+ {
+ memberVisitor.visitProgramMethod(programClass, this);
+ }
+
+
+ public void attributesAccept(ProgramClass programClass, AttributeVisitor attributeVisitor)
+ {
+ for (int index = 0; index < u2attributesCount; index++)
+ {
+ attributes[index].accept(programClass, this, attributeVisitor);
+ }
+ }
+
+
+ // Implementations for Member.
+
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ if (referencedClasses[index] != null)
+ {
+ referencedClasses[index].accept(classVisitor);
+ }
+ }
+ }
+ }
+}
diff --git a/src/proguard/classfile/VisitorAccepter.java b/src/proguard/classfile/VisitorAccepter.java
new file mode 100644
index 000000000..9c7a062c9
--- /dev/null
+++ b/src/proguard/classfile/VisitorAccepter.java
@@ -0,0 +1,47 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile;
+
+
+
+
+/**
+ * This interface is a base interface for visitor accepters. It allows
+ * visitors to set and get any temporary information they desire on the
+ * objects they are visiting. Note that every visitor accepter has only one
+ * such property, so visitors will have to take care not to overwrite each
+ * other's information, if it is still required.
+ *
+ * @author Eric Lafortune
+ */
+public interface VisitorAccepter
+{
+ /**
+ * Gets the visitor information of the visitor accepter.
+ */
+ public Object getVisitorInfo();
+
+
+ /**
+ * Sets the visitor information of the visitor accepter.
+ */
+ public void setVisitorInfo(Object visitorInfo);
+}
diff --git a/src/proguard/classfile/attribute/Attribute.java b/src/proguard/classfile/attribute/Attribute.java
new file mode 100644
index 000000000..f34a0eef6
--- /dev/null
+++ b/src/proguard/classfile/attribute/Attribute.java
@@ -0,0 +1,142 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This abstract class represents an attribute that is attached to a class,
+ * a class member, or a code attribute. Specific types of attributes are
+ * subclassed from it.
+ *
+ * @author Eric Lafortune
+ * @noinspection AbstractClassWithoutAbstractMethods
+ */
+public abstract class Attribute implements VisitorAccepter
+{
+ public int u2attributeNameIndex;
+ //public int u4attributeLength;
+ //public byte info[];
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Create an uninitialized Attribute.
+ */
+ protected Attribute()
+ {
+ }
+
+
+ /**
+ * Create an initialized Attribute.
+ */
+ protected Attribute(int u2attributeNameIndex)
+ {
+ this.u2attributeNameIndex = u2attributeNameIndex;
+ }
+
+
+ /**
+ * Returns the String name of the attribute.
+ */
+ public String getAttributeName(Clazz clazz)
+ {
+ return clazz.getString(u2attributeNameIndex);
+ }
+
+
+ // Methods to be implemented by extensions, if applicable.
+
+ /**
+ * Accepts the given visitor.
+ */
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ throw new UnsupportedOperationException("Method must be overridden in ["+this.getClass().getName()+"] if ever called");
+ }
+
+ /**
+ * Accepts the given visitor in the context of the given field.
+ */
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ // Delegate the default invocation if the field is null anyway.
+ if (field == null)
+ {
+ accept(clazz, attributeVisitor);
+ }
+ else
+ {
+ throw new UnsupportedOperationException("Method must be overridden in ["+this.getClass().getName()+"] if ever called");
+ }
+ }
+
+ /**
+ * Accepts the given visitor in the context of the given method.
+ */
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ // Delegate the default invocation if the method is null anyway.
+ if (method == null)
+ {
+ accept(clazz, (Field)null, attributeVisitor);
+ }
+ else
+ {
+ throw new UnsupportedOperationException("Method must be overridden in ["+this.getClass().getName()+"] if ever called");
+ }
+ }
+
+ /**
+ * Accepts the given visitor in the context of the given code attribute.
+ */
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, AttributeVisitor attributeVisitor)
+ {
+ // Delegate the default invocation if the code attribute is null anyway.
+ if (codeAttribute == null)
+ {
+ accept(clazz, method, attributeVisitor);
+ }
+ else
+ {
+ throw new UnsupportedOperationException("Method must be overridden in ["+this.getClass().getName()+"] if ever called");
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/attribute/BootstrapMethodInfo.java b/src/proguard/classfile/attribute/BootstrapMethodInfo.java
new file mode 100755
index 000000000..f24676613
--- /dev/null
+++ b/src/proguard/classfile/attribute/BootstrapMethodInfo.java
@@ -0,0 +1,89 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * Representation of a bootstrap method.
+ *
+ * @author Eric Lafortune
+ */
+public class BootstrapMethodInfo implements VisitorAccepter
+{
+ public int u2methodHandleIndex;
+ public int u2methodArgumentCount;
+ public int[] u2methodArguments;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized BootstrapMethodInfo.
+ */
+ public BootstrapMethodInfo()
+ {
+ }
+
+
+ /**
+ * Creates an initialized BootstrapMethodInfo.
+ */
+ public BootstrapMethodInfo(int u2methodHandleIndex,
+ int u2methodArgumentCount,
+ int[] u2methodArguments)
+ {
+ this.u2methodHandleIndex = u2methodHandleIndex;
+ this.u2methodArgumentCount = u2methodArgumentCount;
+ this.u2methodArguments = u2methodArguments;
+ }
+
+
+ /**
+ * Applies the given constant pool visitor to the argument constants of the
+ * bootstrap method.
+ */
+ public void methodArgumentsAccept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ for (int index = 0; index < u2methodArgumentCount; index++)
+ {
+ clazz.constantPoolEntryAccept(u2methodArguments[index],
+ constantVisitor);
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/attribute/BootstrapMethodsAttribute.java b/src/proguard/classfile/attribute/BootstrapMethodsAttribute.java
new file mode 100755
index 000000000..4471a75eb
--- /dev/null
+++ b/src/proguard/classfile/attribute/BootstrapMethodsAttribute.java
@@ -0,0 +1,95 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Attribute represents a bootstrap methods attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class BootstrapMethodsAttribute extends Attribute
+{
+ public int u2bootstrapMethodsCount;
+ public BootstrapMethodInfo[] bootstrapMethods;
+
+
+ /**
+ * Creates an uninitialized BootstrapMethodsAttribute.
+ */
+ public BootstrapMethodsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized BootstrapMethodsAttribute.
+ */
+ public BootstrapMethodsAttribute(int u2attributeNameIndex,
+ int u2bootstrapMethodsCount,
+ BootstrapMethodInfo[] bootstrapMethods)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2bootstrapMethodsCount = u2bootstrapMethodsCount;
+ this.bootstrapMethods = bootstrapMethods;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitBootstrapMethodsAttribute(clazz, this);
+ }
+
+
+ /**
+ * Applies the given constant pool visitor to all bootstrap method info
+ * entries.
+ */
+ public void bootstrapMethodEntriesAccept(Clazz clazz, BootstrapMethodInfoVisitor bootstrapMethodInfoVisitor)
+ {
+ for (int index = 0; index < u2bootstrapMethodsCount; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of BootstrapMethodInfo.
+ bootstrapMethodInfoVisitor.visitBootstrapMethodInfo(clazz, bootstrapMethods[index]);
+ }
+ }
+
+
+ /**
+ * Applies the given constant pool visitor to the specified bootstrap method
+ * info entry.
+ */
+ public void bootstrapMethodEntryAccept(Clazz clazz,
+ int bootstrapMethodIndex,
+ BootstrapMethodInfoVisitor bootstrapMethodInfoVisitor)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of BootstrapMethodInfo.
+ bootstrapMethodInfoVisitor.visitBootstrapMethodInfo(clazz, bootstrapMethods[bootstrapMethodIndex]);
+ }
+}
diff --git a/src/proguard/classfile/attribute/CodeAttribute.java b/src/proguard/classfile/attribute/CodeAttribute.java
new file mode 100644
index 000000000..b3d4f4c93
--- /dev/null
+++ b/src/proguard/classfile/attribute/CodeAttribute.java
@@ -0,0 +1,202 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+/**
+ * This Attribute represents a code attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class CodeAttribute extends Attribute
+{
+ public int u2maxStack;
+ public int u2maxLocals;
+ public int u4codeLength;
+ public byte[] code;
+ public int u2exceptionTableLength;
+ public ExceptionInfo[] exceptionTable;
+ public int u2attributesCount;
+ public Attribute[] attributes;
+
+
+ /**
+ * Creates an uninitialized CodeAttribute.
+ */
+ public CodeAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized CodeAttribute.
+ */
+ public CodeAttribute(int u2attributeNameIndex,
+ int u2maxStack,
+ int u2maxLocals,
+ int u4codeLength,
+ byte[] code,
+ int u2exceptionTableLength,
+ ExceptionInfo[] exceptionTable,
+ int u2attributesCount,
+ Attribute[] attributes)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2maxStack = u2maxStack;
+ this.u2maxLocals = u2maxLocals;
+ this.u4codeLength = u4codeLength;
+ this.code = code;
+ this.u2exceptionTableLength = u2exceptionTableLength;
+ this.exceptionTable = exceptionTable;
+ this.u2attributesCount = u2attributesCount;
+ this.attributes = attributes;
+ }
+
+
+ /**
+ * Returns the (first) attribute with the given name.
+ */
+ public Attribute getAttribute(Clazz clazz, String name)
+ {
+ for (int index = 0; index < u2attributesCount; index++)
+ {
+ Attribute attribute = attributes[index];
+ if (attribute.getAttributeName(clazz).equals(name))
+ {
+ return attribute;
+ }
+ }
+
+ return null;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitCodeAttribute(clazz, method, this);
+ }
+
+
+ /**
+ * Applies the given instruction visitor to all instructions.
+ */
+ public void instructionsAccept(Clazz clazz, Method method, InstructionVisitor instructionVisitor)
+ {
+ instructionsAccept(clazz, method, 0, u4codeLength, instructionVisitor);
+ }
+
+
+ /**
+ * Applies the given instruction visitor to the instruction at the specified
+ * offset.
+ */
+ public void instructionAccept(Clazz clazz, Method method, int offset, InstructionVisitor instructionVisitor)
+ {
+ Instruction instruction = InstructionFactory.create(code, offset);
+ instruction.accept(clazz, method, this, offset, instructionVisitor);
+ }
+
+
+ /**
+ * Applies the given instruction visitor to all instructions in the
+ * specified range of offsets.
+ */
+ public void instructionsAccept(Clazz clazz, Method method, int startOffset, int endOffset, InstructionVisitor instructionVisitor)
+ {
+ int offset = startOffset;
+
+ while (offset < endOffset)
+ {
+ // Note that the instruction is only volatile.
+ Instruction instruction = InstructionFactory.create(code, offset);
+ int instructionLength = instruction.length(offset);
+ instruction.accept(clazz, method, this, offset, instructionVisitor);
+ offset += instructionLength;
+ }
+ }
+
+
+ /**
+ * Applies the given exception visitor to all exceptions.
+ */
+ public void exceptionsAccept(Clazz clazz, Method method, ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ for (int index = 0; index < u2exceptionTableLength; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of ExceptionInfo.
+ exceptionInfoVisitor.visitExceptionInfo(clazz, method, this, exceptionTable[index]);
+ }
+ }
+
+
+ /**
+ * Applies the given exception visitor to all exceptions that are applicable
+ * to the instruction at the specified offset.
+ */
+ public void exceptionsAccept(Clazz clazz, Method method, int offset, ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ for (int index = 0; index < u2exceptionTableLength; index++)
+ {
+ ExceptionInfo exceptionInfo = exceptionTable[index];
+ if (exceptionInfo.isApplicable(offset))
+ {
+ exceptionInfoVisitor.visitExceptionInfo(clazz, method, this, exceptionInfo);
+ }
+ }
+ }
+
+
+ /**
+ * Applies the given exception visitor to all exceptions that are applicable
+ * to any of the instructions in the specified range of offsets.
+ */
+ public void exceptionsAccept(Clazz clazz, Method method, int startOffset, int endOffset, ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ for (int index = 0; index < u2exceptionTableLength; index++)
+ {
+ ExceptionInfo exceptionInfo = exceptionTable[index];
+ if (exceptionInfo.isApplicable(startOffset, endOffset))
+ {
+ exceptionInfoVisitor.visitExceptionInfo(clazz, method, this, exceptionInfo);
+ }
+ }
+ }
+
+
+ /**
+ * Applies the given attribute visitor to all attributes.
+ */
+ public void attributesAccept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ for (int index = 0; index < u2attributesCount; index++)
+ {
+ attributes[index].accept(clazz, method, this, attributeVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/ConstantValueAttribute.java b/src/proguard/classfile/attribute/ConstantValueAttribute.java
new file mode 100644
index 000000000..056e377b2
--- /dev/null
+++ b/src/proguard/classfile/attribute/ConstantValueAttribute.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a constant value attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantValueAttribute extends Attribute
+{
+ public int u2constantValueIndex;
+
+
+ /**
+ * Creates an uninitialized ConstantValueAttribute.
+ */
+ public ConstantValueAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ConstantValueAttribute.
+ */
+ public ConstantValueAttribute(int u2attributeNameIndex,
+ int u2constantValueIndex)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2constantValueIndex = u2constantValueIndex;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitConstantValueAttribute(clazz, field, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/DeprecatedAttribute.java b/src/proguard/classfile/attribute/DeprecatedAttribute.java
new file mode 100644
index 000000000..f668063bd
--- /dev/null
+++ b/src/proguard/classfile/attribute/DeprecatedAttribute.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a deprecated attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class DeprecatedAttribute extends Attribute
+{
+ /**
+ * Creates an uninitialized DeprecatedAttribute.
+ */
+ public DeprecatedAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized DeprecatedAttribute.
+ */
+ public DeprecatedAttribute(int u2attributeNameIndex)
+ {
+ super(u2attributeNameIndex);
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitDeprecatedAttribute(clazz, this);
+ }
+
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitDeprecatedAttribute(clazz, field, this);
+ }
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitDeprecatedAttribute(clazz, method, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/EnclosingMethodAttribute.java b/src/proguard/classfile/attribute/EnclosingMethodAttribute.java
new file mode 100644
index 000000000..1c2ecc4bf
--- /dev/null
+++ b/src/proguard/classfile/attribute/EnclosingMethodAttribute.java
@@ -0,0 +1,132 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This Attribute represents an enclosing method attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class EnclosingMethodAttribute extends Attribute
+{
+ public int u2classIndex;
+ public int u2nameAndTypeIndex;
+
+ /**
+ * An extra field pointing to the referenced Clazz object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ */
+ public Clazz referencedClass;
+
+ /**
+ * An extra field optionally pointing to the referenced Method object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ */
+ public Method referencedMethod;
+
+
+ /**
+ * Creates an uninitialized EnclosingMethodAttribute.
+ */
+ public EnclosingMethodAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized EnclosingMethodAttribute.
+ */
+ public EnclosingMethodAttribute(int u2attributeNameIndex,
+ int u2classIndex,
+ int u2nameAndTypeIndex)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2classIndex = u2classIndex;
+ this.u2nameAndTypeIndex = u2nameAndTypeIndex;
+ }
+
+
+ /**
+ * Returns the class name.
+ */
+ public String getClassName(Clazz clazz)
+ {
+ return clazz.getClassName(u2classIndex);
+ }
+
+ /**
+ * Returns the method/field name.
+ */
+ public String getName(Clazz clazz)
+ {
+ return clazz.getName(u2nameAndTypeIndex);
+ }
+
+ /**
+ * Returns the type.
+ */
+ public String getType(Clazz clazz)
+ {
+ return clazz.getType(u2nameAndTypeIndex);
+ }
+
+
+ /**
+ * Lets the referenced class accept the given visitor.
+ */
+ public void referencedClassAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+
+
+ /**
+ * Lets the referenced class member accept the given visitor.
+ */
+ public void referencedMethodAccept(MemberVisitor memberVisitor)
+ {
+ if (referencedMethod != null)
+ {
+ referencedMethod.accept(referencedClass,
+ memberVisitor);
+ }
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitEnclosingMethodAttribute(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/ExceptionInfo.java b/src/proguard/classfile/attribute/ExceptionInfo.java
new file mode 100644
index 000000000..31512e5d3
--- /dev/null
+++ b/src/proguard/classfile/attribute/ExceptionInfo.java
@@ -0,0 +1,100 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.VisitorAccepter;
+
+/**
+ * Representation of an Exception table entry.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionInfo implements VisitorAccepter
+{
+ public int u2startPC;
+ public int u2endPC;
+ public int u2handlerPC;
+ public int u2catchType;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized ExceptionInfo.
+ */
+ public ExceptionInfo()
+ {
+ this(0, 0, 0, 0);
+ }
+
+
+ /**
+ * Creates an ExceptionInfo with the given properties.
+ */
+ public ExceptionInfo(int u2startPC,
+ int u2endPC,
+ int u2handlerPC,
+ int u2catchType)
+ {
+ this.u2startPC = u2startPC;
+ this.u2endPC = u2endPC;
+ this.u2handlerPC = u2handlerPC;
+ this.u2catchType = u2catchType;
+ }
+
+
+ /**
+ * Returns whether the exception's try block contains the instruction at the
+ * given offset.
+ */
+ public boolean isApplicable(int instructionOffset)
+ {
+ return instructionOffset >= u2startPC &&
+ instructionOffset < u2endPC;
+ }
+
+
+ /**
+ * Returns whether the exception's try block overlaps with the specified
+ * block of instructions.
+ */
+ public boolean isApplicable(int startOffset, int endOffset)
+ {
+ return u2startPC < endOffset &&
+ u2endPC > startOffset;
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/attribute/ExceptionsAttribute.java b/src/proguard/classfile/attribute/ExceptionsAttribute.java
new file mode 100644
index 000000000..ff7b84a13
--- /dev/null
+++ b/src/proguard/classfile/attribute/ExceptionsAttribute.java
@@ -0,0 +1,80 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Attribute represents an exceptions attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionsAttribute extends Attribute
+{
+ public int u2exceptionIndexTableLength;
+ public int[] u2exceptionIndexTable;
+
+
+ /**
+ * Creates an uninitialized ExceptionsAttribute.
+ */
+ public ExceptionsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ExceptionsAttribute.
+ */
+ public ExceptionsAttribute(int u2attributeNameIndex,
+ int u2exceptionIndexTableLength,
+ int[] u2exceptionIndexTable)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2exceptionIndexTableLength = u2exceptionIndexTableLength;
+ this.u2exceptionIndexTable = u2exceptionIndexTable;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitExceptionsAttribute(clazz, method, this);
+ }
+
+
+ /**
+ * Applies the given constant pool visitor to all exception class pool info
+ * entries.
+ */
+ public void exceptionEntriesAccept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ for (int index = 0; index < u2exceptionIndexTableLength; index++)
+ {
+ clazz.constantPoolEntryAccept(u2exceptionIndexTable[index],
+ constantVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/InnerClassesAttribute.java b/src/proguard/classfile/attribute/InnerClassesAttribute.java
new file mode 100644
index 000000000..b08d104d5
--- /dev/null
+++ b/src/proguard/classfile/attribute/InnerClassesAttribute.java
@@ -0,0 +1,80 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.visitor.*;
+
+/**
+ * This Attribute represents an inner classes attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class InnerClassesAttribute extends Attribute
+{
+ public int u2classesCount;
+ public InnerClassesInfo[] classes;
+
+
+ /**
+ * Creates an uninitialized InnerClassesAttribute.
+ */
+ public InnerClassesAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized InnerClassesAttribute.
+ */
+ public InnerClassesAttribute(int u2attributeNameIndex,
+ int u2classesCount,
+ InnerClassesInfo[] classes)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2classesCount = u2classesCount;
+ this.classes = classes;
+ }
+
+ //
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitInnerClassesAttribute(clazz, this);
+ }
+
+
+ /**
+ * Applies the given visitor to all inner classes.
+ */
+ public void innerClassEntriesAccept(Clazz clazz, InnerClassesInfoVisitor innerClassesInfoVisitor)
+ {
+ for (int index = 0; index < u2classesCount; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of InnerClassesInfo.
+ innerClassesInfoVisitor.visitInnerClassesInfo(clazz, classes[index]);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/InnerClassesInfo.java b/src/proguard/classfile/attribute/InnerClassesInfo.java
new file mode 100644
index 000000000..87b9de4ee
--- /dev/null
+++ b/src/proguard/classfile/attribute/InnerClassesInfo.java
@@ -0,0 +1,119 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * Representation of an Inner Classes table entry.
+ *
+ * @author Eric Lafortune
+ */
+public class InnerClassesInfo implements VisitorAccepter
+{
+ public int u2innerClassIndex;
+ public int u2outerClassIndex;
+ public int u2innerNameIndex;
+ public int u2innerClassAccessFlags;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Returns the inner class index.
+ */
+ protected int getInnerClassIndex()
+ {
+ return u2innerClassIndex;
+ }
+
+ /**
+ * Returns the name index.
+ */
+ protected int getInnerNameIndex()
+ {
+ return u2innerNameIndex;
+ }
+
+ /**
+ * Sets the name index.
+ */
+ protected void setInnerNameIndex(int index)
+ {
+ u2innerNameIndex = index;
+ }
+
+
+ /**
+ * Applies the given constant pool visitor to the class constant of the
+ * inner class, if any.
+ */
+ public void innerClassConstantAccept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ if (u2innerClassIndex != 0)
+ {
+ clazz.constantPoolEntryAccept(u2innerClassIndex, constantVisitor);
+ }
+ }
+
+
+ /**
+ * Applies the given constant pool visitor to the class constant of the
+ * outer class, if any.
+ */
+ public void outerClassConstantAccept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ if (u2outerClassIndex != 0)
+ {
+ clazz.constantPoolEntryAccept(u2outerClassIndex, constantVisitor);
+ }
+ }
+
+
+ /**
+ * Applies the given constant pool visitor to the Utf8 constant of the
+ * inner name, if any.
+ */
+ public void innerNameConstantAccept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ if (u2innerNameIndex != 0)
+ {
+ clazz.constantPoolEntryAccept(u2innerNameIndex, constantVisitor);
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/attribute/LineNumberInfo.java b/src/proguard/classfile/attribute/LineNumberInfo.java
new file mode 100644
index 000000000..1bcacefbc
--- /dev/null
+++ b/src/proguard/classfile/attribute/LineNumberInfo.java
@@ -0,0 +1,50 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+/**
+ * Representation of an Line Number table entry.
+ *
+ * @author Eric Lafortune
+ */
+public class LineNumberInfo
+{
+ public int u2startPC;
+ public int u2lineNumber;
+
+
+ /**
+ * Creates an uninitialized LineNumberInfo.
+ */
+ public LineNumberInfo()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LineNumberInfo.
+ */
+ public LineNumberInfo(int u2startPC, int u2lineNumber)
+ {
+ this.u2startPC = u2startPC;
+ this.u2lineNumber = u2lineNumber;
+ }
+}
diff --git a/src/proguard/classfile/attribute/LineNumberTableAttribute.java b/src/proguard/classfile/attribute/LineNumberTableAttribute.java
new file mode 100644
index 000000000..c217119b3
--- /dev/null
+++ b/src/proguard/classfile/attribute/LineNumberTableAttribute.java
@@ -0,0 +1,150 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+
+/**
+ * This Attribute represents a line number table attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class LineNumberTableAttribute extends Attribute
+{
+ public int u2lineNumberTableLength;
+ public LineNumberInfo[] lineNumberTable;
+
+
+ /**
+ * Creates an uninitialized LineNumberTableAttribute.
+ */
+ public LineNumberTableAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LineNumberTableAttribute.
+ */
+ public LineNumberTableAttribute(int u2attributeNameIndex,
+ int u2lineNumberTableLength,
+ LineNumberInfo[] lineNumberTable)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2lineNumberTableLength = u2lineNumberTableLength;
+ this.lineNumberTable = lineNumberTable;
+ }
+
+
+ /**
+ * Returns the line number corresponding to the given byte code program
+ * counter.
+ */
+ public int getLineNumber(int pc)
+ {
+ for (int index = u2lineNumberTableLength-1 ; index >= 0 ; index--)
+ {
+ LineNumberInfo info = lineNumberTable[index];
+ if (pc >= info.u2startPC)
+ {
+ return info.u2lineNumber;
+ }
+ }
+
+ return u2lineNumberTableLength > 0 ?
+ lineNumberTable[0].u2lineNumber :
+ 0;
+ }
+
+
+ /**
+ * Returns the lowest line number, or 0 if there aren't any line numbers.
+ */
+ public int getLowestLineNumber()
+ {
+ if (u2lineNumberTableLength == 0)
+ {
+ return 0;
+ }
+
+ int lowestLineNumber = Integer.MAX_VALUE;
+
+ for (int index = 0; index < u2lineNumberTableLength; index++)
+ {
+ int lineNumber = lineNumberTable[index].u2lineNumber;
+ if (lineNumber < lowestLineNumber)
+ {
+ lowestLineNumber = lineNumber;
+ }
+ }
+
+ return lowestLineNumber;
+ }
+
+
+ /**
+ * Returns the highest line number, or 0 if there aren't any line numbers.
+ */
+ public int getHighestLineNumber()
+ {
+ if (u2lineNumberTableLength == 0)
+ {
+ return 0;
+ }
+
+ int highestLineNumber = Integer.MIN_VALUE;
+
+ for (int index = 0; index < u2lineNumberTableLength; index++)
+ {
+ int lineNumber = lineNumberTable[index].u2lineNumber;
+ if (lineNumber > highestLineNumber)
+ {
+ highestLineNumber = lineNumber;
+ }
+ }
+
+ return highestLineNumber;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitLineNumberTableAttribute(clazz, method, codeAttribute, this);
+ }
+
+
+ /**
+ * Applies the given visitor to all line numbers.
+ */
+ public void lineNumbersAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberInfoVisitor lineNumberInfoVisitor)
+ {
+ for (int index = 0; index < u2lineNumberTableLength; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of LineNumberInfo.
+ lineNumberInfoVisitor.visitLineNumberInfo(clazz, method, codeAttribute, lineNumberTable[index]);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/LocalVariableInfo.java b/src/proguard/classfile/attribute/LocalVariableInfo.java
new file mode 100644
index 000000000..00bbd505f
--- /dev/null
+++ b/src/proguard/classfile/attribute/LocalVariableInfo.java
@@ -0,0 +1,117 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * Representation of an Local Variable table entry.
+ *
+ * @author Eric Lafortune
+ */
+public class LocalVariableInfo implements VisitorAccepter, Comparable
+{
+ public int u2startPC;
+ public int u2length;
+ public int u2nameIndex;
+ public int u2descriptorIndex;
+ public int u2index;
+
+ /**
+ * An extra field pointing to the referenced Clazz object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ */
+ public Clazz referencedClass;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized LocalVariableInfo.
+ */
+ public LocalVariableInfo()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LocalVariableInfo.
+ */
+ public LocalVariableInfo(int u2startPC,
+ int u2length,
+ int u2nameIndex,
+ int u2descriptorIndex,
+ int u2index)
+ {
+ this.u2startPC = u2startPC;
+ this.u2length = u2length;
+ this.u2nameIndex = u2nameIndex;
+ this.u2descriptorIndex = u2descriptorIndex;
+ this.u2index = u2index;
+ }
+
+
+ /**
+ * Lets the referenced class accept the given visitor.
+ */
+ public void referencedClassAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+
+
+ // Implementations for Comparable.
+
+ public int compareTo(Object object)
+ {
+ LocalVariableInfo other = (LocalVariableInfo)object;
+
+ return
+ this.u2startPC < other.u2startPC ? -1 : this.u2startPC > other.u2startPC ? 1 :
+ this.u2index < other.u2index ? -1 : this.u2index > other.u2index ? 1 :
+ this.u2length < other.u2length ? -1 : this.u2length > other.u2length ? 1 :
+ this.u2descriptorIndex < other.u2descriptorIndex ? -1 : this.u2descriptorIndex > other.u2descriptorIndex ? 1 :
+ this.u2nameIndex < other.u2nameIndex ? -1 : this.u2nameIndex > other.u2nameIndex ? 1 :
+ 0;
+ }
+}
diff --git a/src/proguard/classfile/attribute/LocalVariableTableAttribute.java b/src/proguard/classfile/attribute/LocalVariableTableAttribute.java
new file mode 100644
index 000000000..9e081c015
--- /dev/null
+++ b/src/proguard/classfile/attribute/LocalVariableTableAttribute.java
@@ -0,0 +1,79 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+
+/**
+ * This Attribute represents a local variable table attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class LocalVariableTableAttribute extends Attribute
+{
+ public int u2localVariableTableLength;
+ public LocalVariableInfo[] localVariableTable;
+
+
+ /**
+ * Creates an uninitialized LocalVariableTableAttribute.
+ */
+ public LocalVariableTableAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LocalVariableTableAttribute.
+ */
+ public LocalVariableTableAttribute(int u2attributeNameIndex,
+ int u2localVariableTableLength,
+ LocalVariableInfo[] localVariableTable)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2localVariableTableLength = u2localVariableTableLength;
+ this.localVariableTable = localVariableTable;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitLocalVariableTableAttribute(clazz, method, codeAttribute, this);
+ }
+
+
+ /**
+ * Applies the given visitor to all local variables.
+ */
+ public void localVariablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfoVisitor localVariableInfoVisitor)
+ {
+ for (int index = 0; index < u2localVariableTableLength; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of LocalVariableInfo.
+ localVariableInfoVisitor.visitLocalVariableInfo(clazz, method, codeAttribute, localVariableTable[index]);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/LocalVariableTypeInfo.java b/src/proguard/classfile/attribute/LocalVariableTypeInfo.java
new file mode 100644
index 000000000..15b9d246a
--- /dev/null
+++ b/src/proguard/classfile/attribute/LocalVariableTypeInfo.java
@@ -0,0 +1,125 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * Representation of an Local Variable table entry.
+ *
+ * @author Eric Lafortune
+ */
+public class LocalVariableTypeInfo implements VisitorAccepter, Comparable
+{
+ public int u2startPC;
+ public int u2length;
+ public int u2nameIndex;
+ public int u2signatureIndex;
+ public int u2index;
+
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * type string. This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized LocalVariableTypeInfo.
+ */
+ public LocalVariableTypeInfo()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LocalVariableTypeInfo.
+ */
+ public LocalVariableTypeInfo(int u2startPC,
+ int u2length,
+ int u2nameIndex,
+ int u2signatureIndex,
+ int u2index)
+ {
+ this.u2startPC = u2startPC;
+ this.u2length = u2length;
+ this.u2nameIndex = u2nameIndex;
+ this.u2signatureIndex = u2signatureIndex;
+ this.u2index = u2index;
+ }
+
+
+ /**
+ * Applies the given visitor to all referenced classes.
+ */
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ Clazz referencedClass = referencedClasses[index];
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+
+
+ // Implementations for Comparable.
+
+ public int compareTo(Object object)
+ {
+ LocalVariableTypeInfo other = (LocalVariableTypeInfo)object;
+
+ return
+ this.u2startPC < other.u2startPC ? -1 : this.u2startPC > other.u2startPC ? 1 :
+ this.u2length < other.u2length ? -1 : this.u2length > other.u2length ? 1 :
+ this.u2index < other.u2index ? -1 : this.u2index > other.u2index ? 1 :
+ this.u2signatureIndex < other.u2signatureIndex ? -1 : this.u2signatureIndex > other.u2signatureIndex ? 1 :
+ this.u2nameIndex < other.u2nameIndex ? -1 : this.u2nameIndex > other.u2nameIndex ? 1 :
+ 0;
+ }
+}
diff --git a/src/proguard/classfile/attribute/LocalVariableTypeTableAttribute.java b/src/proguard/classfile/attribute/LocalVariableTypeTableAttribute.java
new file mode 100644
index 000000000..dda24fb88
--- /dev/null
+++ b/src/proguard/classfile/attribute/LocalVariableTypeTableAttribute.java
@@ -0,0 +1,79 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+
+/**
+ * This Attribute represents a local variable table type attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class LocalVariableTypeTableAttribute extends Attribute
+{
+ public int u2localVariableTypeTableLength;
+ public LocalVariableTypeInfo[] localVariableTypeTable;
+
+
+ /**
+ * Creates an uninitialized LocalVariableTypeTableAttribute.
+ */
+ public LocalVariableTypeTableAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized LocalVariableTypeTableAttribute.
+ */
+ public LocalVariableTypeTableAttribute(int u2attributeNameIndex,
+ int u2localVariableTypeTableLength,
+ LocalVariableTypeInfo[] localVariableTypeTable)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2localVariableTypeTableLength = u2localVariableTypeTableLength;
+ this.localVariableTypeTable = localVariableTypeTable;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitLocalVariableTypeTableAttribute(clazz, method, codeAttribute, this);
+ }
+
+
+ /**
+ * Applies the given visitor to all local variable types.
+ */
+ public void localVariablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfoVisitor localVariableTypeInfoVisitor)
+ {
+ for (int index = 0; index < u2localVariableTypeTableLength; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of LocalVariableTypeInfo.
+ localVariableTypeInfoVisitor.visitLocalVariableTypeInfo(clazz, method, codeAttribute, localVariableTypeTable[index]);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/SignatureAttribute.java b/src/proguard/classfile/attribute/SignatureAttribute.java
new file mode 100644
index 000000000..86f95b826
--- /dev/null
+++ b/src/proguard/classfile/attribute/SignatureAttribute.java
@@ -0,0 +1,100 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This Attribute represents a signature attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class SignatureAttribute extends Attribute
+{
+ public int u2signatureIndex;
+
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * signature string. This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+
+ /**
+ * Creates an uninitialized SignatureAttribute.
+ */
+ public SignatureAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized SignatureAttribute.
+ */
+ public SignatureAttribute(int u2attributeNameIndex,
+ int u2signatureIndex)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2signatureIndex = u2signatureIndex;
+ }
+
+
+ /**
+ * Lets the Clazz objects referenced in the signature string accept the
+ * given visitor.
+ */
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ if (referencedClasses[index] != null)
+ {
+ referencedClasses[index].accept(classVisitor);
+ }
+ }
+ }
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSignatureAttribute(clazz, this);
+ }
+
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSignatureAttribute(clazz, field, this);
+ }
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSignatureAttribute(clazz, method, this);
+ }
+ }
diff --git a/src/proguard/classfile/attribute/SourceDirAttribute.java b/src/proguard/classfile/attribute/SourceDirAttribute.java
new file mode 100644
index 000000000..faa1c79b2
--- /dev/null
+++ b/src/proguard/classfile/attribute/SourceDirAttribute.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a source directory attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class SourceDirAttribute extends Attribute
+{
+ public int u2sourceDirIndex;
+
+
+ /**
+ * Creates an uninitialized SourceDirAttribute.
+ */
+ public SourceDirAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized SourceDirAttribute.
+ */
+ public SourceDirAttribute(int u2attributeNameIndex,
+ int u2sourceDirIndex)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2sourceDirIndex = u2sourceDirIndex;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSourceDirAttribute(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/SourceFileAttribute.java b/src/proguard/classfile/attribute/SourceFileAttribute.java
new file mode 100644
index 000000000..4abac170f
--- /dev/null
+++ b/src/proguard/classfile/attribute/SourceFileAttribute.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a source file attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class SourceFileAttribute extends Attribute
+{
+ public int u2sourceFileIndex;
+
+
+ /**
+ * Creates an uninitialized SourceFileAttribute.
+ */
+ public SourceFileAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized SourceFileAttribute.
+ */
+ public SourceFileAttribute(int u2attributeNameIndex,
+ int u2sourceFileIndex)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2sourceFileIndex = u2sourceFileIndex;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSourceFileAttribute(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/SyntheticAttribute.java b/src/proguard/classfile/attribute/SyntheticAttribute.java
new file mode 100644
index 000000000..013533036
--- /dev/null
+++ b/src/proguard/classfile/attribute/SyntheticAttribute.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a synthetic attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class SyntheticAttribute extends Attribute
+{
+ /**
+ * Creates an uninitialized SyntheticAttribute.
+ */
+ public SyntheticAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized SyntheticAttribute.
+ */
+ public SyntheticAttribute(int u2attributeNameIndex)
+ {
+ super(u2attributeNameIndex);
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSyntheticAttribute(clazz, this);
+ }
+
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSyntheticAttribute(clazz, field, this);
+ }
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitSyntheticAttribute(clazz, method, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/UnknownAttribute.java b/src/proguard/classfile/attribute/UnknownAttribute.java
new file mode 100644
index 000000000..182a9e85c
--- /dev/null
+++ b/src/proguard/classfile/attribute/UnknownAttribute.java
@@ -0,0 +1,82 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute;
+
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents an unknown attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class UnknownAttribute extends Attribute
+{
+ public final int u4attributeLength;
+ public byte[] info;
+
+
+ /**
+ * Creates an uninitialized UnknownAttribute with the given length.
+ */
+ public UnknownAttribute(int attributeLength)
+ {
+ u4attributeLength = attributeLength;
+ }
+
+
+ /**
+ * Creates an initialized UnknownAttribute.
+ */
+ public UnknownAttribute(int u2attributeNameIndex,
+ int u4attributeLength,
+ byte[] info)
+ {
+ super(u2attributeNameIndex);
+
+ this.u4attributeLength = u4attributeLength;
+ this.info = info;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitUnknownAttribute(clazz, this);
+ }
+
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitUnknownAttribute(clazz, this);
+ }
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitUnknownAttribute(clazz, this);
+ }
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitUnknownAttribute(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/Annotation.java b/src/proguard/classfile/attribute/annotation/Annotation.java
new file mode 100644
index 000000000..b2f18d5ac
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/Annotation.java
@@ -0,0 +1,143 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * Representation of an annotation.
+ *
+ * @author Eric Lafortune
+ */
+public class Annotation implements VisitorAccepter
+{
+ public int u2typeIndex;
+ public int u2elementValuesCount;
+ public ElementValue[] elementValues;
+
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * type string. This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized Annotation.
+ */
+ public Annotation()
+ {
+ }
+
+
+ /**
+ * Creates an initialized Annotation.
+ */
+ public Annotation(int u2typeIndex,
+ int u2elementValuesCount,
+ ElementValue[] elementValues)
+ {
+ this.u2typeIndex = u2typeIndex;
+ this.u2elementValuesCount = u2elementValuesCount;
+ this.elementValues = elementValues;
+ }
+
+
+ /**
+ * Returns the type.
+ */
+ public String getType(Clazz clazz)
+ {
+ return clazz.getString(u2typeIndex);
+ }
+
+
+
+ /**
+ * Applies the given visitor to the first referenced class. This is the
+ * main annotation class.
+ */
+ public void referencedClassAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ Clazz referencedClass = referencedClasses[0];
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+ }
+
+
+ /**
+ * Applies the given visitor to all referenced classes.
+ */
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ Clazz referencedClass = referencedClasses[index];
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Applies the given visitor to all element value pairs.
+ */
+ public void elementValuesAccept(Clazz clazz, ElementValueVisitor elementValueVisitor)
+ {
+ for (int index = 0; index < u2elementValuesCount; index++)
+ {
+ elementValues[index].accept(clazz, this, elementValueVisitor);
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/AnnotationDefaultAttribute.java b/src/proguard/classfile/attribute/annotation/AnnotationDefaultAttribute.java
new file mode 100644
index 000000000..b8f29cc1b
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/AnnotationDefaultAttribute.java
@@ -0,0 +1,73 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents an annotation default attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class AnnotationDefaultAttribute extends Attribute
+{
+ public ElementValue defaultValue;
+
+
+ /**
+ * Creates an uninitialized AnnotationDefaultAttribute.
+ */
+ public AnnotationDefaultAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized AnnotationDefaultAttribute.
+ */
+ public AnnotationDefaultAttribute(int u2attributeNameIndex,
+ ElementValue defaultValue)
+ {
+ super(u2attributeNameIndex);
+
+ this.defaultValue = defaultValue;
+ }
+
+
+ /**
+ * Applies the given visitor to the default element value.
+ */
+ public void defaultValueAccept(Clazz clazz, ElementValueVisitor elementValueVisitor)
+ {
+ defaultValue.accept(clazz, null, elementValueVisitor);
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitAnnotationDefaultAttribute(clazz, method, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/AnnotationElementValue.java b/src/proguard/classfile/attribute/annotation/AnnotationElementValue.java
new file mode 100644
index 000000000..8354f5dc9
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/AnnotationElementValue.java
@@ -0,0 +1,76 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+
+/**
+ * This ElementValue represents an annotation element value.
+ *
+ * @author Eric Lafortune
+ */
+public class AnnotationElementValue extends ElementValue
+{
+ public Annotation annotationValue;
+
+
+ /**
+ * Creates an uninitialized AnnotationElementValue.
+ */
+ public AnnotationElementValue()
+ {
+ }
+
+
+ /**
+ * Creates an initialized AnnotationElementValue.
+ */
+ public AnnotationElementValue(int u2elementNameIndex,
+ Annotation annotationValue)
+ {
+ super(u2elementNameIndex);
+
+ this.annotationValue = annotationValue;
+ }
+
+
+ /**
+ * Applies the given visitor to the annotation.
+ */
+ public void annotationAccept(Clazz clazz, AnnotationVisitor annotationVisitor)
+ {
+ annotationVisitor.visitAnnotation(clazz, annotationValue);
+ }
+
+
+ // Implementations for ElementValue.
+
+ public char getTag()
+ {
+ return ClassConstants.ELEMENT_VALUE_ANNOTATION;
+ }
+
+ public void accept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor)
+ {
+ elementValueVisitor.visitAnnotationElementValue(clazz, annotation, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/AnnotationsAttribute.java b/src/proguard/classfile/attribute/annotation/AnnotationsAttribute.java
new file mode 100644
index 000000000..a936ff462
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/AnnotationsAttribute.java
@@ -0,0 +1,100 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.annotation.visitor.AnnotationVisitor;
+
+/**
+ * This Attribute represents an annotations attribute.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class AnnotationsAttribute extends Attribute
+{
+ public int u2annotationsCount;
+ public Annotation[] annotations;
+
+
+ /**
+ * Creates an uninitialized AnnotationsAttribute.
+ */
+ protected AnnotationsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized AnnotationsAttribute.
+ */
+ protected AnnotationsAttribute(int u2attributeNameIndex,
+ int u2annotationsCount,
+ Annotation[] annotations)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2annotationsCount = u2annotationsCount;
+ this.annotations = annotations;
+ }
+
+
+ /**
+ * Applies the given visitor to all class annotations.
+ */
+ public void annotationsAccept(Clazz clazz, AnnotationVisitor annotationVisitor)
+ {
+ for (int index = 0; index < u2annotationsCount; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of Annotation.
+ annotationVisitor.visitAnnotation(clazz, annotations[index]);
+ }
+ }
+
+
+ /**
+ * Applies the given visitor to all field annotations.
+ */
+ public void annotationsAccept(Clazz clazz, Field field, AnnotationVisitor annotationVisitor)
+ {
+ for (int index = 0; index < u2annotationsCount; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of Annotation.
+ annotationVisitor.visitAnnotation(clazz, field, annotations[index]);
+ }
+ }
+
+
+ /**
+ * Applies the given visitor to all method annotations.
+ */
+ public void annotationsAccept(Clazz clazz, Method method, AnnotationVisitor annotationVisitor)
+ {
+ for (int index = 0; index < u2annotationsCount; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of Annotation.
+ annotationVisitor.visitAnnotation(clazz, method, annotations[index]);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/ArrayElementValue.java b/src/proguard/classfile/attribute/annotation/ArrayElementValue.java
new file mode 100644
index 000000000..0aab49bf9
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/ArrayElementValue.java
@@ -0,0 +1,82 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+
+/**
+ * This ElementValue represents an array element value.
+ *
+ * @author Eric Lafortune
+ */
+public class ArrayElementValue extends ElementValue
+{
+ public int u2elementValuesCount;
+ public ElementValue[] elementValues;
+
+
+ /**
+ * Creates an uninitialized ArrayElementValue.
+ */
+ public ArrayElementValue()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ArrayElementValue.
+ */
+ public ArrayElementValue(int u2elementNameIndex,
+ int u2elementValuesCount,
+ ElementValue[] elementValues)
+ {
+ super(u2elementNameIndex);
+
+ this.u2elementValuesCount = u2elementValuesCount;
+ this.elementValues = elementValues;
+ }
+
+
+ // Implementations for ElementValue.
+
+ public char getTag()
+ {
+ return ClassConstants.ELEMENT_VALUE_ARRAY;
+ }
+
+ public void accept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor)
+ {
+ elementValueVisitor.visitArrayElementValue(clazz, annotation, this);
+ }
+
+
+ /**
+ * Applies the given visitor to all nested element values.
+ */
+ public void elementValuesAccept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor)
+ {
+ for (int index = 0; index < u2elementValuesCount; index++)
+ {
+ elementValues[index].accept(clazz, annotation, elementValueVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/ClassElementValue.java b/src/proguard/classfile/attribute/annotation/ClassElementValue.java
new file mode 100644
index 000000000..ffeaf7141
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/ClassElementValue.java
@@ -0,0 +1,95 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ElementValue represents a class element value.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassElementValue extends ElementValue
+{
+ public int u2classInfoIndex;
+
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * type name string. This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+
+ /**
+ * Creates an uninitialized ClassElementValue.
+ */
+ public ClassElementValue()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ClassElementValue.
+ */
+ public ClassElementValue(int u2elementNameIndex,
+ int u2classInfoIndex)
+ {
+ super(u2elementNameIndex);
+
+ this.u2classInfoIndex = u2classInfoIndex;
+ }
+
+
+ /**
+ * Applies the given visitor to all referenced classes.
+ */
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ Clazz referencedClass = referencedClasses[index];
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+ }
+ }
+
+
+ // Implementations for ElementValue.
+
+ public char getTag()
+ {
+ return ClassConstants.ELEMENT_VALUE_CLASS;
+ }
+
+ public void accept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor)
+ {
+ elementValueVisitor.visitClassElementValue(clazz, annotation, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/ConstantElementValue.java b/src/proguard/classfile/attribute/annotation/ConstantElementValue.java
new file mode 100644
index 000000000..8be432934
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/ConstantElementValue.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+
+/**
+ * This ElementValue represents a constant element value.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantElementValue extends ElementValue
+{
+ public final char u1tag;
+ public int u2constantValueIndex;
+
+
+ /**
+ * Creates an uninitialized ConstantElementValue.
+ */
+ public ConstantElementValue(char u1tag)
+ {
+ this.u1tag = u1tag;
+ }
+
+
+ /**
+ * Creates an initialized ConstantElementValue.
+ */
+ public ConstantElementValue(char u1tag,
+ int u2elementNameIndex,
+ int u2constantValueIndex)
+ {
+ super(u2elementNameIndex);
+
+ this.u1tag = u1tag;
+ this.u2constantValueIndex = u2constantValueIndex;
+ }
+
+
+ // Implementations for ElementValue.
+
+ public char getTag()
+ {
+ return u1tag;
+ }
+
+ public void accept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor)
+ {
+ elementValueVisitor.visitConstantElementValue(clazz, annotation, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/ElementValue.java b/src/proguard/classfile/attribute/annotation/ElementValue.java
new file mode 100644
index 000000000..19a71980a
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/ElementValue.java
@@ -0,0 +1,126 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This abstract class represents an element value that is attached to an
+ * annotation or an annotation default. Specific types of element values are
+ * subclassed from it.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class ElementValue implements VisitorAccepter
+{
+ /**
+ * An extra field for the optional element name. It is used in element value
+ * pairs of annotations. Otherwise, it is 0.
+ */
+ public int u2elementNameIndex;
+
+ /**
+ * An extra field pointing to the referenced Clazz
+ * object, if applicable. This field is typically filled out by the
+ * {@link proguard.classfile.util.ClassReferenceInitializer}
.
+ */
+ public Clazz referencedClass;
+
+ /**
+ * An extra field pointing to the referenced Method
+ * object, if applicable. This field is typically filled out by the
+ * {@link proguard.classfile.util.ClassReferenceInitializer}
.
+ */
+ public Method referencedMethod;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Creates an uninitialized ElementValue.
+ */
+ protected ElementValue()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ElementValue.
+ */
+ protected ElementValue(int u2elementNameIndex)
+ {
+ this.u2elementNameIndex = u2elementNameIndex;
+ }
+
+
+ /**
+ * Returns the element name.
+ */
+ public String getMethodName(Clazz clazz)
+ {
+ return clazz.getString(u2elementNameIndex);
+ }
+
+
+ // Abstract methods to be implemented by extensions.
+
+ /**
+ * Returns the tag of this element value.
+ */
+ public abstract char getTag();
+
+
+ /**
+ * Accepts the given visitor.
+ */
+ public abstract void accept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor);
+
+
+
+ /**
+ * Applies the given visitor to the referenced method.
+ */
+ public void referencedMethodAccept(MemberVisitor memberVisitor)
+ {
+ if (referencedMethod != null)
+ {
+ referencedMethod.accept(referencedClass, memberVisitor);
+ }
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/EnumConstantElementValue.java b/src/proguard/classfile/attribute/annotation/EnumConstantElementValue.java
new file mode 100644
index 000000000..cd0f2f984
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/EnumConstantElementValue.java
@@ -0,0 +1,138 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ElementValue represents an enumeration constant element value.
+ *
+ * @author Eric Lafortune
+ */
+public class EnumConstantElementValue extends ElementValue
+{
+ public int u2typeNameIndex;
+ public int u2constantNameIndex;
+
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * type name string. This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+ /**
+ * An extra field optionally pointing to the referenced enum Field object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ */
+ public Field referencedField;
+
+
+ /**
+ * Creates an uninitialized EnumConstantElementValue.
+ */
+ public EnumConstantElementValue()
+ {
+ }
+
+
+ /**
+ * Creates an initialized EnumConstantElementValue.
+ */
+ public EnumConstantElementValue(int u2elementNameIndex,
+ int u2typeNameIndex,
+ int u2constantNameIndex)
+ {
+ super(u2elementNameIndex);
+
+ this.u2typeNameIndex = u2typeNameIndex;
+ this.u2constantNameIndex = u2constantNameIndex;
+ }
+
+
+ /**
+ * Returns the enumeration type name.
+ */
+ public String getTypeName(Clazz clazz)
+ {
+ return clazz.getString(u2typeNameIndex);
+ }
+
+
+ /**
+ * Returns the constant name.
+ */
+ public String getConstantName(Clazz clazz)
+ {
+ return clazz.getString(u2constantNameIndex);
+ }
+
+
+ /**
+ * Applies the given visitor to all referenced classes.
+ */
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ Clazz referencedClass = referencedClasses[index];
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Applies the given visitor to the referenced field.
+ */
+ public void referencedFieldAccept(MemberVisitor memberVisitor)
+ {
+ if (referencedField != null)
+ {
+ referencedField.accept(referencedClasses[0],
+ memberVisitor);
+ }
+ }
+
+
+ // Implementations for ElementValue.
+
+ public char getTag()
+ {
+ return ClassConstants.ELEMENT_VALUE_ENUM_CONSTANT;
+ }
+
+ public void accept(Clazz clazz, Annotation annotation, ElementValueVisitor elementValueVisitor)
+ {
+ elementValueVisitor.visitEnumConstantElementValue(clazz, annotation, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/ParameterAnnotationsAttribute.java b/src/proguard/classfile/attribute/annotation/ParameterAnnotationsAttribute.java
new file mode 100644
index 000000000..ddaa3a6d1
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/ParameterAnnotationsAttribute.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.annotation.visitor.AnnotationVisitor;
+
+/**
+ * This Attribute represents a runtime parameter annotations attribute.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class ParameterAnnotationsAttribute extends Attribute
+{
+ public int u2parametersCount;
+ public int[] u2parameterAnnotationsCount;
+ public Annotation[][] parameterAnnotations;
+
+
+ /**
+ * Creates an uninitialized ParameterAnnotationsAttribute.
+ */
+ protected ParameterAnnotationsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized ParameterAnnotationsAttribute.
+ */
+ protected ParameterAnnotationsAttribute(int u2attributeNameIndex,
+ int u2parametersCount,
+ int[] u2parameterAnnotationsCount,
+ Annotation[][] parameterAnnotations)
+ {
+ super(u2attributeNameIndex);
+
+ this.u2parametersCount = u2parametersCount;
+ this.u2parameterAnnotationsCount = u2parameterAnnotationsCount;
+ this.parameterAnnotations = parameterAnnotations;
+ }
+
+
+ /**
+ * Applies the given visitor to all annotations.
+ */
+ public void annotationsAccept(Clazz clazz, Method method, AnnotationVisitor annotationVisitor)
+ {
+ // Loop over all parameters.
+ for (int parameterIndex = 0; parameterIndex < u2parametersCount; parameterIndex++)
+ {
+ int annotationsCount = u2parameterAnnotationsCount[parameterIndex];
+ Annotation[] annotations = parameterAnnotations[parameterIndex];
+
+ // Loop over all parameter annotations.
+ for (int index = 0; index < annotationsCount; index++)
+ {
+ // We don't need double dispatching here, since there is only one
+ // type of Annotation.
+ annotationVisitor.visitAnnotation(clazz, method, parameterIndex, annotations[index]);
+ }
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/RuntimeInvisibleAnnotationsAttribute.java b/src/proguard/classfile/attribute/annotation/RuntimeInvisibleAnnotationsAttribute.java
new file mode 100644
index 000000000..deda8a53d
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/RuntimeInvisibleAnnotationsAttribute.java
@@ -0,0 +1,70 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a runtime invisible annotations attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class RuntimeInvisibleAnnotationsAttribute extends AnnotationsAttribute
+{
+ /**
+ * Creates an uninitialized RuntimeInvisibleAnnotationsAttribute.
+ */
+ public RuntimeInvisibleAnnotationsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized RuntimeInvisibleAnnotationsAttribute.
+ */
+ public RuntimeInvisibleAnnotationsAttribute(int u2attributeNameIndex,
+ int u2annotationsCount,
+ Annotation[] annotations)
+ {
+ super(u2attributeNameIndex, u2annotationsCount, annotations);
+ }
+
+
+// Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeInvisibleAnnotationsAttribute(clazz, this);
+ }
+
+
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeInvisibleAnnotationsAttribute(clazz, field, this);
+ }
+
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeInvisibleAnnotationsAttribute(clazz, method, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/RuntimeInvisibleParameterAnnotationsAttribute.java b/src/proguard/classfile/attribute/annotation/RuntimeInvisibleParameterAnnotationsAttribute.java
new file mode 100644
index 000000000..2fcae8848
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/RuntimeInvisibleParameterAnnotationsAttribute.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a runtime invisible parameter annotations attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class RuntimeInvisibleParameterAnnotationsAttribute extends ParameterAnnotationsAttribute
+{
+ /**
+ * Creates an uninitialized RuntimeInvisibleParameterAnnotationsAttribute.
+ */
+ public RuntimeInvisibleParameterAnnotationsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized RuntimeInvisibleParameterAnnotationsAttribute.
+ */
+ public RuntimeInvisibleParameterAnnotationsAttribute(int u2attributeNameIndex,
+ int u2parametersCount,
+ int[] u2parameterAnnotationsCount,
+ Annotation[][] parameterAnnotations)
+ {
+ super(u2attributeNameIndex,
+ u2parametersCount,
+ u2parameterAnnotationsCount,
+ parameterAnnotations);
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeInvisibleParameterAnnotationsAttribute(clazz, method, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/RuntimeVisibleAnnotationsAttribute.java b/src/proguard/classfile/attribute/annotation/RuntimeVisibleAnnotationsAttribute.java
new file mode 100644
index 000000000..da94f0c87
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/RuntimeVisibleAnnotationsAttribute.java
@@ -0,0 +1,70 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a runtime visible annotations attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class RuntimeVisibleAnnotationsAttribute extends AnnotationsAttribute
+{
+ /**
+ * Creates an uninitialized RuntimeVisibleAnnotationsAttribute.
+ */
+ public RuntimeVisibleAnnotationsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized RuntimeVisibleAnnotationsAttribute.
+ */
+ public RuntimeVisibleAnnotationsAttribute(int u2attributeNameIndex,
+ int u2annotationsCount,
+ Annotation[] annotations)
+ {
+ super(u2attributeNameIndex, u2annotationsCount, annotations);
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeVisibleAnnotationsAttribute(clazz, this);
+ }
+
+
+ public void accept(Clazz clazz, Field field, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeVisibleAnnotationsAttribute(clazz, field, this);
+ }
+
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeVisibleAnnotationsAttribute(clazz, method, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/RuntimeVisibleParameterAnnotationsAttribute.java b/src/proguard/classfile/attribute/annotation/RuntimeVisibleParameterAnnotationsAttribute.java
new file mode 100644
index 000000000..caa683057
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/RuntimeVisibleParameterAnnotationsAttribute.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a runtime visible parameter annotations attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class RuntimeVisibleParameterAnnotationsAttribute extends ParameterAnnotationsAttribute
+{
+ /**
+ * Creates an uninitialized RuntimeVisibleParameterAnnotationsAttribute.
+ */
+ public RuntimeVisibleParameterAnnotationsAttribute()
+ {
+ }
+
+
+ /**
+ * Creates an initialized RuntimeVisibleParameterAnnotationsAttribute.
+ */
+ public RuntimeVisibleParameterAnnotationsAttribute(int u2attributeNameIndex,
+ int u2parametersCount,
+ int[] u2parameterAnnotationsCount,
+ Annotation[][] parameterAnnotations)
+ {
+ super(u2attributeNameIndex,
+ u2parametersCount,
+ u2parameterAnnotationsCount,
+ parameterAnnotations);
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitRuntimeVisibleParameterAnnotationsAttribute(clazz, method, this);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/package.html b/src/proguard/classfile/attribute/annotation/package.html
new file mode 100644
index 000000000..6aacff3e2
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/package.html
@@ -0,0 +1,4 @@
+
+This package contains classes to represent the annotation attributes inside
+class files.
+
diff --git a/src/proguard/classfile/attribute/annotation/visitor/AllAnnotationVisitor.java b/src/proguard/classfile/attribute/annotation/visitor/AllAnnotationVisitor.java
new file mode 100644
index 000000000..0aadfe3ff
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/AllAnnotationVisitor.java
@@ -0,0 +1,105 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor lets a given AnnotationVisitor visit all Annotation
+ * objects of the attributes it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllAnnotationVisitor
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final AnnotationVisitor annotationVisitor;
+
+
+ /**
+ * Creates a new AllAnnotationVisitor.
+ * @param annotationVisitor the AnnotationVisitor to which visits will be
+ * delegated.
+ */
+ public AllAnnotationVisitor(AnnotationVisitor annotationVisitor)
+ {
+ this.annotationVisitor = annotationVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, annotationVisitor);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, field, annotationVisitor);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, method, annotationVisitor);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, annotationVisitor);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, field, annotationVisitor);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, method, annotationVisitor);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, annotationVisitor);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/visitor/AllElementValueVisitor.java b/src/proguard/classfile/attribute/annotation/visitor/AllElementValueVisitor.java
new file mode 100644
index 000000000..b728b8b5b
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/AllElementValueVisitor.java
@@ -0,0 +1,201 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.util.*;
+
+/**
+ * This AttributeVisitor and AnnotationVisitor lets a given ElementValueVisitor
+ * visit all ElementValue objects of the attributes or annotations that it
+ * visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllElementValueVisitor
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ private final boolean deep;
+ private final ElementValueVisitor elementValueVisitor;
+
+
+ /**
+ * Creates a new AllElementValueVisitor.
+ * @param elementValueVisitor the AllElementValueVisitor to which visits
+ * will be delegated.
+ */
+ public AllElementValueVisitor(ElementValueVisitor elementValueVisitor)
+ {
+ this(false, elementValueVisitor);
+ }
+
+
+ /**
+ * Creates a new AllElementValueVisitor.
+ * @param deep specifies whether the element values
+ * further down the hierarchy should be
+ * visited too.
+ * @param elementValueVisitor the AllElementValueVisitor to which visits
+ * will be delegated.
+ */
+ public AllElementValueVisitor(boolean deep,
+ ElementValueVisitor elementValueVisitor)
+ {
+ this.deep = deep;
+ this.elementValueVisitor = elementValueVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, field, this);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, field, this);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ // Visit the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ // Visit the default element value.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ public void visitAnnotation(Clazz clazz, Field field, Annotation annotation)
+ {
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ public void visitAnnotation(Clazz clazz, Method method, Annotation annotation)
+ {
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ public void visitAnnotation(Clazz clazz, Method method, int parameterIndex, Annotation annotation)
+ {
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ elementValueVisitor.visitConstantElementValue(clazz, annotation, constantElementValue);
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ elementValueVisitor.visitEnumConstantElementValue(clazz, annotation, enumConstantElementValue);
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ elementValueVisitor.visitClassElementValue(clazz, annotation, classElementValue);
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ elementValueVisitor.visitAnnotationElementValue(clazz, annotation, annotationElementValue);
+
+ if (deep)
+ {
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ elementValueVisitor.visitArrayElementValue(clazz, annotation, arrayElementValue);
+
+ if (deep)
+ {
+ arrayElementValue.elementValuesAccept(clazz, annotation, elementValueVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/visitor/AnnotatedClassVisitor.java b/src/proguard/classfile/attribute/annotation/visitor/AnnotatedClassVisitor.java
new file mode 100644
index 000000000..305928eb7
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/AnnotatedClassVisitor.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.annotation.Annotation;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+
+/**
+ * This AnnotationVisitor delegates all visits to a given ClassVisitor.
+ * The latter visits the class of each visited annotation, although
+ * never twice in a row.
+ *
+ * @author Eric Lafortune
+ */
+public class AnnotatedClassVisitor
+extends SimplifiedVisitor
+implements AnnotationVisitor
+{
+ private final ClassVisitor classVisitor;
+
+ private Clazz lastVisitedClass;
+
+
+ public AnnotatedClassVisitor(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ if (!clazz.equals(lastVisitedClass))
+ {
+ clazz.accept(classVisitor);
+
+ lastVisitedClass = clazz;
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/visitor/AnnotationToMemberVisitor.java b/src/proguard/classfile/attribute/annotation/visitor/AnnotationToMemberVisitor.java
new file mode 100644
index 000000000..7833f7e42
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/AnnotationToMemberVisitor.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.Annotation;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+
+
+/**
+ * This AnnotationVisitor delegates all visits to a given MemberVisitor.
+ * The latter visits the class member of each visited class member annotation
+ * or method parameter annotation, although never twice in a row.
+ *
+ * @author Eric Lafortune
+ */
+public class AnnotationToMemberVisitor
+extends SimplifiedVisitor
+implements AnnotationVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+ private Member lastVisitedMember;
+
+
+ public AnnotationToMemberVisitor(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Member member, Annotation annotation)
+ {
+ if (!member.equals(lastVisitedMember))
+ {
+ member.accept(clazz, memberVisitor);
+
+ lastVisitedMember = member;
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/visitor/AnnotationTypeFilter.java b/src/proguard/classfile/attribute/annotation/visitor/AnnotationTypeFilter.java
new file mode 100644
index 000000000..d6ec3cad7
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/AnnotationTypeFilter.java
@@ -0,0 +1,101 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.Annotation;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.util.*;
+
+/**
+ * This AnnotationVisitor
delegates its visits to another given
+ * AnnotationVisitor
, but only when the visited annotation has
+ * a type that matches a given regular expression.
+ *
+ * @author Eric Lafortune
+ */
+public class AnnotationTypeFilter
+implements AnnotationVisitor
+{
+ private final StringMatcher regularExpressionMatcher;
+ private final AnnotationVisitor annotationVisitor;
+
+
+ /**
+ * Creates a new ClassNameFilter.
+ * @param regularExpression the regular expression against which annotation
+ * type names will be matched.
+ * @param annotationVisitor the annotationVisitor
to which
+ * visits will be delegated.
+ */
+ public AnnotationTypeFilter(String regularExpression,
+ AnnotationVisitor annotationVisitor)
+ {
+ this.regularExpressionMatcher = new ListParser(new ClassNameParser()).parse(regularExpression);
+ this.annotationVisitor = annotationVisitor;
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ if (accepted(annotation.getType(clazz)))
+ {
+ annotationVisitor.visitAnnotation(clazz, annotation);
+ }
+ }
+
+
+ public void visitAnnotation(Clazz clazz, Field field, Annotation annotation)
+ {
+ if (accepted(annotation.getType(clazz)))
+ {
+ annotationVisitor.visitAnnotation(clazz, field, annotation);
+ }
+ }
+
+
+ public void visitAnnotation(Clazz clazz, Method method, Annotation annotation)
+ {
+ if (accepted(annotation.getType(clazz)))
+ {
+ annotationVisitor.visitAnnotation(clazz, method, annotation);
+ }
+ }
+
+
+ public void visitAnnotation(Clazz clazz, Method method, int parameterIndex, Annotation annotation)
+ {
+ if (accepted(annotation.getType(clazz)))
+ {
+ annotationVisitor.visitAnnotation(clazz, method, parameterIndex, annotation);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(String name)
+ {
+ return regularExpressionMatcher.matches(name);
+ }
+}
diff --git a/src/proguard/classfile/attribute/annotation/visitor/AnnotationVisitor.java b/src/proguard/classfile/attribute/annotation/visitor/AnnotationVisitor.java
new file mode 100644
index 000000000..8d207afb5
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/AnnotationVisitor.java
@@ -0,0 +1,40 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.Annotation;
+
+/**
+ * This interface specifies the methods for a visitor of
+ * Annotation
objects. Note that there is only a single
+ * implementation of Annotation
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface AnnotationVisitor
+{
+ public void visitAnnotation(Clazz clazz, Annotation annotation);
+ public void visitAnnotation(Clazz clazz, Field field, Annotation annotation);
+ public void visitAnnotation(Clazz clazz, Method method, Annotation annotation);
+ public void visitAnnotation(Clazz clazz, Method method, int parameterIndex, Annotation annotation);
+}
diff --git a/src/proguard/classfile/attribute/annotation/visitor/ElementValueVisitor.java b/src/proguard/classfile/attribute/annotation/visitor/ElementValueVisitor.java
new file mode 100644
index 000000000..2d3a20dc1
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/ElementValueVisitor.java
@@ -0,0 +1,51 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.annotation.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.annotation.*;
+
+/**
+ * This interface specifies the methods for a visitor of ElementValue
+ * objects.
+ *
+ * @author Eric Lafortune
+ */
+public interface ElementValueVisitor
+{
+ public void visitConstantElementValue( Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue);
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue);
+ public void visitClassElementValue( Clazz clazz, Annotation annotation, ClassElementValue classElementValue);
+ public void visitAnnotationElementValue( Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue);
+ public void visitArrayElementValue( Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue);
+
+// public void visitConstantElementValue( Clazz clazz, Field field, Annotation annotation, ConstantElementValue constantElementValue);
+// public void visitEnumConstantElementValue(Clazz clazz, Field field, Annotation annotation, EnumConstantElementValue enumConstantElementValue);
+// public void visitClassElementValue( Clazz clazz, Field field, Annotation annotation, ClassElementValue classElementValue);
+// public void visitAnnotationElementValue( Clazz clazz, Field field, Annotation annotation, AnnotationElementValue annotationElementValue);
+// public void visitArrayElementValue( Clazz clazz, Field field, Annotation annotation, ArrayElementValue arrayElementValue);
+//
+// public void visitConstantElementValue( Clazz clazz, Method method, Annotation annotation, ConstantElementValue constantElementValue);
+// public void visitEnumConstantElementValue(Clazz clazz, Method method, Annotation annotation, EnumConstantElementValue enumConstantElementValue);
+// public void visitClassElementValue( Clazz clazz, Method method, Annotation annotation, ClassElementValue classElementValue);
+// public void visitAnnotationElementValue( Clazz clazz, Method method, Annotation annotation, AnnotationElementValue annotationElementValue);
+// public void visitArrayElementValue( Clazz clazz, Method method, Annotation annotation, ArrayElementValue arrayElementValue);
+}
diff --git a/src/proguard/classfile/attribute/annotation/visitor/package.html b/src/proguard/classfile/attribute/annotation/visitor/package.html
new file mode 100644
index 000000000..10d064850
--- /dev/null
+++ b/src/proguard/classfile/attribute/annotation/visitor/package.html
@@ -0,0 +1,3 @@
+
+This package contains visitors for annotation attributes and their components.
+
diff --git a/src/proguard/classfile/attribute/package.html b/src/proguard/classfile/attribute/package.html
new file mode 100644
index 000000000..d17caaafd
--- /dev/null
+++ b/src/proguard/classfile/attribute/package.html
@@ -0,0 +1,3 @@
+
+This package contains classes to represent the attributes inside class files.
+
diff --git a/src/proguard/classfile/attribute/preverification/DoubleType.java b/src/proguard/classfile/attribute/preverification/DoubleType.java
new file mode 100644
index 000000000..1bc3e5d0a
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/DoubleType.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a Double type.
+ *
+ * @author Eric Lafortune
+ */
+public class DoubleType extends VerificationType
+{
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return DOUBLE_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitDoubleType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackDoubleType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesDoubleType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "d";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/FloatType.java b/src/proguard/classfile/attribute/preverification/FloatType.java
new file mode 100644
index 000000000..c58cd0a81
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/FloatType.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a Float type.
+ *
+ * @author Eric Lafortune
+ */
+public class FloatType extends VerificationType
+{
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return FLOAT_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitFloatType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackFloatType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesFloatType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "f";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/FullFrame.java b/src/proguard/classfile/attribute/preverification/FullFrame.java
new file mode 100644
index 000000000..4f0d72e47
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/FullFrame.java
@@ -0,0 +1,202 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.*;
+
+/**
+ * This StackMapFrame represents a "full frame".
+ *
+ * @author Eric Lafortune
+ */
+public class FullFrame extends StackMapFrame
+{
+ public int variablesCount;
+ public VerificationType[] variables;
+ public int stackCount;
+ public VerificationType[] stack;
+
+
+ /**
+ * Creates an uninitialized FullFrame.
+ */
+ public FullFrame()
+ {
+ }
+
+
+ /**
+ * Creates a FullFrame with the given variables and stack.
+ */
+ public FullFrame(int offsetDelta,
+ VerificationType[] variables,
+ VerificationType[] stack)
+ {
+ this(offsetDelta,
+ variables.length,
+ variables,
+ stack.length,
+ stack);
+ }
+
+
+ /**
+ * Creates a FullFrame with the given variables and stack.
+ */
+ public FullFrame(int offsetDelta,
+ int variablesCount,
+ VerificationType[] variables,
+ int stackCount,
+ VerificationType[] stack)
+ {
+ this.u2offsetDelta = offsetDelta;
+ this.variablesCount = variablesCount;
+ this.variables = variables;
+ this.stackCount = stackCount;
+ this.stack = stack;
+ }
+
+
+ /**
+ * Applies the given verification type visitor to all variables.
+ */
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ for (int index = 0; index < variablesCount; index++)
+ {
+ variables[index].variablesAccept(clazz, method, codeAttribute, offset, index, verificationTypeVisitor);
+ }
+ }
+
+
+ /**
+ * Applies the given verification type visitor to all stack.
+ */
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ for (int index = 0; index < stackCount; index++)
+ {
+ stack[index].stackAccept(clazz, method, codeAttribute, offset, index, verificationTypeVisitor);
+ }
+ }
+
+
+ // Implementations for StackMapFrame.
+
+ public int getTag()
+ {
+ return FULL_FRAME;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrameVisitor stackMapFrameVisitor)
+ {
+ stackMapFrameVisitor.visitFullFrame(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (!super.equals(object))
+ {
+ return false;
+ }
+
+ FullFrame other = (FullFrame)object;
+
+ if (this.u2offsetDelta != other.u2offsetDelta ||
+ this.variablesCount != other.variablesCount ||
+ this.stackCount != other.stackCount)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < variablesCount; index++)
+ {
+ VerificationType thisType = this.variables[index];
+ VerificationType otherType = other.variables[index];
+
+ if (!thisType.equals(otherType))
+ {
+ return false;
+ }
+ }
+
+ for (int index = 0; index < stackCount; index++)
+ {
+ VerificationType thisType = this.stack[index];
+ VerificationType otherType = other.stack[index];
+
+ if (!thisType.equals(otherType))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ public int hashCode()
+ {
+ int hashCode = super.hashCode();
+
+ for (int index = 0; index < variablesCount; index++)
+ {
+ hashCode ^= variables[index].hashCode();
+ }
+
+ for (int index = 0; index < stackCount; index++)
+ {
+ hashCode ^= stack[index].hashCode();
+ }
+
+ return hashCode;
+ }
+
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer(super.toString()).append("Var: ");
+
+ for (int index = 0; index < variablesCount; index++)
+ {
+ buffer = buffer.append('[')
+ .append(variables[index].toString())
+ .append(']');
+ }
+
+ buffer.append(", Stack: ");
+
+ for (int index = 0; index < stackCount; index++)
+ {
+ buffer = buffer.append('[')
+ .append(stack[index].toString())
+ .append(']');
+ }
+
+ return buffer.toString();
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/IntegerType.java b/src/proguard/classfile/attribute/preverification/IntegerType.java
new file mode 100644
index 000000000..9c43cae1c
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/IntegerType.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a Integer type.
+ *
+ * @author Eric Lafortune
+ */
+public class IntegerType extends VerificationType
+{
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return INTEGER_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitIntegerType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackIntegerType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesIntegerType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "i";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/LessZeroFrame.java b/src/proguard/classfile/attribute/preverification/LessZeroFrame.java
new file mode 100644
index 000000000..f722d73c5
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/LessZeroFrame.java
@@ -0,0 +1,103 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.StackMapFrameVisitor;
+
+/**
+ * This StackMapFrame represents an "chop frame".
+ *
+ * @author Eric Lafortune
+ */
+public class LessZeroFrame extends StackMapFrame
+{
+ public int choppedVariablesCount;
+
+
+ /**
+ * Creates an uninitialized LessZeroFrame.
+ */
+ public LessZeroFrame()
+ {
+ }
+
+
+ /**
+ * Creates a LessZeroFrame with the given tag.
+ */
+ public LessZeroFrame(int tag)
+ {
+ choppedVariablesCount = LESS_ZERO_FRAME + 3 - tag;
+ }
+
+
+ /**
+ * Creates a LessZeroFrame with the given number of chopped variables.
+ */
+ public LessZeroFrame(byte choppedVariablesCount)
+ {
+ this.choppedVariablesCount = (int)choppedVariablesCount;
+ }
+
+
+ // Implementations for StackMapFrame.
+
+ public int getTag()
+ {
+ return LESS_ZERO_FRAME + 3 - choppedVariablesCount;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrameVisitor stackMapFrameVisitor)
+ {
+ stackMapFrameVisitor.visitLessZeroFrame(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (!super.equals(object))
+ {
+ return false;
+ }
+
+ LessZeroFrame other = (LessZeroFrame)object;
+
+ return this.u2offsetDelta == other.u2offsetDelta &&
+ this.choppedVariablesCount != other.choppedVariablesCount;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^ choppedVariablesCount;
+ }
+
+
+ public String toString()
+ {
+ return super.toString()+"Var: (chopped "+choppedVariablesCount+"), Stack: (empty)";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/LongType.java b/src/proguard/classfile/attribute/preverification/LongType.java
new file mode 100644
index 000000000..c98616571
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/LongType.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a Long type.
+ *
+ * @author Eric Lafortune
+ */
+public class LongType extends VerificationType
+{
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return LONG_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitLongType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackLongType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesLongType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "l";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/MoreZeroFrame.java b/src/proguard/classfile/attribute/preverification/MoreZeroFrame.java
new file mode 100644
index 000000000..be74df0f7
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/MoreZeroFrame.java
@@ -0,0 +1,161 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.*;
+
+/**
+ * This StackMapFrame represents an "append frame".
+ *
+ * @author Eric Lafortune
+ */
+public class MoreZeroFrame extends StackMapFrame
+{
+ public int additionalVariablesCount;
+ public VerificationType[] additionalVariables;
+
+
+ /**
+ * Creates an uninitialized MoreZeroFrame.
+ */
+ public MoreZeroFrame()
+ {
+ }
+
+
+ /**
+ * Creates a MoreZeroFrame with the given tag.
+ */
+ public MoreZeroFrame(int tag)
+ {
+ additionalVariablesCount = tag + 1 - MORE_ZERO_FRAME;
+ }
+
+
+ /**
+ * Creates a MoreZeroFrame with the given additional variables.
+ */
+ public MoreZeroFrame(VerificationType[] additionalVariables)
+ {
+ this(additionalVariables.length, additionalVariables);
+ }
+
+
+ /**
+ * Creates a MoreZeroFrame with the given additional variables.
+ */
+ public MoreZeroFrame(int additionalVariablesCount,
+ VerificationType[] additionalVariables)
+ {
+ this.additionalVariablesCount = additionalVariablesCount;
+ this.additionalVariables = additionalVariables;
+ }
+
+
+ /**
+ * Applies the given verification type visitor to all variables.
+ */
+ public void additionalVariablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ for (int index = 0; index < additionalVariablesCount; index++)
+ {
+ additionalVariables[index].accept(clazz, method, codeAttribute, offset, verificationTypeVisitor);
+ }
+ }
+
+
+ // Implementations for StackMapFrame.
+
+ public int getTag()
+ {
+ return MORE_ZERO_FRAME + additionalVariablesCount - 1;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrameVisitor stackMapFrameVisitor)
+ {
+ stackMapFrameVisitor.visitMoreZeroFrame(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (!super.equals(object))
+ {
+ return false;
+ }
+
+ MoreZeroFrame other = (MoreZeroFrame)object;
+
+ if (this.u2offsetDelta != other.u2offsetDelta ||
+ this.additionalVariablesCount != other.additionalVariablesCount)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < additionalVariablesCount; index++)
+ {
+ VerificationType thisType = this.additionalVariables[index];
+ VerificationType otherType = other.additionalVariables[index];
+
+ if (!thisType.equals(otherType))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ public int hashCode()
+ {
+ int hashCode = super.hashCode();
+
+ for (int index = 0; index < additionalVariablesCount; index++)
+ {
+ hashCode ^= additionalVariables[index].hashCode();
+ }
+
+ return hashCode;
+ }
+
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer(super.toString()).append("Var: ...");
+
+ for (int index = 0; index < additionalVariablesCount; index++)
+ {
+ buffer = buffer.append('[')
+ .append(additionalVariables[index].toString())
+ .append(']');
+ }
+
+ buffer.append(", Stack: (empty)");
+
+ return buffer.toString();
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/NullType.java b/src/proguard/classfile/attribute/preverification/NullType.java
new file mode 100644
index 000000000..fe0d85fb7
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/NullType.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a Null type.
+ *
+ * @author Eric Lafortune
+ */
+public class NullType extends VerificationType
+{
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return NULL_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitNullType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackNullType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesNullType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "n";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/ObjectType.java b/src/proguard/classfile/attribute/preverification/ObjectType.java
new file mode 100644
index 000000000..4ea370a2e
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/ObjectType.java
@@ -0,0 +1,107 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents an Object type.
+ *
+ * @author Eric Lafortune
+ */
+public class ObjectType extends VerificationType
+{
+ public int u2classIndex;
+
+
+
+ /**
+ * Creates an uninitialized ObjectType.
+ */
+ public ObjectType()
+ {
+ }
+
+
+ /**
+ * Creates an ObjectType that points to the given class constant.
+ */
+ public ObjectType(int u2classIndex)
+ {
+ this.u2classIndex = u2classIndex;
+ }
+
+
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return OBJECT_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitObjectType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackObjectType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesObjectType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (!super.equals(object))
+ {
+ return false;
+ }
+
+ ObjectType other = (ObjectType)object;
+
+ return this.u2classIndex == other.u2classIndex;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ u2classIndex;
+ }
+
+
+ public String toString()
+ {
+ return "a:" + u2classIndex;
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/SameOneFrame.java b/src/proguard/classfile/attribute/preverification/SameOneFrame.java
new file mode 100644
index 000000000..4384aaebc
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/SameOneFrame.java
@@ -0,0 +1,115 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.*;
+
+/**
+ * This StackMapFrame represents a "same locals 1 stack item frame" or a
+ * "same locals 1 stack item frame extended".
+ *
+ * @author Eric Lafortune
+ */
+public class SameOneFrame extends StackMapFrame
+{
+ public VerificationType stackItem;
+
+
+ /**
+ * Creates an uninitialized SameOneFrame.
+ */
+ public SameOneFrame()
+ {
+ }
+
+
+ /**
+ * Creates a SameOneFrame with the given tag.
+ */
+ public SameOneFrame(int tag)
+ {
+ u2offsetDelta = tag - SAME_ONE_FRAME;
+ }
+
+
+ /**
+ * Creates a SameOneFrame with the given stack verification type.
+ */
+ public SameOneFrame(VerificationType stackItem)
+ {
+ this.stackItem = stackItem;
+ }
+
+
+ /**
+ * Applies the given verification type visitor to the stack item.
+ */
+ public void stackItemAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ stackItem.accept(clazz, method, codeAttribute, offset, verificationTypeVisitor);
+ }
+
+
+ // Implementations for StackMapFrame.
+
+ public int getTag()
+ {
+ return u2offsetDelta < 64 ?
+ SAME_ONE_FRAME + u2offsetDelta :
+ SAME_ONE_FRAME_EXTENDED;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrameVisitor stackMapFrameVisitor)
+ {
+ stackMapFrameVisitor.visitSameOneFrame(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (!super.equals(object))
+ {
+ return false;
+ }
+
+ SameOneFrame other = (SameOneFrame)object;
+
+ return this.u2offsetDelta == other.u2offsetDelta &&
+ this.stackItem.equals(other.stackItem);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^ stackItem.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return super.toString()+"Var: ..., Stack: ["+stackItem.toString()+"]";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/SameZeroFrame.java b/src/proguard/classfile/attribute/preverification/SameZeroFrame.java
new file mode 100644
index 000000000..a3bd824d0
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/SameZeroFrame.java
@@ -0,0 +1,74 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.StackMapFrameVisitor;
+
+/**
+ * This StackMapFrame represents a "same frame" or a "same frame extended".
+ *
+ * @author Eric Lafortune
+ * @noinspection PointlessArithmeticExpression
+ */
+public class SameZeroFrame extends StackMapFrame
+{
+ /**
+ * Creates an uninitialized SameZeroFrame.
+ */
+ public SameZeroFrame()
+ {
+ }
+
+
+ /**
+ * Creates a SameZeroFrame with the given tag.
+ */
+ public SameZeroFrame(int tag)
+ {
+ u2offsetDelta = tag - SAME_ZERO_FRAME;
+ }
+
+
+ // Implementations for StackMapFrame.
+
+ public int getTag()
+ {
+ return u2offsetDelta < 64 ?
+ SAME_ZERO_FRAME + u2offsetDelta :
+ SAME_ZERO_FRAME_EXTENDED;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrameVisitor stackMapFrameVisitor)
+ {
+ stackMapFrameVisitor.visitSameZeroFrame(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return super.toString()+"Var: ..., Stack: (empty)";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/StackMapAttribute.java b/src/proguard/classfile/attribute/preverification/StackMapAttribute.java
new file mode 100644
index 000000000..51e69fb9a
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/StackMapAttribute.java
@@ -0,0 +1,91 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.preverification.visitor.StackMapFrameVisitor;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents an exceptions attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class StackMapAttribute extends Attribute
+{
+ public int u2stackMapFramesCount;
+ public FullFrame[] stackMapFrames;
+
+
+ /**
+ * Creates an uninitialized ExceptionsAttribute.
+ */
+ public StackMapAttribute()
+ {
+ }
+
+
+ /**
+ * Creates a StackMapTableAttribute with the given stack map frames.
+ */
+ public StackMapAttribute(FullFrame[] stackMapFrames)
+ {
+ this(stackMapFrames.length, stackMapFrames);
+ }
+
+
+ /**
+ * Creates a StackMapTableAttribute with the given stack map frames.
+ */
+ public StackMapAttribute(int stackMapFramesCount,
+ FullFrame[] stackMapFrames)
+ {
+ this.u2stackMapFramesCount = stackMapFramesCount;
+ this.stackMapFrames = stackMapFrames;
+ }
+
+
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitStackMapAttribute(clazz, method, codeAttribute, this);
+ }
+
+
+ /**
+ * Applies the given stack map frame visitor to all stack map frames.
+ */
+ public void stackMapFramesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapFrameVisitor stackMapFrameVisitor)
+ {
+ for (int index = 0; index < u2stackMapFramesCount; index++)
+ {
+ FullFrame stackMapFrame = stackMapFrames[index];
+
+ // We don't need double dispatching here, since there is only one
+ // type of StackMapFrame.
+ stackMapFrameVisitor.visitFullFrame(clazz, method, codeAttribute, stackMapFrame.getOffsetDelta(), stackMapFrame);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/StackMapFrame.java b/src/proguard/classfile/attribute/preverification/StackMapFrame.java
new file mode 100644
index 000000000..01890f307
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/StackMapFrame.java
@@ -0,0 +1,117 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.StackMapFrameVisitor;
+
+/**
+ * This abstract class represents a stack map frame. Specific types
+ * of entries are subclassed from it.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class StackMapFrame implements VisitorAccepter
+{
+ public static final int SAME_ZERO_FRAME = 0;
+ public static final int SAME_ONE_FRAME = 64;
+ public static final int SAME_ONE_FRAME_EXTENDED = 247;
+ public static final int LESS_ZERO_FRAME = 248;
+ public static final int SAME_ZERO_FRAME_EXTENDED = 251;
+ public static final int MORE_ZERO_FRAME = 252;
+ public static final int FULL_FRAME = 255;
+
+
+ public int u2offsetDelta;
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+
+ /**
+ * Returns the bytecode offset delta relative to the previous stack map
+ * frame.
+ */
+ public int getOffsetDelta()
+ {
+ return u2offsetDelta;
+ }
+
+
+ // Abstract methods to be implemented by extensions.
+
+ /**
+ * Returns the stack map frame tag that specifies the entry type.
+ */
+ public abstract int getTag();
+
+
+ /**
+ * Accepts the given visitor.
+ */
+ public abstract void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrameVisitor stackMapFrameVisitor);
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ StackMapFrame other = (StackMapFrame)object;
+
+ return this.u2offsetDelta == other.u2offsetDelta;
+ }
+
+
+ public int hashCode()
+ {
+ return getClass().hashCode() ^
+ u2offsetDelta;
+ }
+
+
+ public String toString()
+ {
+ return "[" + u2offsetDelta + "] ";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/StackMapTableAttribute.java b/src/proguard/classfile/attribute/preverification/StackMapTableAttribute.java
new file mode 100644
index 000000000..3de059f42
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/StackMapTableAttribute.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.preverification.visitor.StackMapFrameVisitor;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+
+/**
+ * This Attribute represents a stack map table attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class StackMapTableAttribute extends Attribute
+{
+ public int u2stackMapFramesCount;
+ public StackMapFrame[] stackMapFrames;
+
+
+ /**
+ * Creates an uninitialized StackMapTableAttribute.
+ */
+ public StackMapTableAttribute()
+ {
+ }
+
+
+ /**
+ * Creates a StackMapTableAttribute with the given stack map frames.
+ */
+ public StackMapTableAttribute(StackMapFrame[] stackMapFrames)
+ {
+ this(stackMapFrames.length, stackMapFrames);
+ }
+
+
+ /**
+ * Creates a StackMapTableAttribute with the given stack map frames.
+ */
+ public StackMapTableAttribute(int stackMapFramesCount,
+ StackMapFrame[] stackMapFrames)
+ {
+ this.u2stackMapFramesCount = stackMapFramesCount;
+ this.stackMapFrames = stackMapFrames;
+ }
+
+
+ // Implementations for Attribute.
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, AttributeVisitor attributeVisitor)
+ {
+ attributeVisitor.visitStackMapTableAttribute(clazz, method, codeAttribute, this);
+ }
+
+
+ /**
+ * Applies the given stack map frame visitor to all stack map frames.
+ */
+ public void stackMapFramesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapFrameVisitor stackMapFrameVisitor)
+ {
+ int offset = 0;
+
+ for (int index = 0; index < u2stackMapFramesCount; index++)
+ {
+ StackMapFrame stackMapFrame = stackMapFrames[index];
+
+ // Note that the byte code offset is computed differently for the
+ // first stack map frame.
+ offset += stackMapFrame.getOffsetDelta() + (index == 0 ? 0 : 1);
+
+ stackMapFrame.accept(clazz, method, codeAttribute, offset, stackMapFrameVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/TopType.java b/src/proguard/classfile/attribute/preverification/TopType.java
new file mode 100644
index 000000000..02dd1a207
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/TopType.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a Top type.
+ *
+ * @author Eric Lafortune
+ */
+public class TopType extends VerificationType
+{
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return TOP_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitTopType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackTopType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesTopType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "T";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/UninitializedThisType.java b/src/proguard/classfile/attribute/preverification/UninitializedThisType.java
new file mode 100644
index 000000000..7b2bfa931
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/UninitializedThisType.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a UninitializedThis type.
+ *
+ * @author Eric Lafortune
+ */
+public class UninitializedThisType extends VerificationType
+{
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return UNINITIALIZED_THIS_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitUninitializedThisType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackUninitializedThisType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesUninitializedThisType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return "u:this";
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/UninitializedType.java b/src/proguard/classfile/attribute/preverification/UninitializedType.java
new file mode 100644
index 000000000..7e4a0fdb0
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/UninitializedType.java
@@ -0,0 +1,106 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This VerificationType represents a Uninitialized type.
+ *
+ * @author Eric Lafortune
+ */
+public class UninitializedType extends VerificationType
+{
+ public int u2newInstructionOffset;
+
+
+ /**
+ * Creates an uninitialized UninitializedType.
+ */
+ public UninitializedType()
+ {
+ }
+
+
+ /**
+ * Creates an UninitializedType pointing to the given 'new' instruction.
+ */
+ public UninitializedType(int u2newInstructionOffset)
+ {
+ this.u2newInstructionOffset = u2newInstructionOffset;
+ }
+
+
+ // Implementations for VerificationType.
+
+ public int getTag()
+ {
+ return UNINITIALIZED_TYPE;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitUninitializedType(clazz, method, codeAttribute, instructionOffset, this);
+ }
+
+
+ public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitStackUninitializedType(clazz, method, codeAttribute, instructionOffset, stackIndex, this);
+ }
+
+
+ public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor)
+ {
+ verificationTypeVisitor.visitVariablesUninitializedType(clazz, method, codeAttribute, instructionOffset, variableIndex, this);
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (!super.equals(object))
+ {
+ return false;
+ }
+
+ UninitializedType other = (UninitializedType)object;
+
+ return this.u2newInstructionOffset == other.u2newInstructionOffset;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ u2newInstructionOffset;
+ }
+
+
+ public String toString()
+ {
+ return "u:" + u2newInstructionOffset;
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/VerificationType.java b/src/proguard/classfile/attribute/preverification/VerificationType.java
new file mode 100644
index 000000000..02c38722f
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/VerificationType.java
@@ -0,0 +1,103 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.visitor.VerificationTypeVisitor;
+
+/**
+ * This abstract class represents a verification type of a local variable or
+ * a stack element. Specific verification types are subclassed from it.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class VerificationType implements VisitorAccepter
+{
+ public static final int TOP_TYPE = 0;
+ public static final int INTEGER_TYPE = 1;
+ public static final int FLOAT_TYPE = 2;
+ public static final int DOUBLE_TYPE = 3;
+ public static final int LONG_TYPE = 4;
+ public static final int NULL_TYPE = 5;
+ public static final int UNINITIALIZED_THIS_TYPE = 6;
+ public static final int OBJECT_TYPE = 7;
+ public static final int UNINITIALIZED_TYPE = 8;
+
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ /**
+ * Returns the tag of the verification type.
+ */
+ public abstract int getTag();
+
+
+ /**
+ * Accepts the given visitor in the context of a method's code, either on
+ * a stack or as a variable.
+ */
+ public abstract void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, VerificationTypeVisitor verificationTypeVisitor);
+
+
+ /**
+ * Accepts the given visitor in the context of a stack in a method's code .
+ */
+ public abstract void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int stackIndex, VerificationTypeVisitor verificationTypeVisitor);
+
+
+ /**
+ * Accepts the given visitor in the context of a variable in a method's code.
+ */
+ public abstract void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int instructionOffset, int variableIndex, VerificationTypeVisitor verificationTypeVisitor);
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/VerificationTypeFactory.java b/src/proguard/classfile/attribute/preverification/VerificationTypeFactory.java
new file mode 100644
index 000000000..ada9ce881
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/VerificationTypeFactory.java
@@ -0,0 +1,112 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification;
+
+/**
+ * This class provides methods to create and reuse IntegerType objects.
+ *
+ * @author Eric Lafortune
+ */
+public class VerificationTypeFactory
+{
+ // Shared copies of Type objects, to avoid creating a lot of objects.
+ static final IntegerType INTEGER_TYPE = new IntegerType();
+ static final LongType LONG_TYPE = new LongType();
+ static final FloatType FLOAT_TYPE = new FloatType();
+ static final DoubleType DOUBLE_TYPE = new DoubleType();
+ static final TopType TOP_TYPE = new TopType();
+ static final NullType NULL_TYPE = new NullType();
+ static final UninitializedThisType UNINITIALIZED_THIS_TYPE = new UninitializedThisType();
+
+
+ /**
+ * Creates a new IntegerType.
+ */
+ public static IntegerType createIntegerType()
+ {
+ return INTEGER_TYPE;
+ }
+
+ /**
+ * Creates a new LongType.
+ */
+ public static LongType createLongType()
+ {
+ return LONG_TYPE;
+ }
+
+ /**
+ * Creates a new FloatType.
+ */
+ public static FloatType createFloatType()
+ {
+ return FLOAT_TYPE;
+ }
+
+ /**
+ * Creates a new DoubleType.
+ */
+ public static DoubleType createDoubleType()
+ {
+ return DOUBLE_TYPE;
+ }
+
+ /**
+ * Creates a new TopType.
+ */
+ public static TopType createTopType()
+ {
+ return TOP_TYPE;
+ }
+
+ /**
+ * Creates a new NullType.
+ */
+ public static NullType createNullType()
+ {
+ return NULL_TYPE;
+ }
+
+ /**
+ * Creates a new UninitializedThisType.
+ */
+ public static UninitializedThisType createUninitializedThisType()
+ {
+ return UNINITIALIZED_THIS_TYPE;
+ }
+
+ /**
+ * Creates a new UninitializedType for an instance that was created at
+ * the given offset.
+ */
+ public static UninitializedType createUninitializedType(int newInstructionOffset)
+ {
+ return new UninitializedType(newInstructionOffset);
+ }
+
+ /**
+ * Creates a new ObjectType of the given type.
+ */
+ public static ObjectType createObjectType(int classIndex)
+ {
+ return new ObjectType(classIndex);
+ }
+}
diff --git a/src/proguard/classfile/attribute/preverification/visitor/StackMapFrameVisitor.java b/src/proguard/classfile/attribute/preverification/visitor/StackMapFrameVisitor.java
new file mode 100644
index 000000000..5e4cf8874
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/visitor/StackMapFrameVisitor.java
@@ -0,0 +1,40 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.*;
+
+/**
+ * This interface specifies the methods for a visitor of
+ * StackMapFrame
objects.
+ *
+ * @author Eric Lafortune
+ */
+public interface StackMapFrameVisitor
+{
+ public void visitSameZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameZeroFrame sameZeroFrame);
+ public void visitSameOneFrame( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame);
+ public void visitLessZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LessZeroFrame lessZeroFrame);
+ public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame);
+ public void visitFullFrame( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame);
+}
diff --git a/src/proguard/classfile/attribute/preverification/visitor/VerificationTypeVisitor.java b/src/proguard/classfile/attribute/preverification/visitor/VerificationTypeVisitor.java
new file mode 100644
index 000000000..2a3e9e70d
--- /dev/null
+++ b/src/proguard/classfile/attribute/preverification/visitor/VerificationTypeVisitor.java
@@ -0,0 +1,65 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.preverification.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.preverification.*;
+
+/**
+ * This interface specifies the methods for a visitor of
+ * VerificationType
objects. There a methods for stack entries
+ * and methods for variable entries.
+ *
+ * @author Eric Lafortune
+ */
+public interface VerificationTypeVisitor
+{
+ public void visitIntegerType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, IntegerType integerType);
+ public void visitFloatType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FloatType floatType);
+ public void visitLongType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LongType longType);
+ public void visitDoubleType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, DoubleType doubleType);
+ public void visitTopType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TopType topType);
+ public void visitObjectType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ObjectType objectType);
+ public void visitNullType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, NullType nullType);
+ public void visitUninitializedType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedType uninitializedType);
+ public void visitUninitializedThisType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedThisType uninitializedThisType);
+
+ public void visitStackIntegerType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, IntegerType integerType);
+ public void visitStackFloatType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, FloatType floatType);
+ public void visitStackLongType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, LongType longType);
+ public void visitStackDoubleType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, DoubleType doubleType);
+ public void visitStackTopType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, TopType topType);
+ public void visitStackObjectType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, ObjectType objectType);
+ public void visitStackNullType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, NullType nullType);
+ public void visitStackUninitializedType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, UninitializedType uninitializedType);
+ public void visitStackUninitializedThisType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, UninitializedThisType uninitializedThisType);
+
+ public void visitVariablesIntegerType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, IntegerType integerType);
+ public void visitVariablesFloatType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, FloatType floatType);
+ public void visitVariablesLongType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, LongType longType);
+ public void visitVariablesDoubleType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, DoubleType doubleType);
+ public void visitVariablesTopType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, TopType topType);
+ public void visitVariablesObjectType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, ObjectType objectType);
+ public void visitVariablesNullType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, NullType nullType);
+ public void visitVariablesUninitializedType( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, UninitializedType uninitializedType);
+ public void visitVariablesUninitializedThisType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, int index, UninitializedThisType uninitializedThisType);
+}
diff --git a/src/proguard/classfile/attribute/visitor/AllAttributeVisitor.java b/src/proguard/classfile/attribute/visitor/AllAttributeVisitor.java
new file mode 100644
index 000000000..9d8801c3e
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/AllAttributeVisitor.java
@@ -0,0 +1,117 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ClassVisitor, MemberVisitor, and AttributeVisitor lets a given
+ * AttributeVisitor visit all Attribute objects of the program classes,
+ * program class members, or code attributes, respectively, that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllAttributeVisitor
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ AttributeVisitor
+{
+ private final boolean deep;
+ private final AttributeVisitor attributeVisitor;
+
+
+ /**
+ * Creates a new shallow AllAttributeVisitor.
+ * @param attributeVisitor the AttributeVisitor to which visits will be
+ * delegated.
+ */
+ public AllAttributeVisitor(AttributeVisitor attributeVisitor)
+ {
+ this(false, attributeVisitor);
+ }
+
+
+ /**
+ * Creates a new optionally deep AllAttributeVisitor.
+ * @param deep specifies whether the attributes contained
+ * further down the class structure should be
+ * visited too.
+ * @param attributeVisitor the AttributeVisitor to which visits will be
+ * delegated.
+ */
+ public AllAttributeVisitor(boolean deep,
+ AttributeVisitor attributeVisitor)
+ {
+ this.deep = deep;
+ this.attributeVisitor = attributeVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.attributesAccept(attributeVisitor);
+
+ // Visit the attributes further down the class structure, if required.
+ if (deep)
+ {
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+ programClass.attributesAccept(this);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ programMember.attributesAccept(programClass, attributeVisitor);
+
+ // Visit the attributes further down the member structure, if required.
+ if (deep)
+ {
+ programMember.attributesAccept(programClass, this);
+ }
+ }
+
+
+ public void visitLibraryMember(LibraryClass programClass, LibraryMember programMember) {}
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttribute.attributesAccept(clazz, method, attributeVisitor);
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/AllBootstrapMethodInfoVisitor.java b/src/proguard/classfile/attribute/visitor/AllBootstrapMethodInfoVisitor.java
new file mode 100644
index 000000000..d70803c33
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/AllBootstrapMethodInfoVisitor.java
@@ -0,0 +1,55 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor lets a given BootstrapMethodInfoVisitor visit all
+ * bootstrap method objects of the BootstrapMethodsAttribute objects it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllBootstrapMethodInfoVisitor
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final BootstrapMethodInfoVisitor bootstrapMethodInfoVisitor;
+
+
+ public AllBootstrapMethodInfoVisitor(BootstrapMethodInfoVisitor bootstrapMethodInfoVisitor)
+ {
+ this.bootstrapMethodInfoVisitor = bootstrapMethodInfoVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ bootstrapMethodsAttribute.bootstrapMethodEntriesAccept(clazz, bootstrapMethodInfoVisitor);
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/AllExceptionInfoVisitor.java b/src/proguard/classfile/attribute/visitor/AllExceptionInfoVisitor.java
new file mode 100644
index 000000000..927bfd962
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/AllExceptionInfoVisitor.java
@@ -0,0 +1,55 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor lets a given ExceptionInfoVisitor visit all exceptions
+ * objects of the CodeAttribute objects it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllExceptionInfoVisitor
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final ExceptionInfoVisitor exceptionInfoVisitor;
+
+
+ public AllExceptionInfoVisitor(ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ this.exceptionInfoVisitor = exceptionInfoVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttribute.exceptionsAccept(clazz, method, exceptionInfoVisitor);
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/AllInnerClassesInfoVisitor.java b/src/proguard/classfile/attribute/visitor/AllInnerClassesInfoVisitor.java
new file mode 100644
index 000000000..242221820
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/AllInnerClassesInfoVisitor.java
@@ -0,0 +1,55 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor lets a given InnerClassesInfoVisitor visit all
+ * InnerClassessInfo objects of the InnerClassesAttribute objects it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllInnerClassesInfoVisitor
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final InnerClassesInfoVisitor innerClassesInfoVisitor;
+
+
+ public AllInnerClassesInfoVisitor(InnerClassesInfoVisitor innerClassesInfoVisitor)
+ {
+ this.innerClassesInfoVisitor = innerClassesInfoVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ innerClassesAttribute.innerClassEntriesAccept(clazz, innerClassesInfoVisitor);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/attribute/visitor/AttributeNameFilter.java b/src/proguard/classfile/attribute/visitor/AttributeNameFilter.java
new file mode 100644
index 000000000..0db77d559
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/AttributeNameFilter.java
@@ -0,0 +1,386 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.util.*;
+
+import java.util.List;
+
+/**
+ * This AttributeVisitor delegates its visits another AttributeVisitor, but
+ * only when the visited attribute has a name that that matches a given regular
+ * expression.
+ *
+ * @author Eric Lafortune
+ */
+public class AttributeNameFilter
+implements AttributeVisitor
+{
+ private final StringMatcher regularExpressionMatcher;
+ private final AttributeVisitor attributeVisitor;
+
+
+ /**
+ * Creates a new AttributeNameFilter.
+ * @param regularExpression the regular expression against which attribute
+ * names will be matched.
+ * @param attributeVisitor the AttributeVisitor
to which
+ * visits will be delegated.
+ */
+ public AttributeNameFilter(String regularExpression,
+ AttributeVisitor attributeVisitor)
+ {
+ this(new ListParser(new NameParser()).parse(regularExpression),
+ attributeVisitor);
+ }
+
+
+ /**
+ * Creates a new AttributeNameFilter.
+ * @param regularExpression the regular expression against which attribute
+ * names will be matched.
+ * @param attributeVisitor the AttributeVisitor
to which
+ * visits will be delegated.
+ */
+ public AttributeNameFilter(List regularExpression,
+ AttributeVisitor attributeVisitor)
+ {
+ this(new ListParser(new NameParser()).parse(regularExpression),
+ attributeVisitor);
+ }
+
+
+ /**
+ * Creates a new AttributeNameFilter.
+ * @param regularExpressionMatcher the string matcher against which
+ * attribute names will be matched.
+ * @param attributeVisitor the AttributeVisitor
to
+ * which visits will be delegated.
+ */
+ public AttributeNameFilter(StringMatcher regularExpressionMatcher,
+ AttributeVisitor attributeVisitor)
+ {
+ this.regularExpressionMatcher = regularExpressionMatcher;
+ this.attributeVisitor = attributeVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ if (accepted(clazz, unknownAttribute))
+ {
+ unknownAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ if (accepted(clazz, bootstrapMethodsAttribute))
+ {
+ bootstrapMethodsAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ if (accepted(clazz, sourceFileAttribute))
+ {
+ sourceFileAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ if (accepted(clazz, sourceDirAttribute))
+ {
+ sourceDirAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ if (accepted(clazz, innerClassesAttribute))
+ {
+ innerClassesAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ if (accepted(clazz, enclosingMethodAttribute))
+ {
+ enclosingMethodAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ if (accepted(clazz, deprecatedAttribute))
+ {
+ deprecatedAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Field field, DeprecatedAttribute deprecatedAttribute)
+ {
+ if (accepted(clazz, deprecatedAttribute))
+ {
+ deprecatedAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Method method, DeprecatedAttribute deprecatedAttribute)
+ {
+ if (accepted(clazz, deprecatedAttribute))
+ {
+ deprecatedAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ if (accepted(clazz, syntheticAttribute))
+ {
+ syntheticAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Field field, SyntheticAttribute syntheticAttribute)
+ {
+ if (accepted(clazz, syntheticAttribute))
+ {
+ syntheticAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Method method, SyntheticAttribute syntheticAttribute)
+ {
+ if (accepted(clazz, syntheticAttribute))
+ {
+ syntheticAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ if (accepted(clazz, signatureAttribute))
+ {
+ signatureAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Field field, SignatureAttribute signatureAttribute)
+ {
+ if (accepted(clazz, signatureAttribute))
+ {
+ signatureAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Method method, SignatureAttribute signatureAttribute)
+ {
+ if (accepted(clazz, signatureAttribute))
+ {
+ signatureAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ if (accepted(clazz, constantValueAttribute))
+ {
+ constantValueAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ if (accepted(clazz, exceptionsAttribute))
+ {
+ exceptionsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (accepted(clazz, codeAttribute))
+ {
+ codeAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ if (accepted(clazz, stackMapAttribute))
+ {
+ stackMapAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ if (accepted(clazz, stackMapTableAttribute))
+ {
+ stackMapTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ if (accepted(clazz, lineNumberTableAttribute))
+ {
+ lineNumberTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ if (accepted(clazz, localVariableTableAttribute))
+ {
+ localVariableTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ if (accepted(clazz, localVariableTypeTableAttribute))
+ {
+ localVariableTypeTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeVisibleAnnotationsAttribute))
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeVisibleAnnotationsAttribute))
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeVisibleAnnotationsAttribute))
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeInvisibleAnnotationsAttribute))
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeInvisibleAnnotationsAttribute))
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeInvisibleAnnotationsAttribute))
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeVisibleParameterAnnotationsAttribute))
+ {
+ runtimeVisibleParameterAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute)
+ {
+ if (accepted(clazz, runtimeInvisibleParameterAnnotationsAttribute))
+ {
+ runtimeInvisibleParameterAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ if (accepted(clazz, annotationDefaultAttribute))
+ {
+ annotationDefaultAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(Clazz clazz, Attribute attribute)
+ {
+ return regularExpressionMatcher.matches(attribute.getAttributeName(clazz));
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/AttributeVisitor.java b/src/proguard/classfile/attribute/visitor/AttributeVisitor.java
new file mode 100644
index 000000000..76c1ab931
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/AttributeVisitor.java
@@ -0,0 +1,90 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+
+/**
+ * This interface specifies the methods for a visitor of Attribute
+ * objects.
+ *
+ * @author Eric Lafortune
+ */
+public interface AttributeVisitor
+{
+ // Attributes that are attached to classes.
+
+ public void visitUnknownAttribute( Clazz clazz, UnknownAttribute unknownAttribute);
+ public void visitBootstrapMethodsAttribute( Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute);
+ public void visitSourceFileAttribute( Clazz clazz, SourceFileAttribute sourceFileAttribute);
+ public void visitSourceDirAttribute( Clazz clazz, SourceDirAttribute sourceDirAttribute);
+ public void visitInnerClassesAttribute( Clazz clazz, InnerClassesAttribute innerClassesAttribute);
+ public void visitEnclosingMethodAttribute( Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute);
+
+ // Attributes that are attached to classes, fields, and methods.
+
+ public void visitDeprecatedAttribute( Clazz clazz, DeprecatedAttribute deprecatedAttribute);
+ public void visitDeprecatedAttribute( Clazz clazz, Field field, DeprecatedAttribute deprecatedAttribute);
+ public void visitDeprecatedAttribute( Clazz clazz, Method method, DeprecatedAttribute deprecatedAttribute);
+
+ public void visitSyntheticAttribute( Clazz clazz, SyntheticAttribute syntheticAttribute);
+ public void visitSyntheticAttribute( Clazz clazz, Field field, SyntheticAttribute syntheticAttribute);
+ public void visitSyntheticAttribute( Clazz clazz, Method method, SyntheticAttribute syntheticAttribute);
+
+ public void visitSignatureAttribute( Clazz clazz, SignatureAttribute signatureAttribute);
+ public void visitSignatureAttribute( Clazz clazz, Field field, SignatureAttribute signatureAttribute);
+ public void visitSignatureAttribute( Clazz clazz, Method method, SignatureAttribute signatureAttribute);
+
+ // Attributes that are attached to fields.
+
+ public void visitConstantValueAttribute( Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute);
+
+ // Attributes that are attached to methods.
+
+ public void visitExceptionsAttribute( Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute);
+ public void visitCodeAttribute( Clazz clazz, Method method, CodeAttribute codeAttribute);
+
+ // Attributes that are attached to code attributes.
+
+ public void visitStackMapAttribute( Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute);
+ public void visitStackMapTableAttribute( Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute);
+ public void visitLineNumberTableAttribute( Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute);
+ public void visitLocalVariableTableAttribute( Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute);
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute);
+
+ // Annotation attributes.
+
+ public void visitRuntimeVisibleAnnotationsAttribute( Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute);
+ public void visitRuntimeVisibleAnnotationsAttribute( Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute);
+ public void visitRuntimeVisibleAnnotationsAttribute( Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute);
+
+ public void visitRuntimeInvisibleAnnotationsAttribute( Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute);
+ public void visitRuntimeInvisibleAnnotationsAttribute( Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute);
+ public void visitRuntimeInvisibleAnnotationsAttribute( Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute);
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute( Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute);
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute);
+
+ public void visitAnnotationDefaultAttribute( Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute);
+}
diff --git a/src/proguard/classfile/attribute/visitor/BootstrapMethodInfoVisitor.java b/src/proguard/classfile/attribute/visitor/BootstrapMethodInfoVisitor.java
new file mode 100755
index 000000000..9aab92ef7
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/BootstrapMethodInfoVisitor.java
@@ -0,0 +1,40 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+
+import java.beans.MethodDescriptor;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * BootstrapMethodInfo
objects. Note that there is only a single
+ * implementation of BootstrapMethodInfo
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface BootstrapMethodInfoVisitor
+{
+ public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo);
+}
diff --git a/src/proguard/classfile/attribute/visitor/ExceptionInfoVisitor.java b/src/proguard/classfile/attribute/visitor/ExceptionInfoVisitor.java
new file mode 100644
index 000000000..4a765f2aa
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/ExceptionInfoVisitor.java
@@ -0,0 +1,37 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+
+/**
+ * This interface specifies the methods for a visitor of
+ * ExceptionInfo
objects. Note that there is only a single
+ * implementation of ExceptionInfo
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface ExceptionInfoVisitor
+{
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo);
+}
diff --git a/src/proguard/classfile/attribute/visitor/InnerClassesInfoVisitor.java b/src/proguard/classfile/attribute/visitor/InnerClassesInfoVisitor.java
new file mode 100644
index 000000000..b373493cb
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/InnerClassesInfoVisitor.java
@@ -0,0 +1,38 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.InnerClassesInfo;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * InnerClassesInfo
objects. Note that there is only a single
+ * implementation of InnerClassesInfo
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface InnerClassesInfoVisitor
+{
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo);
+}
diff --git a/src/proguard/classfile/attribute/visitor/LineNumberInfoVisitor.java b/src/proguard/classfile/attribute/visitor/LineNumberInfoVisitor.java
new file mode 100644
index 000000000..189b3d0f7
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/LineNumberInfoVisitor.java
@@ -0,0 +1,38 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * LineNumberInfo
objects. Note that there is only a single
+ * implementation of LineNumberInfo
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface LineNumberInfoVisitor
+{
+ public void visitLineNumberInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberInfo lineNumberInfo);
+}
diff --git a/src/proguard/classfile/attribute/visitor/LocalVariableInfoVisitor.java b/src/proguard/classfile/attribute/visitor/LocalVariableInfoVisitor.java
new file mode 100644
index 000000000..c888d6330
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/LocalVariableInfoVisitor.java
@@ -0,0 +1,38 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * LocalVariableInfo
objects. Note that there is only a single
+ * implementation of LocalVariableInfo
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface LocalVariableInfoVisitor
+{
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo);
+}
diff --git a/src/proguard/classfile/attribute/visitor/LocalVariableTypeInfoVisitor.java b/src/proguard/classfile/attribute/visitor/LocalVariableTypeInfoVisitor.java
new file mode 100644
index 000000000..f992e6dad
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/LocalVariableTypeInfoVisitor.java
@@ -0,0 +1,38 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * LocalVariableTypeInfo
objects. Note that there is only a single
+ * implementation of LocalVariableTypeInfo
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface LocalVariableTypeInfoVisitor
+{
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo);
+}
diff --git a/src/proguard/classfile/attribute/visitor/MultiAttributeVisitor.java b/src/proguard/classfile/attribute/visitor/MultiAttributeVisitor.java
new file mode 100644
index 000000000..37c0639f1
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/MultiAttributeVisitor.java
@@ -0,0 +1,365 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+
+/**
+ * This AttributeVisitor delegates all visits to each AttributeVisitor
+ * in a given list.
+ *
+ * @author Eric Lafortune
+ */
+public class MultiAttributeVisitor implements AttributeVisitor
+{
+ private AttributeVisitor[] attributeVisitors;
+
+
+ public MultiAttributeVisitor()
+ {
+ }
+
+
+ public MultiAttributeVisitor(AttributeVisitor[] attributeVisitors)
+ {
+ this.attributeVisitors = attributeVisitors;
+ }
+
+
+ public void addAttributeVisitor(AttributeVisitor attributeVisitor)
+ {
+ incrementArraySize();
+
+ attributeVisitors[attributeVisitors.length - 1] = attributeVisitor;
+ }
+
+
+ private void incrementArraySize()
+ {
+ if (attributeVisitors == null)
+ {
+ attributeVisitors = new AttributeVisitor[1];
+ }
+ else
+ {
+ AttributeVisitor[] newAttributeVisitors =
+ new AttributeVisitor[attributeVisitors.length + 1];
+ System.arraycopy(attributeVisitors, 0,
+ newAttributeVisitors, 0,
+ attributeVisitors.length);
+ attributeVisitors = newAttributeVisitors;
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitUnknownAttribute(clazz, unknownAttribute);
+ }
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitBootstrapMethodsAttribute(clazz, bootstrapMethodsAttribute);
+ }
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSourceFileAttribute(clazz, sourceFileAttribute);
+ }
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSourceDirAttribute(clazz, sourceDirAttribute);
+ }
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitInnerClassesAttribute(clazz, innerClassesAttribute);
+ }
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitEnclosingMethodAttribute(clazz, enclosingMethodAttribute);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitDeprecatedAttribute(clazz, deprecatedAttribute);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSyntheticAttribute(clazz, syntheticAttribute);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute syntheticAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSignatureAttribute(clazz, syntheticAttribute);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Field field, DeprecatedAttribute deprecatedAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitDeprecatedAttribute(clazz, field, deprecatedAttribute);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Field field, SyntheticAttribute syntheticAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSyntheticAttribute(clazz, field, syntheticAttribute);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Field field, SignatureAttribute syntheticAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSignatureAttribute(clazz, field, syntheticAttribute);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Method method, DeprecatedAttribute deprecatedAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitDeprecatedAttribute(clazz, method, deprecatedAttribute);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Method method, SyntheticAttribute syntheticAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSyntheticAttribute(clazz, method, syntheticAttribute);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Method method, SignatureAttribute syntheticAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitSignatureAttribute(clazz, method, syntheticAttribute);
+ }
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitConstantValueAttribute(clazz, field, constantValueAttribute);
+ }
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitExceptionsAttribute(clazz, method, exceptionsAttribute);
+ }
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitCodeAttribute(clazz, method, codeAttribute);
+ }
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitStackMapAttribute(clazz, method, codeAttribute, stackMapAttribute);
+ }
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitStackMapTableAttribute(clazz, method, codeAttribute, stackMapTableAttribute);
+ }
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitLineNumberTableAttribute(clazz, method, codeAttribute, lineNumberTableAttribute);
+ }
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitLocalVariableTableAttribute(clazz, method, codeAttribute, localVariableTableAttribute);
+ }
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitLocalVariableTypeTableAttribute(clazz, method, codeAttribute, localVariableTypeTableAttribute);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeVisibleAnnotationsAttribute(clazz, runtimeVisibleAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeInvisibleAnnotationsAttribute(clazz, runtimeInvisibleAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeVisibleAnnotationsAttribute(clazz, field, runtimeVisibleAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeInvisibleAnnotationsAttribute(clazz, field, runtimeInvisibleAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeVisibleAnnotationsAttribute(clazz, method, runtimeVisibleAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeInvisibleAnnotationsAttribute(clazz, method, runtimeInvisibleAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeVisibleParameterAnnotationsAttribute(clazz, method, runtimeVisibleParameterAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitRuntimeInvisibleParameterAnnotationsAttribute(clazz, method, runtimeInvisibleParameterAnnotationsAttribute);
+ }
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ for (int index = 0; index < attributeVisitors.length; index++)
+ {
+ attributeVisitors[index].visitAnnotationDefaultAttribute(clazz, method, annotationDefaultAttribute);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/NonEmptyAttributeFilter.java b/src/proguard/classfile/attribute/visitor/NonEmptyAttributeFilter.java
new file mode 100644
index 000000000..2ccc09c1a
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/NonEmptyAttributeFilter.java
@@ -0,0 +1,293 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.util.StringMatcher;
+
+/**
+ * This AttributeVisitor delegates its visits another AttributeVisitor, but
+ * only when the visited attribute is not empty. For instance, a local variable
+ * table without variables is empty.
+ *
+ * @author Eric Lafortune
+ */
+public class NonEmptyAttributeFilter
+implements AttributeVisitor
+{
+ private final AttributeVisitor attributeVisitor;
+
+
+ /**
+ * Creates a new NonEmptyAttributeFilter.
+ * @param attributeVisitor the AttributeVisitor
to which
+ * visits will be delegated.
+ */
+ public NonEmptyAttributeFilter(AttributeVisitor attributeVisitor)
+ {
+ this.attributeVisitor = attributeVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ unknownAttribute.accept(clazz, attributeVisitor);
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ if (bootstrapMethodsAttribute.u2bootstrapMethodsCount > 0)
+ {
+ bootstrapMethodsAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ sourceFileAttribute.accept(clazz, attributeVisitor);
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ sourceDirAttribute.accept(clazz, attributeVisitor);
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ if (innerClassesAttribute.u2classesCount > 0)
+ {
+ innerClassesAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ enclosingMethodAttribute.accept(clazz, attributeVisitor);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ deprecatedAttribute.accept(clazz, attributeVisitor);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Field field, DeprecatedAttribute deprecatedAttribute)
+ {
+ deprecatedAttribute.accept(clazz, field, attributeVisitor);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Method method, DeprecatedAttribute deprecatedAttribute)
+ {
+ deprecatedAttribute.accept(clazz, method, attributeVisitor);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ syntheticAttribute.accept(clazz, attributeVisitor);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Field field, SyntheticAttribute syntheticAttribute)
+ {
+ syntheticAttribute.accept(clazz, field, attributeVisitor);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Method method, SyntheticAttribute syntheticAttribute)
+ {
+ syntheticAttribute.accept(clazz, method, attributeVisitor);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ signatureAttribute.accept(clazz, attributeVisitor);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Field field, SignatureAttribute signatureAttribute)
+ {
+ signatureAttribute.accept(clazz, field, attributeVisitor);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Method method, SignatureAttribute signatureAttribute)
+ {
+ signatureAttribute.accept(clazz, method, attributeVisitor);
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ constantValueAttribute.accept(clazz, field, attributeVisitor);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ if (exceptionsAttribute.u2exceptionIndexTableLength > 0)
+ {
+ exceptionsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttribute.accept(clazz, method, attributeVisitor);
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ if (stackMapAttribute.u2stackMapFramesCount > 0)
+ {
+ stackMapAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ if (stackMapTableAttribute.u2stackMapFramesCount > 0)
+ {
+ stackMapTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ if (lineNumberTableAttribute.u2lineNumberTableLength > 0)
+ {
+ lineNumberTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ if (localVariableTableAttribute.u2localVariableTableLength > 0)
+ {
+ localVariableTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ if (localVariableTypeTableAttribute.u2localVariableTypeTableLength > 0)
+ {
+ localVariableTypeTableAttribute.accept(clazz, method, codeAttribute, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (runtimeVisibleAnnotationsAttribute.u2annotationsCount > 0)
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (runtimeVisibleAnnotationsAttribute.u2annotationsCount > 0)
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (runtimeVisibleAnnotationsAttribute.u2annotationsCount > 0)
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (runtimeInvisibleAnnotationsAttribute.u2annotationsCount > 0)
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (runtimeInvisibleAnnotationsAttribute.u2annotationsCount > 0)
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, field, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (runtimeInvisibleAnnotationsAttribute.u2annotationsCount > 0)
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute)
+ {
+ if (runtimeVisibleParameterAnnotationsAttribute.u2parametersCount > 0)
+ {
+ runtimeVisibleParameterAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute)
+ {
+ if (runtimeInvisibleParameterAnnotationsAttribute.u2parametersCount > 0)
+ {
+ runtimeInvisibleParameterAnnotationsAttribute.accept(clazz, method, attributeVisitor);
+ }
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ annotationDefaultAttribute.accept(clazz, method, attributeVisitor);
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/RequiredAttributeFilter.java b/src/proguard/classfile/attribute/visitor/RequiredAttributeFilter.java
new file mode 100644
index 000000000..58e4e40cb
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/RequiredAttributeFilter.java
@@ -0,0 +1,362 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.obfuscate.AttributeShrinker;
+
+/**
+ * This AttributeVisitor delegates its visits to one of two other
+ * AttributeVisitor instances, depending on whether the visited attribute
+ * is strictly required or not.
+ *
+ * Stack map attributes and stack map table attributes are treated as optional.
+ *
+ * @see AttributeShrinker
+ *
+ * @author Eric Lafortune
+ */
+public class RequiredAttributeFilter
+implements AttributeVisitor
+{
+ private final AttributeVisitor requiredAttributeVisitor;
+ private final AttributeVisitor optionalAttributeVisitor;
+
+
+ /**
+ * Creates a new RequiredAttributeFilter for visiting required attributes.
+ * @param requiredAttributeVisitor the visitor that will visit required
+ * attributes.
+ */
+ public RequiredAttributeFilter(AttributeVisitor requiredAttributeVisitor)
+ {
+ this(requiredAttributeVisitor, null);
+ }
+
+
+ /**
+ * Creates a new RequiredAttributeFilter for visiting required and
+ * optional attributes.
+ * @param requiredAttributeVisitor the visitor that will visit required
+ * attributes.
+ * @param optionalAttributeVisitor the visitor that will visit optional
+ * attributes.
+ */
+ public RequiredAttributeFilter(AttributeVisitor requiredAttributeVisitor,
+ AttributeVisitor optionalAttributeVisitor)
+ {
+ this.requiredAttributeVisitor = requiredAttributeVisitor;
+ this.optionalAttributeVisitor = optionalAttributeVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ unknownAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ if (requiredAttributeVisitor != null)
+ {
+ bootstrapMethodsAttribute.accept(clazz, requiredAttributeVisitor);
+ }
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ sourceFileAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ sourceDirAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ innerClassesAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ enclosingMethodAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ deprecatedAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Field field, DeprecatedAttribute deprecatedAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ deprecatedAttribute.accept(clazz, field, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Method method, DeprecatedAttribute deprecatedAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ deprecatedAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ syntheticAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Field field, SyntheticAttribute syntheticAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ syntheticAttribute.accept(clazz, field, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Method method, SyntheticAttribute syntheticAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ syntheticAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ signatureAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Field field, SignatureAttribute signatureAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ signatureAttribute.accept(clazz, field, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Method method, SignatureAttribute signatureAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ signatureAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ if (requiredAttributeVisitor != null)
+ {
+ constantValueAttribute.accept(clazz, field, requiredAttributeVisitor);
+ }
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ exceptionsAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (requiredAttributeVisitor != null)
+ {
+ codeAttribute.accept(clazz, method, requiredAttributeVisitor);
+ }
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ stackMapAttribute.accept(clazz, method, codeAttribute, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ stackMapTableAttribute.accept(clazz, method, codeAttribute, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ lineNumberTableAttribute.accept(clazz, method, codeAttribute, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ localVariableTableAttribute.accept(clazz, method, codeAttribute, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ localVariableTypeTableAttribute.accept(clazz, method, codeAttribute, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, field, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeVisibleAnnotationsAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, field, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeInvisibleAnnotationsAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeVisibleParameterAnnotationsAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ runtimeInvisibleParameterAnnotationsAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ if (optionalAttributeVisitor != null)
+ {
+ annotationDefaultAttribute.accept(clazz, method, optionalAttributeVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/StackSizeComputer.java b/src/proguard/classfile/attribute/visitor/StackSizeComputer.java
new file mode 100644
index 000000000..b5e02e20d
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/StackSizeComputer.java
@@ -0,0 +1,378 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.attribute.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassPrinter;
+import proguard.classfile.attribute.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+import java.util.Arrays;
+
+/**
+ * This AttributeVisitor computes the stack sizes at all instruction offsets
+ * of the code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class StackSizeComputer
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ExceptionInfoVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+
+ private boolean[] evaluated = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
+ private int[] stackSizes = new int[ClassConstants.TYPICAL_CODE_LENGTH];
+
+ private boolean exitInstructionBlock;
+
+ private int stackSize;
+ private int maxStackSize;
+
+
+ /**
+ * Returns whether the instruction at the given offset is reachable in the
+ * most recently visited code attribute.
+ */
+ public boolean isReachable(int instructionOffset)
+ {
+ return evaluated[instructionOffset];
+ }
+
+
+ /**
+ * Returns the stack size at the given instruction offset of the most
+ * recently visited code attribute.
+ */
+ public int getStackSize(int instructionOffset)
+ {
+ if (!evaluated[instructionOffset])
+ {
+ throw new IllegalArgumentException("Unknown stack size at unreachable instruction offset ["+instructionOffset+"]");
+ }
+
+ return stackSizes[instructionOffset];
+ }
+
+
+ /**
+ * Returns the maximum stack size of the most recently visited code attribute.
+ */
+ public int getMaxStackSize()
+ {
+ return maxStackSize;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // TODO: Remove this when the code has stabilized.
+ // Catch any unexpected exceptions from the actual visiting method.
+ try
+ {
+ // Process the code.
+ visitCodeAttribute0(clazz, method, codeAttribute);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while computing stack sizes:");
+ System.err.println(" Class = ["+clazz.getName()+"]");
+ System.err.println(" Method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+
+ if (DEBUG)
+ {
+ method.accept(clazz, new ClassPrinter());
+ }
+
+ throw ex;
+ }
+ }
+
+
+ public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (DEBUG)
+ {
+ System.out.println("StackSizeComputer: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ }
+
+ // Try to reuse the previous array.
+ int codeLength = codeAttribute.u4codeLength;
+ if (evaluated.length < codeLength)
+ {
+ evaluated = new boolean[codeLength];
+ stackSizes = new int[codeLength];
+ }
+ else
+ {
+ Arrays.fill(evaluated, 0, codeLength, false);
+ }
+
+ // The initial stack is always empty.
+ stackSize = 0;
+ maxStackSize = 0;
+
+ // Evaluate the instruction block starting at the entry point of the method.
+ evaluateInstructionBlock(clazz, method, codeAttribute, 0);
+
+ // Evaluate the exception handlers.
+ codeAttribute.exceptionsAccept(clazz, method, this);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ byte opcode = simpleInstruction.opcode;
+
+ // Some simple instructions exit from the current instruction block.
+ exitInstructionBlock =
+ opcode == InstructionConstants.OP_IRETURN ||
+ opcode == InstructionConstants.OP_LRETURN ||
+ opcode == InstructionConstants.OP_FRETURN ||
+ opcode == InstructionConstants.OP_DRETURN ||
+ opcode == InstructionConstants.OP_ARETURN ||
+ opcode == InstructionConstants.OP_RETURN ||
+ opcode == InstructionConstants.OP_ATHROW;
+ }
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Constant pool instructions never end the current instruction block.
+ exitInstructionBlock = false;
+ }
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ byte opcode = variableInstruction.opcode;
+
+ // The ret instruction end the current instruction block.
+ exitInstructionBlock =
+ opcode == InstructionConstants.OP_RET;
+ }
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ byte opcode = branchInstruction.opcode;
+
+ // Evaluate the target instruction blocks.
+ evaluateInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ offset +
+ branchInstruction.branchOffset);
+
+ // Evaluate the instructions after a subroutine branch.
+ if (opcode == InstructionConstants.OP_JSR ||
+ opcode == InstructionConstants.OP_JSR_W)
+ {
+ // We assume subroutine calls (jsr and jsr_w instructions) don't
+ // change the stack, other than popping the return value.
+ stackSize -= 1;
+
+ evaluateInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ offset + branchInstruction.length(offset));
+ }
+
+ // Some branch instructions always end the current instruction block.
+ exitInstructionBlock =
+ opcode == InstructionConstants.OP_GOTO ||
+ opcode == InstructionConstants.OP_GOTO_W ||
+ opcode == InstructionConstants.OP_JSR ||
+ opcode == InstructionConstants.OP_JSR_W;
+ }
+
+
+ public void visitAnySwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SwitchInstruction switchInstruction)
+ {
+ // Evaluate the target instruction blocks.
+
+ // Loop over all jump offsets.
+ int[] jumpOffsets = switchInstruction.jumpOffsets;
+
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ // Evaluate the jump instruction block.
+ evaluateInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ offset + jumpOffsets[index]);
+ }
+
+ // Also evaluate the default instruction block.
+ evaluateInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ offset + switchInstruction.defaultOffset);
+
+ // The switch instruction always ends the current instruction block.
+ exitInstructionBlock = true;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ if (DEBUG)
+ {
+ System.out.println("Exception:");
+ }
+
+ // The stack size when entering the exception handler is always 1.
+ stackSize = 1;
+
+ // Evaluate the instruction block starting at the entry point of the
+ // exception handler.
+ evaluateInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ exceptionInfo.u2handlerPC);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Evaluates a block of instructions that hasn't been handled before,
+ * starting at the given offset and ending at a branch instruction, a return
+ * instruction, or a throw instruction. Branch instructions are handled
+ * recursively.
+ */
+ private void evaluateInstructionBlock(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ int instructionOffset)
+ {
+ if (DEBUG)
+ {
+ if (evaluated[instructionOffset])
+ {
+ System.out.println("-- (instruction block at "+instructionOffset+" already evaluated)");
+ }
+ else
+ {
+ System.out.println("-- instruction block:");
+ }
+ }
+
+ // Remember the initial stack size.
+ int initialStackSize = stackSize;
+
+ // Remember the maximum stack size.
+ if (maxStackSize < stackSize)
+ {
+ maxStackSize = stackSize;
+ }
+
+ // Evaluate any instructions that haven't been evaluated before.
+ while (!evaluated[instructionOffset])
+ {
+ // Mark the instruction as evaluated.
+ evaluated[instructionOffset] = true;
+
+ Instruction instruction = InstructionFactory.create(codeAttribute.code,
+ instructionOffset);
+
+ if (DEBUG)
+ {
+ int stackPushCount = instruction.stackPushCount(clazz);
+ int stackPopCount = instruction.stackPopCount(clazz);
+ System.out.println("["+instructionOffset+"]: "+
+ stackSize+" - "+
+ stackPopCount+" + "+
+ stackPushCount+" = "+
+ (stackSize+stackPushCount-stackPopCount)+": "+
+ instruction.toString(instructionOffset));
+ }
+
+ // Compute the instruction's effect on the stack size.
+ stackSize -= instruction.stackPopCount(clazz);
+
+ if (stackSize < 0)
+ {
+ throw new IllegalArgumentException("Stack size becomes negative after instruction "+
+ instruction.toString(instructionOffset)+" in ["+
+ clazz.getName()+"."+
+ method.getName(clazz)+
+ method.getDescriptor(clazz)+"]");
+ }
+
+ stackSizes[instructionOffset] =
+ stackSize += instruction.stackPushCount(clazz);
+
+ // Remember the maximum stack size.
+ if (maxStackSize < stackSize)
+ {
+ maxStackSize = stackSize;
+ }
+
+ // Remember the next instruction offset.
+ int nextInstructionOffset = instructionOffset +
+ instruction.length(instructionOffset);
+
+ // Visit the instruction, in order to handle branches.
+ instruction.accept(clazz, method, codeAttribute, instructionOffset, this);
+
+ // Stop evaluating after a branch.
+ if (exitInstructionBlock)
+ {
+ break;
+ }
+
+ // Continue with the next instruction.
+ instructionOffset = nextInstructionOffset;
+
+ if (DEBUG)
+ {
+ if (evaluated[instructionOffset])
+ {
+ System.out.println("-- (instruction at "+instructionOffset+" already evaluated)");
+ }
+ }
+ }
+
+ // Restore the stack size for possible subsequent instruction blocks.
+ this.stackSize = initialStackSize;
+ }
+}
diff --git a/src/proguard/classfile/attribute/visitor/package.html b/src/proguard/classfile/attribute/visitor/package.html
new file mode 100644
index 000000000..056244af6
--- /dev/null
+++ b/src/proguard/classfile/attribute/visitor/package.html
@@ -0,0 +1,3 @@
+
+This package contains visitors for attributes and their components.
+
diff --git a/src/proguard/classfile/constant/ClassConstant.java b/src/proguard/classfile/constant/ClassConstant.java
new file mode 100644
index 000000000..bbd9b3145
--- /dev/null
+++ b/src/proguard/classfile/constant/ClassConstant.java
@@ -0,0 +1,105 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This Constant represents a class constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassConstant extends Constant
+{
+ public int u2nameIndex;
+
+ /**
+ * An extra field pointing to the referenced Clazz object.
+ * This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ */
+ public Clazz referencedClass;
+
+ /**
+ * An extra field pointing to the java.lang.Class Clazz object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
..
+ */
+ public Clazz javaLangClassClass;
+
+
+ /**
+ * Creates an uninitialized ClassConstant.
+ */
+ public ClassConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new ClassConstant with the given name index.
+ * @param u2nameIndex the index of the name in the constant pool.
+ * @param referencedClass the referenced class.
+ */
+ public ClassConstant(int u2nameIndex,
+ Clazz referencedClass)
+ {
+ this.u2nameIndex = u2nameIndex;
+ this.referencedClass = referencedClass;
+ }
+
+
+ /**
+ * Returns the name.
+ */
+ public String getName(Clazz clazz)
+ {
+ return clazz.getString(u2nameIndex);
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Class;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitClassConstant(clazz, this);
+ }
+
+
+ /**
+ * Lets the referenced class accept the given visitor.
+ */
+ public void referencedClassAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/constant/Constant.java b/src/proguard/classfile/constant/Constant.java
new file mode 100644
index 000000000..b4168cedb
--- /dev/null
+++ b/src/proguard/classfile/constant/Constant.java
@@ -0,0 +1,68 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This abstract class represents an entry in the ConstantPool. Specific types
+ * of entries are subclassed from it.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class Constant implements VisitorAccepter
+{
+ //public int u1tag;
+ //public byte info[];
+
+ /**
+ * An extra field in which visitors can store information.
+ */
+ public Object visitorInfo;
+
+
+ // Abstract methods to be implemented by extensions.
+
+ /**
+ * Returns the constant pool info tag that specifies the entry type.
+ */
+ public abstract int getTag();
+
+
+ /**
+ * Accepts the given visitor.
+ */
+ public abstract void accept(Clazz clazz, ConstantVisitor constantVisitor);
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return visitorInfo;
+ }
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ this.visitorInfo = visitorInfo;
+ }
+}
diff --git a/src/proguard/classfile/constant/DoubleConstant.java b/src/proguard/classfile/constant/DoubleConstant.java
new file mode 100644
index 000000000..a4c64cfb0
--- /dev/null
+++ b/src/proguard/classfile/constant/DoubleConstant.java
@@ -0,0 +1,82 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a double constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class DoubleConstant extends Constant
+{
+ public double f8value;
+
+
+ /**
+ * Creates an uninitialized DoubleConstant.
+ */
+ public DoubleConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new DoubleConstant with the given double value.
+ */
+ public DoubleConstant(double value)
+ {
+ f8value = value;
+ }
+
+
+ /**
+ * Returns the double value of this DoubleConstant.
+ */
+ public double getValue()
+ {
+ return f8value;
+ }
+
+
+ /**
+ * Sets the double value of this DoubleConstant.
+ */
+ public void setValue(double value)
+ {
+ f8value = value;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Double;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitDoubleConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/FieldrefConstant.java b/src/proguard/classfile/constant/FieldrefConstant.java
new file mode 100644
index 000000000..d552d4798
--- /dev/null
+++ b/src/proguard/classfile/constant/FieldrefConstant.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a field reference constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class FieldrefConstant extends RefConstant
+{
+ /**
+ * Creates an uninitialized FieldrefConstant.
+ */
+ public FieldrefConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new FieldrefConstant with the given name and type indices.
+ * @param u2classIndex the index of the class in the constant pool.
+ * @param u2nameAndTypeIndex the index of the name and type entry in the constant pool.
+ * @param referencedClass the referenced class.
+ * @param referencedMember the referenced member info.
+ */
+ public FieldrefConstant(int u2classIndex,
+ int u2nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ this.u2classIndex = u2classIndex;
+ this.u2nameAndTypeIndex = u2nameAndTypeIndex;
+ this.referencedClass = referencedClass;
+ this.referencedMember = referencedMember;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Fieldref;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitFieldrefConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/FloatConstant.java b/src/proguard/classfile/constant/FloatConstant.java
new file mode 100644
index 000000000..1709fcb8a
--- /dev/null
+++ b/src/proguard/classfile/constant/FloatConstant.java
@@ -0,0 +1,82 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a float constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class FloatConstant extends Constant
+{
+ public float f4value;
+
+
+ /**
+ * Creates an uninitialized FloatConstant.
+ */
+ public FloatConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new FloatConstant with the given float value.
+ */
+ public FloatConstant(float value)
+ {
+ f4value = value;
+ }
+
+
+ /**
+ * Returns the float value of this FloatConstant.
+ */
+ public float getValue()
+ {
+ return f4value;
+ }
+
+
+ /**
+ * Sets the float value of this FloatConstant.
+ */
+ public void setValue(float value)
+ {
+ f4value = value;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Float;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitFloatConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/IntegerConstant.java b/src/proguard/classfile/constant/IntegerConstant.java
new file mode 100644
index 000000000..5f0d7f945
--- /dev/null
+++ b/src/proguard/classfile/constant/IntegerConstant.java
@@ -0,0 +1,82 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a integer constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class IntegerConstant extends Constant
+{
+ public int u4value;
+
+
+ /**
+ * Creates an uninitialized IntegerConstant.
+ */
+ public IntegerConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new IntegerConstant with the given integer value.
+ */
+ public IntegerConstant(int value)
+ {
+ u4value = value;
+ }
+
+
+ /**
+ * Returns the integer value of this IntegerConstant.
+ */
+ public int getValue()
+ {
+ return u4value;
+ }
+
+
+ /**
+ * Sets the integer value of this IntegerConstant.
+ */
+ public void setValue(int value)
+ {
+ u4value = value;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Integer;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitIntegerConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/InterfaceMethodrefConstant.java b/src/proguard/classfile/constant/InterfaceMethodrefConstant.java
new file mode 100644
index 000000000..52f185283
--- /dev/null
+++ b/src/proguard/classfile/constant/InterfaceMethodrefConstant.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a interface method reference constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class InterfaceMethodrefConstant extends RefConstant
+{
+ /**
+ * Creates an uninitialized InterfaceMethodrefConstant.
+ */
+ public InterfaceMethodrefConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new InterfaceMethodrefConstant with the given name and type indices.
+ * @param u2classIndex the index of the class in the constant pool.
+ * @param u2nameAndTypeIndex the index of the name and type entry in the constant pool.
+ * @param referencedClass the referenced class.
+ * @param referencedMember the referenced member info.
+ */
+ public InterfaceMethodrefConstant(int u2classIndex,
+ int u2nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ this.u2classIndex = u2classIndex;
+ this.u2nameAndTypeIndex = u2nameAndTypeIndex;
+ this.referencedClass = referencedClass;
+ this.referencedMember = referencedMember;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_InterfaceMethodref;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitInterfaceMethodrefConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/InvokeDynamicConstant.java b/src/proguard/classfile/constant/InvokeDynamicConstant.java
new file mode 100755
index 000000000..57474aa6d
--- /dev/null
+++ b/src/proguard/classfile/constant/InvokeDynamicConstant.java
@@ -0,0 +1,148 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This Constant represents an invoke dynamic constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class InvokeDynamicConstant extends Constant
+{
+ public int u2bootstrapMethodAttributeIndex;
+ public int u2nameAndTypeIndex;
+
+ /**
+ * An extra field pointing to the Clazz objects referenced in the
+ * descriptor string. This field is filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer ClassReferenceInitializer}
.
+ * References to primitive types are ignored.
+ */
+ public Clazz[] referencedClasses;
+
+
+ /**
+ * Creates an uninitialized InvokeDynamicConstant.
+ */
+ public InvokeDynamicConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new InvokeDynamicConstant with the given bootstrap method
+ * and name-and-type indices.
+ * @param u2bootstrapMethodAttributeIndex the index of the bootstrap method
+ * entry in the bootstrap methods
+ * attribute.
+ * @param u2nameAndTypeIndex the index of the name and type
+ * entry in the constant pool.
+ * @param referencedClasses the classes referenced by the
+ * type.
+ */
+ public InvokeDynamicConstant(int u2bootstrapMethodAttributeIndex,
+ int u2nameAndTypeIndex,
+ Clazz[] referencedClasses)
+ {
+ this.u2bootstrapMethodAttributeIndex = u2bootstrapMethodAttributeIndex;
+ this.u2nameAndTypeIndex = u2nameAndTypeIndex;
+ this.referencedClasses = referencedClasses;
+ }
+
+
+ /**
+ * Returns the index of the bootstrap method in the bootstrap methods
+ * attribute of the class.
+ */
+ public int getBootstrapMethodAttributeIndex()
+ {
+ return u2bootstrapMethodAttributeIndex;
+ }
+
+ /**
+ * Returns the name-and-type index.
+ */
+ public int getNameAndTypeIndex()
+ {
+ return u2nameAndTypeIndex;
+ }
+
+ /**
+ * Returns the method name.
+ */
+ public String getName(Clazz clazz)
+ {
+ return clazz.getName(u2nameAndTypeIndex);
+ }
+
+ /**
+ * Returns the method type.
+ */
+ public String getType(Clazz clazz)
+ {
+ return clazz.getType(u2nameAndTypeIndex);
+ }
+
+
+ /**
+ * Lets the Clazz objects referenced in the descriptor string
+ * accept the given visitor.
+ */
+ public void referencedClassesAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClasses != null)
+ {
+ for (int index = 0; index < referencedClasses.length; index++)
+ {
+ if (referencedClasses[index] != null)
+ {
+ referencedClasses[index].accept(classVisitor);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Lets the bootstrap method handle constant accept the given visitor.
+ */
+ public void bootstrapMethodHandleAccept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ new BootstrapMethodHandleTraveler(constantVisitor).visitInvokeDynamicConstant(clazz, this);
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_InvokeDynamic;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitInvokeDynamicConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/LongConstant.java b/src/proguard/classfile/constant/LongConstant.java
new file mode 100644
index 000000000..2416f017e
--- /dev/null
+++ b/src/proguard/classfile/constant/LongConstant.java
@@ -0,0 +1,82 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a long constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class LongConstant extends Constant
+{
+ public long u8value;
+
+
+ /**
+ * Creates an uninitialized LongConstant.
+ */
+ public LongConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new LongConstant with the given long value.
+ */
+ public LongConstant(long value)
+ {
+ u8value = value;
+ }
+
+
+ /**
+ * Returns the long value of this LongConstant.
+ */
+ public long getValue()
+ {
+ return u8value;
+ }
+
+
+ /**
+ * Sets the long value of this LongConstant.
+ */
+ public void setValue(long value)
+ {
+ u8value = value;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Long;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitLongConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/MethodHandleConstant.java b/src/proguard/classfile/constant/MethodHandleConstant.java
new file mode 100755
index 000000000..6cffd9a54
--- /dev/null
+++ b/src/proguard/classfile/constant/MethodHandleConstant.java
@@ -0,0 +1,124 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a method handle constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodHandleConstant extends Constant
+{
+ public int u1referenceKind;
+ public int u2referenceIndex;
+
+
+ /**
+ * An extra field pointing to the java.lang.invoke.MethodHandle Clazz object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
..
+ */
+ public Clazz javaLangInvokeMethodHandleClass;
+
+
+ /**
+ * Creates an uninitialized MethodHandleConstant.
+ */
+ public MethodHandleConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new MethodHandleConstant with the given type and method ref
+ * index.
+ * @param u1referenceKind the reference kind.
+ * @param u2referenceIndex the index of the field ref constant, interface
+ * method ref constant, or method ref constant in
+ * the constant pool.
+ */
+ public MethodHandleConstant(int u1referenceKind, int u2referenceIndex)
+ {
+ this.u1referenceKind = u1referenceKind;
+ this.u2referenceIndex = u2referenceIndex;
+ }
+
+
+ /**
+ * Returns the kind of reference to which this constant is pointing.
+ * @return One of
+ * {@link ClassConstants#REF_getField },
+ * {@link ClassConstants#REF_getStatic },
+ * {@link ClassConstants#REF_putField },
+ * {@link ClassConstants#REF_putStatic },
+ * {@link ClassConstants#REF_invokeVirtual },
+ * {@link ClassConstants#REF_invokeStatic },
+ * {@link ClassConstants#REF_invokeSpecial },
+ * {@link ClassConstants#REF_newInvokeSpecial}, or
+ * {@link ClassConstants#REF_invokeInterface }.
+ */
+ public int getReferenceKind()
+ {
+ return u1referenceKind;
+ }
+
+ /**
+ * Returns the field ref, interface method ref, or method ref index.
+ */
+ public int getReferenceIndex()
+ {
+ return u2referenceIndex;
+ }
+
+
+ /**
+ * Returns the method/field name.
+ */
+ public String getName(Clazz clazz)
+ {
+ return clazz.getRefName(u2referenceIndex);
+ }
+
+ /**
+ * Returns the type.
+ */
+ public String getType(Clazz clazz)
+ {
+ return clazz.getRefType(u2referenceIndex);
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_MethodHandle;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitMethodHandleConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/MethodTypeConstant.java b/src/proguard/classfile/constant/MethodTypeConstant.java
new file mode 100644
index 000000000..96c136ff2
--- /dev/null
+++ b/src/proguard/classfile/constant/MethodTypeConstant.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a method handle constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodTypeConstant extends Constant
+{
+ public int u2descriptorIndex;
+
+
+ /**
+ * An extra field pointing to the java.lang.invoke.MethodType Clazz object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
..
+ */
+ public Clazz javaLangInvokeMethodTypeClass;
+
+
+ /**
+ * Creates an uninitialized MethodTypeConstant.
+ */
+ public MethodTypeConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new MethodTypeConstant with the given descriptor index.
+ * @param u2descriptorIndex the index of the descriptor in the constant
+ * pool.
+ */
+ public MethodTypeConstant(int u2descriptorIndex)
+ {
+ this.u2descriptorIndex = u2descriptorIndex;
+ }
+
+
+ /**
+ * Returns the descriptor index.
+ */
+ public int getDescriptorIndex()
+ {
+ return u2descriptorIndex;
+ }
+
+
+ /**
+ * Returns the type.
+ */
+ public String getType(Clazz clazz)
+ {
+ return clazz.getString(u2descriptorIndex);
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_MethodType;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitMethodTypeConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/MethodrefConstant.java b/src/proguard/classfile/constant/MethodrefConstant.java
new file mode 100644
index 000000000..1ffa23671
--- /dev/null
+++ b/src/proguard/classfile/constant/MethodrefConstant.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a method reference constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodrefConstant extends RefConstant
+{
+ /**
+ * Creates an uninitialized MethodrefConstant.
+ */
+ public MethodrefConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new MethodrefConstant with the given name and type indices.
+ * @param u2classIndex the index of the class in the constant pool.
+ * @param u2nameAndTypeIndex the index of the name and type entry in the constant pool.
+ * @param referencedClass the referenced class.
+ * @param referencedMember the referenced member info.
+ */
+ public MethodrefConstant(int u2classIndex,
+ int u2nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ this.u2classIndex = u2classIndex;
+ this.u2nameAndTypeIndex = u2nameAndTypeIndex;
+ this.referencedClass = referencedClass;
+ this.referencedMember = referencedMember;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Methodref;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitMethodrefConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/NameAndTypeConstant.java b/src/proguard/classfile/constant/NameAndTypeConstant.java
new file mode 100644
index 000000000..2a4dd66a3
--- /dev/null
+++ b/src/proguard/classfile/constant/NameAndTypeConstant.java
@@ -0,0 +1,119 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+/**
+ * This Constant represents a name and type constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class NameAndTypeConstant extends Constant
+{
+ public int u2nameIndex;
+ public int u2descriptorIndex;
+
+
+ /**
+ * Creates an uninitialized NameAndTypeConstant.
+ */
+ public NameAndTypeConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new NameAndTypeConstant with the given name and type indices.
+ * @param u2nameIndex the index of the name in the constant pool.
+ * @param u2descriptorIndex the index of the descriptor in the constant
+ * pool.
+ */
+ public NameAndTypeConstant(int u2nameIndex,
+ int u2descriptorIndex)
+ {
+ this.u2nameIndex = u2nameIndex;
+ this.u2descriptorIndex = u2descriptorIndex;
+ }
+
+
+ /**
+ * Returns the name index.
+ */
+ protected int getNameIndex()
+ {
+ return u2nameIndex;
+ }
+
+ /**
+ * Sets the name index.
+ */
+ protected void setNameIndex(int index)
+ {
+ u2nameIndex = index;
+ }
+
+ /**
+ * Returns the descriptor index.
+ */
+ protected int getDescriptorIndex()
+ {
+ return u2descriptorIndex;
+ }
+
+ /**
+ * Sets the descriptor index.
+ */
+ protected void setDescriptorIndex(int index)
+ {
+ u2descriptorIndex = index;
+ }
+
+ /**
+ * Returns the name.
+ */
+ public String getName(Clazz clazz)
+ {
+ return clazz.getString(u2nameIndex);
+ }
+
+ /**
+ * Returns the type.
+ */
+ public String getType(Clazz clazz)
+ {
+ return clazz.getString(u2descriptorIndex);
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_NameAndType;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitNameAndTypeConstant(clazz, this);
+ }
+}
diff --git a/src/proguard/classfile/constant/RefConstant.java b/src/proguard/classfile/constant/RefConstant.java
new file mode 100644
index 000000000..0a8fb78be
--- /dev/null
+++ b/src/proguard/classfile/constant/RefConstant.java
@@ -0,0 +1,130 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This Constant represents a ref constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class RefConstant extends Constant
+{
+ public int u2classIndex;
+ public int u2nameAndTypeIndex;
+
+ /**
+ * An extra field pointing to the referenced Clazz object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ */
+ public Clazz referencedClass;
+
+ /**
+ * An extra field optionally pointing to the referenced Member object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
.
+ */
+ public Member referencedMember;
+
+
+ protected RefConstant()
+ {
+ }
+
+
+ /**
+ * Returns the class index.
+ */
+ public int getClassIndex()
+ {
+ return u2classIndex;
+ }
+
+ /**
+ * Returns the name-and-type index.
+ */
+ public int getNameAndTypeIndex()
+ {
+ return u2nameAndTypeIndex;
+ }
+
+ /**
+ * Sets the name-and-type index.
+ */
+ public void setNameAndTypeIndex(int index)
+ {
+ u2nameAndTypeIndex = index;
+ }
+
+ /**
+ * Returns the class name.
+ */
+ public String getClassName(Clazz clazz)
+ {
+ return clazz.getClassName(u2classIndex);
+ }
+
+ /**
+ * Returns the method/field name.
+ */
+ public String getName(Clazz clazz)
+ {
+ return clazz.getName(u2nameAndTypeIndex);
+ }
+
+ /**
+ * Returns the type.
+ */
+ public String getType(Clazz clazz)
+ {
+ return clazz.getType(u2nameAndTypeIndex);
+ }
+
+
+ /**
+ * Lets the referenced class accept the given visitor.
+ */
+ public void referencedClassAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClass != null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+
+
+ /**
+ * Lets the referenced class member accept the given visitor.
+ */
+ public void referencedMemberAccept(MemberVisitor memberVisitor)
+ {
+ if (referencedMember != null)
+ {
+ referencedMember.accept(referencedClass,
+ memberVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/constant/StringConstant.java b/src/proguard/classfile/constant/StringConstant.java
new file mode 100644
index 000000000..9b8374538
--- /dev/null
+++ b/src/proguard/classfile/constant/StringConstant.java
@@ -0,0 +1,135 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This Constant represents a string constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class StringConstant extends Constant
+{
+ public int u2stringIndex;
+
+ /**
+ * An extra field pointing to the referenced Clazz object, if this
+ * string is being used in Class.forName(), .class, or
+ * Class.getDeclaredField/Method constructs.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.DynamicClassReferenceInitializer
+ * DynamicClassReferenceInitializer}
or by the {@link
+ * proguard.classfile.util.DynamicMemberReferenceInitializer
+ * DynamicMemberReferenceInitializer}
.
+ */
+ public Clazz referencedClass;
+
+ /**
+ * An extra field pointing to the referenced Member object, if this
+ * string is being used in Class.getDeclaredField/Method constructs.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.DynamicMemberReferenceInitializer
+ * DynamicMemberReferenceInitializer}
.
+ */
+ public Member referencedMember;
+
+ /**
+ * An extra field pointing to the java.lang.String Clazz object.
+ * This field is typically filled out by the {@link
+ * proguard.classfile.util.ClassReferenceInitializer
+ * ClassReferenceInitializer}
..
+ */
+ public Clazz javaLangStringClass;
+
+
+ /**
+ * Creates an uninitialized StringConstant.
+ */
+ public StringConstant()
+ {
+ }
+
+
+ /**
+ * Creates a new StringConstant with the given string index.
+ * @param u2stringIndex the index of the string in the constant pool.
+ * @param referencedClass the referenced class, if any.
+ * @param referenceMember the referenced class member, if any.
+ */
+ public StringConstant(int u2stringIndex,
+ Clazz referencedClass,
+ Member referenceMember)
+ {
+ this.u2stringIndex = u2stringIndex;
+ this.referencedClass = referencedClass;
+ this.referencedMember = referenceMember;
+ }
+
+
+ /**
+ * Returns the string value.
+ */
+ public String getString(Clazz clazz)
+ {
+ return clazz.getString(u2stringIndex);
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_String;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitStringConstant(clazz, this);
+ }
+
+
+ /**
+ * Lets the referenced class accept the given visitor.
+ */
+ public void referencedClassAccept(ClassVisitor classVisitor)
+ {
+ if (referencedClass != null &&
+ referencedMember == null)
+ {
+ referencedClass.accept(classVisitor);
+ }
+ }
+
+
+ /**
+ * Lets the referenced member accept the given visitor.
+ */
+ public void referencedMemberAccept(MemberVisitor memberVisitor)
+ {
+ if (referencedMember != null)
+ {
+ referencedMember.accept(referencedClass, memberVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/constant/Utf8Constant.java b/src/proguard/classfile/constant/Utf8Constant.java
new file mode 100644
index 000000000..3707ba98f
--- /dev/null
+++ b/src/proguard/classfile/constant/Utf8Constant.java
@@ -0,0 +1,285 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+
+import java.io.UnsupportedEncodingException;
+
+/**
+ * This Constant represents a UTF-8 constant in the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class Utf8Constant extends Constant
+{
+ private static final char TWO_BYTE_LIMIT = 0x80;
+ private static final int TWO_BYTE_CONSTANT1 = 0xc0;
+ private static final int TWO_BYTE_CONSTANT2 = 0x80;
+ private static final int TWO_BYTE_SHIFT1 = 6;
+ private static final int TWO_BYTE_MASK1 = 0x1f;
+ private static final int TWO_BYTE_MASK2 = 0x3f;
+
+ private static final char THREE_BYTE_LIMIT = 0x800;
+ private static final int THREE_BYTE_CONSTANT1 = 0xe0;
+ private static final int THREE_BYTE_CONSTANT2 = 0x80;
+ private static final int THREE_BYTE_CONSTANT3 = 0x80;
+ private static final int THREE_BYTE_SHIFT1 = 12;
+ private static final int THREE_BYTE_SHIFT2 = 6;
+ private static final int THREE_BYTE_MASK1 = 0x0f;
+ private static final int THREE_BYTE_MASK2 = 0x3f;
+ private static final int THREE_BYTE_MASK3 = 0x3f;
+
+
+ // There are a lot of Utf8Constant objects, so we're optimising their storage.
+ // Initially, we're storing the UTF-8 bytes in a byte array.
+ // When the corresponding String is requested, we ditch the array and just
+ // store the String.
+
+ //private int u2length;
+ private byte[] bytes;
+
+ private String string;
+
+
+ /**
+ * Creates an uninitialized Utf8Constant.
+ *
+ */
+ public Utf8Constant()
+ {
+ }
+
+
+ /**
+ * Creates a Utf8Constant containing the given string.
+ */
+ public Utf8Constant(String string)
+ {
+ this.bytes = null;
+ this.string = string;
+ }
+
+
+ /**
+ * Initializes the UTF-8 data with an array of bytes.
+ */
+ public void setBytes(byte[] bytes)
+ {
+ this.bytes = bytes;
+ this.string = null;
+ }
+
+
+ /**
+ * Returns the UTF-8 data as an array of bytes.
+ */
+ public byte[] getBytes()
+ {
+ try
+ {
+ switchToByteArrayRepresentation();
+ }
+ catch (UnsupportedEncodingException ex)
+ {
+ throw new RuntimeException(ex.getMessage());
+ }
+
+ return bytes;
+ }
+
+
+ /**
+ * Initializes the UTF-8 data with a String.
+ */
+ public void setString(String utf8String)
+ {
+ this.bytes = null;
+ this.string = utf8String;
+ }
+
+
+ /**
+ * Returns the UTF-8 data as a String.
+ */
+ public String getString()
+ {
+ try
+ {
+ switchToStringRepresentation();
+ }
+ catch (UnsupportedEncodingException ex)
+ {
+ throw new RuntimeException(ex.getMessage());
+ }
+
+ return string;
+ }
+
+
+ // Implementations for Constant.
+
+ public int getTag()
+ {
+ return ClassConstants.CONSTANT_Utf8;
+ }
+
+ public void accept(Clazz clazz, ConstantVisitor constantVisitor)
+ {
+ constantVisitor.visitUtf8Constant(clazz, this);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Switches to a byte array representation of the UTF-8 data.
+ */
+ private void switchToByteArrayRepresentation() throws UnsupportedEncodingException
+ {
+ if (bytes == null)
+ {
+ bytes = getByteArrayRepresentation(string);
+ string = null;
+ }
+ }
+
+
+ /**
+ * Switches to a String representation of the UTF-8 data.
+ */
+ private void switchToStringRepresentation() throws UnsupportedEncodingException
+ {
+ if (string == null)
+ {
+ string = getStringRepresentation(bytes);
+ bytes = null;
+ }
+ }
+
+
+ /**
+ * Returns the modified UTF-8 byte array representation of the given string.
+ */
+ private byte[] getByteArrayRepresentation(String string) throws UnsupportedEncodingException
+ {
+ // We're computing the byte array ourselves, because the implementation
+ // of String.getBytes("UTF-8") has a bug, at least up to JRE 1.4.2.
+ // Also note the special treatment of the 0 character.
+
+ // Compute the byte array length.
+ int byteLength = 0;
+ int stringLength = string.length();
+ for (int stringIndex = 0; stringIndex < stringLength; stringIndex++)
+ {
+ char c = string.charAt(stringIndex);
+
+ // The character is represented by one, two, or three bytes.
+ byteLength += c == 0 ? 2 :
+ c < TWO_BYTE_LIMIT ? 1 :
+ c < THREE_BYTE_LIMIT ? 2 :
+ 3;
+ }
+
+ // Allocate the byte array with the computed length.
+ byte[] bytes = new byte[byteLength];
+
+ // Fill out the array.
+ int byteIndex = 0;
+ for (int stringIndex = 0; stringIndex < stringLength; stringIndex++)
+ {
+ char c = string.charAt(stringIndex);
+ if (c == 0)
+ {
+ // The 0 character gets a two-byte representation in classes.
+ bytes[byteIndex++] = (byte)TWO_BYTE_CONSTANT1;
+ bytes[byteIndex++] = (byte)TWO_BYTE_CONSTANT2;
+ }
+ else if (c < TWO_BYTE_LIMIT)
+ {
+ // The character is represented by a single byte.
+ bytes[byteIndex++] = (byte)c;
+ }
+ else if (c < THREE_BYTE_LIMIT)
+ {
+ // The character is represented by two bytes.
+ bytes[byteIndex++] = (byte)(TWO_BYTE_CONSTANT1 | ((c >>> TWO_BYTE_SHIFT1) & TWO_BYTE_MASK1));
+ bytes[byteIndex++] = (byte)(TWO_BYTE_CONSTANT2 | ( c & TWO_BYTE_MASK2));
+ }
+ else
+ {
+ // The character is represented by three bytes.
+ bytes[byteIndex++] = (byte)(THREE_BYTE_CONSTANT1 | ((c >>> THREE_BYTE_SHIFT1) & THREE_BYTE_MASK1));
+ bytes[byteIndex++] = (byte)(THREE_BYTE_CONSTANT2 | ((c >>> THREE_BYTE_SHIFT2) & THREE_BYTE_MASK2));
+ bytes[byteIndex++] = (byte)(THREE_BYTE_CONSTANT3 | ( c & THREE_BYTE_MASK3));
+ }
+ }
+
+ return bytes;
+ }
+
+
+ /**
+ * Returns the String representation of the given modified UTF-8 byte array.
+ */
+ private String getStringRepresentation(byte[] bytes) throws UnsupportedEncodingException
+ {
+ // We're computing the string ourselves, because the implementation
+ // of "new String(bytes)" doesn't honor the special treatment of
+ // the 0 character in JRE 1.6_u11.
+
+ // Allocate the byte array with the computed length.
+ char[] chars = new char[bytes.length];
+
+ // Fill out the array.
+ int charIndex = 0;
+ int byteIndex = 0;
+ while (byteIndex < bytes.length)
+ {
+
+ int b = bytes[byteIndex++] & 0xff;
+
+ // Depending on the flag bits in the first byte, the character
+ // is represented by a single byte, by two bytes, or by three
+ // bytes. We're not checking the redundant flag bits in the
+ // second byte and the third byte.
+ try
+ {
+ chars[charIndex++] =
+ (char)(b < TWO_BYTE_CONSTANT1 ? b :
+
+ b < THREE_BYTE_CONSTANT1 ? ((b & TWO_BYTE_MASK1) << TWO_BYTE_SHIFT1) |
+ ((bytes[byteIndex++] & TWO_BYTE_MASK2) ) :
+
+ ((b & THREE_BYTE_MASK1) << THREE_BYTE_SHIFT1) |
+ ((bytes[byteIndex++] & THREE_BYTE_MASK2) << THREE_BYTE_SHIFT2) |
+ ((bytes[byteIndex++] & THREE_BYTE_MASK3) ));
+ }
+ catch (ArrayIndexOutOfBoundsException e)
+ {
+ throw new UnsupportedEncodingException("Missing UTF-8 bytes after initial byte [0x"+Integer.toHexString(b)+"] in string ["+new String(chars, 0, charIndex)+"]");
+ }
+ }
+
+ return new String(chars, 0, charIndex);
+ }
+}
diff --git a/src/proguard/classfile/constant/visitor/AllConstantVisitor.java b/src/proguard/classfile/constant/visitor/AllConstantVisitor.java
new file mode 100644
index 000000000..3c3660921
--- /dev/null
+++ b/src/proguard/classfile/constant/visitor/AllConstantVisitor.java
@@ -0,0 +1,53 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+
+/**
+ * This ClassVisitor lets a given ConstantVisitor visit all constant pool
+ * entries of the program classes it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllConstantVisitor implements ClassVisitor
+{
+ private final ConstantVisitor constantVisitor;
+
+
+ public AllConstantVisitor(ConstantVisitor constantVisitor)
+ {
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.constantPoolEntriesAccept(constantVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+}
diff --git a/src/proguard/classfile/constant/visitor/BootstrapMethodHandleTraveler.java b/src/proguard/classfile/constant/visitor/BootstrapMethodHandleTraveler.java
new file mode 100644
index 000000000..6dce6c567
--- /dev/null
+++ b/src/proguard/classfile/constant/visitor/BootstrapMethodHandleTraveler.java
@@ -0,0 +1,100 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+import proguard.optimize.info.MethodOptimizationInfo;
+
+/**
+ * This ConstantVisitor and BootstrapMethodInfoVisitor travels from any invoke
+ * dynamic constants or bootstrap method info entries that it visits to their
+ * bootstrap method handle constants, and applies a given constant visitor.
+ *
+ * @author Eric Lafortune
+ */
+public class BootstrapMethodHandleTraveler
+extends SimplifiedVisitor
+implements ConstantVisitor,
+ AttributeVisitor,
+ BootstrapMethodInfoVisitor
+{
+ private ConstantVisitor bootstrapMethodHandleVisitor;
+
+ // Field serving as a method argument.
+ int bootstrapMethodAttributeIndex;
+
+
+ /**
+ * Creates a new BootstrapMethodHandleVisitor that will delegate to the
+ * given constant visitor.
+ */
+ public BootstrapMethodHandleTraveler(ConstantVisitor bootstrapMethodHandleVisitor)
+ {
+ this.bootstrapMethodHandleVisitor = bootstrapMethodHandleVisitor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ // Pass the method index.
+ bootstrapMethodAttributeIndex =
+ invokeDynamicConstant.u2bootstrapMethodAttributeIndex;
+
+ // Delegate to the bootstrap method.
+ clazz.attributesAccept(this);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ // Check bootstrap methods.
+ bootstrapMethodsAttribute.bootstrapMethodEntryAccept(clazz,
+ bootstrapMethodAttributeIndex,
+ this);
+ }
+
+
+ // Implementations for BootstrapMethodInfoVisitor.
+
+ public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo)
+ {
+ // Check bootstrap method.
+ clazz.constantPoolEntryAccept(bootstrapMethodInfo.u2methodHandleIndex,
+ bootstrapMethodHandleVisitor);
+ }
+}
diff --git a/src/proguard/classfile/constant/visitor/ConstantTagFilter.java b/src/proguard/classfile/constant/visitor/ConstantTagFilter.java
new file mode 100644
index 000000000..a3fcc8ab7
--- /dev/null
+++ b/src/proguard/classfile/constant/visitor/ConstantTagFilter.java
@@ -0,0 +1,86 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.constant.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor
delegates its visits to one or more
+ * specified types of constants.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantTagFilter
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ private final int constantTagMask;
+ private final ConstantVisitor constantVisitor;
+
+
+ /**
+ * Creates a new ConstantTagFilter.
+ * @param constantTag the type of constants for which visits will be
+ * delegated.
+ * @param constantVisitor the ConstantVisitor
to which visits
+ * will be delegated.
+ */
+ public ConstantTagFilter(int constantTag,
+ ConstantVisitor constantVisitor)
+ {
+ this.constantTagMask = 1 << constantTag;
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ /**
+ * Creates a new ConstantTagFilter.
+ * @param constantTags the types of constants for which visits will be
+ * delegated.
+ * @param constantVisitor the ConstantVisitor
to which visits
+ * will be delegated.
+ */
+ public ConstantTagFilter(int[] constantTags,
+ ConstantVisitor constantVisitor)
+ {
+ int constantTagMask = 0;
+ for (int index = 0; index < constantTags.length; index++)
+ {
+ constantTagMask |= 1 << constantTags[index];
+ }
+
+ this.constantTagMask = constantTagMask;
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant)
+ {
+ if (((1 << constant.getTag()) & constantTagMask) != 0)
+ {
+ constant.accept(clazz, constantVisitor);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/constant/visitor/ConstantVisitor.java b/src/proguard/classfile/constant/visitor/ConstantVisitor.java
new file mode 100644
index 000000000..362d54d9d
--- /dev/null
+++ b/src/proguard/classfile/constant/visitor/ConstantVisitor.java
@@ -0,0 +1,49 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.constant.*;
+
+
+/**
+ * This interface specifies the methods for a visitor of Constant
+ * objects.
+ *
+ * @author Eric Lafortune
+ */
+public interface ConstantVisitor
+{
+ public void visitIntegerConstant( Clazz clazz, IntegerConstant integerConstant);
+ public void visitLongConstant( Clazz clazz, LongConstant longConstant);
+ public void visitFloatConstant( Clazz clazz, FloatConstant floatConstant);
+ public void visitDoubleConstant( Clazz clazz, DoubleConstant doubleConstant);
+ public void visitStringConstant( Clazz clazz, StringConstant stringConstant);
+ public void visitUtf8Constant( Clazz clazz, Utf8Constant utf8Constant);
+ public void visitInvokeDynamicConstant( Clazz clazz, InvokeDynamicConstant invokeDynamicConstant);
+ public void visitMethodHandleConstant( Clazz clazz, MethodHandleConstant methodHandleConstant);
+ public void visitFieldrefConstant( Clazz clazz, FieldrefConstant fieldrefConstant);
+ public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant);
+ public void visitMethodrefConstant( Clazz clazz, MethodrefConstant methodrefConstant);
+ public void visitClassConstant( Clazz clazz, ClassConstant classConstant);
+ public void visitMethodTypeConstant( Clazz clazz, MethodTypeConstant methodTypeConstant);
+ public void visitNameAndTypeConstant( Clazz clazz, NameAndTypeConstant nameAndTypeConstant);
+}
diff --git a/src/proguard/classfile/constant/visitor/ExceptClassConstantFilter.java b/src/proguard/classfile/constant/visitor/ExceptClassConstantFilter.java
new file mode 100644
index 000000000..bff4d1e31
--- /dev/null
+++ b/src/proguard/classfile/constant/visitor/ExceptClassConstantFilter.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.editor.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor
delegates its visits to class constants
+ * to another given ConstantVisitor
, except for one given class.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptClassConstantFilter
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ private final String exceptClassName;
+ private final ConstantVisitor constantVisitor;
+
+
+ /**
+ * Creates a new ExceptClassConstantFilter.
+ * @param exceptClassName the name of the class that will not be visited.
+ * @param constantVisitor the ConstantVisitor
to which visits
+ * will be delegated.
+ */
+ public ExceptClassConstantFilter(String exceptClassName,
+ ConstantVisitor constantVisitor)
+ {
+ this.exceptClassName = exceptClassName;
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ if (!classConstant.getName(clazz).equals(exceptClassName))
+ {
+ constantVisitor.visitClassConstant(clazz, classConstant);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/constant/visitor/MethodrefTraveler.java b/src/proguard/classfile/constant/visitor/MethodrefTraveler.java
new file mode 100644
index 000000000..acd1bc84b
--- /dev/null
+++ b/src/proguard/classfile/constant/visitor/MethodrefTraveler.java
@@ -0,0 +1,60 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.constant.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor travels from any method handle constants that it visits
+ * to their methodref constants, and applies a given constant visitor.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodrefTraveler
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ private ConstantVisitor methodrefConstantVisitor;
+
+
+ /**
+ * Creates a new v that will delegate to the given constant visitor.
+ */
+ public MethodrefTraveler(ConstantVisitor methodrefConstantVisitor)
+ {
+ this.methodrefConstantVisitor = methodrefConstantVisitor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex,
+ methodrefConstantVisitor);
+ }
+}
diff --git a/src/proguard/classfile/constant/visitor/package.html b/src/proguard/classfile/constant/visitor/package.html
new file mode 100644
index 000000000..e20f48e51
--- /dev/null
+++ b/src/proguard/classfile/constant/visitor/package.html
@@ -0,0 +1,3 @@
+
+This package contains visitors for class constants.
+
diff --git a/src/proguard/classfile/editor/AccessFixer.java b/src/proguard/classfile/editor/AccessFixer.java
new file mode 100644
index 000000000..d77053137
--- /dev/null
+++ b/src/proguard/classfile/editor/AccessFixer.java
@@ -0,0 +1,180 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ConstantVisitor fixes the access modifiers of all classes and class
+ * members that are referenced by the constants that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AccessFixer
+extends SimplifiedVisitor
+implements ConstantVisitor,
+ ClassVisitor,
+ MemberVisitor
+{
+ private MyReferencedClassFinder referencedClassFinder = new MyReferencedClassFinder();
+
+ private Clazz referencingClass;
+ private Clazz referencedClass;
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ referencingClass = clazz;
+ referencedClass = stringConstant.referencedClass;
+
+ // Make sure the access flags of the referenced class or class member,
+ // if any, are acceptable.
+ stringConstant.referencedClassAccept(this);
+ stringConstant.referencedMemberAccept(this);
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ // Check the bootstrap method.
+ invokeDynamicConstant.bootstrapMethodHandleAccept(clazz, this);
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ // Check the method reference.
+ clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex, this);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ referencingClass = clazz;
+
+ // Remember the specified class, since it might be different from
+ // the referenced class that actually contains the class member.
+ clazz.constantPoolEntryAccept(refConstant.u2classIndex, referencedClassFinder);
+
+ // Make sure the access flags of the referenced class member are
+ // acceptable.
+ refConstant.referencedMemberAccept(this);
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ referencingClass = clazz;
+
+ // Make sure the access flags of the referenced class are acceptable.
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ int currentAccessFlags = programClass.getAccessFlags();
+ int currentAccessLevel = AccessUtil.accessLevel(currentAccessFlags);
+
+ // Compute the required access level.
+ Clazz referencingClass = this.referencingClass;
+ int requiredAccessLevel =
+ inSamePackage(programClass, referencingClass) ? AccessUtil.PACKAGE_VISIBLE :
+ AccessUtil.PUBLIC;
+
+ // Fix the class access flags if necessary.
+ if (currentAccessLevel < requiredAccessLevel)
+ {
+ programClass.u2accessFlags =
+ AccessUtil.replaceAccessFlags(currentAccessFlags,
+ AccessUtil.accessFlags(requiredAccessLevel));
+ }
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitLibraryMember(LibraryClass libraryClass, LibraryMember libraryMember) {}
+
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ int currentAccessFlags = programMember.getAccessFlags();
+ int currentAccessLevel = AccessUtil.accessLevel(currentAccessFlags);
+
+ // Compute the required access level.
+ int requiredAccessLevel =
+ programClass.equals(referencingClass) ? AccessUtil.PRIVATE :
+ inSamePackage(programClass, referencingClass) ? AccessUtil.PACKAGE_VISIBLE :
+ referencedClass.extends_(referencingClass) &&
+ referencingClass.extends_(programClass) ? AccessUtil.PROTECTED :
+ AccessUtil.PUBLIC;
+
+ // Fix the class member access flags if necessary.
+ if (currentAccessLevel < requiredAccessLevel)
+ {
+ programMember.u2accessFlags =
+ AccessUtil.replaceAccessFlags(currentAccessFlags,
+ AccessUtil.accessFlags(requiredAccessLevel));
+ }
+ }
+
+
+ /**
+ * This ConstantVisitor returns the referenced class of the class constant
+ * that it visits.
+ */
+ private class MyReferencedClassFinder
+ extends SimplifiedVisitor
+ implements ConstantVisitor
+ {
+ // Implementations for ConstantVisitor.
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ referencedClass = classConstant.referencedClass;
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean inSamePackage(ProgramClass class1, Clazz class2)
+ {
+ return ClassUtil.internalPackageName(class1.getName()).equals(
+ ClassUtil.internalPackageName(class2.getName()));
+ }
+}
diff --git a/src/proguard/classfile/editor/AnnotationAdder.java b/src/proguard/classfile/editor/AnnotationAdder.java
new file mode 100644
index 000000000..0389ab112
--- /dev/null
+++ b/src/proguard/classfile/editor/AnnotationAdder.java
@@ -0,0 +1,153 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.AnnotationVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AnnotationVisitor adds all annotations that it visits to the given
+ * target annotation element value, target annotation attribute, or target
+ * parameter annotation attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class AnnotationAdder
+extends SimplifiedVisitor
+implements AnnotationVisitor
+{
+ private static final ElementValue[] EMPTY_ELEMENT_VALUES = new ElementValue[0];
+
+
+ private final ProgramClass targetClass;
+ private final AnnotationElementValue targetAnnotationElementValue;
+ private final AnnotationsAttributeEditor annotationsAttributeEditor;
+ private final ParameterAnnotationsAttributeEditor parameterAnnotationsAttributeEditor;
+
+ private final ConstantAdder constantAdder;
+
+
+ /**
+ * Creates a new AnnotationAdder that will copy annotations into the given
+ * target annotation element value.
+ */
+ public AnnotationAdder(ProgramClass targetClass,
+ AnnotationElementValue targetAnnotationElementValue)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotationElementValue = targetAnnotationElementValue;
+ this.annotationsAttributeEditor = null;
+ this.parameterAnnotationsAttributeEditor = null;
+
+ constantAdder = new ConstantAdder(targetClass);
+ }
+
+
+ /**
+ * Creates a new AnnotationAdder that will copy annotations into the given
+ * target annotations attribute.
+ */
+ public AnnotationAdder(ProgramClass targetClass,
+ AnnotationsAttribute targetAnnotationsAttribute)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotationElementValue = null;
+ this.annotationsAttributeEditor = new AnnotationsAttributeEditor(targetAnnotationsAttribute);
+ this.parameterAnnotationsAttributeEditor = null;
+
+ constantAdder = new ConstantAdder(targetClass);
+ }
+
+
+ /**
+ * Creates a new AnnotationAdder that will copy annotations into the given
+ * target parameter annotations attribute.
+ */
+ public AnnotationAdder(ProgramClass targetClass,
+ ParameterAnnotationsAttribute targetParameterAnnotationsAttribute)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotationElementValue = null;
+ this.annotationsAttributeEditor = null;
+ this.parameterAnnotationsAttributeEditor = new ParameterAnnotationsAttributeEditor(targetParameterAnnotationsAttribute);
+
+ constantAdder = new ConstantAdder(targetClass);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ Annotation newAnnotation =
+ new Annotation(constantAdder.addConstant(clazz, annotation.u2typeIndex),
+ 0,
+ annotation.u2elementValuesCount > 0 ?
+ new ElementValue[annotation.u2elementValuesCount] :
+ EMPTY_ELEMENT_VALUES);
+
+ // TODO: Clone array.
+ newAnnotation.referencedClasses = annotation.referencedClasses;
+
+ // Add the element values.
+ annotation.elementValuesAccept(clazz,
+ new ElementValueAdder(targetClass,
+ newAnnotation,
+ false));
+
+ // What's the target?
+ if (targetAnnotationElementValue != null)
+ {
+ // Simply set the completed annotation.
+ targetAnnotationElementValue.annotationValue = newAnnotation;
+ }
+ else
+ {
+ // Add the completed annotation.
+ annotationsAttributeEditor.addAnnotation(newAnnotation);
+ }
+ }
+
+
+ public void visitAnnotation(Clazz clazz, Method method, int parameterIndex, Annotation annotation)
+ {
+ Annotation newAnnotation =
+ new Annotation(constantAdder.addConstant(clazz, annotation.u2typeIndex),
+ 0,
+ annotation.u2elementValuesCount > 0 ?
+ new ElementValue[annotation.u2elementValuesCount] :
+ EMPTY_ELEMENT_VALUES);
+
+ // TODO: Clone array.
+ newAnnotation.referencedClasses = annotation.referencedClasses;
+
+ // Add the element values.
+ annotation.elementValuesAccept(clazz,
+ new ElementValueAdder(targetClass,
+ newAnnotation,
+ false));
+
+ // Add the completed annotation.
+ parameterAnnotationsAttributeEditor.addAnnotation(parameterIndex, newAnnotation);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/AnnotationsAttributeEditor.java b/src/proguard/classfile/editor/AnnotationsAttributeEditor.java
new file mode 100644
index 000000000..a175c3319
--- /dev/null
+++ b/src/proguard/classfile/editor/AnnotationsAttributeEditor.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.annotation.*;
+
+/**
+ * This class can add annotations to a given annotations attribute.
+ * Annotations to be added must have been filled out beforehand.
+ *
+ * @author Eric Lafortune
+ */
+public class AnnotationsAttributeEditor
+{
+ private AnnotationsAttribute targetAnnotationsAttribute;
+
+
+ /**
+ * Creates a new AnnotationsAttributeEditor that will edit annotations in
+ * the given annotations attribute.
+ */
+ public AnnotationsAttributeEditor(AnnotationsAttribute targetAnnotationsAttribute)
+ {
+ this.targetAnnotationsAttribute = targetAnnotationsAttribute;
+ }
+
+
+ /**
+ * Adds a given annotation to the annotations attribute.
+ */
+ public void addAnnotation(Annotation annotation)
+ {
+ int annotationsCount = targetAnnotationsAttribute.u2annotationsCount;
+ Annotation[] annotations = targetAnnotationsAttribute.annotations;
+
+ // Make sure there is enough space for the new annotation.
+ if (annotations.length <= annotationsCount)
+ {
+ targetAnnotationsAttribute.annotations = new Annotation[annotationsCount+1];
+ System.arraycopy(annotations, 0,
+ targetAnnotationsAttribute.annotations, 0,
+ annotationsCount);
+ annotations = targetAnnotationsAttribute.annotations;
+ }
+
+ // Add the annotation.
+ annotations[targetAnnotationsAttribute.u2annotationsCount++] = annotation;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/AttributeAdder.java b/src/proguard/classfile/editor/AttributeAdder.java
new file mode 100644
index 000000000..ad4ecc0af
--- /dev/null
+++ b/src/proguard/classfile/editor/AttributeAdder.java
@@ -0,0 +1,455 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor adds all attributes that it visits to the given
+ * target class, class member, or attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class AttributeAdder
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private static final byte[] EMPTY_BYTES = new byte[0];
+ private static final int[] EMPTY_INTS = new int[0];
+ private static final Attribute[] EMPTY_ATTRIBUTES = new Attribute[0];
+ private static final ExceptionInfo[] EMPTY_EXCEPTIONS = new ExceptionInfo[0];
+
+
+ private final ProgramClass targetClass;
+ private final ProgramMember targetMember;
+ private final CodeAttribute targetCodeAttribute;
+ private final boolean replaceAttributes;
+
+ private final ConstantAdder constantAdder;
+ private final AttributesEditor attributesEditor;
+
+
+ /**
+ * Creates a new AttributeAdder that will copy attributes into the given
+ * target class.
+ */
+ public AttributeAdder(ProgramClass targetClass,
+ boolean replaceAttributes)
+ {
+ this(targetClass, null, null, replaceAttributes);
+ }
+
+
+ /**
+ * Creates a new AttributeAdder that will copy attributes into the given
+ * target class member.
+ */
+ public AttributeAdder(ProgramClass targetClass,
+ ProgramMember targetMember,
+ boolean replaceAttributes)
+ {
+ this(targetClass, targetMember, null, replaceAttributes);
+ }
+
+
+ /**
+ * Creates a new AttributeAdder that will copy attributes into the given
+ * target attribute.
+ */
+ public AttributeAdder(ProgramClass targetClass,
+ ProgramMember targetMember,
+ CodeAttribute targetCodeAttribute,
+ boolean replaceAttributes)
+ {
+ this.targetClass = targetClass;
+ this.targetMember = targetMember;
+ this.targetCodeAttribute = targetCodeAttribute;
+ this.replaceAttributes = replaceAttributes;
+
+ constantAdder = new ConstantAdder(targetClass);
+ attributesEditor = new AttributesEditor(targetClass,
+ targetMember,
+ targetCodeAttribute,
+ replaceAttributes);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ // Create a copy of the attribute.
+ UnknownAttribute newUnknownAttribute =
+ new UnknownAttribute(constantAdder.addConstant(clazz, unknownAttribute.u2attributeNameIndex),
+ unknownAttribute.u4attributeLength,
+ unknownAttribute.info);
+
+ // Add it to the target class.
+ attributesEditor.addAttribute(newUnknownAttribute);
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ // Create a copy of the attribute.
+ SourceFileAttribute newSourceFileAttribute =
+ new SourceFileAttribute(constantAdder.addConstant(clazz, sourceFileAttribute.u2attributeNameIndex),
+ constantAdder.addConstant(clazz, sourceFileAttribute.u2sourceFileIndex));
+
+ // Add it to the target class.
+ attributesEditor.addAttribute(newSourceFileAttribute);
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ // Create a copy of the attribute.
+ SourceDirAttribute newSourceDirAttribute =
+ new SourceDirAttribute(constantAdder.addConstant(clazz, sourceDirAttribute.u2attributeNameIndex),
+ constantAdder.addConstant(clazz, sourceDirAttribute.u2sourceDirIndex));
+
+ // Add it to the target class.
+ attributesEditor.addAttribute(newSourceDirAttribute);
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ // Create a copy of the attribute.
+ InnerClassesAttribute newInnerClassesAttribute =
+ new InnerClassesAttribute(constantAdder.addConstant(clazz, innerClassesAttribute.u2attributeNameIndex),
+ 0,
+ null);
+
+ // Add it to the target class.
+ attributesEditor.addAttribute(newInnerClassesAttribute);
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ // Create a copy of the attribute.
+ EnclosingMethodAttribute newEnclosingMethodAttribute =
+ new EnclosingMethodAttribute(constantAdder.addConstant(clazz, enclosingMethodAttribute.u2attributeNameIndex),
+ constantAdder.addConstant(clazz, enclosingMethodAttribute.u2classIndex),
+ enclosingMethodAttribute.u2nameAndTypeIndex == 0 ? 0 :
+ constantAdder.addConstant(clazz, enclosingMethodAttribute.u2nameAndTypeIndex));
+
+ newEnclosingMethodAttribute.referencedClass = enclosingMethodAttribute.referencedClass;
+ newEnclosingMethodAttribute.referencedMethod = enclosingMethodAttribute.referencedMethod;
+
+ // Add it to the target class.
+ attributesEditor.addAttribute(newEnclosingMethodAttribute);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ // Create a copy of the attribute.
+ DeprecatedAttribute newDeprecatedAttribute =
+ new DeprecatedAttribute(constantAdder.addConstant(clazz, deprecatedAttribute.u2attributeNameIndex));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newDeprecatedAttribute);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ // Create a copy of the attribute.
+ SyntheticAttribute newSyntheticAttribute =
+ new SyntheticAttribute(constantAdder.addConstant(clazz, syntheticAttribute.u2attributeNameIndex));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newSyntheticAttribute);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ // Create a copy of the attribute.
+ SignatureAttribute newSignatureAttribute =
+ new SignatureAttribute(constantAdder.addConstant(clazz, signatureAttribute.u2attributeNameIndex),
+ constantAdder.addConstant(clazz, signatureAttribute.u2signatureIndex));
+
+ newSignatureAttribute.referencedClasses = signatureAttribute.referencedClasses;
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newSignatureAttribute);
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ // Create a copy of the attribute.
+ ConstantValueAttribute newConstantValueAttribute =
+ new ConstantValueAttribute(constantAdder.addConstant(clazz, constantValueAttribute.u2attributeNameIndex),
+ constantAdder.addConstant(clazz, constantValueAttribute.u2constantValueIndex));
+
+ // Add it to the target field.
+ attributesEditor.addAttribute(newConstantValueAttribute);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ // Create a new exceptions attribute.
+ ExceptionsAttribute newExceptionsAttribute =
+ new ExceptionsAttribute(constantAdder.addConstant(clazz, exceptionsAttribute.u2attributeNameIndex),
+ 0,
+ exceptionsAttribute.u2exceptionIndexTableLength > 0 ?
+ new int[exceptionsAttribute.u2exceptionIndexTableLength] :
+ EMPTY_INTS);
+
+ // Add the exceptions.
+ exceptionsAttribute.exceptionEntriesAccept((ProgramClass)clazz,
+ new ExceptionAdder(targetClass,
+ newExceptionsAttribute));
+
+ // Add it to the target method.
+ attributesEditor.addAttribute(newExceptionsAttribute);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Create a new code attribute.
+ CodeAttribute newCodeAttribute =
+ new CodeAttribute(constantAdder.addConstant(clazz, codeAttribute.u2attributeNameIndex),
+ codeAttribute.u2maxStack,
+ codeAttribute.u2maxLocals,
+ 0,
+ EMPTY_BYTES,
+ 0,
+ codeAttribute.u2exceptionTableLength > 0 ?
+ new ExceptionInfo[codeAttribute.u2exceptionTableLength] :
+ EMPTY_EXCEPTIONS,
+ 0,
+ codeAttribute.u2attributesCount > 0 ?
+ new Attribute[codeAttribute.u2attributesCount] :
+ EMPTY_ATTRIBUTES);
+
+ CodeAttributeComposer codeAttributeComposer = new CodeAttributeComposer();
+
+ codeAttributeComposer.beginCodeFragment(codeAttribute.u4codeLength + 32);
+
+ // Add the instructions.
+ codeAttribute.instructionsAccept(clazz,
+ method,
+ new InstructionAdder(targetClass,
+ codeAttributeComposer));
+
+ // Append a label just after the code.
+ codeAttributeComposer.appendLabel(codeAttribute.u4codeLength);
+
+ // Add the exceptions.
+ codeAttribute.exceptionsAccept(clazz,
+ method,
+ new ExceptionInfoAdder(targetClass,
+ codeAttributeComposer));
+
+ codeAttributeComposer.endCodeFragment();
+
+ // Add the attributes.
+ codeAttribute.attributesAccept(clazz,
+ method,
+ new AttributeAdder(targetClass,
+ targetMember,
+ newCodeAttribute,
+ replaceAttributes));
+
+ // Apply these changes to the new code attribute.
+ codeAttributeComposer.visitCodeAttribute(targetClass,
+ (Method)targetMember,
+ newCodeAttribute);
+
+ // Add the completed code attribute to the target method.
+ attributesEditor.addAttribute(newCodeAttribute);
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ // TODO: Implement method.
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ // TODO: Implement method.
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ // Create a new line number table attribute.
+ LineNumberTableAttribute newLineNumberTableAttribute =
+ new LineNumberTableAttribute(constantAdder.addConstant(clazz, lineNumberTableAttribute.u2attributeNameIndex),
+ 0,
+ new LineNumberInfo[lineNumberTableAttribute.u2lineNumberTableLength]);
+
+ // Add the line numbers.
+ lineNumberTableAttribute.lineNumbersAccept(clazz,
+ method,
+ codeAttribute,
+ new LineNumberInfoAdder(newLineNumberTableAttribute));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newLineNumberTableAttribute);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Create a new local variable table attribute.
+ LocalVariableTableAttribute newLocalVariableTableAttribute =
+ new LocalVariableTableAttribute(constantAdder.addConstant(clazz, localVariableTableAttribute.u2attributeNameIndex),
+ 0,
+ new LocalVariableInfo[localVariableTableAttribute.u2localVariableTableLength]);
+
+ // Add the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz,
+ method,
+ codeAttribute,
+ new LocalVariableInfoAdder(targetClass, newLocalVariableTableAttribute));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newLocalVariableTableAttribute);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Create a new local variable type table attribute.
+ LocalVariableTypeTableAttribute newLocalVariableTypeTableAttribute =
+ new LocalVariableTypeTableAttribute(constantAdder.addConstant(clazz, localVariableTypeTableAttribute.u2attributeNameIndex),
+ 0,
+ new LocalVariableTypeInfo[localVariableTypeTableAttribute.u2localVariableTypeTableLength]);
+
+ // Add the local variable types.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz,
+ method,
+ codeAttribute,
+ new LocalVariableTypeInfoAdder(targetClass, newLocalVariableTypeTableAttribute));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newLocalVariableTypeTableAttribute);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ // Create a new annotations attribute.
+ RuntimeVisibleAnnotationsAttribute newAnnotationsAttribute =
+ new RuntimeVisibleAnnotationsAttribute(constantAdder.addConstant(clazz, runtimeVisibleAnnotationsAttribute.u2attributeNameIndex),
+ 0,
+ new Annotation[runtimeVisibleAnnotationsAttribute.u2annotationsCount]);
+
+ // Add the annotations.
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz,
+ new AnnotationAdder(targetClass,
+ newAnnotationsAttribute));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ // Create a new annotations attribute.
+ RuntimeInvisibleAnnotationsAttribute newAnnotationsAttribute =
+ new RuntimeInvisibleAnnotationsAttribute(constantAdder.addConstant(clazz, runtimeInvisibleAnnotationsAttribute.u2attributeNameIndex),
+ 0,
+ new Annotation[runtimeInvisibleAnnotationsAttribute.u2annotationsCount]);
+
+ // Add the annotations.
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz,
+ new AnnotationAdder(targetClass,
+ newAnnotationsAttribute));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute)
+ {
+ // Create a new annotations attribute.
+ RuntimeVisibleParameterAnnotationsAttribute newParameterAnnotationsAttribute =
+ new RuntimeVisibleParameterAnnotationsAttribute(constantAdder.addConstant(clazz, runtimeVisibleParameterAnnotationsAttribute.u2attributeNameIndex),
+ 0,
+ new int[runtimeVisibleParameterAnnotationsAttribute.u2parametersCount],
+ new Annotation[runtimeVisibleParameterAnnotationsAttribute.u2parametersCount][]);
+
+ // Add the annotations.
+ runtimeVisibleParameterAnnotationsAttribute.annotationsAccept(clazz,
+ method,
+ new AnnotationAdder(targetClass,
+ newParameterAnnotationsAttribute));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newParameterAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute)
+ {
+ // Create a new annotations attribute.
+ RuntimeInvisibleParameterAnnotationsAttribute newParameterAnnotationsAttribute =
+ new RuntimeInvisibleParameterAnnotationsAttribute(constantAdder.addConstant(clazz, runtimeInvisibleParameterAnnotationsAttribute.u2attributeNameIndex),
+ 0,
+ new int[runtimeInvisibleParameterAnnotationsAttribute.u2parametersCount],
+ new Annotation[runtimeInvisibleParameterAnnotationsAttribute.u2parametersCount][]);
+
+ // Add the annotations.
+ runtimeInvisibleParameterAnnotationsAttribute.annotationsAccept(clazz,
+ method,
+ new AnnotationAdder(targetClass,
+ newParameterAnnotationsAttribute));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newParameterAnnotationsAttribute);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ // Create a new annotation default attribute.
+ AnnotationDefaultAttribute newAnnotationDefaultAttribute =
+ new AnnotationDefaultAttribute(constantAdder.addConstant(clazz, annotationDefaultAttribute.u2attributeNameIndex),
+ null);
+
+ // Add the annotations.
+ annotationDefaultAttribute.defaultValueAccept(clazz,
+ new ElementValueAdder(targetClass,
+ newAnnotationDefaultAttribute,
+ false));
+
+ // Add it to the target.
+ attributesEditor.addAttribute(newAnnotationDefaultAttribute);
+ }
+}
diff --git a/src/proguard/classfile/editor/AttributeSorter.java b/src/proguard/classfile/editor/AttributeSorter.java
new file mode 100644
index 000000000..23fe02793
--- /dev/null
+++ b/src/proguard/classfile/editor/AttributeSorter.java
@@ -0,0 +1,89 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+import java.util.*;
+
+/**
+ * This ClassVisitor sorts the attributes of the classes that it visits.
+ * The sorting order is based on the types of the attributes.
+ *
+ * @author Eric Lafortune
+ */
+public class AttributeSorter
+extends SimplifiedVisitor
+implements ClassVisitor, MemberVisitor, AttributeVisitor, Comparator
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Sort the attributes.
+ Arrays.sort(programClass.attributes, 0, programClass.u2attributesCount, this);
+
+ // Sort the attributes of the class members.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ // Sort the attributes.
+ Arrays.sort(programMember.attributes, 0, programMember.u2attributesCount, this);
+
+ // Sort the attributes of the attributes.
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Sort the attributes.
+ Arrays.sort(codeAttribute.attributes, 0, codeAttribute.u2attributesCount, this);
+ }
+
+
+ // Implementations for Comparator.
+
+ public int compare(Object object1, Object object2)
+ {
+ Attribute attribute1 = (Attribute)object1;
+ Attribute attribute2 = (Attribute)object2;
+
+ return attribute1.u2attributeNameIndex < attribute2.u2attributeNameIndex ? -1 :
+ attribute1.u2attributeNameIndex > attribute2.u2attributeNameIndex ? 1 :
+ 0;
+ }
+}
diff --git a/src/proguard/classfile/editor/AttributesEditor.java b/src/proguard/classfile/editor/AttributesEditor.java
new file mode 100644
index 000000000..f50b8f127
--- /dev/null
+++ b/src/proguard/classfile/editor/AttributesEditor.java
@@ -0,0 +1,269 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+
+/**
+ * This class can add and delete attributes to and from classes, fields,
+ * methods, and code attributes. Attributes to be added must be filled out
+ * beforehand, including their references to the constant pool. Existing
+ * attributes of the same type are always replaced.
+ *
+ * @author Eric Lafortune
+ */
+public class AttributesEditor
+{
+ private final ProgramClass targetClass;
+ private final ProgramMember targetMember;
+ private final CodeAttribute targetAttribute;
+ private final boolean replaceAttributes;
+
+
+ /**
+ * Creates a new AttributeAdder that will edit attributes in the given
+ * target class.
+ */
+ public AttributesEditor(ProgramClass targetClass,
+ boolean replaceAttributes)
+ {
+ this(targetClass, null, null, replaceAttributes);
+ }
+
+
+ /**
+ * Creates a new AttributeAdder that will edit attributes in the given
+ * target class member.
+ */
+ public AttributesEditor(ProgramClass targetClass,
+ ProgramMember targetMember,
+ boolean replaceAttributes)
+ {
+ this(targetClass, targetMember, null, replaceAttributes);
+ }
+
+
+ /**
+ * Creates a new AttributeAdder that will edit attributes in the given
+ * target code attribute.
+ */
+ public AttributesEditor(ProgramClass targetClass,
+ ProgramMember targetMember,
+ CodeAttribute targetAttribute,
+ boolean replaceAttributes)
+ {
+ this.targetClass = targetClass;
+ this.targetMember = targetMember;
+ this.targetAttribute = targetAttribute;
+ this.replaceAttributes = replaceAttributes;
+ }
+
+
+ /**
+ * Adds the given attribute to the target.
+ */
+ public void addAttribute(Attribute attribute)
+ {
+ // What's the target?
+ if (targetAttribute != null)
+ {
+ // Try to replace an existing attribute.
+ if (!replaceAttributes ||
+ !replaceAttribute(targetAttribute.u2attributesCount,
+ targetAttribute.attributes,
+ attribute))
+ {
+ // Otherwise append the attribute.
+ targetAttribute.attributes =
+ addAttribute(targetAttribute.u2attributesCount,
+ targetAttribute.attributes,
+ attribute);
+
+ targetAttribute.u2attributesCount++;
+ }
+ }
+ else if (targetMember != null)
+ {
+ // Try to replace an existing attribute.
+ if (!replaceAttributes ||
+ !replaceAttribute(targetMember.u2attributesCount,
+ targetMember.attributes,
+ attribute))
+ {
+ // Otherwise append the attribute.
+ targetMember.attributes =
+ addAttribute(targetMember.u2attributesCount,
+ targetMember.attributes,
+ attribute);
+
+ targetMember.u2attributesCount++;
+ }
+ }
+ else
+ {
+ // Try to replace an existing attribute.
+ if (!replaceAttributes ||
+ !replaceAttribute(targetClass.u2attributesCount,
+ targetClass.attributes,
+ attribute))
+ {
+ // Otherwise append the attribute.
+ targetClass.attributes =
+ addAttribute(targetClass.u2attributesCount,
+ targetClass.attributes,
+ attribute);
+
+ targetClass.u2attributesCount++;
+ }
+ }
+ }
+
+
+ /**
+ * Deletes the specified attribute from the target.
+ */
+ public void deleteAttribute(String attributeName)
+ {
+ // What's the target?
+ if (targetAttribute != null)
+ {
+ targetAttribute.u2attributesCount =
+ deleteAttribute(targetAttribute.u2attributesCount,
+ targetAttribute.attributes,
+ attributeName);
+ }
+ else if (targetMember != null)
+ {
+ targetMember.u2attributesCount =
+ deleteAttribute(targetMember.u2attributesCount,
+ targetMember.attributes,
+ attributeName);
+ }
+ else
+ {
+ targetClass.u2attributesCount =
+ deleteAttribute(targetClass.u2attributesCount,
+ targetClass.attributes,
+ attributeName);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Tries put the given attribute in place of an existing attribute of the
+ * same name, returning whether it was present.
+ */
+ private boolean replaceAttribute(int attributesCount,
+ Attribute[] attributes,
+ Attribute attribute)
+ {
+ // Find the attribute with the same name.
+ int index = findAttribute(attributesCount,
+ attributes,
+ attribute.getAttributeName(targetClass));
+ if (index < 0)
+ {
+ return false;
+ }
+
+ attributes[index] = attribute;
+
+ return true;
+ }
+
+
+ /**
+ * Appends the given attribute to the given array of attributes, creating a
+ * new array if necessary.
+ */
+ private Attribute[] addAttribute(int attributesCount,
+ Attribute[] attributes,
+ Attribute attribute)
+ {
+ // Is the array too small to contain the additional attribute?
+ if (attributes.length <= attributesCount)
+ {
+ // Create a new array and copy the attributes into it.
+ Attribute[] newAttributes = new Attribute[attributesCount + 1];
+ System.arraycopy(attributes, 0,
+ newAttributes, 0,
+ attributesCount);
+ attributes = newAttributes;
+ }
+
+ // Append the attribute.
+ attributes[attributesCount] = attribute;
+
+ return attributes;
+ }
+
+
+ /**
+ * Deletes the attributes with the given name from the given array of
+ * attributes, returning the new number of attributes.
+ */
+ private int deleteAttribute(int attributesCount,
+ Attribute[] attributes,
+ String attributeName)
+ {
+ // Find the attribute.
+ int index = findAttribute(attributesCount,
+ attributes,
+ attributeName);
+ if (index < 0)
+ {
+ return attributesCount;
+ }
+
+ // Shift the other attributes in the array.
+ System.arraycopy(attributes, index + 1,
+ attributes, index,
+ attributesCount - index - 1);
+
+ // Clear the last entry in the array.
+ attributes[--attributesCount] = null;
+
+ return attributesCount;
+ }
+
+
+ /**
+ * Finds the index of the attribute with the given name in the given
+ * array of attributes.
+ */
+ private int findAttribute(int attributesCount,
+ Attribute[] attributes,
+ String attributeName)
+ {
+ for (int index = 0; index < attributesCount; index++)
+ {
+ if (attributes[index].getAttributeName(targetClass).equals(attributeName))
+ {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/src/proguard/classfile/editor/BridgeMethodFixer.java b/src/proguard/classfile/editor/BridgeMethodFixer.java
new file mode 100644
index 000000000..2f1120d78
--- /dev/null
+++ b/src/proguard/classfile/editor/BridgeMethodFixer.java
@@ -0,0 +1,117 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This MemberVisitor fixes all inappropriate bridge access flags of the
+ * program methods that it visits, checking whether the methods to which they
+ * bridge have the same name. Some compilers, like in Eclipse and in later
+ * versions of JDK 1.6, complain if they can't find the method with the same
+ * name.
+ *
+ * @author Eric Lafortune
+ */
+public class BridgeMethodFixer
+extends SimplifiedVisitor
+implements MemberVisitor,
+ AttributeVisitor,
+ InstructionVisitor,
+ ConstantVisitor
+{
+ private static final boolean DEBUG = false;
+
+
+ // Return values for the visitor methods.
+ private String bridgedMethodName;
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if ((programMethod.getAccessFlags() & ClassConstants.INTERNAL_ACC_BRIDGE) != 0)
+ {
+ programMethod.attributesAccept(programClass, this);
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Go over the instructions of the bridge method.
+ codeAttribute.instructionsAccept(clazz, method, this);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ switch (constantInstruction.opcode)
+ {
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ // Get the name of the bridged method.
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+
+ // Check if the name is different.
+ if (!method.getName(clazz).equals(bridgedMethodName))
+ {
+ if (DEBUG)
+ {
+ System.out.println("BridgeMethodFixer: ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"] does not bridge to ["+bridgedMethodName+"]");
+ }
+
+ // Clear the bridge flag.
+ ((ProgramMethod)method).u2accessFlags &= ~ClassConstants.INTERNAL_ACC_BRIDGE;
+ }
+ break;
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyMethodrefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ bridgedMethodName = refConstant.getName(clazz);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/ClassEditor.java b/src/proguard/classfile/editor/ClassEditor.java
new file mode 100644
index 000000000..7703c9dc5
--- /dev/null
+++ b/src/proguard/classfile/editor/ClassEditor.java
@@ -0,0 +1,255 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+
+/**
+ * This class can add interfaces and class members to a given class.
+ * Elements to be added must be filled out beforehand, including their
+ * references to the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassEditor
+{
+ private static final boolean DEBUG = false;
+
+ private ProgramClass targetClass;
+
+
+ /**
+ * Creates a new ClassEditor that will edit elements in the given
+ * target class.
+ */
+ public ClassEditor(ProgramClass targetClass)
+ {
+ this.targetClass = targetClass;
+ }
+
+
+ /**
+ * Adds the given interface.
+ */
+ public void addInterface(int interfaceConstantIndex)
+ {
+ int interfacesCount = targetClass.u2interfacesCount;
+ int[] interfaces = targetClass.u2interfaces;
+
+ // Make sure there is enough space for the new interface.
+ if (interfaces.length <= interfacesCount)
+ {
+ targetClass.u2interfaces = new int[interfacesCount+1];
+ System.arraycopy(interfaces, 0,
+ targetClass.u2interfaces, 0,
+ interfacesCount);
+ interfaces = targetClass.u2interfaces;
+ }
+
+ if (DEBUG)
+ {
+ System.out.println(targetClass.getName()+": adding interface ["+targetClass.getClassName(interfaceConstantIndex)+"]");
+ }
+
+ // Add the interface.
+ interfaces[targetClass.u2interfacesCount++] = interfaceConstantIndex;
+ }
+
+ /**
+ * Removes the given interface.
+ */
+ public void removeInterface(int interfaceConstantIndex)
+ {
+ int interfacesCount = targetClass.u2interfacesCount;
+ int[] interfaces = targetClass.u2interfaces;
+
+ int interfaceIndex = findInterfaceIndex(interfaceConstantIndex);
+
+ // Shift the interface entries.
+ System.arraycopy(interfaces, interfaceIndex+1,
+ interfaces, interfaceIndex,
+ interfacesCount - interfaceIndex - 1);
+
+ // Clear the last entry.
+ interfaces[--targetClass.u2interfacesCount] = 0;
+ }
+
+
+ /**
+ * Finds the index of the given interface in the target class.
+ */
+
+ private int findInterfaceIndex(int interfaceConstantIndex)
+ {
+ int interfacesCount = targetClass.u2interfacesCount;
+ int[] interfaces = targetClass.u2interfaces;
+
+ for (int index = 0; index < interfacesCount; index++)
+ {
+ if (interfaces[index] == interfaceConstantIndex)
+ {
+ return index;
+ }
+ }
+
+ return interfacesCount;
+ }
+
+
+ /**
+ * Adds the given field.
+ */
+ public void addField(Field field)
+ {
+ int fieldsCount = targetClass.u2fieldsCount;
+ Field[] fields = targetClass.fields;
+
+ // Make sure there is enough space for the new field.
+ if (fields.length <= fieldsCount)
+ {
+ targetClass.fields = new ProgramField[fieldsCount+1];
+ System.arraycopy(fields, 0,
+ targetClass.fields, 0,
+ fieldsCount);
+ fields = targetClass.fields;
+ }
+
+ if (DEBUG)
+ {
+ System.out.println(targetClass.getName()+": adding field ["+field.getName(targetClass)+" "+field.getDescriptor(targetClass)+"]");
+ }
+
+ // Add the field.
+ fields[targetClass.u2fieldsCount++] = field;
+ }
+
+
+ /**
+ * Removes the given field. Note that removing a field that is still being
+ * referenced can cause unpredictable effects.
+ */
+ public void removeField(Field field)
+ {
+ int fieldsCount = targetClass.u2fieldsCount;
+ Field[] fields = targetClass.fields;
+
+ int fieldIndex = findFieldIndex(field);
+
+ // Shift the field entries.
+ System.arraycopy(fields, fieldIndex+1,
+ fields, fieldIndex,
+ fieldsCount - fieldIndex - 1);
+
+ // Clear the last entry.
+ fields[--targetClass.u2fieldsCount] = null;
+ }
+
+
+ /**
+ * Finds the index of the given field in the target class.
+ */
+
+ private int findFieldIndex(Field field)
+ {
+ int fieldsCount = targetClass.u2fieldsCount;
+ Field[] fields = targetClass.fields;
+
+ for (int index = 0; index < fieldsCount; index++)
+ {
+ if (fields[index].equals(field))
+ {
+ return index;
+ }
+ }
+
+ return fieldsCount;
+ }
+
+
+ /**
+ * Adds the given method.
+ */
+ public void addMethod(Method method)
+ {
+ int methodsCount = targetClass.u2methodsCount;
+ Method[] methods = targetClass.methods;
+
+ // Make sure there is enough space for the new method.
+ if (methods.length <= methodsCount)
+ {
+ targetClass.methods = new ProgramMethod[methodsCount+1];
+ System.arraycopy(methods, 0,
+ targetClass.methods, 0,
+ methodsCount);
+ methods = targetClass.methods;
+ }
+
+ if (DEBUG)
+ {
+ System.out.println(targetClass.getName()+": adding method ["+method.getName(targetClass)+method.getDescriptor(targetClass)+"]");
+ }
+
+ // Add the method.
+ methods[targetClass.u2methodsCount++] = method;
+ }
+
+
+ /**
+ * Removes the given method. Note that removing a method that is still being
+ * referenced can cause unpredictable effects.
+ */
+ public void removeMethod(Method method)
+ {
+ int methodsCount = targetClass.u2methodsCount;
+ Method[] methods = targetClass.methods;
+
+ int methodIndex = findMethodIndex(method);
+
+ // Shift the method entries.
+ System.arraycopy(methods, methodIndex+1,
+ methods, methodIndex,
+ methodsCount - methodIndex - 1);
+
+ // Clear the last entry.
+ methods[--targetClass.u2methodsCount] = null;
+ }
+
+
+ /**
+ * Finds the index of the given method in the target class.
+ */
+
+ private int findMethodIndex(Method method)
+ {
+ int methodsCount = targetClass.u2methodsCount;
+ Method[] methods = targetClass.methods;
+
+ for (int index = 0; index < methodsCount; index++)
+ {
+ if (methods[index].equals(method))
+ {
+ return index;
+ }
+ }
+
+ return methodsCount;
+ }
+}
diff --git a/src/proguard/classfile/editor/ClassElementSorter.java b/src/proguard/classfile/editor/ClassElementSorter.java
new file mode 100644
index 000000000..9875a292b
--- /dev/null
+++ b/src/proguard/classfile/editor/ClassElementSorter.java
@@ -0,0 +1,52 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.ProgramClass;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor sorts the various elements of the classes that it visits:
+ * interfaces, constants, fields, methods, and attributes.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassElementSorter
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final ClassVisitor interfaceSorter = new InterfaceSorter();
+ private final ClassVisitor constantPoolSorter = new ConstantPoolSorter();
+// private ClassVisitor classMemberSorter = new ClassMemberSorter();
+ private final ClassVisitor attributeSorter = new AttributeSorter();
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.accept(constantPoolSorter);
+ programClass.accept(interfaceSorter);
+// programClass.accept(classMemberSorter);
+ programClass.accept(attributeSorter);
+ }
+}
diff --git a/src/proguard/classfile/editor/ClassMemberSorter.java b/src/proguard/classfile/editor/ClassMemberSorter.java
new file mode 100644
index 000000000..ed0b5b14f
--- /dev/null
+++ b/src/proguard/classfile/editor/ClassMemberSorter.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+import java.util.*;
+
+/**
+ * This ClassVisitor sorts the class members of the classes that it visits.
+ * The sorting order is based on the access flags, the names, and the
+ * descriptors.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassMemberSorter implements ClassVisitor, Comparator
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Sort the fields.
+ Arrays.sort(programClass.fields, 0, programClass.u2fieldsCount, this);
+
+ // Sort the methods.
+ Arrays.sort(programClass.methods, 0, programClass.u2methodsCount, this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ }
+
+
+ // Implementations for Comparator.
+
+ public int compare(Object object1, Object object2)
+ {
+ ProgramMember member1 = (ProgramMember)object1;
+ ProgramMember member2 = (ProgramMember)object2;
+
+ return member1.u2accessFlags < member2.u2accessFlags ? -1 :
+ member1.u2accessFlags > member2.u2accessFlags ? 1 :
+ member1.u2nameIndex < member2.u2nameIndex ? -1 :
+ member1.u2nameIndex > member2.u2nameIndex ? 1 :
+ member1.u2descriptorIndex < member2.u2descriptorIndex ? -1 :
+ member1.u2descriptorIndex > member2.u2descriptorIndex ? 1 :
+ 0;
+ }
+}
diff --git a/src/proguard/classfile/editor/ClassReferenceFixer.java b/src/proguard/classfile/editor/ClassReferenceFixer.java
new file mode 100644
index 000000000..1f8b3966e
--- /dev/null
+++ b/src/proguard/classfile/editor/ClassReferenceFixer.java
@@ -0,0 +1,546 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ClassVisitor fixes references of constant pool entries, fields,
+ * methods, and attributes to classes whose names have changed. Descriptors
+ * of member references are not updated yet.
+ *
+ * @see MemberReferenceFixer
+ * @author Eric Lafortune
+ */
+public class ClassReferenceFixer
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ MemberVisitor,
+ AttributeVisitor,
+ InnerClassesInfoVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ private final boolean ensureUniqueMemberNames;
+
+
+ /**
+ * Creates a new ClassReferenceFixer.
+ * @param ensureUniqueMemberNames specifies whether class members whose
+ * descriptor changes should get new, unique
+ * names, in order to avoid naming conflicts
+ * with similar methods.
+ */
+ public ClassReferenceFixer(boolean ensureUniqueMemberNames)
+ {
+ this.ensureUniqueMemberNames = ensureUniqueMemberNames;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Fix the constant pool.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Fix class members.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ // Fix the attributes.
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Fix class members.
+ libraryClass.fieldsAccept(this);
+ libraryClass.methodsAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ // Has the descriptor changed?
+ String descriptor = programField.getDescriptor(programClass);
+ String newDescriptor = newDescriptor(descriptor,
+ programField.referencedClass);
+
+ if (!descriptor.equals(newDescriptor))
+ {
+ ConstantPoolEditor constantPoolEditor =
+ new ConstantPoolEditor(programClass);
+
+ // Update the descriptor.
+ programField.u2descriptorIndex =
+ constantPoolEditor.addUtf8Constant(newDescriptor);
+
+ // Update the name, if requested.
+ if (ensureUniqueMemberNames)
+ {
+ String name = programField.getName(programClass);
+ String newName = newUniqueMemberName(name, descriptor);
+ programField.u2nameIndex =
+ constantPoolEditor.addUtf8Constant(newName);
+ }
+ }
+
+ // Fix the attributes.
+ programField.attributesAccept(programClass, this);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Has the descriptor changed?
+ String descriptor = programMethod.getDescriptor(programClass);
+ String newDescriptor = newDescriptor(descriptor,
+ programMethod.referencedClasses);
+
+ if (!descriptor.equals(newDescriptor))
+ {
+ ConstantPoolEditor constantPoolEditor =
+ new ConstantPoolEditor(programClass);
+
+ // Update the descriptor.
+ programMethod.u2descriptorIndex =
+ constantPoolEditor.addUtf8Constant(newDescriptor);
+
+ // Update the name, if requested.
+ if (ensureUniqueMemberNames)
+ {
+ String name = programMethod.getName(programClass);
+ String newName = newUniqueMemberName(name, descriptor);
+ programMethod.u2nameIndex =
+ constantPoolEditor.addUtf8Constant(newName);
+ }
+ }
+
+ // Fix the attributes.
+ programMethod.attributesAccept(programClass, this);
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ // Has the descriptor changed?
+ String descriptor = libraryField.getDescriptor(libraryClass);
+ String newDescriptor = newDescriptor(descriptor,
+ libraryField.referencedClass);
+
+ // Update the descriptor.
+ libraryField.descriptor = newDescriptor;
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ // Has the descriptor changed?
+ String descriptor = libraryMethod.getDescriptor(libraryClass);
+ String newDescriptor = newDescriptor(descriptor,
+ libraryMethod.referencedClasses);
+
+ // Update the descriptor.
+ libraryMethod.descriptor = newDescriptor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ // Does the string refer to a class, due to a Class.forName construct?
+ Clazz referencedClass = stringConstant.referencedClass;
+ Member referencedMember = stringConstant.referencedMember;
+ if (referencedClass != null &&
+ referencedMember == null)
+ {
+ // Reconstruct the new class name.
+ String externalClassName = stringConstant.getString(clazz);
+ String internalClassName = ClassUtil.internalClassName(externalClassName);
+ String newInternalClassName = newClassName(internalClassName,
+ referencedClass);
+
+ // Update the String entry if required.
+ if (!newInternalClassName.equals(internalClassName))
+ {
+ String newExternalClassName = ClassUtil.externalClassName(newInternalClassName);
+
+ // Refer to a new Utf8 entry.
+ stringConstant.u2stringIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newExternalClassName);
+ }
+ }
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Do we know the referenced class?
+ Clazz referencedClass = classConstant.referencedClass;
+ if (referencedClass != null)
+ {
+ // Has the class name changed?
+ String className = classConstant.getName(clazz);
+ String newClassName = newClassName(className, referencedClass);
+ if (!className.equals(newClassName))
+ {
+ // Refer to a new Utf8 entry.
+ classConstant.u2nameIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newClassName);
+ }
+ }
+ }
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ // Fix the inner class names.
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Fix the attributes.
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Fix the types of the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Fix the signatures of the local variables.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ // Compute the new signature.
+ String signature = clazz.getString(signatureAttribute.u2signatureIndex);
+ String newSignature = newDescriptor(signature,
+ signatureAttribute.referencedClasses);
+
+ if (!signature.equals(newSignature))
+ {
+ signatureAttribute.u2signatureIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newSignature);
+ }
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ // Fix the annotations.
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ // Fix the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ // Fix the annotation.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ // Fix the inner class name.
+ int innerClassIndex = innerClassesInfo.u2innerClassIndex;
+ int innerNameIndex = innerClassesInfo.u2innerNameIndex;
+ if (innerClassIndex != 0 &&
+ innerNameIndex != 0)
+ {
+ String newInnerName = clazz.getClassName(innerClassIndex);
+ int index = newInnerName.lastIndexOf(ClassConstants.INTERNAL_INNER_CLASS_SEPARATOR);
+ if (index >= 0)
+ {
+ innerClassesInfo.u2innerNameIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newInnerName.substring(index + 1));
+ }
+ }
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ // Has the descriptor changed?
+ String descriptor = clazz.getString(localVariableInfo.u2descriptorIndex);
+ String newDescriptor = newDescriptor(descriptor,
+ localVariableInfo.referencedClass);
+
+ if (!descriptor.equals(newDescriptor))
+ {
+ // Refer to a new Utf8 entry.
+ localVariableInfo.u2descriptorIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newDescriptor);
+ }
+ }
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ // Has the signature changed?
+ String signature = clazz.getString(localVariableTypeInfo.u2signatureIndex);
+ String newSignature = newDescriptor(signature,
+ localVariableTypeInfo.referencedClasses);
+
+ if (!signature.equals(newSignature))
+ {
+ localVariableTypeInfo.u2signatureIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newSignature);
+ }
+ }
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ // Compute the new type name.
+ String typeName = clazz.getString(annotation.u2typeIndex);
+ String newTypeName = newDescriptor(typeName,
+ annotation.referencedClasses);
+
+ if (!typeName.equals(newTypeName))
+ {
+ // Refer to a new Utf8 entry.
+ annotation.u2typeIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newTypeName);
+ }
+
+ // Fix the element values.
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ // Compute the new type name.
+ String typeName = clazz.getString(enumConstantElementValue.u2typeNameIndex);
+ String newTypeName = newDescriptor(typeName,
+ enumConstantElementValue.referencedClasses);
+
+ if (!typeName.equals(newTypeName))
+ {
+ // Refer to a new Utf8 entry.
+ enumConstantElementValue.u2typeNameIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newTypeName);
+ }
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ // Compute the new class name.
+ String className = clazz.getString(classElementValue.u2classInfoIndex);
+ String newClassName = newDescriptor(className,
+ classElementValue.referencedClasses);
+
+ if (!className.equals(newClassName))
+ {
+ // Refer to a new Utf8 entry.
+ classElementValue.u2classInfoIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newClassName);
+ }
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ // Fix the annotation.
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ // Fix the element values.
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ }
+
+
+ // Small utility methods.
+
+ private static String newDescriptor(String descriptor,
+ Clazz referencedClass)
+ {
+ // If there is no referenced class, the descriptor won't change.
+ if (referencedClass == null)
+ {
+ return descriptor;
+ }
+
+ // Unravel and reconstruct the class element of the descriptor.
+ DescriptorClassEnumeration descriptorClassEnumeration =
+ new DescriptorClassEnumeration(descriptor);
+
+ StringBuffer newDescriptorBuffer = new StringBuffer(descriptor.length());
+ newDescriptorBuffer.append(descriptorClassEnumeration.nextFluff());
+
+ // Only if the descriptor contains a class name (e.g. with an array of
+ // primitive types), the descriptor can change.
+ if (descriptorClassEnumeration.hasMoreClassNames())
+ {
+ String className = descriptorClassEnumeration.nextClassName();
+ String fluff = descriptorClassEnumeration.nextFluff();
+
+ String newClassName = newClassName(className,
+ referencedClass);
+
+ newDescriptorBuffer.append(newClassName);
+ newDescriptorBuffer.append(fluff);
+ }
+
+ return newDescriptorBuffer.toString();
+ }
+
+
+ private static String newDescriptor(String descriptor,
+ Clazz[] referencedClasses)
+ {
+ // If there are no referenced classes, the descriptor won't change.
+ if (referencedClasses == null ||
+ referencedClasses.length == 0)
+ {
+ return descriptor;
+ }
+
+ // Unravel and reconstruct the class elements of the descriptor.
+ DescriptorClassEnumeration descriptorClassEnumeration =
+ new DescriptorClassEnumeration(descriptor);
+
+ StringBuffer newDescriptorBuffer = new StringBuffer(descriptor.length());
+ newDescriptorBuffer.append(descriptorClassEnumeration.nextFluff());
+
+ int index = 0;
+ while (descriptorClassEnumeration.hasMoreClassNames())
+ {
+ String className = descriptorClassEnumeration.nextClassName();
+ boolean isInnerClassName = descriptorClassEnumeration.isInnerClassName();
+ String fluff = descriptorClassEnumeration.nextFluff();
+
+ String newClassName = newClassName(className,
+ referencedClasses[index++]);
+
+ // Strip the outer class name again, if it's an inner class.
+ if (isInnerClassName)
+ {
+ newClassName =
+ newClassName.substring(newClassName.lastIndexOf(ClassConstants.INTERNAL_INNER_CLASS_SEPARATOR)+1);
+ }
+
+ newDescriptorBuffer.append(newClassName);
+ newDescriptorBuffer.append(fluff);
+ }
+
+ return newDescriptorBuffer.toString();
+ }
+
+
+ /**
+ * Returns a unique class member name, based on the given name and descriptor.
+ */
+ private String newUniqueMemberName(String name, String descriptor)
+ {
+ return name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT) ?
+ ClassConstants.INTERNAL_METHOD_NAME_INIT :
+ name + ClassConstants.SPECIAL_MEMBER_SEPARATOR + Long.toHexString(Math.abs((descriptor).hashCode()));
+ }
+
+
+ /**
+ * Returns the new class name based on the given class name and the new
+ * name of the given referenced class. Class names of array types
+ * are handled properly.
+ */
+ private static String newClassName(String className,
+ Clazz referencedClass)
+ {
+ // If there is no referenced class, the class name won't change.
+ if (referencedClass == null)
+ {
+ return className;
+ }
+
+ // Reconstruct the class name.
+ String newClassName = referencedClass.getName();
+
+ // Is it an array type?
+ if (className.charAt(0) == ClassConstants.INTERNAL_TYPE_ARRAY)
+ {
+ // Add the array prefixes and suffix "[L...;".
+ newClassName =
+ className.substring(0, className.indexOf(ClassConstants.INTERNAL_TYPE_CLASS_START)+1) +
+ newClassName +
+ ClassConstants.INTERNAL_TYPE_CLASS_END;
+ }
+
+ return newClassName;
+ }
+}
diff --git a/src/proguard/classfile/editor/CodeAttributeComposer.java b/src/proguard/classfile/editor/CodeAttributeComposer.java
new file mode 100644
index 000000000..c59b7123b
--- /dev/null
+++ b/src/proguard/classfile/editor/CodeAttributeComposer.java
@@ -0,0 +1,918 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.preverification.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.util.ArrayUtil;
+
+import java.util.Arrays;
+
+/**
+ * This AttributeVisitor accumulates instructions and exceptions, and then
+ * copies them into code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class CodeAttributeComposer
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ExceptionInfoVisitor,
+ StackMapFrameVisitor,
+ VerificationTypeVisitor,
+ LineNumberInfoVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ public static boolean DEBUG = false;
+ //*/
+
+
+ private static final int MAXIMUM_LEVELS = 32;
+ private static final int INVALID = -1;
+
+
+ private final boolean allowExternalExceptionHandlers;
+ private final boolean shrinkInstructions;
+
+ private int maximumCodeLength;
+ private int codeLength;
+ private int exceptionTableLength;
+ private int level = -1;
+
+ private byte[] code = new byte[ClassConstants.TYPICAL_CODE_LENGTH];
+ private int[] oldInstructionOffsets = new int[ClassConstants.TYPICAL_CODE_LENGTH];
+
+ private final int[] codeFragmentOffsets = new int[MAXIMUM_LEVELS];
+ private final int[] codeFragmentLengths = new int[MAXIMUM_LEVELS];
+ private final int[][] instructionOffsetMap = new int[MAXIMUM_LEVELS][ClassConstants.TYPICAL_CODE_LENGTH + 1];
+
+ private ExceptionInfo[] exceptionTable = new ExceptionInfo[ClassConstants.TYPICAL_EXCEPTION_TABLE_LENGTH];
+
+ private int expectedStackMapFrameOffset;
+
+ private final StackSizeUpdater stackSizeUpdater = new StackSizeUpdater();
+ private final VariableSizeUpdater variableSizeUpdater = new VariableSizeUpdater();
+ private final InstructionWriter instructionWriter = new InstructionWriter();
+
+
+ /**
+ * Creates a new CodeAttributeComposer that doesn't allow external exception
+ * handlers and that automatically shrinks instructions.
+ */
+ public CodeAttributeComposer()
+ {
+ this(false, true);
+ }
+
+
+ /**
+ * Creates a new CodeAttributeComposer.
+ * @param allowExternalExceptionHandlers specifies whether exception
+ * handlers can lie outside the code
+ * fragment in which exceptions are
+ * defined.
+ * @param shrinkInstructions specifies whether instructions
+ * should automatically be shrunk
+ * before being written.
+ */
+ public CodeAttributeComposer(boolean allowExternalExceptionHandlers,
+ boolean shrinkInstructions)
+ {
+ this.allowExternalExceptionHandlers = allowExternalExceptionHandlers;
+ this.shrinkInstructions = shrinkInstructions;
+ }
+
+
+ /**
+ * Starts a new code definition.
+ */
+ public void reset()
+ {
+ maximumCodeLength = 0;
+ codeLength = 0;
+ exceptionTableLength = 0;
+ level = -1;
+
+ instructionWriter.reset(ClassConstants.TYPICAL_CODE_LENGTH);
+ }
+
+
+ /**
+ * Starts a new code fragment. Branch instructions that are added are
+ * assumed to be relative within such code fragments.
+ * @param maximumCodeFragmentLength the maximum length of the code that will
+ * be added as part of this fragment (more
+ * precisely, the maximum old instruction
+ * offset or label that is specified, plus
+ * one).
+ */
+ public void beginCodeFragment(int maximumCodeFragmentLength)
+ {
+ level++;
+
+ if (level >= MAXIMUM_LEVELS)
+ {
+ throw new IllegalArgumentException("Maximum number of code fragment levels exceeded ["+level+"]");
+ }
+
+ // Make sure there is sufficient space for adding the code fragment.
+ // It's only a rough initial estimate for the code length, not even
+ // necessarily a length expressed in bytes.
+ maximumCodeLength += maximumCodeFragmentLength;
+
+ ensureCodeLength(maximumCodeLength);
+
+ // Try to reuse the previous array for this code fragment.
+ if (instructionOffsetMap[level].length <= maximumCodeFragmentLength)
+ {
+ instructionOffsetMap[level] = new int[maximumCodeFragmentLength + 1];
+ }
+
+ // Initialize the offset map.
+ for (int index = 0; index <= maximumCodeFragmentLength; index++)
+ {
+ instructionOffsetMap[level][index] = INVALID;
+ }
+
+ // Remember the location of the code fragment.
+ codeFragmentOffsets[level] = codeLength;
+ codeFragmentLengths[level] = maximumCodeFragmentLength;
+ }
+
+
+ /**
+ * Appends the given instruction with the given old offset.
+ * Branch instructions must fit, for instance by enabling automatic
+ * shrinking of instructions.
+ * @param oldInstructionOffset the old offset of the instruction, to which
+ * branches and other references in the current
+ * code fragment are pointing.
+ * @param instruction the instruction to be appended.
+ */
+ public void appendInstruction(int oldInstructionOffset,
+ Instruction instruction)
+ {
+ if (shrinkInstructions)
+ {
+ instruction = instruction.shrink();
+ }
+
+ if (DEBUG)
+ {
+ println("["+codeLength+"] <- ", instruction.toString(oldInstructionOffset));
+ }
+
+ // Make sure the code and offset arrays are large enough.
+ int newCodeLength = codeLength + instruction.length(codeLength);
+
+ ensureCodeLength(newCodeLength);
+
+ // Remember the old offset of the appended instruction.
+ oldInstructionOffsets[codeLength] = oldInstructionOffset;
+
+ // Fill out the new offset of the appended instruction.
+ instructionOffsetMap[level][oldInstructionOffset] = codeLength;
+
+ // Write the instruction. The instruction writer may widen it later on,
+ // if necessary.
+ instruction.accept(null,
+ null,
+ new CodeAttribute(0, 0, 0, 0, code, 0, null, 0, null),
+ codeLength,
+ instructionWriter);
+ //instruction.write(code, codeLength);
+
+ // Continue appending at the next instruction offset.
+ codeLength = newCodeLength;
+ }
+
+
+ /**
+ * Appends the given label with the given old offset.
+ * @param oldInstructionOffset the old offset of the label, to which
+ * branches and other references in the current
+ * code fragment are pointing.
+ */
+ public void appendLabel(int oldInstructionOffset)
+ {
+ if (DEBUG)
+ {
+ println("["+codeLength+"] <- ", "[" + oldInstructionOffset + "] (label)");
+ }
+
+ // Make sure the code and offset arrays are large enough.
+ ensureCodeLength(codeLength + 1);
+
+ // Remember the old offset of the following instruction.
+ oldInstructionOffsets[codeLength] = oldInstructionOffset;
+
+ // Fill out the new offset of the following instruction.
+ instructionOffsetMap[level][oldInstructionOffset] = codeLength;
+ }
+
+
+ /**
+ * Appends the given instruction without defined offsets.
+ * @param instructions the instructions to be appended.
+ */
+ public void appendInstructions(Instruction[] instructions)
+ {
+ for (int index = 0; index < instructions.length; index++)
+ {
+ appendInstruction(instructions[index]);
+ }
+ }
+
+
+ /**
+ * Appends the given instruction without a defined offset.
+ * Branch instructions should have a label, to allow computing the
+ * new relative offset.
+ * Branch instructions must fit, for instance by enabling automatic
+ * shrinking of instructions.
+ * @param instruction the instruction to be appended.
+ */
+ public void appendInstruction(Instruction instruction)
+ {
+ if (shrinkInstructions)
+ {
+ instruction = instruction.shrink();
+ }
+
+ if (DEBUG)
+ {
+ println("["+codeLength+"] <- ", instruction.toString());
+ }
+
+ // Make sure the code array is large enough.
+ int newCodeLength = codeLength + instruction.length(codeLength);
+
+ ensureCodeLength(newCodeLength);
+
+ // Write the instruction. The instruction writer may widen it later on,
+ // if necessary.
+ instruction.accept(null,
+ null,
+ new CodeAttribute(0, 0, 0, 0, code, 0, null, 0, null),
+ codeLength,
+ instructionWriter);
+ //instruction.write(code, codeLength);
+
+ // Continue appending at the next instruction offset.
+ codeLength = newCodeLength;
+ }
+
+
+ /**
+ * Appends the given exception to the exception table.
+ * @param exceptionInfo the exception to be appended.
+ */
+ public void appendException(ExceptionInfo exceptionInfo)
+ {
+ if (DEBUG)
+ {
+ print(" ", "Exception ["+exceptionInfo.u2startPC+" -> "+exceptionInfo.u2endPC+": "+exceptionInfo.u2handlerPC+"]");
+ }
+
+ // Remap the exception right away.
+ visitExceptionInfo(null, null, null, exceptionInfo);
+
+ if (DEBUG)
+ {
+ System.out.println(" -> ["+exceptionInfo.u2startPC+" -> "+exceptionInfo.u2endPC+": "+exceptionInfo.u2handlerPC+"]");
+ }
+
+ // Don't add the exception if its instruction range is empty.
+ if (exceptionInfo.u2startPC == exceptionInfo.u2endPC)
+ {
+ if (DEBUG)
+ {
+ println(" ", " (not added because of empty instruction range)");
+ }
+
+ return;
+ }
+
+ // Add the exception.
+ exceptionTable =
+ (ExceptionInfo[])ArrayUtil.add(exceptionTable,
+ exceptionTableLength++,
+ exceptionInfo);
+ }
+
+
+ /**
+ * Wraps up the current code fragment, continuing with the previous one on
+ * the stack.
+ */
+ public void endCodeFragment()
+ {
+ if (level < 0)
+ {
+ throw new IllegalArgumentException("Code fragment not begun ["+level+"]");
+ }
+
+ // Remap the instructions of the code fragment.
+ int instructionOffset = codeFragmentOffsets[level];
+ while (instructionOffset < codeLength)
+ {
+ // Get the next instruction.
+ Instruction instruction = InstructionFactory.create(code, instructionOffset);
+
+ // Does this instruction still have to be remapped?
+ if (oldInstructionOffsets[instructionOffset] >= 0)
+ {
+ // Adapt the instruction for its new offset.
+ instruction.accept(null, null, null, instructionOffset, this);
+
+ // Write the instruction back. The instruction writer may still
+ // widen it later on, if necessary.
+ instruction.accept(null,
+ null,
+ new CodeAttribute(0, 0, 0, 0, code, 0, null, 0, null),
+ instructionOffset,
+ instructionWriter);
+ //instruction.write(code, codeLength);
+
+ // Don't remap this instruction again.
+ oldInstructionOffsets[instructionOffset] = -1;
+ }
+
+ // Continue remapping at the next instruction offset.
+ instructionOffset += instruction.length(instructionOffset);
+ }
+
+ // Correct the estimated maximum code length, now that we know the
+ // actual length of this code fragment.
+ maximumCodeLength += codeLength - codeFragmentOffsets[level] -
+ codeFragmentLengths[level];
+
+ // Try to remap the exception handlers that couldn't be remapped before.
+ if (allowExternalExceptionHandlers)
+ {
+ for (int index = 0; index < exceptionTableLength; index++)
+ {
+ ExceptionInfo exceptionInfo = exceptionTable[index];
+
+ // Unmapped exception handlers are still negated.
+ int handlerPC = -exceptionInfo.u2handlerPC;
+ if (handlerPC > 0)
+ {
+ if (remappableExceptionHandler(handlerPC))
+ {
+ exceptionInfo.u2handlerPC = newInstructionOffset(handlerPC);
+ }
+ else if (level == 0)
+ {
+ throw new IllegalStateException("Couldn't remap exception handler offset ["+handlerPC+"]");
+ }
+ }
+ }
+ }
+
+ level--;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (DEBUG)
+ {
+ System.out.println("CodeAttributeComposer: putting results in ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ }
+
+ if (level != -1)
+ {
+ throw new IllegalArgumentException("Code fragment not ended ["+level+"]");
+ }
+
+ level++;
+
+ // Make sure the code attribute has sufficient space for the composed
+ // code.
+ if (codeAttribute.u4codeLength < codeLength)
+ {
+ codeAttribute.code = new byte[codeLength];
+ }
+
+ // Copy the composed code over into the code attribute.
+ codeAttribute.u4codeLength = codeLength;
+ System.arraycopy(code, 0, codeAttribute.code, 0, codeLength);
+
+ // Remove exceptions with empty code blocks (done before).
+ //exceptionTableLength =
+ // removeEmptyExceptions(exceptionTable, exceptionTableLength);
+
+ // Make sure the exception table has sufficient space for the composed
+ // exceptions.
+ if (codeAttribute.exceptionTable.length < exceptionTableLength)
+ {
+ codeAttribute.exceptionTable = new ExceptionInfo[exceptionTableLength];
+ }
+
+ // Copy the exception table.
+ codeAttribute.u2exceptionTableLength = exceptionTableLength;
+ System.arraycopy(exceptionTable, 0, codeAttribute.exceptionTable, 0, exceptionTableLength);
+
+ // Update the maximum stack size and local variable frame size.
+ stackSizeUpdater.visitCodeAttribute(clazz, method, codeAttribute);
+ variableSizeUpdater.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Remap the line number table and the local variable table.
+ codeAttribute.attributesAccept(clazz, method, this);
+
+ // Remap the exception table (done before).
+ //codeAttribute.exceptionsAccept(clazz, method, this);
+
+ // Remove exceptions with empty code blocks (done before).
+ //codeAttribute.u2exceptionTableLength =
+ // removeEmptyExceptions(codeAttribute.exceptionTable,
+ // codeAttribute.u2exceptionTableLength);
+
+ // Make sure instructions are widened if necessary.
+ instructionWriter.visitCodeAttribute(clazz, method, codeAttribute);
+
+ level--;
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ // Remap all stack map entries.
+ expectedStackMapFrameOffset = -1;
+ stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ // Remap all stack map table entries.
+ expectedStackMapFrameOffset = 0;
+ stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ // Remap all line number table entries.
+ lineNumberTableAttribute.lineNumbersAccept(clazz, method, codeAttribute, this);
+
+ // Remove line numbers with empty code blocks.
+ lineNumberTableAttribute.u2lineNumberTableLength =
+ removeEmptyLineNumbers(lineNumberTableAttribute.lineNumberTable,
+ lineNumberTableAttribute.u2lineNumberTableLength,
+ codeAttribute.u4codeLength);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Remap all local variable table entries.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+
+ // Remove local variables with empty code blocks.
+ localVariableTableAttribute.u2localVariableTableLength =
+ removeEmptyLocalVariables(localVariableTableAttribute.localVariableTable,
+ localVariableTableAttribute.u2localVariableTableLength,
+ codeAttribute.u2maxLocals);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Remap all local variable table entries.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+
+ // Remove local variables with empty code blocks.
+ localVariableTypeTableAttribute.u2localVariableTypeTableLength =
+ removeEmptyLocalVariableTypes(localVariableTypeTableAttribute.localVariableTypeTable,
+ localVariableTypeTableAttribute.u2localVariableTypeTableLength,
+ codeAttribute.u2maxLocals);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ // Adjust the branch offset.
+ branchInstruction.branchOffset = newBranchOffset(offset,
+ branchInstruction.branchOffset);
+ }
+
+
+ public void visitAnySwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SwitchInstruction switchInstruction)
+ {
+ // Adjust the default jump offset.
+ switchInstruction.defaultOffset = newBranchOffset(offset,
+ switchInstruction.defaultOffset);
+
+ // Adjust the jump offsets.
+ updateJumpOffsets(offset,
+ switchInstruction.jumpOffsets);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ // Remap the code offsets. Note that the instruction offset map also has
+ // an entry for the first offset after the code, for u2endPC.
+ exceptionInfo.u2startPC = newInstructionOffset(exceptionInfo.u2startPC);
+ exceptionInfo.u2endPC = newInstructionOffset(exceptionInfo.u2endPC);
+
+ // See if we can remap the handler right away. Unmapped exception
+ // handlers are negated, in order to mark them as external.
+ int handlerPC = exceptionInfo.u2handlerPC;
+ exceptionInfo.u2handlerPC =
+ !allowExternalExceptionHandlers ||
+ remappableExceptionHandler(handlerPC) ?
+ newInstructionOffset(handlerPC) :
+ -handlerPC;
+ }
+
+
+ // Implementations for StackMapFrameVisitor.
+
+ public void visitAnyStackMapFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrame stackMapFrame)
+ {
+ // Remap the stack map frame offset.
+ int stackMapFrameOffset = newInstructionOffset(offset);
+
+ int offsetDelta = stackMapFrameOffset;
+
+ // Compute the offset delta if the frame is part of a stack map frame
+ // table (for JDK 6.0) instead of a stack map (for Java Micro Edition).
+ if (expectedStackMapFrameOffset >= 0)
+ {
+ offsetDelta -= expectedStackMapFrameOffset;
+
+ expectedStackMapFrameOffset = stackMapFrameOffset + 1;
+ }
+
+ stackMapFrame.u2offsetDelta = offsetDelta;
+ }
+
+
+ public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)
+ {
+ // Remap the stack map frame offset.
+ visitAnyStackMapFrame(clazz, method, codeAttribute, offset, sameOneFrame);
+
+ // Remap the verification type offset.
+ sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame)
+ {
+ // Remap the stack map frame offset.
+ visitAnyStackMapFrame(clazz, method, codeAttribute, offset, moreZeroFrame);
+
+ // Remap the verification type offsets.
+ moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame)
+ {
+ // Remap the stack map frame offset.
+ visitAnyStackMapFrame(clazz, method, codeAttribute, offset, fullFrame);
+
+ // Remap the verification type offsets.
+ fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this);
+ fullFrame.stackAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for VerificationTypeVisitor.
+
+ public void visitAnyVerificationType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationType verificationType) {}
+
+
+ public void visitUninitializedType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedType uninitializedType)
+ {
+ // Remap the offset of the 'new' instruction.
+ uninitializedType.u2newInstructionOffset = newInstructionOffset(uninitializedType.u2newInstructionOffset);
+ }
+
+
+ // Implementations for LineNumberInfoVisitor.
+
+ public void visitLineNumberInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberInfo lineNumberInfo)
+ {
+ // Remap the code offset.
+ lineNumberInfo.u2startPC = newInstructionOffset(lineNumberInfo.u2startPC);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ // Remap the code offset and length.
+ // TODO: The local variable frame might not be strictly preserved.
+ int startPC = newInstructionOffset(localVariableInfo.u2startPC);
+ int endPC = newInstructionOffset(localVariableInfo.u2startPC +
+ localVariableInfo.u2length);
+
+ localVariableInfo.u2startPC = startPC;
+ localVariableInfo.u2length = endPC - startPC;
+ }
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ // Remap the code offset and length.
+ // TODO: The local variable frame might not be strictly preserved.
+ int startPC = newInstructionOffset(localVariableTypeInfo.u2startPC);
+ int endPC = newInstructionOffset(localVariableTypeInfo.u2startPC +
+ localVariableTypeInfo.u2length);
+
+ localVariableTypeInfo.u2startPC = startPC;
+ localVariableTypeInfo.u2length = endPC - startPC;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Make sure the code arrays have at least the given size.
+ */
+ private void ensureCodeLength(int newCodeLength)
+ {
+ if (code.length < newCodeLength)
+ {
+ // Add 20% to avoid extending the arrays too often.
+ newCodeLength = newCodeLength * 6 / 5;
+
+ code = ArrayUtil.extendArray(code, newCodeLength);
+ oldInstructionOffsets = ArrayUtil.extendArray(oldInstructionOffsets, newCodeLength);
+
+ instructionWriter.extend(newCodeLength);
+ }
+ }
+
+
+ /**
+ * Adjusts the given jump offsets for the instruction at the given offset.
+ */
+ private void updateJumpOffsets(int offset, int[] jumpOffsets)
+ {
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ jumpOffsets[index] = newBranchOffset(offset, jumpOffsets[index]);
+ }
+ }
+
+
+ /**
+ * Computes the new branch offset for the instruction at the given new offset
+ * with the given old branch offset.
+ */
+ private int newBranchOffset(int newInstructionOffset, int oldBranchOffset)
+ {
+ if (newInstructionOffset < 0 ||
+ newInstructionOffset > codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+newInstructionOffset +"] in code with length ["+codeLength+"]");
+ }
+
+ int oldInstructionOffset = oldInstructionOffsets[newInstructionOffset];
+
+ return newInstructionOffset(oldInstructionOffset + oldBranchOffset) -
+ newInstructionOffset(oldInstructionOffset);
+ }
+
+
+ /**
+ * Computes the new instruction offset for the instruction at the given old
+ * offset.
+ */
+ private int newInstructionOffset(int oldInstructionOffset)
+ {
+ if (oldInstructionOffset < 0 ||
+ oldInstructionOffset > codeFragmentLengths[level])
+ {
+ throw new IllegalArgumentException("Instruction offset ["+oldInstructionOffset +"] out of range in code fragment with length ["+codeFragmentLengths[level]+"] at level "+level);
+ }
+
+ int newInstructionOffset = instructionOffsetMap[level][oldInstructionOffset];
+ if (newInstructionOffset == INVALID)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+oldInstructionOffset +"] in code fragment at level "+level);
+ }
+
+ return newInstructionOffset;
+ }
+
+
+ /**
+ * Returns whether the given old exception handler can be remapped in the
+ * current code fragment.
+ */
+ private boolean remappableExceptionHandler(int oldInstructionOffset)
+ {
+ // Can we index in the array?
+ if (oldInstructionOffset > codeFragmentLengths[level])
+ {
+ return false;
+ }
+
+ // Do we have a valid new instruction offset, but not yet right after
+ // the code? That offset is only labeled for mapping try blocks, not
+ // for mapping handlers.
+ int newInstructionOffset =
+ instructionOffsetMap[level][oldInstructionOffset];
+
+ return newInstructionOffset > INVALID &&
+ newInstructionOffset < codeLength;
+ }
+
+
+ /**
+ * Returns the given list of exceptions, without the ones that have empty
+ * code blocks.
+ */
+ private int removeEmptyExceptions(ExceptionInfo[] exceptionInfos,
+ int exceptionInfoCount)
+ {
+ // Overwrite all empty exceptions.
+ int newIndex = 0;
+ for (int index = 0; index < exceptionInfoCount; index++)
+ {
+ ExceptionInfo exceptionInfo = exceptionInfos[index];
+ if (exceptionInfo.u2startPC < exceptionInfo.u2endPC)
+ {
+ exceptionInfos[newIndex++] = exceptionInfo;
+ }
+ }
+
+ // Clear the unused array entries.
+ Arrays.fill(exceptionInfos, newIndex, exceptionInfoCount, null);
+
+ return newIndex;
+ }
+
+
+ /**
+ * Returns the given list of line numbers, without the ones that have empty
+ * code blocks or that exceed the code size.
+ */
+ private int removeEmptyLineNumbers(LineNumberInfo[] lineNumberInfos,
+ int lineNumberInfoCount,
+ int codeLength)
+ {
+ // Overwrite all empty line number entries.
+ int newIndex = 0;
+ for (int index = 0; index < lineNumberInfoCount; index++)
+ {
+ LineNumberInfo lineNumberInfo = lineNumberInfos[index];
+ int startPC = lineNumberInfo.u2startPC;
+ if (startPC < codeLength &&
+ (index == 0 || startPC > lineNumberInfos[index-1].u2startPC))
+ {
+ lineNumberInfos[newIndex++] = lineNumberInfo;
+ }
+ }
+
+ // Clear the unused array entries.
+ Arrays.fill(lineNumberInfos, newIndex, lineNumberInfoCount, null);
+
+ return newIndex;
+ }
+
+
+ /**
+ * Returns the given list of local variables, without the ones that have empty
+ * code blocks or that exceed the actual number of local variables.
+ */
+ private int removeEmptyLocalVariables(LocalVariableInfo[] localVariableInfos,
+ int localVariableInfoCount,
+ int maxLocals)
+ {
+ // Overwrite all empty local variable entries.
+ int newIndex = 0;
+ for (int index = 0; index < localVariableInfoCount; index++)
+ {
+ LocalVariableInfo localVariableInfo = localVariableInfos[index];
+ if (localVariableInfo.u2length > 0 &&
+ localVariableInfo.u2index < maxLocals)
+ {
+ localVariableInfos[newIndex++] = localVariableInfo;
+ }
+ }
+
+ // Clear the unused array entries.
+ Arrays.fill(localVariableInfos, newIndex, localVariableInfoCount, null);
+
+ return newIndex;
+ }
+
+
+ /**
+ * Returns the given list of local variable types, without the ones that
+ * have empty code blocks or that exceed the actual number of local variables.
+ */
+ private int removeEmptyLocalVariableTypes(LocalVariableTypeInfo[] localVariableTypeInfos,
+ int localVariableTypeInfoCount,
+ int maxLocals)
+ {
+ // Overwrite all empty local variable type entries.
+ int newIndex = 0;
+ for (int index = 0; index < localVariableTypeInfoCount; index++)
+ {
+ LocalVariableTypeInfo localVariableTypeInfo = localVariableTypeInfos[index];
+ if (localVariableTypeInfo.u2length > 0 &&
+ localVariableTypeInfo.u2index < maxLocals)
+ {
+ localVariableTypeInfos[newIndex++] = localVariableTypeInfo;
+ }
+ }
+
+ // Clear the unused array entries.
+ Arrays.fill(localVariableTypeInfos, newIndex, localVariableTypeInfoCount, null);
+
+ return newIndex;
+ }
+
+
+ private void println(String string1, String string2)
+ {
+ print(string1, string2);
+
+ System.out.println();
+ }
+
+ private void print(String string1, String string2)
+ {
+ System.out.print(string1);
+
+ for (int index = 0; index < level; index++)
+ {
+ System.out.print(" ");
+ }
+
+ System.out.print(string2);
+ }
+
+
+ public static void main(String[] args)
+ {
+ CodeAttributeComposer composer = new CodeAttributeComposer();
+
+ composer.beginCodeFragment(4);
+ composer.appendInstruction(0, new SimpleInstruction(InstructionConstants.OP_ICONST_0));
+ composer.appendInstruction(1, new VariableInstruction(InstructionConstants.OP_ISTORE, 0));
+ composer.appendInstruction(2, new BranchInstruction(InstructionConstants.OP_GOTO, 1));
+
+ composer.beginCodeFragment(4);
+ composer.appendInstruction(0, new VariableInstruction(InstructionConstants.OP_IINC, 0, 1));
+ composer.appendInstruction(1, new VariableInstruction(InstructionConstants.OP_ILOAD, 0));
+ composer.appendInstruction(2, new SimpleInstruction(InstructionConstants.OP_ICONST_5));
+ composer.appendInstruction(3, new BranchInstruction(InstructionConstants.OP_IFICMPLT, -3));
+ composer.endCodeFragment();
+
+ composer.appendInstruction(3, new SimpleInstruction(InstructionConstants.OP_RETURN));
+ composer.endCodeFragment();
+ }
+}
diff --git a/src/proguard/classfile/editor/CodeAttributeEditor.java b/src/proguard/classfile/editor/CodeAttributeEditor.java
new file mode 100644
index 000000000..337e0d4ef
--- /dev/null
+++ b/src/proguard/classfile/editor/CodeAttributeEditor.java
@@ -0,0 +1,1199 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.preverification.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.util.ArrayUtil;
+
+import java.util.Arrays;
+
+/**
+ * This AttributeVisitor accumulates specified changes to code, and then applies
+ * these accumulated changes to the code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class CodeAttributeEditor
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ExceptionInfoVisitor,
+ StackMapFrameVisitor,
+ VerificationTypeVisitor,
+ LineNumberInfoVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ public static boolean DEBUG = false;
+ //*/
+
+
+ private final boolean updateFrameSizes;
+ private final boolean shrinkInstructions;
+
+ private int codeLength;
+ private boolean modified;
+ private boolean simple;
+
+ /*private*/public Instruction[] preInsertions = new Instruction[ClassConstants.TYPICAL_CODE_LENGTH];
+ /*private*/public Instruction[] replacements = new Instruction[ClassConstants.TYPICAL_CODE_LENGTH];
+ /*private*/public Instruction[] postInsertions = new Instruction[ClassConstants.TYPICAL_CODE_LENGTH];
+ /*private*/public boolean[] deleted = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
+
+ private int[] newInstructionOffsets = new int[ClassConstants.TYPICAL_CODE_LENGTH];
+ private int newOffset;
+ private boolean lengthIncreased;
+
+ private int expectedStackMapFrameOffset;
+
+ private final StackSizeUpdater stackSizeUpdater = new StackSizeUpdater();
+ private final VariableSizeUpdater variableSizeUpdater = new VariableSizeUpdater();
+ private final InstructionWriter instructionWriter = new InstructionWriter();
+
+
+ /**
+ * Creates a new CodeAttributeEditor that automatically updates frame
+ * sizes and shrinks instructions.
+ */
+ public CodeAttributeEditor()
+ {
+ this(true, true);
+ }
+
+
+ /**
+ * Creates a new CodeAttributeEditor.
+ * @param updateFrameSizes specifies whether frame sizes of edited code
+ * should be updated.
+ * @param shrinkInstructions specifies whether added instructions should
+ * automatically be shrunk before being written.
+ */
+ public CodeAttributeEditor(boolean updateFrameSizes,
+ boolean shrinkInstructions)
+ {
+ this.updateFrameSizes = updateFrameSizes;
+ this.shrinkInstructions = shrinkInstructions;
+ }
+
+
+ /**
+ * Resets the accumulated code changes.
+ * @param codeLength the length of the code that will be edited next.
+ */
+ public void reset(int codeLength)
+ {
+ // Try to reuse the previous arrays.
+ if (preInsertions.length < codeLength)
+ {
+ preInsertions = new Instruction[codeLength];
+ replacements = new Instruction[codeLength];
+ postInsertions = new Instruction[codeLength];
+ deleted = new boolean[codeLength];
+ }
+ else
+ {
+ Arrays.fill(preInsertions, 0, codeLength, null);
+ Arrays.fill(replacements, 0, codeLength, null);
+ Arrays.fill(postInsertions, 0, codeLength, null);
+ Arrays.fill(deleted, 0, codeLength, false);
+ }
+
+ this.codeLength = codeLength;
+
+ modified = false;
+ simple = true;
+ }
+
+
+ /**
+ * Extends the size of the accumulated code changes.
+ * @param codeLength the length of the code that will be edited next.
+ */
+ public void extend(int codeLength)
+ {
+ // Try to reuse the previous arrays.
+ if (preInsertions.length < codeLength)
+ {
+ preInsertions = (Instruction[])ArrayUtil.extendArray(preInsertions, codeLength);
+ replacements = (Instruction[])ArrayUtil.extendArray(replacements, codeLength);
+ postInsertions = (Instruction[])ArrayUtil.extendArray(postInsertions, codeLength);
+ deleted = ArrayUtil.extendArray(deleted, codeLength);
+ }
+ else
+ {
+ Arrays.fill(preInsertions, this.codeLength, codeLength, null);
+ Arrays.fill(replacements, this.codeLength, codeLength, null);
+ Arrays.fill(postInsertions, this.codeLength, codeLength, null);
+ Arrays.fill(deleted, this.codeLength, codeLength, false);
+ }
+
+ this.codeLength = codeLength;
+ }
+
+
+ /**
+ * Remembers to place the given instruction right before the instruction
+ * at the given offset.
+ * @param instructionOffset the offset of the instruction.
+ * @param instruction the new instruction.
+ */
+ public void insertBeforeInstruction(int instructionOffset, Instruction instruction)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ preInsertions[instructionOffset] = shrinkInstructions ?
+ instruction.shrink() :
+ instruction;
+
+ modified = true;
+ simple = false;
+
+ }
+
+
+ /**
+ * Remembers to place the given instructions right before the instruction
+ * at the given offset.
+ * @param instructionOffset the offset of the instruction.
+ * @param instructions the new instructions.
+ */
+ public void insertBeforeInstruction(int instructionOffset, Instruction[] instructions)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ CompositeInstruction instruction =
+ new CompositeInstruction(instructions);
+
+ preInsertions[instructionOffset] = shrinkInstructions ?
+ instruction.shrink() :
+ instruction;
+
+ modified = true;
+ simple = false;
+
+ }
+
+
+ /**
+ * Remembers to replace the instruction at the given offset by the given
+ * instruction.
+ * @param instructionOffset the offset of the instruction to be replaced.
+ * @param instruction the new instruction.
+ */
+ public void replaceInstruction(int instructionOffset, Instruction instruction)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ replacements[instructionOffset] = shrinkInstructions ?
+ instruction.shrink() :
+ instruction;
+
+ modified = true;
+ }
+
+
+ /**
+ * Remembers to replace the instruction at the given offset by the given
+ * instructions.
+ * @param instructionOffset the offset of the instruction to be replaced.
+ * @param instructions the new instructions.
+ */
+ public void replaceInstruction(int instructionOffset, Instruction[] instructions)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ CompositeInstruction instruction =
+ new CompositeInstruction(instructions);
+
+ replacements[instructionOffset] = shrinkInstructions ?
+ instruction.shrink() :
+ instruction;
+
+ modified = true;
+ }
+
+
+ /**
+ * Remembers to place the given instruction right after the instruction
+ * at the given offset.
+ * @param instructionOffset the offset of the instruction.
+ * @param instruction the new instruction.
+ */
+ public void insertAfterInstruction(int instructionOffset, Instruction instruction)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ postInsertions[instructionOffset] = shrinkInstructions ?
+ instruction.shrink() :
+ instruction;
+
+ modified = true;
+ simple = false;
+ }
+
+
+ /**
+ * Remembers to place the given instructions right after the instruction
+ * at the given offset.
+ * @param instructionOffset the offset of the instruction.
+ * @param instructions the new instructions.
+ */
+ public void insertAfterInstruction(int instructionOffset, Instruction[] instructions)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ CompositeInstruction instruction =
+ new CompositeInstruction(instructions);
+
+ postInsertions[instructionOffset] = shrinkInstructions ?
+ instruction.shrink() :
+ instruction;
+
+ modified = true;
+ simple = false;
+ }
+
+
+ /**
+ * Remembers to delete the instruction at the given offset.
+ * @param instructionOffset the offset of the instruction to be deleted.
+ */
+ public void deleteInstruction(int instructionOffset)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ deleted[instructionOffset] = true;
+
+ modified = true;
+ simple = false;
+ }
+
+
+ /**
+ * Remembers not to delete the instruction at the given offset.
+ * @param instructionOffset the offset of the instruction not to be deleted.
+ */
+ public void undeleteInstruction(int instructionOffset)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ deleted[instructionOffset] = false;
+ }
+
+
+ /**
+ * Clears all modifications of the instruction at the given offset.
+ * @param instructionOffset the offset of the instruction to be deleted.
+ */
+ public void clearModifications(int instructionOffset)
+ {
+ if (instructionOffset < 0 ||
+ instructionOffset >= codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+instructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ preInsertions[instructionOffset] = null;
+ replacements[instructionOffset] = null;
+ postInsertions[instructionOffset] = null;
+ deleted[instructionOffset] = false;
+ }
+
+
+ /**
+ * Returns whether the code has been modified in any way.
+ */
+ public boolean isModified()
+ {
+ return modified;
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset has been modified
+ * in any way.
+ */
+ public boolean isModified(int instructionOffset)
+ {
+ return preInsertions[instructionOffset] != null ||
+ replacements[instructionOffset] != null ||
+ postInsertions[instructionOffset] != null ||
+ deleted[instructionOffset];
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // TODO: Remove this when the code has stabilized.
+ // Catch any unexpected exceptions from the actual visiting method.
+ try
+ {
+ // Process the code.
+ visitCodeAttribute0(clazz, method, codeAttribute);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while editing code:");
+ System.err.println(" Class = ["+clazz.getName()+"]");
+ System.err.println(" Method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+
+ throw ex;
+ }
+ }
+
+
+ public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Do we have to update the code?
+ if (modified)
+ {
+ if (DEBUG)
+ {
+ System.out.println("CodeAttributeEditor: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ }
+
+ // Can we perform a faster simple replacement of instructions?
+ if (canPerformSimpleReplacements(codeAttribute))
+ {
+ if (DEBUG)
+ {
+ System.out.println(" Simple editing");
+ }
+
+ // Simply overwrite the instructions.
+ performSimpleReplacements(codeAttribute);
+ }
+ else
+ {
+ if (DEBUG)
+ {
+ System.out.println(" Full editing");
+ }
+
+ // Move and remap the instructions.
+ codeAttribute.u4codeLength =
+ updateInstructions(clazz, method, codeAttribute);
+
+ // Update the exception table.
+ codeAttribute.exceptionsAccept(clazz, method, this);
+
+ // Remove exceptions with empty code blocks.
+ codeAttribute.u2exceptionTableLength =
+ removeEmptyExceptions(codeAttribute.exceptionTable,
+ codeAttribute.u2exceptionTableLength);
+
+ // Update the line number table and the local variable tables.
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+ // Make sure instructions are widened if necessary.
+ instructionWriter.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+ // Update the maximum stack size and local variable frame size.
+ if (updateFrameSizes)
+ {
+ stackSizeUpdater.visitCodeAttribute(clazz, method, codeAttribute);
+ variableSizeUpdater.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ // Update all stack map entries.
+ expectedStackMapFrameOffset = -1;
+ stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ // Update all stack map table entries.
+ expectedStackMapFrameOffset = 0;
+ stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ // Update all line number table entries.
+ lineNumberTableAttribute.lineNumbersAccept(clazz, method, codeAttribute, this);
+
+ // Remove line numbers with empty code blocks.
+ lineNumberTableAttribute.u2lineNumberTableLength =
+ removeEmptyLineNumbers(lineNumberTableAttribute.lineNumberTable,
+ lineNumberTableAttribute.u2lineNumberTableLength,
+ codeAttribute.u4codeLength);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Update all local variable table entries.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Update all local variable table entries.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ /**
+ * Checks if it is possible to modifies the given code without having to
+ * update any offsets.
+ * @param codeAttribute the code to be changed.
+ * @return the new code length.
+ */
+ private boolean canPerformSimpleReplacements(CodeAttribute codeAttribute)
+ {
+ if (!simple)
+ {
+ return false;
+ }
+
+ byte[] code = codeAttribute.code;
+ int codeLength = codeAttribute.u4codeLength;
+
+ // Go over all replacement instructions.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ // Check if the replacement instruction, if any, has a different
+ // length than the original instruction.
+ Instruction replacementInstruction = replacements[offset];
+ if (replacementInstruction != null &&
+ replacementInstruction.length(offset) !=
+ InstructionFactory.create(code, offset).length(offset))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Modifies the given code without updating any offsets.
+ * @param codeAttribute the code to be changed.
+ */
+ private void performSimpleReplacements(CodeAttribute codeAttribute)
+ {
+ int codeLength = codeAttribute.u4codeLength;
+
+ // Go over all replacement instructions.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ // Overwrite the original instruction with the replacement
+ // instruction if any.
+ Instruction replacementInstruction = replacements[offset];
+ if (replacementInstruction != null)
+ {
+ replacementInstruction.write(codeAttribute, offset);
+
+ if (DEBUG)
+ {
+ System.out.println(" Replaced "+replacementInstruction.toString(offset));
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Modifies the given code based on the previously specified changes.
+ * @param clazz the class file of the code to be changed.
+ * @param method the method of the code to be changed.
+ * @param codeAttribute the code to be changed.
+ * @return the new code length.
+ */
+ private int updateInstructions(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute)
+ {
+ byte[] oldCode = codeAttribute.code;
+ int oldLength = codeAttribute.u4codeLength;
+
+ // Make sure there is a sufficiently large instruction offset map.
+ if (newInstructionOffsets.length < oldLength + 1)
+ {
+ newInstructionOffsets = new int[oldLength + 1];
+ }
+
+ // Fill out the instruction offset map.
+ int newLength = mapInstructions(oldCode,
+ oldLength);
+
+ // Create a new code array if necessary.
+ if (lengthIncreased)
+ {
+ codeAttribute.code = new byte[newLength];
+ }
+
+ // Prepare for possible widening of instructions.
+ instructionWriter.reset(newLength);
+
+ // Move the instructions into the new code array.
+ moveInstructions(clazz,
+ method,
+ codeAttribute,
+ oldCode,
+ oldLength);
+
+ // We can return the new length.
+ return newLength;
+ }
+
+
+ /**
+ * Fills out the instruction offset map for the given code block.
+ * @param oldCode the instructions to be moved.
+ * @param oldLength the code length.
+ * @return the new code length.
+ */
+ private int mapInstructions(byte[] oldCode, int oldLength)
+ {
+ // Start mapping instructions at the beginning.
+ newOffset = 0;
+ lengthIncreased = false;
+
+ int oldOffset = 0;
+ do
+ {
+ // Get the next instruction.
+ Instruction instruction = InstructionFactory.create(oldCode, oldOffset);
+
+ // Compute the mapping of the instruction.
+ mapInstruction(oldOffset, instruction);
+
+ oldOffset += instruction.length(oldOffset);
+
+ if (newOffset > oldOffset)
+ {
+ lengthIncreased = true;
+ }
+ }
+ while (oldOffset < oldLength);
+
+ // Also add an entry for the first offset after the code.
+ newInstructionOffsets[oldOffset] = newOffset;
+
+ return newOffset;
+ }
+
+
+ /**
+ * Fills out the instruction offset map for the given instruction.
+ * @param oldOffset the instruction's old offset.
+ * @param instruction the instruction to be moved.
+ */
+ private void mapInstruction(int oldOffset,
+ Instruction instruction)
+ {
+ newInstructionOffsets[oldOffset] = newOffset;
+
+ // Account for the pre-inserted instruction, if any.
+ Instruction preInstruction = preInsertions[oldOffset];
+ if (preInstruction != null)
+ {
+ newOffset += preInstruction.length(newOffset);
+ }
+
+ // Account for the replacement instruction, or for the current
+ // instruction, if it shouldn't be deleted.
+ Instruction replacementInstruction = replacements[oldOffset];
+ if (replacementInstruction != null)
+ {
+ newOffset += replacementInstruction.length(newOffset);
+ }
+ else if (!deleted[oldOffset])
+ {
+ // Note that the instruction's length may change at its new offset,
+ // e.g. if it is a switch instruction.
+ newOffset += instruction.length(newOffset);
+ }
+
+ // Account for the post-inserted instruction, if any.
+ Instruction postInstruction = postInsertions[oldOffset];
+ if (postInstruction != null)
+ {
+ newOffset += postInstruction.length(newOffset);
+ }
+ }
+
+
+ /**
+ * Moves the given code block to the new offsets.
+ * @param clazz the class file of the code to be changed.
+ * @param method the method of the code to be changed.
+ * @param codeAttribute the code to be changed.
+ * @param oldCode the original code to be moved.
+ * @param oldLength the original code length.
+ */
+ private void moveInstructions(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ byte[] oldCode,
+ int oldLength)
+ {
+ // Start writing instructions at the beginning.
+ newOffset = 0;
+
+ int oldOffset = 0;
+ do
+ {
+ // Get the next instruction.
+ Instruction instruction = InstructionFactory.create(oldCode, oldOffset);
+
+ // Move the instruction to its new offset.
+ moveInstruction(clazz,
+ method,
+ codeAttribute,
+ oldOffset,
+ instruction);
+
+ oldOffset += instruction.length(oldOffset);
+ }
+ while (oldOffset < oldLength);
+ }
+
+
+ /**
+ * Moves the given instruction to its new offset.
+ * @param clazz the class file of the code to be changed.
+ * @param method the method of the code to be changed.
+ * @param codeAttribute the code to be changed.
+ * @param oldOffset the original instruction offset.
+ * @param instruction the original instruction.
+ */
+ private void moveInstruction(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ int oldOffset,
+ Instruction instruction)
+ {
+ // Update and insert the pre-inserted instruction, if any.
+ Instruction preInstruction = preInsertions[oldOffset];
+ if (preInstruction != null)
+ {
+ if (DEBUG)
+ {
+ System.out.println(" Pre-inserted ["+oldOffset+"] -> "+preInstruction.toString(newOffset));
+ }
+
+ // Update the instruction.
+ preInstruction.accept(clazz, method, codeAttribute, oldOffset, this);
+ }
+
+ // Update and insert the replacement instruction, or the current
+ // instruction, if it shouldn't be deleted.
+ Instruction replacementInstruction = replacements[oldOffset];
+ if (replacementInstruction != null)
+ {
+ if (DEBUG)
+ {
+ System.out.println(" Replaced ["+oldOffset+"] -> "+replacementInstruction.toString(newOffset));
+ }
+
+ // Update the instruction.
+ replacementInstruction.accept(clazz, method, codeAttribute, oldOffset, this);
+ }
+ else if (!deleted[oldOffset])
+ {
+ if (DEBUG)
+ {
+ System.out.println(" Copied ["+oldOffset+"] -> "+instruction.toString(newOffset));
+ }
+
+ // Update the instruction.
+ instruction.accept(clazz, method, codeAttribute, oldOffset, this);
+ }
+
+ // Update and insert the post-inserted instruction, if any.
+ Instruction postInstruction = postInsertions[oldOffset];
+ if (postInstruction != null)
+ {
+ if (DEBUG)
+ {
+ System.out.println(" Post-inserted ["+oldOffset+"] -> "+postInstruction.toString(newOffset));
+ }
+
+ // Update the instruction.
+ postInstruction.accept(clazz, method, codeAttribute, oldOffset, this);
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ // Write out the instruction.
+ instructionWriter.visitSimpleInstruction(clazz,
+ method,
+ codeAttribute,
+ newOffset,
+ simpleInstruction);
+
+ newOffset += simpleInstruction.length(newOffset);
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Write out the instruction.
+ instructionWriter.visitConstantInstruction(clazz,
+ method,
+ codeAttribute,
+ newOffset,
+ constantInstruction);
+
+ newOffset += constantInstruction.length(newOffset);
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ // Write out the instruction.
+ instructionWriter.visitVariableInstruction(clazz,
+ method,
+ codeAttribute,
+ newOffset,
+ variableInstruction);
+
+ newOffset += variableInstruction.length(newOffset);
+ }
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ // Adjust the branch offset.
+ branchInstruction.branchOffset = newBranchOffset(offset,
+ branchInstruction.branchOffset);
+
+ // Write out the instruction.
+ instructionWriter.visitBranchInstruction(clazz,
+ method,
+ codeAttribute,
+ newOffset,
+ branchInstruction);
+
+ newOffset += branchInstruction.length(newOffset);
+ }
+
+
+ public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction)
+ {
+ // Adjust the default jump offset.
+ tableSwitchInstruction.defaultOffset = newBranchOffset(offset,
+ tableSwitchInstruction.defaultOffset);
+
+ // Adjust the jump offsets.
+ newJumpOffsets(offset,
+ tableSwitchInstruction.jumpOffsets);
+
+ // Write out the instruction.
+ instructionWriter.visitTableSwitchInstruction(clazz,
+ method,
+ codeAttribute,
+ newOffset,
+ tableSwitchInstruction);
+
+ newOffset += tableSwitchInstruction.length(newOffset);
+ }
+
+
+ public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction)
+ {
+ // Adjust the default jump offset.
+ lookUpSwitchInstruction.defaultOffset = newBranchOffset(offset,
+ lookUpSwitchInstruction.defaultOffset);
+
+ // Adjust the jump offsets.
+ newJumpOffsets(offset,
+ lookUpSwitchInstruction.jumpOffsets);
+
+ // Write out the instruction.
+ instructionWriter.visitLookUpSwitchInstruction(clazz,
+ method,
+ codeAttribute,
+ newOffset,
+ lookUpSwitchInstruction);
+
+ newOffset += lookUpSwitchInstruction.length(newOffset);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ // Update the code offsets. Note that the instruction offset map also has
+ // an entry for the first offset after the code, for u2endPC.
+ exceptionInfo.u2startPC = newInstructionOffset(exceptionInfo.u2startPC);
+ exceptionInfo.u2endPC = newInstructionOffset(exceptionInfo.u2endPC);
+ exceptionInfo.u2handlerPC = newInstructionOffset(exceptionInfo.u2handlerPC);
+ }
+
+
+ // Implementations for StackMapFrameVisitor.
+
+ public void visitAnyStackMapFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrame stackMapFrame)
+ {
+ // Update the stack map frame offset.
+ int stackMapFrameOffset = newInstructionOffset(offset);
+
+ int offsetDelta = stackMapFrameOffset;
+
+ // Compute the offset delta if the frame is part of a stack map frame
+ // table (for JDK 6.0) instead of a stack map (for Java Micro Edition).
+ if (expectedStackMapFrameOffset >= 0)
+ {
+ offsetDelta -= expectedStackMapFrameOffset;
+
+ expectedStackMapFrameOffset = stackMapFrameOffset + 1;
+ }
+
+ stackMapFrame.u2offsetDelta = offsetDelta;
+ }
+
+
+ public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)
+ {
+ // Update the stack map frame offset.
+ visitAnyStackMapFrame(clazz, method, codeAttribute, offset, sameOneFrame);
+
+ // Update the verification type offset.
+ sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame)
+ {
+ // Update the stack map frame offset.
+ visitAnyStackMapFrame(clazz, method, codeAttribute, offset, moreZeroFrame);
+
+ // Update the verification type offsets.
+ moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame)
+ {
+ // Update the stack map frame offset.
+ visitAnyStackMapFrame(clazz, method, codeAttribute, offset, fullFrame);
+
+ // Update the verification type offsets.
+ fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this);
+ fullFrame.stackAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for VerificationTypeVisitor.
+
+ public void visitAnyVerificationType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationType verificationType) {}
+
+
+ public void visitUninitializedType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedType uninitializedType)
+ {
+ // Update the offset of the 'new' instruction.
+ uninitializedType.u2newInstructionOffset = newInstructionOffset(uninitializedType.u2newInstructionOffset);
+ }
+
+
+ // Implementations for LineNumberInfoVisitor.
+
+ public void visitLineNumberInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberInfo lineNumberInfo)
+ {
+ // Update the code offset.
+ lineNumberInfo.u2startPC = newInstructionOffset(lineNumberInfo.u2startPC);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ // Update the code offset and length.
+ int newStartPC = newInstructionOffset(localVariableInfo.u2startPC);
+ int newEndPC = newInstructionOffset(localVariableInfo.u2startPC +
+ localVariableInfo.u2length);
+
+ localVariableInfo.u2length = newEndPC - newStartPC;
+ localVariableInfo.u2startPC = newStartPC;
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ // Update the code offset and length.
+ int newStartPC = newInstructionOffset(localVariableTypeInfo.u2startPC);
+ int newEndPC = newInstructionOffset(localVariableTypeInfo.u2startPC +
+ localVariableTypeInfo.u2length);
+
+ localVariableTypeInfo.u2length = newEndPC - newStartPC;
+ localVariableTypeInfo.u2startPC = newStartPC;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Adjusts the given jump offsets for the instruction at the given offset.
+ */
+ private void newJumpOffsets(int oldInstructionOffset, int[] oldJumpOffsets)
+ {
+ for (int index = 0; index < oldJumpOffsets.length; index++)
+ {
+ oldJumpOffsets[index] = newBranchOffset(oldInstructionOffset, oldJumpOffsets[index]);
+ }
+ }
+
+
+ /**
+ * Computes the new branch offset for the instruction at the given offset
+ * with the given branch offset.
+ */
+ private int newBranchOffset(int oldInstructionOffset, int oldBranchOffset)
+ {
+ return newInstructionOffset(oldInstructionOffset + oldBranchOffset) - newOffset;
+ }
+
+
+ /**
+ * Computes the new instruction offset for the instruction at the given offset.
+ */
+ private int newInstructionOffset(int oldInstructionOffset)
+ {
+ if (oldInstructionOffset < 0 ||
+ oldInstructionOffset > codeLength)
+ {
+ throw new IllegalArgumentException("Invalid instruction offset ["+oldInstructionOffset+"] in code with length ["+codeLength+"]");
+ }
+
+ return newInstructionOffsets[oldInstructionOffset];
+ }
+
+
+ /**
+ * Returns the given list of exceptions, without the ones that have empty
+ * code blocks.
+ */
+ private int removeEmptyExceptions(ExceptionInfo[] exceptionInfos,
+ int exceptionInfoCount)
+ {
+ // Overwrite all empty exceptions.
+ int newIndex = 0;
+ for (int index = 0; index < exceptionInfoCount; index++)
+ {
+ ExceptionInfo exceptionInfo = exceptionInfos[index];
+ if (exceptionInfo.u2startPC < exceptionInfo.u2endPC)
+ {
+ exceptionInfos[newIndex++] = exceptionInfo;
+ }
+ }
+
+ return newIndex;
+ }
+
+
+ /**
+ * Returns the given list of line numbers, without the ones that have empty
+ * code blocks or that exceed the code size.
+ */
+ private int removeEmptyLineNumbers(LineNumberInfo[] lineNumberInfos,
+ int lineNumberInfoCount,
+ int codeLength)
+ {
+ // Overwrite all empty line number entries.
+ int newIndex = 0;
+ for (int index = 0; index < lineNumberInfoCount; index++)
+ {
+ LineNumberInfo lineNumberInfo = lineNumberInfos[index];
+ int startPC = lineNumberInfo.u2startPC;
+ if (startPC < codeLength &&
+ (index == 0 || startPC > lineNumberInfos[index-1].u2startPC))
+ {
+ lineNumberInfos[newIndex++] = lineNumberInfo;
+ }
+ }
+
+ return newIndex;
+ }
+
+
+ /**
+ * This instruction is a composite of other instructions, for local use
+ * inside the editor class only.
+ */
+ private class CompositeInstruction
+ extends Instruction
+ {
+ private Instruction[] instructions;
+
+
+ private CompositeInstruction(Instruction[] instructions)
+ {
+ this.instructions = instructions;
+ }
+
+
+ // Implementations for Instruction.
+
+ public Instruction shrink()
+ {
+ for (int index = 0; index < instructions.length; index++)
+ {
+ instructions[index] = instructions[index].shrink();
+ }
+
+ return this;
+ }
+
+
+ public void write(byte[] code, int offset)
+ {
+ for (int index = 0; index < instructions.length; index++)
+ {
+ Instruction instruction = instructions[index];
+
+ instruction.write(code, offset);
+
+ offset += instruction.length(offset);
+ }
+ }
+
+
+ protected void readInfo(byte[] code, int offset)
+ {
+ throw new UnsupportedOperationException("Can't read composite instruction");
+ }
+
+
+ protected void writeInfo(byte[] code, int offset)
+ {
+ throw new UnsupportedOperationException("Can't write composite instruction");
+ }
+
+
+ public int length(int offset)
+ {
+ int newOffset = offset;
+
+ for (int index = 0; index < instructions.length; index++)
+ {
+ newOffset += instructions[index].length(newOffset);
+ }
+
+ return newOffset - offset;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor)
+ {
+ if (instructionVisitor != CodeAttributeEditor.this)
+ {
+ throw new UnsupportedOperationException("Unexpected visitor ["+instructionVisitor+"]");
+ }
+
+ for (int index = 0; index < instructions.length; index++)
+ {
+ Instruction instruction = instructions[index];
+
+ instruction.accept(clazz, method, codeAttribute, offset, CodeAttributeEditor.this);
+
+ offset += instruction.length(offset);
+ }
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ StringBuffer stringBuffer = new StringBuffer();
+
+ for (int index = 0; index < instructions.length; index++)
+ {
+ stringBuffer.append(instructions[index].toString()).append("; ");
+ }
+
+ return stringBuffer.toString();
+ }
+ }
+}
diff --git a/src/proguard/classfile/editor/CodeAttributeEditorResetter.java b/src/proguard/classfile/editor/CodeAttributeEditorResetter.java
new file mode 100644
index 000000000..8f767c7b3
--- /dev/null
+++ b/src/proguard/classfile/editor/CodeAttributeEditorResetter.java
@@ -0,0 +1,60 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor resets it CodeAttributeEditor whenever it visits a
+ * code attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class CodeAttributeEditorResetter
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final CodeAttributeEditor codeAttributeEditor;
+
+
+ /**
+ * Creates a new CodeAttributeEditorResetter.
+ * @param codeAttributeEditor the code attribute editor that will be reset.
+ */
+ public CodeAttributeEditorResetter(CodeAttributeEditor codeAttributeEditor)
+ {
+ this.codeAttributeEditor = codeAttributeEditor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttributeEditor.reset(codeAttribute.u4codeLength);
+ }
+}
diff --git a/src/proguard/classfile/editor/ComparableConstant.java b/src/proguard/classfile/editor/ComparableConstant.java
new file mode 100644
index 000000000..476edd69c
--- /dev/null
+++ b/src/proguard/classfile/editor/ComparableConstant.java
@@ -0,0 +1,249 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+
+/**
+ * This class is a Comparable
wrapper of Constant
+ * objects. It can store an index, in order to identify the constant pool
+ * entry after it has been sorted. The comparison is primarily based on the
+ * types of the constant pool entries, and secondarily on the contents of
+ * the constant pool entries.
+ *
+ * @author Eric Lafortune
+ */
+class ComparableConstant
+extends SimplifiedVisitor
+implements Comparable, ConstantVisitor
+{
+ private static final int[] PRIORITIES = new int[19];
+ static
+ {
+ PRIORITIES[ClassConstants.CONSTANT_Integer] = 0; // Possibly byte index (ldc).
+ PRIORITIES[ClassConstants.CONSTANT_Float] = 1;
+ PRIORITIES[ClassConstants.CONSTANT_String] = 2;
+ PRIORITIES[ClassConstants.CONSTANT_Class] = 3;
+ PRIORITIES[ClassConstants.CONSTANT_Long] = 4; // Always wide index (ldc2_w).
+ PRIORITIES[ClassConstants.CONSTANT_Double] = 5; // Always wide index (ldc2_w).
+ PRIORITIES[ClassConstants.CONSTANT_Fieldref] = 6; // Always wide index (getfield,...).
+ PRIORITIES[ClassConstants.CONSTANT_Methodref] = 7; // Always wide index (invokespecial,...).
+ PRIORITIES[ClassConstants.CONSTANT_InterfaceMethodref] = 8; // Always wide index (invokeinterface).
+ PRIORITIES[ClassConstants.CONSTANT_InvokeDynamic] = 9; // Always wide index (invokedynamic).
+ PRIORITIES[ClassConstants.CONSTANT_MethodHandle] = 10;
+ PRIORITIES[ClassConstants.CONSTANT_NameAndType] = 11;
+ PRIORITIES[ClassConstants.CONSTANT_MethodType] = 12;
+ PRIORITIES[ClassConstants.CONSTANT_Utf8] = 13;
+ }
+
+ private final Clazz clazz;
+ private final int thisIndex;
+ private final Constant thisConstant;
+
+ private Constant otherConstant;
+ private int result;
+
+
+ public ComparableConstant(Clazz clazz, int index, Constant constant)
+ {
+ this.clazz = clazz;
+ this.thisIndex = index;
+ this.thisConstant = constant;
+ }
+
+
+ public int getIndex()
+ {
+ return thisIndex;
+ }
+
+
+ public Constant getConstant()
+ {
+ return thisConstant;
+ }
+
+
+ // Implementations for Comparable.
+
+ public int compareTo(Object other)
+ {
+ ComparableConstant otherComparableConstant = (ComparableConstant)other;
+
+ otherConstant = otherComparableConstant.thisConstant;
+
+ // Compare based on the original indices, if the actual constant pool
+ // entries are the same.
+ if (thisConstant == otherConstant)
+ {
+ int otherIndex = otherComparableConstant.thisIndex;
+
+ return thisIndex < otherIndex ? -1 :
+ thisIndex == otherIndex ? 0 :
+ 1;
+ }
+
+ // Compare based on the tags, if they are different.
+ int thisTag = thisConstant.getTag();
+ int otherTag = otherConstant.getTag();
+
+ if (thisTag != otherTag)
+ {
+ return PRIORITIES[thisTag] < PRIORITIES[otherTag] ? -1 : 1;
+ }
+
+ // Otherwise compare based on the contents of the Constant objects.
+ thisConstant.accept(clazz, this);
+
+ return result;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)
+ {
+ int value = integerConstant.getValue();
+ int otherValue = ((IntegerConstant)otherConstant).getValue();
+ result = value < otherValue ? -1 :
+ value == otherValue ? 0 :
+ 1;
+ }
+
+ public void visitLongConstant(Clazz clazz, LongConstant longConstant)
+ {
+ long value = longConstant.getValue();
+ long otherValue = ((LongConstant)otherConstant).getValue();
+ result = value < otherValue ? -1 :
+ value == otherValue ? 0 :
+ 1;
+ }
+
+ public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)
+ {
+ result = Float.compare(floatConstant.getValue(),
+ ((FloatConstant)otherConstant).getValue());
+ }
+
+ public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)
+ {
+ result = Double.compare(doubleConstant.getValue(),
+ ((DoubleConstant)otherConstant).getValue());
+ }
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ result = stringConstant.getString(clazz).compareTo(((StringConstant)otherConstant).getString(clazz));
+ }
+
+ public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)
+ {
+ result = utf8Constant.getString().compareTo(((Utf8Constant)otherConstant).getString());
+ }
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ InvokeDynamicConstant otherInvokeDynamicConstant = (InvokeDynamicConstant)otherConstant;
+
+ int index = invokeDynamicConstant.getBootstrapMethodAttributeIndex();
+ int otherIndex = otherInvokeDynamicConstant.getBootstrapMethodAttributeIndex();
+
+ result = index < otherIndex ? -1 :
+ index > otherIndex ? 1 :
+ (invokeDynamicConstant.getName(clazz) + ' ' +
+ invokeDynamicConstant.getType(clazz))
+ .compareTo
+ (otherInvokeDynamicConstant.getName(clazz) + ' ' +
+ otherInvokeDynamicConstant.getType(clazz));
+ }
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ MethodHandleConstant otherMethodHandleConstant = (MethodHandleConstant)otherConstant;
+
+ int kind = methodHandleConstant.getReferenceKind();
+ int otherKind = methodHandleConstant.getReferenceKind();
+
+ result = kind < otherKind ? -1 :
+ kind > otherKind ? 1 :
+ (methodHandleConstant.getName(clazz) + ' ' +
+ methodHandleConstant.getType(clazz))
+ .compareTo
+ (otherMethodHandleConstant.getName(clazz) + ' ' +
+ otherMethodHandleConstant.getType(clazz));
+ }
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ RefConstant otherRefConstant = (RefConstant)otherConstant;
+ result = (refConstant.getClassName(clazz) + ' ' +
+ refConstant.getName(clazz) + ' ' +
+ refConstant.getType(clazz))
+ .compareTo
+ (otherRefConstant.getClassName(clazz) + ' ' +
+ otherRefConstant.getName(clazz) + ' ' +
+ otherRefConstant.getType(clazz));
+ }
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ result = classConstant.getName(clazz).compareTo(((ClassConstant)otherConstant).getName(clazz));
+ }
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant MethodTypeConstant)
+ {
+ MethodTypeConstant otherMethodTypeConstant = (MethodTypeConstant)otherConstant;
+ result = MethodTypeConstant.getType(clazz)
+ .compareTo
+ (otherMethodTypeConstant.getType(clazz));
+ }
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ NameAndTypeConstant otherNameAndTypeConstant = (NameAndTypeConstant)otherConstant;
+ result = (nameAndTypeConstant.getName(clazz) + ' ' +
+ nameAndTypeConstant.getType(clazz))
+ .compareTo
+ (otherNameAndTypeConstant.getName(clazz) + ' ' +
+ otherNameAndTypeConstant.getType(clazz));
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object other)
+ {
+ return other != null &&
+ this.getClass().equals(other.getClass()) &&
+ this.getConstant().getClass().equals(((ComparableConstant)other).getConstant().getClass()) &&
+ this.compareTo(other) == 0;
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+}
diff --git a/src/proguard/classfile/editor/ConstantAdder.java b/src/proguard/classfile/editor/ConstantAdder.java
new file mode 100644
index 000000000..9d20199d3
--- /dev/null
+++ b/src/proguard/classfile/editor/ConstantAdder.java
@@ -0,0 +1,239 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.util.ListUtil;
+
+/**
+ * This ConstantVisitor adds all constants that it visits to the constant pool
+ * of a given target class.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantAdder
+implements ConstantVisitor
+{
+ private final ConstantPoolEditor constantPoolEditor;
+
+ private int constantIndex;
+
+
+ /**
+ * Creates a new ConstantAdder that will copy constants into the given
+ * target class.
+ */
+ public ConstantAdder(ProgramClass targetClass)
+ {
+ constantPoolEditor = new ConstantPoolEditor(targetClass);
+ }
+
+
+ /**
+ * Adds a copy of the specified constant in the given class and returns
+ * its index. If the specified index is 0, the returned value is 0 too.
+ */
+ public int addConstant(Clazz clazz, int constantIndex)
+ {
+ clazz.constantPoolEntryAccept(constantIndex, this);
+
+ return this.constantIndex;
+ }
+
+
+ /**
+ * Adds a copy of the given constant in the given class and returns
+ * its index.
+ */
+ public int addConstant(Clazz clazz, Constant constant)
+ {
+ constant.accept(clazz, this);
+
+ return this.constantIndex;
+ }
+
+
+ /**
+ * Returns the index of the most recently created constant in the constant
+ * pool of the target class.
+ */
+ public int getConstantIndex()
+ {
+ return constantIndex;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)
+ {
+ constantIndex =
+ constantPoolEditor.addIntegerConstant(integerConstant.getValue());
+ }
+
+
+ public void visitLongConstant(Clazz clazz, LongConstant longConstant)
+ {
+ constantIndex =
+ constantPoolEditor.addLongConstant(longConstant.getValue());
+ }
+
+
+ public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)
+ {
+ constantIndex =
+ constantPoolEditor.addFloatConstant(floatConstant.getValue());
+ }
+
+
+ public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)
+ {
+ constantIndex =
+ constantPoolEditor.addDoubleConstant(doubleConstant.getValue());
+ }
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ constantIndex =
+ constantPoolEditor.addStringConstant(stringConstant.getString(clazz),
+ stringConstant.referencedClass,
+ stringConstant.referencedMember);
+ }
+
+
+ public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)
+ {
+ constantIndex =
+ constantPoolEditor.addUtf8Constant(utf8Constant.getString());
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ // First add the name and type constant.
+ clazz.constantPoolEntryAccept(invokeDynamicConstant.u2nameAndTypeIndex, this);
+
+ // Copy the referenced classes.
+ Clazz[] referencedClasses = invokeDynamicConstant.referencedClasses;
+ Clazz[] referencedClassesCopy = null;
+ if (referencedClasses != null)
+ {
+ referencedClassesCopy = new Clazz[referencedClasses.length];
+ System.arraycopy(referencedClasses, 0,
+ referencedClassesCopy, 0,
+ referencedClasses.length);
+ }
+
+ // Then add the actual invoke dynamic constant.
+ constantIndex =
+ constantPoolEditor.addInvokeDynamicConstant(invokeDynamicConstant.getBootstrapMethodAttributeIndex(),
+ constantIndex,
+ referencedClassesCopy);
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ // First add the field ref, interface method ref, or method ref
+ // constant.
+ clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex, this);
+
+ // Then add the actual method handle constant.
+ constantIndex =
+ constantPoolEditor.addMethodHandleConstant(methodHandleConstant.getReferenceKind(),
+ constantIndex);
+ }
+
+
+ public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
+ {
+ // First add the referenced class constant, with its own referenced class.
+ clazz.constantPoolEntryAccept(fieldrefConstant.u2classIndex, this);
+
+ // Then add the actual field reference constant, with its referenced
+ // class and class member.
+ constantIndex =
+ constantPoolEditor.addFieldrefConstant(constantIndex,
+ fieldrefConstant.getName(clazz),
+ fieldrefConstant.getType(clazz),
+ fieldrefConstant.referencedClass,
+ fieldrefConstant.referencedMember);
+ }
+
+
+ public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant)
+ {
+ // First add the referenced class constant, with its own referenced class.
+ clazz.constantPoolEntryAccept(interfaceMethodrefConstant.u2classIndex, this);
+
+ // Then add the actual interface method reference constant, with its
+ // referenced class and class member.
+ constantIndex =
+ constantPoolEditor.addInterfaceMethodrefConstant(constantIndex,
+ interfaceMethodrefConstant.getName(clazz),
+ interfaceMethodrefConstant.getType(clazz),
+ interfaceMethodrefConstant.referencedClass,
+ interfaceMethodrefConstant.referencedMember);
+ }
+
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ // First add the referenced class constant, with its own referenced class.
+ clazz.constantPoolEntryAccept(methodrefConstant.u2classIndex, this);
+
+ // Then add the actual method reference constant, with its referenced
+ // class and class member.
+ constantIndex =
+ constantPoolEditor.addMethodrefConstant(constantIndex,
+ methodrefConstant.getName(clazz),
+ methodrefConstant.getType(clazz),
+ methodrefConstant.referencedClass,
+ methodrefConstant.referencedMember);
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Add the class constant, with its referenced class..
+ constantIndex =
+ constantPoolEditor.addClassConstant(classConstant.getName(clazz),
+ classConstant.referencedClass);
+ }
+
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
+ {
+ constantIndex =
+ constantPoolEditor.addMethodTypeConstant(methodTypeConstant.getType(clazz));
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ constantIndex =
+ constantPoolEditor.addNameAndTypeConstant(nameAndTypeConstant.getName(clazz),
+ nameAndTypeConstant.getType(clazz));
+ }
+}
diff --git a/src/proguard/classfile/editor/ConstantPoolEditor.java b/src/proguard/classfile/editor/ConstantPoolEditor.java
new file mode 100644
index 000000000..7adbc444c
--- /dev/null
+++ b/src/proguard/classfile/editor/ConstantPoolEditor.java
@@ -0,0 +1,782 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.*;
+
+/**
+ * This class can add constant pool entries to a given class.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantPoolEditor
+{
+ private static final boolean DEBUG = false;
+
+ private ProgramClass targetClass;
+
+
+ /**
+ * Creates a new ConstantPoolEditor that will edit constants in the given
+ * target class.
+ */
+ public ConstantPoolEditor(ProgramClass targetClass)
+ {
+ this.targetClass = targetClass;
+ }
+
+
+ /**
+ * Finds or creates a IntegerConstant constant pool entry with the given
+ * value.
+ * @return the constant pool index of the Utf8Constant.
+ */
+ public int addIntegerConstant(int value)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Integer)
+ {
+ IntegerConstant integerConstant = (IntegerConstant)constant;
+ if (integerConstant.getValue() == value)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new IntegerConstant(value));
+ }
+
+
+ /**
+ * Finds or creates a LongConstant constant pool entry with the given value.
+ * @return the constant pool index of the LongConstant.
+ */
+ public int addLongConstant(long value)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Long)
+ {
+ LongConstant longConstant = (LongConstant)constant;
+ if (longConstant.getValue() == value)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new LongConstant(value));
+ }
+
+
+ /**
+ * Finds or creates a FloatConstant constant pool entry with the given
+ * value.
+ * @return the constant pool index of the FloatConstant.
+ */
+ public int addFloatConstant(float value)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Float)
+ {
+ FloatConstant floatConstant = (FloatConstant)constant;
+ if (floatConstant.getValue() == value)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new FloatConstant(value));
+ }
+
+
+ /**
+ * Finds or creates a DoubleConstant constant pool entry with the given
+ * value.
+ * @return the constant pool index of the DoubleConstant.
+ */
+ public int addDoubleConstant(double value)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Double)
+ {
+ DoubleConstant doubleConstant = (DoubleConstant)constant;
+ if (doubleConstant.getValue() == value)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new DoubleConstant(value));
+ }
+
+
+ /**
+ * Finds or creates a StringConstant constant pool entry with the given
+ * value.
+ * @return the constant pool index of the StringConstant.
+ */
+ public int addStringConstant(String string,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_String)
+ {
+ StringConstant stringConstant = (StringConstant)constant;
+ if (stringConstant.getString(targetClass).equals(string))
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new StringConstant(addUtf8Constant(string),
+ referencedClass,
+ referencedMember));
+ }
+
+
+ /**
+ * Finds or creates a InvokeDynamicConstant constant pool entry with the
+ * given bootstrap method constant pool entry index, method name, and
+ * descriptor.
+ * @return the constant pool index of the InvokeDynamicConstant.
+ */
+ public int addInvokeDynamicConstant(int bootstrapMethodIndex,
+ String name,
+ String descriptor,
+ Clazz[] referencedClasses)
+ {
+ return addInvokeDynamicConstant(bootstrapMethodIndex,
+ addNameAndTypeConstant(name, descriptor),
+ referencedClasses);
+ }
+
+
+ /**
+ * Finds or creates a InvokeDynamicConstant constant pool entry with the given
+ * class constant pool entry index and name and type constant pool entry
+ * index.
+ * @return the constant pool index of the InvokeDynamicConstant.
+ */
+ public int addInvokeDynamicConstant(int bootstrapMethodIndex,
+ int nameAndTypeIndex,
+ Clazz[] referencedClasses)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_InvokeDynamic)
+ {
+ InvokeDynamicConstant invokeDynamicConstant = (InvokeDynamicConstant)constant;
+ if (invokeDynamicConstant.u2bootstrapMethodAttributeIndex == bootstrapMethodIndex &&
+ invokeDynamicConstant.u2nameAndTypeIndex == nameAndTypeIndex)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new InvokeDynamicConstant(bootstrapMethodIndex,
+ nameAndTypeIndex,
+ referencedClasses));
+ }
+
+
+ /**
+ * Finds or creates a MethodHandleConstant constant pool entry of the
+ * specified kind and with the given field ref, interface method ref,
+ * or method ref constant pool entry index.
+ * @return the constant pool index of the MethodHandleConstant.
+ */
+ public int addMethodHandleConstant(int referenceKind,
+ int referenceIndex)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_MethodHandle)
+ {
+ MethodHandleConstant methodHandleConstant = (MethodHandleConstant)constant;
+ if (methodHandleConstant.u1referenceKind == referenceKind &&
+ methodHandleConstant.u2referenceIndex == referenceIndex)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new MethodHandleConstant(referenceKind,
+ referenceIndex));
+ }
+
+
+ /**
+ * Finds or creates a FieldrefConstant constant pool entry for the given
+ * class and field.
+ * @return the constant pool index of the FieldrefConstant.
+ */
+ public int addFieldrefConstant(Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addFieldrefConstant(referencedClass.getName(),
+ referencedMember.getName(referencedClass),
+ referencedMember.getDescriptor(referencedClass),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a FieldrefConstant constant pool entry with the given
+ * class name, field name, and descriptor.
+ * @return the constant pool index of the FieldrefConstant.
+ */
+ public int addFieldrefConstant(String className,
+ String name,
+ String descriptor,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addFieldrefConstant(className,
+ addNameAndTypeConstant(name, descriptor),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a FieldrefConstant constant pool entry with the given
+ * class name, field name, and descriptor.
+ * @return the constant pool index of the FieldrefConstant.
+ */
+ public int addFieldrefConstant(String className,
+ int nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addFieldrefConstant(addClassConstant(className, referencedClass),
+ nameAndTypeIndex,
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a FieldrefConstant constant pool entry with the given
+ * class constant pool entry index, field name, and descriptor.
+ * @return the constant pool index of the FieldrefConstant.
+ */
+ public int addFieldrefConstant(int classIndex,
+ String name,
+ String descriptor,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addFieldrefConstant(classIndex,
+ addNameAndTypeConstant(name, descriptor),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a FieldrefConstant constant pool entry with the given
+ * class constant pool entry index and name and type constant pool entry
+ * index.
+ * @return the constant pool index of the FieldrefConstant.
+ */
+ public int addFieldrefConstant(int classIndex,
+ int nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Fieldref)
+ {
+ FieldrefConstant fieldrefConstant = (FieldrefConstant)constant;
+ if (fieldrefConstant.u2classIndex == classIndex &&
+ fieldrefConstant.u2nameAndTypeIndex == nameAndTypeIndex)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new FieldrefConstant(classIndex,
+ nameAndTypeIndex,
+ referencedClass,
+ referencedMember));
+ }
+
+
+ /**
+ * Finds or creates a InterfaceMethodrefConstant constant pool entry with the
+ * given class name, method name, and descriptor.
+ * @return the constant pool index of the InterfaceMethodrefConstant.
+ */
+ public int addInterfaceMethodrefConstant(String className,
+ String name,
+ String descriptor,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addInterfaceMethodrefConstant(className,
+ addNameAndTypeConstant(name, descriptor),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a InterfaceMethodrefConstant constant pool entry with the
+ * given class name, method name, and descriptor.
+ * @return the constant pool index of the InterfaceMethodrefConstant.
+ */
+ public int addInterfaceMethodrefConstant(String className,
+ int nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addInterfaceMethodrefConstant(addClassConstant(className, referencedClass),
+ nameAndTypeIndex,
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a InterfaceMethodrefConstant constant pool entry for the
+ * given class and method.
+ * @return the constant pool index of the InterfaceMethodrefConstant.
+ */
+ public int addInterfaceMethodrefConstant(Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addInterfaceMethodrefConstant(referencedClass.getName(),
+ referencedMember.getName(referencedClass),
+ referencedMember.getDescriptor(referencedClass),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a InterfaceMethodrefConstant constant pool entry with the
+ * given class constant pool entry index, method name, and descriptor.
+ * @return the constant pool index of the InterfaceMethodrefConstant.
+ */
+ public int addInterfaceMethodrefConstant(int classIndex,
+ String name,
+ String descriptor,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addInterfaceMethodrefConstant(classIndex,
+ addNameAndTypeConstant(name, descriptor),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a InterfaceMethodrefConstant constant pool entry with the
+ * given class constant pool entry index and name and type constant pool
+ * entry index.
+ * @return the constant pool index of the InterfaceMethodrefConstant.
+ */
+ public int addInterfaceMethodrefConstant(int classIndex,
+ int nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_InterfaceMethodref)
+ {
+ InterfaceMethodrefConstant methodrefConstant = (InterfaceMethodrefConstant)constant;
+ if (methodrefConstant.u2classIndex == classIndex &&
+ methodrefConstant.u2nameAndTypeIndex == nameAndTypeIndex)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new InterfaceMethodrefConstant(classIndex,
+ nameAndTypeIndex,
+ referencedClass,
+ referencedMember));
+ }
+
+
+ /**
+ * Finds or creates a MethodrefConstant constant pool entry for the given
+ * class and method.
+ * @return the constant pool index of the MethodrefConstant.
+ */
+ public int addMethodrefConstant(Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addMethodrefConstant(referencedClass.getName(),
+ referencedMember.getName(referencedClass),
+ referencedMember.getDescriptor(referencedClass),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a MethodrefConstant constant pool entry with the given
+ * class name, method name, and descriptor.
+ * @return the constant pool index of the MethodrefConstant.
+ */
+ public int addMethodrefConstant(String className,
+ String name,
+ String descriptor,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addMethodrefConstant(className,
+ addNameAndTypeConstant(name, descriptor),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a MethodrefConstant constant pool entry with the given
+ * class name, method name, and descriptor.
+ * @return the constant pool index of the MethodrefConstant.
+ */
+ public int addMethodrefConstant(String className,
+ int nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addMethodrefConstant(addClassConstant(className, referencedClass),
+ nameAndTypeIndex,
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a MethodrefConstant constant pool entry with the given
+ * class constant pool entry index, method name, and descriptor.
+ * @return the constant pool index of the MethodrefConstant.
+ */
+ public int addMethodrefConstant(int classIndex,
+ String name,
+ String descriptor,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ return addMethodrefConstant(classIndex,
+ addNameAndTypeConstant(name, descriptor),
+ referencedClass,
+ referencedMember);
+ }
+
+
+ /**
+ * Finds or creates a MethodrefConstant constant pool entry with the given
+ * class constant pool entry index and name and type constant pool entry
+ * index.
+ * @return the constant pool index of the MethodrefConstant.
+ */
+ public int addMethodrefConstant(int classIndex,
+ int nameAndTypeIndex,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Methodref)
+ {
+ MethodrefConstant methodrefConstant = (MethodrefConstant)constant;
+ if (methodrefConstant.u2classIndex == classIndex &&
+ methodrefConstant.u2nameAndTypeIndex == nameAndTypeIndex)
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new MethodrefConstant(classIndex,
+ nameAndTypeIndex,
+ referencedClass,
+ referencedMember));
+ }
+
+
+ /**
+ * Finds or creates a ClassConstant constant pool entry for the given class.
+ * @return the constant pool index of the ClassConstant.
+ */
+ public int addClassConstant(Clazz referencedClass)
+ {
+ return addClassConstant(referencedClass.getName(),
+ referencedClass);
+ }
+
+
+ /**
+ * Finds or creates a ClassConstant constant pool entry with the given name.
+ * @return the constant pool index of the ClassConstant.
+ */
+ public int addClassConstant(String name,
+ Clazz referencedClass)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Class)
+ {
+ ClassConstant classConstant = (ClassConstant)constant;
+ if (classConstant.getName(targetClass).equals(name))
+ {
+ return index;
+ }
+ }
+ }
+
+ int nameIndex = addUtf8Constant(name);
+
+ return addConstant(new ClassConstant(nameIndex, referencedClass));
+ }
+
+
+ /**
+ * Finds or creates a MethodTypeConstant constant pool entry with the given
+ * type.
+ * @return the constant pool index of the MethodTypeConstant.
+ */
+ public int addMethodTypeConstant(String type)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_MethodType)
+ {
+ MethodTypeConstant methodTypeConstant = (MethodTypeConstant)constant;
+ if (methodTypeConstant.getType(targetClass).equals(type))
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new MethodTypeConstant(addUtf8Constant(type)));
+ }
+
+
+ /**
+ * Finds or creates a NameAndTypeConstant constant pool entry with the given
+ * name and type.
+ * @return the constant pool index of the NameAndTypeConstant.
+ */
+ public int addNameAndTypeConstant(String name,
+ String type)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_NameAndType)
+ {
+ NameAndTypeConstant nameAndTypeConstant = (NameAndTypeConstant)constant;
+ if (nameAndTypeConstant.getName(targetClass).equals(name) &&
+ nameAndTypeConstant.getType(targetClass).equals(type))
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new NameAndTypeConstant(addUtf8Constant(name),
+ addUtf8Constant(type)));
+ }
+
+
+ /**
+ * Finds or creates a Utf8Constant constant pool entry for the given string.
+ * @return the constant pool index of the Utf8Constant.
+ */
+ public int addUtf8Constant(String string)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Check if the entry already exists.
+ for (int index = 1; index < constantPoolCount; index++)
+ {
+ Constant constant = constantPool[index];
+
+ if (constant != null &&
+ constant.getTag() == ClassConstants.CONSTANT_Utf8)
+ {
+ Utf8Constant utf8Constant = (Utf8Constant)constant;
+ if (utf8Constant.getString().equals(string))
+ {
+ return index;
+ }
+ }
+ }
+
+ return addConstant(new Utf8Constant(string));
+ }
+
+
+ /**
+ * Adds a given constant pool entry to the end of the constant pool/
+ * @return the constant pool index for the added entry.
+ */
+ public int addConstant(Constant constant)
+ {
+ int constantPoolCount = targetClass.u2constantPoolCount;
+ Constant[] constantPool = targetClass.constantPool;
+
+ // Make sure there is enough space for another constant pool entry.
+ if (constantPool.length < constantPoolCount+2)
+ {
+ targetClass.constantPool = new Constant[constantPoolCount+2];
+ System.arraycopy(constantPool, 0,
+ targetClass.constantPool, 0,
+ constantPoolCount);
+ constantPool = targetClass.constantPool;
+ }
+
+ if (DEBUG)
+ {
+ System.out.println(targetClass.getName()+": adding ["+constant.getClass().getName()+"] at index "+targetClass.u2constantPoolCount);
+ }
+
+ // Create a new Utf8Constant for the given string.
+ constantPool[targetClass.u2constantPoolCount++] = constant;
+
+ // Long constants and double constants take up two entries in the
+ // constant pool.
+ int tag = constant.getTag();
+ if (tag == ClassConstants.CONSTANT_Long ||
+ tag == ClassConstants.CONSTANT_Double)
+ {
+ constantPool[targetClass.u2constantPoolCount++] = null;
+ }
+
+ return constantPoolCount;
+ }
+}
diff --git a/src/proguard/classfile/editor/ConstantPoolRemapper.java b/src/proguard/classfile/editor/ConstantPoolRemapper.java
new file mode 100644
index 000000000..eaf7653b2
--- /dev/null
+++ b/src/proguard/classfile/editor/ConstantPoolRemapper.java
@@ -0,0 +1,662 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.preverification.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ClassVisitor remaps all possible references to constant pool entries
+ * of the classes that it visits, based on a given index map. It is assumed that
+ * the constant pool entries themselves have already been remapped.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantPoolRemapper
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ MemberVisitor,
+ AttributeVisitor,
+ BootstrapMethodInfoVisitor,
+ InnerClassesInfoVisitor,
+ ExceptionInfoVisitor,
+ InstructionVisitor,
+ StackMapFrameVisitor,
+ VerificationTypeVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor(false, true);
+
+ private int[] constantIndexMap;
+
+
+ /**
+ * Sets the given mapping of old constant pool entry indexes to their new
+ * indexes.
+ */
+ public void setConstantIndexMap(int[] constantIndexMap)
+ {
+ this.constantIndexMap = constantIndexMap;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Remap the local constant pool references.
+ programClass.u2thisClass = remapConstantIndex(programClass.u2thisClass);
+ programClass.u2superClass = remapConstantIndex(programClass.u2superClass);
+
+ remapConstantIndexArray(programClass.u2interfaces,
+ programClass.u2interfacesCount);
+
+ // Remap the references of the contant pool entries themselves.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Remap the references in all fields, methods, and attributes.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)
+ {
+ // Nothing to do.
+ }
+
+
+ public void visitLongConstant(Clazz clazz, LongConstant longConstant)
+ {
+ // Nothing to do.
+ }
+
+
+ public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)
+ {
+ // Nothing to do.
+ }
+
+
+ public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)
+ {
+ // Nothing to do.
+ }
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ stringConstant.u2stringIndex =
+ remapConstantIndex(stringConstant.u2stringIndex);
+ }
+
+
+ public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)
+ {
+ // Nothing to do.
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ invokeDynamicConstant.u2nameAndTypeIndex =
+ remapConstantIndex(invokeDynamicConstant.u2nameAndTypeIndex);
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ methodHandleConstant.u2referenceIndex =
+ remapConstantIndex(methodHandleConstant.u2referenceIndex);
+ }
+
+
+ public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
+ {
+ fieldrefConstant.u2classIndex =
+ remapConstantIndex(fieldrefConstant.u2classIndex);
+ fieldrefConstant.u2nameAndTypeIndex =
+ remapConstantIndex(fieldrefConstant.u2nameAndTypeIndex);
+ }
+
+
+ public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant)
+ {
+ interfaceMethodrefConstant.u2classIndex =
+ remapConstantIndex(interfaceMethodrefConstant.u2classIndex);
+ interfaceMethodrefConstant.u2nameAndTypeIndex =
+ remapConstantIndex(interfaceMethodrefConstant.u2nameAndTypeIndex);
+ }
+
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ methodrefConstant.u2classIndex =
+ remapConstantIndex(methodrefConstant.u2classIndex);
+ methodrefConstant.u2nameAndTypeIndex =
+ remapConstantIndex(methodrefConstant.u2nameAndTypeIndex);
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ classConstant.u2nameIndex =
+ remapConstantIndex(classConstant.u2nameIndex);
+ }
+
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
+ {
+ methodTypeConstant.u2descriptorIndex =
+ remapConstantIndex(methodTypeConstant.u2descriptorIndex);
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ nameAndTypeConstant.u2nameIndex =
+ remapConstantIndex(nameAndTypeConstant.u2nameIndex);
+ nameAndTypeConstant.u2descriptorIndex =
+ remapConstantIndex(nameAndTypeConstant.u2descriptorIndex);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ visitMember(programClass, programField);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ visitMember(programClass, programMethod);
+ }
+
+
+ private void visitMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ // Remap the local constant pool references.
+ programMember.u2nameIndex =
+ remapConstantIndex(programMember.u2nameIndex);
+ programMember.u2descriptorIndex =
+ remapConstantIndex(programMember.u2descriptorIndex);
+
+ // Remap the constant pool references of the remaining attributes.
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ // Library classes are left unchanged.
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ // Library classes are left unchanged.
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ unknownAttribute.u2attributeNameIndex =
+ remapConstantIndex(unknownAttribute.u2attributeNameIndex);
+
+ // There's not much else we can do with unknown attributes.
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ bootstrapMethodsAttribute.u2attributeNameIndex =
+ remapConstantIndex(bootstrapMethodsAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the bootstrap method entries.
+ bootstrapMethodsAttribute.bootstrapMethodEntriesAccept(clazz, this);
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ sourceFileAttribute.u2attributeNameIndex =
+ remapConstantIndex(sourceFileAttribute.u2attributeNameIndex);
+ sourceFileAttribute.u2sourceFileIndex =
+ remapConstantIndex(sourceFileAttribute.u2sourceFileIndex);
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ sourceDirAttribute.u2attributeNameIndex =
+ remapConstantIndex(sourceDirAttribute.u2attributeNameIndex);
+ sourceDirAttribute.u2sourceDirIndex =
+ remapConstantIndex(sourceDirAttribute.u2sourceDirIndex);
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ innerClassesAttribute.u2attributeNameIndex =
+ remapConstantIndex(innerClassesAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the inner classes.
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ enclosingMethodAttribute.u2attributeNameIndex =
+ remapConstantIndex(enclosingMethodAttribute.u2attributeNameIndex);
+ enclosingMethodAttribute.u2classIndex =
+ remapConstantIndex(enclosingMethodAttribute.u2classIndex);
+ enclosingMethodAttribute.u2nameAndTypeIndex =
+ remapConstantIndex(enclosingMethodAttribute.u2nameAndTypeIndex);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ deprecatedAttribute.u2attributeNameIndex =
+ remapConstantIndex(deprecatedAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ syntheticAttribute.u2attributeNameIndex =
+ remapConstantIndex(syntheticAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ signatureAttribute.u2attributeNameIndex =
+ remapConstantIndex(signatureAttribute.u2attributeNameIndex);
+ signatureAttribute.u2signatureIndex =
+ remapConstantIndex(signatureAttribute.u2signatureIndex);
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ constantValueAttribute.u2attributeNameIndex =
+ remapConstantIndex(constantValueAttribute.u2attributeNameIndex);
+ constantValueAttribute.u2constantValueIndex =
+ remapConstantIndex(constantValueAttribute.u2constantValueIndex);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ exceptionsAttribute.u2attributeNameIndex =
+ remapConstantIndex(exceptionsAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the exceptions.
+ remapConstantIndexArray(exceptionsAttribute.u2exceptionIndexTable,
+ exceptionsAttribute.u2exceptionIndexTableLength);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttribute.u2attributeNameIndex =
+ remapConstantIndex(codeAttribute.u2attributeNameIndex);
+
+ // Initially, the code attribute editor doesn't contain any changes.
+ codeAttributeEditor.reset(codeAttribute.u4codeLength);
+
+ // Remap the constant pool references of the instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ // Apply the code atribute editor. It will only contain any changes if
+ // the code length is changing at any point.
+ codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Remap the constant pool references of the exceptions and attributes.
+ codeAttribute.exceptionsAccept(clazz, method, this);
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ stackMapAttribute.u2attributeNameIndex =
+ remapConstantIndex(stackMapAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the stack map frames.
+ stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ stackMapTableAttribute.u2attributeNameIndex =
+ remapConstantIndex(stackMapTableAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the stack map frames.
+ stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ lineNumberTableAttribute.u2attributeNameIndex =
+ remapConstantIndex(lineNumberTableAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ localVariableTableAttribute.u2attributeNameIndex =
+ remapConstantIndex(localVariableTableAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ localVariableTypeTableAttribute.u2attributeNameIndex =
+ remapConstantIndex(localVariableTypeTableAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the local variables.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ annotationsAttribute.u2attributeNameIndex =
+ remapConstantIndex(annotationsAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the annotations.
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ parameterAnnotationsAttribute.u2attributeNameIndex =
+ remapConstantIndex(parameterAnnotationsAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ annotationDefaultAttribute.u2attributeNameIndex =
+ remapConstantIndex(annotationDefaultAttribute.u2attributeNameIndex);
+
+ // Remap the constant pool references of the annotations.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for BootstrapMethodInfoVisitor.
+
+ public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo)
+ {
+ bootstrapMethodInfo.u2methodHandleIndex =
+ remapConstantIndex(bootstrapMethodInfo.u2methodHandleIndex);
+
+ // Remap the constant pool references of the bootstrap methods..
+ remapConstantIndexArray(bootstrapMethodInfo.u2methodArguments,
+ bootstrapMethodInfo.u2methodArgumentCount);
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ if (innerClassesInfo.u2innerClassIndex != 0)
+ {
+ innerClassesInfo.u2innerClassIndex =
+ remapConstantIndex(innerClassesInfo.u2innerClassIndex);
+ }
+
+ if (innerClassesInfo.u2outerClassIndex != 0)
+ {
+ innerClassesInfo.u2outerClassIndex =
+ remapConstantIndex(innerClassesInfo.u2outerClassIndex);
+ }
+
+ if (innerClassesInfo.u2innerNameIndex != 0)
+ {
+ innerClassesInfo.u2innerNameIndex =
+ remapConstantIndex(innerClassesInfo.u2innerNameIndex);
+ }
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ if (exceptionInfo.u2catchType != 0)
+ {
+ exceptionInfo.u2catchType =
+ remapConstantIndex(exceptionInfo.u2catchType);
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Is the new constant pool index different from the original one?
+ int newConstantIndex = remapConstantIndex(constantInstruction.constantIndex);
+ if (newConstantIndex != constantInstruction.constantIndex)
+ {
+ // Replace the instruction.
+ Instruction replacementInstruction =
+ new ConstantInstruction(constantInstruction.opcode,
+ newConstantIndex,
+ constantInstruction.constant);
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+ }
+ }
+
+
+ // Implementations for StackMapFrameVisitor.
+
+ public void visitAnyStackMapFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrame stackMapFrame) {}
+
+
+ public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)
+ {
+ // Remap the constant pool references of the verification types.
+ sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame)
+ {
+ // Remap the constant pool references of the verification types.
+ moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame)
+ {
+ // Remap the constant pool references of the verification types.
+ fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this);
+ fullFrame.stackAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for VerificationTypeVisitor.
+
+ public void visitAnyVerificationType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationType verificationType) {}
+
+
+ public void visitObjectType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ObjectType objectType)
+ {
+ objectType.u2classIndex =
+ remapConstantIndex(objectType.u2classIndex);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ localVariableInfo.u2nameIndex =
+ remapConstantIndex(localVariableInfo.u2nameIndex);
+ localVariableInfo.u2descriptorIndex =
+ remapConstantIndex(localVariableInfo.u2descriptorIndex);
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ localVariableTypeInfo.u2nameIndex =
+ remapConstantIndex(localVariableTypeInfo.u2nameIndex);
+ localVariableTypeInfo.u2signatureIndex =
+ remapConstantIndex(localVariableTypeInfo.u2signatureIndex);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ annotation.u2typeIndex =
+ remapConstantIndex(annotation.u2typeIndex);
+
+ // Remap the constant pool references of the element values.
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ constantElementValue.u2elementNameIndex =
+ remapConstantIndex(constantElementValue.u2elementNameIndex);
+ constantElementValue.u2constantValueIndex =
+ remapConstantIndex(constantElementValue.u2constantValueIndex);
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ enumConstantElementValue.u2elementNameIndex =
+ remapConstantIndex(enumConstantElementValue.u2elementNameIndex);
+ enumConstantElementValue.u2typeNameIndex =
+ remapConstantIndex(enumConstantElementValue.u2typeNameIndex);
+ enumConstantElementValue.u2constantNameIndex =
+ remapConstantIndex(enumConstantElementValue.u2constantNameIndex);
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ classElementValue.u2elementNameIndex =
+ remapConstantIndex(classElementValue.u2elementNameIndex);
+ classElementValue.u2classInfoIndex =
+ remapConstantIndex(classElementValue.u2classInfoIndex);
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ annotationElementValue.u2elementNameIndex =
+ remapConstantIndex(annotationElementValue.u2elementNameIndex);
+
+ // Remap the constant pool references of the annotation.
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ arrayElementValue.u2elementNameIndex =
+ remapConstantIndex(arrayElementValue.u2elementNameIndex);
+
+ // Remap the constant pool references of the element values.
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Remaps all constant pool indices in the given array.
+ */
+ private void remapConstantIndexArray(int[] array, int length)
+ {
+ for (int index = 0; index < length; index++)
+ {
+ array[index] = remapConstantIndex(array[index]);
+ }
+ }
+
+
+ /**
+ * Returns the new constant pool index of the entry at the
+ * given index.
+ */
+ private int remapConstantIndex(int constantIndex)
+ {
+ return constantIndexMap[constantIndex];
+ }
+}
diff --git a/src/proguard/classfile/editor/ConstantPoolShrinker.java b/src/proguard/classfile/editor/ConstantPoolShrinker.java
new file mode 100644
index 000000000..ee309a010
--- /dev/null
+++ b/src/proguard/classfile/editor/ConstantPoolShrinker.java
@@ -0,0 +1,578 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.preverification.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+import java.util.Arrays;
+
+/**
+ * This ClassVisitor removes all unused entries from the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantPoolShrinker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ ConstantVisitor,
+ AttributeVisitor,
+ BootstrapMethodInfoVisitor,
+ InnerClassesInfoVisitor,
+ ExceptionInfoVisitor,
+ StackMapFrameVisitor,
+ VerificationTypeVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor,
+ InstructionVisitor
+{
+ // A visitor info flag to indicate the constant is being used.
+ private static final Object USED = new Object();
+
+ private int[] constantIndexMap = new int[ClassConstants.TYPICAL_CONSTANT_POOL_SIZE];
+ private final ConstantPoolRemapper constantPoolRemapper = new ConstantPoolRemapper();
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Mark this class's name.
+ markConstant(programClass, programClass.u2thisClass);
+
+ // Mark the superclass class constant.
+ programClass.superClassConstantAccept(this);
+
+ // Mark the interface class constants.
+ programClass.interfaceConstantsAccept(this);
+
+ // Mark the constants referenced by the class members.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ // Mark the attributes.
+ programClass.attributesAccept(this);
+
+ // Shift the used constant pool entries together, filling out the
+ // index map.
+ int newConstantPoolCount =
+ shrinkConstantPool(programClass.constantPool,
+ programClass.u2constantPoolCount);
+
+ // Remap the references to the constant pool if it has shrunk.
+ if (newConstantPoolCount < programClass.u2constantPoolCount)
+ {
+ programClass.u2constantPoolCount = newConstantPoolCount;
+
+ // Remap all constant pool references.
+ constantPoolRemapper.setConstantIndexMap(constantIndexMap);
+ constantPoolRemapper.visitProgramClass(programClass);
+ }
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ // Mark the name and descriptor.
+ markConstant(programClass, programMember.u2nameIndex);
+ markConstant(programClass, programMember.u2descriptorIndex);
+
+ // Mark the attributes.
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant)
+ {
+ markAsUsed(constant);
+ }
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ markAsUsed(stringConstant);
+
+ markConstant(clazz, stringConstant.u2stringIndex);
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ markAsUsed(invokeDynamicConstant);
+
+ markConstant(clazz, invokeDynamicConstant.u2nameAndTypeIndex);
+
+ // Mark the bootstrap methods attribute.
+ clazz.attributesAccept(this);
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ markAsUsed(methodHandleConstant);
+
+ markConstant(clazz, methodHandleConstant.u2referenceIndex);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ markAsUsed(refConstant);
+
+ markConstant(clazz, refConstant.u2classIndex);
+ markConstant(clazz, refConstant.u2nameAndTypeIndex);
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ markAsUsed(classConstant);
+
+ markConstant(clazz, classConstant.u2nameIndex);
+ }
+
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
+ {
+ markAsUsed(methodTypeConstant);
+
+ markConstant(clazz, methodTypeConstant.u2descriptorIndex);
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ markAsUsed(nameAndTypeConstant);
+
+ markConstant(clazz, nameAndTypeConstant.u2nameIndex);
+ markConstant(clazz, nameAndTypeConstant.u2descriptorIndex);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute)
+ {
+ markConstant(clazz, attribute.u2attributeNameIndex);
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ markConstant(clazz, bootstrapMethodsAttribute.u2attributeNameIndex);
+
+ // Mark the bootstrap method entries.
+ bootstrapMethodsAttribute.bootstrapMethodEntriesAccept(clazz, this);
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ markConstant(clazz, sourceFileAttribute.u2attributeNameIndex);
+ markConstant(clazz, sourceFileAttribute.u2sourceFileIndex);
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ markConstant(clazz, sourceDirAttribute.u2attributeNameIndex);
+ markConstant(clazz, sourceDirAttribute.u2sourceDirIndex);
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ markConstant(clazz, innerClassesAttribute.u2attributeNameIndex);
+
+ // Mark the outer class entries.
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ markConstant(clazz, enclosingMethodAttribute.u2attributeNameIndex);
+ markConstant(clazz, enclosingMethodAttribute.u2classIndex);
+
+ if (enclosingMethodAttribute.u2nameAndTypeIndex != 0)
+ {
+ markConstant(clazz, enclosingMethodAttribute.u2nameAndTypeIndex);
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ markConstant(clazz, signatureAttribute.u2attributeNameIndex);
+ markConstant(clazz, signatureAttribute.u2signatureIndex);
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ markConstant(clazz, constantValueAttribute.u2attributeNameIndex);
+ markConstant(clazz, constantValueAttribute.u2constantValueIndex);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ markConstant(clazz, exceptionsAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the exceptions.
+ exceptionsAttribute.exceptionEntriesAccept((ProgramClass)clazz, this);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ markConstant(clazz, codeAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the instructions,
+ // by the exceptions, and by the attributes.
+ codeAttribute.instructionsAccept(clazz, method, this);
+ codeAttribute.exceptionsAccept(clazz, method, this);
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ markConstant(clazz, stackMapAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the stack map frames.
+ stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ markConstant(clazz, stackMapTableAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the stack map frames.
+ stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ markConstant(clazz, localVariableTableAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ markConstant(clazz, localVariableTypeTableAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the local variable types.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ markConstant(clazz, annotationsAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the annotations.
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ markConstant(clazz, parameterAnnotationsAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ markConstant(clazz, annotationDefaultAttribute.u2attributeNameIndex);
+
+ // Mark the constant pool entries referenced by the element value.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for BootstrapMethodInfoVisitor.
+
+ public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo)
+ {
+ markConstant(clazz, bootstrapMethodInfo.u2methodHandleIndex);
+
+ // Mark the constant pool entries referenced by the arguments.
+ bootstrapMethodInfo.methodArgumentsAccept(clazz, this);
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ innerClassesInfo.innerClassConstantAccept(clazz, this);
+ innerClassesInfo.outerClassConstantAccept(clazz, this);
+ innerClassesInfo.innerNameConstantAccept(clazz, this);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ if (exceptionInfo.u2catchType != 0)
+ {
+ markConstant(clazz, exceptionInfo.u2catchType);
+ }
+ }
+
+
+ // Implementations for StackMapFrameVisitor.
+
+ public void visitAnyStackMapFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrame stackMapFrame) {}
+
+
+ public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)
+ {
+ // Mark the constant pool entries referenced by the verification types.
+ sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame)
+ {
+ // Mark the constant pool entries referenced by the verification types.
+ moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame)
+ {
+ // Mark the constant pool entries referenced by the verification types.
+ fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this);
+ fullFrame.stackAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for VerificationTypeVisitor.
+
+ public void visitAnyVerificationType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationType verificationType) {}
+
+
+ public void visitObjectType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ObjectType objectType)
+ {
+ markConstant(clazz, objectType.u2classIndex);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ markConstant(clazz, localVariableInfo.u2nameIndex);
+ markConstant(clazz, localVariableInfo.u2descriptorIndex);
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ markConstant(clazz, localVariableTypeInfo.u2nameIndex);
+ markConstant(clazz, localVariableTypeInfo.u2signatureIndex);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ markConstant(clazz, annotation.u2typeIndex);
+
+ // Mark the constant pool entries referenced by the element values.
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ if (constantElementValue.u2elementNameIndex != 0)
+ {
+ markConstant(clazz, constantElementValue.u2elementNameIndex);
+ }
+
+ markConstant(clazz, constantElementValue.u2constantValueIndex);
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ if (enumConstantElementValue.u2elementNameIndex != 0)
+ {
+ markConstant(clazz, enumConstantElementValue.u2elementNameIndex);
+ }
+
+ markConstant(clazz, enumConstantElementValue.u2typeNameIndex);
+ markConstant(clazz, enumConstantElementValue.u2constantNameIndex);
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ if (classElementValue.u2elementNameIndex != 0)
+ {
+ markConstant(clazz, classElementValue.u2elementNameIndex);
+ }
+
+ markConstant(clazz, classElementValue.u2classInfoIndex);
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ if (annotationElementValue.u2elementNameIndex != 0)
+ {
+ markConstant(clazz, annotationElementValue.u2elementNameIndex);
+ }
+
+ // Mark the constant pool entries referenced by the annotation.
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ if (arrayElementValue.u2elementNameIndex != 0)
+ {
+ markConstant(clazz, arrayElementValue.u2elementNameIndex);
+ }
+
+ // Mark the constant pool entries referenced by the element values.
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ markConstant(clazz, constantInstruction.constantIndex);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Marks the given constant pool entry of the given class. This includes
+ * visiting any referenced objects.
+ */
+ private void markConstant(Clazz clazz, int index)
+ {
+ clazz.constantPoolEntryAccept(index, this);
+ }
+
+
+ /**
+ * Marks the given visitor accepter as being used.
+ */
+ private void markAsUsed(Constant constant)
+ {
+ constant.setVisitorInfo(USED);
+ }
+
+
+ /**
+ * Returns whether the given visitor accepter has been marked as being used.
+ */
+ private boolean isUsed(VisitorAccepter visitorAccepter)
+ {
+ return visitorAccepter.getVisitorInfo() == USED;
+ }
+
+
+ /**
+ * Removes all constants that are not marked as being used from the given
+ * constant pool.
+ * @return the new number of entries.
+ */
+ private int shrinkConstantPool(Constant[] constantPool, int length)
+ {
+ // Create a new index map, if necessary.
+ if (constantIndexMap.length < length)
+ {
+ constantIndexMap = new int[length];
+ }
+
+ int counter = 1;
+ boolean isUsed = false;
+
+ // Shift the used constant pool entries together.
+ for (int index = 1; index < length; index++)
+ {
+ constantIndexMap[index] = counter;
+
+ Constant constant = constantPool[index];
+
+ // Don't update the flag if this is the second half of a long entry.
+ if (constant != null)
+ {
+ isUsed = isUsed(constant);
+ }
+
+ if (isUsed)
+ {
+ constantPool[counter++] = constant;
+ }
+ }
+
+ // Clear the remaining constant pool elements.
+ Arrays.fill(constantPool, counter, length, null);
+
+ return counter;
+ }
+}
diff --git a/src/proguard/classfile/editor/ConstantPoolSorter.java b/src/proguard/classfile/editor/ConstantPoolSorter.java
new file mode 100644
index 000000000..b578624de
--- /dev/null
+++ b/src/proguard/classfile/editor/ConstantPoolSorter.java
@@ -0,0 +1,123 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.Constant;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+import java.util.Arrays;
+
+/**
+ * This ClassVisitor sorts the constant pool entries of the program classes
+ * that it visits. The sorting order is based on the types of the constant pool
+ * entries in the first place, and on their contents in the second place.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantPoolSorter
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private int[] constantIndexMap = new int[ClassConstants.TYPICAL_CONSTANT_POOL_SIZE];
+ private ComparableConstant[] comparableConstantPool = new ComparableConstant[ClassConstants.TYPICAL_CONSTANT_POOL_SIZE];
+ private Constant[] newConstantPool = new Constant[ClassConstants.TYPICAL_CONSTANT_POOL_SIZE];
+
+ private final ConstantPoolRemapper constantPoolRemapper = new ConstantPoolRemapper();
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ int constantPoolCount = programClass.u2constantPoolCount;
+
+ // Sort the constant pool and set up an index map.
+ if (constantIndexMap.length < constantPoolCount)
+ {
+ constantIndexMap = new int[constantPoolCount];
+ comparableConstantPool = new ComparableConstant[constantPoolCount];
+ newConstantPool = new Constant[constantPoolCount];
+ }
+
+ // Initialize an array whose elements can be compared.
+ int sortLength = 0;
+ for (int oldIndex = 1; oldIndex < constantPoolCount; oldIndex++)
+ {
+ Constant constant = programClass.constantPool[oldIndex];
+ if (constant != null)
+ {
+ comparableConstantPool[sortLength++] =
+ new ComparableConstant(programClass, oldIndex, constant);
+ }
+ }
+
+ // Sort the array.
+ Arrays.sort(comparableConstantPool, 0, sortLength);
+
+ // Save the sorted elements.
+ int newLength = 1;
+ int newIndex = 1;
+ ComparableConstant previousComparableConstant = null;
+ for (int sortIndex = 0; sortIndex < sortLength; sortIndex++)
+ {
+ ComparableConstant comparableConstant = comparableConstantPool[sortIndex];
+
+ // Isn't this a duplicate of the previous constant?
+ if (!comparableConstant.equals(previousComparableConstant))
+ {
+ // Remember the index of the new entry.
+ newIndex = newLength;
+
+ // Copy the sorted constant pool entry over to the constant pool.
+ Constant constant = comparableConstant.getConstant();
+
+ newConstantPool[newLength++] = constant;
+
+ // Long entries take up two slots, the second of which is null.
+ int tag = constant.getTag();
+ if (tag == ClassConstants.CONSTANT_Long ||
+ tag == ClassConstants.CONSTANT_Double)
+ {
+ newConstantPool[newLength++] = null;
+ }
+
+ previousComparableConstant = comparableConstant;
+ }
+
+ // Fill out the map array.
+ constantIndexMap[comparableConstant.getIndex()] = newIndex;
+ }
+
+ // Copy the new constant pool over.
+ System.arraycopy(newConstantPool, 0, programClass.constantPool, 0, newLength);
+
+ // Clear any remaining entries.
+ Arrays.fill(programClass.constantPool, newLength, constantPoolCount, null);
+
+ programClass.u2constantPoolCount = newLength;
+
+ // Remap all constant pool references.
+ constantPoolRemapper.setConstantIndexMap(constantIndexMap);
+ constantPoolRemapper.visitProgramClass(programClass);
+ }
+}
diff --git a/src/proguard/classfile/editor/ElementValueAdder.java b/src/proguard/classfile/editor/ElementValueAdder.java
new file mode 100644
index 000000000..9c8b3f943
--- /dev/null
+++ b/src/proguard/classfile/editor/ElementValueAdder.java
@@ -0,0 +1,217 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+
+/**
+ * This AnnotationVisitor adds all element values that it visits to the given
+ * target annotation default attribute, annotation, or element value.
+ *
+ * @author Eric Lafortune
+ */
+public class ElementValueAdder
+implements ElementValueVisitor
+{
+ private static final ElementValue[] EMPTY_ELEMENT_VALUES = new ElementValue[0];
+
+
+ private final ProgramClass targetClass;
+ private final AnnotationDefaultAttribute targetAnnotationDefaultAttribute;
+
+ private final ConstantAdder constantAdder;
+ private final ElementValuesEditor elementValuesEditor;
+
+
+ /**
+ * Creates a new ElementValueAdder that will copy element values into the
+ * given target annotation default attribute value.
+ */
+ public ElementValueAdder(ProgramClass targetClass,
+ AnnotationDefaultAttribute targetAnnotationDefaultAttribute,
+ boolean replaceElementValues)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotationDefaultAttribute = targetAnnotationDefaultAttribute;
+
+ constantAdder = new ConstantAdder(targetClass);
+ elementValuesEditor = null;
+ }
+
+
+ /**
+ * Creates a new ElementValueAdder that will copy element values into the
+ * given target annotation.
+ */
+ public ElementValueAdder(ProgramClass targetClass,
+ Annotation targetAnnotation,
+ boolean replaceElementValues)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotationDefaultAttribute = null;
+
+ constantAdder = new ConstantAdder(targetClass);
+ elementValuesEditor = new ElementValuesEditor(targetClass,
+ targetAnnotation,
+ replaceElementValues);
+ }
+
+
+ /**
+ * Creates a new ElementValueAdder that will copy element values into the
+ * given target element value.
+ */
+ public ElementValueAdder(ProgramClass targetClass,
+ ArrayElementValue targetArrayElementValue,
+ boolean replaceElementValues)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotationDefaultAttribute = null;
+
+ constantAdder = new ConstantAdder(targetClass);
+ elementValuesEditor = new ElementValuesEditor(targetClass,
+ targetArrayElementValue,
+ replaceElementValues);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ // Create a copy of the element value.
+ ConstantElementValue newConstantElementValue =
+ new ConstantElementValue(constantElementValue.u1tag,
+ constantElementValue.u2elementNameIndex == 0 ? 0 :
+ constantAdder.addConstant(clazz, constantElementValue.u2elementNameIndex),
+ constantAdder.addConstant(clazz, constantElementValue.u2constantValueIndex));
+
+ newConstantElementValue.referencedClass = constantElementValue.referencedClass;
+ newConstantElementValue.referencedMethod = constantElementValue.referencedMethod;
+
+ // Add it to the target.
+ addElementValue(newConstantElementValue);
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ // Create a copy of the element value.
+ EnumConstantElementValue newEnumConstantElementValue =
+ new EnumConstantElementValue(enumConstantElementValue.u2elementNameIndex == 0 ? 0 :
+ constantAdder.addConstant(clazz, enumConstantElementValue.u2elementNameIndex),
+ constantAdder.addConstant(clazz, enumConstantElementValue.u2typeNameIndex),
+ constantAdder.addConstant(clazz, enumConstantElementValue.u2constantNameIndex));
+
+ newEnumConstantElementValue.referencedClass = enumConstantElementValue.referencedClass;
+ newEnumConstantElementValue.referencedMethod = enumConstantElementValue.referencedMethod;
+
+ // TODO: Clone array.
+ newEnumConstantElementValue.referencedClasses = enumConstantElementValue.referencedClasses;
+
+ // Add it to the target.
+ addElementValue(newEnumConstantElementValue);
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ // Create a copy of the element value.
+ ClassElementValue newClassElementValue =
+ new ClassElementValue(classElementValue.u2elementNameIndex == 0 ? 0 :
+ constantAdder.addConstant(clazz, classElementValue.u2elementNameIndex),
+ constantAdder.addConstant(clazz, classElementValue.u2classInfoIndex));
+
+ newClassElementValue.referencedClass = classElementValue.referencedClass;
+ newClassElementValue.referencedMethod = classElementValue.referencedMethod;
+
+ // TODO: Clone array.
+ newClassElementValue.referencedClasses = classElementValue.referencedClasses;
+
+ // Add it to the target.
+ addElementValue(newClassElementValue);
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ // Create a copy of the element value.
+ AnnotationElementValue newAnnotationElementValue =
+ new AnnotationElementValue(annotationElementValue.u2elementNameIndex == 0 ? 0 :
+ constantAdder.addConstant(clazz, annotationElementValue.u2elementNameIndex),
+ new Annotation());
+
+ newAnnotationElementValue.referencedClass = annotationElementValue.referencedClass;
+ newAnnotationElementValue.referencedMethod = annotationElementValue.referencedMethod;
+
+ annotationElementValue.annotationAccept(clazz,
+ new AnnotationAdder(targetClass,
+ newAnnotationElementValue));
+
+ // Add it to the target.
+ addElementValue(newAnnotationElementValue);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ // Create a copy of the element value.
+ ArrayElementValue newArrayElementValue =
+ new ArrayElementValue(arrayElementValue.u2elementNameIndex == 0 ? 0 :
+ constantAdder.addConstant(clazz, arrayElementValue.u2elementNameIndex),
+ 0,
+ arrayElementValue.u2elementValuesCount > 0 ?
+ new ElementValue[arrayElementValue.u2elementValuesCount] :
+ EMPTY_ELEMENT_VALUES);
+
+ newArrayElementValue.referencedClass = arrayElementValue.referencedClass;
+ newArrayElementValue.referencedMethod = arrayElementValue.referencedMethod;
+
+ arrayElementValue.elementValuesAccept(clazz,
+ annotation,
+ new ElementValueAdder(targetClass,
+ newArrayElementValue,
+ false));
+
+ // Add it to the target.
+ addElementValue(newArrayElementValue);
+ }
+
+
+ // Small utility methods.
+
+ private void addElementValue(ElementValue newElementValue)
+ {
+ // What's the target?
+ if (targetAnnotationDefaultAttribute != null)
+ {
+ // Simply set the completed element value.
+ targetAnnotationDefaultAttribute.defaultValue = newElementValue;
+ }
+ else
+ {
+ // Add it to the target.
+ elementValuesEditor.addElementValue(newElementValue);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/ElementValuesEditor.java b/src/proguard/classfile/editor/ElementValuesEditor.java
new file mode 100644
index 000000000..57671e6ac
--- /dev/null
+++ b/src/proguard/classfile/editor/ElementValuesEditor.java
@@ -0,0 +1,238 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.annotation.*;
+
+/**
+ * This class can add and delete element values to and from a given target
+ * annotation default attribute, annotation, or array element value. Element
+ * values to be added must be filled out beforehand, including their references
+ * to the constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class ElementValuesEditor
+{
+ private final ProgramClass targetClass;
+ private final Annotation targetAnnotation;
+ private final ArrayElementValue targetArrayElementValue;
+ private final boolean replaceElementValues;
+
+
+ /**
+ * Creates a new ElementValuesEditor that will edit element values in the
+ * given target annotation.
+ */
+ public ElementValuesEditor(ProgramClass targetClass,
+ Annotation targetAnnotation,
+ boolean replaceElementValues)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotation = targetAnnotation;
+ this.targetArrayElementValue = null;
+ this.replaceElementValues = replaceElementValues;
+ }
+
+
+ /**
+ * Creates a new ElementValuesEditor that will edit element values in the
+ * given target array element value.
+ */
+ public ElementValuesEditor(ProgramClass targetClass,
+ ArrayElementValue targetArrayElementValue,
+ boolean replaceElementValues)
+ {
+ this.targetClass = targetClass;
+ this.targetAnnotation = null;
+ this.targetArrayElementValue = targetArrayElementValue;
+ this.replaceElementValues = replaceElementValues;
+ }
+
+
+ /**
+ * Adds the given elementValue to the target.
+ */
+ public void addElementValue(ElementValue elementValue)
+ {
+ // What's the target?
+ if (targetAnnotation != null)
+ {
+ // Try to replace an existing element value.
+ if (!replaceElementValues ||
+ !replaceElementValue(targetAnnotation.u2elementValuesCount,
+ targetAnnotation.elementValues,
+ elementValue))
+ {
+ // Otherwise append the element value.
+ targetAnnotation.elementValues =
+ addElementValue(targetAnnotation.u2elementValuesCount,
+ targetAnnotation.elementValues,
+ elementValue);
+
+ targetAnnotation.u2elementValuesCount++;
+ }
+ }
+ else
+ {
+ // Try to replace an existing element value.
+ if (!replaceElementValues ||
+ !replaceElementValue(targetArrayElementValue.u2elementValuesCount,
+ targetArrayElementValue.elementValues,
+ elementValue))
+ {
+ // Otherwise append the element value.
+ targetArrayElementValue.elementValues =
+ addElementValue(targetArrayElementValue.u2elementValuesCount,
+ targetArrayElementValue.elementValues,
+ elementValue);
+
+ targetArrayElementValue.u2elementValuesCount++;
+ }
+ }
+ }
+
+
+ /**
+ * Deletes the given elementValue to the target.
+ */
+ public void deleteElementValue(String elementValueMethodName)
+ {
+ // What's the target?
+ if (targetAnnotation != null)
+ {
+ // Delete the element value to the target annotation.
+ targetAnnotation.u2elementValuesCount =
+ deleteElementValue(targetAnnotation.u2elementValuesCount,
+ targetAnnotation.elementValues,
+ elementValueMethodName);
+ }
+ else
+ {
+ // Delete the element value to the target array element value.
+ targetArrayElementValue.u2elementValuesCount =
+ deleteElementValue(targetArrayElementValue.u2elementValuesCount,
+ targetArrayElementValue.elementValues,
+ elementValueMethodName);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Tries put the given element value in place of an existing element value
+ * of the same name, returning whether it was present.
+ */
+ private boolean replaceElementValue(int elementValuesCount,
+ ElementValue[] elementValues,
+ ElementValue elementValue)
+ {
+ // Find the element value with the same name.
+ int index = findElementValue(elementValuesCount,
+ elementValues,
+ elementValue.getMethodName(targetClass));
+ if (index < 0)
+ {
+ return false;
+ }
+
+ elementValues[index] = elementValue;
+
+ return true;
+ }
+
+
+ /**
+ * Appends the given element value to the given array of element values,
+ * creating a new array if necessary.
+ */
+ private ElementValue[] addElementValue(int elementValuesCount,
+ ElementValue[] elementValues,
+ ElementValue elementValue)
+ {
+ // Is the array too small to contain the additional elementValue?
+ if (elementValues.length <= elementValuesCount)
+ {
+ // Create a new array and copy the elementValues into it.
+ ElementValue[] newElementValues = new ElementValue[elementValuesCount + 1];
+ System.arraycopy(elementValues, 0,
+ newElementValues, 0,
+ elementValuesCount);
+ elementValues = newElementValues;
+ }
+
+ // Append the elementValue.
+ elementValues[elementValuesCount] = elementValue;
+
+ return elementValues;
+ }
+
+
+ /**
+ * Deletes the element values with the given name from the given array of
+ * element values, returning the new number of element values.
+ */
+ private int deleteElementValue(int elementValuesCount,
+ ElementValue[] elementValues,
+ String elementValueMethodName)
+ {
+ // Find the element value.
+ int index = findElementValue(elementValuesCount,
+ elementValues,
+ elementValueMethodName);
+ if (index < 0)
+ {
+ return elementValuesCount;
+ }
+
+ // Shift the other element values in the array.
+ System.arraycopy(elementValues, index + 1,
+ elementValues, index,
+ elementValuesCount - index - 1);
+
+ // Clear the last entry in the array.
+ elementValues[--elementValuesCount] = null;
+
+ return elementValuesCount;
+ }
+
+
+ /**
+ * Finds the index of the element value with the given name in the given
+ * array of element values.
+ */
+ private int findElementValue(int elementValuesCount,
+ ElementValue[] elementValues,
+ String elementValueName)
+ {
+ for (int index = 0; index < elementValuesCount; index++)
+ {
+ if (elementValues[index].getMethodName(targetClass).equals(elementValueName))
+ {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/ExceptionAdder.java b/src/proguard/classfile/editor/ExceptionAdder.java
new file mode 100644
index 000000000..152a06564
--- /dev/null
+++ b/src/proguard/classfile/editor/ExceptionAdder.java
@@ -0,0 +1,65 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.ExceptionsAttribute;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor adds all class constants that it visits to the given
+ * target exceptions attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionAdder
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ private final ConstantAdder constantAdder;
+ private final ExceptionsAttributeEditor exceptionsAttributeEditor;
+
+
+ /**
+ * Creates a new ExceptionAdder that will copy classes into the given
+ * target exceptions attribute.
+ */
+ public ExceptionAdder(ProgramClass targetClass,
+ ExceptionsAttribute targetExceptionsAttribute)
+ {
+ constantAdder = new ConstantAdder(targetClass);
+ exceptionsAttributeEditor = new ExceptionsAttributeEditor(targetExceptionsAttribute);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Add a class constant to the constant pool.
+ constantAdder.visitClassConstant(clazz, classConstant);
+
+ // Add the index of the class constant to the list of exceptions.
+ exceptionsAttributeEditor.addException(constantAdder.getConstantIndex());
+ }
+}
diff --git a/src/proguard/classfile/editor/ExceptionInfoAdder.java b/src/proguard/classfile/editor/ExceptionInfoAdder.java
new file mode 100644
index 000000000..c1c20fa5a
--- /dev/null
+++ b/src/proguard/classfile/editor/ExceptionInfoAdder.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.ExceptionInfoVisitor;
+
+/**
+ * This ExceptionInfoVisitor adds all exception information that it visits to
+ * the given target code attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionInfoAdder
+implements ExceptionInfoVisitor
+{
+ private final ConstantAdder constantAdder;
+ private final CodeAttributeComposer codeAttributeComposer;
+
+
+ /**
+ * Creates a new ExceptionAdder that will copy exceptions into the given
+ * target code attribute.
+ */
+ public ExceptionInfoAdder(ProgramClass targetClass,
+ CodeAttributeComposer targetComposer)
+ {
+ constantAdder = new ConstantAdder(targetClass);
+ codeAttributeComposer = targetComposer;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ // Create a copy of the exception info.
+ ExceptionInfo newExceptionInfo =
+ new ExceptionInfo(exceptionInfo.u2startPC,
+ exceptionInfo.u2endPC,
+ exceptionInfo.u2handlerPC,
+ exceptionInfo.u2catchType == 0 ? 0 :
+ constantAdder.addConstant(clazz, exceptionInfo.u2catchType));
+
+ // Add the completed exception info.
+ codeAttributeComposer.appendException(newExceptionInfo);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/ExceptionsAttributeEditor.java b/src/proguard/classfile/editor/ExceptionsAttributeEditor.java
new file mode 100644
index 000000000..98bb79ebd
--- /dev/null
+++ b/src/proguard/classfile/editor/ExceptionsAttributeEditor.java
@@ -0,0 +1,68 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.ExceptionsAttribute;
+
+/**
+ * This class can add exceptions to a given exceptions attribute.
+ * Exceptions to be added must have been added to the constant pool and filled
+ * out beforehand.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionsAttributeEditor
+{
+ private ExceptionsAttribute targetExceptionsAttribute;
+
+
+ /**
+ * Creates a new ExceptionsAttributeEditor that will edit exceptions in the
+ * given exceptions attribute.
+ */
+ public ExceptionsAttributeEditor(ExceptionsAttribute targetExceptionsAttribute)
+ {
+ this.targetExceptionsAttribute = targetExceptionsAttribute;
+ }
+
+
+ /**
+ * Adds a given exception to the exceptions attribute.
+ */
+ public void addException(int exceptionIndex)
+ {
+ int exceptionIndexTableLength = targetExceptionsAttribute.u2exceptionIndexTableLength;
+ int[] exceptionIndexTable = targetExceptionsAttribute.u2exceptionIndexTable;
+
+ // Make sure there is enough space for the new exception.
+ if (exceptionIndexTable.length <= exceptionIndexTableLength)
+ {
+ targetExceptionsAttribute.u2exceptionIndexTable = new int[exceptionIndexTableLength+1];
+ System.arraycopy(exceptionIndexTable, 0,
+ targetExceptionsAttribute.u2exceptionIndexTable, 0,
+ exceptionIndexTableLength);
+ exceptionIndexTable = targetExceptionsAttribute.u2exceptionIndexTable;
+ }
+
+ // Add the exception.
+ exceptionIndexTable[targetExceptionsAttribute.u2exceptionIndexTableLength++] = exceptionIndex;
+ }
+}
diff --git a/src/proguard/classfile/editor/InnerClassesAccessFixer.java b/src/proguard/classfile/editor/InnerClassesAccessFixer.java
new file mode 100644
index 000000000..5a5e8a574
--- /dev/null
+++ b/src/proguard/classfile/editor/InnerClassesAccessFixer.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.InnerClassesInfoVisitor;
+import proguard.classfile.attribute.InnerClassesInfo;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This InnerClassesInfoVisitor fixes the inner class access flags of the
+ * inner classes information that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class InnerClassesAccessFixer
+extends SimplifiedVisitor
+implements InnerClassesInfoVisitor,
+ ConstantVisitor,
+ ClassVisitor
+{
+ private int innerClassAccessFlags;
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ // The current access flags are the default.
+ innerClassAccessFlags = innerClassesInfo.u2innerClassAccessFlags;
+
+ // See if we can find new access flags.
+ innerClassesInfo.innerClassConstantAccept(clazz, this);
+
+ // Update the access flags.
+ innerClassesInfo.u2innerClassAccessFlags = innerClassAccessFlags;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ innerClassAccessFlags =
+ AccessUtil.replaceAccessFlags(innerClassAccessFlags,
+ programClass.u2accessFlags);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/InstructionAdder.java b/src/proguard/classfile/editor/InstructionAdder.java
new file mode 100644
index 000000000..422a348fc
--- /dev/null
+++ b/src/proguard/classfile/editor/InstructionAdder.java
@@ -0,0 +1,76 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This InstructionVisitor adds all instructions that it visits to the given
+ * target code attribute.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionAdder
+extends SimplifiedVisitor
+implements InstructionVisitor
+{
+ private final ConstantAdder constantAdder;
+ private final CodeAttributeComposer codeAttributeComposer;
+
+
+ /**
+ * Creates a new InstructionAdder that will copy classes into the given
+ * target code attribute.
+ */
+ public InstructionAdder(ProgramClass targetClass,
+ CodeAttributeComposer targetComposer)
+ {
+ constantAdder = new ConstantAdder(targetClass);
+ codeAttributeComposer = targetComposer;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ // Add the instruction.
+ codeAttributeComposer.appendInstruction(offset, instruction);
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Create a copy of the instruction.
+ Instruction newConstantInstruction =
+ new ConstantInstruction(constantInstruction.opcode,
+ constantAdder.addConstant(clazz, constantInstruction.constantIndex),
+ constantInstruction.constant);
+
+ // Add the instruction.
+ codeAttributeComposer.appendInstruction(offset, newConstantInstruction);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/InstructionWriter.java b/src/proguard/classfile/editor/InstructionWriter.java
new file mode 100644
index 000000000..c4a9b094f
--- /dev/null
+++ b/src/proguard/classfile/editor/InstructionWriter.java
@@ -0,0 +1,320 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This InstructionVisitor writes out the instructions that it visits,
+ * collecting instructions that have to be widened. As an AttributeVisitor,
+ * it then applies the collected changes. The process will be repeated
+ * recursively, if necessary. The caller still has to update the frame sizes.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionWriter
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ AttributeVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ public static boolean DEBUG = false;
+ //*/
+
+
+ private int codeLength;
+
+ private CodeAttributeEditor codeAttributeEditor;
+
+
+ /**
+ * Resets the accumulated code.
+ * @param codeLength the length of the code that will be edited next.
+ */
+ public void reset(int codeLength)
+ {
+ this.codeLength = codeLength;
+
+ if (codeAttributeEditor != null)
+ {
+ codeAttributeEditor.reset(codeLength);
+ }
+ }
+
+
+ /**
+ * Extends the size of the accumulated code.
+ * @param codeLength the length of the code that will be edited next.
+ */
+ public void extend(int codeLength)
+ {
+ this.codeLength = codeLength;
+
+ if (codeAttributeEditor != null)
+ {
+ codeAttributeEditor.extend(codeLength);
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ // Try to write out the instruction.
+ // Simple instructions should always fit.
+ simpleInstruction.write(codeAttribute, offset);
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ try
+ {
+ // Try to write out the instruction.
+ constantInstruction.write(codeAttribute, offset);
+ }
+ catch (IllegalArgumentException exception)
+ {
+ // Create a new constant instruction that will fit.
+ Instruction replacementInstruction =
+ new ConstantInstruction(constantInstruction.opcode,
+ constantInstruction.constantIndex,
+ constantInstruction.constant);
+
+ if (DEBUG)
+ {
+ System.out.println(" "+constantInstruction.toString(offset)+" will be widened to "+replacementInstruction.toString());
+ }
+
+ replaceInstruction(offset, replacementInstruction);
+
+ // Write out a dummy constant instruction for now.
+ constantInstruction.constantIndex = 0;
+ constantInstruction.constant = 0;
+ constantInstruction.write(codeAttribute, offset);
+ }
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ try
+ {
+ // Try to write out the instruction.
+ variableInstruction.write(codeAttribute, offset);
+ }
+ catch (IllegalArgumentException exception)
+ {
+ // Create a new variable instruction that will fit.
+ Instruction replacementInstruction =
+ new VariableInstruction(variableInstruction.opcode,
+ variableInstruction.variableIndex,
+ variableInstruction.constant);
+
+ replaceInstruction(offset, replacementInstruction);
+
+ if (DEBUG)
+ {
+ System.out.println(" "+variableInstruction.toString(offset)+" will be widened to "+replacementInstruction.toString());
+ }
+
+ // Write out a dummy variable instruction for now.
+ variableInstruction.variableIndex = 0;
+ variableInstruction.constant = 0;
+ variableInstruction.write(codeAttribute, offset);
+ }
+ }
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ try
+ {
+ // Try to write out the instruction.
+ branchInstruction.write(codeAttribute, offset);
+ }
+ catch (IllegalArgumentException exception)
+ {
+ // Create a new unconditional branch that will fit.
+ Instruction replacementInstruction =
+ new BranchInstruction(InstructionConstants.OP_GOTO_W,
+ branchInstruction.branchOffset);
+
+ // Create a new instruction that will fit.
+ switch (branchInstruction.opcode)
+ {
+ default:
+ {
+ // Create a new branch instruction that will fit.
+ replacementInstruction =
+ new BranchInstruction(branchInstruction.opcode,
+ branchInstruction.branchOffset);
+
+ break;
+ }
+
+ // Some special cases, for which a wide branch doesn't exist.
+ case InstructionConstants.OP_IFEQ:
+ case InstructionConstants.OP_IFNE:
+ case InstructionConstants.OP_IFLT:
+ case InstructionConstants.OP_IFGE:
+ case InstructionConstants.OP_IFGT:
+ case InstructionConstants.OP_IFLE:
+ case InstructionConstants.OP_IFICMPEQ:
+ case InstructionConstants.OP_IFICMPNE:
+ case InstructionConstants.OP_IFICMPLT:
+ case InstructionConstants.OP_IFICMPGE:
+ case InstructionConstants.OP_IFICMPGT:
+ case InstructionConstants.OP_IFICMPLE:
+ case InstructionConstants.OP_IFACMPEQ:
+ case InstructionConstants.OP_IFACMPNE:
+ {
+ // Insert the complementary conditional branch.
+ Instruction complementaryConditionalBranch =
+ new BranchInstruction((byte)(((branchInstruction.opcode+1) ^ 1) - 1),
+ (1+2) + (1+4));
+
+ insertBeforeInstruction(offset, complementaryConditionalBranch);
+
+ // Create a new unconditional branch that will fit.
+ break;
+ }
+
+ case InstructionConstants.OP_IFNULL:
+ case InstructionConstants.OP_IFNONNULL:
+ {
+ // Insert the complementary conditional branch.
+ Instruction complementaryConditionalBranch =
+ new BranchInstruction((byte)(branchInstruction.opcode ^ 1),
+ (1+2) + (1+4));
+
+ insertBeforeInstruction(offset, complementaryConditionalBranch);
+
+ // Create a new unconditional branch that will fit.
+ break;
+ }
+ }
+
+ if (DEBUG)
+ {
+ System.out.println(" "+branchInstruction.toString(offset)+" will be widened to "+replacementInstruction.toString());
+ }
+
+ replaceInstruction(offset, replacementInstruction);
+
+ // Write out a dummy branch instruction for now.
+ branchInstruction.branchOffset = 0;
+ branchInstruction.write(codeAttribute, offset);
+ }
+ }
+
+
+ public void visitAnySwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SwitchInstruction switchInstruction)
+ {
+ // Try to write out the instruction.
+ // Switch instructions should always fit.
+ switchInstruction.write(codeAttribute, offset);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Avoid doing any work if nothing is changing anyway.
+ if (codeAttributeEditor != null)
+ {
+ if (DEBUG)
+ {
+ System.out.println("InstructionWriter: widening instructions in "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ }
+
+ // Apply the collected expansions.
+ codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Don't keep the editor around. We're assuming it won't be needed
+ // very often, so we don't want to be resetting it all the time.
+ codeAttributeEditor = null;
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Remembers to place the given instruction right before the instruction
+ * at the given offset.
+ */
+ private void insertBeforeInstruction(int instructionOffset, Instruction instruction)
+ {
+ ensureCodeAttributeEditor();
+
+ // Replace the instruction.
+ codeAttributeEditor.insertBeforeInstruction(instructionOffset, instruction);
+ }
+
+
+ /**
+ * Remembers to replace the instruction at the given offset by the given
+ * instruction.
+ */
+ private void replaceInstruction(int instructionOffset, Instruction instruction)
+ {
+ ensureCodeAttributeEditor();
+
+ // Replace the instruction.
+ codeAttributeEditor.replaceInstruction(instructionOffset, instruction);
+ }
+
+
+ /**
+ * Remembers to place the given instruction right after the instruction
+ * at the given offset.
+ */
+ private void insertAfterInstruction(int instructionOffset, Instruction instruction)
+ {
+ ensureCodeAttributeEditor();
+
+ // Replace the instruction.
+ codeAttributeEditor.insertAfterInstruction(instructionOffset, instruction);
+ }
+
+
+ /**
+ * Makes sure there is a code attribute editor for the given code attribute.
+ */
+ private void ensureCodeAttributeEditor()
+ {
+ if (codeAttributeEditor == null)
+ {
+ codeAttributeEditor = new CodeAttributeEditor(false, true);
+ codeAttributeEditor.reset(codeLength);
+ }
+ }
+}
diff --git a/src/proguard/classfile/editor/InterfaceAdder.java b/src/proguard/classfile/editor/InterfaceAdder.java
new file mode 100644
index 000000000..1ad67dc9c
--- /dev/null
+++ b/src/proguard/classfile/editor/InterfaceAdder.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor adds all interfaces that it visits to the given
+ * target class.
+ *
+ * @author Eric Lafortune
+ */
+public class InterfaceAdder
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ private final ConstantAdder constantAdder;
+ private final InterfacesEditor interfacesEditor;
+
+
+ /**
+ * Creates a new InterfaceAdder that will add interfaces to the given
+ * target class.
+ */
+ public InterfaceAdder(ProgramClass targetClass)
+ {
+ constantAdder = new ConstantAdder(targetClass);
+ interfacesEditor = new InterfacesEditor(targetClass);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ interfacesEditor.addInterface(constantAdder.addConstant(clazz, classConstant));
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/InterfaceSorter.java b/src/proguard/classfile/editor/InterfaceSorter.java
new file mode 100644
index 000000000..0d1f28ceb
--- /dev/null
+++ b/src/proguard/classfile/editor/InterfaceSorter.java
@@ -0,0 +1,152 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+import java.util.*;
+
+/**
+ * This ClassVisitor sorts the interfaces of the program classes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class InterfaceSorter
+extends SimplifiedVisitor
+implements ClassVisitor,
+ AttributeVisitor
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ int[] interfaces = programClass.u2interfaces;
+ int interfacesCount = programClass.u2interfacesCount;
+
+ if (interfacesCount > 1)
+ {
+ // Sort the interfaces.
+ Arrays.sort(interfaces, 0, interfacesCount);
+
+ // Remove any duplicate entries.
+ int newInterfacesCount = 0;
+ int previousInterfaceIndex = 0;
+ for (int index = 0; index < interfacesCount; index++)
+ {
+ int interfaceIndex = interfaces[index];
+
+ // Isn't this a duplicate of the previous interface?
+ if (interfaceIndex != previousInterfaceIndex)
+ {
+ interfaces[newInterfacesCount++] = interfaceIndex;
+
+ // Remember the interface.
+ previousInterfaceIndex = interfaceIndex;
+ }
+ }
+
+ programClass.u2interfacesCount = newInterfacesCount;
+
+ // Update the signature, if any
+ programClass.attributesAccept(this);
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ // Process the generic definitions, superclass, and implemented
+ // interfaces.
+ String signature = clazz.getString(signatureAttribute.u2signatureIndex);
+
+ // Count the signature types.
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(signature);
+
+ int count = 0;
+ int interfacesCount = -1;
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ String internalType = internalTypeEnumeration.nextType();
+
+ count++;
+
+ if (ClassUtil.isInternalClassType(internalType))
+ {
+ interfacesCount++;
+ }
+ }
+
+ // Put the signature types in an array.
+ internalTypeEnumeration =
+ new InternalTypeEnumeration(signature);
+
+ String[] internalTypes = new String[count];
+
+ for (int index = 0; index < count; index++)
+ {
+ String internalType = internalTypeEnumeration.nextType();
+
+ internalTypes[index] = internalType;
+ }
+
+ // Sort the interface types in the array.
+ Arrays.sort(internalTypes, count - interfacesCount, count);
+
+ // Recompose the signature types in a string.
+ StringBuffer newSignatureBuffer = new StringBuffer();
+
+ for (int index = 0; index < count; index++)
+ {
+ // Is this not an interface type, or an interface type that isn't
+ // a duplicate of the previous interface type?
+ if (index < count - interfacesCount ||
+ !internalTypes[index].equals(internalTypes[index-1]))
+ {
+ newSignatureBuffer.append(internalTypes[index]);
+ }
+ }
+
+ String newSignature = newSignatureBuffer.toString();
+
+ // Did the signature change?
+ if (!newSignature.equals(signature))
+ {
+ // Update the signature.
+ ((Utf8Constant)((ProgramClass)clazz).constantPool[signatureAttribute.u2signatureIndex]).setString(newSignatureBuffer.toString());
+
+ // Clear the referenced classes.
+ // TODO: Properly update the referenced classes.
+ signatureAttribute.referencedClasses = null;
+ }
+ }
+}
diff --git a/src/proguard/classfile/editor/InterfacesEditor.java b/src/proguard/classfile/editor/InterfacesEditor.java
new file mode 100644
index 000000000..8765e36c3
--- /dev/null
+++ b/src/proguard/classfile/editor/InterfacesEditor.java
@@ -0,0 +1,122 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+
+import java.util.Arrays;
+
+/**
+ * This class can add and delete interfaces to and from classes. References to
+ * the constant pool must be filled out beforehand.
+ *
+ * @author Eric Lafortune
+ */
+public class InterfacesEditor
+{
+ private final ProgramClass targetClass;
+
+
+ /**
+ * Creates a new InterfacesEditor that will edit interfaces in the given
+ * target class.
+ */
+ public InterfacesEditor(ProgramClass targetClass)
+ {
+ this.targetClass = targetClass;
+ }
+
+
+ /**
+ * Adds the specified interface to the target class, if it isn't present yet.
+ */
+ public void addInterface(int interfaceConstantIndex)
+ {
+ // Is the interface not yet present?
+ if (findInterfaceIndex(interfaceConstantIndex) < 0)
+ {
+ int interfacesCount = targetClass.u2interfacesCount++;
+ int[] interfaces = targetClass.u2interfaces;
+
+ // Is the array too small to contain the additional interface?
+ if (interfaces.length <= interfacesCount)
+ {
+ // Create a new array and copy the interfaces into it.
+ int[] newinterfaces = new int[interfacesCount + 1];
+ System.arraycopy(interfaces, 0, newinterfaces, 0, interfacesCount);
+ interfaces = newinterfaces;
+
+ targetClass.u2interfaces = interfaces;
+ }
+
+ // Append the interface.
+ interfaces[interfacesCount] = interfaceConstantIndex;
+ }
+ }
+
+
+ /**
+ * Deletes the given interface from the target class, if it is present.
+ */
+ public void deleteInterface(int interfaceConstantIndex)
+ {
+ // Is the interface already present?
+ int interfaceIndex = findInterfaceIndex(interfaceConstantIndex);
+ if (interfaceIndex >= 0)
+ {
+ int interfacesCount = --targetClass.u2interfacesCount;
+ int[] interfaces = targetClass.u2interfaces;
+
+ // Shift the other interfaces in the array.
+ for (int index = interfaceIndex; index < interfacesCount; index++)
+ {
+ interfaces[index] = interfaces[index + 1];
+ }
+
+ // Clear the remaining entry in the array.
+ interfaces[interfacesCount] = 0;
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Finds the index of the specified interface in the list of interfaces of
+ * the target class.
+ */
+ private int findInterfaceIndex(int interfaceConstantIndex)
+ {
+ int interfacesCount = targetClass.u2interfacesCount;
+ int[] interfaces = targetClass.u2interfaces;
+
+ for (int index = 0; index < interfacesCount; index++)
+ {
+ if (interfaces[index] == interfaceConstantIndex)
+ {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/LineNumberInfoAdder.java b/src/proguard/classfile/editor/LineNumberInfoAdder.java
new file mode 100644
index 000000000..e1bd14a4d
--- /dev/null
+++ b/src/proguard/classfile/editor/LineNumberInfoAdder.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.visitor.LineNumberInfoVisitor;
+import proguard.classfile.attribute.*;
+import proguard.classfile.*;
+
+/**
+ * This LineNumberInfoVisitor adds all line numbers that it visits to the given
+ * target line number attribute.
+ */
+public class LineNumberInfoAdder
+implements LineNumberInfoVisitor
+{
+ private final LineNumberTableAttributeEditor lineNumberTableAttributeEditor;
+
+
+ /**
+ * Creates a new LineNumberInfoAdder that will copy line numbers into the
+ * given target line number table.
+ */
+ public LineNumberInfoAdder(LineNumberTableAttribute targetLineNumberTableAttribute)
+ {
+ this.lineNumberTableAttributeEditor = new LineNumberTableAttributeEditor(targetLineNumberTableAttribute);
+ }
+
+
+ // Implementations for LineNumberInfoVisitor.
+
+ public void visitLineNumberInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberInfo lineNumberInfo)
+ {
+ // Create a new line number.
+ LineNumberInfo newLineNumberInfo =
+ new LineNumberInfo(lineNumberInfo.u2startPC,
+ lineNumberInfo.u2lineNumber);
+
+ // Add it to the target.
+ lineNumberTableAttributeEditor.addLineNumberInfo(newLineNumberInfo);
+ }
+}
diff --git a/src/proguard/classfile/editor/LineNumberTableAttributeEditor.java b/src/proguard/classfile/editor/LineNumberTableAttributeEditor.java
new file mode 100644
index 000000000..f712d4697
--- /dev/null
+++ b/src/proguard/classfile/editor/LineNumberTableAttributeEditor.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.*;
+
+/**
+ * This class can add line numbers to a given line number table attribute.
+ * Line numbers to be added must have been filled out beforehand.
+ *
+ * @author Eric Lafortune
+ */
+public class LineNumberTableAttributeEditor
+{
+ private LineNumberTableAttribute targetLineNumberTableAttribute;
+
+
+ /**
+ * Creates a new LineNumberTableAttributeEditor that will edit line numbers
+ * in the given line number table attribute.
+ */
+ public LineNumberTableAttributeEditor(LineNumberTableAttribute targetLineNumberTableAttribute)
+ {
+ this.targetLineNumberTableAttribute = targetLineNumberTableAttribute;
+ }
+
+
+ /**
+ * Adds a given line number to the line number table attribute.
+ */
+ public void addLineNumberInfo(LineNumberInfo lineNumberInfo)
+ {
+ int lineNumberTableLength = targetLineNumberTableAttribute.u2lineNumberTableLength;
+ LineNumberInfo[] lineNumberTable = targetLineNumberTableAttribute.lineNumberTable;
+
+ // Make sure there is enough space for the new lineNumberInfo.
+ if (lineNumberTable.length <= lineNumberTableLength)
+ {
+ targetLineNumberTableAttribute.lineNumberTable = new LineNumberInfo[lineNumberTableLength+1];
+ System.arraycopy(lineNumberTable, 0,
+ targetLineNumberTableAttribute.lineNumberTable, 0,
+ lineNumberTableLength);
+ lineNumberTable = targetLineNumberTableAttribute.lineNumberTable;
+ }
+
+ // Add the lineNumberInfo.
+ lineNumberTable[targetLineNumberTableAttribute.u2lineNumberTableLength++] = lineNumberInfo;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/LocalVariableInfoAdder.java b/src/proguard/classfile/editor/LocalVariableInfoAdder.java
new file mode 100644
index 000000000..a270fcf8b
--- /dev/null
+++ b/src/proguard/classfile/editor/LocalVariableInfoAdder.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.visitor.LocalVariableInfoVisitor;
+import proguard.classfile.attribute.*;
+import proguard.classfile.*;
+
+/**
+ * This LocalVariableInfoVisitor adds all line numbers that it visits to the given
+ * target line number attribute.
+ */
+public class LocalVariableInfoAdder
+implements LocalVariableInfoVisitor
+{
+ private final ConstantAdder constantAdder;
+ private final LocalVariableTableAttributeEditor localVariableTableAttributeEditor;
+
+
+ /**
+ * Creates a new LocalVariableInfoAdder that will copy line numbers into the
+ * given target line number table.
+ */
+ public LocalVariableInfoAdder(ProgramClass targetClass,
+ LocalVariableTableAttribute targetLocalVariableTableAttribute)
+ {
+ this.constantAdder = new ConstantAdder(targetClass);
+ this.localVariableTableAttributeEditor = new LocalVariableTableAttributeEditor(targetLocalVariableTableAttribute);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ // Create a new line number.
+ LocalVariableInfo newLocalVariableInfo =
+ new LocalVariableInfo(localVariableInfo.u2startPC,
+ localVariableInfo.u2length,
+ constantAdder.addConstant(clazz, localVariableInfo.u2nameIndex),
+ constantAdder.addConstant(clazz, localVariableInfo.u2descriptorIndex),
+ localVariableInfo.u2index);
+
+ newLocalVariableInfo.referencedClass = localVariableInfo.referencedClass;
+
+ // Add it to the target.
+ localVariableTableAttributeEditor.addLocalVariableInfo(newLocalVariableInfo);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/LocalVariableTableAttributeEditor.java b/src/proguard/classfile/editor/LocalVariableTableAttributeEditor.java
new file mode 100644
index 000000000..b9e601fa1
--- /dev/null
+++ b/src/proguard/classfile/editor/LocalVariableTableAttributeEditor.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.*;
+
+/**
+ * This class can add local variables to a given local variable table attribute.
+ * Local variables to be added must have been filled out beforehand.
+ *
+ * @author Eric Lafortune
+ */
+public class LocalVariableTableAttributeEditor
+{
+ private LocalVariableTableAttribute targetLocalVariableTableAttribute;
+
+
+ /**
+ * Creates a new LocalVariableTableAttributeEditor that will edit line numbers
+ * in the given line number table attribute.
+ */
+ public LocalVariableTableAttributeEditor(LocalVariableTableAttribute targetLocalVariableTableAttribute)
+ {
+ this.targetLocalVariableTableAttribute = targetLocalVariableTableAttribute;
+ }
+
+
+ /**
+ * Adds a given line number to the line number table attribute.
+ */
+ public void addLocalVariableInfo(LocalVariableInfo localVariableInfo)
+ {
+ int localVariableTableLength = targetLocalVariableTableAttribute.u2localVariableTableLength;
+ LocalVariableInfo[] localVariableTable = targetLocalVariableTableAttribute.localVariableTable;
+
+ // Make sure there is enough space for the new localVariableInfo.
+ if (localVariableTable.length <= localVariableTableLength)
+ {
+ targetLocalVariableTableAttribute.localVariableTable = new LocalVariableInfo[localVariableTableLength+1];
+ System.arraycopy(localVariableTable, 0,
+ targetLocalVariableTableAttribute.localVariableTable, 0,
+ localVariableTableLength);
+ localVariableTable = targetLocalVariableTableAttribute.localVariableTable;
+ }
+
+ // Add the localVariableInfo.
+ localVariableTable[targetLocalVariableTableAttribute.u2localVariableTableLength++] = localVariableInfo;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/LocalVariableTypeInfoAdder.java b/src/proguard/classfile/editor/LocalVariableTypeInfoAdder.java
new file mode 100644
index 000000000..bed1366a9
--- /dev/null
+++ b/src/proguard/classfile/editor/LocalVariableTypeInfoAdder.java
@@ -0,0 +1,68 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.visitor.LocalVariableTypeInfoVisitor;
+import proguard.classfile.attribute.*;
+import proguard.classfile.*;
+
+/**
+ * This LocalVariableTypeInfoVisitor adds all line numbers that it visits to the given
+ * target line number attribute.
+ */
+public class LocalVariableTypeInfoAdder
+implements LocalVariableTypeInfoVisitor
+{
+ private final ConstantAdder constantAdder;
+ private final LocalVariableTypeTableAttributeEditor localVariableTypeTableAttributeEditor;
+
+
+ /**
+ * Creates a new LocalVariableTypeInfoAdder that will copy line numbers into the
+ * given target line number table.
+ */
+ public LocalVariableTypeInfoAdder(ProgramClass targetClass,
+ LocalVariableTypeTableAttribute targetLocalVariableTypeTableAttribute)
+ {
+ this.constantAdder = new ConstantAdder(targetClass);
+ this.localVariableTypeTableAttributeEditor = new LocalVariableTypeTableAttributeEditor(targetLocalVariableTypeTableAttribute);
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ // Create a new line number.
+ LocalVariableTypeInfo newLocalVariableTypeInfo =
+ new LocalVariableTypeInfo(localVariableTypeInfo.u2startPC,
+ localVariableTypeInfo.u2length,
+ constantAdder.addConstant(clazz, localVariableTypeInfo.u2nameIndex),
+ constantAdder.addConstant(clazz, localVariableTypeInfo.u2signatureIndex),
+ localVariableTypeInfo.u2index);
+
+ // TODO: Clone array.
+ newLocalVariableTypeInfo.referencedClasses = localVariableTypeInfo.referencedClasses;
+
+ // Add it to the target.
+ localVariableTypeTableAttributeEditor.addLocalVariableTypeInfo(newLocalVariableTypeInfo);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/LocalVariableTypeTableAttributeEditor.java b/src/proguard/classfile/editor/LocalVariableTypeTableAttributeEditor.java
new file mode 100644
index 000000000..00f7ef3de
--- /dev/null
+++ b/src/proguard/classfile/editor/LocalVariableTypeTableAttributeEditor.java
@@ -0,0 +1,68 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.*;
+
+/**
+ * This class can add local variables to a given local variable type table
+ * attribute.
+ * Local variable types to be added must have been filled out beforehand.
+ *
+ * @author Eric Lafortune
+ */
+public class LocalVariableTypeTableAttributeEditor
+{
+ private LocalVariableTypeTableAttribute targetLocalVariableTypeTableAttribute;
+
+
+ /**
+ * Creates a new LocalVariableTypeTableAttributeEditor that will edit line numbers
+ * in the given line number table attribute.
+ */
+ public LocalVariableTypeTableAttributeEditor(LocalVariableTypeTableAttribute targetLocalVariableTypeTableAttribute)
+ {
+ this.targetLocalVariableTypeTableAttribute = targetLocalVariableTypeTableAttribute;
+ }
+
+
+ /**
+ * Adds a given line number to the line number table attribute.
+ */
+ public void addLocalVariableTypeInfo(LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ int localVariableTypeTableLength = targetLocalVariableTypeTableAttribute.u2localVariableTypeTableLength;
+ LocalVariableTypeInfo[] localVariableTypeTable = targetLocalVariableTypeTableAttribute.localVariableTypeTable;
+
+ // Make sure there is enough space for the new localVariableTypeInfo.
+ if (localVariableTypeTable.length <= localVariableTypeTableLength)
+ {
+ targetLocalVariableTypeTableAttribute.localVariableTypeTable = new LocalVariableTypeInfo[localVariableTypeTableLength+1];
+ System.arraycopy(localVariableTypeTable, 0,
+ targetLocalVariableTypeTableAttribute.localVariableTypeTable, 0,
+ localVariableTypeTableLength);
+ localVariableTypeTable = targetLocalVariableTypeTableAttribute.localVariableTypeTable;
+ }
+
+ // Add the localVariableTypeInfo.
+ localVariableTypeTable[targetLocalVariableTypeTableAttribute.u2localVariableTypeTableLength++] = localVariableTypeInfo;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/MemberAdder.java b/src/proguard/classfile/editor/MemberAdder.java
new file mode 100644
index 000000000..811acae7e
--- /dev/null
+++ b/src/proguard/classfile/editor/MemberAdder.java
@@ -0,0 +1,294 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This MemberVisitor copies all class members that it visits to the given
+ * target class. Their visitor info is set to the class members from which they
+ * were copied.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberAdder
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+
+ private static final Attribute[] EMPTY_ATTRIBUTES = new Attribute[0];
+
+
+ private final ProgramClass targetClass;
+// private final boolean addFields;
+ private final MemberVisitor extraMemberVisitor;
+
+ private final ConstantAdder constantAdder;
+ private final ClassEditor classEditor;
+ private final ConstantPoolEditor constantPoolEditor;
+
+
+ /**
+ * Creates a new MemberAdder that will copy methods into the given target
+ * class.
+ * @param targetClass the class to which all visited class members will be
+ * added.
+ */
+ public MemberAdder(ProgramClass targetClass)
+ {
+ this(targetClass, null);
+ }
+
+
+ /**
+ * Creates a new MemberAdder that will copy methods into the given target
+ * class.
+ * @param targetClass the class to which all visited class members
+ * will be added.
+ * @param extraMemberVisitor an optional member visitor that visits each
+ * new member right after it has been added. This
+ * allows changing the visitor info, for instance.
+ */
+// * @param addFields specifies whether fields should be added, or fused
+// * with the present fields.
+ public MemberAdder(ProgramClass targetClass,
+// boolean addFields,
+ MemberVisitor extraMemberVisitor)
+ {
+ this.targetClass = targetClass;
+// this.addFields = addFields;
+ this.extraMemberVisitor = extraMemberVisitor;
+
+ constantAdder = new ConstantAdder(targetClass);
+ classEditor = new ClassEditor(targetClass);
+ constantPoolEditor = new ConstantPoolEditor(targetClass);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ //String name = programField.getName(programClass);
+ //String descriptor = programField.getDescriptor(programClass);
+ int accessFlags = programField.getAccessFlags();
+
+ // TODO: Handle field with the same name and descriptor in the target class.
+ // We currently avoid this case, since renaming the identical field
+ // still causes confused field references.
+ //// Does the target class already have such a field?
+ //ProgramField targetField = (ProgramField)targetClass.findField(name, descriptor);
+ //if (targetField != null)
+ //{
+ // // Is the field private or static?
+ // int targetAccessFlags = targetField.getAccessFlags();
+ // if ((targetAccessFlags &
+ // (ClassConstants.INTERNAL_ACC_PRIVATE |
+ // ClassConstants.INTERNAL_ACC_STATIC)) != 0)
+ // {
+ // if (DEBUG)
+ // {
+ // System.out.println("MemberAdder: renaming field ["+targetClass+"."+targetField.getName(targetClass)+" "+targetField.getDescriptor(targetClass)+"]");
+ // }
+ //
+ // // Rename the private or static field.
+ // targetField.u2nameIndex =
+ // constantPoolEditor.addUtf8Constant(newUniqueMemberName(name, targetClass.getName()));
+ // }
+ // else
+ // {
+ // // Keep the non-private and non-static field, but update its
+ // // contents, in order to keep any references to it valid.
+ // if (DEBUG)
+ // {
+ // System.out.println("MemberAdder: updating field ["+programClass+"."+programField.getName(programClass)+" "+programField.getDescriptor(programClass)+"] into ["+targetClass.getName()+"]");
+ // }
+ //
+ // // Combine the access flags.
+ // targetField.u2accessFlags = accessFlags | targetAccessFlags;
+ //
+ // // Add and replace any attributes.
+ // programField.attributesAccept(programClass,
+ // new AttributeAdder(targetClass,
+ // targetField,
+ // true));
+ //
+ // // Don't add a new field.
+ // return;
+ // }
+ //}
+
+ if (DEBUG)
+ {
+ System.out.println("MemberAdder: copying field ["+programClass+"."+programField.getName(programClass)+" "+programField.getDescriptor(programClass)+"] into ["+targetClass.getName()+"]");
+ }
+
+ // Create a copy of the field.
+ ProgramField newProgramField =
+ new ProgramField(accessFlags,
+ constantAdder.addConstant(programClass, programField.u2nameIndex),
+ constantAdder.addConstant(programClass, programField.u2descriptorIndex),
+ 0,
+ programField.u2attributesCount > 0 ?
+ new Attribute[programField.u2attributesCount] :
+ EMPTY_ATTRIBUTES,
+ programField.referencedClass);
+
+ // Link to its visitor info.
+ newProgramField.setVisitorInfo(programField);
+
+ // Copy its attributes.
+ programField.attributesAccept(programClass,
+ new AttributeAdder(targetClass,
+ newProgramField,
+ false));
+
+ // Add the completed field.
+ classEditor.addField(newProgramField);
+
+ // Visit the newly added field, if necessary.
+ if (extraMemberVisitor != null)
+ {
+ extraMemberVisitor.visitProgramField(targetClass, newProgramField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ String name = programMethod.getName(programClass);
+ String descriptor = programMethod.getDescriptor(programClass);
+ int accessFlags = programMethod.getAccessFlags();
+
+ // Does the target class already have such a method?
+ ProgramMethod targetMethod = (ProgramMethod)targetClass.findMethod(name, descriptor);
+ if (targetMethod != null)
+ {
+ // is this source method abstract?
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_ABSTRACT) != 0)
+ {
+ // Keep the target method.
+ if (DEBUG)
+ {
+ System.out.println("MemberAdder: skipping abstract method ["+programClass.getName()+"."+programMethod.getName(programClass)+programMethod.getDescriptor(programClass)+"] into ["+targetClass.getName()+"]");
+ }
+
+ // Don't add a new method.
+ return;
+ }
+
+ // Is the target method abstract?
+ int targetAccessFlags = targetMethod.getAccessFlags();
+ if ((targetAccessFlags & ClassConstants.INTERNAL_ACC_ABSTRACT) != 0)
+ {
+ // Keep the abstract method, but update its contents, in order
+ // to keep any references to it valid.
+ if (DEBUG)
+ {
+ System.out.println("MemberAdder: updating method ["+programClass.getName()+"."+programMethod.getName(programClass)+programMethod.getDescriptor(programClass)+"] into ["+targetClass.getName()+"]");
+ }
+
+ // Replace the access flags.
+ targetMethod.u2accessFlags =
+ accessFlags & ~ClassConstants.INTERNAL_ACC_FINAL;
+
+ // Add and replace the attributes.
+ programMethod.attributesAccept(programClass,
+ new AttributeAdder(targetClass,
+ targetMethod,
+ true));
+
+ // Don't add a new method.
+ return;
+ }
+
+ if (DEBUG)
+ {
+ System.out.println("MemberAdder: renaming method ["+targetClass.getName()+"."+targetMethod.getName(targetClass)+targetMethod.getDescriptor(targetClass)+"]");
+ }
+
+ // TODO: Handle non-abstract method with the same name and descriptor in the target class.
+ // We currently avoid this case, since renaming the identical method
+ // still causes confused method references.
+ //// Rename the private (non-abstract) or static method.
+ //targetMethod.u2nameIndex =
+ // constantPoolEditor.addUtf8Constant(newUniqueMemberName(name, descriptor));
+ }
+
+ if (DEBUG)
+ {
+ System.out.println("MemberAdder: copying method ["+programClass.getName()+"."+programMethod.getName(programClass)+programMethod.getDescriptor(programClass)+"] into ["+targetClass.getName()+"]");
+ }
+
+ // Create a copy of the method.
+ ProgramMethod newProgramMethod =
+ new ProgramMethod(accessFlags & ~ClassConstants.INTERNAL_ACC_FINAL,
+ constantAdder.addConstant(programClass, programMethod.u2nameIndex),
+ constantAdder.addConstant(programClass, programMethod.u2descriptorIndex),
+ 0,
+ programMethod.u2attributesCount > 0 ?
+ new Attribute[programMethod.u2attributesCount] :
+ EMPTY_ATTRIBUTES,
+ programMethod.referencedClasses != null ?
+ (Clazz[])programMethod.referencedClasses.clone() :
+ null);
+
+ // Link to its visitor info.
+ newProgramMethod.setVisitorInfo(programMethod);
+
+ // Copy its attributes.
+ programMethod.attributesAccept(programClass,
+ new AttributeAdder(targetClass,
+ newProgramMethod,
+ false));
+
+ // Add the completed method.
+ classEditor.addMethod(newProgramMethod);
+
+ // Visit the newly added method, if necessary.
+ if (extraMemberVisitor != null)
+ {
+ extraMemberVisitor.visitProgramMethod(targetClass, newProgramMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns a unique class member name, based on the given name and descriptor.
+ */
+ private String newUniqueMemberName(String name, String descriptor)
+ {
+ return name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT) ?
+ ClassConstants.INTERNAL_METHOD_NAME_INIT :
+ name + ClassConstants.SPECIAL_MEMBER_SEPARATOR + Long.toHexString(Math.abs((descriptor).hashCode()));
+ }
+}
diff --git a/src/proguard/classfile/editor/MemberReferenceFixer.java b/src/proguard/classfile/editor/MemberReferenceFixer.java
new file mode 100644
index 000000000..b62304789
--- /dev/null
+++ b/src/proguard/classfile/editor/MemberReferenceFixer.java
@@ -0,0 +1,447 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ClassVisitor fixes constant pool field and method references to fields
+ * and methods whose names or descriptors have changed.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberReferenceFixer
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ MemberVisitor,
+ AttributeVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ private static final boolean DEBUG = false;
+
+
+ private final StackSizeUpdater stackSizeUpdater = new StackSizeUpdater();
+
+ // Parameter for the visitor methods.
+ private int constantIndex;
+
+ // Return values for the visitor methods.
+ private boolean isInterfaceMethod;
+ private boolean stackSizesMayHaveChanged;
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ stackSizesMayHaveChanged = false;
+
+ // Fix the constant pool entries.
+ for (int index = 1; index < programClass.u2constantPoolCount; index++)
+ {
+ Constant constant = programClass.constantPool[index];
+ if (constant != null)
+ {
+ // Fix the entry, replacing it entirely if needed.
+ this.constantIndex = index;
+
+ constant.accept(programClass, this);
+ }
+ }
+
+ // Fix the class members.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ // Fix the attributes.
+ programClass.attributesAccept(this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ // Does the string refer to a class member, due to a
+ // Class.get[Declared]{Field,Method} construct?
+ Member referencedMember = stringConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ Clazz referencedClass = stringConstant.referencedClass;
+
+ // Does it have a new name?
+ String newName = referencedMember.getName(referencedClass);
+
+ if (!stringConstant.getString(clazz).equals(newName))
+ {
+ if (DEBUG)
+ {
+ debug(clazz, stringConstant, referencedClass, referencedMember);
+ }
+
+ // Update the name.
+ stringConstant.u2stringIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newName);
+ }
+ }
+ }
+
+
+ public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
+ {
+ // Do we know the referenced field?
+ Member referencedMember = fieldrefConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ Clazz referencedClass = fieldrefConstant.referencedClass;
+
+ // Does it have a new name or type?
+ String newName = referencedMember.getName(referencedClass);
+ String newType = referencedMember.getDescriptor(referencedClass);
+
+ if (!fieldrefConstant.getName(clazz).equals(newName) ||
+ !fieldrefConstant.getType(clazz).equals(newType))
+ {
+ if (DEBUG)
+ {
+ debug(clazz, fieldrefConstant, referencedClass, referencedMember);
+ }
+
+ // Update the name and type index.
+ fieldrefConstant.u2nameAndTypeIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addNameAndTypeConstant(newName, newType);
+ }
+ }
+ }
+
+
+ public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant)
+ {
+ // Do we know the referenced interface method?
+ Member referencedMember = interfaceMethodrefConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ Clazz referencedClass = interfaceMethodrefConstant.referencedClass;
+
+ // Does it have a new name or type?
+ String newName = referencedMember.getName(referencedClass);
+ String newType = referencedMember.getDescriptor(referencedClass);
+
+ if (!interfaceMethodrefConstant.getName(clazz).equals(newName) ||
+ !interfaceMethodrefConstant.getType(clazz).equals(newType))
+ {
+ if (DEBUG)
+ {
+ debug(clazz, interfaceMethodrefConstant, referencedClass, referencedMember);
+ }
+
+ // Update the name and type index.
+ interfaceMethodrefConstant.u2nameAndTypeIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addNameAndTypeConstant(newName, newType);
+
+ // Remember that the stack sizes of the methods in this class
+ // may have changed.
+ stackSizesMayHaveChanged = true;
+ }
+
+ // Check if this is an interface method.
+ isInterfaceMethod = true;
+ clazz.constantPoolEntryAccept(interfaceMethodrefConstant.u2classIndex, this);
+
+ // Has the method become a non-interface method?
+ if (!isInterfaceMethod)
+ {
+ if (DEBUG)
+ {
+ System.out.println("MemberReferenceFixer:");
+ System.out.println(" Class file = "+clazz.getName());
+ System.out.println(" Ref class = "+referencedClass.getName());
+ System.out.println(" Ref method = "+interfaceMethodrefConstant.getName(clazz)+interfaceMethodrefConstant.getType(clazz));
+ System.out.println(" -> ordinary method");
+ }
+
+ // Replace the interface method reference by a method reference.
+ ((ProgramClass)clazz).constantPool[this.constantIndex] =
+ new MethodrefConstant(interfaceMethodrefConstant.u2classIndex,
+ interfaceMethodrefConstant.u2nameAndTypeIndex,
+ referencedClass,
+ referencedMember);
+ }
+ }
+ }
+
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ // Do we know the referenced method?
+ Member referencedMember = methodrefConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ Clazz referencedClass = methodrefConstant.referencedClass;
+
+ // Does it have a new name or type?
+ String newName = referencedMember.getName(referencedClass);
+ String newType = referencedMember.getDescriptor(referencedClass);
+
+ if (!methodrefConstant.getName(clazz).equals(newName) ||
+ !methodrefConstant.getType(clazz).equals(newType))
+ {
+ if (DEBUG)
+ {
+ debug(clazz, methodrefConstant, referencedClass, referencedMember);
+ }
+
+ // Update the name and type index.
+ methodrefConstant.u2nameAndTypeIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addNameAndTypeConstant(newName, newType);
+
+ // Remember that the stack sizes of the methods in this class
+ // may have changed.
+ stackSizesMayHaveChanged = true;
+ }
+
+ // Check if this is an interface method.
+ isInterfaceMethod = false;
+ clazz.constantPoolEntryAccept(methodrefConstant.u2classIndex, this);
+
+ // Has the method become an interface method?
+ if (isInterfaceMethod)
+ {
+ if (DEBUG)
+ {
+ System.out.println("MemberReferenceFixer:");
+ System.out.println(" Class file = "+clazz.getName());
+ System.out.println(" Ref class = "+referencedClass.getName());
+ System.out.println(" Ref method = "+methodrefConstant.getName(clazz)+methodrefConstant.getType(clazz));
+ System.out.println(" -> interface method");
+ }
+
+ // Replace the method reference by an interface method reference.
+ ((ProgramClass)clazz).constantPool[this.constantIndex] =
+ new InterfaceMethodrefConstant(methodrefConstant.u2classIndex,
+ methodrefConstant.u2nameAndTypeIndex,
+ referencedClass,
+ referencedMember);
+ }
+ }
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Check if this class entry is an array type.
+ if (ClassUtil.isInternalArrayType(classConstant.getName(clazz)))
+ {
+ isInterfaceMethod = false;
+ }
+ else
+ {
+ // Check if this class entry refers to an interface class.
+ Clazz referencedClass = classConstant.referencedClass;
+ if (referencedClass != null)
+ {
+ isInterfaceMethod = (referencedClass.getAccessFlags() & ClassConstants.INTERNAL_ACC_INTERFACE) != 0;
+ }
+ }
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ // Fix the attributes.
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ Member referencedMember = enclosingMethodAttribute.referencedMethod;
+ if (referencedMember != null)
+ {
+ Clazz referencedClass = enclosingMethodAttribute.referencedClass;
+
+ // Does it have a new name or type?
+ String newName = referencedMember.getName(referencedClass);
+ String newType = referencedMember.getDescriptor(referencedClass);
+
+ if (!enclosingMethodAttribute.getName(clazz).equals(newName) ||
+ !enclosingMethodAttribute.getType(clazz).equals(newType))
+ {
+ // Update the name and type index.
+ enclosingMethodAttribute.u2nameAndTypeIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addNameAndTypeConstant(newName,
+ newType);
+ }
+ }
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Recompute the maximum stack size if necessary.
+ if (stackSizesMayHaveChanged)
+ {
+ stackSizeUpdater.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+ // Fix the nested attributes.
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ // Fix the annotations.
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ // Fix the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ // Fix the annotation.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ // Fix the element values.
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ fixElementValue(clazz, annotation, constantElementValue);
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ fixElementValue(clazz, annotation, enumConstantElementValue);
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ fixElementValue(clazz, annotation, classElementValue);
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ fixElementValue(clazz, annotation, annotationElementValue);
+
+ // Fix the annotation.
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ fixElementValue(clazz, annotation, arrayElementValue);
+
+ // Fix the element values.
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Fixes the method reference of the element value, if any.
+ */
+ private void fixElementValue(Clazz clazz,
+ Annotation annotation,
+ ElementValue elementValue)
+ {
+ // Do we know the referenced method?
+ Member referencedMember = elementValue.referencedMethod;
+ if (referencedMember != null)
+ {
+ // Does it have a new name or type?
+ String methodName = elementValue.getMethodName(clazz);
+ String newMethodName = referencedMember.getName(elementValue.referencedClass);
+
+ if (!methodName.equals(newMethodName))
+ {
+ // Update the element name index.
+ elementValue.u2elementNameIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newMethodName);
+ }
+ }
+ }
+
+
+ private void debug(Clazz clazz,
+ StringConstant stringConstant,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ System.out.println("MemberReferenceFixer:");
+ System.out.println(" ["+clazz.getName()+"]: String ["+
+ stringConstant.getString(clazz)+"] -> ["+
+ referencedClass.getName()+"."+referencedMember.getName(referencedClass)+" "+referencedMember.getDescriptor(referencedClass)+"]");
+ }
+
+
+ private void debug(Clazz clazz,
+ RefConstant refConstant,
+ Clazz referencedClass,
+ Member referencedMember)
+ {
+ System.out.println("MemberReferenceFixer:");
+ System.out.println(" ["+clazz.getName()+"]: ["+
+ refConstant.getClassName(clazz)+"."+refConstant.getName(clazz)+" "+refConstant.getType(clazz)+"] -> ["+
+ referencedClass.getName()+"."+referencedMember.getName(referencedClass)+" "+referencedMember.getDescriptor(referencedClass)+"]");
+ }
+}
diff --git a/src/proguard/classfile/editor/MethodInvocationFixer.java b/src/proguard/classfile/editor/MethodInvocationFixer.java
new file mode 100644
index 000000000..e457e6328
--- /dev/null
+++ b/src/proguard/classfile/editor/MethodInvocationFixer.java
@@ -0,0 +1,243 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+
+/**
+ * This AttributeVisitor fixes all inappropriate special/virtual/static/interface
+ * invocations of the code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodInvocationFixer
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ConstantVisitor
+{
+ private static final boolean DEBUG = false;
+
+
+ private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor();
+
+ // Return values for the visitor methods.
+ private Clazz referencedClass;
+ private Clazz referencedMethodClass;
+ private Member referencedMethod;
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Reset the code attribute editor.
+ codeAttributeEditor.reset(codeAttribute.u4codeLength);
+
+ // Remap the variables of the instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ // Apply the code atribute editor.
+ codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ int constantIndex = constantInstruction.constantIndex;
+
+ // Get information on the called class and method, if present.
+ referencedMethod = null;
+
+ clazz.constantPoolEntryAccept(constantIndex, this);
+
+ // Did we find the called class and method?
+ if (referencedClass != null &&
+ referencedMethod != null)
+ {
+ // Do we need to update the opcode?
+ byte opcode = constantInstruction.opcode;
+
+ // Is the method static?
+ if ((referencedMethod.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0)
+ {
+ // But is it not a static invocation?
+ if (opcode != InstructionConstants.OP_INVOKESTATIC)
+ {
+ // Replace the invocation by an invokestatic instruction.
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC,
+ constantIndex);
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+
+ if (DEBUG)
+ {
+ debug(clazz, method, offset, constantInstruction, replacementInstruction);
+ }
+ }
+ }
+
+ // Is the method private, or an instance initializer?
+ else if ((referencedMethod.getAccessFlags() & ClassConstants.INTERNAL_ACC_PRIVATE) != 0 ||
+ referencedMethod.getName(referencedMethodClass).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
+ {
+ // But is it not a special invocation?
+ if (opcode != InstructionConstants.OP_INVOKESPECIAL)
+ {
+ // Replace the invocation by an invokespecial instruction.
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL,
+ constantIndex);
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+
+ if (DEBUG)
+ {
+ debug(clazz, method, offset, constantInstruction, replacementInstruction);
+ }
+ }
+ }
+
+ // Is the method an interface method?
+ else if ((referencedClass.getAccessFlags() & ClassConstants.INTERNAL_ACC_INTERFACE) != 0)
+ {
+ int invokeinterfaceConstant =
+ (ClassUtil.internalMethodParameterSize(referencedMethod.getDescriptor(referencedMethodClass), false)) << 8;
+
+ // But is it not an interface invocation, or is the parameter
+ // size incorrect?
+ if (opcode != InstructionConstants.OP_INVOKEINTERFACE ||
+ constantInstruction.constant != invokeinterfaceConstant)
+ {
+ // Fix the parameter size of the interface invocation.
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_INVOKEINTERFACE,
+ constantIndex,
+ invokeinterfaceConstant);
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+
+ if (DEBUG)
+ {
+ debug(clazz, method, offset, constantInstruction, replacementInstruction);
+ }
+ }
+ }
+
+ // The method is not static, private, an instance initializer, or
+ // an interface method.
+ else
+ {
+ // But is it not a virtual invocation (or a special invocation,
+ // but not a super call)?
+ if (opcode != InstructionConstants.OP_INVOKEVIRTUAL &&
+ (opcode != InstructionConstants.OP_INVOKESPECIAL ||
+ clazz.equals(referencedClass) ||
+ !clazz.extends_(referencedClass)))
+ {
+ // Replace the invocation by an invokevirtual instruction.
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL,
+ constantIndex);
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+
+ if (DEBUG)
+ {
+ debug(clazz, method, offset, constantInstruction, replacementInstruction);
+ }
+ }
+ }
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitAnyMethodrefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ // Remember the referenced class. Note that we're interested in the
+ // class of the method reference, not in the class in which the
+ // method was actually found, unless it is an array type.
+ //
+ if (ClassUtil.isInternalArrayType(refConstant.getClassName(clazz)))
+ {
+ // For an array type, the class will be java.lang.Object.
+ referencedClass = refConstant.referencedClass;
+ }
+ else
+ {
+ clazz.constantPoolEntryAccept(refConstant.u2classIndex, this);
+ }
+
+ // Remember the referenced method.
+ referencedMethodClass = refConstant.referencedClass;
+ referencedMethod = refConstant.referencedMember;
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Remember the referenced class.
+ referencedClass = classConstant.referencedClass;
+ }
+
+
+ // Small utility methods.
+
+ private void debug(Clazz clazz,
+ Method method,
+ int offset,
+ ConstantInstruction constantInstruction,
+ Instruction replacementInstruction)
+ {
+ System.out.println("MethodInvocationFixer:");
+ System.out.println(" Class = "+clazz.getName());
+ System.out.println(" Method = "+method.getName(clazz)+method.getDescriptor(clazz));
+ System.out.println(" Instruction = "+constantInstruction.toString(offset));
+ System.out.println(" -> Class = "+referencedClass);
+ System.out.println(" Method = "+referencedMethod);
+ if ((referencedClass.getAccessFlags() & ClassConstants.INTERNAL_ACC_INTERFACE) != 0)
+ {
+ System.out.println(" Parameter size = "+(ClassUtil.internalMethodParameterSize(referencedMethod.getDescriptor(referencedMethodClass), false)));
+ }
+ System.out.println(" Replacement instruction = "+replacementInstruction.toString(offset));
+ }
+}
diff --git a/src/proguard/classfile/editor/NameAndTypeShrinker.java b/src/proguard/classfile/editor/NameAndTypeShrinker.java
new file mode 100644
index 000000000..650f9baf8
--- /dev/null
+++ b/src/proguard/classfile/editor/NameAndTypeShrinker.java
@@ -0,0 +1,188 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.ConstantPoolRemapper;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+import java.util.Arrays;
+
+
+/**
+ * This ClassVisitor removes NameAndType constant pool entries that are not
+ * used.
+ *
+ * @author Eric Lafortune
+ */
+public class NameAndTypeShrinker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ AttributeVisitor
+{
+ // A visitor info flag to indicate the NameAndType constant pool entry is being used.
+ private static final Object USED = new Object();
+
+ private int[] constantIndexMap;
+ private final ConstantPoolRemapper constantPoolRemapper = new ConstantPoolRemapper();
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Mark the NameAndType entries referenced by all other constant pool
+ // entries.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Mark the NameAndType entries referenced by all EnclosingMethod
+ // attributes.
+ programClass.attributesAccept(this);
+
+ // Shift the used constant pool entries together, filling out the
+ // index map.
+ int newConstantPoolCount =
+ shrinkConstantPool(programClass.constantPool,
+ programClass.u2constantPoolCount);
+
+ // Remap the references to the constant pool if it has shrunk.
+ if (newConstantPoolCount < programClass.u2constantPoolCount)
+ {
+ programClass.u2constantPoolCount = newConstantPoolCount;
+
+ // Remap all constant pool references.
+ constantPoolRemapper.setConstantIndexMap(constantIndexMap);
+ constantPoolRemapper.visitProgramClass(programClass);
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ markNameAndTypeConstant(clazz, invokeDynamicConstant.u2nameAndTypeIndex);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ markNameAndTypeConstant(clazz, refConstant.u2nameAndTypeIndex);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ if (enclosingMethodAttribute.u2nameAndTypeIndex != 0)
+ {
+ markNameAndTypeConstant(clazz, enclosingMethodAttribute.u2nameAndTypeIndex);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Marks the given UTF-8 constant pool entry of the given class.
+ */
+ private void markNameAndTypeConstant(Clazz clazz, int index)
+ {
+ markAsUsed((NameAndTypeConstant)((ProgramClass)clazz).getConstant(index));
+ }
+
+
+ /**
+ * Marks the given VisitorAccepter as being used.
+ * In this context, the VisitorAccepter will be a NameAndTypeConstant object.
+ */
+ private void markAsUsed(VisitorAccepter visitorAccepter)
+ {
+ visitorAccepter.setVisitorInfo(USED);
+ }
+
+
+ /**
+ * Returns whether the given VisitorAccepter has been marked as being used.
+ * In this context, the VisitorAccepter will be a NameAndTypeConstant object.
+ */
+ private boolean isUsed(VisitorAccepter visitorAccepter)
+ {
+ return visitorAccepter.getVisitorInfo() == USED;
+ }
+
+
+ /**
+ * Removes all NameAndType entries that are not marked as being used
+ * from the given constant pool.
+ * @return the new number of entries.
+ */
+ private int shrinkConstantPool(Constant[] constantPool, int length)
+ {
+ // Create a new index map, if necessary.
+ if (constantIndexMap == null ||
+ constantIndexMap.length < length)
+ {
+ constantIndexMap = new int[length];
+ }
+
+ int counter = 1;
+ boolean isUsed = false;
+
+ // Shift the used constant pool entries together.
+ for (int index = 1; index < length; index++)
+ {
+ constantIndexMap[index] = counter;
+
+ Constant constant = constantPool[index];
+
+ // Don't update the flag if this is the second half of a long entry.
+ if (constant != null)
+ {
+ isUsed = constant.getTag() != ClassConstants.CONSTANT_NameAndType ||
+ isUsed(constant);
+ }
+
+ if (isUsed)
+ {
+ constantPool[counter++] = constant;
+ }
+ }
+
+ // Clear the remaining constant pool elements.
+ Arrays.fill(constantPool, counter, length, null);
+
+ return counter;
+ }
+}
diff --git a/src/proguard/classfile/editor/NamedAttributeDeleter.java b/src/proguard/classfile/editor/NamedAttributeDeleter.java
new file mode 100644
index 000000000..6aa5cdf64
--- /dev/null
+++ b/src/proguard/classfile/editor/NamedAttributeDeleter.java
@@ -0,0 +1,54 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.*;
+import proguard.util.StringMatcher;
+
+
+/**
+ * This ClassVisitor deletes attributes with a given name in the program
+ * classes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class NamedAttributeDeleter implements ClassVisitor
+{
+ private final String attributeName;
+
+
+ public NamedAttributeDeleter(String attributeName)
+ {
+ this.attributeName = attributeName;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ new AttributesEditor(programClass, false).deleteAttribute(attributeName);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/ParameterAnnotationsAttributeEditor.java b/src/proguard/classfile/editor/ParameterAnnotationsAttributeEditor.java
new file mode 100644
index 000000000..232747fd5
--- /dev/null
+++ b/src/proguard/classfile/editor/ParameterAnnotationsAttributeEditor.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.attribute.annotation.*;
+
+/**
+ * This class can add annotations to a given parameter annotations attribute.
+ * Annotations to be added must have been filled out beforehand.
+ *
+ * @author Eric Lafortune
+ */
+public class ParameterAnnotationsAttributeEditor
+{
+ private ParameterAnnotationsAttribute targetParameterAnnotationsAttribute;
+
+
+ /**
+ * Creates a new ParameterAnnotationsAttributeEditor that will edit
+ * annotations in the given parameter annotations attribute.
+ */
+ public ParameterAnnotationsAttributeEditor(ParameterAnnotationsAttribute targetParameterAnnotationsAttribute)
+ {
+ this.targetParameterAnnotationsAttribute = targetParameterAnnotationsAttribute;
+ }
+
+
+ /**
+ * Adds a given annotation to the annotations attribute.
+ */
+ public void addAnnotation(int parameterIndex, Annotation annotation)
+ {
+ int annotationsCount = targetParameterAnnotationsAttribute.u2parameterAnnotationsCount[parameterIndex];
+ Annotation[] annotations = targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex];
+
+ // Make sure there is enough space for the new annotation.
+ if (annotations == null ||
+ annotations.length <= annotationsCount)
+ {
+ targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex] = new Annotation[annotationsCount+1];
+ if (annotations != null)
+ {
+ System.arraycopy(annotations, 0,
+ targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex], 0,
+ annotationsCount);
+ }
+ annotations = targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex];
+ }
+
+ // Add the annotation.
+ annotations[targetParameterAnnotationsAttribute.u2parameterAnnotationsCount[parameterIndex]++] = annotation;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/StackSizeUpdater.java b/src/proguard/classfile/editor/StackSizeUpdater.java
new file mode 100644
index 000000000..d90b3d08d
--- /dev/null
+++ b/src/proguard/classfile/editor/StackSizeUpdater.java
@@ -0,0 +1,54 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor computes and updates the maximum stack size of the
+ * code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class StackSizeUpdater
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final StackSizeComputer stackSizeComputer = new StackSizeComputer();
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Compute the stack sizes.
+ stackSizeComputer.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Update the maximum stack size.
+ codeAttribute.u2maxStack = stackSizeComputer.getMaxStackSize();
+ }
+}
diff --git a/src/proguard/classfile/editor/SubclassAdder.java b/src/proguard/classfile/editor/SubclassAdder.java
new file mode 100644
index 000000000..717bb1c94
--- /dev/null
+++ b/src/proguard/classfile/editor/SubclassAdder.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor adds the given class to the list of subclasses of the
+ * classes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class SubclassAdder
+implements ClassVisitor
+{
+ private final Clazz subclass;
+
+
+ /**
+ * Creates a new SubclassAdder that will add the given subclass.
+ */
+ public SubclassAdder(Clazz subclass)
+ {
+ this.subclass = subclass;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.addSubClass(subclass);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.addSubClass(subclass);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/SubclassToAdder.java b/src/proguard/classfile/editor/SubclassToAdder.java
new file mode 100644
index 000000000..109152b7b
--- /dev/null
+++ b/src/proguard/classfile/editor/SubclassToAdder.java
@@ -0,0 +1,60 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor adds all classes that it visits to the list of subclasses
+ * of the given target class.
+ *
+ * @author Eric Lafortune
+ */
+public class SubclassToAdder
+implements ClassVisitor
+{
+ private final Clazz targetClass;
+
+
+ /**
+ * Creates a new SubclassAdder that will add subclasses to the given
+ * target class.
+ */
+ public SubclassToAdder(Clazz targetClass)
+ {
+ this.targetClass = targetClass;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ targetClass.addSubClass(programClass);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ targetClass.addSubClass(libraryClass);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/Utf8Shrinker.java b/src/proguard/classfile/editor/Utf8Shrinker.java
new file mode 100644
index 000000000..eda582697
--- /dev/null
+++ b/src/proguard/classfile/editor/Utf8Shrinker.java
@@ -0,0 +1,455 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.ConstantPoolRemapper;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+import java.util.Arrays;
+
+
+/**
+ * This ClassVisitor removes UTF-8 constant pool entries that are not used.
+ *
+ * @author Eric Lafortune
+ */
+public class Utf8Shrinker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ ConstantVisitor,
+ AttributeVisitor,
+ InnerClassesInfoVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ // A visitor info flag to indicate the UTF-8 constant pool entry is being used.
+ private static final Object USED = new Object();
+
+ private int[] constantIndexMap = new int[ClassConstants.TYPICAL_CONSTANT_POOL_SIZE];
+ private final ConstantPoolRemapper constantPoolRemapper = new ConstantPoolRemapper();
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Mark the UTF-8 entries referenced by the other constant pool entries.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Mark the UTF-8 entries referenced by the fields and methods.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ // Mark the UTF-8 entries referenced by the attributes.
+ programClass.attributesAccept(this);
+
+ // Shift the used constant pool entries together, filling out the
+ // index map.
+ int newConstantPoolCount =
+ shrinkConstantPool(programClass.constantPool,
+ programClass.u2constantPoolCount);
+
+ // Remap the references to the constant pool if it has shrunk.
+ if (newConstantPoolCount < programClass.u2constantPoolCount)
+ {
+ programClass.u2constantPoolCount = newConstantPoolCount;
+
+ // Remap all constant pool references.
+ constantPoolRemapper.setConstantIndexMap(constantIndexMap);
+ constantPoolRemapper.visitProgramClass(programClass);
+ }
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ // Mark the name and descriptor UTF-8 entries.
+ markCpUtf8Entry(programClass, programMember.u2nameIndex);
+ markCpUtf8Entry(programClass, programMember.u2descriptorIndex);
+
+ // Mark the UTF-8 entries referenced by the attributes.
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ markCpUtf8Entry(clazz, stringConstant.u2stringIndex);
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ markCpUtf8Entry(clazz, classConstant.u2nameIndex);
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ markCpUtf8Entry(clazz, nameAndTypeConstant.u2nameIndex);
+ markCpUtf8Entry(clazz, nameAndTypeConstant.u2descriptorIndex);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ // This is the best we can do for unknown attributes.
+ markCpUtf8Entry(clazz, unknownAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ markCpUtf8Entry(clazz, sourceFileAttribute.u2attributeNameIndex);
+
+ markCpUtf8Entry(clazz, sourceFileAttribute.u2sourceFileIndex);
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ markCpUtf8Entry(clazz, sourceDirAttribute.u2attributeNameIndex);
+
+ markCpUtf8Entry(clazz, sourceDirAttribute.u2sourceDirIndex);
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ markCpUtf8Entry(clazz, innerClassesAttribute.u2attributeNameIndex);
+
+ // Mark the UTF-8 entries referenced by the inner classes.
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ markCpUtf8Entry(clazz, enclosingMethodAttribute.u2attributeNameIndex);
+
+ // These entries have already been marked in the constant pool.
+ //clazz.constantPoolEntryAccept(this, enclosingMethodAttribute.u2classIndex);
+ //clazz.constantPoolEntryAccept(this, enclosingMethodAttribute.u2nameAndTypeIndex);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ markCpUtf8Entry(clazz, deprecatedAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ markCpUtf8Entry(clazz, syntheticAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ markCpUtf8Entry(clazz, signatureAttribute.u2attributeNameIndex);
+
+ markCpUtf8Entry(clazz, signatureAttribute.u2signatureIndex);
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ markCpUtf8Entry(clazz, constantValueAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ markCpUtf8Entry(clazz, exceptionsAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ markCpUtf8Entry(clazz, codeAttribute.u2attributeNameIndex);
+
+ // Mark the UTF-8 entries referenced by the attributes.
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ markCpUtf8Entry(clazz, stackMapAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ markCpUtf8Entry(clazz, stackMapTableAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ markCpUtf8Entry(clazz, lineNumberTableAttribute.u2attributeNameIndex);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ markCpUtf8Entry(clazz, localVariableTableAttribute.u2attributeNameIndex);
+
+ // Mark the UTF-8 entries referenced by the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ markCpUtf8Entry(clazz, localVariableTypeTableAttribute.u2attributeNameIndex);
+
+ // Mark the UTF-8 entries referenced by the local variable types.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ markCpUtf8Entry(clazz, annotationsAttribute.u2attributeNameIndex);
+
+ // Mark the UTF-8 entries referenced by the annotations.
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ markCpUtf8Entry(clazz, parameterAnnotationsAttribute.u2attributeNameIndex);
+
+ // Mark the UTF-8 entries referenced by the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ markCpUtf8Entry(clazz, annotationDefaultAttribute.u2attributeNameIndex);
+
+ // Mark the UTF-8 entries referenced by the element value.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ if (innerClassesInfo.u2innerNameIndex != 0)
+ {
+ markCpUtf8Entry(clazz, innerClassesInfo.u2innerNameIndex);
+ }
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ markCpUtf8Entry(clazz, localVariableInfo.u2nameIndex);
+ markCpUtf8Entry(clazz, localVariableInfo.u2descriptorIndex);
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ markCpUtf8Entry(clazz, localVariableTypeInfo.u2nameIndex);
+ markCpUtf8Entry(clazz, localVariableTypeInfo.u2signatureIndex);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ markCpUtf8Entry(clazz, annotation.u2typeIndex);
+
+ // Mark the UTF-8 entries referenced by the element values.
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ if (constantElementValue.u2elementNameIndex != 0)
+ {
+ markCpUtf8Entry(clazz, constantElementValue.u2elementNameIndex);
+ }
+
+ // Only the string constant element value refers to a UTF-8 entry.
+ if (constantElementValue.u1tag == ClassConstants.ELEMENT_VALUE_STRING_CONSTANT)
+ {
+ markCpUtf8Entry(clazz, constantElementValue.u2constantValueIndex);
+ }
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ if (enumConstantElementValue.u2elementNameIndex != 0)
+ {
+ markCpUtf8Entry(clazz, enumConstantElementValue.u2elementNameIndex);
+ }
+
+ markCpUtf8Entry(clazz, enumConstantElementValue.u2typeNameIndex);
+ markCpUtf8Entry(clazz, enumConstantElementValue.u2constantNameIndex);
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ if (classElementValue.u2elementNameIndex != 0)
+ {
+ markCpUtf8Entry(clazz, classElementValue.u2elementNameIndex);
+ }
+
+ markCpUtf8Entry(clazz, classElementValue.u2classInfoIndex);
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ if (annotationElementValue.u2elementNameIndex != 0)
+ {
+ markCpUtf8Entry(clazz, annotationElementValue.u2elementNameIndex);
+ }
+
+ // Mark the UTF-8 entries referenced by the annotation.
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ if (arrayElementValue.u2elementNameIndex != 0)
+ {
+ markCpUtf8Entry(clazz, arrayElementValue.u2elementNameIndex);
+ }
+
+ // Mark the UTF-8 entries referenced by the element values.
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Marks the given UTF-8 constant pool entry of the given class.
+ */
+ private void markCpUtf8Entry(Clazz clazz, int index)
+ {
+ markAsUsed((Utf8Constant)((ProgramClass)clazz).getConstant(index));
+ }
+
+
+ /**
+ * Marks the given VisitorAccepter as being used.
+ * In this context, the VisitorAccepter will be a Utf8Constant object.
+ */
+ private void markAsUsed(VisitorAccepter visitorAccepter)
+ {
+ visitorAccepter.setVisitorInfo(USED);
+ }
+
+
+ /**
+ * Returns whether the given VisitorAccepter has been marked as being used.
+ * In this context, the VisitorAccepter will be a Utf8Constant object.
+ */
+ private boolean isUsed(VisitorAccepter visitorAccepter)
+ {
+ return visitorAccepter.getVisitorInfo() == USED;
+ }
+
+
+ /**
+ * Removes all UTF-8 entries that are not marked as being used
+ * from the given constant pool.
+ * @return the new number of entries.
+ */
+ private int shrinkConstantPool(Constant[] constantPool, int length)
+ {
+ // Create a new index map, if necessary.
+ if (constantIndexMap.length < length)
+ {
+ constantIndexMap = new int[length];
+ }
+
+ int counter = 1;
+ boolean isUsed = false;
+
+ // Shift the used constant pool entries together.
+ for (int index = 1; index < length; index++)
+ {
+ constantIndexMap[index] = counter;
+
+ Constant constant = constantPool[index];
+
+ // Don't update the flag if this is the second half of a long entry.
+ if (constant != null)
+ {
+ isUsed = constant.getTag() != ClassConstants.CONSTANT_Utf8 ||
+ isUsed(constant);
+ }
+
+ if (isUsed)
+ {
+ constantPool[counter++] = constant;
+ }
+ }
+
+ // Clear the remaining constant pool elements.
+ Arrays.fill(constantPool, counter, length, null);
+
+ return counter;
+ }
+}
diff --git a/src/proguard/classfile/editor/VariableCleaner.java b/src/proguard/classfile/editor/VariableCleaner.java
new file mode 100644
index 000000000..63b7d4a91
--- /dev/null
+++ b/src/proguard/classfile/editor/VariableCleaner.java
@@ -0,0 +1,271 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+import java.util.Arrays;
+
+/**
+ * This AttributeVisitor cleans up variable tables in all code attributes that
+ * it visits. It trims overlapping local variables. It removes empty local
+ * variables and empty local variable tables.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableCleaner
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private boolean deleteLocalVariableTableAttribute;
+ private boolean deleteLocalVariableTypeTableAttribute;
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ deleteLocalVariableTableAttribute = false;
+ deleteLocalVariableTypeTableAttribute = false;
+
+ // Trim the local variable table and the local variable type table.
+ codeAttribute.attributesAccept(clazz, method, this);
+
+ // Delete the local variable table if it ended up empty.
+ if (deleteLocalVariableTableAttribute)
+ {
+ AttributesEditor editor =
+ new AttributesEditor((ProgramClass)clazz,
+ (ProgramMember)method,
+ codeAttribute,
+ true);
+
+ editor.deleteAttribute(ClassConstants.ATTR_LocalVariableTable);
+ }
+
+ // Delete the local variable type table if it ended up empty.
+ if (deleteLocalVariableTypeTableAttribute)
+ {
+ AttributesEditor editor =
+ new AttributesEditor((ProgramClass)clazz,
+ (ProgramMember)method,
+ codeAttribute,
+ true);
+
+ editor.deleteAttribute(ClassConstants.ATTR_LocalVariableTypeTable);
+ }
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Clean up local variables that aren't used.
+ localVariableTableAttribute.u2localVariableTableLength =
+ removeUnusedLocalVariables(localVariableTableAttribute.localVariableTable,
+ localVariableTableAttribute.u2localVariableTableLength,
+ codeAttribute.u2maxLocals);
+
+ // Trim the code blocks of the local variables.
+ trimLocalVariables(localVariableTableAttribute.localVariableTable,
+ localVariableTableAttribute.u2localVariableTableLength,
+ codeAttribute.u2maxLocals);
+
+ // Delete the attribute in a moment, if it is empty.
+ if (localVariableTableAttribute.u2localVariableTableLength == 0)
+ {
+ deleteLocalVariableTableAttribute = true;
+ }
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Clean up local variables that aren't used.
+ localVariableTypeTableAttribute.u2localVariableTypeTableLength =
+ removeUnusedLocalVariableTypes(localVariableTypeTableAttribute.localVariableTypeTable,
+ localVariableTypeTableAttribute.u2localVariableTypeTableLength,
+ codeAttribute.u2maxLocals);
+
+ // Trim the code blocks of the local variables.
+ trimLocalVariableTypes(localVariableTypeTableAttribute.localVariableTypeTable,
+ localVariableTypeTableAttribute.u2localVariableTypeTableLength,
+ codeAttribute.u2maxLocals);
+
+ // Delete the attribute in a moment, if it is empty.
+ if (localVariableTypeTableAttribute.u2localVariableTypeTableLength == 0)
+ {
+ deleteLocalVariableTypeTableAttribute = true;
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the given list of local variables, without the ones that aren't
+ * used.
+ */
+ private int removeUnusedLocalVariables(LocalVariableInfo[] localVariableInfos,
+ int localVariableInfoCount,
+ int maxLocals)
+ {
+ // Overwrite all empty local variable entries.
+ // Do keep parameter entries.
+ int newIndex = 0;
+ for (int index = 0; index < localVariableInfoCount; index++)
+ {
+ LocalVariableInfo localVariableInfo = localVariableInfos[index];
+
+ if (localVariableInfo.u2index >= 0 &&
+ localVariableInfo.u2index < maxLocals &&
+ (localVariableInfo.u2startPC == 0 ||
+ localVariableInfo.u2length > 0))
+ {
+ localVariableInfos[newIndex++] = localVariableInfos[index];
+ }
+ }
+
+ // Clean up any remaining array elements.
+ Arrays.fill(localVariableInfos, newIndex, localVariableInfoCount, null);
+
+ return newIndex;
+ }
+
+
+ /**
+ * Returns the given list of local variable types, without the ones that
+ * aren't used.
+ */
+ private int removeUnusedLocalVariableTypes(LocalVariableTypeInfo[] localVariableTypeInfos,
+ int localVariableTypeInfoCount,
+ int maxLocals)
+ {
+ // Overwrite all empty local variable type entries.
+ // Do keep parameter entries.
+ int newIndex = 0;
+ for (int index = 0; index < localVariableTypeInfoCount; index++)
+ {
+ LocalVariableTypeInfo localVariableTypeInfo = localVariableTypeInfos[index];
+
+ if (localVariableTypeInfo.u2index >= 0 &&
+ localVariableTypeInfo.u2index < maxLocals &&
+ (localVariableTypeInfo.u2startPC == 0 ||
+ localVariableTypeInfo.u2length > 0))
+ {
+ localVariableTypeInfos[newIndex++] = localVariableTypeInfos[index];
+ }
+ }
+
+ // Clean up any remaining array elements.
+ Arrays.fill(localVariableTypeInfos, newIndex, localVariableTypeInfoCount, null);
+
+ return newIndex;
+ }
+
+
+ /**
+ * Sorts the given list of local variables and trims their code blocks
+ * when necessary. The block is trimmed at the end, which is a bit
+ * arbitrary.
+ */
+ private void trimLocalVariables(LocalVariableInfo[] localVariableInfos,
+ int localVariableInfoCount,
+ int maxLocals)
+ {
+ // Sort the local variable entries.
+ Arrays.sort(localVariableInfos, 0, localVariableInfoCount);
+
+ int[] startPCs = createMaxArray(maxLocals);
+
+ // Trim the local variable entries, starting at the last one.
+ for (int index = localVariableInfoCount-1; index >= 0; index--)
+ {
+ LocalVariableInfo localVariableInfo = localVariableInfos[index];
+
+ // Make sure the variable's code block doesn't overlap with the
+ // next one for the same variable.
+ int maxLength = startPCs[localVariableInfo.u2index] -
+ localVariableInfo.u2startPC;
+
+ if (localVariableInfo.u2length > maxLength)
+ {
+ localVariableInfo.u2length = maxLength;
+ }
+
+ startPCs[localVariableInfo.u2index] = localVariableInfo.u2startPC;
+ }
+ }
+
+
+ /**
+ * Sorts the given list of local variable types and trims their code blocks
+ * when necessary. The block is trimmed at the end, which is a bit
+ * arbitrary.
+ */
+ private void trimLocalVariableTypes(LocalVariableTypeInfo[] localVariableTypeInfos,
+ int localVariableTypeInfoCount,
+ int maxLocals)
+ {
+ // Sort the local variable entries.
+ Arrays.sort(localVariableTypeInfos, 0, localVariableTypeInfoCount);
+
+ int[] startPCs = createMaxArray(maxLocals);
+
+ // Trim the local variable entries, starting at the last one.
+ for (int index = localVariableTypeInfoCount-1; index >= 0; index--)
+ {
+ LocalVariableTypeInfo localVariableTypeInfo = localVariableTypeInfos[index];
+
+ // Make sure the variable's code block doesn't overlap with the
+ // next one for the same variable.
+ int maxLength = startPCs[localVariableTypeInfo.u2index] -
+ localVariableTypeInfo.u2startPC;
+
+ if (localVariableTypeInfo.u2length > maxLength)
+ {
+ localVariableTypeInfo.u2length = maxLength;
+ }
+
+ startPCs[localVariableTypeInfo.u2index] = localVariableTypeInfo.u2startPC;
+ }
+ }
+
+
+ /**
+ * Creates an integer array of the given length, initialized with
+ * Integer.MAX_VALUE.
+ */
+ private int[] createMaxArray(int length)
+ {
+ int[] startPCs = new int[length];
+ for (int index = 0; index < length; index++)
+ {
+ startPCs[index] = Integer.MAX_VALUE;
+ }
+ return startPCs;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/editor/VariableEditor.java b/src/proguard/classfile/editor/VariableEditor.java
new file mode 100644
index 000000000..b5143b56d
--- /dev/null
+++ b/src/proguard/classfile/editor/VariableEditor.java
@@ -0,0 +1,130 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+import java.util.Arrays;
+
+/**
+ * This AttributeVisitor accumulates specified changes to local variables, and
+ * then applies these accumulated changes to the code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableEditor
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private boolean modified;
+
+ private boolean[] deleted = new boolean[ClassConstants.TYPICAL_VARIABLES_SIZE];
+ private int[] variableMap = new int[ClassConstants.TYPICAL_VARIABLES_SIZE];
+
+ private final VariableRemapper variableRemapper = new VariableRemapper();
+
+
+ /**
+ * Resets the accumulated code changes.
+ * @param maxLocals the length of the local variable frame that will be
+ * edited next.
+ */
+ public void reset(int maxLocals)
+ {
+ // Try to reuse the previous array.
+ if (deleted.length < maxLocals)
+ {
+ // Create a new array.
+ deleted = new boolean[maxLocals];
+ }
+ else
+ {
+ // Reset the array.
+ Arrays.fill(deleted, 0, maxLocals, false);
+ }
+
+ modified = false;
+ }
+
+
+ /**
+ * Remembers to delete the given variable.
+ * @param variableIndex the index of the variable to be deleted.
+ */
+ public void deleteVariable(int variableIndex)
+ {
+ deleted[variableIndex] = true;
+
+ modified = true;
+ }
+
+
+ /**
+ * Returns whether the given variable at the given offset has deleted.
+ */
+ public boolean isDeleted(int instructionOffset)
+ {
+ return deleted[instructionOffset];
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Avoid doing any work if nothing is changing anyway.
+ if (!modified)
+ {
+ return;
+ }
+
+ int oldMaxLocals = codeAttribute.u2maxLocals;
+
+ // Make sure there is a sufficiently large variable map.
+ if (variableMap.length < oldMaxLocals)
+ {
+ variableMap = new int[oldMaxLocals];
+ }
+
+ // Fill out the variable map.
+ int newVariableIndex = 0;
+ for (int oldVariableIndex = 0; oldVariableIndex < oldMaxLocals; oldVariableIndex++)
+ {
+ variableMap[oldVariableIndex] = deleted[oldVariableIndex] ?
+ -1 : newVariableIndex++;
+ }
+
+ // Set the map.
+ variableRemapper.setVariableMap(variableMap);
+
+ // Remap the variables.
+ variableRemapper.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Update the length of local variable frame.
+ codeAttribute.u2maxLocals = newVariableIndex;
+ }
+}
diff --git a/src/proguard/classfile/editor/VariableRemapper.java b/src/proguard/classfile/editor/VariableRemapper.java
new file mode 100644
index 000000000..ca9d88ab0
--- /dev/null
+++ b/src/proguard/classfile/editor/VariableRemapper.java
@@ -0,0 +1,156 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor remaps variable indexes in all attributes that it
+ * visits, based on a given index map.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableRemapper
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor
+{
+ private static final boolean DEBUG = false;
+
+
+ private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor();
+
+ private int[] variableMap;
+
+
+ /**
+ * Sets the given mapping of old variable indexes to their new indexes.
+ * Variables that should disappear can be mapped to -1.
+ */
+ public void setVariableMap(int[] variableMap)
+ {
+ this.variableMap = variableMap;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (DEBUG)
+ {
+ System.out.println("VariableRemapper: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ for (int index= 0; index < codeAttribute.u2maxLocals; index++)
+ {
+ System.out.println(" v"+index+" -> "+variableMap[index]);
+ }
+ }
+
+ // Remap the variables of the attributes, before editing the code and
+ // cleaning up its local variable frame.
+ codeAttribute.attributesAccept(clazz, method, this);
+
+ // Initially, the code attribute editor doesn't contain any changes.
+ codeAttributeEditor.reset(codeAttribute.u4codeLength);
+
+ // Remap the variables of the instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ // Apply the code atribute editor.
+ codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Remap the variable references of the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Remap the variable references of the local variables.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ localVariableInfo.u2index =
+ remapVariable(localVariableInfo.u2index);
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ localVariableTypeInfo.u2index =
+ remapVariable(localVariableTypeInfo.u2index);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ // Is the new variable index different from the original one?
+ int oldVariableIndex = variableInstruction.variableIndex;
+ int newVariableIndex = remapVariable(oldVariableIndex);
+ if (newVariableIndex != oldVariableIndex)
+ {
+ // Replace the instruction.
+ Instruction replacementInstruction =
+ new VariableInstruction(variableInstruction.opcode,
+ newVariableIndex,
+ variableInstruction.constant);
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the new variable index of the given variable.
+ */
+ private int remapVariable(int variableIndex)
+ {
+ return variableMap[variableIndex];
+ }
+}
diff --git a/src/proguard/classfile/editor/VariableSizeUpdater.java b/src/proguard/classfile/editor/VariableSizeUpdater.java
new file mode 100644
index 000000000..2feaa9dac
--- /dev/null
+++ b/src/proguard/classfile/editor/VariableSizeUpdater.java
@@ -0,0 +1,105 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.editor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+
+/**
+ * This AttributeVisitor computes and updates the maximum local variable frame
+ * size of the code attributes that it visits. It also cleans up the local
+ * variable tables.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableSizeUpdater
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+
+ private VariableCleaner variableCleaner = new VariableCleaner();
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // The minimum variable size is determined by the arguments.
+ codeAttribute.u2maxLocals =
+ ClassUtil.internalMethodParameterSize(method.getDescriptor(clazz),
+ method.getAccessFlags());
+
+ if (DEBUG)
+ {
+ System.out.println("VariableSizeUpdater: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ System.out.println(" Max locals: "+codeAttribute.u2maxLocals+" <- parameters");
+ }
+
+ // Go over all instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ // Remove the unused variables of the attributes.
+ variableCleaner.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ int variableSize = variableInstruction.variableIndex + 1;
+ if (variableInstruction.isCategory2())
+ {
+ variableSize++;
+ }
+
+ if (codeAttribute.u2maxLocals < variableSize)
+ {
+ codeAttribute.u2maxLocals = variableSize;
+
+ if (DEBUG)
+ {
+ System.out.println(" Max locals: "+codeAttribute.u2maxLocals+" <- "+variableInstruction.toString(offset));
+ }
+ }
+ }
+}
diff --git a/src/proguard/classfile/editor/package.html b/src/proguard/classfile/editor/package.html
new file mode 100644
index 000000000..d37f541f7
--- /dev/null
+++ b/src/proguard/classfile/editor/package.html
@@ -0,0 +1,3 @@
+
+This package contains visitors to edit byte code.
+
diff --git a/src/proguard/classfile/instruction/BranchInstruction.java b/src/proguard/classfile/instruction/BranchInstruction.java
new file mode 100644
index 000000000..f3a708057
--- /dev/null
+++ b/src/proguard/classfile/instruction/BranchInstruction.java
@@ -0,0 +1,179 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+/**
+ * This interface describes an instruction that branches to a given offset in
+ * the code.
+ *
+ * @author Eric Lafortune
+ */
+public class BranchInstruction extends Instruction
+{
+ public int branchOffset;
+
+
+ /**
+ * Creates an uninitialized BranchInstruction.
+ */
+ public BranchInstruction() {}
+
+
+ public BranchInstruction(byte opcode, int branchOffset)
+ {
+ this.opcode = opcode;
+ this.branchOffset = branchOffset;
+ }
+
+
+ /**
+ * Copies the given instruction into this instruction.
+ * @param branchInstruction the instruction to be copied.
+ * @return this instruction.
+ */
+ public BranchInstruction copy(BranchInstruction branchInstruction)
+ {
+ this.opcode = branchInstruction.opcode;
+ this.branchOffset = branchInstruction.branchOffset;
+
+ return this;
+ }
+
+
+ // Implementations for Instruction.
+
+ public byte canonicalOpcode()
+ {
+ // Remove the _w extension, if any.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_GOTO_W: return InstructionConstants.OP_GOTO;
+
+ case InstructionConstants.OP_JSR_W: return InstructionConstants.OP_JSR;
+
+ default: return opcode;
+ }
+ }
+
+ public Instruction shrink()
+ {
+ // Do we need an ordinary branch or a wide branch?
+ if (requiredBranchOffsetSize() == 2)
+ {
+ // Can we replace the wide branch by an ordinary branch?
+ if (opcode == InstructionConstants.OP_GOTO_W)
+ {
+ opcode = InstructionConstants.OP_GOTO;
+ }
+ else if (opcode == InstructionConstants.OP_JSR_W)
+ {
+ opcode = InstructionConstants.OP_JSR;
+ }
+ }
+ else
+ {
+ // Should we replace the ordinary branch by a wide branch?
+ if (opcode == InstructionConstants.OP_GOTO)
+ {
+ opcode = InstructionConstants.OP_GOTO_W;
+ }
+ else if (opcode == InstructionConstants.OP_JSR)
+ {
+ opcode = InstructionConstants.OP_JSR_W;
+ }
+ else
+ {
+ throw new IllegalArgumentException("Branch instruction can't be widened ("+this.toString()+")");
+ }
+ }
+
+ return this;
+ }
+
+ protected void readInfo(byte[] code, int offset)
+ {
+ branchOffset = readSignedValue(code, offset, branchOffsetSize());
+ }
+
+
+ protected void writeInfo(byte[] code, int offset)
+ {
+ if (requiredBranchOffsetSize() > branchOffsetSize())
+ {
+ throw new IllegalArgumentException("Instruction has invalid branch offset size ("+this.toString(offset)+")");
+ }
+
+ writeSignedValue(code, offset, branchOffset, branchOffsetSize());
+ }
+
+
+ public int length(int offset)
+ {
+ return 1 + branchOffsetSize();
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor)
+ {
+ instructionVisitor.visitBranchInstruction(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public String toString(int offset)
+ {
+ return "["+offset+"] "+toString()+" (target="+(offset+branchOffset)+")";
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return getName()+" "+(branchOffset >= 0 ? "+" : "")+branchOffset;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the branch offset size for this instruction.
+ */
+ private int branchOffsetSize()
+ {
+ return opcode == InstructionConstants.OP_GOTO_W ||
+ opcode == InstructionConstants.OP_JSR_W ? 4 :
+ 2;
+ }
+
+
+ /**
+ * Computes the required branch offset size for this instruction's branch
+ * offset.
+ */
+ private int requiredBranchOffsetSize()
+ {
+ return (short)branchOffset == branchOffset ? 2 : 4;
+ }
+}
diff --git a/src/proguard/classfile/instruction/ConstantInstruction.java b/src/proguard/classfile/instruction/ConstantInstruction.java
new file mode 100644
index 000000000..42d152315
--- /dev/null
+++ b/src/proguard/classfile/instruction/ConstantInstruction.java
@@ -0,0 +1,309 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.ClassUtil;
+
+/**
+ * This Instruction represents an instruction that refers to an entry in the
+ * constant pool.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantInstruction extends Instruction
+implements ConstantVisitor
+{
+ public int constantIndex;
+ public int constant;
+
+
+ // Fields acting as return parameters for the ConstantVisitor methods.
+ private int parameterStackDelta;
+ private int typeStackDelta;
+
+
+ /**
+ * Creates an uninitialized ConstantInstruction.
+ */
+ public ConstantInstruction() {}
+
+
+ /**
+ * Creates a new ConstantInstruction with the given opcode and constant pool
+ * index.
+ */
+ public ConstantInstruction(byte opcode, int constantIndex)
+ {
+ this(opcode, constantIndex, 0);
+ }
+
+
+ /**
+ * Creates a new ConstantInstruction with the given opcode, constant pool
+ * index, and constant.
+ */
+ public ConstantInstruction(byte opcode, int constantIndex, int constant)
+ {
+ this.opcode = opcode;
+ this.constantIndex = constantIndex;
+ this.constant = constant;
+ }
+
+
+ /**
+ * Copies the given instruction into this instruction.
+ * @param constantInstruction the instruction to be copied.
+ * @return this instruction.
+ */
+ public ConstantInstruction copy(ConstantInstruction constantInstruction)
+ {
+ this.opcode = constantInstruction.opcode;
+ this.constantIndex = constantInstruction.constantIndex;
+ this.constant = constantInstruction.constant;
+
+ return this;
+ }
+
+
+ // Implementations for Instruction.
+
+ public byte canonicalOpcode()
+ {
+ // Remove the _w extension, if any.
+ return
+ opcode == InstructionConstants.OP_LDC_W ? InstructionConstants.OP_LDC :
+ opcode;
+ }
+
+ public Instruction shrink()
+ {
+ // Do we need a short index or a long index?
+ if (requiredConstantIndexSize() == 1)
+ {
+ // Can we replace the long instruction by a short instruction?
+ if (opcode == InstructionConstants.OP_LDC_W)
+ {
+ opcode = InstructionConstants.OP_LDC;
+ }
+ }
+ else
+ {
+ // Should we replace the short instruction by a long instruction?
+ if (opcode == InstructionConstants.OP_LDC)
+ {
+ opcode = InstructionConstants.OP_LDC_W;
+ }
+ }
+
+ return this;
+ }
+
+ protected void readInfo(byte[] code, int offset)
+ {
+ int constantIndexSize = constantIndexSize();
+ int constantSize = constantSize();
+
+ constantIndex = readValue(code, offset, constantIndexSize); offset += constantIndexSize;
+ constant = readValue(code, offset, constantSize);
+ }
+
+
+ protected void writeInfo(byte[] code, int offset)
+ {
+ int constantIndexSize = constantIndexSize();
+ int constantSize = constantSize();
+
+ if (requiredConstantIndexSize() > constantIndexSize)
+ {
+ throw new IllegalArgumentException("Instruction has invalid constant index size ("+this.toString(offset)+")");
+ }
+
+ writeValue(code, offset, constantIndex, constantIndexSize); offset += constantIndexSize;
+ writeValue(code, offset, constant, constantSize);
+ }
+
+
+ public int length(int offset)
+ {
+ return 1 + constantIndexSize() + constantSize();
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor)
+ {
+ instructionVisitor.visitConstantInstruction(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public int stackPopCount(Clazz clazz)
+ {
+ int stackPopCount = super.stackPopCount(clazz);
+
+ // Some special cases.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_MULTIANEWARRAY:
+ // For each dimension, an integer size is popped from the stack.
+ stackPopCount += constant;
+ break;
+
+ case InstructionConstants.OP_PUTSTATIC:
+ case InstructionConstants.OP_PUTFIELD:
+ // The field value is be popped from the stack.
+ clazz.constantPoolEntryAccept(constantIndex, this);
+ stackPopCount += typeStackDelta;
+ break;
+
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ case InstructionConstants.OP_INVOKEDYNAMIC:
+ // Some parameters may be popped from the stack.
+ clazz.constantPoolEntryAccept(constantIndex, this);
+ stackPopCount += parameterStackDelta;
+ break;
+ }
+
+ return stackPopCount;
+ }
+
+
+ public int stackPushCount(Clazz clazz)
+ {
+ int stackPushCount = super.stackPushCount(clazz);
+
+ // Some special cases.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_GETSTATIC:
+ case InstructionConstants.OP_GETFIELD:
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ case InstructionConstants.OP_INVOKEDYNAMIC:
+ // The field value or a return value may be pushed onto the stack.
+ clazz.constantPoolEntryAccept(constantIndex, this);
+ stackPushCount += typeStackDelta;
+ break;
+ }
+
+ return stackPushCount;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant) {}
+ public void visitLongConstant(Clazz clazz, LongConstant longConstant) {}
+ public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant) {}
+ public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant) {}
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant) {}
+ public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant) {}
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant) {}
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant) {}
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant) {}
+
+
+ public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
+ {
+ String type = fieldrefConstant.getType(clazz);
+
+ typeStackDelta = ClassUtil.internalTypeSize(ClassUtil.internalMethodReturnType(type));
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ clazz.constantPoolEntryAccept(invokeDynamicConstant.u2nameAndTypeIndex, this);
+ }
+
+
+ public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant)
+ {
+ clazz.constantPoolEntryAccept(interfaceMethodrefConstant.u2nameAndTypeIndex, this);
+ }
+
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ clazz.constantPoolEntryAccept(methodrefConstant.u2nameAndTypeIndex, this);
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ String type = nameAndTypeConstant.getType(clazz);
+
+ parameterStackDelta = ClassUtil.internalMethodParameterSize(type);
+ typeStackDelta = ClassUtil.internalTypeSize(ClassUtil.internalMethodReturnType(type));
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return getName()+" #"+constantIndex+(constantSize() == 0 ? "" : ", "+constant);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the constant pool index size for this instruction.
+ */
+ private int constantIndexSize()
+ {
+ return opcode == InstructionConstants.OP_LDC ? 1 :
+ 2;
+ }
+
+
+ /**
+ * Returns the constant size for this instruction.
+ */
+ private int constantSize()
+ {
+ return opcode == InstructionConstants.OP_MULTIANEWARRAY ? 1 :
+ opcode == InstructionConstants.OP_INVOKEDYNAMIC ||
+ opcode == InstructionConstants.OP_INVOKEINTERFACE ? 2 :
+ 0;
+ }
+
+
+ /**
+ * Computes the required constant pool index size for this instruction's
+ * constant pool index.
+ */
+ private int requiredConstantIndexSize()
+ {
+ return (constantIndex & 0xff) == constantIndex ? 1 :
+ (constantIndex & 0xffff) == constantIndex ? 2 :
+ 4;
+ }
+}
diff --git a/src/proguard/classfile/instruction/Instruction.java b/src/proguard/classfile/instruction/Instruction.java
new file mode 100644
index 000000000..33e705daf
--- /dev/null
+++ b/src/proguard/classfile/instruction/Instruction.java
@@ -0,0 +1,920 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+/**
+ * Base class for representing instructions.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class Instruction
+{
+ // An array for marking Category 2 instructions.
+ private static final boolean[] IS_CATEGORY2 = new boolean[]
+ {
+ false, // nop
+ false, // aconst_null
+ false, // iconst_m1
+ false, // iconst_0
+ false, // iconst_1
+ false, // iconst_2
+ false, // iconst_3
+ false, // iconst_4
+ false, // iconst_5
+ true, // lconst_0
+ true, // lconst_1
+ false, // fconst_0
+ false, // fconst_1
+ false, // fconst_2
+ true, // dconst_0
+ true, // dconst_1
+ false, // bipush
+ false, // sipush
+ false, // ldc
+ false, // ldc_w
+ true, // ldc2_w
+ false, // iload
+ true, // lload
+ false, // fload
+ true, // dload
+ false, // aload
+ false, // iload_0
+ false, // iload_1
+ false, // iload_2
+ false, // iload_3
+ true, // lload_0
+ true, // lload_1
+ true, // lload_2
+ true, // lload_3
+ false, // fload_0
+ false, // fload_1
+ false, // fload_2
+ false, // fload_3
+ true, // dload_0
+ true, // dload_1
+ true, // dload_2
+ true, // dload_3
+ false, // aload_0
+ false, // aload_1
+ false, // aload_2
+ false, // aload_3
+ false, // iaload
+ true, // laload
+ false, // faload
+ true, // daload
+ false, // aaload
+ false, // baload
+ false, // caload
+ false, // saload
+ false, // istore
+ true, // lstore
+ false, // fstore
+ true, // dstore
+ false, // astore
+ false, // istore_0
+ false, // istore_1
+ false, // istore_2
+ false, // istore_3
+ true, // lstore_0
+ true, // lstore_1
+ true, // lstore_2
+ true, // lstore_3
+ false, // fstore_0
+ false, // fstore_1
+ false, // fstore_2
+ false, // fstore_3
+ true, // dstore_0
+ true, // dstore_1
+ true, // dstore_2
+ true, // dstore_3
+ false, // astore_0
+ false, // astore_1
+ false, // astore_2
+ false, // astore_3
+ false, // iastore
+ true, // lastore
+ false, // fastore
+ true, // dastore
+ false, // aastore
+ false, // bastore
+ false, // castore
+ false, // sastore
+ false, // pop
+ true, // pop2
+ false, // dup
+ false, // dup_x1
+ false, // dup_x2
+ true, // dup2
+ true, // dup2_x1
+ true, // dup2_x2
+ false, // swap
+ false, // iadd
+ true, // ladd
+ false, // fadd
+ true, // dadd
+ false, // isub
+ true, // lsub
+ false, // fsub
+ true, // dsub
+ false, // imul
+ true, // lmul
+ false, // fmul
+ true, // dmul
+ false, // idiv
+ true, // ldiv
+ false, // fdiv
+ true, // ddiv
+ false, // irem
+ true, // lrem
+ false, // frem
+ true, // drem
+ false, // ineg
+ true, // lneg
+ false, // fneg
+ true, // dneg
+ false, // ishl
+ true, // lshl
+ false, // ishr
+ true, // lshr
+ false, // iushr
+ true, // lushr
+ false, // iand
+ true, // land
+ false, // ior
+ true, // lor
+ false, // ixor
+ true, // lxor
+ false, // iinc
+ false, // i2l
+ false, // i2f
+ false, // i2d
+ true, // l2i
+ true, // l2f
+ true, // l2d
+ false, // f2i
+ false, // f2l
+ false, // f2d
+ true, // d2i
+ true, // d2l
+ true, // d2f
+ false, // i2b
+ false, // i2c
+ false, // i2s
+ true, // lcmp
+ false, // fcmpl
+ false, // fcmpg
+ true, // dcmpl
+ true, // dcmpg
+ false, // ifeq
+ false, // ifne
+ false, // iflt
+ false, // ifge
+ false, // ifgt
+ false, // ifle
+ false, // ificmpeq
+ false, // ificmpne
+ false, // ificmplt
+ false, // ificmpge
+ false, // ificmpgt
+ false, // ificmple
+ false, // ifacmpeq
+ false, // ifacmpne
+ false, // goto
+ false, // jsr
+ false, // ret
+ false, // tableswitch
+ false, // lookupswitch
+ false, // ireturn
+ true, // lreturn
+ false, // freturn
+ true, // dreturn
+ false, // areturn
+ false, // return
+ false, // getstatic
+ false, // putstatic
+ false, // getfield
+ false, // putfield
+ false, // invokevirtual
+ false, // invokespecial
+ false, // invokestatic
+ false, // invokeinterface
+ false, // invokedynamic
+ false, // new
+ false, // newarray
+ false, // anewarray
+ false, // arraylength
+ false, // athrow
+ false, // checkcast
+ false, // instanceof
+ false, // monitorenter
+ false, // monitorexit
+ false, // wide
+ false, // multianewarray
+ false, // ifnull
+ false, // ifnonnull
+ false, // goto_w
+ false, // jsr_w
+ };
+
+
+ // An array containing the fixed number of entries popped from the stack,
+ // for all instructions.
+ private static final int[] STACK_POP_COUNTS = new int[]
+ {
+ 0, // nop
+ 0, // aconst_null
+ 0, // iconst_m1
+ 0, // iconst_0
+ 0, // iconst_1
+ 0, // iconst_2
+ 0, // iconst_3
+ 0, // iconst_4
+ 0, // iconst_5
+ 0, // lconst_0
+ 0, // lconst_1
+ 0, // fconst_0
+ 0, // fconst_1
+ 0, // fconst_2
+ 0, // dconst_0
+ 0, // dconst_1
+ 0, // bipush
+ 0, // sipush
+ 0, // ldc
+ 0, // ldc_w
+ 0, // ldc2_w
+ 0, // iload
+ 0, // lload
+ 0, // fload
+ 0, // dload
+ 0, // aload
+ 0, // iload_0
+ 0, // iload_1
+ 0, // iload_2
+ 0, // iload_3
+ 0, // lload_0
+ 0, // lload_1
+ 0, // lload_2
+ 0, // lload_3
+ 0, // fload_0
+ 0, // fload_1
+ 0, // fload_2
+ 0, // fload_3
+ 0, // dload_0
+ 0, // dload_1
+ 0, // dload_2
+ 0, // dload_3
+ 0, // aload_0
+ 0, // aload_1
+ 0, // aload_2
+ 0, // aload_3
+ 2, // iaload
+ 2, // laload
+ 2, // faload
+ 2, // daload
+ 2, // aaload
+ 2, // baload
+ 2, // caload
+ 2, // saload
+ 1, // istore
+ 2, // lstore
+ 1, // fstore
+ 2, // dstore
+ 1, // astore
+ 1, // istore_0
+ 1, // istore_1
+ 1, // istore_2
+ 1, // istore_3
+ 2, // lstore_0
+ 2, // lstore_1
+ 2, // lstore_2
+ 2, // lstore_3
+ 1, // fstore_0
+ 1, // fstore_1
+ 1, // fstore_2
+ 1, // fstore_3
+ 2, // dstore_0
+ 2, // dstore_1
+ 2, // dstore_2
+ 2, // dstore_3
+ 1, // astore_0
+ 1, // astore_1
+ 1, // astore_2
+ 1, // astore_3
+ 3, // iastore
+ 4, // lastore
+ 3, // fastore
+ 4, // dastore
+ 3, // aastore
+ 3, // bastore
+ 3, // castore
+ 3, // sastore
+ 1, // pop
+ 2, // pop2
+ 1, // dup
+ 2, // dup_x1
+ 3, // dup_x2
+ 2, // dup2
+ 3, // dup2_x1
+ 4, // dup2_x2
+ 2, // swap
+ 2, // iadd
+ 4, // ladd
+ 2, // fadd
+ 4, // dadd
+ 2, // isub
+ 4, // lsub
+ 2, // fsub
+ 4, // dsub
+ 2, // imul
+ 4, // lmul
+ 2, // fmul
+ 4, // dmul
+ 2, // idiv
+ 4, // ldiv
+ 2, // fdiv
+ 4, // ddiv
+ 2, // irem
+ 4, // lrem
+ 2, // frem
+ 4, // drem
+ 1, // ineg
+ 2, // lneg
+ 1, // fneg
+ 2, // dneg
+ 2, // ishl
+ 3, // lshl
+ 2, // ishr
+ 3, // lshr
+ 2, // iushr
+ 3, // lushr
+ 2, // iand
+ 4, // land
+ 2, // ior
+ 4, // lor
+ 2, // ixor
+ 4, // lxor
+ 0, // iinc
+ 1, // i2l
+ 1, // i2f
+ 1, // i2d
+ 2, // l2i
+ 2, // l2f
+ 2, // l2d
+ 1, // f2i
+ 1, // f2l
+ 1, // f2d
+ 2, // d2i
+ 2, // d2l
+ 2, // d2f
+ 1, // i2b
+ 1, // i2c
+ 1, // i2s
+ 4, // lcmp
+ 2, // fcmpl
+ 2, // fcmpg
+ 4, // dcmpl
+ 4, // dcmpg
+ 1, // ifeq
+ 1, // ifne
+ 1, // iflt
+ 1, // ifge
+ 1, // ifgt
+ 1, // ifle
+ 2, // ificmpeq
+ 2, // ificmpne
+ 2, // ificmplt
+ 2, // ificmpge
+ 2, // ificmpgt
+ 2, // ificmple
+ 2, // ifacmpeq
+ 2, // ifacmpne
+ 0, // goto
+ 0, // jsr
+ 0, // ret
+ 1, // tableswitch
+ 1, // lookupswitch
+ 1, // ireturn
+ 2, // lreturn
+ 1, // freturn
+ 2, // dreturn
+ 1, // areturn
+ 0, // return
+ 0, // getstatic
+ 0, // putstatic
+ 1, // getfield
+ 1, // putfield
+ 1, // invokevirtual
+ 1, // invokespecial
+ 0, // invokestatic
+ 1, // invokeinterface
+ 0, // invokedynamic
+ 0, // new
+ 1, // newarray
+ 1, // anewarray
+ 1, // arraylength
+ 1, // athrow
+ 1, // checkcast
+ 1, // instanceof
+ 1, // monitorenter
+ 1, // monitorexit
+ 0, // wide
+ 0, // multianewarray
+ 1, // ifnull
+ 1, // ifnonnull
+ 0, // goto_w
+ 0, // jsr_w
+ };
+
+
+ // An array containing the fixed number of entries pushed onto the stack,
+ // for all instructions.
+ private static final int[] STACK_PUSH_COUNTS = new int[]
+ {
+ 0, // nop
+ 1, // aconst_null
+ 1, // iconst_m1
+ 1, // iconst_0
+ 1, // iconst_1
+ 1, // iconst_2
+ 1, // iconst_3
+ 1, // iconst_4
+ 1, // iconst_5
+ 2, // lconst_0
+ 2, // lconst_1
+ 1, // fconst_0
+ 1, // fconst_1
+ 1, // fconst_2
+ 2, // dconst_0
+ 2, // dconst_1
+ 1, // bipush
+ 1, // sipush
+ 1, // ldc
+ 1, // ldc_w
+ 2, // ldc2_w
+ 1, // iload
+ 2, // lload
+ 1, // fload
+ 2, // dload
+ 1, // aload
+ 1, // iload_0
+ 1, // iload_1
+ 1, // iload_2
+ 1, // iload_3
+ 2, // lload_0
+ 2, // lload_1
+ 2, // lload_2
+ 2, // lload_3
+ 1, // fload_0
+ 1, // fload_1
+ 1, // fload_2
+ 1, // fload_3
+ 2, // dload_0
+ 2, // dload_1
+ 2, // dload_2
+ 2, // dload_3
+ 1, // aload_0
+ 1, // aload_1
+ 1, // aload_2
+ 1, // aload_3
+ 1, // iaload
+ 2, // laload
+ 1, // faload
+ 2, // daload
+ 1, // aaload
+ 1, // baload
+ 1, // caload
+ 1, // saload
+ 0, // istore
+ 0, // lstore
+ 0, // fstore
+ 0, // dstore
+ 0, // astore
+ 0, // istore_0
+ 0, // istore_1
+ 0, // istore_2
+ 0, // istore_3
+ 0, // lstore_0
+ 0, // lstore_1
+ 0, // lstore_2
+ 0, // lstore_3
+ 0, // fstore_0
+ 0, // fstore_1
+ 0, // fstore_2
+ 0, // fstore_3
+ 0, // dstore_0
+ 0, // dstore_1
+ 0, // dstore_2
+ 0, // dstore_3
+ 0, // astore_0
+ 0, // astore_1
+ 0, // astore_2
+ 0, // astore_3
+ 0, // iastore
+ 0, // lastore
+ 0, // fastore
+ 0, // dastore
+ 0, // aastore
+ 0, // bastore
+ 0, // castore
+ 0, // sastore
+ 0, // pop
+ 0, // pop2
+ 2, // dup
+ 3, // dup_x1
+ 4, // dup_x2
+ 4, // dup2
+ 5, // dup2_x1
+ 6, // dup2_x2
+ 2, // swap
+ 1, // iadd
+ 2, // ladd
+ 1, // fadd
+ 2, // dadd
+ 1, // isub
+ 2, // lsub
+ 1, // fsub
+ 2, // dsub
+ 1, // imul
+ 2, // lmul
+ 1, // fmul
+ 2, // dmul
+ 1, // idiv
+ 2, // ldiv
+ 1, // fdiv
+ 2, // ddiv
+ 1, // irem
+ 2, // lrem
+ 1, // frem
+ 2, // drem
+ 1, // ineg
+ 2, // lneg
+ 1, // fneg
+ 2, // dneg
+ 1, // ishl
+ 2, // lshl
+ 1, // ishr
+ 2, // lshr
+ 1, // iushr
+ 2, // lushr
+ 1, // iand
+ 2, // land
+ 1, // ior
+ 2, // lor
+ 1, // ixor
+ 2, // lxor
+ 0, // iinc
+ 2, // i2l
+ 1, // i2f
+ 2, // i2d
+ 1, // l2i
+ 1, // l2f
+ 2, // l2d
+ 1, // f2i
+ 2, // f2l
+ 2, // f2d
+ 1, // d2i
+ 2, // d2l
+ 1, // d2f
+ 1, // i2b
+ 1, // i2c
+ 1, // i2s
+ 1, // lcmp
+ 1, // fcmpl
+ 1, // fcmpg
+ 1, // dcmpl
+ 1, // dcmpg
+ 0, // ifeq
+ 0, // ifne
+ 0, // iflt
+ 0, // ifge
+ 0, // ifgt
+ 0, // ifle
+ 0, // ificmpeq
+ 0, // ificmpne
+ 0, // ificmplt
+ 0, // ificmpge
+ 0, // ificmpgt
+ 0, // ificmple
+ 0, // ifacmpeq
+ 0, // ifacmpne
+ 0, // goto
+ 1, // jsr
+ 0, // ret
+ 0, // tableswitch
+ 0, // lookupswitch
+ 0, // ireturn
+ 0, // lreturn
+ 0, // freturn
+ 0, // dreturn
+ 0, // areturn
+ 0, // return
+ 0, // getstatic
+ 0, // putstatic
+ 0, // getfield
+ 0, // putfield
+ 0, // invokevirtual
+ 0, // invokespecial
+ 0, // invokestatic
+ 0, // invokeinterface
+ 0, // invokedynamic
+ 1, // new
+ 1, // newarray
+ 1, // anewarray
+ 1, // arraylength
+ 0, // athrow
+ 1, // checkcast
+ 1, // instanceof
+ 0, // monitorenter
+ 0, // monitorexit
+ 0, // wide
+ 1, // multianewarray
+ 0, // ifnull
+ 0, // ifnonnull
+ 0, // goto_w
+ 1, // jsr_w
+ };
+
+
+ public byte opcode;
+
+
+ /**
+ * Returns the canonical opcode of this instruction, i.e. typically the
+ * opcode whose extension has been removed.
+ */
+ public byte canonicalOpcode()
+ {
+ return opcode;
+ }
+
+
+ /**
+ * Shrinks this instruction to its shortest possible form.
+ * @return this instruction.
+ */
+ public abstract Instruction shrink();
+
+
+
+ /**
+ * Writes the Instruction at the given offset in the given code attribute.
+ */
+ public final void write(CodeAttribute codeAttribute, int offset)
+ {
+ write(codeAttribute.code, offset);
+ }
+
+
+ /**
+ * Writes the Instruction at the given offset in the given code array.
+ */
+ public void write(byte[] code, int offset)
+ {
+ // Write the wide opcode, if necessary.
+ if (isWide())
+ {
+ code[offset++] = InstructionConstants.OP_WIDE;
+ }
+
+ // Write the opcode.
+ code[offset++] = opcode;
+
+ // Write any additional arguments.
+ writeInfo(code, offset);
+ }
+
+
+ /**
+ * Returns whether the instruction is wide, i.e. preceded by a wide opcode.
+ * With the current specifications, only variable instructions can be wide.
+ */
+ protected boolean isWide()
+ {
+ return false;
+ }
+
+
+ /**
+ * Reads the data following the instruction opcode.
+ */
+ protected abstract void readInfo(byte[] code, int offset);
+
+
+ /**
+ * Writes data following the instruction opcode.
+ */
+ protected abstract void writeInfo(byte[] code, int offset);
+
+
+ /**
+ * Returns the length in bytes of the instruction.
+ */
+ public abstract int length(int offset);
+
+
+ /**
+ * Accepts the given visitor.
+ */
+ public abstract void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor);
+
+
+ /**
+ * Returns a description of the instruction, at the given offset.
+ */
+ public String toString(int offset)
+ {
+ return "["+offset+"] "+ this.toString();
+ }
+
+
+ /**
+ * Returns the name of the instruction.
+ */
+ public String getName()
+ {
+ return InstructionConstants.NAMES[opcode & 0xff];
+ }
+
+
+ /**
+ * Returns whether the instruction is a Category 2 instruction. This means
+ * that it operates on long or double arguments.
+ */
+ public boolean isCategory2()
+ {
+ return IS_CATEGORY2[opcode & 0xff];
+ }
+
+
+ /**
+ * Returns the number of entries popped from the stack during the execution
+ * of the instruction.
+ */
+ public int stackPopCount(Clazz clazz)
+ {
+ return STACK_POP_COUNTS[opcode & 0xff];
+ }
+
+
+ /**
+ * Returns the number of entries pushed onto the stack during the execution
+ * of the instruction.
+ */
+ public int stackPushCount(Clazz clazz)
+ {
+ return STACK_PUSH_COUNTS[opcode & 0xff];
+ }
+
+
+ // Small utility methods.
+
+ protected static int readByte(byte[] code, int offset)
+ {
+ return code[offset] & 0xff;
+ }
+
+ protected static int readShort(byte[] code, int offset)
+ {
+ return ((code[offset++] & 0xff) << 8) |
+ ( code[offset ] & 0xff );
+ }
+
+ protected static int readInt(byte[] code, int offset)
+ {
+ return ( code[offset++] << 24) |
+ ((code[offset++] & 0xff) << 16) |
+ ((code[offset++] & 0xff) << 8) |
+ ( code[offset ] & 0xff );
+ }
+
+ protected static int readValue(byte[] code, int offset, int valueSize)
+ {
+ switch (valueSize)
+ {
+ case 0: return 0;
+ case 1: return readByte( code, offset);
+ case 2: return readShort(code, offset);
+ case 4: return readInt( code, offset);
+ default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
+ }
+ }
+
+ protected static int readSignedByte(byte[] code, int offset)
+ {
+ return code[offset];
+ }
+
+ protected static int readSignedShort(byte[] code, int offset)
+ {
+ return (code[offset++] << 8) |
+ (code[offset ] & 0xff);
+ }
+
+ protected static int readSignedValue(byte[] code, int offset, int valueSize)
+ {
+ switch (valueSize)
+ {
+ case 0: return 0;
+ case 1: return readSignedByte( code, offset);
+ case 2: return readSignedShort(code, offset);
+ case 4: return readInt( code, offset);
+ default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
+ }
+ }
+
+ protected static void writeByte(byte[] code, int offset, int value)
+ {
+ if (value > 0xff)
+ {
+ throw new IllegalArgumentException("Unsigned byte value larger than 0xff ["+value+"]");
+ }
+
+ code[offset] = (byte)value;
+ }
+
+ protected static void writeShort(byte[] code, int offset, int value)
+ {
+ if (value > 0xffff)
+ {
+ throw new IllegalArgumentException("Unsigned short value larger than 0xffff ["+value+"]");
+ }
+
+ code[offset++] = (byte)(value >> 8);
+ code[offset ] = (byte)(value );
+ }
+
+ protected static void writeInt(byte[] code, int offset, int value)
+ {
+ code[offset++] = (byte)(value >> 24);
+ code[offset++] = (byte)(value >> 16);
+ code[offset++] = (byte)(value >> 8);
+ code[offset ] = (byte)(value );
+ }
+
+ protected static void writeValue(byte[] code, int offset, int value, int valueSize)
+ {
+ switch (valueSize)
+ {
+ case 0: break;
+ case 1: writeByte( code, offset, value); break;
+ case 2: writeShort(code, offset, value); break;
+ case 4: writeInt( code, offset, value); break;
+ default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
+ }
+ }
+
+ protected static void writeSignedByte(byte[] code, int offset, int value)
+ {
+ if ((byte)value != value)
+ {
+ throw new IllegalArgumentException("Signed byte value out of range ["+value+"]");
+ }
+
+ code[offset] = (byte)value;
+ }
+
+ protected static void writeSignedShort(byte[] code, int offset, int value)
+ {
+ if ((short)value != value)
+ {
+ throw new IllegalArgumentException("Signed short value out of range ["+value+"]");
+ }
+
+ code[offset++] = (byte)(value >> 8);
+ code[offset ] = (byte)(value );
+ }
+
+ protected static void writeSignedValue(byte[] code, int offset, int value, int valueSize)
+ {
+ switch (valueSize)
+ {
+ case 0: break;
+ case 1: writeSignedByte( code, offset, value); break;
+ case 2: writeSignedShort(code, offset, value); break;
+ case 4: writeInt( code, offset, value); break;
+ default: throw new IllegalArgumentException("Unsupported value size ["+valueSize+"]");
+ }
+ }
+}
diff --git a/src/proguard/classfile/instruction/InstructionConstants.java b/src/proguard/classfile/instruction/InstructionConstants.java
new file mode 100644
index 000000000..d8cbd9841
--- /dev/null
+++ b/src/proguard/classfile/instruction/InstructionConstants.java
@@ -0,0 +1,449 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+/**
+ * Representation of an instruction.
+ *
+ * @author Eric Lafortune
+ */
+public interface InstructionConstants
+{
+ public static final byte OP_NOP = 0;
+ public static final byte OP_ACONST_NULL = 1;
+ public static final byte OP_ICONST_M1 = 2;
+ public static final byte OP_ICONST_0 = 3;
+ public static final byte OP_ICONST_1 = 4;
+ public static final byte OP_ICONST_2 = 5;
+ public static final byte OP_ICONST_3 = 6;
+ public static final byte OP_ICONST_4 = 7;
+ public static final byte OP_ICONST_5 = 8;
+ public static final byte OP_LCONST_0 = 9;
+ public static final byte OP_LCONST_1 = 10;
+ public static final byte OP_FCONST_0 = 11;
+ public static final byte OP_FCONST_1 = 12;
+ public static final byte OP_FCONST_2 = 13;
+ public static final byte OP_DCONST_0 = 14;
+ public static final byte OP_DCONST_1 = 15;
+ public static final byte OP_BIPUSH = 16;
+ public static final byte OP_SIPUSH = 17;
+ public static final byte OP_LDC = 18;
+ public static final byte OP_LDC_W = 19;
+ public static final byte OP_LDC2_W = 20;
+ public static final byte OP_ILOAD = 21;
+ public static final byte OP_LLOAD = 22;
+ public static final byte OP_FLOAD = 23;
+ public static final byte OP_DLOAD = 24;
+ public static final byte OP_ALOAD = 25;
+ public static final byte OP_ILOAD_0 = 26;
+ public static final byte OP_ILOAD_1 = 27;
+ public static final byte OP_ILOAD_2 = 28;
+ public static final byte OP_ILOAD_3 = 29;
+ public static final byte OP_LLOAD_0 = 30;
+ public static final byte OP_LLOAD_1 = 31;
+ public static final byte OP_LLOAD_2 = 32;
+ public static final byte OP_LLOAD_3 = 33;
+ public static final byte OP_FLOAD_0 = 34;
+ public static final byte OP_FLOAD_1 = 35;
+ public static final byte OP_FLOAD_2 = 36;
+ public static final byte OP_FLOAD_3 = 37;
+ public static final byte OP_DLOAD_0 = 38;
+ public static final byte OP_DLOAD_1 = 39;
+ public static final byte OP_DLOAD_2 = 40;
+ public static final byte OP_DLOAD_3 = 41;
+ public static final byte OP_ALOAD_0 = 42;
+ public static final byte OP_ALOAD_1 = 43;
+ public static final byte OP_ALOAD_2 = 44;
+ public static final byte OP_ALOAD_3 = 45;
+ public static final byte OP_IALOAD = 46;
+ public static final byte OP_LALOAD = 47;
+ public static final byte OP_FALOAD = 48;
+ public static final byte OP_DALOAD = 49;
+ public static final byte OP_AALOAD = 50;
+ public static final byte OP_BALOAD = 51;
+ public static final byte OP_CALOAD = 52;
+ public static final byte OP_SALOAD = 53;
+ public static final byte OP_ISTORE = 54;
+ public static final byte OP_LSTORE = 55;
+ public static final byte OP_FSTORE = 56;
+ public static final byte OP_DSTORE = 57;
+ public static final byte OP_ASTORE = 58;
+ public static final byte OP_ISTORE_0 = 59;
+ public static final byte OP_ISTORE_1 = 60;
+ public static final byte OP_ISTORE_2 = 61;
+ public static final byte OP_ISTORE_3 = 62;
+ public static final byte OP_LSTORE_0 = 63;
+ public static final byte OP_LSTORE_1 = 64;
+ public static final byte OP_LSTORE_2 = 65;
+ public static final byte OP_LSTORE_3 = 66;
+ public static final byte OP_FSTORE_0 = 67;
+ public static final byte OP_FSTORE_1 = 68;
+ public static final byte OP_FSTORE_2 = 69;
+ public static final byte OP_FSTORE_3 = 70;
+ public static final byte OP_DSTORE_0 = 71;
+ public static final byte OP_DSTORE_1 = 72;
+ public static final byte OP_DSTORE_2 = 73;
+ public static final byte OP_DSTORE_3 = 74;
+ public static final byte OP_ASTORE_0 = 75;
+ public static final byte OP_ASTORE_1 = 76;
+ public static final byte OP_ASTORE_2 = 77;
+ public static final byte OP_ASTORE_3 = 78;
+ public static final byte OP_IASTORE = 79;
+ public static final byte OP_LASTORE = 80;
+ public static final byte OP_FASTORE = 81;
+ public static final byte OP_DASTORE = 82;
+ public static final byte OP_AASTORE = 83;
+ public static final byte OP_BASTORE = 84;
+ public static final byte OP_CASTORE = 85;
+ public static final byte OP_SASTORE = 86;
+ public static final byte OP_POP = 87;
+ public static final byte OP_POP2 = 88;
+ public static final byte OP_DUP = 89;
+ public static final byte OP_DUP_X1 = 90;
+ public static final byte OP_DUP_X2 = 91;
+ public static final byte OP_DUP2 = 92;
+ public static final byte OP_DUP2_X1 = 93;
+ public static final byte OP_DUP2_X2 = 94;
+ public static final byte OP_SWAP = 95;
+ public static final byte OP_IADD = 96;
+ public static final byte OP_LADD = 97;
+ public static final byte OP_FADD = 98;
+ public static final byte OP_DADD = 99;
+ public static final byte OP_ISUB = 100;
+ public static final byte OP_LSUB = 101;
+ public static final byte OP_FSUB = 102;
+ public static final byte OP_DSUB = 103;
+ public static final byte OP_IMUL = 104;
+ public static final byte OP_LMUL = 105;
+ public static final byte OP_FMUL = 106;
+ public static final byte OP_DMUL = 107;
+ public static final byte OP_IDIV = 108;
+ public static final byte OP_LDIV = 109;
+ public static final byte OP_FDIV = 110;
+ public static final byte OP_DDIV = 111;
+ public static final byte OP_IREM = 112;
+ public static final byte OP_LREM = 113;
+ public static final byte OP_FREM = 114;
+ public static final byte OP_DREM = 115;
+ public static final byte OP_INEG = 116;
+ public static final byte OP_LNEG = 117;
+ public static final byte OP_FNEG = 118;
+ public static final byte OP_DNEG = 119;
+ public static final byte OP_ISHL = 120;
+ public static final byte OP_LSHL = 121;
+ public static final byte OP_ISHR = 122;
+ public static final byte OP_LSHR = 123;
+ public static final byte OP_IUSHR = 124;
+ public static final byte OP_LUSHR = 125;
+ public static final byte OP_IAND = 126;
+ public static final byte OP_LAND = 127;
+ public static final byte OP_IOR = -128;
+ public static final byte OP_LOR = -127;
+ public static final byte OP_IXOR = -126;
+ public static final byte OP_LXOR = -125;
+ public static final byte OP_IINC = -124;
+ public static final byte OP_I2L = -123;
+ public static final byte OP_I2F = -122;
+ public static final byte OP_I2D = -121;
+ public static final byte OP_L2I = -120;
+ public static final byte OP_L2F = -119;
+ public static final byte OP_L2D = -118;
+ public static final byte OP_F2I = -117;
+ public static final byte OP_F2L = -116;
+ public static final byte OP_F2D = -115;
+ public static final byte OP_D2I = -114;
+ public static final byte OP_D2L = -113;
+ public static final byte OP_D2F = -112;
+ public static final byte OP_I2B = -111;
+ public static final byte OP_I2C = -110;
+ public static final byte OP_I2S = -109;
+ public static final byte OP_LCMP = -108;
+ public static final byte OP_FCMPL = -107;
+ public static final byte OP_FCMPG = -106;
+ public static final byte OP_DCMPL = -105;
+ public static final byte OP_DCMPG = -104;
+ public static final byte OP_IFEQ = -103;
+ public static final byte OP_IFNE = -102;
+ public static final byte OP_IFLT = -101;
+ public static final byte OP_IFGE = -100;
+ public static final byte OP_IFGT = -99;
+ public static final byte OP_IFLE = -98;
+ public static final byte OP_IFICMPEQ = -97;
+ public static final byte OP_IFICMPNE = -96;
+ public static final byte OP_IFICMPLT = -95;
+ public static final byte OP_IFICMPGE = -94;
+ public static final byte OP_IFICMPGT = -93;
+ public static final byte OP_IFICMPLE = -92;
+ public static final byte OP_IFACMPEQ = -91;
+ public static final byte OP_IFACMPNE = -90;
+ public static final byte OP_GOTO = -89;
+ public static final byte OP_JSR = -88;
+ public static final byte OP_RET = -87;
+ public static final byte OP_TABLESWITCH = -86;
+ public static final byte OP_LOOKUPSWITCH = -85;
+ public static final byte OP_IRETURN = -84;
+ public static final byte OP_LRETURN = -83;
+ public static final byte OP_FRETURN = -82;
+ public static final byte OP_DRETURN = -81;
+ public static final byte OP_ARETURN = -80;
+ public static final byte OP_RETURN = -79;
+ public static final byte OP_GETSTATIC = -78;
+ public static final byte OP_PUTSTATIC = -77;
+ public static final byte OP_GETFIELD = -76;
+ public static final byte OP_PUTFIELD = -75;
+ public static final byte OP_INVOKEVIRTUAL = -74;
+ public static final byte OP_INVOKESPECIAL = -73;
+ public static final byte OP_INVOKESTATIC = -72;
+ public static final byte OP_INVOKEINTERFACE = -71;
+ public static final byte OP_INVOKEDYNAMIC = -70;
+ public static final byte OP_NEW = -69;
+ public static final byte OP_NEWARRAY = -68;
+ public static final byte OP_ANEWARRAY = -67;
+ public static final byte OP_ARRAYLENGTH = -66;
+ public static final byte OP_ATHROW = -65;
+ public static final byte OP_CHECKCAST = -64;
+ public static final byte OP_INSTANCEOF = -63;
+ public static final byte OP_MONITORENTER = -62;
+ public static final byte OP_MONITOREXIT = -61;
+ public static final byte OP_WIDE = -60;
+ public static final byte OP_MULTIANEWARRAY = -59;
+ public static final byte OP_IFNULL = -58;
+ public static final byte OP_IFNONNULL = -57;
+ public static final byte OP_GOTO_W = -56;
+ public static final byte OP_JSR_W = -55;
+
+
+ public static final String[] NAMES =
+ {
+ "nop",
+ "aconst_null",
+ "iconst_m1",
+ "iconst_0",
+ "iconst_1",
+ "iconst_2",
+ "iconst_3",
+ "iconst_4",
+ "iconst_5",
+ "lconst_0",
+ "lconst_1",
+ "fconst_0",
+ "fconst_1",
+ "fconst_2",
+ "dconst_0",
+ "dconst_1",
+ "bipush",
+ "sipush",
+ "ldc",
+ "ldc_w",
+ "ldc2_w",
+ "iload",
+ "lload",
+ "fload",
+ "dload",
+ "aload",
+ "iload_0",
+ "iload_1",
+ "iload_2",
+ "iload_3",
+ "lload_0",
+ "lload_1",
+ "lload_2",
+ "lload_3",
+ "fload_0",
+ "fload_1",
+ "fload_2",
+ "fload_3",
+ "dload_0",
+ "dload_1",
+ "dload_2",
+ "dload_3",
+ "aload_0",
+ "aload_1",
+ "aload_2",
+ "aload_3",
+ "iaload",
+ "laload",
+ "faload",
+ "daload",
+ "aaload",
+ "baload",
+ "caload",
+ "saload",
+ "istore",
+ "lstore",
+ "fstore",
+ "dstore",
+ "astore",
+ "istore_0",
+ "istore_1",
+ "istore_2",
+ "istore_3",
+ "lstore_0",
+ "lstore_1",
+ "lstore_2",
+ "lstore_3",
+ "fstore_0",
+ "fstore_1",
+ "fstore_2",
+ "fstore_3",
+ "dstore_0",
+ "dstore_1",
+ "dstore_2",
+ "dstore_3",
+ "astore_0",
+ "astore_1",
+ "astore_2",
+ "astore_3",
+ "iastore",
+ "lastore",
+ "fastore",
+ "dastore",
+ "aastore",
+ "bastore",
+ "castore",
+ "sastore",
+ "pop",
+ "pop2",
+ "dup",
+ "dup_x1",
+ "dup_x2",
+ "dup2",
+ "dup2_x1",
+ "dup2_x2",
+ "swap",
+ "iadd",
+ "ladd",
+ "fadd",
+ "dadd",
+ "isub",
+ "lsub",
+ "fsub",
+ "dsub",
+ "imul",
+ "lmul",
+ "fmul",
+ "dmul",
+ "idiv",
+ "ldiv",
+ "fdiv",
+ "ddiv",
+ "irem",
+ "lrem",
+ "frem",
+ "drem",
+ "ineg",
+ "lneg",
+ "fneg",
+ "dneg",
+ "ishl",
+ "lshl",
+ "ishr",
+ "lshr",
+ "iushr",
+ "lushr",
+ "iand",
+ "land",
+ "ior",
+ "lor",
+ "ixor",
+ "lxor",
+ "iinc",
+ "i2l",
+ "i2f",
+ "i2d",
+ "l2i",
+ "l2f",
+ "l2d",
+ "f2i",
+ "f2l",
+ "f2d",
+ "d2i",
+ "d2l",
+ "d2f",
+ "i2b",
+ "i2c",
+ "i2s",
+ "lcmp",
+ "fcmpl",
+ "fcmpg",
+ "dcmpl",
+ "dcmpg",
+ "ifeq",
+ "ifne",
+ "iflt",
+ "ifge",
+ "ifgt",
+ "ifle",
+ "ificmpeq",
+ "ificmpne",
+ "ificmplt",
+ "ificmpge",
+ "ificmpgt",
+ "ificmple",
+ "ifacmpeq",
+ "ifacmpne",
+ "goto",
+ "jsr",
+ "ret",
+ "tableswitch",
+ "lookupswitch",
+ "ireturn",
+ "lreturn",
+ "freturn",
+ "dreturn",
+ "areturn",
+ "return",
+ "getstatic",
+ "putstatic",
+ "getfield",
+ "putfield",
+ "invokevirtual",
+ "invokespecial",
+ "invokestatic",
+ "invokeinterface",
+ "invokedynamic",
+ "new",
+ "newarray",
+ "anewarray",
+ "arraylength",
+ "athrow",
+ "checkcast",
+ "instanceof",
+ "monitorenter",
+ "monitorexit",
+ "wide",
+ "multianewarray",
+ "ifnull",
+ "ifnonnull",
+ "goto_w",
+ "jsr_w",
+ };
+
+
+ public static final byte ARRAY_T_BOOLEAN = 4;
+ public static final byte ARRAY_T_CHAR = 5;
+ public static final byte ARRAY_T_FLOAT = 6;
+ public static final byte ARRAY_T_DOUBLE = 7;
+ public static final byte ARRAY_T_BYTE = 8;
+ public static final byte ARRAY_T_SHORT = 9;
+ public static final byte ARRAY_T_INT = 10;
+ public static final byte ARRAY_T_LONG = 11;
+}
diff --git a/src/proguard/classfile/instruction/InstructionFactory.java b/src/proguard/classfile/instruction/InstructionFactory.java
new file mode 100644
index 000000000..89d498c60
--- /dev/null
+++ b/src/proguard/classfile/instruction/InstructionFactory.java
@@ -0,0 +1,300 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+/**
+ * This class provides methods to create and reuse Instruction objects.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionFactory
+{
+ /**
+ * Creates a new Instruction from the data in the byte array, starting
+ * at the given index.
+ */
+ public static Instruction create(byte[] code, int offset)
+ {
+ Instruction instruction;
+
+ int index = offset;
+ byte opcode = code[index++];
+
+ boolean wide = false;
+ if (opcode == InstructionConstants.OP_WIDE)
+ {
+ opcode = code[index++];
+ wide = true;
+ }
+
+ switch (opcode)
+ {
+ // Simple instructions.
+ case InstructionConstants.OP_NOP:
+ case InstructionConstants.OP_ACONST_NULL:
+ case InstructionConstants.OP_ICONST_M1:
+ case InstructionConstants.OP_ICONST_0:
+ case InstructionConstants.OP_ICONST_1:
+ case InstructionConstants.OP_ICONST_2:
+ case InstructionConstants.OP_ICONST_3:
+ case InstructionConstants.OP_ICONST_4:
+ case InstructionConstants.OP_ICONST_5:
+ case InstructionConstants.OP_LCONST_0:
+ case InstructionConstants.OP_LCONST_1:
+ case InstructionConstants.OP_FCONST_0:
+ case InstructionConstants.OP_FCONST_1:
+ case InstructionConstants.OP_FCONST_2:
+ case InstructionConstants.OP_DCONST_0:
+ case InstructionConstants.OP_DCONST_1:
+
+ case InstructionConstants.OP_BIPUSH:
+ case InstructionConstants.OP_SIPUSH:
+
+ case InstructionConstants.OP_IALOAD:
+ case InstructionConstants.OP_LALOAD:
+ case InstructionConstants.OP_FALOAD:
+ case InstructionConstants.OP_DALOAD:
+ case InstructionConstants.OP_AALOAD:
+ case InstructionConstants.OP_BALOAD:
+ case InstructionConstants.OP_CALOAD:
+ case InstructionConstants.OP_SALOAD:
+
+ case InstructionConstants.OP_IASTORE:
+ case InstructionConstants.OP_LASTORE:
+ case InstructionConstants.OP_FASTORE:
+ case InstructionConstants.OP_DASTORE:
+ case InstructionConstants.OP_AASTORE:
+ case InstructionConstants.OP_BASTORE:
+ case InstructionConstants.OP_CASTORE:
+ case InstructionConstants.OP_SASTORE:
+ case InstructionConstants.OP_POP:
+ case InstructionConstants.OP_POP2:
+ case InstructionConstants.OP_DUP:
+ case InstructionConstants.OP_DUP_X1:
+ case InstructionConstants.OP_DUP_X2:
+ case InstructionConstants.OP_DUP2:
+ case InstructionConstants.OP_DUP2_X1:
+ case InstructionConstants.OP_DUP2_X2:
+ case InstructionConstants.OP_SWAP:
+ case InstructionConstants.OP_IADD:
+ case InstructionConstants.OP_LADD:
+ case InstructionConstants.OP_FADD:
+ case InstructionConstants.OP_DADD:
+ case InstructionConstants.OP_ISUB:
+ case InstructionConstants.OP_LSUB:
+ case InstructionConstants.OP_FSUB:
+ case InstructionConstants.OP_DSUB:
+ case InstructionConstants.OP_IMUL:
+ case InstructionConstants.OP_LMUL:
+ case InstructionConstants.OP_FMUL:
+ case InstructionConstants.OP_DMUL:
+ case InstructionConstants.OP_IDIV:
+ case InstructionConstants.OP_LDIV:
+ case InstructionConstants.OP_FDIV:
+ case InstructionConstants.OP_DDIV:
+ case InstructionConstants.OP_IREM:
+ case InstructionConstants.OP_LREM:
+ case InstructionConstants.OP_FREM:
+ case InstructionConstants.OP_DREM:
+ case InstructionConstants.OP_INEG:
+ case InstructionConstants.OP_LNEG:
+ case InstructionConstants.OP_FNEG:
+ case InstructionConstants.OP_DNEG:
+ case InstructionConstants.OP_ISHL:
+ case InstructionConstants.OP_LSHL:
+ case InstructionConstants.OP_ISHR:
+ case InstructionConstants.OP_LSHR:
+ case InstructionConstants.OP_IUSHR:
+ case InstructionConstants.OP_LUSHR:
+ case InstructionConstants.OP_IAND:
+ case InstructionConstants.OP_LAND:
+ case InstructionConstants.OP_IOR:
+ case InstructionConstants.OP_LOR:
+ case InstructionConstants.OP_IXOR:
+ case InstructionConstants.OP_LXOR:
+
+ case InstructionConstants.OP_I2L:
+ case InstructionConstants.OP_I2F:
+ case InstructionConstants.OP_I2D:
+ case InstructionConstants.OP_L2I:
+ case InstructionConstants.OP_L2F:
+ case InstructionConstants.OP_L2D:
+ case InstructionConstants.OP_F2I:
+ case InstructionConstants.OP_F2L:
+ case InstructionConstants.OP_F2D:
+ case InstructionConstants.OP_D2I:
+ case InstructionConstants.OP_D2L:
+ case InstructionConstants.OP_D2F:
+ case InstructionConstants.OP_I2B:
+ case InstructionConstants.OP_I2C:
+ case InstructionConstants.OP_I2S:
+ case InstructionConstants.OP_LCMP:
+ case InstructionConstants.OP_FCMPL:
+ case InstructionConstants.OP_FCMPG:
+ case InstructionConstants.OP_DCMPL:
+ case InstructionConstants.OP_DCMPG:
+
+ case InstructionConstants.OP_IRETURN:
+ case InstructionConstants.OP_LRETURN:
+ case InstructionConstants.OP_FRETURN:
+ case InstructionConstants.OP_DRETURN:
+ case InstructionConstants.OP_ARETURN:
+ case InstructionConstants.OP_RETURN:
+
+ case InstructionConstants.OP_NEWARRAY:
+ case InstructionConstants.OP_ARRAYLENGTH:
+ case InstructionConstants.OP_ATHROW:
+
+ case InstructionConstants.OP_MONITORENTER:
+ case InstructionConstants.OP_MONITOREXIT:
+ instruction = new SimpleInstruction();
+ break;
+
+ // Instructions with a contant pool index.
+ case InstructionConstants.OP_LDC:
+ case InstructionConstants.OP_LDC_W:
+ case InstructionConstants.OP_LDC2_W:
+
+ case InstructionConstants.OP_GETSTATIC:
+ case InstructionConstants.OP_PUTSTATIC:
+ case InstructionConstants.OP_GETFIELD:
+ case InstructionConstants.OP_PUTFIELD:
+
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ case InstructionConstants.OP_INVOKEDYNAMIC:
+
+ case InstructionConstants.OP_NEW:
+ case InstructionConstants.OP_ANEWARRAY:
+ case InstructionConstants.OP_CHECKCAST:
+ case InstructionConstants.OP_INSTANCEOF:
+ case InstructionConstants.OP_MULTIANEWARRAY:
+ instruction = new ConstantInstruction();
+ break;
+
+ // Instructions with a local variable index.
+ case InstructionConstants.OP_ILOAD:
+ case InstructionConstants.OP_LLOAD:
+ case InstructionConstants.OP_FLOAD:
+ case InstructionConstants.OP_DLOAD:
+ case InstructionConstants.OP_ALOAD:
+ case InstructionConstants.OP_ILOAD_0:
+ case InstructionConstants.OP_ILOAD_1:
+ case InstructionConstants.OP_ILOAD_2:
+ case InstructionConstants.OP_ILOAD_3:
+ case InstructionConstants.OP_LLOAD_0:
+ case InstructionConstants.OP_LLOAD_1:
+ case InstructionConstants.OP_LLOAD_2:
+ case InstructionConstants.OP_LLOAD_3:
+ case InstructionConstants.OP_FLOAD_0:
+ case InstructionConstants.OP_FLOAD_1:
+ case InstructionConstants.OP_FLOAD_2:
+ case InstructionConstants.OP_FLOAD_3:
+ case InstructionConstants.OP_DLOAD_0:
+ case InstructionConstants.OP_DLOAD_1:
+ case InstructionConstants.OP_DLOAD_2:
+ case InstructionConstants.OP_DLOAD_3:
+ case InstructionConstants.OP_ALOAD_0:
+ case InstructionConstants.OP_ALOAD_1:
+ case InstructionConstants.OP_ALOAD_2:
+ case InstructionConstants.OP_ALOAD_3:
+
+ case InstructionConstants.OP_ISTORE:
+ case InstructionConstants.OP_LSTORE:
+ case InstructionConstants.OP_FSTORE:
+ case InstructionConstants.OP_DSTORE:
+ case InstructionConstants.OP_ASTORE:
+ case InstructionConstants.OP_ISTORE_0:
+ case InstructionConstants.OP_ISTORE_1:
+ case InstructionConstants.OP_ISTORE_2:
+ case InstructionConstants.OP_ISTORE_3:
+ case InstructionConstants.OP_LSTORE_0:
+ case InstructionConstants.OP_LSTORE_1:
+ case InstructionConstants.OP_LSTORE_2:
+ case InstructionConstants.OP_LSTORE_3:
+ case InstructionConstants.OP_FSTORE_0:
+ case InstructionConstants.OP_FSTORE_1:
+ case InstructionConstants.OP_FSTORE_2:
+ case InstructionConstants.OP_FSTORE_3:
+ case InstructionConstants.OP_DSTORE_0:
+ case InstructionConstants.OP_DSTORE_1:
+ case InstructionConstants.OP_DSTORE_2:
+ case InstructionConstants.OP_DSTORE_3:
+ case InstructionConstants.OP_ASTORE_0:
+ case InstructionConstants.OP_ASTORE_1:
+ case InstructionConstants.OP_ASTORE_2:
+ case InstructionConstants.OP_ASTORE_3:
+
+ case InstructionConstants.OP_IINC:
+
+ case InstructionConstants.OP_RET:
+ instruction = new VariableInstruction(wide);
+ break;
+
+ // Instructions with a branch offset operand.
+ case InstructionConstants.OP_IFEQ:
+ case InstructionConstants.OP_IFNE:
+ case InstructionConstants.OP_IFLT:
+ case InstructionConstants.OP_IFGE:
+ case InstructionConstants.OP_IFGT:
+ case InstructionConstants.OP_IFLE:
+ case InstructionConstants.OP_IFICMPEQ:
+ case InstructionConstants.OP_IFICMPNE:
+ case InstructionConstants.OP_IFICMPLT:
+ case InstructionConstants.OP_IFICMPGE:
+ case InstructionConstants.OP_IFICMPGT:
+ case InstructionConstants.OP_IFICMPLE:
+ case InstructionConstants.OP_IFACMPEQ:
+ case InstructionConstants.OP_IFACMPNE:
+ case InstructionConstants.OP_GOTO:
+ case InstructionConstants.OP_JSR:
+
+ case InstructionConstants.OP_IFNULL:
+ case InstructionConstants.OP_IFNONNULL:
+
+ case InstructionConstants.OP_GOTO_W:
+ case InstructionConstants.OP_JSR_W:
+ instruction = new BranchInstruction();
+ break;
+
+ // The tableswitch instruction.
+ case InstructionConstants.OP_TABLESWITCH:
+ instruction = new TableSwitchInstruction();
+ break;
+
+ // The lookupswitch instruction.
+ case InstructionConstants.OP_LOOKUPSWITCH:
+ instruction = new LookUpSwitchInstruction();
+ break;
+
+ default:
+ throw new IllegalArgumentException("Unknown instruction opcode ["+opcode+"] at offset "+offset);
+ }
+
+ instruction.opcode = opcode;
+
+ instruction.readInfo(code, index);
+
+ return instruction;
+ }
+}
diff --git a/src/proguard/classfile/instruction/InstructionUtil.java b/src/proguard/classfile/instruction/InstructionUtil.java
new file mode 100644
index 000000000..c6ae99bfa
--- /dev/null
+++ b/src/proguard/classfile/instruction/InstructionUtil.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.ClassConstants;
+
+/**
+ * Utility methods for converting between representations of names and
+ * descriptions.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionUtil
+{
+ /**
+ * Returns the internal type corresponding to the given 'newarray' type.
+ * @param arrayType InstructionConstants.ARRAY_T_BOOLEAN
,
+ * InstructionConstants.ARRAY_T_BYTE
,
+ * InstructionConstants.ARRAY_T_CHAR
,
+ * InstructionConstants.ARRAY_T_SHORT
,
+ * InstructionConstants.ARRAY_T_INT
,
+ * InstructionConstants.ARRAY_T_LONG
,
+ * InstructionConstants.ARRAY_T_FLOAT
, or
+ * InstructionConstants.ARRAY_T_DOUBLE
.
+ * @return ClassConstants.INTERNAL_TYPE_BOOLEAN
,
+ * ClassConstants.INTERNAL_TYPE_BYTE
,
+ * ClassConstants.INTERNAL_TYPE_CHAR
,
+ * ClassConstants.INTERNAL_TYPE_SHORT
,
+ * ClassConstants.INTERNAL_TYPE_INT
,
+ * ClassConstants.INTERNAL_TYPE_LONG
,
+ * ClassConstants.INTERNAL_TYPE_FLOAT
, or
+ * ClassConstants.INTERNAL_TYPE_DOUBLE
.
+ */
+ public static char internalTypeFromArrayType(byte arrayType)
+ {
+ switch (arrayType)
+ {
+ case InstructionConstants.ARRAY_T_BOOLEAN: return ClassConstants.INTERNAL_TYPE_BOOLEAN;
+ case InstructionConstants.ARRAY_T_CHAR: return ClassConstants.INTERNAL_TYPE_CHAR;
+ case InstructionConstants.ARRAY_T_FLOAT: return ClassConstants.INTERNAL_TYPE_FLOAT;
+ case InstructionConstants.ARRAY_T_DOUBLE: return ClassConstants.INTERNAL_TYPE_DOUBLE;
+ case InstructionConstants.ARRAY_T_BYTE: return ClassConstants.INTERNAL_TYPE_BYTE;
+ case InstructionConstants.ARRAY_T_SHORT: return ClassConstants.INTERNAL_TYPE_SHORT;
+ case InstructionConstants.ARRAY_T_INT: return ClassConstants.INTERNAL_TYPE_INT;
+ case InstructionConstants.ARRAY_T_LONG: return ClassConstants.INTERNAL_TYPE_LONG;
+ default: throw new IllegalArgumentException("Unknown array type ["+arrayType+"]");
+ }
+ }
+}
diff --git a/src/proguard/classfile/instruction/LookUpSwitchInstruction.java b/src/proguard/classfile/instruction/LookUpSwitchInstruction.java
new file mode 100644
index 000000000..807c0cceb
--- /dev/null
+++ b/src/proguard/classfile/instruction/LookUpSwitchInstruction.java
@@ -0,0 +1,135 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+/**
+ * This Instruction represents a simple instruction without variable arguments
+ * or constant pool references.
+ *
+ * @author Eric Lafortune
+ */
+public class LookUpSwitchInstruction extends SwitchInstruction
+{
+ public int[] cases;
+
+
+ /**
+ * Creates an uninitialized LookUpSwitchInstruction.
+ */
+ public LookUpSwitchInstruction() {}
+
+
+ /**
+ * Creates a new LookUpSwitchInstruction with the given arguments.
+ */
+ public LookUpSwitchInstruction(byte opcode,
+ int defaultOffset,
+ int[] cases,
+ int[] jumpOffsets)
+ {
+ this.opcode = opcode;
+ this.defaultOffset = defaultOffset;
+ this.cases = cases;
+ this.jumpOffsets = jumpOffsets;
+ }
+
+
+ /**
+ * Copies the given instruction into this instruction.
+ * @param lookUpSwitchInstruction the instruction to be copied.
+ * @return this instruction.
+ */
+ public LookUpSwitchInstruction copy(LookUpSwitchInstruction lookUpSwitchInstruction)
+ {
+ this.opcode = lookUpSwitchInstruction.opcode;
+ this.defaultOffset = lookUpSwitchInstruction.defaultOffset;
+ this.cases = lookUpSwitchInstruction.cases;
+ this.jumpOffsets = lookUpSwitchInstruction.jumpOffsets;
+
+ return this;
+ }
+
+
+ // Implementations for Instruction.
+
+ public Instruction shrink()
+ {
+ // There aren't any ways to shrink this instruction.
+ return this;
+ }
+
+ protected void readInfo(byte[] code, int offset)
+ {
+ // Skip up to three padding bytes.
+ offset += -offset & 3;
+
+ // Read the two 32-bit arguments.
+ defaultOffset = readInt(code, offset); offset += 4;
+ int jumpOffsetCount = readInt(code, offset); offset += 4;
+
+ // Read the matches-offset pairs.
+ cases = new int[jumpOffsetCount];
+ jumpOffsets = new int[jumpOffsetCount];
+
+ for (int index = 0; index < jumpOffsetCount; index++)
+ {
+ cases[index] = readInt(code, offset); offset += 4;
+ jumpOffsets[index] = readInt(code, offset); offset += 4;
+ }
+ }
+
+
+ protected void writeInfo(byte[] code, int offset)
+ {
+ // Write up to three padding bytes.
+ while ((offset & 3) != 0)
+ {
+ writeByte(code, offset++, 0);
+ }
+
+ // Write the two 32-bit arguments.
+ writeInt(code, offset, defaultOffset); offset += 4;
+ writeInt(code, offset, cases.length); offset += 4;
+
+ // Write the matches-offset pairs.
+ for (int index = 0; index < cases.length; index++)
+ {
+ writeInt(code, offset, cases[index]); offset += 4;
+ writeInt(code, offset, jumpOffsets[index]); offset += 4;
+ }
+ }
+
+
+ public int length(int offset)
+ {
+ return 1 + (-(offset+1) & 3) + 8 + cases.length * 8;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor)
+ {
+ instructionVisitor.visitLookUpSwitchInstruction(clazz, method, codeAttribute, offset, this);
+ }
+}
diff --git a/src/proguard/classfile/instruction/SimpleInstruction.java b/src/proguard/classfile/instruction/SimpleInstruction.java
new file mode 100644
index 000000000..c9a29577b
--- /dev/null
+++ b/src/proguard/classfile/instruction/SimpleInstruction.java
@@ -0,0 +1,255 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+/**
+ * This Instruction represents a simple instruction without variable arguments
+ * or constant pool references.
+ *
+ * @author Eric Lafortune
+ */
+public class SimpleInstruction extends Instruction
+{
+ public int constant;
+
+
+ /**
+ * Creates an uninitialized SimpleInstruction.
+ */
+ public SimpleInstruction() {}
+
+
+ /**
+ * Creates a new SimpleInstruction with the given opcode.
+ */
+ public SimpleInstruction(byte opcode)
+ {
+ this(opcode, embeddedConstant(opcode));
+ }
+
+
+ /**
+ * Creates a new SimpleInstruction with the given opcode and constant.
+ */
+ public SimpleInstruction(byte opcode, int constant)
+ {
+ this.opcode = opcode;
+ this.constant = constant;
+ }
+
+
+ /**
+ * Copies the given instruction into this instruction.
+ * @param simpleInstruction the instruction to be copied.
+ * @return this instruction.
+ */
+ public SimpleInstruction copy(SimpleInstruction simpleInstruction)
+ {
+ this.opcode = simpleInstruction.opcode;
+ this.constant = simpleInstruction.constant;
+
+ return this;
+ }
+
+
+ /**
+ * Return the embedded constant of the given opcode, or 0 if the opcode
+ * doesn't have one.
+ */
+ private static int embeddedConstant(byte opcode)
+ {
+ switch (opcode)
+ {
+ case InstructionConstants.OP_ICONST_M1: return -1;
+
+ case InstructionConstants.OP_ICONST_1:
+ case InstructionConstants.OP_LCONST_1:
+ case InstructionConstants.OP_FCONST_1:
+ case InstructionConstants.OP_DCONST_1: return 1;
+
+ case InstructionConstants.OP_ICONST_2:
+ case InstructionConstants.OP_FCONST_2: return 2;
+
+ case InstructionConstants.OP_ICONST_3: return 3;
+
+ case InstructionConstants.OP_ICONST_4: return 4;
+
+ case InstructionConstants.OP_ICONST_5: return 5;
+
+ default: return 0;
+ }
+ }
+
+
+ // Implementations for Instruction.
+
+ public byte canonicalOpcode()
+ {
+ // Replace any _1, _2, _3,... extension by _0.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_ICONST_M1:
+ case InstructionConstants.OP_ICONST_0:
+ case InstructionConstants.OP_ICONST_1:
+ case InstructionConstants.OP_ICONST_2:
+ case InstructionConstants.OP_ICONST_3:
+ case InstructionConstants.OP_ICONST_4:
+ case InstructionConstants.OP_ICONST_5:
+ case InstructionConstants.OP_BIPUSH:
+ case InstructionConstants.OP_SIPUSH: return InstructionConstants.OP_ICONST_0;
+
+ case InstructionConstants.OP_LCONST_0:
+ case InstructionConstants.OP_LCONST_1: return InstructionConstants.OP_LCONST_0;
+
+ case InstructionConstants.OP_FCONST_0:
+ case InstructionConstants.OP_FCONST_1:
+ case InstructionConstants.OP_FCONST_2: return InstructionConstants.OP_FCONST_0;
+
+ case InstructionConstants.OP_DCONST_0:
+ case InstructionConstants.OP_DCONST_1: return InstructionConstants.OP_DCONST_0;
+
+ default: return opcode;
+ }
+ }
+
+ public Instruction shrink()
+ {
+ // Reconstruct the opcode of the shortest instruction, if there are
+ // any alternatives.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_ICONST_M1:
+ case InstructionConstants.OP_ICONST_0:
+ case InstructionConstants.OP_ICONST_1:
+ case InstructionConstants.OP_ICONST_2:
+ case InstructionConstants.OP_ICONST_3:
+ case InstructionConstants.OP_ICONST_4:
+ case InstructionConstants.OP_ICONST_5:
+ case InstructionConstants.OP_BIPUSH:
+ case InstructionConstants.OP_SIPUSH:
+ switch (requiredConstantSize())
+ {
+ case 0:
+ opcode = (byte)(InstructionConstants.OP_ICONST_0 + constant);
+ break;
+ case 1:
+ opcode = InstructionConstants.OP_BIPUSH;
+ break;
+ case 2:
+ opcode = InstructionConstants.OP_SIPUSH;
+ break;
+ }
+ break;
+
+ case InstructionConstants.OP_LCONST_0:
+ case InstructionConstants.OP_LCONST_1:
+ opcode = (byte)(InstructionConstants.OP_LCONST_0 + constant);
+ break;
+
+ case InstructionConstants.OP_FCONST_0:
+ case InstructionConstants.OP_FCONST_1:
+ case InstructionConstants.OP_FCONST_2:
+ opcode = (byte)(InstructionConstants.OP_FCONST_0 + constant);
+ break;
+
+ case InstructionConstants.OP_DCONST_0:
+ case InstructionConstants.OP_DCONST_1:
+ opcode = (byte)(InstructionConstants.OP_DCONST_0 + constant);
+ break;
+ }
+
+ return this;
+ }
+
+ protected void readInfo(byte[] code, int offset)
+ {
+ int constantSize = constantSize();
+
+ // Also initialize embedded constants that are different from 0.
+ constant = constantSize == 0 ?
+ embeddedConstant(opcode) :
+ readSignedValue(code, offset, constantSize);
+ }
+
+
+ protected void writeInfo(byte[] code, int offset)
+ {
+ int constantSize = constantSize();
+
+ if (requiredConstantSize() > constantSize)
+ {
+ throw new IllegalArgumentException("Instruction has invalid constant size ("+this.toString(offset)+")");
+ }
+
+ writeSignedValue(code, offset, constant, constantSize);
+ }
+
+
+ public int length(int offset)
+ {
+ return 1 + constantSize();
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor)
+ {
+ instructionVisitor.visitSimpleInstruction(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return getName() +
+ (constantSize() > 0 ? " "+constant : "");
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the constant size for this instruction.
+ */
+ private int constantSize()
+ {
+ return opcode == InstructionConstants.OP_BIPUSH ||
+ opcode == InstructionConstants.OP_NEWARRAY ? 1 :
+ opcode == InstructionConstants.OP_SIPUSH ? 2 :
+ 0;
+ }
+
+
+ /**
+ * Computes the required constant size for this instruction.
+ */
+ private int requiredConstantSize()
+ {
+ return constant >= -1 && constant <= 5 ? 0 :
+ (byte)constant == constant ? 1 :
+ (short)constant == constant ? 2 :
+ 4;
+ }
+}
diff --git a/src/proguard/classfile/instruction/SwitchInstruction.java b/src/proguard/classfile/instruction/SwitchInstruction.java
new file mode 100644
index 000000000..3706ba025
--- /dev/null
+++ b/src/proguard/classfile/instruction/SwitchInstruction.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+/**
+ * This Instruction represents a simple instruction without variable arguments
+ * or constant pool references.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class SwitchInstruction extends Instruction
+{
+ public int defaultOffset;
+ public int[] jumpOffsets;
+
+
+ /**
+ * Creates an uninitialized SwitchInstruction.
+ */
+ public SwitchInstruction() {}
+
+
+ /**
+ * Creates a new SwitchInstruction with the given arguments.
+ */
+ public SwitchInstruction(byte opcode,
+ int defaultOffset,
+ int[] jumpOffsets)
+ {
+ this.opcode = opcode;
+ this.defaultOffset = defaultOffset;
+ this.jumpOffsets = jumpOffsets;
+ }
+
+
+ /**
+ * Copies the given instruction into this instruction.
+ * @param switchInstruction the instruction to be copied.
+ * @return this instruction.
+ */
+ public SwitchInstruction copy(SwitchInstruction switchInstruction)
+ {
+ this.opcode = switchInstruction.opcode;
+ this.defaultOffset = switchInstruction.defaultOffset;
+ this.jumpOffsets = switchInstruction.jumpOffsets;
+
+ return this;
+ }
+
+
+ // Implementations for Instruction.
+
+ public String toString(int offset)
+ {
+ return "["+offset+"] "+toString()+" (target="+(offset+defaultOffset)+")";
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return getName()+" ("+jumpOffsets.length+" offsets, default="+defaultOffset+")";
+ }
+}
diff --git a/src/proguard/classfile/instruction/TableSwitchInstruction.java b/src/proguard/classfile/instruction/TableSwitchInstruction.java
new file mode 100644
index 000000000..45490e520
--- /dev/null
+++ b/src/proguard/classfile/instruction/TableSwitchInstruction.java
@@ -0,0 +1,139 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+/**
+ * This Instruction represents a simple instruction without variable arguments
+ * or constant pool references.
+ *
+ * @author Eric Lafortune
+ */
+public class TableSwitchInstruction extends SwitchInstruction
+{
+ public int lowCase;
+ public int highCase;
+
+
+ /**
+ * Creates an uninitialized TableSwitchInstruction.
+ */
+ public TableSwitchInstruction() {}
+
+
+ /**
+ * Creates a new TableSwitchInstruction with the given arguments.
+ */
+ public TableSwitchInstruction(byte opcode,
+ int defaultOffset,
+ int lowCase,
+ int highCase,
+ int[] jumpOffsets)
+ {
+ this.opcode = opcode;
+ this.defaultOffset = defaultOffset;
+ this.lowCase = lowCase;
+ this.highCase = highCase;
+ this.jumpOffsets = jumpOffsets;
+ }
+
+
+ /**
+ * Copies the given instruction into this instruction.
+ * @param tableSwitchInstruction the instruction to be copied.
+ * @return this instruction.
+ */
+ public TableSwitchInstruction copy(TableSwitchInstruction tableSwitchInstruction)
+ {
+ this.opcode = tableSwitchInstruction.opcode;
+ this.defaultOffset = tableSwitchInstruction.defaultOffset;
+ this.lowCase = tableSwitchInstruction.lowCase;
+ this.highCase = tableSwitchInstruction.highCase;
+ this.jumpOffsets = tableSwitchInstruction.jumpOffsets;
+
+ return this;
+ }
+
+
+ // Implementations for Instruction.
+
+ public Instruction shrink()
+ {
+ // There aren't any ways to shrink this instruction.
+ return this;
+ }
+
+ protected void readInfo(byte[] code, int offset)
+ {
+ // Skip up to three padding bytes.
+ offset += -offset & 3;
+
+ // Read the three 32-bit arguments.
+ defaultOffset = readInt(code, offset); offset += 4;
+ lowCase = readInt(code, offset); offset += 4;
+ highCase = readInt(code, offset); offset += 4;
+
+ // Read the jump offsets.
+ jumpOffsets = new int[highCase - lowCase + 1];
+
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ jumpOffsets[index] = readInt(code, offset); offset += 4;
+ }
+ }
+
+
+ protected void writeInfo(byte[] code, int offset)
+ {
+ // Write up to three padding bytes.
+ while ((offset & 3) != 0)
+ {
+ writeByte(code, offset++, 0);
+ }
+
+ // Write the three 32-bit arguments.
+ writeInt(code, offset, defaultOffset); offset += 4;
+ writeInt(code, offset, lowCase); offset += 4;
+ writeInt(code, offset, highCase); offset += 4;
+
+ // Write the jump offsets.
+ int length = highCase - lowCase + 1;
+ for (int index = 0; index < length; index++)
+ {
+ writeInt(code, offset, jumpOffsets[index]); offset += 4;
+ }
+ }
+
+
+ public int length(int offset)
+ {
+ return 1 + (-(offset+1) & 3) + 12 + (highCase - lowCase + 1) * 4;
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor)
+ {
+ instructionVisitor.visitTableSwitchInstruction(clazz, method, codeAttribute, offset, this);
+ }
+}
diff --git a/src/proguard/classfile/instruction/VariableInstruction.java b/src/proguard/classfile/instruction/VariableInstruction.java
new file mode 100644
index 000000000..6390e0ad3
--- /dev/null
+++ b/src/proguard/classfile/instruction/VariableInstruction.java
@@ -0,0 +1,372 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+/**
+ * This Instruction represents an instruction that refers to a variable on the
+ * local variable stack.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableInstruction extends Instruction
+{
+ public boolean wide;
+ public int variableIndex;
+ public int constant;
+
+
+ /**
+ * Creates an uninitialized VariableInstruction.
+ */
+ public VariableInstruction() {}
+
+
+ public VariableInstruction(boolean wide)
+ {
+ this.wide = wide;
+ }
+
+
+ public VariableInstruction(byte opcode)
+ {
+ this(opcode, embeddedVariable(opcode), 0);
+ }
+
+
+ public VariableInstruction(byte opcode,
+ int variableIndex)
+ {
+ this(opcode, variableIndex, 0);
+ }
+
+
+ public VariableInstruction(byte opcode,
+ int variableIndex,
+ int constant)
+ {
+ this.opcode = opcode;
+ this.variableIndex = variableIndex;
+ this.constant = constant;
+ this.wide = requiredVariableIndexSize() > 1 ||
+ requiredConstantSize() > 1;
+ }
+
+
+ /**
+ * Copies the given instruction into this instruction.
+ * @param variableInstruction the instruction to be copied.
+ * @return this instruction.
+ */
+ public VariableInstruction copy(VariableInstruction variableInstruction)
+ {
+ this.opcode = variableInstruction.opcode;
+ this.variableIndex = variableInstruction.variableIndex;
+ this.constant = variableInstruction.constant;
+ this.wide = variableInstruction.wide;
+
+ return this;
+ }
+
+
+ /**
+ * Return the embedded variable of the given opcode, or 0 if the opcode
+ * doesn't have one.
+ */
+ private static int embeddedVariable(byte opcode)
+ {
+ switch (opcode)
+ {
+ case InstructionConstants.OP_ILOAD_1:
+ case InstructionConstants.OP_LLOAD_1:
+ case InstructionConstants.OP_FLOAD_1:
+ case InstructionConstants.OP_DLOAD_1:
+ case InstructionConstants.OP_ALOAD_1:
+ case InstructionConstants.OP_ISTORE_1:
+ case InstructionConstants.OP_LSTORE_1:
+ case InstructionConstants.OP_FSTORE_1:
+ case InstructionConstants.OP_DSTORE_1:
+ case InstructionConstants.OP_ASTORE_1: return 1;
+
+ case InstructionConstants.OP_ILOAD_2:
+ case InstructionConstants.OP_LLOAD_2:
+ case InstructionConstants.OP_FLOAD_2:
+ case InstructionConstants.OP_DLOAD_2:
+ case InstructionConstants.OP_ALOAD_2:
+ case InstructionConstants.OP_ISTORE_2:
+ case InstructionConstants.OP_LSTORE_2:
+ case InstructionConstants.OP_FSTORE_2:
+ case InstructionConstants.OP_DSTORE_2:
+ case InstructionConstants.OP_ASTORE_2: return 2;
+
+ case InstructionConstants.OP_ILOAD_3:
+ case InstructionConstants.OP_LLOAD_3:
+ case InstructionConstants.OP_FLOAD_3:
+ case InstructionConstants.OP_DLOAD_3:
+ case InstructionConstants.OP_ALOAD_3:
+ case InstructionConstants.OP_ISTORE_3:
+ case InstructionConstants.OP_LSTORE_3:
+ case InstructionConstants.OP_FSTORE_3:
+ case InstructionConstants.OP_DSTORE_3:
+ case InstructionConstants.OP_ASTORE_3: return 3;
+
+ default: return 0;
+ }
+ }
+
+
+ /**
+ * Returns whether this instruction stores the value of a variable.
+ * The value is false for the ret instruction, but true for the iinc
+ * instruction.
+ */
+ public boolean isStore()
+ {
+ // A store instruction can be recognized as follows. Note that this
+ // excludes the ret instruction, which has a negative opcode.
+ return opcode >= InstructionConstants.OP_ISTORE ||
+ opcode == InstructionConstants.OP_IINC;
+ }
+
+
+ /**
+ * Returns whether this instruction loads the value of a variable.
+ * The value is true for the ret instruction and for the iinc
+ * instruction.
+ */
+ public boolean isLoad()
+ {
+ // A load instruction can be recognized as follows. Note that this
+ // includes the ret instruction, which has a negative opcode.
+ return opcode < InstructionConstants.OP_ISTORE;
+ }
+
+
+ // Implementations for Instruction.
+
+ public byte canonicalOpcode()
+ {
+ // Remove the _0, _1, _2, _3 extension, if any.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_ILOAD_0:
+ case InstructionConstants.OP_ILOAD_1:
+ case InstructionConstants.OP_ILOAD_2:
+ case InstructionConstants.OP_ILOAD_3: return InstructionConstants.OP_ILOAD;
+ case InstructionConstants.OP_LLOAD_0:
+ case InstructionConstants.OP_LLOAD_1:
+ case InstructionConstants.OP_LLOAD_2:
+ case InstructionConstants.OP_LLOAD_3: return InstructionConstants.OP_LLOAD;
+ case InstructionConstants.OP_FLOAD_0:
+ case InstructionConstants.OP_FLOAD_1:
+ case InstructionConstants.OP_FLOAD_2:
+ case InstructionConstants.OP_FLOAD_3: return InstructionConstants.OP_FLOAD;
+ case InstructionConstants.OP_DLOAD_0:
+ case InstructionConstants.OP_DLOAD_1:
+ case InstructionConstants.OP_DLOAD_2:
+ case InstructionConstants.OP_DLOAD_3: return InstructionConstants.OP_DLOAD;
+ case InstructionConstants.OP_ALOAD_0:
+ case InstructionConstants.OP_ALOAD_1:
+ case InstructionConstants.OP_ALOAD_2:
+ case InstructionConstants.OP_ALOAD_3: return InstructionConstants.OP_ALOAD;
+
+ case InstructionConstants.OP_ISTORE_0:
+ case InstructionConstants.OP_ISTORE_1:
+ case InstructionConstants.OP_ISTORE_2:
+ case InstructionConstants.OP_ISTORE_3: return InstructionConstants.OP_ISTORE;
+ case InstructionConstants.OP_LSTORE_0:
+ case InstructionConstants.OP_LSTORE_1:
+ case InstructionConstants.OP_LSTORE_2:
+ case InstructionConstants.OP_LSTORE_3: return InstructionConstants.OP_LSTORE;
+ case InstructionConstants.OP_FSTORE_0:
+ case InstructionConstants.OP_FSTORE_1:
+ case InstructionConstants.OP_FSTORE_2:
+ case InstructionConstants.OP_FSTORE_3: return InstructionConstants.OP_FSTORE;
+ case InstructionConstants.OP_DSTORE_0:
+ case InstructionConstants.OP_DSTORE_1:
+ case InstructionConstants.OP_DSTORE_2:
+ case InstructionConstants.OP_DSTORE_3: return InstructionConstants.OP_DSTORE;
+ case InstructionConstants.OP_ASTORE_0:
+ case InstructionConstants.OP_ASTORE_1:
+ case InstructionConstants.OP_ASTORE_2:
+ case InstructionConstants.OP_ASTORE_3: return InstructionConstants.OP_ASTORE;
+
+ default: return opcode;
+ }
+ }
+
+ public Instruction shrink()
+ {
+ opcode = canonicalOpcode();
+
+ // Is this instruction pointing to a variable with index from 0 to 3?
+ if (variableIndex <= 3)
+ {
+ switch (opcode)
+ {
+ case InstructionConstants.OP_ILOAD: opcode = (byte)(InstructionConstants.OP_ILOAD_0 + variableIndex); break;
+ case InstructionConstants.OP_LLOAD: opcode = (byte)(InstructionConstants.OP_LLOAD_0 + variableIndex); break;
+ case InstructionConstants.OP_FLOAD: opcode = (byte)(InstructionConstants.OP_FLOAD_0 + variableIndex); break;
+ case InstructionConstants.OP_DLOAD: opcode = (byte)(InstructionConstants.OP_DLOAD_0 + variableIndex); break;
+ case InstructionConstants.OP_ALOAD: opcode = (byte)(InstructionConstants.OP_ALOAD_0 + variableIndex); break;
+
+ case InstructionConstants.OP_ISTORE: opcode = (byte)(InstructionConstants.OP_ISTORE_0 + variableIndex); break;
+ case InstructionConstants.OP_LSTORE: opcode = (byte)(InstructionConstants.OP_LSTORE_0 + variableIndex); break;
+ case InstructionConstants.OP_FSTORE: opcode = (byte)(InstructionConstants.OP_FSTORE_0 + variableIndex); break;
+ case InstructionConstants.OP_DSTORE: opcode = (byte)(InstructionConstants.OP_DSTORE_0 + variableIndex); break;
+ case InstructionConstants.OP_ASTORE: opcode = (byte)(InstructionConstants.OP_ASTORE_0 + variableIndex); break;
+ }
+ }
+
+ // Only make the instruction wide if necessary.
+ wide = requiredVariableIndexSize() > 1 ||
+ requiredConstantSize() > 1;
+
+ return this;
+ }
+
+
+ protected boolean isWide()
+ {
+ return wide;
+ }
+
+
+ protected void readInfo(byte[] code, int offset)
+ {
+ int variableIndexSize = variableIndexSize();
+ int constantSize = constantSize();
+
+ // Also initialize embedded variable indexes.
+ if (variableIndexSize == 0)
+ {
+ // An embedded variable index can be decoded as follows.
+ variableIndex = opcode < InstructionConstants.OP_ISTORE_0 ?
+ (opcode - InstructionConstants.OP_ILOAD_0 ) & 3 :
+ (opcode - InstructionConstants.OP_ISTORE_0) & 3;
+ }
+ else
+ {
+ variableIndex = readValue(code, offset, variableIndexSize); offset += variableIndexSize;
+ }
+
+ constant = readSignedValue(code, offset, constantSize);
+ }
+
+
+ protected void writeInfo(byte[] code, int offset)
+ {
+ int variableIndexSize = variableIndexSize();
+ int constantSize = constantSize();
+
+ if (requiredVariableIndexSize() > variableIndexSize)
+ {
+ throw new IllegalArgumentException("Instruction has invalid variable index size ("+this.toString(offset)+")");
+ }
+
+ if (requiredConstantSize() > constantSize)
+ {
+ throw new IllegalArgumentException("Instruction has invalid constant size ("+this.toString(offset)+")");
+ }
+
+ writeValue(code, offset, variableIndex, variableIndexSize); offset += variableIndexSize;
+ writeSignedValue(code, offset, constant, constantSize);
+ }
+
+
+ public int length(int offset)
+ {
+ return (wide ? 2 : 1) + variableIndexSize() + constantSize();
+ }
+
+
+ public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor)
+ {
+ instructionVisitor.visitVariableInstruction(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return getName() +
+ (wide ? "_w" : "") +
+ " v"+variableIndex +
+ (constantSize() > 0 ? ", "+constant : "");
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the variable index size for this instruction.
+ */
+ private int variableIndexSize()
+ {
+ return (opcode >= InstructionConstants.OP_ILOAD_0 &&
+ opcode <= InstructionConstants.OP_ALOAD_3) ||
+ (opcode >= InstructionConstants.OP_ISTORE_0 &&
+ opcode <= InstructionConstants.OP_ASTORE_3) ? 0 :
+ wide ? 2 :
+ 1;
+ }
+
+
+ /**
+ * Computes the required variable index size for this instruction's variable
+ * index.
+ */
+ private int requiredVariableIndexSize()
+ {
+ return (variableIndex & 0x3) == variableIndex ? 0 :
+ (variableIndex & 0xff) == variableIndex ? 1 :
+ (variableIndex & 0xffff) == variableIndex ? 2 :
+ 4;
+
+ }
+
+
+ /**
+ * Returns the constant size for this instruction.
+ */
+ private int constantSize()
+ {
+ return opcode != InstructionConstants.OP_IINC ? 0 :
+ wide ? 2 :
+ 1;
+ }
+
+
+ /**
+ * Computes the required constant size for this instruction's constant.
+ */
+ private int requiredConstantSize()
+ {
+ return opcode != InstructionConstants.OP_IINC ? 0 :
+ (byte)constant == constant ? 1 :
+ (short)constant == constant ? 2 :
+ 4;
+ }
+}
diff --git a/src/proguard/classfile/instruction/package.html b/src/proguard/classfile/instruction/package.html
new file mode 100644
index 000000000..48c234e3c
--- /dev/null
+++ b/src/proguard/classfile/instruction/package.html
@@ -0,0 +1,9 @@
+
+This package contains classes to represent Java bytecode instructions.
++Not every instruction currently has its own class. Only groups of instructions +that refer to the constant pool get their own representations. +
+While the package is sufficient for the current needs of the ProGuard
+application, it may very well be reorganised and extended in the future.
+
diff --git a/src/proguard/classfile/instruction/visitor/AllInstructionVisitor.java b/src/proguard/classfile/instruction/visitor/AllInstructionVisitor.java
new file mode 100644
index 000000000..4d739c25e
--- /dev/null
+++ b/src/proguard/classfile/instruction/visitor/AllInstructionVisitor.java
@@ -0,0 +1,56 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor lets a given InstructionVisitor visit all Instruction
+ * objects of the CodeAttribute objects it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllInstructionVisitor
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final InstructionVisitor instructionVisitor;
+
+
+ public AllInstructionVisitor(InstructionVisitor instructionVisitor)
+ {
+ this.instructionVisitor = instructionVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttribute.instructionsAccept(clazz, method, instructionVisitor);
+ }
+}
diff --git a/src/proguard/classfile/instruction/visitor/InstructionConstantVisitor.java b/src/proguard/classfile/instruction/visitor/InstructionConstantVisitor.java
new file mode 100644
index 000000000..6b24e98c7
--- /dev/null
+++ b/src/proguard/classfile/instruction/visitor/InstructionConstantVisitor.java
@@ -0,0 +1,65 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor lets a given ConstantVisitor visit all constants
+ * of the instructions it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionConstantVisitor
+extends SimplifiedVisitor
+implements InstructionVisitor
+{
+ private final ConstantVisitor constantVisitor;
+
+
+ /**
+ * Creates a new InstructionConstantVisitor.
+ * @param constantVisitor the ConstantVisitor to which visits will be
+ * delegated.
+ */
+ public InstructionConstantVisitor(ConstantVisitor constantVisitor)
+ {
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex,
+ constantVisitor);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/instruction/visitor/InstructionCounter.java b/src/proguard/classfile/instruction/visitor/InstructionCounter.java
new file mode 100644
index 000000000..562349865
--- /dev/null
+++ b/src/proguard/classfile/instruction/visitor/InstructionCounter.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.Instruction;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This InstructionVisitor counts the number of instructions that has been visited.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionCounter
+extends SimplifiedVisitor
+implements InstructionVisitor
+{
+ private int count;
+
+
+ /**
+ * Returns the number of instructions that has been visited so far.
+ */
+ public int getCount()
+ {
+ return count;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ int offset,
+ Instruction instruction)
+ {
+ count++;
+ }
+}
diff --git a/src/proguard/classfile/instruction/visitor/InstructionVisitor.java b/src/proguard/classfile/instruction/visitor/InstructionVisitor.java
new file mode 100644
index 000000000..cffb15e18
--- /dev/null
+++ b/src/proguard/classfile/instruction/visitor/InstructionVisitor.java
@@ -0,0 +1,42 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.*;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * Instruction
objects.
+ *
+ * @author Eric Lafortune
+ */
+public interface InstructionVisitor
+{
+ public void visitSimpleInstruction( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction);
+ public void visitVariableInstruction( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction);
+ public void visitConstantInstruction( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction);
+ public void visitBranchInstruction( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction);
+ public void visitTableSwitchInstruction( Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction);
+ public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction);
+}
diff --git a/src/proguard/classfile/instruction/visitor/MultiInstructionVisitor.java b/src/proguard/classfile/instruction/visitor/MultiInstructionVisitor.java
new file mode 100644
index 000000000..444fd57c4
--- /dev/null
+++ b/src/proguard/classfile/instruction/visitor/MultiInstructionVisitor.java
@@ -0,0 +1,131 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.instruction.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.*;
+
+
+/**
+ * This InstructionVisitor delegates all visits to each InstructionVisitor
+ * in a given list.
+ *
+ * @author Eric Lafortune
+ */
+public class MultiInstructionVisitor implements InstructionVisitor
+{
+ private static final int ARRAY_SIZE_INCREMENT = 5;
+
+
+ private InstructionVisitor[] instructionVisitors;
+ private int instructionVisitorCount;
+
+
+ public MultiInstructionVisitor()
+ {
+ }
+
+
+ public MultiInstructionVisitor(InstructionVisitor[] instructionVisitors)
+ {
+ this.instructionVisitors = instructionVisitors;
+ this.instructionVisitorCount = instructionVisitors.length;
+ }
+
+
+ public void addInstructionVisitor(InstructionVisitor instructionVisitor)
+ {
+ ensureArraySize();
+
+ instructionVisitors[instructionVisitorCount++] = instructionVisitor;
+ }
+
+
+ private void ensureArraySize()
+ {
+ if (instructionVisitors == null)
+ {
+ instructionVisitors = new InstructionVisitor[ARRAY_SIZE_INCREMENT];
+ }
+ else if (instructionVisitors.length == instructionVisitorCount)
+ {
+ InstructionVisitor[] newInstructionVisitors =
+ new InstructionVisitor[instructionVisitorCount +
+ ARRAY_SIZE_INCREMENT];
+ System.arraycopy(instructionVisitors, 0,
+ newInstructionVisitors, 0,
+ instructionVisitorCount);
+ instructionVisitors = newInstructionVisitors;
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ for (int index = 0; index < instructionVisitorCount; index++)
+ {
+ instructionVisitors[index].visitSimpleInstruction(clazz, method, codeAttribute, offset, simpleInstruction);
+ }
+ }
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ for (int index = 0; index < instructionVisitorCount; index++)
+ {
+ instructionVisitors[index].visitVariableInstruction(clazz, method, codeAttribute, offset, variableInstruction);
+ }
+ }
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ for (int index = 0; index < instructionVisitorCount; index++)
+ {
+ instructionVisitors[index].visitConstantInstruction(clazz, method, codeAttribute, offset, constantInstruction);
+ }
+ }
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ for (int index = 0; index < instructionVisitorCount; index++)
+ {
+ instructionVisitors[index].visitBranchInstruction(clazz, method, codeAttribute, offset, branchInstruction);
+ }
+ }
+
+ public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction)
+ {
+ for (int index = 0; index < instructionVisitorCount; index++)
+ {
+ instructionVisitors[index].visitTableSwitchInstruction(clazz, method, codeAttribute, offset, tableSwitchInstruction);
+ }
+ }
+
+ public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction)
+ {
+ for (int index = 0; index < instructionVisitorCount; index++)
+ {
+ instructionVisitors[index].visitLookUpSwitchInstruction(clazz, method, codeAttribute, offset, lookUpSwitchInstruction);
+ }
+ }
+}
diff --git a/src/proguard/classfile/instruction/visitor/package.html b/src/proguard/classfile/instruction/visitor/package.html
new file mode 100644
index 000000000..a31a4082f
--- /dev/null
+++ b/src/proguard/classfile/instruction/visitor/package.html
@@ -0,0 +1,3 @@
+
+A class file is represented by the {@link proguard.classfile.ClassFile
+ClassFile}
interface. This interface currently has two alternative
+representations:
+
{@link ProgramClassFile ProgramClassFile}
:
+ a complete representation that can be read, modified, and written back.
+{@link LibraryClassFile LibraryClassFile}
:
+ an incomplete representation that can be only be read. It is however
+ more compact than ProgramClassFile
, and sufficient for
+ analyzing class files from library jars.
+PRIVATE
,
+ * PACKAGE_VISIBLE
, PROTECTED
, and PUBLIC
.
+ *
+ * @author Eric Lafortune
+ */
+public class AccessUtil
+{
+ public static final int PRIVATE = 0;
+ public static final int PACKAGE_VISIBLE = 1;
+ public static final int PROTECTED = 2;
+ public static final int PUBLIC = 3;
+
+
+ // The mask of access flags.
+ private static final int ACCESS_MASK =
+ ClassConstants.INTERNAL_ACC_PUBLIC |
+ ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_PROTECTED;
+
+
+ /**
+ * Returns the corresponding access level of the given access flags.
+ * @param accessFlags the internal access flags.
+ * @return the corresponding access level: PRIVATE
,
+ * PACKAGE_VISIBLE
, PROTECTED
, or
+ * PUBLIC
.
+ */
+ public static int accessLevel(int accessFlags)
+ {
+ switch (accessFlags & ACCESS_MASK)
+ {
+ case ClassConstants.INTERNAL_ACC_PRIVATE: return PRIVATE;
+ default: return PACKAGE_VISIBLE;
+ case ClassConstants.INTERNAL_ACC_PROTECTED: return PROTECTED;
+ case ClassConstants.INTERNAL_ACC_PUBLIC: return PUBLIC;
+ }
+ }
+
+
+ /**
+ * Returns the corresponding access flags of the given access level.
+ * @param accessLevel the access level: PRIVATE
,
+ * PACKAGE_VISIBLE
, PROTECTED
,
+ * or PUBLIC
.
+ * @return the corresponding internal access flags, the internal access
+ * flags as a logical bit mask of INTERNAL_ACC_PRIVATE
,
+ * INTERNAL_ACC_PROTECTED
, and
+ * INTERNAL_ACC_PUBLIC
.
+ */
+ public static int accessFlags(int accessLevel)
+ {
+ switch (accessLevel)
+ {
+ case PRIVATE: return ClassConstants.INTERNAL_ACC_PRIVATE;
+ default: return 0;
+ case PROTECTED: return ClassConstants.INTERNAL_ACC_PROTECTED;
+ case PUBLIC: return ClassConstants.INTERNAL_ACC_PUBLIC;
+ }
+ }
+
+
+ /**
+ * Replaces the access part of the given access flags.
+ * @param accessFlags the internal access flags.
+ * @param accessFlags the new internal access flags.
+ */
+ public static int replaceAccessFlags(int accessFlags, int newAccessFlags)
+ {
+ // A private class member should not be explicitly final.
+ if (newAccessFlags == ClassConstants.INTERNAL_ACC_PRIVATE)
+ {
+ accessFlags &= ~ClassConstants.INTERNAL_ACC_FINAL;
+ }
+
+ return (accessFlags & ~ACCESS_MASK) |
+ (newAccessFlags & ACCESS_MASK);
+ }
+}
diff --git a/src/proguard/classfile/util/ClassReferenceInitializer.java b/src/proguard/classfile/util/ClassReferenceInitializer.java
new file mode 100644
index 000000000..431d54afc
--- /dev/null
+++ b/src/proguard/classfile/util/ClassReferenceInitializer.java
@@ -0,0 +1,559 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.visitor.*;
+
+
+/**
+ * This ClassVisitor initializes the references of all classes that
+ * it visits.
+ * + * All class constant pool entries get direct references to the corresponding + * classes. These references make it more convenient to travel up and across + * the class hierarchy. + *
+ * All field and method reference constant pool entries get direct references + * to the corresponding classes, fields, and methods. + *
+ * All name and type constant pool entries get a list of direct references to + * the classes listed in the type. + *
+ * This visitor optionally prints warnings if some items can't be found. + *
+ * The class hierarchy must be initialized before using this visitor.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassReferenceInitializer
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ ConstantVisitor,
+ AttributeVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ private final ClassPool programClassPool;
+ private final ClassPool libraryClassPool;
+ private final WarningPrinter missingClassWarningPrinter;
+ private final WarningPrinter missingMemberWarningPrinter;
+ private final WarningPrinter dependencyWarningPrinter;
+
+ private final MemberFinder memberFinder = new MemberFinder();
+
+
+ /**
+ * Creates a new ClassReferenceInitializer that initializes the references
+ * of all visited class files, optionally printing warnings if some classes
+ * or class members can't be found or if they are in the program class pool.
+ */
+ public ClassReferenceInitializer(ClassPool programClassPool,
+ ClassPool libraryClassPool,
+ WarningPrinter missingClassWarningPrinter,
+ WarningPrinter missingMemberWarningPrinter,
+ WarningPrinter dependencyWarningPrinter)
+ {
+ this.programClassPool = programClassPool;
+ this.libraryClassPool = libraryClassPool;
+ this.missingClassWarningPrinter = missingClassWarningPrinter;
+ this.missingMemberWarningPrinter = missingMemberWarningPrinter;
+ this.dependencyWarningPrinter = dependencyWarningPrinter;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Initialize the constant pool entries.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Initialize all fields and methods.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ // Initialize the attributes.
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Initialize all fields and methods.
+ libraryClass.fieldsAccept(this);
+ libraryClass.methodsAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ programField.referencedClass =
+ findReferencedClass(programClass.getName(),
+ programField.getDescriptor(programClass));
+
+ // Initialize the attributes.
+ programField.attributesAccept(programClass, this);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ programMethod.referencedClasses =
+ findReferencedClasses(programClass.getName(),
+ programMethod.getDescriptor(programClass));
+
+ // Initialize the attributes.
+ programMethod.attributesAccept(programClass, this);
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ libraryField.referencedClass =
+ findReferencedClass(libraryClass.getName(),
+ libraryField.getDescriptor(libraryClass));
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ libraryMethod.referencedClasses =
+ findReferencedClasses(libraryClass.getName(),
+ libraryMethod.getDescriptor(libraryClass));
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ // Fill out the String class.
+ stringConstant.javaLangStringClass =
+ findClass(clazz.getName(), ClassConstants.INTERNAL_NAME_JAVA_LANG_STRING);
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ // Fill out the MethodHandle class.
+ methodHandleConstant.javaLangInvokeMethodHandleClass =
+ findClass(clazz.getName(), ClassConstants.INTERNAL_NAME_JAVA_LANG_INVOKE_METHOD_HANDLE);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ String className = refConstant.getClassName(clazz);
+
+ // Methods for array types should be found in the Object class.
+ if (ClassUtil.isInternalArrayType(className))
+ {
+ className = ClassConstants.INTERNAL_NAME_JAVA_LANG_OBJECT;
+ }
+
+ // See if we can find the referenced class.
+ // Unresolved references are assumed to refer to library classes
+ // that will not change anyway.
+ Clazz referencedClass = findClass(clazz.getName(), className);
+
+ if (referencedClass != null)
+ {
+ String name = refConstant.getName(clazz);
+ String type = refConstant.getType(clazz);
+
+ boolean isFieldRef = refConstant.getTag() == ClassConstants.CONSTANT_Fieldref;
+
+ // See if we can find the referenced class member somewhere in the
+ // hierarchy.
+ refConstant.referencedMember = memberFinder.findMember(clazz,
+ referencedClass,
+ name,
+ type,
+ isFieldRef);
+ refConstant.referencedClass = memberFinder.correspondingClass();
+
+ if (refConstant.referencedMember == null)
+ {
+ // We haven't found the class member anywhere in the hierarchy.
+ missingMemberWarningPrinter.print(clazz.getName(),
+ className,
+ "Warning: " +
+ ClassUtil.externalClassName(clazz.getName()) +
+ ": can't find referenced " +
+ (isFieldRef ?
+ "field '" + ClassUtil.externalFullFieldDescription(0, name, type) :
+ "method '" + ClassUtil.externalFullMethodDescription(className, 0, name, type)) +
+ "' in class " +
+ ClassUtil.externalClassName(className));
+ }
+ }
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ String className = clazz.getName();
+
+ // Fill out the referenced class.
+ classConstant.referencedClass =
+ findClass(className, ClassUtil.internalClassNameFromClassType(classConstant.getName(clazz)));
+
+ // Fill out the Class class.
+ classConstant.javaLangClassClass =
+ findClass(className, ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS);
+ }
+
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
+ {
+ // Fill out the MethodType class.
+ methodTypeConstant.javaLangInvokeMethodTypeClass =
+ findClass(clazz.getName(), ClassConstants.INTERNAL_NAME_JAVA_LANG_INVOKE_METHOD_TYPE);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ String className = clazz.getName();
+ String enclosingClassName = enclosingMethodAttribute.getClassName(clazz);
+
+ // See if we can find the referenced class.
+ enclosingMethodAttribute.referencedClass =
+ findClass(className, enclosingClassName);
+
+ if (enclosingMethodAttribute.referencedClass != null)
+ {
+ // Is there an enclosing method? Otherwise it's just initialization
+ // code outside of the constructors.
+ if (enclosingMethodAttribute.u2nameAndTypeIndex != 0)
+ {
+ String name = enclosingMethodAttribute.getName(clazz);
+ String type = enclosingMethodAttribute.getType(clazz);
+
+ // See if we can find the method in the referenced class.
+ enclosingMethodAttribute.referencedMethod =
+ enclosingMethodAttribute.referencedClass.findMethod(name, type);
+
+ if (enclosingMethodAttribute.referencedMethod == null)
+ {
+ // We couldn't find the enclosing method.
+ missingMemberWarningPrinter.print(className,
+ enclosingClassName,
+ "Warning: " +
+ ClassUtil.externalClassName(className) +
+ ": can't find enclosing method '" +
+ ClassUtil.externalFullMethodDescription(enclosingClassName, 0, name, type) +
+ "' in class " +
+ ClassUtil.externalClassName(enclosingClassName));
+ }
+ }
+ }
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Initialize the nested attributes.
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Initialize the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Initialize the local variable types.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ signatureAttribute.referencedClasses =
+ findReferencedClasses(clazz.getName(),
+ clazz.getString(signatureAttribute.u2signatureIndex));
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ // Initialize the annotations.
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ // Initialize the annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ // Initialize the annotation.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ localVariableInfo.referencedClass =
+ findReferencedClass(clazz.getName(),
+ clazz.getString(localVariableInfo.u2descriptorIndex));
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ localVariableTypeInfo.referencedClasses =
+ findReferencedClasses(clazz.getName(),
+ clazz.getString(localVariableTypeInfo.u2signatureIndex));
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ annotation.referencedClasses =
+ findReferencedClasses(clazz.getName(),
+ clazz.getString(annotation.u2typeIndex));
+
+ // Initialize the element values.
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ initializeElementValue(clazz, annotation, constantElementValue);
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ initializeElementValue(clazz, annotation, enumConstantElementValue);
+
+ enumConstantElementValue.referencedClasses =
+ findReferencedClasses(clazz.getName(),
+ clazz.getString(enumConstantElementValue.u2typeNameIndex));
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ initializeElementValue(clazz, annotation, classElementValue);
+
+ classElementValue.referencedClasses =
+ findReferencedClasses(clazz.getName(),
+ clazz.getString(classElementValue.u2classInfoIndex));
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ initializeElementValue(clazz, annotation, annotationElementValue);
+
+ // Initialize the annotation.
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ initializeElementValue(clazz, annotation, arrayElementValue);
+
+ // Initialize the element values.
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ }
+
+
+ /**
+ * Initializes the referenced method of an element value, if any.
+ */
+ private void initializeElementValue(Clazz clazz, Annotation annotation, ElementValue elementValue)
+ {
+ // See if we have a referenced class.
+ if (annotation != null &&
+ annotation.referencedClasses != null &&
+ elementValue.u2elementNameIndex != 0)
+ {
+ // See if we can find the method in the referenced class
+ // (ignoring the descriptor).
+ String name = clazz.getString(elementValue.u2elementNameIndex);
+
+ Clazz referencedClass = annotation.referencedClasses[0];
+ elementValue.referencedClass = referencedClass;
+ elementValue.referencedMethod = referencedClass.findMethod(name, null);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the single class referenced by the given descriptor, or
+ * null
if there isn't any useful reference.
+ */
+ private Clazz findReferencedClass(String referencingClassName,
+ String descriptor)
+ {
+ DescriptorClassEnumeration enumeration =
+ new DescriptorClassEnumeration(descriptor);
+
+ enumeration.nextFluff();
+
+ if (enumeration.hasMoreClassNames())
+ {
+ return findClass(referencingClassName, enumeration.nextClassName());
+ }
+
+ return null;
+ }
+
+
+ /**
+ * Returns an array of classes referenced by the given descriptor, or
+ * null
if there aren't any useful references.
+ */
+ private Clazz[] findReferencedClasses(String referencingClassName,
+ String descriptor)
+ {
+ DescriptorClassEnumeration enumeration =
+ new DescriptorClassEnumeration(descriptor);
+
+ int classCount = enumeration.classCount();
+ if (classCount > 0)
+ {
+ Clazz[] referencedClasses = new Clazz[classCount];
+
+ boolean foundReferencedClasses = false;
+
+ for (int index = 0; index < classCount; index++)
+ {
+ String fluff = enumeration.nextFluff();
+ String name = enumeration.nextClassName();
+
+ Clazz referencedClass = findClass(referencingClassName, name);
+
+ if (referencedClass != null)
+ {
+ referencedClasses[index] = referencedClass;
+ foundReferencedClasses = true;
+ }
+ }
+
+ if (foundReferencedClasses)
+ {
+ return referencedClasses;
+ }
+ }
+
+ return null;
+ }
+
+
+ /**
+ * Returns the class with the given name, either for the program class pool
+ * or from the library class pool, or null
if it can't be found.
+ */
+ private Clazz findClass(String referencingClassName, String name)
+ {
+ // Is it an array type?
+ if (ClassUtil.isInternalArrayType(name))
+ {
+ // Ignore any primitive array types.
+ if (!ClassUtil.isInternalClassType(name))
+ {
+ return null;
+ }
+
+ // Strip the array part.
+ name = ClassUtil.internalClassNameFromClassType(name);
+ }
+
+ // First look for the class in the program class pool.
+ Clazz clazz = programClassPool.getClass(name);
+
+ // Otherwise look for the class in the library class pool.
+ if (clazz == null)
+ {
+ clazz = libraryClassPool.getClass(name);
+
+ if (clazz == null &&
+ missingClassWarningPrinter != null)
+ {
+ // We didn't find the superclass or interface. Print a warning.
+ missingClassWarningPrinter.print(referencingClassName,
+ name,
+ "Warning: " +
+ ClassUtil.externalClassName(referencingClassName) +
+ ": can't find referenced class " +
+ ClassUtil.externalClassName(name));
+ }
+ }
+ else if (dependencyWarningPrinter != null)
+ {
+ // The superclass or interface was found in the program class pool.
+ // Print a warning.
+ dependencyWarningPrinter.print(referencingClassName,
+ name,
+ "Warning: library class " +
+ ClassUtil.externalClassName(referencingClassName) +
+ " depends on program class " +
+ ClassUtil.externalClassName(name));
+ }
+
+ return clazz;
+ }
+}
diff --git a/src/proguard/classfile/util/ClassSubHierarchyInitializer.java b/src/proguard/classfile/util/ClassSubHierarchyInitializer.java
new file mode 100644
index 000000000..993a55989
--- /dev/null
+++ b/src/proguard/classfile/util/ClassSubHierarchyInitializer.java
@@ -0,0 +1,77 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor adds all classes that it visits to the list of subclasses
+ * of their superclass. These subclass lists make it more convenient to travel
+ *
+ * @author Eric Lafortune
+ */
+public class ClassSubHierarchyInitializer
+implements ClassVisitor
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Add this class to the subclasses of its superclass.
+ addSubclass(programClass, programClass.getSuperClass());
+
+ // Add this class to the subclasses of its interfaces.
+ for (int index = 0; index < programClass.u2interfacesCount; index++)
+ {
+ addSubclass(programClass, programClass.getInterface(index));
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Add this class to the subclasses of its superclass,
+ addSubclass(libraryClass, libraryClass.superClass);
+
+ // Add this class to the subclasses of its interfaces.
+ Clazz[] interfaceClasses = libraryClass.interfaceClasses;
+ if (interfaceClasses != null)
+ {
+ for (int index = 0; index < interfaceClasses.length; index++)
+ {
+ // Add this class to the subclasses of the interface class.
+ addSubclass(libraryClass, interfaceClasses[index]);
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ private void addSubclass(Clazz subclass, Clazz clazz)
+ {
+ if (clazz != null)
+ {
+ clazz.addSubClass(subclass);
+ }
+ }
+}
diff --git a/src/proguard/classfile/util/ClassSuperHierarchyInitializer.java b/src/proguard/classfile/util/ClassSuperHierarchyInitializer.java
new file mode 100644
index 000000000..fb431b86a
--- /dev/null
+++ b/src/proguard/classfile/util/ClassSuperHierarchyInitializer.java
@@ -0,0 +1,163 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor initializes the superclass hierarchy of all classes that
+ * it visits.
+ *
+ * Visited library classes get direct references to their superclasses and + * interfaces, replacing the superclass names and interface names. The direct + * references are equivalent to the names, but they are more efficient to work + * with. + *
+ * This visitor optionally prints warnings if some superclasses can't be found
+ * or if they are in the program class pool.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassSuperHierarchyInitializer
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor
+{
+ private final ClassPool programClassPool;
+ private final ClassPool libraryClassPool;
+ private final WarningPrinter missingWarningPrinter;
+ private final WarningPrinter dependencyWarningPrinter;
+
+
+ /**
+ * Creates a new ClassSuperHierarchyInitializer that initializes the super
+ * hierarchy of all visited class files, optionally printing warnings if
+ * some classes can't be found or if they are in the program class pool.
+ */
+ public ClassSuperHierarchyInitializer(ClassPool programClassPool,
+ ClassPool libraryClassPool,
+ WarningPrinter missingWarningPrinter,
+ WarningPrinter dependencyWarningPrinter)
+ {
+ this.programClassPool = programClassPool;
+ this.libraryClassPool = libraryClassPool;
+ this.missingWarningPrinter = missingWarningPrinter;
+ this.dependencyWarningPrinter = dependencyWarningPrinter;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Link to the super class.
+ programClass.superClassConstantAccept(this);
+
+ // Link to the interfaces.
+ programClass.interfaceConstantsAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ String className = libraryClass.getName();
+
+ // Link to the super class.
+ String superClassName = libraryClass.superClassName;
+ if (superClassName != null)
+ {
+ // Keep a reference to the superclass.
+ libraryClass.superClass = findClass(className, superClassName);
+ }
+
+ // Link to the interfaces.
+ if (libraryClass.interfaceNames != null)
+ {
+ String[] interfaceNames = libraryClass.interfaceNames;
+ Clazz[] interfaceClasses = new Clazz[interfaceNames.length];
+
+ for (int index = 0; index < interfaceNames.length; index++)
+ {
+ // Keep a reference to the interface class.
+ interfaceClasses[index] =
+ findClass(className, interfaceNames[index]);
+ }
+
+ libraryClass.interfaceClasses = interfaceClasses;
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ classConstant.referencedClass =
+ findClass(clazz.getName(), classConstant.getName(clazz));
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the class with the given name, either for the program class pool
+ * or from the library class pool, or null
if it can't be found.
+ */
+ private Clazz findClass(String referencingClassName, String name)
+ {
+ // First look for the class in the program class pool.
+ Clazz clazz = programClassPool.getClass(name);
+
+ // Otherwise look for the class in the library class pool.
+ if (clazz == null)
+ {
+ clazz = libraryClassPool.getClass(name);
+
+ if (clazz == null &&
+ missingWarningPrinter != null)
+ {
+ // We didn't find the superclass or interface. Print a warning.
+ missingWarningPrinter.print(referencingClassName,
+ name,
+ "Warning: " +
+ ClassUtil.externalClassName(referencingClassName) +
+ ": can't find superclass or interface " +
+ ClassUtil.externalClassName(name));
+ }
+ }
+ else if (dependencyWarningPrinter != null)
+ {
+ // The superclass or interface was found in the program class pool.
+ // Print a warning.
+ dependencyWarningPrinter.print(referencingClassName,
+ name,
+ "Warning: library class " +
+ ClassUtil.externalClassName(referencingClassName) +
+ " extends or implements program class " +
+ ClassUtil.externalClassName(name));
+ }
+
+ return clazz;
+ }
+}
diff --git a/src/proguard/classfile/util/ClassUtil.java b/src/proguard/classfile/util/ClassUtil.java
new file mode 100644
index 000000000..fb38616bc
--- /dev/null
+++ b/src/proguard/classfile/util/ClassUtil.java
@@ -0,0 +1,1227 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.ClassConstants;
+
+import java.util.List;
+
+/**
+ * Utility methods for converting between internal and external representations
+ * of names and descriptions.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassUtil
+{
+ private static final String EMPTY_STRING = "";
+
+
+ /**
+ * Checks whether the given class magic number is correct.
+ * @param magicNumber the magic number.
+ * @throws UnsupportedOperationException when the magic number is incorrect.
+ */
+ public static void checkMagicNumber(int magicNumber) throws UnsupportedOperationException
+ {
+ if (magicNumber != ClassConstants.MAGIC)
+ {
+ throw new UnsupportedOperationException("Invalid magic number ["+Integer.toHexString(magicNumber)+"] in class");
+ }
+ }
+
+
+ /**
+ * Returns the combined class version number.
+ * @param majorVersion the major part of the class version number.
+ * @param minorVersion the minor part of the class version number.
+ * @return the combined class version number.
+ */
+ public static int internalClassVersion(int majorVersion, int minorVersion)
+ {
+ return (majorVersion << 16) | minorVersion;
+ }
+
+
+ /**
+ * Returns the major part of the given class version number.
+ * @param classVersion the combined class version number.
+ * @return the major part of the class version number.
+ */
+ public static int internalMajorClassVersion(int classVersion)
+ {
+ return classVersion >>> 16;
+ }
+
+
+ /**
+ * Returns the internal class version number.
+ * @param classVersion the external class version number.
+ * @return the internal class version number.
+ */
+ public static int internalMinorClassVersion(int classVersion)
+ {
+ return classVersion & 0xffff;
+ }
+
+
+ /**
+ * Returns the internal class version number.
+ * @param classVersion the external class version number.
+ * @return the internal class version number.
+ */
+ public static int internalClassVersion(String classVersion)
+ {
+ return
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_0) ||
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_1) ? ClassConstants.INTERNAL_CLASS_VERSION_1_0 :
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_2) ? ClassConstants.INTERNAL_CLASS_VERSION_1_2 :
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_3) ? ClassConstants.INTERNAL_CLASS_VERSION_1_3 :
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_4) ? ClassConstants.INTERNAL_CLASS_VERSION_1_4 :
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_5_ALIAS) ||
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_5) ? ClassConstants.INTERNAL_CLASS_VERSION_1_5 :
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_6_ALIAS) ||
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_6) ? ClassConstants.INTERNAL_CLASS_VERSION_1_6 :
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_7_ALIAS) ||
+ classVersion.equals(ClassConstants.EXTERNAL_CLASS_VERSION_1_7) ? ClassConstants.INTERNAL_CLASS_VERSION_1_7 :
+ 0;
+ }
+
+
+ /**
+ * Returns the minor part of the given class version number.
+ * @param classVersion the combined class version number.
+ * @return the minor part of the class version number.
+ */
+ public static String externalClassVersion(int classVersion)
+ {
+ switch (classVersion)
+ {
+ case ClassConstants.INTERNAL_CLASS_VERSION_1_0: return ClassConstants.EXTERNAL_CLASS_VERSION_1_0;
+ case ClassConstants.INTERNAL_CLASS_VERSION_1_2: return ClassConstants.EXTERNAL_CLASS_VERSION_1_2;
+ case ClassConstants.INTERNAL_CLASS_VERSION_1_3: return ClassConstants.EXTERNAL_CLASS_VERSION_1_3;
+ case ClassConstants.INTERNAL_CLASS_VERSION_1_4: return ClassConstants.EXTERNAL_CLASS_VERSION_1_4;
+ case ClassConstants.INTERNAL_CLASS_VERSION_1_5: return ClassConstants.EXTERNAL_CLASS_VERSION_1_5;
+ case ClassConstants.INTERNAL_CLASS_VERSION_1_6: return ClassConstants.EXTERNAL_CLASS_VERSION_1_6;
+ case ClassConstants.INTERNAL_CLASS_VERSION_1_7: return ClassConstants.EXTERNAL_CLASS_VERSION_1_7;
+ default: return null;
+ }
+ }
+
+
+ /**
+ * Checks whether the given class version number is supported.
+ * @param classVersion the combined class version number.
+ * @throws UnsupportedOperationException when the version is not supported.
+ */
+ public static void checkVersionNumbers(int classVersion) throws UnsupportedOperationException
+ {
+ if (classVersion < ClassConstants.INTERNAL_CLASS_VERSION_1_0 ||
+ classVersion > ClassConstants.INTERNAL_CLASS_VERSION_1_7)
+ {
+ throw new UnsupportedOperationException("Unsupported class version number ["+
+ internalMajorClassVersion(classVersion)+"."+
+ internalMinorClassVersion(classVersion)+"] (maximum "+
+ ClassConstants.INTERNAL_CLASS_VERSION_1_7_MAJOR+"."+
+ ClassConstants.INTERNAL_CLASS_VERSION_1_7_MINOR+", Java "+
+ ClassConstants.EXTERNAL_CLASS_VERSION_1_7+")");
+ }
+ }
+
+
+ /**
+ * Converts an external class name into an internal class name.
+ * @param externalClassName the external class name,
+ * e.g. "java.lang.Object
"
+ * @return the internal class name,
+ * e.g. "java/lang/Object
".
+ */
+ public static String internalClassName(String externalClassName)
+ {
+ return externalClassName.replace(ClassConstants.EXTERNAL_PACKAGE_SEPARATOR,
+ ClassConstants.INTERNAL_PACKAGE_SEPARATOR);
+ }
+
+
+ /**
+ * Converts an internal class description into an external class description.
+ * @param accessFlags the access flags of the class.
+ * @param internalClassName the internal class name,
+ * e.g. "java/lang/Object
".
+ * @return the external class description,
+ * e.g. "public java.lang.Object
".
+ */
+ public static String externalFullClassDescription(int accessFlags,
+ String internalClassName)
+ {
+ return externalClassAccessFlags(accessFlags) +
+ externalClassName(internalClassName);
+ }
+
+
+ /**
+ * Converts an internal class name into an external class name.
+ * @param internalClassName the internal class name,
+ * e.g. "java/lang/Object
".
+ * @return the external class name,
+ * e.g. "java.lang.Object
".
+ */
+ public static String externalClassName(String internalClassName)
+ {
+ return //internalClassName.startsWith(ClassConstants.INTERNAL_PACKAGE_JAVA_LANG) &&
+ //internalClassName.indexOf(ClassConstants.INTERNAL_PACKAGE_SEPARATOR, ClassConstants.INTERNAL_PACKAGE_JAVA_LANG.length() + 1) < 0 ?
+ //internalClassName.substring(ClassConstants.INTERNAL_PACKAGE_JAVA_LANG.length()) :
+ internalClassName.replace(ClassConstants.INTERNAL_PACKAGE_SEPARATOR,
+ ClassConstants.EXTERNAL_PACKAGE_SEPARATOR);
+ }
+
+
+ /**
+ * Returns the external base type of an external array type, dropping any
+ * array brackets.
+ * @param externalArrayType the external array type,
+ * e.g. "java.lang.Object[][]
"
+ * @return the external base type,
+ * e.g. "java.lang.Object
".
+ */
+ public static String externalBaseType(String externalArrayType)
+ {
+ int index = externalArrayType.indexOf(ClassConstants.EXTERNAL_TYPE_ARRAY);
+ return index >= 0 ?
+ externalArrayType.substring(0, index) :
+ externalArrayType;
+ }
+
+
+ /**
+ * Returns the external short class name of an external class name, dropping
+ * the package specification.
+ * @param externalClassName the external class name,
+ * e.g. "java.lang.Object
"
+ * @return the external short class name,
+ * e.g. "Object
".
+ */
+ public static String externalShortClassName(String externalClassName)
+ {
+ int index = externalClassName.lastIndexOf(ClassConstants.EXTERNAL_PACKAGE_SEPARATOR);
+ return externalClassName.substring(index+1);
+ }
+
+
+ /**
+ * Returns whether the given internal type is an array type.
+ * @param internalType the internal type,
+ * e.g. "[[Ljava/lang/Object;
".
+ * @return true
if the given type is an array type,
+ * false
otherwise.
+ */
+ public static boolean isInternalArrayType(String internalType)
+ {
+ return internalType.length() > 1 &&
+ internalType.charAt(0) == ClassConstants.INTERNAL_TYPE_ARRAY;
+ }
+
+
+ /**
+ * Returns the number of dimensions of the given internal type.
+ * @param internalType the internal type,
+ * e.g. "[[Ljava/lang/Object;
".
+ * @return the number of dimensions, e.g. 2.
+ */
+ public static int internalArrayTypeDimensionCount(String internalType)
+ {
+ int dimensions = 0;
+ while (internalType.charAt(dimensions) == ClassConstants.INTERNAL_TYPE_ARRAY)
+ {
+ dimensions++;
+ }
+
+ return dimensions;
+ }
+
+
+ /**
+ * Returns whether the given internal class name is one of the interfaces
+ * that is implemented by all array types. These class names are
+ * "java/lang/Object
", "java/lang/Cloneable
", and
+ * "java/io/Serializable
"
+ * @param internalClassName the internal class name,
+ * e.g. "java/lang/Object
".
+ * @return true
if the given type is an array interface name,
+ * false
otherwise.
+ */
+ public static boolean isInternalArrayInterfaceName(String internalClassName)
+ {
+ return ClassConstants.INTERNAL_NAME_JAVA_LANG_OBJECT.equals(internalClassName) ||
+ ClassConstants.INTERNAL_NAME_JAVA_LANG_CLONEABLE.equals(internalClassName) ||
+ ClassConstants.INTERNAL_NAME_JAVA_IO_SERIALIZABLE.equals(internalClassName);
+ }
+
+
+ /**
+ * Returns whether the given internal type is a plain primitive type
+ * (not void).
+ * @param internalType the internal type,
+ * e.g. "I
".
+ * @return true
if the given type is a class type,
+ * false
otherwise.
+ */
+ public static boolean isInternalPrimitiveType(char internalType)
+ {
+ return internalType == ClassConstants.INTERNAL_TYPE_BOOLEAN ||
+ internalType == ClassConstants.INTERNAL_TYPE_BYTE ||
+ internalType == ClassConstants.INTERNAL_TYPE_CHAR ||
+ internalType == ClassConstants.INTERNAL_TYPE_SHORT ||
+ internalType == ClassConstants.INTERNAL_TYPE_INT ||
+ internalType == ClassConstants.INTERNAL_TYPE_FLOAT ||
+ internalType == ClassConstants.INTERNAL_TYPE_LONG ||
+ internalType == ClassConstants.INTERNAL_TYPE_DOUBLE;
+ }
+
+
+ /**
+ * Returns whether the given internal type is a primitive Category 2 type.
+ * @param internalType the internal type,
+ * e.g. "L
".
+ * @return true
if the given type is a Category 2 type,
+ * false
otherwise.
+ */
+ public static boolean isInternalCategory2Type(String internalType)
+ {
+ return internalType.length() == 1 &&
+ (internalType.charAt(0) == ClassConstants.INTERNAL_TYPE_LONG ||
+ internalType.charAt(0) == ClassConstants.INTERNAL_TYPE_DOUBLE);
+ }
+
+
+ /**
+ * Returns whether the given internal type is a plain class type
+ * (including an array type of a plain class type).
+ * @param internalType the internal type,
+ * e.g. "Ljava/lang/Object;
".
+ * @return true
if the given type is a class type,
+ * false
otherwise.
+ */
+ public static boolean isInternalClassType(String internalType)
+ {
+ int length = internalType.length();
+ return length > 1 &&
+// internalType.charAt(0) == ClassConstants.INTERNAL_TYPE_CLASS_START &&
+ internalType.charAt(length-1) == ClassConstants.INTERNAL_TYPE_CLASS_END;
+ }
+
+
+ /**
+ * Returns the internal type of a given class name.
+ * @param internalClassName the internal class name,
+ * e.g. "java/lang/Object
".
+ * @return the internal type,
+ * e.g. "Ljava/lang/Object;
".
+ */
+ public static String internalTypeFromClassName(String internalClassName)
+ {
+ return internalArrayTypeFromClassName(internalClassName, 0);
+ }
+
+
+ /**
+ * Returns the internal array type of a given class name with a given number
+ * of dimensions. If the number of dimensions is 0, the class name itself is
+ * returned.
+ * @param internalClassName the internal class name,
+ * e.g. "java/lang/Object
".
+ * @param dimensionCount the number of array dimensions.
+ * @return the internal array type of the array elements,
+ * e.g. "Ljava/lang/Object;
".
+ */
+ public static String internalArrayTypeFromClassName(String internalClassName,
+ int dimensionCount)
+ {
+ StringBuffer buffer = new StringBuffer(internalClassName.length() + dimensionCount + 2);
+
+ for (int dimension = 0; dimension < dimensionCount; dimension++)
+ {
+ buffer.append(ClassConstants.INTERNAL_TYPE_ARRAY);
+ }
+
+ return buffer.append(ClassConstants.INTERNAL_TYPE_CLASS_START)
+ .append(internalClassName)
+ .append(ClassConstants.INTERNAL_TYPE_CLASS_END)
+ .toString();
+ }
+
+
+ /**
+ * Returns the internal element type of a given internal array type.
+ * @param internalArrayType the internal array type,
+ * e.g. "[[Ljava/lang/Object;
" or
+ * "[I
".
+ * @return the internal type of the array elements,
+ * e.g. "Ljava/lang/Object;
" or
+ * "I
".
+ */
+ public static String internalTypeFromArrayType(String internalArrayType)
+ {
+ int index = internalArrayType.lastIndexOf(ClassConstants.INTERNAL_TYPE_ARRAY);
+ return internalArrayType.substring(index+1);
+ }
+
+
+ /**
+ * Returns the internal class name of a given internal class type
+ * (including an array type). Types involving primitive types are returned
+ * unchanged.
+ * @param internalClassType the internal class type,
+ * e.g. "[Ljava/lang/Object;
",
+ * "Ljava/lang/Object;
", or
+ * "java/lang/Object
".
+ * @return the internal class name,
+ * e.g. "java/lang/Object
".
+ */
+ public static String internalClassNameFromClassType(String internalClassType)
+ {
+ return isInternalClassType(internalClassType) ?
+ internalClassType.substring(internalClassType.indexOf(ClassConstants.INTERNAL_TYPE_CLASS_START)+1,
+ internalClassType.length()-1) :
+ internalClassType;
+ }
+
+
+ /**
+ * Returns the internal class name of any given internal descriptor type,
+ * disregarding array prefixes.
+ * @param internalClassType the internal class type,
+ * e.g. "Ljava/lang/Object;
" or
+ * "[[I
".
+ * @return the internal class name,
+ * e.g. "java/lang/Object
" or
+ * null
.
+ */
+ public static String internalClassNameFromType(String internalClassType)
+ {
+ if (!isInternalClassType(internalClassType))
+ {
+ return null;
+ }
+
+ // Is it an array type?
+ if (isInternalArrayType(internalClassType))
+ {
+ internalClassType = internalTypeFromArrayType(internalClassType);
+ }
+
+ return internalClassNameFromClassType(internalClassType);
+ }
+
+
+ /**
+ * Returns whether the given method name refers to a class initializer or
+ * an instance initializer.
+ * @param internalMethodName the internal method name,
+ * e.g. "<clinit>
".
+ * @return whether the method name refers to an initializer,
+ * e.g. true
.
+ */
+ public static boolean isInitializer(String internalMethodName)
+ {
+ return internalMethodName.equals(ClassConstants.INTERNAL_METHOD_NAME_CLINIT) ||
+ internalMethodName.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT);
+ }
+
+
+ /**
+ * Returns the internal type of the given internal method descriptor.
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(II)Z
".
+ * @return the internal return type,
+ * e.g. "Z
".
+ */
+ public static String internalMethodReturnType(String internalMethodDescriptor)
+ {
+ int index = internalMethodDescriptor.indexOf(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+ return internalMethodDescriptor.substring(index + 1);
+ }
+
+
+ /**
+ * Returns the number of parameters of the given internal method descriptor.
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(ID)Z
".
+ * @return the number of parameters,
+ * e.g. 2.
+ */
+ public static int internalMethodParameterCount(String internalMethodDescriptor)
+ {
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(internalMethodDescriptor);
+
+ int counter = 0;
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ internalTypeEnumeration.nextType();
+
+ counter++;
+ }
+
+ return counter;
+ }
+
+
+ /**
+ * Returns the size taken up on the stack by the parameters of the given
+ * internal method descriptor. This accounts for long and double parameters
+ * taking up two entries.
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(ID)Z
".
+ * @return the size taken up on the stack,
+ * e.g. 3.
+ */
+ public static int internalMethodParameterSize(String internalMethodDescriptor)
+ {
+ return internalMethodParameterSize(internalMethodDescriptor, true);
+ }
+
+
+ /**
+ * Returns the size taken up on the stack by the parameters of the given
+ * internal method descriptor. This accounts for long and double parameters
+ * taking up two entries, and a non-static method taking up an additional
+ * entry.
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(ID)Z
".
+ * @param accessFlags the access flags of the method,
+ * e.g. 0.
+ * @return the size taken up on the stack,
+ * e.g. 4.
+ */
+ public static int internalMethodParameterSize(String internalMethodDescriptor,
+ int accessFlags)
+ {
+ return internalMethodParameterSize(internalMethodDescriptor,
+ (accessFlags & ClassConstants.INTERNAL_ACC_STATIC) != 0);
+ }
+
+
+ /**
+ * Returns the size taken up on the stack by the parameters of the given
+ * internal method descriptor. This accounts for long and double parameters
+ * taking up two spaces, and a non-static method taking up an additional
+ * entry.
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(ID)Z
".
+ * @param isStatic specifies whether the method is static,
+ * e.g. false.
+ * @return the size taken up on the stack,
+ * e.g. 4.
+ */
+ public static int internalMethodParameterSize(String internalMethodDescriptor,
+ boolean isStatic)
+ {
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(internalMethodDescriptor);
+
+ int size = isStatic ? 0 : 1;
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ String internalType = internalTypeEnumeration.nextType();
+
+ size += internalTypeSize(internalType);
+ }
+
+ return size;
+ }
+
+
+ /**
+ * Returns the size taken up on the stack by the given internal type.
+ * The size is 1, except for long and double types, for which it is 2,
+ * and for the void type, for which 0 is returned.
+ * @param internalType the internal type,
+ * e.g. "I
".
+ * @return the size taken up on the stack,
+ * e.g. 1.
+ */
+ public static int internalTypeSize(String internalType)
+ {
+ if (internalType.length() == 1)
+ {
+ char internalPrimitiveType = internalType.charAt(0);
+ if (internalPrimitiveType == ClassConstants.INTERNAL_TYPE_LONG ||
+ internalPrimitiveType == ClassConstants.INTERNAL_TYPE_DOUBLE)
+ {
+ return 2;
+ }
+ else if (internalPrimitiveType == ClassConstants.INTERNAL_TYPE_VOID)
+ {
+ return 0;
+ }
+ }
+
+ return 1;
+ }
+
+
+ /**
+ * Converts an external type into an internal type.
+ * @param externalType the external type,
+ * e.g. "java.lang.Object[][]
" or
+ * "int[]
".
+ * @return the internal type,
+ * e.g. "[[Ljava/lang/Object;
" or
+ * "[I
".
+ */
+ public static String internalType(String externalType)
+ {
+ // Strip the array part, if any.
+ int dimensionCount = externalArrayTypeDimensionCount(externalType);
+ if (dimensionCount > 0)
+ {
+ externalType = externalType.substring(0, externalType.length() - dimensionCount * ClassConstants.EXTERNAL_TYPE_ARRAY.length());
+ }
+
+ // Analyze the actual type part.
+ char internalTypeChar =
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_VOID ) ?
+ ClassConstants.INTERNAL_TYPE_VOID :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_BOOLEAN) ?
+ ClassConstants.INTERNAL_TYPE_BOOLEAN :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_BYTE ) ?
+ ClassConstants.INTERNAL_TYPE_BYTE :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_CHAR ) ?
+ ClassConstants.INTERNAL_TYPE_CHAR :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_SHORT ) ?
+ ClassConstants.INTERNAL_TYPE_SHORT :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_INT ) ?
+ ClassConstants.INTERNAL_TYPE_INT :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_FLOAT ) ?
+ ClassConstants.INTERNAL_TYPE_FLOAT :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_LONG ) ?
+ ClassConstants.INTERNAL_TYPE_LONG :
+ externalType.equals(ClassConstants.EXTERNAL_TYPE_DOUBLE ) ?
+ ClassConstants.INTERNAL_TYPE_DOUBLE :
+ externalType.equals("%" ) ?
+ '%' :
+ (char)0;
+
+ String internalType =
+ internalTypeChar != 0 ? String.valueOf(internalTypeChar) :
+ ClassConstants.INTERNAL_TYPE_CLASS_START +
+ internalClassName(externalType) +
+ ClassConstants.INTERNAL_TYPE_CLASS_END;
+
+ // Prepend the array part, if any.
+ for (int count = 0; count < dimensionCount; count++)
+ {
+ internalType = ClassConstants.INTERNAL_TYPE_ARRAY + internalType;
+ }
+
+ return internalType;
+ }
+
+
+ /**
+ * Returns the number of dimensions of the given external type.
+ * @param externalType the external type,
+ * e.g. "[[Ljava/lang/Object;
".
+ * @return the number of dimensions, e.g. 2.
+ */
+ public static int externalArrayTypeDimensionCount(String externalType)
+ {
+ int dimensions = 0;
+ int length = ClassConstants.EXTERNAL_TYPE_ARRAY.length();
+ int offset = externalType.length() - length;
+ while (externalType.regionMatches(offset,
+ ClassConstants.EXTERNAL_TYPE_ARRAY,
+ 0,
+ length))
+ {
+ dimensions++;
+ offset -= length;
+ }
+
+ return dimensions;
+ }
+
+
+ /**
+ * Converts an internal type into an external type.
+ * @param internalType the internal type,
+ * e.g. "[[Ljava/lang/Object;
" or
+ * "[I
".
+ * @return the external type,
+ * e.g. "java.lang.Object[][]
" or
+ * "int[]
".
+ */
+ public static String externalType(String internalType)
+ {
+ // Strip the array part, if any.
+ int dimensionCount = internalArrayTypeDimensionCount(internalType);
+ if (dimensionCount > 0)
+ {
+ internalType = internalType.substring(dimensionCount);
+ }
+
+ // Analyze the actual type part.
+ char internalTypeChar = internalType.charAt(0);
+
+ String externalType =
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_VOID ?
+ ClassConstants.EXTERNAL_TYPE_VOID :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_BOOLEAN ?
+ ClassConstants.EXTERNAL_TYPE_BOOLEAN :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_BYTE ?
+ ClassConstants.EXTERNAL_TYPE_BYTE :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_CHAR ?
+ ClassConstants.EXTERNAL_TYPE_CHAR :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_SHORT ?
+ ClassConstants.EXTERNAL_TYPE_SHORT :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_INT ?
+ ClassConstants.EXTERNAL_TYPE_INT :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_FLOAT ?
+ ClassConstants.EXTERNAL_TYPE_FLOAT :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_LONG ?
+ ClassConstants.EXTERNAL_TYPE_LONG :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_DOUBLE ?
+ ClassConstants.EXTERNAL_TYPE_DOUBLE :
+ internalTypeChar == '%' ?
+ "%" :
+ internalTypeChar == ClassConstants.INTERNAL_TYPE_CLASS_START ?
+ externalClassName(internalType.substring(1, internalType.indexOf(ClassConstants.INTERNAL_TYPE_CLASS_END))) :
+ null;
+
+ if (externalType == null)
+ {
+ throw new IllegalArgumentException("Unknown type ["+internalType+"]");
+ }
+
+ // Append the array part, if any.
+ for (int count = 0; count < dimensionCount; count++)
+ {
+ externalType += ClassConstants.EXTERNAL_TYPE_ARRAY;
+ }
+
+ return externalType;
+ }
+
+
+ /**
+ * Returns whether the given internal descriptor String represents a method
+ * descriptor.
+ * @param internalDescriptor the internal descriptor String,
+ * e.g. "(II)Z
".
+ * @return true
if the given String is a method descriptor,
+ * false
otherwise.
+ */
+ public static boolean isInternalMethodDescriptor(String internalDescriptor)
+ {
+ return internalDescriptor.charAt(0) == ClassConstants.INTERNAL_METHOD_ARGUMENTS_OPEN;
+ }
+
+
+ /**
+ * Returns whether the given member String represents an external method
+ * name with arguments.
+ * @param externalMemberNameAndArguments the external member String,
+ * e.g. "myField
" or
+ * e.g. "myMethod(int,int)
".
+ * @return true
if the given String refers to a method,
+ * false
otherwise.
+ */
+ public static boolean isExternalMethodNameAndArguments(String externalMemberNameAndArguments)
+ {
+ return externalMemberNameAndArguments.indexOf(ClassConstants.EXTERNAL_METHOD_ARGUMENTS_OPEN) > 0;
+ }
+
+
+ /**
+ * Returns the name part of the given external method name and arguments.
+ * @param externalMethodNameAndArguments the external method name and arguments,
+ * e.g. "myMethod(int,int)
".
+ * @return the name part of the String, e.g. "myMethod
".
+ */
+ public static String externalMethodName(String externalMethodNameAndArguments)
+ {
+ ExternalTypeEnumeration externalTypeEnumeration =
+ new ExternalTypeEnumeration(externalMethodNameAndArguments);
+
+ return externalTypeEnumeration.methodName();
+ }
+
+
+ /**
+ * Converts the given external method return type and name and arguments to
+ * an internal method descriptor.
+ * @param externalReturnType the external method return type,
+ * e.g. "boolean
".
+ * @param externalMethodNameAndArguments the external method name and arguments,
+ * e.g. "myMethod(int,int)
".
+ * @return the internal method descriptor,
+ * e.g. "(II)Z
".
+ */
+ public static String internalMethodDescriptor(String externalReturnType,
+ String externalMethodNameAndArguments)
+ {
+ StringBuffer internalMethodDescriptor = new StringBuffer();
+ internalMethodDescriptor.append(ClassConstants.INTERNAL_METHOD_ARGUMENTS_OPEN);
+
+ ExternalTypeEnumeration externalTypeEnumeration =
+ new ExternalTypeEnumeration(externalMethodNameAndArguments);
+
+ while (externalTypeEnumeration.hasMoreTypes())
+ {
+ internalMethodDescriptor.append(internalType(externalTypeEnumeration.nextType()));
+ }
+
+ internalMethodDescriptor.append(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+ internalMethodDescriptor.append(internalType(externalReturnType));
+
+ return internalMethodDescriptor.toString();
+ }
+
+
+ /**
+ * Converts the given external method return type and List of arguments to
+ * an internal method descriptor.
+ * @param externalReturnType the external method return type,
+ * e.g. "boolean
".
+ * @param externalArguments the external method arguments,
+ * e.g. { "int", "int" }
.
+ * @return the internal method descriptor,
+ * e.g. "(II)Z
".
+ */
+ public static String internalMethodDescriptor(String externalReturnType,
+ List externalArguments)
+ {
+ StringBuffer internalMethodDescriptor = new StringBuffer();
+ internalMethodDescriptor.append(ClassConstants.INTERNAL_METHOD_ARGUMENTS_OPEN);
+
+ for (int index = 0; index < externalArguments.size(); index++)
+ {
+ internalMethodDescriptor.append(internalType((String)externalArguments.get(index)));
+ }
+
+ internalMethodDescriptor.append(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+ internalMethodDescriptor.append(internalType(externalReturnType));
+
+ return internalMethodDescriptor.toString();
+ }
+
+
+ /**
+ * Converts an internal field description into an external full field description.
+ * @param accessFlags the access flags of the field.
+ * @param fieldName the field name,
+ * e.g. "myField
".
+ * @param internalFieldDescriptor the internal field descriptor,
+ * e.g. "Z
".
+ * @return the external full field description,
+ * e.g. "public boolean myField
".
+ */
+ public static String externalFullFieldDescription(int accessFlags,
+ String fieldName,
+ String internalFieldDescriptor)
+ {
+ return externalFieldAccessFlags(accessFlags) +
+ externalType(internalFieldDescriptor) +
+ ' ' +
+ fieldName;
+ }
+
+
+ /**
+ * Converts an internal method description into an external full method description.
+ * @param internalClassName the internal name of the class of the method,
+ * e.g. "mypackage/MyClass
".
+ * @param accessFlags the access flags of the method.
+ * @param internalMethodName the internal method name,
+ * e.g. "myMethod
" or
+ * "<init>
".
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(II)Z
".
+ * @return the external full method description,
+ * e.g. "public boolean myMethod(int,int)
" or
+ * "public MyClass(int,int)
".
+ */
+ public static String externalFullMethodDescription(String internalClassName,
+ int accessFlags,
+ String internalMethodName,
+ String internalMethodDescriptor)
+ {
+ return externalMethodAccessFlags(accessFlags) +
+ externalMethodReturnTypeAndName(internalClassName,
+ internalMethodName,
+ internalMethodDescriptor) +
+ ClassConstants.EXTERNAL_METHOD_ARGUMENTS_OPEN +
+ externalMethodArguments(internalMethodDescriptor) +
+ ClassConstants.EXTERNAL_METHOD_ARGUMENTS_CLOSE;
+ }
+
+
+ /**
+ * Converts internal class access flags into an external access description.
+ * @param accessFlags the class access flags.
+ * @return the external class access description,
+ * e.g. "public final
".
+ */
+ public static String externalClassAccessFlags(int accessFlags)
+ {
+ return externalClassAccessFlags(accessFlags, "");
+ }
+
+
+ /**
+ * Converts internal class access flags into an external access description.
+ * @param accessFlags the class access flags.
+ * @param prefix a prefix that is added to each access modifier.
+ * @return the external class access description,
+ * e.g. "public final
".
+ */
+ public static String externalClassAccessFlags(int accessFlags, String prefix)
+ {
+ if (accessFlags == 0)
+ {
+ return EMPTY_STRING;
+ }
+
+ StringBuffer string = new StringBuffer(50);
+
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PUBLIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PUBLIC).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PRIVATE) != 0)
+ {
+ // Only in InnerClasses attributes.
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PRIVATE).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PROTECTED) != 0)
+ {
+ // Only in InnerClasses attributes.
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PROTECTED).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_STATIC) != 0)
+ {
+ // Only in InnerClasses attributes.
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_STATIC).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_FINAL) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_FINAL).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_ANNOTATTION) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_ANNOTATION);
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_INTERFACE) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_INTERFACE).append(' ');
+ }
+ else if ((accessFlags & ClassConstants.INTERNAL_ACC_ENUM) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_ENUM).append(' ');
+ }
+ else if ((accessFlags & ClassConstants.INTERNAL_ACC_ABSTRACT) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_ABSTRACT).append(' ');
+ }
+ else if ((accessFlags & ClassConstants.INTERNAL_ACC_SYNTHETIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_SYNTHETIC).append(' ');
+ }
+
+ return string.toString();
+ }
+
+
+ /**
+ * Converts internal field access flags into an external access description.
+ * @param accessFlags the field access flags.
+ * @return the external field access description,
+ * e.g. "public volatile
".
+ */
+ public static String externalFieldAccessFlags(int accessFlags)
+ {
+ return externalFieldAccessFlags(accessFlags, "");
+ }
+
+
+ /**
+ * Converts internal field access flags into an external access description.
+ * @param accessFlags the field access flags.
+ * @param prefix a prefix that is added to each access modifier.
+ * @return the external field access description,
+ * e.g. "public volatile
".
+ */
+ public static String externalFieldAccessFlags(int accessFlags, String prefix)
+ {
+ if (accessFlags == 0)
+ {
+ return EMPTY_STRING;
+ }
+
+ StringBuffer string = new StringBuffer(50);
+
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PUBLIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PUBLIC).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PRIVATE) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PRIVATE).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PROTECTED) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PROTECTED).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_STATIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_STATIC).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_FINAL) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_FINAL).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_VOLATILE) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_VOLATILE).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_TRANSIENT) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_TRANSIENT).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_SYNTHETIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_SYNTHETIC).append(' ');
+ }
+
+ return string.toString();
+ }
+
+
+ /**
+ * Converts internal method access flags into an external access description.
+ * @param accessFlags the method access flags.
+ * @return the external method access description,
+ * e.g. "public synchronized
".
+ */
+ public static String externalMethodAccessFlags(int accessFlags)
+ {
+ return externalMethodAccessFlags(accessFlags, "");
+ }
+
+
+ /**
+ * Converts internal method access flags into an external access description.
+ * @param accessFlags the method access flags.
+ * @param prefix a prefix that is added to each access modifier.
+ * @return the external method access description,
+ * e.g. "public synchronized ".
+ */
+ public static String externalMethodAccessFlags(int accessFlags, String prefix)
+ {
+ if (accessFlags == 0)
+ {
+ return EMPTY_STRING;
+ }
+
+ StringBuffer string = new StringBuffer(50);
+
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PUBLIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PUBLIC).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PRIVATE) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PRIVATE).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PROTECTED) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_PROTECTED).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_STATIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_STATIC).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_FINAL) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_FINAL).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_SYNCHRONIZED) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_SYNCHRONIZED).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_BRIDGE) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_BRIDGE).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_VARARGS) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_VARARGS).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_NATIVE) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_NATIVE).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_ABSTRACT) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_ABSTRACT).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_STRICT) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_STRICT).append(' ');
+ }
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_SYNTHETIC) != 0)
+ {
+ string.append(prefix).append(ClassConstants.EXTERNAL_ACC_SYNTHETIC).append(' ');
+ }
+
+ return string.toString();
+ }
+
+
+ /**
+ * Converts an internal method descriptor into an external method return type.
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(II)Z
".
+ * @return the external method return type,
+ * e.g. "boolean
".
+ */
+ public static String externalMethodReturnType(String internalMethodDescriptor)
+ {
+ return externalType(internalMethodReturnType(internalMethodDescriptor));
+ }
+
+
+ /**
+ * Converts an internal class name, method name, and method descriptor to
+ * an external method return type and name.
+ * @param internalClassName the internal name of the class of the method,
+ * e.g. "mypackage/MyClass
".
+ * @param internalMethodName the internal method name,
+ * e.g. "myMethod
" or
+ * "<init>
".
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(II)Z
".
+ * @return the external method return type and name,
+ * e.g. "boolean myMethod
" or
+ * "MyClass
".
+ */
+ private static String externalMethodReturnTypeAndName(String internalClassName,
+ String internalMethodName,
+ String internalMethodDescriptor)
+ {
+ return internalMethodName.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT) ?
+ externalShortClassName(externalClassName(internalClassName)) :
+ (externalMethodReturnType(internalMethodDescriptor) +
+ ' ' +
+ internalMethodName);
+ }
+
+
+ /**
+ * Converts an internal method descriptor into an external method argument
+ * description.
+ * @param internalMethodDescriptor the internal method descriptor,
+ * e.g. "(II)Z
".
+ * @return the external method argument description,
+ * e.g. "int,int
".
+ */
+ public static String externalMethodArguments(String internalMethodDescriptor)
+ {
+ StringBuffer externalMethodNameAndArguments = new StringBuffer();
+
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(internalMethodDescriptor);
+
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ externalMethodNameAndArguments.append(externalType(internalTypeEnumeration.nextType()));
+ if (internalTypeEnumeration.hasMoreTypes())
+ {
+ externalMethodNameAndArguments.append(ClassConstants.EXTERNAL_METHOD_ARGUMENTS_SEPARATOR);
+ }
+ }
+
+ return externalMethodNameAndArguments.toString();
+ }
+
+
+ /**
+ * Returns the internal package name of the given internal class name.
+ * @param internalClassName the internal class name,
+ * e.g. "java/lang/Object
".
+ * @return the internal package name,
+ * e.g. "java/lang
".
+ */
+ public static String internalPackageName(String internalClassName)
+ {
+ String internalPackagePrefix = internalPackagePrefix(internalClassName);
+ int length = internalPackagePrefix.length();
+ return length > 0 ?
+ internalPackagePrefix.substring(0, length - 1) :
+ "";
+ }
+
+
+ /**
+ * Returns the internal package prefix of the given internal class name.
+ * @param internalClassName the internal class name,
+ * e.g. "java/lang/Object
".
+ * @return the internal package prefix,
+ * e.g. "java/lang/
".
+ */
+ public static String internalPackagePrefix(String internalClassName)
+ {
+ return internalClassName.substring(0, internalClassName.lastIndexOf(ClassConstants.INTERNAL_PACKAGE_SEPARATOR,
+ internalClassName.length() - 2) + 1);
+ }
+
+
+ /**
+ * Returns the external package name of the given external class name.
+ * @param externalClassName the external class name,
+ * e.g. "java.lang.Object
".
+ * @return the external package name,
+ * e.g. "java.lang
".
+ */
+ public static String externalPackageName(String externalClassName)
+ {
+ String externalPackagePrefix = externalPackagePrefix(externalClassName);
+ int length = externalPackagePrefix.length();
+ return length > 0 ?
+ externalPackagePrefix.substring(0, length - 1) :
+ "";
+ }
+
+
+ /**
+ * Returns the external package prefix of the given external class name.
+ * @param externalClassName the external class name,
+ * e.g. "java.lang.Object
".
+ * @return the external package prefix,
+ * e.g. "java.lang.
".
+ */
+ public static String externalPackagePrefix(String externalClassName)
+ {
+ return externalClassName.substring(0, externalClassName.lastIndexOf(ClassConstants.EXTERNAL_PACKAGE_SEPARATOR,
+ externalClassName.length() - 2) + 1);
+ }
+}
diff --git a/src/proguard/classfile/util/DescriptorClassEnumeration.java b/src/proguard/classfile/util/DescriptorClassEnumeration.java
new file mode 100644
index 000000000..81590faae
--- /dev/null
+++ b/src/proguard/classfile/util/DescriptorClassEnumeration.java
@@ -0,0 +1,236 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.ClassConstants;
+
+import java.util.Stack;
+
+/**
+ * A DescriptorClassEnumeration
provides an enumeration of all
+ * classes mentioned in a given descriptor or signature.
+ *
+ * @author Eric Lafortune
+ */
+public class DescriptorClassEnumeration
+{
+ private String descriptor;
+
+ private int index;
+ private int nestingLevel;
+ private boolean isInnerClassName;
+ private String accumulatedClassName;
+ private Stack accumulatedClassNames;
+
+
+ /**
+ * Creates a new DescriptorClassEnumeration for the given descriptor.
+ */
+ public DescriptorClassEnumeration(String descriptor)
+ {
+ this.descriptor = descriptor;
+ }
+
+
+ /**
+ * Returns the number of classes contained in the descriptor. This
+ * is the number of class names that the enumeration will return.
+ */
+ public int classCount()
+ {
+ int count = 0;
+
+ nextFluff();
+ while (hasMoreClassNames())
+ {
+ count++;
+
+ nextClassName();
+ nextFluff();
+ }
+
+ index = 0;
+
+ return count;
+ }
+
+
+ /**
+ * Returns whether the enumeration can provide more class names from the
+ * descriptor.
+ */
+ public boolean hasMoreClassNames()
+ {
+ return index < descriptor.length();
+ }
+
+
+ /**
+ * Returns the next fluff (surrounding class names) from the descriptor.
+ */
+ public String nextFluff()
+ {
+ int fluffStartIndex = index;
+
+ // Find the first token marking the start of a class name 'L' or '.'.
+ loop: while (index < descriptor.length())
+ {
+ switch (descriptor.charAt(index++))
+ {
+ case ClassConstants.INTERNAL_TYPE_GENERIC_START:
+ {
+ nestingLevel++;
+
+ // Make sure we have a stack.
+ if (accumulatedClassNames == null)
+ {
+ accumulatedClassNames = new Stack();
+ }
+
+ // Remember the accumulated class name.
+ accumulatedClassNames.push(accumulatedClassName);
+
+ break;
+ }
+ case ClassConstants.INTERNAL_TYPE_GENERIC_END:
+ {
+ nestingLevel--;
+
+ // Return to the accumulated class name outside the
+ // generic block.
+ accumulatedClassName = (String)accumulatedClassNames.pop();
+
+ continue loop;
+ }
+ case ClassConstants.INTERNAL_TYPE_GENERIC_BOUND:
+ {
+ continue loop;
+ }
+ case ClassConstants.INTERNAL_TYPE_CLASS_START:
+ {
+ // We've found the start of an ordinary class name.
+ nestingLevel += 2;
+ isInnerClassName = false;
+ break loop;
+ }
+ case ClassConstants.INTERNAL_TYPE_CLASS_END:
+ {
+ nestingLevel -= 2;
+ break;
+ }
+ case ClassConstants.EXTERNAL_INNER_CLASS_SEPARATOR:
+ {
+ // We've found the start of an inner class name in a signature.
+ isInnerClassName = true;
+ break loop;
+ }
+ case ClassConstants.INTERNAL_TYPE_GENERIC_VARIABLE_START:
+ {
+ // We've found the start of a type identifier. Skip to the end.
+ while (descriptor.charAt(index++) != ClassConstants.INTERNAL_TYPE_CLASS_END);
+ break;
+ }
+ }
+
+ if (nestingLevel == 1 &&
+ descriptor.charAt(index) != ClassConstants.INTERNAL_TYPE_GENERIC_END)
+ {
+ // We're at the start of a type parameter. Skip to the start
+ // of the bounds.
+ while (descriptor.charAt(index++) != ClassConstants.INTERNAL_TYPE_GENERIC_BOUND);
+ }
+ }
+
+ return descriptor.substring(fluffStartIndex, index);
+ }
+
+
+ /**
+ * Returns the next class name from the descriptor.
+ */
+ public String nextClassName()
+ {
+ int classNameStartIndex = index;
+
+ // Find the first token marking the end of a class name '<' or ';'.
+ loop: while (true)
+ {
+ switch (descriptor.charAt(index))
+ {
+ case ClassConstants.INTERNAL_TYPE_GENERIC_START:
+ case ClassConstants.INTERNAL_TYPE_CLASS_END:
+ case ClassConstants.EXTERNAL_INNER_CLASS_SEPARATOR:
+ {
+ break loop;
+ }
+ }
+
+ index++;
+ }
+
+ String className = descriptor.substring(classNameStartIndex, index);
+
+ // Recompose the inner class name if necessary.
+ accumulatedClassName = isInnerClassName ?
+ accumulatedClassName + ClassConstants.INTERNAL_INNER_CLASS_SEPARATOR + className :
+ className;
+
+ return accumulatedClassName;
+ }
+
+
+ /**
+ * Returns whether the most recently returned class name was a recomposed
+ * inner class name from a signature.
+ */
+ public boolean isInnerClassName()
+ {
+ return isInnerClassName;
+ }
+
+
+ /**
+ * A main method for testing the class name enumeration.
+ */
+ public static void main(String[] args)
+ {
+ try
+ {
+ for (int index = 0; index < args.length; index++)
+ {
+ String descriptor = args[index];
+
+ System.out.println("Descriptor ["+descriptor+"]");
+ DescriptorClassEnumeration enumeration = new DescriptorClassEnumeration(descriptor);
+ System.out.println(" Fluff: ["+enumeration.nextFluff()+"]");
+ while (enumeration.hasMoreClassNames())
+ {
+ System.out.println(" Name: ["+enumeration.nextClassName()+"]");
+ System.out.println(" Fluff: ["+enumeration.nextFluff()+"]");
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/classfile/util/DynamicClassReferenceInitializer.java b/src/proguard/classfile/util/DynamicClassReferenceInitializer.java
new file mode 100644
index 000000000..865e094ef
--- /dev/null
+++ b/src/proguard/classfile/util/DynamicClassReferenceInitializer.java
@@ -0,0 +1,485 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.util.StringMatcher;
+
+/**
+ * This InstructionVisitor initializes any constant Class.forName
or
+ * .class
references of all classes it visits. More specifically,
+ * it fills out the references of string constant pool entries that refer to a
+ * class in the program class pool or in the library class pool.
+ *
+ * It optionally prints notes if on usage of
+ * (SomeClass)Class.forName(variable).newInstance()
.
+ *
+ * The class hierarchy must be initialized before using this visitor.
+ *
+ * @see ClassSuperHierarchyInitializer
+ *
+ * @author Eric Lafortune
+ */
+public class DynamicClassReferenceInitializer
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor,
+ AttributeVisitor
+{
+ public static final int X = InstructionSequenceMatcher.X;
+ public static final int Y = InstructionSequenceMatcher.Y;
+ public static final int Z = InstructionSequenceMatcher.Z;
+
+ public static final int A = InstructionSequenceMatcher.A;
+ public static final int B = InstructionSequenceMatcher.B;
+ public static final int C = InstructionSequenceMatcher.C;
+ public static final int D = InstructionSequenceMatcher.D;
+
+
+ private final Constant[] CLASS_FOR_NAME_CONSTANTS = new Constant[]
+ {
+ // 0
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_FOR_NAME),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_FOR_NAME),
+
+ // 6
+ new MethodrefConstant(1, 7, null, null),
+ new NameAndTypeConstant(8, 9),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_NEW_INSTANCE),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_NEW_INSTANCE),
+
+ // 10
+ new MethodrefConstant(1, 11, null, null),
+ new NameAndTypeConstant(12, 13),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_COMPONENT_TYPE),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_COMPONENT_TYPE),
+ };
+
+ // Class.forName("SomeClass").
+ private final Instruction[] CONSTANT_CLASS_FOR_NAME_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, X),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ };
+
+ // (SomeClass)Class.forName(someName).newInstance().
+ private final Instruction[] CLASS_FOR_NAME_CAST_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 6),
+ new ConstantInstruction(InstructionConstants.OP_CHECKCAST, X),
+ };
+
+
+// private Constant[] DOT_CLASS_JAVAC_CONSTANTS = new Constant[]
+// {
+// new MethodrefConstant(A, 1, null, null),
+// new NameAndTypeConstant(2, 3),
+// new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_DOT_CLASS_JAVAC),
+// new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_DOT_CLASS_JAVAC),
+// };
+
+ private final Constant[] DOT_CLASS_JAVAC_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(A, 1, null, null),
+ new NameAndTypeConstant(B, 2),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_DOT_CLASS_JAVAC),
+ };
+
+ // SomeClass.class = class$("SomeClass") (javac).
+ private final Instruction[] DOT_CLASS_JAVAC_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, X),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ };
+
+
+// private Constant[] DOT_CLASS_JIKES_CONSTANTS = new Constant[]
+// {
+// new MethodrefConstant(A, 1, null, null),
+// new NameAndTypeConstant(2, 3),
+// new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_DOT_CLASS_JIKES),
+// new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_DOT_CLASS_JIKES),
+// };
+
+ private final Constant[] DOT_CLASS_JIKES_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(A, 1, null, null),
+ new NameAndTypeConstant(B, 2),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_DOT_CLASS_JIKES),
+ };
+
+ // SomeClass.class = class("SomeClass", false) (jikes).
+ private final Instruction[] DOT_CLASS_JIKES_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ };
+
+ // return Class.forName(v0).
+ private final Instruction[] DOT_CLASS_JAVAC_IMPLEMENTATION_INSTRUCTIONS = new Instruction[]
+ {
+ new VariableInstruction(InstructionConstants.OP_ALOAD_0),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ new SimpleInstruction(InstructionConstants.OP_ARETURN),
+ };
+
+ // return Class.forName(v0), if (!v1) .getComponentType().
+ private final Instruction[] DOT_CLASS_JIKES_IMPLEMENTATION_INSTRUCTIONS = new Instruction[]
+ {
+ new VariableInstruction(InstructionConstants.OP_ALOAD_0),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ new VariableInstruction(InstructionConstants.OP_ALOAD_1),
+ new BranchInstruction(InstructionConstants.OP_IFNE, +6),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 10),
+ new SimpleInstruction(InstructionConstants.OP_ARETURN),
+ };
+
+ // return Class.forName(v0).getComponentType().
+ private final Instruction[] DOT_CLASS_JIKES_IMPLEMENTATION_INSTRUCTIONS2 = new Instruction[]
+ {
+ new VariableInstruction(InstructionConstants.OP_ALOAD_0),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 10),
+ new SimpleInstruction(InstructionConstants.OP_ARETURN),
+ };
+
+
+ private final ClassPool programClassPool;
+ private final ClassPool libraryClassPool;
+ private final WarningPrinter missingNotePrinter;
+ private final WarningPrinter dependencyWarningPrinter;
+ private final WarningPrinter notePrinter;
+ private final StringMatcher noteExceptionMatcher;
+
+
+ private final InstructionSequenceMatcher constantClassForNameMatcher =
+ new InstructionSequenceMatcher(CLASS_FOR_NAME_CONSTANTS,
+ CONSTANT_CLASS_FOR_NAME_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher classForNameCastMatcher =
+ new InstructionSequenceMatcher(CLASS_FOR_NAME_CONSTANTS,
+ CLASS_FOR_NAME_CAST_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher dotClassJavacMatcher =
+ new InstructionSequenceMatcher(DOT_CLASS_JAVAC_CONSTANTS,
+ DOT_CLASS_JAVAC_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher dotClassJikesMatcher =
+ new InstructionSequenceMatcher(DOT_CLASS_JIKES_CONSTANTS,
+ DOT_CLASS_JIKES_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher dotClassJavacImplementationMatcher =
+ new InstructionSequenceMatcher(CLASS_FOR_NAME_CONSTANTS,
+ DOT_CLASS_JAVAC_IMPLEMENTATION_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher dotClassJikesImplementationMatcher =
+ new InstructionSequenceMatcher(CLASS_FOR_NAME_CONSTANTS,
+ DOT_CLASS_JIKES_IMPLEMENTATION_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher dotClassJikesImplementationMatcher2 =
+ new InstructionSequenceMatcher(CLASS_FOR_NAME_CONSTANTS,
+ DOT_CLASS_JIKES_IMPLEMENTATION_INSTRUCTIONS2);
+
+
+ // A field acting as a return variable for the visitors.
+ private boolean isClassForNameInvocation;
+
+
+ /**
+ * Creates a new DynamicClassReferenceInitializer that optionally prints
+ * warnings and notes, with optional class specifications for which never
+ * to print notes.
+ */
+ public DynamicClassReferenceInitializer(ClassPool programClassPool,
+ ClassPool libraryClassPool,
+ WarningPrinter missingNotePrinter,
+ WarningPrinter dependencyWarningPrinter,
+ WarningPrinter notePrinter,
+ StringMatcher noteExceptionMatcher)
+ {
+ this.programClassPool = programClassPool;
+ this.libraryClassPool = libraryClassPool;
+ this.missingNotePrinter = missingNotePrinter;
+ this.dependencyWarningPrinter = dependencyWarningPrinter;
+ this.notePrinter = notePrinter;
+ this.noteExceptionMatcher = noteExceptionMatcher;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ // Try to match the Class.forName("SomeClass") construct.
+ instruction.accept(clazz, method, codeAttribute, offset,
+ constantClassForNameMatcher);
+
+ // Did we find a match?
+ if (constantClassForNameMatcher.isMatching())
+ {
+ // Fill out the matched string constant.
+ clazz.constantPoolEntryAccept(constantClassForNameMatcher.matchedConstantIndex(X), this);
+
+ // Don't look for the dynamic construct.
+ classForNameCastMatcher.reset();
+ }
+
+ // Try to match the (SomeClass)Class.forName(someName).newInstance()
+ // construct.
+ instruction.accept(clazz, method, codeAttribute, offset,
+ classForNameCastMatcher);
+
+ // Did we find a match?
+ if (classForNameCastMatcher.isMatching())
+ {
+ // Print out a note about the construct.
+ clazz.constantPoolEntryAccept(classForNameCastMatcher.matchedConstantIndex(X), this);
+ }
+
+ // Try to match the javac .class construct.
+ instruction.accept(clazz, method, codeAttribute, offset,
+ dotClassJavacMatcher);
+
+ // Did we find a match?
+ if (dotClassJavacMatcher.isMatching() &&
+ isDotClassMethodref(clazz, dotClassJavacMatcher.matchedConstantIndex(0)))
+ {
+ // Fill out the matched string constant.
+ clazz.constantPoolEntryAccept(dotClassJavacMatcher.matchedConstantIndex(X), this);
+ }
+
+ // Try to match the jikes .class construct.
+ instruction.accept(clazz, method, codeAttribute, offset,
+ dotClassJikesMatcher);
+
+ // Did we find a match?
+ if (dotClassJikesMatcher.isMatching() &&
+ isDotClassMethodref(clazz, dotClassJikesMatcher.matchedConstantIndex(0)))
+ {
+ // Fill out the matched string constant.
+ clazz.constantPoolEntryAccept(dotClassJikesMatcher.matchedConstantIndex(X), this);
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ /**
+ * Fills out the link to the referenced class.
+ */
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ // Save a reference to the corresponding class.
+ String externalClassName = stringConstant.getString(clazz);
+ String internalClassName = ClassUtil.internalClassName(
+ ClassUtil.externalBaseType(externalClassName));
+
+ stringConstant.referencedClass = findClass(clazz.getName(), internalClassName);
+ }
+
+
+ /**
+ * Prints out a note about the class cast to this class, if applicable.
+ */
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Print out a note about the class cast.
+ if (noteExceptionMatcher == null ||
+ !noteExceptionMatcher.matches(classConstant.getName(clazz)))
+ {
+ notePrinter.print(clazz.getName(),
+ classConstant.getName(clazz),
+ "Note: " +
+ ClassUtil.externalClassName(clazz.getName()) +
+ " calls '(" +
+ ClassUtil.externalClassName(classConstant.getName(clazz)) +
+ ")Class.forName(variable).newInstance()'");
+ }
+ }
+
+
+ /**
+ * Checks whether the referenced method is a .class method.
+ */
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ String methodType = methodrefConstant.getType(clazz);
+
+ // Do the method's class and type match?
+ if (methodType.equals(ClassConstants.INTERNAL_METHOD_TYPE_DOT_CLASS_JAVAC) ||
+ methodType.equals(ClassConstants.INTERNAL_METHOD_TYPE_DOT_CLASS_JIKES))
+ {
+ String methodName = methodrefConstant.getName(clazz);
+
+ // Does the method's name match one of the special names?
+ isClassForNameInvocation =
+ methodName.equals(ClassConstants.INTERNAL_METHOD_NAME_DOT_CLASS_JAVAC) ||
+ methodName.equals(ClassConstants.INTERNAL_METHOD_NAME_DOT_CLASS_JIKES);
+
+ if (isClassForNameInvocation)
+ {
+ return;
+ }
+
+ String className = methodrefConstant.getClassName(clazz);
+
+ // Note that we look for the class by name, since the referenced
+ // class has not been initialized yet.
+ Clazz referencedClass = programClassPool.getClass(className);
+ if (referencedClass != null)
+ {
+ // Check if the code of the referenced method is .class code.
+ // Note that we look for the method by name and type, since the
+ // referenced method has not been initialized yet.
+ referencedClass.methodAccept(methodName,
+ methodType,
+ new AllAttributeVisitor(this));
+ }
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Check whether this is class$(String), as generated by javac, or
+ // class(String, boolean), as generated by jikes, or an optimized
+ // version.
+ isClassForNameInvocation =
+ isDotClassMethodCode(clazz, method, codeAttribute,
+ dotClassJavacImplementationMatcher, 5) ||
+ isDotClassMethodCode(clazz, method, codeAttribute,
+ dotClassJikesImplementationMatcher, 12) ||
+ isDotClassMethodCode(clazz, method, codeAttribute,
+ dotClassJikesImplementationMatcher2, 8);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether the given method reference corresponds to a .class
+ * method, as generated by javac or by jikes.
+ */
+ private boolean isDotClassMethodref(Clazz clazz, int methodrefConstantIndex)
+ {
+ isClassForNameInvocation = false;
+
+ // Check if the code of the referenced method is .class code.
+ clazz.constantPoolEntryAccept(methodrefConstantIndex, this);
+
+ return isClassForNameInvocation;
+ }
+
+
+ /**
+ * Returns whether the first whether the first instructions of the
+ * given code attribute match with the given instruction matcher.
+ */
+ private boolean isDotClassMethodCode(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ InstructionSequenceMatcher codeMatcher,
+ int codeLength)
+ {
+ // Check the minimum code length.
+ if (codeAttribute.u4codeLength < codeLength)
+ {
+ return false;
+ }
+
+ // Check the actual instructions.
+ codeMatcher.reset();
+ codeAttribute.instructionsAccept(clazz, method, 0, codeLength, codeMatcher);
+ return codeMatcher.isMatching();
+ }
+
+
+ /**
+ * Returns the class with the given name, either for the program class pool
+ * or from the library class pool, or null
if it can't be found.
+ */
+ private Clazz findClass(String referencingClassName, String name)
+ {
+ // Is it an array type?
+ if (ClassUtil.isInternalArrayType(name))
+ {
+ // Ignore any primitive array types.
+ if (!ClassUtil.isInternalClassType(name))
+ {
+ return null;
+ }
+
+ // Strip the array part.
+ name = ClassUtil.internalClassNameFromClassType(name);
+ }
+
+ // First look for the class in the program class pool.
+ Clazz clazz = programClassPool.getClass(name);
+
+ // Otherwise look for the class in the library class pool.
+ if (clazz == null)
+ {
+ clazz = libraryClassPool.getClass(name);
+
+ if (clazz == null &&
+ missingNotePrinter != null)
+ {
+ // We didn't find the superclass or interface. Print a note.
+ missingNotePrinter.print(referencingClassName,
+ name,
+ "Note: " +
+ ClassUtil.externalClassName(referencingClassName) +
+ ": can't find dynamically referenced class " +
+ ClassUtil.externalClassName(name));
+ }
+ }
+ else if (dependencyWarningPrinter != null)
+ {
+ // The superclass or interface was found in the program class pool.
+ // Print a warning.
+ dependencyWarningPrinter.print(referencingClassName,
+ name,
+ "Warning: library class " +
+ ClassUtil.externalClassName(referencingClassName) +
+ " depends dynamically on program class " +
+ ClassUtil.externalClassName(name));
+ }
+
+ return clazz;
+ }
+}
diff --git a/src/proguard/classfile/util/DynamicMemberReferenceInitializer.java b/src/proguard/classfile/util/DynamicMemberReferenceInitializer.java
new file mode 100644
index 000000000..23c8d4045
--- /dev/null
+++ b/src/proguard/classfile/util/DynamicMemberReferenceInitializer.java
@@ -0,0 +1,943 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.visitor.*;
+import proguard.util.StringMatcher;
+
+/**
+ * This InstructionVisitor initializes any constant
+ * Class.get[Declared]{Field,Method}
references of all instructions
+ * it visits. More specifically, it fills out the references of string constant
+ * pool entries that refer to a class member in the program class pool or in the
+ * library class pool.
+ *
+ * It optionally prints notes if on usage of
+ * (SomeClass)Class.forName(variable).newInstance()
.
+ *
+ * The class hierarchy and references must be initialized before using this
+ * visitor.
+ *
+ * @see ClassSuperHierarchyInitializer
+ * @see ClassReferenceInitializer
+ *
+ * @author Eric Lafortune
+ */
+public class DynamicMemberReferenceInitializer
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor,
+ MemberVisitor
+{
+ /*
+ private static boolean DEBUG = true;
+ /*/
+ private static final boolean DEBUG = false;
+ //*/
+
+ public static final int CLASS_INDEX = InstructionSequenceMatcher.X;
+ public static final int MEMBER_NAME_INDEX = InstructionSequenceMatcher.Y;
+ public static final int TYPE_CLASS_INDEX = InstructionSequenceMatcher.Z;
+
+ public static final int PARAMETER0_CLASS_INDEX = InstructionSequenceMatcher.A;
+ public static final int PARAMETER1_CLASS_INDEX = InstructionSequenceMatcher.B;
+ public static final int PARAMETER2_CLASS_INDEX = InstructionSequenceMatcher.C;
+ public static final int PARAMETER3_CLASS_INDEX = InstructionSequenceMatcher.D;
+
+
+ private final Constant[] GET_FIELD_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_FIELD),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_FIELD),
+ };
+
+ private final Constant[] GET_DECLARED_FIELD_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_DECLARED_FIELD),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_DECLARED_FIELD),
+ };
+
+ private final Constant[] GET_CONSTRUCTOR_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
+ new Utf8Constant(ClassConstants.INTERNAL_CONSTRUCTOR_NAME_CLASS_GET_CONSTRUCTOR),
+ new Utf8Constant(ClassConstants.INTERNAL_CONSTRUCTOR_TYPE_CLASS_GET_CONSTRUCTOR),
+ };
+
+ private final Constant[] GET_DECLARED_CONSTRUCTOR_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
+ new Utf8Constant(ClassConstants.INTERNAL_CONSTRUCTOR_NAME_CLASS_GET_DECLARED_CONSTRUCTOR),
+ new Utf8Constant(ClassConstants.INTERNAL_CONSTRUCTOR_TYPE_CLASS_GET_DECLARED_CONSTRUCTOR),
+ };
+
+ private final Constant[] GET_METHOD_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_METHOD),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_METHOD),
+ };
+
+ private final Constant[] GET_DECLARED_METHOD_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_CLASS_GET_DECLARED_METHOD),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CLASS_GET_DECLARED_METHOD),
+ };
+
+ private final Constant[] NEW_INTEGER_UPDATER_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_INTEGER_FIELD_UPDATER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_NEW_UPDATER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_NEW_INTEGER_UPDATER),
+ };
+
+ private final Constant[] NEW_LONG_UPDATER_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_LONG_FIELD_UPDATER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_NEW_UPDATER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_NEW_LONG_UPDATER),
+ };
+
+ private final Constant[] NEW_REFERENCE_UPDATER_CONSTANTS = new Constant[]
+ {
+ new MethodrefConstant(1, 2, null, null),
+ new ClassConstant(3, null),
+ new NameAndTypeConstant(4, 5),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_REFERENCE_FIELD_UPDATER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_NEW_UPDATER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_NEW_REFERENCE_UPDATER),
+ };
+
+ // SomeClass.class.get[Declared]Field("someField").
+ private final Instruction[] CONSTANT_GET_FIELD_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+// // SomeClass.class.get[Declared]Constructor(new Class[] {}).
+// private final Instruction[] CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS0 = new Instruction[]
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+// new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+// new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+// new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+// };
+//
+// // SomeClass.class.get[Declared]Constructor(new Class[] { A.class }).
+// private final Instruction[] CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS1 = new Instruction[]
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+// new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+// new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+// new SimpleInstruction(InstructionConstants.OP_DUP),
+// new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+// new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+// new SimpleInstruction(InstructionConstants.OP_AASTORE),
+// new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+// };
+//
+// // SomeClass.class.get[Declared]Constructor(new Class[] { A.class, B.class }).
+// private final Instruction[] CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS2 = new Instruction[]
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+// new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+// new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+// new SimpleInstruction(InstructionConstants.OP_DUP),
+// new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+// new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+// new SimpleInstruction(InstructionConstants.OP_AASTORE),
+// new SimpleInstruction(InstructionConstants.OP_DUP),
+// new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+// new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER1_CLASS_INDEX),
+// new SimpleInstruction(InstructionConstants.OP_AASTORE),
+// new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+// };
+
+ // SomeClass.class.get[Declared]Method("someMethod", new Class[] {}).
+ private final Instruction[] CONSTANT_GET_METHOD_INSTRUCTIONS0 = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // SomeClass.class.get[Declared]Method("someMethod", new Class[] { A.class }).
+ private final Instruction[] CONSTANT_GET_METHOD_INSTRUCTIONS1 = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // SomeClass.class.get[Declared]Method("someMethod", new Class[] { A.class, B.class }).
+ private final Instruction[] CONSTANT_GET_METHOD_INSTRUCTIONS2 = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER1_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // AtomicIntegerFieldUpdater.newUpdater(A.class, "someField").
+ // AtomicLongFieldUpdater.newUpdater(A.class, "someField").
+ private final Instruction[] CONSTANT_NEW_PRIMITIVE_UPDATER_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ };
+
+ // AtomicReferenceFieldUpdater.newUpdater(A.class, B.class, "someField").
+ private final Instruction[] CONSTANT_NEW_REFERENCE_UPDATER_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, CLASS_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_LDC, TYPE_CLASS_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ };
+
+ // get[Declared]Field("someField").
+ private final Instruction[] GET_FIELD_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+// // get[Declared]Constructor(new Class[] {}).
+// private final Instruction[] GET_CONSTRUCTOR_INSTRUCTIONS0 = new Instruction[]
+// {
+// new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+// new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+// new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+// };
+
+ // get[Declared]Constructor(new Class[] { A.class }).
+ private final Instruction[] GET_CONSTRUCTOR_INSTRUCTIONS1 = new Instruction[]
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // get[Declared]Constructor(new Class[] { A.class, B.class }).
+ private final Instruction[] GET_CONSTRUCTOR_INSTRUCTIONS2 = new Instruction[]
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER1_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // get[Declared]Method("someMethod", new Class[] {}).
+ private final Instruction[] GET_METHOD_INSTRUCTIONS0 = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // get[Declared]Method("someMethod", new Class[] { A.class }).
+ private final Instruction[] GET_METHOD_INSTRUCTIONS1 = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // get[Declared]Method("someMethod", new Class[] { A.class, B.class }).
+ private final Instruction[] GET_METHOD_INSTRUCTIONS2 = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+ new ConstantInstruction(InstructionConstants.OP_ANEWARRAY, 1),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER0_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_LDC, PARAMETER1_CLASS_INDEX),
+ new SimpleInstruction(InstructionConstants.OP_AASTORE),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, 0),
+ };
+
+ // AtomicIntegerFieldUpdater.newUpdater(..., "someField").
+ // AtomicLongFieldUpdater.newUpdater(..., "someField").
+ // AtomicReferenceFieldUpdater.newUpdater(..., "someField").
+ private final Instruction[] NEW_UPDATER_INSTRUCTIONS = new Instruction[]
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, MEMBER_NAME_INDEX),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, 0),
+ };
+
+
+ private final ClassPool programClassPool;
+ private final ClassPool libraryClassPool;
+ private final WarningPrinter notePrinter;
+ private final StringMatcher noteFieldExceptionMatcher;
+ private final StringMatcher noteMethodExceptionMatcher;
+
+
+ private final InstructionSequenceMatcher constantGetFieldMatcher =
+ new InstructionSequenceMatcher(GET_FIELD_CONSTANTS,
+ CONSTANT_GET_FIELD_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher constantGetDeclaredFieldMatcher =
+ new InstructionSequenceMatcher(GET_DECLARED_FIELD_CONSTANTS,
+ CONSTANT_GET_FIELD_INSTRUCTIONS);
+
+// private final InstructionSequenceMatcher constantGetConstructorMatcher0 =
+// new InstructionSequenceMatcher(GET_CONSTRUCTOR_CONSTANTS,
+// CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS0);
+//
+// private final InstructionSequenceMatcher constantGetDeclaredConstructorMatcher0 =
+// new InstructionSequenceMatcher(GET_DECLARED_CONSTRUCTOR_CONSTANTS,
+// CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS0);
+//
+// private final InstructionSequenceMatcher constantGetConstructorMatcher1 =
+// new InstructionSequenceMatcher(GET_CONSTRUCTOR_CONSTANTS,
+// CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS1);
+//
+// private final InstructionSequenceMatcher constantGetDeclaredConstructorMatcher1 =
+// new InstructionSequenceMatcher(GET_DECLARED_CONSTRUCTOR_CONSTANTS,
+// CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS1);
+//
+// private final InstructionSequenceMatcher constantGetConstructorMatcher2 =
+// new InstructionSequenceMatcher(GET_CONSTRUCTOR_CONSTANTS,
+// CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS2);
+//
+// private final InstructionSequenceMatcher constantGetDeclaredConstructorMatcher2 =
+// new InstructionSequenceMatcher(GET_DECLARED_CONSTRUCTOR_CONSTANTS,
+// CONSTANT_GET_CONSTRUCTOR_INSTRUCTIONS2);
+
+ private final InstructionSequenceMatcher constantGetMethodMatcher0 =
+ new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
+ CONSTANT_GET_METHOD_INSTRUCTIONS0);
+
+ private final InstructionSequenceMatcher constantGetDeclaredMethodMatcher0 =
+ new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
+ CONSTANT_GET_METHOD_INSTRUCTIONS0);
+
+ private final InstructionSequenceMatcher constantGetMethodMatcher1 =
+ new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
+ CONSTANT_GET_METHOD_INSTRUCTIONS1);
+
+ private final InstructionSequenceMatcher constantGetDeclaredMethodMatcher1 =
+ new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
+ CONSTANT_GET_METHOD_INSTRUCTIONS1);
+
+ private final InstructionSequenceMatcher constantGetMethodMatcher2 =
+ new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
+ CONSTANT_GET_METHOD_INSTRUCTIONS2);
+
+ private final InstructionSequenceMatcher constantGetDeclaredMethodMatcher2 =
+ new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
+ CONSTANT_GET_METHOD_INSTRUCTIONS2);
+
+ private final InstructionSequenceMatcher constantGetIntegerUpdaterMatcher =
+ new InstructionSequenceMatcher(NEW_INTEGER_UPDATER_CONSTANTS,
+ CONSTANT_NEW_PRIMITIVE_UPDATER_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher constantGetLongUpdaterMatcher =
+ new InstructionSequenceMatcher(NEW_LONG_UPDATER_CONSTANTS,
+ CONSTANT_NEW_PRIMITIVE_UPDATER_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher constantGetReferenceUpdaterMatcher =
+ new InstructionSequenceMatcher(NEW_REFERENCE_UPDATER_CONSTANTS,
+ CONSTANT_NEW_REFERENCE_UPDATER_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher getFieldMatcher =
+ new InstructionSequenceMatcher(GET_FIELD_CONSTANTS,
+ GET_FIELD_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher getDeclaredFieldMatcher =
+ new InstructionSequenceMatcher(GET_DECLARED_FIELD_CONSTANTS,
+ GET_FIELD_INSTRUCTIONS);
+
+// private final InstructionSequenceMatcher getConstructorMatcher0 =
+// new InstructionSequenceMatcher(GET_CONSTRUCTOR_CONSTANTS,
+// GET_CONSTRUCTOR_INSTRUCTIONS0);
+//
+// private final InstructionSequenceMatcher getDeclaredConstructorMatcher0 =
+// new InstructionSequenceMatcher(GET_DECLARED_CONSTRUCTOR_CONSTANTS,
+// GET_CONSTRUCTOR_INSTRUCTIONS0);
+
+ private final InstructionSequenceMatcher getConstructorMatcher1 =
+ new InstructionSequenceMatcher(GET_CONSTRUCTOR_CONSTANTS,
+ GET_CONSTRUCTOR_INSTRUCTIONS1);
+
+ private final InstructionSequenceMatcher getDeclaredConstructorMatcher1 =
+ new InstructionSequenceMatcher(GET_DECLARED_CONSTRUCTOR_CONSTANTS,
+ GET_CONSTRUCTOR_INSTRUCTIONS1);
+
+ private final InstructionSequenceMatcher getConstructorMatcher2 =
+ new InstructionSequenceMatcher(GET_CONSTRUCTOR_CONSTANTS,
+ GET_CONSTRUCTOR_INSTRUCTIONS2);
+
+ private final InstructionSequenceMatcher getDeclaredConstructorMatcher2 =
+ new InstructionSequenceMatcher(GET_DECLARED_CONSTRUCTOR_CONSTANTS,
+ GET_CONSTRUCTOR_INSTRUCTIONS2);
+
+ private final InstructionSequenceMatcher getMethodMatcher0 =
+ new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
+ GET_METHOD_INSTRUCTIONS0);
+
+ private final InstructionSequenceMatcher getDeclaredMethodMatcher0 =
+ new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
+ GET_METHOD_INSTRUCTIONS0);
+
+ private final InstructionSequenceMatcher getMethodMatcher1 =
+ new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
+ GET_METHOD_INSTRUCTIONS1);
+
+ private final InstructionSequenceMatcher getDeclaredMethodMatcher1 =
+ new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
+ GET_METHOD_INSTRUCTIONS1);
+
+ private final InstructionSequenceMatcher getMethodMatcher2 =
+ new InstructionSequenceMatcher(GET_METHOD_CONSTANTS,
+ GET_METHOD_INSTRUCTIONS2);
+
+ private final InstructionSequenceMatcher getDeclaredMethodMatcher2 =
+ new InstructionSequenceMatcher(GET_DECLARED_METHOD_CONSTANTS,
+ GET_METHOD_INSTRUCTIONS2);
+
+ private final InstructionSequenceMatcher getIntegerUpdaterMatcher =
+ new InstructionSequenceMatcher(NEW_INTEGER_UPDATER_CONSTANTS,
+ NEW_UPDATER_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher getLongUpdaterMatcher =
+ new InstructionSequenceMatcher(NEW_LONG_UPDATER_CONSTANTS,
+ NEW_UPDATER_INSTRUCTIONS);
+
+ private final InstructionSequenceMatcher getReferenceUpdaterMatcher =
+ new InstructionSequenceMatcher(NEW_REFERENCE_UPDATER_CONSTANTS,
+ NEW_UPDATER_INSTRUCTIONS);
+
+ private final MemberFinder memberFinder = new MemberFinder();
+
+
+ // Fields acting as parameters for the visitors.
+ private Clazz referencedClass;
+ private String descriptor;
+ private boolean isDeclared;
+ private boolean isField;
+
+
+
+ /**
+ * Creates a new DynamicMemberReferenceInitializer.
+ */
+ public DynamicMemberReferenceInitializer(ClassPool programClassPool,
+ ClassPool libraryClassPool,
+ WarningPrinter notePrinter,
+ StringMatcher noteFieldExceptionMatcher,
+ StringMatcher noteMethodExceptionMatcher)
+ {
+ this.programClassPool = programClassPool;
+ this.libraryClassPool = libraryClassPool;
+ this.notePrinter = notePrinter;
+ this.noteFieldExceptionMatcher = noteFieldExceptionMatcher;
+ this.noteMethodExceptionMatcher = noteMethodExceptionMatcher;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ // Try to match the SomeClass.class.getField("someField") construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetFieldMatcher,
+ getFieldMatcher, true, false, null, null);
+
+ // Try to match the SomeClass.class.getDeclaredField("someField") construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetDeclaredFieldMatcher,
+ getDeclaredFieldMatcher, true, true, null, null);
+
+// // Try to match the SomeClass.class.getConstructor(new Class[]
+// // {}) construct.
+// matchGetMember(clazz, method, codeAttribute, offset, instruction,
+// cnull, //onstantGetConstructorMatcher0,
+// getConstructorMatcher0, false, false,
+// ClassConstants.INTERNAL_METHOD_NAME_INIT, null);
+//
+// // Try to match the SomeClass.class.getDeclaredConstructor(new Class[]
+// // {}) construct.
+// matchGetMember(clazz, method, codeAttribute, offset, instruction,
+// null, //constantGetDeclaredConstructorMatcher0,
+// getDeclaredConstructorMatcher0, false, true,
+// ClassConstants.INTERNAL_METHOD_NAME_INIT, null);
+
+ // Try to match the SomeClass.class.getConstructor(new Class[]
+ // { A.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ null, //constantGetConstructorMatcher1,
+ getConstructorMatcher1, false, false,
+ ClassConstants.INTERNAL_METHOD_NAME_INIT, null);
+
+ // Try to match the SomeClass.class.getDeclaredConstructor(new Class[]
+ // { A.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ null, //constantGetDeclaredConstructorMatcher1,
+ getDeclaredConstructorMatcher1, false, true,
+ ClassConstants.INTERNAL_METHOD_NAME_INIT, null);
+
+ // Try to match the SomeClass.class.getConstructor(new Class[]
+ // { A.class, B.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ null, //constantGetConstructorMatcher2,
+ getConstructorMatcher2, false, false,
+ ClassConstants.INTERNAL_METHOD_NAME_INIT, null);
+
+ // Try to match the SomeClass.class.getDeclaredConstructor(new Class[]
+ // { A.class, B.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ null, //constantGetDeclaredConstructorMatcher2,
+ getDeclaredConstructorMatcher2, false, true,
+ ClassConstants.INTERNAL_METHOD_NAME_INIT, null);
+
+ // Try to match the SomeClass.class.getMethod("someMethod", new Class[]
+ // {}) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetMethodMatcher0,
+ getMethodMatcher0, false, false, null, null);
+
+ // Try to match the SomeClass.class.getDeclaredMethod("someMethod",
+ // new Class[] {}) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetDeclaredMethodMatcher0,
+ getDeclaredMethodMatcher0, false, true, null, null);
+
+ // Try to match the SomeClass.class.getMethod("someMethod", new Class[]
+ // { A.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetMethodMatcher1,
+ getMethodMatcher1, false, false, null, null);
+
+ // Try to match the SomeClass.class.getDeclaredMethod("someMethod",
+ // new Class[] { A.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetDeclaredMethodMatcher1,
+ getDeclaredMethodMatcher1, false, true, null, null);
+
+ // Try to match the SomeClass.class.getMethod("someMethod", new Class[]
+ // { A.class, B.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetMethodMatcher2,
+ getMethodMatcher2, false, false, null, null);
+
+ // Try to match the SomeClass.class.getDeclaredMethod("someMethod",
+ // new Class[] { A.class, B.class }) construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetDeclaredMethodMatcher2,
+ getDeclaredMethodMatcher2, false, true, null, null);
+
+ // Try to match the AtomicIntegerFieldUpdater.newUpdater(
+ // SomeClass.class, "someField") construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetIntegerUpdaterMatcher,
+ getIntegerUpdaterMatcher, true, false, null,
+ "" + ClassConstants.INTERNAL_TYPE_INT);
+
+ // Try to match the AtomicLongFieldUpdater.newUpdater(
+ // SomeClass.class, "someField") construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetLongUpdaterMatcher,
+ getLongUpdaterMatcher, true, false, null,
+ "" + ClassConstants.INTERNAL_TYPE_LONG);
+
+ // Try to match the AtomicReferenceFieldUpdater.newUpdater(
+ // SomeClass.class, SomeClass.class, "someField") construct.
+ matchGetMember(clazz, method, codeAttribute, offset, instruction,
+ constantGetReferenceUpdaterMatcher,
+ getReferenceUpdaterMatcher, true, false, null, null);
+ }
+
+
+ /**
+ * Tries to match the next instruction and fills out the string constant
+ * or prints out a note accordingly.
+ */
+ private void matchGetMember(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ int offset,
+ Instruction instruction,
+ InstructionSequenceMatcher constantSequenceMatcher,
+ InstructionSequenceMatcher variableSequenceMatcher,
+ boolean isField,
+ boolean isDeclared,
+ String defaultName,
+ String defaultDescriptor)
+ {
+ if (constantSequenceMatcher != null)
+ {
+ // Try to match the next instruction in the constant sequence.
+ instruction.accept(clazz, method, codeAttribute, offset,
+ constantSequenceMatcher);
+
+ // Did we find a match to fill out the string constant?
+ if (constantSequenceMatcher.isMatching())
+ {
+ initializeStringReference(clazz,
+ constantSequenceMatcher,
+ isField,
+ isDeclared,
+ defaultDescriptor);
+
+ // Don't look for the dynamic construct.
+ variableSequenceMatcher.reset();
+ }
+ }
+
+ // Try to match the next instruction in the variable sequence.
+ instruction.accept(clazz, method, codeAttribute, offset,
+ variableSequenceMatcher);
+
+ // Did we find a match to print out a note?
+ if (variableSequenceMatcher.isMatching())
+ {
+ // Print out a note about the dynamic invocation.
+ printDynamicInvocationNote(clazz,
+ variableSequenceMatcher,
+ isField,
+ isDeclared,
+ defaultName,
+ defaultDescriptor);
+ }
+ }
+
+
+ /**
+ * Initializes the reference of the matched string constant to the
+ * referenced class member and its class.
+ */
+ private void initializeStringReference(Clazz clazz,
+ InstructionSequenceMatcher constantSequenceMatcher,
+ boolean isField,
+ boolean isDeclared,
+ String defaultDescriptor)
+ {
+ this.isField = isField;
+ this.isDeclared = isDeclared;
+
+ // Get the member's class.
+ int classIndex = constantSequenceMatcher.matchedConstantIndex(CLASS_INDEX);
+ clazz.constantPoolEntryAccept(classIndex, this);
+
+ // Get the field's reference type, if applicable.
+ int typeClassIndex = constantSequenceMatcher.matchedConstantIndex(TYPE_CLASS_INDEX);
+ descriptor = typeClassIndex <= 0 ? defaultDescriptor :
+ ClassUtil.internalTypeFromClassName(clazz.getClassName(typeClassIndex));
+
+ // Fill out the matched string constant.
+ int memberNameIndex = constantSequenceMatcher.matchedConstantIndex(MEMBER_NAME_INDEX);
+ clazz.constantPoolEntryAccept(memberNameIndex, this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ /**
+ * Remembers the referenced class.
+ */
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ if (DEBUG)
+ {
+ System.out.println("DynamicMemberReferenceInitializer: ["+clazz.getName()+"] matched class ["+classConstant.getName(clazz)+"]");
+ }
+
+ // Remember the referenced class.
+ referencedClass = ClassUtil.isInternalArrayType(classConstant.getName(clazz)) ?
+ null :
+ classConstant.referencedClass;
+ }
+
+
+ /**
+ * Fills out the link to the referenced class member.
+ */
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ if (referencedClass != null)
+ {
+ String name = stringConstant.getString(clazz);
+
+ if (DEBUG)
+ {
+ System.out.println("DynamicMemberReferenceInitializer: ["+clazz.getName()+"] matched string ["+name+"]");
+ }
+
+ // See if we can find the referenced class member locally, or
+ // somewhere in the hierarchy.
+ Member referencedMember = isDeclared ? isField ?
+ (Member)referencedClass.findField(name, descriptor) :
+ (Member)referencedClass.findMethod(name, descriptor) :
+ (Member)memberFinder.findMember(clazz,
+ referencedClass,
+ name,
+ descriptor,
+ isField);
+ if (referencedMember != null)
+ {
+ stringConstant.referencedMember = referencedMember;
+ stringConstant.referencedClass = isDeclared ?
+ referencedClass :
+ memberFinder.correspondingClass();
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Prints out a note on the matched dynamic invocation, if necessary.
+ */
+ private void printDynamicInvocationNote(Clazz clazz,
+ InstructionSequenceMatcher noteSequenceMatcher,
+ boolean isField,
+ boolean isDeclared,
+ String defaultName,
+ String defaultDescriptor)
+ {
+ // Print out a note about the dynamic invocation.
+ if (notePrinter != null &&
+ notePrinter.accepts(clazz.getName()))
+ {
+ // Is the class member name in the list of exceptions?
+ StringMatcher noteExceptionMatcher = isField ?
+ noteFieldExceptionMatcher :
+ noteMethodExceptionMatcher;
+
+ int memberNameIndex = noteSequenceMatcher.matchedConstantIndex(MEMBER_NAME_INDEX);
+ String memberName = memberNameIndex <= 0 ? defaultName :
+ clazz.getStringString(memberNameIndex);
+
+ if (noteExceptionMatcher == null ||
+ !noteExceptionMatcher.matches(memberName))
+ {
+ // Compose the external member name and partial descriptor.
+ String externalMemberDescription = memberName;
+
+ if (!isField)
+ {
+ externalMemberDescription += '(';
+ for (int count = 0; count < 2; count++)
+ {
+ int memberArgumentIndex = noteSequenceMatcher.matchedConstantIndex(
+ PARAMETER0_CLASS_INDEX + count);
+ if (memberArgumentIndex > 0)
+ {
+ if (count > 0)
+ {
+ externalMemberDescription += ',';
+ }
+ String className = clazz.getClassName(memberArgumentIndex);
+ externalMemberDescription += ClassUtil.isInternalArrayType(className) ?
+ ClassUtil.externalType(className) :
+ ClassUtil.externalClassName(className);
+ }
+ }
+ externalMemberDescription += ')';
+ }
+
+ // Print out the actual note.
+ notePrinter.print(clazz.getName(),
+ "Note: " +
+ ClassUtil.externalClassName(clazz.getName()) +
+ " accesses a " +
+ (isDeclared ? "declared " : "") +
+ (isField ? "field" :
+ memberName.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT) ?
+ "constructor" : "method") +
+ " '" +
+ externalMemberDescription +
+ "' dynamically");
+
+ // Print out notes about potential candidates.
+ ClassVisitor classVisitor;
+
+ if (isField)
+ {
+ classVisitor = defaultDescriptor == null ?
+ new AllFieldVisitor(
+ new MemberNameFilter(memberName, this)) :
+ new AllFieldVisitor(
+ new MemberNameFilter(memberName,
+ new MemberDescriptorFilter(defaultDescriptor, this)));
+ }
+ else
+ {
+ // Compose the partial method descriptor.
+ String methodDescriptor = "(";
+ for (int count = 0; count < 2; count++)
+ {
+ int memberArgumentIndex = noteSequenceMatcher.matchedConstantIndex(PARAMETER0_CLASS_INDEX + count);
+ if (memberArgumentIndex > 0)
+ {
+ String className = clazz.getClassName(memberArgumentIndex);
+ methodDescriptor += ClassUtil.isInternalArrayType(className) ?
+ className :
+ ClassUtil.internalTypeFromClassName(className);
+ }
+ }
+ methodDescriptor += ")L***;";
+
+ classVisitor =
+ new AllMethodVisitor(
+ new MemberNameFilter(memberName,
+ new MemberDescriptorFilter(methodDescriptor, this)));
+ }
+
+ programClassPool.classesAcceptAlphabetically(classVisitor);
+ libraryClassPool.classesAcceptAlphabetically(classVisitor);
+ }
+ }
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (notePrinter.accepts(programClass.getName()))
+ {
+ System.out.println(" Maybe this is program field '" +
+ ClassUtil.externalFullClassDescription(0, programClass.getName()) +
+ " { " +
+ ClassUtil.externalFullFieldDescription(0, programField.getName(programClass), programField.getDescriptor(programClass)) +
+ "; }'");
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (notePrinter.accepts(programClass.getName()))
+ {
+ System.out.println(" Maybe this is program method '" +
+ ClassUtil.externalFullClassDescription(0, programClass.getName()) +
+ " { " +
+ ClassUtil.externalFullMethodDescription(programClass.getName(), 0, programMethod.getName(programClass), programMethod.getDescriptor(programClass)) +
+ "; }'");
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (notePrinter.accepts(libraryClass.getName()))
+ {
+ System.out.println(" Maybe this is library field '" +
+ ClassUtil.externalFullClassDescription(0, libraryClass.getName()) +
+ " { " +
+ ClassUtil.externalFullFieldDescription(0, libraryField.getName(libraryClass), libraryField.getDescriptor(libraryClass)) +
+ "; }'");
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (notePrinter.accepts(libraryClass.getName()))
+ {
+ System.out.println(" Maybe this is library method '" +
+ ClassUtil.externalFullClassDescription(0, libraryClass.getName()) +
+ " { " +
+ ClassUtil.externalFullMethodDescription(libraryClass.getName(), 0, libraryMethod.getName(libraryClass), libraryMethod.getDescriptor(libraryClass)) +
+ "; }'");
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/util/EnumFieldReferenceInitializer.java b/src/proguard/classfile/util/EnumFieldReferenceInitializer.java
new file mode 100644
index 000000000..dae6db261
--- /dev/null
+++ b/src/proguard/classfile/util/EnumFieldReferenceInitializer.java
@@ -0,0 +1,150 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.*;
+import proguard.classfile.visitor.*;
+import proguard.util.StringMatcher;
+
+/**
+ * This ElementValueVisitor initializes the field references of the
+ * EnumConstantElementValue instances that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class EnumFieldReferenceInitializer
+extends SimplifiedVisitor
+implements ElementValueVisitor,
+ InstructionVisitor,
+ ConstantVisitor
+{
+ /*
+ private static boolean DEBUG = true;
+ /*/
+ private static final boolean DEBUG = false;
+ //*/
+
+ private MemberVisitor enumFieldFinder = new AllAttributeVisitor(
+ new AllInstructionVisitor(this));
+
+ // Fields acting as parameters and return values for the visitors.
+ private String enumTypeName;
+ private String enumConstantName;
+ private boolean enumConstantNameFound;
+ private Clazz referencedEnumClass;
+ private Field referencedEnumField;
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitAnyElementValue(Clazz clazz, Annotation annotation, ElementValue elementValue) {}
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+
+ if (enumConstantElementValue.referencedClasses != null &&
+ enumConstantElementValue.referencedClasses.length > 0)
+ {
+ referencedEnumClass = enumConstantElementValue.referencedClasses[0];
+ if (referencedEnumClass != null)
+ {
+ // Try to find the enum field through the static enum
+ // initialization code (at least for program classes).
+ enumTypeName = enumConstantElementValue.getTypeName(clazz);
+ enumConstantName = enumConstantElementValue.getConstantName(clazz);
+ referencedEnumField = null;
+ referencedEnumClass.methodAccept(ClassConstants.INTERNAL_METHOD_NAME_CLINIT,
+ ClassConstants.INTERNAL_METHOD_TYPE_CLINIT,
+ enumFieldFinder);
+
+ // Otherwise try to find the enum field through its name.
+ // The constant name could be different from the field name, if
+ // the latter is already obfuscated.
+ if (referencedEnumField == null)
+ {
+ referencedEnumField =
+ referencedEnumClass.findField(enumConstantName,
+ enumTypeName);
+ }
+
+ if (DEBUG)
+ {
+ System.out.println("EnumFieldReferenceInitializer: ["+referencedEnumClass.getName()+"."+enumConstantName+"] -> "+referencedEnumField);
+ }
+
+ enumConstantElementValue.referencedField = referencedEnumField;
+ }
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ switch (constantInstruction.opcode)
+ {
+ case InstructionConstants.OP_LDC:
+ case InstructionConstants.OP_LDC_W:
+ case InstructionConstants.OP_PUTSTATIC:
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ break;
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ enumConstantNameFound =
+ enumConstantName.equals(stringConstant.getString(clazz));
+ }
+
+
+ public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
+ {
+ if (enumConstantNameFound)
+ {
+ if (enumTypeName.equals(fieldrefConstant.getType(clazz)))
+ {
+ referencedEnumField = (Field)fieldrefConstant.referencedMember;
+ }
+
+ enumConstantNameFound = false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/util/ExternalTypeEnumeration.java b/src/proguard/classfile/util/ExternalTypeEnumeration.java
new file mode 100644
index 000000000..e5b706741
--- /dev/null
+++ b/src/proguard/classfile/util/ExternalTypeEnumeration.java
@@ -0,0 +1,106 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.ClassConstants;
+
+
+/**
+ * An ExternalTypeEnumeration
provides an enumeration of all
+ * types listed in a given external descriptor string. The method name can
+ * be retrieved separately.
+ *
+ * A
+ * Note that before JDK 1.5,
+ * If conflicting access flags (public/private/protected) are specified,
+ * having one of them set will be considered sufficient.
+ *
+ * @see ClassConstants
+ *
+ * @author Eric Lafortune
+ */
+public class MemberAccessFilter
+implements MemberVisitor
+{
+ // A mask of conflicting access flags. These are interpreted in a special
+ // way if more of them are required at the same time. In that case, one
+ // of them being set is sufficient.
+ private static final int ACCESS_MASK =
+ ClassConstants.INTERNAL_ACC_PUBLIC |
+ ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_PROTECTED;
+
+ private final int requiredSetAccessFlags;
+ private final int requiredUnsetAccessFlags;
+ private final int requiredOneSetAccessFlags;
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MemberAccessFilter.
+ * @param requiredSetAccessFlags the class access flags that should be
+ * set.
+ * @param requiredUnsetAccessFlags the class access flags that should be
+ * unset.
+ * @param memberVisitor the
+Why the visitor pattern? Class files frequently contain lists of elements of
+various mixed types: class items, constant pool entries, attributes,...
+These lists and types are largely fixed; they won't change much in future
+releases of the Java class file specifications. On the other hand, the kinds
+of operations that we may wish to perform on the class files may change and
+expand. We want to separate the objects and the operations performed upon them.
+This is a good place to use the visitor pattern.
+
+Visitor interfaces avoid having to do series of
+As already mentioned, the main advantage is avoiding lots of
+
+A disadvantage is that the visitor methods always get the same names, specified
+by the visitor interface. These names aren't descriptive at all, making code
+harder to read. It's the visitor classes that describe the operations now.
+
+Also, the visitor methods always have the same parameters and return values, as
+specified by the visitor interfaces. Passing additional parameters is done by
+means of extra fields in the visitor, which is somewhat of a kludge.
+
+Because objects (the visitor accepters) and the operations performed upon them
+(the visitors) are now separated, it becomes harder to associate some state
+with the objects. For convenience, we always provide an extra visitor
+info field in visitor accepters, in which visitors can put any temporary
+information they want.
+
diff --git a/src/proguard/evaluation/BasicBranchUnit.java b/src/proguard/evaluation/BasicBranchUnit.java
new file mode 100644
index 000000000..127e92241
--- /dev/null
+++ b/src/proguard/evaluation/BasicBranchUnit.java
@@ -0,0 +1,126 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.evaluation.value.InstructionOffsetValue;
+
+/**
+ * This BranchUnit remembers the branch unit commands that are invoked on it.
+ * I doesn't consider conditions when branching.
+ *
+ * @author Eric Lafortune
+ */
+public class BasicBranchUnit
+implements BranchUnit
+{
+ private boolean wasCalled;
+ private InstructionOffsetValue traceBranchTargets;
+
+
+ /**
+ * Resets the flag that tells whether any of the branch unit commands was
+ * called.
+ */
+ public void resetCalled()
+ {
+ wasCalled = false;
+ }
+
+ /**
+ * Sets the flag that tells whether any of the branch unit commands was
+ * called.
+ */
+ protected void setCalled()
+ {
+ wasCalled = true;
+ }
+
+ /**
+ * Returns whether any of the branch unit commands was called.
+ */
+ public boolean wasCalled()
+ {
+ return wasCalled;
+ }
+
+
+ /**
+ * Sets the initial branch targets, which will be updated as the branch
+ * methods of the branch unit are called.
+ */
+ public void setTraceBranchTargets(InstructionOffsetValue branchTargets)
+ {
+ this.traceBranchTargets = branchTargets;
+ }
+
+ public InstructionOffsetValue getTraceBranchTargets()
+ {
+ return traceBranchTargets;
+ }
+
+
+ // Implementations for BranchUnit.
+
+ public void branch(Clazz clazz,
+ CodeAttribute codeAttribute,
+ int offset,
+ int branchTarget)
+ {
+ // Override the branch targets.
+ traceBranchTargets = new InstructionOffsetValue(branchTarget);
+
+ wasCalled = true;
+ }
+
+
+ public void branchConditionally(Clazz clazz,
+ CodeAttribute codeAttribute,
+ int offset,
+ int branchTarget,
+ int conditional)
+ {
+ // Accumulate the branch targets.
+ traceBranchTargets =
+ traceBranchTargets.generalize(new InstructionOffsetValue(branchTarget)).instructionOffsetValue();
+
+ wasCalled = true;
+ }
+
+
+ public void returnFromMethod()
+ {
+ // Stop processing this block.
+ traceBranchTargets = InstructionOffsetValue.EMPTY_VALUE;
+
+ wasCalled = true;
+ }
+
+
+ public void throwException()
+ {
+ // Stop processing this block.
+ traceBranchTargets = InstructionOffsetValue.EMPTY_VALUE;
+
+ wasCalled = true;
+ }
+}
diff --git a/src/proguard/evaluation/BasicInvocationUnit.java b/src/proguard/evaluation/BasicInvocationUnit.java
new file mode 100644
index 000000000..474556c2f
--- /dev/null
+++ b/src/proguard/evaluation/BasicInvocationUnit.java
@@ -0,0 +1,425 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.evaluation.value.*;
+
+/**
+ * This InvocationUnit sets up the variables for entering a method,
+ * and it updates the stack for the invocation of a class member,
+ * using simple values.
+ *
+ * @author Eric Lafortune
+ */
+public class BasicInvocationUnit
+extends SimplifiedVisitor
+implements InvocationUnit,
+ ConstantVisitor,
+ MemberVisitor
+{
+ protected final ValueFactory valueFactory;
+
+ // Fields acting as parameters between the visitor methods.
+ private boolean isStatic;
+ private boolean isLoad;
+ private Stack stack;
+ private Clazz returnTypeClass;
+
+
+ /**
+ * Creates a new BasicInvocationUnit with the given value factory.
+ */
+ public BasicInvocationUnit(ValueFactory valueFactory)
+ {
+ this.valueFactory = valueFactory;
+ }
+
+
+ // Implementations for InvocationUnit.
+
+ public void enterMethod(Clazz clazz, Method method, Variables variables)
+ {
+ String descriptor = method.getDescriptor(clazz);
+
+ // Initialize the parameters.
+ boolean isStatic =
+ (method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0;
+
+ // Count the number of parameters, taking into account their categories.
+ int parameterSize = ClassUtil.internalMethodParameterSize(descriptor, isStatic);
+
+ // Reuse the existing parameters object, ensuring the right size.
+ variables.reset(parameterSize);
+
+ // Go over the parameters again.
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(descriptor);
+
+ int parameterIndex = 0;
+ int variableIndex = 0;
+
+ // Put the 'this' reference in variable 0.
+ if (!isStatic)
+ {
+ // Get the reference value.
+ Value value = getMethodParameterValue(clazz,
+ method,
+ parameterIndex++,
+ ClassUtil.internalTypeFromClassName(clazz.getName()),
+ clazz);
+
+ // Store the value in variable 0.
+ variables.store(variableIndex++, value);
+ }
+
+ Clazz[] referencedClasses = ((ProgramMethod)method).referencedClasses;
+ int referencedClassIndex = 0;
+
+ // Set up the variables corresponding to the parameter types and values.
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ String type = internalTypeEnumeration.nextType();
+
+ Clazz referencedClass = referencedClasses != null &&
+ ClassUtil.isInternalClassType(type) ?
+ referencedClasses[referencedClassIndex++] :
+ null;
+
+ // Get the parameter value.
+ Value value = getMethodParameterValue(clazz,
+ method,
+ parameterIndex++,
+ type,
+ referencedClass);
+
+ // Store the value in the corresponding variable.
+ variables.store(variableIndex++, value);
+
+ // Increment the variable index again for Category 2 values.
+ if (value.isCategory2())
+ {
+ variableIndex++;
+ }
+ }
+ }
+
+
+ public void exitMethod(Clazz clazz, Method method, Value returnValue)
+ {
+ setMethodReturnValue(clazz, method, returnValue);
+ }
+
+
+ public void invokeMember(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction, Stack stack)
+ {
+ int constantIndex = constantInstruction.constantIndex;
+
+ switch (constantInstruction.opcode)
+ {
+ case InstructionConstants.OP_GETSTATIC:
+ isStatic = true;
+ isLoad = true;
+ break;
+
+ case InstructionConstants.OP_PUTSTATIC:
+ isStatic = true;
+ isLoad = false;
+ break;
+
+ case InstructionConstants.OP_GETFIELD:
+ isStatic = false;
+ isLoad = true;
+ break;
+
+ case InstructionConstants.OP_PUTFIELD:
+ isStatic = false;
+ isLoad = false;
+ break;
+
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEDYNAMIC:
+ isStatic = true;
+ break;
+
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ isStatic = false;
+ break;
+ }
+
+ // Pop the parameters and push the return value.
+ this.stack = stack;
+ clazz.constantPoolEntryAccept(constantIndex, this);
+ this.stack = null;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
+ {
+ // Pop the field value, if applicable.
+ if (!isLoad)
+ {
+ setFieldValue(clazz, fieldrefConstant, stack.pop());
+ }
+
+ // Pop the reference value, if applicable.
+ if (!isStatic)
+ {
+ setFieldClassValue(clazz, fieldrefConstant, stack.apop());
+ }
+
+ // Push the field value, if applicable.
+ if (isLoad)
+ {
+ String type = fieldrefConstant.getType(clazz);
+
+ stack.push(getFieldValue(clazz, fieldrefConstant, type));
+ }
+ }
+
+
+ public void visitAnyMethodrefConstant(Clazz clazz, RefConstant methodrefConstant)
+ {
+ String type = methodrefConstant.getType(clazz);
+
+ // Count the number of parameters.
+ int parameterCount = ClassUtil.internalMethodParameterCount(type);
+ if (!isStatic)
+ {
+ parameterCount++;
+ }
+
+ // Pop the parameters and the class reference, in reverse order.
+ for (int parameterIndex = parameterCount-1; parameterIndex >= 0; parameterIndex--)
+ {
+ setMethodParameterValue(clazz, methodrefConstant, parameterIndex, stack.pop());
+ }
+
+ // Push the return value, if applicable.
+ String returnType = ClassUtil.internalMethodReturnType(type);
+ if (returnType.charAt(0) != ClassConstants.INTERNAL_TYPE_VOID)
+ {
+ stack.push(getMethodReturnValue(clazz, methodrefConstant, returnType));
+ }
+ }
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ String type = invokeDynamicConstant.getType(clazz);
+
+ // Count the number of parameters.
+ int parameterCount = ClassUtil.internalMethodParameterCount(type);
+ if (!isStatic)
+ {
+ parameterCount++;
+ }
+
+ // Pop the parameters and the class reference, in reverse order.
+ for (int parameterIndex = parameterCount-1; parameterIndex >= 0; parameterIndex--)
+ {
+ stack.pop();
+ }
+
+ // Push the return value, if applicable.
+ String returnType = ClassUtil.internalMethodReturnType(type);
+ if (returnType.charAt(0) != ClassConstants.INTERNAL_TYPE_VOID)
+ {
+ stack.push(getMethodReturnValue(clazz, invokeDynamicConstant, returnType));
+ }
+ }
+
+
+ /**
+ * Sets the class through which the specified field is accessed.
+ */
+ protected void setFieldClassValue(Clazz clazz,
+ RefConstant refConstant,
+ ReferenceValue value)
+ {
+ // We don't care about the new value.
+ }
+
+
+ /**
+ * Returns the class though which the specified field is accessed.
+ */
+ protected Value getFieldClassValue(Clazz clazz,
+ RefConstant refConstant,
+ String type)
+ {
+ // Try to figure out the class of the return type.
+ returnTypeClass = null;
+ refConstant.referencedMemberAccept(this);
+
+ return valueFactory.createValue(type,
+ returnTypeClass,
+ true);
+ }
+
+
+ /**
+ * Sets the value of the specified field.
+ */
+ protected void setFieldValue(Clazz clazz,
+ RefConstant refConstant,
+ Value value)
+ {
+ // We don't care about the new field value.
+ }
+
+
+ /**
+ * Returns the value of the specified field.
+ */
+ protected Value getFieldValue(Clazz clazz,
+ RefConstant refConstant,
+ String type)
+ {
+ // Try to figure out the class of the return type.
+ returnTypeClass = null;
+ refConstant.referencedMemberAccept(this);
+
+ return valueFactory.createValue(type,
+ returnTypeClass,
+ true);
+ }
+
+
+ /**
+ * Sets the value of the specified method parameter.
+ */
+ protected void setMethodParameterValue(Clazz clazz,
+ RefConstant refConstant,
+ int parameterIndex,
+ Value value)
+ {
+ // We don't care about the parameter value.
+ }
+
+
+ /**
+ * Returns the value of the specified method parameter.
+ */
+ protected Value getMethodParameterValue(Clazz clazz,
+ Method method,
+ int parameterIndex,
+ String type,
+ Clazz referencedClass)
+ {
+ return valueFactory.createValue(type, referencedClass, true);
+ }
+
+
+ /**
+ * Sets the return value of the specified method.
+ */
+ protected void setMethodReturnValue(Clazz clazz,
+ Method method,
+ Value value)
+ {
+ // We don't care about the return value.
+ }
+
+
+ /**
+ * Returns the return value of the specified method.
+ */
+ protected Value getMethodReturnValue(Clazz clazz,
+ RefConstant refConstant,
+ String type)
+ {
+ // Try to figure out the class of the return type.
+ returnTypeClass = null;
+ refConstant.referencedMemberAccept(this);
+
+ return valueFactory.createValue(type,
+ returnTypeClass,
+ true);
+ }
+
+
+ /**
+ * Returns the return value of the specified method.
+ */
+ protected Value getMethodReturnValue(Clazz clazz,
+ InvokeDynamicConstant invokeDynamicConstant,
+ String type)
+ {
+ // Try to figure out the class of the return type.
+ Clazz[] referencedClasses = invokeDynamicConstant.referencedClasses;
+
+ Clazz returnTypeClass = referencedClasses == null ? null :
+ referencedClasses[referencedClasses.length - 1];
+
+ return valueFactory.createValue(type,
+ returnTypeClass,
+ true);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ returnTypeClass = programField.referencedClass;
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ Clazz[] referencedClasses = programMethod.referencedClasses;
+ if (referencedClasses != null)
+ {
+ returnTypeClass = referencedClasses[referencedClasses.length - 1];
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass programClass, LibraryField programField)
+ {
+ returnTypeClass = programField.referencedClass;
+ }
+
+
+ public void visitLibraryMethod(LibraryClass programClass, LibraryMethod programMethod)
+ {
+ Clazz[] referencedClasses = programMethod.referencedClasses;
+ if (referencedClasses != null)
+ {
+ returnTypeClass = referencedClasses[referencedClasses.length - 1];
+ }
+ }
+
+
+// public void visitLibraryMember(LibraryClass libraryClass, LibraryMember libraryMember)
+// {
+// }
+}
diff --git a/src/proguard/evaluation/BranchUnit.java b/src/proguard/evaluation/BranchUnit.java
new file mode 100644
index 000000000..a381da760
--- /dev/null
+++ b/src/proguard/evaluation/BranchUnit.java
@@ -0,0 +1,63 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.CodeAttribute;
+
+/**
+ * This InstructionVisitor evaluates the instructions that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public interface BranchUnit
+{
+ /**
+ * Sets the new instruction offset.
+ */
+ public void branch(Clazz clazz,
+ CodeAttribute codeAttribute,
+ int offset,
+ int branchTarget);
+
+
+ /**
+ * Sets the new instruction offset, depending on the certainty of the
+ * conditional branch.
+ */
+ public void branchConditionally(Clazz clazz,
+ CodeAttribute codeAttribute,
+ int offset,
+ int branchTarget,
+ int conditional);
+
+
+ /**
+ * Returns from the method with the given value.
+ */
+ public void returnFromMethod();
+
+
+ /**
+ * Handles the throwing of an exception.
+ */
+ public void throwException();
+}
diff --git a/src/proguard/evaluation/ClassConstantValueFactory.java b/src/proguard/evaluation/ClassConstantValueFactory.java
new file mode 100644
index 000000000..1c418c288
--- /dev/null
+++ b/src/proguard/evaluation/ClassConstantValueFactory.java
@@ -0,0 +1,53 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.evaluation.value.*;
+
+/**
+ * This class creates java.lang.Class ReferenceValue instances that correspond
+ * to specified constant pool entries.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassConstantValueFactory
+extends ConstantValueFactory
+{
+ public ClassConstantValueFactory(ValueFactory valueFactory)
+ {
+ super(valueFactory);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Create a Class reference instead of a reference to the class.
+ value = valueFactory.createReferenceValue(ClassConstants.INTERNAL_NAME_JAVA_LANG_CLASS,
+ classConstant.javaLangClassClass,
+ false);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/ConstantValueFactory.java b/src/proguard/evaluation/ConstantValueFactory.java
new file mode 100644
index 000000000..0afb20c1b
--- /dev/null
+++ b/src/proguard/evaluation/ConstantValueFactory.java
@@ -0,0 +1,113 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.evaluation.value.*;
+
+/**
+ * This class creates Value instance that correspond to specified constant pool
+ * entries.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantValueFactory
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ protected final ValueFactory valueFactory;
+
+ // Field acting as a parameter for the ConstantVisitor methods.
+ protected Value value;
+
+
+ public ConstantValueFactory(ValueFactory valueFactory)
+ {
+ this.valueFactory = valueFactory;
+ }
+
+
+ /**
+ * Returns the Value of the constant pool element at the given index.
+ */
+ public Value constantValue(Clazz clazz,
+ int constantIndex)
+ {
+ // Visit the constant pool entry to get its return value.
+ clazz.constantPoolEntryAccept(constantIndex, this);
+
+ return value;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)
+ {
+ value = valueFactory.createIntegerValue(integerConstant.getValue());
+ }
+
+ public void visitLongConstant(Clazz clazz, LongConstant longConstant)
+ {
+ value = valueFactory.createLongValue(longConstant.getValue());
+ }
+
+ public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)
+ {
+ value = valueFactory.createFloatValue(floatConstant.getValue());
+ }
+
+ public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)
+ {
+ value = valueFactory.createDoubleValue(doubleConstant.getValue());
+ }
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ value = valueFactory.createReferenceValue(ClassConstants.INTERNAL_NAME_JAVA_LANG_STRING,
+ stringConstant.javaLangStringClass,
+ false);
+ }
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ value = valueFactory.createReferenceValue(ClassConstants.INTERNAL_NAME_JAVA_LANG_INVOKE_METHOD_HANDLE,
+ methodHandleConstant.javaLangInvokeMethodHandleClass,
+ false);
+ }
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ value = valueFactory.createReferenceValue(classConstant.getName(clazz),
+ classConstant.referencedClass,
+ false);
+ }
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
+ {
+ value = valueFactory.createReferenceValue(ClassConstants.INTERNAL_NAME_JAVA_LANG_INVOKE_METHOD_TYPE,
+ methodTypeConstant.javaLangInvokeMethodTypeClass,
+ false);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/InvocationUnit.java b/src/proguard/evaluation/InvocationUnit.java
new file mode 100644
index 000000000..e526b356d
--- /dev/null
+++ b/src/proguard/evaluation/InvocationUnit.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.ConstantInstruction;
+import proguard.evaluation.value.Value;
+
+/**
+ * This interface sets up the variables for entering a method,
+ * and it updates the stack for the invocation of a class member.
+ *
+ * @author Eric Lafortune
+ */
+public interface InvocationUnit
+{
+ /**
+ * Sets up the given variables for entering the given method.
+ */
+ public void enterMethod(Clazz clazz,
+ Method method,
+ Variables variables);
+
+
+ /**
+ * Exits the given method with the given return value.
+ */
+ public void exitMethod(Clazz clazz,
+ Method method,
+ Value returnValue);
+
+
+ /**
+ * Updates the given stack corresponding to the execution of the given
+ * field or method reference instruction.
+ */
+ public void invokeMember(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ int offset,
+ ConstantInstruction constantInstruction,
+ Stack stack);
+}
diff --git a/src/proguard/evaluation/Processor.java b/src/proguard/evaluation/Processor.java
new file mode 100644
index 000000000..3bfc5f373
--- /dev/null
+++ b/src/proguard/evaluation/Processor.java
@@ -0,0 +1,908 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.evaluation.value.*;
+
+/**
+ * This InstructionVisitor executes the instructions that it visits on a given
+ * local variable frame and stack.
+ *
+ * @author Eric Lafortune
+ */
+public class Processor
+implements InstructionVisitor
+{
+ private final Variables variables;
+ private final Stack stack;
+ private final ValueFactory valueFactory;
+ private final BranchUnit branchUnit;
+ private final InvocationUnit invocationUnit;
+
+ private final ConstantValueFactory constantValueFactory;
+ private final ClassConstantValueFactory classConstantValueFactory;
+
+
+ /**
+ * Creates a new processor that operates on the given environment.
+ * @param variables the local variable frame.
+ * @param stack the local stack.
+ * @param branchUnit the class that can affect the program counter.
+ * @param invocationUnit the class that can access other program members.
+ */
+ public Processor(Variables variables,
+ Stack stack,
+ ValueFactory valueFactory,
+ BranchUnit branchUnit,
+ InvocationUnit invocationUnit)
+ {
+ this.variables = variables;
+ this.stack = stack;
+ this.valueFactory = valueFactory;
+ this.branchUnit = branchUnit;
+ this.invocationUnit = invocationUnit;
+
+ constantValueFactory = new ConstantValueFactory(valueFactory);
+ classConstantValueFactory = new ClassConstantValueFactory(valueFactory);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ switch (simpleInstruction.opcode)
+ {
+ case InstructionConstants.OP_NOP:
+ break;
+
+ case InstructionConstants.OP_ACONST_NULL:
+ stack.push(valueFactory.createReferenceValueNull());
+ break;
+
+ case InstructionConstants.OP_ICONST_M1:
+ case InstructionConstants.OP_ICONST_0:
+ case InstructionConstants.OP_ICONST_1:
+ case InstructionConstants.OP_ICONST_2:
+ case InstructionConstants.OP_ICONST_3:
+ case InstructionConstants.OP_ICONST_4:
+ case InstructionConstants.OP_ICONST_5:
+ case InstructionConstants.OP_BIPUSH:
+ case InstructionConstants.OP_SIPUSH:
+ stack.push(valueFactory.createIntegerValue(simpleInstruction.constant));
+ break;
+
+ case InstructionConstants.OP_LCONST_0:
+ case InstructionConstants.OP_LCONST_1:
+ stack.push(valueFactory.createLongValue(simpleInstruction.constant));
+ break;
+
+ case InstructionConstants.OP_FCONST_0:
+ case InstructionConstants.OP_FCONST_1:
+ case InstructionConstants.OP_FCONST_2:
+ stack.push(valueFactory.createFloatValue((float)simpleInstruction.constant));
+ break;
+
+ case InstructionConstants.OP_DCONST_0:
+ case InstructionConstants.OP_DCONST_1:
+ stack.push(valueFactory.createDoubleValue((double)simpleInstruction.constant));
+ break;
+
+ case InstructionConstants.OP_IALOAD:
+ case InstructionConstants.OP_BALOAD:
+ case InstructionConstants.OP_CALOAD:
+ case InstructionConstants.OP_SALOAD:
+ stack.ipop();
+ stack.apop();
+ stack.push(valueFactory.createIntegerValue());
+ break;
+
+ case InstructionConstants.OP_LALOAD:
+ stack.ipop();
+ stack.apop();
+ stack.push(valueFactory.createLongValue());
+ break;
+
+ case InstructionConstants.OP_FALOAD:
+ stack.ipop();
+ stack.apop();
+ stack.push(valueFactory.createFloatValue());
+ break;
+
+ case InstructionConstants.OP_DALOAD:
+ stack.ipop();
+ stack.apop();
+ stack.push(valueFactory.createDoubleValue());
+ break;
+
+ case InstructionConstants.OP_AALOAD:
+ {
+ IntegerValue arrayIndex = stack.ipop();
+ ReferenceValue arrayReference = stack.apop();
+ stack.push(arrayReference.arrayLoad(arrayIndex, valueFactory));
+ break;
+ }
+
+ case InstructionConstants.OP_IASTORE:
+ case InstructionConstants.OP_BASTORE:
+ case InstructionConstants.OP_CASTORE:
+ case InstructionConstants.OP_SASTORE:
+ stack.ipop();
+ stack.ipop();
+ stack.apop();
+ break;
+
+ case InstructionConstants.OP_LASTORE:
+ stack.lpop();
+ stack.ipop();
+ stack.apop();
+ break;
+
+ case InstructionConstants.OP_FASTORE:
+ stack.fpop();
+ stack.ipop();
+ stack.apop();
+ break;
+
+ case InstructionConstants.OP_DASTORE:
+ stack.dpop();
+ stack.ipop();
+ stack.apop();
+ break;
+
+ case InstructionConstants.OP_AASTORE:
+ stack.apop();
+ stack.ipop();
+ stack.apop();
+ break;
+
+ case InstructionConstants.OP_POP:
+ stack.pop1();
+ break;
+
+ case InstructionConstants.OP_POP2:
+ stack.pop2();
+ break;
+
+ case InstructionConstants.OP_DUP:
+ stack.dup();
+ break;
+
+ case InstructionConstants.OP_DUP_X1:
+ stack.dup_x1();
+ break;
+
+ case InstructionConstants.OP_DUP_X2:
+ stack.dup_x2();
+ break;
+
+ case InstructionConstants.OP_DUP2:
+ stack.dup2();
+ break;
+
+ case InstructionConstants.OP_DUP2_X1:
+ stack.dup2_x1();
+ break;
+
+ case InstructionConstants.OP_DUP2_X2:
+ stack.dup2_x2();
+ break;
+
+ case InstructionConstants.OP_SWAP:
+ stack.swap();
+ break;
+
+ case InstructionConstants.OP_IADD:
+ stack.push(stack.ipop().add(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LADD:
+ stack.push(stack.lpop().add(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_FADD:
+ stack.push(stack.fpop().add(stack.fpop()));
+ break;
+
+ case InstructionConstants.OP_DADD:
+ stack.push(stack.dpop().add(stack.dpop()));
+ break;
+
+ case InstructionConstants.OP_ISUB:
+ stack.push(stack.ipop().subtractFrom(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LSUB:
+ stack.push(stack.lpop().subtractFrom(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_FSUB:
+ stack.push(stack.fpop().subtractFrom(stack.fpop()));
+ break;
+
+ case InstructionConstants.OP_DSUB:
+ stack.push(stack.dpop().subtractFrom(stack.dpop()));
+ break;
+
+ case InstructionConstants.OP_IMUL:
+ stack.push(stack.ipop().multiply(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LMUL:
+ stack.push(stack.lpop().multiply(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_FMUL:
+ stack.push(stack.fpop().multiply(stack.fpop()));
+ break;
+
+ case InstructionConstants.OP_DMUL:
+ stack.push(stack.dpop().multiply(stack.dpop()));
+ break;
+
+ case InstructionConstants.OP_IDIV:
+ try
+ {
+ stack.push(stack.ipop().divideOf(stack.ipop()));
+ }
+ catch (ArithmeticException ex)
+ {
+ stack.push(valueFactory.createIntegerValue());
+ // TODO: Forward ArithmeticExceptions.
+ //stack.clear();
+ //stack.push(valueFactory.createReference(false));
+ //branchUnit.throwException();
+ }
+ break;
+
+ case InstructionConstants.OP_LDIV:
+ try
+ {
+ stack.push(stack.lpop().divideOf(stack.lpop()));
+ }
+ catch (ArithmeticException ex)
+ {
+ stack.push(valueFactory.createLongValue());
+ // TODO: Forward ArithmeticExceptions.
+ //stack.clear();
+ //stack.push(valueFactory.createReference(false));
+ //branchUnit.throwException();
+ }
+ break;
+
+ case InstructionConstants.OP_FDIV:
+ stack.push(stack.fpop().divideOf(stack.fpop()));
+ break;
+
+ case InstructionConstants.OP_DDIV:
+ stack.push(stack.dpop().divideOf(stack.dpop()));
+ break;
+
+ case InstructionConstants.OP_IREM:
+ try
+ {
+ stack.push(stack.ipop().remainderOf(stack.ipop()));
+ }
+ catch (ArithmeticException ex)
+ {
+ stack.push(valueFactory.createIntegerValue());
+ // TODO: Forward ArithmeticExceptions.
+ //stack.clear();
+ //stack.push(valueFactory.createReference(false));
+ //branchUnit.throwException();
+ }
+ break;
+
+ case InstructionConstants.OP_LREM:
+ try
+ {
+ stack.push(stack.lpop().remainderOf(stack.lpop()));
+ }
+ catch (ArithmeticException ex)
+ {
+ stack.push(valueFactory.createLongValue());
+ // TODO: Forward ArithmeticExceptions.
+ //stack.clear();
+ //stack.push(valueFactory.createReference(false));
+ //branchUnit.throwException();
+ }
+ break;
+
+ case InstructionConstants.OP_FREM:
+ stack.push(stack.fpop().remainderOf(stack.fpop()));
+ break;
+
+ case InstructionConstants.OP_DREM:
+ stack.push(stack.dpop().remainderOf(stack.dpop()));
+ break;
+
+ case InstructionConstants.OP_INEG:
+ stack.push(stack.ipop().negate());
+ break;
+
+ case InstructionConstants.OP_LNEG:
+ stack.push(stack.lpop().negate());
+ break;
+
+ case InstructionConstants.OP_FNEG:
+ stack.push(stack.fpop().negate());
+ break;
+
+ case InstructionConstants.OP_DNEG:
+ stack.push(stack.dpop().negate());
+ break;
+
+ case InstructionConstants.OP_ISHL:
+ stack.push(stack.ipop().shiftLeftOf(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LSHL:
+ stack.push(stack.ipop().shiftLeftOf(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_ISHR:
+ stack.push(stack.ipop().shiftRightOf(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LSHR:
+ stack.push(stack.ipop().shiftRightOf(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_IUSHR:
+ stack.push(stack.ipop().unsignedShiftRightOf(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LUSHR:
+ stack.push(stack.ipop().unsignedShiftRightOf(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_IAND:
+ stack.push(stack.ipop().and(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LAND:
+ stack.push(stack.lpop().and(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_IOR:
+ stack.push(stack.ipop().or(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LOR:
+ stack.push(stack.lpop().or(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_IXOR:
+ stack.push(stack.ipop().xor(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_LXOR:
+ stack.push(stack.lpop().xor(stack.lpop()));
+ break;
+
+ case InstructionConstants.OP_I2L:
+ stack.push(stack.ipop().convertToLong());
+ break;
+
+ case InstructionConstants.OP_I2F:
+ stack.push(stack.ipop().convertToFloat());
+ break;
+
+ case InstructionConstants.OP_I2D:
+ stack.push(stack.ipop().convertToDouble());
+ break;
+
+ case InstructionConstants.OP_L2I:
+ stack.push(stack.lpop().convertToInteger());
+ break;
+
+ case InstructionConstants.OP_L2F:
+ stack.push(stack.lpop().convertToFloat());
+ break;
+
+ case InstructionConstants.OP_L2D:
+ stack.push(stack.lpop().convertToDouble());
+ break;
+
+ case InstructionConstants.OP_F2I:
+ stack.push(stack.fpop().convertToInteger());
+ break;
+
+ case InstructionConstants.OP_F2L:
+ stack.push(stack.fpop().convertToLong());
+ break;
+
+ case InstructionConstants.OP_F2D:
+ stack.push(stack.fpop().convertToDouble());
+ break;
+
+ case InstructionConstants.OP_D2I:
+ stack.push(stack.dpop().convertToInteger());
+ break;
+
+ case InstructionConstants.OP_D2L:
+ stack.push(stack.dpop().convertToLong());
+ break;
+
+ case InstructionConstants.OP_D2F:
+ stack.push(stack.dpop().convertToFloat());
+ break;
+
+ case InstructionConstants.OP_I2B:
+ stack.push(stack.ipop().convertToByte());
+ break;
+
+ case InstructionConstants.OP_I2C:
+ stack.push(stack.ipop().convertToCharacter());
+ break;
+
+ case InstructionConstants.OP_I2S:
+ stack.push(stack.ipop().convertToShort());
+ break;
+
+ case InstructionConstants.OP_LCMP:
+// stack.push(stack.lpop().compareReverse(stack.lpop()));
+
+ LongValue longValue1 = stack.lpop();
+ LongValue longValue2 = stack.lpop();
+ stack.push(longValue2.compare(longValue1));
+ break;
+
+ case InstructionConstants.OP_FCMPL:
+ FloatValue floatValue1 = stack.fpop();
+ FloatValue floatValue2 = stack.fpop();
+ stack.push(floatValue2.compare(floatValue1));
+ break;
+
+ case InstructionConstants.OP_FCMPG:
+ stack.push(stack.fpop().compareReverse(stack.fpop()));
+ break;
+
+ case InstructionConstants.OP_DCMPL:
+ DoubleValue doubleValue1 = stack.dpop();
+ DoubleValue doubleValue2 = stack.dpop();
+ stack.push(doubleValue2.compare(doubleValue1));
+ break;
+
+ case InstructionConstants.OP_DCMPG:
+ stack.push(stack.dpop().compareReverse(stack.dpop()));
+ break;
+
+ case InstructionConstants.OP_IRETURN:
+ invocationUnit.exitMethod(clazz, method, stack.ipop());
+ branchUnit.returnFromMethod();
+ break;
+
+ case InstructionConstants.OP_LRETURN:
+ invocationUnit.exitMethod(clazz, method, stack.lpop());
+ branchUnit.returnFromMethod();
+ break;
+
+ case InstructionConstants.OP_FRETURN:
+ invocationUnit.exitMethod(clazz, method, stack.fpop());
+ branchUnit.returnFromMethod();
+ break;
+
+ case InstructionConstants.OP_DRETURN:
+ invocationUnit.exitMethod(clazz, method, stack.dpop());
+ branchUnit.returnFromMethod();
+ break;
+
+ case InstructionConstants.OP_ARETURN:
+ invocationUnit.exitMethod(clazz, method, stack.apop());
+ branchUnit.returnFromMethod();
+ break;
+
+ case InstructionConstants.OP_RETURN:
+ branchUnit.returnFromMethod();
+ break;
+
+ case InstructionConstants.OP_NEWARRAY:
+ IntegerValue arrayLength = stack.ipop();
+ stack.push(valueFactory.createArrayReferenceValue(String.valueOf(InstructionUtil.internalTypeFromArrayType((byte)simpleInstruction.constant)),
+ null,
+ arrayLength));
+ break;
+
+ case InstructionConstants.OP_ARRAYLENGTH:
+ stack.apop();
+ stack.push(valueFactory.createIntegerValue());
+ break;
+
+ case InstructionConstants.OP_ATHROW:
+ ReferenceValue exceptionReferenceValue = stack.apop();
+ stack.clear();
+ stack.push(exceptionReferenceValue);
+ branchUnit.throwException();
+ break;
+
+ case InstructionConstants.OP_MONITORENTER:
+ case InstructionConstants.OP_MONITOREXIT:
+ stack.apop();
+ break;
+
+ default:
+ throw new IllegalArgumentException("Unknown simple instruction ["+simpleInstruction.opcode+"]");
+ }
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ int constantIndex = constantInstruction.constantIndex;
+
+ switch (constantInstruction.opcode)
+ {
+ case InstructionConstants.OP_LDC:
+ case InstructionConstants.OP_LDC_W:
+ case InstructionConstants.OP_LDC2_W:
+ stack.push(classConstantValueFactory.constantValue(clazz, constantIndex));
+ break;
+
+ case InstructionConstants.OP_GETSTATIC:
+ case InstructionConstants.OP_PUTSTATIC:
+ case InstructionConstants.OP_GETFIELD:
+ case InstructionConstants.OP_PUTFIELD:
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ case InstructionConstants.OP_INVOKEDYNAMIC:
+ invocationUnit.invokeMember(clazz, method, codeAttribute, offset, constantInstruction, stack);
+ break;
+
+ case InstructionConstants.OP_NEW:
+ stack.push(constantValueFactory.constantValue(clazz, constantIndex).referenceValue());
+ break;
+
+ case InstructionConstants.OP_ANEWARRAY:
+ {
+ ReferenceValue referenceValue = constantValueFactory.constantValue(clazz, constantIndex).referenceValue();
+
+ stack.push(valueFactory.createArrayReferenceValue(referenceValue.internalType(),
+ referenceValue.getReferencedClass(),
+ stack.ipop()));
+ break;
+ }
+
+ case InstructionConstants.OP_CHECKCAST:
+ // TODO: Check cast.
+ ReferenceValue castValue = stack.apop();
+ ReferenceValue castResultValue =
+ castValue.isNull() == Value.ALWAYS ? castValue :
+ castValue.isNull() == Value.NEVER ? constantValueFactory.constantValue(clazz, constantIndex).referenceValue() :
+ constantValueFactory.constantValue(clazz, constantIndex).referenceValue().generalize(valueFactory.createReferenceValueNull());
+ stack.push(castResultValue);
+ break;
+
+ case InstructionConstants.OP_INSTANCEOF:
+ {
+ ReferenceValue referenceValue = constantValueFactory.constantValue(clazz, constantIndex).referenceValue();
+
+ int instanceOf = stack.apop().instanceOf(referenceValue.getType(),
+ referenceValue.getReferencedClass());
+
+ stack.push(instanceOf == Value.NEVER ? valueFactory.createIntegerValue(0) :
+ instanceOf == Value.ALWAYS ? valueFactory.createIntegerValue(1) :
+ valueFactory.createIntegerValue());
+ break;
+ }
+
+ case InstructionConstants.OP_MULTIANEWARRAY:
+ {
+ int dimensionCount = constantInstruction.constant;
+ for (int dimension = 0; dimension < dimensionCount; dimension++)
+ {
+ // TODO: Use array lengths.
+ IntegerValue arrayLength = stack.ipop();
+ }
+
+ stack.push(constantValueFactory.constantValue(clazz, constantIndex).referenceValue());
+ break;
+ }
+
+ default:
+ throw new IllegalArgumentException("Unknown constant pool instruction ["+constantInstruction.opcode+"]");
+ }
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ int variableIndex = variableInstruction.variableIndex;
+
+ switch (variableInstruction.opcode)
+ {
+ case InstructionConstants.OP_ILOAD:
+ case InstructionConstants.OP_ILOAD_0:
+ case InstructionConstants.OP_ILOAD_1:
+ case InstructionConstants.OP_ILOAD_2:
+ case InstructionConstants.OP_ILOAD_3:
+ stack.push(variables.iload(variableIndex));
+ break;
+
+ case InstructionConstants.OP_LLOAD:
+ case InstructionConstants.OP_LLOAD_0:
+ case InstructionConstants.OP_LLOAD_1:
+ case InstructionConstants.OP_LLOAD_2:
+ case InstructionConstants.OP_LLOAD_3:
+ stack.push(variables.lload(variableIndex));
+ break;
+
+ case InstructionConstants.OP_FLOAD:
+ case InstructionConstants.OP_FLOAD_0:
+ case InstructionConstants.OP_FLOAD_1:
+ case InstructionConstants.OP_FLOAD_2:
+ case InstructionConstants.OP_FLOAD_3:
+ stack.push(variables.fload(variableIndex));
+ break;
+
+ case InstructionConstants.OP_DLOAD:
+ case InstructionConstants.OP_DLOAD_0:
+ case InstructionConstants.OP_DLOAD_1:
+ case InstructionConstants.OP_DLOAD_2:
+ case InstructionConstants.OP_DLOAD_3:
+ stack.push(variables.dload(variableIndex));
+ break;
+
+ case InstructionConstants.OP_ALOAD:
+ case InstructionConstants.OP_ALOAD_0:
+ case InstructionConstants.OP_ALOAD_1:
+ case InstructionConstants.OP_ALOAD_2:
+ case InstructionConstants.OP_ALOAD_3:
+ stack.push(variables.aload(variableIndex));
+ break;
+
+ case InstructionConstants.OP_ISTORE:
+ case InstructionConstants.OP_ISTORE_0:
+ case InstructionConstants.OP_ISTORE_1:
+ case InstructionConstants.OP_ISTORE_2:
+ case InstructionConstants.OP_ISTORE_3:
+ variables.store(variableIndex, stack.ipop());
+ break;
+
+ case InstructionConstants.OP_LSTORE:
+ case InstructionConstants.OP_LSTORE_0:
+ case InstructionConstants.OP_LSTORE_1:
+ case InstructionConstants.OP_LSTORE_2:
+ case InstructionConstants.OP_LSTORE_3:
+ variables.store(variableIndex, stack.lpop());
+ break;
+
+ case InstructionConstants.OP_FSTORE:
+ case InstructionConstants.OP_FSTORE_0:
+ case InstructionConstants.OP_FSTORE_1:
+ case InstructionConstants.OP_FSTORE_2:
+ case InstructionConstants.OP_FSTORE_3:
+ variables.store(variableIndex, stack.fpop());
+ break;
+
+ case InstructionConstants.OP_DSTORE:
+ case InstructionConstants.OP_DSTORE_0:
+ case InstructionConstants.OP_DSTORE_1:
+ case InstructionConstants.OP_DSTORE_2:
+ case InstructionConstants.OP_DSTORE_3:
+ variables.store(variableIndex, stack.dpop());
+ break;
+
+ case InstructionConstants.OP_ASTORE:
+ case InstructionConstants.OP_ASTORE_0:
+ case InstructionConstants.OP_ASTORE_1:
+ case InstructionConstants.OP_ASTORE_2:
+ case InstructionConstants.OP_ASTORE_3:
+ // The operand on the stack can be a reference or a return
+ // address, so we'll relax the pop operation.
+ //variables.store(variableIndex, stack.apop());
+ variables.store(variableIndex, stack.pop());
+ break;
+
+ case InstructionConstants.OP_IINC:
+ variables.store(variableIndex,
+ variables.iload(variableIndex).add(
+ valueFactory.createIntegerValue(variableInstruction.constant)));
+ break;
+
+ case InstructionConstants.OP_RET:
+ // The return address should be in the last offset of the
+ // given instruction offset variable (even though there may
+ // be other offsets).
+ InstructionOffsetValue instructionOffsetValue = variables.oload(variableIndex);
+ branchUnit.branch(clazz,
+ codeAttribute,
+ offset,
+ instructionOffsetValue.instructionOffset(instructionOffsetValue.instructionOffsetCount()-1));
+ break;
+
+ default:
+ throw new IllegalArgumentException("Unknown variable instruction ["+variableInstruction.opcode+"]");
+ }
+ }
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ int branchTarget = offset + branchInstruction.branchOffset;
+
+ switch (branchInstruction.opcode)
+ {
+ case InstructionConstants.OP_IFEQ:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().equal(valueFactory.createIntegerValue(0)));
+ break;
+
+ case InstructionConstants.OP_IFNE:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().notEqual(valueFactory.createIntegerValue(0)));
+ break;
+
+ case InstructionConstants.OP_IFLT:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().lessThan(valueFactory.createIntegerValue(0)));
+ break;
+
+ case InstructionConstants.OP_IFGE:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().greaterThanOrEqual(valueFactory.createIntegerValue(0)));
+ break;
+
+ case InstructionConstants.OP_IFGT:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().greaterThan(valueFactory.createIntegerValue(0)));
+ break;
+
+ case InstructionConstants.OP_IFLE:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().lessThanOrEqual(valueFactory.createIntegerValue(0)));
+ break;
+
+
+ case InstructionConstants.OP_IFICMPEQ:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().equal(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_IFICMPNE:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().notEqual(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_IFICMPLT:
+ // Note that the stack entries are popped in reverse order.
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().greaterThan(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_IFICMPGE:
+ // Note that the stack entries are popped in reverse order.
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().lessThanOrEqual(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_IFICMPGT:
+ // Note that the stack entries are popped in reverse order.
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().lessThan(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_IFICMPLE:
+ // Note that the stack entries are popped in reverse order.
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.ipop().greaterThanOrEqual(stack.ipop()));
+ break;
+
+ case InstructionConstants.OP_IFACMPEQ:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.apop().equal(stack.apop()));
+ break;
+
+ case InstructionConstants.OP_IFACMPNE:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.apop().notEqual(stack.apop()));
+ break;
+
+ case InstructionConstants.OP_GOTO:
+ case InstructionConstants.OP_GOTO_W:
+ branchUnit.branch(clazz, codeAttribute, offset, branchTarget);
+ break;
+
+
+ case InstructionConstants.OP_JSR:
+ case InstructionConstants.OP_JSR_W:
+ stack.push(new InstructionOffsetValue(offset +
+ branchInstruction.length(offset)));
+ branchUnit.branch(clazz, codeAttribute, offset, branchTarget);
+ break;
+
+ case InstructionConstants.OP_IFNULL:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.apop().isNull());
+ break;
+
+ case InstructionConstants.OP_IFNONNULL:
+ branchUnit.branchConditionally(clazz, codeAttribute, offset, branchTarget,
+ stack.apop().isNotNull());
+ break;
+
+ default:
+ throw new IllegalArgumentException("Unknown branch instruction ["+branchInstruction.opcode+"]");
+ }
+ }
+
+
+ public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction)
+ {
+ IntegerValue indexValue = stack.ipop();
+
+ // If there is no definite branch in any of the cases below,
+ // branch to the default offset.
+ branchUnit.branch(clazz, codeAttribute,
+ offset,
+ offset + tableSwitchInstruction.defaultOffset);
+
+ for (int index = 0; index < tableSwitchInstruction.jumpOffsets.length; index++)
+ {
+ int conditional = indexValue.equal(valueFactory.createIntegerValue(
+ tableSwitchInstruction.lowCase + index));
+ branchUnit.branchConditionally(clazz, codeAttribute,
+ offset,
+ offset + tableSwitchInstruction.jumpOffsets[index],
+ conditional);
+
+ // If this branch is always taken, we can skip the rest.
+ if (conditional == Value.ALWAYS)
+ {
+ break;
+ }
+ }
+ }
+
+
+ public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction)
+ {
+ IntegerValue indexValue = stack.ipop();
+
+ // If there is no definite branch in any of the cases below,
+ // branch to the default offset.
+ branchUnit.branch(clazz, codeAttribute,
+ offset,
+ offset + lookUpSwitchInstruction.defaultOffset);
+
+ for (int index = 0; index < lookUpSwitchInstruction.jumpOffsets.length; index++)
+ {
+ int conditional = indexValue.equal(valueFactory.createIntegerValue(
+ lookUpSwitchInstruction.cases[index]));
+ branchUnit.branchConditionally(clazz, codeAttribute,
+ offset,
+ offset + lookUpSwitchInstruction.jumpOffsets[index],
+ conditional);
+
+ // If this branch is always taken, we can skip the rest.
+ if (conditional == Value.ALWAYS)
+ {
+ break;
+ }
+ }
+ }
+}
diff --git a/src/proguard/evaluation/Stack.java b/src/proguard/evaluation/Stack.java
new file mode 100644
index 000000000..c449e86c4
--- /dev/null
+++ b/src/proguard/evaluation/Stack.java
@@ -0,0 +1,560 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.evaluation.value.*;
+
+import java.util.Arrays;
+
+/**
+ * This class represents an operand stack that contains
+ * The stack stores a given producer Value along with each Value it stores.
+ * It then generalizes a given collected Value with the producer Value
+ * of each Value it loads. The producer Value and the initial collected Value
+ * can be set; the generalized collected Value can be retrieved.
+ *
+ * @author Eric Lafortune
+ */
+public class TracedStack extends Stack
+{
+ private Value producerValue;
+ private Stack producerStack;
+
+
+ /**
+ * Creates a new TracedStack with a given maximum size.
+ */
+ public TracedStack(int maxSize)
+ {
+ super(maxSize);
+
+ producerStack = new Stack(maxSize);
+ }
+
+
+ /**
+ * Creates a new TracedStack that is a copy of the given TracedStack.
+ */
+ public TracedStack(TracedStack tracedStack)
+ {
+ super(tracedStack);
+
+ producerStack = new Stack(tracedStack.producerStack);
+ }
+
+
+ /**
+ * Sets the Value that will be stored along with all push and pop
+ * instructions.
+ */
+ public void setProducerValue(Value producerValue)
+ {
+ this.producerValue = producerValue;
+ }
+
+
+ /**
+ * Gets the specified producer Value from the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the bottom
+ * of the stack.
+ * @return the producer value at the specified position.
+ */
+ public Value getBottomProducerValue(int index)
+ {
+ return producerStack.getBottom(index);
+ }
+
+
+ /**
+ * Sets the specified producer Value on the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the bottom
+ * of the stack.
+ * @param value the producer value to set.
+ */
+ public void setBottomProducerValue(int index, Value value)
+ {
+ producerStack.setBottom(index, value);
+ }
+
+
+ /**
+ * Gets the specified producer Value from the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the top
+ * of the stack.
+ * @return the producer value at the specified position.
+ */
+ public Value getTopProducerValue(int index)
+ {
+ return producerStack.getTop(index);
+ }
+
+
+ /**
+ * Sets the specified producer Value on the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the top
+ * of the stack.
+ * @param value the producer value to set.
+ */
+ public void setTopProducerValue(int index, Value value)
+ {
+ producerStack.setTop(index, value);
+ }
+
+
+ // Implementations for Stack.
+
+ public void reset(int size)
+ {
+ super.reset(size);
+
+ producerStack.reset(size);
+ }
+
+ public void copy(TracedStack other)
+ {
+ super.copy(other);
+
+ producerStack.copy(other.producerStack);
+ }
+
+ public boolean generalize(TracedStack other)
+ {
+ return
+ super.generalize(other) |
+ producerStack.generalize(other.producerStack);
+ }
+
+ public void clear()
+ {
+ super.clear();
+
+ producerStack.clear();
+ }
+
+ public void removeTop(int index)
+ {
+ super.removeTop(index);
+
+ producerStack.removeTop(index);
+ }
+
+ public void push(Value value)
+ {
+ super.push(value);
+
+ producerPush();
+
+ // Account for the extra space required by Category 2 values.
+ if (value.isCategory2())
+ {
+ producerPush();
+ }
+ }
+
+ public Value pop()
+ {
+ Value value = super.pop();
+
+ producerPop();
+
+ // Account for the extra space required by Category 2 values.
+ if (value.isCategory2())
+ {
+ producerPop();
+ }
+
+ return value;
+ }
+
+ public void pop1()
+ {
+ super.pop1();
+
+ producerPop();
+ }
+
+ public void pop2()
+ {
+ super.pop2();
+
+ producerPop();
+ producerPop();
+ }
+
+ public void dup()
+ {
+ super.dup();
+
+ producerPop();
+ producerPush();
+ producerPush();
+ }
+
+ public void dup_x1()
+ {
+ super.dup_x1();
+
+ producerPop();
+ producerPop();
+ producerPush();
+ producerPush();
+ producerPush();
+ }
+
+ public void dup_x2()
+ {
+ super.dup_x2();
+
+ producerPop();
+ producerPop();
+ producerPop();
+ producerPush();
+ producerPush();
+ producerPush();
+ producerPush();
+ }
+
+ public void dup2()
+ {
+ super.dup2();
+
+ producerPop();
+ producerPop();
+ producerPush();
+ producerPush();
+ producerPush();
+ producerPush();
+ }
+
+ public void dup2_x1()
+ {
+ super.dup2_x1();
+
+ producerPop();
+ producerPop();
+ producerPop();
+ producerPush();
+ producerPush();
+ producerPush();
+ producerPush();
+ producerPush();
+ }
+
+ public void dup2_x2()
+ {
+ super.dup2_x2();
+
+ producerPop();
+ producerPop();
+ producerPop();
+ producerPop();
+ producerPush();
+ producerPush();
+ producerPush();
+ producerPush();
+ producerPush();
+ producerPush();
+ }
+
+ public void swap()
+ {
+ super.swap();
+
+ producerPop();
+ producerPop();
+ producerPush();
+ producerPush();
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ TracedStack other = (TracedStack)object;
+
+ return super.equals(object) &&
+ this.producerStack.equals(other.producerStack);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ producerStack.hashCode();
+ }
+
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer();
+
+ for (int index = 0; index < this.size(); index++)
+ {
+ Value value = this.values[index];
+ Value producerValue = producerStack.getBottom(index);
+ buffer = buffer.append('[')
+ .append(producerValue == null ? "empty:" : producerValue.toString())
+ .append(value == null ? "empty" : value.toString())
+ .append(']');
+ }
+
+ return buffer.toString();
+ }
+
+
+ // Small utility methods.
+
+ private void producerPush()
+ {
+ producerStack.push(producerValue);
+ }
+
+
+ private void producerPop()
+ {
+ producerStack.pop();
+ }
+}
diff --git a/src/proguard/evaluation/TracedVariables.java b/src/proguard/evaluation/TracedVariables.java
new file mode 100644
index 000000000..fef54e151
--- /dev/null
+++ b/src/proguard/evaluation/TracedVariables.java
@@ -0,0 +1,199 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.evaluation.value.Value;
+
+/**
+ * This Variables class saves additional information with variables, to keep
+ * track of their origins.
+ *
+ * The Variables class stores a given producer Value along with each Value it
+ * stores. It then generalizes a given collected Value with the producer Value
+ * of each Value it loads. The producer Value and the initial collected Value
+ * can be set; the generalized collected Value can be retrieved.
+ *
+ * @author Eric Lafortune
+ */
+public class TracedVariables extends Variables
+{
+ public static final int NONE = -1;
+
+
+ private Value producerValue;
+ private Variables producerVariables;
+
+
+ /**
+ * Creates a new TracedVariables with a given size.
+ */
+ public TracedVariables(int size)
+ {
+ super(size);
+
+ producerVariables = new Variables(size);
+ }
+
+
+ /**
+ * Creates a new TracedVariables that is a copy of the given TracedVariables.
+ */
+ public TracedVariables(TracedVariables tracedVariables)
+ {
+ super(tracedVariables);
+
+ producerVariables = new Variables(tracedVariables.producerVariables);
+ }
+
+
+ /**
+ * Sets the Value that will be stored along with all store instructions.
+ */
+ public void setProducerValue(Value producerValue)
+ {
+ this.producerValue = producerValue;
+ }
+
+
+ /**
+ * Gets the producer Value for the specified variable, without disturbing it.
+ * @param index the variable index.
+ * @return the producer value of the given variable.
+ */
+ public Value getProducerValue(int index)
+ {
+ return producerVariables.getValue(index);
+ }
+
+
+ /**
+ * Sets the given producer Value for the specified variable, without
+ * disturbing it.
+ * @param index the variable index.
+ * @param value the producer value to set.
+ */
+ public void setProducerValue(int index, Value value)
+ {
+ producerVariables.store(index, value);
+ }
+
+
+ // Implementations for Variables.
+
+ public void reset(int size)
+ {
+ super.reset(size);
+
+ producerVariables.reset(size);
+ }
+
+ public void initialize(TracedVariables other)
+ {
+ super.initialize(other);
+
+ producerVariables.initialize(other.producerVariables);
+ }
+
+ public boolean generalize(TracedVariables other,
+ boolean clearConflictingOtherVariables)
+ {
+ boolean variablesChanged = super.generalize(other, clearConflictingOtherVariables);
+ boolean producersChanged = producerVariables.generalize(other.producerVariables, clearConflictingOtherVariables);
+ /* consumerVariables.generalize(other.consumerVariables)*/
+
+ // Clear any traces if a variable has become null.
+ if (variablesChanged)
+ {
+ for (int index = 0; index < size; index++)
+ {
+ if (values[index] == null)
+ {
+ producerVariables.values[index] = null;
+
+ if (clearConflictingOtherVariables)
+ {
+ other.producerVariables.values[index] = null;
+ }
+ }
+ }
+ }
+
+ return variablesChanged || producersChanged;
+ }
+
+
+ public void store(int index, Value value)
+ {
+ // Store the value itself in the variable.
+ super.store(index, value);
+
+ // Store the producer value in its producer variable.
+ producerVariables.store(index, producerValue);
+
+ // Account for the extra space required by Category 2 values.
+ if (value.isCategory2())
+ {
+ producerVariables.store(index+1, producerValue);
+ }
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ TracedVariables other = (TracedVariables)object;
+
+ return super.equals(object) &&
+ this.producerVariables.equals(other.producerVariables);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ producerVariables.hashCode();
+ }
+
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer();
+
+ for (int index = 0; index < this.size(); index++)
+ {
+ Value value = this.values[index];
+ Value producerValue = producerVariables.getValue(index);
+ buffer = buffer.append('[')
+ .append(producerValue == null ? "empty:" : producerValue.toString())
+ .append(value == null ? "empty" : value.toString())
+ .append(']');
+ }
+
+ return buffer.toString();
+ }
+}
diff --git a/src/proguard/evaluation/Variables.java b/src/proguard/evaluation/Variables.java
new file mode 100644
index 000000000..16b39e7cd
--- /dev/null
+++ b/src/proguard/evaluation/Variables.java
@@ -0,0 +1,347 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.evaluation.value.*;
+
+import java.util.Arrays;
+
+/**
+ * This class represents a local variable frame that contains \
+ With this GUI, you can create, load, modify, and save ProGuard configurations.\
+ \
+ With the ReTrace part of this GUI you can de-obfuscate your stack traces.\
+ \
+ ProGuard and ReTrace are written and maintained by Eric Lafortune.\
+ \
+ Official site at Sourceforge: \
+ http://proguard.sourceforge.net/\
+ \
+ Distributed under the GNU General Public License.\
+
+ * Class files are read as ProgramClass objects or LibraryClass objects,
+ * depending on the
+ * In case of libraries, only public classes are considered, if the
+ *
+ * The class members must have been linked before applying this visitor.
+ *
+ * @see MethodLinker
+ *
+ * @author Eric Lafortune
+ */
+public class MemberObfuscator
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final boolean allowAggressiveOverloading;
+ private final NameFactory nameFactory;
+ private final Map descriptorMap;
+
+
+ /**
+ * Creates a new MemberObfuscator.
+ * @param allowAggressiveOverloading a flag that specifies whether class
+ * members can be overloaded aggressively.
+ * @param nameFactory the factory that can produce
+ * obfuscated member names.
+ * @param descriptorMap the map of descriptors to
+ * [new name - old name] maps.
+ */
+ public MemberObfuscator(boolean allowAggressiveOverloading,
+ NameFactory nameFactory,
+ Map descriptorMap)
+ {
+ this.allowAggressiveOverloading = allowAggressiveOverloading;
+ this.nameFactory = nameFactory;
+ this.descriptorMap = descriptorMap;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz clazz, Member member)
+ {
+ // Special cases:
+ * An empty list results in a StringMatcher that matches any string.
+ */
+ public StringMatcher parse(List regularExpressions)
+ {
+ StringMatcher listMatcher = null;
+
+ // Loop over all simple regular expressions, backward, creating a
+ // linked list of matchers.
+ for (int index = regularExpressions.size()-1; index >= 0; index--)
+ {
+ String regularExpression = (String)regularExpressions.get(index);
+
+ StringMatcher entryMatcher = parseEntry(regularExpression);
+
+ // Prepend the entry matcher.
+ listMatcher =
+ listMatcher == null ?
+ (StringMatcher)entryMatcher :
+ isNegated(regularExpression) ?
+ (StringMatcher)new AndMatcher(entryMatcher, listMatcher) :
+ (StringMatcher)new OrMatcher(entryMatcher, listMatcher);
+ }
+
+ return listMatcher != null ? listMatcher : new ConstantMatcher(true);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Creates a StringMatcher for the given regular expression, which is a
+ * an optionally negated simple expression.
+ */
+ private StringMatcher parseEntry(String regularExpression)
+ {
+ // Wrap the matcher if the regular expression starts with a '!' negator.
+ return isNegated(regularExpression) ?
+ new NotMatcher(stringParser.parse(regularExpression.substring(1))) :
+ stringParser.parse(regularExpression);
+ }
+
+
+ /**
+ * Returns whether the given simple regular expression is negated.
+ */
+ private boolean isNegated(String regularExpression)
+ {
+ return regularExpression.length() > 0 &&
+ regularExpression.charAt(0) == '!';
+ }
+
+
+ /**
+ * A main method for testing name matching.
+ */
+ public static void main(String[] args)
+ {
+ try
+ {
+ System.out.println("Regular expression ["+args[0]+"]");
+ ListParser parser = new ListParser(new NameParser());
+ StringMatcher matcher = parser.parse(args[0]);
+ for (int index = 1; index < args.length; index++)
+ {
+ String string = args[index];
+ System.out.print("String ["+string+"]");
+ System.out.println(" -> match = "+matcher.matches(args[index]));
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/util/ListUtil.java b/src/proguard/util/ListUtil.java
new file mode 100644
index 000000000..18bdce216
--- /dev/null
+++ b/src/proguard/util/ListUtil.java
@@ -0,0 +1,180 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+import java.util.*;
+
+
+/**
+ * This class provides some utility methods for working with
+ *
+ * In order to integrate this plug-in in the toolkit, you'll have to put the
+ * following lines in the file
+ * {j2mewtk.dir}
+ * ExternalTypeEnumeration
object can be reused for processing
+ * different subsequent descriptors, by means of the setDescriptor
+ * method.
+ *
+ * @author Eric Lafortune
+ */
+public class ExternalTypeEnumeration
+{
+ private String descriptor;
+ private int index;
+
+
+ public ExternalTypeEnumeration(String descriptor)
+ {
+ setDescriptor(descriptor);
+ }
+
+
+ ExternalTypeEnumeration()
+ {
+ }
+
+
+ void setDescriptor(String descriptor)
+ {
+ this.descriptor = descriptor;
+
+ reset();
+ }
+
+
+ public void reset()
+ {
+ index = descriptor.indexOf(ClassConstants.EXTERNAL_METHOD_ARGUMENTS_OPEN) + 1;
+
+ if (index < 1)
+ {
+ throw new IllegalArgumentException("Missing opening parenthesis in descriptor ["+descriptor+"]");
+ }
+ }
+
+
+ public boolean hasMoreTypes()
+ {
+ return index < descriptor.length() - 1;
+ }
+
+
+ public String nextType()
+ {
+ int startIndex = index;
+
+ // Find the next separating comma.
+ index = descriptor.indexOf(ClassConstants.EXTERNAL_METHOD_ARGUMENTS_SEPARATOR,
+ startIndex);
+
+ // Otherwise find the closing parenthesis.
+ if (index < 0)
+ {
+ index = descriptor.indexOf(ClassConstants.EXTERNAL_METHOD_ARGUMENTS_CLOSE,
+ startIndex);
+ if (index < 0)
+ {
+ throw new IllegalArgumentException("Missing closing parenthesis in descriptor ["+descriptor+"]");
+ }
+ }
+
+ return descriptor.substring(startIndex, index++).trim();
+ }
+
+
+ public String methodName()
+ {
+ return descriptor.substring(0, descriptor.indexOf(ClassConstants.EXTERNAL_METHOD_ARGUMENTS_OPEN)).trim();
+ }
+}
diff --git a/src/proguard/classfile/util/InstructionSequenceMatcher.java b/src/proguard/classfile/util/InstructionSequenceMatcher.java
new file mode 100644
index 000000000..8c529a90f
--- /dev/null
+++ b/src/proguard/classfile/util/InstructionSequenceMatcher.java
@@ -0,0 +1,754 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+
+import java.util.Arrays;
+
+/**
+ * This InstructionVisitor checks whether a given pattern instruction sequence
+ * occurs in the instructions that are visited. The arguments of the
+ * instruction sequence can be wildcards that are matched.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionSequenceMatcher
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor
+{
+ /*
+ public static boolean DEBUG = true;
+ public static boolean DEBUG_MORE = true;
+ /*/
+ private static final boolean DEBUG = false;
+ private static final boolean DEBUG_MORE = false;
+ //*/
+
+ public static final int X = 0x40000000;
+ public static final int Y = 0x40000001;
+ public static final int Z = 0x40000002;
+
+ public static final int A = 0x40000003;
+ public static final int B = 0x40000004;
+ public static final int C = 0x40000005;
+ public static final int D = 0x40000006;
+
+
+ private final Constant[] patternConstants;
+ private final Instruction[] patternInstructions;
+
+ private boolean matching;
+ private int patternInstructionIndex;
+ private final int[] matchedInstructionOffsets;
+ private int matchedArgumentFlags;
+ private final int[] matchedArguments = new int[7];
+ private final long[] matchedConstantFlags;
+ private final int[] matchedConstantIndices;
+ private int constantFlags;
+ private int previousConstantFlags;
+
+ // Fields acting as a parameter and a return value for visitor methods.
+ private Constant patternConstant;
+ private boolean matchingConstant;
+
+
+ /**
+ * Creates a new InstructionSequenceMatcher.
+ * @param patternConstants any constants referenced by the pattern
+ * instruction.
+ * @param patternInstructions the pattern instruction sequence.
+ */
+ public InstructionSequenceMatcher(Constant[] patternConstants,
+ Instruction[] patternInstructions)
+ {
+ this.patternConstants = patternConstants;
+ this.patternInstructions = patternInstructions;
+
+ matchedInstructionOffsets = new int[patternInstructions.length];
+ matchedConstantFlags = new long[(patternConstants.length + 63) / 64];
+ matchedConstantIndices = new int[patternConstants.length];
+ }
+
+
+ /**
+ * Starts matching from the first instruction again next time.
+ */
+ public void reset()
+ {
+ patternInstructionIndex = 0;
+ matchedArgumentFlags = 0;
+
+ Arrays.fill(matchedConstantFlags, 0L);
+
+ previousConstantFlags = constantFlags;
+ constantFlags = 0;
+ }
+
+
+ /**
+ * Returns whether the complete pattern sequence has been matched.
+ */
+ public boolean isMatching()
+ {
+ return matching;
+ }
+
+
+ /**
+ * Returns the number of instructions in the pattern sequence.
+ */
+ public int instructionCount()
+ {
+ return patternInstructions.length;
+ }
+
+
+ /**
+ * Returns the matched instruction offset of the specified pattern
+ * instruction.
+ */
+ public int matchedInstructionOffset(int index)
+ {
+ return matchedInstructionOffsets[index];
+ }
+
+
+ /**
+ * Returns whether the specified wildcard argument was a constant from
+ * the constant pool in the most recent match.
+ */
+ public boolean wasConstant(int argument)
+ {
+ return (previousConstantFlags & (1 << (argument - X))) != 0;
+ }
+
+
+ /**
+ * Returns the value of the specified matched argument (wildcard or not).
+ */
+ public int matchedArgument(int argument)
+ {
+ int argumentIndex = argument - X;
+ return argumentIndex < 0 ?
+ argument :
+ matchedArguments[argumentIndex];
+ }
+
+
+ /**
+ * Returns the values of the specified matched arguments (wildcard or not).
+ */
+ public int[] matchedArguments(int[] arguments)
+ {
+ int[] matchedArguments = new int[arguments.length];
+
+ for (int index = 0; index < arguments.length; index++)
+ {
+ matchedArguments[index] = matchedArgument(arguments[index]);
+ }
+
+ return matchedArguments;
+ }
+
+
+ /**
+ * Returns the index of the specified matched constant (wildcard or not).
+ */
+ public int matchedConstantIndex(int constantIndex)
+ {
+ int argumentIndex = constantIndex - X;
+ return argumentIndex < 0 ?
+ matchedConstantIndices[constantIndex] :
+ matchedArguments[argumentIndex];
+ }
+
+
+ /**
+ * Returns the value of the specified matched branch offset (wildcard or
+ * not).
+ */
+ public int matchedBranchOffset(int offset, int branchOffset)
+ {
+ int argumentIndex = branchOffset - X;
+ return argumentIndex < 0 ?
+ branchOffset :
+ matchedArguments[argumentIndex] - offset;
+ }
+
+
+ /**
+ * Returns the values of the specified matched jump offsets (wildcard or
+ * not).
+ */
+ public int[] matchedJumpOffsets(int offset, int[] jumpOffsets)
+ {
+ int[] matchedJumpOffsets = new int[jumpOffsets.length];
+
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ matchedJumpOffsets[index] = matchedBranchOffset(offset,
+ jumpOffsets[index]);
+ }
+
+ return matchedJumpOffsets;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ Instruction patternInstruction = patternInstructions[patternInstructionIndex];
+
+ // Check if the instruction matches the next instruction in the sequence.
+ boolean condition =
+ matchingOpcodes(simpleInstruction, patternInstruction) &&
+ matchingArguments(simpleInstruction.constant,
+ ((SimpleInstruction)patternInstruction).constant);
+
+ // Check if the instruction sequence is matching now.
+ checkMatch(condition,
+ clazz,
+ method,
+ codeAttribute,
+ offset,
+ simpleInstruction);
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ Instruction patternInstruction = patternInstructions[patternInstructionIndex];
+
+ // Check if the instruction matches the next instruction in the sequence.
+ boolean condition =
+ matchingOpcodes(variableInstruction, patternInstruction) &&
+ matchingArguments(variableInstruction.variableIndex,
+ ((VariableInstruction)patternInstruction).variableIndex) &&
+ matchingArguments(variableInstruction.constant,
+ ((VariableInstruction)patternInstruction).constant);
+
+ // Check if the instruction sequence is matching now.
+ checkMatch(condition,
+ clazz,
+ method,
+ codeAttribute,
+ offset,
+ variableInstruction);
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ Instruction patternInstruction = patternInstructions[patternInstructionIndex];
+
+ // Check if the instruction matches the next instruction in the sequence.
+ boolean condition =
+ matchingOpcodes(constantInstruction, patternInstruction) &&
+ matchingConstantIndices(clazz,
+ constantInstruction.constantIndex,
+ ((ConstantInstruction)patternInstruction).constantIndex) &&
+ matchingArguments(constantInstruction.constant,
+ ((ConstantInstruction)patternInstruction).constant);
+
+ // Check if the instruction sequence is matching now.
+ checkMatch(condition,
+ clazz,
+ method,
+ codeAttribute,
+ offset,
+ constantInstruction);
+ }
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ Instruction patternInstruction = patternInstructions[patternInstructionIndex];
+
+ // Check if the instruction matches the next instruction in the from
+ // sequence.
+ boolean condition =
+ matchingOpcodes(branchInstruction, patternInstruction) &&
+ matchingBranchOffsets(offset,
+ branchInstruction.branchOffset,
+ ((BranchInstruction)patternInstruction).branchOffset);
+
+ // Check if the instruction sequence is matching now.
+ checkMatch(condition,
+ clazz,
+ method,
+ codeAttribute,
+ offset,
+ branchInstruction);
+ }
+
+
+ public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction)
+ {
+ Instruction patternInstruction = patternInstructions[patternInstructionIndex];
+
+ // Check if the instruction matches the next instruction in the sequence.
+ boolean condition =
+ matchingOpcodes(tableSwitchInstruction, patternInstruction) &&
+ matchingBranchOffsets(offset,
+ tableSwitchInstruction.defaultOffset,
+ ((TableSwitchInstruction)patternInstruction).defaultOffset) &&
+ matchingArguments(tableSwitchInstruction.lowCase,
+ ((TableSwitchInstruction)patternInstruction).lowCase) &&
+ matchingArguments(tableSwitchInstruction.highCase,
+ ((TableSwitchInstruction)patternInstruction).highCase) &&
+ matchingJumpOffsets(offset,
+ tableSwitchInstruction.jumpOffsets,
+ ((TableSwitchInstruction)patternInstruction).jumpOffsets);
+
+ // Check if the instruction sequence is matching now.
+ checkMatch(condition,
+ clazz,
+ method,
+ codeAttribute,
+ offset,
+ tableSwitchInstruction);
+ }
+
+
+ public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction)
+ {
+ Instruction patternInstruction = patternInstructions[patternInstructionIndex];
+
+ // Check if the instruction matches the next instruction in the sequence.
+ boolean condition =
+ matchingOpcodes(lookUpSwitchInstruction, patternInstruction) &&
+ matchingBranchOffsets(offset,
+ lookUpSwitchInstruction.defaultOffset,
+ ((LookUpSwitchInstruction)patternInstruction).defaultOffset) &&
+ matchingArguments(lookUpSwitchInstruction.cases,
+ ((LookUpSwitchInstruction)patternInstruction).cases) &&
+ matchingJumpOffsets(offset,
+ lookUpSwitchInstruction.jumpOffsets,
+ ((LookUpSwitchInstruction)patternInstruction).jumpOffsets);
+
+ // Check if the instruction sequence is matching now.
+ checkMatch(condition,
+ clazz,
+ method,
+ codeAttribute,
+ offset,
+ lookUpSwitchInstruction);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)
+ {
+ IntegerConstant integerPatternConstant = (IntegerConstant)patternConstant;
+
+ // Compare the integer values.
+ matchingConstant = integerConstant.getValue() ==
+ integerPatternConstant.getValue();
+ }
+
+
+ public void visitLongConstant(Clazz clazz, LongConstant longConstant)
+ {
+ LongConstant longPatternConstant = (LongConstant)patternConstant;
+
+ // Compare the long values.
+ matchingConstant = longConstant.getValue() ==
+ longPatternConstant.getValue();
+ }
+
+
+ public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)
+ {
+ FloatConstant floatPatternConstant = (FloatConstant)patternConstant;
+
+ // Compare the float values.
+ matchingConstant = floatConstant.getValue() ==
+ floatPatternConstant.getValue();
+ }
+
+
+ public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)
+ {
+ DoubleConstant doublePatternConstant = (DoubleConstant)patternConstant;
+
+ // Compare the double values.
+ matchingConstant = doubleConstant.getValue() ==
+ doublePatternConstant.getValue();
+ }
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ StringConstant stringPatternConstant = (StringConstant)patternConstant;
+
+ // Check the UTF-8 constant.
+ matchingConstant =
+ matchingConstantIndices(clazz,
+ stringConstant.u2stringIndex,
+ stringPatternConstant.u2stringIndex);
+ }
+
+
+ public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)
+ {
+ Utf8Constant utf8PatternConstant = (Utf8Constant)patternConstant;
+
+ // Compare the actual strings.
+ matchingConstant = utf8Constant.getString().equals(
+ utf8PatternConstant.getString());
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ InvokeDynamicConstant invokeDynamicPatternConstant = (InvokeDynamicConstant)patternConstant;
+
+ // Check the bootstrap method and the name and type.
+ matchingConstant =
+ matchingConstantIndices(clazz,
+ invokeDynamicConstant.getBootstrapMethodAttributeIndex(),
+ invokeDynamicPatternConstant.getBootstrapMethodAttributeIndex()) &&
+ matchingConstantIndices(clazz,
+ invokeDynamicConstant.getNameAndTypeIndex(),
+ invokeDynamicPatternConstant.getNameAndTypeIndex());
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ MethodHandleConstant methodHandlePatternConstant = (MethodHandleConstant)patternConstant;
+
+ // Check the handle type and the name and type.
+ matchingConstant =
+ matchingArguments(methodHandleConstant.getReferenceKind(),
+ methodHandlePatternConstant.getReferenceKind()) &&
+ matchingConstantIndices(clazz,
+ methodHandleConstant.getReferenceIndex(),
+ methodHandlePatternConstant.getReferenceIndex());
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ RefConstant refPatternConstant = (RefConstant)patternConstant;
+
+ // Check the class and the name and type.
+ matchingConstant =
+ matchingConstantIndices(clazz,
+ refConstant.getClassIndex(),
+ refPatternConstant.getClassIndex()) &&
+ matchingConstantIndices(clazz,
+ refConstant.getNameAndTypeIndex(),
+ refPatternConstant.getNameAndTypeIndex());
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ ClassConstant classPatternConstant = (ClassConstant)patternConstant;
+
+ // Check the class name.
+ matchingConstant =
+ matchingConstantIndices(clazz,
+ classConstant.u2nameIndex,
+ classPatternConstant.u2nameIndex);
+ }
+
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
+ {
+ MethodTypeConstant typePatternConstant = (MethodTypeConstant)patternConstant;
+
+ // Check the descriptor.
+ matchingConstant =
+ matchingConstantIndices(clazz,
+ methodTypeConstant.u2descriptorIndex,
+ typePatternConstant.u2descriptorIndex);
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ NameAndTypeConstant typePatternConstant = (NameAndTypeConstant)patternConstant;
+
+ // Check the name and the descriptor.
+ matchingConstant =
+ matchingConstantIndices(clazz,
+ nameAndTypeConstant.u2nameIndex,
+ typePatternConstant.u2nameIndex) &&
+ matchingConstantIndices(clazz,
+ nameAndTypeConstant.u2descriptorIndex,
+ typePatternConstant.u2descriptorIndex);
+ }
+
+
+ // Small utility methods.
+
+ private boolean matchingOpcodes(Instruction instruction1,
+ Instruction instruction2)
+ {
+ // Check the opcode.
+ return instruction1.opcode == instruction2.opcode ||
+ instruction1.canonicalOpcode() == instruction2.opcode;
+ }
+
+
+ private boolean matchingArguments(int argument1,
+ int argument2)
+ {
+ int argumentIndex = argument2 - X;
+ if (argumentIndex < 0)
+ {
+ // Check the literal argument.
+ return argument1 == argument2;
+ }
+ else if (!isMatchingArgumentIndex(argumentIndex))
+ {
+ // Store the wildcard argument.
+ setMatchingArgument(argumentIndex, argument1);
+
+ return true;
+ }
+ else
+ {
+ // Check the previously stored wildcard argument.
+ return matchedArguments[argumentIndex] == argument1;
+ }
+ }
+
+
+ /**
+ * Marks the specified argument (by index) as matching the specified
+ * argument value.
+ */
+ private void setMatchingArgument(int argumentIndex,
+ int argument)
+ {
+ matchedArguments[argumentIndex] = argument;
+ matchedArgumentFlags |= 1 << argumentIndex;
+ }
+
+
+ /**
+ * Returns whether the specified wildcard argument (by index) has been
+ * matched.
+ */
+ private boolean isMatchingArgumentIndex(int argumentIndex)
+ {
+ return (matchedArgumentFlags & (1 << argumentIndex)) != 0;
+ }
+
+
+ private boolean matchingArguments(int[] arguments1,
+ int[] arguments2)
+ {
+ if (arguments1.length != arguments2.length)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < arguments1.length; index++)
+ {
+ if (!matchingArguments(arguments1[index], arguments2[index]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ private boolean matchingConstantIndices(Clazz clazz,
+ int constantIndex1,
+ int constantIndex2)
+ {
+ if (constantIndex2 >= X)
+ {
+ // Remember that we are trying to match a constant.
+ constantFlags |= 1 << (constantIndex2 - X);
+
+ // Check the constant index.
+ return matchingArguments(constantIndex1, constantIndex2);
+ }
+ else if (!isMatchingConstantIndex(constantIndex2))
+ {
+ // Check the actual constant.
+ matchingConstant = false;
+ patternConstant = patternConstants[constantIndex2];
+
+ if (clazz.getTag(constantIndex1) == patternConstant.getTag())
+ {
+ clazz.constantPoolEntryAccept(constantIndex1, this);
+
+ if (matchingConstant)
+ {
+ // Store the constant index.
+ setMatchingConstant(constantIndex2, constantIndex1);
+ }
+ }
+
+ return matchingConstant;
+ }
+ else
+ {
+ // Check a previously stored constant index.
+ return matchedConstantIndices[constantIndex2] == constantIndex1;
+ }
+ }
+
+
+ /**
+ * Marks the specified constant (by index) as matching the specified
+ * constant index value.
+ */
+ private void setMatchingConstant(int constantIndex,
+ int constantIndex1)
+ {
+ matchedConstantIndices[constantIndex] = constantIndex1;
+ matchedConstantFlags[constantIndex / 64] |= 1L << constantIndex;
+ }
+
+
+ /**
+ * Returns whether the specified wildcard constant has been matched.
+ */
+ private boolean isMatchingConstantIndex(int constantIndex)
+ {
+ return (matchedConstantFlags[constantIndex / 64] & (1L << constantIndex)) != 0;
+ }
+
+
+ private boolean matchingBranchOffsets(int offset,
+ int branchOffset1,
+ int branchOffset2)
+ {
+ int argumentIndex = branchOffset2 - X;
+ if (argumentIndex < 0)
+ {
+ // Check the literal argument.
+ return branchOffset1 == branchOffset2;
+ }
+ else if (!isMatchingArgumentIndex(argumentIndex))
+ {
+ // Store a wildcard argument.
+ setMatchingArgument(argumentIndex, offset + branchOffset1);
+
+ return true;
+ }
+ else
+ {
+ // Check the previously stored wildcard argument.
+ return matchedArguments[argumentIndex] == offset + branchOffset1;
+ }
+ }
+
+
+ private boolean matchingJumpOffsets(int offset,
+ int[] jumpOffsets1,
+ int[] jumpOffsets2)
+ {
+ if (jumpOffsets1.length != jumpOffsets2.length)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < jumpOffsets1.length; index++)
+ {
+ if (!matchingBranchOffsets(offset,
+ jumpOffsets1[index],
+ jumpOffsets2[index]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ private void checkMatch(boolean condition,
+ Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ int offset,
+ Instruction instruction)
+ {
+ if (DEBUG_MORE)
+ {
+ System.out.println("InstructionSequenceMatcher: ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"]: "+patternInstructions[patternInstructionIndex].toString(patternInstructionIndex)+(condition?"\t== ":"\t ")+instruction.toString(offset));
+ }
+
+ // Did the instruction match?
+ if (condition)
+ {
+ // Remember the offset of the matching instruction.
+ matchedInstructionOffsets[patternInstructionIndex] = offset;
+
+ // Try to match the next instruction next time.
+ patternInstructionIndex++;
+
+ // Did we match all instructions in the sequence?
+ matching = patternInstructionIndex == patternInstructions.length;
+
+ if (matching)
+ {
+ if (DEBUG)
+ {
+ System.out.println("InstructionSequenceMatcher: ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ for (int index = 0; index < patternInstructionIndex; index++)
+ {
+ System.out.println(" "+InstructionFactory.create(codeAttribute.code, matchedInstructionOffsets[index]).toString(matchedInstructionOffsets[index]));
+ }
+ }
+
+ // Start matching from the first instruction again next time.
+ reset();
+ }
+ }
+ else
+ {
+ // The instruction didn't match.
+ matching = false;
+
+ // Is this a failed second instruction?
+ boolean retry = patternInstructionIndex == 1;
+
+ // Start matching from the first instruction next time.
+ reset();
+
+ // Retry a failed second instruction as a first instruction.
+ if (retry)
+ {
+ instruction.accept(clazz, method, codeAttribute, offset, this);
+ }
+ }
+ }
+}
diff --git a/src/proguard/classfile/util/InternalTypeEnumeration.java b/src/proguard/classfile/util/InternalTypeEnumeration.java
new file mode 100644
index 000000000..9c63ad9e3
--- /dev/null
+++ b/src/proguard/classfile/util/InternalTypeEnumeration.java
@@ -0,0 +1,204 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.ClassConstants;
+
+
+/**
+ * An InternalTypeEnumeration
provides an enumeration of all
+ * parameter types listed in a given internal method descriptor or signature.
+ * The signature can also be a class signature. The return type of a method
+ * descriptor can be retrieved separately.
+ *
+ * @author Eric Lafortune
+ */
+public class InternalTypeEnumeration
+{
+ private String descriptor;
+ private int firstIndex;
+ private int lastIndex;
+ private int index;
+
+
+ /**
+ * Creates a new InternalTypeEnumeration for the given method descriptor.
+ */
+ public InternalTypeEnumeration(String descriptor)
+ {
+ this.descriptor = descriptor;
+ this.firstIndex = descriptor.indexOf(ClassConstants.INTERNAL_METHOD_ARGUMENTS_OPEN);
+ this.lastIndex = descriptor.indexOf(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+ this.index = firstIndex + 1;
+
+ if (lastIndex < 0)
+ {
+ lastIndex = descriptor.length();
+ }
+ }
+
+
+ /**
+ * Returns the formal type parameters from the descriptor, assuming it's a
+ * method descriptor.
+ */
+ public String formalTypeParameters()
+ {
+ return descriptor.substring(0, firstIndex);
+ }
+
+
+ /**
+ * Returns whether the enumeration can provide more types from the method
+ * descriptor.
+ */
+ public boolean hasMoreTypes()
+ {
+ return index < lastIndex;
+ }
+
+
+ /**
+ * Returns the next type from the method descriptor.
+ */
+ public String nextType()
+ {
+ int startIndex = index;
+
+ skipArray();
+
+ char c = descriptor.charAt(index++);
+ switch (c)
+ {
+ case ClassConstants.INTERNAL_TYPE_CLASS_START:
+ case ClassConstants.INTERNAL_TYPE_GENERIC_VARIABLE_START:
+ {
+ skipClass();
+ break;
+ }
+ case ClassConstants.INTERNAL_TYPE_GENERIC_START:
+ {
+ skipGeneric();
+ break;
+ }
+ }
+
+ return descriptor.substring(startIndex, index);
+ }
+
+
+ /**
+ * Returns the return type from the descriptor, assuming it's a method
+ * descriptor.
+ */
+ public String returnType()
+ {
+ return descriptor.substring(lastIndex + 1);
+ }
+
+
+ // Small utility methods.
+
+ private void skipArray()
+ {
+ while (descriptor.charAt(index) == ClassConstants.INTERNAL_TYPE_ARRAY)
+ {
+ index++;
+ }
+ }
+
+
+ private void skipClass()
+ {
+ while (true)
+ {
+ char c = descriptor.charAt(index++);
+ switch (c)
+ {
+ case ClassConstants.INTERNAL_TYPE_GENERIC_START:
+ skipGeneric();
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_CLASS_END:
+ return;
+ }
+ }
+ }
+
+
+ private void skipGeneric()
+ {
+ int nestingLevel = 1;
+
+ do
+ {
+ char c = descriptor.charAt(index++);
+ switch (c)
+ {
+ case ClassConstants.INTERNAL_TYPE_GENERIC_START:
+ nestingLevel++;
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_GENERIC_END:
+ nestingLevel--;
+ break;
+ }
+ }
+ while (nestingLevel > 0);
+ }
+
+
+ /**
+ * A main method for testing the type enumeration.
+ */
+ public static void main(String[] args)
+ {
+ try
+ {
+ for (int index = 0; index < args.length; index++)
+ {
+ String descriptor = args[index];
+
+ System.out.println("Descriptor ["+descriptor+"]");
+ InternalTypeEnumeration enumeration = new InternalTypeEnumeration(descriptor);
+
+ if (enumeration.firstIndex >= 0)
+ {
+ System.out.println(" Formal type parameters ["+enumeration.formalTypeParameters()+"]");
+ }
+
+ while (enumeration.hasMoreTypes())
+ {
+ System.out.println(" Type ["+enumeration.nextType()+"]");
+ }
+
+ if (enumeration.lastIndex < descriptor.length())
+ {
+ System.out.println(" Return type ["+enumeration.returnType()+"]");
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/classfile/util/MemberFinder.java b/src/proguard/classfile/util/MemberFinder.java
new file mode 100644
index 000000000..36c000362
--- /dev/null
+++ b/src/proguard/classfile/util/MemberFinder.java
@@ -0,0 +1,197 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.*;
+
+/**
+ * This class provides methods to find class members in a given class or in its
+ * hierarchy.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberFinder
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private static class MemberFoundException extends RuntimeException {}
+ private static final MemberFoundException MEMBER_FOUND = new MemberFoundException();
+
+ private Clazz clazz;
+ private Member member;
+
+
+ /**
+ * Finds the field with the given name and descriptor in the given
+ * class or its hierarchy.
+ */
+ public Field findField(Clazz referencingClass,
+ Clazz clazz,
+ String name,
+ String descriptor)
+ {
+ return (Field)findMember(referencingClass, clazz, name, descriptor, true);
+ }
+
+
+ /**
+ * Finds the method with the given name and descriptor in the given
+ * class or its hierarchy.
+ */
+ public Method findMethod(Clazz referencingClass,
+ Clazz clazz,
+ String name,
+ String descriptor)
+ {
+ return (Method)findMember(referencingClass, clazz, name, descriptor, false);
+ }
+
+
+ /**
+ * Finds the class member with the given name and descriptor in the given
+ * class or its hierarchy.
+ */
+ public Member findMember(Clazz referencingClass,
+ Clazz clazz,
+ String name,
+ String descriptor,
+ boolean isField)
+ {
+ // Organize a search in the hierarchy of superclasses and interfaces.
+ // The class member may be in a different class, if the code was
+ // compiled with "-target 1.2" or higher (the default in JDK 1.4).
+ try
+ {
+ this.clazz = null;
+ this.member = null;
+ clazz.hierarchyAccept(true, true, true, false, isField ?
+ (ClassVisitor)new NamedFieldVisitor(name, descriptor,
+ new MemberClassAccessFilter(referencingClass, this)) :
+ (ClassVisitor)new NamedMethodVisitor(name, descriptor,
+ new MemberClassAccessFilter(referencingClass, this)));
+ }
+ catch (MemberFoundException ex)
+ {
+ // We've found the member we were looking for.
+ }
+
+ return member;
+ }
+
+
+ /**
+ * Returns the corresponding class of the most recently found class
+ * member.
+ */
+ public Clazz correspondingClass()
+ {
+ return clazz;
+ }
+
+
+ /**
+ * Returns whether the given method is overridden anywhere down the class
+ * hierarchy.
+ */
+ public boolean isOverriden(Clazz clazz,
+ Method method)
+ {
+ String name = method.getName(clazz);
+ String descriptor = method.getDescriptor(clazz);
+
+ // Go looking for the method down the class hierarchy.
+ try
+ {
+ this.clazz = null;
+ this.member = null;
+
+ clazz.hierarchyAccept(false, false, false, true,
+ new NamedMethodVisitor(name, descriptor,
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE, this)));
+ }
+ catch (MemberFoundException ex)
+ {
+ // We've found an overriding method.
+ return true;
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns whether the given field is shadowed anywhere down the class
+ * hierarchy.
+ */
+ public boolean isShadowed(Clazz clazz,
+ Field field)
+ {
+ String name = field.getName(clazz);
+ String descriptor = field.getDescriptor(clazz);
+
+ // Go looking for the field down the class hierarchy.
+ try
+ {
+ this.clazz = null;
+ this.member = null;
+ clazz.hierarchyAccept(false, false, false, true,
+ new NamedFieldVisitor(name, descriptor,
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE, this)));
+ }
+ catch (MemberFoundException ex)
+ {
+ // We've found a shadowing field.
+ return true;
+ }
+
+ return false;
+ }
+
+
+// // Implementations for ClassVisitor.
+//
+// private void visitAnyClass(Clazz clazz)
+// {
+// if (member == null)
+// {
+// member = isField ?
+// (Member)clazz.findField(name, descriptor) :
+// (Member)clazz.findMethod(name, descriptor);
+//
+// if (member != null)
+// {
+// this.clazz = clazz;
+// }
+// }
+// }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz clazz, Member member)
+ {
+ this.clazz = clazz;
+ this.member = member;
+
+ throw MEMBER_FOUND;
+ }
+}
diff --git a/src/proguard/classfile/util/MethodLinker.java b/src/proguard/classfile/util/MethodLinker.java
new file mode 100644
index 000000000..56b6723fb
--- /dev/null
+++ b/src/proguard/classfile/util/MethodLinker.java
@@ -0,0 +1,160 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.*;
+
+import java.util.*;
+
+/**
+ * This ClassVisitor links all corresponding non-private, non-static,
+ * non-initializer methods in the class hierarchies of all visited classes.
+ * Visited classes are typically all class files that are not being subclassed.
+ * Chains of links that have been created in previous invocations are merged
+ * with new chains of links, in order to create a consistent set of chains.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodLinker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor
+{
+ // An object that is reset and reused every time.
+ // The map: [class member name+' '+descriptor - class member info]
+ private final Map memberMap = new HashMap();
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitAnyClass(Clazz clazz)
+ {
+ // Collect all non-private members in this class hierarchy.
+ clazz.hierarchyAccept(true, true, true, false,
+ new AllMethodVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE | ClassConstants.INTERNAL_ACC_STATIC,
+ this)));
+
+ // Clean up for the next class hierarchy.
+ memberMap.clear();
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz clazz, Member member)
+ {
+ // Get the class member's name and descriptor.
+ String name = member.getName(clazz);
+ String descriptor = member.getDescriptor(clazz);
+
+ // Special cases: null
if it can't be found.
+ */
+ private Clazz findClass(String name)
+ {
+ // First look for the class in the program class pool.
+ Clazz clazz = programClassPool.getClass(name);
+
+ // Otherwise look for the class in the library class pool.
+ if (clazz == null)
+ {
+ clazz = libraryClassPool.getClass(name);
+ }
+
+ return clazz;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/util/StringSharer.java b/src/proguard/classfile/util/StringSharer.java
new file mode 100644
index 000000000..dacb2d13f
--- /dev/null
+++ b/src/proguard/classfile/util/StringSharer.java
@@ -0,0 +1,172 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor shares strings in the class files that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class StringSharer
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ AttributeVisitor
+{
+ // A fields acting as an argument for the visitor methods.
+ private String name;
+ private String type;
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Replace name strings in the constant pool by shared strings.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Replace attribute name strings in the constant pool by internalized
+ // strings.
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Replace the super class name string by the shared name string.
+ Clazz superClass = libraryClass.superClass;
+ if (superClass != null)
+ {
+ libraryClass.superClassName = superClass.getName();
+ }
+
+ // Replace the interface name strings by the shared name strings.
+ if (libraryClass.interfaceNames != null)
+ {
+ String[] interfaceNames = libraryClass.interfaceNames;
+ Clazz[] interfaceClasses = new Clazz[interfaceNames.length];
+
+ for (int index = 0; index < interfaceNames.length; index++)
+ {
+ // Keep a reference to the interface class.
+ Clazz interfaceClass = interfaceClasses[index];
+ if (interfaceClass != null)
+ {
+ interfaceNames[index] = interfaceClass.getName();
+ }
+ }
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ Member referencedMember = stringConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ Clazz referencedClass = stringConstant.referencedClass;
+
+ // Put the actual class member's name in the class pool.
+ name = referencedMember.getName(referencedClass);
+ clazz.constantPoolEntryAccept(stringConstant.u2stringIndex, this);
+ }
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ Member referencedMember = refConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ Clazz referencedClass = refConstant.referencedClass;
+
+ // Put the actual class member's name and type strings in the class
+ // pool.
+ name = referencedMember.getName(referencedClass);
+ type = referencedMember.getDescriptor(referencedClass);
+ clazz.constantPoolEntryAccept(refConstant.u2nameAndTypeIndex, this);
+ }
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ if (name != null)
+ {
+ // Put the actual class member's name and type strings in the class
+ // pool.
+ clazz.constantPoolEntryAccept(nameAndTypeConstant.u2nameIndex, this);
+ name = type;
+ clazz.constantPoolEntryAccept(nameAndTypeConstant.u2descriptorIndex, this);
+ }
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ Clazz referencedClass = classConstant.referencedClass;
+ if (referencedClass != null)
+ {
+ // Put the actual class's name string in the class pool.
+ name = referencedClass.getName();
+ clazz.constantPoolEntryAccept(classConstant.u2nameIndex, this);
+ }
+ }
+
+
+ public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)
+ {
+ // Do we have a new string to put into this constant?
+ if (name != null)
+ {
+ // Replace the string, if it's actually the same.
+ if (name.equals(utf8Constant.getString()))
+ {
+ utf8Constant.setString(name);
+ }
+
+ name = null;
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute)
+ {
+ // Put the internalized attribute's name string in the class pool.
+ name = attribute.getAttributeName(clazz).intern();
+ clazz.constantPoolEntryAccept(attribute.u2attributeNameIndex, this);
+ }
+}
diff --git a/src/proguard/classfile/util/WarningPrinter.java b/src/proguard/classfile/util/WarningPrinter.java
new file mode 100644
index 000000000..39172ddd6
--- /dev/null
+++ b/src/proguard/classfile/util/WarningPrinter.java
@@ -0,0 +1,136 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.util;
+
+import proguard.util.*;
+
+import java.io.PrintStream;
+import java.util.List;
+
+/**
+ * This class prints out and counts warnings.
+ *
+ * @author Eric Lafortune
+ */
+public class WarningPrinter
+{
+ private final PrintStream printStream;
+ private final StringMatcher classFilter;
+ private int warningCount;
+
+
+ /**
+ * Creates a new WarningPrinter that prints to the System.err print stream.
+ */
+ public WarningPrinter()
+ {
+ this(System.err);
+ }
+
+
+ /**
+ * Creates a new WarningPrinter that prints to the given print stream.
+ */
+ public WarningPrinter(PrintStream printStream)
+ {
+ this.printStream = printStream;
+ this.classFilter = null;
+ }
+
+
+ /**
+ * Creates a new WarningPrinter that prints to the given print stream,
+ * except if the names of any involved classes matches the given filter.
+ */
+ public WarningPrinter(PrintStream printStream, List classFilter)
+ {
+ this.printStream = printStream;
+ this.classFilter = classFilter == null ? null :
+ new ListParser(new ClassNameParser()).parse(classFilter);
+ }
+
+
+ /**
+ * Prints out the given warning and increments the warning count, if
+ * the given class name passes the class name filter.
+ */
+ public void print(String className, String warning)
+ {
+ if (accepts(className))
+ {
+ print(warning);
+ }
+ }
+
+
+ /**
+ * Returns whether the given class name passes the class name filter.
+ */
+ public boolean accepts(String className)
+ {
+ return classFilter == null ||
+ !classFilter.matches(className);
+ }
+
+
+ /**
+ * Prints out the given warning and increments the warning count, if
+ * the given class names pass the class name filter.
+ */
+ public void print(String className1, String className2, String warning)
+ {
+ if (accepts(className1, className2))
+ {
+ print(warning);
+ }
+ }
+
+
+ /**
+ * Returns whether the given class names pass the class name filter.
+ */
+ public boolean accepts(String className1, String className2)
+ {
+ return classFilter == null ||
+ !(classFilter.matches(className1) ||
+ classFilter.matches(className2));
+ }
+
+
+ /**
+ * Prints out the given warning and increments the warning count.
+ */
+ private void print(String warning)
+ {
+ printStream.println(warning);
+
+ warningCount++;
+ }
+
+
+ /**
+ * Returns the number of warnings printed so far.
+ */
+ public int getWarningCount()
+ {
+ return warningCount;
+ }
+}
diff --git a/src/proguard/classfile/util/package.html b/src/proguard/classfile/util/package.html
new file mode 100644
index 000000000..b1b881ec5
--- /dev/null
+++ b/src/proguard/classfile/util/package.html
@@ -0,0 +1,3 @@
+
+This package contains utility classes for processing class files.
+
diff --git a/src/proguard/classfile/visitor/AllClassVisitor.java b/src/proguard/classfile/visitor/AllClassVisitor.java
new file mode 100644
index 000000000..5c6f3defd
--- /dev/null
+++ b/src/proguard/classfile/visitor/AllClassVisitor.java
@@ -0,0 +1,47 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.ClassPool;
+
+
+/**
+ * This ClassPoolVisitor lets a given ClassVisitor visit all Clazz
+ * objects of the class pools it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllClassVisitor implements ClassPoolVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ public AllClassVisitor(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ public void visitClassPool(ClassPool classPool)
+ {
+ classPool.classesAccept(classVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/AllFieldVisitor.java b/src/proguard/classfile/visitor/AllFieldVisitor.java
new file mode 100644
index 000000000..92c4b0513
--- /dev/null
+++ b/src/proguard/classfile/visitor/AllFieldVisitor.java
@@ -0,0 +1,55 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor lets a given MemberVisitor visit all FieldMember
+ * objects of the classes it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllFieldVisitor implements ClassVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ public AllFieldVisitor(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.fieldsAccept(memberVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.fieldsAccept(memberVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/AllMemberVisitor.java b/src/proguard/classfile/visitor/AllMemberVisitor.java
new file mode 100644
index 000000000..ab26bf34e
--- /dev/null
+++ b/src/proguard/classfile/visitor/AllMemberVisitor.java
@@ -0,0 +1,57 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor lets a given MemberVisitor visit all Member
+ * objects of the classes it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllMemberVisitor implements ClassVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ public AllMemberVisitor(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.fieldsAccept(memberVisitor);
+ programClass.methodsAccept(memberVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.fieldsAccept(memberVisitor);
+ libraryClass.methodsAccept(memberVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/AllMethodVisitor.java b/src/proguard/classfile/visitor/AllMethodVisitor.java
new file mode 100644
index 000000000..5d8e6a39e
--- /dev/null
+++ b/src/proguard/classfile/visitor/AllMethodVisitor.java
@@ -0,0 +1,55 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor lets a given MemberVisitor visit all MethodMember
+ * objects of the classes it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AllMethodVisitor implements ClassVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ public AllMethodVisitor(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.methodsAccept(memberVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.methodsAccept(memberVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/BottomClassFilter.java b/src/proguard/classfile/visitor/BottomClassFilter.java
new file mode 100644
index 000000000..e094ce3b6
--- /dev/null
+++ b/src/proguard/classfile/visitor/BottomClassFilter.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, but only when visiting classes that don't
+ * have any subclasses.
+ *
+ * @author Eric Lafortune
+ */
+public class BottomClassFilter implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ProgramClassFilter.
+ * @param classVisitor the ClassVisitor
to which visits
+ * will be delegated.
+ */
+ public BottomClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Is this a bottom class in the class hierarchy?
+ if (programClass.subClasses == null)
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Is this a bottom class in the class hierarchy?
+ if (libraryClass.subClasses == null)
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassAccessFilter.java b/src/proguard/classfile/visitor/ClassAccessFilter.java
new file mode 100644
index 000000000..18556627f
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassAccessFilter.java
@@ -0,0 +1,88 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, but only when the visited class
+ * has the proper access flags.
+ *
+ * @see ClassConstants
+ *
+ * @author Eric Lafortune
+ */
+public class ClassAccessFilter implements ClassVisitor
+{
+ private final int requiredSetAccessFlags;
+ private final int requiredUnsetAccessFlags;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ClassAccessFilter.
+ * @param requiredSetAccessFlags the class access flags that should be
+ * set.
+ * @param requiredUnsetAccessFlags the class access flags that should be
+ * unset.
+ * @param classVisitor the ClassVisitor
to
+ * which visits will be delegated.
+ */
+ public ClassAccessFilter(int requiredSetAccessFlags,
+ int requiredUnsetAccessFlags,
+ ClassVisitor classVisitor)
+ {
+ this.requiredSetAccessFlags = requiredSetAccessFlags;
+ this.requiredUnsetAccessFlags = requiredUnsetAccessFlags;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (accepted(programClass.getAccessFlags()))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (accepted(libraryClass.getAccessFlags()))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(int accessFlags)
+ {
+ return (requiredSetAccessFlags & ~accessFlags) == 0 &&
+ (requiredUnsetAccessFlags & accessFlags) == 0;
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassCleaner.java b/src/proguard/classfile/visitor/ClassCleaner.java
new file mode 100644
index 000000000..a7ad1f6f7
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassCleaner.java
@@ -0,0 +1,275 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.preverification.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.Constant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ClassVisitor
removes all visitor information of the
+ * classes it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassCleaner
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ MemberVisitor,
+ AttributeVisitor,
+ ExceptionInfoVisitor,
+ InnerClassesInfoVisitor,
+ StackMapFrameVisitor,
+ VerificationTypeVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ clean(programClass);
+
+ programClass.constantPoolEntriesAccept(this);
+
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ clean(libraryClass);
+
+ libraryClass.fieldsAccept(this);
+ libraryClass.methodsAccept(this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant)
+ {
+ clean(constant);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ clean(programMember);
+
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ public void visitLibraryMember(LibraryClass libraryClass, LibraryMember libraryMember)
+ {
+ clean(libraryMember);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute)
+ {
+ clean(attribute);
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ clean(innerClassesAttribute);
+
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ clean(exceptionsAttribute);
+
+ exceptionsAttribute.exceptionEntriesAccept((ProgramClass)clazz, this);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ clean(codeAttribute);
+
+ codeAttribute.exceptionsAccept(clazz, method, this);
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ clean(stackMapAttribute);
+
+ stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ clean(stackMapTableAttribute);
+
+ stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ clean(annotationsAttribute);
+
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ clean(parameterAnnotationsAttribute);
+
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ clean(annotationDefaultAttribute);
+
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ clean(innerClassesInfo);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ clean(exceptionInfo);
+ }
+
+
+ // Implementations for StackMapFrameVisitor.
+
+ public void visitSameZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameZeroFrame sameZeroFrame)
+ {
+ clean(sameZeroFrame);
+ }
+
+
+ public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)
+ {
+ clean(sameOneFrame);
+
+ sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitLessZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LessZeroFrame lessZeroFrame)
+ {
+ clean(lessZeroFrame);
+ }
+
+
+ public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame)
+ {
+ clean(moreZeroFrame);
+
+ moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame)
+ {
+ clean(fullFrame);
+
+ fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this);
+ fullFrame.stackAccept(clazz, method, codeAttribute, offset, this);
+ }
+
+
+ // Implementations for VerificationTypeVisitor.
+
+ public void visitAnyVerificationType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationType verificationType)
+ {
+ clean(verificationType);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ clean(annotation);
+
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitAnyElementValue(Clazz clazz, Annotation annotation, ElementValue elementValue)
+ {
+ clean(elementValue);
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ clean(annotationElementValue);
+
+ annotationElementValue.annotationAccept(clazz, this);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ clean(arrayElementValue);
+ }
+
+
+ // Small utility methods.
+
+ private void clean(VisitorAccepter visitorAccepter)
+ {
+ visitorAccepter.setVisitorInfo(null);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassCollector.java b/src/proguard/classfile/visitor/ClassCollector.java
new file mode 100644
index 000000000..a24bb0b2b
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassCollector.java
@@ -0,0 +1,58 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.util.SimplifiedVisitor;
+
+import java.util.Set;
+
+/**
+ * This ClassVisitor
collects the classes that it visits in the
+ * given collection.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassCollector
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final Set set;
+
+
+ /**
+ * Creates a new ClassCollector.
+ * @param set the Set
in which all class names will be
+ * collected.
+ */
+ public ClassCollector(Set set)
+ {
+ this.set = set;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitAnyClass(Clazz clazz)
+ {
+ set.add(clazz);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassCounter.java b/src/proguard/classfile/visitor/ClassCounter.java
new file mode 100644
index 000000000..b6deef2b6
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassCounter.java
@@ -0,0 +1,56 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This ClassVisitor counts the number of classes that has been visited.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassCounter implements ClassVisitor
+{
+ private int count;
+
+
+ /**
+ * Returns the number of classes that has been visited so far.
+ */
+ public int getCount()
+ {
+ return count;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ count++;
+ }
+
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ count++;
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassHierarchyTraveler.java b/src/proguard/classfile/visitor/ClassHierarchyTraveler.java
new file mode 100644
index 000000000..38ba3d624
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassHierarchyTraveler.java
@@ -0,0 +1,91 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor
lets a given ClassVisitor
+ * optionally travel to the visited class, its superclass, its interfaces, and
+ * its subclasses.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassHierarchyTraveler implements ClassVisitor
+{
+ private final boolean visitThisClass;
+ private final boolean visitSuperClass;
+ private final boolean visitInterfaces;
+ private final boolean visitSubclasses;
+
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ClassHierarchyTraveler.
+ * @param visitThisClass specifies whether to visit the originally visited
+ * classes.
+ * @param visitSuperClass specifies whether to visit the super classes of
+ * the visited classes.
+ * @param visitInterfaces specifies whether to visit the interfaces of
+ * the visited classes.
+ * @param visitSubclasses specifies whether to visit the subclasses of
+ * the visited classes.
+ * @param classVisitor the ClassVisitor
to
+ * which visits will be delegated.
+ */
+ public ClassHierarchyTraveler(boolean visitThisClass,
+ boolean visitSuperClass,
+ boolean visitInterfaces,
+ boolean visitSubclasses,
+ ClassVisitor classVisitor)
+ {
+ this.visitThisClass = visitThisClass;
+ this.visitSuperClass = visitSuperClass;
+ this.visitInterfaces = visitInterfaces;
+ this.visitSubclasses = visitSubclasses;
+
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.hierarchyAccept(visitThisClass,
+ visitSuperClass,
+ visitInterfaces,
+ visitSubclasses,
+ classVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.hierarchyAccept(visitThisClass,
+ visitSuperClass,
+ visitInterfaces,
+ visitSubclasses,
+ classVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassNameFilter.java b/src/proguard/classfile/visitor/ClassNameFilter.java
new file mode 100644
index 000000000..bd66eb1c7
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassNameFilter.java
@@ -0,0 +1,112 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.util.*;
+
+import java.util.List;
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, but only when the visited class has a name that
+ * matches a given regular expression.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassNameFilter implements ClassVisitor
+{
+ private final StringMatcher regularExpressionMatcher;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ClassNameFilter.
+ * @param regularExpression the regular expression against which class names
+ * will be matched.
+ * @param classVisitor the ClassVisitor
to which visits
+ * will be delegated.
+ */
+ public ClassNameFilter(String regularExpression,
+ ClassVisitor classVisitor)
+ {
+ this(new ListParser(new ClassNameParser()).parse(regularExpression),
+ classVisitor);
+ }
+
+
+ /**
+ * Creates a new ClassNameFilter.
+ * @param regularExpression the regular expression against which class names
+ * will be matched.
+ * @param classVisitor the ClassVisitor
to which visits
+ * will be delegated.
+ */
+ public ClassNameFilter(List regularExpression,
+ ClassVisitor classVisitor)
+ {
+ this(new ListParser(new ClassNameParser()).parse(regularExpression),
+ classVisitor);
+ }
+
+
+ /**
+ * Creates a new ClassNameFilter.
+ * @param regularExpressionMatcher the string matcher against which
+ * class names will be matched.
+ * @param classVisitor the ClassVisitor
to which
+ * visits will be delegated.
+ */
+ public ClassNameFilter(StringMatcher regularExpressionMatcher,
+ ClassVisitor classVisitor)
+ {
+ this.regularExpressionMatcher = regularExpressionMatcher;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (accepted(programClass.getName()))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (accepted(libraryClass.getName()))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(String name)
+ {
+ return regularExpressionMatcher.matches(name);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassPoolFiller.java b/src/proguard/classfile/visitor/ClassPoolFiller.java
new file mode 100644
index 000000000..ae234bef9
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassPoolFiller.java
@@ -0,0 +1,55 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+
+/**
+ * This ClassVisitor collects all the classes it visits in a given
+ * class pool.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassPoolFiller
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final ClassPool classPool;
+
+
+ /**
+ * Creates a new ClassPoolFiller.
+ */
+ public ClassPoolFiller(ClassPool classPool)
+ {
+ this.classPool = classPool;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitAnyClass(Clazz clazz)
+ {
+ classPool.addClass(clazz);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassPoolVisitor.java b/src/proguard/classfile/visitor/ClassPoolVisitor.java
new file mode 100644
index 000000000..821304ac9
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassPoolVisitor.java
@@ -0,0 +1,37 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.ClassPool;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * ClassPool
objects. Note that there is only a single
+ * implementation of ClassPool
, such that this interface
+ * is not strictly necessary as a visitor.
+ *
+ * @author Eric Lafortune
+ */
+public interface ClassPoolVisitor
+{
+ public void visitClassPool(ClassPool classPool);
+}
diff --git a/src/proguard/classfile/visitor/ClassPresenceFilter.java b/src/proguard/classfile/visitor/ClassPresenceFilter.java
new file mode 100644
index 000000000..0c55d1d16
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassPresenceFilter.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This ClassVisitor
delegates its visits to one of two
+ * ClassVisitor
instances, depending on whether the name of
+ * the visited class file is present in a given ClassPool
or not.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassPresenceFilter implements ClassVisitor
+{
+ private final ClassPool classPool;
+ private final ClassVisitor presentClassVisitor;
+ private final ClassVisitor missingClassVisitor;
+
+
+ /**
+ * Creates a new ClassPresenceFilter.
+ * @param classPool the ClassPool
in which the
+ * presence will be tested.
+ * @param presentClassVisitor the ClassVisitor
to which visits
+ * of present class files will be delegated.
+ * @param missingClassVisitor the ClassVisitor
to which visits
+ * of missing class files will be delegated.
+ */
+ public ClassPresenceFilter(ClassPool classPool,
+ ClassVisitor presentClassVisitor,
+ ClassVisitor missingClassVisitor)
+ {
+ this.classPool = classPool;
+ this.presentClassVisitor = presentClassVisitor;
+ this.missingClassVisitor = missingClassVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ ClassVisitor classFileVisitor = classFileVisitor(programClass);
+
+ if (classFileVisitor != null)
+ {
+ classFileVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ ClassVisitor classFileVisitor = classFileVisitor(libraryClass);
+
+ if (classFileVisitor != null)
+ {
+ classFileVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the appropriate ClassVisitor
.
+ */
+ private ClassVisitor classFileVisitor(Clazz clazz)
+ {
+ return classPool.getClass(clazz.getName()) != null ?
+ presentClassVisitor :
+ missingClassVisitor;
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassPrinter.java b/src/proguard/classfile/visitor/ClassPrinter.java
new file mode 100644
index 000000000..3121e58de
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassPrinter.java
@@ -0,0 +1,1012 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.preverification.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+
+import java.io.PrintStream;
+
+
+/**
+ * This ClassVisitor
prints out the complete internal
+ * structure of the classes it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassPrinter
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ MemberVisitor,
+ AttributeVisitor,
+ BootstrapMethodInfoVisitor,
+ InnerClassesInfoVisitor,
+ ExceptionInfoVisitor,
+ StackMapFrameVisitor,
+ VerificationTypeVisitor,
+ LineNumberInfoVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor,
+ InstructionVisitor
+{
+ private static final String INDENTATION = " ";
+
+ private final PrintStream ps;
+
+ private int indentation;
+
+
+ /**
+ * Creates a new ClassPrinter that prints to System.out
.
+ */
+ public ClassPrinter()
+ {
+ this(System.out);
+ }
+
+
+ /**
+ * Creates a new ClassPrinter that prints to the given
+ * PrintStream
.
+ */
+ public ClassPrinter(PrintStream printStream)
+ {
+ ps = printStream;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ println("_____________________________________________________________________");
+ println(visitorInfo(programClass) + " " +
+ "Program class: " + programClass.getName());
+ indent();
+ println("Superclass: " + programClass.getSuperName());
+ println("Major version: 0x" + Integer.toHexString(ClassUtil.internalMajorClassVersion(programClass.u4version)));
+ println("Minor version: 0x" + Integer.toHexString(ClassUtil.internalMinorClassVersion(programClass.u4version)));
+ println(" = target " + ClassUtil.externalClassVersion(programClass.u4version));
+ println("Access flags: 0x" + Integer.toHexString(programClass.u2accessFlags));
+ println(" = " +
+ ((programClass.u2accessFlags & ClassConstants.INTERNAL_ACC_ANNOTATTION) != 0 ? "@ " : "") +
+ ClassUtil.externalClassAccessFlags(programClass.u2accessFlags) +
+ ((programClass.u2accessFlags & ClassConstants.INTERNAL_ACC_ENUM) != 0 ? "enum " :
+ (programClass.u2accessFlags & ClassConstants.INTERNAL_ACC_INTERFACE) == 0 ? "class " :
+ "") +
+ ClassUtil.externalClassName(programClass.getName()) +
+ (programClass.u2superClass == 0 ? "" : " extends " +
+ ClassUtil.externalClassName(programClass.getSuperName())));
+ outdent();
+ println();
+
+ println("Interfaces (count = " + programClass.u2interfacesCount + "):");
+ indent();
+ programClass.interfaceConstantsAccept(this);
+ outdent();
+ println();
+
+ println("Constant Pool (count = " + programClass.u2constantPoolCount + "):");
+ indent();
+ programClass.constantPoolEntriesAccept(this);
+ outdent();
+ println();
+
+ println("Fields (count = " + programClass.u2fieldsCount + "):");
+ indent();
+ programClass.fieldsAccept(this);
+ outdent();
+ println();
+
+ println("Methods (count = " + programClass.u2methodsCount + "):");
+ indent();
+ programClass.methodsAccept(this);
+ outdent();
+ println();
+
+ println("Class file attributes (count = " + programClass.u2attributesCount + "):");
+ indent();
+ programClass.attributesAccept(this);
+ outdent();
+ println();
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ println("_____________________________________________________________________");
+ println(visitorInfo(libraryClass) + " " +
+ "Library class: " + libraryClass.getName());
+ indent();
+ println("Superclass: " + libraryClass.getSuperName());
+ println("Access flags: 0x" + Integer.toHexString(libraryClass.u2accessFlags));
+ println(" = " +
+ ((libraryClass.u2accessFlags & ClassConstants.INTERNAL_ACC_ANNOTATTION) != 0 ? "@ " : "") +
+ ClassUtil.externalClassAccessFlags(libraryClass.u2accessFlags) +
+ ((libraryClass.u2accessFlags & ClassConstants.INTERNAL_ACC_ENUM) != 0 ? "enum " :
+ (libraryClass.u2accessFlags & ClassConstants.INTERNAL_ACC_INTERFACE) == 0 ? "class " :
+ "") +
+ ClassUtil.externalClassName(libraryClass.getName()) +
+ (libraryClass.getSuperName() == null ? "" : " extends " +
+ ClassUtil.externalClassName(libraryClass.getSuperName())));
+ outdent();
+ println();
+
+ println("Interfaces (count = " + libraryClass.interfaceClasses.length + "):");
+ for (int index = 0; index < libraryClass.interfaceClasses.length; index++)
+ {
+ Clazz interfaceClass = libraryClass.interfaceClasses[index];
+ if (interfaceClass != null)
+ {
+ println(" + " + interfaceClass.getName());
+ }
+ }
+
+ println("Fields (count = " + libraryClass.fields.length + "):");
+ libraryClass.fieldsAccept(this);
+
+ println("Methods (count = " + libraryClass.methods.length + "):");
+ libraryClass.methodsAccept(this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)
+ {
+ println(visitorInfo(integerConstant) + " Integer [" +
+ integerConstant.getValue() + "]");
+ }
+
+
+ public void visitLongConstant(Clazz clazz, LongConstant longConstant)
+ {
+ println(visitorInfo(longConstant) + " Long [" +
+ longConstant.getValue() + "]");
+ }
+
+
+ public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)
+ {
+ println(visitorInfo(floatConstant) + " Float [" +
+ floatConstant.getValue() + "]");
+ }
+
+
+ public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)
+ {
+ println(visitorInfo(doubleConstant) + " Double [" +
+ doubleConstant.getValue() + "]");
+ }
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ println(visitorInfo(stringConstant) + " String [" +
+ clazz.getString(stringConstant.u2stringIndex) + "]");
+ }
+
+
+ public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)
+ {
+ println(visitorInfo(utf8Constant) + " Utf8 [" +
+ utf8Constant.getString() + "]");
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ println(visitorInfo(invokeDynamicConstant) + " InvokeDynamic [bootstrap method index = " + invokeDynamicConstant.u2bootstrapMethodAttributeIndex + "]:");
+
+ indent();
+ clazz.constantPoolEntryAccept(invokeDynamicConstant.u2nameAndTypeIndex, this);
+ outdent();
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ println(visitorInfo(methodHandleConstant) + " MethodHandle [kind = " + methodHandleConstant.u1referenceKind + "]:");
+
+ indent();
+ clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex, this);
+ outdent();
+ }
+
+
+ public void visitFieldrefConstant(Clazz clazz, FieldrefConstant fieldrefConstant)
+ {
+ println(visitorInfo(fieldrefConstant) + " Fieldref [" +
+ clazz.getClassName(fieldrefConstant.u2classIndex) + "." +
+ clazz.getName(fieldrefConstant.u2nameAndTypeIndex) + " " +
+ clazz.getType(fieldrefConstant.u2nameAndTypeIndex) + "]");
+ }
+
+
+ public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant)
+ {
+ println(visitorInfo(interfaceMethodrefConstant) + " InterfaceMethodref [" +
+ clazz.getClassName(interfaceMethodrefConstant.u2classIndex) + "." +
+ clazz.getName(interfaceMethodrefConstant.u2nameAndTypeIndex) + " " +
+ clazz.getType(interfaceMethodrefConstant.u2nameAndTypeIndex) + "]");
+ }
+
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ println(visitorInfo(methodrefConstant) + " Methodref [" +
+ clazz.getClassName(methodrefConstant.u2classIndex) + "." +
+ clazz.getName(methodrefConstant.u2nameAndTypeIndex) + " " +
+ clazz.getType(methodrefConstant.u2nameAndTypeIndex) + "]");
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ println(visitorInfo(classConstant) + " Class [" +
+ clazz.getString(classConstant.u2nameIndex) + "]");
+ }
+
+
+ public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
+ {
+ println(visitorInfo(methodTypeConstant) + " MethodType [" +
+ clazz.getString(methodTypeConstant.u2descriptorIndex) + "]");
+ }
+
+
+ public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
+ {
+ println(visitorInfo(nameAndTypeConstant) + " NameAndType [" +
+ clazz.getString(nameAndTypeConstant.u2nameIndex) + " " +
+ clazz.getString(nameAndTypeConstant.u2descriptorIndex) + "]");
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ println(visitorInfo(programField) + " " +
+ "Field: " +
+ programField.getName(programClass) + " " +
+ programField.getDescriptor(programClass));
+
+ indent();
+ println("Access flags: 0x" + Integer.toHexString(programField.u2accessFlags));
+ println(" = " +
+ ClassUtil.externalFullFieldDescription(programField.u2accessFlags,
+ programField.getName(programClass),
+ programField.getDescriptor(programClass)));
+
+ visitMember(programClass, programField);
+ outdent();
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ println(visitorInfo(programMethod) + " " +
+ "Method: " +
+ programMethod.getName(programClass) +
+ programMethod.getDescriptor(programClass));
+
+ indent();
+ println("Access flags: 0x" + Integer.toHexString(programMethod.u2accessFlags));
+ println(" = " +
+ ClassUtil.externalFullMethodDescription(programClass.getName(),
+ programMethod.u2accessFlags,
+ programMethod.getName(programClass),
+ programMethod.getDescriptor(programClass)));
+
+ visitMember(programClass, programMethod);
+ outdent();
+ }
+
+
+ private void visitMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ if (programMember.u2attributesCount > 0)
+ {
+ println("Class member attributes (count = " + programMember.u2attributesCount + "):");
+ programMember.attributesAccept(programClass, this);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ println(visitorInfo(libraryField) + " " +
+ "Field: " +
+ libraryField.getName(libraryClass) + " " +
+ libraryField.getDescriptor(libraryClass));
+
+ indent();
+ println("Access flags: 0x" + Integer.toHexString(libraryField.u2accessFlags));
+ println(" = " +
+ ClassUtil.externalFullFieldDescription(libraryField.u2accessFlags,
+ libraryField.getName(libraryClass),
+ libraryField.getDescriptor(libraryClass)));
+ outdent();
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ println(visitorInfo(libraryMethod) + " " +
+ "Method: " +
+ libraryMethod.getName(libraryClass) + " " +
+ libraryMethod.getDescriptor(libraryClass));
+
+ indent();
+ println("Access flags: 0x" + Integer.toHexString(libraryMethod.u2accessFlags));
+ println(" = " +
+ ClassUtil.externalFullMethodDescription(libraryClass.getName(),
+ libraryMethod.u2accessFlags,
+ libraryMethod.getName(libraryClass),
+ libraryMethod.getDescriptor(libraryClass)));
+ outdent();
+ }
+
+
+ // Implementations for AttributeVisitor.
+ // Note that attributes are typically only referenced once, so we don't
+ // test if they are marked already.
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ println(visitorInfo(unknownAttribute) +
+ " Unknown attribute (" + clazz.getString(unknownAttribute.u2attributeNameIndex) + ")");
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ println(visitorInfo(bootstrapMethodsAttribute) +
+ " Bootstrap methods attribute (count = " + bootstrapMethodsAttribute.u2bootstrapMethodsCount + "):");
+
+ indent();
+ bootstrapMethodsAttribute.bootstrapMethodEntriesAccept(clazz, this);
+ outdent();
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ println(visitorInfo(sourceFileAttribute) +
+ " Source file attribute:");
+
+ indent();
+ clazz.constantPoolEntryAccept(sourceFileAttribute.u2sourceFileIndex, this);
+ outdent();
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ println(visitorInfo(sourceDirAttribute) +
+ " Source dir attribute:");
+
+ indent();
+ clazz.constantPoolEntryAccept(sourceDirAttribute.u2sourceDirIndex, this);
+ outdent();
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ println(visitorInfo(innerClassesAttribute) +
+ " Inner classes attribute (count = " + innerClassesAttribute.u2classesCount + ")");
+
+ indent();
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ outdent();
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ println(visitorInfo(enclosingMethodAttribute) +
+ " Enclosing method attribute:");
+
+ indent();
+ clazz.constantPoolEntryAccept(enclosingMethodAttribute.u2classIndex, this);
+
+ if (enclosingMethodAttribute.u2nameAndTypeIndex != 0)
+ {
+ clazz.constantPoolEntryAccept(enclosingMethodAttribute.u2nameAndTypeIndex, this);
+ }
+ outdent();
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ println(visitorInfo(deprecatedAttribute) +
+ " Deprecated attribute");
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ println(visitorInfo(syntheticAttribute) +
+ " Synthetic attribute");
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ println(visitorInfo(signatureAttribute) +
+ " Signature attribute:");
+
+ indent();
+ clazz.constantPoolEntryAccept(signatureAttribute.u2signatureIndex, this);
+ outdent();
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ println(visitorInfo(constantValueAttribute) +
+ " Constant value attribute:");
+
+ clazz.constantPoolEntryAccept(constantValueAttribute.u2constantValueIndex, this);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ println(visitorInfo(exceptionsAttribute) +
+ " Exceptions attribute (count = " + exceptionsAttribute.u2exceptionIndexTableLength + ")");
+
+ indent();
+ exceptionsAttribute.exceptionEntriesAccept((ProgramClass)clazz, this);
+ outdent();
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ println(visitorInfo(codeAttribute) +
+ " Code attribute instructions (code length = "+ codeAttribute.u4codeLength +
+ ", locals = "+ codeAttribute.u2maxLocals +
+ ", stack = "+ codeAttribute.u2maxStack + "):");
+
+ indent();
+
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ println("Code attribute exceptions (count = " +
+ codeAttribute.u2exceptionTableLength + "):");
+
+ codeAttribute.exceptionsAccept(clazz, method, this);
+
+ println("Code attribute attributes (attribute count = " +
+ codeAttribute.u2attributesCount + "):");
+
+ codeAttribute.attributesAccept(clazz, method, this);
+
+ outdent();
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ println(visitorInfo(codeAttribute) +
+ " Stack map attribute (count = "+
+ stackMapAttribute.u2stackMapFramesCount + "):");
+
+ indent();
+ stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ outdent();
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ println(visitorInfo(codeAttribute) +
+ " Stack map table attribute (count = "+
+ stackMapTableAttribute.u2stackMapFramesCount + "):");
+
+ indent();
+ stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
+ outdent();
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ println(visitorInfo(lineNumberTableAttribute) +
+ " Line number table attribute (count = " +
+ lineNumberTableAttribute.u2lineNumberTableLength + ")");
+
+ indent();
+ lineNumberTableAttribute.lineNumbersAccept(clazz, method, codeAttribute, this);
+ outdent();
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ println(visitorInfo(localVariableTableAttribute) +
+ " Local variable table attribute (count = " +
+ localVariableTableAttribute.u2localVariableTableLength + ")");
+
+ indent();
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ outdent();
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ println(visitorInfo(localVariableTypeTableAttribute) +
+ " Local variable type table attribute (count = "+
+ localVariableTypeTableAttribute.u2localVariableTypeTableLength + ")");
+
+ indent();
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ outdent();
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ println(visitorInfo(runtimeVisibleAnnotationsAttribute) +
+ " Runtime visible annotations attribute:");
+
+ indent();
+ runtimeVisibleAnnotationsAttribute.annotationsAccept(clazz, this);
+ outdent();
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ println(visitorInfo(runtimeInvisibleAnnotationsAttribute) +
+ " Runtime invisible annotations attribute:");
+
+ indent();
+ runtimeInvisibleAnnotationsAttribute.annotationsAccept(clazz, this);
+ outdent();
+ }
+
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute)
+ {
+ println(visitorInfo(runtimeVisibleParameterAnnotationsAttribute) +
+ " Runtime visible parameter annotations attribute (parameter count = " + runtimeVisibleParameterAnnotationsAttribute.u2parametersCount + "):");
+
+ indent();
+ runtimeVisibleParameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ outdent();
+ }
+
+
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute)
+ {
+ println(visitorInfo(runtimeInvisibleParameterAnnotationsAttribute) +
+ " Runtime invisible parameter annotations attribute (parameter count = " + runtimeInvisibleParameterAnnotationsAttribute.u2parametersCount + "):");
+
+ indent();
+ runtimeInvisibleParameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ outdent();
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ println(visitorInfo(annotationDefaultAttribute) +
+ " Annotation default attribute:");
+
+ indent();
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ outdent();
+ }
+
+
+ // Implementations for BootstrapMethodInfoVisitor.
+
+ public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo)
+ {
+ println(visitorInfo(bootstrapMethodInfo) +
+ " BootstrapMethodInfo (argument count = " +
+ bootstrapMethodInfo.u2methodArgumentCount+ "):");
+
+ indent();
+ clazz.constantPoolEntryAccept(bootstrapMethodInfo.u2methodHandleIndex, this);
+ bootstrapMethodInfo.methodArgumentsAccept(clazz, this);
+ outdent();
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ println(visitorInfo(innerClassesInfo) +
+ " InnerClassesInfo:");
+
+ indent();
+ println("Access flags: 0x" + Integer.toHexString(innerClassesInfo.u2innerClassAccessFlags) + " = " +
+ ClassUtil.externalClassAccessFlags(innerClassesInfo.u2innerClassAccessFlags));
+ innerClassesInfo.innerClassConstantAccept(clazz, this);
+ innerClassesInfo.outerClassConstantAccept(clazz, this);
+ innerClassesInfo.innerNameConstantAccept(clazz, this);
+ outdent();
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ println(instruction.toString(offset));
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ println(constantInstruction.toString(offset));
+
+ indent();
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ outdent();
+ }
+
+
+ public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction)
+ {
+ println(tableSwitchInstruction.toString(offset));
+
+ indent();
+
+ int[] jumpOffsets = tableSwitchInstruction.jumpOffsets;
+
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ int jumpOffset = jumpOffsets[index];
+ println(Integer.toString(tableSwitchInstruction.lowCase + index) + ": offset = " + jumpOffset + ", target = " + (offset + jumpOffset));
+ }
+
+ int defaultOffset = tableSwitchInstruction.defaultOffset;
+ println("default: offset = " + defaultOffset + ", target = "+ (offset + defaultOffset));
+
+ outdent();
+ }
+
+
+ public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction)
+ {
+ println(lookUpSwitchInstruction.toString(offset));
+
+ indent();
+
+ int[] cases = lookUpSwitchInstruction.cases;
+ int[] jumpOffsets = lookUpSwitchInstruction.jumpOffsets;
+
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ int jumpOffset = jumpOffsets[index];
+ println(Integer.toString(cases[index]) + ": offset = " + jumpOffset + ", target = " + (offset + jumpOffset));
+ }
+
+ int defaultOffset = lookUpSwitchInstruction.defaultOffset;
+ println("default: offset = " + defaultOffset + ", target = "+ (offset + defaultOffset));
+
+ outdent();
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ println(visitorInfo(exceptionInfo) +
+ " ExceptionInfo (" +
+ exceptionInfo.u2startPC + " -> " +
+ exceptionInfo.u2endPC + ": " +
+ exceptionInfo.u2handlerPC + "):");
+
+ if (exceptionInfo.u2catchType != 0)
+ {
+ clazz.constantPoolEntryAccept(exceptionInfo.u2catchType, this);
+ }
+ }
+
+
+ // Implementations for StackMapFrameVisitor.
+
+ public void visitSameZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameZeroFrame sameZeroFrame)
+ {
+ println(visitorInfo(sameZeroFrame) +
+ " [" + offset + "]" +
+ " Var: ..., Stack: (empty)");
+ }
+
+
+ public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)
+ {
+ print(visitorInfo(sameOneFrame) +
+ " [" + offset + "]" +
+ " Var: ..., Stack: ");
+
+ sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this);
+
+ println();
+ }
+
+
+ public void visitLessZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LessZeroFrame lessZeroFrame)
+ {
+ println(visitorInfo(lessZeroFrame) +
+ " [" + offset + "]" +
+ " Var: -" + lessZeroFrame.choppedVariablesCount +
+ ", Stack: (empty)");
+ }
+
+
+ public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame)
+ {
+ print(visitorInfo(moreZeroFrame) +
+ " [" + offset + "]" +
+ " Var: ...");
+
+ moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this);
+
+ ps.println(", Stack: (empty)");
+ }
+
+
+ public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame)
+ {
+ print(visitorInfo(fullFrame) +
+ " [" + offset + "]" +
+ " Var: ");
+
+ fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this);
+
+ ps.print(", Stack: ");
+
+ fullFrame.stackAccept(clazz, method, codeAttribute, offset, this);
+
+ println();
+ }
+
+
+ // Implementations for VerificationTypeVisitor.
+
+ public void visitIntegerType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, IntegerType integerType)
+ {
+ ps.print("[i]");
+ }
+
+
+ public void visitFloatType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FloatType floatType)
+ {
+ ps.print("[f]");
+ }
+
+
+ public void visitLongType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LongType longType)
+ {
+ ps.print("[l]");
+ }
+
+
+ public void visitDoubleType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, DoubleType doubleType)
+ {
+ ps.print("[d]");
+ }
+
+
+ public void visitTopType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TopType topType)
+ {
+ ps.print("[T]");
+ }
+
+
+ public void visitObjectType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ObjectType objectType)
+ {
+ ps.print("[a:" + clazz.getClassName(objectType.u2classIndex) + "]");
+ }
+
+
+ public void visitNullType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, NullType nullType)
+ {
+ ps.print("[n]");
+ }
+
+
+ public void visitUninitializedType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedType uninitializedType)
+ {
+ ps.print("[u:" + uninitializedType.u2newInstructionOffset + "]");
+ }
+
+
+ public void visitUninitializedThisType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, UninitializedThisType uninitializedThisType)
+ {
+ ps.print("[u:this]");
+ }
+
+
+ // Implementations for LineNumberInfoVisitor.
+
+ public void visitLineNumberInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberInfo lineNumberInfo)
+ {
+ println("[" + lineNumberInfo.u2startPC + "] -> line " +
+ lineNumberInfo.u2lineNumber);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ println("v" + localVariableInfo.u2index + ": " +
+ localVariableInfo.u2startPC + " -> " +
+ (localVariableInfo.u2startPC + localVariableInfo.u2length) + " [" +
+ clazz.getString(localVariableInfo.u2descriptorIndex) + " " +
+ clazz.getString(localVariableInfo.u2nameIndex) + "]");
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ println("v" + localVariableTypeInfo.u2index + ": " +
+ localVariableTypeInfo.u2startPC + " -> " +
+ (localVariableTypeInfo.u2startPC + localVariableTypeInfo.u2length) + " [" +
+ clazz.getString(localVariableTypeInfo.u2signatureIndex) + " " +
+ clazz.getString(localVariableTypeInfo.u2nameIndex) + "]");
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ println(visitorInfo(annotation) +
+ " Annotation [" + clazz.getString(annotation.u2typeIndex) + "]:");
+
+ indent();
+ annotation.elementValuesAccept(clazz, this);
+ outdent();
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitConstantElementValue(Clazz clazz, Annotation annotation, ConstantElementValue constantElementValue)
+ {
+ println(visitorInfo(constantElementValue) +
+ " Constant element value [" +
+ (constantElementValue.u2elementNameIndex == 0 ? "(default)" :
+ clazz.getString(constantElementValue.u2elementNameIndex)) + " '" +
+ constantElementValue.u1tag + "']");
+
+ indent();
+ clazz.constantPoolEntryAccept(constantElementValue.u2constantValueIndex, this);
+ outdent();
+ }
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ println(visitorInfo(enumConstantElementValue) +
+ " Enum constant element value [" +
+ (enumConstantElementValue.u2elementNameIndex == 0 ? "(default)" :
+ clazz.getString(enumConstantElementValue.u2elementNameIndex)) + ", " +
+ clazz.getString(enumConstantElementValue.u2typeNameIndex) + ", " +
+ clazz.getString(enumConstantElementValue.u2constantNameIndex) + "]");
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ println(visitorInfo(classElementValue) +
+ " Class element value [" +
+ (classElementValue.u2elementNameIndex == 0 ? "(default)" :
+ clazz.getString(classElementValue.u2elementNameIndex)) + ", " +
+ clazz.getString(classElementValue.u2classInfoIndex) + "]");
+ }
+
+
+ public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
+ {
+ println(visitorInfo(annotationElementValue) +
+ " Annotation element value [" +
+ (annotationElementValue.u2elementNameIndex == 0 ? "(default)" :
+ clazz.getString(annotationElementValue.u2elementNameIndex)) + "]:");
+
+ indent();
+ annotationElementValue.annotationAccept(clazz, this);
+ outdent();
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ println(visitorInfo(arrayElementValue) +
+ " Array element value [" +
+ (arrayElementValue.u2elementNameIndex == 0 ? "(default)" :
+ clazz.getString(arrayElementValue.u2elementNameIndex)) + "]:");
+
+ indent();
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ outdent();
+ }
+
+
+ // Small utility methods.
+
+ private void indent()
+ {
+ indentation++;
+ }
+
+ private void outdent()
+ {
+ indentation--;
+ }
+
+ private void println(String string)
+ {
+ print(string);
+ println();
+
+ }
+
+ private void print(String string)
+ {
+ for (int index = 0; index < indentation; index++)
+ {
+ ps.print(INDENTATION);
+ }
+
+ ps.print(string);
+ }
+
+ private void println()
+ {
+ ps.println();
+ }
+
+
+ private String visitorInfo(VisitorAccepter visitorAccepter)
+ {
+ return visitorAccepter.getVisitorInfo() == null ? "-" : "+";
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassVersionFilter.java b/src/proguard/classfile/visitor/ClassVersionFilter.java
new file mode 100644
index 000000000..73bcc6a0c
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassVersionFilter.java
@@ -0,0 +1,85 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This ClassVisitor
delegates its visits to program classes to
+ * another given ClassVisitor
, but only when the class version
+ * number of the visited program class lies in a given range.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassVersionFilter implements ClassVisitor
+{
+ private final int minimumClassVersion;
+ private final int maximumClassVersion;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ClassVersionFilter.
+ * @param minimumClassVersion the minimum class version number.
+ * @param classVisitor the ClassVisitor
to which visits
+ * will be delegated.
+ */
+ public ClassVersionFilter(int minimumClassVersion,
+ ClassVisitor classVisitor)
+ {
+ this(minimumClassVersion, Integer.MAX_VALUE, classVisitor);
+ }
+
+
+ /**
+ * Creates a new ClassVersionFilter.
+ * @param minimumClassVersion the minimum class version number.
+ * @param maximumClassVersion the maximum class version number.
+ * @param classVisitor the ClassVisitor
to which visits
+ * will be delegated.
+ */
+ public ClassVersionFilter(int minimumClassVersion,
+ int maximumClassVersion,
+ ClassVisitor classVisitor)
+ {
+ this.minimumClassVersion = minimumClassVersion;
+ this.maximumClassVersion = maximumClassVersion;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (programClass.u4version >= minimumClassVersion &&
+ programClass.u4version <= maximumClassVersion)
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Library classes don't have version numbers.
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassVersionSetter.java b/src/proguard/classfile/visitor/ClassVersionSetter.java
new file mode 100644
index 000000000..d3f018319
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassVersionSetter.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+import java.util.Set;
+
+/**
+ * This ClassVisitor
sets the version number of the program classes
+ * that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassVersionSetter implements ClassVisitor
+{
+ private final int classVersion;
+
+ private final Set newerClassVersions;
+
+
+ /**
+ * Creates a new ClassVersionSetter.
+ * @param classVersion the class version number.
+ */
+ public ClassVersionSetter(int classVersion)
+ {
+ this(classVersion, null);
+ }
+
+
+ /**
+ * Creates a new ClassVersionSetter that also stores any newer class version
+ * numbers that it encounters while visiting program classes.
+ * @param classVersion the class version number.
+ * @param newerClassVersions the Set
in which newer class
+ * version numbers can be collected.
+ */
+ public ClassVersionSetter(int classVersion,
+ Set newerClassVersions)
+ {
+ this.classVersion = classVersion;
+ this.newerClassVersions = newerClassVersions;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (programClass.u4version > classVersion &&
+ newerClassVersions != null)
+ {
+ newerClassVersions.add(new Integer(programClass.u4version));
+ }
+
+ programClass.u4version = classVersion;
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Library classes don't have version numbers.
+ }
+}
diff --git a/src/proguard/classfile/visitor/ClassVisitor.java b/src/proguard/classfile/visitor/ClassVisitor.java
new file mode 100644
index 000000000..c4234469e
--- /dev/null
+++ b/src/proguard/classfile/visitor/ClassVisitor.java
@@ -0,0 +1,36 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * Clazz
objects.
+ *
+ * @author Eric Lafortune
+ */
+public interface ClassVisitor
+{
+ public void visitProgramClass(ProgramClass programClass);
+ public void visitLibraryClass(LibraryClass libraryClass);
+}
diff --git a/src/proguard/classfile/visitor/ConcreteClassDownTraveler.java b/src/proguard/classfile/visitor/ConcreteClassDownTraveler.java
new file mode 100644
index 000000000..0b971f0b1
--- /dev/null
+++ b/src/proguard/classfile/visitor/ConcreteClassDownTraveler.java
@@ -0,0 +1,100 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor
lets a given ClassVisitor
+ * travel to the first concrete subclasses down in its hierarchy of abstract
+ * classes and concrete classes.
+ *
+ * @author Eric Lafortune
+ */
+public class ConcreteClassDownTraveler
+implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ConcreteClassDownTraveler.
+ * @param classVisitor the ClassVisitor
to
+ * which visits will be delegated.
+ */
+ public ConcreteClassDownTraveler(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Is this an abstract class or an interface?
+ if ((programClass.getAccessFlags() &
+ (ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) != 0)
+ {
+ // Travel down the hierarchy.
+ Clazz[] subClasses = programClass.subClasses;
+ if (subClasses != null)
+ {
+ for (int index = 0; index < subClasses.length; index++)
+ {
+ subClasses[index].accept(this);
+ }
+ }
+ }
+ else
+ {
+ // Visit the class. Don't descend any further.
+ programClass.accept(classVisitor);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Is this an abstract class or interface?
+ if ((libraryClass.getAccessFlags() &
+ (ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) != 0)
+ {
+ // Travel down the hierarchy.
+ Clazz[] subClasses = libraryClass.subClasses;
+ if (subClasses != null)
+ {
+ for (int index = 0; index < subClasses.length; index++)
+ {
+ subClasses[index].accept(this);
+ }
+ }
+ }
+ else
+ {
+ // Visit the class. Don't descend any further.
+ libraryClass.accept(classVisitor);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/DotClassClassVisitor.java b/src/proguard/classfile/visitor/DotClassClassVisitor.java
new file mode 100644
index 000000000..979f84675
--- /dev/null
+++ b/src/proguard/classfile/visitor/DotClassClassVisitor.java
@@ -0,0 +1,89 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+
+/**
+ * This InstructionVisitor lets a given ClassVisitor
visit all
+ * classes involved in any .class
constructs that it visits.
+ * .class
constructs are actually
+ * compiled differently, using Class.forName
constructs.
+ *
+ * @author Eric Lafortune
+ */
+public class DotClassClassVisitor
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ClassHierarchyTraveler.
+ * @param classVisitor the ClassVisitor
to which visits will
+ * be delegated.
+ */
+ public DotClassClassVisitor(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ byte opcode = constantInstruction.opcode;
+
+ // Could this instruction be a .class construct?
+ if (opcode == InstructionConstants.OP_LDC ||
+ opcode == InstructionConstants.OP_LDC_W)
+ {
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex,
+ this);
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Visit the referenced class from the .class construct.
+ classConstant.referencedClassAccept(classVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ExceptClassFilter.java b/src/proguard/classfile/visitor/ExceptClassFilter.java
new file mode 100644
index 000000000..25c6e68ef
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptClassFilter.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, except for one given class.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptClassFilter implements ClassVisitor
+{
+ private final Clazz exceptClass;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ClassNameFilter.
+ * @param exceptClass the class that will not be visited.
+ * @param classVisitor the ClassVisitor
to which visits will
+ * be delegated.
+ */
+ public ExceptClassFilter(Clazz exceptClass,
+ ClassVisitor classVisitor)
+ {
+ this.exceptClass = exceptClass;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (!programClass.equals(exceptClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (!libraryClass.equals(exceptClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/ExceptClassesFilter.java b/src/proguard/classfile/visitor/ExceptClassesFilter.java
new file mode 100644
index 000000000..bdf72bdec
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptClassesFilter.java
@@ -0,0 +1,90 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, except for classes are in a given list.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptClassesFilter implements ClassVisitor
+{
+ private final Clazz[] exceptClasses;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ExceptClassesFilter.
+ * @param exceptClasses the classes that will not be visited.
+ * @param classVisitor the ClassVisitor
to which visits will
+ * be delegated.
+ */
+ public ExceptClassesFilter(Clazz[] exceptClasses,
+ ClassVisitor classVisitor)
+ {
+ this.exceptClasses = exceptClasses;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (!present(programClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (!present(libraryClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean present(Clazz clazz)
+ {
+ if (exceptClasses == null)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < exceptClasses.length; index++)
+ {
+ if (exceptClasses[index].equals(clazz))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/ExceptionCounter.java b/src/proguard/classfile/visitor/ExceptionCounter.java
new file mode 100644
index 000000000..5c476b656
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptionCounter.java
@@ -0,0 +1,52 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.ExceptionInfoVisitor;
+
+/**
+ * This ExceptionInfoVisitor counts the number of exceptions that has been visited.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionCounter implements ExceptionInfoVisitor
+{
+ private int count;
+
+
+ /**
+ * Returns the number of exceptions that has been visited so far.
+ */
+ public int getCount()
+ {
+ return count;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ count++;
+ }
+}
diff --git a/src/proguard/classfile/visitor/ExceptionExcludedOffsetFilter.java b/src/proguard/classfile/visitor/ExceptionExcludedOffsetFilter.java
new file mode 100644
index 000000000..2fd18aedb
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptionExcludedOffsetFilter.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.ExceptionInfoVisitor;
+
+/**
+ * This ExceptionInfoVisitor
delegates its visits to another given
+ * ExceptionInfoVisitor
, but only when the visited exception
+ * does not cover the instruction at the given offset.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionExcludedOffsetFilter
+implements ExceptionInfoVisitor
+{
+ private final int instructionOffset;
+ private final ExceptionInfoVisitor exceptionInfoVisitor;
+
+
+ /**
+ * Creates a new ExceptionExcludedOffsetFilter.
+ * @param instructionOffset the instruction offset.
+ * @param exceptionInfoVisitor the ExceptionInfoVisitor to which visits
+ * will be delegated.
+ */
+ public ExceptionExcludedOffsetFilter(int instructionOffset,
+ ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ this.instructionOffset = instructionOffset;
+ this.exceptionInfoVisitor = exceptionInfoVisitor;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ if (!exceptionInfo.isApplicable(instructionOffset))
+ {
+ exceptionInfoVisitor.visitExceptionInfo(clazz, method, codeAttribute, exceptionInfo);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/ExceptionHandlerConstantVisitor.java b/src/proguard/classfile/visitor/ExceptionHandlerConstantVisitor.java
new file mode 100644
index 000000000..de7139bc3
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptionHandlerConstantVisitor.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.ExceptionInfoVisitor;
+
+/**
+ * This ExceptionInfoVisitor
lets a given
+ * ConstantVisitor
visit all catch class constants of exceptions
+ * that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionHandlerConstantVisitor
+implements ExceptionInfoVisitor
+{
+ private final ConstantVisitor constantVisitor;
+
+
+ /**
+ * Creates a new ExceptionHandlerConstantVisitor.
+ * @param constantVisitor the ConstantVisitor that will visit the catch
+ * class constants.
+ */
+ public ExceptionHandlerConstantVisitor(ConstantVisitor constantVisitor)
+ {
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ int catchType = exceptionInfo.u2catchType;
+ if (catchType != 0)
+ {
+ clazz.constantPoolEntryAccept(catchType, constantVisitor);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/ExceptionHandlerFilter.java b/src/proguard/classfile/visitor/ExceptionHandlerFilter.java
new file mode 100644
index 000000000..36ead5ec9
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptionHandlerFilter.java
@@ -0,0 +1,70 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.ExceptionInfoVisitor;
+
+/**
+ * This ExceptionInfoVisitor
delegates its visits to another given
+ * ExceptionInfoVisitor
, but only when the visited exception
+ * targets an instruction in the given range of offsets.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionHandlerFilter
+implements ExceptionInfoVisitor
+{
+ private final int startOffset;
+ private final int endOffset;
+ private final ExceptionInfoVisitor exceptionInfoVisitor;
+
+
+ /**
+ * Creates a new ExceptionHandlerFilter.
+ * @param startOffset the start of the instruction offset range.
+ * @param endOffset the end of the instruction offset range.
+ * @param exceptionInfoVisitor the ExceptionInfoVisitor to which visits
+ * will be delegated.
+ */
+ public ExceptionHandlerFilter(int startOffset,
+ int endOffset,
+ ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ this.startOffset = startOffset;
+ this.endOffset = endOffset;
+ this.exceptionInfoVisitor = exceptionInfoVisitor;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ int handlerPC = exceptionInfo.u2handlerPC;
+ if (handlerPC >= startOffset &&
+ handlerPC < endOffset)
+ {
+ exceptionInfoVisitor.visitExceptionInfo(clazz, method, codeAttribute, exceptionInfo);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/ExceptionOffsetFilter.java b/src/proguard/classfile/visitor/ExceptionOffsetFilter.java
new file mode 100644
index 000000000..c84473ab6
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptionOffsetFilter.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.ExceptionInfoVisitor;
+
+/**
+ * This ExceptionInfoVisitor
delegates its visits to another given
+ * ExceptionInfoVisitor
, but only when the visited exception
+ * covers the instruction at the given offset.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionOffsetFilter
+implements ExceptionInfoVisitor
+{
+ private final int instructionOffset;
+ private final ExceptionInfoVisitor exceptionInfoVisitor;
+
+
+ /**
+ * Creates a new ExceptionOffsetFilter.
+ * @param instructionOffset the instruction offset.
+ * @param exceptionInfoVisitor the ExceptionInfoVisitor to which visits
+ * will be delegated.
+ */
+ public ExceptionOffsetFilter(int instructionOffset,
+ ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ this.instructionOffset = instructionOffset;
+ this.exceptionInfoVisitor = exceptionInfoVisitor;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ if (exceptionInfo.isApplicable(instructionOffset))
+ {
+ exceptionInfoVisitor.visitExceptionInfo(clazz, method, codeAttribute, exceptionInfo);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/ExceptionRangeFilter.java b/src/proguard/classfile/visitor/ExceptionRangeFilter.java
new file mode 100644
index 000000000..626a32e23
--- /dev/null
+++ b/src/proguard/classfile/visitor/ExceptionRangeFilter.java
@@ -0,0 +1,68 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.ExceptionInfoVisitor;
+
+/**
+ * This ExceptionInfoVisitor
delegates its visits to another given
+ * ExceptionInfoVisitor
, but only when the visited exception
+ * overlaps with the given instruction range.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionRangeFilter
+implements ExceptionInfoVisitor
+{
+ private final int startOffset;
+ private final int endOffset;
+ private final ExceptionInfoVisitor exceptionInfoVisitor;
+
+
+ /**
+ * Creates a new ExceptionRangeFilter.
+ * @param startOffset the start offset of the instruction range.
+ * @param endOffset the end offset of the instruction range.
+ * @param exceptionInfoVisitor the ExceptionInfoVisitor to which visits
+ * will be delegated.
+ */
+ public ExceptionRangeFilter(int startOffset,
+ int endOffset,
+ ExceptionInfoVisitor exceptionInfoVisitor)
+ {
+ this.startOffset = startOffset;
+ this.endOffset = endOffset;
+ this.exceptionInfoVisitor = exceptionInfoVisitor;
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ if (exceptionInfo.isApplicable(startOffset, endOffset))
+ {
+ exceptionInfoVisitor.visitExceptionInfo(clazz, method, codeAttribute, exceptionInfo);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/ImplementedClassConstantFilter.java b/src/proguard/classfile/visitor/ImplementedClassConstantFilter.java
new file mode 100644
index 000000000..334b85f76
--- /dev/null
+++ b/src/proguard/classfile/visitor/ImplementedClassConstantFilter.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor
delegates its visits to class constants
+ * to another given ConstantVisitor
, except for classes that
+ * extend or implement a given class. This exception includes the class itself.
+ *
+ * @author Eric Lafortune
+ */
+public class ImplementedClassConstantFilter
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ private final Clazz implementedClass;
+ private final ConstantVisitor constantVisitor;
+
+
+ /**
+ * Creates a new ImplementedClassConstantFilter.
+ * @param implementedClass the class whose implementations will not be
+ * visited.
+ * @param constantVisitor the ConstantVisitor
to which visits
+ * will be delegated.
+ */
+ public ImplementedClassConstantFilter(Clazz implementedClass,
+ ConstantVisitor constantVisitor)
+ {
+ this.implementedClass = implementedClass;
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ Clazz referencedClass = classConstant.referencedClass;
+ if (referencedClass == null ||
+ !referencedClass.extendsOrImplements(implementedClass))
+ {
+ constantVisitor.visitClassConstant(clazz, classConstant);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/ImplementedClassFilter.java b/src/proguard/classfile/visitor/ImplementedClassFilter.java
new file mode 100644
index 000000000..abbacfb9d
--- /dev/null
+++ b/src/proguard/classfile/visitor/ImplementedClassFilter.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, except for classes that extend or implement
+ * a given class.
+ *
+ * @author Eric Lafortune
+ */
+public class ImplementedClassFilter implements ClassVisitor
+{
+ private final Clazz implementedClass;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ImplementedClassFilter.
+ * @param implementedClass the class whose implementations will not be
+ * visited.
+ * @param classVisitor the ClassVisitor
to which visits will
+ * be delegated.
+ */
+ public ImplementedClassFilter(Clazz implementedClass,
+ ClassVisitor classVisitor)
+ {
+ this.implementedClass = implementedClass;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (!programClass.extendsOrImplements(implementedClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (!libraryClass.extendsOrImplements(implementedClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/ImplementingClassConstantFilter.java b/src/proguard/classfile/visitor/ImplementingClassConstantFilter.java
new file mode 100644
index 000000000..8e7010de5
--- /dev/null
+++ b/src/proguard/classfile/visitor/ImplementingClassConstantFilter.java
@@ -0,0 +1,70 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor
delegates its visits to class constants
+ * to another given ConstantVisitor
, except for classes that
+ * are extended or implemented by a given class. This exception includes the
+ * class itself.
+ *
+ * @author Eric Lafortune
+ */
+public class ImplementingClassConstantFilter
+extends SimplifiedVisitor
+implements ConstantVisitor
+{
+ private final Clazz implementingClass;
+ private final ConstantVisitor constantVisitor;
+
+
+ /**
+ * Creates a new ImplementingClassConstantFilter.
+ * @param implementingClass the class whose superclasses and interfaces will
+ * not be visited.
+ * @param constantVisitor the ConstantVisitor
to which visits
+ * will be delegated.
+ */
+ public ImplementingClassConstantFilter(Clazz implementingClass,
+ ConstantVisitor constantVisitor)
+ {
+ this.implementingClass = implementingClass;
+ this.constantVisitor = constantVisitor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ Clazz referencedClass = classConstant.referencedClass;
+ if (referencedClass == null ||
+ !implementingClass.extendsOrImplements(referencedClass))
+ {
+ constantVisitor.visitClassConstant(clazz, classConstant);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/LibraryClassFilter.java b/src/proguard/classfile/visitor/LibraryClassFilter.java
new file mode 100644
index 000000000..7437ed3c8
--- /dev/null
+++ b/src/proguard/classfile/visitor/LibraryClassFilter.java
@@ -0,0 +1,60 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, but only when visiting library classes.
+ *
+ * @author Eric Lafortune
+ */
+public class LibraryClassFilter implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new LibraryClassFilter.
+ * @param classVisitor the ClassVisitor
to which visits
+ * will be delegated.
+ */
+ public LibraryClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Don't delegate visits to program classes.
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+}
diff --git a/src/proguard/classfile/visitor/LibraryMemberFilter.java b/src/proguard/classfile/visitor/LibraryMemberFilter.java
new file mode 100644
index 000000000..eae06982a
--- /dev/null
+++ b/src/proguard/classfile/visitor/LibraryMemberFilter.java
@@ -0,0 +1,73 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when visiting members of library
+ * classes.
+ *
+ * @author Eric Lafortune
+ */
+public class LibraryMemberFilter implements MemberVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new ProgramMemberFilter.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public LibraryMemberFilter(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ // Don't delegate visits to program members.
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Don't delegate visits to program members.
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+}
diff --git a/src/proguard/classfile/visitor/MemberAccessFilter.java b/src/proguard/classfile/visitor/MemberAccessFilter.java
new file mode 100644
index 000000000..6bdc15241
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberAccessFilter.java
@@ -0,0 +1,122 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when the visited member has the proper
+ * access flags.
+ * MemberVisitor
to
+ * which visits will be delegated.
+ */
+ public MemberAccessFilter(int requiredSetAccessFlags,
+ int requiredUnsetAccessFlags,
+ MemberVisitor memberVisitor)
+ {
+ this.requiredSetAccessFlags = requiredSetAccessFlags & ~ACCESS_MASK;
+ this.requiredUnsetAccessFlags = requiredUnsetAccessFlags;
+ this.requiredOneSetAccessFlags = requiredSetAccessFlags & ACCESS_MASK;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (accepted(programField.getAccessFlags()))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (accepted(programMethod.getAccessFlags()))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (accepted(libraryField.getAccessFlags()))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (accepted(libraryMethod.getAccessFlags()))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(int accessFlags)
+ {
+ return (requiredSetAccessFlags & ~accessFlags) == 0 &&
+ (requiredUnsetAccessFlags & accessFlags) == 0 &&
+ (requiredOneSetAccessFlags == 0 ||
+ (requiredOneSetAccessFlags & accessFlags) != 0);
+ }
+}
diff --git a/src/proguard/classfile/visitor/MemberClassAccessFilter.java b/src/proguard/classfile/visitor/MemberClassAccessFilter.java
new file mode 100644
index 000000000..3605407aa
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberClassAccessFilter.java
@@ -0,0 +1,106 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when the visited member is accessible
+ * from the given referencing class.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberClassAccessFilter
+implements MemberVisitor
+{
+ private final Clazz referencingClass;
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MemberAccessFilter.
+ * @param referencingClass the class that is accessing the member.
+ * @param memberVisitor the MemberVisitor
to which visits
+ * will be delegated.
+ */
+ public MemberClassAccessFilter(Clazz referencingClass,
+ MemberVisitor memberVisitor)
+ {
+ this.referencingClass = referencingClass;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (accepted(programClass, programField.getAccessFlags()))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (accepted(programClass, programMethod.getAccessFlags()))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (accepted(libraryClass, libraryField.getAccessFlags()))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (accepted(libraryClass, libraryMethod.getAccessFlags()))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(Clazz clazz, int memberAccessFlags)
+ {
+ int accessLevel = AccessUtil.accessLevel(memberAccessFlags);
+
+ return
+ (accessLevel >= AccessUtil.PUBLIC ) ||
+ (accessLevel >= AccessUtil.PRIVATE && referencingClass.equals(clazz) ) ||
+ (accessLevel >= AccessUtil.PACKAGE_VISIBLE && (ClassUtil.internalPackageName(referencingClass.getName()).equals(
+ ClassUtil.internalPackageName(clazz.getName())))) ||
+ (accessLevel >= AccessUtil.PROTECTED && (referencingClass.extends_(clazz) ||
+ referencingClass.extendsOrImplements(clazz)) );
+ }
+}
diff --git a/src/proguard/classfile/visitor/MemberCollector.java b/src/proguard/classfile/visitor/MemberCollector.java
new file mode 100644
index 000000000..46665f8f5
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberCollector.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+import java.util.Set;
+
+/**
+ * This MemberVisitor collects the concatenated name/descriptor strings of
+ * class members that have been visited.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberCollector
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final Set set;
+
+
+ /**
+ * Creates a new MemberCollector.
+ * @param set the Set
in which all method names/descriptor
+ * strings will be collected.
+ */
+ public MemberCollector(Set set)
+ {
+ this.set = set;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+
+ public void visitAnyMember(Clazz clazz, Member member)
+ {
+ set.add(member.getName(clazz) + member.getDescriptor(clazz));
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/MemberCounter.java b/src/proguard/classfile/visitor/MemberCounter.java
new file mode 100644
index 000000000..58df4a75c
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberCounter.java
@@ -0,0 +1,72 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This MemberVisitor counts the number of class members that have been visited.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberCounter implements MemberVisitor
+{
+ private int count;
+
+
+ /**
+ * Returns the number of class members that has been visited so far.
+ */
+ public int getCount()
+ {
+ return count;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitLibraryField(LibraryClass libraryClass,
+ LibraryField libraryField)
+ {
+ count++;
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass,
+ LibraryMethod libraryMethod)
+ {
+ count++;
+ }
+
+
+ public void visitProgramField(ProgramClass programClass,
+ ProgramField programField)
+ {
+ count++;
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass,
+ ProgramMethod programMethod)
+ {
+ count++;
+ }
+}
diff --git a/src/proguard/classfile/visitor/MemberDescriptorFilter.java b/src/proguard/classfile/visitor/MemberDescriptorFilter.java
new file mode 100644
index 000000000..cce515a05
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberDescriptorFilter.java
@@ -0,0 +1,113 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.util.*;
+
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when the visited member
+ * has a descriptor that matches a given regular expression.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberDescriptorFilter implements MemberVisitor
+{
+ private final StringMatcher regularExpressionMatcher;
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MemberDescriptorFilter.
+ * @param regularExpression the regular expression against which member
+ * descriptors will be matched.
+ * @param memberVisitor the MemberVisitor
to which visits
+ * will be delegated.
+ */
+ public MemberDescriptorFilter(String regularExpression,
+ MemberVisitor memberVisitor)
+ {
+ this(new ClassNameParser().parse(regularExpression), memberVisitor);
+ }
+
+
+ /**
+ * Creates a new MemberDescriptorFilter.
+ * @param regularExpressionMatcher the regular expression against which
+ * member descriptors will be matched.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public MemberDescriptorFilter(StringMatcher regularExpressionMatcher,
+ MemberVisitor memberVisitor)
+ {
+ this.regularExpressionMatcher = regularExpressionMatcher;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (accepted(programField.getDescriptor(programClass)))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (accepted(programMethod.getDescriptor(programClass)))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (accepted(libraryField.getDescriptor(libraryClass)))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (accepted(libraryMethod.getDescriptor(libraryClass)))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(String name)
+ {
+ return regularExpressionMatcher.matches(name);
+ }
+}
diff --git a/src/proguard/classfile/visitor/MemberNameFilter.java b/src/proguard/classfile/visitor/MemberNameFilter.java
new file mode 100644
index 000000000..9996a4e62
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberNameFilter.java
@@ -0,0 +1,114 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.util.*;
+
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when the visited member
+ * has a name that matches a given regular expression.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberNameFilter implements MemberVisitor
+{
+ private final StringMatcher regularExpressionMatcher;
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MemberNameFilter.
+ * @param regularExpression the regular expression against which member
+ * names will be matched.
+ * @param memberVisitor the MemberVisitor
to which visits
+ * will be delegated.
+ */
+ public MemberNameFilter(String regularExpression,
+ MemberVisitor memberVisitor)
+ {
+ this(new ListParser(new NameParser()).parse(regularExpression),
+ memberVisitor);
+ }
+
+
+ /**
+ * Creates a new MemberNameFilter.
+ * @param regularExpressionMatcher the regular expression against which
+ * member names will be matched.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public MemberNameFilter(StringMatcher regularExpressionMatcher,
+ MemberVisitor memberVisitor)
+ {
+ this.regularExpressionMatcher = regularExpressionMatcher;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (accepted(programField.getName(programClass)))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (accepted(programMethod.getName(programClass)))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (accepted(libraryField.getName(libraryClass)))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (accepted(libraryMethod.getName(libraryClass)))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean accepted(String name)
+ {
+ return regularExpressionMatcher.matches(name);
+ }
+}
diff --git a/src/proguard/classfile/visitor/MemberToClassVisitor.java b/src/proguard/classfile/visitor/MemberToClassVisitor.java
new file mode 100644
index 000000000..e82e52ff4
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberToClassVisitor.java
@@ -0,0 +1,90 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This MemberVisitor delegates all visits to a given ClassVisitor.
+ * The latter visits the class of each visited class member, although
+ * never twice in a row.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberToClassVisitor implements MemberVisitor
+{
+ private final ClassVisitor classVisitor;
+
+ private Clazz lastVisitedClass;
+
+
+ public MemberToClassVisitor(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (!programClass.equals(lastVisitedClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+
+ lastVisitedClass = programClass;
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (!programClass.equals(lastVisitedClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+
+ lastVisitedClass = programClass;
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (!libraryClass.equals(lastVisitedClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+
+ lastVisitedClass = libraryClass;
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (!libraryClass.equals(lastVisitedClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+
+ lastVisitedClass = libraryClass;
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/MemberVisitor.java b/src/proguard/classfile/visitor/MemberVisitor.java
new file mode 100644
index 000000000..7b45662b2
--- /dev/null
+++ b/src/proguard/classfile/visitor/MemberVisitor.java
@@ -0,0 +1,40 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This interface specifies the methods for a visitor of
+ * ProgramMember
objects and LibraryMember
+ * objects.
+ *
+ * @author Eric Lafortune
+ */
+public interface MemberVisitor
+{
+ public void visitProgramField( ProgramClass programClass, ProgramField programField);
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod);
+
+ public void visitLibraryField( LibraryClass libraryClass, LibraryField libraryField);
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod);
+}
diff --git a/src/proguard/classfile/visitor/MethodImplementationFilter.java b/src/proguard/classfile/visitor/MethodImplementationFilter.java
new file mode 100644
index 000000000..893a6994d
--- /dev/null
+++ b/src/proguard/classfile/visitor/MethodImplementationFilter.java
@@ -0,0 +1,70 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This MemberVisitor
delegates its visits to methods to
+ * another given MemberVisitor
, but only when the visited
+ * method may have implementations.
+ *
+ * @see Clazz#mayHaveImplementations(Method)
+ * @author Eric Lafortune
+ */
+public class MethodImplementationFilter
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MethodImplementationFilter.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public MethodImplementationFilter(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (programClass.mayHaveImplementations(programMethod))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (libraryClass.mayHaveImplementations(libraryMethod))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/MethodImplementationTraveler.java b/src/proguard/classfile/visitor/MethodImplementationTraveler.java
new file mode 100644
index 000000000..c9f942ecd
--- /dev/null
+++ b/src/proguard/classfile/visitor/MethodImplementationTraveler.java
@@ -0,0 +1,128 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This MemberVisitor
lets a given MemberVisitor
+ * travel to all concrete and abstract implementations of the visited methods
+ * in their class hierarchies.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodImplementationTraveler
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final boolean visitThisMethod;
+ private final boolean visitSuperMethods;
+ private final boolean visitInterfaceMethods;
+ private final boolean visitOverridingMethods;
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MethodImplementationTraveler.
+ * @param visitThisMethod specifies whether to visit the originally
+ * visited methods.
+ * @param visitSuperMethods specifies whether to visit the method in
+ * the super classes.
+ * @param visitInterfaceMethods specifies whether to visit the method in
+ * the interface classes.
+ * @param visitOverridingMethods specifies whether to visit the method in
+ * the subclasses.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public MethodImplementationTraveler(boolean visitThisMethod,
+ boolean visitSuperMethods,
+ boolean visitInterfaceMethods,
+ boolean visitOverridingMethods,
+ MemberVisitor memberVisitor)
+ {
+ this.visitThisMethod = visitThisMethod;
+ this.visitSuperMethods = visitSuperMethods;
+ this.visitInterfaceMethods = visitInterfaceMethods;
+ this.visitOverridingMethods = visitOverridingMethods;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (visitThisMethod)
+ {
+ programMethod.accept(programClass, memberVisitor);
+ }
+
+ if (!isSpecial(programClass, programMethod))
+ {
+ programClass.hierarchyAccept(false,
+ visitSuperMethods,
+ visitInterfaceMethods,
+ visitOverridingMethods,
+ new NamedMethodVisitor(programMethod.getName(programClass),
+ programMethod.getDescriptor(programClass),
+ new MemberAccessFilter(0,
+ ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC,
+ memberVisitor)));
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (visitThisMethod)
+ {
+ libraryMethod.accept(libraryClass, memberVisitor);
+ }
+
+ if (!isSpecial(libraryClass, libraryMethod))
+ {
+ libraryClass.hierarchyAccept(false,
+ visitSuperMethods,
+ visitInterfaceMethods,
+ visitOverridingMethods,
+ new NamedMethodVisitor(libraryMethod.getName(libraryClass),
+ libraryMethod.getDescriptor(libraryClass),
+ new MemberAccessFilter(0,
+ ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC,
+ memberVisitor)));
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean isSpecial(Clazz clazz, Method method)
+ {
+ return (method.getAccessFlags() &
+ (ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC)) != 0 ||
+ method.getName(clazz).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT);
+ }
+}
diff --git a/src/proguard/classfile/visitor/MultiClassPoolVisitor.java b/src/proguard/classfile/visitor/MultiClassPoolVisitor.java
new file mode 100644
index 000000000..0e96cf1e1
--- /dev/null
+++ b/src/proguard/classfile/visitor/MultiClassPoolVisitor.java
@@ -0,0 +1,88 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.ClassPool;
+
+
+/**
+ * This ClassPoolVisitor delegates all visits to each ClassPoolVisitor
+ * in a given list.
+ *
+ * @author Eric Lafortune
+ */
+public class MultiClassPoolVisitor implements ClassPoolVisitor
+{
+ private static final int ARRAY_SIZE_INCREMENT = 5;
+
+ private ClassPoolVisitor[] classPoolVisitors;
+ private int classPoolVisitorCount;
+
+
+ public MultiClassPoolVisitor()
+ {
+ }
+
+
+ public MultiClassPoolVisitor(ClassPoolVisitor[] classPoolVisitors)
+ {
+ this.classPoolVisitors = classPoolVisitors;
+ this.classPoolVisitorCount = classPoolVisitors.length;
+ }
+
+
+ public void addClassPoolVisitor(ClassPoolVisitor classPoolVisitor)
+ {
+ ensureArraySize();
+
+ classPoolVisitors[classPoolVisitorCount++] = classPoolVisitor;
+ }
+
+
+ private void ensureArraySize()
+ {
+ if (classPoolVisitors == null)
+ {
+ classPoolVisitors = new ClassPoolVisitor[ARRAY_SIZE_INCREMENT];
+ }
+ else if (classPoolVisitors.length == classPoolVisitorCount)
+ {
+ ClassPoolVisitor[] newClassPoolVisitors =
+ new ClassPoolVisitor[classPoolVisitorCount +
+ ARRAY_SIZE_INCREMENT];
+ System.arraycopy(classPoolVisitors, 0,
+ newClassPoolVisitors, 0,
+ classPoolVisitorCount);
+ classPoolVisitors = newClassPoolVisitors;
+ }
+ }
+
+
+ // Implementations for ClassPoolVisitor.
+
+ public void visitClassPool(ClassPool classPool)
+ {
+ for (int index = 0; index < classPoolVisitorCount; index++)
+ {
+ classPoolVisitors[index].visitClassPool(classPool);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/MultiClassVisitor.java b/src/proguard/classfile/visitor/MultiClassVisitor.java
new file mode 100644
index 000000000..059e9b720
--- /dev/null
+++ b/src/proguard/classfile/visitor/MultiClassVisitor.java
@@ -0,0 +1,97 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor delegates all visits to each ClassVisitor
+ * in a given list.
+ *
+ * @author Eric Lafortune
+ */
+public class MultiClassVisitor implements ClassVisitor
+{
+ private static final int ARRAY_SIZE_INCREMENT = 5;
+
+ private ClassVisitor[] classVisitors;
+ private int classVisitorCount;
+
+
+ public MultiClassVisitor()
+ {
+ }
+
+
+ public MultiClassVisitor(ClassVisitor[] classVisitors)
+ {
+ this.classVisitors = classVisitors;
+ this.classVisitorCount = classVisitors.length;
+ }
+
+
+ public void addClassVisitor(ClassVisitor classVisitor)
+ {
+ ensureArraySize();
+
+ classVisitors[classVisitorCount++] = classVisitor;
+ }
+
+
+ private void ensureArraySize()
+ {
+ if (classVisitors == null)
+ {
+ classVisitors = new ClassVisitor[ARRAY_SIZE_INCREMENT];
+ }
+ else if (classVisitors.length == classVisitorCount)
+ {
+ ClassVisitor[] newClassVisitors =
+ new ClassVisitor[classVisitorCount +
+ ARRAY_SIZE_INCREMENT];
+ System.arraycopy(classVisitors, 0,
+ newClassVisitors, 0,
+ classVisitorCount);
+ classVisitors = newClassVisitors;
+ }
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ for (int index = 0; index < classVisitorCount; index++)
+ {
+ classVisitors[index].visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ for (int index = 0; index < classVisitorCount; index++)
+ {
+ classVisitors[index].visitLibraryClass(libraryClass);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/MultiMemberVisitor.java b/src/proguard/classfile/visitor/MultiMemberVisitor.java
new file mode 100644
index 000000000..800d65ffd
--- /dev/null
+++ b/src/proguard/classfile/visitor/MultiMemberVisitor.java
@@ -0,0 +1,113 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This MemberVisitor delegates all visits to each MemberVisitor
+ * in a given list.
+ *
+ * @author Eric Lafortune
+ */
+public class MultiMemberVisitor implements MemberVisitor
+{
+ private static final int ARRAY_SIZE_INCREMENT = 5;
+
+ private MemberVisitor[] memberVisitors;
+ private int memberVisitorCount;
+
+
+ public MultiMemberVisitor()
+ {
+ }
+
+
+ public MultiMemberVisitor(MemberVisitor[] memberVisitors)
+ {
+ this.memberVisitors = memberVisitors;
+ this.memberVisitorCount = memberVisitors.length;
+ }
+
+
+ public void addMemberVisitor(MemberVisitor memberVisitor)
+ {
+ ensureArraySize();
+
+ memberVisitors[memberVisitorCount++] = memberVisitor;
+ }
+
+
+ private void ensureArraySize()
+ {
+ if (memberVisitors == null)
+ {
+ memberVisitors = new MemberVisitor[ARRAY_SIZE_INCREMENT];
+ }
+ else if (memberVisitors.length == memberVisitorCount)
+ {
+ MemberVisitor[] newMemberVisitors =
+ new MemberVisitor[memberVisitorCount +
+ ARRAY_SIZE_INCREMENT];
+ System.arraycopy(memberVisitors, 0,
+ newMemberVisitors, 0,
+ memberVisitorCount);
+ memberVisitors = newMemberVisitors;
+ }
+ }
+
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ for (int index = 0; index < memberVisitorCount; index++)
+ {
+ memberVisitors[index].visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ for (int index = 0; index < memberVisitorCount; index++)
+ {
+ memberVisitors[index].visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ for (int index = 0; index < memberVisitorCount; index++)
+ {
+ memberVisitors[index].visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ for (int index = 0; index < memberVisitorCount; index++)
+ {
+ memberVisitors[index].visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/NamedClassVisitor.java b/src/proguard/classfile/visitor/NamedClassVisitor.java
new file mode 100644
index 000000000..79e14c956
--- /dev/null
+++ b/src/proguard/classfile/visitor/NamedClassVisitor.java
@@ -0,0 +1,49 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.ClassPool;
+
+
+/**
+ * This class visits Clazz objects with the given name.
+ *
+ * @author Eric Lafortune
+ */
+public class NamedClassVisitor implements ClassPoolVisitor
+{
+ private final ClassVisitor classVisitor;
+ private final String name;
+
+
+ public NamedClassVisitor(ClassVisitor classVisitor,
+ String name)
+ {
+ this.classVisitor = classVisitor;
+ this.name = name;
+ }
+
+
+ public void visitClassPool(ClassPool classPool)
+ {
+ classPool.classAccept(name, classVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/NamedFieldVisitor.java b/src/proguard/classfile/visitor/NamedFieldVisitor.java
new file mode 100644
index 000000000..685f62d54
--- /dev/null
+++ b/src/proguard/classfile/visitor/NamedFieldVisitor.java
@@ -0,0 +1,61 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This class visits ProgramMember objects referring to fields, identified by
+ * a name and descriptor pair.
+ *
+ * @author Eric Lafortune
+ */
+public class NamedFieldVisitor implements ClassVisitor
+{
+ private final String name;
+ private final String descriptor;
+ private final MemberVisitor memberVisitor;
+
+
+ public NamedFieldVisitor(String name,
+ String descriptor,
+ MemberVisitor memberVisitor)
+ {
+ this.name = name;
+ this.descriptor = descriptor;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.fieldAccept(name, descriptor, memberVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.fieldAccept(name, descriptor, memberVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/NamedMethodVisitor.java b/src/proguard/classfile/visitor/NamedMethodVisitor.java
new file mode 100644
index 000000000..c2baf193c
--- /dev/null
+++ b/src/proguard/classfile/visitor/NamedMethodVisitor.java
@@ -0,0 +1,61 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This class visits ProgramMember objects referring to methods, identified by
+ * a name and descriptor pair.
+ *
+ * @author Eric Lafortune
+ */
+public class NamedMethodVisitor implements ClassVisitor
+{
+ private final String name;
+ private final String descriptor;
+ private final MemberVisitor memberVisitor;
+
+
+ public NamedMethodVisitor(String name,
+ String descriptor,
+ MemberVisitor memberVisitor)
+ {
+ this.name = name;
+ this.descriptor = descriptor;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.methodAccept(name, descriptor, memberVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.methodAccept(name, descriptor, memberVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ProgramClassFilter.java b/src/proguard/classfile/visitor/ProgramClassFilter.java
new file mode 100644
index 000000000..976658c43
--- /dev/null
+++ b/src/proguard/classfile/visitor/ProgramClassFilter.java
@@ -0,0 +1,60 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, but only when visiting program classes.
+ *
+ * @author Eric Lafortune
+ */
+public class ProgramClassFilter implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ProgramClassFilter.
+ * @param classVisitor the ClassVisitor
to which visits
+ * will be delegated.
+ */
+ public ProgramClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Don't delegate visits to library classes.
+ }
+}
diff --git a/src/proguard/classfile/visitor/ProgramMemberFilter.java b/src/proguard/classfile/visitor/ProgramMemberFilter.java
new file mode 100644
index 000000000..cf187fbfa
--- /dev/null
+++ b/src/proguard/classfile/visitor/ProgramMemberFilter.java
@@ -0,0 +1,73 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when visiting members of program
+ * classes.
+ *
+ * @author Eric Lafortune
+ */
+public class ProgramMemberFilter implements MemberVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new ProgramMemberFilter.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public ProgramMemberFilter(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ // Don't delegate visits to library members.
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ // Don't delegate visits to library members.
+ }
+}
diff --git a/src/proguard/classfile/visitor/ReferencedClassVisitor.java b/src/proguard/classfile/visitor/ReferencedClassVisitor.java
new file mode 100644
index 000000000..e7fe855d4
--- /dev/null
+++ b/src/proguard/classfile/visitor/ReferencedClassVisitor.java
@@ -0,0 +1,255 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ClassVisitor, MemberVisitor, ConstantVisitor, AttributeVisitor, etc.
+ * lets a given ClassVisitor visit all the referenced classes of the elements
+ * that it visits. Only downstream elements are considered (in order to avoid
+ * loops and repeated visits).
+ *
+ * @author Eric Lafortune
+ */
+public class ReferencedClassVisitor
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ ConstantVisitor,
+ AttributeVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+ AnnotationVisitor,
+ ElementValueVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ public ReferencedClassVisitor(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Visit the constant pool entries.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Visit the fields and methods.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ // Visit the attributes.
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Visit the superclass and interfaces.
+ libraryClass.superClassAccept(classVisitor);
+ libraryClass.interfacesAccept(classVisitor);
+
+ // Visit the fields and methods.
+ libraryClass.fieldsAccept(this);
+ libraryClass.methodsAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ // Let the visitor visit the classes referenced in the descriptor string.
+ programMember.referencedClassesAccept(classVisitor);
+
+ // Visit the attributes.
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ public void visitLibraryMember(LibraryClass programClass, LibraryMember libraryMember)
+ {
+ // Let the visitor visit the classes referenced in the descriptor string.
+ libraryMember.referencedClassesAccept(classVisitor);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ // Let the visitor visit the class referenced in the string constant.
+ stringConstant.referencedClassAccept(classVisitor);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ // Let the visitor visit the class referenced in the reference constant.
+ refConstant.referencedClassAccept(classVisitor);
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ // Let the visitor visit the class referenced in the reference constant.
+ invokeDynamicConstant.referencedClassesAccept(classVisitor);
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Let the visitor visit the class referenced in the class constant.
+ classConstant.referencedClassAccept(classVisitor);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ // Let the visitor visit the class of the enclosing method.
+ enclosingMethodAttribute.referencedClassAccept(classVisitor);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Visit the attributes of the code attribute.
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Visit the local variables.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Visit the local variable types.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ // Let the visitor visit the classes referenced in the signature string.
+ signatureAttribute.referencedClassesAccept(classVisitor);
+ }
+
+
+ public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
+ {
+ // Visit the annotations.
+ annotationsAttribute.annotationsAccept(clazz, this);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ // Visit the parameter annotations.
+ parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ // Visit the default element value.
+ annotationDefaultAttribute.defaultValueAccept(clazz, this);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ // Let the visitor visit the class referenced in the local variable.
+ localVariableInfo.referencedClassAccept(classVisitor);
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ // Let the visitor visit the classes referenced in the local variable type.
+ localVariableTypeInfo.referencedClassesAccept(classVisitor);
+ }
+
+
+ // Implementations for AnnotationVisitor.
+
+ public void visitAnnotation(Clazz clazz, Annotation annotation)
+ {
+ // Let the visitor visit the classes referenced in the annotation.
+ annotation.referencedClassesAccept(classVisitor);
+
+ // Visit the element values.
+ annotation.elementValuesAccept(clazz, this);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitAnyElementValue(Clazz clazz, Annotation annotation, ElementValue elementValue) {}
+
+
+ public void visitEnumConstantElementValue(Clazz clazz, Annotation annotation, EnumConstantElementValue enumConstantElementValue)
+ {
+ // Let the visitor visit the classes referenced in the constant element value.
+ enumConstantElementValue.referencedClassesAccept(classVisitor);
+ }
+
+
+ public void visitClassElementValue(Clazz clazz, Annotation annotation, ClassElementValue classElementValue)
+ {
+ // Let the visitor visit the classes referenced in the class element value.
+ classElementValue.referencedClassesAccept(classVisitor);
+ }
+
+
+ public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
+ {
+ // Visit the element values.
+ arrayElementValue.elementValuesAccept(clazz, annotation, this);
+ }
+}
diff --git a/src/proguard/classfile/visitor/ReferencedMemberVisitor.java b/src/proguard/classfile/visitor/ReferencedMemberVisitor.java
new file mode 100644
index 000000000..3c590757c
--- /dev/null
+++ b/src/proguard/classfile/visitor/ReferencedMemberVisitor.java
@@ -0,0 +1,73 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.annotation.visitor.ElementValueVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This ConstantVisitor and ElementValueVisitor lets a given MemberVisitor
+ * visit all the referenced class members of the elements that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class ReferencedMemberVisitor
+extends SimplifiedVisitor
+implements ConstantVisitor,
+ ElementValueVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ public ReferencedMemberVisitor(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ stringConstant.referencedMemberAccept(memberVisitor);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ refConstant.referencedMemberAccept(memberVisitor);
+ }
+
+
+ // Implementations for ElementValueVisitor.
+
+ public void visitAnyElementValue(Clazz clazz, Annotation annotation, ElementValue elementValue)
+ {
+ elementValue.referencedMethodAccept(memberVisitor);
+ }
+}
diff --git a/src/proguard/classfile/visitor/SimilarMemberVisitor.java b/src/proguard/classfile/visitor/SimilarMemberVisitor.java
new file mode 100644
index 000000000..5087f4892
--- /dev/null
+++ b/src/proguard/classfile/visitor/SimilarMemberVisitor.java
@@ -0,0 +1,125 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This MemberVisitor
lets a given MemberVisitor
+ * visit all members that have the same name and type as the visited methods
+ * in the class hierarchy of a given target class.
+ *
+ * @author Eric Lafortune
+ */
+public class SimilarMemberVisitor
+implements MemberVisitor
+{
+ private final Clazz targetClass;
+ private final boolean visitThisMember;
+ private final boolean visitSuperMembers;
+ private final boolean visitInterfaceMembers;
+ private final boolean visitOverridingMembers;
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new SimilarMemberVisitor.
+ * @param targetClass the class in whose hierarchy to look for
+ * the visited class members.
+ * @param visitThisMember specifies whether to visit the class
+ * members in the target class itself.
+ * @param visitSuperMembers specifies whether to visit the class
+ * members in the super classes of the target
+ * class.
+ * @param visitInterfaceMembers specifies whether to visit the class
+ * members in the interface classes of the
+ * target class.
+ * @param visitOverridingMembers specifies whether to visit the class
+ * members in the subclasses of the target
+ * class.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public SimilarMemberVisitor(Clazz targetClass,
+ boolean visitThisMember,
+ boolean visitSuperMembers,
+ boolean visitInterfaceMembers,
+ boolean visitOverridingMembers,
+ MemberVisitor memberVisitor)
+ {
+ this.targetClass = targetClass;
+ this.visitThisMember = visitThisMember;
+ this.visitSuperMembers = visitSuperMembers;
+ this.visitInterfaceMembers = visitInterfaceMembers;
+ this.visitOverridingMembers = visitOverridingMembers;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ targetClass.hierarchyAccept(visitThisMember,
+ visitSuperMembers,
+ visitInterfaceMembers,
+ visitOverridingMembers,
+ new NamedFieldVisitor(programField.getName(programClass),
+ programField.getDescriptor(programClass),
+ memberVisitor));
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ targetClass.hierarchyAccept(visitThisMember,
+ visitSuperMembers,
+ visitInterfaceMembers,
+ visitOverridingMembers,
+ new NamedFieldVisitor(libraryField.getName(libraryClass),
+ libraryField.getDescriptor(libraryClass),
+ memberVisitor));
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ targetClass.hierarchyAccept(visitThisMember,
+ visitSuperMembers,
+ visitInterfaceMembers,
+ visitOverridingMembers,
+ new NamedMethodVisitor(programMethod.getName(programClass),
+ programMethod.getDescriptor(programClass),
+ memberVisitor));
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ targetClass.hierarchyAccept(visitThisMember,
+ visitSuperMembers,
+ visitInterfaceMembers,
+ visitOverridingMembers,
+ new NamedMethodVisitor(libraryMethod.getName(libraryClass),
+ libraryMethod.getDescriptor(libraryClass),
+ memberVisitor));
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/SimpleClassPrinter.java b/src/proguard/classfile/visitor/SimpleClassPrinter.java
new file mode 100644
index 000000000..df630c7ea
--- /dev/null
+++ b/src/proguard/classfile/visitor/SimpleClassPrinter.java
@@ -0,0 +1,167 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+import proguard.classfile.util.ClassUtil;
+
+import java.io.PrintStream;
+
+
+/**
+ * This ClassVisitor
and MemberVisitor
+ * prints out the class names of the classes it visits, and the full class
+ * member descriptions of the class members it visits. The names are printed
+ * in a readable, Java-like format. The access modifiers can be included or not.
+ *
+ * @author Eric Lafortune
+ */
+public class SimpleClassPrinter
+implements ClassVisitor,
+ MemberVisitor
+{
+ private final boolean printAccessModifiers;
+ private final PrintStream ps;
+
+
+ /**
+ * Creates a new SimpleClassPrinter that prints to
+ * System.out
, including the access modifiers.
+ */
+ public SimpleClassPrinter()
+ {
+ this(true);
+ }
+
+ /**
+ * Creates a new SimpleClassPrinter that prints to
+ * System.out
, with or without the access modifiers.
+ */
+ public SimpleClassPrinter(boolean printAccessModifiers)
+ {
+ this(printAccessModifiers, System.out);
+ }
+
+ /**
+ * Creates a new SimpleClassPrinter that prints to the given
+ * PrintStream
, with or without the access modifiers.
+ */
+ public SimpleClassPrinter(boolean printAccessModifiers,
+ PrintStream printStream)
+ {
+ this.printAccessModifiers = printAccessModifiers;
+ this.ps = printStream;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ ps.println(ClassUtil.externalFullClassDescription(
+ printAccessModifiers ?
+ programClass.getAccessFlags() :
+ 0,
+ programClass.getName()));
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ ps.println(ClassUtil.externalFullClassDescription(
+ printAccessModifiers ?
+ libraryClass.getAccessFlags() :
+ 0,
+ libraryClass.getName()));
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ ps.println(ClassUtil.externalFullClassDescription(
+ printAccessModifiers ?
+ programClass.getAccessFlags() :
+ 0,
+ programClass.getName()) +
+ ": " +
+ ClassUtil.externalFullFieldDescription(
+ printAccessModifiers ?
+ programField.getAccessFlags() :
+ 0,
+ programField.getName(programClass),
+ programField.getDescriptor(programClass)));
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ ps.println(ClassUtil.externalFullClassDescription(
+ printAccessModifiers ?
+ programClass.getAccessFlags() :
+ 0,
+ programClass.getName()) +
+ ": " +
+ ClassUtil.externalFullMethodDescription(
+ programClass.getName(),
+ printAccessModifiers ?
+ programMethod.getAccessFlags() :
+ 0,
+ programMethod.getName(programClass),
+ programMethod.getDescriptor(programClass)));
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ ps.println(ClassUtil.externalFullClassDescription(
+ printAccessModifiers ?
+ libraryClass.getAccessFlags() :
+ 0,
+ libraryClass.getName()) +
+ ": " +
+ ClassUtil.externalFullFieldDescription(
+ printAccessModifiers ?
+ libraryField.getAccessFlags() :
+ 0,
+ libraryField.getName(libraryClass),
+ libraryField.getDescriptor(libraryClass)));
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ ps.println(ClassUtil.externalFullClassDescription(
+ printAccessModifiers ?
+ libraryClass.getAccessFlags() :
+ 0,
+ libraryClass.getName()) +
+ ": " +
+ ClassUtil.externalFullMethodDescription(
+ libraryClass.getName(),
+ printAccessModifiers ?
+ libraryMethod.getAccessFlags() :
+ 0,
+ libraryMethod.getName(libraryClass),
+ libraryMethod.getDescriptor(libraryClass)));
+ }
+}
diff --git a/src/proguard/classfile/visitor/SubclassFilter.java b/src/proguard/classfile/visitor/SubclassFilter.java
new file mode 100644
index 000000000..6b6f84b98
--- /dev/null
+++ b/src/proguard/classfile/visitor/SubclassFilter.java
@@ -0,0 +1,91 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+/**
+ * This ClassVisitor
delegates its visits to another given
+ * ClassVisitor
, except for classes that have a given class as
+ * direct subclass.
+ *
+ * @author Eric Lafortune
+ */
+public class SubclassFilter implements ClassVisitor
+{
+ private final Clazz subclass;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new SubclassFilter.
+ * @param subclass the class whose superclasses will not be visited.
+ * @param classVisitor the ClassVisitor
to which visits will
+ * be delegated.
+ */
+ public SubclassFilter(Clazz subclass,
+ ClassVisitor classVisitor)
+ {
+ this.subclass = subclass;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (!present(programClass.subClasses))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (!present(libraryClass.subClasses))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean present(Clazz[] subclasses)
+ {
+ if (subclasses == null)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < subclasses.length; index++)
+ {
+ if (subclasses[index].equals(subclass))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/SubclassTraveler.java b/src/proguard/classfile/visitor/SubclassTraveler.java
new file mode 100644
index 000000000..32dccb72a
--- /dev/null
+++ b/src/proguard/classfile/visitor/SubclassTraveler.java
@@ -0,0 +1,60 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor
lets a given ClassVisitor
+ * travel to direct subclasses of the visited class.
+ *
+ * @author Eric Lafortune
+ */
+public class SubclassTraveler implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new ClassHierarchyTraveler.
+ * @param classVisitor the ClassVisitor
to
+ * which visits will be delegated.
+ */
+ public SubclassTraveler(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.subclassesAccept(classVisitor);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.subclassesAccept(classVisitor);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/classfile/visitor/VariableClassVisitor.java b/src/proguard/classfile/visitor/VariableClassVisitor.java
new file mode 100644
index 000000000..17a55227b
--- /dev/null
+++ b/src/proguard/classfile/visitor/VariableClassVisitor.java
@@ -0,0 +1,78 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This ClassVisitor delegates all method calls to a ClassVisitor
+ * that can be changed at any time.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableClassVisitor implements ClassVisitor
+{
+ private ClassVisitor classVisitor;
+
+
+ public VariableClassVisitor()
+ {
+ this(null);
+ }
+
+
+ public VariableClassVisitor(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ public void setClassVisitor(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+ public ClassVisitor getClassVisitor()
+ {
+ return classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (classVisitor != null)
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (classVisitor != null)
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/VariableMemberVisitor.java b/src/proguard/classfile/visitor/VariableMemberVisitor.java
new file mode 100644
index 000000000..34c39f377
--- /dev/null
+++ b/src/proguard/classfile/visitor/VariableMemberVisitor.java
@@ -0,0 +1,96 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.classfile.visitor;
+
+import proguard.classfile.*;
+
+
+/**
+ * This MemberVisitor delegates all method calls to a MemberVisitor
+ * that can be changed at any time.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableMemberVisitor implements MemberVisitor
+{
+ private MemberVisitor memberVisitor;
+
+
+ public VariableMemberVisitor()
+ {
+ this(null);
+ }
+
+
+ public VariableMemberVisitor(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ public void setMemberVisitor(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+ public MemberVisitor getMemberVisitor()
+ {
+ return memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (memberVisitor != null)
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (memberVisitor != null)
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (memberVisitor != null)
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (memberVisitor != null)
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+}
diff --git a/src/proguard/classfile/visitor/package.html b/src/proguard/classfile/visitor/package.html
new file mode 100644
index 000000000..d3be40c09
--- /dev/null
+++ b/src/proguard/classfile/visitor/package.html
@@ -0,0 +1,40 @@
+{@link proguard.classfile proguard.classfile}
package using
+the visitor pattern. Cfr., for instance, "Design Patterns, Elements of
+Reusable OO Software", by Gamma, Helm, Johnson, and Vlissider.
+instanceof
tests
+on the elements of a list, followed by type casts and the proper operations.
+Every list element is a visitor accepter. When its accept
method
+is called by a visitor, it calls its corresponding visitX
method
+in the visitor, passing itself as an argument. This technique is called
+double-dispatch.
+instanceof
tests and type casts. Also, implementing a visitor
+interface ensures you're handling all possible visitor accepter types. Each
+type has its own method, which you simply have to implement.
+Value
+ * objects.
+ *
+ * @author Eric Lafortune
+ */
+public class Stack
+{
+ private static final TopValue TOP_VALUE = new TopValue();
+
+
+ protected Value[] values;
+ protected int currentSize;
+ protected int actualMaxSize;
+
+
+ /**
+ * Creates a new Stack with a given maximum size, accounting for the double
+ * space required by Category 2 values.
+ */
+ public Stack(int maxSize)
+ {
+ values = new Value[maxSize];
+ }
+
+
+ /**
+ * Creates a Stack that is a copy of the given Stack.
+ */
+ public Stack(Stack stack)
+ {
+ // Create the values array.
+ this(stack.values.length);
+
+ // Copy the stack contents.
+ copy(stack);
+ }
+
+
+ /**
+ * Returns the actual maximum stack size that was required for all stack
+ * operations, accounting for the double space required by Category 2 values.
+ */
+ public int getActualMaxSize()
+ {
+ return actualMaxSize;
+ }
+
+
+ /**
+ * Resets this Stack, so that it can be reused.
+ */
+ public void reset(int maxSize)
+ {
+ // Is the values array large enough?
+ if (maxSize > values.length)
+ {
+ // Create a new one.
+ values = new Value[maxSize];
+ }
+
+ // Clear the sizes.
+ clear();
+
+ actualMaxSize = 0;
+ }
+
+
+ /**
+ * Copies the values of the given Stack into this Stack.
+ */
+ public void copy(Stack other)
+ {
+ // Is the values array large enough?
+ if (other.values.length > values.length)
+ {
+ // Create a new one.
+ values = new Value[other.values.length];
+ }
+
+ // Copy the stack contents.
+ System.arraycopy(other.values, 0, this.values, 0, other.currentSize);
+
+ // Copy the sizes.
+ currentSize = other.currentSize;
+ actualMaxSize = other.actualMaxSize;
+ }
+
+
+ /**
+ * Generalizes the values of this Stack with the values of the given Stack.
+ * The stacks must have the same current sizes.
+ * @return whether the generalization has made any difference.
+ */
+ public boolean generalize(Stack other)
+ {
+ if (this.currentSize != other.currentSize)
+ {
+ throw new IllegalArgumentException("Stacks have different current sizes ["+this.currentSize+"] and ["+other.currentSize+"]");
+ }
+
+ boolean changed = false;
+
+ // Generalize the stack values.
+ for (int index = 0; index < currentSize; index++)
+ {
+ Value thisValue = this.values[index];
+
+ if (thisValue != null)
+ {
+ Value newValue = null;
+
+ Value otherValue = other.values[index];
+
+ if (otherValue != null)
+ {
+ newValue = thisValue.generalize(otherValue);
+ }
+
+ changed = changed || !thisValue.equals(newValue);
+
+ values[index] = newValue;
+ }
+ }
+
+ // Check if the other stack extends beyond this one.
+ if (this.actualMaxSize < other.actualMaxSize)
+ {
+ this.actualMaxSize = other.actualMaxSize;
+ }
+
+ return changed;
+ }
+
+
+ /**
+ * Clears the stack.
+ */
+ public void clear()
+ {
+ // Clear the stack contents.
+ Arrays.fill(values, 0, currentSize, null);
+
+ currentSize = 0;
+ }
+
+
+ /**
+ * Returns the number of elements currently on the stack, accounting for the
+ * double space required by Category 2 values.
+ */
+ public int size()
+ {
+ return currentSize;
+ }
+
+
+ /**
+ * Gets the specified Value from the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the bottom
+ * of the stack.
+ * @return the value at the specified position.
+ */
+ public Value getBottom(int index)
+ {
+ return values[index];
+ }
+
+
+ /**
+ * Sets the specified Value on the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the bottom
+ * of the stack.
+ * @param value the value to set.
+ */
+ public void setBottom(int index, Value value)
+ {
+ values[index] = value;
+ }
+
+
+ /**
+ * Gets the specified Value from the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the top
+ * of the stack.
+ * @return the value at the specified position.
+ */
+ public Value getTop(int index)
+ {
+ return values[currentSize - index - 1];
+ }
+
+
+ /**
+ * Sets the specified Value on the stack, without disturbing it.
+ * @param index the index of the stack element, counting from the top
+ * of the stack.
+ * @param value the value to set.
+ */
+ public void setTop(int index, Value value)
+ {
+ values[currentSize - index - 1] = value;
+ }
+
+
+ /**
+ * Removes the specified Value from the stack.
+ * @param index the index of the stack element, counting from the top
+ * of the stack.
+ */
+ public void removeTop(int index)
+ {
+ System.arraycopy(values, currentSize - index,
+ values, currentSize - index - 1,
+ index);
+ currentSize--;
+ }
+
+
+ /**
+ * Pushes the given Value onto the stack.
+ */
+ public void push(Value value)
+ {
+ // Account for the extra space required by Category 2 values.
+ if (value.isCategory2())
+ {
+ values[currentSize++] = TOP_VALUE;
+ }
+
+ // Push the value.
+ values[currentSize++] = value;
+
+ // Update the maximum actual size;
+ if (actualMaxSize < currentSize)
+ {
+ actualMaxSize = currentSize;
+ }
+ }
+
+
+ /**
+ * Pops the top Value from the stack.
+ */
+ public Value pop()
+ {
+ Value value = values[--currentSize];
+
+ values[currentSize] = null;
+
+ // Account for the extra space required by Category 2 values.
+ if (value.isCategory2())
+ {
+ values[--currentSize] = null;
+ }
+
+ return value;
+ }
+
+
+ // Pop methods that provide convenient casts to the expected value types.
+
+ /**
+ * Pops the top IntegerValue from the stack.
+ */
+ public IntegerValue ipop()
+ {
+ return pop().integerValue();
+ }
+
+
+ /**
+ * Pops the top LongValue from the stack.
+ */
+ public LongValue lpop()
+ {
+ return pop().longValue();
+ }
+
+
+ /**
+ * Pops the top FloatValue from the stack.
+ */
+ public FloatValue fpop()
+ {
+ return pop().floatValue();
+ }
+
+
+ /**
+ * Pops the top DoubleValue from the stack.
+ */
+ public DoubleValue dpop()
+ {
+ return pop().doubleValue();
+ }
+
+
+ /**
+ * Pops the top ReferenceValue from the stack.
+ */
+ public ReferenceValue apop()
+ {
+ return pop().referenceValue();
+ }
+
+
+ /**
+ * Pops the top InstructionOffsetValue from the stack.
+ */
+ public InstructionOffsetValue opop()
+ {
+ return pop().instructionOffsetValue();
+ }
+
+
+ /**
+ * Pops the top category 1 value from the stack.
+ */
+ public void pop1()
+ {
+ values[--currentSize] = null;
+ }
+
+
+ /**
+ * Pops the top category 2 value from the stack (or alternatively, two
+ * Category 1 stack elements).
+ */
+ public void pop2()
+ {
+ values[--currentSize] = null;
+ values[--currentSize] = null;
+ }
+
+
+ /**
+ * Duplicates the top Category 1 value.
+ */
+ public void dup()
+ {
+ values[currentSize] = values[currentSize - 1].category1Value();
+
+ currentSize++;
+
+ // Update the maximum actual size;
+ if (actualMaxSize < currentSize)
+ {
+ actualMaxSize = currentSize;
+ }
+ }
+
+
+ /**
+ * Duplicates the top Category 1 value, one Category 1 element down the
+ * stack.
+ */
+ public void dup_x1()
+ {
+ values[currentSize] = values[currentSize - 1].category1Value();
+ values[currentSize - 1] = values[currentSize - 2].category1Value();
+ values[currentSize - 2] = values[currentSize ];
+
+ currentSize++;
+
+ // Update the maximum actual size;
+ if (actualMaxSize < currentSize)
+ {
+ actualMaxSize = currentSize;
+ }
+ }
+
+
+ /**
+ * Duplicates the top Category 1 value, two Category 1 elements (or one
+ * Category 2 element) down the stack.
+ */
+ public void dup_x2()
+ {
+ values[currentSize] = values[currentSize - 1].category1Value();
+ values[currentSize - 1] = values[currentSize - 2];
+ values[currentSize - 2] = values[currentSize - 3];
+ values[currentSize - 3] = values[currentSize ];
+
+ currentSize++;
+
+ // Update the maximum actual size;
+ if (actualMaxSize < currentSize)
+ {
+ actualMaxSize = currentSize;
+ }
+ }
+
+ /**
+ * Duplicates the top Category 2 value (or alternatively, the equivalent
+ * Category 1 stack elements).
+ */
+ public void dup2()
+ {
+ values[currentSize ] = values[currentSize - 2];
+ values[currentSize + 1] = values[currentSize - 1];
+
+ currentSize += 2;
+
+ // Update the maximum actual size;
+ if (actualMaxSize < currentSize)
+ {
+ actualMaxSize = currentSize;
+ }
+ }
+
+
+ /**
+ * Duplicates the top Category 2 value, one Category 1 element down the
+ * stack (or alternatively, the equivalent Category 1 stack values).
+ */
+ public void dup2_x1()
+ {
+ values[currentSize + 1] = values[currentSize - 1];
+ values[currentSize ] = values[currentSize - 2];
+ values[currentSize - 1] = values[currentSize - 3];
+ values[currentSize - 2] = values[currentSize + 1];
+ values[currentSize - 3] = values[currentSize ];
+
+ currentSize += 2;
+
+ // Update the maximum actual size;
+ if (actualMaxSize < currentSize)
+ {
+ actualMaxSize = currentSize;
+ }
+ }
+
+
+ /**
+ * Duplicates the top Category 2 value, one Category 2 stack element down
+ * the stack (or alternatively, the equivalent Category 1 stack values).
+ */
+ public void dup2_x2()
+ {
+ values[currentSize + 1] = values[currentSize - 1];
+ values[currentSize ] = values[currentSize - 2];
+ values[currentSize - 1] = values[currentSize - 3];
+ values[currentSize - 2] = values[currentSize - 4];
+ values[currentSize - 3] = values[currentSize + 1];
+ values[currentSize - 4] = values[currentSize ];
+
+ currentSize += 2;
+
+ // Update the maximum actual size;
+ if (actualMaxSize < currentSize)
+ {
+ actualMaxSize = currentSize;
+ }
+ }
+
+
+ /**
+ * Swaps the top two Category 1 values.
+ */
+ public void swap()
+ {
+ Value value1 = values[currentSize - 1].category1Value();
+ Value value2 = values[currentSize - 2].category1Value();
+
+ values[currentSize - 1] = value2;
+ values[currentSize - 2] = value1;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ Stack other = (Stack)object;
+
+ if (this.currentSize != other.currentSize)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < currentSize; index++)
+ {
+ Value thisValue = this.values[index];
+ Value otherValue = other.values[index];
+ if (thisValue == null ? otherValue != null :
+ !thisValue.equals(otherValue))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ public int hashCode()
+ {
+ int hashCode = currentSize;
+
+ for (int index = 0; index < currentSize; index++)
+ {
+ Value value = values[index];
+ if (value != null)
+ {
+ hashCode ^= value.hashCode();
+ }
+ }
+
+ return hashCode;
+ }
+
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer();
+
+ for (int index = 0; index < currentSize; index++)
+ {
+ Value value = values[index];
+ buffer = buffer.append('[')
+ .append(value == null ? "empty" : value.toString())
+ .append(']');
+ }
+
+ return buffer.toString();
+ }
+}
diff --git a/src/proguard/evaluation/TracedStack.java b/src/proguard/evaluation/TracedStack.java
new file mode 100644
index 000000000..08778a114
--- /dev/null
+++ b/src/proguard/evaluation/TracedStack.java
@@ -0,0 +1,342 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation;
+
+import proguard.evaluation.value.Value;
+
+/**
+ * This Stack saves additional information with stack elements, to keep track
+ * of their origins and destinations.
+ * Value
+ * objects. Values are generalizations of all values that have been stored in
+ * the respective variables.
+ *
+ * @author Eric Lafortune
+ */
+public class Variables
+{
+ private static final TopValue TOP_VALUE = new TopValue();
+
+
+ protected Value[] values;
+ protected int size;
+
+
+ /**
+ * Creates a new Variables object with a given maximum number of variables.
+ */
+ public Variables(int size)
+ {
+ this.values = new Value[size];
+ this.size = size;
+ }
+
+
+ /**
+ * Creates a Variables object that is a copy of the given Variables object.
+ */
+ public Variables(Variables variables)
+ {
+ // Create the values array.
+ this(variables.size);
+
+ // Copy the values.
+ initialize(variables);
+ }
+
+
+ /**
+ * Resets this Variables object, so that it can be reused.
+ */
+ public void reset(int size)
+ {
+ // Is the values array large enough?
+ if (size > values.length)
+ {
+ // Create a new one.
+ values = new Value[size];
+ }
+ else
+ {
+ // Clear the variables.
+ Arrays.fill(values, null);
+ }
+
+ this.size = size;
+ }
+
+
+ /**
+ * Initializes the values of this Variables object with the values of the
+ * given Variables object. The other object may have fewer values, in which
+ * case the remaining values are left unchanged.
+ */
+ public void initialize(Variables other)
+ {
+ if (this.size < other.size)
+ {
+ throw new IllegalArgumentException("Variable frame is too small ["+this.size+"] compared to other frame ["+other.size+"]");
+ }
+
+ // Copy the values.
+ System.arraycopy(other.values, 0, this.values, 0, other.size);
+ }
+
+
+ /**
+ * Generalizes the values of this Variables object with the values of the
+ * given Variables object.
+ * @param clearConflictingOtherVariables specifies whether the other
+ * variables should be cleared too,
+ * in case of conflicts.
+ * @return whether the generalization has made any difference.
+ */
+ public boolean generalize(Variables other,
+ boolean clearConflictingOtherVariables)
+ {
+ if (this.size != other.size)
+ {
+ throw new IllegalArgumentException("Variable frames have different sizes ["+this.size+"] and ["+other.size+"]");
+ }
+
+ boolean changed = false;
+
+ for (int index = 0; index < size; index++)
+ {
+ Value thisValue = this.values[index];
+ Value otherValue = other.values[index];
+
+ // Occasionally, two values of different types might be present
+ // in the same variable in a variable frame (corresponding to
+ // two local variables that share the same index), at some point
+ // outside of their scopes. Don't generalize the variable then,
+ // but let it clear instead.
+ if (thisValue != null &&
+ otherValue != null &&
+ thisValue.computationalType() == otherValue.computationalType())
+ {
+ Value newValue = thisValue.generalize(otherValue);
+
+ changed = changed || !thisValue.equals(newValue);
+
+ this.values[index] = newValue;
+ }
+ else
+ {
+ changed = changed || thisValue != null;
+
+ this.values[index] = null;
+
+ if (clearConflictingOtherVariables)
+ {
+ other.values[index] = null;
+ }
+ }
+ }
+
+ return changed;
+ }
+
+
+ /**
+ * Returns the number of variables.
+ */
+ public int size()
+ {
+ return size;
+ }
+
+
+ /**
+ * Gets the Value of the variable with the given index, without disturbing it.
+ */
+ public Value getValue(int index)
+ {
+ if (index < 0 ||
+ index >= size)
+ {
+ throw new IndexOutOfBoundsException("Variable index ["+index+"] out of bounds ["+size+"]");
+ }
+
+ return values[index];
+ }
+
+
+ /**
+ * Stores the given Value at the given variable index.
+ */
+ public void store(int index, Value value)
+ {
+ if (index < 0 ||
+ index >= size)
+ {
+ throw new IndexOutOfBoundsException("Variable index ["+index+"] out of bounds ["+size+"]");
+ }
+
+ // Store the value.
+ values[index] = value;
+
+ // Account for the extra space required by Category 2 values.
+ if (value.isCategory2())
+ {
+ values[index + 1] = TOP_VALUE;
+ }
+ }
+
+
+ /**
+ * Loads the Value from the variable with the given index.
+ */
+ public Value load(int index)
+ {
+ if (index < 0 ||
+ index >= size)
+ {
+ throw new IndexOutOfBoundsException("Variable index ["+index+"] out of bounds ["+size+"]");
+ }
+
+ return values[index];
+ }
+
+
+ // Load methods that provide convenient casts to the expected value types.
+
+ /**
+ * Loads the IntegerValue from the variable with the given index.
+ */
+ public IntegerValue iload(int index)
+ {
+ return load(index).integerValue();
+ }
+
+
+ /**
+ * Loads the LongValue from the variable with the given index.
+ */
+ public LongValue lload(int index)
+ {
+ return load(index).longValue();
+ }
+
+
+ /**
+ * Loads the FloatValue from the variable with the given index.
+ */
+ public FloatValue fload(int index)
+ {
+ return load(index).floatValue();
+ }
+
+
+ /**
+ * Loads the DoubleValue from the variable with the given index.
+ */
+ public DoubleValue dload(int index)
+ {
+ return load(index).doubleValue();
+ }
+
+
+ /**
+ * Loads the ReferenceValue from the variable with the given index.
+ */
+ public ReferenceValue aload(int index)
+ {
+ return load(index).referenceValue();
+ }
+
+
+ /**
+ * Loads the InstructionOffsetValue from the variable with the given index.
+ */
+ public InstructionOffsetValue oload(int index)
+ {
+ return load(index).instructionOffsetValue();
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ Variables other = (Variables)object;
+
+ if (this.size != other.size)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < size; index++)
+ {
+ Value thisValue = this.values[index];
+ Value otherValue = other.values[index];
+
+ // Occasionally, two values of different types might be
+ // present in the same variable in a variable frame
+ // (corresponding to two local variables that share the
+ // same index), at some point outside of their scopes.
+ // We'll ignore these.
+ if (thisValue != null &&
+ otherValue != null &&
+ thisValue.computationalType() == otherValue.computationalType() &&
+ !thisValue.equals(otherValue))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ public int hashCode()
+ {
+ int hashCode = size;
+
+ for (int index = 0; index < size; index++)
+ {
+ Value value = values[index];
+ if (value != null)
+ {
+ hashCode ^= value.hashCode();
+ }
+ }
+
+ return hashCode;
+ }
+
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer();
+
+ for (int index = 0; index < size; index++)
+ {
+ Value value = values[index];
+ buffer = buffer.append('[')
+ .append(value == null ? "empty" : value.toString())
+ .append(']');
+ }
+
+ return buffer.toString();
+ }
+}
diff --git a/src/proguard/evaluation/value/Category1Value.java b/src/proguard/evaluation/value/Category1Value.java
new file mode 100644
index 000000000..a5ebf8673
--- /dev/null
+++ b/src/proguard/evaluation/value/Category1Value.java
@@ -0,0 +1,41 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This abstract class represents a partially evaluated Category 1 value.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class Category1Value extends Value
+{
+ // Implementations for Value.
+
+ public final Category1Value category1Value()
+ {
+ return this;
+ }
+
+ public final boolean isCategory2()
+ {
+ return false;
+ }
+}
diff --git a/src/proguard/evaluation/value/Category2Value.java b/src/proguard/evaluation/value/Category2Value.java
new file mode 100644
index 000000000..2be6e719a
--- /dev/null
+++ b/src/proguard/evaluation/value/Category2Value.java
@@ -0,0 +1,41 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This abstract class represents a partially evaluated Category 2 value.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class Category2Value extends Value
+{
+ // Implementations for Value.
+
+ public final Category2Value category2Value()
+ {
+ return this;
+ }
+
+ public final boolean isCategory2()
+ {
+ return true;
+ }
+}
diff --git a/src/proguard/evaluation/value/ComparisonValue.java b/src/proguard/evaluation/value/ComparisonValue.java
new file mode 100644
index 000000000..abbf31c4b
--- /dev/null
+++ b/src/proguard/evaluation/value/ComparisonValue.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents the result of a comparisons of two scalar
+ * values.
+ *
+ * @author Eric Lafortune
+ */
+final class ComparisonValue extends SpecificIntegerValue
+{
+ private final Value value1;
+ private final Value value2;
+
+
+ /**
+ * Creates a new comparison integer value of the two given scalar values.
+ */
+ public ComparisonValue(Value value1,
+ Value value2)
+ {
+ this.value1 = value1;
+ this.value2 = value2;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value1.equals(((ComparisonValue)object).value1) &&
+ this.value2.equals(((ComparisonValue)object).value2);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value1.hashCode() ^
+ value2.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "("+value1+"~"+ value2 +")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/CompositeDoubleValue.java b/src/proguard/evaluation/value/CompositeDoubleValue.java
new file mode 100644
index 000000000..be739ed52
--- /dev/null
+++ b/src/proguard/evaluation/value/CompositeDoubleValue.java
@@ -0,0 +1,81 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This DoubleValue represents the result of a binary operation on two double
+ * values.
+ *
+ * @author Eric Lafortune
+ */
+final class CompositeDoubleValue extends SpecificDoubleValue
+{
+ public static final byte ADD = '+';
+ public static final byte SUBTRACT = '-';
+ public static final byte MULTIPLY = '*';
+ public static final byte DIVIDE = '/';
+ public static final byte REMAINDER = '%';
+
+
+ private final DoubleValue doubleValue1;
+ private final byte operation;
+ private final DoubleValue doubleValue2;
+
+
+ /**
+ * Creates a new composite double value of the two given double values
+ * and the given operation.
+ */
+ public CompositeDoubleValue(DoubleValue doubleValue1,
+ byte operation,
+ DoubleValue doubleValue2)
+ {
+ this.doubleValue1 = doubleValue1;
+ this.operation = operation;
+ this.doubleValue2 = doubleValue2;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.doubleValue1.equals(((CompositeDoubleValue)object).doubleValue1) &&
+ this.operation == ((CompositeDoubleValue)object).operation &&
+ this.doubleValue2.equals(((CompositeDoubleValue)object).doubleValue2);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ doubleValue1.hashCode() ^
+ doubleValue2.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "("+doubleValue1+((char)operation)+doubleValue2+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/CompositeFloatValue.java b/src/proguard/evaluation/value/CompositeFloatValue.java
new file mode 100644
index 000000000..096106837
--- /dev/null
+++ b/src/proguard/evaluation/value/CompositeFloatValue.java
@@ -0,0 +1,81 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This FloatValue represents the result of a binary operation on two float
+ * values.
+ *
+ * @author Eric Lafortune
+ */
+final class CompositeFloatValue extends SpecificFloatValue
+{
+ public static final byte ADD = '+';
+ public static final byte SUBTRACT = '-';
+ public static final byte MULTIPLY = '*';
+ public static final byte DIVIDE = '/';
+ public static final byte REMAINDER = '%';
+
+
+ private final FloatValue floatValue1;
+ private final byte operation;
+ private final FloatValue floatValue2;
+
+
+ /**
+ * Creates a new composite float value of the two given float values
+ * and the given operation.
+ */
+ public CompositeFloatValue(FloatValue floatValue1,
+ byte operation,
+ FloatValue floatValue2)
+ {
+ this.floatValue1 = floatValue1;
+ this.operation = operation;
+ this.floatValue2 = floatValue2;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.floatValue1.equals(((CompositeFloatValue)object).floatValue1) &&
+ this.operation == ((CompositeFloatValue)object).operation &&
+ this.floatValue2.equals(((CompositeFloatValue)object).floatValue2);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ floatValue1.hashCode() ^
+ floatValue2.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "("+floatValue1+((char)operation)+floatValue2+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/CompositeIntegerValue.java b/src/proguard/evaluation/value/CompositeIntegerValue.java
new file mode 100644
index 000000000..97caa2f6b
--- /dev/null
+++ b/src/proguard/evaluation/value/CompositeIntegerValue.java
@@ -0,0 +1,87 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents the result of a binary operation on two integer
+ * values.
+ *
+ * @author Eric Lafortune
+ */
+final class CompositeIntegerValue extends SpecificIntegerValue
+{
+ public static final byte ADD = '+';
+ public static final byte SUBTRACT = '-';
+ public static final byte MULTIPLY = '*';
+ public static final byte DIVIDE = '/';
+ public static final byte REMAINDER = '%';
+ public static final byte SHIFT_LEFT = '<';
+ public static final byte SHIFT_RIGHT = '>';
+ public static final byte UNSIGNED_SHIFT_RIGHT = '}';
+ public static final byte AND = '&';
+ public static final byte OR = '|';
+ public static final byte XOR = '^';
+
+
+ private final IntegerValue integerValue1;
+ private final byte operation;
+ private final IntegerValue integerValue2;
+
+
+ /**
+ * Creates a new composite integer value of the two given integer values
+ * and the given operation.
+ */
+ public CompositeIntegerValue(IntegerValue integerValue1,
+ byte operation,
+ IntegerValue integerValue2)
+ {
+ this.integerValue1 = integerValue1;
+ this.operation = operation;
+ this.integerValue2 = integerValue2;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.integerValue1.equals(((CompositeIntegerValue)object).integerValue1) &&
+ this.operation == ((CompositeIntegerValue)object).operation &&
+ this.integerValue2.equals(((CompositeIntegerValue)object).integerValue2);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ integerValue1.hashCode() ^
+ integerValue2.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "("+integerValue1+((char)operation)+integerValue2+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/CompositeLongValue.java b/src/proguard/evaluation/value/CompositeLongValue.java
new file mode 100644
index 000000000..3b8a97f71
--- /dev/null
+++ b/src/proguard/evaluation/value/CompositeLongValue.java
@@ -0,0 +1,87 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This LongValue represents the result of a binary operation on two long
+ * values.
+ *
+ * @author Eric Lafortune
+ */
+final class CompositeLongValue extends SpecificLongValue
+{
+ public static final byte ADD = '+';
+ public static final byte SUBTRACT = '-';
+ public static final byte MULTIPLY = '*';
+ public static final byte DIVIDE = '/';
+ public static final byte REMAINDER = '%';
+ public static final byte SHIFT_LEFT = '<';
+ public static final byte SHIFT_RIGHT = '>';
+ public static final byte UNSIGNED_SHIFT_RIGHT = '}';
+ public static final byte AND = '&';
+ public static final byte OR = '|';
+ public static final byte XOR = '^';
+
+
+ private final LongValue longValue1;
+ private final byte operation;
+ private final Value longValue2;
+
+
+ /**
+ * Creates a new composite long value of the two given long values
+ * and the given operation.
+ */
+ public CompositeLongValue(LongValue longValue1,
+ byte operation,
+ Value longValue2)
+ {
+ this.longValue1 = longValue1;
+ this.operation = operation;
+ this.longValue2 = longValue2;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.longValue1.equals(((CompositeLongValue)object).longValue1) &&
+ this.operation == ((CompositeLongValue)object).operation &&
+ this.longValue2.equals(((CompositeLongValue)object).longValue2);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ longValue1.hashCode() ^
+ longValue2.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "("+longValue1+((char)operation)+longValue2+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ConvertedByteValue.java b/src/proguard/evaluation/value/ConvertedByteValue.java
new file mode 100644
index 000000000..eb1a35049
--- /dev/null
+++ b/src/proguard/evaluation/value/ConvertedByteValue.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a byte value that is converted from an
+ * integer value.
+ *
+ * @author Eric Lafortune
+ */
+final class ConvertedByteValue extends SpecificIntegerValue
+{
+ private final IntegerValue value;
+
+
+ /**
+ * Creates a new converted byte value of the given integer value.
+ */
+ public ConvertedByteValue(IntegerValue value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value.equals(((ConvertedByteValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "(byte)("+value+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ConvertedCharacterValue.java b/src/proguard/evaluation/value/ConvertedCharacterValue.java
new file mode 100644
index 000000000..a491bedcb
--- /dev/null
+++ b/src/proguard/evaluation/value/ConvertedCharacterValue.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a character value that is converted from an
+ * integer value.
+ *
+ * @author Eric Lafortune
+ */
+final class ConvertedCharacterValue extends SpecificIntegerValue
+{
+ private final IntegerValue value;
+
+
+ /**
+ * Creates a new converted character value of the given integer value.
+ */
+ public ConvertedCharacterValue(IntegerValue value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value.equals(((ConvertedCharacterValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "(char)("+value+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ConvertedDoubleValue.java b/src/proguard/evaluation/value/ConvertedDoubleValue.java
new file mode 100644
index 000000000..65fab84f3
--- /dev/null
+++ b/src/proguard/evaluation/value/ConvertedDoubleValue.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This DoubleValue represents a double value that is converted from another
+ * scalar value.
+ *
+ * @author Eric Lafortune
+ */
+final class ConvertedDoubleValue extends SpecificDoubleValue
+{
+ private final Value value;
+
+
+ /**
+ * Creates a new converted double value of the given value.
+ */
+ public ConvertedDoubleValue(Value value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value.equals(((ConvertedDoubleValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "(double)("+value+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ConvertedFloatValue.java b/src/proguard/evaluation/value/ConvertedFloatValue.java
new file mode 100644
index 000000000..e74ec8d5e
--- /dev/null
+++ b/src/proguard/evaluation/value/ConvertedFloatValue.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This FloatValue represents a float value that is converted from another
+ * scalar value.
+ *
+ * @author Eric Lafortune
+ */
+final class ConvertedFloatValue extends SpecificFloatValue
+{
+ private final Value value;
+
+
+ /**
+ * Creates a new converted float value of the given value.
+ */
+ public ConvertedFloatValue(Value value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value.equals(((ConvertedFloatValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "(float)("+value+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ConvertedIntegerValue.java b/src/proguard/evaluation/value/ConvertedIntegerValue.java
new file mode 100644
index 000000000..273b5a16a
--- /dev/null
+++ b/src/proguard/evaluation/value/ConvertedIntegerValue.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a integer value that is converted from another
+ * scalar value.
+ *
+ * @author Eric Lafortune
+ */
+final class ConvertedIntegerValue extends SpecificIntegerValue
+{
+ private final Value value;
+
+
+ /**
+ * Creates a new converted integer value of the given value.
+ */
+ public ConvertedIntegerValue(Value value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value.equals(((ConvertedIntegerValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "(int)("+value+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ConvertedLongValue.java b/src/proguard/evaluation/value/ConvertedLongValue.java
new file mode 100644
index 000000000..5cb9104ac
--- /dev/null
+++ b/src/proguard/evaluation/value/ConvertedLongValue.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This LongValue represents a long value that is converted from another
+ * scalar value.
+ *
+ * @author Eric Lafortune
+ */
+final class ConvertedLongValue extends SpecificLongValue
+{
+ private final Value value;
+
+
+ /**
+ * Creates a new converted long value of the given value.
+ */
+ public ConvertedLongValue(Value value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value.equals(((ConvertedLongValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "(long)("+value+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ConvertedShortValue.java b/src/proguard/evaluation/value/ConvertedShortValue.java
new file mode 100644
index 000000000..cef2a206c
--- /dev/null
+++ b/src/proguard/evaluation/value/ConvertedShortValue.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a short value that is converted from an
+ * integer value.
+ *
+ * @author Eric Lafortune
+ */
+final class ConvertedShortValue extends SpecificIntegerValue
+{
+ private final IntegerValue value;
+
+
+ /**
+ * Creates a new converted short value of the given integer value.
+ */
+ public ConvertedShortValue(IntegerValue value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.value.equals(((ConvertedShortValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ value.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "(short)("+value+")";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/DoubleValue.java b/src/proguard/evaluation/value/DoubleValue.java
new file mode 100644
index 000000000..6630b2ff8
--- /dev/null
+++ b/src/proguard/evaluation/value/DoubleValue.java
@@ -0,0 +1,359 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.ClassConstants;
+
+/**
+ * This class represents a partially evaluated double value.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class DoubleValue extends Category2Value
+{
+ /**
+ * Returns the specific double value, if applicable.
+ */
+ public double value()
+ {
+ return 0.0;
+ }
+
+
+ // Basic unary methods.
+
+ /**
+ * Returns the negated value of this DoubleValue.
+ */
+ public abstract DoubleValue negate();
+
+ /**
+ * Converts this DoubleValue to an IntegerValue.
+ */
+ public abstract IntegerValue convertToInteger();
+
+ /**
+ * Converts this DoubleValue to a LongValue.
+ */
+ public abstract LongValue convertToLong();
+
+ /**
+ * Converts this DoubleValue to a FloatValue.
+ */
+ public abstract FloatValue convertToFloat();
+
+
+ // Basic binary methods.
+
+ /**
+ * Returns the generalization of this DoubleValue and the given other
+ * DoubleValue.
+ */
+ public abstract DoubleValue generalize(DoubleValue other);
+
+
+ /**
+ * Returns the sum of this DoubleValue and the given DoubleValue.
+ */
+ public abstract DoubleValue add(DoubleValue other);
+
+ /**
+ * Returns the difference of this DoubleValue and the given DoubleValue.
+ */
+ public abstract DoubleValue subtract(DoubleValue other);
+
+ /**
+ * Returns the difference of the given DoubleValue and this DoubleValue.
+ */
+ public abstract DoubleValue subtractFrom(DoubleValue other);
+
+ /**
+ * Returns the product of this DoubleValue and the given DoubleValue.
+ */
+ public abstract DoubleValue multiply(DoubleValue other);
+
+ /**
+ * Returns the quotient of this DoubleValue and the given DoubleValue.
+ */
+ public abstract DoubleValue divide(DoubleValue other);
+
+ /**
+ * Returns the quotient of the given DoubleValue and this DoubleValue.
+ */
+ public abstract DoubleValue divideOf(DoubleValue other);
+
+ /**
+ * Returns the remainder of this DoubleValue divided by the given DoubleValue.
+ */
+ public abstract DoubleValue remainder(DoubleValue other);
+
+ /**
+ * Returns the remainder of the given DoubleValue divided by this DoubleValue.
+ */
+ public abstract DoubleValue remainderOf(DoubleValue other);
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this DoubleValue is
+ * less than, equal to, or greater than the given DoubleValue, respectively.
+ */
+ public abstract IntegerValue compare(DoubleValue other);
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this DoubleValue is
+ * less than, equal to, or greater than the given DoubleValue, respectively.
+ */
+ public final IntegerValue compareReverse(DoubleValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Similar binary methods, but this time with more specific arguments.
+
+ /**
+ * Returns the generalization of this DoubleValue and the given other
+ * SpecificDoubleValue.
+ */
+ public DoubleValue generalize(SpecificDoubleValue other)
+ {
+ return generalize((DoubleValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this DoubleValue and the given SpecificDoubleValue.
+ */
+ public DoubleValue add(SpecificDoubleValue other)
+ {
+ return add((DoubleValue)other);
+ }
+
+ /**
+ * Returns the difference of this DoubleValue and the given SpecificDoubleValue.
+ */
+ public DoubleValue subtract(SpecificDoubleValue other)
+ {
+ return subtract((DoubleValue)other);
+ }
+
+ /**
+ * Returns the difference of the given SpecificDoubleValue and this DoubleValue.
+ */
+ public DoubleValue subtractFrom(SpecificDoubleValue other)
+ {
+ return subtractFrom((DoubleValue)other);
+ }
+
+ /**
+ * Returns the product of this DoubleValue and the given SpecificDoubleValue.
+ */
+ public DoubleValue multiply(SpecificDoubleValue other)
+ {
+ return multiply((DoubleValue)other);
+ }
+
+ /**
+ * Returns the quotient of this DoubleValue and the given SpecificDoubleValue.
+ */
+ public DoubleValue divide(SpecificDoubleValue other)
+ {
+ return divide((DoubleValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given SpecificDoubleValue and this
+ * DoubleValue.
+ */
+ public DoubleValue divideOf(SpecificDoubleValue other)
+ {
+ return divideOf((DoubleValue)other);
+ }
+
+ /**
+ * Returns the remainder of this DoubleValue divided by the given
+ * SpecificDoubleValue.
+ */
+ public DoubleValue remainder(SpecificDoubleValue other)
+ {
+ return remainder((DoubleValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given SpecificDoubleValue and this
+ * DoubleValue.
+ */
+ public DoubleValue remainderOf(SpecificDoubleValue other)
+ {
+ return remainderOf((DoubleValue)other);
+ }
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this DoubleValue is
+ * less than, equal to, or greater than the given SpecificDoubleValue,
+ * respectively.
+ */
+ public IntegerValue compare(SpecificDoubleValue other)
+ {
+ return compare((DoubleValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this DoubleValue is
+ * less than, equal to, or greater than the given SpecificDoubleValue,
+ * respectively.
+ */
+ public final IntegerValue compareReverse(SpecificDoubleValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Similar binary methods, but this time with particular arguments.
+
+ /**
+ * Returns the generalization of this DoubleValue and the given other
+ * ParticularDoubleValue.
+ */
+ public DoubleValue generalize(ParticularDoubleValue other)
+ {
+ return generalize((SpecificDoubleValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this DoubleValue and the given ParticularDoubleValue.
+ */
+ public DoubleValue add(ParticularDoubleValue other)
+ {
+ return add((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns the difference of this DoubleValue and the given ParticularDoubleValue.
+ */
+ public DoubleValue subtract(ParticularDoubleValue other)
+ {
+ return subtract((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns the difference of the given ParticularDoubleValue and this DoubleValue.
+ */
+ public DoubleValue subtractFrom(ParticularDoubleValue other)
+ {
+ return subtractFrom((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns the product of this DoubleValue and the given ParticularDoubleValue.
+ */
+ public DoubleValue multiply(ParticularDoubleValue other)
+ {
+ return multiply((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns the quotient of this DoubleValue and the given ParticularDoubleValue.
+ */
+ public DoubleValue divide(ParticularDoubleValue other)
+ {
+ return divide((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given ParticularDoubleValue and this
+ * DoubleValue.
+ */
+ public DoubleValue divideOf(ParticularDoubleValue other)
+ {
+ return divideOf((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns the remainder of this DoubleValue divided by the given
+ * ParticularDoubleValue.
+ */
+ public DoubleValue remainder(ParticularDoubleValue other)
+ {
+ return remainder((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given ParticularDoubleValue and this
+ * DoubleValue.
+ */
+ public DoubleValue remainderOf(ParticularDoubleValue other)
+ {
+ return remainderOf((SpecificDoubleValue)other);
+ }
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this DoubleValue is
+ * less than, equal to, or greater than the given ParticularDoubleValue,
+ * respectively.
+ */
+ public IntegerValue compare(ParticularDoubleValue other)
+ {
+ return compare((SpecificDoubleValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this DoubleValue is
+ * less than, equal to, or greater than the given ParticularDoubleValue,
+ * respectively.
+ */
+ public final IntegerValue compareReverse(ParticularDoubleValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Implementations for Value.
+
+ public final DoubleValue doubleValue()
+ {
+ return this;
+ }
+
+ public final Value generalize(Value other)
+ {
+ return this.generalize(other.doubleValue());
+ }
+
+ public final int computationalType()
+ {
+ return TYPE_DOUBLE;
+ }
+
+ public final String internalType()
+ {
+ return String.valueOf(ClassConstants.INTERNAL_TYPE_DOUBLE);
+ }
+}
diff --git a/src/proguard/evaluation/value/FloatValue.java b/src/proguard/evaluation/value/FloatValue.java
new file mode 100644
index 000000000..6dc8bee86
--- /dev/null
+++ b/src/proguard/evaluation/value/FloatValue.java
@@ -0,0 +1,359 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.ClassConstants;
+
+/**
+ * This class represents a partially evaluated float value.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class FloatValue extends Category1Value
+{
+ /**
+ * Returns the specific float value, if applicable.
+ */
+ public float value()
+ {
+ return 0f;
+ }
+
+
+ // Basic unary methods.
+
+ /**
+ * Returns the negated value of this FloatValue.
+ */
+ public abstract FloatValue negate();
+
+ /**
+ * Converts this FloatValue to an IntegerValue.
+ */
+ public abstract IntegerValue convertToInteger();
+
+ /**
+ * Converts this FloatValue to a LongValue.
+ */
+ public abstract LongValue convertToLong();
+
+ /**
+ * Converts this FloatValue to a DoubleValue.
+ */
+ public abstract DoubleValue convertToDouble();
+
+
+ // Basic binary methods.
+
+ /**
+ * Returns the generalization of this FloatValue and the given other
+ * FloatValue.
+ */
+ public abstract FloatValue generalize(FloatValue other);
+
+
+ /**
+ * Returns the sum of this FloatValue and the given FloatValue.
+ */
+ public abstract FloatValue add(FloatValue other);
+
+ /**
+ * Returns the difference of this FloatValue and the given FloatValue.
+ */
+ public abstract FloatValue subtract(FloatValue other);
+
+ /**
+ * Returns the difference of the given FloatValue and this FloatValue.
+ */
+ public abstract FloatValue subtractFrom(FloatValue other);
+
+ /**
+ * Returns the product of this FloatValue and the given FloatValue.
+ */
+ public abstract FloatValue multiply(FloatValue other);
+
+ /**
+ * Returns the quotient of this FloatValue and the given FloatValue.
+ */
+ public abstract FloatValue divide(FloatValue other);
+
+ /**
+ * Returns the quotient of the given FloatValue and this FloatValue.
+ */
+ public abstract FloatValue divideOf(FloatValue other);
+
+ /**
+ * Returns the remainder of this FloatValue divided by the given FloatValue.
+ */
+ public abstract FloatValue remainder(FloatValue other);
+
+ /**
+ * Returns the remainder of the given FloatValue divided by this FloatValue.
+ */
+ public abstract FloatValue remainderOf(FloatValue other);
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this FloatValue is
+ * less than, equal to, or greater than the given FloatValue, respectively.
+ */
+ public abstract IntegerValue compare(FloatValue other);
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this FloatValue is
+ * less than, equal to, or greater than the given FloatValue, respectively.
+ */
+ public final IntegerValue compareReverse(FloatValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Similar binary methods, but this time with more specific arguments.
+
+ /**
+ * Returns the generalization of this FloatValue and the given other
+ * SpecificFloatValue.
+ */
+ public FloatValue generalize(SpecificFloatValue other)
+ {
+ return generalize((FloatValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this FloatValue and the given SpecificFloatValue.
+ */
+ public FloatValue add(SpecificFloatValue other)
+ {
+ return add((FloatValue)other);
+ }
+
+ /**
+ * Returns the difference of this FloatValue and the given SpecificFloatValue.
+ */
+ public FloatValue subtract(SpecificFloatValue other)
+ {
+ return subtract((FloatValue)other);
+ }
+
+ /**
+ * Returns the difference of the given SpecificFloatValue and this FloatValue.
+ */
+ public FloatValue subtractFrom(SpecificFloatValue other)
+ {
+ return subtractFrom((FloatValue)other);
+ }
+
+ /**
+ * Returns the product of this FloatValue and the given SpecificFloatValue.
+ */
+ public FloatValue multiply(SpecificFloatValue other)
+ {
+ return multiply((FloatValue)other);
+ }
+
+ /**
+ * Returns the quotient of this FloatValue and the given SpecificFloatValue.
+ */
+ public FloatValue divide(SpecificFloatValue other)
+ {
+ return divide((FloatValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given SpecificFloatValue and this
+ * FloatValue.
+ */
+ public FloatValue divideOf(SpecificFloatValue other)
+ {
+ return divideOf((FloatValue)other);
+ }
+
+ /**
+ * Returns the remainder of this FloatValue divided by the given
+ * SpecificFloatValue.
+ */
+ public FloatValue remainder(SpecificFloatValue other)
+ {
+ return remainder((FloatValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given SpecificFloatValue and this
+ * FloatValue.
+ */
+ public FloatValue remainderOf(SpecificFloatValue other)
+ {
+ return remainderOf((FloatValue)other);
+ }
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this FloatValue is
+ * less than, equal to, or greater than the given SpecificFloatValue,
+ * respectively.
+ */
+ public IntegerValue compare(SpecificFloatValue other)
+ {
+ return compare((FloatValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this FloatValue is
+ * less than, equal to, or greater than the given SpecificFloatValue,
+ * respectively.
+ */
+ public final IntegerValue compareReverse(SpecificFloatValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Similar binary methods, but this time with particular arguments.
+
+ /**
+ * Returns the generalization of this FloatValue and the given other
+ * ParticularFloatValue.
+ */
+ public FloatValue generalize(ParticularFloatValue other)
+ {
+ return generalize((SpecificFloatValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this FloatValue and the given ParticularFloatValue.
+ */
+ public FloatValue add(ParticularFloatValue other)
+ {
+ return add((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns the difference of this FloatValue and the given ParticularFloatValue.
+ */
+ public FloatValue subtract(ParticularFloatValue other)
+ {
+ return subtract((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns the difference of the given ParticularFloatValue and this FloatValue.
+ */
+ public FloatValue subtractFrom(ParticularFloatValue other)
+ {
+ return subtractFrom((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns the product of this FloatValue and the given ParticularFloatValue.
+ */
+ public FloatValue multiply(ParticularFloatValue other)
+ {
+ return multiply((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns the quotient of this FloatValue and the given ParticularFloatValue.
+ */
+ public FloatValue divide(ParticularFloatValue other)
+ {
+ return divide((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given ParticularFloatValue and this
+ * FloatValue.
+ */
+ public FloatValue divideOf(ParticularFloatValue other)
+ {
+ return divideOf((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns the remainder of this FloatValue divided by the given
+ * ParticularFloatValue.
+ */
+ public FloatValue remainder(ParticularFloatValue other)
+ {
+ return remainder((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given ParticularFloatValue and this
+ * FloatValue.
+ */
+ public FloatValue remainderOf(ParticularFloatValue other)
+ {
+ return remainderOf((SpecificFloatValue)other);
+ }
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this FloatValue is
+ * less than, equal to, or greater than the given ParticularFloatValue,
+ * respectively.
+ */
+ public IntegerValue compare(ParticularFloatValue other)
+ {
+ return compare((SpecificFloatValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this FloatValue is
+ * less than, equal to, or greater than the given ParticularFloatValue,
+ * respectively.
+ */
+ public final IntegerValue compareReverse(ParticularFloatValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Implementations for Value.
+
+ public final FloatValue floatValue()
+ {
+ return this;
+ }
+
+ public final Value generalize(Value other)
+ {
+ return this.generalize(other.floatValue());
+ }
+
+ public final int computationalType()
+ {
+ return TYPE_FLOAT;
+ }
+
+ public final String internalType()
+ {
+ return String.valueOf(ClassConstants.INTERNAL_TYPE_FLOAT);
+ }
+}
diff --git a/src/proguard/evaluation/value/IdentifiedDoubleValue.java b/src/proguard/evaluation/value/IdentifiedDoubleValue.java
new file mode 100644
index 000000000..4ff24668f
--- /dev/null
+++ b/src/proguard/evaluation/value/IdentifiedDoubleValue.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This DoubleValue represents a double value that is identified by a unique ID.
+ *
+ * @author Eric Lafortune
+ */
+final class IdentifiedDoubleValue extends SpecificDoubleValue
+{
+ private final ValueFactory valuefactory;
+ private final int id;
+
+
+ /**
+ * Creates a new double value with the given ID.
+ */
+ public IdentifiedDoubleValue(ValueFactory valuefactory, int id)
+ {
+ this.valuefactory = valuefactory;
+ this.id = id;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.valuefactory.equals(((IdentifiedDoubleValue)object).valuefactory) &&
+ this.id == ((IdentifiedDoubleValue)object).id;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ valuefactory.hashCode() ^
+ id;
+ }
+
+
+ public String toString()
+ {
+ return "d"+id;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/IdentifiedFloatValue.java b/src/proguard/evaluation/value/IdentifiedFloatValue.java
new file mode 100644
index 000000000..c8349bcbb
--- /dev/null
+++ b/src/proguard/evaluation/value/IdentifiedFloatValue.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This FloatValue represents a float value that is identified by a unique ID.
+ *
+ * @author Eric Lafortune
+ */
+final class IdentifiedFloatValue extends SpecificFloatValue
+{
+ private final ValueFactory valuefactory;
+ private final int id;
+
+
+ /**
+ * Creates a new float value with the given ID.
+ */
+ public IdentifiedFloatValue(ValueFactory valuefactory, int id)
+ {
+ this.valuefactory = valuefactory;
+ this.id = id;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.valuefactory.equals(((IdentifiedFloatValue)object).valuefactory) &&
+ this.id == ((IdentifiedFloatValue)object).id;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ valuefactory.hashCode() ^
+ id;
+ }
+
+
+ public String toString()
+ {
+ return "f"+id;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/IdentifiedIntegerValue.java b/src/proguard/evaluation/value/IdentifiedIntegerValue.java
new file mode 100644
index 000000000..6c3ee5d8e
--- /dev/null
+++ b/src/proguard/evaluation/value/IdentifiedIntegerValue.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a integer value that is identified by a unique ID.
+ *
+ * @author Eric Lafortune
+ */
+final class IdentifiedIntegerValue extends SpecificIntegerValue
+{
+ private final ValueFactory valuefactory;
+ private final int id;
+
+
+ /**
+ * Creates a new integer value with the given ID.
+ */
+ public IdentifiedIntegerValue(ValueFactory valuefactory, int id)
+ {
+ this.valuefactory = valuefactory;
+ this.id = id;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.valuefactory.equals(((IdentifiedIntegerValue)object).valuefactory) &&
+ this.id == ((IdentifiedIntegerValue)object).id;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ valuefactory.hashCode() ^
+ id;
+ }
+
+
+ public String toString()
+ {
+ return "i"+id;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/IdentifiedLongValue.java b/src/proguard/evaluation/value/IdentifiedLongValue.java
new file mode 100644
index 000000000..e0b68f2de
--- /dev/null
+++ b/src/proguard/evaluation/value/IdentifiedLongValue.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This LongValue represents a long value that is identified by a unique ID.
+ *
+ * @author Eric Lafortune
+ */
+final class IdentifiedLongValue extends SpecificLongValue
+{
+ private final ValueFactory valuefactory;
+ private final int id;
+
+
+ /**
+ * Creates a new long value with the given ID.
+ */
+ public IdentifiedLongValue(ValueFactory valuefactory, int id)
+ {
+ this.valuefactory = valuefactory;
+ this.id = id;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.valuefactory.equals(((IdentifiedLongValue)object).valuefactory) &&
+ this.id == ((IdentifiedLongValue)object).id;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ valuefactory.hashCode() ^
+ id;
+ }
+
+
+ public String toString()
+ {
+ return "l"+id;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/IdentifiedReferenceValue.java b/src/proguard/evaluation/value/IdentifiedReferenceValue.java
new file mode 100644
index 000000000..5cfbd6093
--- /dev/null
+++ b/src/proguard/evaluation/value/IdentifiedReferenceValue.java
@@ -0,0 +1,102 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.Clazz;
+
+/**
+ * This LongValue represents a reference value that is identified by a unique ID.
+ *
+ * @author Eric Lafortune
+ */
+final class IdentifiedReferenceValue extends ReferenceValue
+{
+ private final ValueFactory valuefactory;
+ private final int id;
+
+
+ /**
+ * Creates a new long value with the given ID.
+ */
+ public IdentifiedReferenceValue(String type,
+ Clazz referencedClass,
+ boolean mayBeNull,
+ ValueFactory valuefactory,
+ int id)
+ {
+ super(type, referencedClass, mayBeNull);
+
+ this.valuefactory = valuefactory;
+ this.id = id;
+ }
+
+
+ // Implementations for ReferenceValue.
+
+ public int equal(ReferenceValue other)
+ {
+ return this.equals(other) ? ALWAYS : MAYBE;
+ }
+
+
+ // Implementations of binary methods of ReferenceValue.
+
+ public ReferenceValue generalize(ReferenceValue other)
+ {
+ // Remove the ID if both values don't share the same ID.
+ return this.equals(other) ?
+ this :
+ new ReferenceValue(type, referencedClass, mayBeNull).generalize(other);
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isSpecific()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.valuefactory.equals(((IdentifiedReferenceValue)object).valuefactory) &&
+ this.id == ((IdentifiedReferenceValue)object).id;
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ valuefactory.hashCode() ^
+ id;
+ }
+
+
+ public String toString()
+ {
+ return super.toString()+'#'+id;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/IdentifiedValueFactory.java b/src/proguard/evaluation/value/IdentifiedValueFactory.java
new file mode 100644
index 000000000..be5c88570
--- /dev/null
+++ b/src/proguard/evaluation/value/IdentifiedValueFactory.java
@@ -0,0 +1,75 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.*;
+import proguard.classfile.util.ClassUtil;
+
+/**
+ * This class provides methods to create and reuse IntegerValue objects.
+ *
+ * @author Eric Lafortune
+ */
+public class IdentifiedValueFactory
+extends SpecificValueFactory
+{
+ private int integerID;
+ private int longID;
+ private int floatID;
+ private int doubleID;
+ private int referenceID;
+
+
+ // Implementations for ValueFactory.
+
+ public IntegerValue createIntegerValue()
+ {
+ return new IdentifiedIntegerValue(this, integerID++);
+ }
+
+
+ public LongValue createLongValue()
+ {
+ return new IdentifiedLongValue(this, longID++);
+ }
+
+
+ public FloatValue createFloatValue()
+ {
+ return new IdentifiedFloatValue(this, floatID++);
+ }
+
+
+ public DoubleValue createDoubleValue()
+ {
+ return new IdentifiedDoubleValue(this, doubleID++);
+ }
+
+
+ public ReferenceValue createReferenceValue(String type,
+ Clazz referencedClass,
+ boolean mayBeNull)
+ {
+ return type == null ?
+ REFERENCE_VALUE_NULL :
+ new IdentifiedReferenceValue(type, referencedClass, mayBeNull, this, referenceID++);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/InstructionOffsetValue.java b/src/proguard/evaluation/value/InstructionOffsetValue.java
new file mode 100644
index 000000000..07a44ee36
--- /dev/null
+++ b/src/proguard/evaluation/value/InstructionOffsetValue.java
@@ -0,0 +1,307 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.ClassConstants;
+
+/**
+ * This class represents a partially evaluated instruction offset. It can
+ * contain 0 or more specific instruction offsets.
+ *
+ * @author Eric Lafortune
+ */
+public class InstructionOffsetValue extends Category1Value
+{
+ public static final InstructionOffsetValue EMPTY_VALUE = new InstructionOffsetValue();
+
+
+ private int[] values;
+
+
+ private InstructionOffsetValue()
+ {
+ }
+
+
+ public InstructionOffsetValue(int value)
+ {
+ this.values = new int[] { value };
+ }
+
+
+ public InstructionOffsetValue(int[] values)
+ {
+ this.values = values;
+ }
+
+
+ public int instructionOffsetCount()
+ {
+ return values == null ? 0 : values.length;
+ }
+
+
+ public int instructionOffset(int index)
+ {
+ return values[index];
+ }
+
+
+ /**
+ * Returns whether the given value is present in this list of instruction
+ * offsets.
+ */
+ public boolean contains(int value)
+ {
+ if (values != null)
+ {
+ for (int index = 0; index < values.length; index++)
+ {
+ if (values[index] == value)
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns the minimum value from this list of instruction offsets.
+ * Returns Integer.MAX_VALUE
if the list is empty.
+ */
+ public int minimumValue()
+ {
+ int minimumValue = Integer.MAX_VALUE;
+
+ if (values != null)
+ {
+ for (int index = 0; index < values.length; index++)
+ {
+ int value = values[index];
+
+ if (minimumValue > value)
+ {
+ minimumValue = value;
+ }
+ }
+ }
+
+ return minimumValue;
+ }
+
+
+ /**
+ * Returns the maximum value from this list of instruction offsets.
+ * Returns Integer.MIN_VALUE
if the list is empty.
+ */
+ public int maximumValue()
+ {
+ int maximumValue = Integer.MIN_VALUE;
+
+ if (values != null)
+ {
+ for (int index = 0; index < values.length; index++)
+ {
+ int value = values[index];
+
+ if (maximumValue < value)
+ {
+ maximumValue = value;
+ }
+ }
+ }
+
+ return maximumValue;
+ }
+
+
+ /**
+ * Returns the generalization of this InstructionOffsetValue and the given
+ * other InstructionOffsetValue. The values of the other InstructionOffsetValue
+ * are guaranteed to remain at the end of the list, in the same order.
+ */
+ public final Value generalize(InstructionOffsetValue other)
+ {
+ // If the values array of either is null, return the other one.
+ if (this.values == null)
+ {
+ return other;
+ }
+
+ if (other.values == null)
+ {
+ return this;
+ }
+
+ // Compute the length of the union of the arrays.
+ int newLength = this.values.length;
+ for (int index = 0; index < other.values.length; index++)
+ {
+ if (!this.contains(other.values[index]))
+ {
+ newLength++;
+ }
+ }
+
+ // If the length of the union array is equal to the length of the values
+ // array of either, return it.
+ if (newLength == other.values.length)
+ {
+ return other;
+ }
+
+ // The ordering of the this array may not be right, so we can't just
+ // use it.
+ //if (newLength == this.values.length)
+ //{
+ // return this;
+ //}
+
+ // Create the union array.
+ int[] newValues = new int[newLength];
+
+ int newIndex = 0;
+
+ // Copy the values that are different from the other array.
+ for (int index = 0; index < this.values.length; index++)
+ {
+ if (!other.contains(this.values[index]))
+ {
+ newValues[newIndex++] = this.values[index];
+ }
+ }
+
+ // Copy the values from the other array.
+ for (int index = 0; index < other.values.length; index++)
+ {
+ newValues[newIndex++] = other.values[index];
+ }
+
+ return new InstructionOffsetValue(newValues);
+ }
+
+
+ // Implementations for Value.
+
+ public final InstructionOffsetValue instructionOffsetValue()
+ {
+ return this;
+ }
+
+ public boolean isSpecific()
+ {
+ return true;
+ }
+
+ public boolean isParticular()
+ {
+ return true;
+ }
+
+ public final Value generalize(Value other)
+ {
+ return this.generalize(other.instructionOffsetValue());
+ }
+
+ public final int computationalType()
+ {
+ return TYPE_INSTRUCTION_OFFSET;
+ }
+
+ public final String internalType()
+ {
+ return String.valueOf(ClassConstants.INTERNAL_TYPE_INT);
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ InstructionOffsetValue other = (InstructionOffsetValue)object;
+ if (this.values == other.values)
+ {
+ return true;
+ }
+
+ if (this.values == null ||
+ other.values == null ||
+ this.values.length != other.values.length)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < other.values.length; index++)
+ {
+ if (!this.contains(other.values[index]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ public int hashCode()
+ {
+ int hashCode = this.getClass().hashCode();
+
+ if (values != null)
+ {
+ for (int index = 0; index < values.length; index++)
+ {
+ hashCode ^= values[index];
+ }
+ }
+
+ return hashCode;
+ }
+
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer();
+
+ if (values != null)
+ {
+ for (int index = 0; index < values.length; index++)
+ {
+ if (index > 0)
+ {
+ buffer.append(',');
+ }
+ buffer.append(values[index]);
+ }
+ }
+
+ return buffer.append(':').toString();
+ }
+}
diff --git a/src/proguard/evaluation/value/IntegerValue.java b/src/proguard/evaluation/value/IntegerValue.java
new file mode 100644
index 000000000..b1824c67b
--- /dev/null
+++ b/src/proguard/evaluation/value/IntegerValue.java
@@ -0,0 +1,1002 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.ClassConstants;
+
+/**
+ * This class represents a partially evaluated integer value.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class IntegerValue extends Category1Value
+{
+ /**
+ * Returns the specific integer value, if applicable.
+ */
+ public int value()
+ {
+ return 0;
+ }
+
+
+ // Basic unary methods.
+
+ /**
+ * Returns the negated value of this IntegerValue.
+ */
+ public abstract IntegerValue negate();
+
+ /**
+ * Converts this IntegerValue to a byte IntegerValue.
+ */
+ public abstract IntegerValue convertToByte();
+
+ /**
+ * Converts this IntegerValue to a character IntegerValue.
+ */
+ public abstract IntegerValue convertToCharacter();
+
+ /**
+ * Converts this IntegerValue to a short IntegerValue.
+ */
+ public abstract IntegerValue convertToShort();
+
+ /**
+ * Converts this IntegerValue to a LongValue.
+ */
+ public abstract LongValue convertToLong();
+
+ /**
+ * Converts this IntegerValue to a FloatValue.
+ */
+ public abstract FloatValue convertToFloat();
+
+ /**
+ * Converts this IntegerValue to a DoubleValue.
+ */
+ public abstract DoubleValue convertToDouble();
+
+
+ // Basic binary methods.
+
+ /**
+ * Returns the generalization of this IntegerValue and the given other
+ * IntegerValue.
+ */
+ public abstract IntegerValue generalize(IntegerValue other);
+
+ /**
+ * Returns the sum of this IntegerValue and the given IntegerValue.
+ */
+ public abstract IntegerValue add(IntegerValue other);
+
+ /**
+ * Returns the difference of this IntegerValue and the given IntegerValue.
+ */
+ public abstract IntegerValue subtract(IntegerValue other);
+
+ /**
+ * Returns the difference of the given IntegerValue and this IntegerValue.
+ */
+ public abstract IntegerValue subtractFrom(IntegerValue other);
+
+ /**
+ * Returns the product of this IntegerValue and the given IntegerValue.
+ */
+ public abstract IntegerValue multiply(IntegerValue other)
+ throws ArithmeticException;
+
+ /**
+ * Returns the quotient of this IntegerValue and the given IntegerValue.
+ */
+ public abstract IntegerValue divide(IntegerValue other)
+ throws ArithmeticException;
+
+ /**
+ * Returns the quotient of the given IntegerValue and this IntegerValue.
+ */
+ public abstract IntegerValue divideOf(IntegerValue other)
+ throws ArithmeticException;
+
+ /**
+ * Returns the remainder of this IntegerValue divided by the given
+ * IntegerValue.
+ */
+ public abstract IntegerValue remainder(IntegerValue other)
+ throws ArithmeticException;
+
+ /**
+ * Returns the remainder of the given IntegerValue divided by this
+ * IntegerValue.
+ */
+ public abstract IntegerValue remainderOf(IntegerValue other)
+ throws ArithmeticException;
+
+ /**
+ * Returns this IntegerValue, shifted left by the given IntegerValue.
+ */
+ public abstract IntegerValue shiftLeft(IntegerValue other);
+
+ /**
+ * Returns this IntegerValue, shifted right by the given IntegerValue.
+ */
+ public abstract IntegerValue shiftRight(IntegerValue other);
+
+ /**
+ * Returns this unsigned IntegerValue, shifted left by the given
+ * IntegerValue.
+ */
+ public abstract IntegerValue unsignedShiftRight(IntegerValue other);
+
+ /**
+ * Returns the given IntegerValue, shifted left by this IntegerValue.
+ */
+ public abstract IntegerValue shiftLeftOf(IntegerValue other);
+
+ /**
+ * Returns the given IntegerValue, shifted right by this IntegerValue.
+ */
+ public abstract IntegerValue shiftRightOf(IntegerValue other);
+
+ /**
+ * Returns the given unsigned IntegerValue, shifted left by this
+ * IntegerValue.
+ */
+ public abstract IntegerValue unsignedShiftRightOf(IntegerValue other);
+
+ /**
+ * Returns the given LongValue, shifted left by this IntegerValue.
+ */
+ public abstract LongValue shiftLeftOf(LongValue other);
+
+ /**
+ * Returns the given LongValue, shifted right by this IntegerValue.
+ */
+ public abstract LongValue shiftRightOf(LongValue other);
+
+ /**
+ * Returns the given unsigned LongValue, shifted right by this IntegerValue.
+ */
+ public abstract LongValue unsignedShiftRightOf(LongValue other);
+
+ /**
+ * Returns the logical and of this IntegerValue and the given
+ * IntegerValue.
+ */
+ public abstract IntegerValue and(IntegerValue other);
+
+ /**
+ * Returns the logical or of this IntegerValue and the given
+ * IntegerValue.
+ */
+ public abstract IntegerValue or(IntegerValue other);
+
+ /**
+ * Returns the logical xor of this IntegerValue and the given
+ * IntegerValue.
+ */
+ public abstract IntegerValue xor(IntegerValue other);
+
+ /**
+ * Returns whether this IntegerValue and the given IntegerValue are equal:
+ * NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public abstract int equal(IntegerValue other);
+
+ /**
+ * Returns whether this IntegerValue is less than the given IntegerValue:
+ * NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public abstract int lessThan(IntegerValue other);
+
+ /**
+ * Returns whether this IntegerValue is less than or equal to the given
+ * IntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public abstract int lessThanOrEqual(IntegerValue other);
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns whether this IntegerValue and the given IntegerValue are different:
+ * NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int notEqual(IntegerValue other)
+ {
+ return -equal(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than the given IntegerValue:
+ * NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int greaterThan(IntegerValue other)
+ {
+ return -lessThanOrEqual(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than or equal to the given IntegerValue:
+ * NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int greaterThanOrEqual(IntegerValue other)
+ {
+ return -lessThan(other);
+ }
+
+
+ // Similar binary methods, but this time with unknown arguments.
+
+ /**
+ * Returns the generalization of this IntegerValue and the given other
+ * UnknownIntegerValue.
+ */
+ public IntegerValue generalize(UnknownIntegerValue other)
+ {
+ return generalize((IntegerValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this IntegerValue and the given UnknownIntegerValue.
+ */
+ public IntegerValue add(UnknownIntegerValue other)
+ {
+ return add((IntegerValue)other);
+ }
+
+ /**
+ * Returns the difference of this IntegerValue and the given UnknownIntegerValue.
+ */
+ public IntegerValue subtract(UnknownIntegerValue other)
+ {
+ return subtract((IntegerValue)other);
+ }
+
+ /**
+ * Returns the difference of the given UnknownIntegerValue and this IntegerValue.
+ */
+ public IntegerValue subtractFrom(UnknownIntegerValue other)
+ {
+ return subtractFrom((IntegerValue)other);
+ }
+
+ /**
+ * Returns the product of this IntegerValue and the given UnknownIntegerValue.
+ */
+ public IntegerValue multiply(UnknownIntegerValue other)
+ {
+ return multiply((IntegerValue)other);
+ }
+
+ /**
+ * Returns the quotient of this IntegerValue and the given
+ * UnknownIntegerValue.
+ */
+ public IntegerValue divide(UnknownIntegerValue other)
+ {
+ return divide((IntegerValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given UnknownIntegerValue and this
+ * IntegerValue.
+ */
+ public IntegerValue divideOf(UnknownIntegerValue other)
+ {
+ return divideOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the remainder of this IntegerValue divided by the given
+ * UnknownIntegerValue.
+ */
+ public IntegerValue remainder(UnknownIntegerValue other)
+ {
+ return remainder((IntegerValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given UnknownIntegerValue divided by this
+ * IntegerValue.
+ */
+ public IntegerValue remainderOf(UnknownIntegerValue other)
+ {
+ return remainderOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns this IntegerValue, shifted left by the given UnknownIntegerValue.
+ */
+ public IntegerValue shiftLeft(UnknownIntegerValue other)
+ {
+ return shiftLeft((IntegerValue)other);
+ }
+
+ /**
+ * Returns this IntegerValue, shifted right by the given UnknownIntegerValue.
+ */
+ public IntegerValue shiftRight(UnknownIntegerValue other)
+ {
+ return shiftRight((IntegerValue)other);
+ }
+
+ /**
+ * Returns this unsigned IntegerValue, shifted right by the given
+ * UnknownIntegerValue.
+ */
+ public IntegerValue unsignedShiftRight(UnknownIntegerValue other)
+ {
+ return unsignedShiftRight((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given UnknownIntegerValue, shifted left by this IntegerValue.
+ */
+ public IntegerValue shiftLeftOf(UnknownIntegerValue other)
+ {
+ return shiftLeftOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given UnknownIntegerValue, shifted right by this IntegerValue.
+ */
+ public IntegerValue shiftRightOf(UnknownIntegerValue other)
+ {
+ return shiftRightOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given unsigned UnknownIntegerValue, shifted right by this
+ * IntegerValue.
+ */
+ public IntegerValue unsignedShiftRightOf(UnknownIntegerValue other)
+ {
+ return unsignedShiftRightOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given UnknownLongValue, shifted left by this IntegerValue.
+ */
+ public LongValue shiftLeftOf(UnknownLongValue other)
+ {
+ return shiftLeftOf((LongValue)other);
+ }
+
+ /**
+ * Returns the given UnknownLongValue, shifted right by this IntegerValue.
+ */
+ public LongValue shiftRightOf(UnknownLongValue other)
+ {
+ return shiftRightOf((LongValue)other);
+ }
+
+ /**
+ * Returns the given unsigned UnknownLongValue, shifted right by this
+ * IntegerValue.
+ */
+ public LongValue unsignedShiftRightOf(UnknownLongValue other)
+ {
+ return unsignedShiftRightOf((LongValue)other);
+ }
+
+ /**
+ * Returns the logical and of this IntegerValue and the given
+ * UnknownIntegerValue.
+ */
+ public IntegerValue and(UnknownIntegerValue other)
+ {
+ return and((IntegerValue)other);
+ }
+
+ /**
+ * Returns the logical or of this IntegerValue and the given
+ * UnknownIntegerValue.
+ */
+ public IntegerValue or(UnknownIntegerValue other)
+ {
+ return or((IntegerValue)other);
+ }
+
+ /**
+ * Returns the logical xor of this IntegerValue and the given
+ * UnknownIntegerValue.
+ */
+ public IntegerValue xor(UnknownIntegerValue other)
+ {
+ return xor((IntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue and the given UnknownIntegerValue are
+ * equal: NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public int equal(UnknownIntegerValue other)
+ {
+ return equal((IntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is less than the given
+ * UnknownIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public int lessThan(UnknownIntegerValue other)
+ {
+ return lessThan((IntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is less than or equal to the given
+ * UnknownIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public int lessThanOrEqual(UnknownIntegerValue other)
+ {
+ return lessThanOrEqual((IntegerValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns whether this IntegerValue and the given UnknownIntegerValue are
+ * different: NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int notEqual(UnknownIntegerValue other)
+ {
+ return -equal(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than the given
+ * UnknownIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public final int greaterThan(UnknownIntegerValue other)
+ {
+ return -lessThanOrEqual(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than or equal to the given
+ * UnknownIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public final int greaterThanOrEqual(UnknownIntegerValue other)
+ {
+ return -lessThan(other);
+ }
+
+
+ // Similar binary methods, but this time with specific arguments.
+
+ /**
+ * Returns the generalization of this IntegerValue and the given other
+ * SpecificIntegerValue.
+ */
+ public IntegerValue generalize(SpecificIntegerValue other)
+ {
+ return generalize((IntegerValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this IntegerValue and the given SpecificIntegerValue.
+ */
+ public IntegerValue add(SpecificIntegerValue other)
+ {
+ return add((IntegerValue)other);
+ }
+
+ /**
+ * Returns the difference of this IntegerValue and the given SpecificIntegerValue.
+ */
+ public IntegerValue subtract(SpecificIntegerValue other)
+ {
+ return subtract((IntegerValue)other);
+ }
+
+ /**
+ * Returns the difference of the given SpecificIntegerValue and this IntegerValue.
+ */
+ public IntegerValue subtractFrom(SpecificIntegerValue other)
+ {
+ return subtractFrom((IntegerValue)other);
+ }
+
+ /**
+ * Returns the product of this IntegerValue and the given SpecificIntegerValue.
+ */
+ public IntegerValue multiply(SpecificIntegerValue other)
+ {
+ return multiply((IntegerValue)other);
+ }
+
+ /**
+ * Returns the quotient of this IntegerValue and the given
+ * SpecificIntegerValue.
+ */
+ public IntegerValue divide(SpecificIntegerValue other)
+ {
+ return divide((IntegerValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given SpecificIntegerValue and this
+ * IntegerValue.
+ */
+ public IntegerValue divideOf(SpecificIntegerValue other)
+ {
+ return divideOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the remainder of this IntegerValue divided by the given
+ * SpecificIntegerValue.
+ */
+ public IntegerValue remainder(SpecificIntegerValue other)
+ {
+ return remainder((IntegerValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given SpecificIntegerValue divided by this
+ * IntegerValue.
+ */
+ public IntegerValue remainderOf(SpecificIntegerValue other)
+ {
+ return remainderOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns this IntegerValue, shifted left by the given SpecificIntegerValue.
+ */
+ public IntegerValue shiftLeft(SpecificIntegerValue other)
+ {
+ return shiftLeft((IntegerValue)other);
+ }
+
+ /**
+ * Returns this IntegerValue, shifted right by the given SpecificIntegerValue.
+ */
+ public IntegerValue shiftRight(SpecificIntegerValue other)
+ {
+ return shiftRight((IntegerValue)other);
+ }
+
+ /**
+ * Returns this unsigned IntegerValue, shifted right by the given
+ * SpecificIntegerValue.
+ */
+ public IntegerValue unsignedShiftRight(SpecificIntegerValue other)
+ {
+ return unsignedShiftRight((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given SpecificIntegerValue, shifted left by this IntegerValue.
+ */
+ public IntegerValue shiftLeftOf(SpecificIntegerValue other)
+ {
+ return shiftLeftOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given SpecificIntegerValue, shifted right by this IntegerValue.
+ */
+ public IntegerValue shiftRightOf(SpecificIntegerValue other)
+ {
+ return shiftRightOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given unsigned SpecificIntegerValue, shifted right by this
+ * IntegerValue.
+ */
+ public IntegerValue unsignedShiftRightOf(SpecificIntegerValue other)
+ {
+ return unsignedShiftRightOf((IntegerValue)other);
+ }
+
+ /**
+ * Returns the given SpecificLongValue, shifted left by this IntegerValue.
+ */
+ public LongValue shiftLeftOf(SpecificLongValue other)
+ {
+ return shiftLeftOf((LongValue)other);
+ }
+
+ /**
+ * Returns the given SpecificLongValue, shifted right by this IntegerValue.
+ */
+ public LongValue shiftRightOf(SpecificLongValue other)
+ {
+ return shiftRightOf((LongValue)other);
+ }
+
+ /**
+ * Returns the given unsigned SpecificLongValue, shifted right by this
+ * IntegerValue.
+ */
+ public LongValue unsignedShiftRightOf(SpecificLongValue other)
+ {
+ return unsignedShiftRightOf((LongValue)other);
+ }
+
+ /**
+ * Returns the logical and of this IntegerValue and the given
+ * SpecificIntegerValue.
+ */
+ public IntegerValue and(SpecificIntegerValue other)
+ {
+ return and((IntegerValue)other);
+ }
+
+ /**
+ * Returns the logical or of this IntegerValue and the given
+ * SpecificIntegerValue.
+ */
+ public IntegerValue or(SpecificIntegerValue other)
+ {
+ return or((IntegerValue)other);
+ }
+
+ /**
+ * Returns the logical xor of this IntegerValue and the given
+ * SpecificIntegerValue.
+ */
+ public IntegerValue xor(SpecificIntegerValue other)
+ {
+ return xor((IntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue and the given SpecificIntegerValue are
+ * equal: NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public int equal(SpecificIntegerValue other)
+ {
+ return equal((IntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is less than the given
+ * SpecificIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public int lessThan(SpecificIntegerValue other)
+ {
+ return lessThan((IntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is less than or equal to the given
+ * SpecificIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public int lessThanOrEqual(SpecificIntegerValue other)
+ {
+ return lessThanOrEqual((IntegerValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns whether this IntegerValue and the given SpecificIntegerValue are
+ * different: NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int notEqual(SpecificIntegerValue other)
+ {
+ return -equal(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than the given
+ * SpecificIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public final int greaterThan(SpecificIntegerValue other)
+ {
+ return -lessThanOrEqual(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than or equal to the given
+ * SpecificIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public final int greaterThanOrEqual(SpecificIntegerValue other)
+ {
+ return -lessThan(other);
+ }
+
+
+ // Similar binary methods, but this time with particular arguments.
+
+ /**
+ * Returns the generalization of this IntegerValue and the given other
+ * ParticularIntegerValue.
+ */
+ public IntegerValue generalize(ParticularIntegerValue other)
+ {
+ return generalize((SpecificIntegerValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this IntegerValue and the given ParticularIntegerValue.
+ */
+ public IntegerValue add(ParticularIntegerValue other)
+ {
+ return add((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the difference of this IntegerValue and the given ParticularIntegerValue.
+ */
+ public IntegerValue subtract(ParticularIntegerValue other)
+ {
+ return subtract((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the difference of the given ParticularIntegerValue and this IntegerValue.
+ */
+ public IntegerValue subtractFrom(ParticularIntegerValue other)
+ {
+ return subtractFrom((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the product of this IntegerValue and the given ParticularIntegerValue.
+ */
+ public IntegerValue multiply(ParticularIntegerValue other)
+ {
+ return multiply((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the quotient of this IntegerValue and the given
+ * ParticularIntegerValue.
+ */
+ public IntegerValue divide(ParticularIntegerValue other)
+ {
+ return divide((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given ParticularIntegerValue and this
+ * IntegerValue.
+ */
+ public IntegerValue divideOf(ParticularIntegerValue other)
+ {
+ return divideOf((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the remainder of this IntegerValue divided by the given
+ * ParticularIntegerValue.
+ */
+ public IntegerValue remainder(ParticularIntegerValue other)
+ {
+ return remainder((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given ParticularIntegerValue divided by this
+ * IntegerValue.
+ */
+ public IntegerValue remainderOf(ParticularIntegerValue other)
+ {
+ return remainderOf((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns this IntegerValue, shifted left by the given ParticularIntegerValue.
+ */
+ public IntegerValue shiftLeft(ParticularIntegerValue other)
+ {
+ return shiftLeft((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns this IntegerValue, shifted right by the given ParticularIntegerValue.
+ */
+ public IntegerValue shiftRight(ParticularIntegerValue other)
+ {
+ return shiftRight((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns this unsigned IntegerValue, shifted right by the given
+ * ParticularIntegerValue.
+ */
+ public IntegerValue unsignedShiftRight(ParticularIntegerValue other)
+ {
+ return unsignedShiftRight((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the given ParticularIntegerValue, shifted left by this IntegerValue.
+ */
+ public IntegerValue shiftLeftOf(ParticularIntegerValue other)
+ {
+ return shiftLeftOf((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the given ParticularIntegerValue, shifted right by this IntegerValue.
+ */
+ public IntegerValue shiftRightOf(ParticularIntegerValue other)
+ {
+ return shiftRightOf((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the given unsigned ParticularIntegerValue, shifted right by this
+ * IntegerValue.
+ */
+ public IntegerValue unsignedShiftRightOf(ParticularIntegerValue other)
+ {
+ return unsignedShiftRightOf((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the given ParticularLongValue, shifted left by this IntegerValue.
+ */
+ public LongValue shiftLeftOf(ParticularLongValue other)
+ {
+ return shiftLeftOf((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the given ParticularLongValue, shifted right by this IntegerValue.
+ */
+ public LongValue shiftRightOf(ParticularLongValue other)
+ {
+ return shiftRightOf((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the given unsigned ParticularLongValue, shifted right by this
+ * IntegerValue.
+ */
+ public LongValue unsignedShiftRightOf(ParticularLongValue other)
+ {
+ return unsignedShiftRightOf((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the logical and of this IntegerValue and the given
+ * ParticularIntegerValue.
+ */
+ public IntegerValue and(ParticularIntegerValue other)
+ {
+ return and((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the logical or of this IntegerValue and the given
+ * ParticularIntegerValue.
+ */
+ public IntegerValue or(ParticularIntegerValue other)
+ {
+ return or((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the logical xor of this IntegerValue and the given
+ * ParticularIntegerValue.
+ */
+ public IntegerValue xor(ParticularIntegerValue other)
+ {
+ return xor((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue and the given ParticularIntegerValue are
+ * equal: NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public int equal(ParticularIntegerValue other)
+ {
+ return equal((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is less than the given
+ * ParticularIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public int lessThan(ParticularIntegerValue other)
+ {
+ return lessThan((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is less than or equal to the given
+ * ParticularIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public int lessThanOrEqual(ParticularIntegerValue other)
+ {
+ return lessThanOrEqual((SpecificIntegerValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns whether this IntegerValue and the given ParticularIntegerValue are
+ * different: NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int notEqual(ParticularIntegerValue other)
+ {
+ return -equal(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than the given
+ * ParticularIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public final int greaterThan(ParticularIntegerValue other)
+ {
+ return -lessThanOrEqual(other);
+ }
+
+ /**
+ * Returns whether this IntegerValue is greater than or equal to the given
+ * ParticularIntegerValue: NEVER
, MAYBE
, or
+ * ALWAYS
.
+ */
+ public final int greaterThanOrEqual(ParticularIntegerValue other)
+ {
+ return -lessThan(other);
+ }
+
+
+ // Implementations for Value.
+
+ public final IntegerValue integerValue()
+ {
+ return this;
+ }
+
+ public final Value generalize(Value other)
+ {
+ return this.generalize(other.integerValue());
+ }
+
+ public final int computationalType()
+ {
+ return TYPE_INTEGER;
+ }
+
+ public final String internalType()
+ {
+ return String.valueOf(ClassConstants.INTERNAL_TYPE_INT);
+ }
+}
diff --git a/src/proguard/evaluation/value/LongValue.java b/src/proguard/evaluation/value/LongValue.java
new file mode 100644
index 000000000..e23c13c43
--- /dev/null
+++ b/src/proguard/evaluation/value/LongValue.java
@@ -0,0 +1,554 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.ClassConstants;
+
+/**
+ * This class represents a partially evaluated long value.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class LongValue extends Category2Value
+{
+ /**
+ * Returns the specific long value, if applicable.
+ */
+ public long value()
+ {
+ return 0;
+ }
+
+
+ // Basic unary methods.
+
+ /**
+ * Returns the negated value of this LongValue.
+ */
+ public abstract LongValue negate();
+
+
+ /**
+ * Converts this LongValue to an IntegerValue.
+ */
+ public abstract IntegerValue convertToInteger();
+
+ /**
+ * Converts this LongValue to a FloatValue.
+ */
+ public abstract FloatValue convertToFloat();
+
+ /**
+ * Converts this LongValue to a DoubleValue.
+ */
+ public abstract DoubleValue convertToDouble();
+
+
+ // Basic binary methods.
+
+ /**
+ * Returns the generalization of this LongValue and the given other
+ * LongValue.
+ */
+ public LongValue generalize(LongValue other)
+ {
+ return other.generalize(this);
+ }
+
+ /**
+ * Returns the sum of this LongValue and the given LongValue.
+ */
+ public LongValue add(LongValue other)
+ {
+ return other.add(this);
+ }
+
+ /**
+ * Returns the difference of this LongValue and the given LongValue.
+ */
+ public LongValue subtract(LongValue other)
+ {
+ return other.subtractFrom(this);
+ }
+
+ /**
+ * Returns the difference of the given LongValue and this LongValue.
+ */
+ public LongValue subtractFrom(LongValue other)
+ {
+ return other.subtract(this);
+ }
+
+ /**
+ * Returns the product of this LongValue and the given LongValue.
+ */
+ public LongValue multiply(LongValue other)
+ throws ArithmeticException
+ {
+ return other.multiply(this);
+ }
+
+ /**
+ * Returns the quotient of this LongValue and the given LongValue.
+ */
+ public LongValue divide(LongValue other)
+ throws ArithmeticException
+ {
+ return other.divideOf(this);
+ }
+
+ /**
+ * Returns the quotient of the given LongValue and this LongValue.
+ */
+ public LongValue divideOf(LongValue other)
+ throws ArithmeticException
+ {
+ return other.divide(this);
+ }
+
+ /**
+ * Returns the remainder of this LongValue divided by the given
+ * LongValue.
+ */
+ public LongValue remainder(LongValue other)
+ throws ArithmeticException
+ {
+ return other.remainderOf(this);
+ }
+
+ /**
+ * Returns the remainder of the given LongValue divided by this
+ * LongValue.
+ */
+ public LongValue remainderOf(LongValue other)
+ throws ArithmeticException
+ {
+ return other.remainder(this);
+ }
+
+ /**
+ * Returns this LongValue, shifted left by the given IntegerValue.
+ */
+ public LongValue shiftLeft(IntegerValue other)
+ {
+ return other.shiftLeftOf(this);
+ }
+
+ /**
+ * Returns this LongValue, shifted right by the given IntegerValue.
+ */
+ public LongValue shiftRight(IntegerValue other)
+ {
+ return other.shiftRightOf(this);
+ }
+
+ /**
+ * Returns this unsigned LongValue, shifted left by the given
+ * IntegerValue.
+ */
+ public LongValue unsignedShiftRight(IntegerValue other)
+ {
+ return other.unsignedShiftRightOf(this);
+ }
+
+ /**
+ * Returns the logical and of this LongValue and the given
+ * LongValue.
+ */
+ public LongValue and(LongValue other)
+ {
+ return other.and(this);
+ }
+
+ /**
+ * Returns the logical or of this LongValue and the given
+ * LongValue.
+ */
+ public LongValue or(LongValue other)
+ {
+ return other.or(this);
+ }
+
+ /**
+ * Returns the logical xor of this LongValue and the given
+ * LongValue.
+ */
+ public LongValue xor(LongValue other)
+ {
+ return other.xor(this);
+ }
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this LongValue is
+ * less than, equal to, or greater than the given LongValue, respectively.
+ */
+ public IntegerValue compare(LongValue other)
+ {
+ return other.compareReverse(this);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this LongValue is
+ * less than, equal to, or greater than the given LongValue, respectively.
+ */
+ public final IntegerValue compareReverse(LongValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Similar binary methods, but this time with more specific arguments.
+
+ /**
+ * Returns the generalization of this LongValue and the given other
+ * SpecificLongValue.
+ */
+ public LongValue generalize(SpecificLongValue other)
+ {
+ return this;
+ }
+
+
+ /**
+ * Returns the sum of this LongValue and the given SpecificLongValue.
+ */
+ public LongValue add(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the difference of this LongValue and the given SpecificLongValue.
+ */
+ public LongValue subtract(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the difference of the given SpecificLongValue and this LongValue.
+ */
+ public LongValue subtractFrom(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the product of this LongValue and the given SpecificLongValue.
+ */
+ public LongValue multiply(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the quotient of this LongValue and the given
+ * SpecificLongValue.
+ */
+ public LongValue divide(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the quotient of the given SpecificLongValue and this
+ * LongValue.
+ */
+ public LongValue divideOf(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the remainder of this LongValue divided by the given
+ * SpecificLongValue.
+ */
+ public LongValue remainder(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the remainder of the given SpecificLongValue divided by this
+ * LongValue.
+ */
+ public LongValue remainderOf(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns this LongValue, shifted left by the given SpecificLongValue.
+ */
+ public LongValue shiftLeft(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns this LongValue, shifted right by the given SpecificLongValue.
+ */
+ public LongValue shiftRight(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns this unsigned LongValue, shifted right by the given
+ * SpecificLongValue.
+ */
+ public LongValue unsignedShiftRight(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the logical and of this LongValue and the given
+ * SpecificLongValue.
+ */
+ public LongValue and(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the logical or of this LongValue and the given
+ * SpecificLongValue.
+ */
+ public LongValue or(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns the logical xor of this LongValue and the given
+ * SpecificLongValue.
+ */
+ public LongValue xor(SpecificLongValue other)
+ {
+ return this;
+ }
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this LongValue is
+ * less than, equal to, or greater than the given SpecificLongValue,
+ * respectively.
+ */
+ public IntegerValue compare(SpecificLongValue other)
+ {
+ return new ComparisonValue(this, other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this LongValue is
+ * less than, equal to, or greater than the given SpecificLongValue,
+ * respectively.
+ */
+ public final IntegerValue compareReverse(SpecificLongValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Similar binary methods, but this time with particular arguments.
+
+ /**
+ * Returns the generalization of this LongValue and the given other
+ * ParticularLongValue.
+ */
+ public LongValue generalize(ParticularLongValue other)
+ {
+ return generalize((SpecificLongValue)other);
+ }
+
+
+ /**
+ * Returns the sum of this LongValue and the given ParticularLongValue.
+ */
+ public LongValue add(ParticularLongValue other)
+ {
+ return add((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the difference of this LongValue and the given ParticularLongValue.
+ */
+ public LongValue subtract(ParticularLongValue other)
+ {
+ return subtract((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the difference of the given ParticularLongValue and this LongValue.
+ */
+ public LongValue subtractFrom(ParticularLongValue other)
+ {
+ return subtractFrom((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the product of this LongValue and the given ParticularLongValue.
+ */
+ public LongValue multiply(ParticularLongValue other)
+ {
+ return multiply((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the quotient of this LongValue and the given
+ * ParticularLongValue.
+ */
+ public LongValue divide(ParticularLongValue other)
+ {
+ return divide((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the quotient of the given ParticularLongValue and this
+ * LongValue.
+ */
+ public LongValue divideOf(ParticularLongValue other)
+ {
+ return divideOf((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the remainder of this LongValue divided by the given
+ * ParticularLongValue.
+ */
+ public LongValue remainder(ParticularLongValue other)
+ {
+ return remainder((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the remainder of the given ParticularLongValue divided by this
+ * LongValue.
+ */
+ public LongValue remainderOf(ParticularLongValue other)
+ {
+ return remainderOf((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns this LongValue, shifted left by the given ParticularIntegerValue.
+ */
+ public LongValue shiftLeft(ParticularIntegerValue other)
+ {
+ return shiftLeft((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns this LongValue, shifted right by the given ParticularIntegerValue.
+ */
+ public LongValue shiftRight(ParticularIntegerValue other)
+ {
+ return shiftRight((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns this unsigned LongValue, shifted right by the given
+ * ParticularIntegerValue.
+ */
+ public LongValue unsignedShiftRight(ParticularIntegerValue other)
+ {
+ return unsignedShiftRight((SpecificIntegerValue)other);
+ }
+
+ /**
+ * Returns the logical and of this LongValue and the given
+ * ParticularLongValue.
+ */
+ public LongValue and(ParticularLongValue other)
+ {
+ return and((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the logical or of this LongValue and the given
+ * ParticularLongValue.
+ */
+ public LongValue or(ParticularLongValue other)
+ {
+ return or((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns the logical xor of this LongValue and the given
+ * ParticularLongValue.
+ */
+ public LongValue xor(ParticularLongValue other)
+ {
+ return xor((SpecificLongValue)other);
+ }
+
+ /**
+ * Returns an IntegerValue with value -1, 0, or 1, if this LongValue is
+ * less than, equal to, or greater than the given ParticularLongValue,
+ * respectively.
+ */
+ public IntegerValue compare(ParticularLongValue other)
+ {
+ return compare((SpecificLongValue)other);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns an IntegerValue with value 1, 0, or -1, if this LongValue is
+ * less than, equal to, or greater than the given ParticularLongValue,
+ * respectively.
+ */
+ public final IntegerValue compareReverse(ParticularLongValue other)
+ {
+ return compare(other).negate();
+ }
+
+
+ // Implementations for Value.
+
+ public final LongValue longValue()
+ {
+ return this;
+ }
+
+ public final Value generalize(Value other)
+ {
+ return this.generalize(other.longValue());
+ }
+
+ public final int computationalType()
+ {
+ return TYPE_LONG;
+ }
+
+ public final String internalType()
+ {
+ return String.valueOf(ClassConstants.INTERNAL_TYPE_INT);
+ }
+}
diff --git a/src/proguard/evaluation/value/NegatedDoubleValue.java b/src/proguard/evaluation/value/NegatedDoubleValue.java
new file mode 100644
index 000000000..7619be776
--- /dev/null
+++ b/src/proguard/evaluation/value/NegatedDoubleValue.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This DoubleValue represents a double value that is negated.
+ *
+ * @author Eric Lafortune
+ */
+final class NegatedDoubleValue extends SpecificDoubleValue
+{
+ private final DoubleValue doubleValue;
+
+
+ /**
+ * Creates a new negated double value of the given double value.
+ */
+ public NegatedDoubleValue(DoubleValue doubleValue)
+ {
+ this.doubleValue = doubleValue;
+ }
+
+
+ // Implementations of unary methods of DoubleValue.
+
+ public DoubleValue negate()
+ {
+ return doubleValue;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.doubleValue.equals(((NegatedDoubleValue)object).doubleValue);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ doubleValue.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "-"+doubleValue;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/NegatedFloatValue.java b/src/proguard/evaluation/value/NegatedFloatValue.java
new file mode 100644
index 000000000..51b50747d
--- /dev/null
+++ b/src/proguard/evaluation/value/NegatedFloatValue.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This FloatValue represents a float value that is negated.
+ *
+ * @author Eric Lafortune
+ */
+final class NegatedFloatValue extends SpecificFloatValue
+{
+ private final FloatValue floatValue;
+
+
+ /**
+ * Creates a new negated float value of the given float value.
+ */
+ public NegatedFloatValue(FloatValue floatValue)
+ {
+ this.floatValue = floatValue;
+ }
+
+
+ // Implementations of unary methods of FloatValue.
+
+ public FloatValue negate()
+ {
+ return floatValue;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.floatValue.equals(((NegatedFloatValue)object).floatValue);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ floatValue.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "-"+floatValue;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/NegatedIntegerValue.java b/src/proguard/evaluation/value/NegatedIntegerValue.java
new file mode 100644
index 000000000..17290836e
--- /dev/null
+++ b/src/proguard/evaluation/value/NegatedIntegerValue.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a integer value that is negated.
+ *
+ * @author Eric Lafortune
+ */
+final class NegatedIntegerValue extends SpecificIntegerValue
+{
+ private final IntegerValue integerValue;
+
+
+ /**
+ * Creates a new negated integer value of the given integer value.
+ */
+ public NegatedIntegerValue(IntegerValue integerValue)
+ {
+ this.integerValue = integerValue;
+ }
+
+
+ // Implementations of unary methods of IntegerValue.
+
+ public IntegerValue negate()
+ {
+ return integerValue;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.integerValue.equals(((NegatedIntegerValue)object).integerValue);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ integerValue.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "-"+integerValue;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/NegatedLongValue.java b/src/proguard/evaluation/value/NegatedLongValue.java
new file mode 100644
index 000000000..75105243f
--- /dev/null
+++ b/src/proguard/evaluation/value/NegatedLongValue.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This LongValue represents a long value that is negated.
+ *
+ * @author Eric Lafortune
+ */
+final class NegatedLongValue extends SpecificLongValue
+{
+ private final LongValue longValue;
+
+
+ /**
+ * Creates a new negated long value of the given long value.
+ */
+ public NegatedLongValue(LongValue longValue)
+ {
+ this.longValue = longValue;
+ }
+
+
+ // Implementations of unary methods of LongValue.
+
+ public LongValue negate()
+ {
+ return longValue;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return this == object ||
+ super.equals(object) &&
+ this.longValue.equals(((NegatedLongValue)object).longValue);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ longValue.hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "-"+longValue;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ParticularDoubleValue.java b/src/proguard/evaluation/value/ParticularDoubleValue.java
new file mode 100644
index 000000000..e8c5aa708
--- /dev/null
+++ b/src/proguard/evaluation/value/ParticularDoubleValue.java
@@ -0,0 +1,221 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This DoubleValue represents a particular double value.
+ *
+ * @author Eric Lafortune
+ */
+final class ParticularDoubleValue extends SpecificDoubleValue
+{
+ private final double value;
+
+
+ /**
+ * Creates a new particular double value.
+ */
+ public ParticularDoubleValue(double value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for DoubleValue.
+
+ public double value()
+ {
+ return value;
+ }
+
+
+ // Implementations of unary methods of DoubleValue.
+
+ public DoubleValue negate()
+ {
+ return new ParticularDoubleValue(-value);
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return new ParticularIntegerValue((int)value);
+ }
+
+ public LongValue convertToLong()
+ {
+ return new ParticularLongValue((long)value);
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return new ParticularFloatValue((float)value);
+ }
+
+
+ // Implementations of binary methods of DoubleValue.
+
+ public DoubleValue generalize(DoubleValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public DoubleValue add(DoubleValue other)
+ {
+ // Careful: -0.0 + 0.0 == 0.0
+ //return value == 0.0 ? other : other.add(this);
+ return other.add(this);
+ }
+
+ public DoubleValue subtract(DoubleValue other)
+ {
+ // Careful: -0.0 + 0.0 == 0.0
+ //return value == 0.0 ? other.negate() : other.subtractFrom(this);
+ return other.subtractFrom(this);
+ }
+
+ public DoubleValue subtractFrom(DoubleValue other)
+ {
+ // Careful: -0.0 + 0.0 == 0.0
+ //return value == 0.0 ? other : other.subtract(this);
+ return other.subtract(this);
+ }
+
+ public DoubleValue multiply(DoubleValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public DoubleValue divide(DoubleValue other)
+ {
+ return other.divideOf(this);
+ }
+
+ public DoubleValue divideOf(DoubleValue other)
+ {
+ return other.divide(this);
+ }
+
+ public DoubleValue remainder(DoubleValue other)
+ {
+ return other.remainderOf(this);
+ }
+
+ public DoubleValue remainderOf(DoubleValue other)
+ {
+ return other.remainder(this);
+ }
+
+ public IntegerValue compare(DoubleValue other)
+ {
+ return other.compareReverse(this);
+ }
+
+
+ // Implementations of binary DoubleValue methods with ParticularDoubleValue
+ // arguments.
+
+ public DoubleValue generalize(ParticularDoubleValue other)
+ {
+ // Also handle NaN and Infinity.
+ return Double.doubleToRawLongBits(this.value) ==
+ Double.doubleToRawLongBits(other.value) ?
+ this : ValueFactory.DOUBLE_VALUE;
+ }
+
+ public DoubleValue add(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(this.value + other.value);
+ }
+
+ public DoubleValue subtract(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(this.value - other.value);
+ }
+
+ public DoubleValue subtractFrom(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(other.value - this.value);
+ }
+
+ public DoubleValue multiply(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(this.value * other.value);
+ }
+
+ public DoubleValue divide(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(this.value / other.value);
+ }
+
+ public DoubleValue divideOf(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(other.value / this.value);
+ }
+
+ public DoubleValue remainder(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(this.value % other.value);
+ }
+
+ public DoubleValue remainderOf(ParticularDoubleValue other)
+ {
+ return new ParticularDoubleValue(other.value % this.value);
+ }
+
+ public IntegerValue compare(ParticularDoubleValue other)
+ {
+ return this.value < other.value ? SpecificValueFactory.INTEGER_VALUE_M1 :
+ this.value == other.value ? SpecificValueFactory.INTEGER_VALUE_0 :
+ SpecificValueFactory.INTEGER_VALUE_1;
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isParticular()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ // Also handle NaN and Infinity.
+ return super.equals(object) &&
+ Double.doubleToLongBits(this.value) ==
+ Double.doubleToLongBits(((ParticularDoubleValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ (int)Double.doubleToLongBits(value);
+ }
+
+
+ public String toString()
+ {
+ return value+"d";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ParticularFloatValue.java b/src/proguard/evaluation/value/ParticularFloatValue.java
new file mode 100644
index 000000000..cbdde310c
--- /dev/null
+++ b/src/proguard/evaluation/value/ParticularFloatValue.java
@@ -0,0 +1,221 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This FloatValue represents a particular float value.
+ *
+ * @author Eric Lafortune
+ */
+final class ParticularFloatValue extends SpecificFloatValue
+{
+ private final float value;
+
+
+ /**
+ * Creates a new particular float value.
+ */
+ public ParticularFloatValue(float value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for FloatValue.
+
+ public float value()
+ {
+ return value;
+ }
+
+
+ // Implementations of unary methods of FloatValue.
+
+ public FloatValue negate()
+ {
+ return new ParticularFloatValue(-value);
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return new ParticularIntegerValue((int)value);
+ }
+
+ public LongValue convertToLong()
+ {
+ return new ParticularLongValue((long)value);
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return new ParticularDoubleValue((float)value);
+ }
+
+
+ // Implementations of binary methods of FloatValue.
+
+ public FloatValue generalize(FloatValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public FloatValue add(FloatValue other)
+ {
+ // Careful: -0.0 + 0.0 == 0.0
+ //return value == 0.0 ? other : other.add(this);
+ return other.add(this);
+ }
+
+ public FloatValue subtract(FloatValue other)
+ {
+ // Careful: -0.0 + 0.0 == 0.0
+ //return value == 0.0 ? other.negate() : other.subtractFrom(this);
+ return other.subtractFrom(this);
+ }
+
+ public FloatValue subtractFrom(FloatValue other)
+ {
+ // Careful: -0.0 + 0.0 == 0.0
+ //return value == 0.0 ? other : other.subtract(this);
+ return other.subtract(this);
+ }
+
+ public FloatValue multiply(FloatValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public FloatValue divide(FloatValue other)
+ {
+ return other.divideOf(this);
+ }
+
+ public FloatValue divideOf(FloatValue other)
+ {
+ return other.divide(this);
+ }
+
+ public FloatValue remainder(FloatValue other)
+ {
+ return other.remainderOf(this);
+ }
+
+ public FloatValue remainderOf(FloatValue other)
+ {
+ return other.remainder(this);
+ }
+
+ public IntegerValue compare(FloatValue other)
+ {
+ return other.compareReverse(this);
+ }
+
+
+ // Implementations of binary FloatValue methods with ParticularFloatValue
+ // arguments.
+
+ public FloatValue generalize(ParticularFloatValue other)
+ {
+ // Also handle NaN and Infinity.
+ return Float.floatToRawIntBits(this.value) ==
+ Float.floatToRawIntBits(other.value) ?
+ this : ValueFactory.FLOAT_VALUE;
+ }
+
+ public FloatValue add(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(this.value + other.value);
+ }
+
+ public FloatValue subtract(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(this.value - other.value);
+ }
+
+ public FloatValue subtractFrom(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(other.value - this.value);
+ }
+
+ public FloatValue multiply(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(this.value * other.value);
+ }
+
+ public FloatValue divide(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(this.value / other.value);
+ }
+
+ public FloatValue divideOf(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(other.value / this.value);
+ }
+
+ public FloatValue remainder(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(this.value % other.value);
+ }
+
+ public FloatValue remainderOf(ParticularFloatValue other)
+ {
+ return new ParticularFloatValue(other.value % this.value);
+ }
+
+ public IntegerValue compare(ParticularFloatValue other)
+ {
+ return this.value < other.value ? SpecificValueFactory.INTEGER_VALUE_M1 :
+ this.value == other.value ? SpecificValueFactory.INTEGER_VALUE_0 :
+ SpecificValueFactory.INTEGER_VALUE_1;
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isParticular()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ // Also handle NaN and Infinity.
+ return super.equals(object) &&
+ Float.floatToIntBits(this.value) ==
+ Float.floatToIntBits(((ParticularFloatValue)object).value);
+ }
+
+
+ public int hashCode()
+ {
+ return super.hashCode() ^
+ Float.floatToIntBits(value);
+ }
+
+
+ public String toString()
+ {
+ return value+"f";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ParticularIntegerValue.java b/src/proguard/evaluation/value/ParticularIntegerValue.java
new file mode 100644
index 000000000..609e95fbb
--- /dev/null
+++ b/src/proguard/evaluation/value/ParticularIntegerValue.java
@@ -0,0 +1,383 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a particular integer value.
+ *
+ * @author Eric Lafortune
+ */
+final class ParticularIntegerValue extends SpecificIntegerValue
+{
+ private final int value;
+
+
+ /**
+ * Creates a new particular integer value.
+ */
+ public ParticularIntegerValue(int value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for IntegerValue.
+
+ public int value()
+ {
+ return value;
+ }
+
+
+ // Implementations of unary methods of IntegerValue.
+
+ public IntegerValue negate()
+ {
+ return new ParticularIntegerValue(-value);
+ }
+
+ public IntegerValue convertToByte()
+ {
+ int byteValue = (byte)value;
+
+ return byteValue == value ?
+ this :
+ new ParticularIntegerValue(byteValue);
+ }
+
+ public IntegerValue convertToCharacter()
+ {
+ int charValue = (char)value;
+
+ return charValue == value ?
+ this :
+ new ParticularIntegerValue(charValue);
+ }
+
+ public IntegerValue convertToShort()
+ {
+ int shortValue = (short)value;
+
+ return shortValue == value ?
+ this :
+ new ParticularIntegerValue(shortValue);
+ }
+
+ public LongValue convertToLong()
+ {
+ return new ParticularLongValue((long)value);
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return new ParticularFloatValue((float)value);
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return new ParticularDoubleValue((double)value);
+ }
+
+
+ // Implementations of binary methods of IntegerValue.
+
+ public IntegerValue generalize(IntegerValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public IntegerValue add(IntegerValue other)
+ {
+ return other.add(this);
+ }
+
+ public IntegerValue subtract(IntegerValue other)
+ {
+ return other.subtractFrom(this);
+ }
+
+ public IntegerValue subtractFrom(IntegerValue other)
+ {
+ return other.subtract(this);
+ }
+
+ public IntegerValue multiply(IntegerValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public IntegerValue divide(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.divideOf(this);
+ }
+
+ public IntegerValue divideOf(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.divide(this);
+ }
+
+ public IntegerValue remainder(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.remainderOf(this);
+ }
+
+ public IntegerValue remainderOf(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.remainder(this);
+ }
+
+ public IntegerValue shiftLeft(IntegerValue other)
+ {
+ return other.shiftLeftOf(this);
+ }
+
+ public IntegerValue shiftLeftOf(IntegerValue other)
+ {
+ return other.shiftLeft(this);
+ }
+
+ public IntegerValue shiftRight(IntegerValue other)
+ {
+ return other.shiftRightOf(this);
+ }
+
+ public IntegerValue shiftRightOf(IntegerValue other)
+ {
+ return other.shiftRight(this);
+ }
+
+ public IntegerValue unsignedShiftRight(IntegerValue other)
+ {
+ return other.unsignedShiftRightOf(this);
+ }
+
+ public IntegerValue unsignedShiftRightOf(IntegerValue other)
+ {
+ return other.unsignedShiftRight(this);
+ }
+
+ public LongValue shiftLeftOf(LongValue other)
+ {
+ return other.shiftLeft(this);
+ }
+
+ public LongValue shiftRightOf(LongValue other)
+ {
+ return other.shiftRight(this);
+ }
+
+ public LongValue unsignedShiftRightOf(LongValue other)
+ {
+ return other.unsignedShiftRight(this);
+ }
+
+ public IntegerValue and(IntegerValue other)
+ {
+ return other.and(this);
+ }
+
+ public IntegerValue or(IntegerValue other)
+ {
+ return other.or(this);
+ }
+
+ public IntegerValue xor(IntegerValue other)
+ {
+ return other.xor(this);
+ }
+
+ public int equal(IntegerValue other)
+ {
+ return other.equal(this);
+ }
+
+ public int lessThan(IntegerValue other)
+ {
+ return other.greaterThan(this);
+ }
+
+ public int lessThanOrEqual(IntegerValue other)
+ {
+ return other.greaterThanOrEqual(this);
+ }
+
+
+ // Implementations of binary IntegerValue methods with ParticularIntegerValue
+ // arguments.
+
+ public IntegerValue generalize(ParticularIntegerValue other)
+ {
+ return generalize((SpecificIntegerValue)other);
+ }
+
+ public IntegerValue add(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value + other.value);
+ }
+
+ public IntegerValue subtract(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value - other.value);
+ }
+
+ public IntegerValue subtractFrom(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(other.value - this.value);
+ }
+
+ public IntegerValue multiply(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value * other.value);
+ }
+
+ public IntegerValue divide(ParticularIntegerValue other)
+ throws ArithmeticException
+ {
+ return new ParticularIntegerValue(this.value / other.value);
+ }
+
+ public IntegerValue divideOf(ParticularIntegerValue other)
+ throws ArithmeticException
+ {
+ return new ParticularIntegerValue(other.value / this.value);
+ }
+
+ public IntegerValue remainder(ParticularIntegerValue other)
+ throws ArithmeticException
+ {
+ return new ParticularIntegerValue(this.value % other.value);
+ }
+
+ public IntegerValue remainderOf(ParticularIntegerValue other)
+ throws ArithmeticException
+ {
+ return new ParticularIntegerValue(other.value % this.value);
+ }
+
+ public IntegerValue shiftLeft(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value << other.value);
+ }
+
+ public IntegerValue shiftRight(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value >> other.value);
+ }
+
+ public IntegerValue unsignedShiftRight(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value >>> other.value);
+ }
+
+ public IntegerValue shiftLeftOf(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(other.value << this.value);
+ }
+
+ public IntegerValue shiftRightOf(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(other.value >> this.value);
+ }
+
+ public IntegerValue unsignedShiftRightOf(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(other.value >>> this.value);
+ }
+
+ public LongValue shiftLeftOf(ParticularLongValue other)
+ {
+ return new ParticularLongValue(other.value() << this.value);
+ }
+
+ public LongValue shiftRightOf(ParticularLongValue other)
+ {
+ return new ParticularLongValue(other.value() >> this.value);
+ }
+
+ public LongValue unsignedShiftRightOf(ParticularLongValue other)
+ {
+ return new ParticularLongValue(other.value() >>> this.value);
+ }
+
+ public IntegerValue and(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value & other.value);
+ }
+
+ public IntegerValue or(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value | other.value);
+ }
+
+ public IntegerValue xor(ParticularIntegerValue other)
+ {
+ return new ParticularIntegerValue(this.value ^ other.value);
+ }
+
+ public int equal(ParticularIntegerValue other)
+ {
+ return this.value == other.value ? ALWAYS : NEVER;
+ }
+
+ public int lessThan(ParticularIntegerValue other)
+ {
+ return this.value < other.value ? ALWAYS : NEVER;
+ }
+
+ public int lessThanOrEqual(ParticularIntegerValue other)
+ {
+ return this.value <= other.value ? ALWAYS : NEVER;
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isParticular()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return super.equals(object) &&
+ this.value == ((ParticularIntegerValue)object).value;
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode() ^
+ value;
+ }
+
+
+ public String toString()
+ {
+ return Integer.toString(value);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ParticularLongValue.java b/src/proguard/evaluation/value/ParticularLongValue.java
new file mode 100644
index 000000000..190323516
--- /dev/null
+++ b/src/proguard/evaluation/value/ParticularLongValue.java
@@ -0,0 +1,271 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This LongValue represents a particular long value.
+ *
+ * @author Eric Lafortune
+ */
+final class ParticularLongValue extends SpecificLongValue
+{
+ private final long value;
+
+
+ /**
+ * Creates a new particular long value.
+ */
+ public ParticularLongValue(long value)
+ {
+ this.value = value;
+ }
+
+
+ // Implementations for LongValue.
+
+ public long value()
+ {
+ return value;
+ }
+
+
+ // Implementations of unary methods of LongValue.
+
+ public LongValue negate()
+ {
+ return new ParticularLongValue(-value);
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return new ParticularIntegerValue((int)value);
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return new ParticularFloatValue((float)value);
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return new ParticularDoubleValue((double)value);
+ }
+
+
+ // Implementations of binary methods of LongValue.
+
+ public LongValue generalize(LongValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public LongValue add(LongValue other)
+ {
+ return other.add(this);
+ }
+
+ public LongValue subtract(LongValue other)
+ {
+ return other.subtractFrom(this);
+ }
+
+ public LongValue subtractFrom(LongValue other)
+ {
+ return other.subtract(this);
+ }
+
+ public LongValue multiply(LongValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public LongValue divide(LongValue other)
+ throws ArithmeticException
+ {
+ return other.divideOf(this);
+ }
+
+ public LongValue divideOf(LongValue other)
+ throws ArithmeticException
+ {
+ return other.divide(this);
+ }
+
+ public LongValue remainder(LongValue other)
+ throws ArithmeticException
+ {
+ return other.remainderOf(this);
+ }
+
+ public LongValue remainderOf(LongValue other)
+ throws ArithmeticException
+ {
+ return other.remainder(this);
+ }
+
+ public LongValue shiftLeft(IntegerValue other)
+ {
+ return other.shiftLeftOf(this);
+ }
+
+ public LongValue shiftRight(IntegerValue other)
+ {
+ return other.shiftRightOf(this);
+ }
+
+ public LongValue unsignedShiftRight(IntegerValue other)
+ {
+ return other.unsignedShiftRightOf(this);
+ }
+
+ public LongValue and(LongValue other)
+ {
+ return other.and(this);
+ }
+
+ public LongValue or(LongValue other)
+ {
+ return other.or(this);
+ }
+
+ public LongValue xor(LongValue other)
+ {
+ return other.xor(this);
+ }
+
+ public IntegerValue compare(LongValue other)
+ {
+ return other.compareReverse(this);
+ }
+
+
+ // Implementations of binary LongValue methods with ParticularLongValue
+ // arguments.
+
+ public LongValue generalize(ParticularLongValue other)
+ {
+ return generalize((SpecificLongValue)other);
+ }
+
+ public LongValue add(ParticularLongValue other)
+ {
+ return new ParticularLongValue(this.value + other.value);
+ }
+
+ public LongValue subtract(ParticularLongValue other)
+ {
+ return new ParticularLongValue(this.value - other.value);
+ }
+
+ public LongValue subtractFrom(ParticularLongValue other)
+ {
+ return new ParticularLongValue(other.value - this.value);
+ }
+
+ public LongValue multiply(ParticularLongValue other)
+ {
+ return new ParticularLongValue(this.value * other.value);
+ }
+
+ public LongValue divide(ParticularLongValue other)
+ throws ArithmeticException
+ {
+ return new ParticularLongValue(this.value / other.value);
+ }
+
+ public LongValue divideOf(ParticularLongValue other)
+ throws ArithmeticException
+ {
+ return new ParticularLongValue(other.value / this.value);
+ }
+
+ public LongValue remainder(ParticularLongValue other)
+ throws ArithmeticException
+ {
+ return new ParticularLongValue(this.value % other.value);
+ }
+
+ public LongValue remainderOf(ParticularLongValue other)
+ throws ArithmeticException
+ {
+ return new ParticularLongValue(other.value % this.value);
+ }
+
+ public LongValue shiftLeft(ParticularIntegerValue other)
+ {
+ return new ParticularLongValue(this.value << other.value());
+ }
+
+ public LongValue shiftRight(ParticularIntegerValue other)
+ {
+ return new ParticularLongValue(this.value >> other.value());
+ }
+
+ public LongValue unsignedShiftRight(ParticularIntegerValue other)
+ {
+ return new ParticularLongValue(this.value >>> other.value());
+ }
+
+ public LongValue and(ParticularLongValue other)
+ {
+ return new ParticularLongValue(this.value & other.value);
+ }
+
+ public LongValue or(ParticularLongValue other)
+ {
+ return new ParticularLongValue(this.value | other.value);
+ }
+
+ public LongValue xor(ParticularLongValue other)
+ {
+ return new ParticularLongValue(this.value ^ other.value);
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isParticular()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return super.equals(object) &&
+ this.value == ((ParticularLongValue)object).value;
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode() ^
+ (int)value;
+ }
+
+
+ public String toString()
+ {
+ return value+"L";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/ReferenceValue.java b/src/proguard/evaluation/value/ReferenceValue.java
new file mode 100644
index 000000000..4a52e82ad
--- /dev/null
+++ b/src/proguard/evaluation/value/ReferenceValue.java
@@ -0,0 +1,540 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.*;
+import proguard.classfile.util.ClassUtil;
+import proguard.classfile.visitor.ClassCollector;
+
+import java.util.*;
+
+/**
+ * This class represents a partially evaluated reference value. It has a type
+ * and a flag that indicates whether the value could be null
. If
+ * the type is null
, the value is null
.
+ *
+ * @author Eric Lafortune
+ */
+public class ReferenceValue extends Category1Value
+{
+ private static final boolean DEBUG = false;
+
+
+ protected final String type;
+ protected final Clazz referencedClass;
+ protected final boolean mayBeNull;
+
+
+ /**
+ * Creates a new ReferenceValue.
+ */
+ public ReferenceValue(String type,
+ Clazz referencedClass,
+ boolean mayBeNull)
+ {
+ this.type = type;
+ this.referencedClass = referencedClass;
+ this.mayBeNull = mayBeNull;
+ }
+
+
+ /**
+ * Returns the type.
+ */
+ public String getType()
+ {
+ return type;
+ }
+
+
+ /**
+ * Returns the class that is referenced by the type.
+ */
+ public Clazz getReferencedClass()
+ {
+ return referencedClass;
+ }
+
+
+ // Basic unary methods.
+
+ /**
+ * Returns whether the type is null
.
+ */
+ public int isNull()
+ {
+ return type == null ? ALWAYS :
+ mayBeNull ? MAYBE :
+ NEVER;
+ }
+
+
+ /**
+ * Returns whether the type is an instance of the given type.
+ */
+ public int instanceOf(String otherType, Clazz otherReferencedClass)
+ {
+ String thisType = this.type;
+
+ // If this type is null, it is never an instance of any class.
+ if (thisType == null)
+ {
+ return NEVER;
+ }
+
+ // Start taking into account the type dimensions.
+ int thisDimensionCount = ClassUtil.internalArrayTypeDimensionCount(thisType);
+ int otherDimensionCount = ClassUtil.internalArrayTypeDimensionCount(otherType);
+ int commonDimensionCount = Math.min(thisDimensionCount, otherDimensionCount);
+
+ // Strip any common array prefixes.
+ thisType = thisType.substring(commonDimensionCount);
+ otherType = otherType.substring(commonDimensionCount);
+
+ // If either stripped type is a primitive type, we can tell right away.
+ if (commonDimensionCount > 0 &&
+ (ClassUtil.isInternalPrimitiveType(thisType.charAt(0)) ||
+ ClassUtil.isInternalPrimitiveType(otherType.charAt(0))))
+ {
+ return !thisType.equals(otherType) ? NEVER :
+ mayBeNull ? MAYBE :
+ ALWAYS;
+ }
+
+ // Strip the class type prefix and suffix of this type, if any.
+ if (thisDimensionCount == commonDimensionCount)
+ {
+ thisType = ClassUtil.internalClassNameFromClassType(thisType);
+ }
+
+ // Strip the class type prefix and suffix of the other type, if any.
+ if (otherDimensionCount == commonDimensionCount)
+ {
+ otherType = ClassUtil.internalClassNameFromClassType(otherType);
+ }
+
+ // If this type is an array type, and the other type is not
+ // java.lang.Object, java.lang.Cloneable, or java.io.Serializable,
+ // this type can never be an instance.
+ if (thisDimensionCount > otherDimensionCount &&
+ !ClassUtil.isInternalArrayInterfaceName(otherType))
+ {
+ return NEVER;
+ }
+
+ // If the other type is an array type, and this type is not
+ // java.lang.Object, java.lang.Cloneable, or java.io.Serializable,
+ // this type can never be an instance.
+ if (thisDimensionCount < otherDimensionCount &&
+ !ClassUtil.isInternalArrayInterfaceName(thisType))
+ {
+ return NEVER;
+ }
+
+ // If this type may be null, it might not be an instance of any class.
+ if (mayBeNull)
+ {
+ return MAYBE;
+ }
+
+ // If this type is equal to the other type, or if the other type is
+ // java.lang.Object, this type is always an instance.
+ if (thisType.equals(otherType) ||
+ ClassConstants.INTERNAL_NAME_JAVA_LANG_OBJECT.equals(otherType))
+ {
+ return ALWAYS;
+ }
+
+ // If this type is an array type, it's ok.
+ if (thisDimensionCount > otherDimensionCount)
+ {
+ return ALWAYS;
+ }
+
+ // If the other type is an array type, it might be ok.
+ if (thisDimensionCount < otherDimensionCount)
+ {
+ return MAYBE;
+ }
+
+ // If the value extends the type, we're sure.
+ return referencedClass != null &&
+ otherReferencedClass != null &&
+ referencedClass.extendsOrImplements(otherReferencedClass) ?
+ ALWAYS :
+ MAYBE;
+ }
+
+
+ /**
+ * Returns the length of the array, assuming this type is an array.
+ */
+ public IntegerValue arrayLength(ValueFactory valueFactory)
+ {
+ return valueFactory.createIntegerValue();
+ }
+
+
+ /**
+ * Returns the value of the array at the given index, assuming this type
+ * is an array.
+ */
+ public Value arrayLoad(IntegerValue integerValue, ValueFactory valueFactory)
+ {
+ return
+ type == null ? ValueFactory.REFERENCE_VALUE_NULL :
+ !ClassUtil.isInternalArrayType(type) ? ValueFactory.REFERENCE_VALUE_JAVA_LANG_OBJECT_MAYBE_NULL :
+ valueFactory.createValue(type.substring(1),
+ referencedClass,
+ true);
+ }
+
+
+ // Basic binary methods.
+
+ /**
+ * Returns the generalization of this ReferenceValue and the given other
+ * ReferenceValue.
+ */
+ public ReferenceValue generalize(ReferenceValue other)
+ {
+ // If both types are identical, the generalization is the same too.
+ if (this.equals(other))
+ {
+ return this;
+ }
+
+ String thisType = this.type;
+ String otherType = other.type;
+
+ // If both types are nul, the generalization is null too.
+ if (thisType == null && otherType == null)
+ {
+ return ValueFactory.REFERENCE_VALUE_NULL;
+ }
+
+ // If this type is null, the generalization is the other type, maybe null.
+ if (thisType == null)
+ {
+ return other.generalizeMayBeNull(true);
+ }
+
+ // If the other type is null, the generalization is this type, maybe null.
+ if (otherType == null)
+ {
+ return this.generalizeMayBeNull(true);
+ }
+
+ boolean mayBeNull = this.mayBeNull || other.mayBeNull;
+
+ // If the two types are equal, the generalization remains the same, maybe null.
+ if (thisType.equals(otherType))
+ {
+ return this.generalizeMayBeNull(mayBeNull);
+ }
+
+ // Start taking into account the type dimensions.
+ int thisDimensionCount = ClassUtil.internalArrayTypeDimensionCount(thisType);
+ int otherDimensionCount = ClassUtil.internalArrayTypeDimensionCount(otherType);
+ int commonDimensionCount = Math.min(thisDimensionCount, otherDimensionCount);
+
+ if (thisDimensionCount == otherDimensionCount)
+ {
+ // See if we can take into account the referenced classes.
+ Clazz thisReferencedClass = this.referencedClass;
+ Clazz otherReferencedClass = other.referencedClass;
+
+ if (thisReferencedClass != null &&
+ otherReferencedClass != null)
+ {
+ if (thisReferencedClass.extendsOrImplements(otherReferencedClass))
+ {
+ return other.generalizeMayBeNull(mayBeNull);
+ }
+
+ if (otherReferencedClass.extendsOrImplements(thisReferencedClass))
+ {
+ return this.generalizeMayBeNull(mayBeNull);
+ }
+
+ // Collect the superclasses and interfaces of this class.
+ Set thisSuperClasses = new HashSet();
+ thisReferencedClass.hierarchyAccept(false, true, true, false,
+ new ClassCollector(thisSuperClasses));
+
+ int thisSuperClassesCount = thisSuperClasses.size();
+ if (thisSuperClassesCount == 0 &&
+ thisReferencedClass.getSuperName() != null)
+ {
+ throw new IllegalArgumentException("Can't find any super classes of ["+thisType+"] (not even immediate super class ["+thisReferencedClass.getSuperName()+"])");
+ }
+
+ // Collect the superclasses and interfaces of the other class.
+ Set otherSuperClasses = new HashSet();
+ otherReferencedClass.hierarchyAccept(false, true, true, false,
+ new ClassCollector(otherSuperClasses));
+
+ int otherSuperClassesCount = otherSuperClasses.size();
+ if (otherSuperClassesCount == 0 &&
+ otherReferencedClass.getSuperName() != null)
+ {
+ throw new IllegalArgumentException("Can't find any super classes of ["+otherType+"] (not even immediate super class ["+otherReferencedClass.getSuperName()+"])");
+ }
+
+ if (DEBUG)
+ {
+ System.out.println("ReferenceValue.generalize this ["+thisReferencedClass.getName()+"] with other ["+otherReferencedClass.getName()+"]");
+ System.out.println(" This super classes: "+thisSuperClasses);
+ System.out.println(" Other super classes: "+otherSuperClasses);
+ }
+
+ // Find the common superclasses.
+ thisSuperClasses.retainAll(otherSuperClasses);
+
+ if (DEBUG)
+ {
+ System.out.println(" Common super classes: "+thisSuperClasses);
+ }
+
+ // Find a class that is a subclass of all common superclasses,
+ // or that at least has the maximum number of common superclasses.
+ Clazz commonClass = null;
+
+ int maximumSuperClassCount = -1;
+
+ // Go over all common superclasses to find it. In case of
+ // multiple subclasses, keep the lowest one alphabetically,
+ // in order to ensure that the choice is deterministic.
+ Iterator commonSuperClasses = thisSuperClasses.iterator();
+ while (commonSuperClasses.hasNext())
+ {
+ Clazz commonSuperClass = (Clazz)commonSuperClasses.next();
+
+ int superClassCount = superClassCount(commonSuperClass, thisSuperClasses);
+ if (maximumSuperClassCount < superClassCount ||
+ (maximumSuperClassCount == superClassCount &&
+ commonClass != null &&
+ commonClass.getName().compareTo(commonSuperClass.getName()) > 0))
+ {
+ commonClass = commonSuperClass;
+ maximumSuperClassCount = superClassCount;
+ }
+ }
+
+ if (commonClass == null)
+ {
+ throw new IllegalArgumentException("Can't find common super class of ["+
+ thisType +"] (with "+thisSuperClassesCount +" known super classes) and ["+
+ otherType+"] (with "+otherSuperClassesCount+" known super classes)");
+ }
+
+ if (DEBUG)
+ {
+ System.out.println(" Best common class: ["+commonClass.getName()+"]");
+ }
+
+ // TODO: Handle more difficult cases, with multiple global subclasses.
+
+ return new ReferenceValue(commonDimensionCount == 0 ?
+ commonClass.getName() :
+ ClassUtil.internalArrayTypeFromClassName(commonClass.getName(),
+ commonDimensionCount),
+ commonClass,
+ mayBeNull);
+ }
+ }
+ else if (thisDimensionCount > otherDimensionCount)
+ {
+ // See if the other type is an interface type of arrays.
+ if (ClassUtil.isInternalArrayInterfaceName(ClassUtil.internalClassNameFromClassType(otherType)))
+ {
+ return other.generalizeMayBeNull(mayBeNull);
+ }
+ }
+ else if (thisDimensionCount < otherDimensionCount)
+ {
+ // See if this type is an interface type of arrays.
+ if (ClassUtil.isInternalArrayInterfaceName(ClassUtil.internalClassNameFromClassType(thisType)))
+ {
+ return this.generalizeMayBeNull(mayBeNull);
+ }
+ }
+
+ // Reduce the common dimension count if either type is an array of
+ // primitives type of this dimension.
+ if (commonDimensionCount > 0 &&
+ (ClassUtil.isInternalPrimitiveType(otherType.charAt(commonDimensionCount))) ||
+ ClassUtil.isInternalPrimitiveType(thisType.charAt(commonDimensionCount)))
+ {
+ commonDimensionCount--;
+ }
+
+ // Fall back on a basic Object or array of Objects type.
+ return commonDimensionCount == 0 ?
+ mayBeNull ?
+ ValueFactory.REFERENCE_VALUE_JAVA_LANG_OBJECT_MAYBE_NULL :
+ ValueFactory.REFERENCE_VALUE_JAVA_LANG_OBJECT_NOT_NULL :
+ new ReferenceValue(ClassUtil.internalArrayTypeFromClassName(ClassConstants.INTERNAL_NAME_JAVA_LANG_OBJECT,
+ commonDimensionCount),
+ null,
+ mayBeNull);
+ }
+
+
+ /**
+ * Returns if the number of superclasses of the given class in the given
+ * set of classes.
+ */
+ private int superClassCount(Clazz subClass, Set classes)
+ {
+ int count = 0;
+
+ Iterator iterator = classes.iterator();
+
+ while (iterator.hasNext())
+ {
+ Clazz clazz = (Clazz)iterator.next();
+ if (subClass.extendsOrImplements(clazz))
+ {
+ count++;
+ }
+ }
+
+ return count;
+ }
+
+
+ /**
+ * Returns whether this ReferenceValue is equal to the given other
+ * ReferenceValue.
+ * @return NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public int equal(ReferenceValue other)
+ {
+ return this.type == null && other.type == null ? ALWAYS : MAYBE;
+ }
+
+
+ // Derived unary methods.
+
+ /**
+ * Returns whether this ReferenceValue is not null
.
+ * @return NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int isNotNull()
+ {
+ return -isNull();
+ }
+
+
+ /**
+ * Returns the generalization of this ReferenceValue and the given other
+ * ReferenceValue.
+ */
+ private ReferenceValue generalizeMayBeNull(boolean mayBeNull)
+ {
+ return this.mayBeNull || !mayBeNull ?
+ this :
+ new ReferenceValue(this.type, this.referencedClass, true);
+ }
+
+
+ // Derived binary methods.
+
+ /**
+ * Returns whether this ReferenceValue and the given ReferenceValue are different.
+ * @return NEVER
, MAYBE
, or ALWAYS
.
+ */
+ public final int notEqual(ReferenceValue other)
+ {
+ return -equal(other);
+ }
+
+
+ // Implementations for Value.
+
+ public final ReferenceValue referenceValue()
+ {
+ return this;
+ }
+
+ public final Value generalize(Value other)
+ {
+ return this.generalize(other.referenceValue());
+ }
+
+ public boolean isParticular()
+ {
+ return type == null;
+ }
+
+ public final int computationalType()
+ {
+ return TYPE_REFERENCE;
+ }
+
+ public final String internalType()
+ {
+ return
+ type == null ? ClassConstants.INTERNAL_TYPE_JAVA_LANG_OBJECT :
+ ClassUtil.isInternalArrayType(type) ? type :
+ ClassConstants.INTERNAL_TYPE_CLASS_START +
+ type +
+ ClassConstants.INTERNAL_TYPE_CLASS_END;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ if (this == object)
+ {
+ return true;
+ }
+
+ if (object == null ||
+ this.getClass() != object.getClass())
+ {
+ return false;
+ }
+
+ ReferenceValue other = (ReferenceValue)object;
+ return this.type == null ? other.type == null :
+ (this.mayBeNull == other.mayBeNull &&
+ this.type.equals(other.type));
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode() ^
+ (type == null ? 0 : type.hashCode() ^ (mayBeNull ? 0 : 1));
+ }
+
+
+ public String toString()
+ {
+ return type == null ?
+ "null" :
+ type + (referencedClass == null ? "?" : "") + (mayBeNull ? "" : "!");
+ }
+}
diff --git a/src/proguard/evaluation/value/SpecificDoubleValue.java b/src/proguard/evaluation/value/SpecificDoubleValue.java
new file mode 100644
index 000000000..644f5534b
--- /dev/null
+++ b/src/proguard/evaluation/value/SpecificDoubleValue.java
@@ -0,0 +1,186 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This DoubleValue represents a specific double value.
+ *
+ * @author Eric Lafortune
+ */
+abstract class SpecificDoubleValue extends DoubleValue
+{
+ // Implementations of unary methods of DoubleValue.
+
+ public DoubleValue negate()
+ {
+ return new NegatedDoubleValue(this);
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return new ConvertedIntegerValue(this);
+ }
+
+ public LongValue convertToLong()
+ {
+ return new ConvertedLongValue(this);
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return new ConvertedFloatValue(this);
+ }
+
+
+ // Implementations of binary methods of DoubleValue.
+
+ public DoubleValue generalize(DoubleValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public DoubleValue add(DoubleValue other)
+ {
+ return other.add(this);
+ }
+
+ public DoubleValue subtract(DoubleValue other)
+ {
+ return other.subtractFrom(this);
+ }
+
+ public DoubleValue subtractFrom(DoubleValue other)
+ {
+ return other.subtract(this);
+ }
+
+ public DoubleValue multiply(DoubleValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public DoubleValue divide(DoubleValue other)
+ {
+ return other.divideOf(this);
+ }
+
+ public DoubleValue divideOf(DoubleValue other)
+ {
+ return other.divide(this);
+ }
+
+ public DoubleValue remainder(DoubleValue other)
+ {
+ return other.remainderOf(this);
+ }
+
+ public DoubleValue remainderOf(DoubleValue other)
+ {
+ return other.remainder(this);
+ }
+
+ public IntegerValue compare(DoubleValue other)
+ {
+ return other.compareReverse(this);
+ }
+
+
+ // Implementations of binary DoubleValue methods with SpecificDoubleValue
+ // arguments.
+
+ public DoubleValue generalize(SpecificDoubleValue other)
+ {
+ return this.equals(other) ? this : ValueFactory.DOUBLE_VALUE;
+ }
+
+ public DoubleValue add(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(this, CompositeDoubleValue.ADD, other);
+ }
+
+ public DoubleValue subtract(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(this, CompositeDoubleValue.SUBTRACT, other);
+ }
+
+ public DoubleValue subtractFrom(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(other, CompositeDoubleValue.SUBTRACT, this);
+ }
+
+ public DoubleValue multiply(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(this, CompositeDoubleValue.MULTIPLY, other);
+ }
+
+ public DoubleValue divide(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(this, CompositeDoubleValue.DIVIDE, other);
+ }
+
+ public DoubleValue divideOf(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(other, CompositeDoubleValue.DIVIDE, this);
+ }
+
+ public DoubleValue remainder(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(this, CompositeDoubleValue.REMAINDER, other);
+ }
+
+ public DoubleValue remainderOf(SpecificDoubleValue other)
+ {
+ return new CompositeDoubleValue(other, CompositeDoubleValue.REMAINDER, this);
+ }
+
+ public IntegerValue compare(SpecificDoubleValue other)
+ {
+ return ValueFactory.INTEGER_VALUE;
+
+ // Not handling NaN properly.
+ //return this.equals(other) ?
+ // SpecificValueFactory.INTEGER_VALUE_0 :
+ // new ComparisonValue(this, other);
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isSpecific()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+}
diff --git a/src/proguard/evaluation/value/SpecificFloatValue.java b/src/proguard/evaluation/value/SpecificFloatValue.java
new file mode 100644
index 000000000..d88baa34a
--- /dev/null
+++ b/src/proguard/evaluation/value/SpecificFloatValue.java
@@ -0,0 +1,186 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This FloatValue represents a specific float value.
+ *
+ * @author Eric Lafortune
+ */
+abstract class SpecificFloatValue extends FloatValue
+{
+ // Implementations of unary methods of FloatValue.
+
+ public FloatValue negate()
+ {
+ return new NegatedFloatValue(this);
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return new ConvertedIntegerValue(this);
+ }
+
+ public LongValue convertToLong()
+ {
+ return new ConvertedLongValue(this);
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return new ConvertedDoubleValue(this);
+ }
+
+
+ // Implementations of binary methods of FloatValue.
+
+ public FloatValue generalize(FloatValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public FloatValue add(FloatValue other)
+ {
+ return other.add(this);
+ }
+
+ public FloatValue subtract(FloatValue other)
+ {
+ return other.subtractFrom(this);
+ }
+
+ public FloatValue subtractFrom(FloatValue other)
+ {
+ return other.subtract(this);
+ }
+
+ public FloatValue multiply(FloatValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public FloatValue divide(FloatValue other)
+ {
+ return other.divideOf(this);
+ }
+
+ public FloatValue divideOf(FloatValue other)
+ {
+ return other.divide(this);
+ }
+
+ public FloatValue remainder(FloatValue other)
+ {
+ return other.remainderOf(this);
+ }
+
+ public FloatValue remainderOf(FloatValue other)
+ {
+ return other.remainder(this);
+ }
+
+ public IntegerValue compare(FloatValue other)
+ {
+ return other.compareReverse(this);
+ }
+
+
+ // Implementations of binary FloatValue methods with SpecificFloatValue
+ // arguments.
+
+ public FloatValue generalize(SpecificFloatValue other)
+ {
+ return this.equals(other) ? this : ValueFactory.FLOAT_VALUE;
+ }
+
+ public FloatValue add(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(this, CompositeFloatValue.ADD, other);
+ }
+
+ public FloatValue subtract(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(this, CompositeFloatValue.SUBTRACT, other);
+ }
+
+ public FloatValue subtractFrom(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(other, CompositeFloatValue.SUBTRACT, this);
+ }
+
+ public FloatValue multiply(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(this, CompositeFloatValue.MULTIPLY, other);
+ }
+
+ public FloatValue divide(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(this, CompositeFloatValue.DIVIDE, other);
+ }
+
+ public FloatValue divideOf(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(other, CompositeFloatValue.DIVIDE, this);
+ }
+
+ public FloatValue remainder(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(this, CompositeFloatValue.REMAINDER, other);
+ }
+
+ public FloatValue remainderOf(SpecificFloatValue other)
+ {
+ return new CompositeFloatValue(other, CompositeFloatValue.REMAINDER, this);
+ }
+
+ public IntegerValue compare(SpecificFloatValue other)
+ {
+ return ValueFactory.INTEGER_VALUE;
+
+ // Not handling NaN properly.
+ //return this.equals(other) ?
+ // SpecificValueFactory.INTEGER_VALUE_0 :
+ // new ComparisonValue(this, other);
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isSpecific()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+}
diff --git a/src/proguard/evaluation/value/SpecificIntegerValue.java b/src/proguard/evaluation/value/SpecificIntegerValue.java
new file mode 100644
index 000000000..81f864649
--- /dev/null
+++ b/src/proguard/evaluation/value/SpecificIntegerValue.java
@@ -0,0 +1,354 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This IntegerValue represents a specific integer value.
+ *
+ * @author Eric Lafortune
+ */
+abstract class SpecificIntegerValue extends IntegerValue
+{
+ // Implementations of unary methods of IntegerValue.
+
+ public IntegerValue negate()
+ {
+ return new NegatedIntegerValue(this);
+ }
+
+ public IntegerValue convertToByte()
+ {
+ return new ConvertedByteValue(this);
+ }
+
+ public IntegerValue convertToCharacter()
+ {
+ return new ConvertedCharacterValue(this);
+ }
+
+ public IntegerValue convertToShort()
+ {
+ return new ConvertedShortValue(this);
+ }
+
+ public LongValue convertToLong()
+ {
+ return new ConvertedLongValue(this);
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return new ConvertedFloatValue(this);
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return new ConvertedDoubleValue(this);
+ }
+
+
+ // Implementations of binary methods of IntegerValue.
+
+ public IntegerValue generalize(IntegerValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public IntegerValue add(IntegerValue other)
+ {
+ return other.add(this);
+ }
+
+ public IntegerValue subtract(IntegerValue other)
+ {
+ return other.subtractFrom(this);
+ }
+
+ public IntegerValue subtractFrom(IntegerValue other)
+ {
+ return other.subtract(this);
+ }
+
+ public IntegerValue multiply(IntegerValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public IntegerValue divide(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.divideOf(this);
+ }
+
+ public IntegerValue divideOf(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.divide(this);
+ }
+
+ public IntegerValue remainder(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.remainderOf(this);
+ }
+
+ public IntegerValue remainderOf(IntegerValue other)
+ throws ArithmeticException
+ {
+ return other.remainder(this);
+ }
+
+ public IntegerValue shiftLeft(IntegerValue other)
+ {
+ return other.shiftLeftOf(this);
+ }
+
+ public IntegerValue shiftLeftOf(IntegerValue other)
+ {
+ return other.shiftLeft(this);
+ }
+
+ public IntegerValue shiftRight(IntegerValue other)
+ {
+ return other.shiftRightOf(this);
+ }
+
+ public IntegerValue shiftRightOf(IntegerValue other)
+ {
+ return other.shiftRight(this);
+ }
+
+ public IntegerValue unsignedShiftRight(IntegerValue other)
+ {
+ return other.unsignedShiftRightOf(this);
+ }
+
+ public IntegerValue unsignedShiftRightOf(IntegerValue other)
+ {
+ return other.unsignedShiftRight(this);
+ }
+
+ public LongValue shiftLeftOf(LongValue other)
+ {
+ return other.shiftLeft(this);
+ }
+
+ public LongValue shiftRightOf(LongValue other)
+ {
+ return other.shiftRight(this);
+ }
+
+ public LongValue unsignedShiftRightOf(LongValue other)
+ {
+ return other.unsignedShiftRight(this);
+ }
+
+ public IntegerValue and(IntegerValue other)
+ {
+ return other.and(this);
+ }
+
+ public IntegerValue or(IntegerValue other)
+ {
+ return other.or(this);
+ }
+
+ public IntegerValue xor(IntegerValue other)
+ {
+ return other.xor(this);
+ }
+
+ public int equal(IntegerValue other)
+ {
+ return other.equal(this);
+ }
+
+ public int lessThan(IntegerValue other)
+ {
+ return other.greaterThan(this);
+ }
+
+ public int lessThanOrEqual(IntegerValue other)
+ {
+ return other.greaterThanOrEqual(this);
+ }
+
+
+ // Implementations of binary IntegerValue methods with SpecificIntegerValue
+ // arguments.
+
+ public IntegerValue generalize(SpecificIntegerValue other)
+ {
+ return this.equals(other) ? this : ValueFactory.INTEGER_VALUE;
+ }
+
+ public IntegerValue add(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(this, CompositeIntegerValue.ADD, other);
+ }
+
+ public IntegerValue subtract(SpecificIntegerValue other)
+ {
+ return this.equals(other) ?
+ SpecificValueFactory.INTEGER_VALUE_0 :
+ new CompositeIntegerValue(this, CompositeIntegerValue.SUBTRACT, other);
+ }
+
+ public IntegerValue subtractFrom(SpecificIntegerValue other)
+ {
+ return this.equals(other) ?
+ SpecificValueFactory.INTEGER_VALUE_0 :
+ new CompositeIntegerValue(other, CompositeIntegerValue.SUBTRACT, this);
+ }
+
+ public IntegerValue multiply(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(this, CompositeIntegerValue.MULTIPLY, other);
+ }
+
+ public IntegerValue divide(SpecificIntegerValue other)
+ throws ArithmeticException
+ {
+ return new CompositeIntegerValue(this, CompositeIntegerValue.DIVIDE, other);
+ }
+
+ public IntegerValue divideOf(SpecificIntegerValue other)
+ throws ArithmeticException
+ {
+ return new CompositeIntegerValue(other, CompositeIntegerValue.DIVIDE, this);
+ }
+
+ public IntegerValue remainder(SpecificIntegerValue other)
+ throws ArithmeticException
+ {
+ return new CompositeIntegerValue(this, CompositeIntegerValue.REMAINDER, other);
+ }
+
+ public IntegerValue remainderOf(SpecificIntegerValue other)
+ throws ArithmeticException
+ {
+ return new CompositeIntegerValue(other, CompositeIntegerValue.REMAINDER, this);
+ }
+
+ public IntegerValue shiftLeft(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(this, CompositeIntegerValue.SHIFT_LEFT, other);
+ }
+
+ public IntegerValue shiftRight(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(this, CompositeIntegerValue.SHIFT_RIGHT, other);
+ }
+
+ public IntegerValue unsignedShiftRight(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(this, CompositeIntegerValue.UNSIGNED_SHIFT_RIGHT, other);
+ }
+
+ public IntegerValue shiftLeftOf(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(other, CompositeIntegerValue.SHIFT_LEFT, this);
+ }
+
+ public IntegerValue shiftRightOf(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(other, CompositeIntegerValue.SHIFT_RIGHT, this);
+ }
+
+ public IntegerValue unsignedShiftRightOf(SpecificIntegerValue other)
+ {
+ return new CompositeIntegerValue(other, CompositeIntegerValue.UNSIGNED_SHIFT_RIGHT, this);
+ }
+
+ public LongValue shiftLeftOf(SpecificLongValue other)
+ {
+ return new CompositeLongValue(other, CompositeLongValue.SHIFT_LEFT, this);
+ }
+
+ public LongValue shiftRightOf(SpecificLongValue other)
+ {
+ return new CompositeLongValue(other, CompositeLongValue.SHIFT_RIGHT, this);
+ }
+
+ public LongValue unsignedShiftRightOf(SpecificLongValue other)
+ {
+ return new CompositeLongValue(other, CompositeLongValue.UNSIGNED_SHIFT_RIGHT, this);
+ }
+
+ public IntegerValue and(SpecificIntegerValue other)
+ {
+ return this.equals(other) ?
+ this :
+ new CompositeIntegerValue(other, CompositeIntegerValue.AND, this);
+ }
+
+ public IntegerValue or(SpecificIntegerValue other)
+ {
+ return this.equals(other) ?
+ this :
+ new CompositeIntegerValue(other, CompositeIntegerValue.OR, this);
+ }
+
+ public IntegerValue xor(SpecificIntegerValue other)
+ {
+ return this.equals(other) ?
+ SpecificValueFactory.INTEGER_VALUE_0 :
+ new CompositeIntegerValue(other, CompositeIntegerValue.XOR, this);
+ }
+
+ public int equal(SpecificIntegerValue other)
+ {
+ return this.equals(other) ? ALWAYS : MAYBE;
+ }
+
+ public int lessThan(SpecificIntegerValue other)
+ {
+ return this.equals(other) ? NEVER : MAYBE;
+ }
+
+ public int lessThanOrEqual(SpecificIntegerValue other)
+ {
+ return this.equals(other) ? ALWAYS : MAYBE;
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isSpecific()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+}
diff --git a/src/proguard/evaluation/value/SpecificLongValue.java b/src/proguard/evaluation/value/SpecificLongValue.java
new file mode 100644
index 000000000..15138b48c
--- /dev/null
+++ b/src/proguard/evaluation/value/SpecificLongValue.java
@@ -0,0 +1,259 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This LongValue represents a specific long value.
+ *
+ * @author Eric Lafortune
+ */
+abstract class SpecificLongValue extends LongValue
+{
+ // Implementations of unary methods of LongValue.
+
+ public LongValue negate()
+ {
+ return new NegatedLongValue(this);
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return new ConvertedIntegerValue(this);
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return new ConvertedFloatValue(this);
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return new ConvertedDoubleValue(this);
+ }
+
+
+ // Implementations of binary methods of LongValue.
+
+ public LongValue generalize(LongValue other)
+ {
+ return other.generalize(this);
+ }
+
+ public LongValue add(LongValue other)
+ {
+ return other.add(this);
+ }
+
+ public LongValue subtract(LongValue other)
+ {
+ return other.subtractFrom(this);
+ }
+
+ public LongValue subtractFrom(LongValue other)
+ {
+ return other.subtract(this);
+ }
+
+ public LongValue multiply(LongValue other)
+ {
+ return other.multiply(this);
+ }
+
+ public LongValue divide(LongValue other)
+ throws ArithmeticException
+ {
+ return other.divideOf(this);
+ }
+
+ public LongValue divideOf(LongValue other)
+ throws ArithmeticException
+ {
+ return other.divide(this);
+ }
+
+ public LongValue remainder(LongValue other)
+ throws ArithmeticException
+ {
+ return other.remainderOf(this);
+ }
+
+ public LongValue remainderOf(LongValue other)
+ throws ArithmeticException
+ {
+ return other.remainder(this);
+ }
+
+ public LongValue shiftLeft(IntegerValue other)
+ {
+ return other.shiftLeftOf(this);
+ }
+
+ public LongValue shiftRight(IntegerValue other)
+ {
+ return other.shiftRightOf(this);
+ }
+
+ public LongValue unsignedShiftRight(IntegerValue other)
+ {
+ return other.unsignedShiftRightOf(this);
+ }
+
+ public LongValue and(LongValue other)
+ {
+ return other.and(this);
+ }
+
+ public LongValue or(LongValue other)
+ {
+ return other.or(this);
+ }
+
+ public LongValue xor(LongValue other)
+ {
+ return other.xor(this);
+ }
+
+ public IntegerValue compare(LongValue other)
+ {
+ return other.compareReverse(this);
+ }
+
+
+ // Implementations of binary LongValue methods with SpecificLongValue
+ // arguments.
+
+ public LongValue generalize(SpecificLongValue other)
+ {
+ return this.equals(other) ? this : ValueFactory.LONG_VALUE;
+ }
+
+ public LongValue add(SpecificLongValue other)
+ {
+ return new CompositeLongValue(this, CompositeLongValue.ADD, other);
+ }
+
+ public LongValue subtract(SpecificLongValue other)
+ {
+ return this.equals(other) ?
+ SpecificValueFactory.LONG_VALUE_0 :
+ new CompositeLongValue(this, CompositeLongValue.SUBTRACT, other);
+ }
+
+ public LongValue subtractFrom(SpecificLongValue other)
+ {
+ return this.equals(other) ?
+ SpecificValueFactory.LONG_VALUE_0 :
+ new CompositeLongValue(other, CompositeLongValue.SUBTRACT, this);
+ }
+
+ public LongValue multiply(SpecificLongValue other)
+ {
+ return new CompositeLongValue(this, CompositeLongValue.MULTIPLY, other);
+ }
+
+ public LongValue divide(SpecificLongValue other)
+ throws ArithmeticException
+ {
+ return new CompositeLongValue(this, CompositeLongValue.DIVIDE, other);
+ }
+
+ public LongValue divideOf(SpecificLongValue other)
+ throws ArithmeticException
+ {
+ return new CompositeLongValue(other, CompositeLongValue.DIVIDE, this);
+ }
+
+ public LongValue remainder(SpecificLongValue other)
+ throws ArithmeticException
+ {
+ return new CompositeLongValue(this, CompositeLongValue.REMAINDER, other);
+ }
+
+ public LongValue remainderOf(SpecificLongValue other)
+ throws ArithmeticException
+ {
+ return new CompositeLongValue(other, CompositeLongValue.REMAINDER, this);
+ }
+
+ public LongValue shiftLeft(SpecificLongValue other)
+ {
+ return new CompositeLongValue(this, CompositeLongValue.SHIFT_LEFT, other);
+ }
+
+ public LongValue shiftRight(SpecificLongValue other)
+ {
+ return new CompositeLongValue(this, CompositeLongValue.SHIFT_RIGHT, other);
+ }
+
+ public LongValue unsignedShiftRight(SpecificLongValue other)
+ {
+ return new CompositeLongValue(this, CompositeLongValue.UNSIGNED_SHIFT_RIGHT, other);
+ }
+
+ public LongValue and(SpecificLongValue other)
+ {
+ return this.equals(other) ?
+ this :
+ new CompositeLongValue(other, CompositeLongValue.AND, this);
+ }
+
+ public LongValue or(SpecificLongValue other)
+ {
+ return this.equals(other) ?
+ this :
+ new CompositeLongValue(other, CompositeLongValue.OR, this);
+ }
+
+ public LongValue xor(SpecificLongValue other)
+ {
+ return this.equals(other) ?
+ SpecificValueFactory.LONG_VALUE_0 :
+ new CompositeLongValue(other, CompositeLongValue.XOR, this);
+ }
+
+ public IntegerValue compare(SpecificLongValue other)
+ {
+ return new ComparisonValue(this, other);
+ }
+
+
+ // Implementations for Value.
+
+ public boolean isSpecific()
+ {
+ return true;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+}
diff --git a/src/proguard/evaluation/value/SpecificValueFactory.java b/src/proguard/evaluation/value/SpecificValueFactory.java
new file mode 100644
index 000000000..f7619387f
--- /dev/null
+++ b/src/proguard/evaluation/value/SpecificValueFactory.java
@@ -0,0 +1,97 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This class provides methods to create and reuse IntegerValue objects.
+ *
+ * @author Eric Lafortune
+ */
+public class SpecificValueFactory
+extends ValueFactory
+{
+ // Shared copies of Value objects, to avoid creating a lot of objects.
+ static final IntegerValue INTEGER_VALUE_M1 = new ParticularIntegerValue(-1);
+ static final IntegerValue INTEGER_VALUE_0 = new ParticularIntegerValue(0);
+ static final IntegerValue INTEGER_VALUE_1 = new ParticularIntegerValue(1);
+ static final IntegerValue INTEGER_VALUE_2 = new ParticularIntegerValue(2);
+ static final IntegerValue INTEGER_VALUE_3 = new ParticularIntegerValue(3);
+ static final IntegerValue INTEGER_VALUE_4 = new ParticularIntegerValue(4);
+ static final IntegerValue INTEGER_VALUE_5 = new ParticularIntegerValue(5);
+ static final LongValue LONG_VALUE_0 = new ParticularLongValue(0);
+ static final LongValue LONG_VALUE_1 = new ParticularLongValue(1);
+ static final FloatValue FLOAT_VALUE_0 = new ParticularFloatValue(0.0f);
+ static final FloatValue FLOAT_VALUE_1 = new ParticularFloatValue(1.0f);
+ static final FloatValue FLOAT_VALUE_2 = new ParticularFloatValue(2.0f);
+ static final DoubleValue DOUBLE_VALUE_0 = new ParticularDoubleValue(0.0);
+ static final DoubleValue DOUBLE_VALUE_1 = new ParticularDoubleValue(1.0);
+
+
+ private static int POS_ZERO_FLOAT_BITS = Float.floatToIntBits(0.0f);
+ private static long POS_ZERO_DOUBLE_BITS = Double.doubleToLongBits(0.0);
+
+
+ // Implementations for ValueFactory.
+
+ public IntegerValue createIntegerValue(int value)
+ {
+ switch (value)
+ {
+ case -1: return INTEGER_VALUE_M1;
+ case 0: return INTEGER_VALUE_0;
+ case 1: return INTEGER_VALUE_1;
+ case 2: return INTEGER_VALUE_2;
+ case 3: return INTEGER_VALUE_3;
+ case 4: return INTEGER_VALUE_4;
+ case 5: return INTEGER_VALUE_5;
+ default: return new ParticularIntegerValue(value);
+ }
+ }
+
+
+ public LongValue createLongValue(long value)
+ {
+ return value == 0 ? LONG_VALUE_0 :
+ value == 1 ? LONG_VALUE_1 :
+ new ParticularLongValue(value);
+ }
+
+
+ public FloatValue createFloatValue(float value)
+ {
+ // Make sure to distinguish between +0.0 and -0.0.
+ return value == 0.0f && Float.floatToIntBits(value) == POS_ZERO_FLOAT_BITS
+ ? FLOAT_VALUE_0 :
+ value == 1.0f ? FLOAT_VALUE_1 :
+ value == 2.0f ? FLOAT_VALUE_2 :
+ new ParticularFloatValue(value);
+ }
+
+
+ public DoubleValue createDoubleValue(double value)
+ {
+ // Make sure to distinguish between +0.0 and -0.0.
+ return value == 0.0 && Double.doubleToLongBits(value) == POS_ZERO_DOUBLE_BITS
+ ? DOUBLE_VALUE_0 :
+ value == 1.0 ? DOUBLE_VALUE_1 :
+ new ParticularDoubleValue(value);
+ }
+}
diff --git a/src/proguard/evaluation/value/TopValue.java b/src/proguard/evaluation/value/TopValue.java
new file mode 100644
index 000000000..c7320fa28
--- /dev/null
+++ b/src/proguard/evaluation/value/TopValue.java
@@ -0,0 +1,79 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This class represents a partially evaluated top value. A top value is the
+ * dummy value that takes up the extra space when storing a long value or a
+ * double value.
+ *
+ * @author Eric Lafortune
+ */
+public class TopValue extends Category1Value
+{
+ // Implementations for Value.
+
+ public boolean isSpecific()
+ {
+ return true;
+ }
+
+ public boolean isParticular()
+ {
+ return true;
+ }
+
+ public final Value generalize(Value other)
+ {
+ return this.getClass() == other.getClass() ? this : null;
+ }
+
+ public final int computationalType()
+ {
+ return TYPE_TOP;
+ }
+
+ public final String internalType()
+ {
+ return null;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "T";
+ }
+}
diff --git a/src/proguard/evaluation/value/UnknownDoubleValue.java b/src/proguard/evaluation/value/UnknownDoubleValue.java
new file mode 100644
index 000000000..f8bad9a60
--- /dev/null
+++ b/src/proguard/evaluation/value/UnknownDoubleValue.java
@@ -0,0 +1,125 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This class represents a partially evaluated double value.
+ *
+ * @author Eric Lafortune
+ */
+public class UnknownDoubleValue extends DoubleValue
+{
+ // Basic unary methods.
+
+ public DoubleValue negate()
+ {
+ return this;
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return ValueFactory.INTEGER_VALUE;
+ }
+
+ public LongValue convertToLong()
+ {
+ return ValueFactory.LONG_VALUE;
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return ValueFactory.FLOAT_VALUE;
+ }
+
+
+ // Basic binary methods.
+
+ public DoubleValue generalize(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue add(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue subtract(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue subtractFrom(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue multiply(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue divide(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue divideOf(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue remainder(DoubleValue other)
+ {
+ return this;
+ }
+
+ public DoubleValue remainderOf(DoubleValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue compare(DoubleValue other)
+ {
+ return ValueFactory.INTEGER_VALUE;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "d";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/UnknownFloatValue.java b/src/proguard/evaluation/value/UnknownFloatValue.java
new file mode 100644
index 000000000..464ceedeb
--- /dev/null
+++ b/src/proguard/evaluation/value/UnknownFloatValue.java
@@ -0,0 +1,125 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This class represents a partially evaluated float value.
+ *
+ * @author Eric Lafortune
+ */
+public class UnknownFloatValue extends FloatValue
+{
+ // Basic unary methods.
+
+ public FloatValue negate()
+ {
+ return this;
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return ValueFactory.INTEGER_VALUE;
+ }
+
+ public LongValue convertToLong()
+ {
+ return ValueFactory.LONG_VALUE;
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return ValueFactory.DOUBLE_VALUE;
+ }
+
+
+ // Basic binary methods.
+
+ public FloatValue generalize(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue add(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue subtract(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue subtractFrom(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue multiply(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue divide(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue divideOf(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue remainder(FloatValue other)
+ {
+ return this;
+ }
+
+ public FloatValue remainderOf(FloatValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue compare(FloatValue other)
+ {
+ return ValueFactory.INTEGER_VALUE;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "f";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/UnknownIntegerValue.java b/src/proguard/evaluation/value/UnknownIntegerValue.java
new file mode 100644
index 000000000..b273b12cb
--- /dev/null
+++ b/src/proguard/evaluation/value/UnknownIntegerValue.java
@@ -0,0 +1,216 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This class represents a partially evaluated integer value.
+ *
+ * @author Eric Lafortune
+ */
+public class UnknownIntegerValue extends IntegerValue
+{
+ // Basic unary methods.
+
+ public IntegerValue negate()
+ {
+ return this;
+ }
+
+ public IntegerValue convertToByte()
+ {
+ return this;
+ }
+
+ public IntegerValue convertToCharacter()
+ {
+ return this;
+ }
+
+ public IntegerValue convertToShort()
+ {
+ return this;
+ }
+
+ public LongValue convertToLong()
+ {
+ return ValueFactory.LONG_VALUE;
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return ValueFactory.FLOAT_VALUE;
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return ValueFactory.DOUBLE_VALUE;
+ }
+
+
+ // Basic binary methods.
+
+ public IntegerValue generalize(IntegerValue other)
+ {
+ return this;
+ }
+
+
+ public IntegerValue add(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue subtract(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue subtractFrom(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue multiply(IntegerValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public IntegerValue divide(IntegerValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public IntegerValue divideOf(IntegerValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public IntegerValue remainder(IntegerValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public IntegerValue remainderOf(IntegerValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public IntegerValue shiftLeft(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue shiftLeftOf(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue shiftRight(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue shiftRightOf(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue unsignedShiftRight(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue unsignedShiftRightOf(IntegerValue other)
+ {
+ return this;
+ }
+
+ public LongValue shiftLeftOf(LongValue other)
+ {
+ return ValueFactory.LONG_VALUE;
+ }
+
+ public LongValue shiftRightOf(LongValue other)
+ {
+ return ValueFactory.LONG_VALUE;
+ }
+
+ public LongValue unsignedShiftRightOf(LongValue other)
+ {
+ return ValueFactory.LONG_VALUE;
+ }
+
+ public IntegerValue and(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue or(IntegerValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue xor(IntegerValue other)
+ {
+ return this;
+ }
+
+ public int equal(IntegerValue other)
+ {
+ return MAYBE;
+ }
+
+ public int lessThan(IntegerValue other)
+ {
+ return MAYBE;
+ }
+
+ public int lessThanOrEqual(IntegerValue other)
+ {
+ return MAYBE;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "i";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/UnknownLongValue.java b/src/proguard/evaluation/value/UnknownLongValue.java
new file mode 100644
index 000000000..ee315bef4
--- /dev/null
+++ b/src/proguard/evaluation/value/UnknownLongValue.java
@@ -0,0 +1,160 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This class represents a partially evaluated long value.
+ *
+ * @author Eric Lafortune
+ */
+public class UnknownLongValue extends LongValue
+{
+ // Basic unary methods.
+
+ public LongValue negate()
+ {
+ return this;
+ }
+
+ public IntegerValue convertToInteger()
+ {
+ return ValueFactory.INTEGER_VALUE;
+ }
+
+ public FloatValue convertToFloat()
+ {
+ return ValueFactory.FLOAT_VALUE;
+ }
+
+ public DoubleValue convertToDouble()
+ {
+ return ValueFactory.DOUBLE_VALUE;
+ }
+
+
+ // Basic binary methods.
+
+ public LongValue generalize(LongValue other)
+ {
+ return this;
+ }
+
+ public LongValue add(LongValue other)
+ {
+ return this;
+ }
+
+ public LongValue subtract(LongValue other)
+ {
+ return this;
+ }
+
+ public LongValue subtractFrom(LongValue other)
+ {
+ return this;
+ }
+
+ public LongValue multiply(LongValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public LongValue divide(LongValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public LongValue divideOf(LongValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public LongValue remainder(LongValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public LongValue remainderOf(LongValue other)
+ throws ArithmeticException
+ {
+ return this;
+ }
+
+ public LongValue shiftLeft(IntegerValue other)
+ {
+ return this;
+ }
+
+ public LongValue shiftRight(IntegerValue other)
+ {
+ return this;
+ }
+
+ public LongValue unsignedShiftRight(IntegerValue other)
+ {
+ return this;
+ }
+
+ public LongValue and(LongValue other)
+ {
+ return this;
+ }
+
+ public LongValue or(LongValue other)
+ {
+ return this;
+ }
+
+ public LongValue xor(LongValue other)
+ {
+ return this;
+ }
+
+ public IntegerValue compare(LongValue other)
+ {
+ return ValueFactory.INTEGER_VALUE;
+ }
+
+
+ // Implementations for Object.
+
+ public boolean equals(Object object)
+ {
+ return object != null &&
+ this.getClass() == object.getClass();
+ }
+
+
+ public int hashCode()
+ {
+ return this.getClass().hashCode();
+ }
+
+
+ public String toString()
+ {
+ return "l";
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/evaluation/value/Value.java b/src/proguard/evaluation/value/Value.java
new file mode 100644
index 000000000..f8d93272a
--- /dev/null
+++ b/src/proguard/evaluation/value/Value.java
@@ -0,0 +1,169 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+/**
+ * This abstract class represents a partially evaluated value.
+ *
+ * @author Eric Lafortune
+ */
+public abstract class Value
+{
+ public static final int NEVER = -1;
+ public static final int MAYBE = 0;
+ public static final int ALWAYS = 1;
+
+ public static final int TYPE_INTEGER = 1;
+ public static final int TYPE_LONG = 2;
+ public static final int TYPE_FLOAT = 3;
+ public static final int TYPE_DOUBLE = 4;
+ public static final int TYPE_REFERENCE = 5;
+ public static final int TYPE_INSTRUCTION_OFFSET = 6;
+ public static final int TYPE_TOP = 7;
+
+
+ /**
+ * Returns this Value as a Category1Value.
+ */
+ public Category1Value category1Value()
+ {
+ throw new IllegalArgumentException("Value is not a Category 1 value [" + this.getClass().getName() + "]");
+ }
+
+ /**
+ * Returns this Value as a Category2Value.
+ */
+ public Category2Value category2Value()
+ {
+ throw new IllegalArgumentException("Value is not a Category 2 value [" + this.getClass().getName() + "]");
+ }
+
+
+ /**
+ * Returns this Value as an IntegerValue.
+ */
+ public IntegerValue integerValue()
+ {
+ throw new IllegalArgumentException("Value is not an integer value [" + this.getClass().getName() + "]");
+ }
+
+ /**
+ * Returns this Value as a LongValue.
+ */
+ public LongValue longValue()
+ {
+ throw new IllegalArgumentException("Value is not a long value [" + this.getClass().getName() + "]");
+ }
+
+ /**
+ * Returns this Value as a FloatValue.
+ */
+ public FloatValue floatValue()
+ {
+ throw new IllegalArgumentException("Value is not a float value [" + this.getClass().getName() + "]");
+ }
+
+ /**
+ * Returns this Value as a DoubleValue.
+ */
+ public DoubleValue doubleValue()
+ {
+ throw new IllegalArgumentException("Value is not a double value [" + this.getClass().getName() + "]");
+ }
+
+ /**
+ * Returns this Value as a ReferenceValue.
+ */
+ public ReferenceValue referenceValue()
+ {
+ throw new IllegalArgumentException("Value is not a reference value [" + this.getClass().getName() + "]");
+ }
+
+ /**
+ * Returns this Value as an InstructionOffsetValue.
+ */
+ public InstructionOffsetValue instructionOffsetValue()
+ {
+ throw new IllegalArgumentException("Value is not an instruction offset value [" + this.getClass().getName() + "]");
+ }
+
+
+ /**
+ * Returns whether this Value represents a single specific (but possibly
+ * unknown) value.
+ */
+ public boolean isSpecific()
+ {
+ return false;
+ }
+
+
+ /**
+ * Returns whether this Value represents a single particular (known)
+ * value.
+ */
+ public boolean isParticular()
+ {
+ return false;
+ }
+
+
+ /**
+ * Returns the generalization of this Value and the given other Value.
+ */
+ public abstract Value generalize(Value other);
+
+
+ /**
+ * Returns whether the computational type of this Value is a category 2 type.
+ * This means that it takes up the space of two category 1 types on the
+ * stack, for instance.
+ */
+ public abstract boolean isCategory2();
+
+
+ /**
+ * Returns the computational type of this Value.
+ * @return TYPE_INTEGER
,
+ * TYPE_LONG
,
+ * TYPE_FLOAT
,
+ * TYPE_DOUBLE
,
+ * TYPE_REFERENCE
, or
+ * TYPE_INSTRUCTION_OFFSET
.
+ */
+ public abstract int computationalType();
+
+
+ /**
+ * Returns the internal type of this Value.
+ * @return ClassConstants.INTERNAL_TYPE_BOOLEAN
,
+ * ClassConstants.INTERNAL_TYPE_BYTE
,
+ * ClassConstants.INTERNAL_TYPE_CHAR
,
+ * ClassConstants.INTERNAL_TYPE_SHORT
,
+ * ClassConstants.INTERNAL_TYPE_INT
,
+ * ClassConstants.INTERNAL_TYPE_LONG
,
+ * ClassConstants.INTERNAL_TYPE_FLOAT
,
+ * ClassConstants.INTERNAL_TYPE_DOUBLE
,
+ * ClassConstants.INTERNAL_TYPE_CLASS_START ... ClassConstants.INTERNAL_TYPE_CLASS_END
, or
+ * an array type containing any of these types (always as String).
+ */
+ public abstract String internalType();
+}
diff --git a/src/proguard/evaluation/value/ValueFactory.java b/src/proguard/evaluation/value/ValueFactory.java
new file mode 100644
index 000000000..c94ac6520
--- /dev/null
+++ b/src/proguard/evaluation/value/ValueFactory.java
@@ -0,0 +1,193 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.evaluation.value;
+
+import proguard.classfile.*;
+import proguard.classfile.util.ClassUtil;
+
+/**
+ * This class provides methods to create and reuse Value objects.
+ *
+ * @author Eric Lafortune
+ */
+public class ValueFactory
+{
+ // Shared copies of Value objects, to avoid creating a lot of objects.
+ static final IntegerValue INTEGER_VALUE = new UnknownIntegerValue();
+ static final LongValue LONG_VALUE = new UnknownLongValue();
+ static final FloatValue FLOAT_VALUE = new UnknownFloatValue();
+ static final DoubleValue DOUBLE_VALUE = new UnknownDoubleValue();
+
+ static final ReferenceValue REFERENCE_VALUE_NULL = new ReferenceValue(null, null, true);
+ static final ReferenceValue REFERENCE_VALUE_JAVA_LANG_OBJECT_MAYBE_NULL = new ReferenceValue(ClassConstants.INTERNAL_NAME_JAVA_LANG_OBJECT, null, true);
+ static final ReferenceValue REFERENCE_VALUE_JAVA_LANG_OBJECT_NOT_NULL = new ReferenceValue(ClassConstants.INTERNAL_NAME_JAVA_LANG_OBJECT, null, false);
+
+
+ /**
+ * Creates a new Value of the given type.
+ * The type must be a fully specified internal type for primitives, classes,
+ * or arrays.
+ */
+ public Value createValue(String type, Clazz referencedClass, boolean mayBeNull)
+ {
+ switch (type.charAt(0))
+ {
+ case ClassConstants.INTERNAL_TYPE_VOID: return null;
+ case ClassConstants.INTERNAL_TYPE_BOOLEAN:
+ case ClassConstants.INTERNAL_TYPE_BYTE:
+ case ClassConstants.INTERNAL_TYPE_CHAR:
+ case ClassConstants.INTERNAL_TYPE_SHORT:
+ case ClassConstants.INTERNAL_TYPE_INT: return createIntegerValue();
+ case ClassConstants.INTERNAL_TYPE_LONG: return createLongValue();
+ case ClassConstants.INTERNAL_TYPE_FLOAT: return createFloatValue();
+ case ClassConstants.INTERNAL_TYPE_DOUBLE: return createDoubleValue();
+ default: return createReferenceValue(ClassUtil.isInternalArrayType(type) ?
+ type :
+ ClassUtil.internalClassNameFromClassType(type),
+ referencedClass,
+ mayBeNull);
+ }
+ }
+
+ /**
+ * Creates a new IntegerValue with an undefined value.
+ */
+ public IntegerValue createIntegerValue()
+ {
+ return INTEGER_VALUE;
+ }
+
+ /**
+ * Creates a new IntegerValue with a given particular value.
+ */
+ public IntegerValue createIntegerValue(int value)
+ {
+ return createIntegerValue();
+ }
+
+
+ /**
+ * Creates a new LongValue with an undefined value.
+ */
+ public LongValue createLongValue()
+ {
+ return LONG_VALUE;
+ }
+
+ /**
+ * Creates a new LongValue with a given particular value.
+ */
+ public LongValue createLongValue(long value)
+ {
+ return createLongValue();
+ }
+
+
+ /**
+ * Creates a new FloatValue with an undefined value.
+ */
+ public FloatValue createFloatValue()
+ {
+ return FLOAT_VALUE;
+ }
+
+ /**
+ * Creates a new FloatValue with a given particular value.
+ */
+ public FloatValue createFloatValue(float value)
+ {
+ return createFloatValue();
+ }
+
+
+ /**
+ * Creates a new DoubleValue with an undefined value.
+ */
+ public DoubleValue createDoubleValue()
+ {
+ return DOUBLE_VALUE;
+ }
+
+ /**
+ * Creates a new DoubleValue with a given particular value.
+ */
+ public DoubleValue createDoubleValue(double value)
+ {
+ return createDoubleValue();
+ }
+
+
+ /**
+ * Creates a new ReferenceValue that represents null
.
+ */
+ public ReferenceValue createReferenceValueNull()
+ {
+ return REFERENCE_VALUE_NULL;
+ }
+
+
+ /**
+ * Creates a new ReferenceValue of the given type. The type must be an
+ * internal class name or an array type. If the type is null
,
+ * the ReferenceValue represents null
.
+ */
+ public ReferenceValue createReferenceValue(String type,
+ Clazz referencedClass,
+ boolean mayBeNull)
+ {
+ return type == null ? REFERENCE_VALUE_NULL :
+ !type.equals(ClassConstants.INTERNAL_NAME_JAVA_LANG_OBJECT) ? new ReferenceValue(type, referencedClass, mayBeNull) :
+ mayBeNull ? REFERENCE_VALUE_JAVA_LANG_OBJECT_MAYBE_NULL :
+ REFERENCE_VALUE_JAVA_LANG_OBJECT_NOT_NULL;
+ }
+
+
+ /**
+ * Creates a new ReferenceValue for arrays of the given type and length.
+ * The type must be a fully specified internal type for primitives, classes,
+ * or arrays.
+ */
+ public ReferenceValue createArrayReferenceValue(String type,
+ Clazz referencedClass,
+ IntegerValue arrayLength)
+ {
+ return createArrayReferenceValue(type,
+ referencedClass,
+ arrayLength,
+ createValue(type, referencedClass, false));
+ }
+
+
+ /**
+ * Creates a new ReferenceValue for arrays of the given type and length,
+ * containing the given element. The type must be a fully specified internal
+ * type for primitives, classes, or arrays.
+ */
+ public ReferenceValue createArrayReferenceValue(String type,
+ Clazz referencedClass,
+ IntegerValue arrayLength,
+ Value elementValue)
+ {
+ return createReferenceValue(ClassConstants.INTERNAL_TYPE_ARRAY + type,
+ referencedClass,
+ false);
+ }
+}
diff --git a/src/proguard/evaluation/value/package.html b/src/proguard/evaluation/value/package.html
new file mode 100644
index 000000000..71e1b1365
--- /dev/null
+++ b/src/proguard/evaluation/value/package.html
@@ -0,0 +1,3 @@
+ListPanel
allows the user to add, edit, filter, move, and
+ * remove ClassPathEntry objects in a ClassPath object.
+ *
+ * @author Eric Lafortune
+ */
+class ClassPathPanel extends ListPanel
+{
+ private final JFrame owner;
+ private final boolean inputAndOutput;
+ private final JFileChooser chooser;
+ private final FilterDialog filterDialog;
+
+
+ public ClassPathPanel(JFrame owner, boolean inputAndOutput)
+ {
+ super();
+
+ super.firstSelectionButton = inputAndOutput ? 3 : 2;
+
+ this.owner = owner;
+ this.inputAndOutput = inputAndOutput;
+
+ list.setCellRenderer(new MyListCellRenderer());
+
+ chooser = new JFileChooser("");
+ chooser.setMultiSelectionEnabled(true);
+ chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
+ chooser.addChoosableFileFilter(
+ new ExtensionFileFilter(msg("jarWarEarZipExtensions"),
+ new String[] { ".jar", ".war", ".ear", ".zip" }));
+ chooser.setApproveButtonText(msg("ok"));
+
+ filterDialog = new FilterDialog(owner, msg("enterFilter"));
+
+ addAddButton(inputAndOutput, false);
+ if (inputAndOutput)
+ {
+ addAddButton(inputAndOutput, true);
+ }
+ addEditButton();
+ addFilterButton();
+ addRemoveButton();
+ addUpButton();
+ addDownButton();
+
+ enableSelectionButtons();
+ }
+
+
+ protected void addAddButton(boolean inputAndOutput,
+ final boolean isOutput)
+ {
+ JButton addButton = new JButton(msg(inputAndOutput ?
+ isOutput ? "addOutput" :
+ "addInput" :
+ "add"));
+ addButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ chooser.setDialogTitle(msg("addJars"));
+ chooser.setSelectedFile(null);
+ chooser.setSelectedFiles(null);
+
+ int returnValue = chooser.showOpenDialog(owner);
+ if (returnValue == JFileChooser.APPROVE_OPTION)
+ {
+ File[] selectedFiles = chooser.getSelectedFiles();
+ ClassPathEntry[] entries = classPathEntries(selectedFiles, isOutput);
+
+ // Add the new elements.
+ addElements(entries);
+ }
+ }
+ });
+
+ addButton(tip(addButton, inputAndOutput ?
+ isOutput ? "addOutputTip" :
+ "addInputTip" :
+ "addTip"));
+ }
+
+
+ protected void addEditButton()
+ {
+ JButton editButton = new JButton(msg("edit"));
+ editButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ boolean isOutput = false;
+
+ int[] selectedIndices = list.getSelectedIndices();
+
+ // Copy the Object array into a File array.
+ File[] selectedFiles = new File[selectedIndices.length];
+ for (int index = 0; index < selectedFiles.length; index++)
+ {
+ ClassPathEntry entry =
+ (ClassPathEntry)listModel.getElementAt(selectedIndices[index]);
+
+ isOutput = entry.isOutput();
+
+ selectedFiles[index] = entry.getFile();
+ }
+
+ chooser.setDialogTitle(msg("chooseJars"));
+
+ // Up to JDK 1.3.1, setSelectedFiles doesn't show in the file
+ // chooser, so we just use setSelectedFile first. It also sets
+ // the current directory.
+ chooser.setSelectedFile(selectedFiles[0].getAbsoluteFile());
+ chooser.setSelectedFiles(selectedFiles);
+
+ int returnValue = chooser.showOpenDialog(owner);
+ if (returnValue == JFileChooser.APPROVE_OPTION)
+ {
+ selectedFiles = chooser.getSelectedFiles();
+ ClassPathEntry[] entries = classPathEntries(selectedFiles, isOutput);
+
+ // If there are the same number of files selected now as
+ // there were before, we can just replace the old ones.
+ if (selectedIndices.length == selectedFiles.length)
+ {
+ // Replace the old elements.
+ setElementsAt(entries, selectedIndices);
+ }
+ else
+ {
+ // Remove the old elements.
+ removeElementsAt(selectedIndices);
+
+ // Add the new elements.
+ addElements(entries);
+ }
+ }
+ }
+ });
+
+ addButton(tip(editButton, "editTip"));
+ }
+
+
+ protected void addFilterButton()
+ {
+ JButton filterButton = new JButton(msg("filter"));
+ filterButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ if (!list.isSelectionEmpty())
+ {
+ int[] selectedIndices = list.getSelectedIndices();
+
+ // Put the filters of the first selected entry in the dialog.
+ getFiltersFrom(selectedIndices[0]);
+
+ int returnValue = filterDialog.showDialog();
+ if (returnValue == FilterDialog.APPROVE_OPTION)
+ {
+ // Apply the entered filters to all selected entries.
+ setFiltersAt(selectedIndices);
+ }
+ }
+ }
+ });
+
+ addButton(tip(filterButton, "filterTip"));
+ }
+
+
+ /**
+ * Sets the ClassPath to be represented in this panel.
+ */
+ public void setClassPath(ClassPath classPath)
+ {
+ listModel.clear();
+
+ if (classPath != null)
+ {
+ for (int index = 0; index < classPath.size(); index++)
+ {
+ listModel.addElement(classPath.get(index));
+ }
+ }
+
+ // Make sure the selection buttons are properly enabled,
+ // since the clear method doesn't seem to notify the listener.
+ enableSelectionButtons();
+ }
+
+
+ /**
+ * Returns the ClassPath currently represented in this panel.
+ */
+ public ClassPath getClassPath()
+ {
+ int size = listModel.size();
+ if (size == 0)
+ {
+ return null;
+ }
+
+ ClassPath classPath = new ClassPath();
+ for (int index = 0; index < size; index++)
+ {
+ classPath.add((ClassPathEntry)listModel.get(index));
+ }
+
+ return classPath;
+ }
+
+
+ /**
+ * Converts the given array of File objects into a corresponding array of
+ * ClassPathEntry objects.
+ */
+ private ClassPathEntry[] classPathEntries(File[] files, boolean isOutput)
+ {
+ ClassPathEntry[] entries = new ClassPathEntry[files.length];
+ for (int index = 0; index < entries.length; index++)
+ {
+ entries[index] = new ClassPathEntry(files[index], isOutput);
+ }
+ return entries;
+ }
+
+
+ /**
+ * Sets up the filter dialog with the filters from the specified class path
+ * entry.
+ */
+ private void getFiltersFrom(int index)
+ {
+ ClassPathEntry firstEntry = (ClassPathEntry)listModel.get(index);
+
+ filterDialog.setFilter(firstEntry.getFilter());
+ filterDialog.setJarFilter(firstEntry.getJarFilter());
+ filterDialog.setWarFilter(firstEntry.getWarFilter());
+ filterDialog.setEarFilter(firstEntry.getEarFilter());
+ filterDialog.setZipFilter(firstEntry.getZipFilter());
+ }
+
+
+ /**
+ * Applies the entered filter to the specified class path entries.
+ * Any previously set filters are discarded.
+ */
+ private void setFiltersAt(int[] indices)
+ {
+ for (int index = indices.length - 1; index >= 0; index--)
+ {
+ ClassPathEntry entry = (ClassPathEntry)listModel.get(indices[index]);
+ entry.setFilter(filterDialog.getFilter());
+ entry.setJarFilter(filterDialog.getJarFilter());
+ entry.setWarFilter(filterDialog.getWarFilter());
+ entry.setEarFilter(filterDialog.getEarFilter());
+ entry.setZipFilter(filterDialog.getZipFilter());
+ }
+
+ // Make sure they are selected and thus repainted.
+ list.setSelectedIndices(indices);
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+
+
+ /**
+ * This ListCellRenderer renders ClassPathEntry objects.
+ */
+ private class MyListCellRenderer implements ListCellRenderer
+ {
+ private static final String ARROW_IMAGE_FILE = "arrow.gif";
+
+ private final JPanel cellPanel = new JPanel(new GridBagLayout());
+ private final JLabel iconLabel = new JLabel("", JLabel.RIGHT);
+ private final JLabel jarNameLabel = new JLabel("", JLabel.RIGHT);
+ private final JLabel filterLabel = new JLabel("", JLabel.RIGHT);
+
+ private final Icon arrowIcon;
+
+
+ public MyListCellRenderer()
+ {
+ GridBagConstraints jarNameLabelConstraints = new GridBagConstraints();
+ jarNameLabelConstraints.anchor = GridBagConstraints.WEST;
+ jarNameLabelConstraints.insets = new Insets(1, 2, 1, 2);
+
+ GridBagConstraints filterLabelConstraints = new GridBagConstraints();
+ filterLabelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ filterLabelConstraints.fill = GridBagConstraints.HORIZONTAL;
+ filterLabelConstraints.weightx = 1.0;
+ filterLabelConstraints.anchor = GridBagConstraints.EAST;
+ filterLabelConstraints.insets = jarNameLabelConstraints.insets;
+
+ arrowIcon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(ARROW_IMAGE_FILE)));
+
+ cellPanel.add(iconLabel, jarNameLabelConstraints);
+ cellPanel.add(jarNameLabel, jarNameLabelConstraints);
+ cellPanel.add(filterLabel, filterLabelConstraints);
+ }
+
+
+ // Implementations for ListCellRenderer.
+
+ public Component getListCellRendererComponent(JList list,
+ Object value,
+ int index,
+ boolean isSelected,
+ boolean cellHasFocus)
+ {
+ ClassPathEntry entry = (ClassPathEntry)value;
+
+ // Prepend an arrow to the output entries.
+ if (inputAndOutput && entry.isOutput())
+ {
+ iconLabel.setIcon(arrowIcon);
+ }
+ else
+ {
+ iconLabel.setIcon(null);
+ }
+
+ // Set the entry name text.
+ jarNameLabel.setText(entry.getName());
+
+ // Set the filter text.
+ StringBuffer filter = null;
+ filter = appendFilter(filter, entry.getZipFilter());
+ filter = appendFilter(filter, entry.getEarFilter());
+ filter = appendFilter(filter, entry.getWarFilter());
+ filter = appendFilter(filter, entry.getJarFilter());
+ filter = appendFilter(filter, entry.getFilter());
+
+ if (filter != null)
+ {
+ filter.append(')');
+ }
+
+ filterLabel.setText(filter != null ? filter.toString() : "");
+
+ // Set the colors.
+ if (isSelected)
+ {
+ cellPanel.setBackground(list.getSelectionBackground());
+ jarNameLabel.setForeground(list.getSelectionForeground());
+ filterLabel.setForeground(list.getSelectionForeground());
+ }
+ else
+ {
+ cellPanel.setBackground(list.getBackground());
+ jarNameLabel.setForeground(list.getForeground());
+ filterLabel.setForeground(list.getForeground());
+ }
+
+ // Make the font color red if this is an input file that can't be read.
+ if (!(inputAndOutput && entry.isOutput()) &&
+ !entry.getFile().canRead())
+ {
+ jarNameLabel.setForeground(Color.red);
+ }
+
+ cellPanel.setOpaque(true);
+
+ return cellPanel;
+ }
+
+
+ private StringBuffer appendFilter(StringBuffer filter, List additionalFilter)
+ {
+ if (filter != null)
+ {
+ filter.append(';');
+ }
+
+ if (additionalFilter != null)
+ {
+ if (filter == null)
+ {
+ filter = new StringBuffer().append('(');
+ }
+
+ filter.append(ListUtil.commaSeparatedString(additionalFilter, true));
+ }
+
+ return filter;
+ }
+ }
+}
diff --git a/src/proguard/gui/ClassSpecificationDialog.java b/src/proguard/gui/ClassSpecificationDialog.java
new file mode 100644
index 000000000..38a3146c8
--- /dev/null
+++ b/src/proguard/gui/ClassSpecificationDialog.java
@@ -0,0 +1,546 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.*;
+import proguard.classfile.ClassConstants;
+import proguard.classfile.util.ClassUtil;
+
+import javax.swing.*;
+import javax.swing.border.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.List;
+
+/**
+ * This JDialog
allows the user to enter a String.
+ *
+ * @author Eric Lafortune
+ */
+final class ClassSpecificationDialog extends JDialog
+{
+ /**
+ * Return value if the dialog is canceled (with the Cancel button or by
+ * closing the dialog window).
+ */
+ public static final int CANCEL_OPTION = 1;
+
+ /**
+ * Return value if the dialog is approved (with the Ok button).
+ */
+ public static final int APPROVE_OPTION = 0;
+
+
+ private final JTextArea commentsTextArea = new JTextArea(4, 20);
+
+ private final JRadioButton keepClassesAndMembersRadioButton = new JRadioButton(msg("keep"));
+ private final JRadioButton keepClassMembersRadioButton = new JRadioButton(msg("keepClassMembers"));
+ private final JRadioButton keepClassesWithMembersRadioButton = new JRadioButton(msg("keepClassesWithMembers"));
+
+ private final JCheckBox allowShrinkingCheckBox = new JCheckBox(msg("allowShrinking"));
+ private final JCheckBox allowOptimizationCheckBox = new JCheckBox(msg("allowOptimization"));
+ private final JCheckBox allowObfuscationCheckBox = new JCheckBox(msg("allowObfuscation"));
+
+
+ private final JRadioButton[] publicRadioButtons;
+ private final JRadioButton[] finalRadioButtons;
+ private final JRadioButton[] abstractRadioButtons;
+ private final JRadioButton[] interfaceRadioButtons;
+ private final JRadioButton[] annotationRadioButtons;
+ private final JRadioButton[] enumRadioButtons;
+ private final JRadioButton[] syntheticRadioButtons;
+
+ private final JTextField annotationTypeTextField = new JTextField(20);
+ private final JTextField classNameTextField = new JTextField(20);
+ private final JTextField extendsAnnotationTypeTextField = new JTextField(20);
+ private final JTextField extendsClassNameTextField = new JTextField(20);
+
+ private final MemberSpecificationsPanel memberSpecificationsPanel;
+
+ private int returnValue;
+
+
+ public ClassSpecificationDialog(JFrame owner, boolean fullKeepOptions)
+ {
+ super(owner, msg("specifyClasses"), true);
+ setResizable(true);
+
+ // Create some constraints that can be reused.
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.anchor = GridBagConstraints.WEST;
+ constraints.insets = new Insets(1, 2, 1, 2);
+
+ GridBagConstraints constraintsStretch = new GridBagConstraints();
+ constraintsStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsStretch.weightx = 1.0;
+ constraintsStretch.anchor = GridBagConstraints.WEST;
+ constraintsStretch.insets = constraints.insets;
+
+ GridBagConstraints constraintsLast = new GridBagConstraints();
+ constraintsLast.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLast.anchor = GridBagConstraints.WEST;
+ constraintsLast.insets = constraints.insets;
+
+ GridBagConstraints constraintsLastStretch = new GridBagConstraints();
+ constraintsLastStretch.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLastStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsLastStretch.weightx = 1.0;
+ constraintsLastStretch.anchor = GridBagConstraints.WEST;
+ constraintsLastStretch.insets = constraints.insets;
+
+ GridBagConstraints panelConstraints = new GridBagConstraints();
+ panelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ panelConstraints.fill = GridBagConstraints.HORIZONTAL;
+ panelConstraints.weightx = 1.0;
+ panelConstraints.weighty = 0.0;
+ panelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ panelConstraints.insets = constraints.insets;
+
+ GridBagConstraints stretchPanelConstraints = new GridBagConstraints();
+ stretchPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ stretchPanelConstraints.fill = GridBagConstraints.BOTH;
+ stretchPanelConstraints.weightx = 1.0;
+ stretchPanelConstraints.weighty = 1.0;
+ stretchPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ stretchPanelConstraints.insets = constraints.insets;
+
+ GridBagConstraints labelConstraints = new GridBagConstraints();
+ labelConstraints.anchor = GridBagConstraints.CENTER;
+ labelConstraints.insets = new Insets(2, 10, 2, 10);
+
+ GridBagConstraints lastLabelConstraints = new GridBagConstraints();
+ lastLabelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ lastLabelConstraints.anchor = GridBagConstraints.CENTER;
+ lastLabelConstraints.insets = labelConstraints.insets;
+
+ GridBagConstraints advancedButtonConstraints = new GridBagConstraints();
+ advancedButtonConstraints.weightx = 1.0;
+ advancedButtonConstraints.weighty = 1.0;
+ advancedButtonConstraints.anchor = GridBagConstraints.SOUTHWEST;
+ advancedButtonConstraints.insets = new Insets(4, 4, 8, 4);
+
+ GridBagConstraints okButtonConstraints = new GridBagConstraints();
+ okButtonConstraints.weightx = 1.0;
+ okButtonConstraints.weighty = 1.0;
+ okButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ okButtonConstraints.insets = advancedButtonConstraints.insets;
+
+ GridBagConstraints cancelButtonConstraints = new GridBagConstraints();
+ cancelButtonConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ cancelButtonConstraints.weighty = 1.0;
+ cancelButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ cancelButtonConstraints.insets = advancedButtonConstraints.insets;
+
+ GridBagLayout layout = new GridBagLayout();
+
+ Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
+
+ // Create the comments panel.
+ JPanel commentsPanel = new JPanel(layout);
+ commentsPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("comments")));
+
+ JScrollPane commentsScrollPane = new JScrollPane(commentsTextArea);
+ commentsScrollPane.setBorder(classNameTextField.getBorder());
+
+ commentsPanel.add(tip(commentsScrollPane, "commentsTip"), constraintsLastStretch);
+
+ // Create the keep option panel.
+ ButtonGroup keepButtonGroup = new ButtonGroup();
+ keepButtonGroup.add(keepClassesAndMembersRadioButton);
+ keepButtonGroup.add(keepClassMembersRadioButton);
+ keepButtonGroup.add(keepClassesWithMembersRadioButton);
+
+ JPanel keepOptionPanel = new JPanel(layout);
+ keepOptionPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("keepTitle")));
+
+ keepOptionPanel.add(tip(keepClassesAndMembersRadioButton, "keepTip"), constraintsLastStretch);
+ keepOptionPanel.add(tip(keepClassMembersRadioButton, "keepClassMembersTip"), constraintsLastStretch);
+ keepOptionPanel.add(tip(keepClassesWithMembersRadioButton, "keepClassesWithMembersTip"), constraintsLastStretch);
+
+ // Create the allow option panel.
+ final JPanel allowOptionPanel = new JPanel(layout);
+ allowOptionPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("allowTitle")));
+
+ allowOptionPanel.add(tip(allowShrinkingCheckBox, "allowShrinkingTip"), constraintsLastStretch);
+ allowOptionPanel.add(tip(allowOptimizationCheckBox, "allowOptimizationTip"), constraintsLastStretch);
+ allowOptionPanel.add(tip(allowObfuscationCheckBox, "allowObfuscationTip"), constraintsLastStretch);
+
+ // Create the access panel.
+ JPanel accessPanel = new JPanel(layout);
+ accessPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("access")));
+
+ accessPanel.add(Box.createGlue(), labelConstraints);
+ accessPanel.add(tip(new JLabel(msg("required")), "requiredTip"), labelConstraints);
+ accessPanel.add(tip(new JLabel(msg("not")), "notTip"), labelConstraints);
+ accessPanel.add(tip(new JLabel(msg("dontCare")), "dontCareTip"), labelConstraints);
+ accessPanel.add(Box.createGlue(), constraintsLastStretch);
+
+ publicRadioButtons = addRadioButtonTriplet("Public", accessPanel);
+ finalRadioButtons = addRadioButtonTriplet("Final", accessPanel);
+ abstractRadioButtons = addRadioButtonTriplet("Abstract", accessPanel);
+ interfaceRadioButtons = addRadioButtonTriplet("Interface", accessPanel);
+ annotationRadioButtons = addRadioButtonTriplet("Annotation", accessPanel);
+ enumRadioButtons = addRadioButtonTriplet("Enum", accessPanel);
+ syntheticRadioButtons = addRadioButtonTriplet("Synthetic", accessPanel);
+
+ // Create the annotation type panel.
+ final JPanel annotationTypePanel = new JPanel(layout);
+ annotationTypePanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("annotation")));
+
+ annotationTypePanel.add(tip(annotationTypeTextField, "classNameTip"), constraintsLastStretch);
+
+ // Create the class name panel.
+ JPanel classNamePanel = new JPanel(layout);
+ classNamePanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("class")));
+
+ classNamePanel.add(tip(classNameTextField, "classNameTip"), constraintsLastStretch);
+
+ // Create the extends annotation type panel.
+ final JPanel extendsAnnotationTypePanel = new JPanel(layout);
+ extendsAnnotationTypePanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("extendsImplementsAnnotation")));
+
+ extendsAnnotationTypePanel.add(tip(extendsAnnotationTypeTextField, "classNameTip"), constraintsLastStretch);
+
+ // Create the extends class name panel.
+ JPanel extendsClassNamePanel = new JPanel(layout);
+ extendsClassNamePanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("extendsImplementsClass")));
+
+ extendsClassNamePanel.add(tip(extendsClassNameTextField, "classNameTip"), constraintsLastStretch);
+
+
+ // Create the class member list panel.
+ memberSpecificationsPanel = new MemberSpecificationsPanel(this, fullKeepOptions);
+ memberSpecificationsPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("classMembers")));
+
+ // Create the Advanced button.
+ final JButton advancedButton = new JButton(msg("basic"));
+ advancedButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ boolean visible = !allowOptionPanel.isVisible();
+
+ allowOptionPanel .setVisible(visible);
+ annotationTypePanel .setVisible(visible);
+ extendsAnnotationTypePanel.setVisible(visible);
+
+ advancedButton.setText(msg(visible ? "basic" : "advanced"));
+
+ pack();
+ }
+ });
+ advancedButton.doClick();
+
+ // Create the Ok button.
+ JButton okButton = new JButton(msg("ok"));
+ okButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ returnValue = APPROVE_OPTION;
+ hide();
+ }
+ });
+
+ // Create the Cancel button.
+ JButton cancelButton = new JButton(msg("cancel"));
+ cancelButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ hide();
+ }
+ });
+
+ // Add all panels to the main panel.
+ JPanel mainPanel = new JPanel(layout);
+ mainPanel.add(tip(commentsPanel, "commentsTip"), panelConstraints);
+ if (fullKeepOptions)
+ {
+ mainPanel.add(tip(keepOptionPanel, "keepTitleTip"), panelConstraints);
+ mainPanel.add(tip(allowOptionPanel, "allowTitleTip"), panelConstraints);
+ }
+ mainPanel.add(tip(accessPanel, "accessTip"), panelConstraints);
+ mainPanel.add(tip(annotationTypePanel, "annotationTip"), panelConstraints);
+ mainPanel.add(tip(classNamePanel, "classTip"), panelConstraints);
+ mainPanel.add(tip(extendsAnnotationTypePanel, "extendsImplementsAnnotationTip"), panelConstraints);
+ mainPanel.add(tip(extendsClassNamePanel, "extendsImplementsClassTip"), panelConstraints);
+ mainPanel.add(tip(memberSpecificationsPanel, "classMembersTip"), stretchPanelConstraints);
+
+ mainPanel.add(tip(advancedButton, "advancedTip"), advancedButtonConstraints);
+ mainPanel.add(okButton, okButtonConstraints);
+ mainPanel.add(cancelButton, cancelButtonConstraints);
+
+ getContentPane().add(new JScrollPane(mainPanel));
+ }
+
+
+ /**
+ * Adds a JLabel and three JRadioButton instances in a ButtonGroup to the
+ * given panel with a GridBagLayout, and returns the buttons in an array.
+ */
+ private JRadioButton[] addRadioButtonTriplet(String labelText,
+ JPanel panel)
+ {
+ GridBagConstraints labelConstraints = new GridBagConstraints();
+ labelConstraints.anchor = GridBagConstraints.WEST;
+ labelConstraints.insets = new Insets(2, 10, 2, 10);
+
+ GridBagConstraints buttonConstraints = new GridBagConstraints();
+ buttonConstraints.insets = labelConstraints.insets;
+
+ GridBagConstraints lastGlueConstraints = new GridBagConstraints();
+ lastGlueConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ lastGlueConstraints.weightx = 1.0;
+
+ // Create the radio buttons.
+ JRadioButton radioButton0 = new JRadioButton();
+ JRadioButton radioButton1 = new JRadioButton();
+ JRadioButton radioButton2 = new JRadioButton();
+
+ // Put them in a button group.
+ ButtonGroup buttonGroup = new ButtonGroup();
+ buttonGroup.add(radioButton0);
+ buttonGroup.add(radioButton1);
+ buttonGroup.add(radioButton2);
+
+ // Add the label and the buttons to the panel.
+ panel.add(new JLabel(labelText), labelConstraints);
+ panel.add(radioButton0, buttonConstraints);
+ panel.add(radioButton1, buttonConstraints);
+ panel.add(radioButton2, buttonConstraints);
+ panel.add(Box.createGlue(), lastGlueConstraints);
+
+ return new JRadioButton[]
+ {
+ radioButton0,
+ radioButton1,
+ radioButton2
+ };
+ }
+
+
+ /**
+ * Sets the KeepClassSpecification to be represented in this dialog.
+ */
+ public void setKeepSpecification(KeepClassSpecification keepClassSpecification)
+ {
+ boolean markClasses = keepClassSpecification.markClasses;
+ boolean markConditionally = keepClassSpecification.markConditionally;
+ boolean allowShrinking = keepClassSpecification.allowShrinking;
+ boolean allowOptimization = keepClassSpecification.allowOptimization;
+ boolean allowObfuscation = keepClassSpecification.allowObfuscation;
+
+ // Figure out the proper keep radio button and set it.
+ JRadioButton keepOptionRadioButton =
+ markConditionally ? keepClassesWithMembersRadioButton :
+ markClasses ? keepClassesAndMembersRadioButton :
+ keepClassMembersRadioButton;
+
+ keepOptionRadioButton.setSelected(true);
+
+ // Set the allow radio buttons.
+ allowShrinkingCheckBox .setSelected(allowShrinking);
+ allowOptimizationCheckBox.setSelected(allowOptimization);
+ allowObfuscationCheckBox .setSelected(allowObfuscation);
+
+ setClassSpecification(keepClassSpecification);
+ }
+
+
+ /**
+ * Sets the ClassSpecification to be represented in this dialog.
+ */
+ public void setClassSpecification(ClassSpecification classSpecification)
+ {
+ String comments = classSpecification.comments;
+ String annotationType = classSpecification.annotationType;
+ String className = classSpecification.className;
+ String extendsAnnotationType = classSpecification.extendsAnnotationType;
+ String extendsClassName = classSpecification.extendsClassName;
+ List keepFieldOptions = classSpecification.fieldSpecifications;
+ List keepMethodOptions = classSpecification.methodSpecifications;
+
+ // Set the comments text area.
+ commentsTextArea.setText(comments == null ? "" : comments);
+
+ // Set the access radio buttons.
+ setClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_PUBLIC, publicRadioButtons);
+ setClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_FINAL, finalRadioButtons);
+ setClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_ABSTRACT, abstractRadioButtons);
+ setClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_INTERFACE, interfaceRadioButtons);
+ setClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_ANNOTATTION, annotationRadioButtons);
+ setClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_ENUM, enumRadioButtons);
+ setClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_SYNTHETIC, syntheticRadioButtons);
+
+ // Set the class and annotation text fields.
+ annotationTypeTextField .setText(annotationType == null ? "" : ClassUtil.externalType(annotationType));
+ classNameTextField .setText(className == null ? "*" : ClassUtil.externalClassName(className));
+ extendsAnnotationTypeTextField.setText(extendsAnnotationType == null ? "" : ClassUtil.externalType(extendsAnnotationType));
+ extendsClassNameTextField .setText(extendsClassName == null ? "" : ClassUtil.externalClassName(extendsClassName));
+
+ // Set the keep class member option list.
+ memberSpecificationsPanel.setMemberSpecifications(keepFieldOptions, keepMethodOptions);
+ }
+
+
+ /**
+ * Returns the KeepClassSpecification currently represented in this dialog.
+ */
+ public KeepClassSpecification getKeepSpecification()
+ {
+ boolean markClasses = !keepClassMembersRadioButton .isSelected();
+ boolean markConditionally = keepClassesWithMembersRadioButton.isSelected();
+ boolean allowShrinking = allowShrinkingCheckBox .isSelected();
+ boolean allowOptimization = allowOptimizationCheckBox .isSelected();
+ boolean allowObfuscation = allowObfuscationCheckBox .isSelected();
+
+ return new KeepClassSpecification(markClasses,
+ markConditionally,
+ allowShrinking,
+ allowOptimization,
+ allowObfuscation,
+ getClassSpecification());
+ }
+
+
+ /**
+ * Returns the ClassSpecification currently represented in this dialog.
+ */
+ public ClassSpecification getClassSpecification()
+ {
+ String comments = commentsTextArea.getText();
+ String annotationType = annotationTypeTextField.getText();
+ String className = classNameTextField.getText();
+ String extendsAnnotationType = extendsAnnotationTypeTextField.getText();
+ String extendsClassName = extendsClassNameTextField.getText();
+
+ ClassSpecification classSpecification =
+ new ClassSpecification(comments.equals("") ? null : comments,
+ 0,
+ 0,
+ annotationType.equals("") ? null : ClassUtil.internalType(annotationType),
+ className.equals("") ||
+ className.equals("*") ? null : ClassUtil.internalClassName(className),
+ extendsAnnotationType.equals("") ? null : ClassUtil.internalType(extendsAnnotationType),
+ extendsClassName.equals("") ? null : ClassUtil.internalClassName(extendsClassName));
+
+ // Also get the access radio button settings.
+ getClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_PUBLIC, publicRadioButtons);
+ getClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_FINAL, finalRadioButtons);
+ getClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_ABSTRACT, abstractRadioButtons);
+ getClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_INTERFACE, interfaceRadioButtons);
+ getClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_ANNOTATTION, annotationRadioButtons);
+ getClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_ENUM, enumRadioButtons);
+ getClassSpecificationRadioButtons(classSpecification, ClassConstants.INTERNAL_ACC_SYNTHETIC, syntheticRadioButtons);
+
+ // Get the keep class member option lists.
+ classSpecification.fieldSpecifications = memberSpecificationsPanel.getMemberSpecifications(true);
+ classSpecification.methodSpecifications = memberSpecificationsPanel.getMemberSpecifications(false);
+
+ return classSpecification;
+ }
+
+
+ /**
+ * Shows this dialog. This method only returns when the dialog is closed.
+ *
+ * @return CANCEL_OPTION
or APPROVE_OPTION
,
+ * depending on the choice of the user.
+ */
+ public int showDialog()
+ {
+ returnValue = CANCEL_OPTION;
+
+ // Open the dialog in the right place, then wait for it to be closed,
+ // one way or another.
+ pack();
+ setLocationRelativeTo(getOwner());
+ show();
+
+ return returnValue;
+ }
+
+
+ /**
+ * Sets the appropriate radio button of a given triplet, based on the access
+ * flags of the given keep option.
+ */
+ private void setClassSpecificationRadioButtons(ClassSpecification classSpecification,
+ int flag,
+ JRadioButton[] radioButtons)
+ {
+ int index = (classSpecification.requiredSetAccessFlags & flag) != 0 ? 0 :
+ (classSpecification.requiredUnsetAccessFlags & flag) != 0 ? 1 :
+ 2;
+ radioButtons[index].setSelected(true);
+ }
+
+
+ /**
+ * Updates the access flag of the given keep option, based on the given radio
+ * button triplet.
+ */
+ private void getClassSpecificationRadioButtons(ClassSpecification classSpecification,
+ int flag,
+ JRadioButton[] radioButtons)
+ {
+ if (radioButtons[0].isSelected())
+ {
+ classSpecification.requiredSetAccessFlags |= flag;
+ }
+ else if (radioButtons[1].isSelected())
+ {
+ classSpecification.requiredUnsetAccessFlags |= flag;
+ }
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+}
diff --git a/src/proguard/gui/ClassSpecificationsPanel.java b/src/proguard/gui/ClassSpecificationsPanel.java
new file mode 100644
index 000000000..bc2924734
--- /dev/null
+++ b/src/proguard/gui/ClassSpecificationsPanel.java
@@ -0,0 +1,231 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.ClassSpecification;
+import proguard.classfile.util.ClassUtil;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.*;
+import java.util.List;
+
+
+/**
+ * This ListPanel
allows the user to add, edit, move, and remove
+ * ClassSpecification entries in a list.
+ *
+ * @author Eric Lafortune
+ */
+class ClassSpecificationsPanel extends ListPanel
+{
+ protected final ClassSpecificationDialog classSpecificationDialog;
+
+
+ public ClassSpecificationsPanel(JFrame owner, boolean fullKeepOptions)
+ {
+ super();
+
+ list.setCellRenderer(new MyListCellRenderer());
+
+ classSpecificationDialog = new ClassSpecificationDialog(owner, fullKeepOptions);
+
+ addAddButton();
+ addEditButton();
+ addRemoveButton();
+ addUpButton();
+ addDownButton();
+
+ enableSelectionButtons();
+ }
+
+
+ protected void addAddButton()
+ {
+ JButton addButton = new JButton(msg("add"));
+ addButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ setClassSpecification(createClassSpecification());
+ int returnValue = classSpecificationDialog.showDialog();
+ if (returnValue == ClassSpecificationDialog.APPROVE_OPTION)
+ {
+ // Add the new element.
+ addElement(getClassSpecification());
+ }
+ }
+ });
+
+ addButton(tip(addButton, "addTip"));
+ }
+
+
+ protected void addEditButton()
+ {
+ JButton editButton = new JButton(msg("edit"));
+ editButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ ClassSpecification selectedClassSpecification =
+ (ClassSpecification)list.getSelectedValue();
+
+ setClassSpecification(selectedClassSpecification);
+ int returnValue = classSpecificationDialog.showDialog();
+ if (returnValue == ClassSpecificationDialog.APPROVE_OPTION)
+ {
+ // Replace the old element.
+ setElementAt(getClassSpecification(),
+ list.getSelectedIndex());
+ }
+ }
+ });
+
+ addButton(tip(editButton, "editTip"));
+ }
+
+
+ protected ClassSpecification createClassSpecification()
+ {
+ return new ClassSpecification();
+ }
+
+
+ protected void setClassSpecification(ClassSpecification classSpecification)
+ {
+ classSpecificationDialog.setClassSpecification(classSpecification);
+ }
+
+
+ protected ClassSpecification getClassSpecification()
+ {
+ return classSpecificationDialog.getClassSpecification();
+ }
+
+
+ /**
+ * Sets the ClassSpecification objects to be represented in this panel.
+ */
+ public void setClassSpecifications(List classSpecifications)
+ {
+ listModel.clear();
+
+ if (classSpecifications != null)
+ {
+ for (int index = 0; index < classSpecifications.size(); index++)
+ {
+ listModel.addElement(classSpecifications.get(index));
+ }
+ }
+
+ // Make sure the selection buttons are properly enabled,
+ // since the clear method doesn't seem to notify the listener.
+ enableSelectionButtons();
+ }
+
+
+ /**
+ * Returns the ClassSpecification objects currently represented in this panel.
+ */
+ public List getClassSpecifications()
+ {
+ int size = listModel.size();
+ if (size == 0)
+ {
+ return null;
+ }
+
+ List classSpecifications = new ArrayList(size);
+ for (int index = 0; index < size; index++)
+ {
+ classSpecifications.add(listModel.get(index));
+ }
+
+ return classSpecifications;
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+
+
+ /**
+ * This ListCellRenderer renders ClassSpecification objects.
+ */
+ private static class MyListCellRenderer implements ListCellRenderer
+ {
+ private final JLabel label = new JLabel();
+
+
+ // Implementations for ListCellRenderer.
+
+ public Component getListCellRendererComponent(JList list,
+ Object value,
+ int index,
+ boolean isSelected,
+ boolean cellHasFocus)
+ {
+ ClassSpecification classSpecification = (ClassSpecification)value;
+
+ String comments = classSpecification.comments;
+
+ label.setText(comments != null ? comments.trim() :
+ classSpecification.className != null ? (msg("class") + ' ' + ClassUtil.externalClassName(classSpecification.className)) :
+ classSpecification.extendsClassName != null ? (msg("extensionsOf") + ' ' + ClassUtil.externalClassName(classSpecification.extendsClassName)) :
+ (msg("specificationNumber") + index));
+
+ if (isSelected)
+ {
+ label.setBackground(list.getSelectionBackground());
+ label.setForeground(list.getSelectionForeground());
+ }
+ else
+ {
+ label.setBackground(list.getBackground());
+ label.setForeground(list.getForeground());
+ }
+
+ label.setOpaque(true);
+
+ return label;
+ }
+ }
+}
diff --git a/src/proguard/gui/ExtensionFileFilter.java b/src/proguard/gui/ExtensionFileFilter.java
new file mode 100644
index 000000000..ee097147b
--- /dev/null
+++ b/src/proguard/gui/ExtensionFileFilter.java
@@ -0,0 +1,78 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import javax.swing.filechooser.FileFilter;
+import java.io.File;
+
+
+/**
+ * This FileFilter
accepts files that end in one of the given
+ * extensions.
+ *
+ * @author Eric Lafortune
+ */
+final class ExtensionFileFilter extends FileFilter
+{
+ private final String description;
+ private final String[] extensions;
+
+
+ /**
+ * Creates a new ExtensionFileFilter.
+ * @param description a description of the filter.
+ * @param extensions an array of acceptable extensions.
+ */
+ public ExtensionFileFilter(String description, String[] extensions)
+ {
+ this.description = description;
+ this.extensions = extensions;
+ }
+
+
+ // Implemntations for FileFilter
+
+ public String getDescription()
+ {
+ return description;
+ }
+
+
+ public boolean accept(File file)
+ {
+ if (file.isDirectory())
+ {
+ return true;
+ }
+
+ String fileName = file.getName().toLowerCase();
+
+ for (int index = 0; index < extensions.length; index++)
+ {
+ if (fileName.endsWith(extensions[index]))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/src/proguard/gui/FilterBuilder.java b/src/proguard/gui/FilterBuilder.java
new file mode 100644
index 000000000..c362cb695
--- /dev/null
+++ b/src/proguard/gui/FilterBuilder.java
@@ -0,0 +1,208 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import javax.swing.*;
+
+/**
+ * This class builds filters corresponding to the selections and names of a
+ * given list of check boxes.
+ */
+public class FilterBuilder
+{
+ private JCheckBox[] checkBoxes;
+ private char separator;
+
+
+ /**
+ * Creates a new FilterBuilder.
+ * @param checkBoxes the check boxes with names and selections that should
+ * be reflected in the output filter.
+ * @param separator the separator for the names in the check boxes.
+ */
+ public FilterBuilder(JCheckBox[] checkBoxes, char separator)
+ {
+ this.checkBoxes = checkBoxes;
+ this.separator = separator;
+ }
+
+
+ /**
+ * Builds a filter for the current names and selections of the check boxes.
+ */
+ public String buildFilter()
+ {
+ StringBuffer positive = new StringBuffer();
+ StringBuffer negative = new StringBuffer();
+
+ buildFilter("", positive, negative);
+
+ return positive.length() <= negative.length() ?
+ positive.toString() :
+ negative.toString();
+ }
+
+
+ /**
+ * Builds two versions of the filter for the given prefix.
+ * @param prefix the prefix.
+ * @param positive the filter to be extended, assuming the matching
+ * strings are accepted.
+ * @param negative the filter to be extended, assuming the matching
+ * strings are rejected.
+ */
+ private void buildFilter(String prefix,
+ StringBuffer positive,
+ StringBuffer negative)
+ {
+ int positiveCount = 0;
+ int negativeCount = 0;
+
+ // Count all selected and unselected check boxes with the prefix.
+ for (int index = 0; index < checkBoxes.length; index++)
+ {
+ JCheckBox checkBox = checkBoxes[index];
+ String name = checkBox.getText();
+
+ if (name.startsWith(prefix))
+ {
+ if (checkBox.isSelected())
+ {
+ positiveCount++;
+ }
+ else
+ {
+ negativeCount++;
+ }
+ }
+ }
+
+ // Are there only unselected check boxes?
+ if (positiveCount == 0)
+ {
+ // Extend the positive filter with exceptions and return.
+ if (positive.length() > 0)
+ {
+ positive.append(',');
+ }
+ positive.append('!').append(prefix);
+ if (prefix.length() == 0 ||
+ prefix.charAt(prefix.length()-1) == separator)
+ {
+ positive.append('*');
+ }
+
+ return;
+ }
+
+ // Are there only selected check boxes?
+ if (negativeCount == 0)
+ {
+ // Extend the negative filter with exceptions and return.
+ if (negative.length() > 0)
+ {
+ negative.append(',');
+ }
+ negative.append(prefix);
+ if (prefix.length() == 0 ||
+ prefix.charAt(prefix.length()-1) == separator)
+ {
+ negative.append('*');
+ }
+
+ return;
+ }
+
+ // Create new positive and negative filters for names starting with the
+ // prefix only.
+ StringBuffer positiveFilter = new StringBuffer();
+ StringBuffer negativeFilter = new StringBuffer();
+
+ String newPrefix = null;
+
+ for (int index = 0; index < checkBoxes.length; index++)
+ {
+ String name = checkBoxes[index].getText();
+
+ if (name.startsWith(prefix))
+ {
+ if (newPrefix == null ||
+ !name.startsWith(newPrefix))
+ {
+ int prefixIndex =
+ name.indexOf(separator, prefix.length()+1);
+
+ newPrefix = prefixIndex >= 0 ?
+ name.substring(0, prefixIndex+1) :
+ name;
+
+ buildFilter(newPrefix,
+ positiveFilter,
+ negativeFilter);
+ }
+ }
+ }
+
+ // Extend the positive filter.
+ if (positiveFilter.length() <= negativeFilter.length() + prefix.length() + 3)
+ {
+ if (positive.length() > 0 &&
+ positiveFilter.length() > 0)
+ {
+ positive.append(',');
+ }
+
+ positive.append(positiveFilter);
+ }
+ else
+ {
+ if (positive.length() > 0 &&
+ negativeFilter.length() > 0)
+ {
+ positive.append(',');
+ }
+
+ positive.append(negativeFilter).append(",!").append(prefix).append('*');
+ }
+
+ // Extend the negative filter.
+ if (negativeFilter.length() <= positiveFilter.length() + prefix.length() + 4)
+ {
+ if (negative.length() > 0 &&
+ negativeFilter.length() > 0)
+ {
+ negative.append(',');
+ }
+
+ negative.append(negativeFilter);
+ }
+ else
+ {
+ if (negative.length() > 0 &&
+ positiveFilter.length() > 0)
+ {
+ negative.append(',');
+ }
+
+ negative.append(positiveFilter).append(',').append(prefix).append('*');
+ }
+ }
+}
diff --git a/src/proguard/gui/FilterDialog.java b/src/proguard/gui/FilterDialog.java
new file mode 100644
index 000000000..88dbd8bb0
--- /dev/null
+++ b/src/proguard/gui/FilterDialog.java
@@ -0,0 +1,320 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.util.ListUtil;
+
+import javax.swing.*;
+import javax.swing.border.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.List;
+
+/**
+ * This JDialog
allows the user to enter a String.
+ *
+ * @author Eric Lafortune
+ */
+public class FilterDialog extends JDialog
+{
+ /**
+ * Return value if the dialog is canceled (with the Cancel button or by
+ * closing the dialog window).
+ */
+ public static final int CANCEL_OPTION = 1;
+
+ /**
+ * Return value if the dialog is approved (with the Ok button).
+ */
+ public static final int APPROVE_OPTION = 0;
+
+ private static final String DEFAULT_FILTER = "**";
+ private static final String DEFAULT_JAR_FILTER = "**.jar";
+ private static final String DEFAULT_WAR_FILTER = "**.war";
+ private static final String DEFAULT_EAR_FILTER = "**.ear";
+ private static final String DEFAULT_ZIP_FILTER = "**.zip";
+
+
+ private final JTextField filterTextField = new JTextField(40);
+ private final JTextField jarFilterTextField = new JTextField(40);
+ private final JTextField warFilterTextField = new JTextField(40);
+ private final JTextField earFilterTextField = new JTextField(40);
+ private final JTextField zipFilterTextField = new JTextField(40);
+ private int returnValue;
+
+
+ public FilterDialog(JFrame owner,
+ String explanation)
+ {
+ super(owner, true);
+ setResizable(true);
+
+ // Create some constraints that can be reused.
+ GridBagConstraints textConstraints = new GridBagConstraints();
+ textConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ textConstraints.fill = GridBagConstraints.HORIZONTAL;
+ textConstraints.weightx = 1.0;
+ textConstraints.weighty = 1.0;
+ textConstraints.anchor = GridBagConstraints.NORTHWEST;
+ textConstraints.insets = new Insets(10, 10, 10, 10);
+
+ GridBagConstraints labelConstraints = new GridBagConstraints();
+ labelConstraints.anchor = GridBagConstraints.WEST;
+ labelConstraints.insets = new Insets(1, 2, 1, 2);
+
+ GridBagConstraints textFieldConstraints = new GridBagConstraints();
+ textFieldConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
+ textFieldConstraints.weightx = 1.0;
+ textFieldConstraints.anchor = GridBagConstraints.WEST;
+ textFieldConstraints.insets = labelConstraints.insets;
+
+ GridBagConstraints panelConstraints = new GridBagConstraints();
+ panelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ panelConstraints.fill = GridBagConstraints.HORIZONTAL;
+ panelConstraints.weightx = 1.0;
+ panelConstraints.weighty = 0.0;
+ panelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ panelConstraints.insets = labelConstraints.insets;
+
+ GridBagConstraints okButtonConstraints = new GridBagConstraints();
+ okButtonConstraints.weightx = 1.0;
+ okButtonConstraints.weighty = 1.0;
+ okButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ okButtonConstraints.insets = new Insets(4, 4, 8, 4);
+
+ GridBagConstraints cancelButtonConstraints = new GridBagConstraints();
+ cancelButtonConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ cancelButtonConstraints.weighty = 1.0;
+ cancelButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ cancelButtonConstraints.insets = okButtonConstraints.insets;
+
+ GridBagLayout layout = new GridBagLayout();
+
+ Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
+
+ // Create the panel with the explanation.
+ JTextArea explanationTextArea = new JTextArea(explanation, 3, 0);
+ explanationTextArea.setOpaque(false);
+ explanationTextArea.setEditable(false);
+ explanationTextArea.setLineWrap(true);
+ explanationTextArea.setWrapStyleWord(true);
+
+ // Create the filter labels.
+ JLabel filterLabel = new JLabel(msg("nameFilter"));
+ JLabel jarFilterLabel = new JLabel(msg("jarNameFilter"));
+ JLabel warFilterLabel = new JLabel(msg("warNameFilter"));
+ JLabel earFilterLabel = new JLabel(msg("earNameFilter"));
+ JLabel zipFilterLabel = new JLabel(msg("zipNameFilter"));
+
+ // Create the filter panel.
+ JPanel filterPanel = new JPanel(layout);
+ filterPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("filters")));
+
+ filterPanel.add(explanationTextArea, textConstraints);
+
+ filterPanel.add(tip(filterLabel, "nameFilterTip"), labelConstraints);
+ filterPanel.add(tip(filterTextField, "fileNameFilterTip"), textFieldConstraints);
+
+ filterPanel.add(tip(jarFilterLabel, "jarNameFilterTip"), labelConstraints);
+ filterPanel.add(tip(jarFilterTextField, "fileNameFilterTip"), textFieldConstraints);
+
+ filterPanel.add(tip(warFilterLabel, "warNameFilterTip"), labelConstraints);
+ filterPanel.add(tip(warFilterTextField, "fileNameFilterTip"), textFieldConstraints);
+
+ filterPanel.add(tip(earFilterLabel, "earNameFilterTip"), labelConstraints);
+ filterPanel.add(tip(earFilterTextField, "fileNameFilterTip"), textFieldConstraints);
+
+ filterPanel.add(tip(zipFilterLabel, "zipNameFilterTip"), labelConstraints);
+ filterPanel.add(tip(zipFilterTextField, "fileNameFilterTip"), textFieldConstraints);
+
+
+ JButton okButton = new JButton(msg("ok"));
+ okButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ returnValue = APPROVE_OPTION;
+ hide();
+ }
+ });
+
+ JButton cancelButton = new JButton(msg("cancel"));
+ cancelButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ hide();
+ }
+ });
+
+ // Add all panels to the main panel.
+ JPanel mainPanel = new JPanel(layout);
+ mainPanel.add(filterPanel, panelConstraints);
+ mainPanel.add(okButton, okButtonConstraints);
+ mainPanel.add(cancelButton, cancelButtonConstraints);
+
+ getContentPane().add(mainPanel);
+ }
+
+
+ /**
+ * Sets the filter to be represented in this dialog.
+ */
+ public void setFilter(List filter)
+ {
+ filterTextField.setText(filter != null ? ListUtil.commaSeparatedString(filter, true) : DEFAULT_FILTER);
+ }
+
+
+ /**
+ * Returns the filter currently represented in this dialog.
+ */
+ public List getFilter()
+ {
+ String filter = filterTextField.getText();
+
+ return filter.equals(DEFAULT_FILTER) ? null : ListUtil.commaSeparatedList(filter);
+ }
+
+
+ /**
+ * Sets the jar filter to be represented in this dialog.
+ */
+ public void setJarFilter(List filter)
+ {
+ jarFilterTextField.setText(filter != null ? ListUtil.commaSeparatedString(filter, true) : DEFAULT_JAR_FILTER);
+ }
+
+
+ /**
+ * Returns the jar filter currently represented in this dialog.
+ */
+ public List getJarFilter()
+ {
+ String filter = jarFilterTextField.getText();
+
+ return filter.equals(DEFAULT_JAR_FILTER) ? null : ListUtil.commaSeparatedList(filter);
+ }
+
+
+ /**
+ * Sets the war filter to be represented in this dialog.
+ */
+ public void setWarFilter(List filter)
+ {
+ warFilterTextField.setText(filter != null ? ListUtil.commaSeparatedString(filter, true) : DEFAULT_WAR_FILTER);
+ }
+
+
+ /**
+ * Returns the war filter currently represented in this dialog.
+ */
+ public List getWarFilter()
+ {
+ String filter = warFilterTextField.getText();
+
+ return filter.equals(DEFAULT_WAR_FILTER) ? null : ListUtil.commaSeparatedList(filter);
+ }
+
+
+ /**
+ * Sets the ear filter to be represented in this dialog.
+ */
+ public void setEarFilter(List filter)
+ {
+ earFilterTextField.setText(filter != null ? ListUtil.commaSeparatedString(filter, true) : DEFAULT_EAR_FILTER);
+ }
+
+
+ /**
+ * Returns the ear filter currently represented in this dialog.
+ */
+ public List getEarFilter()
+ {
+ String filter = earFilterTextField.getText();
+
+ return filter.equals(DEFAULT_EAR_FILTER) ? null : ListUtil.commaSeparatedList(filter);
+ }
+
+
+ /**
+ * Sets the zip filter to be represented in this dialog.
+ */
+ public void setZipFilter(List filter)
+ {
+ zipFilterTextField.setText(filter != null ? ListUtil.commaSeparatedString(filter, true) : DEFAULT_ZIP_FILTER);
+ }
+
+
+ /**
+ * Returns the zip filter currently represented in this dialog.
+ */
+ public List getZipFilter()
+ {
+ String filter = zipFilterTextField.getText();
+
+ return filter.equals(DEFAULT_ZIP_FILTER) ? null : ListUtil.commaSeparatedList(filter);
+ }
+
+
+ /**
+ * Shows this dialog. This method only returns when the dialog is closed.
+ *
+ * @return CANCEL_OPTION
or APPROVE_OPTION
,
+ * depending on the choice of the user.
+ */
+ public int showDialog()
+ {
+ returnValue = CANCEL_OPTION;
+
+ // Open the dialog in the right place, then wait for it to be closed,
+ // one way or another.
+ pack();
+ setLocationRelativeTo(getOwner());
+ show();
+
+ return returnValue;
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+}
diff --git a/src/proguard/gui/GUIResources.java b/src/proguard/gui/GUIResources.java
new file mode 100644
index 000000000..3d7c6c65d
--- /dev/null
+++ b/src/proguard/gui/GUIResources.java
@@ -0,0 +1,56 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+
+
+/**
+ * This class provides some utility methods for working with resource bundles.
+ *
+ * @author Eric Lafortune
+ */
+class GUIResources
+{
+ private static final ResourceBundle messages = ResourceBundle.getBundle(GUIResources.class.getName());
+ private static final MessageFormat formatter = new MessageFormat("");
+
+
+ /**
+ * Returns an internationalized message, based on its key.
+ */
+ public static String getMessage(String messageKey)
+ {
+ return messages.getString(messageKey);
+ }
+
+
+ /**
+ * Returns an internationalized, formatted message, based on its key, with
+ * the given arguments.
+ */
+ public static String getMessage(String messageKey, Object[] messageArguments)
+ {
+ formatter.applyPattern(messages.getString(messageKey));
+ return formatter.format(messageArguments);
+ }
+}
diff --git a/src/proguard/gui/GUIResources.properties b/src/proguard/gui/GUIResources.properties
new file mode 100644
index 000000000..5ab67de8b
--- /dev/null
+++ b/src/proguard/gui/GUIResources.properties
@@ -0,0 +1,643 @@
+# ProGuard -- shrinking, optimization, and obfuscation of Java class files.
+# Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+
+#
+# Tab names.
+#
+proGuardTab = ProGuard
+inputOutputTab = Input/Output
+shrinkingTab = Shrinking
+obfuscationTab = Obfuscation
+optimizationTab = Optimization
+informationTab = Information
+processTab = Process
+reTraceTab = ReTrace
+
+#
+# Splash text.
+#
+developed = Developed by Eric Lafortune
+shrinking = Shrinking
+optimization = Optimization
+obfuscation = Obfuscation
+preverification = Preverification
+
+#
+# Panel titles.
+#
+welcome = Welcome to ProGuard, version 4.9
+options = Options
+keepAdditional = Keep additional classes and class members
+keepNamesAdditional = Keep additional class names and class member names
+assumeNoSideEffectsAdditional = Assume no side effects for additional methods
+whyAreYouKeeping = Why are you keeping
+preverificationAndTargeting = Preverification and targeting
+consistencyAndCorrectness = Consistency and correctness
+processingConsole = Processing console
+reTraceSettings = ReTrace settings
+deobfuscatedStackTrace = De-obfuscated stack trace
+
+keepAdditionalTip = \
+ If required, keep additional classes, fields, and methods as entry points.
+keepNamesAdditionalTip = \
+ If required, keep the names of additional classes, fields, and methods.
+assumeNoSideEffectsAdditionalTip = \
+ Optionally specify additional methods that don't have any side effects.
\
+ Only add entries if you know what you're doing!
+whyAreYouKeepingTip = \
+ Ask ProGuard why it is keeping certain classes, fields, or methods.
+
+#
+# Info texts.
+#
+proGuardInfo = \
+ ProGuard is a free class file shrinker, optimizer, obfuscator, and preverifier.\
+
\
+ You can then process your code right away, or you can run ProGuard from the \
+ command line using your saved configuration.\
+
\
+ Professional support by Saikoa: \
+ http://www.saikoa.com/\
+
\
+ Copyright © 2002-2013.
+
+processingInfo = \
+ You can now start processing your code, \
+ or you can run ProGuard from the command line using your saved configuration.
+
+reTraceInfo = \
+ If you had ProGuard write out a mapping file, \
+ you can de-obfuscate your obfuscated stack traces with ReTrace!\
+ \n\n\
+ You can load an obfuscated stack trace from a file, \
+ or you can paste it straight into the text area above.
+
+#
+# Titles and labels corresponding to common ProGuard options.
+#
+programJars = Program jars, wars, ears, zips, and directories
+libraryJars = Library jars, wars, ears, zips, and directories
+
+shrink = Shrink
+printUsage = Print usage
+
+optimize = Optimize
+allowAccessModification = Allow access modification
+mergeInterfacesAggressively = Merge interfaces aggressively
+optimizations = Optimizations
+optimizationPasses = Optimization passes
+
+obfuscate = Obfuscate
+printMapping = Print mapping
+applyMapping = Apply mapping
+obfuscationDictionary = Obfuscation dictionary
+classObfuscationDictionary = Class obfuscation dictionary
+packageObfuscationDictionary = Package obfuscation dictionary
+overloadAggressively = Overload aggressively
+useUniqueClassMemberNames = Use unique class member names
+keepPackageNames = Keep package names
+flattenPackageHierarchy = Flatten package hierarchy
+repackageClasses = Repackage classes
+useMixedCaseClassNames = Use mixed-case class names
+keepAttributes = Keep attributes
+keepParameterNames = Keep parameter names
+renameSourceFileAttribute = Rename SourceFile attribute
+adaptClassStrings = Adapt class strings
+adaptResourceFileNames = Adapt resource file names
+adaptResourceFileContents = Adapt resource file contents
+
+preverify = Preverify
+microEdition = Micro Edition
+
+verbose = Verbose
+note = Note potential mistakes in the configuration
+warn = Warn about possibly erroneous input
+ignoreWarnings = Ignore warnings about possibly erroneous input
+skipNonPublicLibraryClasses = Skip non-public library classes
+skipNonPublicLibraryClassMembers = Skip non-public library class members
+keepDirectories = Keep directories
+forceProcessing = Force processing
+target = Target
+targets = 1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7
+printSeeds = Print seeds
+printConfiguration = Print configuration
+dump = Print class files
+
+mappingFile = Mapping file
+obfuscatedStackTrace = Obfuscated stack trace
+
+programJarsTip = \
+ The input jars (wars, ears, zips, directories), followed by
\
+ their corresponding output jars (wars, ears, zips, directories).
+libraryJarsTip = \
+ The library jars (wars, ears, zips, directories), on which the program jars depend.
\
+ The library jars are required for processing, but they are not copied to the output.
+
+shrinkTip = \
+ Remove unused classes, fields, and methods from the output.
+printUsageTip = \
+ Print out the list of unused classes, fields, and methods.
+
+optimizeTip = \
+ Optimize the bytecode of the processed classes.
+allowAccessModificationTip = \
+ Allow the optimization step to modify the access modifiers of classes, fields, and methods.
+mergeInterfacesAggressivelyTip = \
+ Allow interfaces to be merged, even if their implementations don't implement all
\
+ interface methods. This is not allowed in the Java language, but it is allowed in bytecode.
+optimizationsTip = \
+ Specify the types of optimizations to be performed.
+optimizationsFilterTip = \
+ A filter for the names of the optimizations to be performed.
+optimizationsSelectTip = \
+ Select from the currently available optimizations...
+optimizationPassesTip = \
+ Specify the number of optimization passes to be performed.
+
+obfuscateTip = \
+ Obfuscate the names of the processed classes, fields, and methods.
+printMappingTip = \
+ Print out the obfuscation mapping of original names to obfuscated names.
+applyMappingTip = \
+ Apply the given mapping of original names to obfuscated names.
+obfuscationDictionaryTip = \
+ Use the words in the given file for obfuscating field names and method names.
+classObfuscationDictionaryTip = \
+ Use the words in the given file for obfuscating class names.
+packageObfuscationDictionaryTip = \
+ Use the words in the given file for obfuscating package names.
+overloadAggressivelyTip = \
+ Allow fields and methods to get the same obfuscated names, even if only their types or
\
+ return types differ. This is not allowed in the Java language, but it is allowed in bytecode.
+useUniqueClassMemberNamesTip = \
+ Make sure fields and methods get the same obfuscation mapping across classes, even
\
+ if they are unrelated. This is advisable if the output is to be obfuscated incrementally.
+keepPackageNamesTip = \
+ Keep the specified package names from being obfuscated.
+packageNamesTip = \
+ An optional comma-separated list of package names,
\
+ e.g. myapplication,mylibrary.**
\
+ Possible wildcards:\
+ \
+
\
+ The negator ?
for any single character, except the package separator.\
+ *
for any number of any characters, except the package separator.\
+ **
for any number of any characters.\
+ !
is also supported.
+flattenPackageHierarchyTip = \
+ Move all packages that are renamed into the given parent package.
+repackageClassesTip = \
+ Move all classes that are renamed into the given package.
+packageTip = \
+ The optional package name.
+useMixedCaseClassNamesTip = \
+ Generate mixed-case obfucated class names. This will complicate unpacking
\
+ the resulting jars on case-insensitive file systems, should that be necessary.
+keepAttributesTip = \
+ Keep the specified optional class file attributes.
+attributesTip = \
+ An optional comma-separated list of class file attributes.\
+ \
+
\
+ The wildcard *
and the negator !
are allowed.
+keepParameterNamesTip = \
+ Keep parameter names and types in "LocalVariable*Table" attributes\
+ in methods that are not obfuscated.
+renameSourceFileAttributeTip = \
+ Put the given string in the "SourceFile" attribute of the processed class files.
\
+ It will appear as the file name of the classes in stack traces.
+sourceFileAttributeTip = \
+ The replacement "SourceFile" string.
+adaptClassStringsTip = \
+ Adapt string constants in the specified classes, based
\
+ on the obfuscated names of corresponding classes.
+adaptResourceFileNamesTip = \
+ Rename the specified resource files, based on the
\
+ obfuscated names of the corresponding class files.
+adaptResourceFileContentsTip = \
+ Adapt the contents of the specified resource files, based
\
+ on the obfuscated names of the processed classes.
+fileNameFilterTip = \
+ A filter on file names,
\
+ e.g. mydirectory1/**,mydirectory2/**
\
+ Possible wildcards:\
+ \
+
\
+ The negator ?
for any single character, except the directory separator.\
+ *
for any number of any characters, except the directory separator.\
+ **
for any number of any characters.\
+ !
is also supported.
+
+preverifyTip = \
+ Preverify the processed classes, for Java Micro Edition or for Java 6.
+microEditionTip = \
+ Target Java Micro Edition.
+
+verboseTip = \
+ Print out verbose messages while processing.
+noteTip = \
+ Print out notes about special or unusual input.
+noteFilterTip = \
+ A filter matching classes for which no notes should be printed.
+warnTip = \
+ Print out warnings about possibly erroneous input.
\
+ Only unset this option if you know what you're doing!
+warnFilterTip = \
+ A filter matching classes for which no warnings should be printed.
+ignoreWarningsTip = \
+ Ignore any warnings about possibly erroneous input.
\
+ Only set this option if you know what you're doing!
+skipNonPublicLibraryClassesTip = \
+ Skip reading non-public library classes, for efficiency.
\
+ You may have to unset this option if ProGuard complains about missing classes.
+skipNonPublicLibraryClassMembersTip = \
+ Skip reading non-public library fields and methods, for efficiency.
\
+ You may have to unset this option if ProGuard complains about missing class members.
+keepDirectoriesTip = \
+ Keep the specified directories in the output jars, wars, ears, zips, or directories.
+directoriesTip = \
+ A filter on directory names,
\
+ e.g. mydirectory1,mydirectory2/**
\
+ Possible wildcards:\
+ \
+
\
+ The negator ?
for any single character, except the directory separator.\
+ *
for any number of any characters, except the directory separator.\
+ **
for any number of any characters.\
+ !
is also supported.
+forceProcessingTip = \
+ Always process the input, even if the output seems up to date.
+targetTip = \
+ Target the specified version of Java.
+printSeedsTip = \
+ Print out the list of kept classes, fields, and methods.
+printConfigurationTip = \
+ Print out the configuration.
+dumpTip = \
+ Print out the internal structure of the processed class files.
+
+mappingFileTip = \
+ The file containing the mapping of original names to obfuscated names.
+obfuscatedStackTraceTip = \
+ A stack trace produced by previously obfuscated code.
+
+#
+# Titles and labels corresponding to ProGuard keep options.
+#
+keepTitle = Keep
+
+keep = Keep classes and class members
+keepClassMembers = Keep class members only
+keepClassesWithMembers = Keep classes and class members, if members are present
+
+allowTitle = Allow
+
+allowShrinking = Allow shrinking
+allowOptimization = Allow optimization
+allowObfuscation = Allow obfuscation
+
+keepTitleTip = Keep the specified classes and/or their fields and methods.
+
+keepTip = \
+ Keep the specified classes, fields, and methods as entry points.
\
+ This is the most common option.
+keepClassMembersTip = \
+ Only keep the specified fields and methods as entry points.
+keepClassesWithMembersTip = \
+ Keep the specified classes, fields, and methods,
\
+ on the condition that the fields and methods are present.
+
+allowTitleTip = \
+ Optionally relax keeping the specified classes, fields, and methods.
\
+ These are advanced options.
+
+allowShrinkingTip = \
+ Remove the specified classes, fields, and methods anyway, if they are not used.
+allowOptimizationTip = \
+ Optimize the specified classes, fields, and methods as entry points anyway.
\
+ Only set this option if you know what you're doing!
+allowObfuscationTip = \
+ Obfuscate the names of the specified classes, fields, and methods anyway.
\
+ Only set this option if you know what you're doing!
+
+#
+# Further keep titles and labels.
+#
+specifyClasses = Specify classes and class members...
+specifyFields = Specify fields...
+specifyMethods = Specify methods...
+
+comments = Comments
+access = Access
+required = Required
+not = Not
+dontCare = Don't care
+annotation = Annotation
+class = Class
+extendsImplementsAnnotation = Extends/implements class with annotation
+extendsImplementsClass = Extends/implements class
+classMembers = Class members
+
+extensionsOf = Extensions of
+specificationNumber = Specification #
+
+fieldType = Field type
+returnType = Return type
+name = Name
+argumentTypes = Argument types
+
+commentsTip = \
+ Optionally add a comment for this option in the configuration file.
+accessTip = \
+ Optionally place constraints on the access modifiers of this element.
\
+ E.g. only match public elements.
+requiredTip = \
+ The access modifier has to be set.
+notTip = \
+ The access modifier must not be set.
+dontCareTip = \
+ The access modifier is irrelevant.
+annotationTip = \
+ Optionally require the given annotation to be present on this element.
\
+ E.g. only match elements that have an annotation myPackage.MyAnnotation
.
\
+ This is an advanced option.
+classTip = \
+ The name of the class or interface.
+extendsImplementsAnnotationTip = \
+ Optionally require the given annotation to be present on the
\
+ extended or implemented class or interface.
\
+ E.g. only match classes that extend a class that has an annotation
\
+ myPackage.MyAnnotation
.
\
+ This is an advanced option.
+extendsImplementsClassTip = \
+ Optionally require the class to implement or extend the given class or interface.
\
+ E.g. only match classes that implement an interface myPackage.MyInterface
.
+classMembersTip = \
+ Optionally keep fields and methods as entry points in the matching class or classes.
\
+ E.g. keep all public 'get*
' methods as entry points.
+
+fieldTypeTip = The field type.
+returnTypeTip = The method return type, if any.
+nameTip = The name.
+argumentTypesTip = The method argument types, if any.
+
+classNameTip = \
+ The class name, e.g. myPackage.MyClass
\
+ Possible wildcards:\
+ \
+
+classNamesTip = \
+ A regular expression to further constrain the class names,?
for any single character, except the package separator.\
+ *
for any number of any characters, except the package separator.\
+ **
for any number of any characters.\
+
\
+ e.g. myPackage1.MyClass,myPackage2.**
\
+ Possible wildcards:\
+ \
+
\
+ The negator ?
for any single character, except the package separator.\
+ *
for any number of any characters, except the package separator.\
+ **
for any number of any characters.\
+ !
is also supported.
+typeTip = \
+ The type, e.g. int
, or java.lang.String[]
\
+ Possible wildcards:\
+ \
+
+fieldNameTip = \
+ The field name, e.g. %
for any primitive type.\
+ ?
for any single character, except the package separator.\
+ *
for any number of any characters, except the package separator.\
+ **
for any number of any characters.\
+ ***
(or empty) for any type.\
+ myField
\
+ Possible wildcards:\
+ \
+
+methodNameTip = \
+ The method name, e.g. ?
for any single character.\
+ *
for any number of any characters.\
+ myMethod
\
+ Possible wildcards:\
+ \
+
+argumentTypes2Tip = \
+ The comma-separated list of argument types,?
for any single character.\
+ *
for any number of any characters.\
+
\
+ e.g. java.lang.String[],int,boolean
\
+ Possible wildcards:\
+ \
+
+
+#
+# Titles and labels corresponding to optimization options.
+#
+selectOptimizations = Select optimizations...
+
+field = Field
+method = Method
+code = Code
+
+class_marking_finalTip = \
+ Mark classes as final, whenever possible.
+class_merging_verticalTip = \
+ Merge classes vertically in the class hierarchy, whenever possible.
+class_merging_horizontalTip = \
+ Merge classes horizontally in the class hierarchy, whenever possible.
+field_removal_writeonlyTip = \
+ Remove write-only fields.
+field_marking_privateTip = \
+ Mark fields as private, whenever possible.
+field_propagation_valueTip = \
+ Propagate the values of fields across methods.
+method_marking_privateTip = \
+ Mark methods as private, whenever possible (devirtualization).
+method_marking_staticTip = \
+ Mark methods as static, whenever possible (devirtualization).
+method_marking_finalTip = \
+ Mark methods as final, whenever possible.
+method_removal_parameterTip = \
+ Remove unused method parameters.
+method_propagation_parameterTip = \
+ Propagate the values of method parameters from method invocations to \
+ the invoked methods.
+method_propagation_returnvalueTip = \
+ Propagate the values of method return values from methods to their \
+ invocations.
+method_inlining_shortTip = \
+ Inline short methods.
+method_inlining_uniqueTip = \
+ Inline methods that are only called once.
+method_inlining_tailrecursionTip = \
+ Simplify tail recursion calls, whenever possible.
+code_mergingTip = \
+ Merge identical blocks of code by modifying branch targets.
+code_simplification_variableTip = \
+ Perform peephole optimizations for variable loading and storing.
+code_simplification_arithmeticTip = \
+ Perform peephole optimizations for arithmetic instructions.
+code_simplification_castTip = \
+ Perform peephole optimizations for casting operations.
+code_simplification_fieldTip = \
+ Perform peephole optimizations for field loading and storing.
+code_simplification_branchTip = \
+ Perform peephole optimizations for branch instructions.
+code_simplification_stringTip = \
+ Perform peephole optimizations for constant strings.
+code_simplification_advancedTip = \
+ Simplify code based on control flow analysis and data flow analysis.
+code_removal_advancedTip = \
+ Remove dead code based on control flow analysis and data flow analysis.
+code_removal_simpleTip = \
+ Remove dead code based on a simple control flow analysis.
+code_removal_variableTip = \
+ Remove unused variables from the local variable frame.
+code_removal_exceptionTip = \
+ Remove exceptions with empty try blocks.
+code_allocation_variableTip = \
+ Optimize variable allocation on the local variable frame.
+
+
+#
+# File selection titles.
+#
+selectConfigurationFile = Select a configuration file...
+saveConfigurationFile = Save configuration...
+selectUsageFile = Select a usage output file...
+selectPrintMappingFile = Select an output mapping file...
+selectApplyMappingFile = Select an input mapping file...
+selectObfuscationDictionaryFile = Select an obfuscation dictionary...
+selectSeedsFile = Select a seeds output file...
+selectDumpFile = Select a class dump file...
+selectStackTraceFile = Select a stack trace file...
+
+cantOpenConfigurationFile = Can''t open the configuration file [{0}]
+cantParseConfigurationFile = Can''t parse the configuration file [{0}]
+cantSaveConfigurationFile = Can''t save the configuration file [{0}]
+cantOpenStackTraceFile = Can''t open the stack trace file [{0}]
+
+jarWarEarZipExtensions = *.jar, *.war, *.ear, *.zip (archives and directories)
+proExtension = *.pro (ProGuard configurations)
+
+addJars = Add one or more jars or directories...
+chooseJars = Choose different jars or directories...
+enterFilter = Optionally filter the file names contained in the selected entries.
+
+filters = Filters
+nameFilter = File name filter
+jarNameFilter = Jar name filter
+warNameFilter = War name filter
+earNameFilter = Ear name filter
+zipNameFilter = Zip name filter
+
+outputFileTip = The optional output file.
+inputFileTip = The input file.
+
+nameFilterTip = A filter on plain class file names and resource file names.
+jarNameFilterTip = A filter on jar file names.
+warNameFilterTip = A filter on war file names.
+earNameFilterTip = A filter on ear file names.
+zipNameFilterTip = A filter on zip file names.
+
+#
+# Simple button texts.
+#
+previous = Previous
+next = Next
+browse = Browse...
+advanced = Advanced options
+basic = Basic options
+selectAll = Select all
+selectNone = Select none
+ok = Ok
+cancel = Cancel
+
+add = Add...
+addInput = Add input...
+addOutput = Add output...
+edit = Edit...
+filter = Filter...
+remove = Remove
+moveUp = Move up
+moveDown = Move down
+
+moveToLibraries = Move to libraries
+moveToProgram = Move to program
+
+addField = Add field...
+addMethod = Add method...
+
+select = Select...
+
+loadConfiguration = Load configuration...
+viewConfiguration = View configuration
+saveConfiguration = Save configuration...
+loadStackTrace = Load stack trace...
+process = Process!
+reTrace = ReTrace!
+
+advancedTip = Toggle between showing basic options and advanced options.
+
+addInputTip = Add an input jar, war, ear, zip, or directory.
+addOutputTip = Add an output jar, war, ear, zip, or directory.
+addTip = Add an entry.
+editTip = Edit the selected entries.
+filterTip = Put filters on the contents of the selected entries.
+removeTip = Remove the selected entries.
+moveUpTip = Move the selected entries up in the list.
+moveDownTip = Move the selected entries down in the list.
+
+moveToLibrariesTip = Move to selected entries to the libraries.
+moveToProgramTip = Move to selected entries to the program.
+
+addFieldTip = Add a field to the specification.
+addMethodTip = Add a method to the specification.
+
+loadConfigurationTip = Optionally load an initial configuration.
+viewConfigurationTip = View the current configuration.
+saveConfigurationTip = Save the current configuration.
+loadStackTraceTip = Load a stack trace from a file.
+processTip = Start processing, based on the current configuration.
+reTraceTip = De-obfuscate the given stack trace.
+
+#
+# Progress messages and error messages.
+#
+warning = Warning
+outOfMemory = Out of memory
+outOfMemoryInfo = \n\
+ You should run the ProGuard GUI with a larger java heap size, \
+ with a command like\
+ \n\n\t\
+ java -Xms128m -Xmx192m -jar proguardgui.jar {0}\
+ \n\n\
+ or you can try running ProGuard from the command line. \
+ with a command like\
+ \n\n\t\
+ java -jar proguard.jar @{0}
+sampleConfigurationFileName = configuration.pro
+errorProcessing = Error during processing
+errorReTracing = Error during retracing
diff --git a/src/proguard/gui/KeepSpecificationsPanel.java b/src/proguard/gui/KeepSpecificationsPanel.java
new file mode 100644
index 000000000..908f02895
--- /dev/null
+++ b/src/proguard/gui/KeepSpecificationsPanel.java
@@ -0,0 +1,81 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.*;
+
+import javax.swing.*;
+
+/**
+ * This %
for any primitive type.\
+ ?
for any single character, except the package separator.\
+ *
for any number of any characters, except the package separator.\
+ **
for any number of any characters.\
+ ***
for any type.\
+ ...
for any number of any arguments.\
+ ListPanel
allows the user to add, edit, move, and remove
+ * KeepClassSpecification entries in a list.
+ *
+ * @author Eric Lafortune
+ */
+final class KeepSpecificationsPanel extends ClassSpecificationsPanel
+{
+ private final boolean markClasses;
+ private final boolean markConditionally;
+ private final boolean allowShrinking;
+ private final boolean allowOptimization;
+ private final boolean allowObfuscation;
+
+
+ public KeepSpecificationsPanel(JFrame owner,
+ boolean markClasses,
+ boolean markConditionally,
+ boolean allowShrinking,
+ boolean allowOptimization,
+ boolean allowObfuscation)
+ {
+ super(owner, true);
+
+ this.markClasses = markClasses;
+ this.markConditionally = markConditionally;
+ this.allowShrinking = allowShrinking;
+ this.allowOptimization = allowOptimization;
+ this.allowObfuscation = allowObfuscation;
+ }
+
+
+ // Factory methods for ClassSpecificationsPanel.
+
+ protected ClassSpecification createClassSpecification()
+ {
+ return new KeepClassSpecification(markClasses,
+ markConditionally,
+ allowShrinking,
+ allowOptimization,
+ allowObfuscation);
+ }
+
+
+ protected void setClassSpecification(ClassSpecification classSpecification)
+ {
+ classSpecificationDialog.setKeepSpecification((KeepClassSpecification)classSpecification);
+ }
+
+
+ protected ClassSpecification getClassSpecification()
+ {
+ return classSpecificationDialog.getKeepSpecification();
+ }
+}
diff --git a/src/proguard/gui/ListPanel.java b/src/proguard/gui/ListPanel.java
new file mode 100644
index 000000000..19a0c4dc1
--- /dev/null
+++ b/src/proguard/gui/ListPanel.java
@@ -0,0 +1,341 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.util.List;
+import java.util.*;
+
+import javax.swing.*;
+import javax.swing.event.*;
+
+/**
+ * This Jpanel
allows the user to move and remove entries in a
+ * list and between lists. Extensions of this class should add buttons to add
+ * and possibly edit entries, and to set and get the resulting list.
+ *
+ * @author Eric Lafortune
+ */
+abstract class ListPanel extends JPanel
+{
+ protected final DefaultListModel listModel = new DefaultListModel();
+ protected final JList list = new JList(listModel);
+
+ protected int firstSelectionButton = 2;
+
+
+ protected ListPanel()
+ {
+ GridBagLayout layout = new GridBagLayout();
+ setLayout(layout);
+
+ GridBagConstraints listConstraints = new GridBagConstraints();
+ listConstraints.gridheight = GridBagConstraints.REMAINDER;
+ listConstraints.fill = GridBagConstraints.BOTH;
+ listConstraints.weightx = 1.0;
+ listConstraints.weighty = 1.0;
+ listConstraints.anchor = GridBagConstraints.NORTHWEST;
+ listConstraints.insets = new Insets(0, 2, 0, 2);
+
+ // Make sure some buttons are disabled or enabled depending on whether
+ // the selection is empty or not.
+ list.addListSelectionListener(new ListSelectionListener()
+ {
+ public void valueChanged(ListSelectionEvent e)
+ {
+ enableSelectionButtons();
+ }
+ });
+
+ add(new JScrollPane(list), listConstraints);
+
+ // something like the following calls are up to the extending class:
+ //addAddButton();
+ //addEditButton();
+ //addRemoveButton();
+ //addUpButton();
+ //addDownButton();
+ //
+ //enableSelectionButtons();
+ }
+
+
+ protected void addRemoveButton()
+ {
+ JButton removeButton = new JButton(msg("remove"));
+ removeButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ // Remove the selected elements.
+ removeElementsAt(list.getSelectedIndices());
+ }
+ });
+
+ addButton(tip(removeButton, "removeTip"));
+ }
+
+
+ protected void addUpButton()
+ {
+ JButton upButton = new JButton(msg("moveUp"));
+ upButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ int[] selectedIndices = list.getSelectedIndices();
+ if (selectedIndices.length > 0 &&
+ selectedIndices[0] > 0)
+ {
+ // Move the selected elements up.
+ moveElementsAt(selectedIndices, -1);
+ }
+ }
+ });
+
+ addButton(tip(upButton, "moveUpTip"));
+ }
+
+
+ protected void addDownButton()
+ {
+ JButton downButton = new JButton(msg("moveDown"));
+ downButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ int[] selectedIndices = list.getSelectedIndices();
+ if (selectedIndices.length > 0 &&
+ selectedIndices[selectedIndices.length-1] < listModel.getSize()-1)
+ {
+ // Move the selected elements down.
+ moveElementsAt(selectedIndices, 1);
+ }
+ }
+ });
+
+ addButton(tip(downButton, "moveDownTip"));
+ }
+
+
+ /**
+ * Adds a button that allows to copy or move entries to another ListPanel.
+ *
+ * @param buttonTextKey the button text key.
+ * @param tipKey the tool tip key.
+ * @param panel the other ListPanel.
+ */
+ public void addCopyToPanelButton(String buttonTextKey,
+ String tipKey,
+ final ListPanel panel)
+ {
+ JButton moveButton = new JButton(msg(buttonTextKey));
+ moveButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ int[] selectedIndices = list.getSelectedIndices();
+ Object[] selectedElements = list.getSelectedValues();
+
+ // Remove the selected elements from this panel.
+ removeElementsAt(selectedIndices);
+
+ // Add the elements to the other panel.
+ panel.addElements(selectedElements);
+ }
+ });
+
+ addButton(tip(moveButton, tipKey));
+ }
+
+
+ protected void addButton(JComponent button)
+ {
+ GridBagConstraints buttonConstraints = new GridBagConstraints();
+ buttonConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ buttonConstraints.fill = GridBagConstraints.HORIZONTAL;
+ buttonConstraints.anchor = GridBagConstraints.NORTHWEST;
+ buttonConstraints.insets = new Insets(0, 2, 0, 2);
+
+ add(button, buttonConstraints);
+ }
+
+
+ /**
+ * Returns a list of all right-hand side buttons.
+ */
+ public List getButtons()
+ {
+ List list = new ArrayList(getComponentCount()-1);
+
+ // Add all buttons.
+ for (int index = 1; index < getComponentCount(); index++)
+ {
+ list.add(getComponent(index));
+ }
+
+ return list;
+ }
+
+
+ protected void addElement(Object element)
+ {
+ listModel.addElement(element);
+
+ // Make sure it is selected.
+ list.setSelectedIndex(listModel.size() - 1);
+ }
+
+
+ protected void addElements(Object[] elements)
+ {
+ // Add the elements one by one.
+ for (int index = 0; index < elements.length; index++)
+ {
+ listModel.addElement(elements[index]);
+ }
+
+ // Make sure they are selected.
+ int[] selectedIndices = new int[elements.length];
+ for (int index = 0; index < selectedIndices.length; index++)
+ {
+ selectedIndices[index] =
+ listModel.size() - selectedIndices.length + index;
+ }
+ list.setSelectedIndices(selectedIndices);
+ }
+
+
+ protected void moveElementsAt(int[] indices, int offset)
+ {
+ // Remember the selected elements.
+ Object[] selectedElements = list.getSelectedValues();
+
+ // Remove the selected elements.
+ removeElementsAt(indices);
+
+ // Update the element indices.
+ for (int index = 0; index < indices.length; index++)
+ {
+ indices[index] += offset;
+ }
+
+ // Reinsert the selected elements.
+ insertElementsAt(selectedElements, indices);
+ }
+
+
+ protected void insertElementsAt(Object[] elements, int[] indices)
+ {
+ for (int index = 0; index < elements.length; index++)
+ {
+ listModel.insertElementAt(elements[index], indices[index]);
+ }
+
+ // Make sure they are selected.
+ list.setSelectedIndices(indices);
+ }
+
+
+ protected void setElementAt(Object element, int index)
+ {
+ listModel.setElementAt(element, index);
+
+ // Make sure it is selected.
+ list.setSelectedIndex(index);
+ }
+
+
+ protected void setElementsAt(Object[] elements, int[] indices)
+ {
+ for (int index = 0; index < elements.length; index++)
+ {
+ listModel.setElementAt(elements[index], indices[index]);
+ }
+
+ // Make sure they are selected.
+ list.setSelectedIndices(indices);
+ }
+
+
+ protected void removeElementsAt(int[] indices)
+ {
+ for (int index = indices.length - 1; index >= 0; index--)
+ {
+ listModel.removeElementAt(indices[index]);
+ }
+
+ // Make sure nothing is selected.
+ list.clearSelection();
+
+ // Make sure the selection buttons are properly enabled,
+ // since the above method doesn't seem to notify the listener.
+ enableSelectionButtons();
+ }
+
+
+ protected void removeAllElements()
+ {
+ listModel.removeAllElements();
+
+ // Make sure the selection buttons are properly enabled,
+ // since the above method doesn't seem to notify the listener.
+ enableSelectionButtons();
+ }
+
+
+ /**
+ * Enables or disables the buttons that depend on a selection.
+ */
+ protected void enableSelectionButtons()
+ {
+ boolean selected = !list.isSelectionEmpty();
+
+ // Loop over all components, except the list itself and the Add button.
+ for (int index = firstSelectionButton; index < getComponentCount(); index++)
+ {
+ getComponent(index).setEnabled(selected);
+ }
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+}
diff --git a/src/proguard/gui/MANIFEST.MF b/src/proguard/gui/MANIFEST.MF
new file mode 100644
index 000000000..05403b491
--- /dev/null
+++ b/src/proguard/gui/MANIFEST.MF
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Main-Class: proguard.gui.ProGuardGUI
+Class-Path: proguard.jar retrace.jar
diff --git a/src/proguard/gui/MemberSpecificationDialog.java b/src/proguard/gui/MemberSpecificationDialog.java
new file mode 100644
index 000000000..4bf72cacb
--- /dev/null
+++ b/src/proguard/gui/MemberSpecificationDialog.java
@@ -0,0 +1,509 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.MemberSpecification;
+import proguard.classfile.ClassConstants;
+import proguard.classfile.util.ClassUtil;
+import proguard.util.ListUtil;
+
+import javax.swing.*;
+import javax.swing.border.*;
+import java.awt.*;
+import java.awt.event.*;
+
+/**
+ * This JDialog
allows the user to enter a String.
+ *
+ * @author Eric Lafortune
+ */
+final class MemberSpecificationDialog extends JDialog
+{
+ /**
+ * Return value if the dialog is canceled (with the Cancel button or by
+ * closing the dialog window).
+ */
+ public static final int CANCEL_OPTION = 1;
+
+ /**
+ * Return value if the dialog is approved (with the Ok button).
+ */
+ public static final int APPROVE_OPTION = 0;
+
+
+ private final boolean isField;
+
+ private final JRadioButton[] publicRadioButtons;
+ private final JRadioButton[] privateRadioButtons;
+ private final JRadioButton[] protectedRadioButtons;
+ private final JRadioButton[] staticRadioButtons;
+ private final JRadioButton[] finalRadioButtons;
+ private final JRadioButton[] syntheticRadioButtons;
+
+ private JRadioButton[] volatileRadioButtons;
+ private JRadioButton[] transientRadioButtons;
+
+ private JRadioButton[] synchronizedRadioButtons;
+ private JRadioButton[] nativeRadioButtons;
+ private JRadioButton[] abstractRadioButtons;
+ private JRadioButton[] strictRadioButtons;
+ private JRadioButton[] bridgeRadioButtons;
+ private JRadioButton[] varargsRadioButtons;
+
+ private final JTextField annotationTypeTextField = new JTextField(20);
+ private final JTextField nameTextField = new JTextField(20);
+ private final JTextField typeTextField = new JTextField(20);
+ private final JTextField argumentTypesTextField = new JTextField(20);
+
+ private int returnValue;
+
+
+ public MemberSpecificationDialog(JDialog owner, boolean isField)
+ {
+ super(owner, msg(isField ? "specifyFields" : "specifyMethods"), true);
+ setResizable(true);
+
+ // Create some constraints that can be reused.
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.anchor = GridBagConstraints.WEST;
+ constraints.insets = new Insets(1, 2, 1, 2);
+
+ GridBagConstraints constraintsStretch = new GridBagConstraints();
+ constraintsStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsStretch.weightx = 1.0;
+ constraintsStretch.anchor = GridBagConstraints.WEST;
+ constraintsStretch.insets = constraints.insets;
+
+ GridBagConstraints constraintsLast = new GridBagConstraints();
+ constraintsLast.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLast.anchor = GridBagConstraints.WEST;
+ constraintsLast.insets = constraints.insets;
+
+ GridBagConstraints constraintsLastStretch = new GridBagConstraints();
+ constraintsLastStretch.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLastStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsLastStretch.weightx = 1.0;
+ constraintsLastStretch.anchor = GridBagConstraints.WEST;
+ constraintsLastStretch.insets = constraints.insets;
+
+ GridBagConstraints panelConstraints = new GridBagConstraints();
+ panelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ panelConstraints.fill = GridBagConstraints.HORIZONTAL;
+ panelConstraints.weightx = 1.0;
+ panelConstraints.weighty = 0.0;
+ panelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ panelConstraints.insets = constraints.insets;
+
+ GridBagConstraints stretchPanelConstraints = new GridBagConstraints();
+ stretchPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ stretchPanelConstraints.fill = GridBagConstraints.BOTH;
+ stretchPanelConstraints.weightx = 1.0;
+ stretchPanelConstraints.weighty = 1.0;
+ stretchPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ stretchPanelConstraints.insets = constraints.insets;
+
+ GridBagConstraints labelConstraints = new GridBagConstraints();
+ labelConstraints.anchor = GridBagConstraints.CENTER;
+ labelConstraints.insets = new Insets(2, 10, 2, 10);
+
+ GridBagConstraints lastLabelConstraints = new GridBagConstraints();
+ lastLabelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ lastLabelConstraints.anchor = GridBagConstraints.CENTER;
+ lastLabelConstraints.insets = labelConstraints.insets;
+
+ GridBagConstraints advancedButtonConstraints = new GridBagConstraints();
+ advancedButtonConstraints.weightx = 1.0;
+ advancedButtonConstraints.weighty = 1.0;
+ advancedButtonConstraints.anchor = GridBagConstraints.SOUTHWEST;
+ advancedButtonConstraints.insets = new Insets(4, 4, 8, 4);
+
+ GridBagConstraints okButtonConstraints = new GridBagConstraints();
+ okButtonConstraints.weightx = 1.0;
+ okButtonConstraints.weighty = 1.0;
+ okButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ okButtonConstraints.insets = advancedButtonConstraints.insets;
+
+ GridBagConstraints cancelButtonConstraints = new GridBagConstraints();
+ cancelButtonConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ cancelButtonConstraints.weighty = 1.0;
+ cancelButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ cancelButtonConstraints.insets = okButtonConstraints.insets;
+
+ GridBagLayout layout = new GridBagLayout();
+
+ Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
+
+ this.isField = isField;
+
+ // Create the access panel.
+ JPanel accessPanel = new JPanel(layout);
+ accessPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("access")));
+
+ accessPanel.add(Box.createGlue(), labelConstraints);
+ accessPanel.add(tip(new JLabel(msg("required")), "requiredTip"), labelConstraints);
+ accessPanel.add(tip(new JLabel(msg("not")), "notTip"), labelConstraints);
+ accessPanel.add(tip(new JLabel(msg("dontCare")), "dontCareTip"), labelConstraints);
+ accessPanel.add(Box.createGlue(), constraintsLastStretch);
+
+ publicRadioButtons = addRadioButtonTriplet("Public", accessPanel);
+ privateRadioButtons = addRadioButtonTriplet("Private", accessPanel);
+ protectedRadioButtons = addRadioButtonTriplet("Protected", accessPanel);
+ staticRadioButtons = addRadioButtonTriplet("Static", accessPanel);
+ finalRadioButtons = addRadioButtonTriplet("Final", accessPanel);
+ syntheticRadioButtons = addRadioButtonTriplet("Synthetic", accessPanel);
+
+ if (isField)
+ {
+ volatileRadioButtons = addRadioButtonTriplet("Volatile", accessPanel);
+ transientRadioButtons = addRadioButtonTriplet("Transient", accessPanel);
+ }
+ else
+ {
+ synchronizedRadioButtons = addRadioButtonTriplet("Synchronized", accessPanel);
+ nativeRadioButtons = addRadioButtonTriplet("Native", accessPanel);
+ abstractRadioButtons = addRadioButtonTriplet("Abstract", accessPanel);
+ strictRadioButtons = addRadioButtonTriplet("Strict", accessPanel);
+ bridgeRadioButtons = addRadioButtonTriplet("Bridge", accessPanel);
+ varargsRadioButtons = addRadioButtonTriplet("Varargs", accessPanel);
+ }
+
+ // Create the type panel.
+ JPanel typePanel = new JPanel(layout);
+ typePanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg(isField ? "fieldType" :
+ "returnType")));
+
+ typePanel.add(tip(typeTextField, "typeTip"), constraintsLastStretch);
+
+ // Create the annotation type panel.
+ final JPanel annotationTypePanel = new JPanel(layout);
+ annotationTypePanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("annotation")));
+
+ annotationTypePanel.add(tip(annotationTypeTextField, "classNameTip"), constraintsLastStretch);
+
+ // Create the name panel.
+ JPanel namePanel = new JPanel(layout);
+ namePanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("name")));
+
+ namePanel.add(tip(nameTextField, isField ? "fieldNameTip" :
+ "methodNameTip"), constraintsLastStretch);
+
+ // Create the arguments panel.
+ JPanel argumentsPanel = new JPanel(layout);
+ argumentsPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder,
+ msg("argumentTypes")));
+
+ argumentsPanel.add(tip(argumentTypesTextField, "argumentTypes2Tip"), constraintsLastStretch);
+
+ // Create the Advanced button.
+ final JButton advancedButton = new JButton(msg("basic"));
+ advancedButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ boolean visible = !annotationTypePanel.isVisible();
+
+ annotationTypePanel.setVisible(visible);
+
+ advancedButton.setText(msg(visible ? "basic" : "advanced"));
+
+ pack();
+ }
+ });
+ advancedButton.doClick();
+
+ // Create the Ok button.
+ JButton okButton = new JButton(msg("ok"));
+ okButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ returnValue = APPROVE_OPTION;
+ hide();
+ }
+ });
+
+ // Create the Cancel button.
+ JButton cancelButton = new JButton(msg("cancel"));
+ cancelButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ hide();
+ }
+ });
+
+ // Add all panels to the main panel.
+ JPanel mainPanel = new JPanel(layout);
+ mainPanel.add(tip(accessPanel, "accessTip"), panelConstraints);
+ mainPanel.add(tip(annotationTypePanel, "annotationTip"), panelConstraints);
+ mainPanel.add(tip(typePanel, isField ? "fieldTypeTip" :
+ "returnTypeTip"), panelConstraints);
+ mainPanel.add(tip(namePanel, "nameTip"), panelConstraints);
+
+ if (!isField)
+ {
+ mainPanel.add(tip(argumentsPanel, "argumentTypesTip"), panelConstraints);
+ }
+
+ mainPanel.add(tip(advancedButton, "advancedTip"), advancedButtonConstraints);
+ mainPanel.add(okButton, okButtonConstraints);
+ mainPanel.add(cancelButton, cancelButtonConstraints);
+
+ getContentPane().add(new JScrollPane(mainPanel));
+ }
+
+
+ /**
+ * Adds a JLabel and three JRadioButton instances in a ButtonGroup to the
+ * given panel with a GridBagLayout, and returns the buttons in an array.
+ */
+ private JRadioButton[] addRadioButtonTriplet(String labelText,
+ JPanel panel)
+ {
+ GridBagConstraints labelConstraints = new GridBagConstraints();
+ labelConstraints.anchor = GridBagConstraints.WEST;
+ labelConstraints.insets = new Insets(2, 10, 2, 10);
+
+ GridBagConstraints buttonConstraints = new GridBagConstraints();
+ buttonConstraints.insets = labelConstraints.insets;
+
+ GridBagConstraints lastGlueConstraints = new GridBagConstraints();
+ lastGlueConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ lastGlueConstraints.weightx = 1.0;
+
+ // Create the radio buttons.
+ JRadioButton radioButton0 = new JRadioButton();
+ JRadioButton radioButton1 = new JRadioButton();
+ JRadioButton radioButton2 = new JRadioButton();
+
+ // Put them in a button group.
+ ButtonGroup buttonGroup = new ButtonGroup();
+ buttonGroup.add(radioButton0);
+ buttonGroup.add(radioButton1);
+ buttonGroup.add(radioButton2);
+
+ // Add the label and the buttons to the panel.
+ panel.add(new JLabel(labelText), labelConstraints);
+ panel.add(radioButton0, buttonConstraints);
+ panel.add(radioButton1, buttonConstraints);
+ panel.add(radioButton2, buttonConstraints);
+ panel.add(Box.createGlue(), lastGlueConstraints);
+
+ return new JRadioButton[]
+ {
+ radioButton0,
+ radioButton1,
+ radioButton2
+ };
+ }
+
+
+ /**
+ * Sets the MemberSpecification to be represented in this dialog.
+ */
+ public void setMemberSpecification(MemberSpecification memberSpecification)
+ {
+ String annotationType = memberSpecification.annotationType;
+ String name = memberSpecification.name;
+ String descriptor = memberSpecification.descriptor;
+
+ // Set the class name text fields.
+ annotationTypeTextField.setText(annotationType == null ? "" : ClassUtil.externalType(annotationType));
+
+ // Set the access radio buttons.
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_PUBLIC, publicRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_PRIVATE, privateRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_PROTECTED, protectedRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_STATIC, staticRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_FINAL, finalRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_SYNTHETIC, syntheticRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_VOLATILE, volatileRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_TRANSIENT, transientRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_SYNCHRONIZED, synchronizedRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_NATIVE, nativeRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_ABSTRACT, abstractRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_STRICT, strictRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_BRIDGE, bridgeRadioButtons);
+ setMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_VARARGS, varargsRadioButtons);
+
+ // Set the class name text fields.
+ nameTextField.setText(name == null ? "*" : name);
+
+ if (isField)
+ {
+ typeTextField .setText(descriptor == null ? "***" : ClassUtil.externalType(descriptor));
+ }
+ else
+ {
+ typeTextField .setText(descriptor == null ? "***" : ClassUtil.externalMethodReturnType(descriptor));
+ argumentTypesTextField.setText(descriptor == null ? "..." : ClassUtil.externalMethodArguments(descriptor));
+ }
+ }
+
+
+ /**
+ * Returns the MemberSpecification currently represented in this dialog.
+ */
+ public MemberSpecification getMemberSpecification()
+ {
+ String annotationType = annotationTypeTextField.getText();
+ String name = nameTextField.getText();
+ String type = typeTextField.getText();
+ String arguments = argumentTypesTextField.getText();
+
+ // Convert all class member specifications into the internal format.
+ annotationType =
+ annotationType.equals("") ||
+ annotationType.equals("***") ? null : ClassUtil.internalType(annotationType);
+
+ if (name.equals("") ||
+ name.equals("*"))
+ {
+ name = null;
+ }
+
+ if (isField)
+ {
+ type =
+ type.equals("") ||
+ type.equals("***") ? null : ClassUtil.internalType(type);
+ }
+ else
+ {
+ if (type.equals(""))
+ {
+ type = ClassConstants.EXTERNAL_TYPE_VOID;
+ }
+
+ type =
+ type .equals("***") &&
+ arguments.equals("...") ? null :
+ ClassUtil.internalMethodDescriptor(type, ListUtil.commaSeparatedList(arguments));
+ }
+
+ MemberSpecification memberSpecification =
+ new MemberSpecification(0, 0, annotationType, name, type);
+
+ // Also get the access radio button settings.
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_PUBLIC, publicRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_PRIVATE, privateRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_PROTECTED, protectedRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_STATIC, staticRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_FINAL, finalRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_SYNTHETIC, syntheticRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_VOLATILE, volatileRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_TRANSIENT, transientRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_SYNCHRONIZED, synchronizedRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_NATIVE, nativeRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_ABSTRACT, abstractRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_STRICT, strictRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_BRIDGE, bridgeRadioButtons);
+ getMemberSpecificationRadioButtons(memberSpecification, ClassConstants.INTERNAL_ACC_VARARGS, varargsRadioButtons);
+
+ return memberSpecification;
+ }
+
+
+ /**
+ * Shows this dialog. This method only returns when the dialog is closed.
+ *
+ * @return CANCEL_OPTION
or APPROVE_OPTION
,
+ * depending on the choice of the user.
+ */
+ public int showDialog()
+ {
+ returnValue = CANCEL_OPTION;
+
+ // Open the dialog in the right place, then wait for it to be closed,
+ // one way or another.
+ pack();
+ setLocationRelativeTo(getOwner());
+ show();
+
+ return returnValue;
+ }
+
+
+ /**
+ * Sets the appropriate radio button of a given triplet, based on the access
+ * flags of the given keep option.
+ */
+ private void setMemberSpecificationRadioButtons(MemberSpecification memberSpecification,
+ int flag,
+ JRadioButton[] radioButtons)
+ {
+ if (radioButtons != null)
+ {
+ int index = (memberSpecification.requiredSetAccessFlags & flag) != 0 ? 0 :
+ (memberSpecification.requiredUnsetAccessFlags & flag) != 0 ? 1 :
+ 2;
+ radioButtons[index].setSelected(true);
+ }
+ }
+
+
+ /**
+ * Updates the access flag of the given keep option, based on the given radio
+ * button triplet.
+ */
+ private void getMemberSpecificationRadioButtons(MemberSpecification memberSpecification,
+ int flag,
+ JRadioButton[] radioButtons)
+ {
+ if (radioButtons != null)
+ {
+ if (radioButtons[0].isSelected())
+ {
+ memberSpecification.requiredSetAccessFlags |= flag;
+ }
+ else if (radioButtons[1].isSelected())
+ {
+ memberSpecification.requiredUnsetAccessFlags |= flag;
+ }
+ }
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+}
diff --git a/src/proguard/gui/MemberSpecificationsPanel.java b/src/proguard/gui/MemberSpecificationsPanel.java
new file mode 100644
index 000000000..6a72a1d8b
--- /dev/null
+++ b/src/proguard/gui/MemberSpecificationsPanel.java
@@ -0,0 +1,304 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.*;
+import proguard.classfile.ClassConstants;
+import proguard.classfile.util.ClassUtil;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.*;
+import java.util.List;
+
+
+/**
+ * This ListPanel
allows the user to add, edit, move, and remove
+ * MemberSpecification entries in a list.
+ *
+ * @author Eric Lafortune
+ */
+final class MemberSpecificationsPanel extends ListPanel
+{
+ private final MemberSpecificationDialog fieldSpecificationDialog;
+ private final MemberSpecificationDialog methodSpecificationDialog;
+
+
+ public MemberSpecificationsPanel(JDialog owner, boolean fullKeepOptions)
+ {
+ super();
+
+ super.firstSelectionButton = fullKeepOptions ? 3 : 2;
+
+ list.setCellRenderer(new MyListCellRenderer());
+
+ fieldSpecificationDialog = new MemberSpecificationDialog(owner, true);
+ methodSpecificationDialog = new MemberSpecificationDialog(owner, false);
+
+ if (fullKeepOptions)
+ {
+ addAddFieldButton();
+ }
+ addAddMethodButton();
+ addEditButton();
+ addRemoveButton();
+ addUpButton();
+ addDownButton();
+
+ enableSelectionButtons();
+ }
+
+
+ protected void addAddFieldButton()
+ {
+ JButton addFieldButton = new JButton(msg("addField"));
+ addFieldButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ fieldSpecificationDialog.setMemberSpecification(new MemberSpecification());
+ int returnValue = fieldSpecificationDialog.showDialog();
+ if (returnValue == MemberSpecificationDialog.APPROVE_OPTION)
+ {
+ // Add the new element.
+ addElement(new MyMemberSpecificationWrapper(fieldSpecificationDialog.getMemberSpecification(),
+ true));
+ }
+ }
+ });
+
+ addButton(tip(addFieldButton, "addFieldTip"));
+ }
+
+
+ protected void addAddMethodButton()
+ {
+ JButton addMethodButton = new JButton(msg("addMethod"));
+ addMethodButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ methodSpecificationDialog.setMemberSpecification(new MemberSpecification());
+ int returnValue = methodSpecificationDialog.showDialog();
+ if (returnValue == MemberSpecificationDialog.APPROVE_OPTION)
+ {
+ // Add the new element.
+ addElement(new MyMemberSpecificationWrapper(methodSpecificationDialog.getMemberSpecification(),
+ false));
+ }
+ }
+ });
+
+ addButton(tip(addMethodButton, "addMethodTip"));
+ }
+
+
+ protected void addEditButton()
+ {
+ JButton editButton = new JButton(msg("edit"));
+ editButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ MyMemberSpecificationWrapper wrapper =
+ (MyMemberSpecificationWrapper)list.getSelectedValue();
+
+ MemberSpecificationDialog memberSpecificationDialog =
+ wrapper.isField ?
+ fieldSpecificationDialog :
+ methodSpecificationDialog;
+
+ memberSpecificationDialog.setMemberSpecification(wrapper.memberSpecification);
+ int returnValue = memberSpecificationDialog.showDialog();
+ if (returnValue == MemberSpecificationDialog.APPROVE_OPTION)
+ {
+ // Replace the old element.
+ wrapper.memberSpecification = memberSpecificationDialog.getMemberSpecification();
+ setElementAt(wrapper,
+ list.getSelectedIndex());
+ }
+ }
+ });
+
+ addButton(tip(editButton, "editTip"));
+ }
+
+
+ /**
+ * Sets the MemberSpecification instances to be represented in this panel.
+ */
+ public void setMemberSpecifications(List fieldSpecifications,
+ List methodSpecifications)
+ {
+ listModel.clear();
+
+ if (fieldSpecifications != null)
+ {
+ for (int index = 0; index < fieldSpecifications.size(); index++)
+ {
+ listModel.addElement(
+ new MyMemberSpecificationWrapper((MemberSpecification)fieldSpecifications.get(index),
+ true));
+ }
+ }
+
+ if (methodSpecifications != null)
+ {
+ for (int index = 0; index < methodSpecifications.size(); index++)
+ {
+ listModel.addElement(
+ new MyMemberSpecificationWrapper((MemberSpecification)methodSpecifications.get(index),
+ false));
+ }
+ }
+
+ // Make sure the selection buttons are properly enabled,
+ // since the clear method doesn't seem to notify the listener.
+ enableSelectionButtons();
+ }
+
+
+ /**
+ * Returns the MemberSpecification instances currently represented in
+ * this panel, referring to fields or to methods.
+ *
+ * @param isField specifies whether specifications referring to fields or
+ * specifications referring to methods should be returned.
+ */
+ public List getMemberSpecifications(boolean isField)
+ {
+ int size = listModel.size();
+ if (size == 0)
+ {
+ return null;
+ }
+
+ List memberSpecifications = new ArrayList(size);
+ for (int index = 0; index < size; index++)
+ {
+ MyMemberSpecificationWrapper wrapper =
+ (MyMemberSpecificationWrapper)listModel.get(index);
+
+ if (wrapper.isField == isField)
+ {
+ memberSpecifications.add(wrapper.memberSpecification);
+ }
+ }
+
+ return memberSpecifications;
+ }
+
+
+ /**
+ * This ListCellRenderer renders MemberSpecification objects.
+ */
+ private static class MyListCellRenderer implements ListCellRenderer
+ {
+ private final JLabel label = new JLabel();
+
+
+ // Implementations for ListCellRenderer.
+
+ public Component getListCellRendererComponent(JList list,
+ Object value,
+ int index,
+ boolean isSelected,
+ boolean cellHasFocus)
+ {
+ MyMemberSpecificationWrapper wrapper = (MyMemberSpecificationWrapper)value;
+
+ MemberSpecification option = wrapper.memberSpecification;
+ String name = option.name;
+ String descriptor = option.descriptor;
+
+ label.setText(wrapper.isField ?
+ (descriptor == null ? name == null ?
+ "Runnable
can show a message dialog.
+ *
+ * @author Eric Lafortune
+ */
+final class MessageDialogRunnable implements Runnable
+{
+ private final Component parentComponent;
+ private final Object message;
+ private final String title;
+ private final int messageType;
+
+
+ /**
+ * Creates a new MessageDialogRunnable object.
+ * @see JOptionPane#showMessageDialog(Component, Object, String, int)
+ */
+ public static void showMessageDialog(Component parentComponent,
+ Object message,
+ String title,
+ int messageType)
+ {
+ try
+ {
+ SwingUtil.invokeAndWait(new MessageDialogRunnable(parentComponent,
+ message,
+ title,
+ messageType));
+ }
+ catch (Exception e)
+ {
+ // Nothing.
+ }
+ }
+
+
+ /**
+ * Creates a new MessageDialogRunnable object.
+ * @see JOptionPane#showMessageDialog(Component, Object, String, int)
+ */
+ public MessageDialogRunnable(Component parentComponent,
+ Object message,
+ String title,
+ int messageType)
+ {
+ this.parentComponent = parentComponent;
+ this.message = message;
+ this.title = title;
+ this.messageType = messageType;
+ }
+
+
+
+ // Implementation for Runnable.
+
+ public void run()
+ {
+ JOptionPane.showMessageDialog(parentComponent,
+ message,
+ title,
+ messageType);
+ }
+}
diff --git a/src/proguard/gui/OptimizationsDialog.java b/src/proguard/gui/OptimizationsDialog.java
new file mode 100644
index 000000000..0af0979c1
--- /dev/null
+++ b/src/proguard/gui/OptimizationsDialog.java
@@ -0,0 +1,251 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.optimize.Optimizer;
+import proguard.util.*;
+
+import javax.swing.*;
+import javax.swing.border.*;
+import java.awt.*;
+import java.awt.event.*;
+
+/**
+ * This JDialog
allows the user to enter a String.
+ *
+ * @author Eric Lafortune
+ */
+final class OptimizationsDialog extends JDialog
+{
+ /**
+ * Return value if the dialog is canceled (with the Cancel button or by
+ * closing the dialog window).
+ */
+ public static final int CANCEL_OPTION = 1;
+
+ /**
+ * Return value if the dialog is approved (with the Ok button).
+ */
+ public static final int APPROVE_OPTION = 0;
+
+
+ private final JCheckBox[] optimizationCheckBoxes = new JCheckBox[Optimizer.OPTIMIZATION_NAMES.length];
+
+ private int returnValue;
+
+
+ public OptimizationsDialog(JFrame owner)
+ {
+ super(owner, msg("selectOptimizations"), true);
+ setResizable(true);
+
+ // Create some constraints that can be reused.
+ GridBagConstraints constraintsLast = new GridBagConstraints();
+ constraintsLast.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLast.anchor = GridBagConstraints.WEST;
+ constraintsLast.insets = new Insets(1, 2, 1, 2);
+
+ GridBagConstraints constraintsLastStretch = new GridBagConstraints();
+ constraintsLastStretch.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLastStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsLastStretch.weightx = 1.0;
+ constraintsLastStretch.anchor = GridBagConstraints.WEST;
+ constraintsLastStretch.insets = constraintsLast.insets;
+
+ GridBagConstraints panelConstraints = new GridBagConstraints();
+ panelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ panelConstraints.fill = GridBagConstraints.HORIZONTAL;
+ panelConstraints.weightx = 1.0;
+ panelConstraints.weighty = 0.0;
+ panelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ panelConstraints.insets = constraintsLast.insets;
+
+ GridBagConstraints selectButtonConstraints = new GridBagConstraints();
+ selectButtonConstraints.weighty = 1.0;
+ selectButtonConstraints.anchor = GridBagConstraints.SOUTHWEST;
+ selectButtonConstraints.insets = new Insets(4, 4, 8, 4);
+
+ GridBagConstraints okButtonConstraints = new GridBagConstraints();
+ okButtonConstraints.weightx = 1.0;
+ okButtonConstraints.weighty = 1.0;
+ okButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ okButtonConstraints.insets = selectButtonConstraints.insets;
+
+ GridBagConstraints cancelButtonConstraints = new GridBagConstraints();
+ cancelButtonConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ cancelButtonConstraints.weighty = 1.0;
+ cancelButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ cancelButtonConstraints.insets = selectButtonConstraints.insets;
+
+ GridBagLayout layout = new GridBagLayout();
+
+ Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
+
+ // Create the optimizations panel.
+ JPanel optimizationsPanel = new JPanel(layout);
+ JPanel optimizationSubpanel = null;
+ String lastOptimizationPrefix = null;
+
+ for (int index = 0; index < Optimizer.OPTIMIZATION_NAMES.length; index++)
+ {
+ String optimizationName = Optimizer.OPTIMIZATION_NAMES[index];
+
+ String optimizationPrefix = optimizationName.substring(0, optimizationName.indexOf('/'));
+
+ if (optimizationSubpanel == null || !optimizationPrefix.equals(lastOptimizationPrefix))
+ {
+ // Create a new keep subpanel and add it.
+ optimizationSubpanel = new JPanel(layout);
+ optimizationSubpanel.setBorder(BorderFactory.createTitledBorder(etchedBorder, msg(optimizationPrefix)));
+ optimizationsPanel.add(optimizationSubpanel, panelConstraints);
+
+ lastOptimizationPrefix = optimizationPrefix;
+ }
+
+ JCheckBox optimizationCheckBox = new JCheckBox(optimizationName);
+ optimizationCheckBoxes[index] = optimizationCheckBox;
+
+ optimizationSubpanel.add(tip(optimizationCheckBox, optimizationName.replace('/', '_')+"Tip"), constraintsLastStretch);
+ }
+
+ // Create the Select All button.
+ JButton selectAllButton = new JButton(msg("selectAll"));
+ selectAllButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ for (int index = 0; index < optimizationCheckBoxes.length; index++)
+ {
+ optimizationCheckBoxes[index].setSelected(true);
+ }
+ }
+ });
+
+ // Create the Select All button.
+ JButton selectNoneButton = new JButton(msg("selectNone"));
+ selectNoneButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ for (int index = 0; index < optimizationCheckBoxes.length; index++)
+ {
+ optimizationCheckBoxes[index].setSelected(false);
+ }
+ }
+ });
+
+ // Create the Ok button.
+ JButton okButton = new JButton(msg("ok"));
+ okButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ returnValue = APPROVE_OPTION;
+ hide();
+ }
+ });
+
+ // Create the Cancel button.
+ JButton cancelButton = new JButton(msg("cancel"));
+ cancelButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ hide();
+ }
+ });
+
+ // Add all panels to the main panel.
+ optimizationsPanel.add(selectAllButton, selectButtonConstraints);
+ optimizationsPanel.add(selectNoneButton, selectButtonConstraints);
+ optimizationsPanel.add(okButton, okButtonConstraints);
+ optimizationsPanel.add(cancelButton, cancelButtonConstraints);
+
+ getContentPane().add(new JScrollPane(optimizationsPanel));
+ }
+
+
+ /**
+ * Sets the initial optimization filter to be used by the dialog.
+ */
+ public void setFilter(String optimizations)
+ {
+ StringMatcher filter = optimizations != null && optimizations.length() > 0 ?
+ new ListParser(new NameParser()).parse(optimizations) :
+ new FixedStringMatcher("");
+
+ for (int index = 0; index < Optimizer.OPTIMIZATION_NAMES.length; index++)
+ {
+ optimizationCheckBoxes[index].setSelected(filter.matches(Optimizer.OPTIMIZATION_NAMES[index]));
+ }
+ }
+
+
+ /**
+ * Returns the optimization filter composed from the settings in the dialog.
+ */
+ public String getFilter()
+ {
+ return new FilterBuilder(optimizationCheckBoxes, '/').buildFilter();
+ }
+
+
+ /**
+ * Shows this dialog. This method only returns when the dialog is closed.
+ *
+ * @return CANCEL_OPTION
or APPROVE_OPTION
,
+ * depending on the choice of the user.
+ */
+ public int showDialog()
+ {
+ returnValue = CANCEL_OPTION;
+
+ // Open the dialog in the right place, then wait for it to be closed,
+ // one way or another.
+ pack();
+ setLocationRelativeTo(getOwner());
+ show();
+
+ return returnValue;
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/gui/ProGuardGUI.java b/src/proguard/gui/ProGuardGUI.java
new file mode 100644
index 000000000..6b08aa8bc
--- /dev/null
+++ b/src/proguard/gui/ProGuardGUI.java
@@ -0,0 +1,1771 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.*;
+import proguard.classfile.util.ClassUtil;
+import proguard.gui.splash.*;
+import proguard.util.ListUtil;
+
+import javax.swing.*;
+import javax.swing.border.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.io.*;
+import java.net.URL;
+import java.util.*;
+import java.util.List;
+
+
+/**
+ * GUI for configuring and executing ProGuard and ReTrace.
+ *
+ * @author Eric Lafortune
+ */
+public class ProGuardGUI extends JFrame
+{
+ private static final String NO_SPLASH_OPTION = "-nosplash";
+
+ private static final String TITLE_IMAGE_FILE = "vtitle.png";
+ private static final String BOILERPLATE_CONFIGURATION = "boilerplate.pro";
+ private static final String DEFAULT_CONFIGURATION = "default.pro";
+
+ private static final String OPTIMIZATIONS_DEFAULT = "*";
+ private static final String KEEP_ATTRIBUTE_DEFAULT = "Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,LocalVariable*Table,*Annotation*,Synthetic,EnclosingMethod";
+ private static final String SOURCE_FILE_ATTRIBUTE_DEFAULT = "SourceFile";
+ private static final String ADAPT_RESOURCE_FILE_NAMES_DEFAULT = "**.properties";
+ private static final String ADAPT_RESOURCE_FILE_CONTENTS_DEFAULT = "**.properties,META-INF/MANIFEST.MF";
+
+ private static final Border BORDER = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
+
+ static boolean systemOutRedirected;
+
+ private final JFileChooser configurationChooser = new JFileChooser("");
+ private final JFileChooser fileChooser = new JFileChooser("");
+
+ private final SplashPanel splashPanel;
+
+ private final ClassPathPanel programPanel = new ClassPathPanel(this, true);
+ private final ClassPathPanel libraryPanel = new ClassPathPanel(this, false);
+
+ private KeepClassSpecification[] boilerplateKeep;
+ private final JCheckBox[] boilerplateKeepCheckBoxes;
+ private final JTextField[] boilerplateKeepTextFields;
+
+ private final KeepSpecificationsPanel additionalKeepPanel = new KeepSpecificationsPanel(this, true, false, false, false, false);
+
+ private KeepClassSpecification[] boilerplateKeepNames;
+ private final JCheckBox[] boilerplateKeepNamesCheckBoxes;
+ private final JTextField[] boilerplateKeepNamesTextFields;
+
+ private final KeepSpecificationsPanel additionalKeepNamesPanel = new KeepSpecificationsPanel(this, true, false, true, false, false);
+
+ private ClassSpecification[] boilerplateNoSideEffectMethods;
+ private final JCheckBox[] boilerplateNoSideEffectMethodCheckBoxes;
+
+ private final ClassSpecificationsPanel additionalNoSideEffectsPanel = new ClassSpecificationsPanel(this, false);
+
+ private final ClassSpecificationsPanel whyAreYouKeepingPanel = new ClassSpecificationsPanel(this, false);
+
+ private final JCheckBox shrinkCheckBox = new JCheckBox(msg("shrink"));
+ private final JCheckBox printUsageCheckBox = new JCheckBox(msg("printUsage"));
+
+ private final JCheckBox optimizeCheckBox = new JCheckBox(msg("optimize"));
+ private final JCheckBox allowAccessModificationCheckBox = new JCheckBox(msg("allowAccessModification"));
+ private final JCheckBox mergeInterfacesAggressivelyCheckBox = new JCheckBox(msg("mergeInterfacesAggressively"));
+ private final JLabel optimizationsLabel = new JLabel(msg("optimizations"));
+ private final JLabel optimizationPassesLabel = new JLabel(msg("optimizationPasses"));
+
+ private final JSpinner optimizationPassesSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 9, 1));
+
+ private final JCheckBox obfuscateCheckBox = new JCheckBox(msg("obfuscate"));
+ private final JCheckBox printMappingCheckBox = new JCheckBox(msg("printMapping"));
+ private final JCheckBox applyMappingCheckBox = new JCheckBox(msg("applyMapping"));
+ private final JCheckBox obfuscationDictionaryCheckBox = new JCheckBox(msg("obfuscationDictionary"));
+ private final JCheckBox classObfuscationDictionaryCheckBox = new JCheckBox(msg("classObfuscationDictionary"));
+ private final JCheckBox packageObfuscationDictionaryCheckBox = new JCheckBox(msg("packageObfuscationDictionary"));
+ private final JCheckBox overloadAggressivelyCheckBox = new JCheckBox(msg("overloadAggressively"));
+ private final JCheckBox useUniqueClassMemberNamesCheckBox = new JCheckBox(msg("useUniqueClassMemberNames"));
+ private final JCheckBox useMixedCaseClassNamesCheckBox = new JCheckBox(msg("useMixedCaseClassNames"));
+ private final JCheckBox keepPackageNamesCheckBox = new JCheckBox(msg("keepPackageNames"));
+ private final JCheckBox flattenPackageHierarchyCheckBox = new JCheckBox(msg("flattenPackageHierarchy"));
+ private final JCheckBox repackageClassesCheckBox = new JCheckBox(msg("repackageClasses"));
+ private final JCheckBox keepAttributesCheckBox = new JCheckBox(msg("keepAttributes"));
+ private final JCheckBox keepParameterNamesCheckBox = new JCheckBox(msg("keepParameterNames"));
+ private final JCheckBox newSourceFileAttributeCheckBox = new JCheckBox(msg("renameSourceFileAttribute"));
+ private final JCheckBox adaptClassStringsCheckBox = new JCheckBox(msg("adaptClassStrings"));
+ private final JCheckBox adaptResourceFileNamesCheckBox = new JCheckBox(msg("adaptResourceFileNames"));
+ private final JCheckBox adaptResourceFileContentsCheckBox = new JCheckBox(msg("adaptResourceFileContents"));
+
+ private final JCheckBox preverifyCheckBox = new JCheckBox(msg("preverify"));
+ private final JCheckBox microEditionCheckBox = new JCheckBox(msg("microEdition"));
+ private final JCheckBox targetCheckBox = new JCheckBox(msg("target"));
+
+ private final JComboBox targetComboBox = new JComboBox(ListUtil.commaSeparatedList(msg("targets")).toArray());
+
+ private final JCheckBox verboseCheckBox = new JCheckBox(msg("verbose"));
+ private final JCheckBox noteCheckBox = new JCheckBox(msg("note"));
+ private final JCheckBox warnCheckBox = new JCheckBox(msg("warn"));
+ private final JCheckBox ignoreWarningsCheckBox = new JCheckBox(msg("ignoreWarnings"));
+ private final JCheckBox skipNonPublicLibraryClassesCheckBox = new JCheckBox(msg("skipNonPublicLibraryClasses"));
+ private final JCheckBox skipNonPublicLibraryClassMembersCheckBox = new JCheckBox(msg("skipNonPublicLibraryClassMembers"));
+ private final JCheckBox keepDirectoriesCheckBox = new JCheckBox(msg("keepDirectories"));
+ private final JCheckBox forceProcessingCheckBox = new JCheckBox(msg("forceProcessing"));
+ private final JCheckBox printSeedsCheckBox = new JCheckBox(msg("printSeeds"));
+ private final JCheckBox printConfigurationCheckBox = new JCheckBox(msg("printConfiguration"));
+ private final JCheckBox dumpCheckBox = new JCheckBox(msg("dump"));
+
+ private final JTextField printUsageTextField = new JTextField(40);
+ private final JTextField optimizationsTextField = new JTextField(40);
+ private final JTextField printMappingTextField = new JTextField(40);
+ private final JTextField applyMappingTextField = new JTextField(40);
+ private final JTextField obfuscationDictionaryTextField = new JTextField(40);
+ private final JTextField classObfuscationDictionaryTextField = new JTextField(40);
+ private final JTextField packageObfuscationDictionaryTextField = new JTextField(40);
+ private final JTextField keepPackageNamesTextField = new JTextField(40);
+ private final JTextField flattenPackageHierarchyTextField = new JTextField(40);
+ private final JTextField repackageClassesTextField = new JTextField(40);
+ private final JTextField keepAttributesTextField = new JTextField(40);
+ private final JTextField newSourceFileAttributeTextField = new JTextField(40);
+ private final JTextField adaptClassStringsTextField = new JTextField(40);
+ private final JTextField adaptResourceFileNamesTextField = new JTextField(40);
+ private final JTextField adaptResourceFileContentsTextField = new JTextField(40);
+ private final JTextField noteTextField = new JTextField(40);
+ private final JTextField warnTextField = new JTextField(40);
+ private final JTextField keepDirectoriesTextField = new JTextField(40);
+ private final JTextField printSeedsTextField = new JTextField(40);
+ private final JTextField printConfigurationTextField = new JTextField(40);
+ private final JTextField dumpTextField = new JTextField(40);
+
+ private final JTextArea consoleTextArea = new JTextArea(msg("processingInfo"), 3, 40);
+
+ private final JCheckBox reTraceVerboseCheckBox = new JCheckBox(msg("verbose"));
+ private final JTextField reTraceMappingTextField = new JTextField(40);
+ private final JTextArea stackTraceTextArea = new JTextArea(3, 40);
+ private final JTextArea reTraceTextArea = new JTextArea(msg("reTraceInfo"), 3, 40);
+
+
+ /**
+ * Creates a new ProGuardGUI.
+ */
+ public ProGuardGUI()
+ {
+ setTitle("ProGuard");
+ setDefaultCloseOperation(EXIT_ON_CLOSE);
+
+ // Create some constraints that can be reused.
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.anchor = GridBagConstraints.WEST;
+ constraints.insets = new Insets(0, 4, 0, 4);
+
+ GridBagConstraints constraintsStretch = new GridBagConstraints();
+ constraintsStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsStretch.weightx = 1.0;
+ constraintsStretch.anchor = GridBagConstraints.WEST;
+ constraintsStretch.insets = constraints.insets;
+
+ GridBagConstraints constraintsLast = new GridBagConstraints();
+ constraintsLast.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLast.anchor = GridBagConstraints.WEST;
+ constraintsLast.insets = constraints.insets;
+
+ GridBagConstraints constraintsLastStretch = new GridBagConstraints();
+ constraintsLastStretch.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLastStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsLastStretch.weightx = 1.0;
+ constraintsLastStretch.anchor = GridBagConstraints.WEST;
+ constraintsLastStretch.insets = constraints.insets;
+
+ GridBagConstraints splashPanelConstraints = new GridBagConstraints();
+ splashPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ splashPanelConstraints.fill = GridBagConstraints.BOTH;
+ splashPanelConstraints.weightx = 1.0;
+ splashPanelConstraints.weighty = 0.02;
+ splashPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ //splashPanelConstraints.insets = constraints.insets;
+
+ GridBagConstraints welcomePaneConstraints = new GridBagConstraints();
+ welcomePaneConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ welcomePaneConstraints.fill = GridBagConstraints.NONE;
+ welcomePaneConstraints.weightx = 1.0;
+ welcomePaneConstraints.weighty = 0.01;
+ welcomePaneConstraints.anchor = GridBagConstraints.CENTER;//NORTHWEST;
+ welcomePaneConstraints.insets = new Insets(20, 40, 20, 40);
+
+ GridBagConstraints panelConstraints = new GridBagConstraints();
+ panelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ panelConstraints.fill = GridBagConstraints.HORIZONTAL;
+ panelConstraints.weightx = 1.0;
+ panelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ panelConstraints.insets = constraints.insets;
+
+ GridBagConstraints stretchPanelConstraints = new GridBagConstraints();
+ stretchPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ stretchPanelConstraints.fill = GridBagConstraints.BOTH;
+ stretchPanelConstraints.weightx = 1.0;
+ stretchPanelConstraints.weighty = 1.0;
+ stretchPanelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ stretchPanelConstraints.insets = constraints.insets;
+
+ GridBagConstraints glueConstraints = new GridBagConstraints();
+ glueConstraints.fill = GridBagConstraints.BOTH;
+ glueConstraints.weightx = 0.01;
+ glueConstraints.weighty = 0.01;
+ glueConstraints.anchor = GridBagConstraints.NORTHWEST;
+ glueConstraints.insets = constraints.insets;
+
+ GridBagConstraints bottomButtonConstraints = new GridBagConstraints();
+ bottomButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ bottomButtonConstraints.insets = new Insets(2, 2, 4, 6);
+ bottomButtonConstraints.ipadx = 10;
+ bottomButtonConstraints.ipady = 2;
+
+ GridBagConstraints lastBottomButtonConstraints = new GridBagConstraints();
+ lastBottomButtonConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ lastBottomButtonConstraints.anchor = GridBagConstraints.SOUTHEAST;
+ lastBottomButtonConstraints.insets = bottomButtonConstraints.insets;
+ lastBottomButtonConstraints.ipadx = bottomButtonConstraints.ipadx;
+ lastBottomButtonConstraints.ipady = bottomButtonConstraints.ipady;
+
+ // Leave room for a growBox on Mac OS X.
+ if (System.getProperty("os.name").toLowerCase().startsWith("mac os x"))
+ {
+ lastBottomButtonConstraints.insets = new Insets(2, 2, 4, 6 + 16);
+ }
+
+ GridBagLayout layout = new GridBagLayout();
+
+ configurationChooser.addChoosableFileFilter(
+ new ExtensionFileFilter(msg("proExtension"), new String[] { ".pro" }));
+
+ // Create the opening panel.
+ Sprite splash =
+ new CompositeSprite(new Sprite[]
+ {
+ new ColorSprite(new ConstantColor(Color.gray),
+ new FontSprite(new ConstantFont(new Font("sansserif", Font.BOLD, 90)),
+ new TextSprite(new ConstantString("ProGuard"),
+ new ConstantInt(160),
+ new LinearInt(-10, 120, new SmoothTiming(500, 1000))))),
+
+ new ColorSprite(new ConstantColor(Color.white),
+ new FontSprite(new ConstantFont(new Font("sansserif", Font.BOLD, 45)),
+ new ShadowedSprite(new ConstantInt(3),
+ new ConstantInt(3),
+ new ConstantDouble(0.4),
+ new ConstantInt(1),
+ new CompositeSprite(new Sprite[]
+ {
+ new TextSprite(new ConstantString(msg("shrinking")),
+ new LinearInt(1000, 60, new SmoothTiming(1000, 2000)),
+ new ConstantInt(70)),
+ new TextSprite(new ConstantString(msg("optimization")),
+ new LinearInt(1000, 400, new SmoothTiming(1500, 2500)),
+ new ConstantInt(60)),
+ new TextSprite(new ConstantString(msg("obfuscation")),
+ new LinearInt(1000, 10, new SmoothTiming(2000, 3000)),
+ new ConstantInt(145)),
+ new TextSprite(new ConstantString(msg("preverification")),
+ new LinearInt(1000, 350, new SmoothTiming(2500, 3500)),
+ new ConstantInt(140)),
+ new FontSprite(new ConstantFont(new Font("sansserif", Font.BOLD, 30)),
+ new TextSprite(new TypeWriterString(msg("developed"), new LinearTiming(3500, 5500)),
+ new ConstantInt(250),
+ new ConstantInt(200))),
+ })))),
+ });
+ splashPanel = new SplashPanel(splash, 0.5, 5500L);
+ splashPanel.setPreferredSize(new Dimension(0, 200));
+
+ JEditorPane welcomePane = new JEditorPane("text/html", msg("proGuardInfo"));
+ welcomePane.setPreferredSize(new Dimension(640, 350));
+ // The constant HONOR_DISPLAY_PROPERTIES isn't present yet in JDK 1.4.
+ //welcomePane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
+ welcomePane.putClientProperty("JEditorPane.honorDisplayProperties", Boolean.TRUE);
+ welcomePane.setOpaque(false);
+ welcomePane.setEditable(false);
+ welcomePane.setBorder(new EmptyBorder(20, 20, 20, 20));
+ addBorder(welcomePane, "welcome");
+
+ JPanel proGuardPanel = new JPanel(layout);
+ proGuardPanel.add(splashPanel, splashPanelConstraints);
+ proGuardPanel.add(welcomePane, welcomePaneConstraints);
+
+ // Create the input panel.
+ // TODO: properly clone the ClassPath objects.
+ // This is awkward to implement in the generic ListPanel.addElements(...)
+ // method, since the Object.clone() method is not public.
+ programPanel.addCopyToPanelButton("moveToLibraries", "moveToLibrariesTip", libraryPanel);
+ libraryPanel.addCopyToPanelButton("moveToProgram", "moveToProgramTip", programPanel);
+
+ // Collect all buttons of these panels and make sure they are equally
+ // sized.
+ List panelButtons = new ArrayList();
+ panelButtons.addAll(programPanel.getButtons());
+ panelButtons.addAll(libraryPanel.getButtons());
+ setCommonPreferredSize(panelButtons);
+
+ addBorder(programPanel, "programJars" );
+ addBorder(libraryPanel, "libraryJars" );
+
+ JPanel inputOutputPanel = new JPanel(layout);
+ inputOutputPanel.add(tip(programPanel, "programJarsTip"), stretchPanelConstraints);
+ inputOutputPanel.add(tip(libraryPanel, "libraryJarsTip"), stretchPanelConstraints);
+
+ // Load the boiler plate options.
+ loadBoilerplateConfiguration();
+
+ // Create the boiler plate keep panels.
+ boilerplateKeepCheckBoxes = new JCheckBox[boilerplateKeep.length];
+ boilerplateKeepTextFields = new JTextField[boilerplateKeep.length];
+
+ JButton printUsageBrowseButton = createBrowseButton(printUsageTextField,
+ msg("selectUsageFile"));
+
+ JPanel shrinkingOptionsPanel = new JPanel(layout);
+ addBorder(shrinkingOptionsPanel, "options");
+
+ shrinkingOptionsPanel.add(tip(shrinkCheckBox, "shrinkTip"), constraintsLastStretch);
+ shrinkingOptionsPanel.add(tip(printUsageCheckBox, "printUsageTip"), constraints);
+ shrinkingOptionsPanel.add(tip(printUsageTextField, "outputFileTip"), constraintsStretch);
+ shrinkingOptionsPanel.add(tip(printUsageBrowseButton, "selectUsageFile"), constraintsLast);
+
+ JPanel shrinkingPanel = new JPanel(layout);
+
+ shrinkingPanel.add(shrinkingOptionsPanel, panelConstraints);
+ addClassSpecifications(extractClassSpecifications(boilerplateKeep),
+ shrinkingPanel,
+ boilerplateKeepCheckBoxes,
+ boilerplateKeepTextFields);
+
+ addBorder(additionalKeepPanel, "keepAdditional");
+ shrinkingPanel.add(tip(additionalKeepPanel, "keepAdditionalTip"), stretchPanelConstraints);
+
+ // Create the boiler plate keep names panels.
+ boilerplateKeepNamesCheckBoxes = new JCheckBox[boilerplateKeepNames.length];
+ boilerplateKeepNamesTextFields = new JTextField[boilerplateKeepNames.length];
+
+ JButton printMappingBrowseButton = createBrowseButton(printMappingTextField,
+ msg("selectPrintMappingFile"));
+ JButton applyMappingBrowseButton = createBrowseButton(applyMappingTextField,
+ msg("selectApplyMappingFile"));
+ JButton obfucationDictionaryBrowseButton = createBrowseButton(obfuscationDictionaryTextField,
+ msg("selectObfuscationDictionaryFile"));
+ JButton classObfucationDictionaryBrowseButton = createBrowseButton(classObfuscationDictionaryTextField,
+ msg("selectObfuscationDictionaryFile"));
+ JButton packageObfucationDictionaryBrowseButton = createBrowseButton(packageObfuscationDictionaryTextField,
+ msg("selectObfuscationDictionaryFile"));
+
+ JPanel obfuscationOptionsPanel = new JPanel(layout);
+ addBorder(obfuscationOptionsPanel, "options");
+
+ obfuscationOptionsPanel.add(tip(obfuscateCheckBox, "obfuscateTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(printMappingCheckBox, "printMappingTip"), constraints);
+ obfuscationOptionsPanel.add(tip(printMappingTextField, "outputFileTip"), constraintsStretch);
+ obfuscationOptionsPanel.add(tip(printMappingBrowseButton, "selectPrintMappingFile"), constraintsLast);
+ obfuscationOptionsPanel.add(tip(applyMappingCheckBox, "applyMappingTip"), constraints);
+ obfuscationOptionsPanel.add(tip(applyMappingTextField, "inputFileTip"), constraintsStretch);
+ obfuscationOptionsPanel.add(tip(applyMappingBrowseButton, "selectApplyMappingFile"), constraintsLast);
+ obfuscationOptionsPanel.add(tip(obfuscationDictionaryCheckBox, "obfuscationDictionaryTip"), constraints);
+ obfuscationOptionsPanel.add(tip(obfuscationDictionaryTextField, "inputFileTip"), constraintsStretch);
+ obfuscationOptionsPanel.add(tip(obfucationDictionaryBrowseButton, "selectObfuscationDictionaryFile"), constraintsLast);
+ obfuscationOptionsPanel.add(tip(classObfuscationDictionaryCheckBox, "classObfuscationDictionaryTip"), constraints);
+ obfuscationOptionsPanel.add(tip(classObfuscationDictionaryTextField, "inputFileTip"), constraintsStretch);
+ obfuscationOptionsPanel.add(tip(classObfucationDictionaryBrowseButton, "selectObfuscationDictionaryFile"), constraintsLast);
+ obfuscationOptionsPanel.add(tip(packageObfuscationDictionaryCheckBox, "packageObfuscationDictionaryTip"), constraints);
+ obfuscationOptionsPanel.add(tip(packageObfuscationDictionaryTextField, "inputFileTip"), constraintsStretch);
+ obfuscationOptionsPanel.add(tip(packageObfucationDictionaryBrowseButton, "selectObfuscationDictionaryFile"), constraintsLast);
+ obfuscationOptionsPanel.add(tip(overloadAggressivelyCheckBox, "overloadAggressivelyTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(useUniqueClassMemberNamesCheckBox, "useUniqueClassMemberNamesTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(useMixedCaseClassNamesCheckBox, "useMixedCaseClassNamesTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(keepPackageNamesCheckBox, "keepPackageNamesTip"), constraints);
+ obfuscationOptionsPanel.add(tip(keepPackageNamesTextField, "packageNamesTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(flattenPackageHierarchyCheckBox, "flattenPackageHierarchyTip"), constraints);
+ obfuscationOptionsPanel.add(tip(flattenPackageHierarchyTextField, "packageTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(repackageClassesCheckBox, "repackageClassesTip"), constraints);
+ obfuscationOptionsPanel.add(tip(repackageClassesTextField, "packageTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(keepAttributesCheckBox, "keepAttributesTip"), constraints);
+ obfuscationOptionsPanel.add(tip(keepAttributesTextField, "attributesTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(keepParameterNamesCheckBox, "keepParameterNamesTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(newSourceFileAttributeCheckBox, "renameSourceFileAttributeTip"), constraints);
+ obfuscationOptionsPanel.add(tip(newSourceFileAttributeTextField, "sourceFileAttributeTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(adaptClassStringsCheckBox, "adaptClassStringsTip"), constraints);
+ obfuscationOptionsPanel.add(tip(adaptClassStringsTextField, "classNamesTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(adaptResourceFileNamesCheckBox, "adaptResourceFileNamesTip"), constraints);
+ obfuscationOptionsPanel.add(tip(adaptResourceFileNamesTextField, "fileNameFilterTip"), constraintsLastStretch);
+ obfuscationOptionsPanel.add(tip(adaptResourceFileContentsCheckBox, "adaptResourceFileContentsTip"), constraints);
+ obfuscationOptionsPanel.add(tip(adaptResourceFileContentsTextField, "fileNameFilterTip"), constraintsLastStretch);
+
+ JPanel obfuscationPanel = new JPanel(layout);
+
+ obfuscationPanel.add(obfuscationOptionsPanel, panelConstraints);
+ addClassSpecifications(extractClassSpecifications(boilerplateKeepNames),
+ obfuscationPanel,
+ boilerplateKeepNamesCheckBoxes,
+ boilerplateKeepNamesTextFields);
+
+ addBorder(additionalKeepNamesPanel, "keepNamesAdditional");
+ obfuscationPanel.add(tip(additionalKeepNamesPanel, "keepNamesAdditionalTip"), stretchPanelConstraints);
+
+ // Create the boiler plate "no side effect methods" panels.
+ boilerplateNoSideEffectMethodCheckBoxes = new JCheckBox[boilerplateNoSideEffectMethods.length];
+
+ JPanel optimizationOptionsPanel = new JPanel(layout);
+ addBorder(optimizationOptionsPanel, "options");
+
+ JButton optimizationsButton =
+ createOptimizationsButton(optimizationsTextField);
+
+ optimizationOptionsPanel.add(tip(optimizeCheckBox, "optimizeTip"), constraintsLastStretch);
+ optimizationOptionsPanel.add(tip(allowAccessModificationCheckBox, "allowAccessModificationTip"), constraintsLastStretch);
+ optimizationOptionsPanel.add(tip(mergeInterfacesAggressivelyCheckBox, "mergeInterfacesAggressivelyTip"), constraintsLastStretch);
+ optimizationOptionsPanel.add(tip(optimizationsLabel, "optimizationsTip"), constraints);
+ optimizationOptionsPanel.add(tip(optimizationsTextField, "optimizationsFilterTip"), constraintsStretch);
+ optimizationOptionsPanel.add(tip(optimizationsButton, "optimizationsSelectTip"), constraintsLast);
+ optimizationOptionsPanel.add(tip(optimizationPassesLabel, "optimizationPassesTip"), constraints);
+ optimizationOptionsPanel.add(tip(optimizationPassesSpinner, "optimizationPassesTip"), constraintsLast);
+
+ JPanel optimizationPanel = new JPanel(layout);
+
+ optimizationPanel.add(optimizationOptionsPanel, panelConstraints);
+ addClassSpecifications(boilerplateNoSideEffectMethods,
+ optimizationPanel,
+ boilerplateNoSideEffectMethodCheckBoxes,
+ null);
+
+ addBorder(additionalNoSideEffectsPanel, "assumeNoSideEffectsAdditional");
+ optimizationPanel.add(tip(additionalNoSideEffectsPanel, "assumeNoSideEffectsAdditionalTip"), stretchPanelConstraints);
+
+ // Create the options panel.
+ JPanel preverificationOptionsPanel = new JPanel(layout);
+ addBorder(preverificationOptionsPanel, "preverificationAndTargeting");
+
+ preverificationOptionsPanel.add(tip(preverifyCheckBox, "preverifyTip"), constraintsLastStretch);
+ preverificationOptionsPanel.add(tip(microEditionCheckBox, "microEditionTip"), constraintsLastStretch);
+ preverificationOptionsPanel.add(tip(targetCheckBox, "targetTip"), constraints);
+ preverificationOptionsPanel.add(tip(targetComboBox, "targetTip"), constraintsLast);
+
+ JButton printSeedsBrowseButton =
+ createBrowseButton(printSeedsTextField, msg("selectSeedsFile"));
+
+ JButton printConfigurationBrowseButton =
+ createBrowseButton(printConfigurationTextField, msg( "selectConfigurationFile"));
+
+ JButton dumpBrowseButton =
+ createBrowseButton(dumpTextField, msg("selectDumpFile"));
+
+ // Select the most recent target by default.
+ targetComboBox.setSelectedIndex(targetComboBox.getItemCount() - 1);
+
+ JPanel consistencyPanel = new JPanel(layout);
+ addBorder(consistencyPanel, "consistencyAndCorrectness");
+
+ consistencyPanel.add(tip(verboseCheckBox, "verboseTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(noteCheckBox, "noteTip"), constraints);
+ consistencyPanel.add(tip(noteTextField, "noteFilterTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(warnCheckBox, "warnTip"), constraints);
+ consistencyPanel.add(tip(warnTextField, "warnFilterTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(ignoreWarningsCheckBox, "ignoreWarningsTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(skipNonPublicLibraryClassesCheckBox, "skipNonPublicLibraryClassesTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(skipNonPublicLibraryClassMembersCheckBox, "skipNonPublicLibraryClassMembersTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(keepDirectoriesCheckBox, "keepDirectoriesTip"), constraints);
+ consistencyPanel.add(tip(keepDirectoriesTextField, "directoriesTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(forceProcessingCheckBox, "forceProcessingTip"), constraintsLastStretch);
+ consistencyPanel.add(tip(printSeedsCheckBox, "printSeedsTip"), constraints);
+ consistencyPanel.add(tip(printSeedsTextField, "outputFileTip"), constraintsStretch);
+ consistencyPanel.add(tip(printSeedsBrowseButton, "selectSeedsFile"), constraintsLast);
+ consistencyPanel.add(tip(printConfigurationCheckBox, "printConfigurationTip"), constraints);
+ consistencyPanel.add(tip(printConfigurationTextField, "outputFileTip"), constraintsStretch);
+ consistencyPanel.add(tip(printConfigurationBrowseButton, "selectConfigurationFile"), constraintsLast);
+ consistencyPanel.add(tip(dumpCheckBox, "dumpTip"), constraints);
+ consistencyPanel.add(tip(dumpTextField, "outputFileTip"), constraintsStretch);
+ consistencyPanel.add(tip(dumpBrowseButton, "selectDumpFile"), constraintsLast);
+
+ // Collect all components that are followed by text fields and make
+ // sure they are equally sized. That way the text fields start at the
+ // same horizontal position.
+ setCommonPreferredSize(Arrays.asList(new JComponent[] {
+ printMappingCheckBox,
+ applyMappingCheckBox,
+ flattenPackageHierarchyCheckBox,
+ repackageClassesCheckBox,
+ newSourceFileAttributeCheckBox,
+ }));
+
+ JPanel optionsPanel = new JPanel(layout);
+
+ optionsPanel.add(preverificationOptionsPanel, panelConstraints);
+ optionsPanel.add(consistencyPanel, panelConstraints);
+
+ addBorder(whyAreYouKeepingPanel, "whyAreYouKeeping");
+ optionsPanel.add(tip(whyAreYouKeepingPanel, "whyAreYouKeepingTip"), stretchPanelConstraints);
+
+ // Create the process panel.
+ consoleTextArea.setOpaque(false);
+ consoleTextArea.setEditable(false);
+ consoleTextArea.setLineWrap(false);
+ consoleTextArea.setWrapStyleWord(false);
+ JScrollPane consoleScrollPane = new JScrollPane(consoleTextArea);
+ consoleScrollPane.setBorder(new EmptyBorder(1, 1, 1, 1));
+ addBorder(consoleScrollPane, "processingConsole");
+
+ JPanel processPanel = new JPanel(layout);
+ processPanel.add(consoleScrollPane, stretchPanelConstraints);
+
+ // Create the load, save, and process buttons.
+ JButton loadButton = new JButton(msg("loadConfiguration"));
+ loadButton.addActionListener(new MyLoadConfigurationActionListener());
+
+ JButton viewButton = new JButton(msg("viewConfiguration"));
+ viewButton.addActionListener(new MyViewConfigurationActionListener());
+
+ JButton saveButton = new JButton(msg("saveConfiguration"));
+ saveButton.addActionListener(new MySaveConfigurationActionListener());
+
+ JButton processButton = new JButton(msg("process"));
+ processButton.addActionListener(new MyProcessActionListener());
+
+ // Create the ReTrace panel.
+ JPanel reTraceSettingsPanel = new JPanel(layout);
+ addBorder(reTraceSettingsPanel, "reTraceSettings");
+
+ JButton reTraceMappingBrowseButton = createBrowseButton(reTraceMappingTextField,
+ msg("selectApplyMappingFile"));
+
+ JLabel reTraceMappingLabel = new JLabel(msg("mappingFile"));
+ reTraceMappingLabel.setForeground(reTraceVerboseCheckBox.getForeground());
+
+ reTraceSettingsPanel.add(tip(reTraceVerboseCheckBox, "verboseTip"), constraintsLastStretch);
+ reTraceSettingsPanel.add(tip(reTraceMappingLabel, "mappingFileTip"), constraints);
+ reTraceSettingsPanel.add(tip(reTraceMappingTextField, "inputFileTip"), constraintsStretch);
+ reTraceSettingsPanel.add(tip(reTraceMappingBrowseButton, "selectApplyMappingFile"), constraintsLast);
+
+ stackTraceTextArea.setOpaque(true);
+ stackTraceTextArea.setEditable(true);
+ stackTraceTextArea.setLineWrap(false);
+ stackTraceTextArea.setWrapStyleWord(true);
+ JScrollPane stackTraceScrollPane = new JScrollPane(stackTraceTextArea);
+ addBorder(stackTraceScrollPane, "obfuscatedStackTrace");
+
+ reTraceTextArea.setOpaque(false);
+ reTraceTextArea.setEditable(false);
+ reTraceTextArea.setLineWrap(true);
+ reTraceTextArea.setWrapStyleWord(true);
+ JScrollPane reTraceScrollPane = new JScrollPane(reTraceTextArea);
+ reTraceScrollPane.setBorder(new EmptyBorder(1, 1, 1, 1));
+ addBorder(reTraceScrollPane, "deobfuscatedStackTrace");
+
+ JPanel reTracePanel = new JPanel(layout);
+ reTracePanel.add(reTraceSettingsPanel, panelConstraints);
+ reTracePanel.add(tip(stackTraceScrollPane, "obfuscatedStackTraceTip"), panelConstraints);
+ reTracePanel.add(reTraceScrollPane, stretchPanelConstraints);
+
+ // Create the load button.
+ JButton loadStackTraceButton = new JButton(msg("loadStackTrace"));
+ loadStackTraceButton.addActionListener(new MyLoadStackTraceActionListener());
+
+ JButton reTraceButton = new JButton(msg("reTrace"));
+ reTraceButton.addActionListener(new MyReTraceActionListener());
+
+ // Create the main tabbed pane.
+ TabbedPane tabs = new TabbedPane();
+ tabs.add(msg("proGuardTab"), proGuardPanel);
+ tabs.add(msg("inputOutputTab"), inputOutputPanel);
+ tabs.add(msg("shrinkingTab"), shrinkingPanel);
+ tabs.add(msg("obfuscationTab"), obfuscationPanel);
+ tabs.add(msg("optimizationTab"), optimizationPanel);
+ tabs.add(msg("informationTab"), optionsPanel);
+ tabs.add(msg("processTab"), processPanel);
+ tabs.add(msg("reTraceTab"), reTracePanel);
+ tabs.addImage(Toolkit.getDefaultToolkit().getImage(
+ this.getClass().getResource(TITLE_IMAGE_FILE)));
+
+ // Add the bottom buttons to each panel.
+ proGuardPanel .add(Box.createGlue(), glueConstraints);
+ proGuardPanel .add(tip(loadButton, "loadConfigurationTip"), bottomButtonConstraints);
+ proGuardPanel .add(createNextButton(tabs), lastBottomButtonConstraints);
+
+ inputOutputPanel .add(Box.createGlue(), glueConstraints);
+ inputOutputPanel .add(createPreviousButton(tabs), bottomButtonConstraints);
+ inputOutputPanel .add(createNextButton(tabs), lastBottomButtonConstraints);
+
+ shrinkingPanel .add(Box.createGlue(), glueConstraints);
+ shrinkingPanel .add(createPreviousButton(tabs), bottomButtonConstraints);
+ shrinkingPanel .add(createNextButton(tabs), lastBottomButtonConstraints);
+
+ obfuscationPanel .add(Box.createGlue(), glueConstraints);
+ obfuscationPanel .add(createPreviousButton(tabs), bottomButtonConstraints);
+ obfuscationPanel .add(createNextButton(tabs), lastBottomButtonConstraints);
+
+ optimizationPanel .add(Box.createGlue(), glueConstraints);
+ optimizationPanel .add(createPreviousButton(tabs), bottomButtonConstraints);
+ optimizationPanel .add(createNextButton(tabs), lastBottomButtonConstraints);
+
+ optionsPanel .add(Box.createGlue(), glueConstraints);
+ optionsPanel .add(createPreviousButton(tabs), bottomButtonConstraints);
+ optionsPanel .add(createNextButton(tabs), lastBottomButtonConstraints);
+
+ processPanel .add(Box.createGlue(), glueConstraints);
+ processPanel .add(createPreviousButton(tabs), bottomButtonConstraints);
+ processPanel .add(tip(viewButton, "viewConfigurationTip"), bottomButtonConstraints);
+ processPanel .add(tip(saveButton, "saveConfigurationTip"), bottomButtonConstraints);
+ processPanel .add(tip(processButton, "processTip"), lastBottomButtonConstraints);
+
+ reTracePanel .add(Box.createGlue(), glueConstraints);
+ reTracePanel .add(tip(loadStackTraceButton, "loadStackTraceTip"), bottomButtonConstraints);
+ reTracePanel .add(tip(reTraceButton, "reTraceTip"), lastBottomButtonConstraints);
+
+ // Add the main tabs to the frame.
+ getContentPane().add(tabs);
+
+ // Pack the entire GUI before setting some default values.
+ pack();
+
+ // Initialize the GUI settings to reasonable defaults.
+ loadConfiguration(this.getClass().getResource(DEFAULT_CONFIGURATION));
+ }
+
+
+ public void startSplash()
+ {
+ splashPanel.start();
+ }
+
+
+ public void skipSplash()
+ {
+ splashPanel.stop();
+ }
+
+
+ /**
+ * Loads the boilerplate keep class options from the boilerplate file
+ * into the boilerplate array.
+ */
+ private void loadBoilerplateConfiguration()
+ {
+ try
+ {
+ // Parse the boilerplate configuration file.
+ ConfigurationParser parser = new ConfigurationParser(
+ this.getClass().getResource(BOILERPLATE_CONFIGURATION),
+ System.getProperties());
+
+ Configuration configuration = new Configuration();
+
+ try
+ {
+ parser.parse(configuration);
+
+ // We're interested in the keep options.
+ boilerplateKeep =
+ extractKeepSpecifications(configuration.keep, false, false);
+
+ // We're interested in the keep options.
+ boilerplateKeepNames =
+ extractKeepSpecifications(configuration.keep, true, false);
+
+ // We're interested in the side effects options.
+ boilerplateNoSideEffectMethods = new ClassSpecification[configuration.assumeNoSideEffects.size()];
+ configuration.assumeNoSideEffects.toArray(boilerplateNoSideEffectMethods);
+ }
+ finally
+ {
+ parser.close();
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+
+
+ /**
+ * Returns an array containing the ClassSpecifications instances with
+ * matching flags.
+ */
+ private KeepClassSpecification[] extractKeepSpecifications(List keepSpecifications,
+ boolean allowShrinking,
+ boolean allowObfuscation)
+ {
+ List matches = new ArrayList();
+
+ for (int index = 0; index < keepSpecifications.size(); index++)
+ {
+ KeepClassSpecification keepClassSpecification = (KeepClassSpecification)keepSpecifications.get(index);
+ if (keepClassSpecification.allowShrinking == allowShrinking &&
+ keepClassSpecification.allowObfuscation == allowObfuscation)
+ {
+ matches.add(keepClassSpecification);
+ }
+ }
+
+ KeepClassSpecification[] matchingKeepClassSpecifications = new KeepClassSpecification[matches.size()];
+ matches.toArray(matchingKeepClassSpecifications);
+
+ return matchingKeepClassSpecifications;
+ }
+
+
+ /**
+ * Returns an array containing the ClassSpecification instances of the
+ * given array of KeepClassSpecification instances.
+ */
+ private ClassSpecification[] extractClassSpecifications(KeepClassSpecification[] keepClassSpecifications)
+ {
+ ClassSpecification[] classSpecifications = new ClassSpecification[keepClassSpecifications.length];
+
+ for (int index = 0; index < classSpecifications.length; index++)
+ {
+ classSpecifications[index] = keepClassSpecifications[index];
+ }
+
+ return classSpecifications;
+ }
+
+
+ /**
+ * Creates a panel with the given boiler plate class specifications.
+ */
+ private void addClassSpecifications(ClassSpecification[] boilerplateClassSpecifications,
+ JPanel classSpecificationsPanel,
+ JCheckBox[] boilerplateCheckBoxes,
+ JTextField[] boilerplateTextFields)
+ {
+ // Create some constraints that can be reused.
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.anchor = GridBagConstraints.WEST;
+ constraints.insets = new Insets(0, 4, 0, 4);
+
+ GridBagConstraints constraintsLastStretch = new GridBagConstraints();
+ constraintsLastStretch.gridwidth = GridBagConstraints.REMAINDER;
+ constraintsLastStretch.fill = GridBagConstraints.HORIZONTAL;
+ constraintsLastStretch.weightx = 1.0;
+ constraintsLastStretch.anchor = GridBagConstraints.WEST;
+ constraintsLastStretch.insets = constraints.insets;
+
+ GridBagConstraints panelConstraints = new GridBagConstraints();
+ panelConstraints.gridwidth = GridBagConstraints.REMAINDER;
+ panelConstraints.fill = GridBagConstraints.HORIZONTAL;
+ panelConstraints.weightx = 1.0;
+ panelConstraints.anchor = GridBagConstraints.NORTHWEST;
+ panelConstraints.insets = constraints.insets;
+
+ GridBagLayout layout = new GridBagLayout();
+
+ String lastPanelName = null;
+ JPanel keepSubpanel = null;
+ for (int index = 0; index < boilerplateClassSpecifications.length; index++)
+ {
+ // The panel structure is derived from the comments.
+ String comments = boilerplateClassSpecifications[index].comments;
+ int dashIndex = comments.indexOf('-');
+ int periodIndex = comments.indexOf('.', dashIndex);
+ String panelName = comments.substring(0, dashIndex).trim();
+ String optionName = comments.substring(dashIndex + 1, periodIndex).replace('_', '.').trim();
+ String toolTip = comments.substring(periodIndex + 1);
+ if (keepSubpanel == null || !panelName.equals(lastPanelName))
+ {
+ // Create a new keep subpanel and add it.
+ keepSubpanel = new JPanel(layout);
+ keepSubpanel.setBorder(BorderFactory.createTitledBorder(BORDER, panelName));
+ classSpecificationsPanel.add(keepSubpanel, panelConstraints);
+
+ lastPanelName = panelName;
+ }
+
+ // Add the check box to the subpanel.
+ JCheckBox boilerplateCheckBox = new JCheckBox(optionName);
+ boilerplateCheckBox.setToolTipText(toolTip);
+ boilerplateCheckBoxes[index] = boilerplateCheckBox;
+ keepSubpanel.add(boilerplateCheckBox,
+ boilerplateTextFields != null ?
+ constraints :
+ constraintsLastStretch);
+
+ if (boilerplateTextFields != null)
+ {
+ // Add the text field to the subpanel.
+ boilerplateTextFields[index] = new JTextField(40);
+ keepSubpanel.add(tip(boilerplateTextFields[index], "classNamesTip"), constraintsLastStretch);
+ }
+ }
+ }
+
+
+ /**
+ * Adds a standard border with the title that corresponds to the given key
+ * in the GUI resources.
+ */
+ private void addBorder(JComponent component, String titleKey)
+ {
+ Border oldBorder = component.getBorder();
+ Border newBorder = BorderFactory.createTitledBorder(BORDER, msg(titleKey));
+
+ component.setBorder(oldBorder == null ?
+ newBorder :
+ new CompoundBorder(newBorder, oldBorder));
+ }
+
+
+ /**
+ * Creates a Previous button for the given tabbed pane.
+ */
+ private JButton createPreviousButton(final TabbedPane tabbedPane)
+ {
+ JButton browseButton = new JButton(msg("previous"));
+ browseButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ tabbedPane.previous();
+ }
+ });
+
+ return browseButton;
+ }
+
+
+ /**
+ * Creates a Next button for the given tabbed pane.
+ */
+ private JButton createNextButton(final TabbedPane tabbedPane)
+ {
+ JButton browseButton = new JButton(msg("next"));
+ browseButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ tabbedPane.next();
+ }
+ });
+
+ return browseButton;
+ }
+
+
+ /**
+ * Creates a browse button that opens a file browser for the given text field.
+ */
+ private JButton createBrowseButton(final JTextField textField,
+ final String title)
+ {
+ JButton browseButton = new JButton(msg("browse"));
+ browseButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ // Update the file chooser.
+ fileChooser.setDialogTitle(title);
+ fileChooser.setSelectedFile(new File(textField.getText()));
+
+ int returnVal = fileChooser.showDialog(ProGuardGUI.this, msg("ok"));
+ if (returnVal == JFileChooser.APPROVE_OPTION)
+ {
+ // Update the text field.
+ textField.setText(fileChooser.getSelectedFile().getPath());
+ }
+ }
+ });
+
+ return browseButton;
+ }
+
+
+ protected JButton createOptimizationsButton(final JTextField textField)
+ {
+ final OptimizationsDialog optimizationsDialog = new OptimizationsDialog(ProGuardGUI.this);
+
+ JButton optimizationsButton = new JButton(msg("select"));
+ optimizationsButton.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ // Update the dialog.
+ optimizationsDialog.setFilter(textField.getText());
+
+ int returnValue = optimizationsDialog.showDialog();
+ if (returnValue == OptimizationsDialog.APPROVE_OPTION)
+ {
+ // Update the text field.
+ textField.setText(optimizationsDialog.getFilter());
+ }
+ }
+ });
+
+ return optimizationsButton;
+ }
+
+
+ /**
+ * Sets the preferred sizes of the given components to the maximum of their
+ * current preferred sizes.
+ */
+ private void setCommonPreferredSize(List components)
+ {
+ // Find the maximum preferred size.
+ Dimension maximumSize = null;
+ for (int index = 0; index < components.size(); index++)
+ {
+ JComponent component = (JComponent)components.get(index);
+ Dimension size = component.getPreferredSize();
+ if (maximumSize == null ||
+ size.getWidth() > maximumSize.getWidth())
+ {
+ maximumSize = size;
+ }
+ }
+
+ // Set the size that we found as the preferred size for all components.
+ for (int index = 0; index < components.size(); index++)
+ {
+ JComponent component = (JComponent)components.get(index);
+ component.setPreferredSize(maximumSize);
+ }
+ }
+
+
+ /**
+ * Updates to GUI settings to reflect the given ProGuard configuration.
+ */
+ private void setProGuardConfiguration(Configuration configuration)
+ {
+ // Set up the input and output jars and directories.
+ programPanel.setClassPath(configuration.programJars);
+ libraryPanel.setClassPath(configuration.libraryJars);
+
+ // Set up the boilerplate keep options.
+ for (int index = 0; index < boilerplateKeep.length; index++)
+ {
+ String classNames =
+ findMatchingKeepSpecifications(boilerplateKeep[index],
+ configuration.keep);
+
+ boilerplateKeepCheckBoxes[index].setSelected(classNames != null);
+ boilerplateKeepTextFields[index].setText(classNames == null ? "*" : classNames);
+ }
+
+
+ // Set up the boilerplate keep names options.
+ for (int index = 0; index < boilerplateKeepNames.length; index++)
+ {
+ String classNames =
+ findMatchingKeepSpecifications(boilerplateKeepNames[index],
+ configuration.keep);
+
+ boilerplateKeepNamesCheckBoxes[index].setSelected(classNames != null);
+ boilerplateKeepNamesTextFields[index].setText(classNames == null ? "*" : classNames);
+ }
+
+ // Set up the additional keep options. Note that the matched boilerplate
+ // options have been removed from the list.
+ additionalKeepPanel.setClassSpecifications(filteredKeepSpecifications(configuration.keep,
+ false));
+
+ // Set up the additional keep options. Note that the matched boilerplate
+ // options have been removed from the list.
+ additionalKeepNamesPanel.setClassSpecifications(filteredKeepSpecifications(configuration.keep,
+ true));
+
+
+ // Set up the boilerplate "no side effect methods" options.
+ for (int index = 0; index < boilerplateNoSideEffectMethods.length; index++)
+ {
+ boolean found =
+ findClassSpecification(boilerplateNoSideEffectMethods[index],
+ configuration.assumeNoSideEffects);
+
+ boilerplateNoSideEffectMethodCheckBoxes[index].setSelected(found);
+ }
+
+ // Set up the additional keep options. Note that the matched boilerplate
+ // options have been removed from the list.
+ additionalNoSideEffectsPanel.setClassSpecifications(configuration.assumeNoSideEffects);
+
+ // Set up the "why are you keeping" options.
+ whyAreYouKeepingPanel.setClassSpecifications(configuration.whyAreYouKeeping);
+
+ // Set up the other options.
+ shrinkCheckBox .setSelected(configuration.shrink);
+ printUsageCheckBox .setSelected(configuration.printUsage != null);
+
+ optimizeCheckBox .setSelected(configuration.optimize);
+ allowAccessModificationCheckBox .setSelected(configuration.allowAccessModification);
+ mergeInterfacesAggressivelyCheckBox .setSelected(configuration.mergeInterfacesAggressively);
+ optimizationPassesSpinner.getModel() .setValue(new Integer(configuration.optimizationPasses));
+
+ obfuscateCheckBox .setSelected(configuration.obfuscate);
+ printMappingCheckBox .setSelected(configuration.printMapping != null);
+ applyMappingCheckBox .setSelected(configuration.applyMapping != null);
+ obfuscationDictionaryCheckBox .setSelected(configuration.obfuscationDictionary != null);
+ classObfuscationDictionaryCheckBox .setSelected(configuration.classObfuscationDictionary != null);
+ packageObfuscationDictionaryCheckBox .setSelected(configuration.packageObfuscationDictionary != null);
+ overloadAggressivelyCheckBox .setSelected(configuration.overloadAggressively);
+ useUniqueClassMemberNamesCheckBox .setSelected(configuration.useUniqueClassMemberNames);
+ useMixedCaseClassNamesCheckBox .setSelected(configuration.useMixedCaseClassNames);
+ keepPackageNamesCheckBox .setSelected(configuration.keepPackageNames != null);
+ flattenPackageHierarchyCheckBox .setSelected(configuration.flattenPackageHierarchy != null);
+ repackageClassesCheckBox .setSelected(configuration.repackageClasses != null);
+ keepAttributesCheckBox .setSelected(configuration.keepAttributes != null);
+ keepParameterNamesCheckBox .setSelected(configuration.keepParameterNames);
+ newSourceFileAttributeCheckBox .setSelected(configuration.newSourceFileAttribute != null);
+ adaptClassStringsCheckBox .setSelected(configuration.adaptClassStrings != null);
+ adaptResourceFileNamesCheckBox .setSelected(configuration.adaptResourceFileNames != null);
+ adaptResourceFileContentsCheckBox .setSelected(configuration.adaptResourceFileContents != null);
+
+ preverifyCheckBox .setSelected(configuration.preverify);
+ microEditionCheckBox .setSelected(configuration.microEdition);
+ targetCheckBox .setSelected(configuration.targetClassVersion != 0);
+
+ verboseCheckBox .setSelected(configuration.verbose);
+ noteCheckBox .setSelected(configuration.note == null || !configuration.note.isEmpty());
+ warnCheckBox .setSelected(configuration.warn == null || !configuration.warn.isEmpty());
+ ignoreWarningsCheckBox .setSelected(configuration.ignoreWarnings);
+ skipNonPublicLibraryClassesCheckBox .setSelected(configuration.skipNonPublicLibraryClasses);
+ skipNonPublicLibraryClassMembersCheckBox.setSelected(configuration.skipNonPublicLibraryClassMembers);
+ keepDirectoriesCheckBox .setSelected(configuration.keepDirectories != null);
+ forceProcessingCheckBox .setSelected(configuration.lastModified == Long.MAX_VALUE);
+ printSeedsCheckBox .setSelected(configuration.printSeeds != null);
+ printConfigurationCheckBox .setSelected(configuration.printConfiguration != null);
+ dumpCheckBox .setSelected(configuration.dump != null);
+
+ printUsageTextField .setText(fileName(configuration.printUsage));
+ optimizationsTextField .setText(configuration.optimizations == null ? OPTIMIZATIONS_DEFAULT : ListUtil.commaSeparatedString(configuration.optimizations, true));
+ printMappingTextField .setText(fileName(configuration.printMapping));
+ applyMappingTextField .setText(fileName(configuration.applyMapping));
+ obfuscationDictionaryTextField .setText(fileName(configuration.obfuscationDictionary));
+ classObfuscationDictionaryTextField .setText(fileName(configuration.classObfuscationDictionary));
+ packageObfuscationDictionaryTextField .setText(fileName(configuration.packageObfuscationDictionary));
+ keepPackageNamesTextField .setText(configuration.keepPackageNames == null ? "" : ClassUtil.externalClassName(ListUtil.commaSeparatedString(configuration.keepPackageNames, true)));
+ flattenPackageHierarchyTextField .setText(configuration.flattenPackageHierarchy);
+ repackageClassesTextField .setText(configuration.repackageClasses);
+ keepAttributesTextField .setText(configuration.keepAttributes == null ? KEEP_ATTRIBUTE_DEFAULT : ListUtil.commaSeparatedString(configuration.keepAttributes, true));
+ newSourceFileAttributeTextField .setText(configuration.newSourceFileAttribute == null ? SOURCE_FILE_ATTRIBUTE_DEFAULT : configuration.newSourceFileAttribute);
+ adaptClassStringsTextField .setText(configuration.adaptClassStrings == null ? "" : ClassUtil.externalClassName(ListUtil.commaSeparatedString(configuration.adaptClassStrings, true)));
+ adaptResourceFileNamesTextField .setText(configuration.adaptResourceFileNames == null ? ADAPT_RESOURCE_FILE_NAMES_DEFAULT : ListUtil.commaSeparatedString(configuration.adaptResourceFileNames, true));
+ adaptResourceFileContentsTextField .setText(configuration.adaptResourceFileContents == null ? ADAPT_RESOURCE_FILE_CONTENTS_DEFAULT : ListUtil.commaSeparatedString(configuration.adaptResourceFileContents, true));
+ noteTextField .setText(ListUtil.commaSeparatedString(configuration.note, true));
+ warnTextField .setText(ListUtil.commaSeparatedString(configuration.warn, true));
+ keepDirectoriesTextField .setText(ListUtil.commaSeparatedString(configuration.keepDirectories, true));
+ printSeedsTextField .setText(fileName(configuration.printSeeds));
+ printConfigurationTextField .setText(fileName(configuration.printConfiguration));
+ dumpTextField .setText(fileName(configuration.dump));
+
+ if (configuration.targetClassVersion != 0)
+ {
+ targetComboBox.setSelectedItem(ClassUtil.externalClassVersion(configuration.targetClassVersion));
+ }
+ else
+ {
+ targetComboBox.setSelectedIndex(targetComboBox.getItemCount() - 1);
+ }
+
+ if (configuration.printMapping != null)
+ {
+ reTraceMappingTextField.setText(fileName(configuration.printMapping));
+ }
+ }
+
+
+ /**
+ * Returns the ProGuard configuration that reflects the current GUI settings.
+ */
+ private Configuration getProGuardConfiguration()
+ {
+ Configuration configuration = new Configuration();
+
+ // Get the input and output jars and directories.
+ configuration.programJars = programPanel.getClassPath();
+ configuration.libraryJars = libraryPanel.getClassPath();
+
+ List keep = new ArrayList();
+
+ // Collect the additional keep options.
+ List additionalKeep = additionalKeepPanel.getClassSpecifications();
+ if (additionalKeep != null)
+ {
+ keep.addAll(additionalKeep);
+ }
+
+ // Collect the additional keep names options.
+ List additionalKeepNames = additionalKeepNamesPanel.getClassSpecifications();
+ if (additionalKeepNames != null)
+ {
+ keep.addAll(additionalKeepNames);
+ }
+
+ // Collect the boilerplate keep options.
+ for (int index = 0; index < boilerplateKeep.length; index++)
+ {
+ if (boilerplateKeepCheckBoxes[index].isSelected())
+ {
+ keep.add(classSpecification(boilerplateKeep[index],
+ boilerplateKeepTextFields[index].getText()));
+ }
+ }
+
+ // Collect the boilerplate keep names options.
+ for (int index = 0; index < boilerplateKeepNames.length; index++)
+ {
+ if (boilerplateKeepNamesCheckBoxes[index].isSelected())
+ {
+ keep.add(classSpecification(boilerplateKeepNames[index],
+ boilerplateKeepNamesTextFields[index].getText()));
+ }
+ }
+
+ // Put the list of keep specifications in the configuration.
+ if (keep.size() > 0)
+ {
+ configuration.keep = keep;
+ }
+
+
+ // Collect the boilerplate "no side effect methods" options.
+ List noSideEffectMethods = new ArrayList();
+
+ for (int index = 0; index < boilerplateNoSideEffectMethods.length; index++)
+ {
+ if (boilerplateNoSideEffectMethodCheckBoxes[index].isSelected())
+ {
+ noSideEffectMethods.add(boilerplateNoSideEffectMethods[index]);
+ }
+ }
+
+ // Collect the additional "no side effect methods" options.
+ List additionalNoSideEffectOptions = additionalNoSideEffectsPanel.getClassSpecifications();
+ if (additionalNoSideEffectOptions != null)
+ {
+ noSideEffectMethods.addAll(additionalNoSideEffectOptions);
+ }
+
+ // Put the list of "no side effect methods" options in the configuration.
+ if (noSideEffectMethods.size() > 0)
+ {
+ configuration.assumeNoSideEffects = noSideEffectMethods;
+ }
+
+
+ // Collect the "why are you keeping" options.
+ configuration.whyAreYouKeeping = whyAreYouKeepingPanel.getClassSpecifications();
+
+
+ // Get the other options.
+ configuration.shrink = shrinkCheckBox .isSelected();
+ configuration.printUsage = printUsageCheckBox .isSelected() ? new File(printUsageTextField .getText()) : null;
+
+ configuration.optimize = optimizeCheckBox .isSelected();
+ configuration.allowAccessModification = allowAccessModificationCheckBox .isSelected();
+ configuration.mergeInterfacesAggressively = mergeInterfacesAggressivelyCheckBox .isSelected();
+ configuration.optimizations = optimizationsTextField.getText().length() > 1 ? ListUtil.commaSeparatedList(optimizationsTextField .getText()) : null;
+ configuration.optimizationPasses = ((SpinnerNumberModel)optimizationPassesSpinner.getModel()).getNumber().intValue();
+
+ configuration.obfuscate = obfuscateCheckBox .isSelected();
+ configuration.printMapping = printMappingCheckBox .isSelected() ? new File(printMappingTextField .getText()) : null;
+ configuration.applyMapping = applyMappingCheckBox .isSelected() ? new File(applyMappingTextField .getText()) : null;
+ configuration.obfuscationDictionary = obfuscationDictionaryCheckBox .isSelected() ? new File(obfuscationDictionaryTextField .getText()) : null;
+ configuration.classObfuscationDictionary = classObfuscationDictionaryCheckBox .isSelected() ? new File(classObfuscationDictionaryTextField .getText()) : null;
+ configuration.packageObfuscationDictionary = packageObfuscationDictionaryCheckBox .isSelected() ? new File(packageObfuscationDictionaryTextField .getText()) : null;
+ configuration.overloadAggressively = overloadAggressivelyCheckBox .isSelected();
+ configuration.useUniqueClassMemberNames = useUniqueClassMemberNamesCheckBox .isSelected();
+ configuration.useMixedCaseClassNames = useMixedCaseClassNamesCheckBox .isSelected();
+ configuration.keepPackageNames = keepPackageNamesCheckBox .isSelected() ? keepPackageNamesTextField.getText().length() > 0 ? ListUtil.commaSeparatedList(ClassUtil.internalClassName(keepPackageNamesTextField.getText())) : new ArrayList() : null;
+ configuration.flattenPackageHierarchy = flattenPackageHierarchyCheckBox .isSelected() ? ClassUtil.internalClassName(flattenPackageHierarchyTextField .getText()) : null;
+ configuration.repackageClasses = repackageClassesCheckBox .isSelected() ? ClassUtil.internalClassName(repackageClassesTextField .getText()) : null;
+ configuration.keepAttributes = keepAttributesCheckBox .isSelected() ? ListUtil.commaSeparatedList(keepAttributesTextField .getText()) : null;
+ configuration.keepParameterNames = keepParameterNamesCheckBox .isSelected();
+ configuration.newSourceFileAttribute = newSourceFileAttributeCheckBox .isSelected() ? newSourceFileAttributeTextField .getText() : null;
+ configuration.adaptClassStrings = adaptClassStringsCheckBox .isSelected() ? adaptClassStringsTextField.getText().length() > 0 ? ListUtil.commaSeparatedList(ClassUtil.internalClassName(adaptClassStringsTextField.getText())) : new ArrayList() : null;
+ configuration.adaptResourceFileNames = adaptResourceFileNamesCheckBox .isSelected() ? ListUtil.commaSeparatedList(adaptResourceFileNamesTextField .getText()) : null;
+ configuration.adaptResourceFileContents = adaptResourceFileContentsCheckBox .isSelected() ? ListUtil.commaSeparatedList(adaptResourceFileContentsTextField .getText()) : null;
+
+ configuration.preverify = preverifyCheckBox .isSelected();
+ configuration.microEdition = microEditionCheckBox .isSelected();
+ configuration.targetClassVersion = targetCheckBox .isSelected() ? ClassUtil.internalClassVersion(targetComboBox.getSelectedItem().toString()) : 0;
+
+ configuration.verbose = verboseCheckBox .isSelected();
+ configuration.note = noteCheckBox .isSelected() ? noteTextField.getText().length() > 0 ? ListUtil.commaSeparatedList(ClassUtil.internalClassName(noteTextField.getText())) : null : new ArrayList();
+ configuration.warn = warnCheckBox .isSelected() ? warnTextField.getText().length() > 0 ? ListUtil.commaSeparatedList(ClassUtil.internalClassName(warnTextField.getText())) : null : new ArrayList();
+ configuration.ignoreWarnings = ignoreWarningsCheckBox .isSelected();
+ configuration.skipNonPublicLibraryClasses = skipNonPublicLibraryClassesCheckBox .isSelected();
+ configuration.skipNonPublicLibraryClassMembers = skipNonPublicLibraryClassMembersCheckBox.isSelected();
+ configuration.keepDirectories = keepDirectoriesCheckBox .isSelected() ? keepDirectoriesTextField.getText().length() > 0 ? ListUtil.commaSeparatedList(ClassUtil.internalClassName(keepDirectoriesTextField.getText())) : new ArrayList() : null;
+ configuration.lastModified = forceProcessingCheckBox .isSelected() ? Long.MAX_VALUE : System.currentTimeMillis();
+ configuration.printSeeds = printSeedsCheckBox .isSelected() ? new File(printSeedsTextField .getText()) : null;
+ configuration.printConfiguration = printConfigurationCheckBox .isSelected() ? new File(printConfigurationTextField .getText()) : null;
+ configuration.dump = dumpCheckBox .isSelected() ? new File(dumpTextField .getText()) : null;
+
+ return configuration;
+ }
+
+
+ /**
+ * Looks in the given list for a class specification that is identical to
+ * the given template. Returns true if it is found, and removes the matching
+ * class specification as a side effect.
+ */
+ private boolean findClassSpecification(ClassSpecification classSpecificationTemplate,
+ List classSpecifications)
+ {
+ if (classSpecifications == null)
+ {
+ return false;
+ }
+
+ for (int index = 0; index < classSpecifications.size(); index++)
+ {
+ if (classSpecificationTemplate.equals(classSpecifications.get(index)))
+ {
+ // Remove the matching option as a side effect.
+ classSpecifications.remove(index);
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns the subset of the given list of keep specifications, with
+ * matching shrinking flag.
+ */
+ private List filteredKeepSpecifications(List keepSpecifications,
+ boolean allowShrinking)
+ {
+ List filteredKeepSpecifications = new ArrayList();
+
+ for (int index = 0; index < keepSpecifications.size(); index++)
+ {
+ KeepClassSpecification keepClassSpecification =
+ (KeepClassSpecification)keepSpecifications.get(index);
+
+ if (keepClassSpecification.allowShrinking == allowShrinking)
+ {
+ filteredKeepSpecifications.add(keepClassSpecification);
+ }
+ }
+
+ return filteredKeepSpecifications;
+ }
+
+
+ /**
+ * Looks in the given list for keep specifications that match the given
+ * template. Returns a comma-separated string of class names from
+ * matching keep specifications, and removes the matching keep
+ * specifications as a side effect.
+ */
+ private String findMatchingKeepSpecifications(KeepClassSpecification keepClassSpecificationTemplate,
+ List keepSpecifications)
+ {
+ if (keepSpecifications == null)
+ {
+ return null;
+ }
+
+ StringBuffer buffer = null;
+
+ for (int index = 0; index < keepSpecifications.size(); index++)
+ {
+ KeepClassSpecification listedKeepClassSpecification =
+ (KeepClassSpecification)keepSpecifications.get(index);
+ String className = listedKeepClassSpecification.className;
+ keepClassSpecificationTemplate.className = className;
+ if (keepClassSpecificationTemplate.equals(listedKeepClassSpecification))
+ {
+ if (buffer == null)
+ {
+ buffer = new StringBuffer();
+ }
+ else
+ {
+ buffer.append(',');
+ }
+ buffer.append(className == null ? "*" : ClassUtil.externalClassName(className));
+
+ // Remove the matching option as a side effect.
+ keepSpecifications.remove(index--);
+ }
+ }
+
+ return buffer == null ? null : buffer.toString();
+ }
+
+
+ /**
+ * Returns a class specification or keep specification, based on the given
+ * template and the class name to be filled in.
+ */
+ private ClassSpecification classSpecification(ClassSpecification classSpecificationTemplate,
+ String className)
+ {
+ // Create a copy of the template.
+ ClassSpecification classSpecification =
+ (ClassSpecification)classSpecificationTemplate.clone();
+
+ // Set the class name in the copy.
+ classSpecification.className =
+ className.equals("") ||
+ className.equals("*") ?
+ null :
+ ClassUtil.internalClassName(className);
+
+ // Return the modified copy.
+ return classSpecification;
+ }
+
+
+ // Methods and internal classes related to actions.
+
+ /**
+ * Loads the given ProGuard configuration into the GUI.
+ */
+ private void loadConfiguration(File file)
+ {
+ // Set the default directory and file in the file choosers.
+ configurationChooser.setSelectedFile(file.getAbsoluteFile());
+ fileChooser.setCurrentDirectory(file.getAbsoluteFile().getParentFile());
+
+ try
+ {
+ // Parse the configuration file.
+ ConfigurationParser parser = new ConfigurationParser(file,
+ System.getProperties());
+
+ Configuration configuration = new Configuration();
+
+ try
+ {
+ parser.parse(configuration);
+
+ // Let the GUI reflect the configuration.
+ setProGuardConfiguration(configuration);
+ }
+ catch (ParseException ex)
+ {
+ JOptionPane.showMessageDialog(getContentPane(),
+ msg("cantParseConfigurationFile", file.getPath()),
+ msg("warning"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ finally
+ {
+ parser.close();
+ }
+ }
+ catch (IOException ex)
+ {
+ JOptionPane.showMessageDialog(getContentPane(),
+ msg("cantOpenConfigurationFile", file.getPath()),
+ msg("warning"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+
+ /**
+ * Loads the given ProGuard configuration into the GUI.
+ */
+ private void loadConfiguration(URL url)
+ {
+ try
+ {
+ // Parse the configuration file.
+ ConfigurationParser parser = new ConfigurationParser(url,
+ System.getProperties());
+
+ Configuration configuration = new Configuration();
+
+ try
+ {
+ parser.parse(configuration);
+
+ // Let the GUI reflect the configuration.
+ setProGuardConfiguration(configuration);
+ }
+ catch (ParseException ex)
+ {
+ JOptionPane.showMessageDialog(getContentPane(),
+ msg("cantParseConfigurationFile", url),
+ msg("warning"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ finally
+ {
+ parser.close();
+ }
+ }
+ catch (IOException ex)
+ {
+ JOptionPane.showMessageDialog(getContentPane(),
+ msg("cantOpenConfigurationFile", url),
+ msg("warning"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+
+ /**
+ * Saves the current ProGuard configuration to the given file.
+ */
+ private void saveConfiguration(File file)
+ {
+ try
+ {
+ // Save the configuration file.
+ ConfigurationWriter writer = new ConfigurationWriter(file);
+ writer.write(getProGuardConfiguration());
+ writer.close();
+ }
+ catch (Exception ex)
+ {
+ JOptionPane.showMessageDialog(getContentPane(),
+ msg("cantSaveConfigurationFile", file.getPath()),
+ msg("warning"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+
+ /**
+ * Loads the given stack trace into the GUI.
+ */
+ private void loadStackTrace(File file)
+ {
+ try
+ {
+ StringBuffer buffer = new StringBuffer(1024);
+
+ Reader reader = new BufferedReader(new FileReader(file));
+ try
+ {
+ while (true)
+ {
+ int c = reader.read();
+ if (c < 0)
+ {
+ break;
+ }
+
+ buffer.append(c);
+ }
+ }
+ finally
+ {
+ reader.close();
+ }
+
+ // Put the stack trace in the text area.
+ stackTraceTextArea.setText(buffer.toString());
+ }
+ catch (IOException ex)
+ {
+ JOptionPane.showMessageDialog(getContentPane(),
+ msg("cantOpenStackTraceFile", fileName(file)),
+ msg("warning"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+
+ /**
+ * This ActionListener loads a ProGuard configuration file and initializes
+ * the GUI accordingly.
+ */
+ private class MyLoadConfigurationActionListener implements ActionListener
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ configurationChooser.setDialogTitle(msg("selectConfigurationFile"));
+
+ int returnValue = configurationChooser.showOpenDialog(ProGuardGUI.this);
+ if (returnValue == JFileChooser.APPROVE_OPTION)
+ {
+ loadConfiguration(configurationChooser.getSelectedFile());
+ }
+ }
+ }
+
+
+ /**
+ * This ActionListener saves a ProGuard configuration file based on the
+ * current GUI settings.
+ */
+ private class MySaveConfigurationActionListener implements ActionListener
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ configurationChooser.setDialogTitle(msg("saveConfigurationFile"));
+
+ int returnVal = configurationChooser.showSaveDialog(ProGuardGUI.this);
+ if (returnVal == JFileChooser.APPROVE_OPTION)
+ {
+ saveConfiguration(configurationChooser.getSelectedFile());
+ }
+ }
+ }
+
+
+ /**
+ * This ActionListener displays the ProGuard configuration specified by the
+ * current GUI settings.
+ */
+ private class MyViewConfigurationActionListener implements ActionListener
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ // Make sure System.out has not been redirected yet.
+ if (!systemOutRedirected)
+ {
+ consoleTextArea.setText("");
+
+ TextAreaOutputStream outputStream =
+ new TextAreaOutputStream(consoleTextArea);
+
+ try
+ {
+ // TODO: write out relative path names and path names with system properties.
+
+ // Write the configuration.
+ ConfigurationWriter writer = new ConfigurationWriter(outputStream);
+ try
+ {
+ writer.write(getProGuardConfiguration());
+ }
+ finally
+ {
+ writer.close();
+ }
+ }
+ catch (IOException ex)
+ {
+ // This shouldn't happen.
+ }
+
+ // Scroll to the top of the configuration.
+ consoleTextArea.setCaretPosition(0);
+ }
+ }
+ }
+
+
+ /**
+ * This ActionListener executes ProGuard based on the current GUI settings.
+ */
+ private class MyProcessActionListener implements ActionListener
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ // Make sure System.out has not been redirected yet.
+ if (!systemOutRedirected)
+ {
+ systemOutRedirected = true;
+
+ // Get the informational configuration file name.
+ File configurationFile = configurationChooser.getSelectedFile();
+ String configurationFileName = configurationFile != null ?
+ configurationFile.getName() :
+ msg("sampleConfigurationFileName");
+
+ // Create the ProGuard thread.
+ Thread proGuardThread =
+ new Thread(new ProGuardRunnable(consoleTextArea,
+ getProGuardConfiguration(),
+ configurationFileName));
+
+ // Run it.
+ proGuardThread.start();
+ }
+ }
+ }
+
+
+ /**
+ * This ActionListener loads an obfuscated stack trace from a file and puts
+ * it in the proper text area.
+ */
+ private class MyLoadStackTraceActionListener implements ActionListener
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ fileChooser.setDialogTitle(msg("selectStackTraceFile"));
+ fileChooser.setSelectedFile(null);
+
+ int returnValue = fileChooser.showOpenDialog(ProGuardGUI.this);
+ if (returnValue == JFileChooser.APPROVE_OPTION)
+ {
+
+ loadStackTrace(fileChooser.getSelectedFile());
+ }
+ }
+ }
+
+
+ /**
+ * This ActionListener executes ReTrace based on the current GUI settings.
+ */
+ private class MyReTraceActionListener implements ActionListener
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ // Make sure System.out has not been redirected yet.
+ if (!systemOutRedirected)
+ {
+ systemOutRedirected = true;
+
+ boolean verbose = reTraceVerboseCheckBox.isSelected();
+ File retraceMappingFile = new File(reTraceMappingTextField.getText());
+ String stackTrace = stackTraceTextArea.getText();
+
+ // Create the ReTrace runnable.
+ Runnable reTraceRunnable = new ReTraceRunnable(reTraceTextArea,
+ verbose,
+ retraceMappingFile,
+ stackTrace);
+
+ // Run it in this thread, because it won't take long anyway.
+ reTraceRunnable.run();
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the canonical file name for the given file, or the empty string
+ * if the file name is empty.
+ */
+ private String fileName(File file)
+ {
+ if (file == null)
+ {
+ return "";
+ }
+ else
+ {
+ try
+ {
+ return file.getCanonicalPath();
+ }
+ catch (IOException ex)
+ {
+ return file.getPath();
+ }
+ }
+ }
+
+
+ /**
+ * Attaches the tool tip from the GUI resources that corresponds to the
+ * given key, to the given component.
+ */
+ private static JComponent tip(JComponent component, String messageKey)
+ {
+ component.setToolTipText(msg(messageKey));
+
+ return component;
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private static String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key and argument.
+ */
+ private String msg(String messageKey,
+ Object messageArgument)
+ {
+ return GUIResources.getMessage(messageKey, new Object[] {messageArgument});
+ }
+
+
+ /**
+ * The main method for the ProGuard GUI.
+ */
+ public static void main(final String[] args)
+ {
+ try
+ {
+ SwingUtil.invokeAndWait(new Runnable()
+ {
+ public void run()
+ {
+ try
+ {
+ ProGuardGUI gui = new ProGuardGUI();
+
+ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ Dimension guiSize = gui.getSize();
+ gui.setLocation((screenSize.width - guiSize.width) / 2,
+ (screenSize.height - guiSize.height) / 2);
+ gui.show();
+
+ // Start the splash animation, unless specified otherwise.
+ int argIndex = 0;
+ if (argIndex < args.length &&
+ NO_SPLASH_OPTION.startsWith(args[argIndex]))
+ {
+ gui.skipSplash();
+ argIndex++;
+ }
+ else
+ {
+ gui.startSplash();
+ }
+
+ // Load an initial configuration, if specified.
+ if (argIndex < args.length)
+ {
+ gui.loadConfiguration(new File(args[argIndex]));
+ argIndex++;
+ }
+
+ if (argIndex < args.length)
+ {
+ System.out.println(gui.getClass().getName() + ": ignoring extra arguments [" + args[argIndex] + "...]");
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Internal problem starting the ProGuard GUI (" + e.getMessage() + ")");
+ }
+ }
+ });
+ }
+ catch (Exception e)
+ {
+ System.out.println("Internal problem starting the ProGuard GUI (" + e.getMessage() + ")");
+ }
+ }
+}
diff --git a/src/proguard/gui/ProGuardRunnable.java b/src/proguard/gui/ProGuardRunnable.java
new file mode 100644
index 000000000..b341b7bb6
--- /dev/null
+++ b/src/proguard/gui/ProGuardRunnable.java
@@ -0,0 +1,154 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.*;
+
+import javax.swing.*;
+import java.awt.*;
+import java.io.PrintStream;
+
+
+/**
+ * This Runnable
runs ProGuard, sending console output to a text
+ * area and any exceptions to message dialogs.
+ *
+ * @see ProGuard
+ * @author Eric Lafortune
+ */
+final class ProGuardRunnable implements Runnable
+{
+ private final JTextArea consoleTextArea;
+ private final Configuration configuration;
+ private final String configurationFileName;
+
+
+ /**
+ * Creates a new ProGuardRunnable object.
+ * @param consoleTextArea the text area to send the console output to.
+ * @param configuration the ProGuard configuration.
+ * @param configurationFileName the optional file name of the configuration,
+ * for informational purposes.
+ */
+ public ProGuardRunnable(JTextArea consoleTextArea,
+ Configuration configuration,
+ String configurationFileName)
+ {
+ this.consoleTextArea = consoleTextArea;
+ this.configuration = configuration;
+ this.configurationFileName = configurationFileName;
+ }
+
+
+ // Implementation for Runnable.
+
+ public void run()
+ {
+ consoleTextArea.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ consoleTextArea.setText("");
+
+ // Redirect the System's out and err streams to the console text area.
+ PrintStream oldOut = System.out;
+ PrintStream oldErr = System.err;
+
+ PrintStream printStream =
+ new PrintStream(new TextAreaOutputStream(consoleTextArea), true);
+
+ System.setOut(printStream);
+ System.setErr(printStream);
+
+ try
+ {
+ // Create a new ProGuard object with the GUI's configuration.
+ ProGuard proGuard = new ProGuard(configuration);
+
+ // Run it.
+ proGuard.execute();
+
+ // Print out the completion message.
+ System.out.println("Processing completed successfully");
+ }
+ catch (Exception ex)
+ {
+ //ex.printStackTrace();
+
+ // Print out the exception message.
+ System.out.println(ex.getMessage());
+
+ // Show a dialog as well.
+ MessageDialogRunnable.showMessageDialog(consoleTextArea,
+ ex.getMessage(),
+ msg("errorProcessing"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ catch (OutOfMemoryError er)
+ {
+ // Forget about the ProGuard object as quickly as possible.
+ System.gc();
+
+ // Print out a message suggesting what to do next.
+ System.out.println(msg("outOfMemoryInfo", configurationFileName));
+
+ // Show a dialog as well.
+ MessageDialogRunnable.showMessageDialog(consoleTextArea,
+ msg("outOfMemory"),
+ msg("errorProcessing"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ finally
+ {
+ // Make sure all output has been sent to the console text area.
+ printStream.close();
+
+ // Restore the old System's out and err streams.
+ System.setOut(oldOut);
+ System.setErr(oldErr);
+ }
+
+ consoleTextArea.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+
+ // Reset the global static redirection lock.
+ ProGuardGUI.systemOutRedirected = false;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key and argument.
+ */
+ private String msg(String messageKey,
+ Object messageArgument)
+ {
+ return GUIResources.getMessage(messageKey, new Object[] {messageArgument});
+ }
+}
diff --git a/src/proguard/gui/ReTraceRunnable.java b/src/proguard/gui/ReTraceRunnable.java
new file mode 100644
index 000000000..6f1b13572
--- /dev/null
+++ b/src/proguard/gui/ReTraceRunnable.java
@@ -0,0 +1,149 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import proguard.retrace.ReTrace;
+
+import javax.swing.*;
+import java.awt.*;
+import java.io.*;
+
+
+/**
+ * This Runnable
runs ReTrace, sending console output to a text
+ * area and any exceptions to message dialogs.
+ *
+ * @see ReTrace
+ * @author Eric Lafortune
+ */
+final class ReTraceRunnable implements Runnable
+{
+ private final JTextArea consoleTextArea;
+ private final boolean verbose;
+ private final File mappingFile;
+ private final String stackTrace;
+
+
+ /**
+ * Creates a new ProGuardRunnable object.
+ * @param consoleTextArea the text area to send the console output to.
+ * @param verbose specifies whether the de-obfuscated stack trace
+ * should be verbose.
+ * @param mappingFile the mapping file that was written out by ProGuard.
+ */
+ public ReTraceRunnable(JTextArea consoleTextArea,
+ boolean verbose,
+ File mappingFile,
+ String stackTrace)
+ {
+ this.consoleTextArea = consoleTextArea;
+ this.verbose = verbose;
+ this.mappingFile = mappingFile;
+ this.stackTrace = stackTrace;
+ }
+
+
+ // Implementation for Runnable.
+
+ public void run()
+ {
+ consoleTextArea.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ consoleTextArea.setText("");
+
+ // Redirect the stack trace string to the System's in stream, and the
+ // out and err streams to the console text area.
+ InputStream oldIn = System.in;
+ PrintStream oldOut = System.out;
+ PrintStream oldErr = System.err;
+
+ ByteArrayInputStream inputStream =
+ new ByteArrayInputStream(stackTrace.getBytes());
+
+ PrintStream printStream =
+ new PrintStream(new TextAreaOutputStream(consoleTextArea), true);
+
+ System.setIn(inputStream);
+ System.setOut(printStream);
+ System.setErr(printStream);
+
+ try
+ {
+ // Create a new ProGuard object with the GUI's configuration.
+ ReTrace reTrace = new ReTrace(ReTrace.STACK_TRACE_EXPRESSION,
+ verbose,
+ mappingFile);
+
+ // Run it.
+ reTrace.execute();
+ }
+ catch (Exception ex)
+ {
+ // Print out the exception message.
+ System.out.println(ex.getMessage());
+
+ // Show a dialog as well.
+ MessageDialogRunnable.showMessageDialog(consoleTextArea,
+ ex.getMessage(),
+ msg("errorReTracing"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ catch (OutOfMemoryError er)
+ {
+ // Forget about the ProGuard object as quickly as possible.
+ System.gc();
+
+ // Print out a message suggesting what to do next.
+ System.out.println(msg("outOfMemory"));
+
+ // Show a dialog as well.
+ MessageDialogRunnable.showMessageDialog(consoleTextArea,
+ msg("outOfMemory"),
+ msg("errorReTracing"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+
+ // Make sure all output has been sent to the console text area.
+ printStream.flush();
+
+ // Restore the old System's in, out, and err streams.
+ System.setIn(oldIn);
+ System.setOut(oldOut);
+ System.setErr(oldErr);
+
+ consoleTextArea.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+ consoleTextArea.setCaretPosition(0);
+
+ // Reset the global static redirection lock.
+ ProGuardGUI.systemOutRedirected = false;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the message from the GUI resources that corresponds to the given
+ * key.
+ */
+ private String msg(String messageKey)
+ {
+ return GUIResources.getMessage(messageKey);
+ }
+}
diff --git a/src/proguard/gui/SwingUtil.java b/src/proguard/gui/SwingUtil.java
new file mode 100644
index 000000000..373fdc9d4
--- /dev/null
+++ b/src/proguard/gui/SwingUtil.java
@@ -0,0 +1,82 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import javax.swing.*;
+import java.lang.reflect.InvocationTargetException;
+
+
+/**
+ * This utility class provides variants of the invocation method from the
+ * SwingUtilities
class.
+ *
+ * @see SwingUtilities
+ * @author Eric Lafortune
+ */
+public class SwingUtil
+{
+ /**
+ * Invokes the given Runnable in the AWT event dispatching thread,
+ * and waits for it to finish. This method may be called from any thread,
+ * including the event dispatching thread itself.
+ * @see SwingUtilities#invokeAndWait(Runnable)
+ * @param runnable the Runnable to be executed.
+ */
+ public static void invokeAndWait(Runnable runnable)
+ throws InterruptedException, InvocationTargetException
+ {
+ try
+ {
+ if (SwingUtilities.isEventDispatchThread())
+ {
+ runnable.run();
+ }
+ else
+ {
+ SwingUtilities.invokeAndWait(runnable);
+ }
+ }
+ catch (Exception ex)
+ {
+ // Ignore any exceptions.
+ }
+ }
+
+
+ /**
+ * Invokes the given Runnable in the AWT event dispatching thread, not
+ * necessarily right away. This method may be called from any thread,
+ * including the event dispatching thread itself.
+ * @see SwingUtilities#invokeLater(Runnable)
+ * @param runnable the Runnable to be executed.
+ */
+ public static void invokeLater(Runnable runnable)
+ {
+ if (SwingUtilities.isEventDispatchThread())
+ {
+ runnable.run();
+ }
+ else
+ {
+ SwingUtilities.invokeLater(runnable);
+ }
+ }
+}
diff --git a/src/proguard/gui/TabbedPane.java b/src/proguard/gui/TabbedPane.java
new file mode 100644
index 000000000..c6b6678bd
--- /dev/null
+++ b/src/proguard/gui/TabbedPane.java
@@ -0,0 +1,229 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+
+
+/**
+ * This Jpanel
is similar to a JTabbedPane
.
+ * It uses buttons on the left-hand side to switch between panels.
+ * An image can be added below these buttons.
+ * Some methods are provided to switch between tabs.
+ *
+ * @author Eric Lafortune
+ */
+public class TabbedPane
+ extends JPanel
+{
+ private final CardLayout cardLayout = new CardLayout();
+ private final JPanel cardPanel = new JPanel(cardLayout);
+ private final ButtonGroup buttonGroup = new ButtonGroup();
+
+
+ /**
+ * Creates a new TabbedPane.
+ */
+ public TabbedPane()
+ {
+ GridBagLayout layout = new GridBagLayout();
+ setLayout(layout);
+
+ GridBagConstraints cardConstraints = new GridBagConstraints();
+ cardConstraints.gridx = 1;
+ cardConstraints.gridy = 0;
+ cardConstraints.gridheight = GridBagConstraints.REMAINDER;
+ cardConstraints.fill = GridBagConstraints.BOTH;
+ cardConstraints.weightx = 1.0;
+ cardConstraints.weighty = 1.0;
+ cardConstraints.anchor = GridBagConstraints.NORTHWEST;
+
+ add(cardPanel, cardConstraints);
+ }
+
+
+ /**
+ * Adds a component with a given title to the tabbed pane.
+ *
+ * @param title the title that will be used in the tab button.
+ * @param component the component that will be added as a tab.
+ */
+ public Component add(final String title, Component component)
+ {
+ GridBagConstraints buttonConstraints = new GridBagConstraints();
+ buttonConstraints.gridx = 0;
+ buttonConstraints.fill = GridBagConstraints.HORIZONTAL;
+ buttonConstraints.anchor = GridBagConstraints.NORTHWEST;
+ buttonConstraints.ipadx = 10;
+ buttonConstraints.ipady = 4;
+
+ JToggleButton button = new JToggleButton(title);
+
+ // Let the button react on the mouse press, instead of waiting for the
+ // mouse release.
+ button.setModel(new JToggleButton.ToggleButtonModel()
+ {
+ public void setPressed(boolean b)
+ {
+ if ((isPressed() == b) || !isEnabled())
+ {
+ return;
+ }
+
+ if (!b && isArmed())
+ {
+ setSelected(!this.isSelected());
+ }
+
+ if (b)
+ {
+ stateMask |= PRESSED;
+ }
+ else
+ {
+ stateMask &= ~PRESSED;
+ }
+
+ fireStateChanged();
+
+ if (isPressed())
+ {
+ fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getActionCommand()));
+ }
+ }
+
+ });
+
+ // Switch to the tab on a button press.
+ button.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ cardLayout.show(cardPanel, title);
+ }
+ });
+
+ // Only one button can be selected at the same time.
+ buttonGroup.add(button);
+
+ // If this is the first tab, make sure its button is selected.
+ if (cardPanel.getComponentCount() == 0)
+ {
+ button.setSelected(true);
+ }
+
+ // Add the button and its panel.
+ add(button, buttonConstraints);
+ cardPanel.add(title, component);
+
+ return component;
+ }
+
+
+ /**
+ * Adds an image below the tab buttons, after all tabs have been added.
+ * The image will only be as visible as permitted by the available space.
+ *
+ * @param image the image.
+ * @return the component containing the image.
+ */
+ public Component addImage(final Image image)
+ {
+ GridBagConstraints imageConstraints = new GridBagConstraints();
+ imageConstraints.gridx = 0;
+ imageConstraints.weighty = 1.0;
+ imageConstraints.fill = GridBagConstraints.BOTH;
+ imageConstraints.anchor = GridBagConstraints.SOUTHWEST;
+
+ JButton component = new JButton(new ImageIcon(image));
+ component.setFocusPainted(false);
+ component.setFocusable(false);
+ component.setRequestFocusEnabled(false);
+ component.setRolloverEnabled(false);
+ component.setMargin(new Insets(0, 0, 0, 0));
+ component.setHorizontalAlignment(JButton.LEFT);
+ component.setVerticalAlignment(JButton.BOTTOM);
+ component.setPreferredSize(new Dimension(0, 0));
+
+ add(component, imageConstraints);
+
+ return component;
+ }
+
+
+ /**
+ * Selects the first tab.
+ */
+ public void first()
+ {
+ cardLayout.first(cardPanel);
+ updateButtonSelection();
+ }
+
+
+ /**
+ * Selects the last tab.
+ */
+ public void last()
+ {
+ cardLayout.last(cardPanel);
+ updateButtonSelection();
+ }
+
+
+ /**
+ * Selects the previous tab.
+ */
+ public void previous()
+ {
+ cardLayout.previous(cardPanel);
+ updateButtonSelection();
+ }
+
+
+ /**
+ * Selects the next tab.
+ */
+ public void next()
+ {
+ cardLayout.next(cardPanel);
+ updateButtonSelection();
+ }
+
+
+ /**
+ * Lets the button selection reflect the currently visible panel.
+ */
+ private void updateButtonSelection()
+ {
+ int count = cardPanel.getComponentCount();
+ for (int index = 0 ; index < count ; index++) {
+ Component card = cardPanel.getComponent(index);
+ if (card.isShowing())
+ {
+ JToggleButton button = (JToggleButton)getComponent(index+1);
+ button.setSelected(true);
+ }
+ }
+ }
+}
diff --git a/src/proguard/gui/TextAreaOutputStream.java b/src/proguard/gui/TextAreaOutputStream.java
new file mode 100644
index 000000000..84ba562a3
--- /dev/null
+++ b/src/proguard/gui/TextAreaOutputStream.java
@@ -0,0 +1,81 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui;
+
+import javax.swing.*;
+import java.io.*;
+import java.lang.reflect.InvocationTargetException;
+
+
+/**
+ * This PrintStream
appends its output to a given text area.
+ *
+ * @author Eric Lafortune
+ */
+final class TextAreaOutputStream extends FilterOutputStream implements Runnable
+{
+ private final JTextArea textArea;
+
+
+ public TextAreaOutputStream(JTextArea textArea)
+ {
+ super(new ByteArrayOutputStream());
+
+ this.textArea = textArea;
+ }
+
+
+ // Implementation for FilterOutputStream.
+
+ public void flush() throws IOException
+ {
+ super.flush();
+
+ try
+ {
+ // Append the accumulated buffer contents to the text area.
+ SwingUtil.invokeAndWait(this);
+ }
+ catch (Exception e)
+ {
+ // Nothing.
+ }
+ }
+
+
+ // Implementation for Runnable.
+
+ public void run()
+ {
+ ByteArrayOutputStream out = (ByteArrayOutputStream)super.out;
+
+ // Has any new text been written?
+ String text = out.toString();
+ if (text.length() > 0)
+ {
+ // Append the accumulated text to the text area.
+ textArea.append(text);
+
+ // Clear the buffer.
+ out.reset();
+ }
+ }
+}
diff --git a/src/proguard/gui/arrow.gif b/src/proguard/gui/arrow.gif
new file mode 100644
index 000000000..c58e34ea4
Binary files /dev/null and b/src/proguard/gui/arrow.gif differ
diff --git a/src/proguard/gui/boilerplate.pro b/src/proguard/gui/boilerplate.pro
new file mode 100644
index 000000000..711c07d6a
--- /dev/null
+++ b/src/proguard/gui/boilerplate.pro
@@ -0,0 +1,384 @@
+# Keep - Applications. Keep all application classes, along with their 'main'
+# methods.
+-keepclasseswithmembers public class * {
+ public static void main(java.lang.String[]);
+}
+
+# Keep - Applets. Keep all extensions of java.applet.Applet.
+-keep public class * extends java.applet.Applet
+
+# Keep - Servlets. Keep all extensions of javax.servlet.Servlet.
+-keep public class * extends javax.servlet.Servlet
+
+# Keep - Midlets. Keep all extensions of javax.microedition.midlet.MIDlet.
+-keep public class * extends javax.microedition.midlet.MIDlet
+
+# Keep - Xlets. Keep all extensions of javax.tv.xlet.Xlet.
+-keep public class * extends javax.tv.xlet.Xlet
+
+# Keep - Library. Keep all public and protected classes, fields, and methods.
+-keep public class * {
+ public protected null
to undo the fixing.
+ */
+ public void setOverrideColor(Color color)
+ {
+ this.overrideColor = color;
+ graphics.setColor(color != null ? color : this.color);
+ }
+
+ /**
+ * Fixes the Font of the Graphics2D.
+ *
+ * @param font the fixed Font, or null
to undo the fixing.
+ */
+ public void setOverrideFont(Font font)
+ {
+ this.overrideFont = font;
+ graphics.setFont(font != null ? font : this.font);
+ }
+
+ /**
+ * Fixes the Paint of the Graphics2D.
+ *
+ * @param paint the fixed Paint, or null
to undo the fixing.
+ */
+ public void setOverridePaint(Paint paint)
+ {
+ this.overridePaint = paint;
+ graphics.setPaint(paint != null ? paint : this.paint);
+ }
+
+ /**
+ * Fixes the Stroke of the Graphics2D.
+ *
+ * @param stroke the fixed Stroke, or null
to undo the fixing.
+ */
+ public void setOverrideStroke(Stroke stroke)
+ {
+ this.overrideStroke = stroke;
+ graphics.setStroke(stroke != null ? stroke : this.stroke);
+ }
+
+ /**
+ * Fixes the XORMode of the Graphics2D.
+ *
+ * @param color the fixed XORMode Color, or null
to undo the fixing.
+ */
+ public void setOverrideXORMode(Color color)
+ {
+ this.overrideXORMode = color;
+ if (color != null)
+ {
+ graphics.setXORMode(color);
+ }
+ else
+ {
+ graphics.setPaintMode();
+ }
+ }
+
+
+ // Implementations for Graphics2D.
+
+ public void setColor(Color color)
+ {
+ this.color = color;
+ if (overrideColor == null)
+ {
+ graphics.setColor(color);
+ }
+ }
+
+ public void setFont(Font font)
+ {
+ this.font = font;
+ if (overrideFont == null)
+ {
+ graphics.setFont(font);
+ }
+ }
+
+ public void setPaint(Paint paint)
+ {
+ this.paint = paint;
+ if (overridePaint == null)
+ {
+ graphics.setPaint(paint);
+ }
+ }
+
+ public void setStroke(Stroke stroke)
+ {
+ this.stroke = stroke;
+ if (overrideStroke == null)
+ {
+ graphics.setStroke(stroke);
+ }
+ }
+
+ public void setXORMode(Color color)
+ {
+ if (overrideXORMode == null)
+ {
+ graphics.setXORMode(color);
+ }
+ }
+
+ public void setPaintMode()
+ {
+ if (overrideXORMode == null)
+ {
+ graphics.setPaintMode();
+ }
+ }
+
+
+ public Color getColor()
+ {
+ return overrideColor != null ? color : graphics.getColor();
+ }
+
+ public Font getFont()
+ {
+ return overrideFont != null ? font : graphics.getFont();
+ }
+
+ public Paint getPaint()
+ {
+ return overridePaint != null ? paint : graphics.getPaint();
+ }
+
+ public Stroke getStroke()
+ {
+ return overrideStroke != null ? stroke : graphics.getStroke();
+ }
+
+
+ public Graphics create()
+ {
+ OverrideGraphics2D g = new OverrideGraphics2D((Graphics2D)graphics.create());
+ g.setOverrideColor(overrideColor);
+ g.setOverrideFont(overrideFont);
+ g.setOverridePaint(overridePaint);
+ g.setOverrideStroke(overrideStroke);
+
+ return g;
+ }
+
+ public Graphics create(int x, int y, int width, int height)
+ {
+ OverrideGraphics2D g = new OverrideGraphics2D((Graphics2D)graphics.create(x, y, width, height));
+ g.setOverrideColor(overrideColor);
+ g.setOverrideFont(overrideFont);
+ g.setOverridePaint(overridePaint);
+ g.setOverrideStroke(overrideStroke);
+
+ return g;
+ }
+
+
+ // Delegation for Graphics2D
+
+ public void addRenderingHints(Map hints)
+ {
+ graphics.addRenderingHints(hints);
+ }
+
+ public void clearRect(int x, int y, int width, int height)
+ {
+ graphics.clearRect(x, y, width, height);
+ }
+
+ public void clip(Shape s)
+ {
+ graphics.clip(s);
+ }
+
+ public void clipRect(int x, int y, int width, int height)
+ {
+ graphics.clipRect(x, y, width, height);
+ }
+
+ public void copyArea(int x, int y, int width, int height, int dx, int dy)
+ {
+ graphics.copyArea(x, y, width, height, dx, dy);
+ }
+
+ public void dispose()
+ {
+ graphics.dispose();
+ }
+
+ public void draw(Shape s)
+ {
+ graphics.draw(s);
+ }
+
+ public void draw3DRect(int x, int y, int width, int height, boolean raised)
+ {
+ graphics.draw3DRect(x, y, width, height, raised);
+ }
+
+ public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
+ {
+ graphics.drawArc(x, y, width, height, startAngle, arcAngle);
+ }
+
+ public void drawBytes(byte[] data, int offset, int length, int x, int y)
+ {
+ graphics.drawBytes(data, offset, length, x, y);
+ }
+
+ public void drawChars(char[] data, int offset, int length, int x, int y)
+ {
+ graphics.drawChars(data, offset, length, x, y);
+ }
+
+ public void drawGlyphVector(GlyphVector g, float x, float y)
+ {
+ graphics.drawGlyphVector(g, x, y);
+ }
+
+ public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
+ {
+ return graphics.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer);
+ }
+
+ public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
+ {
+ return graphics.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer);
+ }
+
+ public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
+ {
+ return graphics.drawImage(img, x, y, width, height, bgcolor, observer);
+ }
+
+ public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
+ {
+ return graphics.drawImage(img, x, y, width, height, observer);
+ }
+
+ public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
+ {
+ return graphics.drawImage(img, x, y, bgcolor, observer);
+ }
+
+ public boolean drawImage(Image img, int x, int y, ImageObserver observer)
+ {
+ return graphics.drawImage(img, x, y, observer);
+ }
+
+ public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs)
+ {
+ return graphics.drawImage(img, xform, obs);
+ }
+
+ public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y)
+ {
+ graphics.drawImage(img, op, x, y);
+ }
+
+ public void drawLine(int x1, int y1, int x2, int y2)
+ {
+ graphics.drawLine(x1, y1, x2, y2);
+ }
+
+ public void drawOval(int x, int y, int width, int height)
+ {
+ graphics.drawOval(x, y, width, height);
+ }
+
+ public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
+ {
+ graphics.drawPolygon(xPoints, yPoints, nPoints);
+ }
+
+ public void drawPolygon(Polygon p)
+ {
+ graphics.drawPolygon(p);
+ }
+
+ public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
+ {
+ graphics.drawPolyline(xPoints, yPoints, nPoints);
+ }
+
+ public void drawRect(int x, int y, int width, int height)
+ {
+ graphics.drawRect(x, y, width, height);
+ }
+
+ public void drawRenderableImage(RenderableImage img, AffineTransform xform)
+ {
+ graphics.drawRenderableImage(img, xform);
+ }
+
+ public void drawRenderedImage(RenderedImage img, AffineTransform xform)
+ {
+ graphics.drawRenderedImage(img, xform);
+ }
+
+ public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
+ {
+ graphics.drawRoundRect(x, y, width, height, arcWidth, arcHeight);
+ }
+
+ public void drawString(String s, float x, float y)
+ {
+ graphics.drawString(s, x, y);
+ }
+
+ public void drawString(String str, int x, int y)
+ {
+ graphics.drawString(str, x, y);
+ }
+
+ public void drawString(AttributedCharacterIterator iterator, float x, float y)
+ {
+ graphics.drawString(iterator, x, y);
+ }
+
+ public void drawString(AttributedCharacterIterator iterator, int x, int y)
+ {
+ graphics.drawString(iterator, x, y);
+ }
+
+ public boolean equals(Object obj)
+ {
+ return graphics.equals(obj);
+ }
+
+ public void fill(Shape s)
+ {
+ graphics.fill(s);
+ }
+
+ public void fill3DRect(int x, int y, int width, int height, boolean raised)
+ {
+ graphics.fill3DRect(x, y, width, height, raised);
+ }
+
+ public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
+ {
+ graphics.fillArc(x, y, width, height, startAngle, arcAngle);
+ }
+
+ public void fillOval(int x, int y, int width, int height)
+ {
+ graphics.fillOval(x, y, width, height);
+ }
+
+ public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
+ {
+ graphics.fillPolygon(xPoints, yPoints, nPoints);
+ }
+
+ public void fillPolygon(Polygon p)
+ {
+ graphics.fillPolygon(p);
+ }
+
+ public void fillRect(int x, int y, int width, int height)
+ {
+ graphics.fillRect(x, y, width, height);
+ }
+
+ public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
+ {
+ graphics.fillRoundRect(x, y, width, height, arcWidth, arcHeight);
+ }
+
+ public Color getBackground()
+ {
+ return graphics.getBackground();
+ }
+
+ public Shape getClip()
+ {
+ return graphics.getClip();
+ }
+
+ public Rectangle getClipBounds()
+ {
+ return graphics.getClipBounds();
+ }
+
+ public Rectangle getClipBounds(Rectangle r)
+ {
+ return graphics.getClipBounds(r);
+ }
+
+ public Rectangle getClipRect()
+ {
+ return graphics.getClipRect();
+ }
+
+ public Composite getComposite()
+ {
+ return graphics.getComposite();
+ }
+
+ public GraphicsConfiguration getDeviceConfiguration()
+ {
+ return graphics.getDeviceConfiguration();
+ }
+
+ public FontMetrics getFontMetrics()
+ {
+ return graphics.getFontMetrics();
+ }
+
+ public FontMetrics getFontMetrics(Font f)
+ {
+ return graphics.getFontMetrics(f);
+ }
+
+ public FontRenderContext getFontRenderContext()
+ {
+ return graphics.getFontRenderContext();
+ }
+
+ public Object getRenderingHint(Key hintKey)
+ {
+ return graphics.getRenderingHint(hintKey);
+ }
+
+ public RenderingHints getRenderingHints()
+ {
+ return graphics.getRenderingHints();
+ }
+
+ public AffineTransform getTransform()
+ {
+ return graphics.getTransform();
+ }
+
+ public int hashCode()
+ {
+ return graphics.hashCode();
+ }
+
+ public boolean hit(Rectangle rect, Shape s, boolean onStroke)
+ {
+ return graphics.hit(rect, s, onStroke);
+ }
+
+ public boolean hitClip(int x, int y, int width, int height)
+ {
+ return graphics.hitClip(x, y, width, height);
+ }
+
+ public void rotate(double theta)
+ {
+ graphics.rotate(theta);
+ }
+
+ public void rotate(double theta, double x, double y)
+ {
+ graphics.rotate(theta, x, y);
+ }
+
+ public void scale(double sx, double sy)
+ {
+ graphics.scale(sx, sy);
+ }
+
+ public void setBackground(Color color)
+ {
+ graphics.setBackground(color);
+ }
+
+ public void setClip(int x, int y, int width, int height)
+ {
+ graphics.setClip(x, y, width, height);
+ }
+
+ public void setClip(Shape clip)
+ {
+ graphics.setClip(clip);
+ }
+
+ public void setComposite(Composite comp)
+ {
+ graphics.setComposite(comp);
+ }
+
+ public void setRenderingHint(Key hintKey, Object hintValue)
+ {
+ graphics.setRenderingHint(hintKey, hintValue);
+ }
+
+ public void setRenderingHints(Map hints)
+ {
+ graphics.setRenderingHints(hints);
+ }
+
+ public void setTransform(AffineTransform Tx)
+ {
+ graphics.setTransform(Tx);
+ }
+
+ public void shear(double shx, double shy)
+ {
+ graphics.shear(shx, shy);
+ }
+
+ public String toString()
+ {
+ return graphics.toString();
+ }
+
+ public void transform(AffineTransform Tx)
+ {
+ graphics.transform(Tx);
+ }
+
+ public void translate(double tx, double ty)
+ {
+ graphics.translate(tx, ty);
+ }
+
+ public void translate(int x, int y)
+ {
+ graphics.translate(x, y);
+ }
+}
diff --git a/src/proguard/gui/splash/RectangleSprite.java b/src/proguard/gui/splash/RectangleSprite.java
new file mode 100644
index 000000000..547b54925
--- /dev/null
+++ b/src/proguard/gui/splash/RectangleSprite.java
@@ -0,0 +1,114 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This Sprite represents an animated rounded rectangle. It can optionally be filled.
+ *
+ * @author Eric Lafortune
+ */
+public class RectangleSprite implements Sprite
+{
+ private final boolean filled;
+ private final VariableColor color;
+ private final VariableInt x;
+ private final VariableInt y;
+ private final VariableInt width;
+ private final VariableInt height;
+ private final VariableInt arcWidth;
+ private final VariableInt arcHeight;
+
+
+ /**
+ * Creates a new rectangular RectangleSprite.
+ * @param filled specifies whether the rectangle should be filled.
+ * @param color the variable color of the rectangle.
+ * @param x the variable x-ordinate of the upper-left corner of the rectangle.
+ * @param y the variable y-ordinate of the upper-left corner of the rectangle.
+ * @param width the variable width of the rectangle.
+ * @param height the variable height of the rectangle.
+ */
+ public RectangleSprite(boolean filled,
+ VariableColor color,
+ VariableInt x,
+ VariableInt y,
+ VariableInt width,
+ VariableInt height)
+ {
+ this(filled, color, x, y, width, height, new ConstantInt(0), new ConstantInt(0));
+ }
+
+
+ /**
+ * Creates a new RectangleSprite with rounded corners.
+ * @param filled specifies whether the rectangle should be filled.
+ * @param color the variable color of the rectangle.
+ * @param x the variable x-ordinate of the upper-left corner of the rectangle.
+ * @param y the variable y-ordinate of the upper-left corner of the rectangle.
+ * @param width the variable width of the rectangle.
+ * @param height the variable height of the rectangle.
+ * @param arcWidth the variable width of the corner arcs.
+ * @param arcHeight the variable height of the corner arcs.
+ */
+ public RectangleSprite(boolean filled,
+ VariableColor color,
+ VariableInt x,
+ VariableInt y,
+ VariableInt width,
+ VariableInt height,
+ VariableInt arcWidth,
+ VariableInt arcHeight)
+ {
+ this.filled = filled;
+ this.color = color;
+ this.x = x;
+ this.y = y;
+ this.width = width;
+ this.height = height;
+ this.arcWidth = arcWidth;
+ this.arcHeight = arcHeight;
+ }
+
+ // Implementation for Sprite.
+
+ public void paint(Graphics graphics, long time)
+ {
+ graphics.setColor(color.getColor(time));
+
+ int xt = x.getInt(time);
+ int yt = y.getInt(time);
+ int w = width.getInt(time);
+ int h = height.getInt(time);
+ int aw = arcWidth.getInt(time);
+ int ah = arcHeight.getInt(time);
+
+ if (filled)
+ {
+ graphics.fillRoundRect(xt, yt, w, h, aw, ah);
+ }
+ else
+ {
+ graphics.drawRoundRect(xt, yt, w, h, aw, ah);
+ }
+ }
+}
diff --git a/src/proguard/gui/splash/SawToothTiming.java b/src/proguard/gui/splash/SawToothTiming.java
new file mode 100644
index 000000000..393f27e64
--- /dev/null
+++ b/src/proguard/gui/splash/SawToothTiming.java
@@ -0,0 +1,53 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This Timing ramps up linearly from 0 to 1 in a given repeated time interval.
+ *
+ * @author Eric Lafortune
+ */
+public class SawToothTiming implements Timing
+{
+ private final long period;
+ private final long phase;
+
+
+ /**
+ * Creates a new SawToothTiming.
+ * @param period the time period for a full cycle.
+ * @param phase the phase of the cycle, which is added to the actual time.
+ */
+ public SawToothTiming(long period, long phase)
+ {
+ this.period = period;
+ this.phase = phase;
+ }
+
+
+ // Implementation for Timing.
+
+ public double getTiming(long time)
+ {
+ // Compute the translated and scaled saw-tooth function.
+ return (double)((time + phase) % period) / (double)period;
+ }
+}
diff --git a/src/proguard/gui/splash/ShadowedSprite.java b/src/proguard/gui/splash/ShadowedSprite.java
new file mode 100644
index 000000000..fadca5f6e
--- /dev/null
+++ b/src/proguard/gui/splash/ShadowedSprite.java
@@ -0,0 +1,109 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This Sprite adds a drop shadow to another Sprite.
+ *
+ * @author Eric Lafortune
+ */
+public class ShadowedSprite implements Sprite
+{
+ private final VariableInt xOffset;
+ private final VariableInt yOffset;
+ private final VariableDouble alpha;
+ private final VariableInt blur;
+ private final Sprite sprite;
+
+ private float cachedAlpha = -1.0f;
+ private Color cachedColor;
+
+
+ /**
+ * Creates a new ShadowedSprite.
+ * @param xOffset the variable x-offset of the shadow, relative to the sprite itself.
+ * @param yOffset the variable y-offset of the shadow, relative to the sprite itself.
+ * @param alpha the variable darkness of the shadow (between 0 and 1).
+ * @param blur the variable blur of the shadow (0 for sharp shadows, 1 or
+ * more for increasingly blurry shadows).
+ * @param sprite the Sprite to be painted with its shadow.
+ */
+ public ShadowedSprite(VariableInt xOffset,
+ VariableInt yOffset,
+ VariableDouble alpha,
+ VariableInt blur,
+ Sprite sprite)
+ {
+ this.xOffset = xOffset;
+ this.yOffset = yOffset;
+ this.alpha = alpha;
+ this.blur = blur;
+ this.sprite = sprite;
+ }
+
+
+ // Implementation for Sprite.
+
+ public void paint(Graphics graphics, long time)
+ {
+ double l = alpha.getDouble(time);
+ int b = blur.getInt(time) + 1;
+
+ float a = 1.0f - (float)Math.pow(1.0 - l, 1.0/(b*b));
+ if (a != cachedAlpha)
+ {
+ cachedAlpha = a;
+ cachedColor = new Color(0f, 0f, 0f, a);
+ }
+
+ // Set up the shadow graphics.
+ //OverrideGraphics2D g = new OverrideGraphics2D((Graphics2D)graphics);
+ //g.setOverrideColor(cachedColor);
+
+ // Set the shadow color.
+ Color actualColor = graphics.getColor();
+ graphics.setColor(cachedColor);
+
+ int xo = xOffset.getInt(time) - b/2;
+ int yo = yOffset.getInt(time) - b/2;
+
+ // Draw the sprite's shadow.
+ for (int x = 0; x < b; x++)
+ {
+ for (int y = 0; y < b; y++)
+ {
+ int xt = xo + x;
+ int yt = yo + y;
+ graphics.translate(xt, yt);
+ sprite.paint(graphics, time);
+ graphics.translate(-xt, -yt);
+ }
+ }
+
+ // Restore the actual sprite color.
+ graphics.setColor(actualColor);
+
+ // Draw the sprite itself in the ordinary graphics.
+ sprite.paint(graphics, time);
+ }
+}
diff --git a/src/proguard/gui/splash/SineTiming.java b/src/proguard/gui/splash/SineTiming.java
new file mode 100644
index 000000000..ab3d0c132
--- /dev/null
+++ b/src/proguard/gui/splash/SineTiming.java
@@ -0,0 +1,53 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This Timing varies between 0 and 1, as a sine wave over time.
+ *
+ * @author Eric Lafortune
+ */
+public class SineTiming implements Timing
+{
+ private final long period;
+ private final long phase;
+
+
+ /**
+ * Creates a new SineTiming.
+ * @param period the time period for a full cycle.
+ * @param phase the phase of the cycle, which is added to the actual time.
+ */
+ public SineTiming(long period, long phase)
+ {
+ this.period = period;
+ this.phase = phase;
+ }
+
+
+ // Implementation for Timing.
+
+ public double getTiming(long time)
+ {
+ // Compute the translated and scaled sine function.
+ return 0.5 + 0.5 * Math.sin(2.0 * Math.PI * (time + phase) / period);
+ }
+}
diff --git a/src/proguard/gui/splash/SmoothTiming.java b/src/proguard/gui/splash/SmoothTiming.java
new file mode 100644
index 000000000..a691d3ce2
--- /dev/null
+++ b/src/proguard/gui/splash/SmoothTiming.java
@@ -0,0 +1,66 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This Timing ramps up smoothly from 0 to 1 in a given time interval.
+ *
+ * @author Eric Lafortune
+ */
+public class SmoothTiming implements Timing
+{
+ private final long fromTime;
+ private final long toTime;
+
+
+ /**
+ * Creates a new SmoothTiming.
+ * @param fromTime the time at which the timing starts ramping up from 0.
+ * @param toTime the time at which the timing stops ramping up at 1.
+ */
+ public SmoothTiming(long fromTime, long toTime)
+ {
+ this.fromTime = fromTime;
+ this.toTime = toTime;
+ }
+
+
+ // Implementation for Timing.
+
+ public double getTiming(long time)
+ {
+ if (time <= fromTime)
+ {
+ return 0.0;
+ }
+
+ if (time >= toTime)
+ {
+ return 1.0;
+ }
+
+ // Compute the linear interpolation.
+ double timing = (double) (time - fromTime) / (double) (toTime - fromTime);
+
+ // Smooth the interpolation at the ends.
+ return timing * timing * (3.0 - 2.0 * timing);
+ }
+}
diff --git a/src/proguard/gui/splash/SplashPanel.java b/src/proguard/gui/splash/SplashPanel.java
new file mode 100644
index 000000000..af959e9f9
--- /dev/null
+++ b/src/proguard/gui/splash/SplashPanel.java
@@ -0,0 +1,235 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import proguard.gui.SwingUtil;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * This JPanel renders an animated Sprite.
+ *
+ * @author Eric Lafortune
+ */
+public class SplashPanel extends JPanel
+{
+ private final MyAnimator animator = new MyAnimator();
+ private final MyRepainter repainter = new MyRepainter();
+
+ private final Sprite sprite;
+ private final double sleepFactor;
+
+ private long startTime = Long.MAX_VALUE;
+ private final long stopTime;
+
+ private volatile Thread animationThread;
+
+
+ /**
+ * Creates a new SplashPanel with the given Sprite, which will be animated
+ * indefinitely.
+ * @param sprite the Sprite that will be animated.
+ * @param processorLoad the fraction of processing time to be spend on
+ * animating the Sprite (between 0 and 1).
+ */
+ public SplashPanel(Sprite sprite, double processorLoad)
+ {
+ this(sprite, processorLoad, (long)Integer.MAX_VALUE);
+ }
+
+
+ /**
+ * Creates a new SplashPanel with the given Sprite, which will be animated
+ * for a limited period of time.
+ * @param sprite the Sprite that will be animated.
+ * @param processorLoad the fraction of processing time to be spend on
+ * animating the Sprite (between 0 and 1).
+ * @param stopTime the number of milliseconds after which the
+ * animation will be stopped automatically.
+ */
+ public SplashPanel(Sprite sprite, double processorLoad, long stopTime)
+ {
+ this.sprite = sprite;
+ this.sleepFactor = (1.0-processorLoad) / processorLoad;
+ this.stopTime = stopTime;
+
+ // Restart the animation on a mouse click.
+ addMouseListener(new MouseAdapter()
+ {
+ public void mouseClicked(MouseEvent e)
+ {
+ SplashPanel.this.start();
+ }
+ });
+ }
+
+
+ /**
+ * Starts the animation.
+ */
+ public void start()
+ {
+ // Go to the beginning of the animation.
+ startTime = System.currentTimeMillis();
+
+ // Make sure we have an animation thread running.
+ if (animationThread == null)
+ {
+ animationThread = new Thread(animator);
+ animationThread.start();
+ }
+ }
+
+
+ /**
+ * Stops the animation.
+ */
+ public void stop()
+ {
+ // Go to the end of the animation.
+ startTime = 0L;
+
+ // Let the animation thread stop itself.
+ animationThread = null;
+
+ // Repaint the SplashPanel one last time.
+ try
+ {
+ SwingUtil.invokeAndWait(repainter);
+ }
+ catch (InterruptedException ex)
+ {
+ // Nothing.
+ }
+ catch (InvocationTargetException ex)
+ {
+ // Nothing.
+ }
+ }
+
+
+ // Implementation for JPanel.
+
+ public void paintComponent(Graphics graphics)
+ {
+ super.paintComponent(graphics);
+
+ sprite.paint(graphics, System.currentTimeMillis() - startTime);
+ }
+
+
+ /**
+ * This Runnable makes sure its SplashPanel gets repainted regularly,
+ * depending on the targeted processor load.
+ */
+ private class MyAnimator implements Runnable
+ {
+ public void run()
+ {
+ try
+ {
+ while (animationThread != null)
+ {
+ // Check if we should stop the animation.
+ long time = System.currentTimeMillis();
+ if (time > startTime + stopTime)
+ {
+ animationThread = null;
+ }
+
+ // Do a repaint and time it.
+ SwingUtil.invokeAndWait(repainter);
+
+ // Sleep for a proportional while.
+ long repaintTime = System.currentTimeMillis() - time;
+ long sleepTime = (long)(sleepFactor * repaintTime);
+ if (sleepTime < 10L)
+ {
+ sleepTime = 10L;
+ }
+
+ Thread.sleep(sleepTime);
+ }
+ }
+ catch (InterruptedException ex)
+ {
+ // Nothing.
+ }
+ catch (InvocationTargetException ex)
+ {
+ // Nothing.
+ }
+ }
+ }
+
+
+ /**
+ * This Runnable repaints its SplashPanel.
+ */
+ private class MyRepainter implements Runnable
+ {
+ public void run()
+ {
+ SplashPanel.this.repaint();
+ }
+ }
+
+
+ /**
+ * A main method for testing the splash panel.
+ */
+ public static void main(String[] args)
+ {
+ JFrame frame = new JFrame();
+ frame.setTitle("Animation");
+ frame.setSize(800, 600);
+ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ Dimension frameSize = frame.getSize();
+ frame.setLocation((screenSize.width - frameSize.width) / 2,
+ (screenSize.height - frameSize.height) / 2);
+
+ Sprite sprite =
+ new ClipSprite(
+ new ConstantColor(Color.white),
+ new ConstantColor(Color.lightGray),
+ new CircleSprite(true,
+ new LinearInt(200, 600, new SineTiming(2345L, 0L)),
+ new LinearInt(200, 400, new SineTiming(3210L, 0L)),
+ new ConstantInt(150)),
+ new ColorSprite(new ConstantColor(Color.gray),
+ new FontSprite(new ConstantFont(new Font("sansserif", Font.BOLD, 90)),
+ new TextSprite(new ConstantString("ProGuard"),
+ new ConstantInt(200),
+ new ConstantInt(300)))));
+
+ SplashPanel panel = new SplashPanel(sprite, 0.5);
+ panel.setBackground(Color.white);
+
+ frame.getContentPane().add(panel);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.setVisible(true);
+
+ panel.start();
+ }
+}
diff --git a/src/proguard/gui/splash/Sprite.java b/src/proguard/gui/splash/Sprite.java
new file mode 100644
index 000000000..f1f6e72c3
--- /dev/null
+++ b/src/proguard/gui/splash/Sprite.java
@@ -0,0 +1,41 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This interface describes objects that can paint themselves, possibly varying
+ * as a function of time.
+ *
+ * @author Eric Lafortune
+ */
+public interface Sprite
+{
+ /**
+ * Paints the object.
+ *
+ * @param graphics the Graphics to paint on.
+ * @param time the time since the start of the animation, expressed in
+ * milliseconds.
+ */
+ public void paint(Graphics graphics, long time);
+}
diff --git a/src/proguard/gui/splash/TextSprite.java b/src/proguard/gui/splash/TextSprite.java
new file mode 100644
index 000000000..69bd4c768
--- /dev/null
+++ b/src/proguard/gui/splash/TextSprite.java
@@ -0,0 +1,89 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This Sprite represents a text.
+ *
+ * @author Eric Lafortune
+ */
+public class TextSprite implements Sprite
+{
+ private final VariableString[] text;
+ private final VariableInt spacing;
+ private final VariableInt x;
+ private final VariableInt y;
+
+
+ /**
+ * Creates a new TextSprite containing a single line of text.
+ * @param text the variable text string.
+ * @param x the variable x-coordinate of the lower-left corner of the text.
+ * @param y the variable y-coordinate of the lower-left corner of the text.
+ */
+ public TextSprite(VariableString text,
+ VariableInt x,
+ VariableInt y)
+ {
+ this(new VariableString[] { text }, new ConstantInt(0), x, y);
+ }
+
+
+ /**
+ * Creates a new TextSprite containing a multiple lines of text.
+ * @param text the variable text strings.
+ * @param spacing the variable spacing between the lines of text.
+ * @param x the variable x-coordinate of the lower-left corner of the
+ * first line of text.
+ * @param y the variable y-coordinate of the lower-left corner of the
+ * first line of text.
+ */
+ public TextSprite(VariableString[] text,
+ VariableInt spacing,
+ VariableInt x,
+ VariableInt y)
+ {
+
+ this.text = text;
+ this.spacing = spacing;
+ this.x = x;
+ this.y = y;
+ }
+
+
+ // Implementation for Sprite.
+
+ public void paint(Graphics graphics, long time)
+ {
+
+ int xt = x.getInt(time);
+ int yt = y.getInt(time);
+
+ int spacingt = spacing.getInt(time);
+
+ for (int index = 0; index < text.length; index++)
+ {
+ graphics.drawString(text[index].getString(time), xt, yt + index * spacingt);
+ }
+ }
+}
diff --git a/src/proguard/gui/splash/TimeSwitchSprite.java b/src/proguard/gui/splash/TimeSwitchSprite.java
new file mode 100644
index 000000000..dd292adf6
--- /dev/null
+++ b/src/proguard/gui/splash/TimeSwitchSprite.java
@@ -0,0 +1,75 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This Sprite displays another Sprite in a given time interval.
+ * The time of the encapsulated Sprite is shifted by the start time.
+ *
+ * @author Eric Lafortune
+ */
+public class TimeSwitchSprite implements Sprite
+{
+ private final long onTime;
+ private final long offTime;
+ private final Sprite sprite;
+
+
+ /**
+ * Creates a new TimeSwitchSprite for displaying a given Sprite starting at
+ * a given time.
+ * @param onTime the start time.
+ * @param sprite the toggled Sprite.
+ */
+ public TimeSwitchSprite(long onTime, Sprite sprite)
+ {
+ this(onTime, 0L, sprite);
+ }
+
+
+ /**
+ * Creates a new TimeSwitchSprite for displaying a given Sprite in a given
+ * time interval.
+ * @param onTime the start time.
+ * @param offTime the stop time.
+ * @param sprite the toggled Sprite.
+ */
+ public TimeSwitchSprite(long onTime, long offTime, Sprite sprite)
+ {
+ this.onTime = onTime;
+ this.offTime = offTime;
+ this.sprite = sprite;
+ }
+
+
+ // Implementation for Sprite.
+
+ public void paint(Graphics graphics, long time)
+ {
+ if (time >= onTime && (offTime <= 0 || time <= offTime))
+ {
+ sprite.paint(graphics, time - onTime);
+ }
+
+ }
+}
diff --git a/src/proguard/gui/splash/Timing.java b/src/proguard/gui/splash/Timing.java
new file mode 100644
index 000000000..bb159006d
--- /dev/null
+++ b/src/proguard/gui/splash/Timing.java
@@ -0,0 +1,34 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This interface maps a time to a normalized timing between 0 and 1.
+ *
+ * @author Eric Lafortune
+ */
+interface Timing
+{
+ /**
+ * Returns the timing for the given time.
+ */
+ public double getTiming(long time);
+}
diff --git a/src/proguard/gui/splash/TypeWriterString.java b/src/proguard/gui/splash/TypeWriterString.java
new file mode 100644
index 000000000..d304dcab7
--- /dev/null
+++ b/src/proguard/gui/splash/TypeWriterString.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This VariableString produces a String that grows linearly with respect to its
+ * Timing, as if it is being written on a typewriter. A cursor at the end
+ * precedes the typed characters.
+ *
+ * @author Eric Lafortune
+ */
+public class TypeWriterString implements VariableString
+{
+ private final String string;
+ private final Timing timing;
+
+ private int cachedLength = -1;
+ private String cachedString;
+
+
+ /**
+ * Creates a new TypeWriterString.
+ * @param string the basic String.
+ * @param timing the applied timing.
+ */
+ public TypeWriterString(String string, Timing timing)
+ {
+ this.string = string;
+ this.timing = timing;
+ }
+
+
+ // Implementation for VariableString.
+
+ public String getString(long time)
+ {
+ double t = timing.getTiming(time);
+
+ int stringLength = string.length();
+ int length = (int)(stringLength * t + 0.5);
+ if (length != cachedLength)
+ {
+ cachedLength = length;
+ cachedString = string.substring(0, length);
+ if (t > 0.0 && length < stringLength)
+ {
+ cachedString += "_";
+ }
+ }
+
+ return cachedString;
+ }
+}
diff --git a/src/proguard/gui/splash/VariableColor.java b/src/proguard/gui/splash/VariableColor.java
new file mode 100644
index 000000000..ce573aa1e
--- /dev/null
+++ b/src/proguard/gui/splash/VariableColor.java
@@ -0,0 +1,36 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This interface represents a Color that varies with time.
+ *
+ * @author Eric Lafortune
+ */
+interface VariableColor
+{
+ /**
+ * Returns the Color for the given time.
+ */
+ public Color getColor(long time);
+}
diff --git a/src/proguard/gui/splash/VariableDouble.java b/src/proguard/gui/splash/VariableDouble.java
new file mode 100644
index 000000000..73174036e
--- /dev/null
+++ b/src/proguard/gui/splash/VariableDouble.java
@@ -0,0 +1,34 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This interface represents a double that varies with time.
+ *
+ * @author Eric Lafortune
+ */
+interface VariableDouble
+{
+ /**
+ * Returns the double for the given time.
+ */
+ public double getDouble(long time);
+}
diff --git a/src/proguard/gui/splash/VariableFont.java b/src/proguard/gui/splash/VariableFont.java
new file mode 100644
index 000000000..0668c38f5
--- /dev/null
+++ b/src/proguard/gui/splash/VariableFont.java
@@ -0,0 +1,36 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This interface represents a Font that varies with time.
+ *
+ * @author Eric Lafortune
+ */
+interface VariableFont
+{
+ /**
+ * Returns the Font for the given time.
+ */
+ public Font getFont(long time);
+}
diff --git a/src/proguard/gui/splash/VariableInt.java b/src/proguard/gui/splash/VariableInt.java
new file mode 100644
index 000000000..b4523ef15
--- /dev/null
+++ b/src/proguard/gui/splash/VariableInt.java
@@ -0,0 +1,34 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This interface represents an integer that varies with time.
+ *
+ * @author Eric Lafortune
+ */
+interface VariableInt
+{
+ /**
+ * Returns the integer for the given time.
+ */
+ public int getInt(long time);
+}
diff --git a/src/proguard/gui/splash/VariableSizeFont.java b/src/proguard/gui/splash/VariableSizeFont.java
new file mode 100644
index 000000000..52b8ab26a
--- /dev/null
+++ b/src/proguard/gui/splash/VariableSizeFont.java
@@ -0,0 +1,65 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+import java.awt.*;
+
+/**
+ * This VariableFont varies in size with respect to its Timing.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableSizeFont implements VariableFont
+{
+ private final Font font;
+ private final VariableDouble size;
+
+ private float cachedSize = -1.0f;
+ private Font cachedFont;
+
+
+ /**
+ * Creates a new VariableSizeFont
+ * @param font the base font.
+ * @param size the variable size of the font.
+ */
+ public VariableSizeFont(Font font, VariableDouble size)
+ {
+ this.font = font;
+ this.size = size;
+ }
+
+
+ // Implementation for VariableFont.
+
+ public Font getFont(long time)
+ {
+ float s = (float)size.getDouble(time);
+
+ if (s != cachedSize)
+ {
+ cachedSize = s;
+ cachedFont = font.deriveFont((float)s);
+ }
+
+ return cachedFont;
+ }
+}
diff --git a/src/proguard/gui/splash/VariableString.java b/src/proguard/gui/splash/VariableString.java
new file mode 100644
index 000000000..81ca8f6ea
--- /dev/null
+++ b/src/proguard/gui/splash/VariableString.java
@@ -0,0 +1,34 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.gui.splash;
+
+/**
+ * This interface represents a String that varies with time.
+ *
+ * @author Eric Lafortune
+ */
+interface VariableString
+{
+ /**
+ * Returns the String for the given time.
+ */
+ public String getString(long time);
+}
diff --git a/src/proguard/gui/splash/package.html b/src/proguard/gui/splash/package.html
new file mode 100644
index 000000000..209fad7c1
--- /dev/null
+++ b/src/proguard/gui/splash/package.html
@@ -0,0 +1,4 @@
+
+This package contains a library for creating splash screens and animations
+with text, graphical elements, and some special effects.
+
diff --git a/src/proguard/gui/vtitle.png b/src/proguard/gui/vtitle.png
new file mode 100644
index 000000000..218f71620
Binary files /dev/null and b/src/proguard/gui/vtitle.png differ
diff --git a/src/proguard/io/CascadingDataEntryWriter.java b/src/proguard/io/CascadingDataEntryWriter.java
new file mode 100644
index 000000000..62f3bf701
--- /dev/null
+++ b/src/proguard/io/CascadingDataEntryWriter.java
@@ -0,0 +1,94 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.*;
+
+/**
+ * This DataEntryWriter delegates to a given DataEntryWriter, or failing that,
+ * to another given DataEntryWriter.
+ *
+ * @author Eric Lafortune
+ */
+public class CascadingDataEntryWriter implements DataEntryWriter
+{
+ private DataEntryWriter dataEntryWriter1;
+ private DataEntryWriter dataEntryWriter2;
+
+
+ /**
+ * Creates a new CascadingDataEntryWriter.
+ * @param dataEntryWriter1 the DataEntryWriter to which the writing will be
+ * delegated first.
+ * @param dataEntryWriter2 the DataEntryWriter to which the writing will be
+ * delegated, if the first one can't provide an
+ * output stream.
+ */
+ public CascadingDataEntryWriter(DataEntryWriter dataEntryWriter1,
+ DataEntryWriter dataEntryWriter2)
+ {
+ this.dataEntryWriter1 = dataEntryWriter1;
+ this.dataEntryWriter2 = dataEntryWriter2;
+ }
+
+
+ // Implementations for DataEntryWriter.
+
+
+ public boolean createDirectory(DataEntry dataEntry) throws IOException
+ {
+ // Try to create a directory with the first data entry writer, or
+ // otherwise with the second data entry writer.
+ return dataEntryWriter1.createDirectory(dataEntry) ||
+ dataEntryWriter2.createDirectory(dataEntry);
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry) throws IOException
+ {
+ return getOutputStream(dataEntry, null);
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry,
+ Finisher finisher) throws IOException
+ {
+ // Try to get an output stream from the first data entry writer.
+ OutputStream outputStream =
+ dataEntryWriter1.getOutputStream(dataEntry, finisher);
+
+ // Return it, if it's not null. Otherwise try to get an output stream
+ // from the second data entry writer.
+ return outputStream != null ?
+ outputStream :
+ dataEntryWriter2.getOutputStream(dataEntry, finisher);
+ }
+
+
+ public void close() throws IOException
+ {
+ dataEntryWriter1.close();
+ dataEntryWriter2.close();
+
+ dataEntryWriter1 = null;
+ dataEntryWriter2 = null;
+ }
+}
diff --git a/src/proguard/io/ClassFilter.java b/src/proguard/io/ClassFilter.java
new file mode 100644
index 000000000..aabc5bac8
--- /dev/null
+++ b/src/proguard/io/ClassFilter.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.ClassConstants;
+import proguard.util.ExtensionMatcher;
+
+import java.io.IOException;
+
+
+/**
+ * This DataEntryReader delegates to one of two other DataEntryReader instances,
+ * depending on the extension of the data entry.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassFilter extends FilteredDataEntryReader
+{
+ /**
+ * Creates a new ClassFilter that delegates reading classes to the
+ * given reader.
+ */
+ public ClassFilter(DataEntryReader classReader)
+ {
+ this(classReader, null);
+ }
+
+
+ /**
+ * Creates a new ClassFilter that delegates to either of the two given
+ * readers.
+ */
+ public ClassFilter(DataEntryReader classReader,
+ DataEntryReader dataEntryReader)
+ {
+ super(new DataEntryNameFilter(
+ new ExtensionMatcher(ClassConstants.CLASS_FILE_EXTENSION)),
+ classReader,
+ dataEntryReader);
+ }
+}
diff --git a/src/proguard/io/ClassReader.java b/src/proguard/io/ClassReader.java
new file mode 100644
index 000000000..0ad382ba4
--- /dev/null
+++ b/src/proguard/io/ClassReader.java
@@ -0,0 +1,115 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.*;
+import proguard.classfile.io.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+import java.io.*;
+
+/**
+ * This DataEntryReader applies a given ClassVisitor to the class
+ * definitions that it reads.
+ * isLibrary
flag.
+ * skipNonPublicLibraryClasses
flag is set.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassReader implements DataEntryReader
+{
+ private final boolean isLibrary;
+ private final boolean skipNonPublicLibraryClasses;
+ private final boolean skipNonPublicLibraryClassMembers;
+ private final WarningPrinter warningPrinter;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new DataEntryClassFilter for reading the specified
+ * Clazz objects.
+ */
+ public ClassReader(boolean isLibrary,
+ boolean skipNonPublicLibraryClasses,
+ boolean skipNonPublicLibraryClassMembers,
+ WarningPrinter warningPrinter,
+ ClassVisitor classVisitor)
+ {
+ this.isLibrary = isLibrary;
+ this.skipNonPublicLibraryClasses = skipNonPublicLibraryClasses;
+ this.skipNonPublicLibraryClassMembers = skipNonPublicLibraryClassMembers;
+ this.warningPrinter = warningPrinter;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for DataEntryReader.
+
+ public void read(DataEntry dataEntry) throws IOException
+ {
+ try
+ {
+ // Get the input stream.
+ InputStream inputStream = dataEntry.getInputStream();
+
+ // Wrap it into a data input stream.
+ DataInputStream dataInputStream = new DataInputStream(inputStream);
+
+ // Create a Clazz representation.
+ Clazz clazz;
+ if (isLibrary)
+ {
+ clazz = new LibraryClass();
+ clazz.accept(new LibraryClassReader(dataInputStream, skipNonPublicLibraryClasses, skipNonPublicLibraryClassMembers));
+ }
+ else
+ {
+ clazz = new ProgramClass();
+ clazz.accept(new ProgramClassReader(dataInputStream));
+ }
+
+ // Apply the visitor, if we have a real class.
+ String className = clazz.getName();
+ if (className != null)
+ {
+ if (!dataEntry.getName().replace(File.pathSeparatorChar, ClassConstants.INTERNAL_PACKAGE_SEPARATOR).equals(className+ClassConstants.CLASS_FILE_EXTENSION) &&
+ warningPrinter != null)
+ {
+ warningPrinter.print(className,
+ "Warning: class [" + dataEntry.getName() + "] unexpectedly contains class [" + ClassUtil.externalClassName(className) + "]");
+ }
+
+ clazz.accept(classVisitor);
+ }
+
+ dataEntry.closeInputStream();
+ }
+ catch (Exception ex)
+ {
+ throw (IOException)new IOException("Can't process class ["+dataEntry.getName()+"] ("+ex.getMessage()+")").initCause(ex);
+ }
+ }
+}
diff --git a/src/proguard/io/ClassRewriter.java b/src/proguard/io/ClassRewriter.java
new file mode 100644
index 000000000..97e8aef56
--- /dev/null
+++ b/src/proguard/io/ClassRewriter.java
@@ -0,0 +1,80 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.*;
+import proguard.classfile.io.ProgramClassWriter;
+
+import java.io.*;
+
+
+/**
+ * This DataEntryReader reads class entries and writes their corresponding
+ * versions from the ClassPool to a given DataEntryWriter.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassRewriter implements DataEntryReader
+{
+ private final ClassPool classPool;
+ private final DataEntryWriter dataEntryWriter;
+
+
+ public ClassRewriter(ClassPool classPool,
+ DataEntryWriter dataEntryWriter)
+ {
+ this.classPool = classPool;
+ this.dataEntryWriter = dataEntryWriter;
+ }
+
+
+ // Implementations for DataEntryReader.
+
+ public void read(DataEntry dataEntry) throws IOException
+ {
+ String inputName = dataEntry.getName();
+ String className = inputName.substring(0, inputName.length() - ClassConstants.CLASS_FILE_EXTENSION.length());
+
+ // Find the modified class corrsponding to the input entry.
+ ProgramClass programClass = (ProgramClass)classPool.getClass(className);
+ if (programClass != null)
+ {
+ // Rename the data entry if necessary.
+ String newClassName = programClass.getName();
+ if (!className.equals(newClassName))
+ {
+ dataEntry = new RenamedDataEntry(dataEntry, newClassName + ClassConstants.CLASS_FILE_EXTENSION);
+ }
+
+ // Get the output entry corresponding to this input entry.
+ OutputStream outputStream = dataEntryWriter.getOutputStream(dataEntry);
+ if (outputStream != null)
+ {
+ // Write the class to the output entry.
+ DataOutputStream classOutputStream = new DataOutputStream(outputStream);
+
+ new ProgramClassWriter(classOutputStream).visitProgramClass(programClass);
+
+ classOutputStream.flush();
+ }
+ }
+ }
+}
diff --git a/src/proguard/io/DataEntry.java b/src/proguard/io/DataEntry.java
new file mode 100644
index 000000000..681331bfc
--- /dev/null
+++ b/src/proguard/io/DataEntry.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.*;
+
+/**
+ * This interface describes a data entry, e.g. a ZIP entry, a file, or a
+ * directory.
+ *
+ * @author Eric Lafortune
+ */
+public interface DataEntry
+{
+ /**
+ * Returns the name of this data entry.
+ */
+ public String getName();
+
+ /**
+ * Returns whether the data entry represents a directory.
+ */
+ public boolean isDirectory();
+
+
+ /**
+ * Returns an input stream for reading the content of this data entry.
+ * The data entry may not represent a directory.
+ */
+ public InputStream getInputStream() throws IOException;
+
+
+ /**
+ * Closes the previously retrieved InputStream.
+ */
+ public void closeInputStream() throws IOException;
+
+
+ /**
+ * Returns the parent of this data entry, or null if it doesn't
+ * have one.
+ */
+ public DataEntry getParent();
+}
diff --git a/src/proguard/io/DataEntryClassWriter.java b/src/proguard/io/DataEntryClassWriter.java
new file mode 100644
index 000000000..e9f0327cb
--- /dev/null
+++ b/src/proguard/io/DataEntryClassWriter.java
@@ -0,0 +1,85 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.*;
+import proguard.classfile.io.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+import java.io.*;
+
+/**
+ * This ClassVisitor writes out the ProgramClass objects that it visits to the
+ * given DataEntry, modified to have the correct name.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryClassWriter
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final DataEntryWriter dataEntryWriter;
+ private final DataEntry templateDataEntry;
+
+
+ /**
+ * Creates a new DataEntryClassWriter for writing to the given
+ * DataEntryWriter, based on the given template DataEntry.
+ */
+ public DataEntryClassWriter(DataEntryWriter dataEntryWriter,
+ DataEntry templateDataEntry)
+ {
+ this.dataEntryWriter = dataEntryWriter;
+ this.templateDataEntry = templateDataEntry;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Rename the data entry if necessary.
+ String actualClassName = programClass.getName();
+ DataEntry actualDataEntry =
+ new RenamedDataEntry(templateDataEntry,
+ actualClassName + ClassConstants.CLASS_FILE_EXTENSION);
+
+ try
+ {
+ // Get the output entry corresponding to this input entry.
+ OutputStream outputStream = dataEntryWriter.getOutputStream(actualDataEntry);
+ if (outputStream != null)
+ {
+ // Write the class to the output entry.
+ DataOutputStream classOutputStream = new DataOutputStream(outputStream);
+
+ new ProgramClassWriter(classOutputStream).visitProgramClass(programClass);
+
+ classOutputStream.flush();
+ }
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException("Can't write program class ["+actualClassName+"] to ["+actualDataEntry+"] ("+e.getMessage()+")", e);
+ }
+ }
+}
diff --git a/src/proguard/io/DataEntryCopier.java b/src/proguard/io/DataEntryCopier.java
new file mode 100644
index 000000000..f63e3e888
--- /dev/null
+++ b/src/proguard/io/DataEntryCopier.java
@@ -0,0 +1,247 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.util.ExtensionMatcher;
+
+import java.io.*;
+
+
+/**
+ * This DataEntryReader writes the ZIP entries and files that it reads to a
+ * given DataEntryWriter.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryCopier implements DataEntryReader
+{
+ private static final int BUFFER_SIZE = 1024;
+
+ private final DataEntryWriter dataEntryWriter;
+ private final byte[] buffer = new byte[BUFFER_SIZE];
+
+
+
+ public DataEntryCopier(DataEntryWriter dataEntryWriter)
+ {
+ this.dataEntryWriter = dataEntryWriter;
+ }
+
+
+ // Implementations for DataEntryReader.
+
+ public void read(DataEntry dataEntry) throws IOException
+ {
+ try
+ {
+ if (dataEntry.isDirectory())
+ {
+ dataEntryWriter.createDirectory(dataEntry);
+ }
+ else
+ {
+ // Get the output entry corresponding to this input entry.
+ OutputStream outputStream = dataEntryWriter.getOutputStream(dataEntry);
+ if (outputStream != null)
+ {
+ InputStream inputStream = dataEntry.getInputStream();
+
+ // Copy the data from the input entry to the output entry.
+ copyData(inputStream, outputStream);
+
+ // Close the data entries.
+ dataEntry.closeInputStream();
+ }
+ }
+ }
+ catch (IOException ex)
+ {
+ System.err.println("Warning: can't write resource [" + dataEntry.getName() + "] (" + ex.getMessage() + ")");
+ }
+ }
+
+
+ /**
+ * Copies all data that it can read from the given input stream to the
+ * given output stream.
+ */
+ protected void copyData(InputStream inputStream,
+ OutputStream outputStream)
+ throws IOException
+ {
+ while (true)
+ {
+ int count = inputStream.read(buffer);
+ if (count < 0)
+ {
+ break;
+ }
+ outputStream.write(buffer, 0, count);
+ }
+
+ outputStream.flush();
+ }
+
+
+ /**
+ * A main method for testing file/jar/war/directory copying.
+ */
+ public static void main(String[] args)
+ {
+ try
+ {
+ String input = args[0];
+ String output = args[1];
+
+ boolean outputIsJar = output.endsWith(".jar");
+ boolean outputIsWar = output.endsWith(".war");
+ boolean outputIsEar = output.endsWith(".ear");
+ boolean outputIsZip = output.endsWith(".zip");
+
+ DataEntryWriter writer = new DirectoryWriter(new File(output),
+ outputIsJar ||
+ outputIsWar ||
+ outputIsEar ||
+ outputIsZip);
+
+ if (!outputIsJar)
+ {
+ // Zip up any zips, if necessary.
+ DataEntryWriter zipWriter = new JarWriter(writer);
+ if (outputIsZip)
+ {
+ // Always zip.
+ writer = zipWriter;
+ }
+ else
+ {
+ // Only zip up zips.
+ writer = new FilteredDataEntryWriter(new DataEntryParentFilter(
+ new DataEntryNameFilter(
+ new ExtensionMatcher(".zip"))),
+ zipWriter,
+ writer);
+ }
+
+ // Zip up any wars, if necessary.
+ DataEntryWriter warWriter = new JarWriter(writer);
+ if (outputIsWar)
+ {
+ // Always zip.
+ writer = warWriter;
+ }
+ else
+ {
+ // Only zip up wars.
+ writer = new FilteredDataEntryWriter(new DataEntryParentFilter(
+ new DataEntryNameFilter(
+ new ExtensionMatcher(".war"))),
+ warWriter,
+ writer);
+ }
+ }
+
+ // Zip up any jars, if necessary.
+ DataEntryWriter jarWriter = new JarWriter(writer);
+ if (outputIsJar)
+ {
+ // Always zip.
+ writer = jarWriter;
+ }
+ else
+ {
+ // Only zip up jars.
+ writer = new FilteredDataEntryWriter(new DataEntryParentFilter(
+ new DataEntryNameFilter(
+ new ExtensionMatcher(".jar"))),
+ jarWriter,
+ writer);
+ }
+
+
+ // Create the copying DataEntryReader.
+ DataEntryReader reader = new DataEntryCopier(writer);
+
+
+ boolean inputIsJar = input.endsWith(".jar");
+ boolean inputIsWar = input.endsWith(".war");
+ boolean inputIsZip = input.endsWith(".zip");
+
+ // Unzip any jars, if necessary.
+ DataEntryReader jarReader = new JarReader(reader);
+ if (inputIsJar)
+ {
+ // Always unzip.
+ reader = jarReader;
+ }
+ else
+ {
+ // Only unzip jar entries.
+ reader = new FilteredDataEntryReader(new DataEntryNameFilter(
+ new ExtensionMatcher(".jar")),
+ jarReader,
+ reader);
+
+ // Unzip any wars, if necessary.
+ DataEntryReader warReader = new JarReader(reader);
+ if (inputIsWar)
+ {
+ // Always unzip.
+ reader = warReader;
+ }
+ else
+ {
+ // Only unzip war entries.
+ reader = new FilteredDataEntryReader(new DataEntryNameFilter(
+ new ExtensionMatcher(".war")),
+ warReader,
+ reader);
+ }
+
+ // Unzip any zips, if necessary.
+ DataEntryReader zipReader = new JarReader(reader);
+ if (inputIsZip)
+ {
+ // Always unzip.
+ reader = zipReader;
+ }
+ else
+ {
+ // Only unzip zip entries.
+ reader = new FilteredDataEntryReader(new DataEntryNameFilter(
+ new ExtensionMatcher(".zip")),
+ zipReader,
+ reader);
+ }
+ }
+
+ DirectoryPump directoryReader = new DirectoryPump(new File(input));
+
+ directoryReader.pumpDataEntries(reader);
+
+ writer.close();
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/io/DataEntryDirectoryFilter.java b/src/proguard/io/DataEntryDirectoryFilter.java
new file mode 100644
index 000000000..5bf46bbce
--- /dev/null
+++ b/src/proguard/io/DataEntryDirectoryFilter.java
@@ -0,0 +1,40 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.util.StringMatcher;
+
+/**
+ * This DataEntryFilter filters data entries based on whether they represent
+ * directories.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryDirectoryFilter
+implements DataEntryFilter
+{
+ // Implementations for DataEntryFilter.
+
+ public boolean accepts(DataEntry dataEntry)
+ {
+ return dataEntry != null && dataEntry.isDirectory();
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/io/DataEntryFilter.java b/src/proguard/io/DataEntryFilter.java
new file mode 100644
index 000000000..b8b6b2078
--- /dev/null
+++ b/src/proguard/io/DataEntryFilter.java
@@ -0,0 +1,38 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+
+/**
+ * This interface provides a method to filter data entries.
+ *
+ * @author Eric Lafortune
+ */
+public interface DataEntryFilter
+{
+ /**
+ * Checks whether the filter accepts the given data entry.
+ * @param dataEntry the data entry to filter.
+ * @return a boolean indicating whether the filter accepts the given data
+ * entry.
+ */
+ public boolean accepts(DataEntry dataEntry);
+}
diff --git a/src/proguard/io/DataEntryNameFilter.java b/src/proguard/io/DataEntryNameFilter.java
new file mode 100644
index 000000000..5aebcddaa
--- /dev/null
+++ b/src/proguard/io/DataEntryNameFilter.java
@@ -0,0 +1,54 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.util.StringMatcher;
+
+/**
+ * This DataEntryFilter filters data entries based on whether their names match
+ * a given StringMatcher.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryNameFilter
+implements DataEntryFilter
+{
+ private final StringMatcher stringMatcher;
+
+
+ /**
+ * Creates a new DataEntryNameFilter.
+ * @param stringMatcher the string matcher that will be applied to the names
+ * of the filtered data entries.
+ */
+ public DataEntryNameFilter(StringMatcher stringMatcher)
+ {
+ this.stringMatcher = stringMatcher;
+ }
+
+
+ // Implementations for DataEntryFilter.
+
+ public boolean accepts(DataEntry dataEntry)
+ {
+ return dataEntry != null && stringMatcher.matches(dataEntry.getName());
+ }
+}
diff --git a/src/proguard/io/DataEntryObfuscator.java b/src/proguard/io/DataEntryObfuscator.java
new file mode 100644
index 000000000..c5742e98e
--- /dev/null
+++ b/src/proguard/io/DataEntryObfuscator.java
@@ -0,0 +1,150 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.*;
+import proguard.classfile.util.ClassUtil;
+
+import java.io.IOException;
+import java.util.Map;
+
+/**
+ * This DataEntryReader delegates to another DataEntryReader, renaming the
+ * data entries based on the renamed classes in the given ClassPool.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryObfuscator implements DataEntryReader
+{
+ private final ClassPool classPool;
+ private final Map packagePrefixMap;
+ private final DataEntryReader dataEntryReader;
+
+
+ /**
+ * Creates a new DataEntryObfuscator.
+ * @param classPool the class pool that maps from old names to new
+ * names.
+ * @param packagePrefixMap the map from old package prefixes to new package
+ * prefixes.
+ * @param dataEntryReader the DataEntryReader to which calls will be
+ * delegated.
+ */
+ public DataEntryObfuscator(ClassPool classPool,
+ Map packagePrefixMap,
+ DataEntryReader dataEntryReader)
+ {
+ this.classPool = classPool;
+ this.packagePrefixMap = packagePrefixMap;
+ this.dataEntryReader = dataEntryReader;
+ }
+
+
+ // Implementations for DataEntryReader.
+
+ public void read(DataEntry dataEntry) throws IOException
+ {
+ // Delegate to the actual data entry reader.
+ dataEntryReader.read(renamedDataEntry(dataEntry));
+ }
+
+
+ /**
+ * Create a renamed data entry, if possible.
+ */
+ private DataEntry renamedDataEntry(DataEntry dataEntry)
+ {
+ String dataEntryName = dataEntry.getName();
+
+ // Try to find a corresponding class name by removing increasingly
+ // long suffixes.
+ for (int suffixIndex = dataEntryName.length() - 1;
+ suffixIndex > 0;
+ suffixIndex--)
+ {
+ char c = dataEntryName.charAt(suffixIndex);
+ if (!Character.isLetterOrDigit(c))
+ {
+ // Chop off the suffix.
+ String className = dataEntryName.substring(0, suffixIndex);
+
+ // Did we get to the package separator?
+ if (c == ClassConstants.INTERNAL_PACKAGE_SEPARATOR)
+ {
+ break;
+ }
+
+ // Is there a class corresponding to the data entry?
+ Clazz clazz = classPool.getClass(className);
+ if (clazz != null)
+ {
+ // Did the class get a new name?
+ String newClassName = clazz.getName();
+ if (!className.equals(newClassName))
+ {
+ // Return a renamed data entry.
+ String newDataEntryName =
+ newClassName + dataEntryName.substring(suffixIndex);
+
+ return new RenamedDataEntry(dataEntry, newDataEntryName);
+ }
+ else
+ {
+ // Otherwise stop looking.
+ return dataEntry;
+ }
+ }
+ }
+ }
+
+ // Try to find a corresponding package name by increasingly removing
+ // more subpackages.
+ String packagePrefix = dataEntryName;
+ do
+ {
+ // Chop off the class name or the last subpackage name.
+ packagePrefix = ClassUtil.internalPackagePrefix(packagePrefix);
+
+ // Is there a package corresponding to the package prefix?
+ String newPackagePrefix = (String)packagePrefixMap.get(packagePrefix);
+ if (newPackagePrefix != null)
+ {
+ // Did the package get a new name?
+ if (!packagePrefix.equals(newPackagePrefix))
+ {
+ // Return a renamed data entry.
+ String newDataEntryName =
+ newPackagePrefix + dataEntryName.substring(packagePrefix.length());
+
+ return new RenamedDataEntry(dataEntry, newDataEntryName);
+ }
+ else
+ {
+ // Otherwise stop looking.
+ return dataEntry;
+ }
+ }
+ }
+ while (packagePrefix.length() > 0);
+
+ return dataEntry;
+ }
+}
diff --git a/src/proguard/io/DataEntryParentFilter.java b/src/proguard/io/DataEntryParentFilter.java
new file mode 100644
index 000000000..1cc199778
--- /dev/null
+++ b/src/proguard/io/DataEntryParentFilter.java
@@ -0,0 +1,51 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+/**
+ * This DataEntryFilter delegates filtering to a DataEntryFilter for its parent.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryParentFilter
+implements DataEntryFilter
+{
+ private final DataEntryFilter dataEntryFilter;
+
+
+ /**
+ * Creates a new ParentFilter.
+ * @param dataEntryFilter the filter that will be applied to the data
+ * entry's parent.
+ */
+ public DataEntryParentFilter(DataEntryFilter dataEntryFilter)
+ {
+ this.dataEntryFilter = dataEntryFilter;
+ }
+
+
+ // Implementations for DataEntryFilter.
+
+ public boolean accepts(DataEntry dataEntry)
+ {
+ return dataEntry != null && dataEntryFilter.accepts(dataEntry.getParent());
+ }
+}
diff --git a/src/proguard/io/DataEntryPump.java b/src/proguard/io/DataEntryPump.java
new file mode 100644
index 000000000..ddf946b96
--- /dev/null
+++ b/src/proguard/io/DataEntryPump.java
@@ -0,0 +1,43 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.IOException;
+
+
+/**
+ * This interface provides a method to pump data entries. The implementation
+ * determines the source and the type of the data entries. Typical examples
+ * are zip entries coming from a zip file of file entries coming from a
+ * directory structure. The reader can for instance collect the classes,
+ * or copy the resource files that are presented.
+ *
+ * @author Eric Lafortune
+ */
+public interface DataEntryPump
+{
+ /**
+ * Applies the given DataEntryReader to all data entries that the
+ * implementation can provide.
+ */
+ public void pumpDataEntries(DataEntryReader dataEntryReader)
+ throws IOException;
+}
diff --git a/src/proguard/io/DataEntryReader.java b/src/proguard/io/DataEntryReader.java
new file mode 100644
index 000000000..39dc82db0
--- /dev/null
+++ b/src/proguard/io/DataEntryReader.java
@@ -0,0 +1,38 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.IOException;
+
+
+/**
+ * This interface provides methods for reading data entries. The implementation
+ * determines what to do with the read data, if anything.
+ *
+ * @author Eric Lafortune
+ */
+public interface DataEntryReader
+{
+ /**
+ * Reads the given data entry.
+ */
+ public void read(DataEntry dataEntry) throws IOException;
+}
diff --git a/src/proguard/io/DataEntryRenamer.java b/src/proguard/io/DataEntryRenamer.java
new file mode 100644
index 000000000..99600aeca
--- /dev/null
+++ b/src/proguard/io/DataEntryRenamer.java
@@ -0,0 +1,104 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.ClassConstants;
+
+import java.io.IOException;
+import java.util.Map;
+
+/**
+ * This DataEntryReader delegates to another DataEntryReader, renaming the
+ * data entries based on the given map. Entries whose name does not appear
+ * in the map may be passed to an alternative DataEntryReader.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryRenamer implements DataEntryReader
+{
+ private final Map nameMap;
+ private final DataEntryReader renamedDataEntryReader;
+ private final DataEntryReader missingDataEntryReader;
+
+
+ /**
+ * Creates a new DataEntryRenamer.
+ * @param nameMap the map from old names to new names.
+ * @param renamedDataEntryReader the DataEntryReader to which renamed data
+ * entries will be passed.
+ */
+ public DataEntryRenamer(Map nameMap,
+ DataEntryReader renamedDataEntryReader)
+ {
+ this(nameMap, renamedDataEntryReader, null);
+ }
+
+
+ /**
+ * Creates a new DataEntryRenamer.
+ * @param nameMap the map from old names to new names.
+ * @param renamedDataEntryReader the DataEntryReader to which renamed data
+ * entries will be passed.
+ * @param missingDataEntryReader the optional DataEntryReader to which data
+ * entries that can't be renamed will be
+ * passed.
+ */
+ public DataEntryRenamer(Map nameMap,
+ DataEntryReader renamedDataEntryReader,
+ DataEntryReader missingDataEntryReader)
+ {
+ this.nameMap = nameMap;
+ this.renamedDataEntryReader = renamedDataEntryReader;
+ this.missingDataEntryReader = missingDataEntryReader;
+ }
+
+
+ // Implementations for DataEntryReader.
+
+ public void read(DataEntry dataEntry) throws IOException
+ {
+ String name = dataEntry.getName();
+
+ // Add a directory separator if necessary.
+ if (dataEntry.isDirectory() &&
+ name.length() > 0)
+ {
+ name += ClassConstants.INTERNAL_PACKAGE_SEPARATOR;
+ }
+
+ String newName = (String)nameMap.get(name);
+ if (newName != null)
+ {
+ // Remove the directory separator if necessary.
+ if (dataEntry.isDirectory() &&
+ newName.length() > 0)
+ {
+ newName = newName.substring(0, newName.length() - 1);
+ }
+
+ renamedDataEntryReader.read(new RenamedDataEntry(dataEntry, newName));
+ }
+ else if (missingDataEntryReader != null)
+ {
+ missingDataEntryReader.read(dataEntry);
+ }
+ }
+}
diff --git a/src/proguard/io/DataEntryRewriter.java b/src/proguard/io/DataEntryRewriter.java
new file mode 100644
index 000000000..ec0776710
--- /dev/null
+++ b/src/proguard/io/DataEntryRewriter.java
@@ -0,0 +1,148 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.*;
+
+import java.io.*;
+
+/**
+ * This DataEntryReader writes the resource data entries that it reads to a
+ * given DataEntryWriter, updating their contents based on the renamed classes
+ * in the given ClassPool.
+ *
+ * @author Eric Lafortune
+ */
+public class DataEntryRewriter extends DataEntryCopier
+{
+ private final ClassPool classPool;
+
+
+ /**
+ * Creates a new DataEntryRewriter.
+ */
+ public DataEntryRewriter(ClassPool classPool,
+ DataEntryWriter dataEntryWriter)
+ {
+ super(dataEntryWriter);
+
+ this.classPool = classPool;
+ }
+
+
+ // Implementations for DataEntryCopier.
+
+ protected void copyData(InputStream inputStream,
+ OutputStream outputStream)
+ throws IOException
+ {
+ Reader reader = new BufferedReader(new InputStreamReader(inputStream));
+ Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream));
+
+ copyData(reader, writer);
+
+ writer.flush();
+ outputStream.flush();
+ }
+
+
+ /**
+ * Copies all data that it can read from the given reader to the given
+ * writer.
+ */
+ protected void copyData(Reader reader,
+ Writer writer)
+ throws IOException
+ {
+ StringBuffer word = new StringBuffer();
+
+ while (true)
+ {
+ int i = reader.read();
+ if (i < 0)
+ {
+ break;
+ }
+
+ // Is the character part of a word?
+ char c = (char)i;
+ if (Character.isJavaIdentifierPart(c) ||
+ c == '.' ||
+ c == '-')
+ {
+ // Collect the characters in this word.
+ word.append(c);
+ }
+ else
+ {
+ // Write out the updated word, if any.
+ writeUpdatedWord(writer, word.toString());
+ word.setLength(0);
+
+ // Write out the character that terminated it.
+ writer.write(c);
+ }
+ }
+
+ // Write out the final word.
+ writeUpdatedWord(writer, word.toString());
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Writes the given word to the given writer, after having adapted it,
+ * based on the renamed class names.
+ */
+ private void writeUpdatedWord(Writer writer, String word)
+ throws IOException
+ {
+ if (word.length() > 0)
+ {
+ String newWord = word;
+
+ boolean containsDots = word.indexOf('.') >= 0;
+
+ // Replace dots by forward slashes.
+ String className = containsDots ?
+ word.replace('.', ClassConstants.INTERNAL_PACKAGE_SEPARATOR) :
+ word;
+
+ // Find the class corrsponding to the word.
+ Clazz clazz = classPool.getClass(className);
+ if (clazz != null)
+ {
+ // Update the word if necessary.
+ String newClassName = clazz.getName();
+ if (!className.equals(newClassName))
+ {
+ // Replace forward slashes by dots.
+ newWord = containsDots ?
+ newClassName.replace(ClassConstants.INTERNAL_PACKAGE_SEPARATOR, '.') :
+ newClassName;
+ }
+ }
+
+ writer.write(newWord);
+ }
+ }
+}
diff --git a/src/proguard/io/DataEntryWriter.java b/src/proguard/io/DataEntryWriter.java
new file mode 100644
index 000000000..871f823bf
--- /dev/null
+++ b/src/proguard/io/DataEntryWriter.java
@@ -0,0 +1,73 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.*;
+
+
+/**
+ * This interface provides methods for writing data entries, such as ZIP entries
+ * or files. The implementation determines to which type of data entry the
+ * data will be written.
+ *
+ * @author Eric Lafortune
+ */
+public interface DataEntryWriter
+{
+ /**
+ * Creates a directory.
+ * @param dataEntry the data entry for which the directory is to be created.
+ * @return whether the directory has been created.
+ */
+ public boolean createDirectory(DataEntry dataEntry) throws IOException;
+
+
+ /**
+ * Returns an output stream for writing data. The caller must not close
+ * the output stream; closing the output stream is the responsibility of
+ * the implementation of this interface.
+ * @param dataEntry the data entry for which the output stream is to be created.
+ * @return the output stream. The stream may be
null
to indicate
+ * that the data entry should not be written.
+ */
+ public OutputStream getOutputStream(DataEntry dataEntry) throws IOException;
+
+
+ /**
+ * Returns an output stream for writing data. The caller must not close
+ * the output stream; closing the output stream is the responsibility of
+ * the implementation of this interface.
+ * @param dataEntry the data entry for which the output stream is to be created.
+ * @param finisher the optional finisher that will be called before this
+ * class closes the output stream (at some later point in
+ * time) that will be returned (now).
+ * @return the output stream. The stream may be null
to indicate
+ * that the data entry should not be written.
+ */
+ public OutputStream getOutputStream(DataEntry dataEntry,
+ Finisher finisher) throws IOException;
+
+
+ /**
+ * Finishes writing all data entries.
+ */
+ public void close() throws IOException;
+}
diff --git a/src/proguard/io/DirectoryFilter.java b/src/proguard/io/DirectoryFilter.java
new file mode 100644
index 000000000..72e2e6de4
--- /dev/null
+++ b/src/proguard/io/DirectoryFilter.java
@@ -0,0 +1,58 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.ClassConstants;
+import proguard.util.ExtensionMatcher;
+
+import java.io.IOException;
+
+
+/**
+ * This DataEntryReader delegates to one of two other DataEntryReader instances,
+ * depending on whether the data entry represents a directory or not.
+ *
+ * @author Eric Lafortune
+ */
+public class DirectoryFilter extends FilteredDataEntryReader
+{
+ /**
+ * Creates a new ClassFilter that delegates reading directories to the
+ * given reader.
+ */
+ public DirectoryFilter(DataEntryReader directoryReader)
+ {
+ this (directoryReader, null);
+ }
+
+
+ /**
+ * Creates a new ClassFilter that delegates to either of the two given
+ * readers.
+ */
+ public DirectoryFilter(DataEntryReader directoryReader,
+ DataEntryReader otherReader)
+ {
+ super(new DataEntryDirectoryFilter(),
+ directoryReader,
+ otherReader);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/io/DirectoryPump.java b/src/proguard/io/DirectoryPump.java
new file mode 100644
index 000000000..cd6c2ab20
--- /dev/null
+++ b/src/proguard/io/DirectoryPump.java
@@ -0,0 +1,78 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.*;
+
+
+/**
+ * This class can read a given file or directory, recursively, applying a given
+ * DataEntryReader to all files it comes across.
+ *
+ * @author Eric Lafortune
+ */
+public class DirectoryPump implements DataEntryPump
+{
+ private final File directory;
+
+
+ public DirectoryPump(File directory)
+ {
+ this.directory = directory;
+ }
+
+
+ // Implementations for DataEntryPump.
+
+ public void pumpDataEntries(DataEntryReader dataEntryReader)
+ throws IOException
+ {
+ if (!directory.exists())
+ {
+ throw new IOException("No such file or directory");
+ }
+
+ readFiles(directory, dataEntryReader);
+ }
+
+
+ /**
+ * Reads the given subdirectory recursively, applying the given DataEntryReader
+ * to all files that are encountered.
+ */
+ private void readFiles(File file, DataEntryReader dataEntryReader)
+ throws IOException
+ {
+ // Pass the file data entry to the reader.
+ dataEntryReader.read(new FileDataEntry(directory, file));
+
+ if (file.isDirectory())
+ {
+ // Recurse into the subdirectory.
+ File[] files = file.listFiles();
+
+ for (int index = 0; index < files.length; index++)
+ {
+ readFiles(files[index], dataEntryReader);
+ }
+ }
+ }
+}
diff --git a/src/proguard/io/DirectoryWriter.java b/src/proguard/io/DirectoryWriter.java
new file mode 100644
index 000000000..7948ee225
--- /dev/null
+++ b/src/proguard/io/DirectoryWriter.java
@@ -0,0 +1,165 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.ClassConstants;
+
+import java.io.*;
+
+
+/**
+ * This DataEntryWriter writes data entries to individual files in a given
+ * directory.
+ *
+ * @author Eric Lafortune
+ */
+public class DirectoryWriter implements DataEntryWriter
+{
+ private final File baseFile;
+ private final boolean isFile;
+
+ private File currentFile;
+ private OutputStream currentOutputStream;
+ private Finisher currentFinisher;
+
+
+ /**
+ * Creates a new DirectoryWriter.
+ * @param baseFile the base directory to which all files will be written.
+ */
+ public DirectoryWriter(File baseFile,
+ boolean isFile)
+ {
+ this.baseFile = baseFile;
+ this.isFile = isFile;
+ }
+
+
+ // Implementations for DataEntryWriter.
+
+ public boolean createDirectory(DataEntry dataEntry) throws IOException
+ {
+ // Should we close the current file?
+ if (!isFile &&
+ currentFile != null)
+ {
+ closeEntry();
+ }
+
+ File directory = getFile(dataEntry);
+ if (!directory.exists() &&
+ !directory.mkdirs())
+ {
+ throw new IOException("Can't create directory [" + directory.getPath() + "]");
+ }
+
+ return true;
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry) throws IOException
+ {
+ return getOutputStream(dataEntry, null);
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry,
+ Finisher finisher) throws IOException
+ {
+ File file = getFile(dataEntry);
+
+ // Should we close the current file?
+ if (!isFile &&
+ currentFile != null &&
+ !currentFile.equals(file))
+ {
+ closeEntry();
+ }
+
+ // Do we need a new stream?
+ if (currentOutputStream == null)
+ {
+ // Make sure the parent directories exist.
+ File parentDirectory = file.getParentFile();
+ if (parentDirectory != null &&
+ !parentDirectory.exists() &&
+ !parentDirectory.mkdirs())
+ {
+ throw new IOException("Can't create directory [" + parentDirectory.getPath() + "]");
+ }
+
+ // Open a new output stream for writing to the file.
+ currentOutputStream =
+ new BufferedOutputStream(
+ new FileOutputStream(file));
+
+ currentFinisher = finisher;
+ currentFile = file;
+ }
+
+ return currentOutputStream;
+ }
+
+
+ public void close() throws IOException
+ {
+ // Close the file stream, if any.
+ closeEntry();
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the file for the given data entry.
+ */
+ private File getFile(DataEntry dataEntry)
+ {
+ // Use the specified file, or construct a new file.
+ return isFile ?
+ baseFile :
+ new File(baseFile,
+ dataEntry.getName().replace(ClassConstants.INTERNAL_PACKAGE_SEPARATOR,
+ File.separatorChar));
+ }
+
+
+ /**
+ * Closes the previous file, if any.
+ */
+ private void closeEntry() throws IOException
+ {
+ // Close the file stream, if any.
+ if (currentOutputStream != null)
+ {
+ // Let any finisher finish up first.
+ if (currentFinisher != null)
+ {
+ currentFinisher.finish();
+ currentFinisher = null;
+ }
+
+ currentOutputStream.close();
+ currentOutputStream = null;
+ currentFile = null;
+ }
+ }
+}
diff --git a/src/proguard/io/FileDataEntry.java b/src/proguard/io/FileDataEntry.java
new file mode 100644
index 000000000..618a092b0
--- /dev/null
+++ b/src/proguard/io/FileDataEntry.java
@@ -0,0 +1,96 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.ClassConstants;
+
+import java.io.*;
+
+/**
+ * This DataEntry
represents a file.
+ *
+ * @author Eric Lafortune
+ */
+public class FileDataEntry implements DataEntry
+{
+ private final File directory;
+ private final File file;
+ private InputStream inputStream;
+
+
+ public FileDataEntry(File directory,
+ File file)
+ {
+ this.directory = directory;
+ this.file = file;
+ }
+
+
+ // Implementations for DataEntry.
+
+ public String getName()
+ {
+ // Chop the directory name from the file name and get the right separators.
+ return file.equals(directory) ?
+ file.getName() :
+ file.getPath()
+ .substring(directory.getPath().length() + File.separator.length())
+ .replace(File.separatorChar, ClassConstants.INTERNAL_PACKAGE_SEPARATOR);
+ }
+
+
+ public boolean isDirectory()
+ {
+ return file.isDirectory();
+ }
+
+
+ public InputStream getInputStream() throws IOException
+ {
+ if (inputStream == null)
+ {
+ inputStream = new BufferedInputStream(new FileInputStream(file));
+ }
+
+ return inputStream;
+ }
+
+
+ public void closeInputStream() throws IOException
+ {
+ inputStream.close();
+ inputStream = null;
+ }
+
+
+ public DataEntry getParent()
+ {
+ return null;
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return getName();
+ }
+}
diff --git a/src/proguard/io/FilteredDataEntryReader.java b/src/proguard/io/FilteredDataEntryReader.java
new file mode 100644
index 000000000..03b5dd81c
--- /dev/null
+++ b/src/proguard/io/FilteredDataEntryReader.java
@@ -0,0 +1,90 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.IOException;
+
+
+/**
+ * This DataEntryReader delegates to one of two other DataEntryReader instances,
+ * depending on whether the data entry passes through a given data entry filter
+ * or not.
+ *
+ * @author Eric Lafortune
+ */
+public class FilteredDataEntryReader implements DataEntryReader
+{
+ private final DataEntryFilter dataEntryFilter;
+ private final DataEntryReader acceptedDataEntryReader;
+ private final DataEntryReader rejectedDataEntryReader;
+
+
+ /**
+ * Creates a new FilteredDataEntryReader with only a reader for accepted
+ * data entries.
+ * @param dataEntryFilter the data entry filter.
+ * @param acceptedDataEntryReader the DataEntryReader to which the reading
+ * will be delegated if the filter accepts
+ * the data entry. May be null
.
+ */
+ public FilteredDataEntryReader(DataEntryFilter dataEntryFilter,
+ DataEntryReader acceptedDataEntryReader)
+ {
+ this(dataEntryFilter, acceptedDataEntryReader, null);
+ }
+
+
+ /**
+ * Creates a new FilteredDataEntryReader.
+ * @param dataEntryFilter the data entry filter.
+ * @param acceptedDataEntryReader the DataEntryReader to which the reading
+ * will be delegated if the filter accepts
+ * the data entry. May be null
.
+ * @param rejectedDataEntryReader the DataEntryReader to which the reading
+ * will be delegated if the filter does not
+ * accept the data entry. May be
+ * null
.
+ */
+ public FilteredDataEntryReader(DataEntryFilter dataEntryFilter,
+ DataEntryReader acceptedDataEntryReader,
+ DataEntryReader rejectedDataEntryReader)
+ {
+ this.dataEntryFilter = dataEntryFilter;
+ this.acceptedDataEntryReader = acceptedDataEntryReader;
+ this.rejectedDataEntryReader = rejectedDataEntryReader;
+ }
+
+
+ // Implementations for DataEntryReader.
+
+ public void read(DataEntry dataEntry)
+ throws IOException
+ {
+ DataEntryReader dataEntryReader = dataEntryFilter.accepts(dataEntry) ?
+ acceptedDataEntryReader :
+ rejectedDataEntryReader;
+
+ if (dataEntryReader != null)
+ {
+ dataEntryReader.read(dataEntry);
+ }
+ }
+}
diff --git a/src/proguard/io/FilteredDataEntryWriter.java b/src/proguard/io/FilteredDataEntryWriter.java
new file mode 100644
index 000000000..b3b751ce2
--- /dev/null
+++ b/src/proguard/io/FilteredDataEntryWriter.java
@@ -0,0 +1,125 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.*;
+
+/**
+ * This DataEntryWriter delegates to one of two other DataEntryWriter instances,
+ * depending on whether the data entry passes through a given data entry filter
+ * or not.
+ *
+ * @author Eric Lafortune
+ */
+public class FilteredDataEntryWriter implements DataEntryWriter
+{
+ private final DataEntryFilter dataEntryFilter;
+ private DataEntryWriter acceptedDataEntryWriter;
+ private DataEntryWriter rejectedDataEntryWriter;
+
+
+ /**
+ * Creates a new FilteredDataEntryWriter with only a writer for accepted
+ * data entries.
+ * @param dataEntryFilter the data entry filter.
+ * @param acceptedDataEntryWriter the DataEntryWriter to which the writing
+ * will be delegated if the filter accepts
+ * the data entry. May be null
.
+ */
+ public FilteredDataEntryWriter(DataEntryFilter dataEntryFilter,
+ DataEntryWriter acceptedDataEntryWriter)
+ {
+ this(dataEntryFilter, acceptedDataEntryWriter, null);
+ }
+
+
+ /**
+ * Creates a new FilteredDataEntryWriter.
+ * @param dataEntryFilter the data entry filter.
+ * @param acceptedDataEntryWriter the DataEntryWriter to which the writing
+ * will be delegated if the filter accepts
+ * the data entry. May be null
.
+ * @param rejectedDataEntryWriter the DataEntryWriter to which the writing
+ * will be delegated if the filter does not
+ * accept the data entry. May be
+ * null
.
+ */
+ public FilteredDataEntryWriter(DataEntryFilter dataEntryFilter,
+ DataEntryWriter acceptedDataEntryWriter,
+ DataEntryWriter rejectedDataEntryWriter)
+ {
+ this.dataEntryFilter = dataEntryFilter;
+ this.acceptedDataEntryWriter = acceptedDataEntryWriter;
+ this.rejectedDataEntryWriter = rejectedDataEntryWriter;
+ }
+
+
+ // Implementations for DataEntryWriter.
+
+ public boolean createDirectory(DataEntry dataEntry) throws IOException
+ {
+ // Get the right data entry writer.
+ DataEntryWriter dataEntryWriter = dataEntryFilter.accepts(dataEntry) ?
+ acceptedDataEntryWriter :
+ rejectedDataEntryWriter;
+
+ // Delegate to it, if it's not null.
+ return dataEntryWriter != null &&
+ dataEntryWriter.createDirectory(dataEntry);
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry) throws IOException
+ {
+ return getOutputStream(dataEntry, null);
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry,
+ Finisher finisher) throws IOException
+ {
+ // Get the right data entry writer.
+ DataEntryWriter dataEntryWriter = dataEntryFilter.accepts(dataEntry) ?
+ acceptedDataEntryWriter :
+ rejectedDataEntryWriter;
+
+ // Delegate to it, if it's not null.
+ return dataEntryWriter != null ?
+ dataEntryWriter.getOutputStream(dataEntry, finisher) :
+ null;
+ }
+
+
+ public void close() throws IOException
+ {
+ if (acceptedDataEntryWriter != null)
+ {
+ acceptedDataEntryWriter.close();
+ acceptedDataEntryWriter = null;
+ }
+
+ if (rejectedDataEntryWriter != null)
+ {
+ rejectedDataEntryWriter.close();
+ rejectedDataEntryWriter = null;
+ }
+ }
+}
diff --git a/src/proguard/io/Finisher.java b/src/proguard/io/Finisher.java
new file mode 100644
index 000000000..7d5f93f06
--- /dev/null
+++ b/src/proguard/io/Finisher.java
@@ -0,0 +1,37 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.IOException;
+
+/**
+ * This interface specifies a listener that is called to finish an output stream
+ * before it is closed.
+ *
+ * @author Eric Lafortune
+ */
+public interface Finisher
+{
+ /**
+ * Finishes an output stream right before it is closed.
+ */
+ public void finish() throws IOException;
+}
diff --git a/src/proguard/io/JarReader.java b/src/proguard/io/JarReader.java
new file mode 100644
index 000000000..be4c97b64
--- /dev/null
+++ b/src/proguard/io/JarReader.java
@@ -0,0 +1,75 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.IOException;
+import java.util.zip.*;
+
+/**
+ * This DataEntryReader lets a given DataEntryReader read all data entries of
+ * the read jar/war/zip data entries.
+ *
+ * @author Eric Lafortune
+ */
+public class JarReader implements DataEntryReader
+{
+ private final DataEntryReader dataEntryReader;
+
+
+ /**
+ * Creates a new JarReader.
+ */
+ public JarReader(DataEntryReader dataEntryReader)
+ {
+ this.dataEntryReader = dataEntryReader;
+ }
+
+
+ // Implementation for DataEntryReader.
+
+ public void read(DataEntry dataEntry) throws IOException
+ {
+ ZipInputStream zipInputStream = new ZipInputStream(dataEntry.getInputStream());
+
+ try
+ {
+ // Get all entries from the input jar.
+ while (true)
+ {
+ // Can we get another entry?
+ ZipEntry zipEntry = zipInputStream.getNextEntry();
+ if (zipEntry == null)
+ {
+ break;
+ }
+
+ // Delegate the actual reading to the data entry reader.
+ dataEntryReader.read(new ZipDataEntry(dataEntry,
+ zipEntry,
+ zipInputStream));
+ }
+ }
+ finally
+ {
+ dataEntry.closeInputStream();
+ }
+ }
+}
diff --git a/src/proguard/io/JarWriter.java b/src/proguard/io/JarWriter.java
new file mode 100644
index 000000000..d85e63b44
--- /dev/null
+++ b/src/proguard/io/JarWriter.java
@@ -0,0 +1,235 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.ClassConstants;
+
+import java.io.*;
+import java.util.*;
+import java.util.jar.*;
+import java.util.zip.*;
+
+
+/**
+ * This DataEntryWriter sends data entries to a given jar/zip file.
+ * The manifest and comment properties can optionally be set.
+ *
+ * @author Eric Lafortune
+ */
+public class JarWriter implements DataEntryWriter, Finisher
+{
+ private final DataEntryWriter dataEntryWriter;
+ private final Manifest manifest;
+ private final String comment;
+
+ private OutputStream currentParentOutputStream;
+ private ZipOutputStream currentJarOutputStream;
+ private Finisher currentFinisher;
+ private DataEntry currentDataEntry;
+
+ // The names of the jar entries that are already in the jar.
+ private final Set jarEntryNames = new HashSet();
+
+
+ /**
+ * Creates a new JarWriter without manifest or comment.
+ */
+ public JarWriter(DataEntryWriter dataEntryWriter)
+ {
+ this(dataEntryWriter, null, null);
+ }
+
+
+ /**
+ * Creates a new JarWriter.
+ */
+ public JarWriter(DataEntryWriter dataEntryWriter,
+ Manifest manifest,
+ String comment)
+ {
+ this.dataEntryWriter = dataEntryWriter;
+ this.manifest = manifest;
+ this.comment = comment;
+ }
+
+
+ // Implementations for DataEntryWriter.
+
+ public boolean createDirectory(DataEntry dataEntry) throws IOException
+ {
+ //Make sure we can start with a new entry.
+ if (!prepareEntry(dataEntry))
+ {
+ return false;
+ }
+
+ // Close the previous ZIP entry, if any.
+ closeEntry();
+
+ // Get the directory entry name.
+ String name = dataEntry.getName() + ClassConstants.INTERNAL_PACKAGE_SEPARATOR;
+
+ // We have to check if the name is already used, because
+ // ZipOutputStream doesn't handle this case properly (it throws
+ // an exception which can be caught, but the ZipDataEntry is
+ // remembered anyway).
+ if (jarEntryNames.add(name))
+ {
+ // Create a new directory entry.
+ currentJarOutputStream.putNextEntry(new ZipEntry(name));
+ currentJarOutputStream.closeEntry();
+ }
+
+ // Clear the finisher.
+ currentFinisher = null;
+ currentDataEntry = null;
+
+ return true;
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry) throws IOException
+ {
+ return getOutputStream(dataEntry, null);
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry,
+ Finisher finisher) throws IOException
+ {
+ //Make sure we can start with a new entry.
+ if (!prepareEntry(dataEntry))
+ {
+ return null;
+ }
+
+ // Do we need a new entry?
+ if (!dataEntry.equals(currentDataEntry))
+ {
+ // Close the previous ZIP entry, if any.
+ closeEntry();
+
+ // Get the entry name.
+ String name = dataEntry.getName();
+
+ // We have to check if the name is already used, because
+ // ZipOutputStream doesn't handle this case properly (it throws
+ // an exception which can be caught, but the ZipDataEntry is
+ // remembered anyway).
+ if (!jarEntryNames.add(name))
+ {
+ throw new IOException("Duplicate zip entry ["+dataEntry+"]");
+ }
+
+ // Create a new entry.
+ currentJarOutputStream.putNextEntry(new ZipEntry(name));
+
+ // Set up the finisher for the entry.
+ currentFinisher = finisher;
+ currentDataEntry = dataEntry;
+ }
+
+ return currentJarOutputStream;
+ }
+
+
+ public void finish() throws IOException
+ {
+ // Finish the entire ZIP stream, if any.
+ if (currentJarOutputStream != null)
+ {
+ // Close the previous ZIP entry, if any.
+ closeEntry();
+
+ // Finish the entire ZIP stream.
+ currentJarOutputStream.finish();
+ currentJarOutputStream = null;
+ currentParentOutputStream = null;
+ jarEntryNames.clear();
+ }
+ }
+
+
+ public void close() throws IOException
+ {
+ // Close the parent stream.
+ dataEntryWriter.close();
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Makes sure the current output stream is set up for the given entry.
+ */
+ private boolean prepareEntry(DataEntry dataEntry) throws IOException
+ {
+ // Get the parent stream, new or exisiting.
+ // This may finish our own jar output stream.
+ OutputStream parentOutputStream =
+ dataEntryWriter.getOutputStream(dataEntry.getParent(), this);
+
+ // Did we get a stream?
+ if (parentOutputStream == null)
+ {
+ return false;
+ }
+
+ // Do we need a new stream?
+ if (currentParentOutputStream == null)
+ {
+ currentParentOutputStream = parentOutputStream;
+
+ // Create a new jar stream, with a manifest, if set.
+ currentJarOutputStream = manifest != null ?
+ new JarOutputStream(parentOutputStream, manifest) :
+ new ZipOutputStream(parentOutputStream);
+
+ // Add a comment, if set.
+ if (comment != null)
+ {
+ currentJarOutputStream.setComment(comment);
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Closes the previous ZIP entry, if any.
+ */
+ private void closeEntry() throws IOException
+ {
+ if (currentDataEntry != null)
+ {
+ // Let any finisher finish up first.
+ if (currentFinisher != null)
+ {
+ currentFinisher.finish();
+ currentFinisher = null;
+ }
+
+ currentJarOutputStream.closeEntry();
+ currentDataEntry = null;
+ }
+ }
+}
diff --git a/src/proguard/io/ManifestRewriter.java b/src/proguard/io/ManifestRewriter.java
new file mode 100644
index 000000000..8a8c7ae82
--- /dev/null
+++ b/src/proguard/io/ManifestRewriter.java
@@ -0,0 +1,211 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.*;
+
+import java.io.*;
+
+/**
+ * This DataEntryReader writes the manifest data entries that it reads to a
+ * given DataEntryWriter, updating their contents based on the renamed classes
+ * in the given ClassPool.
+ *
+ * @author Eric Lafortune
+ */
+public class ManifestRewriter extends DataEntryRewriter
+{
+ /**
+ * Creates a new ManifestRewriter.
+ */
+ public ManifestRewriter(ClassPool classPool,
+ DataEntryWriter dataEntryWriter)
+ {
+ super(classPool, dataEntryWriter);
+ }
+
+
+ // Implementations for DataEntryRewriter.
+
+ protected void copyData(Reader reader,
+ Writer writer)
+ throws IOException
+ {
+ super.copyData(new SplitLineReader(reader),
+ new SplitLineWriter(writer));
+ }
+
+
+ /**
+ * This Reader reads manifest files, joining any split lines. It replaces
+ * the allowed CR/LF/CR+LF alternatives by simple LF in the process.
+ */
+ private static class SplitLineReader extends FilterReader
+ {
+ private static final int NONE = -2;
+
+ private int bufferedCharacter = NONE;
+
+
+ public SplitLineReader(Reader reader)
+ {
+ super(reader);
+ }
+
+
+ // Implementations for Reader.
+
+ public int read() throws IOException
+ {
+ while (true)
+ {
+ // Get the buffered character or the first character.
+ int c1 = bufferedCharacter != NONE ?
+ bufferedCharacter :
+ super.read();
+
+ // Clear the buffered character.
+ bufferedCharacter = NONE;
+
+ // Return it if it's an ordinary character.
+ if (c1 != '\n' && c1 != '\r')
+ {
+ return c1;
+ }
+
+ // It's a newline. Read the second character to see if it's a
+ // continuation.
+ int c2 = super.read();
+
+ // Skip any corresponding, redundant \n or \r.
+ if ((c2 == '\n' || c2 == '\r') && c1 != c2)
+ {
+ c2 = super.read();
+ }
+
+ // Isn't it a continuation after all?
+ if (c2 != ' ')
+ {
+ // Buffer the second character and return a newline.
+ bufferedCharacter = c2;
+ return '\n';
+ }
+
+ // Just continue after the continuation characters.
+ }
+ }
+
+
+ public int read(char[] cbuf, int off, int len) throws IOException
+ {
+ // Delegate to reading a single character at a time.
+ int count = 0;
+ while (count < len)
+ {
+ int c = read();
+ if (c == -1)
+ {
+ break;
+ }
+
+ cbuf[off + count++] = (char)c;
+ }
+
+ return count;
+ }
+
+
+ public long skip(long n) throws IOException
+ {
+ // Delegate to reading a single character at a time.
+ int count = 0;
+ while (count < n)
+ {
+ int c = read();
+ if (c == -1)
+ {
+ break;
+ }
+
+ count++;
+ }
+
+ return count;
+ }
+ }
+
+
+ /**
+ * This Writer writes manifest files, splitting any long lines.
+ */
+ private static class SplitLineWriter extends FilterWriter
+ {
+ private int counter = 0;
+
+
+ public SplitLineWriter(Writer writer)
+ {
+ super(writer);
+ }
+
+
+ // Implementations for Reader.
+
+ public void write(int c) throws IOException
+ {
+ // TODO: We should actually count the Utf-8 bytes, not the characters.
+ if (c == '\n')
+ {
+ // Reset the character count.
+ counter = 0;
+ }
+ else if (counter == 70)
+ {
+ // Insert a newline and a space.
+ super.write('\n');
+ super.write(' ');
+
+ counter = 2;
+ }
+ else
+ {
+ counter++;
+ }
+
+ super.write(c);
+ }
+
+
+ public void write(char[] cbuf, int off, int len) throws IOException
+ {
+ for (int count = 0; count < len; count++)
+ {
+ write(cbuf[off + count]);
+ }
+ }
+
+
+ public void write(String str, int off, int len) throws IOException
+ {
+ write(str.toCharArray(), off, len);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/io/NameFilter.java b/src/proguard/io/NameFilter.java
new file mode 100644
index 000000000..67d630ef4
--- /dev/null
+++ b/src/proguard/io/NameFilter.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.util.*;
+
+import java.util.List;
+
+/**
+ * This DataEntryReader delegates to one of two other DataEntryReader instances,
+ * depending on the name of the data entry.
+ *
+ * @author Eric Lafortune
+ */
+public class NameFilter extends FilteredDataEntryReader
+{
+ /**
+ * Creates a new NameFilter that delegates to the given reader, depending
+ * on the given list of filters.
+ */
+ public NameFilter(String regularExpression,
+ DataEntryReader acceptedDataEntryReader)
+ {
+ this(regularExpression, acceptedDataEntryReader, null);
+ }
+
+
+ /**
+ * Creates a new NameFilter that delegates to either of the two given
+ * readers, depending on the given list of filters.
+ */
+ public NameFilter(String regularExpression,
+ DataEntryReader acceptedDataEntryReader,
+ DataEntryReader rejectedDataEntryReader)
+ {
+ super(new DataEntryNameFilter(new ListParser(new FileNameParser()).parse(regularExpression)),
+ acceptedDataEntryReader,
+ rejectedDataEntryReader);
+ }
+
+
+ /**
+ * Creates a new NameFilter that delegates to the given reader, depending
+ * on the given list of filters.
+ */
+ public NameFilter(List regularExpressions,
+ DataEntryReader acceptedDataEntryReader)
+ {
+ this(regularExpressions, acceptedDataEntryReader, null);
+ }
+
+
+ /**
+ * Creates a new NameFilter that delegates to either of the two given
+ * readers, depending on the given list of filters.
+ */
+ public NameFilter(List regularExpressions,
+ DataEntryReader acceptedDataEntryReader,
+ DataEntryReader rejectedDataEntryReader)
+ {
+ super(new DataEntryNameFilter(new ListParser(new FileNameParser()).parse(regularExpressions)),
+ acceptedDataEntryReader,
+ rejectedDataEntryReader);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/io/ParentDataEntryWriter.java b/src/proguard/io/ParentDataEntryWriter.java
new file mode 100644
index 000000000..f24ef37fe
--- /dev/null
+++ b/src/proguard/io/ParentDataEntryWriter.java
@@ -0,0 +1,75 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.*;
+
+/**
+ * This DataEntryWriter lets another DataEntryWriter write the parent data
+ * entries.
+ *
+ * @author Eric Lafortune
+ */
+public class ParentDataEntryWriter implements DataEntryWriter
+{
+ private DataEntryWriter dataEntryWriter;
+
+
+ /**
+ * Creates a new ParentDataEntryWriter.
+ * @param dataEntryWriter the DataEntryWriter to which the writing will be
+ * delegated, passing the data entries' parents.
+ */
+ public ParentDataEntryWriter(DataEntryWriter dataEntryWriter)
+ {
+ this.dataEntryWriter = dataEntryWriter;
+ }
+
+
+ // Implementations for DataEntryWriter.
+
+
+ public boolean createDirectory(DataEntry dataEntry) throws IOException
+ {
+ return getOutputStream(dataEntry) != null;
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry) throws IOException
+ {
+ return getOutputStream(dataEntry, null);
+ }
+
+
+ public OutputStream getOutputStream(DataEntry dataEntry,
+ Finisher finisher) throws IOException
+ {
+ return dataEntryWriter.getOutputStream(dataEntry.getParent(),
+ finisher);
+ }
+
+
+ public void close() throws IOException
+ {
+ dataEntryWriter.close();
+ dataEntryWriter = null;
+ }
+}
diff --git a/src/proguard/io/RenamedDataEntry.java b/src/proguard/io/RenamedDataEntry.java
new file mode 100644
index 000000000..a0f5657c7
--- /dev/null
+++ b/src/proguard/io/RenamedDataEntry.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import java.io.*;
+
+/**
+ * This DataEntry wraps another data entry, returning a different name instead
+ * of the wrapped data entry's name.
+ *
+ * @author Eric Lafortune
+ */
+public class RenamedDataEntry implements DataEntry
+{
+ private final DataEntry dataEntry;
+ private final String name;
+
+
+ public RenamedDataEntry(DataEntry dataEntry,
+ String name)
+ {
+ this.dataEntry = dataEntry;
+ this.name = name;
+ }
+
+
+ // Implementations for DataEntry.
+
+ public String getName()
+ {
+ return name;
+ }
+
+
+ public boolean isDirectory()
+ {
+ return dataEntry.isDirectory();
+ }
+
+
+ public InputStream getInputStream() throws IOException
+ {
+ return dataEntry.getInputStream();
+ }
+
+
+ public void closeInputStream() throws IOException
+ {
+ dataEntry.closeInputStream();
+ }
+
+
+ public DataEntry getParent()
+ {
+ return dataEntry.getParent();
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return name + " == " + dataEntry;
+ }
+}
diff --git a/src/proguard/io/ZipDataEntry.java b/src/proguard/io/ZipDataEntry.java
new file mode 100644
index 000000000..20a9d3bbc
--- /dev/null
+++ b/src/proguard/io/ZipDataEntry.java
@@ -0,0 +1,98 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.io;
+
+import proguard.classfile.ClassConstants;
+
+import java.io.*;
+import java.util.zip.*;
+
+/**
+ * This DataEntry
represents a ZIP entry.
+ *
+ * @author Eric Lafortune
+ */
+public class ZipDataEntry implements DataEntry
+{
+ private final DataEntry parent;
+ private final ZipEntry zipEntry;
+ private ZipInputStream zipInputStream;
+
+
+ public ZipDataEntry(DataEntry parent,
+ ZipEntry zipEntry,
+ ZipInputStream zipInputStream)
+ {
+ this.parent = parent;
+ this.zipEntry = zipEntry;
+ this.zipInputStream = zipInputStream;
+ }
+
+
+ // Implementations for DataEntry.
+
+ public String getName()
+ {
+ // Get the right separators.
+ String name = zipEntry.getName()
+ .replace(File.separatorChar, ClassConstants.INTERNAL_PACKAGE_SEPARATOR);
+
+ // Chop the trailing directory slash, if any.
+ int length = name.length();
+ return length > 0 &&
+ name.charAt(length-1) == ClassConstants.INTERNAL_PACKAGE_SEPARATOR ?
+ name.substring(0, length -1) :
+ name;
+ }
+
+
+ public boolean isDirectory()
+ {
+ return zipEntry.isDirectory();
+ }
+
+
+ public InputStream getInputStream() throws IOException
+ {
+ return zipInputStream;
+ }
+
+
+ public void closeInputStream() throws IOException
+ {
+ zipInputStream.closeEntry();
+ zipInputStream = null;
+ }
+
+
+ public DataEntry getParent()
+ {
+ return parent;
+ }
+
+
+ // Implementations for Object.
+
+ public String toString()
+ {
+ return parent.toString() + ':' + getName();
+ }
+}
diff --git a/src/proguard/io/package.html b/src/proguard/io/package.html
new file mode 100644
index 000000000..4ad9f4193
--- /dev/null
+++ b/src/proguard/io/package.html
@@ -0,0 +1,4 @@
+
+This package contains classes to read and write files, optionally wrapped in
+jars, wars, ears, zips, directories,...
+
diff --git a/src/proguard/obfuscate/AttributeShrinker.java b/src/proguard/obfuscate/AttributeShrinker.java
new file mode 100644
index 000000000..0c3ab944c
--- /dev/null
+++ b/src/proguard/obfuscate/AttributeShrinker.java
@@ -0,0 +1,120 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+import java.util.Arrays;
+
+/**
+ * This ClassVisitor removes attributes that are not marked as being used or
+ * required.
+ *
+ * @see AttributeUsageMarker
+ *
+ * @author Eric Lafortune
+ */
+public class AttributeShrinker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ AttributeVisitor
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Compact the array for class attributes.
+ programClass.u2attributesCount =
+ shrinkArray(programClass.attributes,
+ programClass.u2attributesCount);
+
+ // Compact the attributes in fields, methods, and class attributes,
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Library classes are left unchanged.
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
+ {
+ // Compact the attributes array.
+ programMember.u2attributesCount =
+ shrinkArray(programMember.attributes,
+ programMember.u2attributesCount);
+
+ // Compact any attributes of the remaining attributes.
+ programMember.attributesAccept(programClass, this);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Compact the attributes array.
+ codeAttribute.u2attributesCount =
+ shrinkArray(codeAttribute.attributes,
+ codeAttribute.u2attributesCount);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Removes all VisitorAccepter objects that are not marked as being used
+ * from the given array.
+ * @return the new number of VisitorAccepter objects.
+ */
+ private static int shrinkArray(VisitorAccepter[] array, int length)
+ {
+ int counter = 0;
+
+ // Shift the used objects together.
+ for (int index = 0; index < length; index++)
+ {
+ if (AttributeUsageMarker.isUsed(array[index]))
+ {
+ array[counter++] = array[index];
+ }
+ }
+
+ // Clear the remaining array elements.
+ Arrays.fill(array, counter, length, null);
+
+ return counter;
+ }
+}
diff --git a/src/proguard/obfuscate/AttributeUsageMarker.java b/src/proguard/obfuscate/AttributeUsageMarker.java
new file mode 100644
index 000000000..32a512b8c
--- /dev/null
+++ b/src/proguard/obfuscate/AttributeUsageMarker.java
@@ -0,0 +1,71 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.Attribute;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor marks all attributes that it visits.
+ *
+ * @see AttributeShrinker
+ *
+ * @author Eric Lafortune
+ */
+public class AttributeUsageMarker
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ // A visitor info flag to indicate the attribute is being used.
+ private static final Object USED = new Object();
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute)
+ {
+ markAsUsed(attribute);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Marks the given VisitorAccepter as being used (or useful).
+ * In this context, the VisitorAccepter will be an Attribute object.
+ */
+ private static void markAsUsed(VisitorAccepter visitorAccepter)
+ {
+ visitorAccepter.setVisitorInfo(USED);
+ }
+
+
+ /**
+ * Returns whether the given VisitorAccepter has been marked as being used.
+ * In this context, the VisitorAccepter will be an Attribute object.
+ */
+ static boolean isUsed(VisitorAccepter visitorAccepter)
+ {
+ return visitorAccepter.getVisitorInfo() == USED;
+ }
+}
diff --git a/src/proguard/obfuscate/ClassObfuscator.java b/src/proguard/obfuscate/ClassObfuscator.java
new file mode 100644
index 000000000..9e1a91c79
--- /dev/null
+++ b/src/proguard/obfuscate/ClassObfuscator.java
@@ -0,0 +1,541 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.ClassVisitor;
+import proguard.util.*;
+
+import java.util.*;
+
+/**
+ * This ClassVisitor
comes up with obfuscated names for the
+ * classes it visits, and for their class members. The actual renaming is
+ * done afterward.
+ *
+ * @see ClassRenamer
+ *
+ * @author Eric Lafortune
+ */
+public class ClassObfuscator
+extends SimplifiedVisitor
+implements ClassVisitor,
+ AttributeVisitor,
+ InnerClassesInfoVisitor,
+ ConstantVisitor
+{
+ private final DictionaryNameFactory classNameFactory;
+ private final DictionaryNameFactory packageNameFactory;
+ private final boolean useMixedCaseClassNames;
+ private final StringMatcher keepPackageNamesMatcher;
+ private final String flattenPackageHierarchy;
+ private final String repackageClasses;
+ private final boolean allowAccessModification;
+
+ private final Set classNamesToAvoid = new HashSet();
+
+ // Map: [package prefix - new package prefix]
+ private final Map packagePrefixMap = new HashMap();
+
+ // Map: [package prefix - package name factory]
+ private final Map packagePrefixPackageNameFactoryMap = new HashMap();
+
+ // Map: [package prefix - numeric class name factory]
+ private final Map packagePrefixClassNameFactoryMap = new HashMap();
+
+ // Map: [package prefix - numeric class name factory]
+ private final Map packagePrefixNumericClassNameFactoryMap = new HashMap();
+
+ // Field acting as temporary variables and as return values for names
+ // of outer classes and types of inner classes.
+ private String newClassName;
+ private boolean numericClassName;
+
+
+ /**
+ * Creates a new ClassObfuscator.
+ * @param programClassPool the class pool in which class names
+ * have to be unique.
+ * @param classNameFactory the optional class obfuscation dictionary.
+ * @param packageNameFactory the optional package obfuscation
+ * dictionary.
+ * @param useMixedCaseClassNames specifies whether obfuscated packages and
+ * classes can get mixed-case names.
+ * @param keepPackageNames the optional filter for which matching
+ * package names are kept.
+ * @param flattenPackageHierarchy the base package if the obfuscated package
+ * hierarchy is to be flattened.
+ * @param repackageClasses the base package if the obfuscated classes
+ * are to be repackaged.
+ * @param allowAccessModification specifies whether obfuscated classes can
+ * be freely moved between packages.
+ */
+ public ClassObfuscator(ClassPool programClassPool,
+ DictionaryNameFactory classNameFactory,
+ DictionaryNameFactory packageNameFactory,
+ boolean useMixedCaseClassNames,
+ List keepPackageNames,
+ String flattenPackageHierarchy,
+ String repackageClasses,
+ boolean allowAccessModification)
+ {
+ this.classNameFactory = classNameFactory;
+ this.packageNameFactory = packageNameFactory;
+
+ // First append the package separator if necessary.
+ if (flattenPackageHierarchy != null &&
+ flattenPackageHierarchy.length() > 0)
+ {
+ flattenPackageHierarchy += ClassConstants.INTERNAL_PACKAGE_SEPARATOR;
+ }
+
+ // First append the package separator if necessary.
+ if (repackageClasses != null &&
+ repackageClasses.length() > 0)
+ {
+ repackageClasses += ClassConstants.INTERNAL_PACKAGE_SEPARATOR;
+ }
+
+ this.useMixedCaseClassNames = useMixedCaseClassNames;
+ this.keepPackageNamesMatcher = keepPackageNames == null ? null :
+ new ListParser(new FileNameParser()).parse(keepPackageNames);
+ this.flattenPackageHierarchy = flattenPackageHierarchy;
+ this.repackageClasses = repackageClasses;
+ this.allowAccessModification = allowAccessModification;
+
+ // Map the root package onto the root package.
+ packagePrefixMap.put("", "");
+
+ // Collect all names that have been taken already.
+ programClassPool.classesAccept(new MyKeepCollector());
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Does this class still need a new name?
+ newClassName = newClassName(programClass);
+ if (newClassName == null)
+ {
+ // Make sure the outer class has a name, if it exists. The name will
+ // be stored as the new class name, as a side effect, so we'll be
+ // able to use it as a prefix.
+ programClass.attributesAccept(this);
+
+ // Figure out a package prefix. The package prefix may actually be
+ // the an outer class prefix, if any, or it may be the fixed base
+ // package, if classes are to be repackaged.
+ String newPackagePrefix = newClassName != null ?
+ newClassName + ClassConstants.INTERNAL_INNER_CLASS_SEPARATOR :
+ newPackagePrefix(ClassUtil.internalPackagePrefix(programClass.getName()));
+
+ // Come up with a new class name, numeric or ordinary.
+ newClassName = newClassName != null && numericClassName ?
+ generateUniqueNumericClassName(newPackagePrefix) :
+ generateUniqueClassName(newPackagePrefix);
+
+ setNewClassName(programClass, newClassName);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // This can happen for dubious input, if the outer class of a program
+ // class is a library class, and its name is requested.
+ newClassName = libraryClass.getName();
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ // Make sure the outer classes have a name, if they exist.
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ // Make sure the enclosing class has a name.
+ enclosingMethodAttribute.referencedClassAccept(this);
+
+ String innerClassName = clazz.getName();
+ String outerClassName = clazz.getClassName(enclosingMethodAttribute.u2classIndex);
+
+ numericClassName = isNumericClassName(innerClassName,
+ outerClassName);
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ // Make sure the outer class has a name, if it exists.
+ int innerClassIndex = innerClassesInfo.u2innerClassIndex;
+ int outerClassIndex = innerClassesInfo.u2outerClassIndex;
+ if (innerClassIndex != 0 &&
+ outerClassIndex != 0)
+ {
+ String innerClassName = clazz.getClassName(innerClassIndex);
+ if (innerClassName.equals(clazz.getName()))
+ {
+ clazz.constantPoolEntryAccept(outerClassIndex, this);
+
+ String outerClassName = clazz.getClassName(outerClassIndex);
+
+ numericClassName = isNumericClassName(innerClassName,
+ outerClassName);
+ }
+ }
+ }
+
+
+ /**
+ * Returns whether the given inner class name is a numeric name.
+ */
+ private boolean isNumericClassName(String innerClassName,
+ String outerClassName)
+ {
+ int innerClassNameStart = outerClassName.length() + 1;
+ int innerClassNameLength = innerClassName.length();
+
+ if (innerClassNameStart >= innerClassNameLength)
+ {
+ return false;
+ }
+
+ for (int index = innerClassNameStart; index < innerClassNameLength; index++)
+ {
+ if (!Character.isDigit(innerClassName.charAt(index)))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Make sure the outer class has a name.
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ /**
+ * This ClassVisitor collects package names and class names that have to
+ * be kept.
+ */
+ private class MyKeepCollector implements ClassVisitor
+ {
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Does the class already have a new name?
+ String newClassName = newClassName(programClass);
+ if (newClassName != null)
+ {
+ // Remember not to use this name.
+ classNamesToAvoid.add(mixedCaseClassName(newClassName));
+
+ // Are we not aggressively repackaging all obfuscated classes?
+ if (repackageClasses == null ||
+ !allowAccessModification)
+ {
+ String className = programClass.getName();
+
+ // Keep the package name for all other classes in the same
+ // package. Do this recursively if we're not doing any
+ // repackaging.
+ mapPackageName(className,
+ newClassName,
+ repackageClasses == null &&
+ flattenPackageHierarchy == null);
+ }
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ }
+
+
+ /**
+ * Makes sure the package name of the given class will always be mapped
+ * consistently with its new name.
+ */
+ private void mapPackageName(String className,
+ String newClassName,
+ boolean recursively)
+ {
+ String packagePrefix = ClassUtil.internalPackagePrefix(className);
+ String newPackagePrefix = ClassUtil.internalPackagePrefix(newClassName);
+
+ // Put the mapping of this package prefix, and possibly of its
+ // entire hierarchy, into the package prefix map.
+ do
+ {
+ packagePrefixMap.put(packagePrefix, newPackagePrefix);
+
+ if (!recursively)
+ {
+ break;
+ }
+
+ packagePrefix = ClassUtil.internalPackagePrefix(packagePrefix);
+ newPackagePrefix = ClassUtil.internalPackagePrefix(newPackagePrefix);
+ }
+ while (packagePrefix.length() > 0 &&
+ newPackagePrefix.length() > 0);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Finds or creates the new package prefix for the given package.
+ */
+ private String newPackagePrefix(String packagePrefix)
+ {
+ // Doesn't the package prefix have a new package prefix yet?
+ String newPackagePrefix = (String)packagePrefixMap.get(packagePrefix);
+ if (newPackagePrefix == null)
+ {
+ // Are we keeping the package name?
+ if (keepPackageNamesMatcher != null &&
+ keepPackageNamesMatcher.matches(packagePrefix.length() > 0 ?
+ packagePrefix.substring(0, packagePrefix.length()-1) :
+ packagePrefix))
+ {
+ return packagePrefix;
+ }
+
+ // Are we forcing a new package prefix?
+ if (repackageClasses != null)
+ {
+ return repackageClasses;
+ }
+
+ // Are we forcing a new superpackage prefix?
+ // Otherwise figure out the new superpackage prefix, recursively.
+ String newSuperPackagePrefix = flattenPackageHierarchy != null ?
+ flattenPackageHierarchy :
+ newPackagePrefix(ClassUtil.internalPackagePrefix(packagePrefix));
+
+ // Come up with a new package prefix.
+ newPackagePrefix = generateUniquePackagePrefix(newSuperPackagePrefix);
+
+ // Remember to use this mapping in the future.
+ packagePrefixMap.put(packagePrefix, newPackagePrefix);
+ }
+
+ return newPackagePrefix;
+ }
+
+
+ /**
+ * Creates a new package prefix in the given new superpackage.
+ */
+ private String generateUniquePackagePrefix(String newSuperPackagePrefix)
+ {
+ // Find the right name factory for this package.
+ NameFactory packageNameFactory =
+ (NameFactory)packagePrefixPackageNameFactoryMap.get(newSuperPackagePrefix);
+ if (packageNameFactory == null)
+ {
+ // We haven't seen packages in this superpackage before. Create
+ // a new name factory for them.
+ packageNameFactory = new SimpleNameFactory(useMixedCaseClassNames);
+ if (this.packageNameFactory != null)
+ {
+ packageNameFactory =
+ new DictionaryNameFactory(this.packageNameFactory,
+ packageNameFactory);
+ }
+
+ packagePrefixPackageNameFactoryMap.put(newSuperPackagePrefix,
+ packageNameFactory);
+ }
+
+ return generateUniquePackagePrefix(newSuperPackagePrefix, packageNameFactory);
+ }
+
+
+ /**
+ * Creates a new package prefix in the given new superpackage, with the
+ * given package name factory.
+ */
+ private String generateUniquePackagePrefix(String newSuperPackagePrefix,
+ NameFactory packageNameFactory)
+ {
+ // Come up with package names until we get an original one.
+ String newPackagePrefix;
+ do
+ {
+ // Let the factory produce a package name.
+ newPackagePrefix = newSuperPackagePrefix +
+ packageNameFactory.nextName() +
+ ClassConstants.INTERNAL_PACKAGE_SEPARATOR;
+ }
+ while (packagePrefixMap.containsValue(newPackagePrefix));
+
+ return newPackagePrefix;
+ }
+
+
+ /**
+ * Creates a new class name in the given new package.
+ */
+ private String generateUniqueClassName(String newPackagePrefix)
+ {
+ // Find the right name factory for this package.
+ NameFactory classNameFactory =
+ (NameFactory)packagePrefixClassNameFactoryMap.get(newPackagePrefix);
+ if (classNameFactory == null)
+ {
+ // We haven't seen classes in this package before.
+ // Create a new name factory for them.
+ classNameFactory = new SimpleNameFactory(useMixedCaseClassNames);
+ if (this.classNameFactory != null)
+ {
+ classNameFactory =
+ new DictionaryNameFactory(this.classNameFactory,
+ classNameFactory);
+ }
+
+ packagePrefixClassNameFactoryMap.put(newPackagePrefix,
+ classNameFactory);
+ }
+
+ return generateUniqueClassName(newPackagePrefix, classNameFactory);
+ }
+
+
+ /**
+ * Creates a new class name in the given new package.
+ */
+ private String generateUniqueNumericClassName(String newPackagePrefix)
+ {
+ // Find the right name factory for this package.
+ NameFactory classNameFactory =
+ (NameFactory)packagePrefixNumericClassNameFactoryMap.get(newPackagePrefix);
+ if (classNameFactory == null)
+ {
+ // We haven't seen classes in this package before.
+ // Create a new name factory for them.
+ classNameFactory = new NumericNameFactory();
+
+ packagePrefixNumericClassNameFactoryMap.put(newPackagePrefix,
+ classNameFactory);
+ }
+
+ return generateUniqueClassName(newPackagePrefix, classNameFactory);
+ }
+
+
+ /**
+ * Creates a new class name in the given new package, with the given
+ * class name factory.
+ */
+ private String generateUniqueClassName(String newPackagePrefix,
+ NameFactory classNameFactory)
+ {
+ // Come up with class names until we get an original one.
+ String newClassName;
+ String newMixedCaseClassName;
+ do
+ {
+ // Let the factory produce a class name.
+ newClassName = newPackagePrefix +
+ classNameFactory.nextName();
+
+ newMixedCaseClassName = mixedCaseClassName(newClassName);
+ }
+ while (classNamesToAvoid.contains(newMixedCaseClassName));
+
+ // Explicitly make sure the name isn't used again if we have a
+ // user-specified dictionary and we're not allowed to have mixed case
+ // class names -- just to protect against problematic dictionaries.
+ if (this.classNameFactory != null &&
+ !useMixedCaseClassNames)
+ {
+ classNamesToAvoid.add(newMixedCaseClassName);
+ }
+
+ return newClassName;
+ }
+
+
+ /**
+ * Returns the given class name, unchanged if mixed-case class names are
+ * allowed, or the lower-case version otherwise.
+ */
+ private String mixedCaseClassName(String className)
+ {
+ return useMixedCaseClassNames ?
+ className :
+ className.toLowerCase();
+ }
+
+
+ /**
+ * Assigns a new name to the given class.
+ * @param clazz the given class.
+ * @param name the new name.
+ */
+ static void setNewClassName(Clazz clazz, String name)
+ {
+ clazz.setVisitorInfo(name);
+ }
+
+
+ /**
+ * Retrieves the new name of the given class.
+ * @param clazz the given class.
+ * @return the class's new name, or null
if it doesn't
+ * have one yet.
+ */
+ static String newClassName(Clazz clazz)
+ {
+ Object visitorInfo = clazz.getVisitorInfo();
+
+ return visitorInfo instanceof String ?
+ (String)visitorInfo :
+ null;
+ }
+}
diff --git a/src/proguard/obfuscate/ClassRenamer.java b/src/proguard/obfuscate/ClassRenamer.java
new file mode 100644
index 000000000..4c5e4963f
--- /dev/null
+++ b/src/proguard/obfuscate/ClassRenamer.java
@@ -0,0 +1,109 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.ConstantPoolEditor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ClassVisitor
renames the class names and class member
+ * names of the classes it visits, using names previously determined by the
+ * obfuscator.
+ *
+ * @see ClassObfuscator
+ * @see MemberObfuscator
+ *
+ * @author Eric Lafortune
+ */
+public class ClassRenamer
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ ConstantVisitor
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Rename this class.
+ programClass.thisClassConstantAccept(this);
+
+ // Rename the class members.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ libraryClass.thisClassName = ClassObfuscator.newClassName(libraryClass);
+
+ // Rename the class members.
+ libraryClass.fieldsAccept(this);
+ libraryClass.methodsAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMember(ProgramClass programClass,
+ ProgramMember programMember)
+ {
+ // Has the class member name changed?
+ String name = programMember.getName(programClass);
+ String newName = MemberObfuscator.newMemberName(programMember);
+ if (newName != null &&
+ !newName.equals(name))
+ {
+ programMember.u2nameIndex =
+ new ConstantPoolEditor(programClass).addUtf8Constant(newName);
+ }
+ }
+
+ public void visitLibraryMember(LibraryClass libraryClass,
+ LibraryMember libraryMember)
+ {
+ String newName = MemberObfuscator.newMemberName(libraryMember);
+ if (newName != null)
+ {
+ libraryMember.name = newName;
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Update the Class entry if required.
+ String newName = ClassObfuscator.newClassName(clazz);
+ if (newName != null)
+ {
+ // Refer to a new Utf8 entry.
+ classConstant.u2nameIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newName);
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/DictionaryNameFactory.java b/src/proguard/obfuscate/DictionaryNameFactory.java
new file mode 100644
index 000000000..4a7e28c04
--- /dev/null
+++ b/src/proguard/obfuscate/DictionaryNameFactory.java
@@ -0,0 +1,189 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * This NameFactory
generates names that are read from a
+ * specified input file.
+ * Comments (everything starting with '#' on a single line) are ignored.
+ *
+ * @author Eric Lafortune
+ */
+public class DictionaryNameFactory implements NameFactory
+{
+ private static final char COMMENT_CHARACTER = '#';
+
+
+ private final List names;
+ private final NameFactory nameFactory;
+
+ private int index = 0;
+
+
+ /**
+ * Creates a new DictionaryNameFactory
.
+ * @param file the file from which the names can be read.
+ * @param nameFactory the name factory from which names will be retrieved
+ * if the list of read names has been exhausted.
+ */
+ public DictionaryNameFactory(File file,
+ NameFactory nameFactory) throws IOException
+ {
+ this.names = new ArrayList();
+ this.nameFactory = nameFactory;
+
+ Reader reader = new FileReader(file);
+
+ try
+ {
+ StringBuffer buffer = new StringBuffer();
+
+ while (true)
+ {
+ // Read the next character.
+ int c = reader.read();
+
+ // Is it a valid identifier character?
+ if (c != -1 &&
+ (buffer.length() == 0 ?
+ Character.isJavaIdentifierStart((char)c) :
+ Character.isJavaIdentifierPart((char)c)))
+ {
+ // Append it to the current identifier.
+ buffer.append((char)c);
+ }
+ else
+ {
+ // Did we collect a new identifier?
+ if (buffer.length() > 0)
+ {
+ // Add the completed name to the list of names, if it's
+ // not in it yet.
+ String name = buffer.toString();
+ if (!names.contains(name))
+ {
+ names.add(name);
+ }
+
+ // Clear the buffer.
+ buffer.setLength(0);
+ }
+
+ // Is this the beginning of a comment line?
+ if (c == COMMENT_CHARACTER)
+ {
+ // Skip all characters till the end of the line.
+ do
+ {
+ c = reader.read();
+ }
+ while (c != -1 &&
+ c != '\n' &&
+ c != '\r');
+ }
+
+ // Is this the end of the file?
+ if (c == -1)
+ {
+ // Just return.
+ return;
+ }
+ }
+ }
+ }
+ finally
+ {
+ reader.close();
+ }
+ }
+
+
+ /**
+ * Creates a new DictionaryNameFactory
.
+ * @param dictionaryNameFactory the dictionary name factory whose dictionary
+ * will be used.
+ * @param nameFactory the name factory from which names will be
+ * retrieved if the list of read names has been
+ * exhausted.
+ */
+ public DictionaryNameFactory(DictionaryNameFactory dictionaryNameFactory,
+ NameFactory nameFactory)
+ {
+ this.names = dictionaryNameFactory.names;
+ this.nameFactory = nameFactory;
+ }
+
+
+ // Implementations for NameFactory.
+
+ public void reset()
+ {
+ index = 0;
+
+ nameFactory.reset();
+ }
+
+
+ public String nextName()
+ {
+ String name;
+
+ // Do we still have names?
+ if (index < names.size())
+ {
+ // Return the next name.
+ name = (String)names.get(index++);
+ }
+ else
+ {
+ // Return the next different name from the other name factory.
+ do
+ {
+ name = nameFactory.nextName();
+ }
+ while (names.contains(name));
+ }
+
+ return name;
+ }
+
+
+ public static void main(String[] args)
+ {
+ try
+ {
+ DictionaryNameFactory factory =
+ new DictionaryNameFactory(new File(args[0]), new SimpleNameFactory());
+
+ for (int counter = 0; counter < 50; counter++)
+ {
+ System.out.println("["+factory.nextName()+"]");
+ }
+ }
+ catch (IOException ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/MapCleaner.java b/src/proguard/obfuscate/MapCleaner.java
new file mode 100644
index 000000000..d11f4436c
--- /dev/null
+++ b/src/proguard/obfuscate/MapCleaner.java
@@ -0,0 +1,57 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+import java.util.Map;
+
+/**
+ * This ClassVisitor clears a given map whenever it visits a class.
+ *
+ * @author Eric Lafortune
+ */
+public class MapCleaner
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final Map map;
+
+
+ /**
+ * Creates a new MapCleaner.
+ * @param map the map to be cleared.
+ */
+ public MapCleaner(Map map)
+ {
+ this.map = map;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitAnyClass(Clazz clazz)
+ {
+ map.clear();
+ }
+}
diff --git a/src/proguard/obfuscate/MappingKeeper.java b/src/proguard/obfuscate/MappingKeeper.java
new file mode 100644
index 000000000..7ab1e2577
--- /dev/null
+++ b/src/proguard/obfuscate/MappingKeeper.java
@@ -0,0 +1,177 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.util.ListUtil;
+
+
+/**
+ * This MappingKeeper applies the mappings that it receives to its class pool,
+ * so these mappings are ensured in a subsequent obfuscation step.
+ *
+ * @author Eric Lafortune
+ */
+public class MappingKeeper implements MappingProcessor
+{
+ private final ClassPool classPool;
+ private final WarningPrinter warningPrinter;
+
+ // A field acting as a parameter.
+ private Clazz clazz;
+
+
+ /**
+ * Creates a new MappingKeeper.
+ * @param classPool the class pool in which class names and class
+ * member names have to be mapped.
+ * @param warningPrinter the optional warning printer to which warnings
+ * can be printed.
+ */
+ public MappingKeeper(ClassPool classPool,
+ WarningPrinter warningPrinter)
+ {
+ this.classPool = classPool;
+ this.warningPrinter = warningPrinter;
+ }
+
+
+ // Implementations for MappingProcessor.
+
+ public boolean processClassMapping(String className,
+ String newClassName)
+ {
+ // Find the class.
+ String name = ClassUtil.internalClassName(className);
+
+ clazz = classPool.getClass(name);
+ if (clazz != null)
+ {
+ String newName = ClassUtil.internalClassName(newClassName);
+
+ // Print out a warning if the mapping conflicts with a name that
+ // was set before.
+ if (warningPrinter != null)
+ {
+ String currentNewName = ClassObfuscator.newClassName(clazz);
+ if (currentNewName != null &&
+ !currentNewName.equals(newName))
+ {
+ warningPrinter.print(name,
+ currentNewName,
+ "Warning: " +
+ className +
+ " is not being kept as '" +
+ ClassUtil.externalClassName(currentNewName) +
+ "', but remapped to '" +
+ newClassName + "'");
+ }
+ }
+
+ ClassObfuscator.setNewClassName(clazz, newName);
+
+ // The class members have to be kept as well.
+ return true;
+ }
+
+ return false;
+ }
+
+
+ public void processFieldMapping(String className,
+ String fieldType,
+ String fieldName,
+ String newFieldName)
+ {
+ if (clazz != null)
+ {
+ // Find the field.
+ String name = fieldName;
+ String descriptor = ClassUtil.internalType(fieldType);
+
+ Field field = clazz.findField(name, descriptor);
+ if (field != null)
+ {
+ // Print out a warning if the mapping conflicts with a name that
+ // was set before.
+ if (warningPrinter != null)
+ {
+ String currentNewName = MemberObfuscator.newMemberName(field);
+ if (currentNewName != null &&
+ !currentNewName.equals(newFieldName))
+ {
+ warningPrinter.print(ClassUtil.internalClassName(className),
+ "Warning: " +
+ className +
+ ": field '" + fieldType + " " + fieldName +
+ "' is not being kept as '" + currentNewName +
+ "', but remapped to '" + newFieldName + "'");
+ }
+ }
+
+ // Make sure the mapping name will be kept.
+ MemberObfuscator.setFixedNewMemberName(field, newFieldName);
+ }
+ }
+ }
+
+
+ public void processMethodMapping(String className,
+ int firstLineNumber,
+ int lastLineNumber,
+ String methodReturnType,
+ String methodName,
+ String methodArguments,
+ String newMethodName)
+ {
+ if (clazz != null)
+ {
+ // Find the method.
+ String descriptor = ClassUtil.internalMethodDescriptor(methodReturnType,
+ ListUtil.commaSeparatedList(methodArguments));
+
+ Method method = clazz.findMethod(methodName, descriptor);
+ if (method != null)
+ {
+ // Print out a warning if the mapping conflicts with a name that
+ // was set before.
+ if (warningPrinter != null)
+ {
+ String currentNewName = MemberObfuscator.newMemberName(method);
+ if (currentNewName != null &&
+ !currentNewName.equals(newMethodName))
+ {
+ warningPrinter.print(ClassUtil.internalClassName(className),
+ "Warning: " +
+ className +
+ ": method '" + methodReturnType + " " + methodName + ClassConstants.EXTERNAL_METHOD_ARGUMENTS_OPEN + methodArguments + ClassConstants.EXTERNAL_METHOD_ARGUMENTS_CLOSE +
+ "' is not being kept as '" + currentNewName +
+ "', but remapped to '" + newMethodName + "'");
+ }
+ }
+
+ // Make sure the mapping name will be kept.
+ MemberObfuscator.setFixedNewMemberName(method, newMethodName);
+ }
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/MappingPrinter.java b/src/proguard/obfuscate/MappingPrinter.java
new file mode 100644
index 000000000..a28d10c16
--- /dev/null
+++ b/src/proguard/obfuscate/MappingPrinter.java
@@ -0,0 +1,147 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+import java.io.PrintStream;
+
+
+/**
+ * This ClassVisitor prints out the renamed classes and class members with
+ * their old names and new names.
+ *
+ * @see ClassRenamer
+ *
+ * @author Eric Lafortune
+ */
+public class MappingPrinter
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ AttributeVisitor
+{
+ private final PrintStream ps;
+
+
+ /**
+ * Creates a new MappingPrinter that prints to System.out
.
+ */
+ public MappingPrinter()
+ {
+ this(System.out);
+ }
+
+
+ /**
+ * Creates a new MappingPrinter that prints to the given stream.
+ * @param printStream the stream to which to print
+ */
+ public MappingPrinter(PrintStream printStream)
+ {
+ this.ps = printStream;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ String name = programClass.getName();
+ String newName = ClassObfuscator.newClassName(programClass);
+
+ ps.println(ClassUtil.externalClassName(name) +
+ " -> " +
+ ClassUtil.externalClassName(newName) +
+ ":");
+
+ // Print out the class members.
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ String newName = MemberObfuscator.newMemberName(programField);
+ if (newName != null)
+ {
+ ps.println(" " +
+ ClassUtil.externalFullFieldDescription(
+ 0,
+ programField.getName(programClass),
+ programField.getDescriptor(programClass)) +
+ " -> " +
+ newName);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Special cases: MemberVisitor
clears the new names of the class members
+ * that it visits.
+ *
+ * @see MemberObfuscator
+ *
+ * @author Eric Lafortune
+ */
+public class MemberNameCleaner implements MemberVisitor
+{
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ MemberObfuscator.setNewMemberName(programField, null);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ MemberObfuscator.setNewMemberName(programMethod, null);
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ MemberObfuscator.setNewMemberName(libraryField, null);
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ MemberObfuscator.setNewMemberName(libraryMethod, null);
+ }
+}
diff --git a/src/proguard/obfuscate/MemberNameCollector.java b/src/proguard/obfuscate/MemberNameCollector.java
new file mode 100644
index 000000000..1544901be
--- /dev/null
+++ b/src/proguard/obfuscate/MemberNameCollector.java
@@ -0,0 +1,106 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+
+import java.util.Map;
+
+/**
+ * This MemberVisitor collects all new (obfuscation) names of the members
+ * that it visits.
+ *
+ * @see MemberObfuscator
+ *
+ * @author Eric Lafortune
+ */
+public class MemberNameCollector
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final boolean allowAggressiveOverloading;
+ private final Map descriptorMap;
+
+
+ /**
+ * Creates a new MemberNameCollector.
+ * @param allowAggressiveOverloading a flag that specifies whether class
+ * members can be overloaded aggressively.
+ * @param descriptorMap the map of descriptors to
+ * [new name - old name] maps.
+ */
+ public MemberNameCollector(boolean allowAggressiveOverloading,
+ Map descriptorMap)
+ {
+ this.allowAggressiveOverloading = allowAggressiveOverloading;
+ this.descriptorMap = descriptorMap;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz clazz, Member member)
+ {
+ // Special cases: MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when the visited member has a new name.
+ * Constructors are judged based on the class name.
+ *
+ * @see ClassObfuscator
+ * @see MemberObfuscator
+ *
+ * @author Eric Lafortune
+ */
+public class MemberNameFilter implements MemberVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MemberNameFilter.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public MemberNameFilter(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (hasName(programField))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (hasName(programClass, programMethod))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (hasName(libraryField))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (hasName(libraryClass, libraryMethod))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether the given class has a new name.
+ */
+ private boolean hasName(Clazz clazz)
+ {
+ return ClassObfuscator.newClassName(clazz) != null;
+ }
+
+
+ /**
+ * Returns whether the given method has a new name.
+ */
+ private boolean hasName(Clazz clazz, Method method)
+ {
+ return
+ hasName(method) ||
+ (hasName(clazz) &&
+ method.getName(clazz).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT));
+ }
+
+
+ /**
+ * Returns whether the given class member has a new name.
+ */
+ private boolean hasName(Member member)
+ {
+ return MemberObfuscator.newMemberName(member) != null;
+ }
+}
diff --git a/src/proguard/obfuscate/MemberObfuscator.java b/src/proguard/obfuscate/MemberObfuscator.java
new file mode 100644
index 000000000..adf590c5d
--- /dev/null
+++ b/src/proguard/obfuscate/MemberObfuscator.java
@@ -0,0 +1,230 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+
+import java.util.*;
+
+/**
+ * This MemberVisitor obfuscates all class members that it visits.
+ * It uses names from the given name factory. At the same time, it avoids names
+ * from the given descriptor map.
+ * null
if it doesn't
+ * have one yet.
+ */
+ static String newMemberName(Member member)
+ {
+ return (String)MethodLinker.lastVisitorAccepter(member).getVisitorInfo();
+ }
+
+
+ /**
+ * This VisitorAccepter can be used to wrap a name string, to indicate that
+ * the name is fixed.
+ */
+ private static class MyFixedName implements VisitorAccepter
+ {
+ private String newName;
+
+
+ public MyFixedName(String newName)
+ {
+ this.newName = newName;
+ }
+
+
+ // Implementations for VisitorAccepter.
+
+ public Object getVisitorInfo()
+ {
+ return newName;
+ }
+
+
+ public void setVisitorInfo(Object visitorInfo)
+ {
+ newName = (String)visitorInfo;
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/MemberSpecialNameFilter.java b/src/proguard/obfuscate/MemberSpecialNameFilter.java
new file mode 100644
index 000000000..0eb4d2d4e
--- /dev/null
+++ b/src/proguard/obfuscate/MemberSpecialNameFilter.java
@@ -0,0 +1,101 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when the visited member has a
+ * special new name. A special name is a name that might have been produced by
+ * a SpecialNameFactory
.
+ *
+ * @see MemberObfuscator
+ * @see SpecialNameFactory
+ *
+ * @author Eric Lafortune
+ */
+public class MemberSpecialNameFilter implements MemberVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new MemberSpecialNameFilter.
+ * @param memberVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public MemberSpecialNameFilter(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (hasSpecialName(programField))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (hasSpecialName(programMethod))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (hasSpecialName(libraryField))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (hasSpecialName(libraryMethod))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether the given class member has a special new name.
+ * @param member the class member.
+ */
+ private static boolean hasSpecialName(Member member)
+ {
+ return SpecialNameFactory.isSpecialName(MemberObfuscator.newMemberName(member));
+ }
+}
diff --git a/src/proguard/obfuscate/MultiMappingProcessor.java b/src/proguard/obfuscate/MultiMappingProcessor.java
new file mode 100644
index 000000000..051260f42
--- /dev/null
+++ b/src/proguard/obfuscate/MultiMappingProcessor.java
@@ -0,0 +1,96 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+/**
+ * This MappingKeeper delegates all method calls to each MappingProcessor
+ * in a given list.
+ *
+ * @author Eric Lafortune
+ */
+public class MultiMappingProcessor implements MappingProcessor
+{
+ private final MappingProcessor[] mappingProcessors;
+
+
+ /**
+ * Creates a new MultiMappingProcessor.
+ * @param mappingProcessors the mapping processors to which method calls
+ * will be delegated.
+ */
+ public MultiMappingProcessor(MappingProcessor[] mappingProcessors)
+ {
+ this.mappingProcessors = mappingProcessors;
+ }
+
+
+ // Implementations for MappingProcessor.
+
+ public boolean processClassMapping(String className,
+ String newClassName)
+ {
+ boolean result = false;
+
+ for (int index = 0; index < mappingProcessors.length; index++)
+ {
+ result |= mappingProcessors[index].processClassMapping(className,
+ newClassName);
+ }
+
+ return result;
+ }
+
+
+ public void processFieldMapping(String className,
+ String fieldType,
+ String fieldName,
+ String newFieldName)
+ {
+ for (int index = 0; index < mappingProcessors.length; index++)
+ {
+ mappingProcessors[index].processFieldMapping(className,
+ fieldType,
+ fieldName,
+ newFieldName);
+ }
+ }
+
+
+ public void processMethodMapping(String className,
+ int firstLineNumber,
+ int lastLineNumber,
+ String methodReturnType,
+ String methodName,
+ String methodArguments,
+ String newMethodName)
+ {
+ for (int index = 0; index < mappingProcessors.length; index++)
+ {
+ mappingProcessors[index].processMethodMapping(className,
+ firstLineNumber,
+ lastLineNumber,
+ methodReturnType,
+ methodName,
+ methodArguments,
+ newMethodName);
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/NameFactory.java b/src/proguard/obfuscate/NameFactory.java
new file mode 100644
index 000000000..97ebe5af1
--- /dev/null
+++ b/src/proguard/obfuscate/NameFactory.java
@@ -0,0 +1,34 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+/**
+ * This interfaces provides methods to generate unique sequences of names.
+ * The names must be valid Java identifiers.
+ *
+ * @author Eric Lafortune
+ */
+public interface NameFactory
+{
+ public void reset();
+
+ public String nextName();
+}
diff --git a/src/proguard/obfuscate/NameFactoryResetter.java b/src/proguard/obfuscate/NameFactoryResetter.java
new file mode 100644
index 000000000..b04d12e94
--- /dev/null
+++ b/src/proguard/obfuscate/NameFactoryResetter.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor resets a given name factory whenever it visits a class
+ * file.
+ *
+ * @author Eric Lafortune
+ */
+public class NameFactoryResetter implements ClassVisitor
+{
+ private final NameFactory nameFactory;
+
+
+ /**
+ * Creates a new NameFactoryResetter.
+ * @param nameFactory the name factory to be reset.
+ */
+ public NameFactoryResetter(NameFactory nameFactory)
+ {
+ this.nameFactory = nameFactory;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ nameFactory.reset();
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ nameFactory.reset();
+ }
+}
diff --git a/src/proguard/obfuscate/NameMarker.java b/src/proguard/obfuscate/NameMarker.java
new file mode 100644
index 000000000..5283ef342
--- /dev/null
+++ b/src/proguard/obfuscate/NameMarker.java
@@ -0,0 +1,166 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.visitor.*;
+
+
+/**
+ * This ClassVisitor
and MemberVisitor
+ * marks names of the classes and class members it visits. The marked names
+ * will remain unchanged in the obfuscation step.
+ *
+ * @see ClassObfuscator
+ * @see MemberObfuscator
+ *
+ * @author Eric Lafortune
+ */
+class NameMarker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ AttributeVisitor,
+ InnerClassesInfoVisitor,
+ ConstantVisitor
+{
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ keepClassName(programClass);
+
+ // Make sure any outer class names are kept as well.
+ programClass.attributesAccept(this);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ keepClassName(libraryClass);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ keepFieldName(programClass, programField);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ keepMethodName(programClass, programMethod);
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ keepFieldName(libraryClass, libraryField);
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ keepMethodName(libraryClass, libraryMethod);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ // Make sure the outer class names are kept as well.
+ innerClassesAttribute.innerClassEntriesAccept(clazz, this);
+ }
+
+
+ // Implementations for InnerClassesInfoVisitor.
+
+ public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
+ {
+ // Make sure the outer class name is kept as well.
+ int innerClassIndex = innerClassesInfo.u2innerClassIndex;
+ int outerClassIndex = innerClassesInfo.u2outerClassIndex;
+ if (innerClassIndex != 0 &&
+ outerClassIndex != 0 &&
+ clazz.getClassName(innerClassIndex).equals(clazz.getName()))
+ {
+ clazz.constantPoolEntryAccept(outerClassIndex, this);
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Make sure the outer class name is kept as well.
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ // Small utility method.
+
+ /**
+ * Ensures the name of the given class name will be kept.
+ */
+ public void keepClassName(Clazz clazz)
+ {
+ ClassObfuscator.setNewClassName(clazz,
+ clazz.getName());
+ }
+
+
+ /**
+ * Ensures the name of the given field name will be kept.
+ */
+ private void keepFieldName(Clazz clazz, Field field)
+ {
+ MemberObfuscator.setFixedNewMemberName(field,
+ field.getName(clazz));
+ }
+
+
+ /**
+ * Ensures the name of the given method name will be kept.
+ */
+ private void keepMethodName(Clazz clazz, Method method)
+ {
+ String name = method.getName(clazz);
+
+ if (!name.equals(ClassConstants.INTERNAL_METHOD_NAME_CLINIT) &&
+ !name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
+ {
+ MemberObfuscator.setFixedNewMemberName(method,
+ method.getName(clazz));
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/NumericNameFactory.java b/src/proguard/obfuscate/NumericNameFactory.java
new file mode 100644
index 000000000..b1e38b113
--- /dev/null
+++ b/src/proguard/obfuscate/NumericNameFactory.java
@@ -0,0 +1,49 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import java.util.*;
+
+
+/**
+ * This NameFactory
generates unique numeric names, starting at
+ * "1".
+ *
+ * @author Eric Lafortune
+ */
+public class NumericNameFactory implements NameFactory
+{
+ private int index;
+
+
+ // Implementations for NameFactory.
+
+ public void reset()
+ {
+ index = 0;
+ }
+
+
+ public String nextName()
+ {
+ return Integer.toString(++index);
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/obfuscate/Obfuscator.java b/src/proguard/obfuscate/Obfuscator.java
new file mode 100644
index 000000000..1bbfc52b7
--- /dev/null
+++ b/src/proguard/obfuscate/Obfuscator.java
@@ -0,0 +1,454 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.*;
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.visitor.AllConstantVisitor;
+import proguard.classfile.editor.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.util.*;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * This class can perform obfuscation of class pools according to a given
+ * specification.
+ *
+ * @author Eric Lafortune
+ */
+public class Obfuscator
+{
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new Obfuscator.
+ */
+ public Obfuscator(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Performs obfuscation of the given program class pool.
+ */
+ public void execute(ClassPool programClassPool,
+ ClassPool libraryClassPool) throws IOException
+ {
+ // Check if we have at least some keep commands.
+ if (configuration.keep == null &&
+ configuration.applyMapping == null &&
+ configuration.printMapping == null)
+ {
+ throw new IOException("You have to specify '-keep' options for the obfuscation step.");
+ }
+
+ // Clean up any old visitor info.
+ programClassPool.classesAccept(new ClassCleaner());
+ libraryClassPool.classesAccept(new ClassCleaner());
+
+ // If the class member names have to correspond globally,
+ // link all class members in all classes, otherwise
+ // link all non-private methods in all class hierarchies.
+ ClassVisitor memberInfoLinker =
+ configuration.useUniqueClassMemberNames ?
+ (ClassVisitor)new AllMemberVisitor(new MethodLinker()) :
+ (ClassVisitor)new BottomClassFilter(new MethodLinker());
+
+ programClassPool.classesAccept(memberInfoLinker);
+ libraryClassPool.classesAccept(memberInfoLinker);
+
+ // Create a visitor for marking the seeds.
+ NameMarker nameMarker = new NameMarker();
+ ClassPoolVisitor classPoolvisitor =
+ ClassSpecificationVisitorFactory.createClassPoolVisitor(configuration.keep,
+ nameMarker,
+ nameMarker,
+ false,
+ false,
+ true);
+ // Mark the seeds.
+ programClassPool.accept(classPoolvisitor);
+ libraryClassPool.accept(classPoolvisitor);
+
+ // All library classes and library class members keep their names.
+ libraryClassPool.classesAccept(nameMarker);
+ libraryClassPool.classesAccept(new AllMemberVisitor(nameMarker));
+
+ // Mark attributes that have to be kept.
+ AttributeVisitor attributeUsageMarker =
+ new NonEmptyAttributeFilter(
+ new AttributeUsageMarker());
+
+ AttributeVisitor optionalAttributeUsageMarker =
+ configuration.keepAttributes == null ? null :
+ new AttributeNameFilter(new ListParser(new NameParser()).parse(configuration.keepAttributes),
+ attributeUsageMarker);
+
+ programClassPool.classesAccept(
+ new AllAttributeVisitor(true,
+ new RequiredAttributeFilter(attributeUsageMarker,
+ optionalAttributeUsageMarker)));
+
+ // Keep parameter names and types if specified.
+ if (configuration.keepParameterNames)
+ {
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new MemberNameFilter(
+ new AllAttributeVisitor(true,
+ new ParameterNameMarker(attributeUsageMarker)))));
+ }
+
+ // Remove the attributes that can be discarded. Note that the attributes
+ // may only be discarded after the seeds have been marked, since the
+ // configuration may rely on annotations.
+ programClassPool.classesAccept(new AttributeShrinker());
+
+ // Apply the mapping, if one has been specified. The mapping can
+ // override the names of library classes and of library class members.
+ if (configuration.applyMapping != null)
+ {
+ WarningPrinter warningPrinter = new WarningPrinter(System.err, configuration.warn);
+
+ MappingReader reader = new MappingReader(configuration.applyMapping);
+
+ MappingProcessor keeper =
+ new MultiMappingProcessor(new MappingProcessor[]
+ {
+ new MappingKeeper(programClassPool, warningPrinter),
+ new MappingKeeper(libraryClassPool, null),
+ });
+
+ reader.pump(keeper);
+
+ // Print out a summary of the warnings if necessary.
+ int mappingWarningCount = warningPrinter.getWarningCount();
+ if (mappingWarningCount > 0)
+ {
+ System.err.println("Warning: there were " + mappingWarningCount +
+ " kept classes and class members that were remapped anyway.");
+ System.err.println(" You should adapt your configuration or edit the mapping file.");
+
+ if (!configuration.ignoreWarnings)
+ {
+ System.err.println(" If you are sure this remapping won't hurt,");
+ System.err.println(" you could try your luck using the '-ignorewarnings' option.");
+ throw new IOException("Please correct the above warnings first.");
+ }
+ }
+ }
+
+ // Come up with new names for all classes.
+ DictionaryNameFactory classNameFactory = configuration.classObfuscationDictionary != null ?
+ new DictionaryNameFactory(configuration.classObfuscationDictionary, null) :
+ null;
+
+ DictionaryNameFactory packageNameFactory = configuration.packageObfuscationDictionary != null ?
+ new DictionaryNameFactory(configuration.packageObfuscationDictionary, null) :
+ null;
+
+ programClassPool.classesAccept(
+ new ClassObfuscator(programClassPool,
+ classNameFactory,
+ packageNameFactory,
+ configuration.useMixedCaseClassNames,
+ configuration.keepPackageNames,
+ configuration.flattenPackageHierarchy,
+ configuration.repackageClasses,
+ configuration.allowAccessModification));
+
+ // Come up with new names for all class members.
+ NameFactory nameFactory = new SimpleNameFactory();
+
+ if (configuration.obfuscationDictionary != null)
+ {
+ nameFactory = new DictionaryNameFactory(configuration.obfuscationDictionary,
+ nameFactory);
+ }
+
+ WarningPrinter warningPrinter = new WarningPrinter(System.err, configuration.warn);
+
+ // Maintain a map of names to avoid [descriptor - new name - old name].
+ Map descriptorMap = new HashMap();
+
+ // Do the class member names have to be globally unique?
+ if (configuration.useUniqueClassMemberNames)
+ {
+ // Collect all member names in all classes.
+ programClassPool.classesAccept(
+ new AllMemberVisitor(
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)));
+
+ // Assign new names to all members in all classes.
+ programClassPool.classesAccept(
+ new AllMemberVisitor(
+ new MemberObfuscator(configuration.overloadAggressively,
+ nameFactory,
+ descriptorMap)));
+ }
+ else
+ {
+ // Come up with new names for all non-private class members.
+ programClassPool.classesAccept(
+ new MultiClassVisitor(new ClassVisitor[]
+ {
+ // Collect all private member names in this class and down
+ // the hierarchy.
+ new ClassHierarchyTraveler(true, false, false, true,
+ new AllMemberVisitor(
+ new MemberAccessFilter(ClassConstants.INTERNAL_ACC_PRIVATE, 0,
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)))),
+
+ // Collect all non-private member names anywhere in the hierarchy.
+ new ClassHierarchyTraveler(true, true, true, true,
+ new AllMemberVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)))),
+
+ // Assign new names to all non-private members in this class.
+ new AllMemberVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberObfuscator(configuration.overloadAggressively,
+ nameFactory,
+ descriptorMap))),
+
+ // Clear the collected names.
+ new MapCleaner(descriptorMap)
+ }));
+
+ // Come up with new names for all private class members.
+ programClassPool.classesAccept(
+ new MultiClassVisitor(new ClassVisitor[]
+ {
+ // Collect all member names in this class.
+ new AllMemberVisitor(
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)),
+
+ // Collect all non-private member names higher up the hierarchy.
+ new ClassHierarchyTraveler(false, true, true, false,
+ new AllMemberVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)))),
+
+ // Collect all member names from interfaces of abstract
+ // classes down the hierarchy.
+ // Due to an error in the JLS/JVMS, virtual invocations
+ // may end up at a private method otherwise (Sun/Oracle
+ // bugs #6691741 and #6684387, ProGuard bug #3471941,
+ // and ProGuard test #1180).
+ new ClassHierarchyTraveler(false, false, false, true,
+ new ClassAccessFilter(ClassConstants.INTERNAL_ACC_ABSTRACT, 0,
+ new ClassHierarchyTraveler(false, false, true, false,
+ new AllMemberVisitor(
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap))))),
+
+ // Assign new names to all private members in this class.
+ new AllMemberVisitor(
+ new MemberAccessFilter(ClassConstants.INTERNAL_ACC_PRIVATE, 0,
+ new MemberObfuscator(configuration.overloadAggressively,
+ nameFactory,
+ descriptorMap))),
+
+ // Clear the collected names.
+ new MapCleaner(descriptorMap)
+ }));
+ }
+
+ // Some class members may have ended up with conflicting names.
+ // Come up with new, globally unique names for them.
+ NameFactory specialNameFactory =
+ new SpecialNameFactory(new SimpleNameFactory());
+
+ // Collect a map of special names to avoid
+ // [descriptor - new name - old name].
+ Map specialDescriptorMap = new HashMap();
+
+ programClassPool.classesAccept(
+ new AllMemberVisitor(
+ new MemberSpecialNameFilter(
+ new MemberNameCollector(configuration.overloadAggressively,
+ specialDescriptorMap))));
+
+ libraryClassPool.classesAccept(
+ new AllMemberVisitor(
+ new MemberSpecialNameFilter(
+ new MemberNameCollector(configuration.overloadAggressively,
+ specialDescriptorMap))));
+
+ // Replace conflicting non-private member names with special names.
+ programClassPool.classesAccept(
+ new MultiClassVisitor(new ClassVisitor[]
+ {
+ // Collect all private member names in this class and down
+ // the hierarchy.
+ new ClassHierarchyTraveler(true, false, false, true,
+ new AllMemberVisitor(
+ new MemberAccessFilter(ClassConstants.INTERNAL_ACC_PRIVATE, 0,
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)))),
+
+ // Collect all non-private member names in this class and
+ // higher up the hierarchy.
+ new ClassHierarchyTraveler(true, true, true, false,
+ new AllMemberVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)))),
+
+ // Assign new names to all conflicting non-private members
+ // in this class and higher up the hierarchy.
+ new ClassHierarchyTraveler(true, true, true, false,
+ new AllMemberVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberNameConflictFixer(configuration.overloadAggressively,
+ descriptorMap,
+ warningPrinter,
+ new MemberObfuscator(configuration.overloadAggressively,
+ specialNameFactory,
+ specialDescriptorMap))))),
+
+ // Clear the collected names.
+ new MapCleaner(descriptorMap)
+ }));
+
+ // Replace conflicting private member names with special names.
+ // This is only possible if those names were kept or mapped.
+ programClassPool.classesAccept(
+ new MultiClassVisitor(new ClassVisitor[]
+ {
+ // Collect all member names in this class.
+ new AllMemberVisitor(
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)),
+
+ // Collect all non-private member names higher up the hierarchy.
+ new ClassHierarchyTraveler(false, true, true, false,
+ new AllMemberVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberNameCollector(configuration.overloadAggressively,
+ descriptorMap)))),
+
+ // Assign new names to all conflicting private members in this
+ // class.
+ new AllMemberVisitor(
+ new MemberAccessFilter(ClassConstants.INTERNAL_ACC_PRIVATE, 0,
+ new MemberNameConflictFixer(configuration.overloadAggressively,
+ descriptorMap,
+ warningPrinter,
+ new MemberObfuscator(configuration.overloadAggressively,
+ specialNameFactory,
+ specialDescriptorMap)))),
+
+ // Clear the collected names.
+ new MapCleaner(descriptorMap)
+ }));
+
+ // Print out any warnings about member name conflicts.
+ int warningCount = warningPrinter.getWarningCount();
+ if (warningCount > 0)
+ {
+ System.err.println("Warning: there were " + warningCount +
+ " conflicting class member name mappings.");
+ System.err.println(" Your configuration may be inconsistent.");
+
+ if (!configuration.ignoreWarnings)
+ {
+ System.err.println(" If you are sure the conflicts are harmless,");
+ System.err.println(" you could try your luck using the '-ignorewarnings' option.");
+ throw new IOException("Please correct the above warnings first.");
+ }
+ }
+
+ // Print out the mapping, if requested.
+ if (configuration.printMapping != null)
+ {
+ PrintStream ps =
+ configuration.printMapping == Configuration.STD_OUT ? System.out :
+ new PrintStream(
+ new BufferedOutputStream(
+ new FileOutputStream(configuration.printMapping)));
+
+ // Print out items that will be removed.
+ programClassPool.classesAcceptAlphabetically(new MappingPrinter(ps));
+
+ if (ps == System.out)
+ {
+ ps.flush();
+ }
+ else
+ {
+ ps.close();
+ }
+ }
+
+ // Actually apply the new names.
+ programClassPool.classesAccept(new ClassRenamer());
+ libraryClassPool.classesAccept(new ClassRenamer());
+
+ // Update all references to these new names.
+ programClassPool.classesAccept(new ClassReferenceFixer(false));
+ libraryClassPool.classesAccept(new ClassReferenceFixer(false));
+ programClassPool.classesAccept(new MemberReferenceFixer());
+
+ // Make package visible elements public or protected, if obfuscated
+ // classes are being repackaged aggressively.
+ if (configuration.repackageClasses != null &&
+ configuration.allowAccessModification)
+ {
+ programClassPool.classesAccept(
+ new AllConstantVisitor(
+ new AccessFixer()));
+
+ // Fix the access flags of the inner classes information.
+ programClassPool.classesAccept(
+ new AllAttributeVisitor(
+ new AllInnerClassesInfoVisitor(
+ new InnerClassesAccessFixer())));
+ }
+
+ // Fix the bridge method flags.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new BridgeMethodFixer()));
+
+ // Rename the source file attributes, if requested.
+ if (configuration.newSourceFileAttribute != null)
+ {
+ programClassPool.classesAccept(new SourceFileRenamer(configuration.newSourceFileAttribute));
+ }
+
+ // Remove unused constants.
+ programClassPool.classesAccept(
+ new ConstantPoolShrinker());
+ }
+}
diff --git a/src/proguard/obfuscate/ParameterNameMarker.java b/src/proguard/obfuscate/ParameterNameMarker.java
new file mode 100644
index 000000000..22af12522
--- /dev/null
+++ b/src/proguard/obfuscate/ParameterNameMarker.java
@@ -0,0 +1,128 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.*;
+
+/**
+ * This AttributeVisitor trims and marks all local variable (type) table
+ * attributes that it visits. It keeps parameter names and types and removes
+ * the ordinary local variable names and types.
+ *
+ * @author Eric Lafortune
+ */
+public class ParameterNameMarker
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private final AttributeVisitor attributeUsageMarker;
+
+
+ /**
+ * Constructs a new ParameterNameMarker.
+ * @param attributeUsageMarker the marker that will be used to mark
+ * attributes containing local variable info.
+ */
+ public ParameterNameMarker(AttributeVisitor attributeUsageMarker)
+ {
+ this.attributeUsageMarker = attributeUsageMarker;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ if (!AttributeUsageMarker.isUsed(localVariableTableAttribute) &&
+ hasParameters(clazz, method))
+ {
+ // Shift the entries that start at offset 0 to the front.
+ int newIndex = 0;
+
+ for (int index = 0; index < localVariableTableAttribute.u2localVariableTableLength; index++)
+ {
+ LocalVariableInfo localVariableInfo =
+ localVariableTableAttribute.localVariableTable[index];
+
+ if (localVariableInfo.u2startPC == 0)
+ {
+ localVariableTableAttribute.localVariableTable[newIndex++] =
+ localVariableInfo;
+ }
+ }
+
+ // Trim the table.
+ localVariableTableAttribute.u2localVariableTableLength = newIndex;
+
+ // Mark the table if there are any entries.
+ if (newIndex > 0)
+ {
+ attributeUsageMarker.visitLocalVariableTableAttribute(clazz, method, codeAttribute, localVariableTableAttribute);
+ }
+ }
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ if (!AttributeUsageMarker.isUsed(localVariableTypeTableAttribute) &&
+ hasParameters(clazz, method))
+ {
+ // Shift the entries that start at offset 0 to the front.
+ int newIndex = 0;
+
+ for (int index = 0; index < localVariableTypeTableAttribute.u2localVariableTypeTableLength; index++)
+ {
+ LocalVariableTypeInfo localVariableTypeInfo =
+ localVariableTypeTableAttribute.localVariableTypeTable[index];
+
+ if (localVariableTypeInfo.u2startPC == 0)
+ {
+ localVariableTypeTableAttribute.localVariableTypeTable[newIndex++] =
+ localVariableTypeInfo;
+ }
+ }
+
+ // Trim the table.
+ localVariableTypeTableAttribute.u2localVariableTypeTableLength = newIndex;
+
+ // Mark the table if there are any entries.
+ if (newIndex > 0)
+ {
+ attributeUsageMarker.visitLocalVariableTypeTableAttribute(clazz, method, codeAttribute, localVariableTypeTableAttribute);
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean hasParameters(Clazz clazz, Method method)
+ {
+ return method.getDescriptor(clazz).charAt(1) != ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/obfuscate/SimpleNameFactory.java b/src/proguard/obfuscate/SimpleNameFactory.java
new file mode 100644
index 000000000..0473852d5
--- /dev/null
+++ b/src/proguard/obfuscate/SimpleNameFactory.java
@@ -0,0 +1,156 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import java.util.*;
+
+
+/**
+ * This NameFactory
generates unique short names, using mixed-case
+ * characters or lower-case characters only.
+ *
+ * @author Eric Lafortune
+ */
+public class SimpleNameFactory implements NameFactory
+{
+ private static final int CHARACTER_COUNT = 26;
+
+ private static final List cachedMixedCaseNames = new ArrayList();
+ private static final List cachedLowerCaseNames = new ArrayList();
+
+ private final boolean generateMixedCaseNames;
+ private int index = 0;
+
+
+ /**
+ * Creates a new SimpleNameFactory
that generates mixed-case names.
+ */
+ public SimpleNameFactory()
+ {
+ this(true);
+ }
+
+
+ /**
+ * Creates a new SimpleNameFactory
.
+ * @param generateMixedCaseNames a flag to indicate whether the generated
+ * names will be mixed-case, or lower-case only.
+ */
+ public SimpleNameFactory(boolean generateMixedCaseNames)
+ {
+ this.generateMixedCaseNames = generateMixedCaseNames;
+ }
+
+
+ // Implementations for NameFactory.
+
+ public void reset()
+ {
+ index = 0;
+ }
+
+
+ public String nextName()
+ {
+ return name(index++);
+ }
+
+
+ /**
+ * Returns the name at the given index.
+ */
+ private String name(int index)
+ {
+ // Which cache do we need?
+ List cachedNames = generateMixedCaseNames ?
+ cachedMixedCaseNames :
+ cachedLowerCaseNames;
+
+ // Do we have the name in the cache?
+ if (index < cachedNames.size())
+ {
+ return (String)cachedNames.get(index);
+ }
+
+ // Create a new name and cache it.
+ String name = newName(index);
+ cachedNames.add(index, name);
+
+ return name;
+ }
+
+
+ /**
+ * Creates and returns the name at the given index.
+ */
+ private String newName(int index)
+ {
+ // If we're allowed to generate mixed-case names, we can use twice as
+ // many characters.
+ int totalCharacterCount = generateMixedCaseNames ?
+ 2 * CHARACTER_COUNT :
+ CHARACTER_COUNT;
+
+ int baseIndex = index / totalCharacterCount;
+ int offset = index % totalCharacterCount;
+
+ char newChar = charAt(offset);
+
+ String newName = baseIndex == 0 ?
+ new String(new char[] { newChar }) :
+ (name(baseIndex-1) + newChar);
+
+ return newName;
+ }
+
+
+ /**
+ * Returns the character with the given index, between 0 and the number of
+ * acceptable characters.
+ */
+ private char charAt(int index)
+ {
+ return (char)((index < CHARACTER_COUNT ? 'a' - 0 :
+ 'A' - CHARACTER_COUNT) + index);
+ }
+
+
+ public static void main(String[] args)
+ {
+ System.out.println("Some mixed-case names:");
+ printNameSamples(new SimpleNameFactory(true), 60);
+ System.out.println("Some lower-case names:");
+ printNameSamples(new SimpleNameFactory(false), 60);
+ System.out.println("Some more mixed-case names:");
+ printNameSamples(new SimpleNameFactory(true), 80);
+ System.out.println("Some more lower-case names:");
+ printNameSamples(new SimpleNameFactory(false), 80);
+ }
+
+
+ private static void printNameSamples(SimpleNameFactory factory, int count)
+ {
+ for (int counter = 0; counter < count; counter++)
+ {
+ System.out.println(" ["+factory.nextName()+"]");
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/SourceFileRenamer.java b/src/proguard/obfuscate/SourceFileRenamer.java
new file mode 100644
index 000000000..248d18f51
--- /dev/null
+++ b/src/proguard/obfuscate/SourceFileRenamer.java
@@ -0,0 +1,84 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.editor.ConstantPoolEditor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor changes the name stored in the source file attributes
+ * and source dir attributes of the classes that it visits, if the
+ * attributes are present.
+ *
+ * @author Eric Lafortune
+ */
+public class SourceFileRenamer
+extends SimplifiedVisitor
+implements ClassVisitor,
+ AttributeVisitor
+{
+ private final String newSourceFileAttribute;
+
+
+ /**
+ * Creates a new SourceFileRenamer.
+ * @param newSourceFileAttribute the new string to be put in the source file
+ * attributes.
+ */
+ public SourceFileRenamer(String newSourceFileAttribute)
+ {
+ this.newSourceFileAttribute = newSourceFileAttribute;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Only visit the class attributes.
+ programClass.attributesAccept(this);
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ // Fix the source file attribute.
+ sourceFileAttribute.u2sourceFileIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newSourceFileAttribute);
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ // Fix the source file attribute.
+ sourceDirAttribute.u2sourceDirIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newSourceFileAttribute);
+ }
+}
diff --git a/src/proguard/obfuscate/SpecialNameFactory.java b/src/proguard/obfuscate/SpecialNameFactory.java
new file mode 100644
index 000000000..596f91924
--- /dev/null
+++ b/src/proguard/obfuscate/SpecialNameFactory.java
@@ -0,0 +1,83 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.obfuscate;
+
+/**
+ * This NameFactory
generates names that are special, by appending
+ * a suffix.
+ *
+ * @author Eric Lafortune
+ */
+public class SpecialNameFactory implements NameFactory
+{
+ private static final char SPECIAL_SUFFIX = '_';
+
+
+ private final NameFactory nameFactory;
+
+
+ /**
+ * Creates a new SpecialNameFactory
.
+ * @param nameFactory the name factory from which original names will be
+ * retrieved.
+ */
+ public SpecialNameFactory(NameFactory nameFactory)
+ {
+ this.nameFactory = nameFactory;
+ }
+
+
+ // Implementations for NameFactory.
+
+ public void reset()
+ {
+ nameFactory.reset();
+ }
+
+
+ public String nextName()
+ {
+ return nameFactory.nextName() + SPECIAL_SUFFIX;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether the given name is special.
+ */
+ static boolean isSpecialName(String name)
+ {
+ return name != null &&
+ name.charAt(name.length()-1) == SPECIAL_SUFFIX;
+ }
+
+
+ public static void main(String[] args)
+ {
+ SpecialNameFactory factory = new SpecialNameFactory(new SimpleNameFactory());
+
+ for (int counter = 0; counter < 50; counter++)
+ {
+ System.out.println("["+factory.nextName()+"]");
+ }
+ }
+}
diff --git a/src/proguard/obfuscate/package.html b/src/proguard/obfuscate/package.html
new file mode 100644
index 000000000..a82d26681
--- /dev/null
+++ b/src/proguard/obfuscate/package.html
@@ -0,0 +1,3 @@
+
+This package contains classes to perform obfuscation of class files.
+
diff --git a/src/proguard/optimize/BootstrapMethodArgumentShrinker.java b/src/proguard/optimize/BootstrapMethodArgumentShrinker.java
new file mode 100644
index 000000000..26f134954
--- /dev/null
+++ b/src/proguard/optimize/BootstrapMethodArgumentShrinker.java
@@ -0,0 +1,103 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.ConstantPoolEditor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.info.*;
+import proguard.optimize.peephole.VariableShrinker;
+
+/**
+ * This BootstrapMethodInfoVisitor removes unused constant arguments from
+ * bootstrap method entries that it visits.
+ *
+ * @see ParameterUsageMarker
+ * @see VariableUsageMarker
+ * @see VariableShrinker
+ * @author Eric Lafortune
+ */
+public class BootstrapMethodArgumentShrinker
+extends SimplifiedVisitor
+implements BootstrapMethodInfoVisitor,
+ ConstantVisitor,
+ MemberVisitor
+{
+ private long usedParameters;
+
+
+ // Implementations for BootstrapMethodInfoVisitor.
+
+ public void visitBootstrapMethodInfo(Clazz clazz, BootstrapMethodInfo bootstrapMethodInfo)
+ {
+ // Check which method parameters are used.
+ usedParameters = -1L;
+ clazz.constantPoolEntryAccept(bootstrapMethodInfo.u2methodHandleIndex, this);
+
+ // Remove the unused arguments.
+ int methodArgumentCount = bootstrapMethodInfo.u2methodArgumentCount;
+ int[] methodArguments = bootstrapMethodInfo.u2methodArguments;
+
+ int newArgumentIndex = 0;
+
+ for (int argumentIndex = 0; argumentIndex < methodArgumentCount; argumentIndex++)
+ {
+ if (argumentIndex >= 64 ||
+ (usedParameters & (1L << argumentIndex)) != 0L)
+ {
+ methodArguments[newArgumentIndex++] = methodArguments[argumentIndex];
+ }
+ }
+
+ // Update the number of arguments.
+ bootstrapMethodInfo.u2methodArgumentCount = newArgumentIndex;
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ // Check the referenced bootstrap method.
+ clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex, this);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ // Check the referenced class member itself.
+ refConstant.referencedMemberAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ usedParameters = ParameterUsageMarker.getUsedParameters(programMethod);
+ }
+}
diff --git a/src/proguard/optimize/ChangedCodePrinter.java b/src/proguard/optimize/ChangedCodePrinter.java
new file mode 100644
index 000000000..668d43de9
--- /dev/null
+++ b/src/proguard/optimize/ChangedCodePrinter.java
@@ -0,0 +1,297 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.ClassUtil;
+
+/**
+ * This AttributeVisitor delegates its call to another AttributeVisitor, and
+ * prints out the code if the other visitor has changed it.
+ *
+ * @author Eric Lafortune
+ */
+public class ChangedCodePrinter
+implements AttributeVisitor
+{
+ private final AttributeVisitor attributeVisitor;
+
+
+ public ChangedCodePrinter(AttributeVisitor attributeVisitor)
+ {
+ this.attributeVisitor = attributeVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+
+ public void visitUnknownAttribute(Clazz clazz, UnknownAttribute unknownAttribute)
+ {
+ attributeVisitor.visitUnknownAttribute(clazz, unknownAttribute);
+ }
+
+
+ public void visitBootstrapMethodsAttribute(Clazz clazz, BootstrapMethodsAttribute bootstrapMethodsAttribute)
+ {
+ attributeVisitor.visitBootstrapMethodsAttribute(clazz, bootstrapMethodsAttribute);
+ }
+
+
+ public void visitSourceFileAttribute(Clazz clazz, SourceFileAttribute sourceFileAttribute)
+ {
+ attributeVisitor.visitSourceFileAttribute(clazz, sourceFileAttribute);
+ }
+
+
+ public void visitSourceDirAttribute(Clazz clazz, SourceDirAttribute sourceDirAttribute)
+ {
+ attributeVisitor.visitSourceDirAttribute(clazz, sourceDirAttribute);
+ }
+
+
+ public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
+ {
+ attributeVisitor.visitInnerClassesAttribute(clazz, innerClassesAttribute);
+ }
+
+
+ public void visitEnclosingMethodAttribute(Clazz clazz, EnclosingMethodAttribute enclosingMethodAttribute)
+ {
+ attributeVisitor.visitEnclosingMethodAttribute(clazz, enclosingMethodAttribute);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, DeprecatedAttribute deprecatedAttribute)
+ {
+ attributeVisitor.visitDeprecatedAttribute(clazz, deprecatedAttribute);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, SyntheticAttribute syntheticAttribute)
+ {
+ attributeVisitor.visitSyntheticAttribute(clazz, syntheticAttribute);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute syntheticAttribute)
+ {
+ attributeVisitor.visitSignatureAttribute(clazz, syntheticAttribute);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Field field, DeprecatedAttribute deprecatedAttribute)
+ {
+ attributeVisitor.visitDeprecatedAttribute(clazz, field, deprecatedAttribute);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Field field, SyntheticAttribute syntheticAttribute)
+ {
+ attributeVisitor.visitSyntheticAttribute(clazz, field, syntheticAttribute);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Field field, SignatureAttribute syntheticAttribute)
+ {
+ attributeVisitor.visitSignatureAttribute(clazz, field, syntheticAttribute);
+ }
+
+
+ public void visitDeprecatedAttribute(Clazz clazz, Method method, DeprecatedAttribute deprecatedAttribute)
+ {
+ attributeVisitor.visitDeprecatedAttribute(clazz, method, deprecatedAttribute);
+ }
+
+
+ public void visitSyntheticAttribute(Clazz clazz, Method method, SyntheticAttribute syntheticAttribute)
+ {
+ attributeVisitor.visitSyntheticAttribute(clazz, method, syntheticAttribute);
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Method method, SignatureAttribute syntheticAttribute)
+ {
+ attributeVisitor.visitSignatureAttribute(clazz, method, syntheticAttribute);
+ }
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ attributeVisitor.visitConstantValueAttribute(clazz, field, constantValueAttribute);
+ }
+
+
+ public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
+ {
+ attributeVisitor.visitExceptionsAttribute(clazz, method, exceptionsAttribute);
+ }
+
+
+ public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
+ {
+ attributeVisitor.visitStackMapAttribute(clazz, method, codeAttribute, stackMapAttribute);
+ }
+
+
+ public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
+ {
+ attributeVisitor.visitStackMapTableAttribute(clazz, method, codeAttribute, stackMapTableAttribute);
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ attributeVisitor.visitLineNumberTableAttribute(clazz, method, codeAttribute, lineNumberTableAttribute);
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ attributeVisitor.visitLocalVariableTableAttribute(clazz, method, codeAttribute, localVariableTableAttribute);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ attributeVisitor.visitLocalVariableTypeTableAttribute(clazz, method, codeAttribute, localVariableTypeTableAttribute);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeVisibleAnnotationsAttribute(clazz, runtimeVisibleAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeInvisibleAnnotationsAttribute(clazz, runtimeInvisibleAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeVisibleAnnotationsAttribute(clazz, field, runtimeVisibleAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Field field, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeInvisibleAnnotationsAttribute(clazz, field, runtimeInvisibleAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeVisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleAnnotationsAttribute runtimeVisibleAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeVisibleAnnotationsAttribute(clazz, method, runtimeVisibleAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeInvisibleAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleAnnotationsAttribute runtimeInvisibleAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeInvisibleAnnotationsAttribute(clazz, method, runtimeInvisibleAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeVisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeVisibleParameterAnnotationsAttribute runtimeVisibleParameterAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeVisibleParameterAnnotationsAttribute(clazz, method, runtimeVisibleParameterAnnotationsAttribute);
+ }
+
+
+ public void visitRuntimeInvisibleParameterAnnotationsAttribute(Clazz clazz, Method method, RuntimeInvisibleParameterAnnotationsAttribute runtimeInvisibleParameterAnnotationsAttribute)
+ {
+ attributeVisitor.visitRuntimeInvisibleParameterAnnotationsAttribute(clazz, method, runtimeInvisibleParameterAnnotationsAttribute);
+ }
+
+
+ public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
+ {
+ attributeVisitor.visitAnnotationDefaultAttribute(clazz, method, annotationDefaultAttribute);
+ }
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ byte[] code = codeAttribute.code;
+ byte[] oldCode = new byte[code.length];
+
+ // Copy the current code.
+ System.arraycopy(code, 0, oldCode, 0, codeAttribute.u4codeLength);
+
+ // Delegate to the real visitor.
+ attributeVisitor.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Check if the code has changed.
+ if (codeHasChanged(codeAttribute, oldCode))
+ {
+ printChangedCode(clazz, method, codeAttribute, oldCode);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private boolean codeHasChanged(CodeAttribute codeAttribute, byte[] oldCode)
+ {
+ if (oldCode.length != codeAttribute.u4codeLength)
+ {
+ return true;
+ }
+
+ for (int index = 0; index < codeAttribute.u4codeLength; index++)
+ {
+ if (oldCode[index] != codeAttribute.code[index])
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ private void printChangedCode(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ byte[] oldCode)
+ {
+ System.out.println("Class "+ClassUtil.externalClassName(clazz.getName()));
+ System.out.println("Method "+ClassUtil.externalFullMethodDescription(clazz.getName(),
+ 0,
+ method.getName(clazz),
+ method.getDescriptor(clazz)));
+
+ for (int index = 0; index < codeAttribute.u4codeLength; index++)
+ {
+ System.out.println(
+ (oldCode[index] == codeAttribute.code[index]? " -- ":" => ")+
+ index+": "+
+ Integer.toHexString(0x100|oldCode[index] &0xff).substring(1)+" "+
+ Integer.toHexString(0x100|codeAttribute.code[index]&0xff).substring(1));
+ }
+ }
+}
diff --git a/src/proguard/optimize/ConstantMemberFilter.java b/src/proguard/optimize/ConstantMemberFilter.java
new file mode 100644
index 000000000..1f30a302b
--- /dev/null
+++ b/src/proguard/optimize/ConstantMemberFilter.java
@@ -0,0 +1,77 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.evaluation.value.Value;
+import proguard.optimize.evaluation.StoringInvocationUnit;
+
+/**
+ * This MemberVisitor
delegates its visits to program class members
+ * to another given MemberVisitor
, but only when the visited
+ * class member has been marked as a constant.
+ *
+ * @see StoringInvocationUnit
+ * @author Eric Lafortune
+ */
+public class ConstantMemberFilter
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final MemberVisitor constantMemberVisitor;
+
+
+ /**
+ * Creates a new ConstantMemberFilter.
+ * @param constantMemberVisitor the MemberVisitor
to which
+ * visits to constant members will be delegated.
+ */
+ public ConstantMemberFilter(MemberVisitor constantMemberVisitor)
+ {
+ this.constantMemberVisitor = constantMemberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ Value value = StoringInvocationUnit.getFieldValue(programField);
+ if (value != null &&
+ value.isParticular())
+ {
+ constantMemberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ Value value = StoringInvocationUnit.getMethodReturnValue(programMethod);
+ if (value != null &&
+ value.isParticular())
+ {
+ constantMemberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+}
diff --git a/src/proguard/optimize/ConstantParameterFilter.java b/src/proguard/optimize/ConstantParameterFilter.java
new file mode 100644
index 000000000..1500fd0a9
--- /dev/null
+++ b/src/proguard/optimize/ConstantParameterFilter.java
@@ -0,0 +1,79 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.evaluation.value.Value;
+import proguard.optimize.evaluation.StoringInvocationUnit;
+import proguard.optimize.info.ParameterUsageMarker;
+
+/**
+ * This MemberVisitor
delegates its visits to program methods
+ * to another given MemberVisitor
, for each method parameter
+ * that has been marked as constant.
+ *
+ * @see StoringInvocationUnit
+ * @author Eric Lafortune
+ */
+public class ConstantParameterFilter
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final MemberVisitor constantParameterVisitor;
+
+
+ /**
+ * Creates a new ConstantParameterFilter.
+ * @param constantParameterVisitor the MemberVisitor
to which
+ * visits will be delegated.
+ */
+ public ConstantParameterFilter(MemberVisitor constantParameterVisitor)
+ {
+ this.constantParameterVisitor = constantParameterVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // All parameters of non-static methods are shifted by one in the local
+ // variable frame.
+ int firstParameterIndex =
+ (programMethod.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0 ?
+ 0 : 1;
+
+ int parameterCount =
+ ClassUtil.internalMethodParameterCount(programMethod.getDescriptor(programClass));
+
+ for (int index = firstParameterIndex; index < parameterCount; index++)
+ {
+ Value value = StoringInvocationUnit.getMethodParameterValue(programMethod, index);
+ if (value != null &&
+ value.isParticular())
+ {
+ constantParameterVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/DuplicateInitializerFixer.java b/src/proguard/optimize/DuplicateInitializerFixer.java
new file mode 100644
index 000000000..95bc2f10f
--- /dev/null
+++ b/src/proguard/optimize/DuplicateInitializerFixer.java
@@ -0,0 +1,215 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.editor.ConstantPoolEditor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This MemberVisitor adds an additional parameter to the duplicate
+ * initialization methods that it visits.
+ */
+public class DuplicateInitializerFixer
+extends SimplifiedVisitor
+implements MemberVisitor,
+ AttributeVisitor
+{
+ private static final boolean DEBUG = false;
+
+ private static final char[] TYPES = new char[]
+ {
+ ClassConstants.INTERNAL_TYPE_BYTE,
+ ClassConstants.INTERNAL_TYPE_CHAR,
+ ClassConstants.INTERNAL_TYPE_SHORT,
+ ClassConstants.INTERNAL_TYPE_INT,
+ ClassConstants.INTERNAL_TYPE_BOOLEAN
+ };
+
+
+ private final MemberVisitor extraFixedInitializerVisitor;
+
+
+ /**
+ * Creates a new DuplicateInitializerFixer.
+ */
+ public DuplicateInitializerFixer()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new DuplicateInitializerFixer with an extra visitor.
+ * @param extraFixedInitializerVisitor an optional extra visitor for all
+ * initializers that have been fixed.
+ */
+ public DuplicateInitializerFixer(MemberVisitor extraFixedInitializerVisitor)
+ {
+ this.extraFixedInitializerVisitor = extraFixedInitializerVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Is it a class instance initializer?
+ String name = programMethod.getName(programClass);
+ if (name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
+ {
+ // Is there already another initializer with the same descriptor?
+ String descriptor = programMethod.getDescriptor(programClass);
+ Method similarMethod = programClass.findMethod(name, descriptor);
+ if (!programMethod.equals(similarMethod))
+ {
+ // Should this initializer be preserved?
+ if (KeepMarker.isKept(programMethod))
+ {
+ // Fix the other initializer.
+ programMethod = (ProgramMethod)similarMethod;
+ }
+
+ int index = descriptor.indexOf(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+
+ // Try to find a new, unique descriptor.
+ int typeCounter = 0;
+ while (true)
+ {
+ // Construct the new descriptor by inserting a new type
+ // as an additional last argument.
+ StringBuffer newDescriptorBuffer =
+ new StringBuffer(descriptor.substring(0, index));
+
+ for (int arrayDimension = 0; arrayDimension < typeCounter / TYPES.length; arrayDimension++)
+ {
+ newDescriptorBuffer.append(ClassConstants.INTERNAL_TYPE_ARRAY);
+ }
+
+ newDescriptorBuffer.append(TYPES[typeCounter % TYPES.length]);
+ newDescriptorBuffer.append(descriptor.substring(index));
+
+ String newDescriptor = newDescriptorBuffer.toString();
+
+ // Is the new initializer descriptor unique?
+ if (programClass.findMethod(name, newDescriptor) == null)
+ {
+ if (DEBUG)
+ {
+ System.out.println("DuplicateInitializerFixer:");
+ System.out.println(" ["+programClass.getName()+"."+name+descriptor+"] ("+ClassUtil.externalClassAccessFlags(programMethod.getAccessFlags())+") -> ["+newDescriptor+"]");
+ }
+
+ // Update the descriptor.
+ programMethod.u2descriptorIndex =
+ new ConstantPoolEditor(programClass).addUtf8Constant(newDescriptor);
+
+ // Fix the local variable frame size, the method
+ // signature, and the parameter annotations, if
+ // necessary.
+ programMethod.attributesAccept(programClass,
+ this);
+
+ // Visit the initializer, if required.
+ if (extraFixedInitializerVisitor != null)
+ {
+ extraFixedInitializerVisitor.visitProgramMethod(programClass, programMethod);
+ }
+
+ // We're done with this constructor.
+ return;
+ }
+
+ typeCounter++;
+ }
+ }
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // The minimum variable size is determined by the arguments.
+ int maxLocals =
+ ClassUtil.internalMethodParameterSize(method.getDescriptor(clazz),
+ method.getAccessFlags());
+
+ if (codeAttribute.u2maxLocals < maxLocals)
+ {
+ codeAttribute.u2maxLocals = maxLocals;
+ }
+ }
+
+
+ public void visitSignatureAttribute(Clazz clazz, Method method, SignatureAttribute signatureAttribute)
+ {
+ String descriptor = method.getDescriptor(clazz);
+ int descriptorIndex = descriptor.indexOf(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+ String signature = clazz.getString(signatureAttribute.u2signatureIndex);
+ int signatureIndex = signature.indexOf(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+
+ String newSignature = signature.substring(0, signatureIndex) +
+ descriptor.charAt(descriptorIndex - 1) +
+ signature.substring(signatureIndex);
+
+ // Update the signature.
+ signatureAttribute.u2signatureIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newSignature);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ // Update the number of parameters.
+ int oldParametersCount = parameterAnnotationsAttribute.u2parametersCount++;
+
+ if (parameterAnnotationsAttribute.u2parameterAnnotationsCount == null ||
+ parameterAnnotationsAttribute.u2parameterAnnotationsCount.length < parameterAnnotationsAttribute.u2parametersCount)
+ {
+ int[] annotationsCounts = new int[parameterAnnotationsAttribute.u2parametersCount];
+ Annotation[][] annotations = new Annotation[parameterAnnotationsAttribute.u2parametersCount][];
+
+ System.arraycopy(parameterAnnotationsAttribute.u2parameterAnnotationsCount,
+ 0,
+ annotationsCounts,
+ 0,
+ oldParametersCount);
+
+ System.arraycopy(parameterAnnotationsAttribute.parameterAnnotations,
+ 0,
+ annotations,
+ 0,
+ oldParametersCount);
+
+ parameterAnnotationsAttribute.u2parameterAnnotationsCount = annotationsCounts;
+ parameterAnnotationsAttribute.parameterAnnotations = annotations;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/DuplicateInitializerInvocationFixer.java b/src/proguard/optimize/DuplicateInitializerInvocationFixer.java
new file mode 100644
index 000000000..5edaba0e6
--- /dev/null
+++ b/src/proguard/optimize/DuplicateInitializerInvocationFixer.java
@@ -0,0 +1,161 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.CodeAttributeEditor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This AttributeVisitor adds an additional integer parameter to the tweaked
+ * initialization method invocations that it visits.
+ */
+public class DuplicateInitializerInvocationFixer
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ConstantVisitor,
+ MemberVisitor
+{
+ private static final boolean DEBUG = false;
+
+ private final InstructionVisitor extraAddedInstructionVisitor;
+
+ private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor();
+
+ private String descriptor;
+ private int descriptorLengthDelta;
+
+
+ /**
+ * Creates a new DuplicateInitializerInvocationFixer.
+ */
+ public DuplicateInitializerInvocationFixer()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new DuplicateInitializerInvocationFixer.
+ * @param extraAddedInstructionVisitor an optional extra visitor for all
+ * added instructions.
+ */
+ public DuplicateInitializerInvocationFixer(InstructionVisitor extraAddedInstructionVisitor)
+ {
+ this.extraAddedInstructionVisitor = extraAddedInstructionVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+
+ // Reset the code changes.
+ codeAttributeEditor.reset(codeAttribute.u4codeLength);
+
+ // Fix any duplicate constructor invocations.
+ codeAttribute.instructionsAccept(clazz,
+ method,
+ this);
+
+ // Apply all accumulated changes to the code.
+ codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ if (constantInstruction.opcode == InstructionConstants.OP_INVOKESPECIAL)
+ {
+ descriptorLengthDelta = 0;
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+
+ if (descriptorLengthDelta > 0)
+ {
+ Instruction extraInstruction =
+ new SimpleInstruction(descriptorLengthDelta == 1 ?
+ InstructionConstants.OP_ICONST_0 :
+ InstructionConstants.OP_ACONST_NULL);
+
+ codeAttributeEditor.insertBeforeInstruction(offset,
+ extraInstruction);
+
+ if (DEBUG)
+ {
+ System.out.println(" ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"] Inserting "+extraInstruction.toString()+" before "+constantInstruction.toString(offset));
+ }
+
+ if (extraAddedInstructionVisitor != null)
+ {
+ extraInstruction.accept(null, null, null, offset, extraAddedInstructionVisitor);
+ }
+ }
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ // Check the referenced constructor descriptor.
+ descriptor = methodrefConstant.getType(clazz);
+ methodrefConstant.referencedMemberAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod) {}
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ descriptorLengthDelta =
+ programMethod.getDescriptor(programClass).length() - descriptor.length();
+
+ if (DEBUG)
+ {
+ if (descriptorLengthDelta > 0)
+ {
+ System.out.println("DuplicateInitializerInvocationFixer:");
+ System.out.println(" ["+programClass.getName()+"."+programMethod.getName(programClass)+programMethod.getDescriptor(programClass)+"] ("+ClassUtil.externalClassAccessFlags(programMethod.getAccessFlags())+") referenced by:");
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/KeepMarker.java b/src/proguard/optimize/KeepMarker.java
new file mode 100644
index 000000000..b0eab7b4c
--- /dev/null
+++ b/src/proguard/optimize/KeepMarker.java
@@ -0,0 +1,103 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.util.MethodLinker;
+import proguard.classfile.visitor.*;
+import proguard.optimize.info.NoSideEffectMethodMarker;
+
+
+/**
+ * This ClassVisitor
and MemberVisitor
+ * marks classes and class members it visits. The marked elements
+ * will remain unchanged as necessary in the optimization step.
+ *
+ * @see NoSideEffectMethodMarker
+ * @author Eric Lafortune
+ */
+public class KeepMarker
+implements ClassVisitor,
+ MemberVisitor
+{
+ // A visitor info flag to indicate the visitor accepter is being kept.
+ private static final Object KEPT = new Object();
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ markAsKept(programClass);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ markAsKept(libraryClass);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ markAsKept(programField);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ markAsKept(MethodLinker.lastMember(programMethod));
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ markAsKept(libraryField);
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ markAsKept(MethodLinker.lastMember(libraryMethod));
+ }
+
+
+ // Small utility methods.
+
+ private static void markAsKept(VisitorAccepter visitorAccepter)
+ {
+ visitorAccepter.setVisitorInfo(KEPT);
+ }
+
+
+ public static boolean isKept(VisitorAccepter visitorAccepter)
+ {
+ // We're also checking for the constant in NoSideEffectMethodMarker,
+ // to keep things simple.
+ Object visitorInfo =
+ MethodLinker.lastVisitorAccepter(visitorAccepter).getVisitorInfo();
+
+ return visitorInfo == KEPT ||
+ visitorInfo == NoSideEffectMethodMarker.KEPT_BUT_NO_SIDE_EFFECTS;
+ }
+}
diff --git a/src/proguard/optimize/KeptClassFilter.java b/src/proguard/optimize/KeptClassFilter.java
new file mode 100644
index 000000000..60a9d3e3f
--- /dev/null
+++ b/src/proguard/optimize/KeptClassFilter.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor delegates all its method calls to another ClassVisitor,
+ * but only for Clazz objects that are marked as kept.
+ *
+ * @see KeepMarker
+ *
+ * @author Eric Lafortune
+ */
+public class KeptClassFilter
+implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new KeptClassFilter.
+ * @param classVisitor the class visitor to which the visiting will be
+ * delegated.
+ */
+ public KeptClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (KeepMarker.isKept(programClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (KeepMarker.isKept(libraryClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/KeptMemberFilter.java b/src/proguard/optimize/KeptMemberFilter.java
new file mode 100644
index 000000000..1bdadb4c5
--- /dev/null
+++ b/src/proguard/optimize/KeptMemberFilter.java
@@ -0,0 +1,87 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This MemberVisitor delegates all its method calls to another MemberVisitor,
+ * but only for Member objects that are marked as kept.
+ *
+ * @see KeepMarker
+ *
+ * @author Eric Lafortune
+ */
+public class KeptMemberFilter
+implements MemberVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new KeptMemberFilter.
+ * @param memberVisitor the member visitor to which the visiting will be
+ * delegated.
+ */
+ public KeptMemberFilter(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (KeepMarker.isKept(programField))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (KeepMarker.isKept(programMethod))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (KeepMarker.isKept(libraryField))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (KeepMarker.isKept(libraryMethod))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/MemberDescriptorSpecializer.java b/src/proguard/optimize/MemberDescriptorSpecializer.java
new file mode 100644
index 000000000..4dce62e3f
--- /dev/null
+++ b/src/proguard/optimize/MemberDescriptorSpecializer.java
@@ -0,0 +1,138 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.editor.ClassReferenceFixer;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.evaluation.value.Value;
+import proguard.optimize.evaluation.StoringInvocationUnit;
+
+/**
+ * This MemberVisitor specializes parameters in the descriptors of the
+ * methods that it visits.
+ *
+ * @see StoringInvocationUnit
+ * @see ClassReferenceFixer
+ * @author Eric Lafortune
+ */
+public class MemberDescriptorSpecializer
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private static final boolean DEBUG = false;
+
+
+ private final MemberVisitor extraParameterMemberVisitor;
+
+
+ /**
+ * Creates a new MethodDescriptorShrinker.
+ */
+ public MemberDescriptorSpecializer()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new MethodDescriptorShrinker with an extra visitor.
+ * @param extraParameterMemberVisitor an optional extra visitor for all
+ * class members whose parameters have
+ * been specialized.
+ */
+ public MemberDescriptorSpecializer(MemberVisitor extraParameterMemberVisitor)
+ {
+ this.extraParameterMemberVisitor = extraParameterMemberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ Value parameterValue = StoringInvocationUnit.getFieldValue(programField);
+ if (parameterValue.computationalType() == Value.TYPE_REFERENCE)
+ {
+ Clazz referencedClass = parameterValue.referenceValue().getReferencedClass();
+ if (programField.referencedClass != referencedClass)
+ {
+ if (DEBUG)
+ {
+ System.out.println("MemberDescriptorSpecializer: "+programClass.getName()+"."+programField.getName(programClass)+" "+programField.getDescriptor(programClass));
+ System.out.println(" "+programField.referencedClass.getName()+" -> "+referencedClass.getName());
+ }
+
+ programField.referencedClass = referencedClass;
+
+ // Visit the field, if required.
+ if (extraParameterMemberVisitor != null)
+ {
+ extraParameterMemberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // All parameters of non-static methods are shifted by one in the local
+ // variable frame.
+ int firstParameterIndex =
+ (programMethod.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0 ?
+ 0 : 1;
+
+ int parameterCount =
+ ClassUtil.internalMethodParameterCount(programMethod.getDescriptor(programClass));
+
+ int classIndex = 0;
+
+ // Go over the parameters.
+ for (int parameterIndex = firstParameterIndex; parameterIndex < parameterCount; parameterIndex++)
+ {
+ Value parameterValue = StoringInvocationUnit.getMethodParameterValue(programMethod, parameterIndex);
+ if (parameterValue.computationalType() == Value.TYPE_REFERENCE)
+ {
+ Clazz referencedClass = parameterValue.referenceValue().getReferencedClass();
+ if (programMethod.referencedClasses[classIndex] != referencedClass)
+ {
+ if (DEBUG)
+ {
+ System.out.println("MemberDescriptorSpecializer: "+programClass.getName()+"."+programMethod.getName(programClass)+programMethod.getDescriptor(programClass));
+ System.out.println(" "+programMethod.referencedClasses[classIndex].getName()+" -> "+referencedClass.getName());
+ }
+
+ programMethod.referencedClasses[classIndex] = referencedClass;
+
+ // Visit the method, if required.
+ if (extraParameterMemberVisitor != null)
+ {
+ extraParameterMemberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+ classIndex++;
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/MethodDescriptorShrinker.java b/src/proguard/optimize/MethodDescriptorShrinker.java
new file mode 100644
index 000000000..d8d44250d
--- /dev/null
+++ b/src/proguard/optimize/MethodDescriptorShrinker.java
@@ -0,0 +1,317 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.editor.ConstantPoolEditor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.info.*;
+import proguard.optimize.peephole.VariableShrinker;
+
+/**
+ * This MemberVisitor removes unused parameters in the descriptors of the
+ * methods that it visits.
+ *
+ * @see ParameterUsageMarker
+ * @see VariableUsageMarker
+ * @see VariableShrinker
+ * @author Eric Lafortune
+ */
+public class MethodDescriptorShrinker
+extends SimplifiedVisitor
+implements MemberVisitor,
+ AttributeVisitor
+{
+ private static final boolean DEBUG = false;
+
+
+ private final MemberVisitor extraMemberVisitor;
+
+
+ /**
+ * Creates a new MethodDescriptorShrinker.
+ */
+ public MethodDescriptorShrinker()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new MethodDescriptorShrinker with an extra visitor.
+ * @param extraMemberVisitor an optional extra visitor for all methods whose
+ * parameters have been simplified.
+ */
+ public MethodDescriptorShrinker(MemberVisitor extraMemberVisitor)
+ {
+ this.extraMemberVisitor = extraMemberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Update the descriptor if it has any unused parameters.
+ String descriptor = programMethod.getDescriptor(programClass);
+ String newDescriptor = shrinkDescriptor(programMethod, descriptor);
+
+ if (!descriptor.equals(newDescriptor))
+ {
+ // Shrink the signature and parameter annotations.
+ programMethod.attributesAccept(programClass, this);
+
+ String name = programMethod.getName(programClass);
+ String newName = name;
+
+ // Append a code, if the method isn't a class instance initializer.
+ if (!name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
+ {
+ newName += ClassConstants.SPECIAL_MEMBER_SEPARATOR + Long.toHexString(Math.abs((descriptor).hashCode()));
+ }
+
+ if (DEBUG)
+ {
+ System.out.println("MethodDescriptorShrinker:");
+ System.out.println(" ["+programClass.getName()+"."+
+ name+descriptor+"] -> ["+
+ newName+newDescriptor+"]");
+ }
+
+ ConstantPoolEditor constantPoolEditor =
+ new ConstantPoolEditor(programClass);
+
+ // Update the name, if necessary.
+ if (!newName.equals(name))
+ {
+ programMethod.u2nameIndex =
+ constantPoolEditor.addUtf8Constant(newName);
+ }
+
+ // Update the referenced classes.
+ programMethod.referencedClasses =
+ shrinkReferencedClasses(programMethod,
+ descriptor,
+ programMethod.referencedClasses);
+
+ // Finally, update the descriptor itself.
+ programMethod.u2descriptorIndex =
+ constantPoolEditor.addUtf8Constant(newDescriptor);
+
+ // Visit the method, if required.
+ if (extraMemberVisitor != null)
+ {
+ extraMemberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitSignatureAttribute(Clazz clazz, Method method, SignatureAttribute signatureAttribute)
+ {
+ // Compute the new signature.
+ String signature = clazz.getString(signatureAttribute.u2signatureIndex);
+ String newSignature = shrinkDescriptor(method, signature);
+
+ // Update the signature.
+ signatureAttribute.u2signatureIndex =
+ new ConstantPoolEditor((ProgramClass)clazz).addUtf8Constant(newSignature);
+
+ // Update the referenced classes.
+ signatureAttribute.referencedClasses =
+ shrinkReferencedClasses(method,
+ signature,
+ signatureAttribute.referencedClasses);
+ }
+
+
+ public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
+ {
+ int[] annotationsCounts = parameterAnnotationsAttribute.u2parameterAnnotationsCount;
+ Annotation[][] annotations = parameterAnnotationsAttribute.parameterAnnotations;
+
+ // All parameters of non-static methods are shifted by one in the local
+ // variable frame.
+ int parameterIndex =
+ (method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0 ?
+ 0 : 1;
+
+ int annotationIndex = 0;
+ int newAnnotationIndex = 0;
+
+ // Go over the parameters.
+ String descriptor = method.getDescriptor(clazz);
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(descriptor);
+
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ String type = internalTypeEnumeration.nextType();
+ if (ParameterUsageMarker.isParameterUsed(method, parameterIndex))
+ {
+ annotationsCounts[newAnnotationIndex] = annotationsCounts[annotationIndex];
+ annotations[newAnnotationIndex++] = annotations[annotationIndex];
+ }
+
+ annotationIndex++;
+
+ parameterIndex += ClassUtil.isInternalCategory2Type(type) ? 2 : 1;
+ }
+
+ // Update the number of parameters.
+ parameterAnnotationsAttribute.u2parametersCount = newAnnotationIndex;
+
+ // Clear the unused entries.
+ while (newAnnotationIndex < annotationIndex)
+ {
+ annotationsCounts[newAnnotationIndex] = 0;
+ annotations[newAnnotationIndex++] = null;
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns a shrunk descriptor or signature of the given method.
+ */
+ private String shrinkDescriptor(Method method, String descriptor)
+ {
+ // All parameters of non-static methods are shifted by one in the local
+ // variable frame.
+ int parameterIndex =
+ (method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0 ?
+ 0 : 1;
+
+ // Go over the parameters.
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(descriptor);
+
+ StringBuffer newDescriptorBuffer = new StringBuffer();
+
+ newDescriptorBuffer.append(internalTypeEnumeration.formalTypeParameters());
+ newDescriptorBuffer.append(ClassConstants.INTERNAL_METHOD_ARGUMENTS_OPEN);
+
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ String type = internalTypeEnumeration.nextType();
+ if (ParameterUsageMarker.isParameterUsed(method, parameterIndex))
+ {
+ newDescriptorBuffer.append(type);
+ }
+ else if (DEBUG)
+ {
+ System.out.println(" Deleting parameter #"+parameterIndex+" ["+type+"]");
+ }
+
+ parameterIndex += ClassUtil.isInternalCategory2Type(type) ? 2 : 1;
+ }
+
+ newDescriptorBuffer.append(ClassConstants.INTERNAL_METHOD_ARGUMENTS_CLOSE);
+ newDescriptorBuffer.append(internalTypeEnumeration.returnType());
+
+ return newDescriptorBuffer.toString();
+ }
+
+
+ /**
+ * Shrinks the array of referenced classes of the given method.
+ */
+ private Clazz[] shrinkReferencedClasses(Method method,
+ String descriptor,
+ Clazz[] referencedClasses)
+ {
+ if (referencedClasses != null)
+ {
+ // All parameters of non-static methods are shifted by one in the local
+ // variable frame.
+ int parameterIndex =
+ (method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0 ?
+ 0 : 1;
+
+ int referencedClassIndex = 0;
+ int newReferencedClassIndex = 0;
+
+ // Go over the parameters.
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(descriptor);
+
+ // Also look at the formal type parameters.
+ String type = internalTypeEnumeration.formalTypeParameters();
+ int count = new DescriptorClassEnumeration(type).classCount();
+ for (int counter = 0; counter < count; counter++)
+ {
+ referencedClasses[newReferencedClassIndex++] =
+ referencedClasses[referencedClassIndex++];
+ }
+
+ while (internalTypeEnumeration.hasMoreTypes())
+ {
+ // Consider the classes referenced by this parameter type.
+ type = internalTypeEnumeration.nextType();
+ count = new DescriptorClassEnumeration(type).classCount();
+
+ if (ParameterUsageMarker.isParameterUsed(method, parameterIndex))
+ {
+ // Copy the referenced classes.
+ for (int counter = 0; counter < count; counter++)
+ {
+ referencedClasses[newReferencedClassIndex++] =
+ referencedClasses[referencedClassIndex++];
+ }
+ }
+ else
+ {
+ // Skip the referenced classes.
+ referencedClassIndex += count;
+ }
+
+ parameterIndex += ClassUtil.isInternalCategory2Type(type) ? 2 : 1;
+ }
+
+ // Also look at the return value.
+ type = internalTypeEnumeration.returnType();
+ count = new DescriptorClassEnumeration(type).classCount();
+ for (int counter = 0; counter < count; counter++)
+ {
+ referencedClasses[newReferencedClassIndex++] =
+ referencedClasses[referencedClassIndex++];
+ }
+
+ // Clear the unused entries.
+ while (newReferencedClassIndex < referencedClassIndex)
+ {
+ referencedClasses[newReferencedClassIndex++] = null;
+ }
+ }
+
+ return referencedClasses;
+ }
+}
diff --git a/src/proguard/optimize/MethodStaticizer.java b/src/proguard/optimize/MethodStaticizer.java
new file mode 100644
index 000000000..c8bdd11dc
--- /dev/null
+++ b/src/proguard/optimize/MethodStaticizer.java
@@ -0,0 +1,87 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.editor.MethodInvocationFixer;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.info.ParameterUsageMarker;
+import proguard.optimize.peephole.VariableShrinker;
+
+/**
+ * This MemberVisitor makes all methods that it visits static, if their 'this'
+ * parameters are unused.
+ *
+ * @see ParameterUsageMarker
+ * @see MethodInvocationFixer
+ * @see VariableShrinker
+ * @author Eric Lafortune
+ */
+public class MethodStaticizer
+extends SimplifiedVisitor
+implements MemberVisitor,
+ AttributeVisitor
+{
+ private final MemberVisitor extraStaticMemberVisitor;
+
+
+ /**
+ * Creates a new MethodStaticizer.
+ */
+ public MethodStaticizer()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new MethodStaticizer with an extra visitor.
+ * @param extraStaticMemberVisitor an optional extra visitor for all
+ * methods that have been made static.
+ */
+ public MethodStaticizer(MemberVisitor extraStaticMemberVisitor)
+ {
+ this.extraStaticMemberVisitor = extraStaticMemberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Is the 'this' parameter being used?
+ if (!ParameterUsageMarker.isParameterUsed(programMethod, 0))
+ {
+ // Make the method static.
+ programMethod.u2accessFlags =
+ (programMethod.getAccessFlags() & ~ClassConstants.INTERNAL_ACC_FINAL) |
+ ClassConstants.INTERNAL_ACC_STATIC;
+
+ // Visit the method, if required.
+ if (extraStaticMemberVisitor != null)
+ {
+ extraStaticMemberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/OptimizationInfoMemberFilter.java b/src/proguard/optimize/OptimizationInfoMemberFilter.java
new file mode 100644
index 000000000..2c5454cab
--- /dev/null
+++ b/src/proguard/optimize/OptimizationInfoMemberFilter.java
@@ -0,0 +1,94 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.info.*;
+
+/**
+ * This MemberVisitor
delegates its visits to another given
+ * MemberVisitor
, but only when the visited member has optimization
+ * info.
+ *
+ * @see FieldOptimizationInfo
+ * @see MethodOptimizationInfo
+ * @author Eric Lafortune
+ */
+public class OptimizationInfoMemberFilter
+implements MemberVisitor
+{
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new OptimizationInfoMemberFilter.
+ * @param memberVisitor the MemberVisitor
to which visits will
+ * be delegated.
+ */
+ public OptimizationInfoMemberFilter(MemberVisitor memberVisitor)
+ {
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ // Does the field have optimization info?
+ if (FieldOptimizationInfo.getFieldOptimizationInfo(programField) != null)
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ // Does the field have optimization info?
+ if (FieldOptimizationInfo.getFieldOptimizationInfo(libraryField) != null)
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Does the method have optimization info?
+ if (MethodOptimizationInfo.getMethodOptimizationInfo(programMethod) != null)
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ // Does the method have optimization info?
+ if (MethodOptimizationInfo.getMethodOptimizationInfo(libraryMethod) != null)
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+}
diff --git a/src/proguard/optimize/Optimizer.java b/src/proguard/optimize/Optimizer.java
new file mode 100644
index 000000000..8042825ec
--- /dev/null
+++ b/src/proguard/optimize/Optimizer.java
@@ -0,0 +1,963 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.*;
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.Constant;
+import proguard.classfile.constant.visitor.*;
+import proguard.classfile.editor.*;
+import proguard.classfile.instruction.visitor.*;
+import proguard.classfile.util.MethodLinker;
+import proguard.classfile.visitor.*;
+import proguard.evaluation.*;
+import proguard.evaluation.value.*;
+import proguard.optimize.evaluation.*;
+import proguard.optimize.info.*;
+import proguard.optimize.peephole.*;
+import proguard.util.*;
+
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * This class optimizes class pools according to a given configuration.
+ *
+ * @author Eric Lafortune
+ */
+public class Optimizer
+{
+ private static final String CLASS_MARKING_FINAL = "class/marking/final";
+ private static final String CLASS_MERGING_VERTICAL = "class/merging/vertical";
+ private static final String CLASS_MERGING_HORIZONTAL = "class/merging/horizontal";
+ private static final String FIELD_REMOVAL_WRITEONLY = "field/removal/writeonly";
+ private static final String FIELD_MARKING_PRIVATE = "field/marking/private";
+ private static final String FIELD_PROPAGATION_VALUE = "field/propagation/value";
+ private static final String METHOD_MARKING_PRIVATE = "method/marking/private";
+ private static final String METHOD_MARKING_STATIC = "method/marking/static";
+ private static final String METHOD_MARKING_FINAL = "method/marking/final";
+ private static final String METHOD_REMOVAL_PARAMETER = "method/removal/parameter";
+ private static final String METHOD_PROPAGATION_PARAMETER = "method/propagation/parameter";
+ private static final String METHOD_PROPAGATION_RETURNVALUE = "method/propagation/returnvalue";
+ private static final String METHOD_INLINING_SHORT = "method/inlining/short";
+ private static final String METHOD_INLINING_UNIQUE = "method/inlining/unique";
+ private static final String METHOD_INLINING_TAILRECURSION = "method/inlining/tailrecursion";
+ private static final String CODE_MERGING = "code/merging";
+ private static final String CODE_SIMPLIFICATION_VARIABLE = "code/simplification/variable";
+ private static final String CODE_SIMPLIFICATION_ARITHMETIC = "code/simplification/arithmetic";
+ private static final String CODE_SIMPLIFICATION_CAST = "code/simplification/cast";
+ private static final String CODE_SIMPLIFICATION_FIELD = "code/simplification/field";
+ private static final String CODE_SIMPLIFICATION_BRANCH = "code/simplification/branch";
+ private static final String CODE_SIMPLIFICATION_STRING = "code/simplification/string";
+ private static final String CODE_SIMPLIFICATION_ADVANCED = "code/simplification/advanced";
+ private static final String CODE_REMOVAL_ADVANCED = "code/removal/advanced";
+ private static final String CODE_REMOVAL_SIMPLE = "code/removal/simple";
+ private static final String CODE_REMOVAL_VARIABLE = "code/removal/variable";
+ private static final String CODE_REMOVAL_EXCEPTION = "code/removal/exception";
+ private static final String CODE_ALLOCATION_VARIABLE = "code/allocation/variable";
+
+
+ public static final String[] OPTIMIZATION_NAMES = new String[]
+ {
+ CLASS_MARKING_FINAL,
+ CLASS_MERGING_VERTICAL,
+ CLASS_MERGING_HORIZONTAL,
+ FIELD_REMOVAL_WRITEONLY,
+ FIELD_MARKING_PRIVATE,
+ FIELD_PROPAGATION_VALUE,
+ METHOD_MARKING_PRIVATE,
+ METHOD_MARKING_STATIC,
+ METHOD_MARKING_FINAL,
+ METHOD_REMOVAL_PARAMETER,
+ METHOD_PROPAGATION_PARAMETER,
+ METHOD_PROPAGATION_RETURNVALUE,
+ METHOD_INLINING_SHORT,
+ METHOD_INLINING_UNIQUE,
+ METHOD_INLINING_TAILRECURSION,
+ CODE_MERGING,
+ CODE_SIMPLIFICATION_VARIABLE,
+ CODE_SIMPLIFICATION_ARITHMETIC,
+ CODE_SIMPLIFICATION_CAST,
+ CODE_SIMPLIFICATION_FIELD,
+ CODE_SIMPLIFICATION_BRANCH,
+ CODE_SIMPLIFICATION_STRING,
+ CODE_SIMPLIFICATION_ADVANCED,
+ CODE_REMOVAL_ADVANCED,
+ CODE_REMOVAL_SIMPLE,
+ CODE_REMOVAL_VARIABLE,
+ CODE_REMOVAL_EXCEPTION,
+ CODE_ALLOCATION_VARIABLE,
+ };
+
+
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new Optimizer.
+ */
+ public Optimizer(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Performs optimization of the given program class pool.
+ */
+ public boolean execute(ClassPool programClassPool,
+ ClassPool libraryClassPool) throws IOException
+ {
+ // Check if we have at least some keep commands.
+ if (configuration.keep == null &&
+ configuration.applyMapping == null &&
+ configuration.printMapping == null)
+ {
+ throw new IOException("You have to specify '-keep' options for the optimization step.");
+ }
+
+ // Create a matcher for filtering optimizations.
+ StringMatcher filter = configuration.optimizations != null ?
+ new ListParser(new NameParser()).parse(configuration.optimizations) :
+ new ConstantMatcher(true);
+
+ boolean classMarkingFinal = filter.matches(CLASS_MARKING_FINAL);
+ boolean classMergingVertical = filter.matches(CLASS_MERGING_VERTICAL);
+ boolean classMergingHorizontal = filter.matches(CLASS_MERGING_HORIZONTAL);
+ boolean fieldRemovalWriteonly = filter.matches(FIELD_REMOVAL_WRITEONLY);
+ boolean fieldMarkingPrivate = filter.matches(FIELD_MARKING_PRIVATE);
+ boolean fieldPropagationValue = filter.matches(FIELD_PROPAGATION_VALUE);
+ boolean methodMarkingPrivate = filter.matches(METHOD_MARKING_PRIVATE);
+ boolean methodMarkingStatic = filter.matches(METHOD_MARKING_STATIC);
+ boolean methodMarkingFinal = filter.matches(METHOD_MARKING_FINAL);
+ boolean methodRemovalParameter = filter.matches(METHOD_REMOVAL_PARAMETER);
+ boolean methodPropagationParameter = filter.matches(METHOD_PROPAGATION_PARAMETER);
+ boolean methodPropagationReturnvalue = filter.matches(METHOD_PROPAGATION_RETURNVALUE);
+ boolean methodInliningShort = filter.matches(METHOD_INLINING_SHORT);
+ boolean methodInliningUnique = filter.matches(METHOD_INLINING_UNIQUE);
+ boolean methodInliningTailrecursion = filter.matches(METHOD_INLINING_TAILRECURSION);
+ boolean codeMerging = filter.matches(CODE_MERGING);
+ boolean codeSimplificationVariable = filter.matches(CODE_SIMPLIFICATION_VARIABLE);
+ boolean codeSimplificationArithmetic = filter.matches(CODE_SIMPLIFICATION_ARITHMETIC);
+ boolean codeSimplificationCast = filter.matches(CODE_SIMPLIFICATION_CAST);
+ boolean codeSimplificationField = filter.matches(CODE_SIMPLIFICATION_FIELD);
+ boolean codeSimplificationBranch = filter.matches(CODE_SIMPLIFICATION_BRANCH);
+ boolean codeSimplificationString = filter.matches(CODE_SIMPLIFICATION_STRING);
+ boolean codeSimplificationAdvanced = filter.matches(CODE_SIMPLIFICATION_ADVANCED);
+ boolean codeRemovalAdvanced = filter.matches(CODE_REMOVAL_ADVANCED);
+ boolean codeRemovalSimple = filter.matches(CODE_REMOVAL_SIMPLE);
+ boolean codeRemovalVariable = filter.matches(CODE_REMOVAL_VARIABLE);
+ boolean codeRemovalException = filter.matches(CODE_REMOVAL_EXCEPTION);
+ boolean codeAllocationVariable = filter.matches(CODE_ALLOCATION_VARIABLE);
+
+ // Create counters to count the numbers of optimizations.
+ ClassCounter classMarkingFinalCounter = new ClassCounter();
+ ClassCounter classMergingVerticalCounter = new ClassCounter();
+ ClassCounter classMergingHorizontalCounter = new ClassCounter();
+ MemberCounter fieldRemovalWriteonlyCounter = new MemberCounter();
+ MemberCounter fieldMarkingPrivateCounter = new MemberCounter();
+ MemberCounter fieldPropagationValueCounter = new MemberCounter();
+ MemberCounter methodMarkingPrivateCounter = new MemberCounter();
+ MemberCounter methodMarkingStaticCounter = new MemberCounter();
+ MemberCounter methodMarkingFinalCounter = new MemberCounter();
+ MemberCounter methodRemovalParameterCounter = new MemberCounter();
+ MemberCounter methodPropagationParameterCounter = new MemberCounter();
+ MemberCounter methodPropagationReturnvalueCounter = new MemberCounter();
+ InstructionCounter methodInliningShortCounter = new InstructionCounter();
+ InstructionCounter methodInliningUniqueCounter = new InstructionCounter();
+ InstructionCounter methodInliningTailrecursionCounter = new InstructionCounter();
+ InstructionCounter codeMergingCounter = new InstructionCounter();
+ InstructionCounter codeSimplificationVariableCounter = new InstructionCounter();
+ InstructionCounter codeSimplificationArithmeticCounter = new InstructionCounter();
+ InstructionCounter codeSimplificationCastCounter = new InstructionCounter();
+ InstructionCounter codeSimplificationFieldCounter = new InstructionCounter();
+ InstructionCounter codeSimplificationBranchCounter = new InstructionCounter();
+ InstructionCounter codeSimplificationStringCounter = new InstructionCounter();
+ InstructionCounter codeSimplificationAdvancedCounter = new InstructionCounter();
+ InstructionCounter deletedCounter = new InstructionCounter();
+ InstructionCounter addedCounter = new InstructionCounter();
+ MemberCounter codeRemovalVariableCounter = new MemberCounter();
+ ExceptionCounter codeRemovalExceptionCounter = new ExceptionCounter();
+ MemberCounter codeAllocationVariableCounter = new MemberCounter();
+ MemberCounter initializerFixCounter1 = new MemberCounter();
+ MemberCounter initializerFixCounter2 = new MemberCounter();
+
+ // Some optimizations are required by other optimizations.
+ codeSimplificationAdvanced =
+ codeSimplificationAdvanced ||
+ fieldPropagationValue ||
+ methodPropagationParameter ||
+ methodPropagationReturnvalue;
+
+ codeRemovalAdvanced =
+ codeRemovalAdvanced ||
+ fieldRemovalWriteonly ||
+ methodMarkingStatic ||
+ methodRemovalParameter;
+
+ codeRemovalSimple =
+ codeRemovalSimple ||
+ codeSimplificationBranch;
+
+ codeRemovalException =
+ codeRemovalException ||
+ codeRemovalAdvanced ||
+ codeRemovalSimple;
+
+ // Clean up any old visitor info.
+ programClassPool.classesAccept(new ClassCleaner());
+ libraryClassPool.classesAccept(new ClassCleaner());
+
+ // Link all methods that should get the same optimization info.
+ programClassPool.classesAccept(new BottomClassFilter(
+ new MethodLinker()));
+ libraryClassPool.classesAccept(new BottomClassFilter(
+ new MethodLinker()));
+
+ // Create a visitor for marking the seeds.
+ KeepMarker keepMarker = new KeepMarker();
+ ClassPoolVisitor classPoolvisitor =
+ ClassSpecificationVisitorFactory.createClassPoolVisitor(configuration.keep,
+ keepMarker,
+ keepMarker,
+ false,
+ true,
+ false);
+ // Mark the seeds.
+ programClassPool.accept(classPoolvisitor);
+ libraryClassPool.accept(classPoolvisitor);
+
+ // All library classes and library class members remain unchanged.
+ libraryClassPool.classesAccept(keepMarker);
+ libraryClassPool.classesAccept(new AllMemberVisitor(keepMarker));
+
+ // We also keep all classes that are involved in .class constructs.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new AllInstructionVisitor(
+ new DotClassClassVisitor(keepMarker)))));
+
+ // We also keep all classes that are accessed dynamically.
+ programClassPool.classesAccept(
+ new AllConstantVisitor(
+ new ConstantTagFilter(ClassConstants.CONSTANT_String,
+ new ReferencedClassVisitor(keepMarker))));
+
+ // We also keep all class members that are accessed dynamically.
+ programClassPool.classesAccept(
+ new AllConstantVisitor(
+ new ConstantTagFilter(ClassConstants.CONSTANT_String,
+ new ReferencedMemberVisitor(keepMarker))));
+
+ // We also keep all bootstrap method signatures.
+ programClassPool.classesAccept(
+ new ClassVersionFilter(ClassConstants.INTERNAL_CLASS_VERSION_1_7,
+ new AllAttributeVisitor(
+ new AttributeNameFilter(ClassConstants.ATTR_BootstrapMethods,
+ new AllBootstrapMethodInfoVisitor(
+ new BootstrapMethodHandleTraveler(
+ new MethodrefTraveler(
+ new ReferencedMemberVisitor(keepMarker))))))));
+
+ // Attach some optimization info to all classes and class members, so
+ // it can be filled out later.
+ programClassPool.classesAccept(new ClassOptimizationInfoSetter());
+
+ programClassPool.classesAccept(new AllMemberVisitor(
+ new MemberOptimizationInfoSetter()));
+
+ if (configuration.assumeNoSideEffects != null)
+ {
+ // Create a visitor for marking methods that don't have any side effects.
+ NoSideEffectMethodMarker noSideEffectMethodMarker = new NoSideEffectMethodMarker();
+ ClassPoolVisitor noClassPoolvisitor =
+ ClassSpecificationVisitorFactory.createClassPoolVisitor(configuration.assumeNoSideEffects,
+ null,
+ noSideEffectMethodMarker);
+
+ // Mark the seeds.
+ programClassPool.accept(noClassPoolvisitor);
+ libraryClassPool.accept(noClassPoolvisitor);
+ }
+
+ if (classMarkingFinal)
+ {
+ // Make classes final, whereever possible.
+ programClassPool.classesAccept(
+ new ClassFinalizer(classMarkingFinalCounter));
+ }
+
+ if (methodMarkingFinal)
+ {
+ // Make methods final, whereever possible.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new MethodFinalizer(methodMarkingFinalCounter)));
+ }
+
+ if (fieldRemovalWriteonly)
+ {
+ // Mark all fields that are write-only.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new AllInstructionVisitor(
+ new ReadWriteFieldMarker()))));
+
+ // Count the write-only fields.
+ programClassPool.classesAccept(
+ new AllFieldVisitor(
+ new WriteOnlyFieldFilter(fieldRemovalWriteonlyCounter)));
+ }
+ else
+ {
+ // Mark all fields as read/write.
+ programClassPool.classesAccept(
+ new AllFieldVisitor(
+ new ReadWriteFieldMarker()));
+ }
+
+ // Mark all used parameters, including the 'this' parameters.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new OptimizationInfoMemberFilter(
+ new ParameterUsageMarker(!methodMarkingStatic,
+ !methodRemovalParameter))));
+
+ // Mark all classes that have static initializers.
+ programClassPool.classesAccept(new StaticInitializerContainingClassMarker());
+
+ // Mark all methods that have side effects.
+ programClassPool.accept(new SideEffectMethodMarker());
+
+// System.out.println("Optimizer.execute: before evaluation simplification");
+// programClassPool.classAccept("abc/Def", new NamedMethodVisitor("abc", null, new ClassPrinter()));
+
+ // Perform partial evaluation for filling out fields, method parameters,
+ // and method return values.
+ ValueFactory valueFactory = new IdentifiedValueFactory();
+
+ if (fieldPropagationValue ||
+ methodPropagationParameter ||
+ methodPropagationReturnvalue)
+ {
+ // Fill out fields, method parameters, and return values, so they
+ // can be propagated.
+ InvocationUnit storingInvocationUnit =
+ new StoringInvocationUnit(valueFactory,
+ fieldPropagationValue,
+ methodPropagationParameter,
+ methodPropagationReturnvalue);
+
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new PartialEvaluator(valueFactory, storingInvocationUnit, false))));
+
+ if (fieldPropagationValue)
+ {
+ // Count the constant fields.
+ programClassPool.classesAccept(
+ new AllFieldVisitor(
+ new ConstantMemberFilter(fieldPropagationValueCounter)));
+ }
+
+ if (methodPropagationParameter)
+ {
+ // Count the constant method parameters.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new ConstantParameterFilter(methodPropagationParameterCounter)));
+ }
+
+ if (methodPropagationReturnvalue)
+ {
+ // Count the constant method return values.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new ConstantMemberFilter(methodPropagationReturnvalueCounter)));
+ }
+ }
+
+ InvocationUnit loadingInvocationUnit =
+ new LoadingInvocationUnit(valueFactory,
+ fieldPropagationValue,
+ methodPropagationParameter,
+ methodPropagationReturnvalue);
+
+ if (codeSimplificationAdvanced)
+ {
+ // Simplify based on partial evaluation, propagating constant
+ // field values, method parameter values, and return values.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new EvaluationSimplifier(
+ new PartialEvaluator(valueFactory, loadingInvocationUnit, false),
+ codeSimplificationAdvancedCounter))));
+ }
+
+ if (codeRemovalAdvanced)
+ {
+ // Remove code based on partial evaluation, also removing unused
+ // parameters from method invocations, and making methods static
+ // if possible.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new EvaluationShrinker(
+ new PartialEvaluator(valueFactory, loadingInvocationUnit, !codeSimplificationAdvanced),
+ deletedCounter, addedCounter))));
+ }
+
+ if (methodRemovalParameter)
+ {
+ // Shrink the parameters in the method descriptors.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new OptimizationInfoMemberFilter(
+ new MethodDescriptorShrinker())));
+ }
+
+ if (methodMarkingStatic)
+ {
+ // Make all non-static methods that don't require the 'this'
+ // parameter static.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new OptimizationInfoMemberFilter(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_STATIC,
+ new MethodStaticizer(methodMarkingStaticCounter)))));
+ }
+
+ if (methodRemovalParameter)
+ {
+ // Fix all references to class members.
+ // This operation also updates the stack sizes.
+ programClassPool.classesAccept(
+ new MemberReferenceFixer());
+
+ // Remove unused bootstrap method arguments.
+ programClassPool.classesAccept(
+ new AllAttributeVisitor(
+ new AllBootstrapMethodInfoVisitor(
+ new BootstrapMethodArgumentShrinker())));
+ }
+
+ if (methodRemovalParameter ||
+ methodMarkingPrivate ||
+ methodMarkingStatic)
+ {
+ // Remove all unused parameters from the byte code, shifting all
+ // remaining variables.
+ // This operation also updates the local variable frame sizes.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new ParameterShrinker(methodRemovalParameterCounter))));
+ }
+ else if (codeRemovalAdvanced)
+ {
+ // Just update the local variable frame sizes.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new StackSizeUpdater())));
+ }
+
+ if (methodRemovalParameter &&
+ methodRemovalParameterCounter.getCount() > 0)
+ {
+ // Tweak the descriptors of duplicate initializers, due to removed
+ // method parameters.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new DuplicateInitializerFixer(initializerFixCounter1)));
+
+ if (initializerFixCounter1.getCount() > 0)
+ {
+ // Fix all invocations of tweaked initializers.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new DuplicateInitializerInvocationFixer(addedCounter))));
+
+ // Fix all references to tweaked initializers.
+ programClassPool.classesAccept(new MemberReferenceFixer());
+ }
+ }
+
+ //// Specializing the class member descriptors seems to increase the
+ //// class file size, on average.
+ //// Specialize all class member descriptors.
+ //programClassPool.classesAccept(new AllMemberVisitor(
+ // new OptimizationInfoMemberFilter(
+ // new MemberDescriptorSpecializer())));
+ //
+ //// Fix all references to classes, for MemberDescriptorSpecializer.
+ //programClassPool.classesAccept(new AllMemberVisitor(
+ // new OptimizationInfoMemberFilter(
+ // new ClassReferenceFixer(true))));
+
+ // Mark all classes with package visible members.
+ // Mark all exception catches of methods.
+ // Count all method invocations.
+ // Mark super invocations and other access of methods.
+ programClassPool.classesAccept(
+ new MultiClassVisitor(
+ new ClassVisitor[]
+ {
+ new PackageVisibleMemberContainingClassMarker(),
+ new AllConstantVisitor(
+ new PackageVisibleMemberInvokingClassMarker()),
+ new AllMethodVisitor(
+ new MultiMemberVisitor(
+ new MemberVisitor[]
+ {
+ new AllAttributeVisitor(
+ new MultiAttributeVisitor(
+ new AttributeVisitor[]
+ {
+ new CatchExceptionMarker(),
+ new AllInstructionVisitor(
+ new MultiInstructionVisitor(
+ new InstructionVisitor[]
+ {
+ new InstantiationClassMarker(),
+ new InstanceofClassMarker(),
+ new DotClassMarker(),
+ new MethodInvocationMarker(),
+ new SuperInvocationMarker(),
+ new BackwardBranchMarker(),
+ new AccessMethodMarker(),
+ })),
+ new AllExceptionInfoVisitor(
+ new ExceptionHandlerConstantVisitor(
+ new ReferencedClassVisitor(
+ new CaughtClassMarker()))),
+ })),
+ })),
+ }));
+
+ if (classMergingVertical)
+ {
+ // Merge classes into their superclasses or interfaces.
+ programClassPool.classesAccept(
+ new VerticalClassMerger(configuration.allowAccessModification,
+ configuration.mergeInterfacesAggressively,
+ classMergingVerticalCounter));
+ }
+
+ if (classMergingHorizontal)
+ {
+ // Merge classes into their sibling classes.
+ programClassPool.classesAccept(
+ new HorizontalClassMerger(configuration.allowAccessModification,
+ configuration.mergeInterfacesAggressively,
+ classMergingHorizontalCounter));
+ }
+
+ if (classMergingVerticalCounter .getCount() > 0 ||
+ classMergingHorizontalCounter.getCount() > 0)
+ {
+ // Clean up inner class attributes to avoid loops.
+ programClassPool.classesAccept(new RetargetedInnerClassAttributeRemover());
+
+ // Update references to merged classes.
+ programClassPool.classesAccept(new TargetClassChanger());
+ programClassPool.classesAccept(new ClassReferenceFixer(true));
+ programClassPool.classesAccept(new MemberReferenceFixer());
+
+ if (configuration.allowAccessModification)
+ {
+ // Fix the access flags of referenced merged classes and their
+ // class members.
+ programClassPool.classesAccept(
+ new AllConstantVisitor(
+ new AccessFixer()));
+ }
+
+ // Fix the access flags of the inner classes information.
+ programClassPool.classesAccept(
+ new AllAttributeVisitor(
+ new AllInnerClassesInfoVisitor(
+ new InnerClassesAccessFixer())));
+
+ // Tweak the descriptors of duplicate initializers, due to merged
+ // parameter classes.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new DuplicateInitializerFixer(initializerFixCounter2)));
+
+ if (initializerFixCounter2.getCount() > 0)
+ {
+ // Fix all invocations of tweaked initializers.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new DuplicateInitializerInvocationFixer(addedCounter))));
+
+ // Fix all references to tweaked initializers.
+ programClassPool.classesAccept(new MemberReferenceFixer());
+ }
+ }
+
+ if (methodInliningUnique)
+ {
+ // Inline methods that are only invoked once.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new MethodInliner(configuration.microEdition,
+ configuration.allowAccessModification,
+ true,
+ methodInliningUniqueCounter))));
+ }
+
+ if (methodInliningShort)
+ {
+ // Inline short methods.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new MethodInliner(configuration.microEdition,
+ configuration.allowAccessModification,
+ false,
+ methodInliningShortCounter))));
+ }
+
+ if (methodInliningTailrecursion)
+ {
+ // Simplify tail recursion calls.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new TailRecursionSimplifier(methodInliningTailrecursionCounter))));
+ }
+
+ if (fieldMarkingPrivate ||
+ methodMarkingPrivate)
+ {
+ // Mark all class members that can not be made private.
+ programClassPool.classesAccept(
+ new NonPrivateMemberMarker());
+ }
+
+ if (fieldMarkingPrivate)
+ {
+ // Make all non-private fields private, whereever possible.
+ programClassPool.classesAccept(
+ new ClassAccessFilter(0, ClassConstants.INTERNAL_ACC_INTERFACE,
+ new AllFieldVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberPrivatizer(fieldMarkingPrivateCounter)))));
+ }
+
+ if (methodMarkingPrivate)
+ {
+ // Make all non-private methods private, whereever possible.
+ programClassPool.classesAccept(
+ new ClassAccessFilter(0, ClassConstants.INTERNAL_ACC_INTERFACE,
+ new AllMethodVisitor(
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ new MemberPrivatizer(methodMarkingPrivateCounter)))));
+ }
+
+ if ((methodInliningUniqueCounter .getCount() > 0 ||
+ methodInliningShortCounter .getCount() > 0 ||
+ methodInliningTailrecursionCounter.getCount() > 0) &&
+ configuration.allowAccessModification)
+ {
+ // Fix the access flags of referenced classes and class members,
+ // for MethodInliner.
+ programClassPool.classesAccept(
+ new AllConstantVisitor(
+ new AccessFixer()));
+ }
+
+ if (methodRemovalParameterCounter .getCount() > 0 ||
+ classMergingVerticalCounter .getCount() > 0 ||
+ classMergingHorizontalCounter .getCount() > 0 ||
+ methodMarkingPrivateCounter .getCount() > 0 )
+ {
+ // Fix invocations of interface methods, of methods that have become
+ // non-abstract or private, and of methods that have moved to a
+ // different package.
+ programClassPool.classesAccept(
+ new AllMemberVisitor(
+ new AllAttributeVisitor(
+ new MethodInvocationFixer())));
+ }
+
+ if (codeMerging)
+ {
+ // Share common blocks of code at branches.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new GotoCommonCodeReplacer(codeMergingCounter))));
+ }
+
+ // Create a branch target marker and a code attribute editor that can
+ // be reused for all code attributes.
+ BranchTargetFinder branchTargetFinder = new BranchTargetFinder();
+ CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor();
+
+ List peepholeOptimizations = new ArrayList();
+ if (codeSimplificationVariable)
+ {
+ // Peephole optimizations involving local variables.
+ peepholeOptimizations.add(
+ new InstructionSequencesReplacer(InstructionSequenceConstants.CONSTANTS,
+ InstructionSequenceConstants.VARIABLE,
+ branchTargetFinder, codeAttributeEditor, codeSimplificationVariableCounter));
+ }
+
+ if (codeSimplificationArithmetic)
+ {
+ // Peephole optimizations involving arithmetic operations.
+ peepholeOptimizations.add(
+ new InstructionSequencesReplacer(InstructionSequenceConstants.CONSTANTS,
+ InstructionSequenceConstants.ARITHMETIC,
+ branchTargetFinder, codeAttributeEditor, codeSimplificationArithmeticCounter));
+ }
+
+ if (codeSimplificationCast)
+ {
+ // Peephole optimizations involving cast operations.
+ peepholeOptimizations.add(
+ new InstructionSequencesReplacer(InstructionSequenceConstants.CONSTANTS,
+ InstructionSequenceConstants.CAST,
+ branchTargetFinder, codeAttributeEditor, codeSimplificationCastCounter));
+ }
+
+ if (codeSimplificationField)
+ {
+ // Peephole optimizations involving fields.
+ peepholeOptimizations.add(
+ new InstructionSequencesReplacer(InstructionSequenceConstants.CONSTANTS,
+ InstructionSequenceConstants.FIELD,
+ branchTargetFinder, codeAttributeEditor, codeSimplificationFieldCounter));
+ }
+
+ if (codeSimplificationBranch)
+ {
+ // Peephole optimizations involving branches.
+ peepholeOptimizations.add(
+ new InstructionSequencesReplacer(InstructionSequenceConstants.CONSTANTS,
+ InstructionSequenceConstants.BRANCH,
+ branchTargetFinder, codeAttributeEditor, codeSimplificationBranchCounter));
+
+ // Include optimization of branches to branches and returns.
+ peepholeOptimizations.add(
+ new GotoGotoReplacer(codeAttributeEditor, codeSimplificationBranchCounter));
+ peepholeOptimizations.add(
+ new GotoReturnReplacer(codeAttributeEditor, codeSimplificationBranchCounter));
+ }
+
+ if (codeSimplificationString)
+ {
+ // Peephole optimizations involving branches.
+ peepholeOptimizations.add(
+ new InstructionSequencesReplacer(InstructionSequenceConstants.CONSTANTS,
+ InstructionSequenceConstants.STRING,
+ branchTargetFinder, codeAttributeEditor, codeSimplificationStringCounter));
+ }
+
+ if (!peepholeOptimizations.isEmpty())
+ {
+ // Convert the list into an array.
+ InstructionVisitor[] peepholeOptimizationsArray =
+ new InstructionVisitor[peepholeOptimizations.size()];
+ peepholeOptimizations.toArray(peepholeOptimizationsArray);
+
+ // Perform the peephole optimisations.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new PeepholeOptimizer(branchTargetFinder, codeAttributeEditor,
+ new MultiInstructionVisitor(
+ peepholeOptimizationsArray)))));
+ }
+
+ if (codeRemovalException)
+ {
+ // Remove unnecessary exception handlers.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new UnreachableExceptionRemover(codeRemovalExceptionCounter))));
+ }
+
+ if (codeRemovalSimple)
+ {
+ // Remove unreachable code.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new UnreachableCodeRemover(deletedCounter))));
+ }
+
+ if (codeRemovalVariable)
+ {
+ // Remove all unused local variables.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new VariableShrinker(codeRemovalVariableCounter))));
+ }
+
+ if (codeAllocationVariable)
+ {
+ // Optimize the variables.
+ programClassPool.classesAccept(
+ new AllMethodVisitor(
+ new AllAttributeVisitor(
+ new VariableOptimizer(false, codeAllocationVariableCounter))));
+ }
+
+
+ // Remove unused constants.
+ programClassPool.classesAccept(
+ new ConstantPoolShrinker());
+
+ int classMarkingFinalCount = classMarkingFinalCounter .getCount();
+ int classMergingVerticalCount = classMergingVerticalCounter .getCount();
+ int classMergingHorizontalCount = classMergingHorizontalCounter .getCount();
+ int fieldRemovalWriteonlyCount = fieldRemovalWriteonlyCounter .getCount();
+ int fieldMarkingPrivateCount = fieldMarkingPrivateCounter .getCount();
+ int fieldPropagationValueCount = fieldPropagationValueCounter .getCount();
+ int methodMarkingPrivateCount = methodMarkingPrivateCounter .getCount();
+ int methodMarkingStaticCount = methodMarkingStaticCounter .getCount();
+ int methodMarkingFinalCount = methodMarkingFinalCounter .getCount();
+ int methodRemovalParameterCount = methodRemovalParameterCounter .getCount() - methodMarkingStaticCounter.getCount() - initializerFixCounter1.getCount() - initializerFixCounter2.getCount();
+ int methodPropagationParameterCount = methodPropagationParameterCounter .getCount();
+ int methodPropagationReturnvalueCount = methodPropagationReturnvalueCounter.getCount();
+ int methodInliningShortCount = methodInliningShortCounter .getCount();
+ int methodInliningUniqueCount = methodInliningUniqueCounter .getCount();
+ int methodInliningTailrecursionCount = methodInliningTailrecursionCounter .getCount();
+ int codeMergingCount = codeMergingCounter .getCount();
+ int codeSimplificationVariableCount = codeSimplificationVariableCounter .getCount();
+ int codeSimplificationArithmeticCount = codeSimplificationArithmeticCounter.getCount();
+ int codeSimplificationCastCount = codeSimplificationCastCounter .getCount();
+ int codeSimplificationFieldCount = codeSimplificationFieldCounter .getCount();
+ int codeSimplificationBranchCount = codeSimplificationBranchCounter .getCount();
+ int codeSimplificationStringCount = codeSimplificationStringCounter .getCount();
+ int codeSimplificationAdvancedCount = codeSimplificationAdvancedCounter .getCount();
+ int codeRemovalCount = deletedCounter .getCount() - addedCounter.getCount();
+ int codeRemovalVariableCount = codeRemovalVariableCounter .getCount();
+ int codeRemovalExceptionCount = codeRemovalExceptionCounter .getCount();
+ int codeAllocationVariableCount = codeAllocationVariableCounter .getCount();
+
+ // Forget about constant fields, parameters, and return values, if they
+ // didn't lead to any useful optimizations. We want to avoid fruitless
+ // additional optimization passes.
+ if (codeSimplificationAdvancedCount == 0)
+ {
+ fieldPropagationValueCount = 0;
+ methodPropagationParameterCount = 0;
+ methodPropagationReturnvalueCount = 0;
+ }
+
+ if (configuration.verbose)
+ {
+ System.out.println(" Number of finalized classes: " + classMarkingFinalCount + disabled(classMarkingFinal));
+ System.out.println(" Number of vertically merged classes: " + classMergingVerticalCount + disabled(classMergingVertical));
+ System.out.println(" Number of horizontally merged classes: " + classMergingHorizontalCount + disabled(classMergingHorizontal));
+ System.out.println(" Number of removed write-only fields: " + fieldRemovalWriteonlyCount + disabled(fieldRemovalWriteonly));
+ System.out.println(" Number of privatized fields: " + fieldMarkingPrivateCount + disabled(fieldMarkingPrivate));
+ System.out.println(" Number of inlined constant fields: " + fieldPropagationValueCount + disabled(fieldPropagationValue));
+ System.out.println(" Number of privatized methods: " + methodMarkingPrivateCount + disabled(methodMarkingPrivate));
+ System.out.println(" Number of staticized methods: " + methodMarkingStaticCount + disabled(methodMarkingStatic));
+ System.out.println(" Number of finalized methods: " + methodMarkingFinalCount + disabled(methodMarkingFinal));
+ System.out.println(" Number of removed method parameters: " + methodRemovalParameterCount + disabled(methodRemovalParameter));
+ System.out.println(" Number of inlined constant parameters: " + methodPropagationParameterCount + disabled(methodPropagationParameter));
+ System.out.println(" Number of inlined constant return values: " + methodPropagationReturnvalueCount + disabled(methodPropagationReturnvalue));
+ System.out.println(" Number of inlined short method calls: " + methodInliningShortCount + disabled(methodInliningShort));
+ System.out.println(" Number of inlined unique method calls: " + methodInliningUniqueCount + disabled(methodInliningUnique));
+ System.out.println(" Number of inlined tail recursion calls: " + methodInliningTailrecursionCount + disabled(methodInliningTailrecursion));
+ System.out.println(" Number of merged code blocks: " + codeMergingCount + disabled(codeMerging));
+ System.out.println(" Number of variable peephole optimizations: " + codeSimplificationVariableCount + disabled(codeSimplificationVariable));
+ System.out.println(" Number of arithmetic peephole optimizations: " + codeSimplificationArithmeticCount + disabled(codeSimplificationArithmetic));
+ System.out.println(" Number of cast peephole optimizations: " + codeSimplificationCastCount + disabled(codeSimplificationCast));
+ System.out.println(" Number of field peephole optimizations: " + codeSimplificationFieldCount + disabled(codeSimplificationField));
+ System.out.println(" Number of branch peephole optimizations: " + codeSimplificationBranchCount + disabled(codeSimplificationBranch));
+ System.out.println(" Number of string peephole optimizations: " + codeSimplificationStringCount + disabled(codeSimplificationString));
+ System.out.println(" Number of simplified instructions: " + codeSimplificationAdvancedCount + disabled(codeSimplificationAdvanced));
+ System.out.println(" Number of removed instructions: " + codeRemovalCount + disabled(codeRemovalAdvanced));
+ System.out.println(" Number of removed local variables: " + codeRemovalVariableCount + disabled(codeRemovalVariable));
+ System.out.println(" Number of removed exception blocks: " + codeRemovalExceptionCount + disabled(codeRemovalException));
+ System.out.println(" Number of optimized local variable frames: " + codeAllocationVariableCount + disabled(codeAllocationVariable));
+ }
+
+ return classMarkingFinalCount > 0 ||
+ classMergingVerticalCount > 0 ||
+ classMergingHorizontalCount > 0 ||
+ fieldRemovalWriteonlyCount > 0 ||
+ fieldMarkingPrivateCount > 0 ||
+ methodMarkingPrivateCount > 0 ||
+ methodMarkingStaticCount > 0 ||
+ methodMarkingFinalCount > 0 ||
+ fieldPropagationValueCount > 0 ||
+ methodRemovalParameterCount > 0 ||
+ methodPropagationParameterCount > 0 ||
+ methodPropagationReturnvalueCount > 0 ||
+ methodInliningShortCount > 0 ||
+ methodInliningUniqueCount > 0 ||
+ methodInliningTailrecursionCount > 0 ||
+ codeMergingCount > 0 ||
+ codeSimplificationVariableCount > 0 ||
+ codeSimplificationArithmeticCount > 0 ||
+ codeSimplificationCastCount > 0 ||
+ codeSimplificationFieldCount > 0 ||
+ codeSimplificationBranchCount > 0 ||
+ codeSimplificationStringCount > 0 ||
+ codeSimplificationAdvancedCount > 0 ||
+ codeRemovalCount > 0 ||
+ codeRemovalVariableCount > 0 ||
+ codeRemovalExceptionCount > 0 ||
+ codeAllocationVariableCount > 0;
+ }
+
+
+ /**
+ * Returns a String indicating whether the given flag is enabled or
+ * disabled.
+ */
+ private String disabled(boolean flag)
+ {
+ return flag ? "" : " (disabled)";
+ }
+
+
+ /**
+ * Returns a String indicating whether the given flags are enabled or
+ * disabled.
+ */
+ private String disabled(boolean flag1, boolean flag2)
+ {
+ return flag1 && flag2 ? "" :
+ flag1 || flag2 ? " (partially disabled)" :
+ " (disabled)";
+ }
+}
diff --git a/src/proguard/optimize/ParameterShrinker.java b/src/proguard/optimize/ParameterShrinker.java
new file mode 100644
index 000000000..33d37d141
--- /dev/null
+++ b/src/proguard/optimize/ParameterShrinker.java
@@ -0,0 +1,146 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.editor.VariableRemapper;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.info.ParameterUsageMarker;
+
+/**
+ * This MemberVisitor removes unused parameters from the code of the methods
+ * that it visits.
+ *
+ * @see ParameterUsageMarker
+ * @see MethodStaticizer
+ * @see MethodDescriptorShrinker
+ * @author Eric Lafortune
+ */
+public class ParameterShrinker
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private static final boolean DEBUG = false;
+
+
+ private final MemberVisitor extraVariableMemberVisitor;
+
+ private final VariableRemapper variableRemapper = new VariableRemapper();
+
+
+ /**
+ * Creates a new ParameterShrinker.
+ */
+ public ParameterShrinker()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new ParameterShrinker with an extra visitor.
+ * @param extraVariableMemberVisitor an optional extra visitor for all
+ * removed parameters.
+ */
+ public ParameterShrinker(MemberVisitor extraVariableMemberVisitor)
+ {
+ this.extraVariableMemberVisitor = extraVariableMemberVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Get the original parameter size that was saved.
+ int oldParameterSize = ParameterUsageMarker.getParameterSize(method);
+
+ // Compute the new parameter size from the shrunk descriptor.
+ int newParameterSize =
+ ClassUtil.internalMethodParameterSize(method.getDescriptor(clazz),
+ method.getAccessFlags());
+
+ if (oldParameterSize > newParameterSize)
+ {
+ // Get the total size of the local variable frame.
+ int maxLocals = codeAttribute.u2maxLocals;
+
+ if (DEBUG)
+ {
+ System.out.println("ParameterShrinker: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ System.out.println(" Old parameter size = " + oldParameterSize);
+ System.out.println(" New parameter size = " + newParameterSize);
+ System.out.println(" Max locals = " + maxLocals);
+ }
+
+ // Create a variable map.
+ int[] variableMap = new int[maxLocals];
+
+ // Move unused parameters right after the parameter block.
+ int usedParameterIndex = 0;
+ int unusedParameterIndex = newParameterSize;
+ for (int parameterIndex = 0; parameterIndex < oldParameterSize; parameterIndex++)
+ {
+ // Is the variable required as a parameter?
+ if (ParameterUsageMarker.isParameterUsed(method, parameterIndex))
+ {
+ // Keep the variable as a parameter.
+ variableMap[parameterIndex] = usedParameterIndex++;
+ }
+ else
+ {
+ if (DEBUG)
+ {
+ System.out.println(" Deleting parameter #"+parameterIndex);
+ }
+
+ // Shift the variable to the unused parameter block,
+ // in case it is still used as a variable.
+ variableMap[parameterIndex] = unusedParameterIndex++;
+
+ // Visit the method, if required.
+ if (extraVariableMemberVisitor != null)
+ {
+ method.accept(clazz, extraVariableMemberVisitor);
+ }
+ }
+ }
+
+ // Fill out the remainder of the map.
+ for (int variableIndex = oldParameterSize; variableIndex < maxLocals; variableIndex++)
+ {
+ variableMap[variableIndex] = variableIndex;
+ }
+
+ // Set the map.
+ variableRemapper.setVariableMap(variableMap);
+
+ // Remap the variables.
+ variableRemapper.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+ }
+}
diff --git a/src/proguard/optimize/TailRecursionSimplifier.java b/src/proguard/optimize/TailRecursionSimplifier.java
new file mode 100644
index 000000000..f820566a9
--- /dev/null
+++ b/src/proguard/optimize/TailRecursionSimplifier.java
@@ -0,0 +1,356 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.MethodrefConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.CodeAttributeComposer;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+
+/**
+ * This MemberVisitor simplifies tail recursion calls in all methods that it
+ * visits.
+ *
+ * @author Eric Lafortune
+ */
+public class TailRecursionSimplifier
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ConstantVisitor,
+ ExceptionInfoVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+
+ private final InstructionVisitor extraTailRecursionVisitor;
+
+
+ private final CodeAttributeComposer codeAttributeComposer = new CodeAttributeComposer();
+ private final MyRecursionChecker recursionChecker = new MyRecursionChecker();
+
+ private Method targetMethod;
+ private boolean inlinedAny;
+
+
+
+ /**
+ * Creates a new TailRecursionSimplifier.
+ */
+ public TailRecursionSimplifier()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new TailRecursionSimplifier with an extra visitor.
+ * @param extraTailRecursionVisitor an optional extra visitor for all
+ * simplified tail recursions.
+ */
+ public TailRecursionSimplifier(InstructionVisitor extraTailRecursionVisitor)
+ {
+ this.extraTailRecursionVisitor = extraTailRecursionVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ int accessFlags = method.getAccessFlags();
+
+ if (// Only check the method if it is private, static, or final.
+ (accessFlags & (ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC |
+ ClassConstants.INTERNAL_ACC_FINAL)) != 0 &&
+
+ // Only check the method if it is not synchronized, etc.
+ (accessFlags & (ClassConstants.INTERNAL_ACC_SYNCHRONIZED |
+ ClassConstants.INTERNAL_ACC_NATIVE |
+ ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) == 0)
+ {
+// codeAttributeComposer.DEBUG = DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ targetMethod = method;
+ inlinedAny = false;
+ codeAttributeComposer.reset();
+
+ // The code may expand, due to expanding constant and variable
+ // instructions.
+ codeAttributeComposer.beginCodeFragment(codeAttribute.u4codeLength);
+
+ // Copy the instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ // Update the code attribute if any code has been inlined.
+ if (inlinedAny)
+ {
+ // Copy the exceptions.
+ codeAttribute.exceptionsAccept(clazz, method, this);
+
+ // Append a label just after the code.
+ codeAttributeComposer.appendLabel(codeAttribute.u4codeLength);
+
+ codeAttributeComposer.endCodeFragment();
+
+ codeAttributeComposer.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ // Copy the instruction.
+ codeAttributeComposer.appendInstruction(offset, instruction);
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Is it a method invocation?
+ switch (constantInstruction.opcode)
+ {
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ {
+ // Is it a recursive call?
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, recursionChecker);
+
+ if (recursionChecker.isRecursive())
+ {
+ // Is the next instruction a return?
+ int nextOffset =
+ offset + constantInstruction.length(offset);
+
+ Instruction nextInstruction =
+ InstructionFactory.create(codeAttribute.code, nextOffset);
+
+ switch (nextInstruction.opcode)
+ {
+ case InstructionConstants.OP_IRETURN:
+ case InstructionConstants.OP_LRETURN:
+ case InstructionConstants.OP_FRETURN:
+ case InstructionConstants.OP_DRETURN:
+ case InstructionConstants.OP_ARETURN:
+ case InstructionConstants.OP_RETURN:
+ {
+ // Isn't the recursive call inside a try/catch block?
+ codeAttribute.exceptionsAccept(clazz, method, offset, recursionChecker);
+
+ if (recursionChecker.isRecursive())
+ {
+ if (DEBUG)
+ {
+ System.out.println("TailRecursionSimplifier: ["+
+ clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"], inlining "+constantInstruction.toString(offset));
+ }
+
+ // Append a label.
+ codeAttributeComposer.appendLabel(offset);
+
+ storeParameters(clazz, method);
+
+ // Branch back to the start of the method.
+ int gotoOffset = offset + 1;
+ codeAttributeComposer.appendInstruction(gotoOffset,
+ new BranchInstruction(InstructionConstants.OP_GOTO, -gotoOffset));
+
+ // The original return instruction will be
+ // removed elsewhere, if possible.
+
+ // Remember that the code has changed.
+ inlinedAny = true;
+
+ if (extraTailRecursionVisitor != null)
+ {
+ extraTailRecursionVisitor.visitConstantInstruction(clazz, method, codeAttribute, offset, constantInstruction);
+ }
+
+ // The invocation itself is no longer necessary.
+ return;
+ }
+ }
+ }
+ }
+
+ break;
+ }
+ }
+
+ // Copy the instruction.
+ codeAttributeComposer.appendInstruction(offset, constantInstruction);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ codeAttributeComposer.appendException(new ExceptionInfo(exceptionInfo.u2startPC,
+ exceptionInfo.u2endPC,
+ exceptionInfo.u2handlerPC,
+ exceptionInfo.u2catchType));
+ }
+
+
+ /**
+ * This ConstantVisitor and ExceptionInfoVisitor returns whether a method
+ * invocation can be treated as tail-recursive.
+ */
+ private class MyRecursionChecker
+ extends SimplifiedVisitor
+ implements ConstantVisitor,
+ ExceptionInfoVisitor
+ {
+ private boolean recursive;
+
+
+ /**
+ * Returns whether the method invocation can be treated as
+ * tail-recursive.
+ */
+ public boolean isRecursive()
+ {
+ return recursive;
+ }
+
+ // Implementations for ConstantVisitor.
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ recursive = targetMethod.equals(methodrefConstant.referencedMember);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ recursive = false;
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Appends instructions to pop the parameters for the given method, storing
+ * them in new local variables.
+ */
+ private void storeParameters(Clazz clazz, Method method)
+ {
+ String descriptor = method.getDescriptor(clazz);
+
+ boolean isStatic =
+ (method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0;
+
+ // Count the number of parameters, taking into account their categories.
+ int parameterSize = ClassUtil.internalMethodParameterSize(descriptor);
+ int parameterOffset = isStatic ? 0 : 1;
+
+ // Store the parameter types.
+ String[] parameterTypes = new String[parameterSize];
+
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(descriptor);
+
+ for (int parameterIndex = 0; parameterIndex < parameterSize; parameterIndex++)
+ {
+ String parameterType = internalTypeEnumeration.nextType();
+ parameterTypes[parameterIndex] = parameterType;
+ if (ClassUtil.internalTypeSize(parameterType) == 2)
+ {
+ parameterIndex++;
+ }
+ }
+
+ codeAttributeComposer.beginCodeFragment(parameterSize + 1);
+
+ // Go over the parameter types backward, storing the stack entries
+ // in their corresponding variables.
+ for (int parameterIndex = parameterSize-1; parameterIndex >= 0; parameterIndex--)
+ {
+ String parameterType = parameterTypes[parameterIndex];
+ if (parameterType != null)
+ {
+ byte opcode;
+ switch (parameterType.charAt(0))
+ {
+ case ClassConstants.INTERNAL_TYPE_BOOLEAN:
+ case ClassConstants.INTERNAL_TYPE_BYTE:
+ case ClassConstants.INTERNAL_TYPE_CHAR:
+ case ClassConstants.INTERNAL_TYPE_SHORT:
+ case ClassConstants.INTERNAL_TYPE_INT:
+ opcode = InstructionConstants.OP_ISTORE;
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_LONG:
+ opcode = InstructionConstants.OP_LSTORE;
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_FLOAT:
+ opcode = InstructionConstants.OP_FSTORE;
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_DOUBLE:
+ opcode = InstructionConstants.OP_DSTORE;
+ break;
+
+ default:
+ opcode = InstructionConstants.OP_ASTORE;
+ break;
+ }
+
+ codeAttributeComposer.appendInstruction(parameterSize-parameterIndex-1,
+ new VariableInstruction(opcode, parameterOffset + parameterIndex));
+ }
+ }
+
+ // Put the 'this' reference in variable 0.
+ if (!isStatic)
+ {
+ codeAttributeComposer.appendInstruction(parameterSize,
+ new VariableInstruction(InstructionConstants.OP_ASTORE, 0));
+ }
+
+ codeAttributeComposer.endCodeFragment();
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/WriteOnlyFieldFilter.java b/src/proguard/optimize/WriteOnlyFieldFilter.java
new file mode 100644
index 000000000..762bd91d2
--- /dev/null
+++ b/src/proguard/optimize/WriteOnlyFieldFilter.java
@@ -0,0 +1,65 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.info.ReadWriteFieldMarker;
+
+/**
+ * This MemberVisitor
delegates its visits to program fields to
+ * other given MemberVisitor
instances, but only when the visited
+ * field has been marked as write-only.
+ *
+ * @see ReadWriteFieldMarker
+ * @author Eric Lafortune
+ */
+public class WriteOnlyFieldFilter
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final MemberVisitor writeOnlyFieldVisitor;
+
+
+ /**
+ * Creates a new WriteOnlyFieldFilter.
+ * @param writeOnlyFieldVisitor the MemberVisitor
to which
+ * visits to write-only fields will be delegated.
+ */
+ public WriteOnlyFieldFilter(MemberVisitor writeOnlyFieldVisitor)
+ {
+ this.writeOnlyFieldVisitor = writeOnlyFieldVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+
+ if (ReadWriteFieldMarker.isWritten(programField) &&
+ !ReadWriteFieldMarker.isRead(programField))
+ {
+ writeOnlyFieldVisitor.visitProgramField(programClass, programField);
+ }
+ }
+}
diff --git a/src/proguard/optimize/evaluation/EvaluationShrinker.java b/src/proguard/optimize/evaluation/EvaluationShrinker.java
new file mode 100644
index 000000000..2e86532a8
--- /dev/null
+++ b/src/proguard/optimize/evaluation/EvaluationShrinker.java
@@ -0,0 +1,2222 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.constant.RefConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.CodeAttributeEditor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.evaluation.*;
+import proguard.evaluation.value.*;
+import proguard.optimize.info.*;
+
+import java.util.Arrays;
+
+/**
+ * This AttributeVisitor simplifies the code attributes that it visits, based
+ * on partial evaluation.
+ *
+ * @author Eric Lafortune
+ */
+public class EvaluationShrinker
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ //*
+ private static final boolean DEBUG_RESULTS = false;
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG_RESULTS = true;
+ private static boolean DEBUG = true;
+ //*/
+
+ private static final int UNSUPPORTED = -1;
+ private static final int NOP = InstructionConstants.OP_NOP & 0xff;
+ private static final int POP = InstructionConstants.OP_POP & 0xff;
+ private static final int POP2 = InstructionConstants.OP_POP2 & 0xff;
+ private static final int DUP = InstructionConstants.OP_DUP & 0xff;
+ private static final int DUP_X1 = InstructionConstants.OP_DUP_X1 & 0xff;
+ private static final int DUP_X2 = InstructionConstants.OP_DUP_X2 & 0xff;
+ private static final int DUP2 = InstructionConstants.OP_DUP2 & 0xff;
+ private static final int DUP2_X1 = InstructionConstants.OP_DUP2_X1 & 0xff;
+ private static final int DUP2_X2 = InstructionConstants.OP_DUP2_X2 & 0xff;
+ private static final int SWAP = InstructionConstants.OP_SWAP & 0xff;
+ private static final int MOV_X2 = DUP_X2 | (POP << 8);
+ private static final int MOV2_X1 = DUP2_X1 | (POP2 << 8);
+ private static final int MOV2_X2 = DUP2_X2 | (POP2 << 8);
+ private static final int POP_X1 = SWAP | (POP << 8);
+ private static final int POP_X2 = DUP2_X1 | (POP2 << 8) | (POP << 16);
+ private static final int POP_X3 = UNSUPPORTED;
+ private static final int POP2_X1 = DUP_X2 | (POP << 8) | (POP2 << 16);
+ private static final int POP2_X2 = DUP2_X2 | (POP2 << 8) | (POP2 << 16);
+ private static final int POP3 = POP2 | (POP << 8);
+ private static final int POP4 = POP2 | (POP2 << 8);
+ private static final int POP_DUP = POP | (DUP << 8);
+ private static final int POP_SWAP_POP = POP | (SWAP << 8) | (POP << 16);
+ private static final int POP2_SWAP_POP = POP2 | (SWAP << 8) | (POP << 16);
+ private static final int SWAP_DUP_X1 = SWAP | (DUP_X1 << 8);
+ private static final int SWAP_DUP_X1_SWAP = SWAP | (DUP_X1 << 8) | (SWAP << 16);
+ private static final int SWAP_POP_DUP = SWAP | (POP << 8) | (DUP << 16);
+ private static final int SWAP_POP_DUP_X1 = SWAP | (POP << 8) | (DUP_X1 << 16);
+ private static final int DUP_X2_POP2 = DUP_X2 | (POP2 << 8);
+ private static final int DUP2_X1_POP3 = DUP2_X1 | (POP2 << 8) | (POP << 16);
+ private static final int DUP2_X2_POP3 = DUP2_X2 | (POP2 << 8) | (POP << 16);
+ private static final int DUP2_X2_SWAP_POP = DUP2_X2 | (SWAP << 8) | (POP << 16);
+
+
+ private final InstructionVisitor extraDeletedInstructionVisitor;
+ private final InstructionVisitor extraAddedInstructionVisitor;
+
+ private final PartialEvaluator partialEvaluator;
+ private final PartialEvaluator simplePartialEvaluator = new PartialEvaluator();
+ private final SideEffectInstructionChecker sideEffectInstructionChecker = new SideEffectInstructionChecker(true, true);
+ private final MyUnusedParameterSimplifier unusedParameterSimplifier = new MyUnusedParameterSimplifier();
+ private final MyProducerMarker producerMarker = new MyProducerMarker();
+ private final MyVariableInitializationMarker variableInitializationMarker = new MyVariableInitializationMarker();
+ private final MyStackConsistencyFixer stackConsistencyFixer = new MyStackConsistencyFixer();
+ private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor(false, false);
+
+ private boolean[][] stacksNecessaryAfter = new boolean[ClassConstants.TYPICAL_CODE_LENGTH][ClassConstants.TYPICAL_STACK_SIZE];
+ private boolean[][] stacksSimplifiedBefore = new boolean[ClassConstants.TYPICAL_CODE_LENGTH][ClassConstants.TYPICAL_STACK_SIZE];
+ private boolean[] instructionsNecessary = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
+
+ private int maxMarkedOffset;
+
+
+ /**
+ * Creates a new EvaluationShrinker.
+ */
+ public EvaluationShrinker()
+ {
+ this(new PartialEvaluator(), null, null);
+ }
+
+
+ /**
+ * Creates a new EvaluationShrinker.
+ * @param partialEvaluator the partial evaluator that will
+ * execute the code and provide
+ * information about the results.
+ * @param extraDeletedInstructionVisitor an optional extra visitor for all
+ * deleted instructions.
+ * @param extraAddedInstructionVisitor an optional extra visitor for all
+ * added instructions.
+ */
+ public EvaluationShrinker(PartialEvaluator partialEvaluator,
+ InstructionVisitor extraDeletedInstructionVisitor,
+ InstructionVisitor extraAddedInstructionVisitor)
+ {
+ this.partialEvaluator = partialEvaluator;
+ this.extraDeletedInstructionVisitor = extraDeletedInstructionVisitor;
+ this.extraAddedInstructionVisitor = extraAddedInstructionVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG = DEBUG_RESULTS =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // TODO: Remove this when the evaluation shrinker has stabilized.
+ // Catch any unexpected exceptions from the actual visiting method.
+ try
+ {
+ // Process the code.
+ visitCodeAttribute0(clazz, method, codeAttribute);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while shrinking instructions after partial evaluation:");
+ System.err.println(" Class = ["+clazz.getName()+"]");
+ System.err.println(" Method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+ System.err.println("Not optimizing this method");
+
+ if (DEBUG)
+ {
+ method.accept(clazz, new ClassPrinter());
+
+ throw ex;
+ }
+ }
+ }
+
+
+ public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (DEBUG_RESULTS)
+ {
+ System.out.println();
+ System.out.println("Class "+ClassUtil.externalClassName(clazz.getName()));
+ System.out.println("Method "+ClassUtil.externalFullMethodDescription(clazz.getName(),
+ 0,
+ method.getName(clazz),
+ method.getDescriptor(clazz)));
+ }
+
+ // Initialize the necessary array.
+ initializeNecessary(codeAttribute);
+
+ // Evaluate the method.
+ partialEvaluator.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Evaluate the method the way the JVM verifier would do it.
+ simplePartialEvaluator.visitCodeAttribute(clazz, method, codeAttribute);
+
+ int codeLength = codeAttribute.u4codeLength;
+
+ // Reset the code changes.
+ codeAttributeEditor.reset(codeLength);
+
+ // Mark any unused method parameters on the stack.
+ if (DEBUG) System.out.println("Invocation simplification:");
+
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ if (partialEvaluator.isTraced(offset))
+ {
+ Instruction instruction = InstructionFactory.create(codeAttribute.code,
+ offset);
+
+ instruction.accept(clazz, method, codeAttribute, offset, unusedParameterSimplifier);
+ }
+ }
+
+ // Mark all essential instructions that have been encountered as used.
+ if (DEBUG) System.out.println("Usage initialization: ");
+
+ maxMarkedOffset = -1;
+
+ // The invocation of the "super" or "this" true
if the above offsets are
+ * branch targets, false
if they
+ * are branch origins.
+ */
+ private void markStraddlingBranches(int instructionOffset,
+ InstructionOffsetValue branchOffsets,
+ boolean isPointingToTargets)
+ {
+ if (branchOffsets != null)
+ {
+ // Loop over all branch offsets.
+ int branchCount = branchOffsets.instructionOffsetCount();
+ for (int branchIndex = 0; branchIndex < branchCount; branchIndex++)
+ {
+ // Is the branch straddling forward any necessary instructions?
+ int branchOffset = branchOffsets.instructionOffset(branchIndex);
+
+ // Is the offset pointing to a branch origin or to a branch target?
+ if (isPointingToTargets)
+ {
+ markStraddlingBranch(instructionOffset,
+ branchOffset,
+ instructionOffset,
+ branchOffset);
+ }
+ else
+ {
+ markStraddlingBranch(instructionOffset,
+ branchOffset,
+ branchOffset,
+ instructionOffset);
+ }
+ }
+ }
+ }
+
+
+ private void markStraddlingBranch(int instructionOffsetStart,
+ int instructionOffsetEnd,
+ int branchOrigin,
+ int branchTarget)
+ {
+ if (!isInstructionNecessary(branchOrigin) &&
+ isAnyInstructionNecessary(instructionOffsetStart, instructionOffsetEnd))
+ {
+ if (DEBUG) System.out.print("["+branchOrigin+"->"+branchTarget+"]");
+
+ // Mark the branch instruction.
+ markInstruction(branchOrigin);
+ }
+ }
+
+
+ /**
+ * Pushes a specified type of stack entry before or at the given offset.
+ * The instruction is marked as necessary.
+ */
+ private void insertPushInstructions(int offset,
+ boolean replace,
+ int computationalType)
+ {
+ // Mark this instruction.
+ markInstruction(offset);
+
+ // Create a simple push instrucion.
+ Instruction replacementInstruction =
+ new SimpleInstruction(pushOpcode(computationalType));
+
+ if (DEBUG) System.out.println(": "+replacementInstruction.toString(offset));
+
+ // Replace or insert the push instruction.
+ if (replace)
+ {
+ // Replace the push instruction.
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+ }
+ else
+ {
+ // Insert the push instruction.
+ codeAttributeEditor.insertBeforeInstruction(offset, replacementInstruction);
+
+ if (extraAddedInstructionVisitor != null)
+ {
+ replacementInstruction.accept(null, null, null, offset, extraAddedInstructionVisitor);
+ }
+ }
+ }
+
+
+ /**
+ * Returns the opcode of a push instruction corresponding to the given
+ * computational type.
+ * @param computationalType the computational type to be pushed on the stack.
+ */
+ private byte pushOpcode(int computationalType)
+ {
+ switch (computationalType)
+ {
+ case Value.TYPE_INTEGER: return InstructionConstants.OP_ICONST_0;
+ case Value.TYPE_LONG: return InstructionConstants.OP_LCONST_0;
+ case Value.TYPE_FLOAT: return InstructionConstants.OP_FCONST_0;
+ case Value.TYPE_DOUBLE: return InstructionConstants.OP_DCONST_0;
+ case Value.TYPE_REFERENCE:
+ case Value.TYPE_INSTRUCTION_OFFSET: return InstructionConstants.OP_ACONST_NULL;
+ }
+
+ throw new IllegalArgumentException("No push opcode for computational type ["+computationalType+"]");
+ }
+
+
+ /**
+ * Pops the given number of stack entries at or after the given offset.
+ * The instructions are marked as necessary.
+ */
+ private void insertPopInstructions(int offset, boolean replace, int popCount)
+ {
+ // Mark this instruction.
+ markInstruction(offset);
+
+ switch (popCount)
+ {
+ case 1:
+ {
+ // Replace or insert a single pop instruction.
+ Instruction popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP);
+
+ if (replace)
+ {
+ codeAttributeEditor.replaceInstruction(offset, popInstruction);
+ }
+ else
+ {
+ codeAttributeEditor.insertAfterInstruction(offset, popInstruction);
+
+ if (extraAddedInstructionVisitor != null)
+ {
+ popInstruction.accept(null, null, null, offset, extraAddedInstructionVisitor);
+ }
+ }
+ break;
+ }
+ case 2:
+ {
+ // Replace or insert a single pop2 instruction.
+ Instruction popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP2);
+
+ if (replace)
+ {
+ codeAttributeEditor.replaceInstruction(offset, popInstruction);
+ }
+ else
+ {
+ codeAttributeEditor.insertAfterInstruction(offset, popInstruction);
+
+ if (extraAddedInstructionVisitor != null)
+ {
+ popInstruction.accept(null, null, null, offset, extraAddedInstructionVisitor);
+ }
+ }
+ break;
+ }
+ default:
+ {
+ // Replace or insert the specified number of pop instructions.
+ Instruction[] popInstructions =
+ new Instruction[popCount / 2 + popCount % 2];
+
+ Instruction popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP2);
+
+ for (int index = 0; index < popCount / 2; index++)
+ {
+ popInstructions[index] = popInstruction;
+ }
+
+ if (popCount % 2 == 1)
+ {
+ popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP);
+
+ popInstructions[popCount / 2] = popInstruction;
+ }
+
+ if (replace)
+ {
+ codeAttributeEditor.replaceInstruction(offset, popInstructions);
+
+ for (int index = 1; index < popInstructions.length; index++)
+ {
+ if (extraAddedInstructionVisitor != null)
+ {
+ popInstructions[index].accept(null, null, null, offset, extraAddedInstructionVisitor);
+ }
+ }
+ }
+ else
+ {
+ codeAttributeEditor.insertAfterInstruction(offset, popInstructions);
+
+ for (int index = 0; index < popInstructions.length; index++)
+ {
+ if (extraAddedInstructionVisitor != null)
+ {
+ popInstructions[index].accept(null, null, null, offset, extraAddedInstructionVisitor);
+ }
+ }
+ }
+ break;
+ }
+ }
+ }
+
+
+ /**
+ * Replaces the instruction at a given offset by a static invocation.
+ */
+ private void replaceByStaticInvocation(Clazz clazz,
+ int offset,
+ ConstantInstruction constantInstruction)
+ {
+ // Remember the replacement instruction.
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC,
+ constantInstruction.constantIndex);
+
+ if (DEBUG) System.out.println(" Replacing by static invocation "+constantInstruction.toString(offset)+" -> "+replacementInstruction.toString());
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+ }
+
+
+ /**
+ * Replaces the given instruction by an infinite loop.
+ */
+ private void replaceByInfiniteLoop(Clazz clazz,
+ int offset)
+ {
+ if (DEBUG) System.out.println(" Inserting infinite loop at ["+offset+"]");
+
+ // Mark the instruction.
+ markInstruction(offset);
+
+ // Replace the instruction by an infinite loop.
+ Instruction replacementInstruction =
+ new BranchInstruction(InstructionConstants.OP_GOTO, 0);
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether the given instruction is a dup or swap instruction
+ * (dup, dup_x1, dup_x2, dup2, dup2_x1, dup2_x2, swap).
+ */
+ private boolean isDupOrSwap(Instruction instruction)
+ {
+ return instruction.opcode >= InstructionConstants.OP_DUP &&
+ instruction.opcode <= InstructionConstants.OP_SWAP;
+ }
+
+
+ /**
+ * Returns whether the given instruction is a pop instruction
+ * (pop, pop2).
+ */
+ private boolean isPop(Instruction instruction)
+ {
+ return instruction.opcode == InstructionConstants.OP_POP ||
+ instruction.opcode == InstructionConstants.OP_POP2;
+ }
+
+
+ /**
+ * Returns whether any traced but unnecessary instruction between the two
+ * given offsets is branching over the second given offset.
+ */
+ private boolean isAnyUnnecessaryInstructionBranchingOver(int instructionOffset1,
+ int instructionOffset2)
+ {
+ for (int offset = instructionOffset1; offset < instructionOffset2; offset++)
+ {
+ // Is it a traced but unmarked straddling branch?
+ if (partialEvaluator.isTraced(offset) &&
+ !isInstructionNecessary(offset) &&
+ isAnyLargerThan(partialEvaluator.branchTargets(offset),
+ instructionOffset2))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns whether all of the given instruction offsets (at least one)
+ * are smaller than or equal to the given offset.
+ */
+ private boolean isAllSmallerThanOrEqual(InstructionOffsetValue instructionOffsets,
+ int instructionOffset)
+ {
+ if (instructionOffsets != null)
+ {
+ // Loop over all instruction offsets.
+ int branchCount = instructionOffsets.instructionOffsetCount();
+ if (branchCount > 0)
+ {
+ for (int branchIndex = 0; branchIndex < branchCount; branchIndex++)
+ {
+ // Is the offset larger than the reference offset?
+ if (instructionOffsets.instructionOffset(branchIndex) > instructionOffset)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns whether any of the given instruction offsets (at least one)
+ * is larger than the given offset.
+ */
+ private boolean isAnyLargerThan(InstructionOffsetValue instructionOffsets,
+ int instructionOffset)
+ {
+ if (instructionOffsets != null)
+ {
+ // Loop over all instruction offsets.
+ int branchCount = instructionOffsets.instructionOffsetCount();
+ if (branchCount > 0)
+ {
+ for (int branchIndex = 0; branchIndex < branchCount; branchIndex++)
+ {
+ // Is the offset larger than the reference offset?
+ if (instructionOffsets.instructionOffset(branchIndex) > instructionOffset)
+ {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Initializes the necessary data structure.
+ */
+ private void initializeNecessary(CodeAttribute codeAttribute)
+ {
+ int codeLength = codeAttribute.u4codeLength;
+ int maxLocals = codeAttribute.u2maxLocals;
+ int maxStack = codeAttribute.u2maxStack;
+
+ // Create new arrays for storing information at each instruction offset.
+ if (stacksNecessaryAfter.length < codeLength ||
+ stacksNecessaryAfter[0].length < maxStack)
+ {
+ stacksNecessaryAfter = new boolean[codeLength][maxStack];
+ }
+ else
+ {
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ Arrays.fill(stacksNecessaryAfter[offset], 0, maxStack, false);
+ }
+ }
+
+ if (stacksSimplifiedBefore.length < codeLength ||
+ stacksSimplifiedBefore[0].length < maxStack)
+ {
+ stacksSimplifiedBefore = new boolean[codeLength][maxStack];
+ }
+ else
+ {
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ Arrays.fill(stacksSimplifiedBefore[offset], 0, maxStack, false);
+ }
+ }
+
+ if (instructionsNecessary.length < codeLength)
+ {
+ instructionsNecessary = new boolean[codeLength];
+ }
+ else
+ {
+ Arrays.fill(instructionsNecessary, 0, codeLength, false);
+ }
+ }
+
+
+ /**
+ * Returns whether the specified variable is initialized at the specified
+ * offset.
+ */
+ private boolean isVariableInitialization(int instructionOffset,
+ int variableIndex)
+ {
+ // Wasn't the variable set yet?
+ Value valueBefore = partialEvaluator.getVariablesBefore(instructionOffset).getValue(variableIndex);
+ if (valueBefore == null)
+ {
+ return true;
+ }
+
+ // Is the computational type different now?
+ Value valueAfter = partialEvaluator.getVariablesAfter(instructionOffset).getValue(variableIndex);
+ if (valueAfter.computationalType() != valueBefore.computationalType())
+ {
+ return true;
+ }
+
+ // Is the reference type different now?
+ if (valueAfter.computationalType() == Value.TYPE_REFERENCE &&
+ (valueAfter.referenceValue().isNull() == Value.ALWAYS ||
+ !valueAfter.referenceValue().getType().equals(valueBefore.referenceValue().getType())))
+ {
+ return true;
+ }
+
+ // Was the producer an argument (which may be removed)?
+ Value producersBefore = partialEvaluator.getVariablesBefore(instructionOffset).getProducerValue(variableIndex);
+ return producersBefore.instructionOffsetValue().instructionOffsetCount() == 1 &&
+ producersBefore.instructionOffsetValue().instructionOffset(0) == PartialEvaluator.AT_METHOD_ENTRY;
+ }
+
+
+ /**
+ * Marks the stack entry after the given offset.
+ * @param instructionOffset the offset of the stack entry to be marked.
+ * @param stackIndex the index of the stack entry to be marked
+ * (counting from the bottom).
+ */
+ private void markStackEntryAfter(int instructionOffset,
+ int stackIndex)
+ {
+ if (!isStackEntryNecessaryAfter(instructionOffset, stackIndex))
+ {
+ if (DEBUG) System.out.print("["+instructionOffset+".s"+stackIndex+"],");
+
+ stacksNecessaryAfter[instructionOffset][stackIndex] = true;
+
+ if (maxMarkedOffset < instructionOffset)
+ {
+ maxMarkedOffset = instructionOffset;
+ }
+ }
+ }
+
+
+
+ /**
+ * Returns whether the stack specified entries before the given offset are
+ * present.
+ */
+ private boolean isStackEntriesPresentBefore(int instructionOffset,
+ int stackIndex1,
+ int stackIndex2)
+ {
+ boolean present1 = isStackEntryPresentBefore(instructionOffset, stackIndex1);
+ boolean present2 = isStackEntryPresentBefore(instructionOffset, stackIndex2);
+
+// if (present1 ^ present2)
+// {
+// throw new UnsupportedOperationException("Can't handle partial use of dup2 instructions");
+// }
+
+ return present1 || present2;
+ }
+
+
+ /**
+ * Returns whether the specified stack entry before the given offset is
+ * present.
+ * @param instructionOffset the offset of the stack entry to be checked.
+ * @param stackIndex the index of the stack entry to be checked
+ * (counting from the bottom).
+ */
+ private boolean isStackEntryPresentBefore(int instructionOffset,
+ int stackIndex)
+ {
+ TracedStack tracedStack =
+ partialEvaluator.getStackBefore(instructionOffset);
+
+ InstructionOffsetValue producerOffsets =
+ tracedStack.getBottomProducerValue(stackIndex).instructionOffsetValue();
+
+ return isAnyStackEntryNecessaryAfter(producerOffsets, stackIndex);
+ }
+
+
+ /**
+ * Returns whether the stack specified entries after the given offset are
+ * necessary.
+ */
+ private boolean isStackEntriesNecessaryAfter(int instructionOffset,
+ int stackIndex1,
+ int stackIndex2)
+ {
+ boolean present1 = isStackEntryNecessaryAfter(instructionOffset, stackIndex1);
+ boolean present2 = isStackEntryNecessaryAfter(instructionOffset, stackIndex2);
+
+// if (present1 ^ present2)
+// {
+// throw new UnsupportedOperationException("Can't handle partial use of dup2 instructions");
+// }
+
+ return present1 || present2;
+ }
+
+
+ /**
+ * Returns whether any of the stack entries after the given offsets are
+ * necessary.
+ * @param instructionOffsets the offsets of the stack entries to be checked.
+ * @param stackIndex the index of the stack entries to be checked
+ * (counting from the bottom).
+ */
+ private boolean isAnyStackEntryNecessaryAfter(InstructionOffsetValue instructionOffsets,
+ int stackIndex)
+ {
+ int offsetCount = instructionOffsets.instructionOffsetCount();
+
+ for (int offsetIndex = 0; offsetIndex < offsetCount; offsetIndex++)
+ {
+ if (isStackEntryNecessaryAfter(instructionOffsets.instructionOffset(offsetIndex), stackIndex))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns whether the specified stack entry after the given offset is
+ * necessary.
+ * @param instructionOffset the offset of the stack entry to be checked.
+ * @param stackIndex the index of the stack entry to be checked
+ * (counting from the bottom).
+ */
+ private boolean isStackEntryNecessaryAfter(int instructionOffset,
+ int stackIndex)
+ {
+ return instructionOffset == PartialEvaluator.AT_CATCH_ENTRY ||
+ stacksNecessaryAfter[instructionOffset][stackIndex];
+ }
+
+
+ private void markStackSimplificationBefore(int instructionOffset,
+ int stackIndex)
+ {
+ stacksSimplifiedBefore[instructionOffset][stackIndex] = true;
+ }
+
+
+ private boolean isStackSimplifiedBefore(int instructionOffset,
+ int stackIndex)
+ {
+ return stacksSimplifiedBefore[instructionOffset][stackIndex];
+ }
+
+
+ private void markInstruction(int instructionOffset)
+ {
+ if (!isInstructionNecessary(instructionOffset))
+ {
+ if (DEBUG) System.out.print(instructionOffset+",");
+
+ instructionsNecessary[instructionOffset] = true;
+
+ if (maxMarkedOffset < instructionOffset)
+ {
+ maxMarkedOffset = instructionOffset;
+ }
+ }
+ }
+
+
+ private boolean isAnyInstructionNecessary(int instructionOffset1,
+ int instructionOffset2)
+ {
+ for (int instructionOffset = instructionOffset1;
+ instructionOffset < instructionOffset2;
+ instructionOffset++)
+ {
+ if (isInstructionNecessary(instructionOffset))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns the highest offset of an instruction that has been marked as
+ * necessary, before the given offset.
+ */
+ private int lastNecessaryInstructionOffset(int instructionOffset)
+ {
+ for (int offset = instructionOffset-1; offset >= 0; offset--)
+ {
+ if (isInstructionNecessary(instructionOffset))
+ {
+ return offset;
+ }
+ }
+
+ return 0;
+ }
+
+
+ private boolean isInstructionNecessary(int instructionOffset)
+ {
+ return instructionOffset == PartialEvaluator.AT_METHOD_ENTRY ||
+ instructionsNecessary[instructionOffset];
+ }
+}
diff --git a/src/proguard/optimize/evaluation/EvaluationSimplifier.java b/src/proguard/optimize/evaluation/EvaluationSimplifier.java
new file mode 100644
index 000000000..e6e73d909
--- /dev/null
+++ b/src/proguard/optimize/evaluation/EvaluationSimplifier.java
@@ -0,0 +1,988 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.editor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.evaluation.*;
+import proguard.evaluation.value.*;
+import proguard.optimize.info.*;
+
+/**
+ * This AttributeVisitor simplifies the code attributes that it visits, based
+ * on partial evaluation.
+ *
+ * @author Eric Lafortune
+ */
+public class EvaluationSimplifier
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor
+{
+ private static final int POS_ZERO_FLOAT_BITS = Float.floatToIntBits(0.0f);
+ private static final long POS_ZERO_DOUBLE_BITS = Double.doubleToLongBits(0.0);
+
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+ private final InstructionVisitor extraInstructionVisitor;
+
+ private final PartialEvaluator partialEvaluator;
+ private final SideEffectInstructionChecker sideEffectInstructionChecker = new SideEffectInstructionChecker(true, true);
+ private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor(false, true);
+
+
+ /**
+ * Creates a new EvaluationSimplifier.
+ */
+ public EvaluationSimplifier()
+ {
+ this(new PartialEvaluator(), null);
+ }
+
+
+ /**
+ * Creates a new EvaluationSimplifier.
+ * @param partialEvaluator the partial evaluator that will
+ * execute the code and provide
+ * information about the results.
+ * @param extraInstructionVisitor an optional extra visitor for all
+ * simplified instructions.
+ */
+ public EvaluationSimplifier(PartialEvaluator partialEvaluator,
+ InstructionVisitor extraInstructionVisitor)
+ {
+ this.partialEvaluator = partialEvaluator;
+ this.extraInstructionVisitor = extraInstructionVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // TODO: Remove this when the evaluation simplifier has stabilized.
+ // Catch any unexpected exceptions from the actual visiting method.
+ try
+ {
+ // Process the code.
+ visitCodeAttribute0(clazz, method, codeAttribute);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while simplifying instructions after partial evaluation:");
+ System.err.println(" Class = ["+clazz.getName()+"]");
+ System.err.println(" Method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+ System.err.println("Not optimizing this method");
+
+ if (DEBUG)
+ {
+ method.accept(clazz, new ClassPrinter());
+
+ throw ex;
+ }
+ }
+ }
+
+
+ public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (DEBUG)
+ {
+ System.out.println();
+ System.out.println("Class "+ClassUtil.externalClassName(clazz.getName()));
+ System.out.println("Method "+ClassUtil.externalFullMethodDescription(clazz.getName(),
+ 0,
+ method.getName(clazz),
+ method.getDescriptor(clazz)));
+ }
+
+ // Evaluate the method.
+ partialEvaluator.visitCodeAttribute(clazz, method, codeAttribute);
+
+ int codeLength = codeAttribute.u4codeLength;
+
+ // Reset the code changes.
+ codeAttributeEditor.reset(codeLength);
+
+ // Replace any instructions that can be simplified.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ if (partialEvaluator.isTraced(offset))
+ {
+ Instruction instruction = InstructionFactory.create(codeAttribute.code,
+ offset);
+
+ instruction.accept(clazz, method, codeAttribute, offset, this);
+ }
+ }
+
+ // Apply all accumulated changes to the code.
+ codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ switch (simpleInstruction.opcode)
+ {
+ case InstructionConstants.OP_IALOAD:
+ case InstructionConstants.OP_BALOAD:
+ case InstructionConstants.OP_CALOAD:
+ case InstructionConstants.OP_SALOAD:
+ case InstructionConstants.OP_IADD:
+ case InstructionConstants.OP_ISUB:
+ case InstructionConstants.OP_IMUL:
+ case InstructionConstants.OP_IDIV:
+ case InstructionConstants.OP_IREM:
+ case InstructionConstants.OP_INEG:
+ case InstructionConstants.OP_ISHL:
+ case InstructionConstants.OP_ISHR:
+ case InstructionConstants.OP_IUSHR:
+ case InstructionConstants.OP_IAND:
+ case InstructionConstants.OP_IOR:
+ case InstructionConstants.OP_IXOR:
+ case InstructionConstants.OP_L2I:
+ case InstructionConstants.OP_F2I:
+ case InstructionConstants.OP_D2I:
+ case InstructionConstants.OP_I2B:
+ case InstructionConstants.OP_I2C:
+ case InstructionConstants.OP_I2S:
+ replaceIntegerPushInstruction(clazz, offset, simpleInstruction);
+ break;
+
+ case InstructionConstants.OP_LALOAD:
+ case InstructionConstants.OP_LADD:
+ case InstructionConstants.OP_LSUB:
+ case InstructionConstants.OP_LMUL:
+ case InstructionConstants.OP_LDIV:
+ case InstructionConstants.OP_LREM:
+ case InstructionConstants.OP_LNEG:
+ case InstructionConstants.OP_LSHL:
+ case InstructionConstants.OP_LSHR:
+ case InstructionConstants.OP_LUSHR:
+ case InstructionConstants.OP_LAND:
+ case InstructionConstants.OP_LOR:
+ case InstructionConstants.OP_LXOR:
+ case InstructionConstants.OP_I2L:
+ case InstructionConstants.OP_F2L:
+ case InstructionConstants.OP_D2L:
+ replaceLongPushInstruction(clazz, offset, simpleInstruction);
+ break;
+
+ case InstructionConstants.OP_FALOAD:
+ case InstructionConstants.OP_FADD:
+ case InstructionConstants.OP_FSUB:
+ case InstructionConstants.OP_FMUL:
+ case InstructionConstants.OP_FDIV:
+ case InstructionConstants.OP_FREM:
+ case InstructionConstants.OP_FNEG:
+ case InstructionConstants.OP_I2F:
+ case InstructionConstants.OP_L2F:
+ case InstructionConstants.OP_D2F:
+ replaceFloatPushInstruction(clazz, offset, simpleInstruction);
+ break;
+
+ case InstructionConstants.OP_DALOAD:
+ case InstructionConstants.OP_DADD:
+ case InstructionConstants.OP_DSUB:
+ case InstructionConstants.OP_DMUL:
+ case InstructionConstants.OP_DDIV:
+ case InstructionConstants.OP_DREM:
+ case InstructionConstants.OP_DNEG:
+ case InstructionConstants.OP_I2D:
+ case InstructionConstants.OP_L2D:
+ case InstructionConstants.OP_F2D:
+ replaceDoublePushInstruction(clazz, offset, simpleInstruction);
+ break;
+
+ case InstructionConstants.OP_AALOAD:
+ replaceReferencePushInstruction(clazz, offset, simpleInstruction);
+ break;
+ }
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ int variableIndex = variableInstruction.variableIndex;
+
+ switch (variableInstruction.opcode)
+ {
+ case InstructionConstants.OP_ILOAD:
+ case InstructionConstants.OP_ILOAD_0:
+ case InstructionConstants.OP_ILOAD_1:
+ case InstructionConstants.OP_ILOAD_2:
+ case InstructionConstants.OP_ILOAD_3:
+ replaceIntegerPushInstruction(clazz, offset, variableInstruction, variableIndex);
+ break;
+
+ case InstructionConstants.OP_LLOAD:
+ case InstructionConstants.OP_LLOAD_0:
+ case InstructionConstants.OP_LLOAD_1:
+ case InstructionConstants.OP_LLOAD_2:
+ case InstructionConstants.OP_LLOAD_3:
+ replaceLongPushInstruction(clazz, offset, variableInstruction, variableIndex);
+ break;
+
+ case InstructionConstants.OP_FLOAD:
+ case InstructionConstants.OP_FLOAD_0:
+ case InstructionConstants.OP_FLOAD_1:
+ case InstructionConstants.OP_FLOAD_2:
+ case InstructionConstants.OP_FLOAD_3:
+ replaceFloatPushInstruction(clazz, offset, variableInstruction, variableIndex);
+ break;
+
+ case InstructionConstants.OP_DLOAD:
+ case InstructionConstants.OP_DLOAD_0:
+ case InstructionConstants.OP_DLOAD_1:
+ case InstructionConstants.OP_DLOAD_2:
+ case InstructionConstants.OP_DLOAD_3:
+ replaceDoublePushInstruction(clazz, offset, variableInstruction, variableIndex);
+ break;
+
+ case InstructionConstants.OP_ALOAD:
+ case InstructionConstants.OP_ALOAD_0:
+ case InstructionConstants.OP_ALOAD_1:
+ case InstructionConstants.OP_ALOAD_2:
+ case InstructionConstants.OP_ALOAD_3:
+ replaceReferencePushInstruction(clazz, offset, variableInstruction);
+ break;
+
+ case InstructionConstants.OP_ASTORE:
+ case InstructionConstants.OP_ASTORE_0:
+ case InstructionConstants.OP_ASTORE_1:
+ case InstructionConstants.OP_ASTORE_2:
+ case InstructionConstants.OP_ASTORE_3:
+ deleteReferencePopInstruction(clazz, offset, variableInstruction);
+ break;
+
+ case InstructionConstants.OP_RET:
+ replaceBranchInstruction(clazz, offset, variableInstruction);
+ break;
+ }
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ switch (constantInstruction.opcode)
+ {
+ case InstructionConstants.OP_GETSTATIC:
+ case InstructionConstants.OP_GETFIELD:
+ replaceAnyPushInstruction(clazz, offset, constantInstruction);
+ break;
+
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ if (constantInstruction.stackPushCount(clazz) > 0 &&
+ !sideEffectInstructionChecker.hasSideEffects(clazz,
+ method,
+ codeAttribute,
+ offset,
+ constantInstruction))
+ {
+ replaceAnyPushInstruction(clazz, offset, constantInstruction);
+ }
+
+ break;
+
+ case InstructionConstants.OP_CHECKCAST:
+ replaceReferencePushInstruction(clazz, offset, constantInstruction);
+ break;
+ }
+ }
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ switch (branchInstruction.opcode)
+ {
+ case InstructionConstants.OP_GOTO:
+ case InstructionConstants.OP_GOTO_W:
+ // Don't replace unconditional branches.
+ break;
+
+ case InstructionConstants.OP_JSR:
+ case InstructionConstants.OP_JSR_W:
+ replaceJsrInstruction(clazz, offset, branchInstruction);
+ break;
+
+ default:
+ replaceBranchInstruction(clazz, offset, branchInstruction);
+ break;
+ }
+ }
+
+
+ public void visitAnySwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SwitchInstruction switchInstruction)
+ {
+ // First try to simplify it to a simple branch.
+ replaceBranchInstruction(clazz, offset, switchInstruction);
+
+ // Otherwise make sure all branch targets are valid.
+ if (!codeAttributeEditor.isModified(offset))
+ {
+ replaceSwitchInstruction(clazz, offset, switchInstruction);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Replaces the push instruction at the given offset by a simpler push
+ * instruction, if possible.
+ */
+ private void replaceAnyPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ Value pushedValue = partialEvaluator.getStackAfter(offset).getTop(0);
+ if (pushedValue.isParticular())
+ {
+ switch (pushedValue.computationalType())
+ {
+ case Value.TYPE_INTEGER:
+ replaceIntegerPushInstruction(clazz, offset, instruction);
+ break;
+ case Value.TYPE_LONG:
+ replaceLongPushInstruction(clazz, offset, instruction);
+ break;
+ case Value.TYPE_FLOAT:
+ replaceFloatPushInstruction(clazz, offset, instruction);
+ break;
+ case Value.TYPE_DOUBLE:
+ replaceDoublePushInstruction(clazz, offset, instruction);
+ break;
+ case Value.TYPE_REFERENCE:
+ replaceReferencePushInstruction(clazz, offset, instruction);
+ break;
+ }
+ }
+ }
+
+
+ /**
+ * Replaces the integer pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceIntegerPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ replaceIntegerPushInstruction(clazz,
+ offset,
+ instruction,
+ partialEvaluator.getVariablesBefore(offset).size());
+ }
+
+
+ /**
+ * Replaces the integer pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceIntegerPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction,
+ int maxVariableIndex)
+ {
+ Value pushedValue = partialEvaluator.getStackAfter(offset).getTop(0);
+ if (pushedValue.isParticular())
+ {
+ // Push a constant instead.
+ int value = pushedValue.integerValue().value();
+ if ((short)value == value)
+ {
+ replaceConstantPushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_SIPUSH,
+ value);
+ }
+ else
+ {
+ ConstantPoolEditor constantPoolEditor =
+ new ConstantPoolEditor((ProgramClass)clazz);
+
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_LDC,
+ constantPoolEditor.addIntegerConstant(value));
+
+ replaceInstruction(clazz, offset, instruction, replacementInstruction);
+ }
+ }
+ else if (pushedValue.isSpecific())
+ {
+ // Load an equivalent lower-numbered variable instead, if any.
+ TracedVariables variables = partialEvaluator.getVariablesBefore(offset);
+ for (int variableIndex = 0; variableIndex < maxVariableIndex; variableIndex++)
+ {
+ if (pushedValue.equals(variables.load(variableIndex)))
+ {
+ replaceVariablePushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_ILOAD,
+ variableIndex);
+ break;
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Replaces the long pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceLongPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ replaceLongPushInstruction(clazz,
+ offset,
+ instruction,
+ partialEvaluator.getVariablesBefore(offset).size());
+ }
+
+
+ /**
+ * Replaces the long pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceLongPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction,
+ int maxVariableIndex)
+ {
+ Value pushedValue = partialEvaluator.getStackAfter(offset).getTop(0);
+ if (pushedValue.isParticular())
+ {
+ // Push a constant instead.
+ long value = pushedValue.longValue().value();
+ if (value == 0L ||
+ value == 1L)
+ {
+ replaceConstantPushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_LCONST_0,
+ (int)value);
+ }
+ else
+ {
+ ConstantPoolEditor constantPoolEditor =
+ new ConstantPoolEditor((ProgramClass)clazz);
+
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W,
+ constantPoolEditor.addLongConstant(value));
+
+ replaceInstruction(clazz, offset, instruction, replacementInstruction);
+ }
+ }
+ else if (pushedValue.isSpecific())
+ {
+ // Load an equivalent lower-numbered variable instead, if any.
+ TracedVariables variables = partialEvaluator.getVariablesBefore(offset);
+ for (int variableIndex = 0; variableIndex < maxVariableIndex; variableIndex++)
+ {
+ // Note that we have to check the second part as well.
+ if (pushedValue.equals(variables.load(variableIndex)) &&
+ variables.load(variableIndex + 1) != null &&
+ variables.load(variableIndex + 1).computationalType() == Value.TYPE_TOP)
+ {
+ replaceVariablePushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_LLOAD,
+ variableIndex);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Replaces the float pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceFloatPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ replaceFloatPushInstruction(clazz,
+ offset,
+ instruction,
+ partialEvaluator.getVariablesBefore(offset).size());
+ }
+
+
+ /**
+ * Replaces the float pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceFloatPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction,
+ int maxVariableIndex)
+ {
+ Value pushedValue = partialEvaluator.getStackAfter(offset).getTop(0);
+ if (pushedValue.isParticular())
+ {
+ // Push a constant instead.
+ // Make sure to distinguish between +0.0 and -0.0.
+ float value = pushedValue.floatValue().value();
+ if (value == 0.0f && Float.floatToIntBits(value) == POS_ZERO_FLOAT_BITS ||
+ value == 1.0f ||
+ value == 2.0f)
+ {
+ replaceConstantPushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_FCONST_0,
+ (int)value);
+ }
+ else
+ {
+ ConstantPoolEditor constantPoolEditor =
+ new ConstantPoolEditor((ProgramClass)clazz);
+
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_LDC,
+ constantPoolEditor.addFloatConstant(value));
+
+ replaceInstruction(clazz, offset, instruction, replacementInstruction);
+ }
+ }
+ else if (pushedValue.isSpecific())
+ {
+ // Load an equivalent lower-numbered variable instead, if any.
+ TracedVariables variables = partialEvaluator.getVariablesBefore(offset);
+ for (int variableIndex = 0; variableIndex < maxVariableIndex; variableIndex++)
+ {
+ if (pushedValue.equals(variables.load(variableIndex)))
+ {
+ replaceVariablePushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_FLOAD,
+ variableIndex);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Replaces the double pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceDoublePushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ replaceDoublePushInstruction(clazz,
+ offset,
+ instruction,
+ partialEvaluator.getVariablesBefore(offset).size());
+ }
+
+
+ /**
+ * Replaces the double pushing instruction at the given offset by a simpler
+ * push instruction, if possible.
+ */
+ private void replaceDoublePushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction,
+ int maxVariableIndex)
+ {
+ Value pushedValue = partialEvaluator.getStackAfter(offset).getTop(0);
+ if (pushedValue.isParticular())
+ {
+ // Push a constant instead.
+ // Make sure to distinguish between +0.0 and -0.0.
+ double value = pushedValue.doubleValue().value();
+ if (value == 0.0 && Double.doubleToLongBits(value) == POS_ZERO_DOUBLE_BITS ||
+ value == 1.0)
+ {
+ replaceConstantPushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_DCONST_0,
+ (int)value);
+ }
+ else
+ {
+ ConstantPoolEditor constantPoolEditor =
+ new ConstantPoolEditor((ProgramClass)clazz);
+
+ Instruction replacementInstruction =
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W,
+ constantPoolEditor.addDoubleConstant(value));
+
+ replaceInstruction(clazz, offset, instruction, replacementInstruction);
+ }
+ }
+ else if (pushedValue.isSpecific())
+ {
+ // Load an equivalent lower-numbered variable instead, if any.
+ TracedVariables variables = partialEvaluator.getVariablesBefore(offset);
+ for (int variableIndex = 0; variableIndex < maxVariableIndex; variableIndex++)
+ {
+ // Note that we have to check the second part as well.
+ if (pushedValue.equals(variables.load(variableIndex)) &&
+ variables.load(variableIndex + 1) != null &&
+ variables.load(variableIndex + 1).computationalType() == Value.TYPE_TOP)
+ {
+ replaceVariablePushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_DLOAD,
+ variableIndex);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Replaces the reference pushing instruction at the given offset by a
+ * simpler push instruction, if possible.
+ */
+ private void replaceReferencePushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ Value pushedValue = partialEvaluator.getStackAfter(offset).getTop(0);
+ if (pushedValue.isParticular())
+ {
+ // A reference value can only be specific if it is null.
+ replaceConstantPushInstruction(clazz,
+ offset,
+ instruction,
+ InstructionConstants.OP_ACONST_NULL,
+ 0);
+ }
+ }
+
+
+ /**
+ * Replaces the instruction at a given offset by a given push instruction
+ * of a constant.
+ */
+ private void replaceConstantPushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction,
+ byte replacementOpcode,
+ int value)
+ {
+ Instruction replacementInstruction =
+ new SimpleInstruction(replacementOpcode, value);
+
+ replaceInstruction(clazz, offset, instruction, replacementInstruction);
+ }
+
+
+ /**
+ * Replaces the instruction at a given offset by a given push instruction
+ * of a variable.
+ */
+ private void replaceVariablePushInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction,
+ byte replacementOpcode,
+ int variableIndex)
+ {
+ Instruction replacementInstruction =
+ new VariableInstruction(replacementOpcode, variableIndex);
+
+ replaceInstruction(clazz, offset, instruction, replacementInstruction);
+ }
+
+
+ /**
+ * Replaces the given 'jsr' instruction by a simpler branch instruction,
+ * if it jumps to a subroutine that doesn't return or a subroutine that
+ * is only called from one place.
+ */
+ private void replaceJsrInstruction(Clazz clazz,
+ int offset,
+ BranchInstruction branchInstruction)
+ {
+ // Is the subroutine ever returning?
+ int subroutineStart = offset + branchInstruction.branchOffset;
+ if (!partialEvaluator.isSubroutineReturning(subroutineStart) ||
+ partialEvaluator.branchOrigins(subroutineStart).instructionOffsetCount() == 1)
+ {
+ // All 'jsr' instructions to this subroutine can be replaced
+ // by unconditional branch instructions.
+ replaceBranchInstruction(clazz, offset, branchInstruction);
+ }
+ else if (!partialEvaluator.isTraced(offset + branchInstruction.length(offset)))
+ {
+ // We have to make sure the instruction after this 'jsr'
+ // instruction is valid, even if it is never reached.
+ replaceByInfiniteLoop(clazz, offset + branchInstruction.length(offset), branchInstruction);
+ }
+ }
+
+
+ /**
+ * Deletes the reference popping instruction at the given offset, if
+ * it is at the start of a subroutine that doesn't return or a subroutine
+ * that is only called from one place.
+ */
+ private void deleteReferencePopInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ if (partialEvaluator.isSubroutineStart(offset) &&
+ (!partialEvaluator.isSubroutineReturning(offset) ||
+ partialEvaluator.branchOrigins(offset).instructionOffsetCount() == 1))
+ {
+ if (DEBUG) System.out.println(" Deleting store of subroutine return address "+instruction.toString(offset));
+
+ // A reference value can only be specific if it is null.
+ codeAttributeEditor.deleteInstruction(offset);
+ }
+ }
+
+
+ /**
+ * Deletes the given branch instruction, or replaces it by a simpler branch
+ * instruction, if possible.
+ */
+ private void replaceBranchInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ InstructionOffsetValue branchTargets = partialEvaluator.branchTargets(offset);
+
+ // Is there exactly one branch target (not from a goto or jsr)?
+ if (branchTargets != null &&
+ branchTargets.instructionOffsetCount() == 1)
+ {
+ // Is it branching to the next instruction?
+ int branchOffset = branchTargets.instructionOffset(0) - offset;
+ if (branchOffset == instruction.length(offset))
+ {
+ if (DEBUG) System.out.println(" Ignoring zero branch instruction at ["+offset+"]");
+ }
+ else
+ {
+ // Replace the branch instruction by a simple branch instruction.
+ Instruction replacementInstruction =
+ new BranchInstruction(InstructionConstants.OP_GOTO,
+ branchOffset);
+
+ replaceInstruction(clazz, offset, instruction, replacementInstruction);
+ }
+ }
+ }
+
+
+ /**
+ * Makes sure all branch targets of the given switch instruction are valid.
+ */
+ private void replaceSwitchInstruction(Clazz clazz,
+ int offset,
+ SwitchInstruction switchInstruction)
+ {
+ // Get the actual branch targets.
+ InstructionOffsetValue branchTargets = partialEvaluator.branchTargets(offset);
+
+ // Get an offset that can serve as a valid default offset.
+ int defaultOffset =
+ branchTargets.instructionOffset(branchTargets.instructionOffsetCount()-1) -
+ offset;
+
+ Instruction replacementInstruction = null;
+
+ // Check the jump offsets.
+ int[] jumpOffsets = switchInstruction.jumpOffsets;
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ if (!branchTargets.contains(offset + jumpOffsets[index]))
+ {
+ // Replace the unused offset.
+ jumpOffsets[index] = defaultOffset;
+
+ // Remember to replace the instruction.
+ replacementInstruction = switchInstruction;
+ }
+ }
+
+ // Check the default offset.
+ if (!branchTargets.contains(offset + switchInstruction.defaultOffset))
+ {
+ // Replace the unused offset.
+ switchInstruction.defaultOffset = defaultOffset;
+
+ // Remember to replace the instruction.
+ replacementInstruction = switchInstruction;
+ }
+
+ if (replacementInstruction != null)
+ {
+ replaceInstruction(clazz, offset, switchInstruction, replacementInstruction);
+ }
+ }
+
+
+ /**
+ * Replaces the given instruction by an infinite loop.
+ */
+ private void replaceByInfiniteLoop(Clazz clazz,
+ int offset,
+ Instruction instruction)
+ {
+ // Replace the instruction by an infinite loop.
+ Instruction replacementInstruction =
+ new BranchInstruction(InstructionConstants.OP_GOTO, 0);
+
+ if (DEBUG) System.out.println(" Replacing unreachable instruction by infinite loop "+replacementInstruction.toString(offset));
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+
+ // Visit the instruction, if required.
+ if (extraInstructionVisitor != null)
+ {
+ // Note: we're not passing the right arguments for now, knowing that
+ // they aren't used anyway.
+ instruction.accept(clazz, null, null, offset, extraInstructionVisitor);
+ }
+ }
+
+
+ /**
+ * Replaces the instruction at a given offset by a given push instruction.
+ */
+ private void replaceInstruction(Clazz clazz,
+ int offset,
+ Instruction instruction,
+ Instruction replacementInstruction)
+ {
+ // Pop unneeded stack entries if necessary.
+ int popCount =
+ instruction.stackPopCount(clazz) -
+ replacementInstruction.stackPopCount(clazz);
+
+ insertPopInstructions(offset, popCount);
+
+ if (DEBUG) System.out.println(" Replacing instruction "+instruction.toString(offset)+" -> "+replacementInstruction.toString()+(popCount == 0 ? "" : " ("+popCount+" pops)"));
+
+ codeAttributeEditor.replaceInstruction(offset, replacementInstruction);
+
+ // Visit the instruction, if required.
+ if (extraInstructionVisitor != null)
+ {
+ // Note: we're not passing the right arguments for now, knowing that
+ // they aren't used anyway.
+ instruction.accept(clazz, null, null, offset, extraInstructionVisitor);
+ }
+ }
+
+
+ /**
+ * Pops the given number of stack entries before the instruction at the
+ * given offset.
+ */
+ private void insertPopInstructions(int offset, int popCount)
+ {
+ switch (popCount)
+ {
+ case 0:
+ {
+ break;
+ }
+ case 1:
+ {
+ // Insert a single pop instruction.
+ Instruction popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP);
+
+ codeAttributeEditor.insertBeforeInstruction(offset,
+ popInstruction);
+ break;
+ }
+ case 2:
+ {
+ // Insert a single pop2 instruction.
+ Instruction popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP2);
+
+ codeAttributeEditor.insertBeforeInstruction(offset,
+ popInstruction);
+ break;
+ }
+ default:
+ {
+ // Insert the specified number of pop instructions.
+ Instruction[] popInstructions =
+ new Instruction[popCount / 2 + popCount % 2];
+
+ Instruction popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP2);
+
+ for (int index = 0; index < popCount / 2; index++)
+ {
+ popInstructions[index] = popInstruction;
+ }
+
+ if (popCount % 2 == 1)
+ {
+ popInstruction =
+ new SimpleInstruction(InstructionConstants.OP_POP);
+
+ popInstructions[popCount / 2] = popInstruction;
+ }
+
+ codeAttributeEditor.insertBeforeInstruction(offset,
+ popInstructions);
+ break;
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/evaluation/LivenessAnalyzer.java b/src/proguard/optimize/evaluation/LivenessAnalyzer.java
new file mode 100644
index 000000000..5ce8ccb97
--- /dev/null
+++ b/src/proguard/optimize/evaluation/LivenessAnalyzer.java
@@ -0,0 +1,526 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.evaluation.value.*;
+
+/**
+ * This AttributeVisitor analyzes the liveness of the variables in the code
+ * attributes that it visits, based on partial evaluation.
+ *
+ * @author Eric Lafortune
+ */
+public class LivenessAnalyzer
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ExceptionInfoVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+ private static final int MAX_VARIABLES_SIZE = 64;
+
+ private final PartialEvaluator partialEvaluator;
+
+ private long[] isAliveBefore = new long[ClassConstants.TYPICAL_CODE_LENGTH];
+ private long[] isAliveAfter = new long[ClassConstants.TYPICAL_CODE_LENGTH];
+ private long[] isCategory2 = new long[ClassConstants.TYPICAL_CODE_LENGTH];
+
+ // Fields acting as global temporary variables.
+ private boolean checkAgain;
+ private long alive;
+
+
+ /**
+ * Creates a new LivenessAnalyzer.
+ */
+ public LivenessAnalyzer()
+ {
+ this(new PartialEvaluator());
+ }
+
+
+ /**
+ * Creates a new LivenessAnalyzer that will use the given partial evaluator.
+ * It will run this evaluator on every code attribute that it visits.
+ */
+ public LivenessAnalyzer(PartialEvaluator partialEvaluator)
+ {
+ this.partialEvaluator = partialEvaluator;
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset has ever been
+ * executed during the partial evaluation.
+ */
+ public boolean isTraced(int instructionOffset)
+ {
+ return partialEvaluator.isTraced(instructionOffset);
+ }
+
+
+ /**
+ * Returns whether the specified variable is alive before the instruction
+ * at the given offset.
+ */
+ public boolean isAliveBefore(int instructionOffset, int variableIndex)
+ {
+ return variableIndex >= MAX_VARIABLES_SIZE ||
+ (isAliveBefore[instructionOffset] & (1L << variableIndex)) != 0;
+ }
+
+
+ /**
+ * Sets whether the specified variable is alive before the instruction
+ * at the given offset.
+ */
+ public void setAliveBefore(int instructionOffset, int variableIndex, boolean alive)
+ {
+ if (variableIndex < MAX_VARIABLES_SIZE)
+ {
+ if (alive)
+ {
+ isAliveBefore[instructionOffset] |= 1L << variableIndex;
+ }
+ else
+ {
+ isAliveBefore[instructionOffset] &= ~(1L << variableIndex);
+ }
+ }
+ }
+
+
+ /**
+ * Returns whether the specified variable is alive after the instruction
+ * at the given offset.
+ */
+ public boolean isAliveAfter(int instructionOffset, int variableIndex)
+ {
+ return variableIndex >= MAX_VARIABLES_SIZE ||
+ (isAliveAfter[instructionOffset] & (1L << variableIndex)) != 0;
+ }
+
+
+ /**
+ * Sets whether the specified variable is alive after the instruction
+ * at the given offset.
+ */
+ public void setAliveAfter(int instructionOffset, int variableIndex, boolean alive)
+ {
+ if (variableIndex < MAX_VARIABLES_SIZE)
+ {
+ if (alive)
+ {
+ isAliveAfter[instructionOffset] |= 1L << variableIndex;
+ }
+ else
+ {
+ isAliveAfter[instructionOffset] &= ~(1L << variableIndex);
+ }
+ }
+ }
+
+
+ /**
+ * Returns whether the specified variable takes up two entries after the
+ * instruction at the given offset.
+ */
+ public boolean isCategory2(int instructionOffset, int variableIndex)
+ {
+ return variableIndex < MAX_VARIABLES_SIZE &&
+ (isCategory2[instructionOffset] & (1L << variableIndex)) != 0;
+ }
+
+
+ /**
+ * Sets whether the specified variable takes up two entries after the
+ * instruction at the given offset.
+ */
+ public void setCategory2(int instructionOffset, int variableIndex, boolean category2)
+ {
+ if (variableIndex < MAX_VARIABLES_SIZE)
+ {
+ if (category2)
+ {
+ isCategory2[instructionOffset] |= 1L << variableIndex;
+ }
+ else
+ {
+ isCategory2[instructionOffset] &= ~(1L << variableIndex);
+ }
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ if (DEBUG)
+ {
+ System.out.println();
+ System.out.println("Liveness analysis: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ }
+
+ // Initialize the global arrays.
+ initializeArrays(codeAttribute);
+
+ // Evaluate the method.
+ partialEvaluator.visitCodeAttribute(clazz, method, codeAttribute);
+
+ int codeLength = codeAttribute.u4codeLength;
+ int variablesSize = codeAttribute.u2maxLocals;
+
+ // We'll only really analyze the first 64 variables.
+ if (variablesSize > MAX_VARIABLES_SIZE)
+ {
+ variablesSize = MAX_VARIABLES_SIZE;
+ }
+
+ // Mark liveness blocks, as many times as necessary.
+ do
+ {
+ checkAgain = false;
+ alive = 0L;
+
+ // Loop over all traced instructions, backward.
+ for (int offset = codeLength - 1; offset >= 0; offset--)
+ {
+ if (partialEvaluator.isTraced(offset))
+ {
+ // Update the liveness based on the branch targets.
+ InstructionOffsetValue branchTargets = partialEvaluator.branchTargets(offset);
+ if (branchTargets != null)
+ {
+ // Update the liveness right after the branch instruction.
+ alive = combinedLiveness(branchTargets);
+ }
+
+ // Merge the current liveness.
+ alive |= isAliveAfter[offset];
+
+ // Update the liveness after the instruction.
+ isAliveAfter[offset] = alive;
+
+ // Update the current liveness based on the instruction.
+ codeAttribute.instructionAccept(clazz, method, offset, this);
+
+ // Merge the current liveness.
+ alive |= isAliveBefore[offset];
+
+ // Update the liveness before the instruction.
+ if ((~isAliveBefore[offset] & alive) != 0L)
+ {
+ isAliveBefore[offset] = alive;
+
+ // Do we have to check again after this loop?
+ checkAgain |= offset < maxOffset(partialEvaluator.branchOrigins(offset));
+ }
+ }
+ }
+
+ // Account for the liveness at the start of the exception handlers.
+ codeAttribute.exceptionsAccept(clazz, method, this);
+ }
+ while (checkAgain);
+
+ // Loop over all instructions, to mark variables that take up two entries.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ if (partialEvaluator.isTraced(offset))
+ {
+ // Loop over all variables.
+ for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
+ {
+ // Is the variable alive and a category 2 type?
+ if (isAliveBefore(offset, variableIndex))
+ {
+ Value value = partialEvaluator.getVariablesBefore(offset).getValue(variableIndex);
+ if (value != null && value.isCategory2())
+ {
+ // Mark it as such.
+ setCategory2(offset, variableIndex, true);
+
+ // Mark the next variable as well.
+ setAliveBefore(offset, variableIndex + 1, true);
+ setCategory2( offset, variableIndex + 1, true);
+ }
+ }
+
+ // Is the variable alive and a category 2 type?
+ if (isAliveAfter(offset, variableIndex))
+ {
+ Value value = partialEvaluator.getVariablesAfter(offset).getValue(variableIndex);
+ if (value != null && value.isCategory2())
+ {
+ // Mark it as such.
+ setCategory2(offset, variableIndex, true);
+
+ // Mark the next variable as well.
+ setAliveAfter(offset, variableIndex + 1, true);
+ setCategory2( offset, variableIndex + 1, true);
+ }
+ }
+ }
+ }
+ }
+
+ if (DEBUG)
+ {
+ // Loop over all instructions.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ if (partialEvaluator.isTraced(offset))
+ {
+ long aliveBefore = isAliveBefore[offset];
+ long aliveAfter = isAliveAfter[offset];
+ long category2 = isCategory2[offset];
+
+ // Print out the liveness of all variables before the instruction.
+ for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
+ {
+ long variableMask = (1L << variableIndex);
+ System.out.print((aliveBefore & variableMask) == 0L ? '.' :
+ (category2 & variableMask) == 0L ? 'x' :
+ '*');
+ }
+
+ // Print out the instruction itself.
+ System.out.println(" "+ InstructionFactory.create(codeAttribute.code, offset).toString(offset));
+
+ // Print out the liveness of all variables after the instruction.
+ for (int variableIndex = 0; variableIndex < variablesSize; variableIndex++)
+ {
+ long variableMask = (1L << variableIndex);
+ System.out.print((aliveAfter & variableMask) == 0L ? '.' :
+ (category2 & variableMask) == 0L ? 'x' :
+ '=');
+ }
+
+ System.out.println();
+ }
+ }
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ int variableIndex = variableInstruction.variableIndex;
+ if (variableIndex < MAX_VARIABLES_SIZE)
+ {
+ long livenessMask = 1L << variableIndex;
+
+ // Is it a load instruction or a store instruction?
+ if (variableInstruction.isLoad())
+ {
+ // Start marking the variable before the load instruction.
+ alive |= livenessMask;
+ }
+ else
+ {
+ // Stop marking the variable before the store instruction.
+ alive &= ~livenessMask;
+
+ // But do mark the variable right after the store instruction.
+ isAliveAfter[offset] |= livenessMask;
+ }
+ }
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Special case: variable 0 ('this') in an initializer has to be alive
+ // as long as it hasn't been initialized.
+ if (offset == partialEvaluator.superInitializationOffset())
+ {
+ alive |= 1L;
+ }
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ // Are any variables alive at the start of the handler?
+ long alive = isAliveBefore[exceptionInfo.u2handlerPC];
+ if (alive != 0L)
+ {
+ // Set the same liveness flags for the entire try block.
+ int startOffset = exceptionInfo.u2startPC;
+ int endOffset = exceptionInfo.u2endPC;
+
+ for (int offset = startOffset; offset < endOffset; offset++)
+ {
+ if (partialEvaluator.isTraced(offset))
+ {
+ if ((~(isAliveBefore[offset] & isAliveAfter[offset]) & alive) != 0L)
+ {
+ isAliveBefore[offset] |= alive;
+ isAliveAfter[offset] |= alive;
+
+ // Check again after having marked this try block.
+ checkAgain = true;
+ }
+ }
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Initializes the global arrays.
+ */
+ private void initializeArrays(CodeAttribute codeAttribute)
+ {
+ int codeLength = codeAttribute.u4codeLength;
+
+ // Create new arrays for storing information at each instruction offset.
+ if (isAliveBefore.length < codeLength)
+ {
+ isAliveBefore = new long[codeLength];
+ isAliveAfter = new long[codeLength];
+ isCategory2 = new long[codeLength];
+ }
+ else
+ {
+ for (int index = 0; index < codeLength; index++)
+ {
+ isAliveBefore[index] = 0L;
+ isAliveAfter[index] = 0L;
+ isCategory2[index] = 0L;
+ }
+ }
+ }
+
+
+ /**
+ * Returns the combined liveness mask of the variables right before the
+ * specified instruction offsets.
+ */
+ private long combinedLiveness(InstructionOffsetValue instructionOffsetValue)
+ {
+ long alive = 0L;
+
+ int count = instructionOffsetValue.instructionOffsetCount();
+ for (int index = 0; index < count; index++)
+ {
+ alive |= isAliveBefore[instructionOffsetValue.instructionOffset(index)];
+ }
+
+ return alive;
+ }
+
+
+ /**
+ * Returns the minimum offset from the given instruction offsets.
+ */
+ private int minOffset(Value instructionOffsets)
+ {
+ return minOffset(instructionOffsets, Integer.MAX_VALUE);
+ }
+
+
+ /**
+ * Returns the minimum offset from the given instruction offsets.
+ */
+ private int minOffset(Value instructionOffsets, int minOffset)
+ {
+ if (instructionOffsets != null)
+ {
+ InstructionOffsetValue instructionOffsetValue =
+ instructionOffsets.instructionOffsetValue();
+
+ int count = instructionOffsetValue.instructionOffsetCount();
+ for (int index = 0; index < count; index++)
+ {
+ int offset = instructionOffsetValue.instructionOffset(index);
+ if (minOffset > offset)
+ {
+ minOffset = offset;
+ }
+ }
+ }
+
+ return minOffset;
+ }
+
+
+ /**
+ * Returns the maximum offset from the given instruction offsets.
+ */
+ private int maxOffset(Value instructionOffsets)
+ {
+ return maxOffset(instructionOffsets, Integer.MIN_VALUE);
+ }
+
+
+ /**
+ * Returns the maximum offset from the given instruction offsets.
+ */
+ private int maxOffset(Value instructionOffsets, int maxOffset)
+ {
+ if (instructionOffsets != null)
+ {
+ InstructionOffsetValue instructionOffsetValue =
+ instructionOffsets.instructionOffsetValue();
+
+ int count = instructionOffsetValue.instructionOffsetCount();
+ for (int index = 0; index < count; index++)
+ {
+ int offset = instructionOffsetValue.instructionOffset(index);
+ if (maxOffset < offset)
+ {
+ maxOffset = offset;
+ }
+ }
+ }
+
+ return maxOffset;
+ }
+}
diff --git a/src/proguard/optimize/evaluation/LoadingInvocationUnit.java b/src/proguard/optimize/evaluation/LoadingInvocationUnit.java
new file mode 100644
index 000000000..d6baa67cd
--- /dev/null
+++ b/src/proguard/optimize/evaluation/LoadingInvocationUnit.java
@@ -0,0 +1,195 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.RefConstant;
+import proguard.evaluation.BasicInvocationUnit;
+import proguard.evaluation.value.*;
+
+/**
+ * This InvocationUbit loads parameter values and return values that were
+ * previously stored with the methods that are invoked.
+ *
+ * @see StoringInvocationUnit
+ * @author Eric Lafortune
+ */
+public class LoadingInvocationUnit
+extends BasicInvocationUnit
+{
+ private final boolean loadFieldValues;
+ private final boolean loadMethodParameterValues;
+ private final boolean loadMethodReturnValues;
+
+
+ /**
+ * Creates a new LoadingInvocationUnit with the given value factory.
+ */
+ public LoadingInvocationUnit(ValueFactory valueFactory)
+ {
+ this(valueFactory, false, false, false);
+ }
+
+
+ /**
+ * Creates a new LoadingInvocationUnit with the given value factory, for
+ * loading the specified values.
+ */
+ public LoadingInvocationUnit(ValueFactory valueFactory,
+ boolean loadFieldValues,
+ boolean loadMethodParameterValues,
+ boolean loadMethodReturnValues)
+ {
+ super(valueFactory);
+
+ this.loadFieldValues = loadFieldValues;
+ this.loadMethodParameterValues = loadMethodParameterValues;
+ this.loadMethodReturnValues = loadMethodReturnValues;
+ }
+
+
+ // Implementations for BasicInvocationUnit.
+
+ protected Value getFieldClassValue(Clazz clazz,
+ RefConstant refConstant,
+ String type)
+ {
+ if (loadFieldValues)
+ {
+ // Do we know this field?
+ Member referencedMember = refConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ // Retrieve the stored field class value.
+ ReferenceValue value = StoringInvocationUnit.getFieldClassValue((Field)referencedMember);
+ if (value != null &&
+ value.isParticular())
+ {
+ return value;
+ }
+ }
+ }
+
+ return super.getFieldClassValue(clazz, refConstant, type);
+ }
+
+
+ protected Value getFieldValue(Clazz clazz,
+ RefConstant refConstant,
+ String type)
+ {
+ if (loadFieldValues)
+ {
+ // Do we know this field?
+ Member referencedMember = refConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ // Retrieve the stored field value.
+ Value value = StoringInvocationUnit.getFieldValue((Field)referencedMember);
+ if (value != null &&
+ value.isParticular())
+ {
+ return value;
+ }
+ }
+ }
+
+ return super.getFieldValue(clazz, refConstant, type);
+ }
+
+
+ protected Value getMethodParameterValue(Clazz clazz,
+ Method method,
+ int parameterIndex,
+ String type,
+ Clazz referencedClass)
+ {
+ if (loadMethodParameterValues)
+ {
+ // Retrieve the stored method parameter value.
+ Value value = StoringInvocationUnit.getMethodParameterValue(method, parameterIndex);
+ if (value != null &&
+ value.isParticular())
+ {
+ return value;
+ }
+ }
+
+ return super.getMethodParameterValue(clazz,
+ method,
+ parameterIndex,
+ type,
+ referencedClass);
+ }
+
+
+ protected Value getMethodReturnValue(Clazz clazz,
+ RefConstant refConstant,
+ String type)
+ {
+ if (loadMethodReturnValues)
+ {
+ // Do we know this method?
+ Member referencedMember = refConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ // Retrieve the stored method return value.
+ Value value = StoringInvocationUnit.getMethodReturnValue((Method)referencedMember);
+ if (value != null &&
+ value.isParticular())
+ {
+ return value;
+ }
+ }
+ }
+
+ return super.getMethodReturnValue(clazz,
+ refConstant,
+ type);
+ }
+
+
+// // Small utility methods.
+//
+// private Value refresh(Value value)
+// {
+// if (value.isParticular())
+// {
+// return value;
+// }
+//
+// switch (value.computationalType())
+// {
+// case Value.TYPE_INTEGER: return valueFactory.createIntegerValue();
+// case Value.TYPE_LONG: return valueFactory.createLongValue();
+// case Value.TYPE_FLOAT: return valueFactory.createFloatValue();
+// case Value.TYPE_DOUBLE: return valueFactory.createDoubleValue();
+// default:
+// {
+// ReferenceValue referenceValue = value.referenceValue();
+//
+// return valueFactory.createReferenceValue(referenceValue.getType(),
+// referenceValue.getReferencedClass(),
+// referenceValue.isNull() != Value.NEVER);
+// }
+// }
+// }
+}
diff --git a/src/proguard/optimize/evaluation/PartialEvaluator.java b/src/proguard/optimize/evaluation/PartialEvaluator.java
new file mode 100644
index 000000000..6a5bedf6e
--- /dev/null
+++ b/src/proguard/optimize/evaluation/PartialEvaluator.java
@@ -0,0 +1,1275 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.instruction.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.evaluation.*;
+import proguard.evaluation.value.*;
+import proguard.optimize.peephole.BranchTargetFinder;
+
+import java.util.Arrays;
+
+/**
+ * This AttributeVisitor performs partial evaluation on the code attributes
+ * that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class PartialEvaluator
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ ExceptionInfoVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ private static final boolean DEBUG_RESULTS = false;
+ /*/
+ private static boolean DEBUG = true;
+ private static boolean DEBUG_RESULTS = true;
+ //*/
+
+ private static final int MAXIMUM_EVALUATION_COUNT = 5;
+
+ public static final int NONE = -2;
+ public static final int AT_METHOD_ENTRY = -1;
+ public static final int AT_CATCH_ENTRY = -1;
+
+ private final ValueFactory valueFactory;
+ private final InvocationUnit invocationUnit;
+ private final boolean evaluateAllCode;
+
+ private InstructionOffsetValue[] branchOriginValues = new InstructionOffsetValue[ClassConstants.TYPICAL_CODE_LENGTH];
+ private InstructionOffsetValue[] branchTargetValues = new InstructionOffsetValue[ClassConstants.TYPICAL_CODE_LENGTH];
+ private TracedVariables[] variablesBefore = new TracedVariables[ClassConstants.TYPICAL_CODE_LENGTH];
+ private TracedStack[] stacksBefore = new TracedStack[ClassConstants.TYPICAL_CODE_LENGTH];
+ private TracedVariables[] variablesAfter = new TracedVariables[ClassConstants.TYPICAL_CODE_LENGTH];
+ private TracedStack[] stacksAfter = new TracedStack[ClassConstants.TYPICAL_CODE_LENGTH];
+ private boolean[] generalizedContexts = new boolean[ClassConstants.TYPICAL_CODE_LENGTH];
+ private int[] evaluationCounts = new int[ClassConstants.TYPICAL_CODE_LENGTH];
+ private boolean evaluateExceptions;
+
+ private final BasicBranchUnit branchUnit;
+ private final BranchTargetFinder branchTargetFinder;
+
+ private final java.util.Stack callingInstructionBlockStack;
+ private final java.util.Stack instructionBlockStack = new java.util.Stack();
+
+
+ /**
+ * Creates a simple PartialEvaluator.
+ */
+ public PartialEvaluator()
+ {
+ this(new ValueFactory(),
+ new BasicInvocationUnit(new ValueFactory()),
+ true);
+ }
+
+
+ /**
+ * Creates a new PartialEvaluator.
+ * @param valueFactory the value factory that will create all values
+ * during evaluation.
+ * @param invocationUnit the invocation unit that will handle all
+ * communication with other fields and methods.
+ * @param evaluateAllCode a flag that specifies whether all branch targets
+ * and exception handlers should be evaluated,
+ * even if they are unreachable.
+ */
+ public PartialEvaluator(ValueFactory valueFactory,
+ InvocationUnit invocationUnit,
+ boolean evaluateAllCode)
+ {
+ this(valueFactory,
+ invocationUnit,
+ evaluateAllCode,
+ evaluateAllCode ?
+ new BasicBranchUnit() :
+ new TracedBranchUnit(),
+ new BranchTargetFinder(),
+ null);
+ }
+
+
+ /**
+ * Creates a new PartialEvaluator, based on an existing one.
+ * @param partialEvaluator the subroutine calling partial evaluator.
+ */
+ private PartialEvaluator(PartialEvaluator partialEvaluator)
+ {
+ this(partialEvaluator.valueFactory,
+ partialEvaluator.invocationUnit,
+ partialEvaluator.evaluateAllCode,
+ partialEvaluator.branchUnit,
+ partialEvaluator.branchTargetFinder,
+ partialEvaluator.instructionBlockStack);
+ }
+
+
+ /**
+ * Creates a new PartialEvaluator.
+ * @param valueFactory the value factory that will create all
+ * values during evaluation.
+ * @param invocationUnit the invocation unit that will handle all
+ * communication with other fields and methods.
+ * @param evaluateAllCode a flag that specifies whether all branch
+ * targets and exception handlers should be
+ * evaluated, even if they are unreachable.
+ * @param branchUnit the branch unit that will handle all
+ * branches.
+ * @param branchTargetFinder the utility class that will find all
+ * branches.
+ */
+ private PartialEvaluator(ValueFactory valueFactory,
+ InvocationUnit invocationUnit,
+ boolean evaluateAllCode,
+ BasicBranchUnit branchUnit,
+ BranchTargetFinder branchTargetFinder,
+ java.util.Stack callingInstructionBlockStack)
+ {
+ this.valueFactory = valueFactory;
+ this.invocationUnit = invocationUnit;
+ this.evaluateAllCode = evaluateAllCode;
+ this.branchUnit = branchUnit;
+ this.branchTargetFinder = branchTargetFinder;
+ this.callingInstructionBlockStack = callingInstructionBlockStack == null ?
+ this.instructionBlockStack :
+ callingInstructionBlockStack;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG = DEBUG_RESULTS =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // TODO: Remove this when the partial evaluator has stabilized.
+ // Catch any unexpected exceptions from the actual visiting method.
+ try
+ {
+ // Process the code.
+ visitCodeAttribute0(clazz, method, codeAttribute);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while performing partial evaluation:");
+ System.err.println(" Class = ["+clazz.getName()+"]");
+ System.err.println(" Method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+
+ if (DEBUG)
+ {
+ method.accept(clazz, new ClassPrinter());
+
+ System.out.println("Evaluation results:");
+
+ int offset = 0;
+ do
+ {
+ if (isBranchOrExceptionTarget(offset))
+ {
+ System.out.println("Branch target from ["+branchOriginValues[offset]+"]:");
+ if (isTraced(offset))
+ {
+ System.out.println(" Vars: "+variablesBefore[offset]);
+ System.out.println(" Stack: "+stacksBefore[offset]);
+ }
+ }
+
+ Instruction instruction = InstructionFactory.create(codeAttribute.code,
+ offset);
+ System.out.println(instruction.toString(offset));
+
+ if (isTraced(offset))
+ {
+ int initializationOffset = branchTargetFinder.initializationOffset(offset);
+ if (initializationOffset != NONE)
+ {
+ System.out.println(" is to be initialized at ["+initializationOffset+"]");
+ }
+
+ InstructionOffsetValue branchTargets = branchTargets(offset);
+ if (branchTargets != null)
+ {
+ System.out.println(" has overall been branching to "+branchTargets);
+ }
+
+ System.out.println(" Vars: "+variablesAfter[offset]);
+ System.out.println(" Stack: "+stacksAfter[offset]);
+ }
+
+ offset += instruction.length(offset);
+ }
+ while (offset < codeAttribute.u4codeLength);
+ }
+
+ throw ex;
+ }
+ }
+
+
+ public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // Evaluate the instructions, starting at the entry point.
+ if (DEBUG)
+ {
+ System.out.println();
+ System.out.println("Partial evaluation: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ System.out.println(" Max locals = "+codeAttribute.u2maxLocals);
+ System.out.println(" Max stack = "+codeAttribute.u2maxStack);
+ }
+
+ // Reuse the existing variables and stack objects, ensuring the right size.
+ TracedVariables variables = new TracedVariables(codeAttribute.u2maxLocals);
+ TracedStack stack = new TracedStack(codeAttribute.u2maxStack);
+
+ // Initialize the reusable arrays and variables.
+ initializeArrays(codeAttribute);
+ initializeParameters(clazz, method, codeAttribute, variables);
+
+ // Find all instruction offsets,...
+ codeAttribute.accept(clazz, method, branchTargetFinder);
+
+ // Start executing the first instruction block.
+ evaluateInstructionBlockAndExceptionHandlers(clazz,
+ method,
+ codeAttribute,
+ variables,
+ stack,
+ 0,
+ codeAttribute.u4codeLength);
+
+ if (DEBUG_RESULTS)
+ {
+ System.out.println("Evaluation results:");
+
+ int offset = 0;
+ do
+ {
+ if (isBranchOrExceptionTarget(offset))
+ {
+ System.out.println("Branch target from ["+branchOriginValues[offset]+"]:");
+ if (isTraced(offset))
+ {
+ System.out.println(" Vars: "+variablesBefore[offset]);
+ System.out.println(" Stack: "+stacksBefore[offset]);
+ }
+ }
+
+ Instruction instruction = InstructionFactory.create(codeAttribute.code,
+ offset);
+ System.out.println(instruction.toString(offset));
+
+ if (isTraced(offset))
+ {
+ int initializationOffset = branchTargetFinder.initializationOffset(offset);
+ if (initializationOffset != NONE)
+ {
+ System.out.println(" is to be initialized at ["+initializationOffset+"]");
+ }
+
+ InstructionOffsetValue branchTargets = branchTargets(offset);
+ if (branchTargets != null)
+ {
+ System.out.println(" has overall been branching to "+branchTargets);
+ }
+
+ System.out.println(" Vars: "+variablesAfter[offset]);
+ System.out.println(" Stack: "+stacksAfter[offset]);
+ }
+
+ offset += instruction.length(offset);
+ }
+ while (offset < codeAttribute.u4codeLength);
+ }
+ }
+
+
+ /**
+ * Returns whether a block of instructions is ever used.
+ */
+ public boolean isTraced(int startOffset, int endOffset)
+ {
+ for (int index = startOffset; index < endOffset; index++)
+ {
+ if (isTraced(index))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset has ever been
+ * executed during the partial evaluation.
+ */
+ public boolean isTraced(int instructionOffset)
+ {
+ return evaluationCounts[instructionOffset] > 0;
+ }
+
+
+ /**
+ * Returns whether there is an instruction at the given offset.
+ */
+ public boolean isInstruction(int instructionOffset)
+ {
+ return branchTargetFinder.isInstruction(instructionOffset);
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset is the target of a
+ * branch instruction or an exception.
+ */
+ public boolean isBranchOrExceptionTarget(int instructionOffset)
+ {
+ return branchTargetFinder.isBranchTarget(instructionOffset) ||
+ branchTargetFinder.isExceptionHandler(instructionOffset);
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset is the start of a
+ * subroutine.
+ */
+ public boolean isSubroutineStart(int instructionOffset)
+ {
+ return branchTargetFinder.isSubroutineStart(instructionOffset);
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset is a subroutine
+ * invocation.
+ */
+ public boolean isSubroutineInvocation(int instructionOffset)
+ {
+ return branchTargetFinder.isSubroutineInvocation(instructionOffset);
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset is part of a
+ * subroutine.
+ */
+ public boolean isSubroutine(int instructionOffset)
+ {
+ return branchTargetFinder.isSubroutine(instructionOffset);
+ }
+
+
+ /**
+ * Returns whether the subroutine at the given offset is ever returning
+ * by means of a regular 'ret' instruction.
+ */
+ public boolean isSubroutineReturning(int instructionOffset)
+ {
+ return branchTargetFinder.isSubroutineReturning(instructionOffset);
+ }
+
+
+ /**
+ * Returns the offset after the subroutine that starts at the given
+ * offset.
+ */
+ public int subroutineEnd(int instructionOffset)
+ {
+ return branchTargetFinder.subroutineEnd(instructionOffset);
+ }
+
+
+ /**
+ * Returns the instruction offset at which the object instance that is
+ * created at the given 'new' instruction offset is initialized, or
+ * NONE
if it is not being created.
+ */
+ public int initializationOffset(int instructionOffset)
+ {
+ return branchTargetFinder.initializationOffset(instructionOffset);
+ }
+
+
+ /**
+ * Returns whether the method is an instance initializer.
+ */
+ public boolean isInitializer()
+ {
+ return branchTargetFinder.isInitializer();
+ }
+
+
+ /**
+ * Returns the instruction offset at which this initializer is calling
+ * the "super" or "this" initializer method, or NONE
if it is
+ * not an initializer.
+ */
+ public int superInitializationOffset()
+ {
+ return branchTargetFinder.superInitializationOffset();
+ }
+
+
+ /**
+ * Returns the offset of the 'new' instruction that corresponds to the
+ * invocation of the instance initializer at the given offset, or
+ * AT_METHOD_ENTRY
if the invocation is calling the "super" or
+ * "this" initializer method, , or NONE
if it is not a 'new'
+ * instruction.
+ */
+ public int creationOffset(int offset)
+ {
+ return branchTargetFinder.creationOffset(offset);
+ }
+
+
+ /**
+ * Returns the variables before execution of the instruction at the given
+ * offset.
+ */
+ public TracedVariables getVariablesBefore(int instructionOffset)
+ {
+ return variablesBefore[instructionOffset];
+ }
+
+
+ /**
+ * Returns the variables after execution of the instruction at the given
+ * offset.
+ */
+ public TracedVariables getVariablesAfter(int instructionOffset)
+ {
+ return variablesAfter[instructionOffset];
+ }
+
+
+ /**
+ * Returns the stack before execution of the instruction at the given
+ * offset.
+ */
+ public TracedStack getStackBefore(int instructionOffset)
+ {
+ return stacksBefore[instructionOffset];
+ }
+
+
+ /**
+ * Returns the stack after execution of the instruction at the given
+ * offset.
+ */
+ public TracedStack getStackAfter(int instructionOffset)
+ {
+ return stacksAfter[instructionOffset];
+ }
+
+
+ /**
+ * Returns the instruction offsets that branch to the given instruction
+ * offset.
+ */
+ public InstructionOffsetValue branchOrigins(int instructionOffset)
+ {
+ return branchOriginValues[instructionOffset];
+ }
+
+
+ /**
+ * Returns the instruction offsets to which the given instruction offset
+ * branches.
+ */
+ public InstructionOffsetValue branchTargets(int instructionOffset)
+ {
+ return branchTargetValues[instructionOffset];
+ }
+
+
+ // Utility methods to evaluate instruction blocks.
+
+ /**
+ * Pushes block of instructions to be executed in the calling partial
+ * evaluator.
+ */
+ private void pushCallingInstructionBlock(TracedVariables variables,
+ TracedStack stack,
+ int startOffset)
+ {
+ callingInstructionBlockStack.push(new MyInstructionBlock(variables,
+ stack,
+ startOffset));
+ }
+
+
+ /**
+ * Pushes block of instructions to be executed in this partial evaluator.
+ */
+ private void pushInstructionBlock(TracedVariables variables,
+ TracedStack stack,
+ int startOffset)
+ {
+ instructionBlockStack.push(new MyInstructionBlock(variables,
+ stack,
+ startOffset));
+ }
+
+
+ /**
+ * Evaluates the instruction block and the exception handlers covering the
+ * given instruction range in the given code.
+ */
+ private void evaluateInstructionBlockAndExceptionHandlers(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ TracedVariables variables,
+ TracedStack stack,
+ int startOffset,
+ int endOffset)
+ {
+ evaluateInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ variables,
+ stack,
+ startOffset);
+
+ evaluateExceptionHandlers(clazz,
+ method,
+ codeAttribute,
+ startOffset,
+ endOffset);
+ }
+
+
+ /**
+ * Evaluates a block of instructions, starting at the given offset and ending
+ * at a branch instruction, a return instruction, or a throw instruction.
+ */
+ private void evaluateInstructionBlock(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ TracedVariables variables,
+ TracedStack stack,
+ int startOffset)
+ {
+ // Execute the initial instruction block.
+ evaluateSingleInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ variables,
+ stack,
+ startOffset);
+
+ // Execute all resulting instruction blocks on the execution stack.
+ while (!instructionBlockStack.empty())
+ {
+ if (DEBUG) System.out.println("Popping alternative branch out of "+instructionBlockStack.size()+" blocks");
+
+ MyInstructionBlock instructionBlock =
+ (MyInstructionBlock)instructionBlockStack.pop();
+
+ evaluateSingleInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ instructionBlock.variables,
+ instructionBlock.stack,
+ instructionBlock.startOffset);
+ }
+ }
+
+
+ /**
+ * Evaluates a block of instructions, starting at the given offset and ending
+ * at a branch instruction, a return instruction, or a throw instruction.
+ * Instruction blocks that are to be evaluated as a result are pushed on
+ * the given stack.
+ */
+ private void evaluateSingleInstructionBlock(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ TracedVariables variables,
+ TracedStack stack,
+ int startOffset)
+ {
+ byte[] code = codeAttribute.code;
+
+ if (DEBUG)
+ {
+ System.out.println("Instruction block starting at ["+startOffset+"] in "+
+ ClassUtil.externalFullMethodDescription(clazz.getName(),
+ 0,
+ method.getName(clazz),
+ method.getDescriptor(clazz)));
+ System.out.println("Init vars: "+variables);
+ System.out.println("Init stack: "+stack);
+ }
+
+ Processor processor = new Processor(variables,
+ stack,
+ valueFactory,
+ branchUnit,
+ invocationUnit);
+
+ int instructionOffset = startOffset;
+
+ int maxOffset = startOffset;
+
+ // Evaluate the subsequent instructions.
+ while (true)
+ {
+ if (maxOffset < instructionOffset)
+ {
+ maxOffset = instructionOffset;
+ }
+
+ // Maintain a generalized local variable frame and stack at this
+ // instruction offset, before execution.
+ int evaluationCount = evaluationCounts[instructionOffset];
+ if (evaluationCount == 0)
+ {
+ // First time we're passing by this instruction.
+ if (variablesBefore[instructionOffset] == null)
+ {
+ // There's not even a context at this index yet.
+ variablesBefore[instructionOffset] = new TracedVariables(variables);
+ stacksBefore[instructionOffset] = new TracedStack(stack);
+ }
+ else
+ {
+ // Reuse the context objects at this index.
+ variablesBefore[instructionOffset].initialize(variables);
+ stacksBefore[instructionOffset].copy(stack);
+ }
+
+ // We'll execute in the generalized context, because it is
+ // the same as the current context.
+ generalizedContexts[instructionOffset] = true;
+ }
+ else
+ {
+ // Merge in the current context.
+ boolean variablesChanged = variablesBefore[instructionOffset].generalize(variables, true);
+ boolean stackChanged = stacksBefore[instructionOffset].generalize(stack);
+
+ //System.out.println("GVars: "+variablesBefore[instructionOffset]);
+ //System.out.println("GStack: "+stacksBefore[instructionOffset]);
+
+ // Bail out if the current context is the same as last time.
+ if (!variablesChanged &&
+ !stackChanged &&
+ generalizedContexts[instructionOffset])
+ {
+ if (DEBUG) System.out.println("Repeated variables, stack, and branch targets");
+
+ break;
+ }
+
+ // See if this instruction has been evaluated an excessive number
+ // of times.
+ if (evaluationCount >= MAXIMUM_EVALUATION_COUNT)
+ {
+ if (DEBUG) System.out.println("Generalizing current context after "+evaluationCount+" evaluations");
+
+ // Continue, but generalize the current context.
+ // Note that the most recent variable values have to remain
+ // last in the generalizations, for the sake of the ret
+ // instruction.
+ variables.generalize(variablesBefore[instructionOffset], false);
+ stack.generalize(stacksBefore[instructionOffset]);
+
+ // We'll execute in the generalized context.
+ generalizedContexts[instructionOffset] = true;
+ }
+ else
+ {
+ // We'll execute in the current context.
+ generalizedContexts[instructionOffset] = false;
+ }
+ }
+
+ // We'll evaluate this instruction.
+ evaluationCounts[instructionOffset]++;
+
+ // Remember this instruction's offset with any stored value.
+ Value storeValue = new InstructionOffsetValue(instructionOffset);
+ variables.setProducerValue(storeValue);
+ stack.setProducerValue(storeValue);
+
+ // Reset the trace value.
+ InstructionOffsetValue traceValue = InstructionOffsetValue.EMPTY_VALUE;
+
+ // Note that the instruction is only volatile.
+ Instruction instruction = InstructionFactory.create(code, instructionOffset);
+
+ // By default, the next instruction will be the one after this
+ // instruction.
+ int nextInstructionOffset = instructionOffset +
+ instruction.length(instructionOffset);
+ InstructionOffsetValue nextInstructionOffsetValue = new InstructionOffsetValue(nextInstructionOffset);
+ branchUnit.resetCalled();
+ branchUnit.setTraceBranchTargets(nextInstructionOffsetValue);
+
+ if (DEBUG)
+ {
+ System.out.println(instruction.toString(instructionOffset));
+ }
+
+ try
+ {
+ // Process the instruction. The processor may modify the
+ // variables and the stack, and it may call the branch unit
+ // and the invocation unit.
+ instruction.accept(clazz,
+ method,
+ codeAttribute,
+ instructionOffset,
+ processor);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while evaluating instruction:");
+ System.err.println(" Class = ["+clazz.getName()+"]");
+ System.err.println(" Method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ System.err.println(" Instruction = "+instruction.toString(instructionOffset));
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+
+ throw ex;
+ }
+
+ // Collect the branch targets from the branch unit.
+ InstructionOffsetValue branchTargets = branchUnit.getTraceBranchTargets();
+ int branchTargetCount = branchTargets.instructionOffsetCount();
+
+ // Stop tracing.
+ branchUnit.setTraceBranchTargets(traceValue);
+
+ if (DEBUG)
+ {
+ if (branchUnit.wasCalled())
+ {
+ System.out.println(" is branching to "+branchTargets);
+ }
+ if (branchTargetValues[instructionOffset] != null)
+ {
+ System.out.println(" has up till now been branching to "+branchTargetValues[instructionOffset]);
+ }
+
+ System.out.println(" Vars: "+variables);
+ System.out.println(" Stack: "+stack);
+ }
+
+ // Maintain a generalized local variable frame and stack at this
+ // instruction offset, after execution.
+ if (evaluationCount == 0)
+ {
+ // First time we're passing by this instruction.
+ if (variablesAfter[instructionOffset] == null)
+ {
+ // There's not even a context at this index yet.
+ variablesAfter[instructionOffset] = new TracedVariables(variables);
+ stacksAfter[instructionOffset] = new TracedStack(stack);
+ }
+ else
+ {
+ // Reuse the context objects at this index.
+ variablesAfter[instructionOffset].initialize(variables);
+ stacksAfter[instructionOffset].copy(stack);
+ }
+ }
+ else
+ {
+ // Merge in the current context.
+ variablesAfter[instructionOffset].generalize(variables, true);
+ stacksAfter[instructionOffset].generalize(stack);
+ }
+
+ // Did the branch unit get called?
+ if (branchUnit.wasCalled())
+ {
+ // Accumulate the branch targets at this offset.
+ branchTargetValues[instructionOffset] = branchTargetValues[instructionOffset] == null ?
+ branchTargets :
+ branchTargetValues[instructionOffset].generalize(branchTargets).instructionOffsetValue();
+
+ // Are there no branch targets at all?
+ if (branchTargetCount == 0)
+ {
+ // Exit from this code block.
+ break;
+ }
+
+ // Accumulate the branch origins at the branch target offsets.
+ InstructionOffsetValue instructionOffsetValue = new InstructionOffsetValue(instructionOffset);
+ for (int index = 0; index < branchTargetCount; index++)
+ {
+ int branchTarget = branchTargets.instructionOffset(index);
+ branchOriginValues[branchTarget] = branchOriginValues[branchTarget] == null ?
+ instructionOffsetValue:
+ branchOriginValues[branchTarget].generalize(instructionOffsetValue).instructionOffsetValue();
+ }
+
+ // Are there multiple branch targets?
+ if (branchTargetCount > 1)
+ {
+ // Push them on the execution stack and exit from this block.
+ for (int index = 0; index < branchTargetCount; index++)
+ {
+ if (DEBUG) System.out.println("Pushing alternative branch #"+index+" out of "+branchTargetCount+", from ["+instructionOffset+"] to ["+branchTargets.instructionOffset(index)+"]");
+
+ pushInstructionBlock(new TracedVariables(variables),
+ new TracedStack(stack),
+ branchTargets.instructionOffset(index));
+ }
+
+ break;
+ }
+
+ if (DEBUG) System.out.println("Definite branch from ["+instructionOffset+"] to ["+branchTargets.instructionOffset(0)+"]");
+ }
+
+ // Just continue with the next instruction.
+ instructionOffset = branchTargets.instructionOffset(0);
+
+ // Is this a subroutine invocation?
+ if (instruction.opcode == InstructionConstants.OP_JSR ||
+ instruction.opcode == InstructionConstants.OP_JSR_W)
+ {
+ // Evaluate the subroutine in another partial evaluator.
+ evaluateSubroutine(clazz,
+ method,
+ codeAttribute,
+ variables,
+ stack,
+ instructionOffset,
+ instructionBlockStack);
+
+ break;
+ }
+ else if (instruction.opcode == InstructionConstants.OP_RET)
+ {
+ // Let the partial evaluator that has called the subroutine
+ // handle the evaluation after the return.
+ pushCallingInstructionBlock(new TracedVariables(variables),
+ new TracedStack(stack),
+ instructionOffset);
+ break;
+ }
+ }
+
+ if (DEBUG) System.out.println("Ending processing of instruction block starting at ["+startOffset+"]");
+ }
+
+
+ /**
+ * Evaluates a subroutine and its exception handlers, starting at the given
+ * offset and ending at a subroutine return instruction.
+ */
+ private void evaluateSubroutine(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ TracedVariables variables,
+ TracedStack stack,
+ int subroutineStart,
+ java.util.Stack instructionBlockStack)
+ {
+ int subroutineEnd = branchTargetFinder.subroutineEnd(subroutineStart);
+
+ if (DEBUG) System.out.println("Evaluating subroutine from "+subroutineStart+" to "+subroutineEnd);
+
+ // Create a temporary partial evaluator, so there are no conflicts
+ // with variables that are alive across subroutine invocations, between
+ // different invocations.
+ PartialEvaluator subroutinePartialEvaluator =
+ new PartialEvaluator(this);
+
+ subroutinePartialEvaluator.initializeArrays(codeAttribute);
+
+ // Evaluate the subroutine.
+ subroutinePartialEvaluator.evaluateInstructionBlockAndExceptionHandlers(clazz,
+ method,
+ codeAttribute,
+ variables,
+ stack,
+ subroutineStart,
+ subroutineEnd);
+
+ // Merge back the temporary partial evaluator. This way, we'll get
+ // the lowest common denominator of stacks and variables.
+ generalize(subroutinePartialEvaluator, 0, codeAttribute.u4codeLength);
+
+ if (DEBUG) System.out.println("Ending subroutine from "+subroutineStart+" to "+subroutineEnd);
+ }
+
+
+ /**
+ * Generalizes the results of this partial evaluator with those of another
+ * given partial evaluator, over a given range of instructions.
+ */
+ private void generalize(PartialEvaluator other,
+ int codeStart,
+ int codeEnd)
+ {
+ if (DEBUG) System.out.println("Generalizing with temporary partial evaluation");
+
+ for (int offset = codeStart; offset < codeEnd; offset++)
+ {
+ if (other.branchOriginValues[offset] != null)
+ {
+ branchOriginValues[offset] = branchOriginValues[offset] == null ?
+ other.branchOriginValues[offset] :
+ branchOriginValues[offset].generalize(other.branchOriginValues[offset]).instructionOffsetValue();
+ }
+
+ if (other.isTraced(offset))
+ {
+ if (other.branchTargetValues[offset] != null)
+ {
+ branchTargetValues[offset] = branchTargetValues[offset] == null ?
+ other.branchTargetValues[offset] :
+ branchTargetValues[offset].generalize(other.branchTargetValues[offset]).instructionOffsetValue();
+ }
+
+ if (evaluationCounts[offset] == 0)
+ {
+ variablesBefore[offset] = other.variablesBefore[offset];
+ stacksBefore[offset] = other.stacksBefore[offset];
+ variablesAfter[offset] = other.variablesAfter[offset];
+ stacksAfter[offset] = other.stacksAfter[offset];
+ generalizedContexts[offset] = other.generalizedContexts[offset];
+ evaluationCounts[offset] = other.evaluationCounts[offset];
+ }
+ else
+ {
+ variablesBefore[offset].generalize(other.variablesBefore[offset], false);
+ stacksBefore[offset] .generalize(other.stacksBefore[offset]);
+ variablesAfter[offset] .generalize(other.variablesAfter[offset], false);
+ stacksAfter[offset] .generalize(other.stacksAfter[offset]);
+ //generalizedContexts[offset]
+ evaluationCounts[offset] += other.evaluationCounts[offset];
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Evaluates the exception handlers covering and targeting the given
+ * instruction range in the given code.
+ */
+ private void evaluateExceptionHandlers(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ int startOffset,
+ int endOffset)
+ {
+ if (DEBUG) System.out.println("Evaluating exceptions covering ["+startOffset+" -> "+endOffset+"]:");
+
+ ExceptionHandlerFilter exceptionEvaluator =
+ new ExceptionHandlerFilter(startOffset,
+ endOffset,
+ this);
+
+ // Evaluate the exception catch blocks, until their entry variables
+ // have stabilized.
+ do
+ {
+ // Reset the flag to stop evaluating.
+ evaluateExceptions = false;
+
+ // Evaluate all relevant exception catch blocks once.
+ codeAttribute.exceptionsAccept(clazz,
+ method,
+ startOffset,
+ endOffset,
+ exceptionEvaluator);
+ }
+ while (evaluateExceptions);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ int startPC = exceptionInfo.u2startPC;
+ int endPC = exceptionInfo.u2endPC;
+
+ // Do we have to evaluate this exception catch block?
+ if (isTraced(startPC, endPC))
+ {
+ int handlerPC = exceptionInfo.u2handlerPC;
+ int catchType = exceptionInfo.u2catchType;
+
+ if (DEBUG) System.out.println("Evaluating exception ["+startPC +" -> "+endPC +": "+handlerPC+"]:");
+
+ // Reuse the existing variables and stack objects, ensuring the
+ // right size.
+ TracedVariables variables = new TracedVariables(codeAttribute.u2maxLocals);
+ TracedStack stack = new TracedStack(codeAttribute.u2maxStack);
+
+ // Initialize the trace values.
+ Value storeValue = new InstructionOffsetValue(AT_CATCH_ENTRY);
+ variables.setProducerValue(storeValue);
+ stack.setProducerValue(storeValue);
+
+ // Initialize the variables by generalizing the variables of the
+ // try block. Make sure to include the results of the last
+ // instruction for preverification.
+ generalizeVariables(startPC,
+ endPC,
+ evaluateAllCode,
+ variables);
+
+ // Initialize the the stack.
+ //stack.push(valueFactory.createReference((ClassConstant)((ProgramClass)clazz).getConstant(exceptionInfo.u2catchType), false));
+ String catchClassName = catchType != 0 ?
+ clazz.getClassName(catchType) :
+ ClassConstants.INTERNAL_NAME_JAVA_LANG_THROWABLE;
+
+ Clazz catchClass = catchType != 0 ?
+ ((ClassConstant)((ProgramClass)clazz).getConstant(catchType)).referencedClass :
+ null;
+
+ stack.push(valueFactory.createReferenceValue(catchClassName,
+ catchClass,
+ false));
+
+ int evaluationCount = evaluationCounts[handlerPC];
+
+ // Evaluate the instructions, starting at the entry point.
+ evaluateInstructionBlock(clazz,
+ method,
+ codeAttribute,
+ variables,
+ stack,
+ handlerPC);
+
+ // Remember to evaluate all exception handlers once more.
+ if (!evaluateExceptions)
+ {
+ evaluateExceptions = evaluationCount < evaluationCounts[handlerPC];
+ }
+ }
+// else if (evaluateAllCode)
+// {
+// if (DEBUG) System.out.println("No information for partial evaluation of exception ["+startPC +" -> "+endPC +": "+exceptionInfo.u2handlerPC+"] yet");
+//
+// // We don't have any information on the try block yet, but we do
+// // have to evaluate the exception handler.
+// // Remember to evaluate all exception handlers once more.
+// evaluateExceptions = true;
+// }
+ else
+ {
+ if (DEBUG) System.out.println("No information for partial evaluation of exception ["+startPC +" -> "+endPC +": "+exceptionInfo.u2handlerPC+"]");
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Initializes the data structures for the variables, stack, etc.
+ */
+ private void initializeArrays(CodeAttribute codeAttribute)
+ {
+ int codeLength = codeAttribute.u4codeLength;
+
+ // Create new arrays for storing information at each instruction offset.
+ if (variablesAfter.length < codeLength)
+ {
+ // Create new arrays.
+ branchOriginValues = new InstructionOffsetValue[codeLength];
+ branchTargetValues = new InstructionOffsetValue[codeLength];
+ variablesBefore = new TracedVariables[codeLength];
+ stacksBefore = new TracedStack[codeLength];
+ variablesAfter = new TracedVariables[codeLength];
+ stacksAfter = new TracedStack[codeLength];
+ generalizedContexts = new boolean[codeLength];
+ evaluationCounts = new int[codeLength];
+ }
+ else
+ {
+ // Reset the arrays.
+ Arrays.fill(branchOriginValues, null);
+ Arrays.fill(branchTargetValues, null);
+ Arrays.fill(generalizedContexts, false);
+ Arrays.fill(evaluationCounts, 0);
+
+ for (int index = 0; index < codeLength; index++)
+ {
+ if (variablesBefore[index] != null)
+ {
+ variablesBefore[index].reset(codeAttribute.u2maxLocals);
+ }
+
+ if (stacksBefore[index] != null)
+ {
+ stacksBefore[index].reset(codeAttribute.u2maxStack);
+ }
+
+ if (variablesAfter[index] != null)
+ {
+ variablesAfter[index].reset(codeAttribute.u2maxLocals);
+ }
+
+ if (stacksAfter[index] != null)
+ {
+ stacksAfter[index].reset(codeAttribute.u2maxStack);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Initializes the data structures for the variables, stack, etc.
+ */
+ private void initializeParameters(Clazz clazz,
+ Method method,
+ CodeAttribute codeAttribute,
+ TracedVariables variables)
+ {
+ // Create the method parameters.
+ TracedVariables parameters = new TracedVariables(codeAttribute.u2maxLocals);
+
+ // Remember this instruction's offset with any stored value.
+ Value storeValue = new InstructionOffsetValue(AT_METHOD_ENTRY);
+ parameters.setProducerValue(storeValue);
+
+ // Initialize the method parameters.
+ invocationUnit.enterMethod(clazz, method, parameters);
+
+ if (DEBUG)
+ {
+ System.out.println(" Params: "+parameters);
+ }
+
+ // Initialize the variables with the parameters.
+ variables.initialize(parameters);
+
+ // Set the store value of each parameter variable.
+ InstructionOffsetValue atMethodEntry = new InstructionOffsetValue(AT_METHOD_ENTRY);
+
+ for (int index = 0; index < parameters.size(); index++)
+ {
+ variables.setProducerValue(index, atMethodEntry);
+ }
+ }
+
+
+ /**
+ * Generalize the local variable frames of a block of instructions.
+ */
+ private void generalizeVariables(int startOffset,
+ int endOffset,
+ boolean includeAfterLastInstruction,
+ TracedVariables generalizedVariables)
+ {
+ boolean first = true;
+ int lastIndex = -1;
+
+ // Generalize the variables before each of the instructions in the block.
+ for (int index = startOffset; index < endOffset; index++)
+ {
+ if (isTraced(index))
+ {
+ TracedVariables tracedVariables = variablesBefore[index];
+
+ if (first)
+ {
+ // Initialize the variables with the first traced local
+ // variable frame.
+ generalizedVariables.initialize(tracedVariables);
+
+ first = false;
+ }
+ else
+ {
+ // Generalize the variables with the traced local variable
+ // frame. We can't use the return value, because local
+ // generalization can be different a couple of times,
+ // with the global generalization being the same.
+ generalizedVariables.generalize(tracedVariables, false);
+ }
+
+ lastIndex = index;
+ }
+ }
+
+ // Generalize the variables after the last instruction in the block,
+ // if required.
+ if (includeAfterLastInstruction &&
+ lastIndex >= 0)
+ {
+ TracedVariables tracedVariables = variablesAfter[lastIndex];
+
+ if (first)
+ {
+ // Initialize the variables with the local variable frame.
+ generalizedVariables.initialize(tracedVariables);
+ }
+ else
+ {
+ // Generalize the variables with the local variable frame.
+ generalizedVariables.generalize(tracedVariables, false);
+ }
+ }
+
+ // Just clear the variables if there aren't any traced instructions
+ // in the block.
+ if (first)
+ {
+ generalizedVariables.reset(generalizedVariables.size());
+ }
+ }
+
+
+ private static class MyInstructionBlock
+ {
+ private TracedVariables variables;
+ private TracedStack stack;
+ private int startOffset;
+
+
+ private MyInstructionBlock(TracedVariables variables,
+ TracedStack stack,
+ int startOffset)
+ {
+ this.variables = variables;
+ this.stack = stack;
+ this.startOffset = startOffset;
+ }
+ }
+}
diff --git a/src/proguard/optimize/evaluation/StoringInvocationUnit.java b/src/proguard/optimize/evaluation/StoringInvocationUnit.java
new file mode 100644
index 000000000..846f6857a
--- /dev/null
+++ b/src/proguard/optimize/evaluation/StoringInvocationUnit.java
@@ -0,0 +1,207 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.RefConstant;
+import proguard.evaluation.BasicInvocationUnit;
+import proguard.evaluation.value.*;
+import proguard.optimize.info.*;
+
+/**
+ * This InvocationUbit stores parameter values and return values with the
+ * methods that are invoked.
+ *
+ * @see LoadingInvocationUnit
+ * @author Eric Lafortune
+ */
+public class StoringInvocationUnit
+extends BasicInvocationUnit
+{
+ private boolean storeFieldValues;
+ private boolean storeMethodParameterValues;
+ private boolean storeMethodReturnValues;
+
+
+ /**
+ * Creates a new StoringInvocationUnit with the given value factory.
+ */
+ public StoringInvocationUnit(ValueFactory valueFactory)
+ {
+ this(valueFactory, true, true, true);
+ }
+
+
+ /**
+ * Creates a new StoringInvocationUnit with the given value factory, for
+ * storing the specified values.
+ */
+ public StoringInvocationUnit(ValueFactory valueFactory,
+ boolean storeFieldValues,
+ boolean storeMethodParameterValues,
+ boolean storeMethodReturnValues)
+ {
+ super(valueFactory);
+
+ this.storeFieldValues = storeFieldValues;
+ this.storeMethodParameterValues = storeMethodParameterValues;
+ this.storeMethodReturnValues = storeMethodReturnValues;
+ }
+
+
+ // Implementations for BasicInvocationUnit.
+
+ protected void setFieldClassValue(Clazz clazz,
+ RefConstant refConstant,
+ ReferenceValue value)
+ {
+ if (storeFieldValues)
+ {
+ Member referencedMember = refConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ generalizeFieldClassValue((Field)referencedMember, value);
+ }
+ }
+ }
+
+
+ protected void setFieldValue(Clazz clazz,
+ RefConstant refConstant,
+ Value value)
+ {
+ if (storeFieldValues)
+ {
+ Member referencedMember = refConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ generalizeFieldValue((Field)referencedMember, value);
+ }
+ }
+ }
+
+
+ protected void setMethodParameterValue(Clazz clazz,
+ RefConstant refConstant,
+ int parameterIndex,
+ Value value)
+ {
+ if (storeMethodParameterValues)
+ {
+ Member referencedMember = refConstant.referencedMember;
+ if (referencedMember != null)
+ {
+ generalizeMethodParameterValue((Method)referencedMember,
+ parameterIndex,
+ value);
+ }
+ }
+ }
+
+
+ protected void setMethodReturnValue(Clazz clazz,
+ Method method,
+ Value value)
+ {
+ if (storeMethodReturnValues)
+ {
+ generalizeMethodReturnValue(method, value);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private static void generalizeFieldClassValue(Field field, ReferenceValue value)
+ {
+ FieldOptimizationInfo info = FieldOptimizationInfo.getFieldOptimizationInfo(field);
+ if (info != null)
+ {
+ info.generalizeReferencedClass(value);
+ }
+ }
+
+
+ public static ReferenceValue getFieldClassValue(Field field)
+ {
+ FieldOptimizationInfo info = FieldOptimizationInfo.getFieldOptimizationInfo(field);
+ return info != null ?
+ info.getReferencedClass() :
+ null;
+ }
+
+
+ private static void generalizeFieldValue(Field field, Value value)
+ {
+ FieldOptimizationInfo info = FieldOptimizationInfo.getFieldOptimizationInfo(field);
+ if (info != null)
+ {
+ info.generalizeValue(value);
+ }
+ }
+
+
+ public static Value getFieldValue(Field field)
+ {
+ FieldOptimizationInfo info = FieldOptimizationInfo.getFieldOptimizationInfo(field);
+ return info != null ?
+ info.getValue() :
+ null;
+ }
+
+
+ private static void generalizeMethodParameterValue(Method method, int parameterIndex, Value value)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.generalizeParameter(parameterIndex, value);
+ }
+ }
+
+
+ public static Value getMethodParameterValue(Method method, int parameterIndex)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info != null ?
+ info.getParameter(parameterIndex) :
+ null;
+ }
+
+
+ private static void generalizeMethodReturnValue(Method method, Value value)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.generalizeReturnValue(value);
+ }
+ }
+
+
+ public static Value getMethodReturnValue(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info != null ?
+ info.getReturnValue() :
+ null;
+ }
+}
diff --git a/src/proguard/optimize/evaluation/TracedBranchUnit.java b/src/proguard/optimize/evaluation/TracedBranchUnit.java
new file mode 100644
index 000000000..e6acf6f2c
--- /dev/null
+++ b/src/proguard/optimize/evaluation/TracedBranchUnit.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.Clazz;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.evaluation.BasicBranchUnit;
+import proguard.evaluation.value.Value;
+
+/**
+ * This BranchUnit remembers the branch unit commands that are invoked on it.
+ *
+ * @author Eric Lafortune
+ */
+class TracedBranchUnit
+extends BasicBranchUnit
+{
+ // Implementations for BranchUnit.
+
+ public void branchConditionally(Clazz clazz,
+ CodeAttribute codeAttribute,
+ int offset,
+ int branchTarget,
+ int conditional)
+ {
+ if (conditional == Value.ALWAYS)
+ {
+ // Always branch.
+ super.branch(clazz, codeAttribute, offset, branchTarget);
+ }
+ else if (conditional != Value.NEVER)
+ {
+ // Maybe branch.
+ super.branchConditionally(clazz, codeAttribute, offset, branchTarget, conditional);
+ }
+ else
+ {
+ super.setCalled();
+ }
+ }
+}
diff --git a/src/proguard/optimize/evaluation/VariableOptimizer.java b/src/proguard/optimize/evaluation/VariableOptimizer.java
new file mode 100644
index 000000000..73efddc0f
--- /dev/null
+++ b/src/proguard/optimize/evaluation/VariableOptimizer.java
@@ -0,0 +1,357 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.evaluation;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.editor.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.classfile.attribute.*;
+import proguard.classfile.util.*;
+
+/**
+ * This AttributeVisitor optimizes variable allocation based on their the liveness,
+ * in the code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableOptimizer
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+ private static final int MAX_VARIABLES_SIZE = 64;
+
+
+ private final boolean reuseThis;
+ private final MemberVisitor extraVariableMemberVisitor;
+
+ private final LivenessAnalyzer livenessAnalyzer = new LivenessAnalyzer();
+ private final VariableRemapper variableRemapper = new VariableRemapper();
+ private VariableCleaner variableCleaner = new VariableCleaner();
+
+ private int[] variableMap = new int[ClassConstants.TYPICAL_VARIABLES_SIZE];
+
+
+ /**
+ * Creates a new VariableOptimizer.
+ * @param reuseThis specifies whether the 'this' variable can be reused.
+ * Many JVMs for JME and IBM's JVMs for JSE can't handle
+ * such reuse.
+ */
+ public VariableOptimizer(boolean reuseThis)
+ {
+ this(reuseThis, null);
+ }
+
+
+ /**
+ * Creates a new VariableOptimizer with an extra visitor.
+ * @param reuseThis specifies whether the 'this' variable
+ * can be reused. Many JVMs for JME and
+ * IBM's JVMs for JSE can't handle such
+ * reuse.
+ * @param extraVariableMemberVisitor an optional extra visitor for all
+ * removed variables.
+ */
+ public VariableOptimizer(boolean reuseThis,
+ MemberVisitor extraVariableMemberVisitor)
+ {
+ this.reuseThis = reuseThis;
+ this.extraVariableMemberVisitor = extraVariableMemberVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // Initialize the global arrays.
+ initializeArrays(codeAttribute);
+
+ // Analyze the liveness of the variables in the code.
+ livenessAnalyzer.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Trim the variables in the local variable tables, because even
+ // clipping the tables individually may leave some inconsistencies
+ // between them.
+ codeAttribute.attributesAccept(clazz, method, this);
+
+ int startIndex =
+ (method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0 ||
+ reuseThis ? 0 : 1;
+
+ int parameterSize =
+ ClassUtil.internalMethodParameterSize(method.getDescriptor(clazz),
+ method.getAccessFlags());
+
+ int variableSize = codeAttribute.u2maxLocals;
+ int codeLength = codeAttribute.u4codeLength;
+
+ boolean remapping = false;
+
+ // Loop over all variables.
+ for (int oldIndex = 0; oldIndex < variableSize; oldIndex++)
+ {
+ // By default, the variable will be mapped onto itself.
+ variableMap[oldIndex] = oldIndex;
+
+ // Only try remapping the variable if it's not a parameter.
+ if (oldIndex >= parameterSize &&
+ oldIndex < MAX_VARIABLES_SIZE)
+ {
+ // Try to remap the variable to a variable with a smaller index.
+ for (int newIndex = startIndex; newIndex < oldIndex; newIndex++)
+ {
+ if (areNonOverlapping(oldIndex, newIndex, codeLength))
+ {
+ variableMap[oldIndex] = newIndex;
+
+ updateLiveness(oldIndex, newIndex, codeLength);
+
+ remapping = true;
+
+ // This variable has been remapped. Go to the next one.
+ break;
+ }
+ }
+ }
+ }
+
+ // Have we been able to remap any variables?
+ if (remapping)
+ {
+ if (DEBUG)
+ {
+ System.out.println("VariableOptimizer: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+ for (int index= 0; index < variableSize; index++)
+ {
+ System.out.println(" v"+index+" -> "+variableMap[index]);
+ }
+ }
+
+ // Remap the variables.
+ variableRemapper.setVariableMap(variableMap);
+ variableRemapper.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Visit the method, if required.
+ if (extraVariableMemberVisitor != null)
+ {
+ method.accept(clazz, extraVariableMemberVisitor);
+ }
+ }
+ else
+ {
+ // Just clean up any empty variables.
+ variableCleaner.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+ }
+
+
+ public void visitLocalVariableTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTableAttribute localVariableTableAttribute)
+ {
+ // Trim the variables in the local variable table.
+ localVariableTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ public void visitLocalVariableTypeTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeTableAttribute localVariableTypeTableAttribute)
+ {
+ // Trim the variables in the local variable type table.
+ localVariableTypeTableAttribute.localVariablesAccept(clazz, method, codeAttribute, this);
+ }
+
+
+ // Implementations for LocalVariableInfoVisitor.
+
+ public void visitLocalVariableInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableInfo localVariableInfo)
+ {
+ // Trim the local variable to the instructions at which it is alive.
+ int variable = localVariableInfo.u2index;
+ int startPC = localVariableInfo.u2startPC;
+ int endPC = startPC + localVariableInfo.u2length;
+
+ startPC = firstLiveness(startPC, endPC, variable);
+ endPC = lastLiveness(startPC, endPC, variable);
+
+ // Leave the start address of unused variables unchanged.
+ int length = endPC - startPC;
+ if (length > 0)
+ {
+ localVariableInfo.u2startPC = startPC;
+ }
+
+ localVariableInfo.u2length = length;
+ }
+
+
+ // Implementations for LocalVariableTypeInfoVisitor.
+
+ public void visitLocalVariableTypeInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, LocalVariableTypeInfo localVariableTypeInfo)
+ {
+ // Trim the local variable type to the instructions at which it is alive.
+ int variable = localVariableTypeInfo.u2index;
+ int startPC = localVariableTypeInfo.u2startPC;
+ int endPC = startPC + localVariableTypeInfo.u2length;
+
+ startPC = firstLiveness(startPC, endPC, variable);
+ endPC = lastLiveness(startPC, endPC, variable);
+
+ // Leave the start address of unused variables unchanged.
+ int length = endPC - startPC;
+ if (length > 0)
+ {
+ localVariableTypeInfo.u2startPC = startPC;
+ }
+
+ localVariableTypeInfo.u2length = length;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Initializes the global arrays.
+ */
+ private void initializeArrays(CodeAttribute codeAttribute)
+ {
+ int codeLength = codeAttribute.u4codeLength;
+
+ // Create new arrays for storing information at each instruction offset.
+ if (variableMap.length < codeLength)
+ {
+ variableMap = new int[codeLength];
+ }
+ }
+
+
+ /**
+ * Returns whether the given variables are never alive at the same time.
+ */
+ private boolean areNonOverlapping(int variableIndex1,
+ int variableIndex2,
+ int codeLength)
+ {
+ // Loop over all instructions.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ if ((livenessAnalyzer.isAliveBefore(offset, variableIndex1) &&
+ livenessAnalyzer.isAliveBefore(offset, variableIndex2)) ||
+
+ (livenessAnalyzer.isAliveAfter(offset, variableIndex1) &&
+ livenessAnalyzer.isAliveAfter(offset, variableIndex2)) ||
+
+ // For now, exclude Category 2 variables.
+ livenessAnalyzer.isCategory2(offset, variableIndex1))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Updates the liveness resulting from mapping the given old variable on
+ * the given new variable.
+ */
+ private void updateLiveness(int oldVariableIndex,
+ int newVariableIndex,
+ int codeLength)
+ {
+ // Loop over all instructions.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ // Update the liveness before the instruction.
+ if (livenessAnalyzer.isAliveBefore(offset, oldVariableIndex))
+ {
+ livenessAnalyzer.setAliveBefore(offset, oldVariableIndex, false);
+ livenessAnalyzer.setAliveBefore(offset, newVariableIndex, true);
+ }
+
+ // Update the liveness after the instruction.
+ if (livenessAnalyzer.isAliveAfter(offset, oldVariableIndex))
+ {
+ livenessAnalyzer.setAliveAfter(offset, oldVariableIndex, false);
+ livenessAnalyzer.setAliveAfter(offset, newVariableIndex, true);
+ }
+ }
+ }
+
+
+ /**
+ * Returns the first instruction offset between the given offsets at which
+ * the given variable goes alive.
+ */
+ private int firstLiveness(int startOffset, int endOffset, int variableIndex)
+ {
+ for (int offset = startOffset; offset < endOffset; offset++)
+ {
+ if (livenessAnalyzer.isTraced(offset) &&
+ livenessAnalyzer.isAliveBefore(offset, variableIndex))
+ {
+ return offset;
+ }
+ }
+
+ return endOffset;
+ }
+
+
+ /**
+ * Returns the last instruction offset between the given offsets before
+ * which the given variable is still alive.
+ */
+ private int lastLiveness(int startOffset, int endOffset, int variableIndex)
+ {
+ int previousOffset = endOffset;
+
+ for (int offset = endOffset-1; offset >= startOffset; offset--)
+ {
+ if (livenessAnalyzer.isTraced(offset))
+ {
+ if (livenessAnalyzer.isAliveBefore(offset, variableIndex))
+ {
+ return previousOffset;
+ }
+
+ previousOffset = offset;
+ }
+ }
+
+ return endOffset;
+ }
+}
diff --git a/src/proguard/optimize/evaluation/package.html b/src/proguard/optimize/evaluation/package.html
new file mode 100644
index 000000000..5341f9f8b
--- /dev/null
+++ b/src/proguard/optimize/evaluation/package.html
@@ -0,0 +1,4 @@
+
+This package contains visitors that perform partial evaluation and subsequent
+optimizations on byte code.
+
diff --git a/src/proguard/optimize/info/AccessMethodMarker.java b/src/proguard/optimize/info/AccessMethodMarker.java
new file mode 100644
index 000000000..e4c8d7c8c
--- /dev/null
+++ b/src/proguard/optimize/info/AccessMethodMarker.java
@@ -0,0 +1,202 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This InstructionVisitor marks the types of class accesses and class member
+ * accesses of the methods whose instructions it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class AccessMethodMarker
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor,
+ ClassVisitor,
+ MemberVisitor
+{
+ private Method invokingMethod;
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ invokingMethod = method;
+
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ // Check the referenced class or class member, if any.
+ stringConstant.referencedClassAccept(this);
+ stringConstant.referencedMemberAccept(this);
+ }
+
+
+ public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
+ {
+ // Check the bootstrap method.
+ invokeDynamicConstant.bootstrapMethodHandleAccept(clazz, this);
+ }
+
+
+ public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
+ {
+ // Check the method reference.
+ clazz.constantPoolEntryAccept(methodHandleConstant.u2referenceIndex, this);
+ }
+
+
+ public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ // Check the referenced class.
+ clazz.constantPoolEntryAccept(refConstant.u2classIndex, this);
+
+ // Check the referenced class member itself.
+ refConstant.referencedClassAccept(this);
+ refConstant.referencedMemberAccept(this);
+ }
+
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ // Check the referenced class.
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitAnyClass(Clazz clazz)
+ {
+ int accessFlags = clazz.getAccessFlags();
+
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PUBLIC) == 0)
+ {
+ setAccessesPackageCode(invokingMethod);
+ }
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz clazz, Member member)
+ {
+ int accessFlags = member.getAccessFlags();
+
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_PRIVATE) != 0)
+ {
+ setAccessesPrivateCode(invokingMethod);
+ }
+ else if ((accessFlags & ClassConstants.INTERNAL_ACC_PROTECTED) != 0)
+ {
+ setAccessesProtectedCode(invokingMethod);
+ }
+ else if ((accessFlags & ClassConstants.INTERNAL_ACC_PUBLIC) == 0)
+ {
+ setAccessesPackageCode(invokingMethod);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private static void setAccessesPrivateCode(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.setAccessesPrivateCode();
+ }
+ }
+
+
+ /**
+ * Returns whether the given method accesses private class members.
+ */
+ public static boolean accessesPrivateCode(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info == null || info.accessesPrivateCode();
+ }
+
+
+ private static void setAccessesPackageCode(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.setAccessesPackageCode();
+ }
+ }
+
+
+ /**
+ * Returns whether the given method accesses package visible classes or class
+ * members.
+ */
+ public static boolean accessesPackageCode(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info == null || info.accessesPackageCode();
+ }
+
+
+ private static void setAccessesProtectedCode(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.setAccessesProtectedCode();
+ }
+ }
+
+
+ /**
+ * Returns whether the given method accesses protected class members.
+ */
+ public static boolean accessesProtectedCode(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info == null || info.accessesProtectedCode();
+ }
+}
diff --git a/src/proguard/optimize/info/BackwardBranchMarker.java b/src/proguard/optimize/info/BackwardBranchMarker.java
new file mode 100644
index 000000000..07bfefb6b
--- /dev/null
+++ b/src/proguard/optimize/info/BackwardBranchMarker.java
@@ -0,0 +1,90 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This InstructionVisitor marks all methods that branch backward in any of the
+ * instructions that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class BackwardBranchMarker
+extends SimplifiedVisitor
+implements InstructionVisitor
+{
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ markBackwardBranch(method, branchInstruction.branchOffset);
+ }
+
+
+ public void visitAnySwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SwitchInstruction switchInstruction)
+ {
+ markBackwardBranch(method, switchInstruction.defaultOffset);
+
+ for (int index = 0; index < switchInstruction.jumpOffsets.length; index++)
+ {
+ markBackwardBranch(method, switchInstruction.jumpOffsets[index]);
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Marks the given method if the given branch offset is negative.
+ */
+ private void markBackwardBranch(Method method, int branchOffset)
+ {
+ if (branchOffset < 0)
+ {
+ setBranchesBackward(method);
+ }
+ }
+
+
+ private static void setBranchesBackward(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.setBranchesBackward();
+ }
+ }
+
+
+ public static boolean branchesBackward(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info == null || info.branchesBackward();
+ }
+}
diff --git a/src/proguard/optimize/info/CatchExceptionMarker.java b/src/proguard/optimize/info/CatchExceptionMarker.java
new file mode 100644
index 000000000..8f87a08bd
--- /dev/null
+++ b/src/proguard/optimize/info/CatchExceptionMarker.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor marks all methods that catch exceptions.
+ *
+ * @author Eric Lafortune
+ */
+public class CatchExceptionMarker
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (codeAttribute.u2exceptionTableLength > 0)
+ {
+ markCatchException(method);
+ }
+ }
+
+
+ // Small utility methods.
+
+ private static void markCatchException(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.setCatchesExceptions();
+ }
+ }
+
+
+ public static boolean catchesExceptions(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info == null ||
+ info.catchesExceptions();
+ }
+}
diff --git a/src/proguard/optimize/info/CaughtClassFilter.java b/src/proguard/optimize/info/CaughtClassFilter.java
new file mode 100644
index 000000000..762e7de96
--- /dev/null
+++ b/src/proguard/optimize/info/CaughtClassFilter.java
@@ -0,0 +1,63 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor delegates all its method calls to another ClassVisitor,
+ * but only for Clazz objects that are caught as exceptions.
+ *
+ * @see CaughtClassMarker
+ * @author Eric Lafortune
+ */
+public class CaughtClassFilter
+implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ public CaughtClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (CaughtClassMarker.isCaught(programClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (CaughtClassMarker.isCaught(libraryClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/CaughtClassMarker.java b/src/proguard/optimize/info/CaughtClassMarker.java
new file mode 100644
index 000000000..1752f0c0c
--- /dev/null
+++ b/src/proguard/optimize/info/CaughtClassMarker.java
@@ -0,0 +1,64 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor marks all program classes that it visits as caught.
+ * This means that these classes are exception classes that occur in exception
+ * handlers.
+ *
+ * @author Eric Lafortune
+ */
+public class CaughtClassMarker
+implements ClassVisitor
+{
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ setCaught(programClass);
+ }
+
+
+ // Small utility methods.
+
+ private static void setCaught(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ if (info != null)
+ {
+ info.setCaught();
+ }
+ }
+
+
+ public static boolean isCaught(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ return info == null || info.isCaught();
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/ClassOptimizationInfo.java b/src/proguard/optimize/info/ClassOptimizationInfo.java
new file mode 100644
index 000000000..dbe041ee0
--- /dev/null
+++ b/src/proguard/optimize/info/ClassOptimizationInfo.java
@@ -0,0 +1,165 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.Clazz;
+
+/**
+ * This class stores some optimization information that can be attached to
+ * a class.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassOptimizationInfo
+{
+ private boolean isInstantiated = false;
+ private boolean isInstanceofed = false;
+ private boolean isDotClassed = false;
+ private boolean isCaught = false;
+ private boolean containsStaticInitializer = false;
+ private boolean containsPackageVisibleMembers = false;
+ private boolean invokesPackageVisibleMembers = false;
+ private Clazz targetClass;
+
+
+ public void setInstantiated()
+ {
+ isInstantiated = true;
+ }
+
+
+ public boolean isInstantiated()
+ {
+ return isInstantiated;
+ }
+
+
+ public void setInstanceofed()
+ {
+ isInstanceofed = true;
+ }
+
+
+ public boolean isInstanceofed()
+ {
+ return isInstanceofed;
+ }
+
+
+ public void setDotClassed()
+ {
+ isDotClassed = true;
+ }
+
+
+ public boolean isDotClassed()
+ {
+ return isDotClassed;
+ }
+
+
+ public void setCaught()
+ {
+ isCaught = true;
+ }
+
+
+ public boolean isCaught()
+ {
+ return isCaught;
+ }
+
+
+ public void setContainsStaticInitializer()
+ {
+ containsStaticInitializer = true;
+ }
+
+
+ public boolean containsStaticInitializer()
+ {
+ return containsStaticInitializer;
+ }
+
+
+ public void setContainsPackageVisibleMembers()
+ {
+ containsPackageVisibleMembers = true;
+ }
+
+
+ public boolean containsPackageVisibleMembers()
+ {
+ return containsPackageVisibleMembers;
+ }
+
+
+ public void setInvokesPackageVisibleMembers()
+ {
+ invokesPackageVisibleMembers = true;
+ }
+
+
+ public boolean invokesPackageVisibleMembers()
+ {
+ return invokesPackageVisibleMembers;
+ }
+
+
+ public void setTargetClass(Clazz targetClass)
+ {
+ this.targetClass = targetClass;
+ }
+
+
+ public Clazz getTargetClass()
+ {
+ return targetClass;
+ }
+
+
+ public void merge(ClassOptimizationInfo other)
+ {
+ this.isInstantiated |= other.isInstantiated;
+ this.isInstanceofed |= other.isInstanceofed;
+ this.isDotClassed |= other.isDotClassed;
+ this.isCaught |= other.isCaught;
+ this.containsStaticInitializer |= other.containsStaticInitializer;
+ this.containsPackageVisibleMembers |= other.containsPackageVisibleMembers;
+ this.invokesPackageVisibleMembers |= other.invokesPackageVisibleMembers;
+ }
+
+
+ public static void setClassOptimizationInfo(Clazz clazz)
+ {
+ clazz.setVisitorInfo(new ClassOptimizationInfo());
+ }
+
+
+ public static ClassOptimizationInfo getClassOptimizationInfo(Clazz clazz)
+ {
+ Object visitorInfo = clazz.getVisitorInfo();
+
+ return visitorInfo instanceof ClassOptimizationInfo ?
+ (ClassOptimizationInfo)visitorInfo :
+ null;
+ }
+}
diff --git a/src/proguard/optimize/info/ClassOptimizationInfoSetter.java b/src/proguard/optimize/info/ClassOptimizationInfoSetter.java
new file mode 100644
index 000000000..f3d78e258
--- /dev/null
+++ b/src/proguard/optimize/info/ClassOptimizationInfoSetter.java
@@ -0,0 +1,47 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+import proguard.optimize.KeepMarker;
+
+/**
+ * This ClassVisitor attaches a ClassOptimizationInfo instance to every class
+ * that is not being kept that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassOptimizationInfoSetter
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ // Implementations for MemberVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (!KeepMarker.isKept(programClass))
+ {
+ ClassOptimizationInfo.setClassOptimizationInfo(programClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/DotClassFilter.java b/src/proguard/optimize/info/DotClassFilter.java
new file mode 100644
index 000000000..c3fd87839
--- /dev/null
+++ b/src/proguard/optimize/info/DotClassFilter.java
@@ -0,0 +1,63 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor delegates all its method calls to another ClassVisitor,
+ * but only for Clazz objects that are used in a .class construct.
+ *
+ * @see DotClassMarker
+ * @author Eric Lafortune
+ */
+public class DotClassFilter
+implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ public DotClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (DotClassMarker.isDotClassed(programClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (DotClassMarker.isDotClassed(libraryClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/DotClassMarker.java b/src/proguard/optimize/info/DotClassMarker.java
new file mode 100644
index 000000000..ef5cfd1fe
--- /dev/null
+++ b/src/proguard/optimize/info/DotClassMarker.java
@@ -0,0 +1,96 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This InstructionVisitor marks all classes that are used in a .class
+ * construct by any of the instructions that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class DotClassMarker
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor,
+ ClassVisitor
+{
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ if (constantInstruction.opcode == InstructionConstants.OP_LDC ||
+ constantInstruction.opcode == InstructionConstants.OP_LDC_W)
+ {
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ setDotClassed(programClass);
+ }
+
+
+ // Small utility methods.
+
+ private static void setDotClassed(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ if (info != null)
+ {
+ info.setDotClassed();
+ }
+ }
+
+
+ public static boolean isDotClassed(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ return info == null || info.isDotClassed();
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/ExceptionInstructionChecker.java b/src/proguard/optimize/info/ExceptionInstructionChecker.java
new file mode 100644
index 000000000..4bfa96fea
--- /dev/null
+++ b/src/proguard/optimize/info/ExceptionInstructionChecker.java
@@ -0,0 +1,193 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.RefConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This class can tell whether an instruction might throw exceptions.
+ *
+ * @author Eric Lafortune
+ */
+public class ExceptionInstructionChecker
+extends SimplifiedVisitor
+implements InstructionVisitor
+// ConstantVisitor,
+// MemberVisitor
+{
+ // A return value for the visitor methods.
+ private boolean mayThrowExceptions;
+
+
+ /**
+ * Returns whether the given instruction may throw exceptions.
+ */
+ public boolean mayThrowExceptions(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ mayThrowExceptions = false;
+
+ instruction.accept(clazz, method, codeAttribute, offset, this);
+
+ return mayThrowExceptions;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ byte opcode = simpleInstruction.opcode;
+
+ // Check for instructions that may throw exceptions.
+ // Note that monitorexit can not sensibly throw exceptions, except the
+ // broken and deprecated asynchronous ThreadDeath. Removing the
+ // artificial infinite looping exception blocks that recent compilers
+ // add does not strictly follow the JVM specs, but it does have the
+ // additional benefit of avoiding a bug in the JVM in JDK 1.1.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_IDIV:
+ case InstructionConstants.OP_LDIV:
+ case InstructionConstants.OP_IREM:
+ case InstructionConstants.OP_LREM:
+ case InstructionConstants.OP_IALOAD:
+ case InstructionConstants.OP_LALOAD:
+ case InstructionConstants.OP_FALOAD:
+ case InstructionConstants.OP_DALOAD:
+ case InstructionConstants.OP_AALOAD:
+ case InstructionConstants.OP_BALOAD:
+ case InstructionConstants.OP_CALOAD:
+ case InstructionConstants.OP_SALOAD:
+ case InstructionConstants.OP_IASTORE:
+ case InstructionConstants.OP_LASTORE:
+ case InstructionConstants.OP_FASTORE:
+ case InstructionConstants.OP_DASTORE:
+ case InstructionConstants.OP_AASTORE:
+ case InstructionConstants.OP_BASTORE:
+ case InstructionConstants.OP_CASTORE:
+ case InstructionConstants.OP_SASTORE:
+ case InstructionConstants.OP_NEWARRAY:
+ case InstructionConstants.OP_ARRAYLENGTH:
+ case InstructionConstants.OP_ATHROW:
+ case InstructionConstants.OP_MONITORENTER:
+ // These instructions may throw exceptions.
+ mayThrowExceptions = true;
+ }
+
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ byte opcode = constantInstruction.opcode;
+
+ // Check for instructions that may throw exceptions.
+ switch (opcode)
+ {
+ case InstructionConstants.OP_GETSTATIC:
+ case InstructionConstants.OP_PUTSTATIC:
+ case InstructionConstants.OP_GETFIELD:
+ case InstructionConstants.OP_PUTFIELD:
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ case InstructionConstants.OP_INVOKEDYNAMIC:
+ case InstructionConstants.OP_NEW:
+ case InstructionConstants.OP_ANEWARRAY:
+ case InstructionConstants.OP_CHECKCAST:
+ case InstructionConstants.OP_INSTANCEOF:
+ case InstructionConstants.OP_MULTIANEWARRAY:
+ // These instructions may throw exceptions.
+ mayThrowExceptions = true;
+ }
+
+// case InstructionConstants.OP_INVOKEVIRTUAL:
+// case InstructionConstants.OP_INVOKESPECIAL:
+// case InstructionConstants.OP_INVOKESTATIC:
+// case InstructionConstants.OP_INVOKEINTERFACE:
+// // Check if the invoking the method may throw an exception.
+// clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ }
+
+
+// // Implementations for ConstantVisitor.
+//
+// public void visitAnyMethodrefConstant(Clazz clazz, RefConstant refConstant)
+// {
+// Member referencedMember = refConstant.referencedMember;
+//
+// // Do we have a reference to the method?
+// if (referencedMember == null)
+// {
+// // We'll have to assume invoking the unknown method may throw an
+// // an exception.
+// mayThrowExceptions = true;
+// }
+// else
+// {
+// // First check the referenced method itself.
+// refConstant.referencedMemberAccept(this);
+//
+// // If the result isn't conclusive, check down the hierarchy.
+// if (!mayThrowExceptions)
+// {
+// Clazz referencedClass = refConstant.referencedClass;
+// Method referencedMethod = (Method)referencedMember;
+//
+// // Check all other implementations of the method in the class
+// // hierarchy.
+// referencedClass.methodImplementationsAccept(referencedMethod,
+// false,
+// false,
+// true,
+// true,
+// this);
+// }
+// }
+// }
+//
+//
+// // Implementations for MemberVisitor.
+//
+// public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+// {
+// mayThrowExceptions = mayThrowExceptions ||
+// ExceptionMethodMarker.mayThrowExceptions(programMethod);
+// }
+//
+//
+// public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+// {
+// mayThrowExceptions = mayThrowExceptions ||
+// !NoExceptionMethodMarker.doesntThrowExceptions(libraryMethod);
+// }
+}
diff --git a/src/proguard/optimize/info/FieldOptimizationInfo.java b/src/proguard/optimize/info/FieldOptimizationInfo.java
new file mode 100644
index 000000000..0fa916717
--- /dev/null
+++ b/src/proguard/optimize/info/FieldOptimizationInfo.java
@@ -0,0 +1,204 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.util.*;
+import proguard.evaluation.value.*;
+import proguard.evaluation.ConstantValueFactory;
+
+/**
+ * This class stores some optimization information that can be attached to
+ * a field.
+ *
+ * @author Eric Lafortune
+ */
+public class FieldOptimizationInfo
+extends SimplifiedVisitor
+implements AttributeVisitor
+{
+ private static final SpecificValueFactory VALUE_FACTORY = new SpecificValueFactory();
+ private static final ConstantValueFactory CONSTANT_VALUE_FACTORY = new ConstantValueFactory(VALUE_FACTORY);
+
+ private boolean isWritten;
+ private boolean isRead;
+ private boolean canBeMadePrivate = true;
+ private ReferenceValue referencedClass;
+ private Value value;
+
+
+ public FieldOptimizationInfo(Clazz clazz, Field field)
+ {
+ int accessFlags = field.getAccessFlags();
+
+ isWritten =
+ isRead = (accessFlags & ClassConstants.INTERNAL_ACC_VOLATILE) != 0;
+
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_STATIC) != 0)
+ {
+ // See if we can initialize the static field with a constant value.
+ field.accept(clazz, new AllAttributeVisitor(this));
+ }
+
+ if ((accessFlags & ClassConstants.INTERNAL_ACC_FINAL) == 0 &&
+ value == null)
+ {
+ // Otherwise initialize the non-final field with the default value.
+ value = initialValue(field.getDescriptor(clazz));
+ }
+ }
+
+
+ public FieldOptimizationInfo(FieldOptimizationInfo FieldOptimizationInfo)
+ {
+ this.isWritten = FieldOptimizationInfo.isWritten;
+ this.isRead = FieldOptimizationInfo.isRead;
+ this.canBeMadePrivate = FieldOptimizationInfo.canBeMadePrivate;
+ this.referencedClass = FieldOptimizationInfo.referencedClass;
+ this.value = FieldOptimizationInfo.value;
+ }
+
+
+ public void setWritten()
+ {
+ isWritten = true;
+ }
+
+
+ public boolean isWritten()
+ {
+ return isWritten;
+ }
+
+
+ public void setRead()
+ {
+ isRead = true;
+ }
+
+
+ public boolean isRead()
+ {
+ return isRead;
+ }
+
+
+ public void setCanNotBeMadePrivate()
+ {
+ canBeMadePrivate = false;
+ }
+
+
+ public boolean canBeMadePrivate()
+ {
+ return canBeMadePrivate;
+ }
+
+
+ public void generalizeReferencedClass(ReferenceValue referencedClass)
+ {
+ this.referencedClass = this.referencedClass != null ?
+ this.referencedClass.generalize(referencedClass) :
+ referencedClass;
+ }
+
+
+ public ReferenceValue getReferencedClass()
+ {
+ return referencedClass;
+ }
+
+
+ public void generalizeValue(Value value)
+ {
+ this.value = this.value != null ?
+ this.value.generalize(value) :
+ value;
+ }
+
+
+ public Value getValue()
+ {
+ return value;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitConstantValueAttribute(Clazz clazz, Field field, ConstantValueAttribute constantValueAttribute)
+ {
+ // Retrieve the initial static field value.
+ value = CONSTANT_VALUE_FACTORY.constantValue(clazz, constantValueAttribute.u2constantValueIndex);
+ }
+
+
+ // Small utility methods.
+
+ private Value initialValue(String type)
+ {
+ switch (type.charAt(0))
+ {
+ case ClassConstants.INTERNAL_TYPE_BOOLEAN:
+ case ClassConstants.INTERNAL_TYPE_BYTE:
+ case ClassConstants.INTERNAL_TYPE_CHAR:
+ case ClassConstants.INTERNAL_TYPE_SHORT:
+ case ClassConstants.INTERNAL_TYPE_INT:
+ return VALUE_FACTORY.createIntegerValue(0);
+
+ case ClassConstants.INTERNAL_TYPE_LONG:
+ return VALUE_FACTORY.createLongValue(0L);
+
+ case ClassConstants.INTERNAL_TYPE_FLOAT:
+ return VALUE_FACTORY.createFloatValue(0.0f);
+
+ case ClassConstants.INTERNAL_TYPE_DOUBLE:
+ return VALUE_FACTORY.createDoubleValue(0.0);
+
+ case ClassConstants.INTERNAL_TYPE_CLASS_START:
+ case ClassConstants.INTERNAL_TYPE_ARRAY:
+ return VALUE_FACTORY.createReferenceValueNull();
+
+ default:
+ throw new IllegalArgumentException("Invalid type ["+type+"]");
+ }
+ }
+
+
+ public static void setFieldOptimizationInfo(Clazz clazz, Field field)
+ {
+ field.setVisitorInfo(new FieldOptimizationInfo(clazz, field));
+ }
+
+
+ public static FieldOptimizationInfo getFieldOptimizationInfo(Field field)
+ {
+ Object visitorInfo = field.getVisitorInfo();
+
+ return visitorInfo instanceof FieldOptimizationInfo ?
+ (FieldOptimizationInfo)visitorInfo :
+ null;
+ }
+}
diff --git a/src/proguard/optimize/info/InstanceofClassFilter.java b/src/proguard/optimize/info/InstanceofClassFilter.java
new file mode 100644
index 000000000..7cd85bc9f
--- /dev/null
+++ b/src/proguard/optimize/info/InstanceofClassFilter.java
@@ -0,0 +1,63 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor delegates all its method calls to another ClassVisitor,
+ * but only for Clazz objects that are used in an 'instanceof' test.
+ *
+ * @see InstanceofClassMarker
+ * @author Eric Lafortune
+ */
+public class InstanceofClassFilter
+implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ public InstanceofClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (InstanceofClassMarker.isInstanceofed(programClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (InstanceofClassMarker.isInstanceofed(libraryClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/InstanceofClassMarker.java b/src/proguard/optimize/info/InstanceofClassMarker.java
new file mode 100644
index 000000000..96d5bafe1
--- /dev/null
+++ b/src/proguard/optimize/info/InstanceofClassMarker.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This InstructionVisitor marks all classes that are used in an 'instanceof'
+ * test by any of the instructions that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class InstanceofClassMarker
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor,
+ ClassVisitor
+{
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ if (constantInstruction.opcode == InstructionConstants.OP_INSTANCEOF)
+ {
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ setInstanceofed(programClass);
+ }
+
+
+ // Small utility methods.
+
+ private static void setInstanceofed(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ if (info != null)
+ {
+ info.setInstanceofed();
+ }
+ }
+
+
+ public static boolean isInstanceofed(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ return info == null || info.isInstanceofed();
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/InstantiationClassFilter.java b/src/proguard/optimize/info/InstantiationClassFilter.java
new file mode 100644
index 000000000..a659f064e
--- /dev/null
+++ b/src/proguard/optimize/info/InstantiationClassFilter.java
@@ -0,0 +1,62 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor delegates all its method calls to another ClassVisitor,
+ * but only for Clazz objects that are instantiated.
+ *
+ * @author Eric Lafortune
+ */
+public class InstantiationClassFilter
+implements ClassVisitor
+{
+ private final ClassVisitor classVisitor;
+
+
+ public InstantiationClassFilter(ClassVisitor classVisitor)
+ {
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (InstantiationClassMarker.isInstantiated(programClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (InstantiationClassMarker.isInstantiated(libraryClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/InstantiationClassMarker.java b/src/proguard/optimize/info/InstantiationClassMarker.java
new file mode 100644
index 000000000..b4afffdb3
--- /dev/null
+++ b/src/proguard/optimize/info/InstantiationClassMarker.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.ClassConstant;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This InstructionVisitor marks all classes that are instantiated by any of
+ * the instructions that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class InstantiationClassMarker
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor,
+ ClassVisitor
+{
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ if (constantInstruction.opcode == InstructionConstants.OP_NEW)
+ {
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
+ {
+ classConstant.referencedClassAccept(this);
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ setInstantiated(programClass);
+ }
+
+
+ // Small utility methods.
+
+ private static void setInstantiated(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ if (info != null)
+ {
+ info.setInstantiated();
+ }
+ }
+
+
+ public static boolean isInstantiated(Clazz clazz)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ return info == null || info.isInstantiated();
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/info/MemberOptimizationInfoSetter.java b/src/proguard/optimize/info/MemberOptimizationInfoSetter.java
new file mode 100644
index 000000000..3c27c930d
--- /dev/null
+++ b/src/proguard/optimize/info/MemberOptimizationInfoSetter.java
@@ -0,0 +1,59 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.KeepMarker;
+
+/**
+ * This MemberVisitor attaches a FieldOptimizationInfo instance to every field
+ * and a MethodOptimizationInfo instance to every method that is not being kept
+ * that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class MemberOptimizationInfoSetter
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (!KeepMarker.isKept(programField))
+ {
+ FieldOptimizationInfo.setFieldOptimizationInfo(programClass,
+ programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (!KeepMarker.isKept(programMethod))
+ {
+ MethodOptimizationInfo.setMethodOptimizationInfo(programClass,
+ programMethod);
+ }
+ }
+}
diff --git a/src/proguard/optimize/info/MethodInvocationMarker.java b/src/proguard/optimize/info/MethodInvocationMarker.java
new file mode 100644
index 000000000..afb23366c
--- /dev/null
+++ b/src/proguard/optimize/info/MethodInvocationMarker.java
@@ -0,0 +1,107 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This InstructionVisitor counts the number of times methods are invoked from
+ * the instructions that are visited.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodInvocationMarker
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor,
+ MemberVisitor
+{
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
+ {
+ // Mark the referenced method, if any.
+ stringConstant.referencedMemberAccept(this);
+ }
+
+
+ public void visitAnyMethodrefConstant(Clazz clazz, RefConstant refConstant)
+ {
+ // Mark the referenced method.
+ refConstant.referencedMemberAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz Clazz, Member member) {}
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ incrementInvocationCount(programMethod);
+ }
+
+
+ // Small utility methods.
+
+ private static void incrementInvocationCount(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.incrementInvocationCount();
+ }
+ }
+
+
+ /**
+ * Returns the number of times the given method was invoked by the
+ * instructions that were visited.
+ */
+ public static int getInvocationCount(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info != null ? info.getInvocationCount() :
+ Integer.MAX_VALUE;
+ }
+}
diff --git a/src/proguard/optimize/info/MethodOptimizationInfo.java b/src/proguard/optimize/info/MethodOptimizationInfo.java
new file mode 100644
index 000000000..fe754e5b4
--- /dev/null
+++ b/src/proguard/optimize/info/MethodOptimizationInfo.java
@@ -0,0 +1,302 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.evaluation.value.Value;
+
+/**
+ * This class stores some optimization information that can be attached to
+ * a method.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodOptimizationInfo
+{
+ private boolean hasNoSideEffects = false;
+ private boolean hasSideEffects = false;
+ private boolean canBeMadePrivate = true;
+ private boolean catchesExceptions = false;
+ private boolean branchesBackward = false;
+ private boolean invokesSuperMethods = false;
+ private boolean accessesPrivateCode = false;
+ private boolean accessesPackageCode = false;
+ private boolean accessesProtectedCode = false;
+ private int invocationCount = 0;
+ private int parameterSize = 0;
+ private long usedParameters = 0L;
+ private Value[] parameters;
+ private Value returnValue;
+
+
+ /**
+ * Creates a new MethodOptimizationInfo for the given method.
+ */
+ public MethodOptimizationInfo(Clazz clazz, Method method)
+ {
+ // Set up an array of the right size for storing information about the
+ // passed parameters.
+ int parameterCount =
+ ClassUtil.internalMethodParameterCount(method.getDescriptor(clazz));
+
+ if ((method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) == 0)
+ {
+ parameterCount++;
+ }
+
+ if (parameterCount > 0)
+ {
+ parameters = new Value[parameterCount];
+ }
+ }
+
+
+ public void setNoSideEffects()
+ {
+ hasNoSideEffects = true;
+ }
+
+
+ public boolean hasNoSideEffects()
+ {
+ return hasNoSideEffects;
+ }
+
+
+ public void setSideEffects()
+ {
+ hasSideEffects = true;
+ }
+
+
+ public boolean hasSideEffects()
+ {
+ return hasSideEffects;
+ }
+
+
+ public void setCanNotBeMadePrivate()
+ {
+ canBeMadePrivate = false;
+ }
+
+
+ public boolean canBeMadePrivate()
+ {
+ return canBeMadePrivate;
+ }
+
+
+ public void setCatchesExceptions()
+ {
+ catchesExceptions = true;
+ }
+
+
+ public boolean catchesExceptions()
+ {
+ return catchesExceptions;
+ }
+
+
+ public void setBranchesBackward()
+ {
+ branchesBackward = true;
+ }
+
+
+ public boolean branchesBackward()
+ {
+ return branchesBackward;
+ }
+
+
+ public void setInvokesSuperMethods()
+ {
+ invokesSuperMethods = true;
+ }
+
+
+ public boolean invokesSuperMethods()
+ {
+ return invokesSuperMethods;
+ }
+
+
+ public void setAccessesPrivateCode()
+ {
+ accessesPrivateCode = true;
+ }
+
+
+ public boolean accessesPrivateCode()
+ {
+ return accessesPrivateCode;
+ }
+
+
+ public void setAccessesPackageCode()
+ {
+ accessesPackageCode = true;
+ }
+
+
+ public boolean accessesPackageCode()
+ {
+ return accessesPackageCode;
+ }
+
+
+ public void setAccessesProtectedCode()
+ {
+ accessesProtectedCode = true;
+ }
+
+
+ public boolean accessesProtectedCode()
+ {
+ return accessesProtectedCode;
+ }
+
+
+ public void incrementInvocationCount()
+ {
+ invocationCount++;
+ }
+
+
+ public int getInvocationCount()
+ {
+ return invocationCount;
+ }
+
+
+ public void setParameterSize(int parameterSize)
+ {
+ this.parameterSize = parameterSize;
+ }
+
+
+ public int getParameterSize()
+ {
+ return parameterSize;
+ }
+
+
+ public void setParameterUsed(int parameterIndex)
+ {
+ usedParameters |= 1L << parameterIndex;
+ }
+
+
+ public void setUsedParameters(long usedParameters)
+ {
+ this.usedParameters = usedParameters;
+ }
+
+
+ public boolean isParameterUsed(int parameterIndex)
+ {
+ return parameterIndex >= 64 || (usedParameters & (1L << parameterIndex)) != 0;
+ }
+
+
+ public long getUsedParameters()
+ {
+ return usedParameters;
+ }
+
+
+ public void generalizeParameter(int parameterIndex, Value parameter)
+ {
+ parameters[parameterIndex] = parameters[parameterIndex] != null ?
+ parameters[parameterIndex].generalize(parameter) :
+ parameter;
+ }
+
+
+ public Value getParameter(int parameterIndex)
+ {
+ return parameters != null ?
+ parameters[parameterIndex] :
+ null;
+ }
+
+
+ public void generalizeReturnValue(Value returnValue)
+ {
+ this.returnValue = this.returnValue != null ?
+ this.returnValue.generalize(returnValue) :
+ returnValue;
+ }
+
+
+ public Value getReturnValue()
+ {
+ return returnValue;
+ }
+
+
+ public void merge(MethodOptimizationInfo other)
+ {
+ if (other != null)
+ {
+ this.hasNoSideEffects &= other.hasNoSideEffects;
+ this.hasSideEffects |= other.hasSideEffects;
+ //this.canBeMadePrivate &= other.canBeMadePrivate;
+ this.catchesExceptions |= other.catchesExceptions;
+ this.branchesBackward |= other.branchesBackward;
+ this.invokesSuperMethods |= other.invokesSuperMethods;
+ this.accessesPrivateCode |= other.accessesPrivateCode;
+ this.accessesPackageCode |= other.accessesPackageCode;
+ this.accessesProtectedCode |= other.accessesProtectedCode;
+ }
+ else
+ {
+ this.hasNoSideEffects = false;
+ this.hasSideEffects = true;
+ //this.canBeMadePrivate = false;
+ this.catchesExceptions = true;
+ this.branchesBackward = true;
+ this.invokesSuperMethods = true;
+ this.accessesPrivateCode = true;
+ this.accessesPackageCode = true;
+ this.accessesProtectedCode = true;
+ }
+ }
+
+
+ public static void setMethodOptimizationInfo(Clazz clazz, Method method)
+ {
+ MethodLinker.lastMember(method).setVisitorInfo(new MethodOptimizationInfo(clazz, method));
+ }
+
+
+ public static MethodOptimizationInfo getMethodOptimizationInfo(Method method)
+ {
+ Object visitorInfo = MethodLinker.lastMember(method).getVisitorInfo();
+
+ return visitorInfo instanceof MethodOptimizationInfo ?
+ (MethodOptimizationInfo)visitorInfo :
+ null;
+ }
+}
diff --git a/src/proguard/optimize/info/NoSideEffectMethodMarker.java b/src/proguard/optimize/info/NoSideEffectMethodMarker.java
new file mode 100644
index 000000000..bf5ce453c
--- /dev/null
+++ b/src/proguard/optimize/info/NoSideEffectMethodMarker.java
@@ -0,0 +1,91 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This MemberVisitor marks all methods that it visits as not having any side
+ * effects. It will make the SideEffectMethodMarker consider them as such
+ * without further analysis.
+ *
+ * @see SideEffectMethodMarker
+ * @author Eric Lafortune
+ */
+public class NoSideEffectMethodMarker
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ // A visitor info flag to indicate the visitor accepter is being kept,
+ // but that it doesn't have any side effects.
+ public static final Object KEPT_BUT_NO_SIDE_EFFECTS = new Object();
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz Clazz, Member member)
+ {
+ // Ignore any attempts to mark fields.
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ markNoSideEffects(programMethod);
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ markNoSideEffects(libraryMethod);
+ }
+
+
+ // Small utility methods.
+
+ private static void markNoSideEffects(Method method)
+ {
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ if (info != null)
+ {
+ info.setNoSideEffects();
+ }
+ else
+ {
+ MethodLinker.lastMember(method).setVisitorInfo(KEPT_BUT_NO_SIDE_EFFECTS);
+ }
+ }
+
+
+ public static boolean hasNoSideEffects(Method method)
+ {
+ if (MethodLinker.lastVisitorAccepter(method).getVisitorInfo() == KEPT_BUT_NO_SIDE_EFFECTS)
+ {
+ return true;
+ }
+
+ MethodOptimizationInfo info = MethodOptimizationInfo.getMethodOptimizationInfo(method);
+ return info != null &&
+ info.hasNoSideEffects();
+ }
+}
diff --git a/src/proguard/optimize/info/NonPrivateMemberMarker.java b/src/proguard/optimize/info/NonPrivateMemberMarker.java
new file mode 100644
index 000000000..06f8500df
--- /dev/null
+++ b/src/proguard/optimize/info/NonPrivateMemberMarker.java
@@ -0,0 +1,171 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.info;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ClassVisitor marks all class members that can not be made private in the
+ * classes that it visits, and in the classes to which they refer.
+ *
+ * @author Eric Lafortune
+ */
+public class NonPrivateMemberMarker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor,
+ MemberVisitor
+{
+ private final MethodImplementationFilter filteredMethodMarker = new MethodImplementationFilter(this);
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Mark all referenced class members in different classes.
+ programClass.constantPoolEntriesAccept(this);
+
+ // Explicitly mark the NONE
if it is not being created.
+ */
+ public int initializationOffset(int offset)
+ {
+ return initializationOffsets[offset];
+ }
+
+
+ /**
+ * Returns whether the method is an instance initializer, in the
+ * CodeAttribute that was visited most recently.
+ */
+ public boolean isInitializer()
+ {
+ return superInitializationOffset != NONE;
+ }
+
+
+ /**
+ * Returns the instruction offset at which this initializer is calling
+ * the "super" or "this" initializer method, or NONE
if it is
+ * not an initializer.
+ */
+ public int superInitializationOffset()
+ {
+ return superInitializationOffset;
+ }
+
+
+ /**
+ * Returns whether the instruction at the given offset is the special
+ * invocation of an instance initializer, in the CodeAttribute that was
+ * visited most recently.
+ */
+ public boolean isInitializer(int offset)
+ {
+ return creationOffsets[offset] != NONE;
+ }
+
+
+ /**
+ * Returns the offset of the 'new' instruction that corresponds to the
+ * invocation of the instance initializer at the given offset, or
+ * AT_METHOD_ENTRY
if the invocation is calling the "super" or
+ * "this" initializer method, , or NONE
if it is not a 'new'
+ * instruction.
+ */
+ public int creationOffset(int offset)
+ {
+ return creationOffsets[offset];
+ }
+
+
+ /**
+ * Returns whether the method contains subroutines, in the CodeAttribute
+ * that was visited most recently.
+ */
+ public boolean containsSubroutines()
+ {
+ return containsSubroutines;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // Make sure there are sufficiently large arrays.
+ int codeLength = codeAttribute.u4codeLength;
+ if (subroutineStarts.length < codeLength)
+ {
+ // Create new arrays.
+ instructionMarks = new short[codeLength + 1];
+ subroutineStarts = new int[codeLength];
+ subroutineEnds = new int[codeLength];
+ creationOffsets = new int[codeLength];
+ initializationOffsets = new int[codeLength];
+
+ // Reset the arrays.
+ Arrays.fill(subroutineStarts, 0, codeLength, UNKNOWN);
+ Arrays.fill(subroutineEnds, 0, codeLength, UNKNOWN);
+ Arrays.fill(creationOffsets, 0, codeLength, NONE);
+ Arrays.fill(initializationOffsets, 0, codeLength, NONE);
+ }
+ else
+ {
+ // Reset the arrays.
+ Arrays.fill(instructionMarks, 0, codeLength, (short)0);
+ Arrays.fill(subroutineStarts, 0, codeLength, UNKNOWN);
+ Arrays.fill(subroutineEnds, 0, codeLength, UNKNOWN);
+ Arrays.fill(creationOffsets, 0, codeLength, NONE);
+ Arrays.fill(initializationOffsets, 0, codeLength, NONE);
+
+ instructionMarks[codeLength] = 0;
+ }
+
+ superInitializationOffset = NONE;
+ containsSubroutines = false;
+
+ // Iterate until all subroutines have been fully marked.
+ do
+ {
+ repeat = false;
+ currentSubroutineStart = NO_SUBROUTINE;
+ recentCreationOffsetIndex = 0;
+
+ // Initialize the stack of 'new' instruction offsets if this method
+ // is an instance initializer.
+ if (method.getName(clazz).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
+ {
+ recentCreationOffsets[recentCreationOffsetIndex++] = AT_METHOD_ENTRY;
+ }
+
+ // Mark branch targets by going over all instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+ }
+ while (repeat);
+
+ // The end of the code is a branch target sentinel.
+ instructionMarks[codeLength] = BRANCH_TARGET;
+
+ // Mark branch targets in the exception table.
+ codeAttribute.exceptionsAccept(clazz, method, this);
+
+ if (containsSubroutines)
+ {
+ // Set the subroutine returning flag and the subroutine end at each
+ // subroutine start.
+ int previousSubroutineStart = NO_SUBROUTINE;
+
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ if (isInstruction(offset))
+ {
+ int subroutineStart = subroutineStarts[offset];
+
+ if (subroutineStart >= 0 &&
+ isSubroutineReturning(offset))
+ {
+ instructionMarks[subroutineStart] |= SUBROUTINE_RETURNING;
+ }
+
+ if (previousSubroutineStart >= 0)
+ {
+ subroutineEnds[previousSubroutineStart] = offset;
+ }
+
+ previousSubroutineStart = subroutineStart;
+ }
+ }
+
+ if (previousSubroutineStart >= 0)
+ {
+ subroutineEnds[previousSubroutineStart] = codeLength;
+ }
+
+ // Set the subroutine returning flag and the subroutine end at each
+ // subroutine instruction, based on the marks at the subroutine
+ // start.
+ for (int offset = 0; offset < codeLength; offset++)
+ {
+ if (isSubroutine(offset))
+ {
+ int subroutineStart = subroutineStarts[offset];
+
+ if (isSubroutineReturning(subroutineStart))
+ {
+ instructionMarks[offset] |= SUBROUTINE_RETURNING;
+ }
+
+ subroutineEnds[offset] = subroutineEnds[subroutineStart];
+ }
+ }
+ }
+
+ if (DEBUG)
+ {
+ System.out.println();
+ System.out.println("Branch targets: "+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz));
+
+ for (int index = 0; index < codeLength; index++)
+ {
+ if (isInstruction(index))
+ {
+ System.out.println("" +
+ (isBranchOrigin(index) ? 'B' : '-') +
+ (isAfterBranch(index) ? 'b' : '-') +
+ (isBranchTarget(index) ? 'T' : '-') +
+ (isExceptionStart(index) ? 'E' : '-') +
+ (isExceptionEnd(index) ? 'e' : '-') +
+ (isExceptionHandler(index) ? 'H' : '-') +
+ (isSubroutineInvocation(index) ? 'J' : '-') +
+ (isSubroutineStart(index) ? 'S' : '-') +
+ (isSubroutineReturning(index) ? 'r' : '-') +
+ (isSubroutine(index) ? " ["+subroutineStart(index)+" -> "+subroutineEnd(index)+"]" : "") +
+ (isNew(index) ? " ["+initializationOffset(index)+"] " : " ---- ") +
+ InstructionFactory.create(codeAttribute.code, index).toString(index));
+ }
+ }
+ }
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ // Mark the instruction.
+ instructionMarks[offset] |= INSTRUCTION;
+
+ // Check if this is an instruction of a subroutine.
+ checkSubroutine(offset);
+
+ byte opcode = simpleInstruction.opcode;
+ if (opcode == InstructionConstants.OP_IRETURN ||
+ opcode == InstructionConstants.OP_LRETURN ||
+ opcode == InstructionConstants.OP_FRETURN ||
+ opcode == InstructionConstants.OP_DRETURN ||
+ opcode == InstructionConstants.OP_ARETURN ||
+ opcode == InstructionConstants.OP_ATHROW)
+ {
+ // Mark the branch origin.
+ markBranchOrigin(offset);
+
+ // Mark the next instruction.
+ markAfterBranchOrigin(offset + simpleInstruction.length(offset));
+ }
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Mark the instruction.
+ instructionMarks[offset] |= INSTRUCTION;
+
+ // Check if this is an instruction of a subroutine.
+ checkSubroutine(offset);
+
+ // Check if the instruction is a 'new' instruction.
+ if (constantInstruction.opcode == InstructionConstants.OP_NEW)
+ {
+ // Push the 'new' instruction offset on the stack.
+ recentCreationOffsets[recentCreationOffsetIndex++] = offset;
+ }
+ else
+ {
+ // Check if the instruction is an initializer invocation.
+ isInitializer = false;
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+ if (isInitializer)
+ {
+ // Pop the 'new' instruction offset from the stack.
+ int recentCreationOffset = recentCreationOffsets[--recentCreationOffsetIndex];
+
+ // Fill it out in the creation offsets.
+ creationOffsets[offset] = recentCreationOffset;
+
+ // Fill out the initialization offsets.
+ if (recentCreationOffset == AT_METHOD_ENTRY)
+ {
+ superInitializationOffset = offset;
+ }
+ else
+ {
+ initializationOffsets[recentCreationOffset] = offset;
+ }
+ }
+ }
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ // Mark the instruction.
+ instructionMarks[offset] |= INSTRUCTION;
+
+ // Check if this is an instruction of a subroutine.
+ checkSubroutine(offset);
+
+ if (variableInstruction.opcode == InstructionConstants.OP_RET)
+ {
+ // Mark the method.
+ containsSubroutines = true;
+
+ // Mark the branch origin.
+ markBranchOrigin(offset);
+
+ // Mark the subroutine return at its return instruction.
+ instructionMarks[offset] |= SUBROUTINE_RETURNING;
+
+ // Mark the next instruction.
+ markAfterBranchOrigin(offset + variableInstruction.length(offset));
+ }
+ }
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ int branchOffset = branchInstruction.branchOffset;
+ int targetOffset = offset + branchOffset;
+
+ // Mark the branch origin.
+ markBranchOrigin(offset);
+
+ // Check if this is an instruction of a subroutine.
+ checkSubroutine(offset);
+
+ // Mark the branch target.
+ markBranchTarget(offset, branchOffset);
+
+ byte opcode = branchInstruction.opcode;
+ if (opcode == InstructionConstants.OP_JSR ||
+ opcode == InstructionConstants.OP_JSR_W)
+ {
+ // Mark the method.
+ containsSubroutines = true;
+
+ // Mark the subroutine invocation.
+ instructionMarks[offset] |= SUBROUTINE_INVOCATION;
+
+ // Mark the new subroutine start.
+ markBranchSubroutineStart(offset, branchOffset, targetOffset);
+ }
+ else if (currentSubroutineStart != UNKNOWN)
+ {
+ // Mark the continued subroutine start.
+ markBranchSubroutineStart(offset, branchOffset, currentSubroutineStart);
+ }
+
+ if (opcode == InstructionConstants.OP_GOTO ||
+ opcode == InstructionConstants.OP_GOTO_W)
+ {
+ // Mark the next instruction.
+ markAfterBranchOrigin(offset + branchInstruction.length(offset));
+ }
+ }
+
+
+ public void visitAnySwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SwitchInstruction switchInstruction)
+ {
+ // Mark the branch origin.
+ markBranchOrigin(offset);
+
+ // Check if this is an instruction of a subroutine.
+ checkSubroutine(offset);
+
+ // Mark the branch targets of the default jump offset.
+ markBranch(offset, switchInstruction.defaultOffset);
+
+ // Mark the branch targets of the jump offsets.
+ markBranches(offset, switchInstruction.jumpOffsets);
+
+ // Mark the next instruction.
+ markAfterBranchOrigin(offset + switchInstruction.length(offset));
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant) {}
+
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ isInitializer = methodrefConstant.getName(clazz).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT);
+ }
+
+
+ // Implementations for ExceptionInfoVisitor.
+
+ public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
+ {
+ // Mark the exception offsets.
+ instructionMarks[exceptionInfo.u2startPC] |= EXCEPTION_START;
+ instructionMarks[exceptionInfo.u2endPC] |= EXCEPTION_END;
+ instructionMarks[exceptionInfo.u2handlerPC] |= EXCEPTION_HANDLER;
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Marks the branch targets and their subroutine starts at the given
+ * offsets.
+ */
+ private void markBranches(int offset, int[] jumpOffsets)
+ {
+ for (int index = 0; index < jumpOffsets.length; index++)
+ {
+ markBranch(offset, jumpOffsets[index]);
+ }
+ }
+
+
+ /**
+ * Marks the branch target and its subroutine start at the given offset.
+ */
+ private void markBranch(int offset, int jumpOffset)
+ {
+ markBranchTarget(offset, jumpOffset);
+
+ if (currentSubroutineStart != UNKNOWN)
+ {
+ markBranchSubroutineStart(offset, jumpOffset, currentSubroutineStart);
+ }
+ }
+
+ /**
+ * Marks the branch origin at the given offset.
+ */
+ private void markBranchOrigin(int offset)
+ {
+ instructionMarks[offset] |= INSTRUCTION | BRANCH_ORIGIN;
+ }
+
+
+ /**
+ * Marks the branch target at the given offset.
+ */
+ private void markBranchTarget(int offset, int jumpOffset)
+ {
+ int targetOffset = offset + jumpOffset;
+
+ instructionMarks[targetOffset] |= BRANCH_TARGET;
+ }
+
+
+ /**
+ * Marks the subroutine start at the given offset, if applicable.
+ */
+ private void markBranchSubroutineStart(int offset,
+ int jumpOffset,
+ int subroutineStart)
+ {
+ int targetOffset = offset + jumpOffset;
+
+ // Are we marking a subroutine and branching to an offset that hasn't
+ // been marked yet?
+ if (subroutineStarts[targetOffset] == UNKNOWN)
+ {
+ // Is it a backward branch?
+ if (jumpOffset < 0)
+ {
+ // Remember the smallest subroutine start.
+ if (subroutineStart > targetOffset)
+ {
+ subroutineStart = targetOffset;
+ }
+
+ // We'll have to go over all instructions again.
+ repeat = true;
+ }
+
+ // Mark the subroutine start of the target.
+ subroutineStarts[targetOffset] = subroutineStart;
+ }
+ }
+
+
+ /**
+ * Marks the instruction at the given offset, after a branch.
+ */
+ private void markAfterBranchOrigin(int nextOffset)
+ {
+ instructionMarks[nextOffset] |= AFTER_BRANCH;
+
+ // Stop marking a subroutine.
+ currentSubroutineStart = UNKNOWN;
+ }
+
+
+ /**
+ * Checks if the specified instruction is inside a subroutine.
+ */
+ private void checkSubroutine(int offset)
+ {
+ // Are we inside a previously marked subroutine?
+ if (subroutineStarts[offset] != UNKNOWN)
+ {
+ // Start marking a subroutine.
+ currentSubroutineStart = subroutineStarts[offset];
+ }
+
+ // Are we marking a subroutine?
+ else if (currentSubroutineStart != UNKNOWN)
+ {
+ // Mark the subroutine start.
+ subroutineStarts[offset] = currentSubroutineStart;
+
+ if (currentSubroutineStart >= 0)
+ {
+ // Mark the subroutine end at the subroutine start.
+ subroutineEnds[currentSubroutineStart] = offset;
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/peephole/ClassFinalizer.java b/src/proguard/optimize/peephole/ClassFinalizer.java
new file mode 100644
index 000000000..378f972ea
--- /dev/null
+++ b/src/proguard/optimize/peephole/ClassFinalizer.java
@@ -0,0 +1,84 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.optimize.KeepMarker;
+
+/**
+ * This ClassVisitor
makes the program classes that it visits
+ * final, if possible.
+ *
+ * @author Eric Lafortune
+ */
+public class ClassFinalizer
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final ClassVisitor extraClassVisitor;
+
+
+ /**
+ * Creates a new ClassFinalizer.
+ */
+ public ClassFinalizer()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new ClassFinalizer.
+ * @param extraClassVisitor an optional extra visitor for all finalized
+ * classes.
+ */
+ public ClassFinalizer(ClassVisitor extraClassVisitor)
+ {
+ this.extraClassVisitor = extraClassVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // If the class is not final/interface/abstract,
+ // and it is not being kept,
+ // and it doesn't have any subclasses,
+ // then make it final.
+ if ((programClass.u2accessFlags & (ClassConstants.INTERNAL_ACC_FINAL |
+ ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) == 0 &&
+ !KeepMarker.isKept(programClass) &&
+ programClass.subClasses == null)
+ {
+ programClass.u2accessFlags |= ClassConstants.INTERNAL_ACC_FINAL;
+
+ // Visit the class, if required.
+ if (extraClassVisitor != null)
+ {
+ extraClassVisitor.visitProgramClass(programClass);
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/peephole/ClassMerger.java b/src/proguard/optimize/peephole/ClassMerger.java
new file mode 100644
index 000000000..aa40c75b2
--- /dev/null
+++ b/src/proguard/optimize/peephole/ClassMerger.java
@@ -0,0 +1,641 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.AttributeNameFilter;
+import proguard.classfile.constant.visitor.*;
+import proguard.classfile.editor.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.optimize.KeepMarker;
+import proguard.optimize.info.*;
+import proguard.util.*;
+
+import java.util.*;
+
+/**
+ * This ClassVisitor inlines the classes that it visits in a given target class,
+ * whenever possible.
+ *
+ * @see RetargetedInnerClassAttributeRemover
+ * @see TargetClassChanger
+ * @see ClassReferenceFixer
+ * @see MemberReferenceFixer
+ * @see AccessFixer
+ * @author Eric Lafortune
+ */
+public class ClassMerger
+extends SimplifiedVisitor
+implements ClassVisitor,
+ ConstantVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = System.getProperty("cm") != null;
+ //*/
+
+
+ private final ProgramClass targetClass;
+ private final boolean allowAccessModification;
+ private final boolean mergeInterfacesAggressively;
+ private final ClassVisitor extraClassVisitor;
+
+ private final MemberVisitor fieldOptimizationInfoCopier = new FieldOptimizationInfoCopier();
+
+
+ /**
+ * Creates a new ClassMerger that will merge classes into the given target
+ * class.
+ * @param targetClass the class into which all visited
+ * classes will be merged.
+ * @param allowAccessModification specifies whether the access modifiers
+ * of classes can be changed in order to
+ * merge them.
+ * @param mergeInterfacesAggressively specifies whether interfaces may
+ * be merged aggressively.
+ */
+ public ClassMerger(ProgramClass targetClass,
+ boolean allowAccessModification,
+ boolean mergeInterfacesAggressively)
+ {
+ this(targetClass, allowAccessModification, mergeInterfacesAggressively, null);
+ }
+
+
+ /**
+ * Creates a new ClassMerger that will merge classes into the given target
+ * class.
+ * @param targetClass the class into which all visited
+ * classes will be merged.
+ * @param allowAccessModification specifies whether the access modifiers
+ * of classes can be changed in order to
+ * merge them.
+ * @param mergeInterfacesAggressively specifies whether interfaces may
+ * be merged aggressively.
+ * @param extraClassVisitor an optional extra visitor for all
+ * merged classes.
+ */
+ public ClassMerger(ProgramClass targetClass,
+ boolean allowAccessModification,
+ boolean mergeInterfacesAggressively,
+ ClassVisitor extraClassVisitor)
+ {
+ this.targetClass = targetClass;
+ this.allowAccessModification = allowAccessModification;
+ this.mergeInterfacesAggressively = mergeInterfacesAggressively;
+ this.extraClassVisitor = extraClassVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ //final String CLASS_NAME = "abc/Def";
+ //DEBUG = programClass.getName().equals(CLASS_NAME) ||
+ // targetClass.getName().equals(CLASS_NAME);
+
+ // TODO: Remove this when the class merger has stabilized.
+ // Catch any unexpected exceptions from the actual visiting method.
+ try
+ {
+ visitProgramClass0(programClass);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while merging classes:");
+ System.err.println(" Class = ["+programClass.getName()+"]");
+ System.err.println(" Target class = ["+targetClass.getName()+"]");
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+
+ if (DEBUG)
+ {
+ programClass.accept(new ClassPrinter());
+ targetClass.accept(new ClassPrinter());
+ }
+
+ throw ex;
+ }
+ }
+
+ public void visitProgramClass0(ProgramClass programClass)
+ {
+ if (!programClass.equals(targetClass) &&
+
+ // Don't merge classes that must be preserved.
+ !KeepMarker.isKept(programClass) &&
+ !KeepMarker.isKept(targetClass) &&
+
+ // Only merge classes that haven't been retargeted yet.
+ getTargetClass(programClass) == null &&
+ getTargetClass(targetClass) == null &&
+
+ // Don't merge annotation classes, with all their introspection and
+ // infinite recursion.
+ (programClass.getAccessFlags() & ClassConstants.INTERNAL_ACC_ANNOTATTION) == 0 &&
+
+ // Only merge classes if we can change the access permissions, or
+ // if they are in the same package, or
+ // if they are public and don't contain or invoke package visible
+ // class members.
+ (allowAccessModification ||
+ ((programClass.getAccessFlags() &
+ targetClass.getAccessFlags() &
+ ClassConstants.INTERNAL_ACC_PUBLIC) != 0 &&
+ !PackageVisibleMemberContainingClassMarker.containsPackageVisibleMembers(programClass) &&
+ !PackageVisibleMemberInvokingClassMarker.invokesPackageVisibleMembers(programClass)) ||
+ ClassUtil.internalPackageName(programClass.getName()).equals(
+ ClassUtil.internalPackageName(targetClass.getName()))) &&
+
+ // Only merge two classes or two interfaces or two abstract classes,
+ // or a class into an interface with a single implementation.
+ ((programClass.getAccessFlags() &
+ (ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) ==
+ (targetClass.getAccessFlags() &
+ (ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) ||
+ (isOnlySubClass(programClass, targetClass) &&
+ (programClass.getSuperClass().equals(targetClass) ||
+ programClass.getSuperClass().equals(targetClass.getSuperClass())))) &&
+
+ // One class must not implement the other class indirectly.
+ !indirectlyImplementedInterfaces(programClass).contains(targetClass) &&
+ !targetClass.extendsOrImplements(programClass) &&
+
+ // The two classes must have the same superclasses and interfaces
+ // with static initializers.
+ initializedSuperClasses(programClass).equals(initializedSuperClasses(targetClass)) &&
+
+ // The two classes must have the same superclasses and interfaces
+ // that are tested with 'instanceof'.
+ instanceofedSuperClasses(programClass).equals(instanceofedSuperClasses(targetClass)) &&
+
+ // The two classes must have the same superclasses that are caught
+ // as exceptions.
+ caughtSuperClasses(programClass).equals(caughtSuperClasses(targetClass)) &&
+
+ // The two classes must not both be part of a .class construct.
+ !(DotClassMarker.isDotClassed(programClass) &&
+ DotClassMarker.isDotClassed(targetClass)) &&
+
+ // The classes must not have clashing fields.
+ !haveAnyIdenticalFields(programClass, targetClass) &&
+
+ // The two classes must not introduce any unwanted fields.
+ !introducesUnwantedFields(programClass, targetClass) &&
+ !introducesUnwantedFields(targetClass, programClass) &&
+
+ // The two classes must not shadow each others fields.
+ !shadowsAnyFields(programClass, targetClass) &&
+ !shadowsAnyFields(targetClass, programClass) &&
+
+ // The classes must not have clashing methods.
+ !haveAnyIdenticalMethods(programClass, targetClass) &&
+
+ // The classes must not introduce abstract methods, unless
+ // explicitly allowed.
+ (mergeInterfacesAggressively ||
+ (!introducesUnwantedAbstractMethods(programClass, targetClass) &&
+ !introducesUnwantedAbstractMethods(targetClass, programClass))) &&
+
+ // The classes must not override each others concrete methods.
+ !overridesAnyMethods(programClass, targetClass) &&
+ !overridesAnyMethods(targetClass, programClass) &&
+
+ // The classes must not shadow each others non-private methods.
+ !shadowsAnyMethods(programClass, targetClass) &&
+ !shadowsAnyMethods(targetClass, programClass))
+ {
+ if (DEBUG)
+ {
+ System.out.println("ClassMerger ["+programClass.getName()+"] -> ["+targetClass.getName()+"]");
+ System.out.println(" Source interface? ["+((programClass.getAccessFlags() & ClassConstants.INTERNAL_ACC_INTERFACE)!=0)+"]");
+ System.out.println(" Target interface? ["+((targetClass.getAccessFlags() & ClassConstants.INTERNAL_ACC_INTERFACE)!=0)+"]");
+ System.out.println(" Source subclasses ["+programClass.subClasses+"]");
+ System.out.println(" Target subclasses ["+targetClass.subClasses+"]");
+ System.out.println(" Source superclass ["+programClass.getSuperClass().getName()+"]");
+ System.out.println(" Target superclass ["+targetClass.getSuperClass().getName()+"]");
+
+ //System.out.println("=== Before ===");
+ //programClass.accept(new ClassPrinter());
+ //targetClass.accept(new ClassPrinter());
+ }
+
+ // Combine the access flags.
+ int targetAccessFlags = targetClass.getAccessFlags();
+ int sourceAccessFlags = programClass.getAccessFlags();
+
+ targetClass.u2accessFlags =
+ ((targetAccessFlags &
+ sourceAccessFlags) &
+ (ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) |
+ ((targetAccessFlags |
+ sourceAccessFlags) &
+ (ClassConstants.INTERNAL_ACC_PUBLIC |
+ ClassConstants.INTERNAL_ACC_SUPER |
+ ClassConstants.INTERNAL_ACC_ANNOTATTION |
+ ClassConstants.INTERNAL_ACC_ENUM));
+
+ // Copy over the superclass, unless it's the target class itself.
+ //if (!targetClass.getName().equals(programClass.getSuperName()))
+ //{
+ // targetClass.u2superClass =
+ // new ConstantAdder(targetClass).addConstant(programClass, programClass.u2superClass);
+ //}
+
+ // Copy over the interfaces that aren't present yet and that
+ // wouldn't cause loops in the class hierarchy.
+ programClass.interfaceConstantsAccept(
+ new ExceptClassConstantFilter(targetClass.getName(),
+ new ImplementedClassConstantFilter(targetClass,
+ new ImplementingClassConstantFilter(targetClass,
+ new InterfaceAdder(targetClass)))));
+
+ // Copy over the class members.
+ MemberAdder memberAdder =
+ new MemberAdder(targetClass, fieldOptimizationInfoCopier);
+
+ programClass.fieldsAccept(memberAdder);
+ programClass.methodsAccept(memberAdder);
+
+ // Copy over the other attributes.
+ programClass.attributesAccept(
+ new AttributeNameFilter(new NotMatcher(new OrMatcher(new OrMatcher(
+ new FixedStringMatcher(ClassConstants.ATTR_SourceFile),
+ new FixedStringMatcher(ClassConstants.ATTR_InnerClasses)),
+ new FixedStringMatcher(ClassConstants.ATTR_EnclosingMethod))),
+ new AttributeAdder(targetClass, true)));
+
+ // Update the optimization information of the target class.
+ ClassOptimizationInfo info =
+ ClassOptimizationInfo.getClassOptimizationInfo(targetClass);
+ if (info != null)
+ {
+ info.merge(ClassOptimizationInfo.getClassOptimizationInfo(programClass));
+ }
+
+ // Remember to replace the inlined class by the target class.
+ setTargetClass(programClass, targetClass);
+
+ //if (DEBUG)
+ //{
+ // System.out.println("=== After ====");
+ // targetClass.accept(new ClassPrinter());
+ //}
+
+ // Visit the merged class, if required.
+ if (extraClassVisitor != null)
+ {
+ extraClassVisitor.visitProgramClass(programClass);
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether a given class is the only subclass of another given class.
+ */
+ private boolean isOnlySubClass(Clazz subClass,
+ ProgramClass clazz)
+ {
+ // TODO: The list of subclasses is not up to date.
+ return clazz.subClasses != null &&
+ clazz.subClasses.length == 1 &&
+ clazz.subClasses[0].equals(subClass);
+ }
+
+
+ /**
+ * Returns the set of indirectly implemented interfaces.
+ */
+ private Set indirectlyImplementedInterfaces(Clazz clazz)
+ {
+ Set set = new HashSet();
+
+ ReferencedClassVisitor referencedInterfaceCollector =
+ new ReferencedClassVisitor(
+ new ClassHierarchyTraveler(false, false, true, false,
+ new ClassCollector(set)));
+
+ // Visit all superclasses and collect their interfaces.
+ clazz.superClassConstantAccept(referencedInterfaceCollector);
+
+ // Visit all interfaces and collect their interfaces.
+ clazz.interfaceConstantsAccept(referencedInterfaceCollector);
+
+ return set;
+ }
+
+
+ /**
+ * Returns the set of superclasses and interfaces that are initialized.
+ */
+ private Set initializedSuperClasses(Clazz clazz)
+ {
+ Set set = new HashSet();
+
+ // Visit all superclasses and interfaces, collecting the ones that have
+ // static initializers.
+ clazz.hierarchyAccept(true, true, true, false,
+ new StaticInitializerContainingClassFilter(
+ new ClassCollector(set)));
+
+ return set;
+ }
+
+
+ /**
+ * Returns the set of superclasses and interfaces that are used in
+ * 'instanceof' tests.
+ */
+ private Set instanceofedSuperClasses(Clazz clazz)
+ {
+ Set set = new HashSet();
+
+ // Visit all superclasses and interfaces, collecting the ones that are
+ // used in an 'instanceof' test.
+ clazz.hierarchyAccept(true, true, true, false,
+ new InstanceofClassFilter(
+ new ClassCollector(set)));
+
+ return set;
+ }
+
+
+ /**
+ * Returns the set of superclasses that are caught as exceptions.
+ */
+ private Set caughtSuperClasses(Clazz clazz)
+ {
+ // Don't bother if this isn't an exception at all.
+ if (!clazz.extends_(ClassConstants.INTERNAL_NAME_JAVA_LANG_THROWABLE))
+ {
+ return Collections.EMPTY_SET;
+ }
+
+ // Visit all superclasses, collecting the ones that are caught
+ // (plus java.lang.Object, in the current implementation).
+ Set set = new HashSet();
+
+ clazz.hierarchyAccept(true, true, false, false,
+ new CaughtClassFilter(
+ new ClassCollector(set)));
+
+ return set;
+ }
+
+
+ /**
+ * Returns whether the two given classes have class members with the same
+ * name and descriptor.
+ */
+ private boolean haveAnyIdenticalFields(Clazz clazz, Clazz targetClass)
+ {
+ MemberCounter counter = new MemberCounter();
+
+ // Visit all fields, counting the with the same name and descriptor in
+ // the target class.
+ clazz.fieldsAccept(new SimilarMemberVisitor(targetClass, true, false, false, false,
+ counter));
+
+ return counter.getCount() > 0;
+ }
+
+
+ /**
+ * Returns whether the given class would introduce any unwanted fields
+ * in the target class.
+ */
+ private boolean introducesUnwantedFields(ProgramClass programClass,
+ ProgramClass targetClass)
+ {
+ // It's ok if the target class is never instantiated, without any other
+ // subclasses except for maybe the source class.
+ if (!InstantiationClassMarker.isInstantiated(targetClass) &&
+ (targetClass.subClasses == null ||
+ isOnlySubClass(programClass, targetClass)))
+ {
+ return false;
+ }
+
+ MemberCounter counter = new MemberCounter();
+
+ // Count all non-static fields in the the source class.
+ programClass.fieldsAccept(new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_STATIC,
+ counter));
+
+ return counter.getCount() > 0;
+ }
+
+
+ /**
+ * Returns whether the given class or its subclasses shadow any fields in
+ * the given target class.
+ */
+ private boolean shadowsAnyFields(Clazz clazz, Clazz targetClass)
+ {
+ MemberCounter counter = new MemberCounter();
+
+ // Visit all fields, counting the ones that are shadowing non-private
+ // fields in the class hierarchy of the target class.
+ clazz.hierarchyAccept(true, false, false, true,
+ new AllFieldVisitor(
+ new SimilarMemberVisitor(targetClass, true, true, true, false,
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ counter))));
+
+ return counter.getCount() > 0;
+ }
+
+
+ /**
+ * Returns whether the two given classes have class members with the same
+ * name and descriptor.
+ */
+ private boolean haveAnyIdenticalMethods(Clazz clazz, Clazz targetClass)
+ {
+ MemberCounter counter = new MemberCounter();
+
+ // Visit all non-abstract methods, counting the ones that are also
+ // present in the target class.
+ clazz.methodsAccept(new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_ABSTRACT,
+ new SimilarMemberVisitor(targetClass, true, false, false, false,
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_ABSTRACT,
+ counter))));
+
+ return counter.getCount() > 0;
+ }
+
+
+ /**
+ * Returns whether the given class would introduce any abstract methods
+ * in the target class.
+ */
+ private boolean introducesUnwantedAbstractMethods(Clazz clazz,
+ ProgramClass targetClass)
+ {
+ // It's ok if the target class is already abstract and it has at most
+ // the class as a subclass.
+ if ((targetClass.getAccessFlags() &
+ (ClassConstants.INTERNAL_ACC_ABSTRACT |
+ ClassConstants.INTERNAL_ACC_INTERFACE)) != 0 &&
+ (targetClass.subClasses == null ||
+ isOnlySubClass(clazz, targetClass)))
+ {
+ return false;
+ }
+
+ MemberCounter counter = new MemberCounter();
+ Set targetSet = new HashSet();
+
+ // Collect all abstract methods, and similar abstract methods in the
+ // class hierarchy of the target class.
+ clazz.methodsAccept(new MemberAccessFilter(ClassConstants.INTERNAL_ACC_ABSTRACT, 0,
+ new MultiMemberVisitor(new MemberVisitor[]
+ {
+ counter,
+ new SimilarMemberVisitor(targetClass, true, true, true, false,
+ new MemberAccessFilter(ClassConstants.INTERNAL_ACC_ABSTRACT, 0,
+ new MemberCollector(targetSet)))
+ })));
+
+ return targetSet.size() < counter.getCount();
+ }
+
+
+ /**
+ * Returns whether the given class overrides any methods in the given
+ * target class.
+ */
+ private boolean overridesAnyMethods(Clazz clazz, Clazz targetClass)
+ {
+ MemberCounter counter = new MemberCounter();
+
+ // Visit all non-private non-static methods, counting the ones that are
+ // being overridden in the class hierarchy of the target class.
+ clazz.methodsAccept(new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE | ClassConstants.INTERNAL_ACC_STATIC | ClassConstants.INTERNAL_ACC_ABSTRACT,
+ new MemberNameFilter(new NotMatcher(new FixedStringMatcher(ClassConstants.INTERNAL_METHOD_NAME_CLINIT)),
+ new MemberNameFilter(new NotMatcher(new FixedStringMatcher(ClassConstants.INTERNAL_METHOD_NAME_INIT)),
+ new SimilarMemberVisitor(targetClass, true, true, false, false,
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE | ClassConstants.INTERNAL_ACC_STATIC | ClassConstants.INTERNAL_ACC_ABSTRACT,
+ counter))))));
+
+ return counter.getCount() > 0;
+ }
+
+
+ /**
+ * Returns whether the given class or its subclasses shadow any methods in
+ * the given target class.
+ */
+ private boolean shadowsAnyMethods(Clazz clazz, Clazz targetClass)
+ {
+ MemberCounter counter = new MemberCounter();
+
+ // Visit all private methods, counting the ones that are shadowing
+ // non-private methods in the class hierarchy of the target class.
+ clazz.hierarchyAccept(true, false, false, true,
+ new AllMethodVisitor(
+ new MemberAccessFilter(ClassConstants.INTERNAL_ACC_PRIVATE, 0,
+ new MemberNameFilter(new NotMatcher(new FixedStringMatcher(ClassConstants.INTERNAL_METHOD_NAME_INIT)),
+ new SimilarMemberVisitor(targetClass, true, true, true, false,
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ counter))))));
+
+ // Visit all static methods, counting the ones that are shadowing
+ // non-private methods in the class hierarchy of the target class.
+ clazz.hierarchyAccept(true, false, false, true,
+ new AllMethodVisitor(
+ new MemberAccessFilter(ClassConstants.INTERNAL_ACC_STATIC, 0,
+ new MemberNameFilter(new NotMatcher(new FixedStringMatcher(ClassConstants.INTERNAL_METHOD_NAME_CLINIT)),
+ new SimilarMemberVisitor(targetClass, true, true, true, false,
+ new MemberAccessFilter(0, ClassConstants.INTERNAL_ACC_PRIVATE,
+ counter))))));
+
+ return counter.getCount() > 0;
+ }
+
+
+ public static void setTargetClass(Clazz clazz, Clazz targetClass)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ if (info != null)
+ {
+ info.setTargetClass(targetClass);
+ }
+ }
+
+
+ public static Clazz getTargetClass(Clazz clazz)
+ {
+ Clazz targetClass = null;
+
+ // Return the last target class, if any.
+ while (true)
+ {
+ ClassOptimizationInfo info = ClassOptimizationInfo.getClassOptimizationInfo(clazz);
+ if (info == null)
+ {
+ return targetClass;
+ }
+
+ clazz = info.getTargetClass();
+ if (clazz == null)
+ {
+ return targetClass;
+ }
+
+ targetClass = clazz;
+ }
+ }
+
+
+ /**
+ * This MemberVisitor copies field optimization info from copied fields.
+ */
+ private static class FieldOptimizationInfoCopier
+ extends SimplifiedVisitor
+ implements MemberVisitor
+ {
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ // Copy the optimization info from the field that was just copied.
+ ProgramField copiedField = (ProgramField)programField.getVisitorInfo();
+ Object info = copiedField.getVisitorInfo();
+
+ programField.setVisitorInfo(info instanceof FieldOptimizationInfo ?
+ new FieldOptimizationInfo((FieldOptimizationInfo)info) :
+ info);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Linked methods share their optimization info.
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/peephole/GotoCommonCodeReplacer.java b/src/proguard/optimize/peephole/GotoCommonCodeReplacer.java
new file mode 100644
index 000000000..3bfd98cad
--- /dev/null
+++ b/src/proguard/optimize/peephole/GotoCommonCodeReplacer.java
@@ -0,0 +1,263 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.AttributeVisitor;
+import proguard.classfile.editor.CodeAttributeEditor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This AttributeVisitor redirects unconditional branches so any common code
+ * is shared, and the code preceding the branch can be removed, in the code
+ * attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class GotoCommonCodeReplacer
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+
+ private final InstructionVisitor extraInstructionVisitor;
+
+ private final BranchTargetFinder branchTargetFinder = new BranchTargetFinder();
+ private final CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor(true, false);
+
+
+ /**
+ * Creates a new GotoCommonCodeReplacer.
+ * @param extraInstructionVisitor an optional extra visitor for all replaced
+ * goto instructions.
+ */
+ public GotoCommonCodeReplacer(InstructionVisitor extraInstructionVisitor)
+ {
+ this.extraInstructionVisitor = extraInstructionVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+// DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ // Mark all branch targets.
+ branchTargetFinder.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Reset the code attribute editor.
+ codeAttributeEditor.reset(codeAttribute.u4codeLength);
+
+ // Remap the variables of the instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ // Apply the code atribute editor.
+ codeAttributeEditor.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ // Check if the instruction is an unconditional goto instruction that
+ // isn't the target of a branch itself.
+ byte opcode = branchInstruction.opcode;
+ if ((opcode == InstructionConstants.OP_GOTO ||
+ opcode == InstructionConstants.OP_GOTO_W) &&
+ !branchTargetFinder.isBranchTarget(offset))
+ {
+ int branchOffset = branchInstruction.branchOffset;
+ int targetOffset = offset + branchOffset;
+
+ // Get the number of common bytes.
+ int commonCount = commonByteCodeCount(codeAttribute, offset, targetOffset);
+
+ if (commonCount > 0 &&
+ !exceptionBoundary(codeAttribute, offset, targetOffset))
+ {
+ if (DEBUG)
+ {
+ System.out.println("GotoCommonCodeReplacer: "+clazz.getName()+"."+method.getName(clazz)+" (["+(offset-commonCount)+"] - "+branchInstruction.toString(offset)+" -> "+targetOffset+")");
+ }
+
+ // Delete the common instructions.
+ for (int delta = 0; delta <= commonCount; delta++)
+ {
+ int deleteOffset = offset - delta;
+ if (branchTargetFinder.isInstruction(deleteOffset))
+ {
+ codeAttributeEditor.clearModifications(deleteOffset);
+ codeAttributeEditor.deleteInstruction(deleteOffset);
+ }
+ }
+
+ // Redirect the goto instruction, if it is still necessary.
+ int newBranchOffset = branchOffset - commonCount;
+ if (newBranchOffset != branchInstruction.length(offset))
+ {
+ Instruction newGotoInstruction =
+ new BranchInstruction(opcode, newBranchOffset).shrink();
+ codeAttributeEditor.replaceInstruction(offset,
+ newGotoInstruction);
+ }
+
+ // Visit the instruction, if required.
+ if (extraInstructionVisitor != null)
+ {
+ extraInstructionVisitor.visitBranchInstruction(clazz, method, codeAttribute, offset, branchInstruction);
+ }
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns the number of common bytes preceding the given offsets,
+ * avoiding branches and exception blocks.
+ */
+ private int commonByteCodeCount(CodeAttribute codeAttribute, int offset1, int offset2)
+ {
+ // Find the block of common instructions preceding it.
+ byte[] code = codeAttribute.code;
+
+ int successfulDelta = 0;
+
+ for (int delta = 1;
+ delta <= offset1 &&
+ delta <= offset2 &&
+ offset2 - delta != offset1;
+ delta++)
+ {
+ int newOffset1 = offset1 - delta;
+ int newOffset2 = offset2 - delta;
+
+ // Is the code identical at both offsets?
+ if (code[newOffset1] != code[newOffset2])
+ {
+ break;
+ }
+
+ // Are there instructions at either offset but not both?
+ if (branchTargetFinder.isInstruction(newOffset1) ^
+ branchTargetFinder.isInstruction(newOffset2))
+ {
+ break;
+ }
+
+ // Are there instructions at both offsets?
+ if (branchTargetFinder.isInstruction(newOffset1) &&
+ branchTargetFinder.isInstruction(newOffset2))
+ {
+ // Are the offsets involved in some branches?
+ // Note that the preverifier doesn't like initializer
+ // invocations to be moved around.
+ // Also note that the preverifier doesn't like pop instructions
+ // that work on different operands.
+ if (branchTargetFinder.isBranchOrigin(newOffset1) ||
+ branchTargetFinder.isBranchTarget(newOffset1) ||
+ branchTargetFinder.isExceptionStart(newOffset1) ||
+ branchTargetFinder.isExceptionEnd(newOffset1) ||
+ branchTargetFinder.isInitializer(newOffset1) ||
+ branchTargetFinder.isExceptionStart(newOffset2) ||
+ branchTargetFinder.isExceptionEnd(newOffset2) ||
+ isPop(code[newOffset1]))
+ {
+ break;
+ }
+
+ // Make sure the new branch target was a branch target before,
+ // in order not to introduce new entries in the stack map table.
+ if (branchTargetFinder.isBranchTarget(newOffset2))
+ {
+ successfulDelta = delta;
+ }
+
+ if (branchTargetFinder.isBranchTarget(newOffset1))
+ {
+ break;
+ }
+ }
+ }
+
+ return successfulDelta;
+ }
+
+
+ /**
+ * Returns whether the given opcode represents a pop instruction that must
+ * get a consistent type (pop, pop2, arraylength).
+ */
+ private boolean isPop(byte opcode)
+ {
+ return opcode == InstructionConstants.OP_POP ||
+ opcode == InstructionConstants.OP_POP2 ||
+ opcode == InstructionConstants.OP_ARRAYLENGTH;
+ }
+
+
+ /**
+ * Returns the whether there is a boundary of an exception block between
+ * the given offsets (including both).
+ */
+ private boolean exceptionBoundary(CodeAttribute codeAttribute, int offset1, int offset2)
+ {
+ // Swap the offsets if the second one is smaller than the first one.
+ if (offset2 < offset1)
+ {
+ int offset = offset1;
+ offset1 = offset2;
+ offset2 = offset;
+ }
+
+ // Check if there is a boundary of an exception block.
+ for (int offset = offset1; offset <= offset2; offset++)
+ {
+ if (branchTargetFinder.isExceptionStart(offset) ||
+ branchTargetFinder.isExceptionEnd(offset))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/src/proguard/optimize/peephole/GotoGotoReplacer.java b/src/proguard/optimize/peephole/GotoGotoReplacer.java
new file mode 100644
index 000000000..4a490a10b
--- /dev/null
+++ b/src/proguard/optimize/peephole/GotoGotoReplacer.java
@@ -0,0 +1,115 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.editor.CodeAttributeEditor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This InstructionVisitor simplifies unconditional branches to other
+ * unconditional branches.
+ *
+ * @author Eric Lafortune
+ */
+public class GotoGotoReplacer
+extends SimplifiedVisitor
+implements InstructionVisitor
+{
+ private final CodeAttributeEditor codeAttributeEditor;
+ private final InstructionVisitor extraInstructionVisitor;
+
+
+ /**
+ * Creates a new GotoGotoReplacer.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ */
+ public GotoGotoReplacer(CodeAttributeEditor codeAttributeEditor)
+ {
+ this(codeAttributeEditor, null);
+ }
+
+
+ /**
+ * Creates a new GotoGotoReplacer.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ * @param extraInstructionVisitor an optional extra visitor for all replaced
+ * goto instructions.
+ */
+ public GotoGotoReplacer(CodeAttributeEditor codeAttributeEditor,
+ InstructionVisitor extraInstructionVisitor)
+ {
+ this.codeAttributeEditor = codeAttributeEditor;
+ this.extraInstructionVisitor = extraInstructionVisitor;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ // Check if the instruction is an unconditional goto instruction.
+ byte opcode = branchInstruction.opcode;
+ if (opcode == InstructionConstants.OP_GOTO ||
+ opcode == InstructionConstants.OP_GOTO_W)
+ {
+ // Check if the goto instruction points to another simple goto
+ // instruction.
+ int branchOffset = branchInstruction.branchOffset;
+ int targetOffset = offset + branchOffset;
+
+ if (branchOffset != 0 &&
+ branchOffset != branchInstruction.length(offset) &&
+ !codeAttributeEditor.isModified(offset) &&
+ !codeAttributeEditor.isModified(targetOffset))
+ {
+ Instruction targetInstruction =
+ InstructionFactory.create(codeAttribute.code, targetOffset);
+
+ if (targetInstruction.opcode == InstructionConstants.OP_GOTO)
+ {
+ // Simplify the goto instruction.
+ int targetBranchOffset = ((BranchInstruction)targetInstruction).branchOffset;
+
+ Instruction newBranchInstruction =
+ new BranchInstruction(opcode,
+ (branchOffset + targetBranchOffset));
+ codeAttributeEditor.replaceInstruction(offset,
+ newBranchInstruction);
+
+ // Visit the instruction, if required.
+ if (extraInstructionVisitor != null)
+ {
+ extraInstructionVisitor.visitBranchInstruction(clazz, method, codeAttribute, offset, branchInstruction);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/peephole/GotoReturnReplacer.java b/src/proguard/optimize/peephole/GotoReturnReplacer.java
new file mode 100644
index 000000000..b6deec862
--- /dev/null
+++ b/src/proguard/optimize/peephole/GotoReturnReplacer.java
@@ -0,0 +1,115 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.editor.CodeAttributeEditor;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+
+/**
+ * This InstructionVisitor replaces unconditional branches to return instructions
+ * by these same return instructions.
+ *
+ * @author Eric Lafortune
+ */
+public class GotoReturnReplacer
+extends SimplifiedVisitor
+implements InstructionVisitor
+{
+ private final CodeAttributeEditor codeAttributeEditor;
+ private final InstructionVisitor extraInstructionVisitor;
+
+
+ /**
+ * Creates a new GotoReturnReplacer.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ */
+ public GotoReturnReplacer(CodeAttributeEditor codeAttributeEditor)
+ {
+ this(codeAttributeEditor, null);
+ }
+
+
+ /**
+ * Creates a new GotoReturnReplacer.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ * @param extraInstructionVisitor an optional extra visitor for all replaced
+ * goto instructions.
+ */
+ public GotoReturnReplacer(CodeAttributeEditor codeAttributeEditor,
+ InstructionVisitor extraInstructionVisitor)
+ {
+ this.codeAttributeEditor = codeAttributeEditor;
+ this.extraInstructionVisitor = extraInstructionVisitor;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction) {}
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ // Check if the instruction is an unconditional goto instruction.
+ byte opcode = branchInstruction.opcode;
+ if (opcode == InstructionConstants.OP_GOTO ||
+ opcode == InstructionConstants.OP_GOTO_W)
+ {
+ // Check if the goto instruction points to a return instruction.
+ int targetOffset = offset + branchInstruction.branchOffset;
+
+ if (!codeAttributeEditor.isModified(offset) &&
+ !codeAttributeEditor.isModified(targetOffset))
+ {
+ Instruction targetInstruction = InstructionFactory.create(codeAttribute.code,
+ targetOffset);
+ switch (targetInstruction.opcode)
+ {
+ case InstructionConstants.OP_IRETURN:
+ case InstructionConstants.OP_LRETURN:
+ case InstructionConstants.OP_FRETURN:
+ case InstructionConstants.OP_DRETURN:
+ case InstructionConstants.OP_ARETURN:
+ case InstructionConstants.OP_RETURN:
+ // Replace the goto instruction by the return instruction.
+ Instruction returnInstruction =
+ new SimpleInstruction(targetInstruction.opcode);
+ codeAttributeEditor.replaceInstruction(offset,
+ returnInstruction);
+
+ // Visit the instruction, if required.
+ if (extraInstructionVisitor != null)
+ {
+ extraInstructionVisitor.visitBranchInstruction(clazz, method, codeAttribute, offset, branchInstruction);
+ }
+
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/peephole/HorizontalClassMerger.java b/src/proguard/optimize/peephole/HorizontalClassMerger.java
new file mode 100644
index 000000000..31d3d3357
--- /dev/null
+++ b/src/proguard/optimize/peephole/HorizontalClassMerger.java
@@ -0,0 +1,90 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.*;
+
+/**
+ * This ClassVisitor inlines siblings in the program classes that it visits,
+ * whenever possible.
+ *
+ * @see ClassMerger
+ * @author Eric Lafortune
+ */
+public class HorizontalClassMerger
+extends SimplifiedVisitor
+implements ClassVisitor
+{
+ private final boolean allowAccessModification;
+ private final boolean mergeInterfacesAggressively;
+ private final ClassVisitor extraClassVisitor;
+
+
+ /**
+ * Creates a new HorizontalClassMerger.
+ * @param allowAccessModification specifies whether the access modifiers
+ * of classes can be changed in order to
+ * merge them.
+ * @param mergeInterfacesAggressively specifies whether interfaces may
+ * be merged aggressively.
+ */
+ public HorizontalClassMerger(boolean allowAccessModification,
+ boolean mergeInterfacesAggressively)
+ {
+ this(allowAccessModification, mergeInterfacesAggressively, null);
+ }
+
+
+ /**
+ * Creates a new VerticalClassMerger.
+ * @param allowAccessModification specifies whether the access modifiers
+ * of classes can be changed in order to
+ * merge them.
+ * @param mergeInterfacesAggressively specifies whether interfaces may
+ * be merged aggressively.
+ * @param extraClassVisitor an optional extra visitor for all
+ * merged classes.
+ */
+ public HorizontalClassMerger(boolean allowAccessModification,
+ boolean mergeInterfacesAggressively,
+ ClassVisitor extraClassVisitor)
+ {
+ this.allowAccessModification = allowAccessModification;
+ this.mergeInterfacesAggressively = mergeInterfacesAggressively;
+ this.extraClassVisitor = extraClassVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ programClass.superClassConstantAccept(new ReferencedClassVisitor(
+ new SubclassTraveler(
+ new ProgramClassFilter(
+ new ClassMerger(programClass,
+ allowAccessModification,
+ mergeInterfacesAggressively,
+ extraClassVisitor)))));
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/peephole/InstructionSequenceConstants.java b/src/proguard/optimize/peephole/InstructionSequenceConstants.java
new file mode 100644
index 000000000..4ab9056c4
--- /dev/null
+++ b/src/proguard/optimize/peephole/InstructionSequenceConstants.java
@@ -0,0 +1,5090 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.visitor.ClassPrinter;
+
+/**
+ * This class contains a set of instruction sequences and their suggested
+ * replacements.
+ *
+ * @see InstructionSequencesReplacer
+ * @see InstructionSequenceReplacer
+ * @author Eric Lafortune
+ */
+public class InstructionSequenceConstants
+{
+ private static final int X = InstructionSequenceReplacer.X;
+ private static final int Y = InstructionSequenceReplacer.Y;
+ private static final int Z = InstructionSequenceReplacer.Z;
+
+ private static final int A = InstructionSequenceReplacer.A;
+ private static final int B = InstructionSequenceReplacer.B;
+ private static final int C = InstructionSequenceReplacer.C;
+ private static final int D = InstructionSequenceReplacer.D;
+
+ private static final int STRING_A_LENGTH = InstructionSequenceReplacer.STRING_A_LENGTH;
+ private static final int BOOLEAN_A_STRING = InstructionSequenceReplacer.BOOLEAN_A_STRING;
+ private static final int CHAR_A_STRING = InstructionSequenceReplacer.CHAR_A_STRING;
+ private static final int INT_A_STRING = InstructionSequenceReplacer.INT_A_STRING;
+ private static final int LONG_A_STRING = InstructionSequenceReplacer.LONG_A_STRING;
+ private static final int FLOAT_A_STRING = InstructionSequenceReplacer.FLOAT_A_STRING;
+ private static final int DOUBLE_A_STRING = InstructionSequenceReplacer.DOUBLE_A_STRING;
+ private static final int STRING_A_STRING = InstructionSequenceReplacer.STRING_A_STRING;
+ private static final int BOOLEAN_B_STRING = InstructionSequenceReplacer.BOOLEAN_B_STRING;
+ private static final int CHAR_B_STRING = InstructionSequenceReplacer.CHAR_B_STRING;
+ private static final int INT_B_STRING = InstructionSequenceReplacer.INT_B_STRING;
+ private static final int LONG_B_STRING = InstructionSequenceReplacer.LONG_B_STRING;
+ private static final int FLOAT_B_STRING = InstructionSequenceReplacer.FLOAT_B_STRING;
+ private static final int DOUBLE_B_STRING = InstructionSequenceReplacer.DOUBLE_B_STRING;
+ private static final int STRING_B_STRING = InstructionSequenceReplacer.STRING_B_STRING;
+
+ private static final int I_32768 = 0;
+ private static final int I_65536 = 1;
+ private static final int I_16777216 = 2;
+
+// private static final int I_0x000000ff
+ private static final int I_0x0000ff00 = 3;
+ private static final int I_0x00ff0000 = 4;
+ private static final int I_0xff000000 = 5;
+ private static final int I_0x0000ffff = 6;
+ private static final int I_0xffff0000 = 7;
+
+ private static final int L_M1 = 8;
+ private static final int L_2 = 9;
+ private static final int L_4 = 10;
+ private static final int L_8 = 11;
+ private static final int L_16 = 12;
+ private static final int L_32 = 13;
+ private static final int L_64 = 14;
+ private static final int L_128 = 15;
+ private static final int L_256 = 16;
+ private static final int L_512 = 17;
+ private static final int L_1024 = 18;
+ private static final int L_2048 = 19;
+ private static final int L_4096 = 20;
+ private static final int L_8192 = 21;
+ private static final int L_16384 = 22;
+ private static final int L_32768 = 23;
+ private static final int L_65536 = 24;
+ private static final int L_16777216 = 25;
+ private static final int L_4294967296 = 26;
+
+ private static final int L_0x00000000ffffffff = 27;
+ private static final int L_0xffffffff00000000 = 28;
+
+ private static final int F_M1 = 29;
+
+ private static final int D_M1 = 30;
+
+ private static final int STRING_EMPTY = 31;
+
+ private static final int FIELD_I = 32; // Implicitly uses X and Y.
+ private static final int FIELD_L = 33; // Implicitly uses X and Y.
+ private static final int FIELD_F = 34; // Implicitly uses X and Y.
+ private static final int FIELD_D = 35; // Implicitly uses X and Y.
+
+ private static final int METHOD_STRING_EQUALS = 36;
+ private static final int METHOD_STRING_LENGTH = 37;
+ private static final int METHOD_STRING_VALUEOF_Z = 38;
+ private static final int METHOD_STRING_VALUEOF_C = 39;
+ private static final int METHOD_STRING_VALUEOF_I = 40;
+ private static final int METHOD_STRING_VALUEOF_J = 41;
+ private static final int METHOD_STRING_VALUEOF_F = 42;
+ private static final int METHOD_STRING_VALUEOF_D = 43;
+ private static final int METHOD_STRING_VALUEOF_OBJECT = 44;
+ private static final int METHOD_STRINGBUFFER_INIT = 45;
+ private static final int METHOD_STRINGBUFFER_INIT_STRING = 46;
+ private static final int METHOD_STRINGBUFFER_APPEND_Z = 47;
+ private static final int METHOD_STRINGBUFFER_APPEND_C = 48;
+ private static final int METHOD_STRINGBUFFER_APPEND_I = 49;
+ private static final int METHOD_STRINGBUFFER_APPEND_J = 50;
+ private static final int METHOD_STRINGBUFFER_APPEND_F = 51;
+ private static final int METHOD_STRINGBUFFER_APPEND_D = 52;
+ private static final int METHOD_STRINGBUFFER_APPEND_STRING = 53;
+ private static final int METHOD_STRINGBUFFER_APPEND_OBJECT = 54;
+ private static final int METHOD_STRINGBUFFER_LENGTH = 55;
+ private static final int METHOD_STRINGBUFFER_TOSTRING = 56;
+ private static final int METHOD_STRINGBUILDER_INIT = 57;
+ private static final int METHOD_STRINGBUILDER_INIT_STRING = 58;
+ private static final int METHOD_STRINGBUILDER_APPEND_Z = 59;
+ private static final int METHOD_STRINGBUILDER_APPEND_C = 60;
+ private static final int METHOD_STRINGBUILDER_APPEND_I = 61;
+ private static final int METHOD_STRINGBUILDER_APPEND_J = 62;
+ private static final int METHOD_STRINGBUILDER_APPEND_F = 63;
+ private static final int METHOD_STRINGBUILDER_APPEND_D = 64;
+ private static final int METHOD_STRINGBUILDER_APPEND_STRING = 65;
+ private static final int METHOD_STRINGBUILDER_APPEND_OBJECT = 66;
+ private static final int METHOD_STRINGBUILDER_LENGTH = 67;
+ private static final int METHOD_STRINGBUILDER_TOSTRING = 68;
+
+ private static final int CLASS_STRING = 69;
+ private static final int CLASS_STRINGBUFFER = 70;
+ private static final int CLASS_STRINGBUILDER = 71;
+
+ private static final int NAME_AND_TYPE_I = 72; // Implicitly uses Y.
+ private static final int NAME_AND_TYPE_L = 73; // Implicitly uses Y.
+ private static final int NAME_AND_TYPE_F = 74; // Implicitly uses Y.
+ private static final int NAME_AND_TYPE_D = 75; // Implicitly uses Y.
+
+ private static final int NAME_AND_TYPE_EQUALS = 76;
+ private static final int NAME_AND_TYPE_LENGTH = 77;
+ private static final int NAME_AND_TYPE_VALUEOF_Z = 78;
+ private static final int NAME_AND_TYPE_VALUEOF_C = 79;
+ private static final int NAME_AND_TYPE_VALUEOF_I = 80;
+ private static final int NAME_AND_TYPE_VALUEOF_J = 81;
+ private static final int NAME_AND_TYPE_VALUEOF_F = 82;
+ private static final int NAME_AND_TYPE_VALUEOF_D = 83;
+ private static final int NAME_AND_TYPE_VALUEOF_OBJECT = 84;
+ private static final int NAME_AND_TYPE_INIT = 85;
+ private static final int NAME_AND_TYPE_INIT_STRING = 86;
+ private static final int NAME_AND_TYPE_APPEND_Z_STRINGBUFFER = 87;
+ private static final int NAME_AND_TYPE_APPEND_C_STRINGBUFFER = 88;
+ private static final int NAME_AND_TYPE_APPEND_I_STRINGBUFFER = 89;
+ private static final int NAME_AND_TYPE_APPEND_J_STRINGBUFFER = 90;
+ private static final int NAME_AND_TYPE_APPEND_F_STRINGBUFFER = 91;
+ private static final int NAME_AND_TYPE_APPEND_D_STRINGBUFFER = 92;
+ private static final int NAME_AND_TYPE_APPEND_STRING_STRINGBUFFER = 93;
+ private static final int NAME_AND_TYPE_APPEND_OBJECT_STRINGBUFFER = 94;
+ private static final int NAME_AND_TYPE_APPEND_Z_STRINGBUILDER = 95;
+ private static final int NAME_AND_TYPE_APPEND_C_STRINGBUILDER = 96;
+ private static final int NAME_AND_TYPE_APPEND_I_STRINGBUILDER = 97;
+ private static final int NAME_AND_TYPE_APPEND_J_STRINGBUILDER = 98;
+ private static final int NAME_AND_TYPE_APPEND_F_STRINGBUILDER = 99;
+ private static final int NAME_AND_TYPE_APPEND_D_STRINGBUILDER = 100;
+ private static final int NAME_AND_TYPE_APPEND_STRING_STRINGBUILDER = 101;
+ private static final int NAME_AND_TYPE_APPEND_OBJECT_STRINGBUILDER = 102;
+ private static final int NAME_AND_TYPE_TOSTRING = 103;
+
+ private static final int UTF8_EMPTY = 104;
+ private static final int UTF8_I = 105;
+ private static final int UTF8_L = 106;
+ private static final int UTF8_F = 107;
+ private static final int UTF8_D = 108;
+ private static final int UTF8_STRING = 109;
+ private static final int UTF8_STRINGBUFFER = 110;
+ private static final int UTF8_STRINGBUILDER = 111;
+ private static final int UTF8_EQUALS = 112;
+ private static final int UTF8_OBJECT_Z = 113;
+ private static final int UTF8_LENGTH = 114;
+ private static final int UTF8__I = 115;
+ private static final int UTF8_VALUEOF = 116;
+ private static final int UTF8_Z_STRING = 117;
+ private static final int UTF8_C_STRING = 118;
+ private static final int UTF8_I_STRING = 119;
+ private static final int UTF8_J_STRING = 120;
+ private static final int UTF8_F_STRING = 121;
+ private static final int UTF8_D_STRING = 122;
+ private static final int UTF8_OBJECT_STRING = 123;
+ private static final int UTF8_INIT = 124;
+ private static final int UTF8__VOID = 125;
+ private static final int UTF8_STRING_VOID = 126;
+ private static final int UTF8_TOSTRING = 127;
+ private static final int UTF8__STRING = 128;
+ private static final int UTF8_APPEND = 129;
+ private static final int UTF8_Z_STRINGBUFFER = 130;
+ private static final int UTF8_C_STRINGBUFFER = 131;
+ private static final int UTF8_I_STRINGBUFFER = 132;
+ private static final int UTF8_J_STRINGBUFFER = 133;
+ private static final int UTF8_F_STRINGBUFFER = 134;
+ private static final int UTF8_D_STRINGBUFFER = 135;
+ private static final int UTF8_STRING_STRINGBUFFER = 136;
+ private static final int UTF8_OBJECT_STRINGBUFFER = 137;
+ private static final int UTF8_Z_STRINGBUILDER = 138;
+ private static final int UTF8_C_STRINGBUILDER = 139;
+ private static final int UTF8_I_STRINGBUILDER = 140;
+ private static final int UTF8_J_STRINGBUILDER = 141;
+ private static final int UTF8_F_STRINGBUILDER = 142;
+ private static final int UTF8_D_STRINGBUILDER = 143;
+ private static final int UTF8_STRING_STRINGBUILDER = 144;
+ private static final int UTF8_OBJECT_STRINGBUILDER = 145;
+
+ private static final int SENTINEL = 146;
+
+
+ public static final Constant[] CONSTANTS = new Constant[]
+ {
+ new IntegerConstant(32768),
+ new IntegerConstant(65536),
+ new IntegerConstant(16777216),
+
+ new IntegerConstant(0x0000ff00),
+ new IntegerConstant(0x00ff0000),
+ new IntegerConstant(0xff000000),
+ new IntegerConstant(0x0000ffff),
+ new IntegerConstant(0xffff0000),
+
+ new LongConstant(-1L),
+ new LongConstant(2L),
+ new LongConstant(4L),
+ new LongConstant(8L),
+ new LongConstant(16L),
+ new LongConstant(32L),
+ new LongConstant(64L),
+ new LongConstant(128L),
+ new LongConstant(256L),
+ new LongConstant(512L),
+ new LongConstant(1024L),
+ new LongConstant(2048L),
+ new LongConstant(4096L),
+ new LongConstant(8192L),
+ new LongConstant(16384L),
+ new LongConstant(32768L),
+ new LongConstant(65536L),
+ new LongConstant(16777216L),
+ new LongConstant(4294967296L),
+
+ new LongConstant(0x00000000ffffffffL),
+ new LongConstant(0xffffffff00000000L),
+
+ new FloatConstant(-1f),
+
+ new DoubleConstant(-1d),
+
+ new StringConstant(UTF8_EMPTY, null, null),
+
+ new FieldrefConstant(X, NAME_AND_TYPE_I, null, null),
+ new FieldrefConstant(X, NAME_AND_TYPE_L, null, null),
+ new FieldrefConstant(X, NAME_AND_TYPE_F, null, null),
+ new FieldrefConstant(X, NAME_AND_TYPE_D, null, null),
+
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_EQUALS, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_LENGTH, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_VALUEOF_Z, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_VALUEOF_C, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_VALUEOF_I, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_VALUEOF_J, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_VALUEOF_F, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_VALUEOF_D, null, null),
+ new MethodrefConstant(CLASS_STRING, NAME_AND_TYPE_VALUEOF_OBJECT, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_INIT, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_INIT_STRING, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_Z_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_C_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_I_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_J_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_F_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_D_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_STRING_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_APPEND_OBJECT_STRINGBUFFER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_LENGTH, null, null),
+ new MethodrefConstant(CLASS_STRINGBUFFER, NAME_AND_TYPE_TOSTRING, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_INIT, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_INIT_STRING, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_Z_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_C_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_I_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_J_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_F_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_D_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_STRING_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_APPEND_OBJECT_STRINGBUILDER, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_LENGTH, null, null),
+ new MethodrefConstant(CLASS_STRINGBUILDER, NAME_AND_TYPE_TOSTRING, null, null),
+
+ new ClassConstant(UTF8_STRING, null),
+ new ClassConstant(UTF8_STRINGBUFFER, null),
+ new ClassConstant(UTF8_STRINGBUILDER, null),
+
+ new NameAndTypeConstant(Y, UTF8_I),
+ new NameAndTypeConstant(Y, UTF8_L),
+ new NameAndTypeConstant(Y, UTF8_F),
+ new NameAndTypeConstant(Y, UTF8_D),
+ new NameAndTypeConstant(UTF8_EQUALS, UTF8_OBJECT_Z),
+ new NameAndTypeConstant(UTF8_LENGTH, UTF8__I),
+ new NameAndTypeConstant(UTF8_VALUEOF, UTF8_Z_STRING),
+ new NameAndTypeConstant(UTF8_VALUEOF, UTF8_C_STRING),
+ new NameAndTypeConstant(UTF8_VALUEOF, UTF8_I_STRING),
+ new NameAndTypeConstant(UTF8_VALUEOF, UTF8_J_STRING),
+ new NameAndTypeConstant(UTF8_VALUEOF, UTF8_F_STRING),
+ new NameAndTypeConstant(UTF8_VALUEOF, UTF8_D_STRING),
+ new NameAndTypeConstant(UTF8_VALUEOF, UTF8_OBJECT_STRING),
+ new NameAndTypeConstant(UTF8_INIT, UTF8__VOID),
+ new NameAndTypeConstant(UTF8_INIT, UTF8_STRING_VOID),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_Z_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_C_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_I_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_J_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_F_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_D_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_STRING_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_OBJECT_STRINGBUFFER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_Z_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_C_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_I_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_J_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_F_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_D_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_STRING_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_APPEND, UTF8_OBJECT_STRINGBUILDER),
+ new NameAndTypeConstant(UTF8_TOSTRING, UTF8__STRING),
+
+ new Utf8Constant(""),
+ new Utf8Constant("I"),
+ new Utf8Constant("J"),
+ new Utf8Constant("F"),
+ new Utf8Constant("D"),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_STRING),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_NAME_JAVA_LANG_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_EQUALS),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_EQUALS),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_LENGTH),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_LENGTH),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_VALUEOF),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_VALUEOF_BOOLEAN),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_VALUEOF_CHAR),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_VALUEOF_INT),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_VALUEOF_LONG),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_VALUEOF_FLOAT),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_VALUEOF_DOUBLE),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_VALUEOF_OBJECT),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_INIT),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_INIT),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_STRING_VOID),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_TOSTRING),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_TOSTRING),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_NAME_APPEND),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_BOOLEAN_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CHAR_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_INT_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_LONG_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_FLOAT_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_DOUBLE_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_STRING_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_OBJECT_STRING_BUFFER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_BOOLEAN_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_CHAR_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_INT_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_LONG_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_FLOAT_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_DOUBLE_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_STRING_STRING_BUILDER),
+ new Utf8Constant(ClassConstants.INTERNAL_METHOD_TYPE_OBJECT_STRING_BUILDER),
+ };
+
+ public static final Instruction[][][] VARIABLE = new Instruction[][][]
+ {
+ { // nop = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_NOP),
+ },{
+ // Nothing.
+ },
+ },
+ { // iload/pop = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // lload/pop2 = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },{
+ // Nothing.
+ },
+ },
+ { // fload/pop = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // dload/pop2 = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },{
+ // Nothing.
+ },
+ },
+ { // aload/pop = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // i = i = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // l = l = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new VariableInstruction(InstructionConstants.OP_LSTORE, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // f = f = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new VariableInstruction(InstructionConstants.OP_FSTORE, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // d = d = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new VariableInstruction(InstructionConstants.OP_DSTORE, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // a = a = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+ new VariableInstruction(InstructionConstants.OP_ASTORE, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // istore/istore = pop/istore
+ {
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },
+ },
+ { // lstore/lstore = pop2/lstore
+ {
+ new VariableInstruction(InstructionConstants.OP_LSTORE, X),
+ new VariableInstruction(InstructionConstants.OP_LSTORE, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new VariableInstruction(InstructionConstants.OP_LSTORE, X),
+ },
+ },
+ { // fstore/fstore = pop/fstore
+ {
+ new VariableInstruction(InstructionConstants.OP_FSTORE, X),
+ new VariableInstruction(InstructionConstants.OP_FSTORE, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new VariableInstruction(InstructionConstants.OP_FSTORE, X),
+ },
+ },
+ { // dstore/dstore = pop2/dstore
+ {
+ new VariableInstruction(InstructionConstants.OP_DSTORE, X),
+ new VariableInstruction(InstructionConstants.OP_DSTORE, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new VariableInstruction(InstructionConstants.OP_DSTORE, X),
+ },
+ },
+ { // astore/astore = pop/astore
+ {
+ new VariableInstruction(InstructionConstants.OP_ASTORE, X),
+ new VariableInstruction(InstructionConstants.OP_ASTORE, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new VariableInstruction(InstructionConstants.OP_ASTORE, X),
+ },
+ },
+ { // istore/iload = dup/istore
+ {
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },
+ },
+ { // lstore/lload = dup2/lstore
+ {
+ new VariableInstruction(InstructionConstants.OP_LSTORE, X),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP2),
+ new VariableInstruction(InstructionConstants.OP_LSTORE, X),
+ },
+ },
+ { // fstore/fload = dup/fstore
+ {
+ new VariableInstruction(InstructionConstants.OP_FSTORE, X),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new VariableInstruction(InstructionConstants.OP_FSTORE, X),
+ },
+ },
+ { // dstore/dload = dup2/dstore
+ {
+ new VariableInstruction(InstructionConstants.OP_DSTORE, X),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP2),
+ new VariableInstruction(InstructionConstants.OP_DSTORE, X),
+ },
+ },
+ { // astore/aload = dup/astore
+ {
+ new VariableInstruction(InstructionConstants.OP_ASTORE, X),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new VariableInstruction(InstructionConstants.OP_ASTORE, X),
+ },
+ },
+ };
+
+ public static final Instruction[][][] ARITHMETIC = new Instruction[][][]
+ {
+ { // c + i = i + c
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },
+ },
+ { // b + i = i + b
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },
+ },
+ { // s + i = i + s
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },
+ },
+ { // c + i = i + c
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },
+ },
+ { // c * i = i * c
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },
+ },
+ { // b * i = i * b
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },
+ },
+ { // s * i = i * s
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },
+ },
+ { // c * i = i * c
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },
+ },
+ { // c + l = l + c
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, A),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_LADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, A),
+ new SimpleInstruction(InstructionConstants.OP_LADD),
+ },
+ },
+ { // c + l = l + c
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_LADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new SimpleInstruction(InstructionConstants.OP_LADD),
+ },
+ },
+ { // c * l = l * c
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, A),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_LLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, A),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },
+ },
+ { // c + f = f + c
+ {
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, A),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_FADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, A),
+ new SimpleInstruction(InstructionConstants.OP_FADD),
+ },
+ },
+ { // c + f = f + c
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_FADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new SimpleInstruction(InstructionConstants.OP_FADD),
+ },
+ },
+ { // c * f = f * c
+ {
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, A),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_FMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, A),
+ new SimpleInstruction(InstructionConstants.OP_FMUL),
+ },
+ },
+ { // c * f = f * c
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_FLOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },
+ },
+ { // c + d = d + c
+ {
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, A),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_DADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, A),
+ new SimpleInstruction(InstructionConstants.OP_DADD),
+ },
+ },
+ { // c + d = d + c
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_DADD),
+ },{
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new SimpleInstruction(InstructionConstants.OP_DADD),
+ },
+ },
+ { // c * d = d * c
+ {
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, A),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_DMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, A),
+ new SimpleInstruction(InstructionConstants.OP_DMUL),
+ },
+ },
+ { // c * d = d * c
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_DMUL),
+ },{
+ new VariableInstruction(InstructionConstants.OP_DLOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new SimpleInstruction(InstructionConstants.OP_DMUL),
+ },
+ },
+ { // i = i + c = i += c
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, A),
+ },
+ },
+ { // i = i + b = i += b
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, A),
+ },
+ },
+ { // i = i + s = i += s
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, A),
+ },
+ },
+ { // i = i - -1 = i++
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, 1),
+ },
+ },
+ { // i = i - 1 = i--
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, -1),
+ },
+ },
+ { // i = i - 2 = i -= 2
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, -2),
+ },
+ },
+ { // i = i - 3 = i -= 3
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_3),
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, -3),
+ },
+ },
+ { // i = i - 4 = i -= 4
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_4),
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, -4),
+ },
+ },
+ { // i = i - 5 = i -= 5
+ {
+ new VariableInstruction(InstructionConstants.OP_ILOAD, X),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_5),
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ new VariableInstruction(InstructionConstants.OP_ISTORE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_IINC, X, -5),
+ },
+ },
+ { // ... + 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... + 0L = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LADD),
+ },{
+ // Nothing.
+ },
+ },
+ // Not valid for -0.0.
+// { // ... + 0f = ...
+// {
+// new SimpleInstruction(InstructionConstants.OP_FCONST_0),
+// new SimpleInstruction(InstructionConstants.OP_FADD),
+// },{
+// // Nothing.
+// },
+// },
+// { // ... + 0d = ...
+// {
+// new SimpleInstruction(InstructionConstants.OP_DCONST_0),
+// new SimpleInstruction(InstructionConstants.OP_DADD),
+// },{
+// // Nothing.
+// },
+// },
+ { // ... - 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... - 0L = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LSUB),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... - 0f = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_FSUB),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... - 0d = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_DSUB),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... * -1 = -...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_INEG),
+ },
+ },
+ { // ... * 0 = 0
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ },
+ },
+ { // ... * 1 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... * 2 = ... << 1
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 4 = ... << 2
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_4),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 8 = ... << 3
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ICONST_3),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 16 = ... << 4
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 4),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 32 = ... << 5
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 5),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 64 = ... << 6
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 64),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 6),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 128 = ... << 7
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 128),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 7),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 256 = ... << 8
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 256),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 512 = ... << 9
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 512),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 9),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 1024 = ... << 10
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 1024),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 10),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 2048 = ... << 11
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 2048),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 11),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 4096 = ... << 12
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 4096),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 12),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 8192 = ... << 13
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 8192),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 13),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 16384 = ... << 14
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 16384),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 14),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 32768 = ... << 15
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_32768),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 15),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 65536 = ... << 16
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_65536),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * 16777216 = ... << 24
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_16777216),
+ new SimpleInstruction(InstructionConstants.OP_IMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },
+ },
+ { // ... * -1L = -...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_M1),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_LNEG),
+ },
+ },
+ { // ... * 0L = 0L
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ },
+ },
+ { // ... * 1L = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_1),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... * 2L = ... << 1
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_2),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 4L = ... << 2
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_4),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 8L = ... << 3
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_8),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ICONST_3),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 16L = ... << 4
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_16),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 4),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 32L = ... << 5
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_32),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 5),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 64L = ... << 6
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_64),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 6),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 128L = ... << 7
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_128),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 7),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 256L = ... << 8
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_256),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 512L = ... << 9
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_512),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 9),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 1024L = ... << 10
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_1024),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 10),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 2048L = ... << 11
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_2048),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 11),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 4096L = ... << 12
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_4096),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 12),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 8192L = ... << 13
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_8192),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 13),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 16384L = ... << 14
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_16384),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 14),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 32768L = ... << 15
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_32768),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 15),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 65536LL = ... << 16
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_65536),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 16777216L = ... << 24
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_16777216),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * 4294967296L = ... << 32
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_4294967296),
+ new SimpleInstruction(InstructionConstants.OP_LMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },
+ },
+ { // ... * -1f = -...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, F_M1),
+ new SimpleInstruction(InstructionConstants.OP_FMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_FNEG),
+ },
+ },
+ // Not valid for -0.0 and for NaN.
+// { // ... * 0f = 0f
+// {
+// new SimpleInstruction(InstructionConstants.OP_FCONST_0),
+// new SimpleInstruction(InstructionConstants.OP_FMUL),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_POP),
+// new SimpleInstruction(InstructionConstants.OP_FCONST_0),
+// },
+// },
+ { // ... * 1f = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_FCONST_1),
+ new SimpleInstruction(InstructionConstants.OP_FMUL),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... * -1d = -...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, D_M1),
+ new SimpleInstruction(InstructionConstants.OP_DMUL),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DNEG),
+ },
+ },
+ // Not valid for -0.0 and for NaN.
+// { // ... * 0d = 0d
+// {
+// new SimpleInstruction(InstructionConstants.OP_DCONST_0),
+// new SimpleInstruction(InstructionConstants.OP_DMUL),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_POP2),
+// new SimpleInstruction(InstructionConstants.OP_DCONST_0),
+// },
+// },
+ { // ... * 1d = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_DCONST_1),
+ new SimpleInstruction(InstructionConstants.OP_DMUL),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... / -1 = -...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new SimpleInstruction(InstructionConstants.OP_IDIV),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_INEG),
+ },
+ },
+ { // ... / 1 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new SimpleInstruction(InstructionConstants.OP_IDIV),
+ },{
+ // Nothing.
+ },
+ },
+ // Not valid for negative values.
+// { // ... / 2 = ... >> 1
+// {
+// new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 4 = ... >> 2
+// {
+// new SimpleInstruction(InstructionConstants.OP_ICONST_4),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 8 = ... >> 3
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_3),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 16 = ... >> 4
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 4),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 32 = ... >> 5
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 5),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 64 = ... >> 6
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 64),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 6),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 128 = ... >> 7
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 128),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 7),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 256 = ... >> 8
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 256),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 512 = ... >> 9
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 512),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 9),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 1024 = ... >> 10
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 1024),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 10),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 2048 = ... >> 11
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 2048),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 11),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 4096 = ... >> 12
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 4096),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 12),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 8192 = ... >> 13
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 8192),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 13),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 16384 = ... >> 14
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 16384),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 14),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 32768 = ... >> 15
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC, I_32768),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 15),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 65536 = ... >> 16
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC, I_65536),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+// { // ... / 16777216 = ... >> 24
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC, I_16777216),
+// new SimpleInstruction(InstructionConstants.OP_IDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+// new SimpleInstruction(InstructionConstants.OP_ISHR),
+// },
+// },
+ { // ... / -1L = -...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_M1),
+ new SimpleInstruction(InstructionConstants.OP_LDIV),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_LNEG),
+ },
+ },
+ { // ... / 1L = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_1),
+ new SimpleInstruction(InstructionConstants.OP_LDIV),
+ },{
+ // Nothing.
+ },
+ },
+ // Not valid for negative values.
+// { // ... / 2L = ... >> 1
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_2),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 4L = ... >> 2
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_4),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 8L = ... >> 3
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_8),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_3),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 16L = ... >> 4
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_16),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 4),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 32L = ... >> 5
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_32),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 5),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 64L = ... >> 6
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_64),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 6),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 128L = ... >> 7
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_128),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 7),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 256L = ... >> 8
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_256),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 512L = ... >> 9
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_512),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 9),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 1024L = ... >> 10
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_1024),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 10),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 2048L = ... >> 11
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_2048),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 11),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 4096L = ... >> 12
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_4096),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 12),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 8192L = ... >> 13
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_8192),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 13),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 16384L = ... >> 14
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_16384),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 14),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 32768L = ... >> 15
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_32768),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 15),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 65536LL = ... >> 16
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_65536),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 16777216L = ... >> 24
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_16777216),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+// { // ... / 4294967296L = ... >> 32
+// {
+// new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_4294967296),
+// new SimpleInstruction(InstructionConstants.OP_LDIV),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+// new SimpleInstruction(InstructionConstants.OP_LSHR),
+// },
+// },
+ { // ... / -1f = -...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, F_M1),
+ new SimpleInstruction(InstructionConstants.OP_FDIV),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_FNEG),
+ },
+ },
+ { // ... / 1f = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_FCONST_1),
+ new SimpleInstruction(InstructionConstants.OP_FDIV),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... / -1d = -...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, D_M1),
+ new SimpleInstruction(InstructionConstants.OP_DDIV),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DNEG),
+ },
+ },
+ { // ... / 1d = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_DCONST_1),
+ new SimpleInstruction(InstructionConstants.OP_DDIV),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... % 1 = 0
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new SimpleInstruction(InstructionConstants.OP_IREM),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ },
+ },
+ // Not valid for negative values.
+// { // ... % 2 = ... & 0x1
+// {
+// new SimpleInstruction(InstructionConstants.OP_ICONST_2),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 4 = ... & 0x3
+// {
+// new SimpleInstruction(InstructionConstants.OP_ICONST_4),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_ICONST_3),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 8 = ... & 0x07
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 0x07),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 16 = ... & 0x0f
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 0x0f),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 32 = ... & 0x1f
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 0x1f),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 64 = ... & 0x3f
+// {
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 64),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 0x3f),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 128 = ... & 0x7f
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 128),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BIPUSH, 0x7f),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 256 = ... & 0x00ff
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 256),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0x00ff),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 512 = ... & 0x01ff
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 512),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0x01ff),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 1024 = ... & 0x03ff
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 1024),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0x03ff),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 2048 = ... & 0x07ff
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 2048),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0x07ff),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 4096 = ... & 0x0fff
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 4096),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0x0fff),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 8192 = ... & 0x1fff
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 8192),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0x1fff),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+// { // ... % 16384 = ... & 0x3fff
+// {
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 16384),
+// new SimpleInstruction(InstructionConstants.OP_IREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0x3fff),
+// new SimpleInstruction(InstructionConstants.OP_IAND),
+// },
+// },
+ { // ... % 1L = 0L
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_1),
+ new SimpleInstruction(InstructionConstants.OP_LREM),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ },
+ },
+// { // ... % 1f = 0f
+// {
+// new SimpleInstruction(InstructionConstants.OP_FCONST_1),
+// new SimpleInstruction(InstructionConstants.OP_FREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_POP),
+// new SimpleInstruction(InstructionConstants.OP_FCONST_0),
+// },
+// },
+// { // ... % 1d = 0d
+// {
+// new SimpleInstruction(InstructionConstants.OP_DCONST_1),
+// new SimpleInstruction(InstructionConstants.OP_DREM),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_POP2),
+// new SimpleInstruction(InstructionConstants.OP_DCONST_0),
+// },
+// },
+ { // -(-...) = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_INEG),
+ new SimpleInstruction(InstructionConstants.OP_INEG),
+ },{
+ // Nothing.
+ },
+ },
+ { // -(-...) = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LNEG),
+ new SimpleInstruction(InstructionConstants.OP_LNEG),
+ },{
+ // Nothing.
+ },
+ },
+ { // -(-...) = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_FNEG),
+ new SimpleInstruction(InstructionConstants.OP_FNEG),
+ },{
+ // Nothing.
+ },
+ },
+ { // -(-...) = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_DNEG),
+ new SimpleInstruction(InstructionConstants.OP_DNEG),
+ },{
+ // Nothing.
+ },
+ },
+ { // +(-...) = -...
+ {
+ new SimpleInstruction(InstructionConstants.OP_INEG),
+ new SimpleInstruction(InstructionConstants.OP_IADD),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ISUB),
+ },
+ },
+ { // +(-...) = -...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LNEG),
+ new SimpleInstruction(InstructionConstants.OP_LADD),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_LSUB),
+ },
+ },
+ { // +(-...) = -...
+ {
+ new SimpleInstruction(InstructionConstants.OP_FNEG),
+ new SimpleInstruction(InstructionConstants.OP_FADD),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_FSUB),
+ },
+ },
+ { // +(-...) = -...
+ {
+ new SimpleInstruction(InstructionConstants.OP_DNEG),
+ new SimpleInstruction(InstructionConstants.OP_DADD),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DSUB),
+ },
+ },
+ { // ... << 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... << 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... >> 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... >> 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LSHR),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... >>> 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... >>> 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LUSHR),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... & -1 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... & 0 = 0
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ },
+ },
+ { // ... & -1L = ...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_M1),
+ new SimpleInstruction(InstructionConstants.OP_LAND),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... & 0L = 0L
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LAND),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ },
+ },
+ { // ... | -1 = -1
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new SimpleInstruction(InstructionConstants.OP_IOR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ },
+ },
+ { // ... | 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_IOR),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... | -1L = -1L
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_M1),
+ new SimpleInstruction(InstructionConstants.OP_LAND),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_M1),
+ },
+ },
+ { // ... | 0L = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LOR),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... ^ 0 = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new SimpleInstruction(InstructionConstants.OP_IXOR),
+ },{
+ // Nothing.
+ },
+ },
+ { // ... ^ 0L = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0),
+ new SimpleInstruction(InstructionConstants.OP_LXOR),
+ },{
+ // Nothing.
+ },
+ },
+ { // (... & 0x0000ff00) >> 8 = (... >> 8) & 0xff
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0x0000ff00),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0xff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },
+ },
+ { // (... & 0x0000ff00) >>> 8 = (... >>> 8) & 0xff
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0x0000ff00),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 8),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0xff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },
+ },
+ { // (... & 0x00ff0000) >> 16 = (... >> 16) & 0xff
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0x00ff0000),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0xff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },
+ },
+ { // (... & 0x00ff0000) >>> 16 = (... >>> 16) & 0xff
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0x00ff0000),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0xff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },
+ },
+ { // (... & 0xff000000) >> 24 = ... >> 24
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0xff000000),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },
+ },
+ { // (... & 0xffff0000) >> 16 = ... >> 16
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0xffff0000),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },
+ },
+ { // (... & 0xffff0000) >>> 16 = ... >>> 16
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0xffff0000),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },
+ },
+ { // (... >> 24) & 0xff = ... >>> 24
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0xff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },
+ },
+ { // (... >>> 24) & 0xff = ... >>> 24
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0xff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },
+ },
+ { // (byte)(... & 0x000000ff) = (byte)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, 0xff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },
+ },
+ { // (char)(... & 0x0000ffff) = (char)...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0x0000ffff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },
+ },
+ { // (short)(... & 0x0000ffff) = (short)...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, I_0x0000ffff),
+ new SimpleInstruction(InstructionConstants.OP_IAND),
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },
+ },
+ { // (byte)(... >> 24) = ... >> 24
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },
+ },
+ { // (byte)(... >>> 24) = ... >> 24
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },
+ },
+ { // (char)(... >> 16) = ... >>> 16
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },
+ },
+ { // (char)(... >>> 16) = ... >>> 16
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },
+ },
+ { // (short)(... >> 16) = ... >> 16
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },
+ },
+ { // (short)(... >>> 16) = ... >> 16
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },
+ },
+ { // ... << 24 >> 24 = (byte)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 24),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },
+ },
+ { // ... << 16 >>> 16 = (char)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_IUSHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },
+ },
+ { // ... << 16 >> 16 = (short)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHL),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 16),
+ new SimpleInstruction(InstructionConstants.OP_ISHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },
+ },
+ { // ... << 32 >> 32 = (long)(int)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_LSHL),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_LSHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_L2I),
+ new SimpleInstruction(InstructionConstants.OP_I2L),
+ },
+ },
+ { // (int)(... & 0x00000000ffffffffL) = (int)...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_0x00000000ffffffff),
+ new SimpleInstruction(InstructionConstants.OP_LAND),
+ new SimpleInstruction(InstructionConstants.OP_L2I),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_L2I),
+ },
+ },
+ { // (... & 0xffffffff00000000L) >> 32 = ... >> 32
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_0xffffffff00000000),
+ new SimpleInstruction(InstructionConstants.OP_LAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_LSHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_LSHR),
+ },
+ },
+ { // (... & 0xffffffff00000000L) >>> 32 = ... >>> 32
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, L_0xffffffff00000000),
+ new SimpleInstruction(InstructionConstants.OP_LAND),
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_LUSHR),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, 32),
+ new SimpleInstruction(InstructionConstants.OP_LUSHR),
+ },
+ },
+ { // ... += 0 = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_IINC, X, 0),
+ },{
+ // Nothing.
+ },
+ },
+ };
+
+ public static final Instruction[][][] FIELD = new Instruction[][][]
+ {
+ { // getfield/putfield = nothing
+ {
+ new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Y),
+ new ConstantInstruction(InstructionConstants.OP_PUTFIELD, Y),
+ },{
+ // Nothing.
+ },
+ },
+// { // putfield_L/putfield_L = pop2_x1/putfield
+// {
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_L),
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_L),
+// },{
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new SimpleInstruction(InstructionConstants.OP_POP2),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_L),
+// },
+// },
+// { // putfield_D/putfield_D = pop2_x1/putfield
+// {
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_D),
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_D),
+// },{
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new SimpleInstruction(InstructionConstants.OP_POP2),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_D),
+// },
+// },
+// { // putfield/putfield = pop_x1/putfield
+// {
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, Y),
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, Y),
+// },{
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new SimpleInstruction(InstructionConstants.OP_POP),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, Y),
+// },
+// },
+// { // putfield_L/getfield_L = dup2_x1/putfield
+// {
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_L),
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// new ConstantInstruction(InstructionConstants.OP_GETFIELD, FIELD_L),
+// },{
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new SimpleInstruction(InstructionConstants.OP_DUP2_X1),
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_L),
+// },
+// },
+// { // putfield_D/getfield_D = dup2_x1/putfield
+// {
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_D),
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// new ConstantInstruction(InstructionConstants.OP_GETFIELD, FIELD_D),
+// },{
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new SimpleInstruction(InstructionConstants.OP_DUP2_X1),
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, FIELD_D),
+// },
+// },
+// { // putfield/getfield = dup_x1/putfield
+// {
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, Y),
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// new ConstantInstruction(InstructionConstants.OP_GETFIELD, Y),
+// },{
+// new VariableInstruction(InstructionConstants.OP_ALOAD, X),
+// // ...
+// new SimpleInstruction(InstructionConstants.OP_DUP_X1),
+// new ConstantInstruction(InstructionConstants.OP_PUTFIELD, Y),
+// },
+// },
+ { // getstatic/putstatic = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, X),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // putstatic_L/putstatic_L = pop2/putstatic
+ {
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_L),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_L),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_L),
+ },
+ },
+ { // putstatic_D/putstatic_D = pop2/putstatic
+ {
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_D),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_D),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_D),
+ },
+ },
+ { // putstatic/putstatic = pop/putstatic
+ {
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, X),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, X),
+ },
+ },
+ { // putstatic_L/getstatic_L = dup2/putstatic
+ {
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_L),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, FIELD_L),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP2),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_L),
+ },
+ },
+ { // putstatic_D/getstatic_D = dup2/putstatic
+ {
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_D),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, FIELD_D),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP2),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, FIELD_D),
+ },
+ },
+ { // putstatic/getstatic = dup/putstatic
+ {
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, X),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, X),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_PUTSTATIC, X),
+ },
+ },
+ };
+
+ public static final Instruction[][][] CAST = new Instruction[][][]
+ {
+ { // (byte)(byte)... = (byte)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },
+ },
+ { // (byte)(char)... = (byte)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },
+ },
+ { // (byte)(short)... = (byte)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },
+ },
+ { // (char)(char)... = (char)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },
+ },
+ { // (char)(short)... = (char)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ },
+ },
+ { // (short)(byte)... = (byte)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2B),
+ },
+ },
+ { // (short)(char)... = (short)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2C),
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },
+ },
+ { // (short)(short)... = (short)...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_I2S),
+ },
+ },
+ { // (int)(long)... = ...
+ {
+ new SimpleInstruction(InstructionConstants.OP_I2L),
+ new SimpleInstruction(InstructionConstants.OP_L2I),
+ },{
+ // Nothing.
+ },
+ },
+ { // (X)(X)... = (X)...
+ {
+ new ConstantInstruction(InstructionConstants.OP_CHECKCAST, X),
+ new ConstantInstruction(InstructionConstants.OP_CHECKCAST, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_CHECKCAST, X),
+ },
+ },
+ // Not handled correctly in all cases by VMs prior to Java 6...
+// { // (byte)bytes[...] = bytes[...]
+// {
+// new SimpleInstruction(InstructionConstants.OP_BALOAD),
+// new SimpleInstruction(InstructionConstants.OP_I2B),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BALOAD),
+// },
+// },
+// { // (short)bytes[...] = bytes[...]
+// {
+// new SimpleInstruction(InstructionConstants.OP_BALOAD),
+// new SimpleInstruction(InstructionConstants.OP_I2S),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BALOAD),
+// },
+// },
+// { // (char)chars[...] = chars[...]
+// {
+// new SimpleInstruction(InstructionConstants.OP_CALOAD),
+// new SimpleInstruction(InstructionConstants.OP_I2C),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_CALOAD),
+// },
+// },
+// { // (short)shorts[...] = shorts[...]
+// {
+// new SimpleInstruction(InstructionConstants.OP_SALOAD),
+// new SimpleInstruction(InstructionConstants.OP_I2S),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SALOAD),
+// },
+// },
+// { // bytes[...] = (byte)... = bytes[...] = ...
+// {
+// new SimpleInstruction(InstructionConstants.OP_I2B),
+// new SimpleInstruction(InstructionConstants.OP_BASTORE),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_BASTORE),
+// },
+// },
+// { // chars[...] = (char)... = chars[...] = ...
+// {
+// new SimpleInstruction(InstructionConstants.OP_I2C),
+// new SimpleInstruction(InstructionConstants.OP_CASTORE),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_CASTORE),
+// },
+// },
+// { // shorts[...] = (short)... = shorts[...] = ...
+// {
+// new SimpleInstruction(InstructionConstants.OP_I2S),
+// new SimpleInstruction(InstructionConstants.OP_SASTORE),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SASTORE),
+// },
+// },
+ };
+
+ public static final Instruction[][][] BRANCH = new Instruction[][][]
+ {
+ { // goto +3 = nothing
+ {
+ new BranchInstruction(InstructionConstants.OP_GOTO, 3),
+ },{
+ // Nothing.
+ },
+ },
+ { // ifeq +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFEQ, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // ifne +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFNE, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // iflt +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFLT, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // ifge +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFGE, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // ifgt +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFGT, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // ifle +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFLE, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // ificmpeq +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPEQ, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ificmpne +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPNE, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ificmplt +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ificmpge +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ificmpgt +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ificmple +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ifacmpeq +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFACMPEQ, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ifacmpne +3 = pop2
+ {
+ new BranchInstruction(InstructionConstants.OP_IFACMPNE, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP2),
+ },
+ },
+ { // ifnull +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFNULL, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // ifnonnull +3 = pop
+ {
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, 3),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // if (... == 0) = ifeq
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFICMPEQ, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },
+ },
+ { // if (0 == i) = iload/ifeq
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPEQ, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },
+ },
+ { // if (0 == i) = getstatic/ifeq
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPEQ, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },
+ },
+ { // if (0 == i) = getfield/ifeq
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPEQ, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },
+ },
+ { // if (... != 0) = ifne
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFICMPNE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },
+ },
+ { // if (0 != i) = iload/ifeq
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPNE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },
+ },
+ { // if (0 != i) = getstatic/ifeq
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPNE, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },
+ },
+ { // if (0 != i) = getfield/ifeq
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPNE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },
+ },
+ { // if (... < 0) = iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (... < 1) = ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (0 > i) = iload/iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (1 > i) = iload/ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (0 > i) = getstatic/iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (1 > i) = getstatic/ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (0 > i) = getfield/iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (1 > i) = getfield/ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (... >= 0) = ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (... >= 1) = ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (0 <= i) = iload/ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (1 <= i) = iload/ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (0 <= i) = getstatic/ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (1 <= i) = getstatic/ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (0 <= i) = getfield/ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (1 <= i) = getfield/ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (... > 0) = ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (... > -1) = ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (0 < i) = iload/ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (-1 < i) = iload/ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (0 < i) = getstatic/ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (-1 < i) = getstatic/ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (0 < i) = getfield/ifgt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // if (-1 < i) = getfield/ifge
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // if (... <= 0) = ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (... <= -1) = iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (0 >= i) = iload/ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (-1 >= i) = iload/iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (0 >= i) = getstatic/ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (-1 >= i) = getstatic/iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (0 >= i) = getfield/ifle
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // if (-1 >= i) = getfield/iflt
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_M1),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // if (... == null) = ifnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new BranchInstruction(InstructionConstants.OP_IFACMPEQ, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFNULL, X),
+ },
+ },
+ { // if (null == a) = aload/ifnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFACMPEQ, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFNULL, X),
+ },
+ },
+ { // if (null == a) = getstatic/ifnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFACMPEQ, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFNULL, X),
+ },
+ },
+ { // if (null == a) = getfield/ifnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFACMPEQ, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFNULL, X),
+ },
+ },
+ { // if (... != null) = ifnonnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new BranchInstruction(InstructionConstants.OP_IFACMPNE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, X),
+ },
+ },
+ { // if (null != a) = aload/ifnonnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFACMPNE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, X),
+ },
+ },
+ { // if (null != a) = getstatic/ifnonnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFACMPNE, X),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_GETSTATIC, Y),
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, X),
+ },
+ },
+ { // if (null != a) = getfield/ifnonnull
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFACMPNE, X),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, Y),
+ new ConstantInstruction(InstructionConstants.OP_GETFIELD, Z),
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, X),
+ },
+ },
+ { // iconst_0/ifeq = goto
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },
+ },
+ { // iconst/ifeq = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // bipush/ifeq = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, A),
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // sipush/ifeq = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // iconst_0/ifne = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // iconst/ifne = goto
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },
+ },
+ { // bipush/ifne = goto
+ {
+ new SimpleInstruction(InstructionConstants.OP_BIPUSH, A),
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },
+ },
+ { // sipush/ifne = goto
+ {
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, A),
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },
+ },
+ { // iconst_0/iflt = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // iconst_0/ifge = goto
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },
+ },
+ { // iconst_0/ifgt = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // iconst_0/ifle = goto
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0),
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },
+ },
+ { // aconst_null/ifnull = goto
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new BranchInstruction(InstructionConstants.OP_IFNULL, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },
+ },
+ { // aconst_null/ifnonnul = nothing
+ {
+ new SimpleInstruction(InstructionConstants.OP_ACONST_NULL),
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, X),
+ },{
+ // Nothing.
+ },
+ },
+ { // ifeq/goto = ifne
+ {
+ new BranchInstruction(InstructionConstants.OP_IFEQ, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFNE, X),
+ },
+ },
+ { // ifne/goto = ifeq
+ {
+ new BranchInstruction(InstructionConstants.OP_IFNE, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFEQ, X),
+ },
+ },
+ { // iflt/goto = ifge
+ {
+ new BranchInstruction(InstructionConstants.OP_IFLT, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFGE, X),
+ },
+ },
+ { // ifge/goto = iflt
+ {
+ new BranchInstruction(InstructionConstants.OP_IFGE, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFLT, X),
+ },
+ },
+ { // ifgt/goto = ifle
+ {
+ new BranchInstruction(InstructionConstants.OP_IFGT, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFLE, X),
+ },
+ },
+ { // ifle/goto = ifgt
+ {
+ new BranchInstruction(InstructionConstants.OP_IFLE, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFGT, X),
+ },
+ },
+ { // ificmpeq/goto = ificmpne
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPEQ, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFICMPNE, X),
+ },
+ },
+ { // ificmpne/goto = ificmpeq
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPNE, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFICMPEQ, X),
+ },
+ },
+ { // ificmplt/goto = ificmpge
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, X),
+ },
+ },
+ { // ificmpge/goto = ificmplt
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPGE, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFICMPLT, X),
+ },
+ },
+ { // ificmpgt/goto = ificmple
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, X),
+ },
+ },
+ { // ificmple/goto = ificmpgt
+ {
+ new BranchInstruction(InstructionConstants.OP_IFICMPLE, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFICMPGT, X),
+ },
+ },
+ { // ifacmpeq/goto = ifacmpne
+ {
+ new BranchInstruction(InstructionConstants.OP_IFACMPEQ, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFACMPNE, X),
+ },
+ },
+ { // ifacmpne/goto = ifacmpeq
+ {
+ new BranchInstruction(InstructionConstants.OP_IFACMPNE, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFACMPEQ, X),
+ },
+ },
+ { // ifnull/goto = ifnonnull
+ {
+ new BranchInstruction(InstructionConstants.OP_IFNULL, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, X),
+ },
+ },
+ { // ifnonnull/goto = ifnull
+ {
+ new BranchInstruction(InstructionConstants.OP_IFNONNULL, 6),
+ new BranchInstruction(InstructionConstants.OP_GOTO, X),
+ },{
+ new BranchInstruction(InstructionConstants.OP_IFNULL, X),
+ },
+ },
+// { // switch (...) { default: ... } = pop/goto ...
+// {
+// new TableSwitchInstruction(InstructionConstants.OP_TABLESWITCH, A, X, Y, 0, new int[0]),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_POP),
+// new BranchInstruction(InstructionConstants.OP_GOTO, A),
+// },
+// },
+// { // switch (...) { default: ... } = pop/goto ...
+// {
+// new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, A, 0, new int[0], new int[0]),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_POP),
+// new BranchInstruction(InstructionConstants.OP_GOTO, A),
+// },
+// },
+ { // switch (...) { case/case/default: ... } = switch (...) { case/default: ... }
+ {
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, A, new int[] { X, Y }, new int[] { A, B }),
+ },{
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, A, new int[] { Y }, new int[] { B }),
+ },
+ },
+ { // switch (...) { case/case/default: ... } = switch (...) { case/default: ... }
+ {
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, B, new int[] { X, Y }, new int[] { A, B }),
+ },{
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, B, new int[] { X }, new int[] { A }),
+ },
+ },
+ { // switch (...) { case/case/case/default: ... } = switch (...) { case/case/default: ... }
+ {
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, A, new int[] { X, Y, Z }, new int[] { A, B, C }),
+ },{
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, A, new int[] { Y, Z }, new int[] { B, C }),
+ },
+ },
+ { // switch (...) { case/case/case/default: ... } = switch (...) { case/case/default: ... }
+ {
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, B, new int[] { X, Y, Z }, new int[] { A, B, C }),
+ },{
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, B, new int[] { X, Z }, new int[] { A, C }),
+ },
+ },
+ { // switch (...) { case/case/case/default: ... } = switch (...) { case/case/default: ... }
+ {
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, C, new int[] { X, Y, Z }, new int[] { A, B, C }),
+ },{
+ new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, C, new int[] { X, Y }, new int[] { A, B }),
+ },
+ },
+// { // switch (...) { case ...: ... default: ... }
+// // = if (... == ...) ... else ...
+// {
+// new TableSwitchInstruction(InstructionConstants.OP_TABLESWITCH, A, X, Y, 1, new int[] { B }),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, X),
+// new BranchInstruction(InstructionConstants.OP_IFICMPNE, A),
+// new BranchInstruction(InstructionConstants.OP_GOTO, B),
+// },
+// },
+// { // switch (...) { case ...: ... default: ... }
+// // = if (... == ...) ... else ...
+// {
+// new LookUpSwitchInstruction(InstructionConstants.OP_LOOKUPSWITCH, A, 1, new int[] { X }, new int[] { B }),
+// },{
+// new SimpleInstruction(InstructionConstants.OP_SIPUSH, X),
+// new BranchInstruction(InstructionConstants.OP_IFICMPNE, A),
+// new BranchInstruction(InstructionConstants.OP_GOTO, B),
+// },
+// }
+ };
+
+ public static final Instruction[][][] STRING = new Instruction[][][]
+ {
+ { // "...".equals("...") = true
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRING_EQUALS),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_ICONST_1),
+ },
+ },
+ { // "...".length() = ...
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRING_LENGTH),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, STRING_A_LENGTH),
+ },
+ },
+ { // String.valueOf(Z) = "....
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_Z),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, BOOLEAN_A_STRING),
+ },
+ },
+ { // String.valueOf(C) = "...."
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, CHAR_A_STRING),
+ },
+ },
+ { // String.valueOf(Cc) = "...."
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, CHAR_A_STRING),
+ },
+ },
+ { // String.valueOf(I) = "...."
+ {
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, INT_A_STRING),
+ },
+ },
+ { // String.valueOf(Ic) = "...."
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, INT_A_STRING),
+ },
+ },
+ { // String.valueOf(J) = "...."
+ {
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, LONG_A_STRING),
+ },
+ },
+ { // String.valueOf(Jc) = "...."
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, LONG_A_STRING),
+ },
+ },
+ { // String.valueOf(F) = "...."
+ {
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, FLOAT_A_STRING),
+ },
+ },
+ { // String.valueOf(Fc) = "...."
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, FLOAT_A_STRING),
+ },
+ },
+ { // String.valueOf(D) = "...."
+ {
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, DOUBLE_A_STRING),
+ },
+ },
+ { // String.valueOf(Dc) = "...."
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, DOUBLE_A_STRING),
+ },
+ },
+
+ { // new StringBuffer("...").toString() = "..." (ignoring identity)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ },
+ },
+ { // new StringBuffer(string).toString() = string (ignoring identity)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ },
+ },
+ { // new StringBuffer("...").length() = length
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_LENGTH),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, STRING_A_LENGTH),
+ },
+ },
+ { // new StringBuffer() (without dup) = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...") (without dup) = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer()/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...")/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...").append(z)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_Z),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...").append(c)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...").append(i)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...").append(l)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...").append(f)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...").append(d)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer("...").append(s)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // StringBuffer#toString()/pop = pop
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // StringBuffer#append("") = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_EMPTY),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuffer().append(Z) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_Z),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, BOOLEAN_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(C) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, CHAR_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(Cc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, CHAR_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(I) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, INT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(Ic) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, INT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(J) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, LONG_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(Jc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, LONG_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(F) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, FLOAT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(Fc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, FLOAT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(D) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, DOUBLE_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append(Dc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, DOUBLE_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer().append("...") = new StringBuffer("...")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(Z) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_Z),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | BOOLEAN_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(C) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(Cc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(I) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(Ic) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(J) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(Jc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(F) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(Fc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(D) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append(Dc) = new StringBuffer("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // new StringBuffer("...").append("...") = new StringBuffer("......")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | STRING_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(Z) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_Z),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | BOOLEAN_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(C) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(Cc) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(I) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(Ic) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(J) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(Jc) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(F) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(Fc) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(D) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append(Dc) = StringBuffer#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // StringBuffer#append("...").append("...") = StringBuffer#append("......")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | STRING_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ },
+ },
+ { // new StringBuffer().append(z).toString() = String.valueOf(z)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_Z),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_Z),
+ },
+ },
+ { // new StringBuffer().append(c).toString() = String.valueOf(c)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_C),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_C),
+ },
+ },
+ { // new StringBuffer().append(i).toString() = String.valueOf(i)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_I),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_I),
+ },
+ },
+ { // new StringBuffer().append(j).toString() = String.valueOf(j)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_J),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_LLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_J),
+ },
+ },
+ { // new StringBuffer().append(f).toString() = String.valueOf(f)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_F),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_FLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_F),
+ },
+ },
+ { // new StringBuffer().append(d).toString() = String.valueOf(d)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_D),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_DLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_D),
+ },
+ },
+ { // new StringBuffer().append(string).toString() = string
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ },
+ },
+ { // new StringBuffer().append(object).toString() = String.valueOf(object)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUFFER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUFFER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_APPEND_OBJECT),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUFFER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_OBJECT),
+ },
+ },
+
+ { // new StringBuilder("...").toString() = "..." (ignoring identity)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ },
+ },
+ { // new StringBuilder(string).toString() = string (ignoring identity)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ },
+ },
+ { // new StringBuilder("...").length() = length
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_LENGTH),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_SIPUSH, STRING_A_LENGTH),
+ },
+ },
+ { // new StringBuilder() (without dup) = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...") (without dup) = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder()/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...")/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...").append(z)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_Z),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...").append(c)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...").append(i)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...").append(l)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...").append(f)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...").append(d)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder("...").append(s)/pop = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ // Nothing.
+ },
+ },
+ { // StringBuilder#toString()/pop = pop
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },{
+ new SimpleInstruction(InstructionConstants.OP_POP),
+ },
+ },
+ { // StringBuilder#append("") = nothing
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_EMPTY),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },{
+ // Nothing.
+ },
+ },
+ { // new StringBuilder().append(Z) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_Z),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, BOOLEAN_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(C) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, CHAR_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(Cc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, CHAR_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(I) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, INT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(Ic) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, INT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(J) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, LONG_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(Jc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, LONG_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(F) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, FLOAT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(Fc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, FLOAT_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(D) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, DOUBLE_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append(Dc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, DOUBLE_A_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder().append("...") = new StringBuilder("...")
+ {
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(Z) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_Z),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | BOOLEAN_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(C) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(Cc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(I) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(Ic) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(J) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(Jc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(F) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(Fc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(D) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append(Dc) = new StringBuilder("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // new StringBuilder("...").append("...") = new StringBuilder("......")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | STRING_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(Z) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_Z),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | BOOLEAN_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(C) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(Cc) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | CHAR_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(I) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_ICONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(Ic) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | INT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(J) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_LCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(Jc) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | LONG_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(F) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_FCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(Fc) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | FLOAT_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(D) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new SimpleInstruction(InstructionConstants.OP_DCONST_0, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append(Dc) = StringBuilder#append("....")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC2_W, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | DOUBLE_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // StringBuilder#append("...").append("...") = StringBuilder#append("......")
+ {
+ new ConstantInstruction(InstructionConstants.OP_LDC, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_LDC, B),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },{
+ new ConstantInstruction(InstructionConstants.OP_LDC, STRING_A_STRING | STRING_B_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ },
+ },
+ { // new StringBuilder().append(z).toString() = String.valueOf(z)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_Z),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_Z),
+ },
+ },
+ { // new StringBuilder().append(c).toString() = String.valueOf(c)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_C),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_C),
+ },
+ },
+ { // new StringBuilder().append(i).toString() = String.valueOf(i)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_I),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ILOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_I),
+ },
+ },
+ { // new StringBuilder().append(j).toString() = String.valueOf(j)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_LLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_J),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_LLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_J),
+ },
+ },
+ { // new StringBuilder().append(f).toString() = String.valueOf(f)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_FLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_F),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_FLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_F),
+ },
+ },
+ { // new StringBuilder().append(d).toString() = String.valueOf(d)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_DLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_D),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_DLOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_D),
+ },
+ },
+ { // new StringBuilder().append(string).toString() = string
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_STRING),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ },
+ },
+ { // new StringBuilder().append(object).toString() = String.valueOf(object)
+ {
+ new ConstantInstruction(InstructionConstants.OP_NEW, CLASS_STRINGBUILDER),
+ new SimpleInstruction(InstructionConstants.OP_DUP),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESPECIAL, METHOD_STRINGBUILDER_INIT),
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_APPEND_OBJECT),
+ new ConstantInstruction(InstructionConstants.OP_INVOKEVIRTUAL, METHOD_STRINGBUILDER_TOSTRING),
+ },{
+ new VariableInstruction(InstructionConstants.OP_ALOAD, A),
+ new ConstantInstruction(InstructionConstants.OP_INVOKESTATIC, METHOD_STRING_VALUEOF_OBJECT),
+ },
+ },
+ };
+
+
+ /**
+ * Prints out the constants and the instruction sequences.
+ */
+ public static void main(String[] args)
+ {
+ ProgramClass clazz = new ProgramClass();
+ clazz.constantPool = CONSTANTS;
+
+ ClassPrinter printer = new ClassPrinter();
+
+ for (int index = 0; index < CONSTANTS.length; index++)
+ {
+ System.out.print("["+index+"] ");
+ try
+ {
+ CONSTANTS[index].accept(clazz, printer);
+ }
+ catch (Exception e)
+ {
+ System.out.println("("+e.getClass().getName()+")");
+ }
+ }
+
+ if (CONSTANTS.length != SENTINEL)
+ {
+ throw new IllegalStateException("Constants length ["+CONSTANTS.length+"] different from number of constant names ["+SENTINEL+"]");
+ }
+
+ Instruction[][][] sequences = STRING;
+
+ for (int sequence = 0; sequence < sequences.length; sequence++)
+ {
+ System.out.println();
+ Instruction[] instructions = sequences[sequence][0];
+ for (int index = 0; index < instructions.length; index++)
+ {
+ Instruction instruction = instructions[index];
+ try
+ {
+ instruction.accept(clazz, null, null, index, new ClassPrinter());
+ }
+ catch (Exception e) {}
+ }
+
+ System.out.println("=>");
+ instructions = sequences[sequence][1];
+ for (int index = 0; index < instructions.length; index++)
+ {
+ Instruction instruction = instructions[index];
+ try
+ {
+ instruction.accept(clazz, null, null, index, new ClassPrinter());
+ }
+ catch (Exception e) {}
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/peephole/InstructionSequenceReplacer.java b/src/proguard/optimize/peephole/InstructionSequenceReplacer.java
new file mode 100644
index 000000000..7ec1a95af
--- /dev/null
+++ b/src/proguard/optimize/peephole/InstructionSequenceReplacer.java
@@ -0,0 +1,420 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.CodeAttribute;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+
+/**
+ * This InstructionVisitor replaces a given pattern instruction sequence by
+ * another given replacement instruction sequence. The arguments of the
+ * instruction sequences can be wildcards that are matched and replaced.
+ *
+ * @see InstructionSequenceMatcher
+ * @author Eric Lafortune
+ */
+public class InstructionSequenceReplacer
+extends SimplifiedVisitor
+implements InstructionVisitor,
+ ConstantVisitor
+{
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ public static boolean DEBUG = true;
+ //*/
+
+ public static final int X = InstructionSequenceMatcher.X;
+ public static final int Y = InstructionSequenceMatcher.Y;
+ public static final int Z = InstructionSequenceMatcher.Z;
+
+ public static final int A = InstructionSequenceMatcher.A;
+ public static final int B = InstructionSequenceMatcher.B;
+ public static final int C = InstructionSequenceMatcher.C;
+ public static final int D = InstructionSequenceMatcher.D;
+
+ private static final int BOOLEAN_STRING = 0x1;
+ private static final int CHAR_STRING = 0x2;
+ private static final int INT_STRING = 0x3;
+ private static final int LONG_STRING = 0x4;
+ private static final int FLOAT_STRING = 0x5;
+ private static final int DOUBLE_STRING = 0x6;
+ private static final int STRING_STRING = 0x7;
+
+ public static final int STRING_A_LENGTH = 0x20000000;
+ public static final int BOOLEAN_A_STRING = 0x20000001;
+ public static final int CHAR_A_STRING = 0x20000002;
+ public static final int INT_A_STRING = 0x20000003;
+ public static final int LONG_A_STRING = 0x20000004;
+ public static final int FLOAT_A_STRING = 0x20000005;
+ public static final int DOUBLE_A_STRING = 0x20000006;
+ public static final int STRING_A_STRING = 0x20000007;
+ public static final int BOOLEAN_B_STRING = 0x20000010;
+ public static final int CHAR_B_STRING = 0x20000020;
+ public static final int INT_B_STRING = 0x20000030;
+ public static final int LONG_B_STRING = 0x20000040;
+ public static final int FLOAT_B_STRING = 0x20000050;
+ public static final int DOUBLE_B_STRING = 0x20000060;
+ public static final int STRING_B_STRING = 0x20000070;
+
+
+ private final InstructionSequenceMatcher instructionSequenceMatcher;
+ private final Constant[] patternConstants;
+ private final Instruction[] replacementInstructions;
+ private final BranchTargetFinder branchTargetFinder;
+ private final CodeAttributeEditor codeAttributeEditor;
+ private final InstructionVisitor extraInstructionVisitor;
+
+ private final MyReplacementInstructionFactory replacementInstructionFactory = new MyReplacementInstructionFactory();
+
+
+ /**
+ * Creates a new InstructionSequenceReplacer.
+ * @param patternConstants any constants referenced by the pattern
+ * instruction.
+ * @param patternInstructions the pattern instruction sequence.
+ * @param replacementInstructions the replacement instruction sequence.
+ * @param branchTargetFinder a branch target finder that has been
+ * initialized to indicate branch targets
+ * in the visited code.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ */
+ public InstructionSequenceReplacer(Constant[] patternConstants,
+ Instruction[] patternInstructions,
+ Instruction[] replacementInstructions,
+ BranchTargetFinder branchTargetFinder,
+ CodeAttributeEditor codeAttributeEditor)
+ {
+ this(patternConstants,
+ patternInstructions,
+ replacementInstructions,
+ branchTargetFinder,
+ codeAttributeEditor,
+ null);
+ }
+
+
+ /**
+ * Creates a new InstructionSequenceReplacer.
+ * @param patternConstants any constants referenced by the pattern
+ * instruction.
+ * @param branchTargetFinder a branch target finder that has been
+ * initialized to indicate branch targets
+ * in the visited code.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ * @param extraInstructionVisitor an optional extra visitor for all deleted
+ * load instructions.
+ */
+ public InstructionSequenceReplacer(Constant[] patternConstants,
+ Instruction[] patternInstructions,
+ Instruction[] replacementInstructions,
+ BranchTargetFinder branchTargetFinder,
+ CodeAttributeEditor codeAttributeEditor,
+ InstructionVisitor extraInstructionVisitor)
+ {
+ this.instructionSequenceMatcher = new InstructionSequenceMatcher(patternConstants, patternInstructions);
+ this.patternConstants = patternConstants;
+ this.replacementInstructions = replacementInstructions;
+ this.branchTargetFinder = branchTargetFinder;
+ this.codeAttributeEditor = codeAttributeEditor;
+ this.extraInstructionVisitor = extraInstructionVisitor;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ // Reset the instruction sequence matcher if the instruction is a branch
+ // target or if it has already been modified.
+ if (branchTargetFinder.isTarget(offset) ||
+ codeAttributeEditor.isModified(offset))
+ {
+ instructionSequenceMatcher.reset();
+ }
+
+ // Try to match the instruction.
+ instruction.accept(clazz, method, codeAttribute, offset, instructionSequenceMatcher);
+
+ // Did the instruction sequence match and is it still unmodified?
+ if (instructionSequenceMatcher.isMatching() &&
+ matchedInstructionsUnmodified())
+ {
+ if (DEBUG)
+ {
+ System.out.println("InstructionSequenceReplacer: ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ System.out.println(" Matched:");
+ for (int index = 0; index < instructionSequenceMatcher.instructionCount(); index++)
+ {
+ int matchedOffset = instructionSequenceMatcher.matchedInstructionOffset(index);
+ System.out.println(" "+InstructionFactory.create(codeAttribute.code, matchedOffset).toString(matchedOffset));
+ }
+ System.out.println(" Replacement:");
+ for (int index = 0; index < replacementInstructions.length; index++)
+ {
+ int matchedOffset = instructionSequenceMatcher.matchedInstructionOffset(index);
+ System.out.println(" "+replacementInstructionFactory.create(clazz, index).shrink().toString(matchedOffset));
+ }
+ }
+
+ // Replace the instruction sequence.
+ for (int index = 0; index < replacementInstructions.length; index++)
+ {
+ codeAttributeEditor.replaceInstruction(instructionSequenceMatcher.matchedInstructionOffset(index),
+ replacementInstructionFactory.create(clazz, index));
+ }
+
+ // Delete any remaining instructions in the from sequence.
+ for (int index = replacementInstructions.length; index < instructionSequenceMatcher.instructionCount(); index++)
+ {
+ codeAttributeEditor.deleteInstruction(instructionSequenceMatcher.matchedInstructionOffset(index));
+ }
+
+ // Visit the instruction, if required.
+ if (extraInstructionVisitor != null)
+ {
+ instruction.accept(clazz,
+ method,
+ codeAttribute,
+ offset,
+ extraInstructionVisitor);
+ }
+ }
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether the matched pattern instructions haven't been modified
+ * before.
+ */
+ private boolean matchedInstructionsUnmodified()
+ {
+ for (int index = 0; index < instructionSequenceMatcher.instructionCount(); index++)
+ {
+ if (codeAttributeEditor.isModified(instructionSequenceMatcher.matchedInstructionOffset(index)))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * This class creates replacement instructions for matched sequences, with
+ * any matched arguments filled out.
+ */
+ private class MyReplacementInstructionFactory
+ implements InstructionVisitor
+ {
+ private Instruction replacementInstruction;
+
+
+ /**
+ * Creates the replacement instruction for the given index in the
+ * instruction sequence.
+ */
+ public Instruction create(Clazz clazz, int index)
+ {
+ // Create the instruction.
+ replacementInstructions[index].accept(clazz,
+ null,
+ null,
+ instructionSequenceMatcher.matchedInstructionOffset(index),
+ this);
+
+ // Return it.
+ return replacementInstruction;
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ replacementInstruction =
+ new SimpleInstruction(simpleInstruction.opcode,
+ matchedArgument(clazz, simpleInstruction.constant));
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ replacementInstruction =
+ new VariableInstruction(variableInstruction.opcode,
+ instructionSequenceMatcher.matchedArgument(variableInstruction.variableIndex),
+ instructionSequenceMatcher.matchedArgument(variableInstruction.constant));
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ replacementInstruction =
+ new ConstantInstruction(constantInstruction.opcode,
+ matchedConstantIndex((ProgramClass)clazz,
+ constantInstruction.constantIndex),
+ instructionSequenceMatcher.matchedArgument(constantInstruction.constant));
+ }
+
+
+ public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
+ {
+ replacementInstruction =
+ new BranchInstruction(branchInstruction.opcode,
+ instructionSequenceMatcher.matchedBranchOffset(offset,
+ branchInstruction.branchOffset));
+ }
+
+
+ public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction)
+ {
+ replacementInstruction =
+ new TableSwitchInstruction(tableSwitchInstruction.opcode,
+ instructionSequenceMatcher.matchedBranchOffset(offset, tableSwitchInstruction.defaultOffset),
+ instructionSequenceMatcher.matchedArgument(tableSwitchInstruction.lowCase),
+ instructionSequenceMatcher.matchedArgument(tableSwitchInstruction.highCase),
+ instructionSequenceMatcher.matchedJumpOffsets(offset,
+ tableSwitchInstruction.jumpOffsets));
+
+ }
+
+
+ public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction)
+ {
+ replacementInstruction =
+ new LookUpSwitchInstruction(lookUpSwitchInstruction.opcode,
+ instructionSequenceMatcher.matchedBranchOffset(offset, lookUpSwitchInstruction.defaultOffset),
+ instructionSequenceMatcher.matchedArguments(lookUpSwitchInstruction.cases),
+ instructionSequenceMatcher.matchedJumpOffsets(offset, lookUpSwitchInstruction.jumpOffsets));
+ }
+
+
+ /**
+ * Returns the matched argument for the given pattern argument.
+ */
+ private int matchedArgument(Clazz clazz, int argument)
+ {
+ // Special case: do we have to compute the string length?
+ if (argument == STRING_A_LENGTH)
+ {
+ // Return the string length.
+ return clazz.getStringString(instructionSequenceMatcher.matchedArgument(A)).length();
+ }
+
+ // Otherwise, just return the matched argument.
+ return instructionSequenceMatcher.matchedArgument(argument);
+ }
+
+
+ /**
+ * Returns the matched or newly created constant index for the given
+ * pattern constant index.
+ */
+ private int matchedConstantIndex(ProgramClass programClass, int constantIndex)
+ {
+ // Special case: do we have to create a concatenated string?
+ if (constantIndex >= BOOLEAN_A_STRING &&
+ constantIndex <= (STRING_A_STRING | STRING_B_STRING))
+ {
+ // Create a new string constant and return its index.
+ return new ConstantPoolEditor(programClass).addStringConstant(
+ argumentAsString(programClass, constantIndex & 0xf, A) +
+ argumentAsString(programClass, (constantIndex >>> 4) & 0xf, B),
+ null,
+ null);
+ }
+
+ int matchedConstantIndex =
+ instructionSequenceMatcher.matchedConstantIndex(constantIndex);
+
+ // Do we have a matched constant index?
+ if (matchedConstantIndex > 0)
+ {
+ // Return its index.
+ return matchedConstantIndex;
+ }
+
+ // Otherwise, we still have to create a new constant.
+ // This currently only works for constants without any wildcards.
+ ProgramClass dummyClass = new ProgramClass();
+ dummyClass.constantPool = patternConstants;
+
+ return new ConstantAdder(programClass).addConstant(dummyClass, constantIndex);
+ }
+
+
+ private String argumentAsString(ProgramClass programClass,
+ int valueType,
+ int argument)
+ {
+ switch (valueType)
+ {
+ case BOOLEAN_STRING:
+ return Boolean.toString((instructionSequenceMatcher.wasConstant(argument) ?
+ ((IntegerConstant)(programClass.getConstant(instructionSequenceMatcher.matchedConstantIndex(argument)))).getValue() :
+ instructionSequenceMatcher.matchedArgument(argument)) != 0);
+
+ case CHAR_STRING:
+ return Character.toString((char)(instructionSequenceMatcher.wasConstant(argument) ?
+ ((IntegerConstant)(programClass.getConstant(instructionSequenceMatcher.matchedConstantIndex(argument)))).getValue() :
+ instructionSequenceMatcher.matchedArgument(argument)));
+
+ case INT_STRING:
+ return Integer.toString(instructionSequenceMatcher.wasConstant(argument) ?
+ ((IntegerConstant)(programClass.getConstant(instructionSequenceMatcher.matchedConstantIndex(argument)))).getValue() :
+ instructionSequenceMatcher.matchedArgument(argument));
+
+ case LONG_STRING:
+ return Long.toString(instructionSequenceMatcher.wasConstant(argument) ?
+ ((LongConstant)(programClass.getConstant(instructionSequenceMatcher.matchedConstantIndex(argument)))).getValue() :
+ instructionSequenceMatcher.matchedArgument(argument));
+
+ case FLOAT_STRING:
+ return Float.toString(instructionSequenceMatcher.wasConstant(argument) ?
+ ((FloatConstant)(programClass.getConstant(instructionSequenceMatcher.matchedConstantIndex(argument)))).getValue() :
+ instructionSequenceMatcher.matchedArgument(argument));
+
+ case DOUBLE_STRING:
+ return Double.toString(instructionSequenceMatcher.wasConstant(argument) ?
+ ((DoubleConstant)(programClass.getConstant(instructionSequenceMatcher.matchedConstantIndex(argument)))).getValue() :
+ instructionSequenceMatcher.matchedArgument(argument));
+
+ case STRING_STRING:
+ return
+ programClass.getStringString(instructionSequenceMatcher.matchedConstantIndex(argument));
+
+ default:
+ return "";
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/peephole/InstructionSequencesReplacer.java b/src/proguard/optimize/peephole/InstructionSequencesReplacer.java
new file mode 100644
index 000000000..22fb6cd46
--- /dev/null
+++ b/src/proguard/optimize/peephole/InstructionSequencesReplacer.java
@@ -0,0 +1,138 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.constant.Constant;
+import proguard.classfile.editor.CodeAttributeEditor;
+import proguard.classfile.instruction.Instruction;
+import proguard.classfile.instruction.visitor.*;
+
+/**
+ * This InstructionVisitor replaces multiple instruction sequences at once.
+ *
+ * @see InstructionSequenceReplacer
+ * @author Eric Lafortune
+ */
+public class InstructionSequencesReplacer
+extends MultiInstructionVisitor
+implements InstructionVisitor
+{
+ private static final int PATTERN_INDEX = 0;
+ private static final int REPLACEMENT_INDEX = 1;
+
+
+ /**
+ * Creates a new InstructionSequencesReplacer.
+ * @param patternConstants any constants referenced by the pattern
+ * instruction.
+ * @param instructionSequences the instruction sequences to be replaced,
+ * with subsequently the sequence pair index,
+ * the patten/replacement index (0 or 1),
+ * and the instruction index in the sequence.
+ * @param branchTargetFinder a branch target finder that has been
+ * initialized to indicate branch targets
+ * in the visited code.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ */
+ public InstructionSequencesReplacer(Constant[] patternConstants,
+ Instruction[][][] instructionSequences,
+ BranchTargetFinder branchTargetFinder,
+ CodeAttributeEditor codeAttributeEditor)
+ {
+ this(patternConstants,
+ instructionSequences,
+ branchTargetFinder,
+ codeAttributeEditor,
+ null);
+ }
+
+
+ /**
+ * Creates a new InstructionSequenceReplacer.
+ * @param patternConstants any constants referenced by the pattern
+ * instruction.
+ * @param instructionSequences the instruction sequences to be replaced,
+ * with subsequently the sequence pair index,
+ * the patten/replacement index (0 or 1),
+ * and the instruction index in the sequence.
+ * @param branchTargetFinder a branch target finder that has been
+ * initialized to indicate branch targets
+ * in the visited code.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ * @param extraInstructionVisitor an optional extra visitor for all deleted
+ * load instructions.
+ */
+ public InstructionSequencesReplacer(Constant[] patternConstants,
+ Instruction[][][] instructionSequences,
+ BranchTargetFinder branchTargetFinder,
+ CodeAttributeEditor codeAttributeEditor,
+ InstructionVisitor extraInstructionVisitor)
+ {
+ super(createInstructionSequenceReplacers(patternConstants,
+ instructionSequences,
+ branchTargetFinder,
+ codeAttributeEditor,
+ extraInstructionVisitor));
+ }
+
+
+ /**
+ * Creates an array of InstructionSequenceReplacer instances.
+ * @param patternConstants any constants referenced by the pattern
+ * instruction.
+ * @param instructionSequences the instruction sequences to be replaced,
+ * with subsequently the sequence pair index,
+ * the from/to index (0 or 1), and the
+ * instruction index in the sequence.
+ * @param branchTargetFinder a branch target finder that has been
+ * initialized to indicate branch targets
+ * in the visited code.
+ * @param codeAttributeEditor a code editor that can be used for
+ * accumulating changes to the code.
+ * @param extraInstructionVisitor an optional extra visitor for all deleted
+ * load instructions.
+ */
+ private static InstructionVisitor[] createInstructionSequenceReplacers(Constant[] patternConstants,
+ Instruction[][][] instructionSequences,
+ BranchTargetFinder branchTargetFinder,
+ CodeAttributeEditor codeAttributeEditor,
+ InstructionVisitor extraInstructionVisitor)
+ {
+ InstructionVisitor[] instructionSequenceReplacers =
+ new InstructionSequenceReplacer[instructionSequences.length];
+
+ for (int index = 0; index < instructionSequenceReplacers.length; index++)
+ {
+ Instruction[][] instructionSequencePair = instructionSequences[index];
+ instructionSequenceReplacers[index] =
+ new InstructionSequenceReplacer(patternConstants,
+ instructionSequencePair[PATTERN_INDEX],
+ instructionSequencePair[REPLACEMENT_INDEX],
+ branchTargetFinder,
+ codeAttributeEditor,
+ extraInstructionVisitor);
+ }
+
+ return instructionSequenceReplacers;
+ }
+}
diff --git a/src/proguard/optimize/peephole/MemberPrivatizer.java b/src/proguard/optimize/peephole/MemberPrivatizer.java
new file mode 100644
index 000000000..f57281c36
--- /dev/null
+++ b/src/proguard/optimize/peephole/MemberPrivatizer.java
@@ -0,0 +1,103 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.editor.MethodInvocationFixer;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.MemberVisitor;
+import proguard.optimize.info.NonPrivateMemberMarker;
+
+/**
+ * This MemberVisitor makes all class members that it visits private, unless
+ * they have been marked by a NonPrivateMemberMarker. The invocations of
+ * privatized methods still have to be fixed.
+ *
+ * @see NonPrivateMemberMarker
+ * @see MethodInvocationFixer
+ * @author Eric Lafortune
+ */
+public class MemberPrivatizer
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final MemberVisitor extraMemberVisitor;
+
+
+ /**
+ * Creates a new MemberPrivatizer.
+ */
+ public MemberPrivatizer()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new MemberPrivatizer.
+ * @param extraMemberVisitor an optional extra visitor for all privatized
+ * class members.
+ */
+ public MemberPrivatizer(MemberVisitor extraMemberVisitor)
+ {
+ this.extraMemberVisitor = extraMemberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ // Is the field unmarked?
+ if (NonPrivateMemberMarker.canBeMadePrivate(programField))
+ {
+ // Make the field private.
+ programField.u2accessFlags =
+ AccessUtil.replaceAccessFlags(programField.u2accessFlags,
+ ClassConstants.INTERNAL_ACC_PRIVATE);
+
+ // Visit the field, if required.
+ if (extraMemberVisitor != null)
+ {
+ extraMemberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Is the method unmarked?
+ if (NonPrivateMemberMarker.canBeMadePrivate(programMethod))
+ {
+ // Make the method private.
+ programMethod.u2accessFlags =
+ AccessUtil.replaceAccessFlags(programMethod.u2accessFlags,
+ ClassConstants.INTERNAL_ACC_PRIVATE);
+
+ // Visit the method, if required.
+ if (extraMemberVisitor != null)
+ {
+ extraMemberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+ }
+}
diff --git a/src/proguard/optimize/peephole/MethodFinalizer.java b/src/proguard/optimize/peephole/MethodFinalizer.java
new file mode 100644
index 000000000..89174ac49
--- /dev/null
+++ b/src/proguard/optimize/peephole/MethodFinalizer.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.optimize.KeepMarker;
+
+/**
+ * This MemberVisitor
makes the program methods that it visits
+ * final, if possible.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodFinalizer
+extends SimplifiedVisitor
+implements MemberVisitor
+{
+ private final MemberVisitor extraMemberVisitor;
+
+ private final MemberFinder memberFinder = new MemberFinder();
+
+
+ /**
+ * Creates a new ClassFinalizer.
+ */
+ public MethodFinalizer()
+ {
+ this(null);
+ }
+
+
+ /**
+ * Creates a new ClassFinalizer.
+ * @param extraMemberVisitor an optional extra visitor for all finalized
+ * methods.
+ */
+ public MethodFinalizer(MemberVisitor extraMemberVisitor)
+ {
+ this.extraMemberVisitor = extraMemberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ String name = programMethod.getName(programClass);
+
+ // If the method is not already private/static/final/abstract,
+ // and it is not a constructor,
+ // and its class is final,
+ // or it is not being kept and it is not overridden,
+ // then make it final.
+ if ((programMethod.u2accessFlags & (ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC |
+ ClassConstants.INTERNAL_ACC_FINAL |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) == 0 &&
+ !name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT) &&
+ ((programClass.u2accessFlags & ClassConstants.INTERNAL_ACC_FINAL) != 0 ||
+ (!KeepMarker.isKept(programMethod) &&
+ (programClass.subClasses == null ||
+ !memberFinder.isOverriden(programClass, programMethod)))))
+ {
+ programMethod.u2accessFlags |= ClassConstants.INTERNAL_ACC_FINAL;
+
+ // Visit the method, if required.
+ if (extraMemberVisitor != null)
+ {
+ extraMemberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/optimize/peephole/MethodInliner.java b/src/proguard/optimize/peephole/MethodInliner.java
new file mode 100644
index 000000000..947cd43d6
--- /dev/null
+++ b/src/proguard/optimize/peephole/MethodInliner.java
@@ -0,0 +1,599 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.optimize.peephole;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.editor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+import proguard.optimize.*;
+import proguard.optimize.info.*;
+
+import java.util.*;
+
+/**
+ * This AttributeVisitor inlines short methods or methods that are only invoked
+ * once, in the code attributes that it visits.
+ *
+ * @author Eric Lafortune
+ */
+public class MethodInliner
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ InstructionVisitor,
+ ConstantVisitor,
+ MemberVisitor
+{
+ private static final int MAXIMUM_INLINED_CODE_LENGTH = Integer.parseInt(System.getProperty("maximum.inlined.code.length", "8"));
+ private static final int MAXIMUM_RESULTING_CODE_LENGTH_JSE = Integer.parseInt(System.getProperty("maximum.resulting.code.length", "7000"));
+ private static final int MAXIMUM_RESULTING_CODE_LENGTH_JME = Integer.parseInt(System.getProperty("maximum.resulting.code.length", "2000"));
+
+ //*
+ private static final boolean DEBUG = false;
+ /*/
+ private static boolean DEBUG = true;
+ //*/
+
+
+ private final boolean microEdition;
+ private final boolean allowAccessModification;
+ private final boolean inlineSingleInvocations;
+ private final InstructionVisitor extraInlinedInvocationVisitor;
+
+ private final CodeAttributeComposer codeAttributeComposer = new CodeAttributeComposer();
+ private final AccessMethodMarker accessMethodMarker = new AccessMethodMarker();
+ private final CatchExceptionMarker catchExceptionMarker = new CatchExceptionMarker();
+ private final StackSizeComputer stackSizeComputer = new StackSizeComputer();
+
+ private ProgramClass targetClass;
+ private ProgramMethod targetMethod;
+ private ConstantAdder constantAdder;
+ private ExceptionInfoAdder exceptionInfoAdder;
+ private int estimatedResultingCodeLength;
+ private boolean inlining;
+ private Stack inliningMethods = new Stack();
+ private boolean emptyInvokingStack;
+ private int uninitializedObjectCount;
+ private int variableOffset;
+ private boolean inlined;
+ private boolean inlinedAny;
+
+
+ /**
+ * Creates a new MethodInliner.
+ * @param microEdition indicates whether the resulting code is
+ * targeted at Java Micro Edition.
+ * @param allowAccessModification indicates whether the access modifiers of
+ * classes and class members can be changed
+ * in order to inline methods.
+ * @param inlineSingleInvocations indicates whether the single invocations
+ * should be inlined, or, alternatively,
+ * short methods.
+ */
+ public MethodInliner(boolean microEdition,
+ boolean allowAccessModification,
+ boolean inlineSingleInvocations)
+ {
+ this(microEdition,
+ allowAccessModification,
+ inlineSingleInvocations,
+ null);
+ }
+
+
+ /**
+ * Creates a new MethodInliner.
+ * @param microEdition indicates whether the resulting code is
+ * targeted at Java Micro Edition.
+ * @param allowAccessModification indicates whether the access modifiers of
+ * classes and class members can be changed
+ * in order to inline methods.
+ * @param inlineSingleInvocations indicates whether the single invocations
+ * should be inlined, or, alternatively,
+ * short methods.
+ * @param extraInlinedInvocationVisitor an optional extra visitor for all
+ * inlined invocation instructions.
+ */
+ public MethodInliner(boolean microEdition,
+ boolean allowAccessModification,
+ boolean inlineSingleInvocations,
+ InstructionVisitor extraInlinedInvocationVisitor)
+ {
+ this.microEdition = microEdition;
+ this.allowAccessModification = allowAccessModification;
+ this.inlineSingleInvocations = inlineSingleInvocations;
+ this.extraInlinedInvocationVisitor = extraInlinedInvocationVisitor;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // TODO: Remove this when the method inliner has stabilized.
+ // Catch any unexpected exceptions from the actual visiting method.
+ try
+ {
+ // Process the code.
+ visitCodeAttribute0(clazz, method, codeAttribute);
+ }
+ catch (RuntimeException ex)
+ {
+ System.err.println("Unexpected error while inlining method:");
+ System.err.println(" Target class = ["+targetClass.getName()+"]");
+ System.err.println(" Target method = ["+targetMethod.getName(targetClass)+targetMethod.getDescriptor(targetClass)+"]");
+ if (inlining)
+ {
+ System.err.println(" Inlined class = ["+clazz.getName()+"]");
+ System.err.println(" Inlined method = ["+method.getName(clazz)+method.getDescriptor(clazz)+"]");
+ }
+ System.err.println(" Exception = ["+ex.getClass().getName()+"] ("+ex.getMessage()+")");
+ System.err.println("Not inlining this method");
+
+ if (DEBUG)
+ {
+ targetMethod.accept(targetClass, new ClassPrinter());
+ if (inlining)
+ {
+ method.accept(clazz, new ClassPrinter());
+ }
+
+ throw ex;
+ }
+ }
+ }
+
+
+ public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ if (!inlining)
+ {
+// codeAttributeComposer.DEBUG = DEBUG =
+// clazz.getName().equals("abc/Def") &&
+// method.getName(clazz).equals("abc");
+
+ targetClass = (ProgramClass)clazz;
+ targetMethod = (ProgramMethod)method;
+ constantAdder = new ConstantAdder(targetClass);
+ exceptionInfoAdder = new ExceptionInfoAdder(targetClass, codeAttributeComposer);
+ estimatedResultingCodeLength = codeAttribute.u4codeLength;
+ inliningMethods.clear();
+ uninitializedObjectCount = method.getName(clazz).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT) ? 1 : 0;
+ inlinedAny = false;
+ codeAttributeComposer.reset();
+ stackSizeComputer.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Append the body of the code.
+ copyCode(clazz, method, codeAttribute);
+
+ targetClass = null;
+ targetMethod = null;
+ constantAdder = null;
+
+ // Update the code attribute if any code has been inlined.
+ if (inlinedAny)
+ {
+ codeAttributeComposer.visitCodeAttribute(clazz, method, codeAttribute);
+
+ // Update the accessing flags.
+ codeAttribute.instructionsAccept(clazz, method, accessMethodMarker);
+
+ // Update the exception catching flags.
+ catchExceptionMarker.visitCodeAttribute(clazz, method, codeAttribute);
+ }
+ }
+
+ // Only inline the method if it is invoked once or if it is short.
+ else if ((inlineSingleInvocations ?
+ MethodInvocationMarker.getInvocationCount(method) == 1 :
+ codeAttribute.u4codeLength <= MAXIMUM_INLINED_CODE_LENGTH) &&
+ estimatedResultingCodeLength + codeAttribute.u4codeLength <
+ (microEdition ?
+ MAXIMUM_RESULTING_CODE_LENGTH_JME :
+ MAXIMUM_RESULTING_CODE_LENGTH_JSE))
+ {
+ if (DEBUG)
+ {
+ System.out.println("MethodInliner: inlining ["+
+ clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"] in ["+
+ targetClass.getName()+"."+targetMethod.getName(targetClass)+targetMethod.getDescriptor(targetClass)+"]");
+ }
+
+ // Ignore the removal of the original method invocation,
+ // the addition of the parameter setup, and
+ // the modification of a few inlined instructions.
+ estimatedResultingCodeLength += codeAttribute.u4codeLength;
+
+ // Append instructions to store the parameters.
+ storeParameters(clazz, method);
+
+ // Inline the body of the code.
+ copyCode(clazz, method, codeAttribute);
+
+ inlined = true;
+ inlinedAny = true;
+ }
+ }
+
+
+ /**
+ * Appends instructions to pop the parameters for the given method, storing
+ * them in new local variables.
+ */
+ private void storeParameters(Clazz clazz, Method method)
+ {
+ String descriptor = method.getDescriptor(clazz);
+
+ boolean isStatic =
+ (method.getAccessFlags() & ClassConstants.INTERNAL_ACC_STATIC) != 0;
+
+ // Count the number of parameters, taking into account their categories.
+ int parameterCount = ClassUtil.internalMethodParameterCount(descriptor);
+ int parameterSize = ClassUtil.internalMethodParameterSize(descriptor);
+ int parameterOffset = isStatic ? 0 : 1;
+
+ // Store the parameter types.
+ String[] parameterTypes = new String[parameterSize];
+
+ InternalTypeEnumeration internalTypeEnumeration =
+ new InternalTypeEnumeration(descriptor);
+
+ for (int parameterIndex = 0; parameterIndex < parameterSize; parameterIndex++)
+ {
+ String parameterType = internalTypeEnumeration.nextType();
+ parameterTypes[parameterIndex] = parameterType;
+ if (ClassUtil.internalTypeSize(parameterType) == 2)
+ {
+ parameterIndex++;
+ }
+ }
+
+ codeAttributeComposer.beginCodeFragment(parameterSize+1);
+
+ // Go over the parameter types backward, storing the stack entries
+ // in their corresponding variables.
+ for (int parameterIndex = parameterSize-1; parameterIndex >= 0; parameterIndex--)
+ {
+ String parameterType = parameterTypes[parameterIndex];
+ if (parameterType != null)
+ {
+ byte opcode;
+ switch (parameterType.charAt(0))
+ {
+ case ClassConstants.INTERNAL_TYPE_BOOLEAN:
+ case ClassConstants.INTERNAL_TYPE_BYTE:
+ case ClassConstants.INTERNAL_TYPE_CHAR:
+ case ClassConstants.INTERNAL_TYPE_SHORT:
+ case ClassConstants.INTERNAL_TYPE_INT:
+ opcode = InstructionConstants.OP_ISTORE;
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_LONG:
+ opcode = InstructionConstants.OP_LSTORE;
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_FLOAT:
+ opcode = InstructionConstants.OP_FSTORE;
+ break;
+
+ case ClassConstants.INTERNAL_TYPE_DOUBLE:
+ opcode = InstructionConstants.OP_DSTORE;
+ break;
+
+ default:
+ opcode = InstructionConstants.OP_ASTORE;
+ break;
+ }
+
+ codeAttributeComposer.appendInstruction(parameterSize-parameterIndex-1,
+ new VariableInstruction(opcode, variableOffset + parameterOffset + parameterIndex));
+ }
+ }
+
+ // Put the 'this' reference in variable 0 (plus offset).
+ if (!isStatic)
+ {
+ codeAttributeComposer.appendInstruction(parameterSize,
+ new VariableInstruction(InstructionConstants.OP_ASTORE, variableOffset));
+ }
+
+ codeAttributeComposer.endCodeFragment();
+ }
+
+
+ /**
+ * Appends the code of the given code attribute.
+ */
+ private void copyCode(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ // The code may expand, due to expanding constant and variable
+ // instructions.
+ codeAttributeComposer.beginCodeFragment(codeAttribute.u4codeLength);
+
+ // Copy the instructions.
+ codeAttribute.instructionsAccept(clazz, method, this);
+
+ // Append a label just after the code.
+ codeAttributeComposer.appendLabel(codeAttribute.u4codeLength);
+
+ // Copy the exceptions.
+ codeAttribute.exceptionsAccept(clazz, method, exceptionInfoAdder);
+
+ codeAttributeComposer.endCodeFragment();
+ }
+
+
+ // Implementations for InstructionVisitor.
+
+ public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction instruction)
+ {
+ codeAttributeComposer.appendInstruction(offset, instruction);
+ }
+
+
+ public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
+ {
+ // Are we inlining this instruction?
+ if (inlining)
+ {
+ // Replace any return instructions by branches to the end of the code.
+ switch (simpleInstruction.opcode)
+ {
+ case InstructionConstants.OP_IRETURN:
+ case InstructionConstants.OP_LRETURN:
+ case InstructionConstants.OP_FRETURN:
+ case InstructionConstants.OP_DRETURN:
+ case InstructionConstants.OP_ARETURN:
+ case InstructionConstants.OP_RETURN:
+ // Are we not at the last instruction?
+ if (offset < codeAttribute.u4codeLength-1)
+ {
+ // Replace the return instruction by a branch instruction.
+ Instruction branchInstruction =
+ new BranchInstruction(InstructionConstants.OP_GOTO_W,
+ codeAttribute.u4codeLength - offset);
+
+ codeAttributeComposer.appendInstruction(offset,
+ branchInstruction);
+ }
+ else
+ {
+ // Just leave out the instruction, but put in a label,
+ // for the sake of any other branch instructions.
+ codeAttributeComposer.appendLabel(offset);
+ }
+
+ return;
+ }
+ }
+
+ codeAttributeComposer.appendInstruction(offset, simpleInstruction);
+ }
+
+
+ public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
+ {
+ // Are we inlining this instruction?
+ if (inlining)
+ {
+ // Update the variable index.
+ variableInstruction.variableIndex += variableOffset;
+ }
+
+ codeAttributeComposer.appendInstruction(offset, variableInstruction);
+ }
+
+
+ public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
+ {
+ // Is it a method invocation?
+ switch (constantInstruction.opcode)
+ {
+ case InstructionConstants.OP_NEW:
+ uninitializedObjectCount++;
+ break;
+
+ case InstructionConstants.OP_INVOKEVIRTUAL:
+ case InstructionConstants.OP_INVOKESPECIAL:
+ case InstructionConstants.OP_INVOKESTATIC:
+ case InstructionConstants.OP_INVOKEINTERFACE:
+ // See if we can inline it.
+ inlined = false;
+
+ // Append a label, in case the invocation will be inlined.
+ codeAttributeComposer.appendLabel(offset);
+
+ emptyInvokingStack =
+ !inlining &&
+ stackSizeComputer.isReachable(offset) &&
+ stackSizeComputer.getStackSize(offset) == 0;
+
+ variableOffset += codeAttribute.u2maxLocals;
+
+ clazz.constantPoolEntryAccept(constantInstruction.constantIndex, this);
+
+ variableOffset -= codeAttribute.u2maxLocals;
+
+ // Was the method inlined?
+ if (inlined)
+ {
+ if (extraInlinedInvocationVisitor != null)
+ {
+ extraInlinedInvocationVisitor.visitConstantInstruction(clazz, method, codeAttribute, offset, constantInstruction);
+ }
+
+ // The invocation itself is no longer necessary.
+ return;
+ }
+
+ break;
+ }
+
+ // Are we inlining this instruction?
+ if (inlining)
+ {
+ // Make sure the constant is present in the constant pool of the
+ // target class.
+ constantInstruction.constantIndex =
+ constantAdder.addConstant(clazz, constantInstruction.constantIndex);
+ }
+
+ codeAttributeComposer.appendInstruction(offset, constantInstruction);
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitInterfaceMethodrefConstant(Clazz clazz, InterfaceMethodrefConstant interfaceMethodrefConstant) {}
+
+
+ public void visitMethodrefConstant(Clazz clazz, MethodrefConstant methodrefConstant)
+ {
+ methodrefConstant.referencedMemberAccept(this);
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitAnyMember(Clazz Clazz, Member member) {}
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ int accessFlags = programMethod.getAccessFlags();
+
+ if (// Don't inline methods that must be preserved.
+ !KeepMarker.isKept(programMethod) &&
+
+ // Only inline the method if it is private, static, or final.
+ (accessFlags & (ClassConstants.INTERNAL_ACC_PRIVATE |
+ ClassConstants.INTERNAL_ACC_STATIC |
+ ClassConstants.INTERNAL_ACC_FINAL)) != 0 &&
+
+ // Only inline the method if it is not synchronized, etc.
+ (accessFlags & (ClassConstants.INTERNAL_ACC_SYNCHRONIZED |
+ ClassConstants.INTERNAL_ACC_NATIVE |
+ ClassConstants.INTERNAL_ACC_INTERFACE |
+ ClassConstants.INTERNAL_ACC_ABSTRACT)) == 0 &&
+
+ // Don't inline an System.out
.
+ * @param shortestUsageMarker the usage marker that was used to mark the
+ * classes and class members.
+ */
+ public ShortestUsagePrinter(ShortestUsageMarker shortestUsageMarker)
+ {
+ this(shortestUsageMarker, true);
+ }
+
+
+ /**
+ * Creates a new UsagePrinter that prints to the given stream.
+ * @param shortestUsageMarker the usage marker that was used to mark the
+ * classes and class members.
+ * @param verbose specifies whether the output should be verbose.
+ */
+ public ShortestUsagePrinter(ShortestUsageMarker shortestUsageMarker,
+ boolean verbose)
+ {
+ this(shortestUsageMarker, verbose, System.out);
+ }
+
+ /**
+ * Creates a new UsagePrinter that prints to the given stream.
+ * @param shortestUsageMarker the usage marker that was used to mark the
+ * classes and class members.
+ * @param verbose specifies whether the output should be verbose.
+ * @param printStream the stream to which to print.
+ */
+ public ShortestUsagePrinter(ShortestUsageMarker shortestUsageMarker,
+ boolean verbose,
+ PrintStream printStream)
+ {
+ this.shortestUsageMarker = shortestUsageMarker;
+ this.verbose = verbose;
+ this.ps = printStream;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Print the name of this class.
+ ps.println(ClassUtil.externalClassName(programClass.getName()));
+
+ // Print the reason for keeping this class.
+ printReason(programClass);
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ // Print the name of this class.
+ ps.println(ClassUtil.externalClassName(libraryClass.getName()));
+
+ // Print the reason for keeping this class.
+ ps.println(" is a library class.\n");
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ // Print the name of this field.
+ String name = programField.getName(programClass);
+ String type = programField.getDescriptor(programClass);
+
+ ps.println(ClassUtil.externalClassName(programClass.getName()) +
+ (verbose ?
+ ": " + ClassUtil.externalFullFieldDescription(0, name, type):
+ "." + name));
+
+ // Print the reason for keeping this method.
+ printReason(programField);
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ // Print the name of this method.
+ String name = programMethod.getName(programClass);
+ String type = programMethod.getDescriptor(programClass);
+
+ ps.print(ClassUtil.externalClassName(programClass.getName()) +
+ (verbose ?
+ ": " + ClassUtil.externalFullMethodDescription(programClass.getName(), 0, name, type):
+ "." + name));
+ programMethod.attributesAccept(programClass, this);
+ ps.println();
+
+ // Print the reason for keeping this method.
+ printReason(programMethod);
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ // Print the name of this field.
+ String name = libraryField.getName(libraryClass);
+ String type = libraryField.getDescriptor(libraryClass);
+
+ ps.println(ClassUtil.externalClassName(libraryClass.getName()) +
+ (verbose ?
+ ": " + ClassUtil.externalFullFieldDescription(0, name, type):
+ "." + name));
+
+ // Print the reason for keeping this field.
+ ps.println(" is a library field.\n");
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ // Print the name of this method.
+ String name = libraryMethod.getName(libraryClass);
+ String type = libraryMethod.getDescriptor(libraryClass);
+
+ ps.println(ClassUtil.externalClassName(libraryClass.getName()) +
+ (verbose ?
+ ": " + ClassUtil.externalFullMethodDescription(libraryClass.getName(), 0, name, type):
+ "." + name));
+
+ // Print the reason for keeping this method.
+ ps.println(" is a library method.\n");
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ ps.print(" (" +
+ lineNumberTableAttribute.getLowestLineNumber() + ":" +
+ lineNumberTableAttribute.getHighestLineNumber() + ")");
+ }
+
+
+ // Small utility methods.
+
+ private void printReason(VisitorAccepter visitorAccepter)
+ {
+ if (shortestUsageMarker.isUsed(visitorAccepter))
+ {
+ ShortestUsageMark shortestUsageMark = shortestUsageMarker.getShortestUsageMark(visitorAccepter);
+
+ // Print the reason for keeping this class.
+ ps.print(" " + shortestUsageMark.getReason());
+
+ // Print the class or method that is responsible, with its reasons.
+ shortestUsageMark.acceptClassVisitor(this);
+ shortestUsageMark.acceptMemberVisitor(this);
+ }
+ else
+ {
+ ps.println(" is not being kept.\n");
+ }
+ }
+}
diff --git a/src/proguard/shrink/Shrinker.java b/src/proguard/shrink/Shrinker.java
new file mode 100644
index 000000000..0472c3d4d
--- /dev/null
+++ b/src/proguard/shrink/Shrinker.java
@@ -0,0 +1,179 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.shrink;
+
+import proguard.*;
+import proguard.classfile.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.visitor.*;
+
+import java.io.*;
+
+/**
+ * This class shrinks class pools according to a given configuration.
+ *
+ * @author Eric Lafortune
+ */
+public class Shrinker
+{
+ private final Configuration configuration;
+
+
+ /**
+ * Creates a new Shrinker.
+ */
+ public Shrinker(Configuration configuration)
+ {
+ this.configuration = configuration;
+ }
+
+
+ /**
+ * Performs shrinking of the given program class pool.
+ */
+ public ClassPool execute(ClassPool programClassPool,
+ ClassPool libraryClassPool) throws IOException
+ {
+ // Check if we have at least some keep commands.
+ if (configuration.keep == null)
+ {
+ throw new IOException("You have to specify '-keep' options for the shrinking step.");
+ }
+
+ // Clean up any old visitor info.
+ programClassPool.classesAccept(new ClassCleaner());
+ libraryClassPool.classesAccept(new ClassCleaner());
+
+ // Create a visitor for marking the seeds.
+ UsageMarker usageMarker = configuration.whyAreYouKeeping == null ?
+ new UsageMarker() :
+ new ShortestUsageMarker();
+
+ // Automatically mark the parameterless constructors of seed classes,
+ // mainly for convenience and for backward compatibility.
+ ClassVisitor classUsageMarker =
+ new MultiClassVisitor(new ClassVisitor[]
+ {
+ usageMarker,
+ new NamedMethodVisitor(ClassConstants.INTERNAL_METHOD_NAME_INIT,
+ ClassConstants.INTERNAL_METHOD_TYPE_INIT,
+ usageMarker)
+ });
+
+ ClassPoolVisitor classPoolvisitor =
+ ClassSpecificationVisitorFactory.createClassPoolVisitor(configuration.keep,
+ classUsageMarker,
+ usageMarker,
+ true,
+ false,
+ false);
+ // Mark the seeds.
+ programClassPool.accept(classPoolvisitor);
+ libraryClassPool.accept(classPoolvisitor);
+
+ // Mark interfaces that have to be kept.
+ programClassPool.classesAccept(new InterfaceUsageMarker(usageMarker));
+
+ // Mark the inner class and annotation information that has to be kept.
+ programClassPool.classesAccept(
+ new UsedClassFilter(usageMarker,
+ new AllAttributeVisitor(true,
+ new MultiAttributeVisitor(new AttributeVisitor[]
+ {
+ new InnerUsageMarker(usageMarker),
+ new AnnotationUsageMarker(usageMarker),
+ new SignatureUsageMarker(usageMarker),
+ new LocalVariableTypeUsageMarker(usageMarker)
+ }))));
+
+ // Should we explain ourselves?
+ if (configuration.whyAreYouKeeping != null)
+ {
+ System.out.println();
+
+ // Create a visitor for explaining classes and class members.
+ ShortestUsagePrinter shortestUsagePrinter =
+ new ShortestUsagePrinter((ShortestUsageMarker)usageMarker,
+ configuration.verbose);
+
+ ClassPoolVisitor whyClassPoolvisitor =
+ ClassSpecificationVisitorFactory.createClassPoolVisitor(configuration.whyAreYouKeeping,
+ shortestUsagePrinter,
+ shortestUsagePrinter);
+
+ // Mark the seeds.
+ programClassPool.accept(whyClassPoolvisitor);
+ libraryClassPool.accept(whyClassPoolvisitor);
+ }
+
+ if (configuration.printUsage != null)
+ {
+ PrintStream ps =
+ configuration.printUsage == Configuration.STD_OUT ? System.out :
+ new PrintStream(
+ new BufferedOutputStream(
+ new FileOutputStream(configuration.printUsage)));
+
+ // Print out items that will be removed.
+ programClassPool.classesAcceptAlphabetically(
+ new UsagePrinter(usageMarker, true, ps));
+
+ if (ps == System.out)
+ {
+ ps.flush();
+ }
+ else
+ {
+ ps.close();
+ }
+ }
+
+ // Discard unused program classes.
+ int originalProgramClassPoolSize = programClassPool.size();
+
+ ClassPool newProgramClassPool = new ClassPool();
+ programClassPool.classesAccept(
+ new UsedClassFilter(usageMarker,
+ new MultiClassVisitor(
+ new ClassVisitor[] {
+ new ClassShrinker(usageMarker),
+ new ClassPoolFiller(newProgramClassPool)
+ })));
+
+ programClassPool.clear();
+
+ // Check if we have at least some output classes.
+ int newProgramClassPoolSize = newProgramClassPool.size();
+ if (newProgramClassPoolSize == 0)
+ {
+ throw new IOException("The output jar is empty. Did you specify the proper '-keep' options?");
+ }
+
+ if (configuration.verbose)
+ {
+ System.out.println("Removing unused program classes and class elements...");
+ System.out.println(" Original number of program classes: " + originalProgramClassPoolSize);
+ System.out.println(" Final number of program classes: " + newProgramClassPoolSize);
+ }
+
+ return newProgramClassPool;
+ }
+}
diff --git a/src/proguard/shrink/SignatureUsageMarker.java b/src/proguard/shrink/SignatureUsageMarker.java
new file mode 100644
index 000000000..9c5cd4d29
--- /dev/null
+++ b/src/proguard/shrink/SignatureUsageMarker.java
@@ -0,0 +1,117 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package proguard.shrink;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.ConstantVisitor;
+import proguard.classfile.util.SimplifiedVisitor;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This AttributeVisitor recursively marks all Signature attributes that it
+ * visits and that point to used classes.
+ *
+ * @see UsageMarker
+ *
+ * @author Eric Lafortune
+ */
+public class SignatureUsageMarker
+extends SimplifiedVisitor
+implements AttributeVisitor,
+ ClassVisitor,
+ ConstantVisitor
+{
+ private final UsageMarker usageMarker;
+
+ // Fields acting as a return parameters for several methods.
+ private boolean attributeUsed;
+
+
+ /**
+ * Creates a new SignatureUsageMarker.
+ * @param usageMarker the usage marker that is used to mark the classes
+ * and class members.
+ */
+ public SignatureUsageMarker(UsageMarker usageMarker)
+ {
+ this.usageMarker = usageMarker;
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitSignatureAttribute(Clazz clazz, SignatureAttribute signatureAttribute)
+ {
+ // Only keep the signature if all of its classes are used.
+ attributeUsed = true;
+ signatureAttribute.referencedClassesAccept(this);
+
+ if (attributeUsed)
+ {
+ // We got a positive used flag, so the signature is useful.
+ usageMarker.markAsUsed(signatureAttribute);
+
+ markConstant(clazz, signatureAttribute.u2attributeNameIndex);
+ markConstant(clazz, signatureAttribute.u2signatureIndex);
+ }
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitLibraryClass(LibraryClass libraryClass) {}
+
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ // Don't keep the signature if one of its classes is not used.
+ if (!usageMarker.isUsed(programClass))
+ {
+ attributeUsed = false;
+ }
+ }
+
+
+ // Implementations for ConstantVisitor.
+
+ public void visitAnyConstant(Clazz clazz, Constant constant)
+ {
+ usageMarker.markAsUsed(constant);
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Marks the given constant pool entry of the given class.
+ */
+ private void markConstant(Clazz clazz, int index)
+ {
+ clazz.constantPoolEntryAccept(index, this);
+ }
+}
diff --git a/src/proguard/shrink/UsageMarker.java b/src/proguard/shrink/UsageMarker.java
new file mode 100644
index 000000000..51210b568
--- /dev/null
+++ b/src/proguard/shrink/UsageMarker.java
@@ -0,0 +1,1052 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.shrink;
+
+import proguard.classfile.*;
+import proguard.classfile.attribute.*;
+import proguard.classfile.attribute.annotation.*;
+import proguard.classfile.attribute.preverification.*;
+import proguard.classfile.attribute.preverification.visitor.*;
+import proguard.classfile.attribute.visitor.*;
+import proguard.classfile.constant.*;
+import proguard.classfile.constant.visitor.*;
+import proguard.classfile.instruction.*;
+import proguard.classfile.instruction.visitor.InstructionVisitor;
+import proguard.classfile.util.*;
+import proguard.classfile.visitor.*;
+
+
+/**
+ * This ClassVisitor and MemberVisitor recursively marks all classes and class
+ * elements that are being used.
+ *
+ * @see ClassShrinker
+ *
+ * @author Eric Lafortune
+ */
+class UsageMarker
+extends SimplifiedVisitor
+implements ClassVisitor,
+ MemberVisitor,
+ ConstantVisitor,
+ AttributeVisitor,
+ InnerClassesInfoVisitor,
+ ExceptionInfoVisitor,
+ StackMapFrameVisitor,
+ VerificationTypeVisitor,
+ LocalVariableInfoVisitor,
+ LocalVariableTypeInfoVisitor,
+// AnnotationVisitor,
+// ElementValueVisitor,
+ InstructionVisitor
+{
+ // A visitor info flag to indicate the ProgramMember object is being used,
+ // if its Clazz can be determined as being used as well.
+ private static final Object POSSIBLY_USED = new Object();
+ // A visitor info flag to indicate the visitor accepter is being used.
+ private static final Object USED = new Object();
+
+
+ private final MyInterfaceUsageMarker interfaceUsageMarker = new MyInterfaceUsageMarker();
+ private final MyPossiblyUsedMemberUsageMarker possiblyUsedMemberUsageMarker = new MyPossiblyUsedMemberUsageMarker();
+ private final MemberVisitor nonEmptyMethodUsageMarker = new AllAttributeVisitor(
+ new MyNonEmptyMethodUsageMarker());
+ private final ConstantVisitor parameterlessConstructorMarker = new ConstantTagFilter(new int[] { ClassConstants.CONSTANT_String, ClassConstants.CONSTANT_Class },
+ new ReferencedClassVisitor(
+ new NamedMethodVisitor(ClassConstants.INTERNAL_METHOD_NAME_INIT,
+ ClassConstants.INTERNAL_METHOD_TYPE_INIT,
+ this)));
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (shouldBeMarkedAsUsed(programClass))
+ {
+ // Mark this class.
+ markAsUsed(programClass);
+
+ markProgramClassBody(programClass);
+ }
+ }
+
+
+ protected void markProgramClassBody(ProgramClass programClass)
+ {
+ // Mark this class's name.
+ markConstant(programClass, programClass.u2thisClass);
+
+ // Mark the superclass.
+ if (programClass.u2superClass != 0)
+ {
+ markConstant(programClass, programClass.u2superClass);
+ }
+
+ // Give the interfaces preliminary marks.
+ programClass.hierarchyAccept(false, false, true, false,
+ interfaceUsageMarker);
+
+ // Explicitly mark the System.out
.
+ * @param usageMarker the usage marker that was used to mark the
+ * classes and class members.
+ * @param printUnusedItems a flag that indicates whether only unused items
+ * should be printed, or alternatively, only used
+ * items.
+ */
+ public UsagePrinter(UsageMarker usageMarker,
+ boolean printUnusedItems)
+ {
+ this(usageMarker, printUnusedItems, System.out);
+ }
+
+
+ /**
+ * Creates a new UsagePrinter that prints to the given stream.
+ * @param usageMarker the usage marker that was used to mark the
+ * classes and class members.
+ * @param printUnusedItems a flag that indicates whether only unused items
+ * should be printed, or alternatively, only used
+ * items.
+ * @param printStream the stream to which to print.
+ */
+ public UsagePrinter(UsageMarker usageMarker,
+ boolean printUnusedItems,
+ PrintStream printStream)
+ {
+ this.usageMarker = usageMarker;
+ this.printUnusedItems = printUnusedItems;
+ this.ps = printStream;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (usageMarker.isUsed(programClass))
+ {
+ if (printUnusedItems)
+ {
+ className = programClass.getName();
+
+ programClass.fieldsAccept(this);
+ programClass.methodsAccept(this);
+
+ className = null;
+ }
+ else
+ {
+ ps.println(ClassUtil.externalClassName(programClass.getName()));
+ }
+ }
+ else
+ {
+ if (printUnusedItems)
+ {
+ ps.println(ClassUtil.externalClassName(programClass.getName()));
+ }
+ }
+ }
+
+
+ // Implementations for MemberVisitor.
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (usageMarker.isUsed(programField) ^ printUnusedItems)
+ {
+ printClassNameHeader();
+
+ ps.println(" " +
+ ClassUtil.externalFullFieldDescription(
+ programField.getAccessFlags(),
+ programField.getName(programClass),
+ programField.getDescriptor(programClass)));
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (usageMarker.isUsed(programMethod) ^ printUnusedItems)
+ {
+ printClassNameHeader();
+
+ ps.print("====");
+ ps.print(" ");
+ programMethod.attributesAccept(programClass, this);
+ ps.println(ClassUtil.externalFullMethodDescription(
+ programClass.getName(),
+ programMethod.getAccessFlags(),
+ programMethod.getName(programClass),
+ programMethod.getDescriptor(programClass)));
+ }
+ }
+
+
+ // Implementations for AttributeVisitor.
+
+ public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
+
+
+ public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
+ {
+ codeAttribute.attributesAccept(clazz, method, this);
+ }
+
+
+ public void visitLineNumberTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, LineNumberTableAttribute lineNumberTableAttribute)
+ {
+ ps.print(lineNumberTableAttribute.getLowestLineNumber() + ":" +
+ lineNumberTableAttribute.getHighestLineNumber() + ":");
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Prints the class name field. The field is then cleared, so it is not
+ * printed again.
+ */
+ private void printClassNameHeader()
+ {
+ if (className != null)
+ {
+ ps.println(ClassUtil.externalClassName(className) + ":");
+ className = null;
+ }
+ }
+}
diff --git a/src/proguard/shrink/UsedClassFilter.java b/src/proguard/shrink/UsedClassFilter.java
new file mode 100644
index 000000000..7630b0bbf
--- /dev/null
+++ b/src/proguard/shrink/UsedClassFilter.java
@@ -0,0 +1,74 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.shrink;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.ClassVisitor;
+
+/**
+ * This ClassVisitor delegates all its method calls to another ClassVisitor,
+ * but only for Clazz objects that are marked as used.
+ *
+ * @see UsageMarker
+ *
+ * @author Eric Lafortune
+ */
+public class UsedClassFilter
+implements ClassVisitor
+{
+ private final UsageMarker usageMarker;
+ private final ClassVisitor classVisitor;
+
+
+ /**
+ * Creates a new UsedClassFilter.
+ * @param usageMarker the usage marker that is used to mark the classes
+ * and class members.
+ * @param classVisitor the class visitor to which the visiting will be
+ * delegated.
+ */
+ public UsedClassFilter(UsageMarker usageMarker,
+ ClassVisitor classVisitor)
+ {
+ this.usageMarker = usageMarker;
+ this.classVisitor = classVisitor;
+ }
+
+
+ // Implementations for ClassVisitor.
+
+ public void visitProgramClass(ProgramClass programClass)
+ {
+ if (usageMarker.isUsed(programClass))
+ {
+ classVisitor.visitProgramClass(programClass);
+ }
+ }
+
+
+ public void visitLibraryClass(LibraryClass libraryClass)
+ {
+ if (usageMarker.isUsed(libraryClass))
+ {
+ classVisitor.visitLibraryClass(libraryClass);
+ }
+ }
+}
diff --git a/src/proguard/shrink/UsedMemberFilter.java b/src/proguard/shrink/UsedMemberFilter.java
new file mode 100644
index 000000000..f1a9c7544
--- /dev/null
+++ b/src/proguard/shrink/UsedMemberFilter.java
@@ -0,0 +1,93 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.shrink;
+
+import proguard.classfile.*;
+import proguard.classfile.visitor.MemberVisitor;
+
+/**
+ * This MemberVisitor delegates all its method calls to another MemberVisitor,
+ * but only for Member objects that are marked as used.
+ *
+ * @see UsageMarker
+ *
+ * @author Eric Lafortune
+ */
+public class UsedMemberFilter
+implements MemberVisitor
+{
+ private final UsageMarker usageMarker;
+ private final MemberVisitor memberVisitor;
+
+
+ /**
+ * Creates a new UsedMemberFilter.
+ * @param usageMarker the usage marker that is used to mark the classes
+ * and class members.
+ * @param memberVisitor the member visitor to which the visiting will be
+ * delegated.
+ */
+ public UsedMemberFilter(UsageMarker usageMarker,
+ MemberVisitor memberVisitor)
+ {
+ this.usageMarker = usageMarker;
+ this.memberVisitor = memberVisitor;
+ }
+
+
+ // Implementations for MemberVisitor.
+
+
+ public void visitProgramField(ProgramClass programClass, ProgramField programField)
+ {
+ if (usageMarker.isUsed(programField))
+ {
+ memberVisitor.visitProgramField(programClass, programField);
+ }
+ }
+
+
+ public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
+ {
+ if (usageMarker.isUsed(programMethod))
+ {
+ memberVisitor.visitProgramMethod(programClass, programMethod);
+ }
+ }
+
+
+ public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
+ {
+ if (usageMarker.isUsed(libraryField))
+ {
+ memberVisitor.visitLibraryField(libraryClass, libraryField);
+ }
+ }
+
+
+ public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
+ {
+ if (usageMarker.isUsed(libraryMethod))
+ {
+ memberVisitor.visitLibraryMethod(libraryClass, libraryMethod);
+ }
+ }
+}
diff --git a/src/proguard/shrink/package.html b/src/proguard/shrink/package.html
new file mode 100644
index 000000000..897319880
--- /dev/null
+++ b/src/proguard/shrink/package.html
@@ -0,0 +1,3 @@
+
+This package contains classes to perform shrinking of class files.
+
diff --git a/src/proguard/util/AndMatcher.java b/src/proguard/util/AndMatcher.java
new file mode 100644
index 000000000..1aa372638
--- /dev/null
+++ b/src/proguard/util/AndMatcher.java
@@ -0,0 +1,49 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings matches both given StringMatcher
+ * instances.
+ *
+ * @author Eric Lafortune
+ */
+public class AndMatcher implements StringMatcher
+{
+ private final StringMatcher matcher1;
+ private final StringMatcher matcher2;
+
+
+ public AndMatcher(StringMatcher matcher1, StringMatcher matcher2)
+ {
+ this.matcher1 = matcher1;
+ this.matcher2 = matcher2;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return matcher1.matches(string) &&
+ matcher2.matches(string);
+ }
+}
diff --git a/src/proguard/util/ArrayUtil.java b/src/proguard/util/ArrayUtil.java
new file mode 100644
index 000000000..d78cf4a5f
--- /dev/null
+++ b/src/proguard/util/ArrayUtil.java
@@ -0,0 +1,960 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+import java.lang.reflect.Array;
+import java.util.Arrays;
+
+/**
+ * This class contains utility methods operating on arrays.
+ */
+public class ArrayUtil
+{
+ /**
+ * Returns whether the elements of the two given arrays are the same.
+ * @param array1 the first array.
+ * @param array2 the second array.
+ * @param size the size of the arrays to be checked.
+ * @return whether the elements are the same.
+ */
+ public static boolean equal(byte[] array1, byte[] array2, int size)
+ {
+ for (int index = 0; index < size; index++)
+ {
+ if (array1[index] != array2[index])
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Returns whether the elements of the two given arrays are the same.
+ * @param array1 the first array.
+ * @param array2 the second array.
+ * @param size the size of the arrays to be checked.
+ * @return whether the elements are the same.
+ */
+ public static boolean equal(short[] array1, short[] array2, int size)
+ {
+ for (int index = 0; index < size; index++)
+ {
+ if (array1[index] != array2[index])
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Returns whether the elements of the two given arrays are the same.
+ * @param array1 the first array.
+ * @param array2 the second array.
+ * @param size the size of the arrays to be checked.
+ * @return whether the elements are the same.
+ */
+ public static boolean equal(int[] array1, int[] array2, int size)
+ {
+ for (int index = 0; index < size; index++)
+ {
+ if (array1[index] != array2[index])
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Returns whether the elements of the two given arrays are the same.
+ * @param array1 the first array.
+ * @param array2 the second array.
+ * @param size the size of the arrays to be checked.
+ * @return whether the elements are the same.
+ */
+ public static boolean equal(Object[] array1, Object[] array2, int size)
+ {
+ for (int index = 0; index < size; index++)
+ {
+ if (!array1[index].equals(array2[index]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Returns a hash code for the elements of the given array.
+ * @param array the array.
+ * @param size the size of the array to be taken into account.
+ * @return a hash code.
+ */
+ public static int hashCode(byte[] array, int size)
+ {
+ int hashCode = 0;
+
+ for (int index = 0; index < size; index++)
+ {
+ hashCode ^= array[index];
+ }
+
+ return hashCode;
+ }
+
+
+ /**
+ * Returns a hash code for the elements of the given array.
+ * @param array the array.
+ * @param size the size of the array to be taken into account.
+ * @return a hash code.
+ */
+ public static int hashCode(short[] array, int size)
+ {
+ int hashCode = 0;
+
+ for (int index = 0; index < size; index++)
+ {
+ hashCode ^= array[index];
+ }
+
+ return hashCode;
+ }
+
+
+ /**
+ * Returns a hash code for the elements of the given array.
+ * @param array the array.
+ * @param size the size of the array to be taken into account.
+ * @return a hash code.
+ */
+ public static int hashCode(int[] array, int size)
+ {
+ int hashCode = 0;
+
+ for (int index = 0; index < size; index++)
+ {
+ hashCode ^= array[index];
+ }
+
+ return hashCode;
+ }
+
+
+ /**
+ * Returns a hash code for the elements of the given array.
+ * @param array the array.
+ * @param size the size of the array to be taken into account.
+ * @return a hash code.
+ */
+ public static int hashCode(Object[] array, int size)
+ {
+ int hashCode = 0;
+
+ for (int index = 0; index < size; index++)
+ {
+ hashCode ^= array[index].hashCode();
+ }
+
+ return hashCode;
+ }
+
+
+ /**
+ * Compares the elements of the two given arrays.
+ * @param array1 the first array.
+ * @param size1 the size of the first array.
+ * @param array2 the second array.
+ * @param size2 the size of the second array.
+ * @return 0 if all elements are the same,
+ * -1 if the first different element in the first array is smaller
+ * than the corresponding element in the second array,
+ * or 1 if it is larger.
+ */
+ public static int compare(byte[] array1, int size1,
+ byte[] array2, int size2)
+ {
+ int minSize = Math.min(size1, size2);
+
+ for (int index = 0; index < minSize; index++)
+ {
+ if (array1[index] < array2[index])
+ {
+ return -1;
+ }
+ else if (array1[index] > array2[index])
+ {
+ return 1;
+ }
+ }
+
+ return size1 < size2 ? -1 :
+ size1 == size2 ? 0 :
+ 1;
+ }
+
+
+ /**
+ * Compares the elements of the two given arrays.
+ * @param array1 the first array.
+ * @param size1 the size of the first array.
+ * @param array2 the second array.
+ * @param size2 the size of the second array.
+ * @return 0 if all elements are the same,
+ * -1 if the first different element in the first array is smaller
+ * than the corresponding element in the second array,
+ * or 1 if it is larger.
+ */
+ public static int compare(short[] array1, int size1,
+ short[] array2, int size2)
+ {
+ int minSize = Math.min(size1, size2);
+
+ for (int index = 0; index < minSize; index++)
+ {
+ if (array1[index] < array2[index])
+ {
+ return -1;
+ }
+ else if (array1[index] > array2[index])
+ {
+ return 1;
+ }
+ }
+
+ return size1 < size2 ? -1 :
+ size1 == size2 ? 0 :
+ 1;
+ }
+
+
+ /**
+ * Compares the elements of the two given arrays.
+ * @param array1 the first array.
+ * @param size1 the size of the first array.
+ * @param array2 the second array.
+ * @param size2 the size of the second array.
+ * @return 0 if all elements are the same,
+ * -1 if the first different element in the first array is smaller
+ * than the corresponding element in the second array,
+ * or 1 if it is larger.
+ */
+ public static int compare(int[] array1, int size1,
+ int[] array2, int size2)
+ {
+ int minSize = Math.min(size1, size2);
+
+ for (int index = 0; index < minSize; index++)
+ {
+ if (array1[index] < array2[index])
+ {
+ return -1;
+ }
+ else if (array1[index] > array2[index])
+ {
+ return 1;
+ }
+ }
+
+ return size1 < size2 ? -1 :
+ size1 == size2 ? 0 :
+ 1;
+ }
+
+
+ /**
+ * Compares the elements of the two given arrays.
+ * @param array1 the first array.
+ * @param size1 the size of the first array.
+ * @param array2 the second array.
+ * @param size2 the size of the second array.
+ * @return 0 if all elements are the same,
+ * -1 if the first different element in the first array is smaller
+ * than the corresponding element in the second array,
+ * or 1 if it is larger.
+ */
+ public static int compare(Comparable[] array1, int size1,
+ Comparable[] array2, int size2)
+ {
+ int minSize = Math.min(size1, size2);
+
+ for (int index = 0; index < minSize; index++)
+ {
+ int comparison = ObjectUtil.compare(array1[index], array2[index]);
+ if (comparison != 0)
+ {
+ return comparison;
+ }
+ }
+
+ return size1 < size2 ? -1 :
+ size1 == size2 ? 0 :
+ 1;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static boolean[] extendArray(boolean[] array, int size)
+ {
+ // Reuse the existing array if possible.
+ if (array.length >= size)
+ {
+ return array;
+ }
+
+ // Otherwise create and initialize a new array.
+ boolean[] newArray = new boolean[size];
+
+ System.arraycopy(array, 0,
+ newArray, 0,
+ array.length);
+
+ return newArray;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @param initialValue the intial value of the elements.
+ * @return the original array, or a copy if it had to be
+ * extended.
+ */
+ public static boolean[] ensureArraySize(boolean[] array,
+ int size,
+ boolean initialValue)
+ {
+ // Is the existing array large enough?
+ if (array.length >= size)
+ {
+ // Reinitialize the existing array.
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ else
+ {
+ // Otherwise create and initialize a new array.
+ array = new boolean[size];
+
+ if (initialValue)
+ {
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ }
+
+ return array;
+ }
+
+
+ /**
+ * Adds the given element to the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static byte[] add(byte[] array, int size, byte element)
+ {
+ array = extendArray(array, size + 1);
+
+ array[size] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Inserts the given element in the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index at which the element is to be added.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static byte[] insert(byte[] array, int size, int index, byte element)
+ {
+ array = extendArray(array, size + 1);
+
+ // Move the last part.
+ System.arraycopy(array, index,
+ array, index + 1,
+ size - index);
+
+ array[index] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Removes the specified element from the given array.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index of the element to be removed.
+ */
+ public static void remove(byte[] array, int size, int index)
+ {
+ System.arraycopy(array, index + 1,
+ array, index,
+ array.length - index - 1);
+
+ array[size - 1] = 0;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static byte[] extendArray(byte[] array, int size)
+ {
+ // Reuse the existing array if possible.
+ if (array.length >= size)
+ {
+ return array;
+ }
+
+ // Otherwise create and initialize a new array.
+ byte[] newArray = new byte[size];
+
+ System.arraycopy(array, 0,
+ newArray, 0,
+ array.length);
+
+ return newArray;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @param initialValue the intial value of the elements.
+ * @return the original array, or a copy if it had to be
+ * extended.
+ */
+ public static byte[] ensureArraySize(byte[] array,
+ int size,
+ byte initialValue)
+ {
+ // Is the existing array large enough?
+ if (array.length >= size)
+ {
+ // Reinitialize the existing array.
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ else
+ {
+ // Otherwise create and initialize a new array.
+ array = new byte[size];
+
+ if (initialValue != 0)
+ {
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ }
+
+ return array;
+ }
+
+
+ /**
+ * Adds the given element to the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static short[] add(short[] array, int size, short element)
+ {
+ array = extendArray(array, size + 1);
+
+ array[size] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Inserts the given element in the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index at which the element is to be added.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static short[] insert(short[] array, int size, int index, short element)
+ {
+ array = extendArray(array, size + 1);
+
+ // Move the last part.
+ System.arraycopy(array, index,
+ array, index + 1,
+ size - index);
+
+ array[index] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Removes the specified element from the given array.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index of the element to be removed.
+ */
+ public static void remove(short[] array, int size, int index)
+ {
+ System.arraycopy(array, index + 1,
+ array, index,
+ array.length - index - 1);
+
+ array[size - 1] = 0;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static short[] extendArray(short[] array, int size)
+ {
+ // Reuse the existing array if possible.
+ if (array.length >= size)
+ {
+ return array;
+ }
+
+ // Otherwise create and initialize a new array.
+ short[] newArray = new short[size];
+
+ System.arraycopy(array, 0,
+ newArray, 0,
+ array.length);
+
+ return newArray;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @param initialValue the intial value of the elements.
+ * @return the original array, or a copy if it had to be
+ * extended.
+ */
+ public static short[] ensureArraySize(short[] array,
+ int size,
+ short initialValue)
+ {
+ // Is the existing array large enough?
+ if (array.length >= size)
+ {
+ // Reinitialize the existing array.
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ else
+ {
+ // Otherwise create and initialize a new array.
+ array = new short[size];
+
+ if (initialValue != 0)
+ {
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ }
+
+ return array;
+ }
+
+
+ /**
+ * Adds the given element to the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static int[] add(int[] array, int size, int element)
+ {
+ array = extendArray(array, size + 1);
+
+ array[size] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Inserts the given element in the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index at which the element is to be added.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static int[] insert(int[] array, int size, int index, int element)
+ {
+ array = extendArray(array, size + 1);
+
+ // Move the last part.
+ System.arraycopy(array, index,
+ array, index + 1,
+ size - index);
+
+ array[index] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Removes the specified element from the given array.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index of the element to be removed.
+ */
+ public static void remove(int[] array, int size, int index)
+ {
+ System.arraycopy(array, index + 1,
+ array, index,
+ array.length - index - 1);
+
+ array[size - 1] = 0;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static int[] extendArray(int[] array, int size)
+ {
+ // Reuse the existing array if possible.
+ if (array.length >= size)
+ {
+ return array;
+ }
+
+ // Otherwise create and initialize a new array.
+ int[] newArray = new int[size];
+
+ System.arraycopy(array, 0,
+ newArray, 0,
+ array.length);
+
+ return newArray;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @param initialValue the intial value of the elements.
+ * @return the original array, or a copy if it had to be
+ * extended.
+ */
+ public static int[] ensureArraySize(int[] array,
+ int size,
+ int initialValue)
+ {
+ // Is the existing array large enough?
+ if (array.length >= size)
+ {
+ // Reinitialize the existing array.
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ else
+ {
+ // Otherwise create and initialize a new array.
+ array = new int[size];
+
+ if (initialValue != 0)
+ {
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ }
+
+ return array;
+ }
+
+
+ /**
+ * Adds the given element to the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static long[] add(long[] array, int size, long element)
+ {
+ array = extendArray(array, size + 1);
+
+ array[size] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Inserts the given element in the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index at which the element is to be added.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static long[] insert(long[] array, int size, int index, long element)
+ {
+ array = extendArray(array, size + 1);
+
+ // Move the last part.
+ System.arraycopy(array, index,
+ array, index + 1,
+ size - index);
+
+ array[index] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Removes the specified element from the given array.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index of the element to be removed.
+ */
+ public static void remove(long[] array, int size, int index)
+ {
+ System.arraycopy(array, index + 1,
+ array, index,
+ array.length - index - 1);
+
+ array[size - 1] = 0;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static long[] extendArray(long[] array, int size)
+ {
+ // Reuse the existing array if possible.
+ if (array.length >= size)
+ {
+ return array;
+ }
+
+ // Otherwise create and initialize a new array.
+ long[] newArray = new long[size];
+
+ System.arraycopy(array, 0,
+ newArray, 0,
+ array.length);
+
+ return newArray;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @param initialValue the intial value of the elements.
+ * @return the original array, or a copy if it had to be
+ * extended.
+ */
+ public static long[] ensureArraySize(long[] array,
+ int size,
+ long initialValue)
+ {
+ // Is the existing array large enough?
+ if (array.length >= size)
+ {
+ // Reinitialize the existing array.
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ else
+ {
+ // Otherwise create and initialize a new array.
+ array = new long[size];
+
+ if (initialValue != 0L)
+ {
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ }
+
+ return array;
+ }
+
+
+ /**
+ * Adds the given element to the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static Object[] add(Object[] array, int size, Object element)
+ {
+ array = extendArray(array, size + 1);
+
+ array[size] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Inserts the given element in the given array.
+ * The array is extended if necessary.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index at which the element is to be added.
+ * @param element the element to be added.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static Object[] insert(Object[] array, int size, int index, Object element)
+ {
+ array = extendArray(array, size + 1);
+
+ // Move the last part.
+ System.arraycopy(array, index,
+ array, index + 1,
+ size - index);
+
+ array[index] = element;
+
+ return array;
+ }
+
+
+ /**
+ * Removes the specified element from the given array.
+ * @param array the array.
+ * @param size the original size of the array.
+ * @param index the index of the element to be removed.
+ */
+ public static void remove(Object[] array, int size, int index)
+ {
+ System.arraycopy(array, index + 1,
+ array, index,
+ array.length - index - 1);
+
+ array[size - 1] = null;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @return the original array, or a copy if it had to be extended.
+ */
+ public static Object[] extendArray(Object[] array, int size)
+ {
+ // Reuse the existing array if possible.
+ if (array.length >= size)
+ {
+ return array;
+ }
+
+ // Otherwise create and initialize a new array.
+ Object[] newArray = (Object[])Array.newInstance(array.getClass().getComponentType(), size);
+
+ System.arraycopy(array, 0,
+ newArray, 0,
+ array.length);
+
+ return newArray;
+ }
+
+
+ /**
+ * Ensures the given array has a given size.
+ * @param array the array.
+ * @param size the target size of the array.
+ * @param initialValue the intial value of the elements.
+ * @return the original array, or a copy if it had to be
+ * extended.
+ */
+ public static Object[] ensureArraySize(Object[] array,
+ int size,
+ Object initialValue)
+ {
+ // Is the existing array large enough?
+ if (array.length >= size)
+ {
+ // Reinitialize the existing array.
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ else
+ {
+ // Otherwise create and initialize a new array.
+ array = (Object[])Array.newInstance(array.getClass().getComponentType(), size);
+
+ if (initialValue != null)
+ {
+ Arrays.fill(array, 0, size, initialValue);
+ }
+ }
+
+ return array;
+ }
+}
diff --git a/src/proguard/util/ClassNameParser.java b/src/proguard/util/ClassNameParser.java
new file mode 100644
index 000000000..22a07035f
--- /dev/null
+++ b/src/proguard/util/ClassNameParser.java
@@ -0,0 +1,216 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+import proguard.classfile.ClassConstants;
+
+/**
+ * This StringParser can create StringMatcher instances for regular expressions
+ * matching internal class names (or descriptors containing class names).
+ * The regular expressions can contain the following wildcards:
+ * '%' for a single internal primitive type character (V, Z, B, C, S, I, F,
+ * J, or D),
+ * '?' for a single regular class name character,
+ * '*' for any number of regular class name characters,
+ * '**' for any number of regular class name characters or package separator
+ * characters ('/'),
+ * 'L***;' for a single internal type (class name or primitive type,
+ * array or non-array), and
+ * 'L///;' for any number of internal types (class names and primitive
+ * types).
+ *
+ * @author Eric Lafortune
+ */
+public class ClassNameParser implements StringParser
+{
+ private static final char[] INTERNAL_PRIMITIVE_TYPES = new char[]
+ {
+ ClassConstants.INTERNAL_TYPE_VOID,
+ ClassConstants.INTERNAL_TYPE_BOOLEAN,
+ ClassConstants.INTERNAL_TYPE_BYTE,
+ ClassConstants.INTERNAL_TYPE_CHAR,
+ ClassConstants.INTERNAL_TYPE_SHORT,
+ ClassConstants.INTERNAL_TYPE_INT,
+ ClassConstants.INTERNAL_TYPE_LONG,
+ ClassConstants.INTERNAL_TYPE_FLOAT,
+ ClassConstants.INTERNAL_TYPE_DOUBLE,
+ };
+
+
+ // Implementations for StringParser.
+
+ public StringMatcher parse(String regularExpression)
+ {
+ int index;
+ StringMatcher nextMatcher = new EmptyStringMatcher();
+
+ // Look for wildcards.
+ for (index = 0; index < regularExpression.length(); index++)
+ {
+ // Is there an 'L///;' wildcard?
+ if (regularExpression.regionMatches(index, "L///;", 0, 5))
+ {
+ SettableMatcher settableMatcher = new SettableMatcher();
+
+ // Create a matcher, recursively, for the remainder of the
+ // string, optionally preceded by any type.
+ nextMatcher =
+ new OrMatcher(parse(regularExpression.substring(index + 5)),
+ createAnyTypeMatcher(settableMatcher));
+
+ settableMatcher.setMatcher(nextMatcher);
+
+ break;
+ }
+
+ // Is there an 'L***;' wildcard?
+ if (regularExpression.regionMatches(index, "L***;", 0, 5))
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ createAnyTypeMatcher(parse(regularExpression.substring(index + 5)));
+ break;
+ }
+
+ // Is there a '**' wildcard?
+ if (regularExpression.regionMatches(index, "**", 0, 2))
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ new char[] { ClassConstants.INTERNAL_TYPE_CLASS_END },
+ 0,
+ Integer.MAX_VALUE,
+ parse(regularExpression.substring(index + 2)));
+ break;
+ }
+
+ // Is there a '*' wildcard?
+ else if (regularExpression.charAt(index) == '*')
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ new char[] { ClassConstants.INTERNAL_TYPE_CLASS_END, ClassConstants.INTERNAL_PACKAGE_SEPARATOR },
+ 0,
+ Integer.MAX_VALUE,
+ parse(regularExpression.substring(index + 1)));
+ break;
+ }
+
+ // Is there a '?' wildcard?
+ else if (regularExpression.charAt(index) == '?')
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ new char[] { ClassConstants.INTERNAL_TYPE_CLASS_END, ClassConstants.INTERNAL_PACKAGE_SEPARATOR },
+ 1,
+ 1,
+ parse(regularExpression.substring(index + 1)));
+ break;
+ }
+
+ // Is there a '%' wildcard?
+ else if (regularExpression.charAt(index) == '%')
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(INTERNAL_PRIMITIVE_TYPES,
+ null,
+ 1,
+ 1,
+ parse(regularExpression.substring(index + 1)));
+ break;
+ }
+ }
+
+ // Return a matcher for the fixed first part of the regular expression,
+ // if any, and the remainder.
+ return index != 0 ?
+ (StringMatcher)new FixedStringMatcher(regularExpression.substring(0, index), nextMatcher) :
+ (StringMatcher)nextMatcher;
+ }
+
+
+ // Small utility methods.
+
+
+ /**
+ * Creates a StringMatcher that matches any type (class or primitive type,
+ * array or non-array) and then the given matcher.
+ */
+ private VariableStringMatcher createAnyTypeMatcher(StringMatcher nextMatcher)
+ {
+ return new VariableStringMatcher(new char[] { ClassConstants.INTERNAL_TYPE_ARRAY },
+ null,
+ 0,
+ 255,
+ new OrMatcher(
+ new VariableStringMatcher(INTERNAL_PRIMITIVE_TYPES,
+ null,
+ 1,
+ 1,
+ nextMatcher),
+ new VariableStringMatcher(new char[] { ClassConstants.INTERNAL_TYPE_CLASS_START },
+ null,
+ 1,
+ 1,
+ new VariableStringMatcher(null,
+ new char[] { ClassConstants.INTERNAL_TYPE_CLASS_END },
+ 0,
+ Integer.MAX_VALUE,
+ new VariableStringMatcher(new char[] { ClassConstants.INTERNAL_TYPE_CLASS_END },
+ null,
+ 1,
+ 1,
+ nextMatcher)))));
+ }
+
+
+ /**
+ * A main method for testing class name matching.
+ */
+ public static void main(String[] args)
+ {
+ try
+ {
+ System.out.println("Regular expression ["+args[0]+"]");
+ ClassNameParser parser = new ClassNameParser();
+ StringMatcher matcher = parser.parse(args[0]);
+ for (int index = 1; index < args.length; index++)
+ {
+ String string = args[index];
+ System.out.print("String ["+string+"]");
+ System.out.println(" -> match = "+matcher.matches(args[index]));
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/util/ConstantMatcher.java b/src/proguard/util/ConstantMatcher.java
new file mode 100644
index 000000000..8c0f1e18e
--- /dev/null
+++ b/src/proguard/util/ConstantMatcher.java
@@ -0,0 +1,48 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher matches any string or no string at all.
+ *
+ * @author Eric Lafortune
+ */
+public class ConstantMatcher implements StringMatcher
+{
+ private boolean matches;
+
+
+ /**
+ * Creates a new ConstantMatcher that always returns the given result.
+ */
+ public ConstantMatcher(boolean matches)
+ {
+ this.matches = matches;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return matches;
+ }
+}
\ No newline at end of file
diff --git a/src/proguard/util/EmptyStringMatcher.java b/src/proguard/util/EmptyStringMatcher.java
new file mode 100644
index 000000000..f07c6666c
--- /dev/null
+++ b/src/proguard/util/EmptyStringMatcher.java
@@ -0,0 +1,36 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings are empty.
+ *
+ * @author Eric Lafortune
+ */
+public class EmptyStringMatcher implements StringMatcher
+{
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return string.length() == 0;
+ }
+}
diff --git a/src/proguard/util/ExtensionMatcher.java b/src/proguard/util/ExtensionMatcher.java
new file mode 100644
index 000000000..eeb627ac5
--- /dev/null
+++ b/src/proguard/util/ExtensionMatcher.java
@@ -0,0 +1,63 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings end in a given extension, ignoring
+ * its case.
+ *
+ * @author Eric Lafortune
+ */
+public class ExtensionMatcher implements StringMatcher
+{
+ private final String extension;
+
+
+ /**
+ * Creates a new StringMatcher.
+ * @param extension the extension against which strings will be matched.
+ */
+ public ExtensionMatcher(String extension)
+ {
+ this.extension = extension;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return endsWithIgnoreCase(string, extension);
+ }
+
+
+ /**
+ * Returns whether the given string ends with the given suffix, ignoring its
+ * case.
+ */
+ private static boolean endsWithIgnoreCase(String string, String suffix)
+ {
+ int stringLength = string.length();
+ int suffixLength = suffix.length();
+
+ return string.regionMatches(true, stringLength - suffixLength, suffix, 0, suffixLength);
+ }
+}
diff --git a/src/proguard/util/FileNameParser.java b/src/proguard/util/FileNameParser.java
new file mode 100644
index 000000000..9ec6d22eb
--- /dev/null
+++ b/src/proguard/util/FileNameParser.java
@@ -0,0 +1,121 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+import java.io.File;
+
+/**
+ * This StringParser can create StringMatcher instances for regular expressions
+ * matching file names. The regular expressions can contain the following
+ * wildcards:
+ * '?' for a single regular file name character,
+ * '*' for any number of regular file name characters, and
+ * '**' for any number of regular file name characters or directory separator
+ * characters (always including '/').
+ *
+ * @author Eric Lafortune
+ */
+public class FileNameParser implements StringParser
+{
+ // Implementations for StringParser.
+
+ public StringMatcher parse(String regularExpression)
+ {
+ int index;
+ StringMatcher nextMatcher = new EmptyStringMatcher();
+
+ // Look for wildcards.
+ for (index = 0; index < regularExpression.length(); index++)
+ {
+ // Is there a '**' wildcard?
+ if (regularExpression.regionMatches(index, "**", 0, 2))
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ null,
+ 0,
+ Integer.MAX_VALUE,
+ parse(regularExpression.substring(index + 2)));
+ break;
+ }
+
+ // Is there a '*' wildcard?
+ else if (regularExpression.charAt(index) == '*')
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ new char[] { File.pathSeparatorChar, '/' },
+ 0,
+ Integer.MAX_VALUE,
+ parse(regularExpression.substring(index + 1)));
+ break;
+ }
+
+ // Is there a '?' wildcard?
+ else if (regularExpression.charAt(index) == '?')
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ new char[] { File.pathSeparatorChar, '/' },
+ 1,
+ 1,
+ parse(regularExpression.substring(index + 1)));
+ break;
+ }
+ }
+
+ // Return a matcher for the fixed first part of the regular expression,
+ // if any, and the remainder.
+ return index != 0 ?
+ (StringMatcher)new FixedStringMatcher(regularExpression.substring(0, index), nextMatcher) :
+ (StringMatcher)nextMatcher;
+ }
+
+
+ /**
+ * A main method for testing file name matching.
+ */
+ public static void main(String[] args)
+ {
+ try
+ {
+ System.out.println("Regular expression ["+args[0]+"]");
+ FileNameParser parser = new FileNameParser();
+ StringMatcher matcher = parser.parse(args[0]);
+ for (int index = 1; index < args.length; index++)
+ {
+ String string = args[index];
+ System.out.print("String ["+string+"]");
+ System.out.println(" -> match = "+matcher.matches(args[index]));
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/util/FixedStringMatcher.java b/src/proguard/util/FixedStringMatcher.java
new file mode 100644
index 000000000..2f0227121
--- /dev/null
+++ b/src/proguard/util/FixedStringMatcher.java
@@ -0,0 +1,56 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings start with a given fixed string
+ * and then match another optional given StringMatcher.
+ *
+ * @author Eric Lafortune
+ */
+public class FixedStringMatcher implements StringMatcher
+{
+ private final String fixedString;
+ private final StringMatcher nextMatcher;
+
+
+ public FixedStringMatcher(String fixedString)
+ {
+ this(fixedString, null);
+ }
+
+
+ public FixedStringMatcher(String fixedString, StringMatcher nextMatcher)
+ {
+ this.fixedString = fixedString;
+ this.nextMatcher = nextMatcher;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return string.startsWith(fixedString) &&
+ (nextMatcher == null ||
+ nextMatcher.matches(string.substring(fixedString.length())));
+ }
+}
diff --git a/src/proguard/util/ListMatcher.java b/src/proguard/util/ListMatcher.java
new file mode 100644
index 000000000..e07bff07f
--- /dev/null
+++ b/src/proguard/util/ListMatcher.java
@@ -0,0 +1,69 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings match a given list of StringMatcher
+ * instances. The instances are considered sequentially. Each instance in the
+ * list can optionally be negated, meaning that a match makes the entire
+ * remaining match fail.
+ *
+ * @author Eric Lafortune
+ */
+public class ListMatcher implements StringMatcher
+{
+ private final StringMatcher[] matchers;
+ private final boolean[] negate;
+
+
+ public ListMatcher(StringMatcher[] matchers)
+ {
+ this(matchers, null);
+ }
+
+
+ public ListMatcher(StringMatcher[] matchers, boolean[] negate)
+ {
+ this.matchers = matchers;
+ this.negate = negate;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ // Check the list of matchers.
+ for (int index = 0; index < matchers.length; index++)
+ {
+ StringMatcher matcher = matchers[index];
+ if (matcher.matches(string))
+ {
+ return negate == null ||
+ !negate[index];
+ }
+ }
+
+ return negate != null &&
+ negate[negate.length - 1];
+
+ }
+}
diff --git a/src/proguard/util/ListParser.java b/src/proguard/util/ListParser.java
new file mode 100644
index 000000000..b3b45185d
--- /dev/null
+++ b/src/proguard/util/ListParser.java
@@ -0,0 +1,137 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+import java.util.List;
+
+/**
+ * This StringParser can create StringMatcher instances for regular expressions.
+ * The regular expressions are either presented as a list, or they are
+ * interpreted as comma-separated lists, optionally prefixed with '!' negators.
+ * If an entry with a negator matches, a negative match is returned, without
+ * considering any subsequent entries in the list. The creation of StringMatcher
+ * instances for the entries is delegated to the given StringParser.
+ *
+ * @author Eric Lafortune
+ */
+public class ListParser implements StringParser
+{
+ private final StringParser stringParser;
+
+
+ /**
+ * Creates a new ListParser that parses individual elements in the
+ * comma-separated list with the given StringParser.
+ */
+ public ListParser(StringParser stringParser)
+ {
+ this.stringParser = stringParser;
+ }
+
+
+ // Implementations for StringParser.
+
+ public StringMatcher parse(String regularExpression)
+ {
+ // Does the regular expression contain a ',' list separator?
+ return parse(ListUtil.commaSeparatedList(regularExpression));
+ }
+
+
+ /**
+ * Creates a StringMatcher for the given regular expression, which can
+ * be a list of optionally negated simple entries.
+ * java.util.List
objects.
+ *
+ * @author Eric Lafortune
+ */
+public class ListUtil
+{
+ /**
+ * Creates a comma-separated String from the given List of String objects.
+ */
+ public static String commaSeparatedString(List list, boolean quoteStrings)
+ {
+ if (list == null)
+ {
+ return null;
+ }
+
+ StringBuffer buffer = new StringBuffer();
+
+ for (int index = 0; index < list.size(); index++)
+ {
+ if (index > 0)
+ {
+ buffer.append(',');
+ }
+
+ String string = (String)list.get(index);
+
+ if (quoteStrings)
+ {
+ string = quotedString(string);
+ }
+
+ buffer.append(string);
+ }
+
+ return buffer.toString();
+ }
+
+
+ /**
+ * Creates a List of String objects from the given comma-separated String.
+ */
+ public static List commaSeparatedList(String string)
+ {
+ if (string == null)
+ {
+ return null;
+ }
+
+ List list = new ArrayList();
+ int index = 0;
+ while ((index = skipWhitespace(string, index)) < string.length())
+ {
+ int nextIndex;
+
+ // Do we have an opening quote?
+ if (string.charAt(index) == '\'')
+ {
+ // Parse a quoted string.
+ nextIndex = string.indexOf('\'', index + 1);
+ if (nextIndex < 0)
+ {
+ nextIndex = string.length();
+ }
+
+ list.add(string.substring(index + 1, nextIndex));
+ }
+ else
+ {
+ // Parse a non-quoted string.
+ nextIndex = string.indexOf(',', index);
+ if (nextIndex < 0)
+ {
+ nextIndex = string.length();
+ }
+
+ String substring = string.substring(index, nextIndex).trim();
+ if (substring.length() > 0)
+ {
+ list.add(substring);
+ }
+ }
+
+ index = nextIndex + 1;
+ }
+
+ return list;
+ }
+
+
+ /**
+ * Skips any whitespace characters.
+ */
+ private static int skipWhitespace(String string, int index)
+ {
+ while (index < string.length() &&
+ Character.isWhitespace(string.charAt(index)))
+ {
+ index++;
+ }
+ return index;
+ }
+
+
+ /**
+ * Returns a quoted version of the given string, if necessary.
+ */
+ private static String quotedString(String string)
+ {
+ return string.length() == 0 ||
+ string.indexOf(' ') >= 0 ||
+ string.indexOf('@') >= 0 ||
+ string.indexOf('{') >= 0 ||
+ string.indexOf('}') >= 0 ||
+ string.indexOf('(') >= 0 ||
+ string.indexOf(')') >= 0 ||
+ string.indexOf(':') >= 0 ||
+ string.indexOf(';') >= 0 ||
+ string.indexOf(',') >= 0 ? ("'" + string + "'") :
+ ( string );
+ }
+
+
+ public static void main(String[] args)
+ {
+ if (args.length == 1)
+ {
+ System.out.println("Input string: ["+args[0]+"]");
+
+ List list = commaSeparatedList(args[0]);
+
+ System.out.println("Resulting list:");
+ for (int index = 0; index < list.size(); index++)
+ {
+ System.out.println("["+list.get(index)+"]");
+ }
+ }
+ else
+ {
+ List list = Arrays.asList(args);
+
+ System.out.println("Input list:");
+ for (int index = 0; index < list.size(); index++)
+ {
+ System.out.println("["+list.get(index)+"]");
+ }
+
+ String string = commaSeparatedString(list, true);
+
+ System.out.println("Resulting string: ["+string+"]");
+ }
+ }
+}
diff --git a/src/proguard/util/NameParser.java b/src/proguard/util/NameParser.java
new file mode 100644
index 000000000..f25d52e75
--- /dev/null
+++ b/src/proguard/util/NameParser.java
@@ -0,0 +1,106 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringParser can create StringMatcher instances for regular expressions
+ * matching names. The regular expressions are interpreted as comma-separated
+ * lists of names, optionally prefixed with '!' negators.
+ * If a name with a negator matches, a negative match is returned, without
+ * considering any subsequent entries in the list.
+ * Names can contain the following wildcards:
+ * '?' for a single character, and
+ * '*' for any number of characters.
+ *
+ * @author Eric Lafortune
+ */
+public class NameParser implements StringParser
+{
+ // Implementations for StringParser.
+
+ public StringMatcher parse(String regularExpression)
+ {
+ int index;
+ StringMatcher nextMatcher = new EmptyStringMatcher();
+
+ // Look for wildcards.
+ for (index = 0; index < regularExpression.length(); index++)
+ {
+ // Is there a '*' wildcard?
+ if (regularExpression.charAt(index) == '*')
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ null,
+ 0,
+ Integer.MAX_VALUE,
+ parse(regularExpression.substring(index + 1)));
+ break;
+ }
+
+ // Is there a '?' wildcard?
+ else if (regularExpression.charAt(index) == '?')
+ {
+ // Create a matcher for the wildcard and, recursively, for the
+ // remainder of the string.
+ nextMatcher =
+ new VariableStringMatcher(null,
+ null,
+ 1,
+ 1,
+ parse(regularExpression.substring(index + 1)));
+ break;
+ }
+ }
+
+ // Return a matcher for the fixed first part of the regular expression,
+ // if any, and the remainder.
+ return index != 0 ?
+ (StringMatcher)new FixedStringMatcher(regularExpression.substring(0, index), nextMatcher) :
+ (StringMatcher)nextMatcher;
+ }
+
+
+ /**
+ * A main method for testing name matching.
+ */
+ public static void main(String[] args)
+ {
+ try
+ {
+ System.out.println("Regular expression ["+args[0]+"]");
+ NameParser parser = new NameParser();
+ StringMatcher matcher = parser.parse(args[0]);
+ for (int index = 1; index < args.length; index++)
+ {
+ String string = args[index];
+ System.out.print("String ["+string+"]");
+ System.out.println(" -> match = "+matcher.matches(args[index]));
+ }
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+}
diff --git a/src/proguard/util/NotMatcher.java b/src/proguard/util/NotMatcher.java
new file mode 100644
index 000000000..af539d065
--- /dev/null
+++ b/src/proguard/util/NotMatcher.java
@@ -0,0 +1,46 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings does not match the given
+ * StringMatcher.
+ *
+ * @author Eric Lafortune
+ */
+public class NotMatcher implements StringMatcher
+{
+ private final StringMatcher matcher;
+
+
+ public NotMatcher(StringMatcher matcher)
+ {
+ this.matcher = matcher;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return !matcher.matches(string);
+ }
+}
diff --git a/src/proguard/util/ObjectUtil.java b/src/proguard/util/ObjectUtil.java
new file mode 100644
index 000000000..c5de36a34
--- /dev/null
+++ b/src/proguard/util/ObjectUtil.java
@@ -0,0 +1,67 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package proguard.util;
+
+/**
+ * This class contains utility methods operating on objects.
+ */
+public class ObjectUtil
+{
+ /**
+ * Returns whether the given objects are the same.
+ * @param object1 the first object, may be null.
+ * @param object2 the second object, may be null.
+ * @return whether the objects are the same.
+ */
+ public static boolean equal(Object object1, Object object2)
+ {
+ return object1 == null ?
+ object2 == null :
+ object1.equals(object2);
+ }
+
+
+ /**
+ * Returns the hash code of the given object, or 0 if it is null.
+ * @param object the object, may be null.
+ * @return the hash code.
+ */
+ public static int hashCode(Object object)
+ {
+ return object == null ? 0 : object.hashCode();
+ }
+
+
+ /**
+ * Returns a comparison of the two given objects.
+ * @param object1 the first object, may be null.
+ * @param object2 the second object, may be null.
+ * @return -1, 0, or 1.
+ * @see Comparable#compareTo(Object)
+ */
+ public static int compare(Comparable object1, Comparable object2)
+ {
+ return object1 == null ?
+ object2 == null ? 0 : -1 :
+ object2 == null ? 1 : object1.compareTo(object2);
+ }
+}
diff --git a/src/proguard/util/OrMatcher.java b/src/proguard/util/OrMatcher.java
new file mode 100644
index 000000000..7ad85c48c
--- /dev/null
+++ b/src/proguard/util/OrMatcher.java
@@ -0,0 +1,49 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings matches either of the given
+ * StringMatcher instances.
+ *
+ * @author Eric Lafortune
+ */
+public class OrMatcher implements StringMatcher
+{
+ private final StringMatcher matcher1;
+ private final StringMatcher matcher2;
+
+
+ public OrMatcher(StringMatcher matcher1, StringMatcher matcher2)
+ {
+ this.matcher1 = matcher1;
+ this.matcher2 = matcher2;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return matcher1.matches(string) ||
+ matcher2.matches(string);
+ }
+}
diff --git a/src/proguard/util/SettableMatcher.java b/src/proguard/util/SettableMatcher.java
new file mode 100644
index 000000000..8650ccc84
--- /dev/null
+++ b/src/proguard/util/SettableMatcher.java
@@ -0,0 +1,46 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher delegates to a another StringMatcher that can be set
+ * after this StringMatcher has been constructed.
+ *
+ * @author Eric Lafortune
+ */
+public class SettableMatcher implements StringMatcher
+{
+ private StringMatcher matcher;
+
+
+ public void setMatcher(StringMatcher matcher)
+ {
+ this.matcher = matcher;
+ }
+
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ return matcher.matches(string);
+ }
+}
diff --git a/src/proguard/util/StringMatcher.java b/src/proguard/util/StringMatcher.java
new file mode 100644
index 000000000..146dbfce0
--- /dev/null
+++ b/src/proguard/util/StringMatcher.java
@@ -0,0 +1,38 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+
+/**
+ * This interface provides a method to determine whether strings match a given
+ * criterion, which is specified by the implementation.
+ *
+ * @author Eric Lafortune
+ */
+public interface StringMatcher
+{
+ /**
+ * Checks whether the given string matches.
+ * @param string the string to match.
+ * @return a boolean indicating whether the string matches the criterion.
+ */
+ public boolean matches(String string);
+}
diff --git a/src/proguard/util/StringParser.java b/src/proguard/util/StringParser.java
new file mode 100644
index 000000000..39d04d53e
--- /dev/null
+++ b/src/proguard/util/StringParser.java
@@ -0,0 +1,35 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This interface provides a method to create a SringMatcher for a given
+ * regular expression.
+ *
+ * @author Eric Lafortune
+ */
+public interface StringParser
+{
+ /**
+ * Creates a StringMatcher for the given regular expression.
+ */
+ public StringMatcher parse(String regularExpression);
+}
diff --git a/src/proguard/util/VariableStringMatcher.java b/src/proguard/util/VariableStringMatcher.java
new file mode 100644
index 000000000..5a07c2ac2
--- /dev/null
+++ b/src/proguard/util/VariableStringMatcher.java
@@ -0,0 +1,126 @@
+/*
+ * ProGuard -- shrinking, optimization, obfuscation, and preverification
+ * of Java bytecode.
+ *
+ * Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package proguard.util;
+
+/**
+ * This StringMatcher tests whether strings start with a specified variable
+ * string and then match another given StringMatcher.
+ *
+ * @author Eric Lafortune
+ */
+public class VariableStringMatcher implements StringMatcher
+{
+ private final char[] allowedCharacters;
+ private final char[] disallowedCharacters;
+ private final int minimumLength;
+ private final int maximumLength;
+ private final StringMatcher nextMatcher;
+
+
+ public VariableStringMatcher(char[] allowedCharacters,
+ char[] disallowedCharacters,
+ int minimumLength,
+ int maximumLength,
+ StringMatcher nextMatcher)
+ {
+ this.allowedCharacters = allowedCharacters;
+ this.disallowedCharacters = disallowedCharacters;
+ this.minimumLength = minimumLength;
+ this.maximumLength = maximumLength;
+ this.nextMatcher = nextMatcher;
+ }
+
+ // Implementations for StringMatcher.
+
+ public boolean matches(String string)
+ {
+ if (string.length() < minimumLength)
+ {
+ return false;
+ }
+
+ // Check the first minimum number of characters.
+ for (int index = 0; index < minimumLength; index++)
+ {
+ if (!isAllowedCharacter(string.charAt(index)))
+ {
+ return false;
+ }
+ }
+
+ int maximumLength = Math.min(this.maximumLength, string.length());
+
+ // Check the remaining characters, up to the maximum number.
+ for (int index = minimumLength; index < maximumLength; index++)
+ {
+ if (nextMatcher.matches(string.substring(index)))
+ {
+ return true;
+ }
+
+ if (!isAllowedCharacter(string.charAt(index)))
+ {
+ return false;
+ }
+ }
+
+ // Check the remaining characters in the string.
+ return nextMatcher.matches(string.substring(maximumLength));
+ }
+
+
+ // Small utility methods.
+
+ /**
+ * Returns whether the given character is allowed in the variable string.
+ */
+ private boolean isAllowedCharacter(char character)
+ {
+ // Check the allowed characters.
+ if (allowedCharacters != null)
+ {
+ for (int index = 0; index < allowedCharacters.length; index++)
+ {
+ if (allowedCharacters[index] == character)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ // Check the disallowed characters.
+ if (disallowedCharacters != null)
+ {
+ for (int index = 0; index < disallowedCharacters.length; index++)
+ {
+ if (disallowedCharacters[index] == character)
+ {
+ return false;
+ }
+ }
+ }
+
+ // Any remaining character is allowed.
+ return true;
+ }
+}
diff --git a/src/proguard/util/package.html b/src/proguard/util/package.html
new file mode 100644
index 000000000..cb14fdc0a
--- /dev/null
+++ b/src/proguard/util/package.html
@@ -0,0 +1,3 @@
+/wtklib/Linux/ktools.properties
or
+ * {j2mewtk.dir}\wtklib\Windows\ktools.properties
(whichever is
+ * applicable).
+ *
+ * obfuscator.runner.class.name: proguard.wtk.ProGuardObfuscator
+ * obfuscator.runner.classpath: /usr/local/java/proguard1.6/lib/proguard.jar
+ *
+ * Please make sure the class path is set correctly for your system.
+ *
+ * @author Eric Lafortune
+ */
+public class ProGuardObfuscator implements Obfuscator
+{
+ private static final String DEFAULT_CONFIGURATION = "default.pro";
+
+
+ // Implementations for Obfuscator.
+
+ public void createScriptFile(File jadFile,
+ File projectDir)
+ {
+ // We don't really need to create a script file;
+ // we'll just fill out all options in the run method.
+ }
+
+
+ public void run(File obfuscatedJarFile,
+ String wtkBinDir,
+ String wtkLibDir,
+ String jarFileName,
+ String projectDirName,
+ String classPath,
+ String emptyAPI)
+ throws IOException
+ {
+ // Create the ProGuard configuration.
+ Configuration configuration = new Configuration();
+
+ // Parse the default configuration file.
+ ConfigurationParser parser = new ConfigurationParser(this.getClass().getResource(DEFAULT_CONFIGURATION),
+ System.getProperties());
+
+ try
+ {
+ parser.parse(configuration);
+
+ // Fill out the library class path.
+ configuration.libraryJars = classPath(classPath);
+
+ // Fill out the program class path (input and output).
+ configuration.programJars = new ClassPath();
+ configuration.programJars.add(new ClassPathEntry(new File(jarFileName), false));
+ configuration.programJars.add(new ClassPathEntry(obfuscatedJarFile, true));
+
+ // The preverify tool seems to unpack the resulting classes,
+ // so we must not use mixed-case class names on Windows.
+ configuration.useMixedCaseClassNames =
+ !System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7);
+
+ // Run ProGuard with these options.
+ ProGuard proGuard = new ProGuard(configuration);
+ proGuard.execute();
+
+ }
+ catch (ParseException ex)
+ {
+ throw new IOException(ex.getMessage());
+ }
+ finally
+ {
+ parser.close();
+ }
+ }
+
+
+ /**
+ * Converts the given class path String into a ClassPath object.
+ */
+ private ClassPath classPath(String classPathString)
+ {
+ ClassPath classPath = new ClassPath();
+
+ String separator = System.getProperty("path.separator");
+
+ int index = 0;
+ while (index < classPathString.length())
+ {
+ // Find the next separator, or the end of the String.
+ int next_index = classPathString.indexOf(separator, index);
+ if (next_index < 0)
+ {
+ next_index = classPathString.length();
+ }
+
+ // Create and add the found class path entry.
+ ClassPathEntry classPathEntry =
+ new ClassPathEntry(new File(classPathString.substring(index, next_index)),
+ false);
+
+ classPath.add(classPathEntry);
+
+ // Continue after the separator.
+ index = next_index + 1;
+ }
+
+ return classPath;
+ }
+}
diff --git a/src/proguard/wtk/default.pro b/src/proguard/wtk/default.pro
new file mode 100644
index 000000000..d31714f0d
--- /dev/null
+++ b/src/proguard/wtk/default.pro
@@ -0,0 +1,114 @@
+-dontnote
+-microedition
+-mergeinterfacesaggressively
+-overloadaggressively
+-repackageclasses ''
+-allowaccessmodification
+
+# Keep all extensions of javax.microedition.midlet.MIDlet.
+-keep public class * extends javax.microedition.midlet.MIDlet
+
+# Keep all native class/method names.
+-keepclasseswithmembernames class * {
+ native