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:pt.ist.esw.advice.ProcessAnnotations.java

License:Open Source License

public ProcessAnnotations(ProgramArgs args) {
    this.args = args;
    annotation = Type.getType(args.annotationClass);
    annotationInstance = Type//w w  w  . j  a va  2s  . c o  m
            .getObjectType(GenerateAnnotationInstance.getAnnotationInstanceName(args.annotationClass));

    Map<String, Object> annotationElements = new HashMap<String, Object>();
    for (java.lang.reflect.Method element : args.annotationClass.getDeclaredMethods()) {
        if (element.getReturnType().isArray()) {
            throw new Error("FIXME: Annotations containing arrays are not yet supported");
        }
        Object defaultValue = element.getDefaultValue();
        if (defaultValue instanceof Class) {
            defaultValue = Type.getType((Class<?>) defaultValue);
        }
        annotationElements.put(element.getName(), defaultValue);
    }
    defaultAnnotationElements = Collections.unmodifiableMap(annotationElements);

    try {
        InputStream is = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(annotationInstance.getInternalName() + ".class");
        ClassReader cr = new ClassReader(is);
        ClassNode cNode = new ClassNode();
        cr.accept(cNode, 0);
        annotationFields = cNode.fields != null ? cNode.fields : Collections.<FieldNode>emptyList();

        StringBuffer ctorDescriptor = new StringBuffer("(");
        for (FieldNode field : annotationFields) {
            ctorDescriptor.append(field.desc);
        }
        ctorDescriptor.append(")V");
        annotationInstanceCtorDesc = ctorDescriptor.toString();
    } catch (IOException e) {
        throw new RuntimeException(
                "Error opening " + annotationInstance + " class. Have you run GenerateAnnotationInstance?", e);
    }
}

From source file:rubah.bytecode.transformers.ProcessUpdateClass.java

License:Open Source License

public static Map<String, MethodNode> getMethodNodeIndex(byte[] bytecode) {
    Map<String, MethodNode> methodNodeIndex = new HashMap<String, MethodNode>();
    ClassNode classNode = new ClassNode();
    new ClassReader(bytecode).accept(classNode, 0);
    for (Object obj : classNode.methods) {
        MethodNode mn = (MethodNode) obj;
        methodNodeIndex.put(mn.name + mn.desc, mn);
    }//from   w w w.ja  va  2  s .  c o m

    return methodNodeIndex;
}

From source file:sidechecker.SideCheckerTransformer.java

public void CheckClassForProperSiding(String s, String s2, byte[] bytes) {
    if (needsInit) {
        init();/*  ww w.j av a2  s  .  c  o  m*/
    }

    if (s == null || bytes == null) //should never happen
        return;

    for (String exception : exceptions) {
        if (s.startsWith(exception))
            return;
    }

    if (filter != null) {
        if (!s.startsWith(filter)) // basic hack to allow users to filter out other mods
            return;
    } else {
        boolean flag = false; // is the class from a 'directory' class
        final String replace = s.replace('.', '\\') + ".class";
        for (File f : files) {
            File t = new File(f, replace);
            if (t.exists()) {
                flag = true;
                break;
            }
        }

        if (!flag)
            return;
    }

    ClassNode classNode = new ClassNode();
    ClassReader reader = new ClassReader(bytes);

    reader.accept(classNode, 0);

    curClass = s;
    curFile = classNode.sourceFile;
    curMethod = "";

    ClassInfo.registerClass(s, bytes);

    if (hasClientAnnotation(classNode.visibleAnnotations))
        return; // class is client-side and has a license to be so

    // inner class handling
    if (classNode.outerClass != null) {
        if (classNode.outerMethod != null && classNode.outerMethodDesc != null) {
            if (ClassInfo.hasClientMethod(classNode.outerClass, classNode.outerMethod,
                    classNode.outerMethodDesc))
                return;
        } else if (ClassInfo.isClientClass(classNode.outerClass)) {
            return;
        }
    }

    if (classNode.superName != null && ClassInfo.isClientClass(classNode.superName)) {
        logger.info("----------------------------------------------------------------");
        logger.info("Error: Class " + s + " extends client-side class " + classNode.superName
                + " but does not include annotation");
        logger.info(log("Class: " + s, "class", 1));
        logger.info("----------------------------------------------------------------");
        if (crashOnSeriousError)
            throwException();

        return;
    }

    for (String interfaces : classNode.interfaces) {
        if (ClassInfo.isClientClass(interfaces)) {
            logger.info("----------------------------------------------------------------");
            logger.info("Error: Class " + s + " extends client-side class " + classNode.superName
                    + " but does not include annotation");
            logger.info(log("Class: " + s, "class", 1));
            logger.info("----------------------------------------------------------------");
            if (crashOnSeriousError)
                throwException();

            return;
        }
    }

    for (MethodNode method : classNode.methods) {
        curMethod = method.name;
        if (shouldProcess(method.visibleAnnotations)) {
            if (ClassInfo.hasClientMethod(classNode.superName, method.name, method.desc)) {
                int line = -1;
                for (AbstractInsnNode instruction : method.instructions.toArray()) {
                    if (instruction.getType() == AbstractInsnNode.LINE) {
                        line = ((LineNumberNode) instruction).line;
                        break;
                    }
                }
                warnings.add(log("Method: ", method.name, line));
            }

            method.accept(ClientCheckerMethodVisitor.instance);
        }
    }

    for (FieldNode fieldNode : classNode.fields) {
        if (!hasClientAnnotation(fieldNode.visibleAnnotations)) {
            if (fieldNode.desc.startsWith("L"))
                if (ClassInfo.isClientClass(stripToType(fieldNode.desc))) {
                    errors.add(log("Field Type: ", fieldNode.desc, 1));
                }
        }
    }

    boolean crash = false;

    if (!warnings.isEmpty() || !errors.isEmpty()) {
        logger.info("----------------------------------------------------------------");
        if (!warnings.isEmpty()) {
            logger.info("Warning: Class " + s
                    + " overrides client-side methods and does not include the SideOnly annotation");
            for (String method : warnings) {
                logger.info(method);
            }

            if (crashOnWarning)
                crash = true;
            warnings.clear();
        }

        if (!errors.isEmpty()) {
            logger.info("Error: Class " + s
                    + " has references to client-side code in non-client-side fields/methods");

            for (String problem : errors) {
                logger.info(problem);
            }
            errors.clear();

            if (crashOnSeriousError)
                crash = true;
        }
        logger.info("----------------------------------------------------------------");
    }

    if (crash)
        throwException();
}

From source file:test.compile.TestMeasure.java

License:Apache License

public static void main(String[] args) throws Exception {

    InputStream in = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("test/compile/Logic2.class");
    ClassReader cr = new ClassReader(in);
    ClassNode cn = new ClassNode();
    cr.accept(cn, 0);//from w w  w.j a v a2  s. co m

    RandomAccessFile ra = new RandomAccessFile(Thread.currentThread().getContextClassLoader()
            .getResource("test/compile/Logic2.class").getFile().toString(), "r");
    byte[] bbb = new byte[(int) ra.length()];
    ra.read(bbb);
    ra.close();

    ClassReader cr2 = new ClassReader(bbb);
    ClassNode cn2 = new ClassNode();
    cr2.accept(cn2, 0);

    MeasureHelper.instrumentCheckPoint("classname", cn);
    byte[] bb = GemliteHelper.classNodeToBytes(cn);
    GemliteHelper.checkAsmBytes(bb, "d:/tmp/measure.check.log");

    byte[] bb2 = GemliteHelper.classNodeToBytes(cn2);
    GemliteHelper.checkAsmBytes(bb2, "d:/tmp/before.check.log");
}

From source file:the.bytecode.club.bootloader.resource.ExternalLibrary.java

License:Open Source License

protected ClassNode create(byte[] b) {
    ClassReader cr = new ClassReader(b);
    ClassNode cn = new ClassNode();
    cr.accept(cn, 0);/*  w ww .  j ava 2 s. c  om*/
    return cn;
}

From source file:the.bytecode.club.bytecodeviewer.FileContainer.java

License:Open Source License

public ClassNode getClassNode(String name) {
    if (!classes.containsKey(name)) {
        byte[] bytes = files.get(name + ".class");
        if (bytes != null) {
            ClassReader reader = new ClassReader(bytes);
            ClassNode classNode = new ClassNode();
            reader.accept(classNode, ClassReader.EXPAND_FRAMES);
            classes.put(name, classNode);
        }/*  ww w .j a  v  a 2  s  .  c  om*/
    }
    return classes.get(name);
}

From source file:the.bytecode.club.bytecodeviewer.JarUtils.java

License:Open Source License

/**
 * Creates a new ClassNode instances from the provided byte[]
 * @param bytez the class file's byte[]/*from w  ww. j  av  a 2s.co  m*/
 * @return the ClassNode instance
 */
public static ClassNode getNode(final byte[] bytez) {
    ClassReader cr = new ClassReader(bytez);
    ClassNode cn = new ClassNode();
    try {
        cr.accept(cn, ClassReader.EXPAND_FRAMES);
    } catch (Exception e) {
        try {
            cr.accept(cn, ClassReader.SKIP_FRAMES);
        } catch (Exception e2) {
            e2.printStackTrace(); //just skip it
        }
    }
    cr = null;
    return cn;
}

From source file:the.bytecode.club.bytecodeviewer.obfuscators.mapping.Refactorer.java

License:Open Source License

public void run() {
    if (getHooks() == null)
        return;//from w  w  w.  ja  v a  2  s  .c  o  m

    RefactorMapper mapper = new RefactorMapper(getHooks());
    Map<String, ClassNode> refactored = new HashMap<>();
    for (ClassNode cn : BytecodeViewer.getLoadedClasses()) {
        String oldName = cn.name;
        ClassReader cr = new ClassReader(getClassNodeBytes(cn));
        ClassWriter cw = new ClassWriter(cr, 0);
        RemappingClassAdapter rca = new RemappingClassAdapter(cw, mapper);
        cr.accept(rca, ClassReader.EXPAND_FRAMES);
        cr = new ClassReader(cw.toByteArray());
        cn = new ClassNode();
        cr.accept(cn, 0);
        refactored.put(oldName, cn);
    }
    /*for (Map.Entry<String, ClassNode> factor : refactored.entrySet()) {
    BytecodeViewer.relocate(factor.getKey(), factor.getValue());
    }*/
    mapper.printMap();
}

From source file:the.bytecode.club.bytecodeviewer.plugin.strategies.CompiledJavaPluginLaunchStrategy.java

License:Open Source License

private static Set<LoadedNodeData> loadData(File jarFile) throws Throwable {
    ZipInputStream jis = new ZipInputStream(new FileInputStream(jarFile));
    ZipEntry entry;/*from ww  w  .ja  v  a2s  .co  m*/

    Set<LoadedNodeData> set = new HashSet<LoadedNodeData>();

    while ((entry = jis.getNextEntry()) != null) {
        try {
            String name = entry.getName();
            if (name.endsWith(".class")) {
                byte[] bytes = JarUtils.getBytes(jis);
                String magic = String.format("%02X", bytes[0]) + String.format("%02X", bytes[1])
                        + String.format("%02X", bytes[2]) + String.format("%02X", bytes[3]);
                if (magic.toLowerCase().equals("cafebabe")) {
                    try {
                        ClassReader cr = new ClassReader(bytes);
                        ClassNode cn = new ClassNode();
                        cr.accept(cn, 0);
                        LoadedNodeData data = new LoadedNodeData(bytes, cn);
                        set.add(data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out
                            .println(jarFile + ">" + name + ": Header does not start with CAFEBABE, ignoring.");
                }
            }
        } catch (Exception e) {
            new the.bytecode.club.bytecodeviewer.api.ExceptionUI(e);
        } finally {
            jis.closeEntry();
        }
    }
    jis.close();

    return set;
}

From source file:tod.experiments.Instrument.java

License:Open Source License

public static void main(String[] args) throws FileNotFoundException, IOException {
    String theClassFile = args[0];
    byte[] theClassData = Utils.readInputStream_byte(new FileInputStream(theClassFile));

    ClassReader cr = new ClassReader(theClassData);
    ClassNode theClassNode = new ClassNode();
    cr.accept(theClassNode, 0);//w ww .  ja  va 2 s  .c o  m

    String theName = theClassNode.name.replace('/', '.');
    System.out.println(theName);

    TODConfig theConfig = new TODConfig();
    StructureDatabase theStructureDatabase = StructureDatabase.create(theConfig, false);
    ASMInstrumenter2 theInstrumenter = new ASMInstrumenter2(theConfig, theStructureDatabase);

    InstrumentedClass theInstrumentedClass = theInstrumenter.instrumentClass(theName, theClassData, false);

    IClassInfo theClass = theStructureDatabase.getClass(theName, true);
    String theSig = "()Ltod/impl/evdbng/db/file/Tuple;";
    IBehaviorInfo theBehavior = theClass.getBehavior("fetchNext",
            LocationUtils.getArgumentTypes(theStructureDatabase, theSig),
            LocationUtils.getReturnType(theStructureDatabase, theSig));

    JFrame theFrame = new JFrame("TOD - Instrument");
    theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    theFrame.setContentPane(new DisassemblyPanel(theBehavior));
    theFrame.pack();
    theFrame.setVisible(true);
}