Indify.java revision 4250
0N/A/*
0N/A * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
0N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
0N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
0N/A * or visit www.oracle.com if you need additional information or have any
0N/A * questions.
0N/A */
0N/A
0N/Apackage indify;
0N/A
0N/Aimport java.util.*;
0N/Aimport java.io.*;
0N/Aimport java.lang.reflect.Modifier;
0N/Aimport java.util.regex.*;
0N/A
0N/A/**
0N/A * Transform one or more class files to incorporate JSR 292 features,
0N/A * such as {@code invokedynamic}.
0N/A * <p>
0N/A * This is a standalone program in a single source file.
0N/A * In this form, it may be useful for test harnesses, small experiments, and javadoc examples.
0N/A * Copies of this file may show up in multiple locations for standalone usage.
0N/A * The primary maintained location of this file is as follows:
0N/A * <a href="http://kenai.com/projects/ninja/sources/indify-repo/content/src/indify/Indify.java">
0N/A * http://kenai.com/projects/ninja/sources/indify-repo/content/src/indify/Indify.java</a>
0N/A * <p>
0N/A * Static private methods named MH_x and MT_x (where x is arbitrary)
0N/A * must be stereotyped generators of MethodHandle and MethodType
0N/A * constants. All calls to them are transformed to {@code CONSTANT_MethodHandle}
0N/A * and {@code CONSTANT_MethodType} "ldc" instructions.
0N/A * The stereotyped code must create method types by calls to {@code methodType} or
0N/A * {@code fromMethodDescriptorString}. The "lookup" argument must be created
0N/A * by calls to {@code java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
0N/A * The class and string arguments must be constant.
0N/A * The following methods of {@code java.lang.invoke.MethodHandle.Lookup Lookup} are
0N/A * allowed for method handle creation: {@code findStatic}, {@code findVirtual},
0N/A * {@code findConstructor}, {@code findSpecial},
0N/A * {@code findGetter}, {@code findSetter},
0N/A * {@code findStaticGetter}, or {@code findStaticSetter}.
0N/A * The call to one of these methods must be followed immediately
0N/A * by an {@code areturn} instruction.
0N/A * The net result of the call to the MH_x or MT_x method must be
0N/A * the creation of a constant method handle. Thus, replacing calls
0N/A * to MH_x or MT_x methods by {@code ldc} instructions should leave
0N/A * the meaning of the program unchanged.
0N/A * <p>
0N/A * Static private methods named INDY_x must be stereotyped generators
0N/A * of {@code invokedynamic} call sites.
0N/A * All calls to them must be immediately followed by
0N/A * {@code invokeExact} calls.
0N/A * All such pairs of calls are transformed to {@code invokedynamic}
0N/A * instructions. Each INDY_x method must begin with a call to a
0N/A * MH_x method, which is taken to be its bootstrap method.
0N/A * The method must be immediately invoked (via {@code invokeGeneric}
0N/A * on constant lookup, name, and type arguments. An object array of
0N/A * constants may also be appended to the {@code invokeGeneric call}.
0N/A * This call must be cast to {@code CallSite}, and the result must be
0N/A * immediately followed by a call to {@code dynamicInvoker}, with the
0N/A * resulting method handle returned.
0N/A * <p>
0N/A * The net result of all of these actions is equivalent to the JVM's
0N/A * execution of an {@code invokedynamic} instruction in the unlinked state.
0N/A * Running this code once should produce the same results as running
0N/A * the corresponding {@code invokedynamic} instruction.
0N/A * In order to model the caching behavior, the code of an INDY_x
0N/A * method is allowed to begin with getstatic, aaload, and if_acmpne
0N/A * instructions which load a static method handle value and return it
0N/A * if the value is non-null.
0N/A * <p>
0N/A * Example usage:
0N/A * <blockquote><pre>
0N/A$ JAVA_HOME=(some recent OpenJDK 7 build)
0N/A$ ant
0N/A$ $JAVA_HOME/bin/java -cp build/classes indify.Indify --overwrite --dest build/testout build/classes/indify/Example.class
0N/A$ $JAVA_HOME/bin/java -cp build/classes indify.Example
0N/AMT = (java.lang.Object)java.lang.Object
0N/AMH = adder(int,int)java.lang.Integer
0N/Aadder(1,2) = 3
0N/Acalling indy: 42
0N/A$ $JAVA_HOME/bin/java -cp build/testout indify.Example
0N/A(same output as above)
0N/A * </pre></blockquote>
0N/A * <p>
0N/A * A version of this transformation built on top of <a href="http://asm.ow2.org/">http://asm.ow2.org/</a> would be welcome.
0N/A * @author John Rose
0N/A */
0N/Apublic class Indify {
0N/A public static void main(String... av) throws IOException {
0N/A new Indify().run(av);
0N/A }
0N/A
0N/A public File dest;
0N/A public String[] classpath = {"."};
0N/A public boolean keepgoing = false;
0N/A public boolean expandProperties = false;
0N/A public boolean overwrite = false;
0N/A public boolean quiet = false;
0N/A public boolean verbose = false;
0N/A public boolean all = false;
0N/A public int verifySpecifierCount = -1;
0N/A
0N/A public void run(String... av) throws IOException {
0N/A List<String> avl = new ArrayList<>(Arrays.asList(av));
0N/A parseOptions(avl);
0N/A if (avl.isEmpty())
0N/A throw new IllegalArgumentException("Usage: indify [--dest dir] [option...] file...");
0N/A if ("--java".equals(avl.get(0))) {
0N/A avl.remove(0);
0N/A try {
0N/A runApplication(avl.toArray(new String[0]));
0N/A } catch (Exception ex) {
0N/A if (ex instanceof RuntimeException) throw (RuntimeException) ex;
0N/A throw new RuntimeException(ex);
0N/A }
0N/A return;
0N/A }
0N/A Exception err = null;
0N/A for (String a : avl) {
0N/A try {
0N/A indify(a);
0N/A } catch (Exception ex) {
0N/A if (err == null) err = ex;
0N/A System.err.println("failure on "+a);
0N/A if (!keepgoing) break;
0N/A }
0N/A }
0N/A if (err != null) {
0N/A if (err instanceof IOException) throw (IOException) err;
0N/A throw (RuntimeException) err;
0N/A }
0N/A }
0N/A
0N/A /** Execute the given application under a class loader which indifies all application classes. */
0N/A public void runApplication(String... av) throws Exception {
0N/A List<String> avl = new ArrayList<>(Arrays.asList(av));
0N/A String mainClassName = avl.remove(0);
0N/A av = avl.toArray(new String[0]);
0N/A Class<?> mainClass = Class.forName(mainClassName, true, makeClassLoader());
0N/A java.lang.reflect.Method main = mainClass.getMethod("main", String[].class);
0N/A try { main.setAccessible(true); } catch (SecurityException ex) { }
0N/A main.invoke(null, (Object) av);
0N/A }
0N/A
0N/A public void parseOptions(List<String> av) throws IOException {
0N/A for (; !av.isEmpty(); av.remove(0)) {
0N/A String a = av.get(0);
0N/A if (a.startsWith("-")) {
0N/A String a2 = null;
0N/A int eq = a.indexOf('=');
0N/A if (eq > 0) {
0N/A a2 = maybeExpandProperties(a.substring(eq+1));
0N/A a = a.substring(0, eq+1);
0N/A }
0N/A switch (a) {
0N/A case "--java":
0N/A return; // keep this argument
0N/A case "-d": case "--dest": case "-d=": case "--dest=":
0N/A dest = new File(a2 != null ? a2 : maybeExpandProperties(av.remove(1)));
0N/A break;
0N/A case "-cp": case "--classpath":
0N/A classpath = maybeExpandProperties(av.remove(1)).split("["+File.pathSeparatorChar+"]");
0N/A break;
0N/A case "-k": case "--keepgoing": case "--keepgoing=":
0N/A keepgoing = booleanOption(a2); // print errors but keep going
0N/A break;
0N/A case "--expand-properties": case "--expand-properties=":
0N/A expandProperties = booleanOption(a2); // expand property references in subsequent arguments
0N/A break;
0N/A case "--verify-specifier-count": case "--verify-specifier-count=":
0N/A verifySpecifierCount = Integer.valueOf(a2);
0N/A break;
0N/A case "--overwrite": case "--overwrite=":
0N/A overwrite = booleanOption(a2); // overwrite output files
0N/A break;
0N/A case "--all": case "--all=":
0N/A all = booleanOption(a2); // copy all classes, even if no patterns
0N/A break;
0N/A case "-q": case "--quiet": case "--quiet=":
0N/A quiet = booleanOption(a2); // less output
0N/A break;
0N/A case "-v": case "--verbose": case "--verbose=":
0N/A verbose = booleanOption(a2); // more output
0N/A break;
0N/A default:
0N/A throw new IllegalArgumentException("unrecognized flag: "+a);
0N/A }
0N/A continue;
0N/A } else {
0N/A break;
0N/A }
0N/A }
0N/A if (dest == null && !overwrite)
0N/A throw new RuntimeException("no output specified; need --dest d or --overwrite");
0N/A if (expandProperties) {
0N/A for (int i = 0; i < av.size(); i++)
0N/A av.set(i, maybeExpandProperties(av.get(i)));
0N/A }
0N/A }
0N/A
0N/A private boolean booleanOption(String s) {
0N/A if (s == null) return true;
0N/A switch (s) {
0N/A case "true": case "yes": case "on": case "1": return true;
0N/A case "false": case "no": case "off": case "0": return false;
0N/A }
0N/A throw new IllegalArgumentException("unrecognized boolean flag="+s);
0N/A }
0N/A
0N/A private String maybeExpandProperties(String s) {
0N/A if (!expandProperties) return s;
0N/A Set<String> propsDone = new HashSet<>();
0N/A while (s.contains("${")) {
0N/A int lbrk = s.indexOf("${");
0N/A int rbrk = s.indexOf('}', lbrk);
0N/A if (rbrk < 0) break;
0N/A String prop = s.substring(lbrk+2, rbrk);
0N/A if (!propsDone.add(prop)) break;
0N/A String value = System.getProperty(prop);
0N/A if (verbose) System.err.println("expanding ${"+prop+"} => "+value);
0N/A if (value == null) break;
0N/A s = s.substring(0, lbrk) + value + s.substring(rbrk+1);
0N/A }
0N/A return s;
0N/A }
0N/A
0N/A public void indify(String a) throws IOException {
0N/A File f = new File(a);
0N/A String fn = f.getName();
0N/A if (fn.endsWith(".class") && f.isFile())
0N/A indifyFile(f, dest);
0N/A else if (fn.endsWith(".jar") && f.isFile())
0N/A indifyJar(f, dest);
0N/A else if (f.isDirectory())
0N/A indifyTree(f, dest);
0N/A else if (!keepgoing)
0N/A throw new RuntimeException("unrecognized file: "+a);
0N/A }
0N/A
0N/A private void ensureDirectory(File dir) {
0N/A if (dir.mkdirs() && !quiet)
0N/A System.err.println("created "+dir);
0N/A }
0N/A
0N/A public void indifyFile(File f, File dest) throws IOException {
0N/A if (verbose) System.err.println("reading "+f);
0N/A ClassFile cf = new ClassFile(f);
0N/A Logic logic = new Logic(cf);
0N/A boolean changed = logic.transform();
0N/A logic.reportPatternMethods(quiet, keepgoing);
0N/A if (changed || all) {
0N/A File outfile;
0N/A if (dest != null) {
0N/A ensureDirectory(dest);
0N/A outfile = classPathFile(dest, cf.nameString());
0N/A } else {
0N/A outfile = f; // overwrite input file, no matter where it is
0N/A }
0N/A cf.writeTo(outfile);
0N/A if (!quiet) System.err.println("wrote "+outfile);
0N/A }
0N/A }
0N/A
0N/A File classPathFile(File pathDir, String className) {
0N/A String qualname = className.replace('.','/')+".class";
0N/A qualname = qualname.replace('/', File.separatorChar);
0N/A return new File(pathDir, qualname);
0N/A }
0N/A
0N/A public void indifyJar(File f, Object dest) throws IOException {
0N/A throw new UnsupportedOperationException("Not yet implemented");
0N/A }
0N/A
0N/A public void indifyTree(File f, File dest) throws IOException {
0N/A if (verbose) System.err.println("reading directory: "+f);
0N/A for (File f2 : f.listFiles(new FilenameFilter() {
0N/A public boolean accept(File dir, String name) {
0N/A if (name.endsWith(".class")) return true;
0N/A if (name.contains(".")) return false;
0N/A // return true if it might be a package name:
0N/A return Character.isJavaIdentifierStart(name.charAt(0));
0N/A }})) {
0N/A if (f2.getName().endsWith(".class"))
0N/A indifyFile(f2, dest);
0N/A else if (f2.isDirectory())
0N/A indifyTree(f2, dest);
0N/A }
0N/A }
0N/A
0N/A public ClassLoader makeClassLoader() {
0N/A return new Loader();
0N/A }
0N/A private class Loader extends ClassLoader {
0N/A Loader() {
0N/A this(Indify.class.getClassLoader());
0N/A }
0N/A Loader(ClassLoader parent) {
0N/A super(parent);
0N/A }
0N/A public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
0N/A File f = findClassInPath(name);
0N/A if (f != null) {
0N/A try {
0N/A Class<?> c = transformAndLoadClass(f);
0N/A if (c != null) {
0N/A if (resolve) resolveClass(c);
0N/A return c;
0N/A }
0N/A } catch (ClassNotFoundException ex) {
0N/A // fall through
0N/A } catch (IOException ex) {
0N/A // fall through
0N/A } catch (Exception ex) {
0N/A // pass error from reportPatternMethods, etc.
0N/A if (ex instanceof RuntimeException) throw (RuntimeException) ex;
0N/A throw new RuntimeException(ex);
0N/A }
0N/A }
0N/A return super.loadClass(name, resolve);
0N/A }
0N/A private File findClassInPath(String name) {
0N/A for (String s : classpath) {
0N/A File f = classPathFile(new File(s), name);
0N/A //System.out.println("Checking for "+f);
0N/A if (f.exists() && f.canRead()) {
0N/A return f;
0N/A }
0N/A }
0N/A return null;
0N/A }
0N/A protected Class<?> findClass(String name) throws ClassNotFoundException {
0N/A try {
0N/A File f = findClassInPath(name);
0N/A if (f != null) {
0N/A Class<?> c = transformAndLoadClass(f);
0N/A if (c != null) return c;
0N/A }
0N/A } catch (IOException ex) {
0N/A throw new ClassNotFoundException("IO error", ex);
0N/A }
0N/A throw new ClassNotFoundException();
0N/A }
0N/A private Class<?> transformAndLoadClass(File f) throws ClassNotFoundException, IOException {
0N/A if (verbose) System.err.println("Loading class from "+f);
0N/A ClassFile cf = new ClassFile(f);
0N/A Logic logic = new Logic(cf);
0N/A boolean changed = logic.transform();
0N/A if (verbose && !changed) System.err.println("(no change)");
0N/A logic.reportPatternMethods(!verbose, keepgoing);
0N/A byte[] bytes = cf.toByteArray();
0N/A return defineClass(null, bytes, 0, bytes.length);
0N/A }
0N/A }
0N/A
0N/A private class Logic {
0N/A // Indify logic, per se.
0N/A ClassFile cf;
0N/A final char[] poolMarks;
0N/A final Map<Method,Constant> constants = new HashMap<>();
0N/A final Map<Method,String> indySignatures = new HashMap<>();
0N/A Logic(ClassFile cf) {
0N/A this.cf = cf;
0N/A poolMarks = new char[cf.pool.size()];
0N/A }
0N/A boolean transform() {
0N/A if (!initializeMarks()) return false;
0N/A if (!findPatternMethods()) return false;
0N/A Pool pool = cf.pool;
0N/A //for (Constant c : cp) System.out.println(" # "+c);
0N/A for (Method m : cf.methods) {
0N/A if (constants.containsKey(m)) continue; // don't bother
0N/A // Transform references.
0N/A int blab = 0;
0N/A for (Instruction i = m.instructions(); i != null; i = i.next()) {
0N/A if (i.bc != opc_invokestatic) continue;
0N/A int methi = i.u2At(1);
0N/A if (poolMarks[methi] == 0) continue;
0N/A Short[] ref = pool.getMemberRef((short)methi);
0N/A Method conm = findMember(cf.methods, ref[1], ref[2]);
0N/A if (conm == null) continue;
0N/A Constant con = constants.get(conm);
0N/A if (con == null) continue;
0N/A if (blab++ == 0 && !quiet)
0N/A System.err.println("patching "+cf.nameString()+"."+m);
0N/A //if (blab == 1) { for (Instruction j = m.instructions(); j != null; j = j.next()) System.out.println(" |"+j); }
0N/A if (con.tag == CONSTANT_InvokeDynamic) {
0N/A // need to patch the following instruction too,
0N/A // but there are usually intervening argument pushes too
0N/A Instruction i2 = findPop(i);
0N/A Short[] ref2 = null;
0N/A short ref2i = 0;
0N/A if (i2 != null && i2.bc == opc_invokevirtual &&
0N/A poolMarks[(char)(ref2i = (short) i2.u2At(1))] == 'D')
0N/A ref2 = pool.getMemberRef(ref2i);
0N/A if (ref2 == null || !"invokeExact".equals(pool.getString(ref2[1]))) {
0N/A System.err.println(m+": failed to create invokedynamic at "+i.pc);
0N/A continue;
0N/A }
0N/A String invType = pool.getString(ref2[2]);
0N/A String bsmType = indySignatures.get(conm);
0N/A if (!invType.equals(bsmType)) {
0N/A System.err.println(m+": warning: "+conm+" call type and local invoke type differ: "
0N/A +bsmType+", "+invType);
0N/A }
0N/A assert(i.len == 3 || i2.len == 3);
0N/A if (!quiet) System.err.println(i+" "+conm+";...; "+i2+" => invokedynamic "+con);
0N/A int start = i.pc + 3, end = i2.pc;
0N/A System.arraycopy(i.codeBase, start, i.codeBase, i.pc, end-start);
0N/A i.forceNext(0); // force revisit of new instruction
0N/A i2.u1AtPut(-3, opc_invokedynamic);
0N/A i2.u2AtPut(-2, con.index);
0N/A i2.u2AtPut(0, (short)0);
0N/A i2.u1AtPut(2, opc_nop);
0N/A //System.out.println(new Instruction(i.codeBase, i2.pc-3));
0N/A } else {
0N/A if (!quiet) System.err.println(i+" "+conm+" => ldc "+con);
0N/A assert(i.len == 3);
0N/A i.u1AtPut(0, opc_ldc_w);
0N/A i.u2AtPut(1, con.index);
0N/A }
0N/A }
0N/A //if (blab >= 1) { for (Instruction j = m.instructions(); j != null; j = j.next()) System.out.println(" |"+j); }
0N/A }
0N/A cf.methods.removeAll(constants.keySet());
0N/A return true;
0N/A }
0N/A
0N/A // Scan forward from the instruction to find where the stack p
0N/A // below the current sp at the instruction.
0N/A Instruction findPop(Instruction i) {
0N/A //System.out.println("findPop from "+i);
0N/A Pool pool = cf.pool;
0N/A JVMState jvm = new JVMState();
0N/A decode:
0N/A for (i = i.clone().next(); i != null; i = i.next()) {
0N/A String pops = INSTRUCTION_POPS[i.bc];
0N/A //System.out.println(" "+i+" "+jvm.stack+" : "+pops.replace("$", " => "));
0N/A if (pops == null) break;
0N/A if (jvm.stackMotion(i.bc)) continue decode;
0N/A if (pops.indexOf('Q') >= 0) {
0N/A Short[] ref = pool.getMemberRef((short) i.u2At(1));
0N/A String type = simplifyType(pool.getString(CONSTANT_Utf8, ref[2]));
0N/A switch (i.bc) {
0N/A case opc_getstatic:
0N/A case opc_getfield:
0N/A case opc_putstatic:
0N/A case opc_putfield:
0N/A pops = pops.replace("Q", type);
0N/A break;
0N/A default:
0N/A if (!type.startsWith("("))
0N/A throw new InternalError(i.toString());
0N/A pops = pops.replace("Q$Q", type.substring(1).replace(")","$"));
0N/A break;
0N/A }
0N/A //System.out.println("special type: "+type+" => "+pops);
0N/A }
0N/A int npops = pops.indexOf('$');
0N/A if (npops < 0) throw new InternalError();
0N/A if (npops > jvm.sp()) return i;
0N/A List<Object> args = jvm.args(npops);
0N/A int k = 0;
0N/A for (Object x : args) {
0N/A char have = (Character) x;
0N/A char want = pops.charAt(k++);
0N/A if (have == 'X' || want == 'X') continue;
0N/A if (have != want) break decode;
0N/A }
0N/A if (pops.charAt(k++) != '$') break decode;
0N/A args.clear();
0N/A while (k < pops.length())
0N/A args.add(pops.charAt(k++));
0N/A }
0N/A System.err.println("*** bailout on jvm: "+jvm.stack+" "+i);
0N/A return null;
0N/A }
0N/A
0N/A boolean findPatternMethods() {
0N/A boolean found = false;
0N/A for (char mark : "THI".toCharArray()) {
0N/A for (Method m : cf.methods) {
0N/A if (!Modifier.isPrivate(m.access)) continue;
0N/A if (!Modifier.isStatic(m.access)) continue;
0N/A if (nameAndTypeMark(m.name, m.type) == mark) {
0N/A Constant con = scanPattern(m, mark);
0N/A if (con == null) continue;
0N/A constants.put(m, con);
0N/A found = true;
0N/A }
0N/A }
0N/A }
0N/A return found;
0N/A }
0N/A
0N/A void reportPatternMethods(boolean quietly, boolean allowMatchFailure) {
0N/A if (!quietly && !constants.keySet().isEmpty())
0N/A System.err.println("pattern methods removed: "+constants.keySet());
0N/A for (Method m : cf.methods) {
0N/A if (nameMark(cf.pool.getString(m.name)) != 0 &&
0N/A constants.get(m) == null) {
0N/A String failure = "method has special name but fails to match pattern: "+m;
0N/A if (!allowMatchFailure)
0N/A throw new IllegalArgumentException(failure);
0N/A else if (!quietly)
0N/A System.err.println("warning: "+failure);
0N/A }
0N/A }
0N/A if (verifySpecifierCount >= 0) {
0N/A List<Object[]> specs = bootstrapMethodSpecifiers(false);
0N/A int specsLen = (specs == null ? 0 : specs.size());
0N/A // Pass by specsLen == 0, to help with associated (inner) classes.
0N/A if (specsLen == 0) specsLen = verifySpecifierCount;
0N/A if (specsLen != verifySpecifierCount) {
0N/A throw new IllegalArgumentException("BootstrapMethods length is "+specsLen+" but should be "+verifySpecifierCount);
0N/A }
0N/A }
0N/A if (!quiet) System.err.flush();
0N/A }
0N/A
0N/A // mark constant pool entries according to participation in patterns
0N/A boolean initializeMarks() {
0N/A boolean changed = false;
0N/A for (;;) {
0N/A boolean changed1 = false;
0N/A int cpindex = -1;
0N/A for (Constant e : cf.pool) {
0N/A ++cpindex;
0N/A if (e == null) continue;
0N/A char mark = poolMarks[cpindex];
0N/A if (mark != 0) continue;
0N/A switch (e.tag) {
0N/A case CONSTANT_Utf8:
0N/A mark = nameMark(e.itemString()); break;
0N/A case CONSTANT_NameAndType:
0N/A mark = nameAndTypeMark(e.itemIndexes()); break;
0N/A case CONSTANT_Class: {
0N/A int n1 = e.itemIndex();
0N/A char nmark = poolMarks[(char)n1];
0N/A if ("DJ".indexOf(nmark) >= 0)
0N/A mark = nmark;
0N/A break;
0N/A }
0N/A case CONSTANT_Field:
0N/A case CONSTANT_Method: {
0N/A Short[] n12 = e.itemIndexes();
0N/A short cl = n12[0];
0N/A short nt = n12[1];
0N/A char cmark = poolMarks[(char)cl];
0N/A if (cmark != 0) {
0N/A mark = cmark; // it is a java.lang.invoke.* or java.lang.* method
0N/A break;
0N/A }
0N/A String cls = cf.pool.getString(CONSTANT_Class, cl);
0N/A if (cls.equals(cf.nameString())) {
0N/A switch (poolMarks[(char)nt]) {
0N/A // it is a private MH/MT/INDY method
0N/A case 'T': case 'H': case 'I':
0N/A mark = poolMarks[(char)nt];
0N/A break;
0N/A }
0N/A }
0N/A break;
0N/A }
0N/A default: break;
0N/A }
0N/A if (mark != 0) {
0N/A poolMarks[cpindex] = mark;
0N/A changed1 = true;
0N/A }
0N/A }
0N/A if (!changed1)
0N/A break;
0N/A changed = true;
0N/A }
0N/A return changed;
0N/A }
0N/A char nameMark(String s) {
0N/A if (s.startsWith("MT_")) return 'T';
0N/A else if (s.startsWith("MH_")) return 'H';
0N/A else if (s.startsWith("INDY_")) return 'I';
0N/A else if (s.startsWith("java/lang/invoke/")) return 'D';
0N/A else if (s.startsWith("java/lang/")) return 'J';
0N/A return 0;
0N/A }
0N/A char nameAndTypeMark(Short[] n12) {
0N/A return nameAndTypeMark(n12[0], n12[1]);
0N/A }
0N/A char nameAndTypeMark(short n1, short n2) {
0N/A char mark = poolMarks[(char)n1];
0N/A if (mark == 0) return 0;
0N/A String descr = cf.pool.getString(CONSTANT_Utf8, n2);
0N/A String requiredType;
0N/A switch (poolMarks[(char)n1]) {
0N/A case 'H': requiredType = "()Ljava/lang/invoke/MethodHandle;"; break;
0N/A case 'T': requiredType = "()Ljava/lang/invoke/MethodType;"; break;
0N/A case 'I': requiredType = "()Ljava/lang/invoke/MethodHandle;"; break;
0N/A default: return 0;
0N/A }
0N/A if (matchType(descr, requiredType)) return mark;
0N/A return 0;
0N/A }
0N/A
0N/A boolean matchType(String descr, String requiredType) {
0N/A if (descr.equals(requiredType)) return true;
0N/A return false;
0N/A }
0N/A
0N/A private class JVMState {
0N/A final List<Object> stack = new ArrayList<>();
0N/A int sp() { return stack.size(); }
0N/A void push(Object x) { stack.add(x); }
0N/A void push2(Object x) { stack.add(EMPTY_SLOT); stack.add(x); }
0N/A void pushAt(int pos, Object x) { stack.add(stack.size()+pos, x); }
0N/A Object pop() { return stack.remove(sp()-1); }
0N/A Object top() { return stack.get(sp()-1); }
0N/A List<Object> args(boolean hasRecv, String type) {
0N/A return args(argsize(type) + (hasRecv ? 1 : 0));
0N/A }
0N/A List<Object> args(int argsize) {
0N/A return stack.subList(sp()-argsize, sp());
0N/A }
0N/A boolean stackMotion(int bc) {
0N/A switch (bc) {
0N/A case opc_pop: pop(); break;
0N/A case opc_pop2: pop(); pop(); break;
0N/A case opc_swap: pushAt(-1, pop()); break;
0N/A case opc_dup: push(top()); break;
0N/A case opc_dup_x1: pushAt(-2, top()); break;
0N/A case opc_dup_x2: pushAt(-3, top()); break;
0N/A // ? also: dup2{,_x1,_x2}
0N/A default: return false;
0N/A }
0N/A return true;
0N/A }
0N/A }
0N/A private final String EMPTY_SLOT = "_";
0N/A private void removeEmptyJVMSlots(List<Object> args) {
0N/A for (;;) {
0N/A int i = args.indexOf(EMPTY_SLOT);
0N/A if (i >= 0 && i+1 < args.size()
0N/A && (isConstant(args.get(i+1), CONSTANT_Long) ||
0N/A isConstant(args.get(i+1), CONSTANT_Double)))
0N/A args.remove(i);
0N/A else break;
0N/A }
0N/A }
0N/A
0N/A private Constant scanPattern(Method m, char patternMark) {
0N/A if (verbose) System.err.println("scan "+m+" for pattern="+patternMark);
0N/A int wantTag;
0N/A switch (patternMark) {
0N/A case 'T': wantTag = CONSTANT_MethodType; break;
0N/A case 'H': wantTag = CONSTANT_MethodHandle; break;
0N/A case 'I': wantTag = CONSTANT_InvokeDynamic; break;
0N/A default: throw new InternalError();
0N/A }
0N/A Instruction i = m.instructions();
0N/A JVMState jvm = new JVMState();
0N/A Pool pool = cf.pool;
0N/A int branchCount = 0;
0N/A Object arg;
0N/A List<Object> args;
0N/A List<Object> bsmArgs = null; // args to invokeGeneric
0N/A decode:
0N/A for (; i != null; i = i.next()) {
0N/A //System.out.println(jvm.stack+" "+i);
0N/A int bc = i.bc;
0N/A switch (bc) {
0N/A case opc_ldc: jvm.push(pool.get(i.u1At(1))); break;
0N/A case opc_ldc_w: jvm.push(pool.get(i.u2At(1))); break;
0N/A case opc_ldc2_w: jvm.push2(pool.get(i.u2At(1))); break;
0N/A case opc_aconst_null: jvm.push(null); break;
0N/A case opc_bipush: jvm.push((int)(byte) i.u1At(1)); break;
0N/A case opc_sipush: jvm.push((int)(short)i.u2At(1)); break;
0N/A
0N/A // these support creation of a restarg array
0N/A case opc_anewarray:
0N/A arg = jvm.pop();
0N/A if (!(arg instanceof Integer)) break decode;
0N/A arg = Arrays.asList(new Object[(Integer)arg]);
0N/A jvm.push(arg);
0N/A break;
0N/A case opc_dup:
0N/A jvm.push(jvm.top()); break;
0N/A case opc_aastore:
0N/A args = jvm.args(3); // array, index, value
0N/A if (args.get(0) instanceof List &&
0N/A args.get(1) instanceof Integer) {
0N/A ((List<Object>)args.get(0)).set( (Integer)args.get(1), args.get(2) );
0N/A }
0N/A args.clear();
0N/A break;
0N/A
0N/A case opc_new:
0N/A {
0N/A String type = pool.getString(CONSTANT_Class, (short)i.u2At(1));
0N/A //System.out.println("new "+type);
0N/A switch (type) {
0N/A case "java/lang/StringBuilder":
0N/A jvm.push("StringBuilder");
0N/A continue decode; // go to next instruction
0N/A }
0N/A break decode; // bail out
0N/A }
0N/A
0N/A case opc_getstatic:
0N/A {
0N/A // int.class compiles to getstatic Integer.TYPE
0N/A int fieldi = i.u2At(1);
0N/A char mark = poolMarks[fieldi];
0N/A //System.err.println("getstatic "+fieldi+Arrays.asList(pool.getStrings(pool.getMemberRef((short)fieldi)))+mark);
0N/A if (mark == 'J') {
0N/A Short[] ref = pool.getMemberRef((short) fieldi);
0N/A String name = pool.getString(CONSTANT_Utf8, ref[1]);
0N/A if ("TYPE".equals(name)) {
0N/A String wrapperName = pool.getString(CONSTANT_Class, ref[0]).replace('/', '.');
0N/A // a primitive type descriptor
0N/A Class<?> primClass;
0N/A try {
0N/A primClass = (Class<?>) Class.forName(wrapperName).getField(name).get(null);
0N/A } catch (Exception ex) {
0N/A throw new InternalError("cannot load "+wrapperName+"."+name);
0N/A }
0N/A jvm.push(primClass);
0N/A break;
0N/A }
0N/A }
0N/A // unknown field; keep going...
0N/A jvm.push(UNKNOWN_CON);
0N/A break;
0N/A }
0N/A case opc_putstatic:
0N/A {
0N/A if (patternMark != 'I') break decode;
0N/A jvm.pop();
0N/A // unknown field; keep going...
0N/A break;
0N/A }
0N/A
0N/A case opc_invokestatic:
0N/A case opc_invokevirtual:
0N/A case opc_invokespecial:
0N/A {
0N/A boolean hasRecv = (bc != opc_invokestatic);
0N/A int methi = i.u2At(1);
0N/A char mark = poolMarks[methi];
0N/A Short[] ref = pool.getMemberRef((short)methi);
0N/A String type = pool.getString(CONSTANT_Utf8, ref[2]);
0N/A //System.out.println("invoke "+pool.getString(CONSTANT_Utf8, ref[1])+" "+Arrays.asList(ref)+" : "+type);
0N/A args = jvm.args(hasRecv, type);
0N/A String intrinsic = null;
0N/A Constant con;
0N/A if (mark == 'D' || mark == 'J') {
0N/A intrinsic = pool.getString(CONSTANT_Utf8, ref[1]);
0N/A if (mark == 'J') {
0N/A String cls = pool.getString(CONSTANT_Class, ref[0]);
0N/A cls = cls.substring(1+cls.lastIndexOf('/'));
0N/A intrinsic = cls+"."+intrinsic;
0N/A }
0N/A //System.out.println("recognized intrinsic "+intrinsic);
0N/A byte refKind = -1;
0N/A switch (intrinsic) {
0N/A case "findGetter": refKind = REF_getField; break;
0N/A case "findStaticGetter": refKind = REF_getStatic; break;
0N/A case "findSetter": refKind = REF_putField; break;
0N/A case "findStaticSetter": refKind = REF_putStatic; break;
0N/A case "findVirtual": refKind = REF_invokeVirtual; break;
0N/A case "findStatic": refKind = REF_invokeStatic; break;
0N/A case "findSpecial": refKind = REF_invokeSpecial; break;
0N/A case "findConstructor": refKind = REF_newInvokeSpecial; break;
0N/A }
0N/A if (refKind >= 0 && (con = parseMemberLookup(refKind, args)) != null) {
0N/A args.clear(); args.add(con);
0N/A continue;
0N/A }
0N/A }
0N/A Method ownMethod = null;
0N/A if (mark == 'T' || mark == 'H' || mark == 'I') {
0N/A ownMethod = findMember(cf.methods, ref[1], ref[2]);
0N/A }
0N/A //if (intrinsic != null) System.out.println("intrinsic = "+intrinsic);
0N/A switch (intrinsic == null ? "" : intrinsic) {
0N/A case "fromMethodDescriptorString":
0N/A con = makeMethodTypeCon(args.get(0));
0N/A args.clear(); args.add(con);
0N/A continue;
0N/A case "methodType": {
0N/A flattenVarargs(args); // there are several overloadings, some with varargs
0N/A StringBuilder buf = new StringBuilder();
0N/A String rtype = null;
0N/A for (Object typeArg : args) {
0N/A if (typeArg instanceof Class) {
0N/A Class<?> argClass = (Class<?>) typeArg;
0N/A if (argClass.isPrimitive()) {
0N/A char tchar;
0N/A switch (argClass.getName()) {
0N/A case "void": tchar = 'V'; break;
0N/A case "boolean": tchar = 'Z'; break;
0N/A case "byte": tchar = 'B'; break;
0N/A case "char": tchar = 'C'; break;
0N/A case "short": tchar = 'S'; break;
0N/A case "int": tchar = 'I'; break;
0N/A case "long": tchar = 'J'; break;
0N/A case "float": tchar = 'F'; break;
0N/A case "double": tchar = 'D'; break;
0N/A default: throw new InternalError(argClass.toString());
0N/A }
0N/A buf.append(tchar);
0N/A } else {
0N/A // should not happen, but...
0N/A buf.append('L').append(argClass.getName().replace('.','/')).append(';');
0N/A }
0N/A } else if (typeArg instanceof Constant) {
0N/A Constant argCon = (Constant) typeArg;
0N/A if (argCon.tag == CONSTANT_Class) {
0N/A String cn = pool.get(argCon.itemIndex()).itemString();
0N/A if (cn.endsWith(";"))
0N/A buf.append(cn);
0N/A else
0N/A buf.append('L').append(cn).append(';');
0N/A } else {
0N/A break decode;
0N/A }
0N/A } else {
0N/A break decode;
0N/A }
0N/A if (rtype == null) {
0N/A // first arg is treated differently
0N/A rtype = buf.toString();
0N/A buf.setLength(0);
0N/A buf.append('(');
0N/A }
0N/A }
0N/A buf.append(')').append(rtype);
0N/A con = con = makeMethodTypeCon(buf.toString());
0N/A args.clear(); args.add(con);
0N/A continue;
0N/A }
0N/A case "lookup":
0N/A case "dynamicInvoker":
0N/A args.clear(); args.add(intrinsic);
0N/A continue;
0N/A case "lookupClass":
0N/A if (args.equals(Arrays.asList("lookup"))) {
0N/A // fold lookup().lookupClass() to the enclosing class
0N/A args.clear(); args.add(pool.get(cf.thisc));
0N/A continue;
0N/A }
0N/A break;
0N/A case "invoke":
0N/A case "invokeGeneric":
0N/A case "invokeWithArguments":
0N/A if (patternMark != 'I') break decode;
0N/A if ("invokeWithArguments".equals(intrinsic))
0N/A flattenVarargs(args);
0N/A bsmArgs = new ArrayList(args);
0N/A args.clear(); args.add("invokeGeneric");
0N/A continue;
0N/A case "Integer.valueOf":
0N/A case "Float.valueOf":
0N/A case "Long.valueOf":
0N/A case "Double.valueOf":
0N/A removeEmptyJVMSlots(args);
0N/A if (args.size() == 1) {
0N/A arg = args.remove(0);
0N/A assert(3456 == (CONSTANT_Integer*1000 + CONSTANT_Float*100 + CONSTANT_Long*10 + CONSTANT_Double));
0N/A if (isConstant(arg, CONSTANT_Integer + "IFLD".indexOf(intrinsic.charAt(0)))
0N/A || arg instanceof Number) {
0N/A args.add(arg); continue;
0N/A }
0N/A }
0N/A break decode;
0N/A case "StringBuilder.append":
0N/A // allow calls like ("value = "+x)
0N/A removeEmptyJVMSlots(args);
0N/A args.subList(1, args.size()).clear();
0N/A continue;
0N/A case "StringBuilder.toString":
0N/A args.clear();
0N/A args.add(intrinsic);
0N/A continue;
0N/A }
0N/A if (!hasRecv && ownMethod != null && patternMark != 0) {
0N/A con = constants.get(ownMethod);
0N/A if (con == null) break decode;
0N/A args.clear(); args.add(con);
0N/A continue;
0N/A } else if (type.endsWith(")V")) {
0N/A // allow calls like println("reached the pattern method")
0N/A args.clear();
0N/A continue;
0N/A }
0N/A break decode; // bail out for most calls
0N/A }
0N/A case opc_areturn:
0N/A {
0N/A ++branchCount;
0N/A if (bsmArgs != null) {
0N/A // parse bsmArgs as (MH, lookup, String, MT, [extra])
0N/A Constant indyCon = makeInvokeDynamicCon(bsmArgs);
0N/A if (indyCon != null) {
0N/A Constant typeCon = (Constant) bsmArgs.get(3);
0N/A indySignatures.put(m, pool.getString(typeCon.itemIndex()));
0N/A return indyCon;
0N/A }
0N/A System.err.println(m+": inscrutable bsm arguments: "+bsmArgs);
0N/A break decode; // bail out
0N/A }
0N/A arg = jvm.pop();
0N/A if (branchCount == 2 && UNKNOWN_CON.equals(arg))
0N/A break; // merge to next path
0N/A if (isConstant(arg, wantTag))
0N/A return (Constant) arg;
0N/A break decode; // bail out
0N/A }
0N/A default:
0N/A if (jvm.stackMotion(i.bc)) break;
0N/A if (bc >= opc_nconst_MIN && bc <= opc_nconst_MAX)
0N/A { jvm.push(INSTRUCTION_CONSTANTS[bc - opc_nconst_MIN]); break; }
0N/A if (patternMark == 'I') {
0N/A // these support caching paths in INDY_x methods
0N/A if (bc == opc_aload || bc >= opc_aload_0 && bc <= opc_aload_MAX)
0N/A { jvm.push(UNKNOWN_CON); break; }
0N/A if (bc == opc_astore || bc >= opc_astore_0 && bc <= opc_astore_MAX)
0N/A { jvm.pop(); break; }
0N/A switch (bc) {
0N/A case opc_getfield:
0N/A case opc_aaload:
0N/A jvm.push(UNKNOWN_CON); break;
0N/A case opc_ifnull:
0N/A case opc_ifnonnull:
0N/A // ignore branch target
0N/A if (++branchCount != 1) break decode;
0N/A jvm.pop();
0N/A break;
0N/A case opc_checkcast:
0N/A arg = jvm.top();
0N/A if ("invokeWithArguments".equals(arg) ||
0N/A "invokeGeneric".equals(arg))
0N/A break; // assume it is a helpful cast
0N/A break decode;
0N/A default:
0N/A break decode; // bail out
0N/A }
0N/A continue decode; // go to next instruction
0N/A }
0N/A break decode; // bail out
0N/A } //end switch
0N/A }
0N/A System.err.println(m+": bailout on "+i+" jvm stack: "+jvm.stack);
0N/A return null;
0N/A }
0N/A private final String UNKNOWN_CON = "<unknown>";
0N/A
0N/A private void flattenVarargs(List<Object> args) {
0N/A int size = args.size();
0N/A if (size > 0 && args.get(size-1) instanceof List)
0N/A args.addAll((List<Object>) args.remove(size-1));
0N/A }
0N/A
0N/A private boolean isConstant(Object x, int tag) {
0N/A return x instanceof Constant && ((Constant)x).tag == tag;
0N/A }
0N/A private Constant makeMethodTypeCon(Object x) {
0N/A short utfIndex;
0N/A if (x instanceof String)
0N/A utfIndex = (short) cf.pool.addConstant(CONSTANT_Utf8, x).index;
0N/A else if (isConstant(x, CONSTANT_String))
0N/A utfIndex = ((Constant)x).itemIndex();
0N/A else return null;
0N/A return cf.pool.addConstant(CONSTANT_MethodType, utfIndex);
0N/A }
0N/A private Constant parseMemberLookup(byte refKind, List<Object> args) {
0N/A // E.g.: lookup().findStatic(Foo.class, "name", MethodType)
0N/A if (args.size() != 4) return null;
0N/A int argi = 0;
0N/A if (!"lookup".equals(args.get(argi++))) return null;
0N/A short refindex, cindex, ntindex, nindex, tindex;
0N/A Object con;
0N/A if (!isConstant(con = args.get(argi++), CONSTANT_Class)) return null;
0N/A cindex = (short)((Constant)con).index;
0N/A if (!isConstant(con = args.get(argi++), CONSTANT_String)) return null;
0N/A nindex = ((Constant)con).itemIndex();
0N/A if (isConstant(con = args.get(argi++), CONSTANT_MethodType) ||
0N/A isConstant(con, CONSTANT_Class)) {
0N/A tindex = ((Constant)con).itemIndex();
0N/A } else return null;
0N/A ntindex = (short) cf.pool.addConstant(CONSTANT_NameAndType,
0N/A new Short[]{ nindex, tindex }).index;
0N/A byte reftag = CONSTANT_Method;
0N/A if (refKind <= REF_putStatic)
0N/A reftag = CONSTANT_Field;
0N/A else if (refKind == REF_invokeInterface)
0N/A reftag = CONSTANT_InterfaceMethod;
0N/A Constant ref = cf.pool.addConstant(reftag, new Short[]{ cindex, ntindex });
0N/A return cf.pool.addConstant(CONSTANT_MethodHandle, new Object[]{ refKind, (short)ref.index });
0N/A }
0N/A private Constant makeInvokeDynamicCon(List<Object> args) {
0N/A // E.g.: MH_bsm.invokeGeneric(lookup(), "name", MethodType, "extraArg")
0N/A removeEmptyJVMSlots(args);
0N/A if (args.size() < 4) return null;
0N/A int argi = 0;
0N/A short nindex, tindex, ntindex, bsmindex;
0N/A Object con;
0N/A if (!isConstant(con = args.get(argi++), CONSTANT_MethodHandle)) return null;
bsmindex = (short) ((Constant)con).index;
if (!"lookup".equals(args.get(argi++))) return null;
if (!isConstant(con = args.get(argi++), CONSTANT_String)) return null;
nindex = ((Constant)con).itemIndex();
if (!isConstant(con = args.get(argi++), CONSTANT_MethodType)) return null;
tindex = ((Constant)con).itemIndex();
ntindex = (short) cf.pool.addConstant(CONSTANT_NameAndType,
new Short[]{ nindex, tindex }).index;
List<Object> extraArgs = new ArrayList<Object>();
if (argi < args.size()) {
extraArgs.addAll(args.subList(argi, args.size() - 1));
Object lastArg = args.get(args.size() - 1);
if (lastArg instanceof List) {
List<Object> lastArgs = (List<Object>) lastArg;
removeEmptyJVMSlots(lastArgs);
extraArgs.addAll(lastArgs);
} else {
extraArgs.add(lastArg);
}
}
List<Short> extraArgIndexes = new CountedList<>(Short.class);
for (Object x : extraArgs) {
if (x instanceof Number) {
Object num = null; byte numTag = 0;
if (x instanceof Integer) { num = x; numTag = CONSTANT_Integer; }
if (x instanceof Float) { num = Float.floatToRawIntBits((Float)x); numTag = CONSTANT_Float; }
if (x instanceof Long) { num = x; numTag = CONSTANT_Long; }
if (x instanceof Double) { num = Double.doubleToRawLongBits((Double)x); numTag = CONSTANT_Double; }
if (num != null) x = cf.pool.addConstant(numTag, x);
}
if (!(x instanceof Constant)) {
System.err.println("warning: unrecognized BSM argument "+x);
return null;
}
extraArgIndexes.add((short) ((Constant)x).index);
}
List<Object[]> specs = bootstrapMethodSpecifiers(true);
int specindex = -1;
Object[] spec = new Object[]{ bsmindex, extraArgIndexes };
for (Object[] spec1 : specs) {
if (Arrays.equals(spec1, spec)) {
specindex = specs.indexOf(spec1);
if (verbose) System.err.println("reusing BSM specifier: "+spec1[0]+spec1[1]);
break;
}
}
if (specindex == -1) {
specindex = (short) specs.size();
specs.add(spec);
if (verbose) System.err.println("adding BSM specifier: "+spec[0]+spec[1]);
}
return cf.pool.addConstant(CONSTANT_InvokeDynamic,
new Short[]{ (short)specindex, ntindex });
}
List<Object[]> bootstrapMethodSpecifiers(boolean createIfNotFound) {
Attr bsms = cf.findAttr("BootstrapMethods");
if (bsms == null) {
if (!createIfNotFound) return null;
bsms = new Attr(cf, "BootstrapMethods", new byte[]{0,0});
assert(bsms == cf.findAttr("BootstrapMethods"));
}
if (bsms.item instanceof byte[]) {
// unflatten
List<Object[]> specs = new CountedList<>(Object[].class);
DataInputStream in = new DataInputStream(new ByteArrayInputStream((byte[]) bsms.item));
try {
int len = (char) in.readShort();
for (int i = 0; i < len; i++) {
short bsm = in.readShort();
int argc = (char) in.readShort();
List<Short> argv = new CountedList<>(Short.class);
for (int j = 0; j < argc; j++)
argv.add(in.readShort());
specs.add(new Object[]{ bsm, argv });
}
} catch (IOException ex) { throw new InternalError(); }
bsms.item = specs;
}
return (List<Object[]>) bsms.item;
}
}
private DataInputStream openInput(File f) throws IOException {
return new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
}
private DataOutputStream openOutput(File f) throws IOException {
if (!overwrite && f.exists())
throw new IOException("file already exists: "+f);
ensureDirectory(f.getParentFile());
return new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
}
static byte[] readRawBytes(DataInputStream in, int size) throws IOException {
byte[] bytes = new byte[size];
int nr = in.read(bytes);
if (nr != size)
throw new InternalError("wrong size: "+nr);
return bytes;
}
private interface Chunk {
void readFrom(DataInputStream in) throws IOException;
void writeTo(DataOutputStream out) throws IOException;
}
private static class CountedList<T> extends ArrayList<T> implements Chunk {
final Class<? extends T> itemClass;
final int rowlen;
CountedList(Class<? extends T> itemClass, int rowlen) {
this.itemClass = itemClass;
this.rowlen = rowlen;
}
CountedList(Class<? extends T> itemClass) { this(itemClass, -1); }
public void readFrom(DataInputStream in) throws IOException {
int count = in.readUnsignedShort();
while (size() < count) {
if (rowlen < 0) {
add(readInput(in, itemClass));
} else {
Class<?> elemClass = itemClass.getComponentType();
Object[] row = (Object[]) java.lang.reflect.Array.newInstance(elemClass, rowlen);
for (int i = 0; i < rowlen; i++)
row[i] = readInput(in, elemClass);
add(itemClass.cast(row));
}
}
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeShort((short)size());
for (T item : this) {
writeOutput(out, item);
}
}
}
private static <T> T readInput(DataInputStream in, Class<T> dataClass) throws IOException {
Object data;
if (dataClass == Integer.class) {
data = in.readInt();
} else if (dataClass == Short.class) {
data = in.readShort();
} else if (dataClass == Byte.class) {
data = in.readByte();
} else if (dataClass == String.class) {
data = in.readUTF();
} else if (Chunk.class.isAssignableFrom(dataClass)) {
T obj;
try { obj = dataClass.newInstance(); }
catch (Exception ex) { throw new RuntimeException(ex); }
((Chunk)obj).readFrom(in);
data = obj;
} else {
throw new InternalError("bad input datum: "+dataClass);
}
return dataClass.cast(data);
}
private static <T> T readInput(byte[] bytes, Class<T> dataClass) {
try {
return readInput(new DataInputStream(new ByteArrayInputStream(bytes)), dataClass);
} catch (IOException ex) {
throw new InternalError();
}
}
private static void readInputs(DataInputStream in, Object... data) throws IOException {
for (Object x : data) ((Chunk)x).readFrom(in);
}
private static void writeOutput(DataOutputStream out, Object data) throws IOException {
if (data == null) {
return;
} if (data instanceof Integer) {
out.writeInt((Integer)data);
} else if (data instanceof Long) {
out.writeLong((Long)data);
} else if (data instanceof Short) {
out.writeShort((Short)data);
} else if (data instanceof Byte) {
out.writeByte((Byte)data);
} else if (data instanceof String) {
out.writeUTF((String)data);
} else if (data instanceof byte[]) {
out.write((byte[])data);
} else if (data instanceof Object[]) {
for (Object x : (Object[]) data)
writeOutput(out, x);
} else if (data instanceof Chunk) {
Chunk x = (Chunk) data;
x.writeTo(out);
} else if (data instanceof List) {
for (Object x : (List<?>) data)
writeOutput(out, x);
} else {
throw new InternalError("bad output datum: "+data+" : "+data.getClass().getName());
}
}
private static void writeOutputs(DataOutputStream out, Object... data) throws IOException {
for (Object x : data) writeOutput(out, x);
}
public static abstract class Outer {
public abstract List<? extends Inner> inners();
protected void linkInners() {
for (Inner i : inners()) {
i.linkOuter(this);
if (i instanceof Outer)
((Outer)i).linkInners();
}
}
public <T extends Outer> T outer(Class<T> c) {
for (Outer walk = this;; walk = ((Inner)walk).outer()) {
if (c.isInstance(walk))
return c.cast(walk);
//if (!(walk instanceof Inner)) return null;
}
}
public abstract List<Attr> attrs();
public Attr findAttr(String name) {
return findAttr(outer(ClassFile.class).pool.stringIndex(name, false));
}
public Attr findAttr(int name) {
if (name == 0) return null;
for (Attr a : attrs()) {
if (a.name == name) return a;
}
return null;
}
}
public interface Inner { Outer outer(); void linkOuter(Outer o); }
public static abstract class InnerOuter extends Outer implements Inner {
public Outer outer;
public Outer outer() { return outer; }
public void linkOuter(Outer o) { assert(outer == null); outer = o; }
}
public static class Constant<T> implements Chunk {
public final byte tag;
public final T item;
public final int index;
public Constant(int index, byte tag, T item) {
this.index = index;
this.tag = tag;
this.item = item;
}
public Constant checkTag(byte tag) {
if (this.tag != tag) throw new InternalError(this.toString());
return this;
}
public String itemString() { return (String)item; }
public Short itemIndex() { return (Short)item; }
public Short[] itemIndexes() { return (Short[])item; }
public void readFrom(DataInputStream in) throws IOException {
throw new InternalError("do not call");
}
public void writeTo(DataOutputStream out) throws IOException {
writeOutputs(out, tag, item);
}
public boolean equals(Object x) { return (x instanceof Constant && equals((Constant)x)); }
public boolean equals(Constant that) {
return (this.tag == that.tag && this.itemAsComparable().equals(that.itemAsComparable()));
}
public int hashCode() { return (tag * 31) + this.itemAsComparable().hashCode(); }
public Object itemAsComparable() {
switch (tag) {
case CONSTANT_Double: return Double.longBitsToDouble((Long)item);
case CONSTANT_Float: return Float.intBitsToFloat((Integer)item);
}
return (item instanceof Object[] ? Arrays.asList((Object[])item) : item);
}
public String toString() {
String itstr = String.valueOf(itemAsComparable());
return (index + ":" + tagName(tag) + (itstr.startsWith("[")?"":"=") + itstr);
}
private static String[] TAG_NAMES;
public static String tagName(byte tag) { // used for error messages
if (TAG_NAMES == null)
TAG_NAMES = ("None Utf8 Unicode Integer Float Long Double Class String"
+" Fieldref Methodref InterfaceMethodref NameAndType #13 #14"
+" MethodHandle MethodType InvokeDynamic#17 InvokeDynamic").split(" ");
if ((tag & 0xFF) >= TAG_NAMES.length) return "#"+(tag & 0xFF);
return TAG_NAMES[tag & 0xFF];
}
}
public static class Pool extends CountedList<Constant> implements Chunk {
private Map<String,Short> strings = new TreeMap<>();
public Pool() {
super(Constant.class);
}
public void readFrom(DataInputStream in) throws IOException {
int count = in.readUnsignedShort();
add(null); // always ignore first item
while (size() < count) {
readConstant(in);
}
}
public <T> Constant<T> addConstant(byte tag, T item) {
Constant<T> con = new Constant<>(size(), tag, item);
int idx = indexOf(con);
if (idx >= 0) return get(idx);
add(con);
if (tag == CONSTANT_Utf8) strings.put((String)item, (short) con.index);
return con;
}
private void readConstant(DataInputStream in) throws IOException {
byte tag = in.readByte();
int index = size();
Object arg;
switch (tag) {
case CONSTANT_Utf8:
arg = in.readUTF();
strings.put((String) arg, (short) size());
break;
case CONSTANT_Integer:
case CONSTANT_Float:
arg = in.readInt(); break;
case CONSTANT_Long:
case CONSTANT_Double:
add(new Constant(index, tag, in.readLong()));
add(null);
return;
case CONSTANT_Class:
case CONSTANT_String:
arg = in.readShort(); break;
case CONSTANT_Field:
case CONSTANT_Method:
case CONSTANT_InterfaceMethod:
case CONSTANT_NameAndType:
case CONSTANT_InvokeDynamic:
// read an ordered pair
arg = new Short[] { in.readShort(), in.readShort() };
break;
case CONSTANT_MethodHandle:
// read an ordered pair; first part is a u1 (not u2)
arg = new Object[] { in.readByte(), in.readShort() };
break;
case CONSTANT_MethodType:
arg = in.readShort(); break;
default:
throw new InternalError("bad CP tag "+tag);
}
add(new Constant(index, tag, arg));
}
// Access:
public Constant get(int index) {
// extra 1-bits get into the shorts
return super.get((char) index);
}
String getString(byte tag, short index) {
get(index).checkTag(tag);
return getString(index);
}
String getString(short index) {
Object v = get(index).item;
if (v instanceof Short)
v = get((Short)v).checkTag(CONSTANT_Utf8).item;
return (String) v;
}
String[] getStrings(Short[] indexes) {
String[] res = new String[indexes.length];
for (int i = 0; i < indexes.length; i++)
res[i] = getString(indexes[i]);
return res;
}
int stringIndex(String name, boolean createIfNotFound) {
Short x = strings.get(name);
if (x != null) return (char)(int) x;
if (!createIfNotFound) return 0;
return addConstant(CONSTANT_Utf8, name).index;
}
Short[] getMemberRef(short index) {
Short[] cls_nnt = get(index).itemIndexes();
Short[] name_type = get(cls_nnt[1]).itemIndexes();
return new Short[]{ cls_nnt[0], name_type[0], name_type[1] };
}
}
public class ClassFile extends Outer implements Chunk {
ClassFile(File f) throws IOException {
DataInputStream in = openInput(f);
try {
readFrom(in);
} finally {
if (in != null) in.close();
}
}
public int magic, version; // <min:maj>
public final Pool pool = new Pool();
public short access, thisc, superc;
public final List<Short> interfaces = new CountedList<>(Short.class);
public final List<Field> fields = new CountedList<>(Field.class);
public final List<Method> methods = new CountedList<>(Method.class);
public final List<Attr> attrs = new CountedList<>(Attr.class);
public final void readFrom(DataInputStream in) throws IOException {
magic = in.readInt(); version = in.readInt();
if (magic != 0xCAFEBABE) throw new IOException("bad magic number");
pool.readFrom(in);
Code_index = pool.stringIndex("Code", false);
access = in.readShort(); thisc = in.readShort(); superc = in.readShort();
readInputs(in, interfaces, fields, methods, attrs);
if (in.read() >= 0) throw new IOException("junk after end of file");
linkInners();
}
void writeTo(File f) throws IOException {
DataOutputStream out = openOutput(f);
try {
writeTo(out);
} finally {
out.close();
}
}
public void writeTo(DataOutputStream out) throws IOException {
writeOutputs(out, magic, version, pool,
access, thisc, superc, interfaces,
fields, methods, attrs);
}
public byte[] toByteArray() {
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
writeTo(new DataOutputStream(buf));
return buf.toByteArray();
} catch (IOException ex) {
throw new InternalError();
}
}
public List<Inner> inners() {
List<Inner> inns = new ArrayList<>();
inns.addAll(fields); inns.addAll(methods); inns.addAll(attrs);
return inns;
}
public List<Attr> attrs() { return attrs; }
// derived stuff:
public String nameString() { return pool.getString(CONSTANT_Class, thisc); }
int Code_index;
}
private static <T extends Member> T findMember(List<T> mems, int name, int type) {
if (name == 0 || type == 0) return null;
for (T m : mems) {
if (m.name == name && m.type == type) return m;
}
return null;
}
public static class Member extends InnerOuter implements Chunk {
public short access, name, type;
public final List<Attr> attrs = new CountedList<>(Attr.class);
public void readFrom(DataInputStream in) throws IOException {
access = in.readShort(); name = in.readShort(); type = in.readShort();
readInputs(in, attrs);
}
public void writeTo(DataOutputStream out) throws IOException {
writeOutputs(out, access, name, type, attrs);
}
public List<Attr> inners() { return attrs; }
public List<Attr> attrs() { return attrs; }
public ClassFile outer() { return (ClassFile) outer; }
public String nameString() { return outer().pool.getString(CONSTANT_Utf8, name); }
public String typeString() { return outer().pool.getString(CONSTANT_Utf8, type); }
public String toString() {
if (outer == null) return super.toString();
return nameString() + (this instanceof Method ? "" : ":")
+ simplifyType(typeString());
}
}
public static class Field extends Member {
}
public static class Method extends Member {
public Code code() {
Attr a = findAttr("Code");
if (a == null) return null;
return (Code) a.item;
}
public Instruction instructions() {
Code code = code();
if (code == null) return null;
return code.instructions();
}
}
public static class Attr extends InnerOuter implements Chunk {
public short name;
public int size = -1; // no pre-declared size
public Object item;
public Attr() {}
public Attr(Outer outer, String name, Object item) {
ClassFile cf = outer.outer(ClassFile.class);
linkOuter(outer);
this.name = (short) cf.pool.stringIndex(name, true);
this.item = item;
outer.attrs().add(this);
}
public void readFrom(DataInputStream in) throws IOException {
name = in.readShort();
size = in.readInt();
item = readRawBytes(in, size);
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeShort(name);
// write the 4-byte size header and then the contents:
byte[] bytes;
int trueSize;
if (item instanceof byte[]) {
bytes = (byte[]) item;
out.writeInt(trueSize = bytes.length);
out.write(bytes);
} else {
trueSize = flatten(out);
//if (!(item instanceof Code)) System.err.println("wrote complex attr name="+(int)(char)name+" size="+trueSize+" data="+Arrays.toString(flatten()));
}
if (trueSize != size && size >= 0)
System.err.println("warning: attribute size changed "+size+" to "+trueSize);
}
public void linkOuter(Outer o) {
super.linkOuter(o);
if (item instanceof byte[] &&
outer instanceof Method &&
((Method)outer).outer().Code_index == name) {
item = readInput((byte[])item, Code.class);
}
}
public List<Inner> inners() {
if (item instanceof Inner)
return Collections.nCopies(1, (Inner)item);
return Collections.emptyList();
}
public List<Attr> attrs() { return null; } // Code overrides this
public byte[] flatten() {
ByteArrayOutputStream buf = new ByteArrayOutputStream(Math.max(20, size));
flatten(buf);
return buf.toByteArray();
}
public int flatten(DataOutputStream out) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream(Math.max(20, size));
int trueSize = flatten(buf);
out.writeInt(trueSize);
buf.writeTo(out);
return trueSize;
}
private int flatten(ByteArrayOutputStream buf) {
try {
writeOutput(new DataOutputStream(buf), item);
return buf.size();
} catch (IOException ex) {
throw new InternalError();
}
}
public String nameString() {
ClassFile cf = outer(ClassFile.class);
if (cf == null) return "#"+name;
return cf.pool.getString(name);
}
public String toString() {
return nameString()+(size < 0 ? "=" : "["+size+"]=")+item;
}
}
public static class Code extends InnerOuter implements Chunk {
public short stacks, locals;
public byte[] bytes;
public final List<Short[]> etable = new CountedList<>(Short[].class, 4);
public final List<Attr> attrs = new CountedList<>(Attr.class);
// etable[N] = (N)*{ startpc, endpc, handlerpc, catchtype }
public void readFrom(DataInputStream in) throws IOException {
stacks = in.readShort(); locals = in.readShort();
bytes = readRawBytes(in, in.readInt());
readInputs(in, etable, attrs);
}
public void writeTo(DataOutputStream out) throws IOException {
writeOutputs(out, stacks, locals, bytes.length, bytes, etable, attrs);
}
public List<Attr> inners() { return attrs; }
public List<Attr> attrs() { return attrs; }
public Instruction instructions() {
return new Instruction(bytes, 0);
}
}
// lots of constants
private static final byte
CONSTANT_Utf8 = 1,
CONSTANT_Integer = 3,
CONSTANT_Float = 4,
CONSTANT_Long = 5,
CONSTANT_Double = 6,
CONSTANT_Class = 7,
CONSTANT_String = 8,
CONSTANT_Field = 9,
CONSTANT_Method = 10,
CONSTANT_InterfaceMethod = 11,
CONSTANT_NameAndType = 12,
CONSTANT_MethodHandle = 15, // JSR 292
CONSTANT_MethodType = 16, // JSR 292
CONSTANT_InvokeDynamic = 18; // JSR 292
private static final byte
REF_getField = 1,
REF_getStatic = 2,
REF_putField = 3,
REF_putStatic = 4,
REF_invokeVirtual = 5,
REF_invokeStatic = 6,
REF_invokeSpecial = 7,
REF_newInvokeSpecial = 8,
REF_invokeInterface = 9;
private static final int
opc_nop = 0,
opc_aconst_null = 1,
opc_nconst_MIN = 2, // iconst_m1
opc_nconst_MAX = 15, // dconst_1
opc_bipush = 16,
opc_sipush = 17,
opc_ldc = 18,
opc_ldc_w = 19,
opc_ldc2_w = 20,
opc_aload = 25,
opc_aload_0 = 42,
opc_aload_MAX = 45,
opc_aaload = 50,
opc_astore = 58,
opc_astore_0 = 75,
opc_astore_MAX = 78,
opc_aastore = 83,
opc_pop = 87,
opc_pop2 = 88,
opc_dup = 89,
opc_dup_x1 = 90,
opc_dup_x2 = 91,
opc_dup2 = 92,
opc_dup2_x1 = 93,
opc_dup2_x2 = 94,
opc_swap = 95,
opc_tableswitch = 170,
opc_lookupswitch = 171,
opc_areturn = 176,
opc_getstatic = 178,
opc_putstatic = 179,
opc_getfield = 180,
opc_putfield = 181,
opc_invokevirtual = 182,
opc_invokespecial = 183,
opc_invokestatic = 184,
opc_invokeinterface = 185,
opc_invokedynamic = 186,
opc_new = 187,
opc_anewarray = 189,
opc_checkcast = 192,
opc_ifnull = 198,
opc_ifnonnull = 199,
opc_wide = 196;
private static final Object[] INSTRUCTION_CONSTANTS = {
-1, 0, 1, 2, 3, 4, 5, 0L, 1L, 0.0F, 1.0F, 2.0F, 0.0D, 1.0D
};
private static final String INSTRUCTION_FORMATS =
"nop$ aconst_null$L iconst_m1$I iconst_0$I iconst_1$I "+
"iconst_2$I iconst_3$I iconst_4$I iconst_5$I lconst_0$J_ "+
"lconst_1$J_ fconst_0$F fconst_1$F fconst_2$F dconst_0$D_ "+
"dconst_1$D_ bipush=bx$I sipush=bxx$I ldc=bk$X ldc_w=bkk$X "+
"ldc2_w=bkk$X_ iload=bl/wbll$I lload=bl/wbll$J_ fload=bl/wbll$F "+
"dload=bl/wbll$D_ aload=bl/wbll$L iload_0$I iload_1$I "+
"iload_2$I iload_3$I lload_0$J_ lload_1$J_ lload_2$J_ "+
"lload_3$J_ fload_0$F fload_1$F fload_2$F fload_3$F dload_0$D_ "+
"dload_1$D_ dload_2$D_ dload_3$D_ aload_0$L aload_1$L "+
"aload_2$L aload_3$L iaload$LI$I laload$LI$J_ faload$LI$F "+
"daload$LI$D_ aaload$LI$L baload$LI$I caload$LI$I saload$LI$I "+
"istore=bl/wbll$I$ lstore=bl/wbll$J_$ fstore=bl/wbll$F$ "+
"dstore=bl/wbll$D_$ astore=bl/wbll$L$ istore_0$I$ istore_1$I$ "+
"istore_2$I$ istore_3$I$ lstore_0$J_$ lstore_1$J_$ "+
"lstore_2$J_$ lstore_3$J_$ fstore_0$F$ fstore_1$F$ fstore_2$F$ "+
"fstore_3$F$ dstore_0$D_$ dstore_1$D_$ dstore_2$D_$ "+
"dstore_3$D_$ astore_0$L$ astore_1$L$ astore_2$L$ astore_3$L$ "+
"iastore$LII$ lastore$LIJ_$ fastore$LIF$ dastore$LID_$ "+
"aastore$LIL$ bastore$LII$ castore$LII$ sastore$LII$ pop$X$ "+
"pop2$XX$ dup$X$XX dup_x1$XX$XXX dup_x2$XXX$XXXX dup2$XX$XXXX "+
"dup2_x1$XXX$XXXXX dup2_x2$XXXX$XXXXXX swap$XX$XX "+
"iadd$II$I ladd$J_J_$J_ fadd$FF$F dadd$D_D_$D_ isub$II$I "+
"lsub$J_J_$J_ fsub$FF$F dsub$D_D_$D_ imul$II$I lmul$J_J_$J_ "+
"fmul$FF$F dmul$D_D_$D_ idiv$II$I ldiv$J_J_$J_ fdiv$FF$F "+
"ddiv$D_D_$D_ irem$II$I lrem$J_J_$J_ frem$FF$F drem$D_D_$D_ "+
"ineg$I$I lneg$J_$J_ fneg$F$F dneg$D_$D_ ishl$II$I lshl$J_I$J_ "+
"ishr$II$I lshr$J_I$J_ iushr$II$I lushr$J_I$J_ iand$II$I "+
"land$J_J_$J_ ior$II$I lor$J_J_$J_ ixor$II$I lxor$J_J_$J_ "+
"iinc=blx/wbllxx$ i2l$I$J_ i2f$I$F i2d$I$D_ l2i$J_$I l2f$J_$F "+
"l2d$J_$D_ f2i$F$I f2l$F$J_ f2d$F$D_ d2i$D_$I d2l$D_$J_ "+
"d2f$D_$F i2b$I$I i2c$I$I i2s$I$I lcmp fcmpl fcmpg dcmpl dcmpg "+
"ifeq=boo ifne=boo iflt=boo ifge=boo ifgt=boo ifle=boo "+
"if_icmpeq=boo if_icmpne=boo if_icmplt=boo if_icmpge=boo "+
"if_icmpgt=boo if_icmple=boo if_acmpeq=boo if_acmpne=boo "+
"goto=boo jsr=boo ret=bl/wbll tableswitch=* lookupswitch=* "+
"ireturn lreturn freturn dreturn areturn return "+
"getstatic=bkf$Q putstatic=bkf$Q$ getfield=bkf$L$Q "+
"putfield=bkf$LQ$ invokevirtual=bkm$LQ$Q "+
"invokespecial=bkm$LQ$Q invokestatic=bkm$Q$Q "+
"invokeinterface=bkixx$LQ$Q invokedynamic=bkd__$Q$Q new=bkc$L "+
"newarray=bx$I$L anewarray=bkc$I$L arraylength$L$I athrow "+
"checkcast=bkc$L$L instanceof=bkc$L$I monitorenter$L "+
"monitorexit$L wide=* multianewarray=bkcx ifnull=boo "+
"ifnonnull=boo goto_w=boooo jsr_w=boooo ";
private static final String[] INSTRUCTION_NAMES;
private static final String[] INSTRUCTION_POPS;
private static final int[] INSTRUCTION_INFO;
static {
String[] insns = INSTRUCTION_FORMATS.split(" ");
assert(insns[opc_lookupswitch].startsWith("lookupswitch"));
assert(insns[opc_tableswitch].startsWith("tableswitch"));
assert(insns[opc_wide].startsWith("wide"));
assert(insns[opc_invokedynamic].startsWith("invokedynamic"));
int[] info = new int[256];
String[] names = new String[256];
String[] pops = new String[256];
for (int i = 0; i < insns.length; i++) {
String insn = insns[i];
int dl = insn.indexOf('$');
if (dl > 0) {
String p = insn.substring(dl+1);
if (p.indexOf('$') < 0) p = "$" + p;
pops[i] = p;
insn = insn.substring(0, dl);
}
int eq = insn.indexOf('=');
if (eq < 0) {
info[i] = 1;
names[i] = insn;
continue;
}
names[i] = insn.substring(0, eq);
String fmt = insn.substring(eq+1);
if (fmt.equals("*")) {
info[i] = 0;
continue;
}
int sl = fmt.indexOf('/');
if (sl < 0) {
info[i] = (char) fmt.length();
} else {
String wfmt = fmt.substring(sl+1);
fmt = fmt.substring(0, sl);
info[i] = (char)( fmt.length() + (wfmt.length() * 16) );
}
}
INSTRUCTION_INFO = info;
INSTRUCTION_NAMES = names;
INSTRUCTION_POPS = pops;
}
public static class Instruction implements Cloneable {
byte[] codeBase;
int pc;
int bc;
int info;
int wide;
int len;
Instruction(byte[] codeBase, int pc) {
this.codeBase = codeBase;
init(pc);
}
public Instruction clone() {
try {
return (Instruction) super.clone();
} catch (CloneNotSupportedException ex) {
throw new InternalError();
}
}
private Instruction init(int pc) {
this.pc = pc;
this.bc = codeBase[pc] & 0xFF;
this.info = INSTRUCTION_INFO[bc];
this.wide = 0;
this.len = (info & 0x0F);
if (len == 0)
computeLength();
return this;
}
Instruction next() {
if (len == 0 && bc != 0) throw new InternalError();
int npc = pc + len;
if (npc == codeBase.length)
return null;
return init(npc);
}
void forceNext(int newLen) {
bc = opc_nop;
len = newLen;
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(pc).append(":").append(INSTRUCTION_NAMES[bc]);
switch (len) {
case 3: buf.append(" ").append(u2At(1)); break;
case 5: buf.append(" ").append(u2At(1)).append(" ").append(u2At(3)); break;
default: for (int i = 1; i < len; i++) buf.append(" ").append(u1At(1));
}
return buf.toString();
}
// these are the hard parts
private void computeLength() {
int cases;
switch (bc) {
case opc_wide:
bc = codeBase[pc + 1];
info = INSTRUCTION_INFO[bc];
len = ((info >> 4) & 0x0F);
if (len == 0) throw new RuntimeException("misplaced wide bytecode: "+bc);
return;
case opc_tableswitch:
cases = (u4At(alignedIntOffset(2)) - u4At(alignedIntOffset(1)) + 1);
len = alignedIntOffset(3 + cases*1);
return;
case opc_lookupswitch:
cases = u4At(alignedIntOffset(1));
len = alignedIntOffset(2 + cases*2);
return;
default:
throw new RuntimeException("unknown bytecode: "+bc);
}
}
// switch code
// clget the Nth int (where 0 is the first after the opcode itself)
public int alignedIntOffset(int n) {
int pos = pc + 1;
pos += ((-pos) & 0x03); // align it
pos += (n * 4);
return pos - pc;
}
public int u1At(int pos) {
return (codeBase[pc+pos] & 0xFF);
}
public int u2At(int pos) {
return (u1At(pos+0)<<8) + u1At(pos+1);
}
public int u4At(int pos) {
return (u2At(pos+0)<<16) + u2At(pos+2);
}
public void u1AtPut(int pos, int x) {
codeBase[pc+pos] = (byte)x;
}
public void u2AtPut(int pos, int x) {
codeBase[pc+pos+0] = (byte)(x >> 8);
codeBase[pc+pos+1] = (byte)(x >> 0);
}
}
static String simplifyType(String type) {
String simpleType = OBJ_SIGNATURE.matcher(type).replaceAll("L");
assert(simpleType.matches("^\\([A-Z]*\\)[A-Z]$"));
// change (DD)D to (D_D_)D_
simpleType = WIDE_SIGNATURE.matcher(simpleType).replaceAll("\\0_");
return simpleType;
}
static int argsize(String type) {
return simplifyType(type).length()-3;
}
private static final Pattern OBJ_SIGNATURE = Pattern.compile("\\[*L[^;]*;|\\[+[A-Z]");
private static final Pattern WIDE_SIGNATURE = Pattern.compile("[JD]");
}