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:cn.edu.sjtu.se.yudiZheng.UnreachableCodeDetector.java

License:Open Source License

public void visitClassContext(ClassContext classContext) {

    ClassReader cr = new ClassReader(classContext.getJavaClass().getBytes());
    ClassNode cn = new ClassNode();
    cr.accept(cn, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);

    for (MethodNode method : (List<MethodNode>) cn.methods) {

        CtrlFlowGraph cfg = CtrlFlowGraph.build(method);
        List<BasicBlock> connected = new LinkedList<BasicBlock>(cfg.getNodes());

        connected.remove(cfg.getBB(method.instructions.getFirst()));

        for (TryCatchBlockNode tcb : (List<TryCatchBlockNode>) method.tryCatchBlocks) {
            connected.remove(cfg.getBB(tcb.handler));
        }//from   w  w w  . j a  v  a  2s .c o m

        for (BasicBlock bb : connected) {

            if (bb.getPredecessors().size() == 0) {
                reporter.reportBug(new BugInstance(this, "UNREACHABLE", NORMAL_PRIORITY).addClass(cn).addMethod(
                        cn.name, method.name, method.desc, (method.access & Opcodes.ACC_STATIC) != 0));
            }
        }
    }
}

From source file:co.paralleluniverse.common.reflection.ASMUtil.java

License:Open Source License

public static ClassNode getClassNode(String className, boolean skipCode, ClassLoader cl) throws IOException {
    if (className == null)
        return null;
    try (InputStream is = cl.getResourceAsStream(classToResource(className))) {
        if (is == null)
            throw new IOException("Resource " + classToResource(className) + " not found.");
        ClassReader cr = new ClassReader(is);
        ClassNode cn = new ClassNode();
        cr.accept(cn, ClassReader.SKIP_DEBUG | (skipCode ? 0 : ClassReader.SKIP_CODE));
        return cn;
    }//from  w  w  w  .j a  va  2  s.co  m
}

From source file:co.paralleluniverse.common.reflection.ASMUtil.java

License:Open Source License

public static ClassNode getClassNode(File classFile, boolean skipCode) throws IOException {
    if (classFile == null)
        return null;
    if (!classFile.exists())
        return null;
    try (InputStream is = new FileInputStream(classFile)) {
        ClassReader cr = new ClassReader(is);
        ClassNode cn = new ClassNode();
        cr.accept(cn, ClassReader.SKIP_DEBUG | (skipCode ? 0 : ClassReader.SKIP_CODE));
        return cn;
    }/*w w  w  .j  a  va2  s.  co  m*/
}

From source file:com.android.apigenerator.AndroidJarReader.java

License:Apache License

public Map<String, ApiClass> getClasses() {
    HashMap<String, ApiClass> map = new HashMap<String, ApiClass>();

    // Get all the android.jar. They are in platforms-#
    int apiLevel = 0;
    while (true) {
        apiLevel++;/*from w  ww .j a v  a2  s .com*/
        try {
            File jar = new File(mSdkFolder, "platforms/android-" + apiLevel + "/android.jar");
            if (jar.exists() == false) {
                System.out.println("Last API level found: " + (apiLevel - 1));
                break;
            }

            FileInputStream fis = new FileInputStream(jar);
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry entry = zis.getNextEntry();
            while (entry != null) {
                String name = entry.getName();

                if (name.endsWith(".class")) {

                    int index = 0;
                    do {
                        int size = zis.read(BUFFER, index, BUFFER.length - index);
                        if (size >= 0) {
                            index += size;
                        } else {
                            break;
                        }
                    } while (true);

                    byte[] b = new byte[index];
                    System.arraycopy(BUFFER, 0, b, 0, index);

                    ClassReader reader = new ClassReader(b);
                    ClassNode classNode = new ClassNode();
                    reader.accept(classNode, 0 /*flags*/);

                    if (classNode != null) {
                        ApiClass theClass = addClass(map, classNode.name, apiLevel);

                        // super class
                        if (classNode.superName != null) {
                            theClass.addSuperClass(classNode.superName, apiLevel);
                        }

                        // interfaces
                        for (Object interfaceName : classNode.interfaces) {
                            theClass.addInterface((String) interfaceName, apiLevel);
                        }

                        // fields
                        for (Object field : classNode.fields) {
                            FieldNode fieldNode = (FieldNode) field;
                            if ((fieldNode.access & Opcodes.ACC_PRIVATE) != 0) {
                                continue;
                            }
                            if (fieldNode.name.startsWith("this$") == false
                                    && fieldNode.name.equals("$VALUES") == false) {
                                theClass.addField(fieldNode.name, apiLevel);
                            }
                        }

                        // methods
                        for (Object method : classNode.methods) {
                            MethodNode methodNode = (MethodNode) method;
                            if ((methodNode.access & Opcodes.ACC_PRIVATE) != 0) {
                                continue;
                            }
                            if (methodNode.name.equals("<clinit>") == false) {
                                theClass.addMethod(methodNode.name + methodNode.desc, apiLevel);
                            }
                        }
                    }
                }
                entry = zis.getNextEntry();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    postProcessClasses(map);

    return map;
}

From source file:com.android.apigenerator.enumfix.AndroidJarReader.java

License:Apache License

public Map<String, ApiClass> getEnumClasses() {
    HashMap<String, ApiClass> map = new HashMap<String, ApiClass>();

    // Get all the android.jar. They are in platforms-#
    for (int apiLevel = 1; apiLevel <= MAX_API; apiLevel++) {
        try {/*from w ww  . j a v a2  s  . c om*/
            File jar = new File(mSdkFolder, "platforms/android-" + apiLevel + "/android.jar");
            if (jar.exists() == false) {
                System.err.println("Missing android.jar for API level " + apiLevel);
                continue;
            }

            FileInputStream fis = new FileInputStream(jar);
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry entry = zis.getNextEntry();
            while (entry != null) {
                String name = entry.getName();

                if (name.endsWith(".class")) {

                    int index = 0;
                    do {
                        int size = zis.read(BUFFER, index, BUFFER.length - index);
                        if (size >= 0) {
                            index += size;
                        } else {
                            break;
                        }
                    } while (true);

                    byte[] b = new byte[index];
                    System.arraycopy(BUFFER, 0, b, 0, index);

                    ClassReader reader = new ClassReader(b);
                    ClassNode classNode = new ClassNode();
                    reader.accept(classNode, 0 /*flags*/);

                    if (classNode != null && classNode.superName != null
                            && classNode.superName.equals("java/lang/Enum")) {

                        ApiClass theClass = addClass(map, classNode.name, apiLevel);
                        theClass.addSuperClass("java/lang/Enum", apiLevel);

                        List fields = classNode.fields;
                        for (Object f : fields) {
                            FieldNode fnode = (FieldNode) f;
                            if (fnode.desc.substring(1, fnode.desc.length() - 1).equals(classNode.name)) {
                                theClass.addField(fnode.name, apiLevel);
                            }
                        }
                    }
                }
                entry = zis.getNextEntry();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    return map;
}

From source file:com.android.build.gradle.internal.incremental.AsmUtils.java

License:Apache License

@NonNull
public static ClassNode readClass(@NonNull ClassReader classReader) {
    ClassNode node = new ClassNode();
    classReader.accept(node, ClassReader.EXPAND_FRAMES);
    return node;//from  ww  w . j a va 2  s.  com
}

From source file:com.android.build.gradle.internal.incremental.AsmUtils.java

License:Apache License

@NonNull
public static ClassNode readClass(ClassLoader classLoader, String className) throws IOException {
    try (InputStream is = classLoader.getResourceAsStream(className + ".class")) {
        if (is == null) {
            throw new IOException("Failed to find byte code for " + className);
        }//from   www  .jav  a 2 s .co m

        ClassReader parentClassReader = new ClassReader(is);
        ClassNode node = new ClassNode();
        parentClassReader.accept(node, ClassReader.EXPAND_FRAMES);
        return node;
    }
}

From source file:com.android.build.gradle.internal.incremental.IncrementalSupportVisitorTest.java

License:Apache License

@NonNull
static ClassNode parseClass(@NonNull Class<?> clazz) throws IOException {
    // parse the class with asm.
    Type type = Type.getType(clazz);
    ClassReader cr = new ClassReader(type.getInternalName());
    ClassNode classNode = new ClassNode();
    cr.accept(classNode, 0);//w ww.  j  ava 2 s .c  om
    return classNode;
}

From source file:com.android.build.gradle.internal.incremental.InstantRunMethodVerifierTest.java

License:Apache License

@Before
public void setup() throws IOException {
    ClassReader classReader = new ClassReader(InstantRunMethodVerifierTarget.class.getName());
    targetClass = new ClassNode();
    classReader.accept(targetClass, ClassReader.SKIP_FRAMES);
}

From source file:com.android.build.gradle.internal2.incremental.IncrementalVisitor.java

License:Apache License

@Nullable
public static File instrumentClass(@NonNull File inputRootDirectory, @NonNull File inputFile,
        @NonNull File outputDirectory, @NonNull VisitorBuilder visitorBuilder) throws IOException {

    byte[] classBytes;
    String path = FileUtils.relativePath(inputFile, inputRootDirectory);
    if (!inputFile.getPath().endsWith(SdkConstants.DOT_CLASS)) {
        File outputFile = new File(outputDirectory, path);
        Files.createParentDirs(outputFile);
        Files.copy(inputFile, outputFile);
        return outputFile;
    }/*from   w  w w . jav a2 s  .  c  o  m*/
    classBytes = Files.toByteArray(inputFile);
    ClassReader classReader = new ClassReader(classBytes);
    // override the getCommonSuperClass to use the thread context class loader instead of
    // the system classloader. This is useful as ASM needs to load classes from the project
    // which the system classloader does not have visibility upon.
    // TODO: investigate if there is not a simpler way than overriding.
    ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES) {
        @Override
        protected String getCommonSuperClass(final String type1, final String type2) {
            Class<?> c, d;
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            try {
                c = Class.forName(type1.replace('/', '.'), false, classLoader);
                d = Class.forName(type2.replace('/', '.'), false, classLoader);
            } catch (Exception e) {
                throw new RuntimeException(e.toString());
            }
            if (c.isAssignableFrom(d)) {
                return type1;
            }
            if (d.isAssignableFrom(c)) {
                return type2;
            }
            if (c.isInterface() || d.isInterface()) {
                return "java/lang/Object";
            } else {
                do {
                    c = c.getSuperclass();
                } while (!c.isAssignableFrom(d));
                return c.getName().replace('.', '/');
            }
        }
    };

    ClassNode classNode = new ClassNode();
    classReader.accept(classNode, ClassReader.EXPAND_FRAMES);

    // when dealing with interface, we just copy the inputFile over without any changes unless
    // this is a package private interface.
    AccessRight accessRight = AccessRight.fromNodeAccess(classNode.access);
    File outputFile = new File(outputDirectory, path);
    if ((classNode.access & Opcodes.ACC_INTERFACE) != 0) {
        if (visitorBuilder.getOutputType() == OutputType.INSTRUMENT) {
            // don't change the name of interfaces.
            Files.createParentDirs(outputFile);
            if (accessRight == AccessRight.PACKAGE_PRIVATE) {
                classNode.access = classNode.access | Opcodes.ACC_PUBLIC;
                classNode.accept(classWriter);
                Files.write(classWriter.toByteArray(), outputFile);
            } else {
                // just copy the input file over, no change.
                Files.write(classBytes, outputFile);
            }
            return outputFile;
        } else {
            return null;
        }
    }

    List<ClassNode> parentsNodes = parseParents(inputFile, classNode);

    // if we could not determine the parent hierarchy, disable instant run.
    if (parentsNodes.isEmpty() || isPackageInstantRunDisabled(inputFile, classNode)) {
        if (visitorBuilder.getOutputType() == OutputType.INSTRUMENT) {
            Files.createParentDirs(outputFile);
            Files.write(classBytes, outputFile);
            return outputFile;
        } else {
            return null;
        }
    }

    outputFile = new File(outputDirectory, visitorBuilder.getMangledRelativeClassFilePath(path));
    Files.createParentDirs(outputFile);
    IncrementalVisitor visitor = visitorBuilder.build(classNode, parentsNodes, classWriter);
    classNode.accept(visitor);

    Files.write(classWriter.toByteArray(), outputFile);
    return outputFile;
}