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.codename1.tools.ikvm.Parser.java

/**
 * Parses an InputStream containing a class.
 * @param input The input stream with a class.
 * @return If a transformation occurred, the bytes for the changed class will be returned.  Otherwise null will be returned.
 * @throws Exception //from   w  ww.  j  av  a2  s .c om
 */
public static byte[] parse(InputStream input, ClassLoader classLoader) throws Exception {
    ClassReader r = new ClassReader(input);
    Parser p = new Parser();
    //ClassWriter w = new ClassWriter(r, 0);
    ClassNode classNode = new ClassNode();
    //p.classNode = classNode;

    r.accept(classNode, 0);
    //r.accept(p, ClassReader.EXPAND_FRAMES)

    List<MethodNode> methodsToAdd = new ArrayList<MethodNode>();
    int methodNum = 0;
    for (Object o : classNode.methods) {
        methodNum++;
        MethodNode methodNode = (MethodNode) o;
        boolean synchronizedMethod = (methodNode.access & Opcodes.ACC_SYNCHRONIZED) == Opcodes.ACC_SYNCHRONIZED;
        if (synchronizedMethod) {
            // Check for a try statement
            final boolean[] tryCatchFound = new boolean[1];
            //System.out.println("Found sync method "+methodNode.name+". Checking for try blocks");
            methodNode.accept(new MethodVisitor(Opcodes.ASM5) {

                @Override
                public void visitTryCatchBlock(Label label, Label label1, Label label2, String string) {
                    tryCatchFound[0] = true;
                }

            });
            if (!tryCatchFound[0]) {
                continue;
            }

            //System.out.println("Instructions: "+Arrays.toString(methodNode.instructions.toArray()));

            System.out.println("Transforming method " + methodNode.name + " of class " + classNode.name);
            MethodDescriptor md = new MethodDescriptor(methodNode.access, methodNode.name, methodNode.desc);
            //methodNode.access = methodNode.access & ~Opcodes.ACC_SYNCHRONIZED;
            String privateMethodName = (md.constructor ? "___cn1init__" : methodNode.name) + "___cn1sync"
                    + (methodNum);
            MethodNode syncMethod = new MethodNode(methodNode.access, methodNode.name, methodNode.desc,
                    methodNode.signature,
                    (String[]) methodNode.exceptions.toArray(new String[methodNode.exceptions.size()]));

            methodNode.name = privateMethodName;
            methodNode.access = (methodNode.access | Opcodes.ACC_PRIVATE) & ~Opcodes.ACC_PUBLIC
                    & ~Opcodes.ACC_PROTECTED & ~Opcodes.ACC_SYNCHRONIZED;
            LabelNode startLabel = new LabelNode();
            syncMethod.instructions.add(startLabel);
            LabelNode endLabel = new LabelNode();

            int argIndex = 0;
            if (!md.staticMethod) {
                //System.out.println(methodNode.name + " is not static");
                syncMethod.localVariables.add(new LocalVariableNode("arg" + (argIndex),
                        "L" + classNode.name + ";", null, startLabel, endLabel, argIndex));
                syncMethod.instructions.add(new VarInsnNode(Opcodes.ALOAD, argIndex++));

            }

            for (ByteCodeMethodArg arg : md.arguments) {
                char typeChar = arg.type;
                if (arg.dim > 0) {
                    typeChar = 'L';
                }
                if (arg.desc == null || arg.desc.isEmpty()) {
                    throw new RuntimeException(
                            "Invalid arg description for arg " + argIndex + " of method " + methodNode.name);
                }
                syncMethod.localVariables.add(new LocalVariableNode("arg" + (argIndex), arg.desc, arg.desc,
                        startLabel, endLabel, argIndex));

                switch (typeChar) {
                case 'L':
                    syncMethod.instructions.add(new VarInsnNode(Opcodes.ALOAD, argIndex++));
                    //syncMethod.localVariables.add(new LocalVariableNode("arg"+(argIndex-1), arg.desc, null, startLabel, endLabel, argIndex-1));
                    break;
                case 'S':
                case 'I':
                case 'B':
                case 'Z':
                case 'C':
                    syncMethod.instructions.add(new VarInsnNode(Opcodes.ILOAD, argIndex++));
                    break;
                case 'J':
                    syncMethod.instructions.add(new VarInsnNode(Opcodes.LLOAD, argIndex++));
                    argIndex++; // arg index increments 2 for double size args
                    break;
                case 'F':
                    syncMethod.instructions.add(new VarInsnNode(Opcodes.FLOAD, argIndex++));
                    break;
                case 'D':
                    syncMethod.instructions.add(new VarInsnNode(Opcodes.DLOAD, argIndex++));
                    argIndex++;// arg index increments 2 for double size args
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported argument type " + arg.type);
                }
            }

            if (md.staticMethod) {
                syncMethod.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, classNode.name,
                        privateMethodName, methodNode.desc));
            } else {
                syncMethod.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, classNode.name,
                        privateMethodName, methodNode.desc));
            }

            if (md.returnType != null) {
                char typeChar = md.returnType.type;
                if (md.returnType.dim > 0) {
                    typeChar = 'L';
                }
                switch (typeChar) {
                case 'L':
                    syncMethod.instructions.add(new InsnNode(Opcodes.ARETURN));
                    break;
                case 'S':
                case 'I':
                case 'B':
                case 'Z':
                case 'C':
                    syncMethod.instructions.add(new InsnNode(Opcodes.IRETURN));
                    break;
                case 'J':
                    syncMethod.instructions.add(new InsnNode(Opcodes.LRETURN));
                    break;
                case 'F':
                    syncMethod.instructions.add(new InsnNode(Opcodes.FRETURN));
                    break;
                case 'D':
                    syncMethod.instructions.add(new InsnNode(Opcodes.DRETURN));
                    break;
                case 'V':
                    syncMethod.instructions.add(new InsnNode(Opcodes.RETURN));
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported argument type " + md.returnType.type);
                }
            } else {
                syncMethod.instructions.add(new InsnNode(Opcodes.DRETURN));
            }

            syncMethod.instructions.add(endLabel);

            methodsToAdd.add(syncMethod);

        }
    }
    if (!methodsToAdd.isEmpty()) {
        changed = true;
        System.out
                .println("Transforming " + methodsToAdd.size() + " synchronized methods in " + classNode.name);
        classNode.methods.addAll(methodsToAdd);
        ClassWriter w = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        classNode.accept(w);
        byte[] out = w.toByteArray();
        if (verify) {
            verify(out, classLoader);
        }
        return out;
    } else {
        ClassWriter w = new ClassWriter(0);
        classNode.accept(w);
        byte[] out = w.toByteArray();
        return out;
    }

}

From source file:com.dank.util.io.Fetcher.java

License:Open Source License

public static File getFile() {
    ConfigCrawler crawler = new ConfigCrawler();
    try {//from  w ww  .  j  ava  2 s .  c om
        crawler.crawl();

        JarInputStream input = crawler.stream();
        String hash = Integer.toString(input.getManifest().hashCode());
        int revision = -1;

        JarEntry entry;
        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().equals("client.class")) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] bytes = new byte[4096];
                int read;
                while ((read = input.read(bytes, 0, bytes.length)) > -1)
                    output.write(bytes, 0, read);

                ClassReader reader = new ClassReader(output.toByteArray());
                ClassNode node = new ClassNode();
                reader.accept(node, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
                revision = getRevision(node);
            }
        }
        input.close();

        if (!Files.exists(Paths.get("").resolve("./jars/" + revision + "/" + hash + "/"))) {
            Files.createDirectories(Paths.get("").resolve("./jars/" + revision + "/"));
            crawler.download(Paths.get("").resolve("./jars/" + revision + "/").toString());
        }

        System.out.println(
                "Fetched gamepack " + revision + "(" + hash + ") with " + crawler.size() + " parameter(s).");
        System.out.println();

        return Paths.get("").resolve("./jars/" + revision + "/gamepack.jar").toFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new File("");
}

From source file:com.develorium.metracer.dynamic.MetracerClassFileTransformer.java

License:Apache License

private InstrumentClassResult instrumentClass(byte theBytecode[], ClassLoader theLoader, Patterns thePatterns) {
    ClassReader reader = new ClassReader(theBytecode);
    ClassNode parsedClass = new ClassNode();
    reader.accept(parsedClass, 0);// w ww  . j a  va2s .co m

    MetracerClassWriter writer = new MetracerClassWriter(reader, theLoader);
    MetracerClassVisitor visitor = new MetracerClassVisitor(writer, theLoader, thePatterns, parsedClass);
    reader.accept(visitor, ClassReader.EXPAND_FRAMES);

    InstrumentClassResult rv = new InstrumentClassResult();
    rv.isChanged = visitor.getIsChanged();
    rv.bytecode = visitor.getIsChanged() ? writer.toByteArray() : theBytecode;
    return rv;
}

From source file:com.develorium.metracer.statik.MetracerClassFileTransformer.java

License:Apache License

private InstrumentClassResult instrumentClass(byte theBytecode[], ClassLoader theLoader) {
    ClassReader reader = new ClassReader(theBytecode);
    ClassNode parsedClass = new ClassNode();
    reader.accept(parsedClass, 0);/*from   w w w. j  a va2  s . co  m*/

    MetracerClassWriter writer = new MetracerClassWriter(reader, theLoader);
    MetracerClassVisitor visitor = new MetracerClassVisitor(writer, theLoader, patterns, parsedClass);
    reader.accept(visitor, ClassReader.EXPAND_FRAMES);

    InstrumentClassResult rv = new InstrumentClassResult();
    rv.bytecode = visitor.getIsChanged() ? writer.toByteArray() : theBytecode;
    rv.hasSlf4jLogger = visitor.getHasSlf4Logger();
    return rv;
}

From source file:com.facebook.buck.android.ClassNodeListSupplier.java

License:Apache License

private void loadClassNodes(JarFile jarFile, ImmutableList.Builder<ClassNode> builder) throws IOException {
    for (JarEntry entry : Collections.list(jarFile.entries())) {
        String name = entry.getName();
        if (entry.isDirectory() || (name == null) || !name.endsWith(".class")) {
            continue;
        }//from w w  w.  j av a2  s.  co m

        ClassNode node = new ClassNode();
        try (InputStream stream = jarFile.getInputStream(entry)) {
            ClassReader reader = new ClassReader(stream);
            reader.accept(node, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
        }
        builder.add(node);
    }
}

From source file:com.facebook.buck.java.abi.AbiClass.java

License:Apache License

public static AbiClass extract(Path pathToJar, String className) throws IOException {
    try (ZipFile zip = new ZipFile(pathToJar.toString())) {
        ZipEntry entry = zip.getEntry(className);
        try (InputStream entryStream = zip.getInputStream(entry)) {
            ClassReader reader = new ClassReader(entryStream);
            ClassNode classNode = new ClassNode();
            reader.accept(classNode, 0);

            return new AbiClass(classNode);
        }// w w w  .j  a  v  a2s  .  c  o m
    }
}

From source file:com.facebook.buck.tools.dxanalysis.DxAnalysisMain.java

License:Apache License

private static ImmutableMap<String, ClassNode> loadAllClasses(String zipFileName) throws IOException {
    ImmutableMap.Builder<String, ClassNode> allClassesBuilder = ImmutableMap.builder();
    try (ZipFile inJar = new ZipFile(zipFileName)) {
        for (ZipEntry entry : Collections.list(inJar.entries())) {
            if (!entry.getName().endsWith(".class")) {
                continue;
            }//from  w  ww  . j ava  2s  .  c o m
            // Skip external libraries.
            if (entry.getName().startsWith("junit/") || entry.getName().startsWith("org/junit/")
                    || entry.getName().startsWith("com/google/common/")) {
                continue;
            }
            byte[] rawClass = ByteStreams.toByteArray(inJar.getInputStream(entry));
            ClassNode klass = new ClassNode();
            new ClassReader(rawClass).accept(klass, ClassReader.EXPAND_FRAMES);
            allClassesBuilder.put(klass.name, klass);
        }
    }
    return allClassesBuilder.build();
}

From source file:com.facebook.infrastructure.continuations.ContinuationClassTransformer.java

License:Apache License

public byte[] transform(ClassLoader classLoader, String className, Class redefiningClass,
        ProtectionDomain domain, byte[] bytes) throws IllegalClassFormatException {
    /*//ww  w.  ja v  a2s .com
     * Use the ASM class reader to see which classes support the Suspendable
     * annotation. If they do then those classes need to have their bytecodes
     * transformed for Continuation support.
     */
    ClassReader classReader = new ClassReader(bytes);
    ClassNode classNode = new ClassNode();
    classReader.accept(classNode, true);
    List<AnnotationNode> annotationNodes = classNode.visibleAnnotations;

    for (AnnotationNode annotationNode : annotationNodes) {
        if (annotationNode.desc.indexOf(ContinuationClassTransformer.targetAnnotation_) != -1) {
            System.out.println("Transforming class " + className);
            bytes = transformer_.transform(bytes);
        }
    }

    return bytes;
}

From source file:com.facebook.swift.codec.internal.compiler.byteCode.ClassDefinition.java

License:Apache License

public ClassNode getClassNode() {
    ClassNode classNode = new ClassNode();
    classNode.version = V1_6;/* www .  jav a 2 s  .  c  o  m*/

    classNode.access = access;

    classNode.name = name;

    classNode.superName = superClass.getClassName();
    for (ParameterizedType interfaceType : interfaces) {
        classNode.interfaces.add(interfaceType.getClassName());
    }

    // add generic signature if super class or any interface is generic
    if (superClass.isGeneric() || any(interfaces, ParameterizedType.isGenericType())) {
        classNode.signature = genericClassSignature(superClass, interfaces);
    }

    for (FieldDefinition field : fields) {
        classNode.fields.add(field.getFieldNode());
    }

    for (MethodDefinition method : methods) {
        classNode.methods.add(method.getMethodNode());
    }

    return classNode;
}

From source file:com.github.fge.grappa.transform.ParserExtensionVerificationTest.java

License:Apache License

public static void verifyIntegrity(String classInternalName, byte[] classCode) {
    Preconditions.checkNotNull(classCode, "classCode");
    ClassNode generatedClassNode = new ClassNode();
    ClassReader classReader = new ClassReader(classCode);
    classReader.accept(generatedClassNode, 0);

    for (Object methodObj : generatedClassNode.methods) {
        AsmTestUtils.verifyMethodIntegrity(classInternalName, (MethodNode) methodObj);
    }/* www.java  2 s  .  com*/
}