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:ca.weblite.mirah.ant.mirrors.ClassReader.java

/**
 * Generates the the mirah mirrors for a specific java source file.  This 
 * file must be a .java file.  It cannot be a directory.
 * //from   w w  w.j  a  va  2  s.  c  o  m
 * @param javaSourceFile
 * @throws IOException 
 */
public void parse() throws IOException {

    File javaSourceFile = sourceFile;
    JavaCompiler compiler = JavacTool.create();
    MyFileObject[] fos = new MyFileObject[] { new MyFileObject(javaSourceFile) };

    JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, Arrays.asList(fos));
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    final Stack<Set<String>> typeParams = new Stack<Set<String>>();
    TreePathScanner scanner;
    scanner = new TreePathScanner() {

        private boolean isGenericType(String type) {
            Stack<Set> desk = new Stack<Set>();
            boolean found = false;
            while (!typeParams.empty()) {
                Set params = typeParams.pop();
                desk.push(params);
                if (params.contains(type)) {
                    found = true;

                    break;
                }

            }
            while (!desk.empty()) {
                typeParams.push(desk.pop());
            }
            return found;
        }

        String formatType(String type) {
            int pos = type.indexOf("<");
            if (pos >= 0) {
                type = type.substring(0, pos);
            }
            if (isGenericType(type)) {
                return "Object";
            }
            return type;
        }

        @Override
        public Object visitCompilationUnit(CompilationUnitTree cut, Object p) {
            PackageScope scope = new PackageScope(scopeStack.peek(), cut.getPackageName().toString());
            scope.addImport(scope.getPackageName() + ".*");
            scope.addImport("java.lang.*");
            scope.addImport("*");
            packageScope = scope;
            scopeStack.push(scope);
            return super.visitCompilationUnit(cut, p);

        }

        @Override
        public Object visitImport(ImportTree it, Object p) {

            String path = it.getQualifiedIdentifier().toString();
            packageScope.addImport(path);

            return super.visitImport(it, p);
        }

        private void decorateClassNode(ClassTree ct, ClassNode classNode) {
            int flags = getFlags(ct.getModifiers().getFlags());
            switch (ct.getKind()) {
            case INTERFACE:
                flags |= Opcodes.ACC_INTERFACE;
                break;

            case ENUM:
                flags |= Opcodes.ACC_ENUM;
                break;

            }
            classNode.access = flags;
            classNode.sourceFile = sourceFile.getPath();
            String extendsClause = "java.lang.Object";
            if (ct.getExtendsClause() != null) {
                extendsClause = ct.getExtendsClause().toString();
            }

            String superPath = scopeStack.peek().resolveName(extendsClause, false);

            ClassIndex.Node superNode = scopeStack.peek().getLoader().find(superPath);

            if (superNode == null) {
                throw new RuntimeException("Failed to find super class " + superPath);
            }

            classNode.superName = superNode.internalName;

            classNode.interfaces = new ArrayList<String>();
            String impl = ct.getImplementsClause().toString();
            if (!"".equals(impl)) {
                String[] interfaces = impl.split(",");
                for (String iface : interfaces) {
                    iface = iface.trim();
                    String ipath = scopeStack.peek().resolveName(iface, false);
                    ClassIndex.Node iNode = scopeStack.peek().getLoader().find(ipath);
                    if (iNode == null) {
                        throw new RuntimeException("Failed to load " + "interface " + ipath);
                    }

                    classNode.interfaces.add(iNode.internalName);
                }
            }
        }

        @Override
        public Object visitClass(ClassTree ct, Object p) {
            ClassScope clsScope = null;
            ClassNode currClassNode = null;
            if (scopeStack.peek() == packageScope) {
                String path = packageScope.getPackageName() + "." + ct.getSimpleName();
                ClassIndex.Node n = packageScope.getLoader().find(path);
                if (n == null) {
                    throw new RuntimeException("Failed to find class " + path);
                }
                node.name = n.internalName;
                currClassNode = node;
                decorateClassNode(ct, node);

                clsScope = new ClassScope(scopeStack.peek(), n);

            } else {
                // This must be an internal class
                ClassNode parentClass = classNodeStack.peek();
                if (parentClass.innerClasses == null) {
                    parentClass.innerClasses = new ArrayList<>();
                }
                String path = scopeStack.peek().resolveName(ct.getSimpleName().toString(), false);

                ClassIndex.Node n = packageScope.getLoader().find(path);
                if (n == null) {
                    throw new RuntimeException("Failed to find class " + path);
                }
                InnerClassNode innerNode = new InnerClassNode(n.internalName, parentClass.name, n.simpleName,
                        getFlags(ct.getModifiers().getFlags()));
                parentClass.innerClasses.add(innerNode);

                ClassNode cls = new ClassNode();
                cls.name = n.internalName;
                cls.outerClass = parentClass.name;

                decorateClassNode(ct, cls);
                clsScope = new ClassScope(scopeStack.peek(), n);
                currClassNode = cls;
            }

            scopeStack.push(clsScope);
            classNodeStack.push(currClassNode);
            Object out = super.visitClass(ct, p);
            classNodeStack.pop();
            scopeStack.pop();

            return out;

        }

        /**
         * Converts modifier flags from Javac Tree into int flags usable in 
         * TypeMirror
         * @param mods
         * @return 
         */
        int getFlags(Set<Modifier> mods) {
            int flags = 0;
            for (Modifier m : mods) {
                switch (m) {
                case ABSTRACT:
                    flags |= Opcodes.ACC_ABSTRACT;
                    break;
                case FINAL:
                    flags |= Opcodes.ACC_FINAL;
                    break;
                case PRIVATE:
                    flags |= Opcodes.ACC_PRIVATE;
                    break;
                case PROTECTED:
                    flags |= Opcodes.ACC_PROTECTED;
                    break;
                case PUBLIC:

                    flags |= Opcodes.ACC_PUBLIC;
                    break;
                case STATIC:
                    flags |= Opcodes.ACC_STATIC;
                    break;
                }
            }

            return flags;
        }

        @Override
        public Object visitVariable(final VariableTree vt, Object p) {
            String typeName = vt.getType().toString();
            String typePath = scopeStack.peek().resolveName(vt.getType().toString(), false);
            String typeDescriptor = scopeStack.peek().resolveName(vt.getType().toString(), true);
            String name = vt.getName().toString();
            int flags = getFlags(vt.getModifiers().getFlags());

            FieldNode fieldNode = new FieldNode(flags, name, typeDescriptor, null, null);

            ClassNode cls = classNodeStack.peek();
            if (cls.fields == null) {
                cls.fields = new ArrayList<FieldNode>();

            }
            cls.fields.add(fieldNode);

            return super.visitVariable(vt, p);
        }

        String generateMethodDescriptor(MethodTree mt) {
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (VariableTree v : mt.getParameters()) {
                String type = scopeStack.peek().resolveName(v.getType().toString(), true);
                sb.append(type);

            }
            sb.append(")");
            String returnType = scopeStack.peek().resolveName(mt.getReturnType().toString(), true);
            sb.append(returnType);

            return sb.toString();
        }

        @Override
        public Object visitMethod(final MethodTree mt, Object p) {

            MethodNode m = new MethodNode();

            int flags = getFlags(mt.getModifiers().getFlags());
            m.access = flags;
            m.desc = generateMethodDescriptor(mt);
            m.name = mt.getName().toString();
            ClassNode cls = classNodeStack.peek();
            if (cls.methods == null) {
                cls.methods = new ArrayList<MethodNode>();
            }
            cls.methods.add(m);

            return mt;
        }
    };
    scanner.scan(asts, null);

}

From source file:ca.weblite.mirah.ant.mirrors.ClassReaderTest.java

@Test
public void testParseClass() throws IOException {
    ClassNode node = new ClassNode();
    ResourceLoader loader = new ResourceLoader();

    System.out.println(System.getProperties());
    loader.setClassPath(System.getProperty("sun.boot.class.path") + File.pathSeparator
            + System.getProperty("java.class.path"));
    loader.setJavaSourcePath("test");
    File file = new File("test/ca/weblite/mirah/ant/mirrors/SampleJavaClass.java");
    loader.fillIndex();/*from  www  . j  a  va  2 s.  co  m*/
    assertTrue("java.util.Map not found", loader.find("java.util.Map") != null);
    ClassReader reader = new ClassReader(node, file, loader);
    reader.parse();

    assertEquals("Class name is incorrect", "ca/weblite/mirah/ant/mirrors/SampleJavaClass", node.name);

    boolean foundSomeField = false;
    boolean foundObjField = false;
    boolean foundPrivateField = false;
    boolean foundPublicField = false;
    boolean foundProtectedField = false;
    for (Object o : node.fields) {
        FieldNode n = (FieldNode) o;
        System.out.println("Field " + n.name + " desc " + n.desc);
        if ("someField".equals(n.name) && "I".equals(n.desc)) {
            foundSomeField = true;
        }
        if ("someObjField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundObjField = true;
            assertTrue("someObjeField is not public", ((n.access & Opcodes.ACC_PUBLIC) == 0));
            assertTrue("someObjeField is not private", ((n.access & Opcodes.ACC_PRIVATE) == 0));
            assertTrue("someObjeField is not protected", ((n.access & Opcodes.ACC_PROTECTED) == 0));
            assertTrue("someObjeField is not abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("someObjeField is not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }

        if ("privateField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundPrivateField = true;
            assertTrue("privateField is not public", ((n.access & Opcodes.ACC_PUBLIC) == 0));
            assertTrue("privateField should be private", ((n.access & Opcodes.ACC_PRIVATE) != 0));
            assertTrue("privateField is not protected", ((n.access & Opcodes.ACC_PROTECTED) == 0));
            assertTrue("privateField is not abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("privateField is not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }

        if ("protectedField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundProtectedField = true;
            assertTrue("protectedField should not public", ((n.access & Opcodes.ACC_PUBLIC) == 0));
            assertTrue("protectedField should not be private", ((n.access & Opcodes.ACC_PRIVATE) == 0));
            assertTrue("protectedField should be protected", ((n.access & Opcodes.ACC_PROTECTED) != 0));
            assertTrue("protectedField should not be abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("protectedField should not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }

        if ("publicField".equals(n.name) && "Ljava/lang/Object;".equals(n.desc)) {
            foundPublicField = true;
            assertTrue("publicField should be public", ((n.access & Opcodes.ACC_PUBLIC) != 0));
            assertTrue("publicField should not be private", ((n.access & Opcodes.ACC_PRIVATE) == 0));
            assertTrue("publicField should not be protected", ((n.access & Opcodes.ACC_PROTECTED) == 0));
            assertTrue("publicField should not be abstract", ((n.access & Opcodes.ACC_ABSTRACT) == 0));
            assertTrue("publicField should not static", ((n.access & Opcodes.ACC_STATIC) == 0));
        }
    }
    assertTrue("someField was not found", foundSomeField);
    assertTrue("object field was not found", foundObjField);
    assertTrue("private field was not found", foundPrivateField);
    assertTrue("public field was not found", foundPublicField);
    assertTrue("protected field was not found", foundProtectedField);
}

From source file:ca.weblite.mirah.ant.mirrors.JavaSourceMirrorLoader.java

@Override
public MirrorType findMirror(Type type) {
    MirrorType out = null;//w  w  w  . j a v a2s . com
    if ((out = super.findMirror(type)) == null) {
        if (type.getSort() == Type.ARRAY) {
            return findArrayMirror(Type.getType(type.getDescriptor().substring(1)));
        }
        String path = null;
        String[] parts = type.getInternalName().split("/");
        int len = parts.length;
        while (path == null && len > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < len; i++) {
                sb.append(parts[i]).append("/");
            }
            String test = sb.substring(0, sb.length() - 1) + ".java";
            path = findInClassPath(test);
        }
        ClassNode node = new ClassNode();

    }
    return out;
}

From source file:ca.weblite.netbeans.mirah.lexer.ClassQuery.java

/**
* Returns a list containing one parameter name for each argument accepted
* by the given constructor. If the class was compiled with debugging
* symbols, the parameter names will match those provided in the Java source
* code. Otherwise, a generic "arg" parameter name is generated ("arg0" for
* the first argument, "arg1" for the second...).
* 
* This method relies on the constructor's class loader to locate the
* bytecode resource that defined its class.
* 
* @param constructor//from  w  w  w .  j av  a 2 s .c  o  m
* @return 
* @throws IOException
*/
public List<String> getParameterNames(Constructor<?> constructor) throws IOException {
    //Class<?> declaringClass = constructor.getDeclaringClass();
    Class declaringClass = cls;
    ClassLoader declaringClassLoader = declaringClass.getClassLoader();

    Type declaringType = Type.getType(declaringClass);
    String constructorDescriptor = Type.getConstructorDescriptor(constructor);
    String url = declaringType.getInternalName() + ".class";

    InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url);
    if (classFileInputStream == null) {
        throw new IllegalArgumentException(
                "The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: "
                        + url + ")");
    }

    ClassNode classNode;
    try {
        classNode = new ClassNode();
        ClassReader classReader = new ClassReader(classFileInputStream);
        classReader.accept(classNode, 0);
    } finally {
        classFileInputStream.close();
    }

    @SuppressWarnings("unchecked")
    List<MethodNode> methods = classNode.methods;
    for (MethodNode method : methods) {
        if (method.name.equals("<init>") && method.desc.equals(constructorDescriptor)) {
            Type[] argumentTypes = Type.getArgumentTypes(method.desc);
            List<String> parameterNames = new ArrayList<String>(argumentTypes.length);

            @SuppressWarnings("unchecked")
            List<LocalVariableNode> localVariables = method.localVariables;
            for (int i = 0; i < argumentTypes.length; i++) {
                // The first local variable actually represents the "this" object
                parameterNames.add(localVariables.get(i + 1).name);
            }

            return parameterNames;
        }
    }

    return null;
}

From source file:ca.weblite.netbeans.mirah.lexer.ClassQuery.java

public static List<String> getParameterNames(Class cls, Method constructor, FileObject fo) throws IOException {
    //Class<?> declaringClass = constructor.getDeclaringClass();
    Class declaringClass = cls;//from w ww.j a  v a2s.  co  m
    ClassLoader declaringClassLoader = declaringClass.getClassLoader();
    if (declaringClassLoader == null) {
        cls = findClass(cls.getName(), fo);
        declaringClassLoader = cls.getClassLoader();

    }
    if (declaringClassLoader == null) {
        return null;
    }
    Type declaringType = Type.getType(declaringClass);
    String constructorDescriptor = Type.getMethodDescriptor(constructor);
    String url = declaringType.getInternalName() + ".class";

    InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url);
    if (classFileInputStream == null) {
        throw new IllegalArgumentException(
                "The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: "
                        + url + ")");
    }

    ClassNode classNode;
    try {
        classNode = new ClassNode();
        ClassReader classReader = new ClassReader(classFileInputStream);
        classReader.accept(classNode, 0);
    } finally {
        classFileInputStream.close();
    }

    @SuppressWarnings("unchecked")
    List<MethodNode> methods = classNode.methods;
    for (MethodNode method : methods) {
        if (method.name.equals(constructor.getName()) && method.desc.equals(constructorDescriptor)) {
            Type[] argumentTypes = Type.getArgumentTypes(method.desc);
            List<String> parameterNames = new ArrayList<String>(argumentTypes.length);
            @SuppressWarnings("unchecked")
            List<LocalVariableNode> localVariables = method.localVariables;
            boolean isStatic = true;
            if (localVariables != null && !localVariables.isEmpty()
                    && localVariables.get(0).name.equals("this")) {
                isStatic = false;
            }
            int offset = isStatic ? 0 : 1;
            for (int i = 0; i < argumentTypes.length; i++) {
                // The first local variable actually represents the "this" object
                try {
                    parameterNames.add(localVariables.get(i + offset).name);
                } catch (NullPointerException npe) {
                    npe.printStackTrace();
                }
            }

            return parameterNames;
        }
    }

    List<String> out = null;
    cls = cls.getSuperclass();
    while (cls != null && out == null) {
        out = getParameterNames(cls, constructor, fo);
        cls = cls.getSuperclass();
    }
    if (out != null) {
        return out;
    }
    return null;
}

From source file:chibill.DeobLoader.loader.Remappers.java

License:Open Source License

private String getFieldType(String owner, String name) {
    if (fieldDescriptions.containsKey(owner)) {
        return fieldDescriptions.get(owner).get(name);
    }// w w w. jav  a2s  .c  o  m
    synchronized (fieldDescriptions) {
        byte[] classBytes = Byte;
        if (classBytes == null) {
            return null;
        }
        ClassReader cr = new ClassReader(classBytes);
        ClassNode classNode = new ClassNode();
        cr.accept(classNode, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
        Map<String, String> resMap = Maps.newHashMap();
        for (FieldNode fieldNode : (List<FieldNode>) classNode.fields) {
            resMap.put(fieldNode.name, fieldNode.desc);
        }
        fieldDescriptions.put(owner, resMap);
        return resMap.get(name);

    }
}

From source file:cl.inria.stiq.db.structure.analysis.Disassembler.java

License:Open Source License

public static DisassembledBehavior disassemble(IBehaviorInfo aBehavior) {
    IClassInfo theClass = aBehavior.getDeclaringType();
    MethodNode theMethodNode = null;/*from w  ww . j  a  va  2 s.  co m*/
    ClassReader cr = null;

    byte[] theBytecode = theClass.getBytecode().instrumented;
    if (theBytecode != null) {
        cr = new ClassReader(theBytecode);
        ClassNode cn = new ClassNode();
        cr.accept(cn, 0);

        // Search the requested method
        String theSig = aBehavior.getDescriptor();
        for (Iterator theIterator = cn.methods.iterator(); theIterator.hasNext();) {
            MethodNode theMethod = (MethodNode) theIterator.next();
            if (!theMethod.name.equals(aBehavior.getName()))
                continue;
            if (!theMethod.desc.equals(theSig))
                continue;
            theMethodNode = theMethod;
            break;
        }
    }

    if (theMethodNode == null)
        return null;

    MyTraceMethodVisitor theVisitor = new MyTraceMethodVisitor(cr);
    theMethodNode.accept(theVisitor);

    return new DisassembledBehavior(aBehavior, theVisitor.getInstructions());

}

From source file:Client.JClassPatcher.java

License:Open Source License

public byte[] patch(byte[] data) {
    ClassReader reader = new ClassReader(data);
    ClassNode node = new ClassNode();
    reader.accept(node, ClassReader.SKIP_DEBUG);

    if (node.name.equals("ua"))
        patchRenderer(node);/* w w  w. j  ava 2  s.co m*/
    else if (node.name.equals("e"))
        patchApplet(node);
    else if (node.name.equals("qa"))
        patchMenu(node);
    else if (node.name.equals("m"))
        patchData(node);
    else if (node.name.equals("client"))
        patchClient(node);
    else if (node.name.equals("f"))
        patchRandom(node);

    // Patch applied to all classes
    patchGeneric(node);

    if (Settings.DISASSEMBLE) {
        Logger.Info("Disassembling file: " + node.name + ".class");
        dumpClass(node);
    }

    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    node.accept(writer);
    return writer.toByteArray();
}

From source file:Client.RSC_Recovery.java

License:Open Source License

public static void main(String[] args) {
    Settings.initDir();/*from   w w w.ja  va  2s  . c o m*/

    File folder = new File(Settings.Dir.CACHE);
    File[] files = folder.listFiles();

    File manifest = new File("recovery/META-INF/MANIFEST.MF");
    BufferedWriter writer = null;

    try {
        writer = new BufferedWriter(new FileWriter(manifest));
        writer.write("Manifest-Version: 1.0\n");
        writer.write("\n");
    } catch (Exception e) {
    }

    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        String filename = file.getName();
        String class_name = "null";
        String sha_digest = "null";

        sha_digest = DatatypeConverter.printBase64Binary(Util.hexStringByte(filename));

        try {
            byte[] data = Files.readAllBytes(file.toPath());
            ClassReader reader = new ClassReader(data);
            ClassNode node = new ClassNode();
            reader.accept(node, ClassReader.SKIP_DEBUG);
            class_name = node.name + ".class";

            File dump = new File("recovery/" + class_name);
            Files.write(dump.toPath(), data);

            Logger.Info("Filename: " + filename);
            Logger.Info("Class Name: " + class_name);
            Logger.Info("SHA1-Digest: " + sha_digest);

            writer.write("Name: " + class_name + "\n");
            writer.write("SHA1-Digest: " + sha_digest + "\n");
            writer.write("\n");
        } catch (Exception e) {
            Logger.Error("Failed to recover '" + filename + "'");
        }
    }

    try {
        writer.close();
    } catch (Exception e) {
    }
}

From source file:clientapi.load.ClientTransformer.java

License:Apache License

/**
 * Creates a {@code ClassNode} from specified bytecode
 *
 * @param bytecode Class bytecode/*from ww  w.  jav  a2 s .co m*/
 * @return ClassNode
 */
private ClassNode getClassNode(byte[] bytecode) {
    if (bytecode == null)
        return null;

    ClassNode cn = new ClassNode();
    new ClassReader(bytecode).accept(cn, 0);
    return cn;
}