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

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

Introduction

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

Prototype

public void accept(final ClassVisitor classVisitor) 

Source Link

Document

Makes the given class visitor visit this class.

Usage

From source file:com.github.wreulicke.bean.validation.ASMMethodParameterValidationInjectorTest.java

License:Open Source License

@Test
public void firstCase() throws IOException {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES + ClassWriter.COMPUTE_MAXS);
    ClassReader reader = new ClassReader(getByteCode(Example.class));
    ClassNode node = new ClassNode();
    reader.accept(node, ClassReader.EXPAND_FRAMES);
    ASMMethodParameterValidationInjector injector = new ASMMethodParameterValidationInjector();
    injector.inject(node);//from  ww  w. java  2  s . c  o m
    node.accept(writer);
    byte[] result = writer.toByteArray();
    // ByteCodes.dumpAndDecomplie((p) -> p.resolve("Example.class"), getByteCode(Example.class));
}

From source file:com.github.wreulicke.bean.validation.ASMNotNullInstrumentation.java

License:Open Source License

@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES + ClassWriter.COMPUTE_MAXS);
    ClassReader reader = new ClassReader(classfileBuffer);
    ClassNode node = new ClassNode();
    reader.accept(node, ClassReader.EXPAND_FRAMES);
    new InnerNotNullInstrumentation(node).visit();
    node.accept(writer);
    return writer.toByteArray();
}

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

License:Apache License

private void assemble1(Path file, Path output) throws IOException {
    try (BufferedReader bufferedReader = Files.newBufferedReader(file, Charset.forName(encoding))) {
        ANTLRStringStream is = new ANTLRReaderStream(bufferedReader);
        is.name = file.toString();/* w  w  w .  j a v  a2 s. c om*/
        JasminLexer lexer = new JasminLexer(is);
        CommonTokenStream ts = new CommonTokenStream(lexer);
        JasminParser parser = new JasminParser(ts);
        parser.rebuildLine = autogenLines;
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        ClassNode cn = parser.parse();
        if (cn.version == 0) {
            cn.version = versions[classVersion];
        }
        if (dump) {
            new JasminDumper(new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), true))
                    .dump(cn);
        }
        cn.accept(cw);
        Path clzFile = output.resolve(cn.name.replace('.', '/') + ".class");
        createParentDirectories(clzFile);
        Files.write(clzFile, cw.toByteArray());
    } catch (RecognitionException e) {
        System.err.println("Fail to assemble " + file);
        e.printStackTrace();
    }
}

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

License:Apache License

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();/* w ww. j av  a 2 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 byte[] writeClass(ClassNode classNode) {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
}

From source file:com.insightfullogic.stripper.Runner.java

License:Open Source License

static void rewrite(final String classFile, final ClassRules rules) {
    try {//from   ww  w.  j  av  a 2  s .c  o m
        // Read
        final ClassReader cr = new ClassReader(classFile);
        final ClassNode cls = new ClassNode();
        cr.accept(cls, 0);

        rules.strip(cls);

        // Write
        final ClassWriter cw = new ClassWriter(0);
        cls.accept(cw);
        try (FileOutputStream out = new FileOutputStream(classFile)) {
            out.write(cw.toByteArray());
        }
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.licel.jcardsim.utils.JavaCardApiProcessor.java

License:Apache License

public static void proxyClass(File buildDir, String proxyClassFile, String targetClassFile,
        boolean skipConstructor) throws IOException {
    File proxyFile = new File(buildDir, proxyClassFile.replace(".", File.separator) + ".class");
    FileInputStream fProxyClass = new FileInputStream(proxyFile);
    FileInputStream fTargetClass = new FileInputStream(
            new File(buildDir, targetClassFile.replace(".", File.separator) + ".class"));
    ClassReader crProxy = new ClassReader(fProxyClass);
    ClassNode cnProxy = new ClassNode();
    crProxy.accept(cnProxy, 0);/* www.  jav  a2 s. co  m*/
    ClassReader crTarget = new ClassReader(fTargetClass);
    ClassNode cnTarget = new ClassNode();
    crTarget.accept(cnTarget, 0);

    ClassNode cnProxyRemapped = new ClassNode();
    HashMap<String, String> map = new HashMap();
    map.put(cnProxy.name, cnTarget.name);
    // inner classes
    for (int i = 0; i < 10; i++) {
        map.put(cnProxy.name + "$1", cnTarget.name + "$1");
    }
    RemappingClassAdapter ra = new RemappingClassAdapter(cnProxyRemapped, new SimpleRemapper(map));
    cnProxy.accept(ra);

    ClassWriter cw = new ClassWriter(crTarget, 0);
    MergeAdapter ma = new MergeAdapter(cw, cnProxyRemapped, skipConstructor);
    cnTarget.accept(ma);
    fProxyClass.close();
    fTargetClass.close();
    FileOutputStream fos = new FileOutputStream(
            new File(buildDir, targetClassFile.replace(".", File.separator) + ".class"));
    fos.write(cw.toByteArray());
    fos.close();
    // remove proxy class
    proxyFile.delete();
}

From source file:com.licel.jcardsim.utils.JavaCardApiProcessor.java

License:Apache License

public static void copyClass(File buildDir, String proxyClassFile, String targetClassName, Map map)
        throws IOException {
    File sourceFile = new File(buildDir, proxyClassFile.replace(".", File.separator) + ".class");
    FileInputStream fProxyClass = new FileInputStream(sourceFile);
    ClassReader crProxy = new ClassReader(fProxyClass);
    ClassNode cnProxy = new ClassNode();
    crProxy.accept(cnProxy, 0);//from  w ww. j av a  2  s.  co m

    ClassWriter cw = new ClassWriter(0);
    map.put(cnProxy.name, targetClassName.replace(".", "/"));
    RemappingClassAdapter ra = new RemappingClassAdapter(cw, new SimpleRemapper(map));
    cnProxy.accept(ra);

    fProxyClass.close();
    FileOutputStream fos = new FileOutputStream(
            new File(buildDir, targetClassName.replace(".", File.separator) + ".class"));
    fos.write(cw.toByteArray());
    fos.close();

    // remove source class
    sourceFile.delete();
}

From source file:com.licel.jcardsim.utils.JavaCardApiProcessor.java

License:Apache License

public static void proxyExceptionClass(File buildDir, String targetClassName) throws IOException {
    FileInputStream fTargetClass = new FileInputStream(
            new File(buildDir, targetClassName.replace(".", File.separator) + ".class"));
    ClassReader crTarget = new ClassReader(fTargetClass);
    ClassNode cnTarget = new ClassNode();
    crTarget.accept(cnTarget, 0);/*w  w w  . ja va  2s  . co m*/
    ClassWriter cw = new ClassWriter(0);
    ExceptionClassProxy ecc = new ExceptionClassProxy(cw, cnTarget.version, cnTarget.name, cnTarget.superName);
    cnTarget.accept(ecc);

    fTargetClass.close();
    FileOutputStream fos = new FileOutputStream(
            new File(buildDir, targetClassName.replace(".", File.separator) + ".class"));
    fos.write(cw.toByteArray());
    fos.close();

}

From source file:com.liferay.portal.nio.intraband.proxy.IntrabandProxyUtil.java

License:Open Source License

protected static Class<?> toClass(ClassNode classNode, ClassLoader classLoader) {

    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);

    classNode.accept(classWriter);

    byte[] data = classWriter.toByteArray();

    try {/*from w ww.  ja  v a  2s.c o m*/
        if (PropsValues.INTRABAND_PROXY_DUMP_CLASSES_ENABLED) {
            File classFile = new File(_DUMP_DIR, classNode.name.concat(".class"));

            FileUtil.write(classFile, data);

            if (_log.isInfoEnabled()) {
                _log.info("Dumpped class " + classFile.getAbsolutePath());
            }
        }

        return (Class<?>) _defineClassMethod.invoke(classLoader,
                StringUtil.replace(classNode.name, CharPool.SLASH, CharPool.PERIOD), data, 0, data.length);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}