Example usage for org.objectweb.asm.tree ClassNode ClassNode

List of usage examples for org.objectweb.asm.tree ClassNode ClassNode

Introduction

In this page you can find the example usage for org.objectweb.asm.tree ClassNode ClassNode.

Prototype

public ClassNode() 

Source Link

Document

Constructs a new ClassNode .

Usage

From source file:com.google.template.soy.jbcsrc.internal.ClassData.java

License:Apache License

/**
 * Runs the {@link CheckClassAdapter} on this class in basic analysis mode.
 *
 * <p>Basic anaylsis mode can flag verification errors that don't depend on knowing complete type
 * information for the classes and methods being called. This is useful for flagging simple
 * generation mistakes (e.g. stack underflows, method return type mismatches, accessing invalid
 * locals). Additionally, the error messages are more useful than what the java verifier normally
 * presents.//w  w  w  . j a  va2  s  .co  m
 */
public void checkClass() {
    ClassNode cv = new ClassNode();
    new ClassReader(data).accept(new CheckClassAdapter(cv, true /* check data flow */), 0);
    // double check our fields while we are here.
    checkState(type.internalName().equals(cv.name));
    checkState(numberOfFields == cv.fields.size());
}

From source file:com.google.template.soy.jbcsrc.internal.MemoryClassLoaderTest.java

License:Apache License

@Test
public void testAsResource() throws IOException {
    BooleanInvoker invoker = ExpressionEvaluator.createInvoker(BooleanInvoker.class, FALSE);
    byte[] classBytes = ByteStreams.toByteArray(invoker.getClass().getClassLoader()
            .getResourceAsStream(invoker.getClass().getName().replace('.', '/') + ".class"));
    ClassNode node = new ClassNode();
    new ClassReader(classBytes).accept(node, 0);
    assertThat(node.name).isEqualTo(Type.getInternalName(invoker.getClass()));
}

From source file:com.google.template.soy.jbcsrc.MemoryClassLoaderTest.java

License:Apache License

public void testAsResource() throws IOException {
    BooleanInvoker invoker = ExpressionTester.createInvoker(BooleanInvoker.class, FALSE);
    byte[] classBytes = ByteStreams.toByteArray(invoker.getClass().getClassLoader()
            .getResourceAsStream(invoker.getClass().getName().replace('.', '/') + ".class"));
    ClassNode node = new ClassNode();
    new ClassReader(classBytes).accept(node, 0);
    assertEquals(Type.getInternalName(invoker.getClass()), node.name);
}

From source file:com.googlecode.d2j.jasmin.Jar2JasminCmd.java

License:Apache License

private void disassemble1(Path file, Path output) throws IOException {
    try (InputStream is = Files.newInputStream(file)) {
        ClassReader r = new ClassReader(is);
        Path jFile = output.resolve(r.getClassName().replace('.', '/') + ".j");
        createParentDirectories(jFile);/*from   w  w w. j  a v a  2  s . c  o  m*/
        try (BufferedWriter out = Files.newBufferedWriter(jFile, Charset.forName(encoding))) {
            PrintWriter pw = new PrintWriter(out);
            ClassNode node = new ClassNode();
            r.accept(node, (debugInfo ? 0 : ClassReader.SKIP_DEBUG) | ClassReader.EXPAND_FRAMES);
            new JasminDumper(pw).dump(node);
            pw.flush();
        }
    }
}

From source file:com.googlecode.dex2jar.test.TestUtils.java

License:Apache License

@SuppressWarnings("rawtypes")
public static void verify(final ClassReader cr, PrintWriter out)
        throws AnalyzerException, IllegalArgumentException, IllegalAccessException {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    List methods = cn.methods;/*from w  w  w. ja va  2s.co  m*/

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = (MethodNode) methods.get(i);

        List tryCatchBlocks = method.tryCatchBlocks;
        for (int j = 0; j < tryCatchBlocks.size(); j++) {
            TryCatchBlockNode tcn = (TryCatchBlockNode) tryCatchBlocks.get(j);
            if (tcn.start.equals(tcn.end)) {
                throw new DexException("try/catch block %d in %s has same start(%s) and end(%s)", j,
                        method.name, tcn.start.getLabel(), tcn.end.getLabel());
            }
        }

        BasicVerifier verifier = new BasicVerifier();
        Analyzer a = new Analyzer(verifier);
        try {
            a.analyze(cn.name, method);
        } catch (Exception e) {
            out.println(cr.getClassName() + "." + method.name + method.desc);
            printAnalyzerResult(method, a, out);
            e.printStackTrace(out);
            out.flush();
            throw new DexException("method " + method.name + " " + method.desc, e);
        }
    }
}

From source file:com.googlecode.dex2jar.tools.AsmVerify.java

License:Apache License

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length < 1) {
        usage();// w w w  . j a v  a  2  s. c  o m
        return;
    }

    List<Path> files = new ArrayList<>();
    for (String fn : remainingArgs) {
        Path file = new File(fn).toPath();
        if (!Files.exists(file)) {
            System.err.println(fn + " is not exists");
            usage();
            return;
        }
        files.add(file);
    }

    for (Path file : files) {
        System.out.println("verify " + file);
        walkJarOrDir(file, new FileVisitorX() {
            @Override
            public void visitFile(Path file, Path relative) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    ClassReader cr = new ClassReader(Files.readAllBytes(file));
                    ClassNode cn = new ClassNode();
                    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);
                    for (MethodNode method : cn.methods) {
                        BasicVerifier verifier = new BasicVerifier();
                        Analyzer<BasicValue> a = new Analyzer<>(verifier);
                        try {
                            a.analyze(cn.name, method);
                        } catch (Exception ex) {
                            System.err.println("Error verify method " + cr.getClassName() + "." + method.name
                                    + " " + method.desc);
                            if (detail) {
                                ex.printStackTrace(System.err);
                                printAnalyzerResult(method, a, new PrintWriter(
                                        new OutputStreamWriter(System.err, StandardCharsets.UTF_8)));
                            }
                        }
                    }
                }
            }
        });
    }
}

From source file:com.googlecode.dex2jar.tools.DecryptStringCmd.java

License:Apache License

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();//from   w  w  w. j a v  a2 s  .c  o  m
        return;
    }

    final Path jar = new File(remainingArgs[0]).toPath();
    if (!Files.exists(jar)) {
        System.err.println(jar + " is not exists");
        return;
    }
    if (methodName == null || methodOwner == null) {
        System.err.println("Please set --decrypt-method-owner and --decrypt-method-name");
        return;
    }

    if (output == null) {
        if (Files.isDirectory(jar)) {
            output = new File(jar.getFileName() + "-decrypted.jar").toPath();
        } else {
            output = new File(getBaseName(jar.getFileName().toString()) + "-decrypted.jar").toPath();
        }
    }

    if (Files.exists(output) && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        return;
    }

    System.err.println(jar + " -> " + output);

    List<String> list = new ArrayList<String>();
    if (classpath != null) {
        list.addAll(Arrays.asList(classpath.split(";|:")));
    }
    list.add(jar.toAbsolutePath().toString());
    URL[] urls = new URL[list.size()];
    for (int i = 0; i < list.size(); i++) {
        urls[i] = new File(list.get(i)).toURI().toURL();
    }
    final Method jmethod;
    try {
        URLClassLoader cl = new URLClassLoader(urls);
        jmethod = cl.loadClass(methodOwner).getMethod(methodName, String.class);
        jmethod.setAccessible(true);
    } catch (Exception ex) {
        System.err.println("can't load method: String " + methodOwner + "." + methodName + "(String), message:"
                + ex.getMessage());
        return;
    }
    final String methodOwnerInternalType = this.methodOwner.replace('.', '/');
    try (FileSystem outputFileSystem = createZip(output)) {
        final Path outputBase = outputFileSystem.getPath("/");
        walkJarOrDir(jar, new FileVisitorX() {
            @Override
            public void visitFile(Path file, Path relative) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {

                    ClassReader cr = new ClassReader(Files.readAllBytes(file));
                    ClassNode cn = new ClassNode();
                    cr.accept(cn, 0);

                    for (Object m0 : cn.methods) {
                        MethodNode m = (MethodNode) m0;
                        if (m.instructions == null) {
                            continue;
                        }
                        AbstractInsnNode p = m.instructions.getFirst();
                        while (p != null) {
                            if (p.getOpcode() == Opcodes.LDC) {
                                LdcInsnNode ldc = (LdcInsnNode) p;
                                if (ldc.cst instanceof String) {
                                    String v = (String) ldc.cst;
                                    AbstractInsnNode q = p.getNext();
                                    if (q.getOpcode() == Opcodes.INVOKESTATIC) {
                                        MethodInsnNode mn = (MethodInsnNode) q;
                                        if (mn.name.equals(methodName)
                                                && mn.desc.equals("(Ljava/lang/String;)Ljava/lang/String;")
                                                && mn.owner.equals(methodOwnerInternalType)) {
                                            try {
                                                Object newValue = jmethod.invoke(null, v);
                                                ldc.cst = newValue;
                                            } catch (Exception e) {
                                                // ignore
                                            }
                                            m.instructions.remove(q);
                                        }
                                    }
                                }
                            }
                            p = p.getNext();
                        }
                    }

                    ClassWriter cw = new ClassWriter(0);
                    cn.accept(cw);
                    Files.write(outputBase.resolve(relative), cw.toByteArray());
                } else {
                    Files.copy(file, outputBase.resolve(relative));
                }
            }
        });
    }
}

From source file:com.hea3ven.hardmodetweaks.core.ClassTransformerHardModeTweaks.java

License:Open Source License

private ClassNode readClass(byte[] basicClass) {
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(basicClass);
    classReader.accept(classNode, 0);/*from  w  ww . ja  v  a  2 s . c o m*/
    return classNode;
}

From source file:com.helger.meta.asm.ASMUtils.java

License:Apache License

/**
 * Read the passed class file using ASM and build a {@link ClassNode}.
 *
 * @param aBytes//from w w w  . j  a  v  a2 s . c o  m
 *        The bytes representing the content of the class file to read. May
 *        not be <code>null</code>.
 * @return The read {@link ClassNode}.
 */
@Nonnull
public static ClassNode readClass(@Nonnull final byte[] aBytes) {
    // Interpret the class file
    final ClassReader cr = new ClassReader(aBytes);
    final ClassNode cn = new ClassNode();
    cr.accept(cn, 0);
    return cn;
}

From source file:com.heliosdecompiler.helios.LoadedFile.java

License:Apache License

public void reset() {
    readDataQuick();//from   w  w w .  ja  v a2  s . c o  m
    if (files.size() > 0) {
        // Read all data of potential class files
        BackgroundTaskHandler.INSTANCE.submit(() -> {
            Map<String, ClassNode> emptyClasses = new HashMap<>();
            files.entrySet().stream().filter(ent -> ent.getKey().endsWith(".class")).forEach(ent -> {
                try {
                    ClassReader classReader = new ClassReader(new ByteArrayInputStream(ent.getValue()));
                    ClassNode classNode = new ClassNode();
                    classReader.accept(classNode,
                            ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);

                    // Store by ClassNode name
                    emptyClasses.put(classNode.name, classNode);
                    // Also store by path
                    emptyClasses.put(ent.getKey(), classNode);
                } catch (Exception ignored) { //Malformed class
                }
            });
            // Lock the map
            this.emptyClasses = Collections.unmodifiableMap(emptyClasses);
            if (!this.isPath) {
                // Read the code as well
                // fixme If path jars are guarenteed to not require code then maybe we can merge emptyClasses and classes
                // fixme this seems to hog cpu cycles or something
                BackgroundTaskHandler.INSTANCE.submit(() -> {
                    Map<String, ClassNode> classes = new HashMap<>();
                    files.entrySet().stream().filter(ent -> ent.getKey().endsWith(".class")).forEach(ent -> {
                        try {
                            ClassReader classReader = new ClassReader(new ByteArrayInputStream(ent.getValue()));
                            ClassNode classNode = new ClassNode();
                            classReader.accept(classNode, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);

                            // Store by ClassNode name
                            classes.put(classNode.name, classNode);
                            // Also store by path
                            classes.put(ent.getKey(), classNode);
                        } catch (Exception ignored) { //Malformed class
                        }
                    });
                    // Lock the map
                    this.classes = Collections.unmodifiableMap(classes);
                });
            } else {
                this.classes = Collections.synchronizedMap(new HashMap<>());
            }
        });
    }
}