Example usage for org.objectweb.asm ClassReader ClassReader

List of usage examples for org.objectweb.asm ClassReader ClassReader

Introduction

In this page you can find the example usage for org.objectweb.asm ClassReader ClassReader.

Prototype

public ClassReader(final String className) throws IOException 

Source Link

Document

Constructs a new ClassReader object.

Usage

From source file:TestMapper.java

License:Apache License

@SuppressWarnings("rawtypes")
public final static Map<String, Object> checkInstrument(String classpath, String className) {
    Map<String, Object> map = new HashMap<>();
    try {//from   w  ww. j a v  a2  s  . c om
        System.setProperty("current-project-name", "checkInstrument");
        System.setProperty("current-project-path", classpath);
        String targetDir = classpath;

        File f = new File(classpath);
        URLClassLoader ucl = new URLClassLoader(new URL[] { f.toURI().toURL() },
                Thread.currentThread().getContextClassLoader());

        String classFileName = className.replace('.', '/') + ".class";
        // set Domain class file
        File file = new File(targetDir + "/" + classFileName);
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        in.close();

        // --------------------Mapper start-------------------------------
        ClassReader cr = new ClassReader(bytes);
        ClassNode cn = new ClassNode();
        cr.accept(cn, 0);
        DomainMojoHelper.setLoader(ucl);
        MapperToolProcessor proc = new MapperToolProcessor();
        ProcessResult result = proc.process(file, bytes, cn);
        proc.getMapperRegister().endProcess();

        // mapper check
        byte[] mapperClassBytes = result.newBytes;
        ClassNode mapper = result.node;
        String mapperClassName = mapper.name.replaceAll("\\/", "\\.");

        System.out.println("------------ Dump bytecode ------------");

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(bo);
        GemliteHelper.dumpBytecode(mapper, pw);
        pw.flush();
        byte[] dumpBytes = bo.toByteArray();
        map.put("dumpBytes", new String(dumpBytes));
        bo.reset();

        System.out.println("------------ Dump bytecode end ------------");
        GemliteHelper.checkAsmBytes(mapperClassBytes, pw);
        byte[] verifyBytes = bo.toByteArray();
        map.put("verifyBytes", new String(verifyBytes));
        // Test gen mapper class
        ByteArrayClassLoader ba = new ByteArrayClassLoader(mapperClassBytes, ucl);
        Class cls = ba.loadClass(mapperClassName);
        map.put("cls", cls);
        System.out.println("Class -> " + cls);

        // Test gen reg class
        ClassNode reg = proc.getMapperRegister().getReg();
        String regClassName = reg.name.replaceAll("\\/", "\\.");
        bo.reset();
        GemliteHelper.dumpBytecode(reg, pw);
        byte[] regDump = bo.toByteArray();
        map.put("regDump", new String(regDump));
        bo.reset();
        GemliteHelper.checkAsmBytes(proc.getMapperRegister().getFileBytes(), pw);
        byte[] regVerify = bo.toByteArray();
        map.put("regVerify", new String(regVerify));

    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;

}

From source file:Test2.java

License:Apache License

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

    String name = "abcd";
    System.out.println(name.substring(0));
    File f = new File("D:/springsource/gemlite_prod/ynd.test.domain/target/classes/");
    URLClassLoader ucl = new URLClassLoader(new URL[] { f.toURI().toURL() });
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(
            "D:/springsource/gemlite_prod/ynd.test.domain/target/classes/ynd/test/Ac01.class"));
    byte[] bytes = new byte[in.available()];
    in.read(bytes);/*from  w  ww .  java2s. c  o m*/
    in.close();

    ClassReader cr = new ClassReader(bytes);
    ClassNode cn = new ClassNode();
    cr.accept(cn, 0);

    System.out.println(cn.sourceFile + " " + cn.outerClass);
    //    for (Object o : cn.methods)
    //    {
    //      MethodNode mn = (MethodNode) o;
    //      System.out.println(mn.name + " " + mn.desc);
    //    }
    //    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    //    for (Object o : cn.visibleAnnotations)
    //    {
    //      AnnotationNode an = (AnnotationNode) o;
    //      if (DomainMojoConstant.AN_Key.equals(an.desc))
    //      {
    //        Type t = (Type) an.values.get(1);
    //        System.out.println(t.getClassName()+" "+t.getInternalName());
    //        InputStream x1 =  ucl.getResourceAsStream(t.getInternalName()+".class");
    //        System.out.println("&&"+x1.toString());
    //      }
    //      System.out.println(an.desc + " " + an.values);
    //    }

}

From source file:Test1.java

License:Apache License

public static void main(String[] args) throws Exception {
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(
            "D:/springsource/gemlite_prod/ynd.test.domain/target/classes/ynd/test/Ac01.class"));
    byte[] bytes = new byte[in.available()];
    in.read(bytes);/*from  w w w .  j  a  v  a 2 s . c o m*/
    in.close();

    ClassReader cr = new ClassReader(bytes);
    ClassNode cn = new ClassNode();
    cr.accept(cn, 0);

    cn.interfaces.add(DATAS_NAME);
    implementInterface(cn);
}

From source file:Test1.java

License:Apache License

private static void implementInterface(ClassNode cn) throws Exception {

    // MethodNode fromMethod = new MethodNode(ACC_PUBLIC, "fromData",
    // "(Ljava/io/DataInput;)V", null, new String[] {
    // "java/io/IOException",
    // "java/lang/ClassNotFoundException" });
    // mv = cw.visitMethod(ACC_PUBLIC, "toData", "(Ljava/io/DataOutput;)V",
    // null, new String[] { "java/io/IOException" });
    MethodNode toMethod = new MethodNode(ACC_PUBLIC, "toData", "(Ljava/io/DataOutput;)V", null,
            new String[] { "java/io/IOException" });
    InsnList instToMethod = toMethod.instructions;
    for (int i = 0; i < cn.fields.size(); i++) {
        FieldNode fn = (FieldNode) cn.fields.get(i);
        toMethod(cn.name, fn, instToMethod);
    }/*from  www  .  jav a2s  . co  m*/
    instToMethod.add(new InsnNode(RETURN));
    cn.methods.add(toMethod);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    cn.accept(cw);
    byte[] bt = cw.toByteArray();

    ClassReader cr = new ClassReader(bt);
    CheckClassAdapter ca = new CheckClassAdapter(cw);
    FileOutputStream fo = new FileOutputStream("d:/x1.log");
    PrintWriter pw = new PrintWriter(fo);
    ca.verify(cr, true, pw);

    ByteArrayClassLoader bacl = new ByteArrayClassLoader(bt);

    Class cls = bacl.loadClass("ynd.test.Ac01");
    DataSerializable di = (DataSerializable) cls.newInstance();
    di.toData(null);
}

From source file:Java6to2.java

License:Open Source License

private static byte[] transform(InputStream classfile) throws IOException {
    ClassReader cr = new ClassReader(classfile);
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = new ClassVisitor(ASM7, cw) {
        String internalName;//from  w ww  . j a  v  a2 s.  com
        boolean classLookupMethodGenerated;
        Set fieldsGenerated = new HashSet();

        public void visit(int version, int access, String name, String signature, String superName,
                String[] interfaces) {
            /* Change class file version to 1.2 */
            cv.visit(V1_2, access, name, signature, superName, interfaces);
            this.internalName = name;
        }

        /**
         * Generates the synthetic "class$" method, used to lookup classes via Class.forName(). This uses the exact same code as does JDK8 javac for target 1.2.
         */
        void generateSyntheticClassLookupMethod() {
            MethodVisitor mv = cv.visitMethod(ACC_PRIVATE | ACC_STATIC | ACC_SYNTHETIC, "class$",
                    "(Ljava/lang/String;)Ljava/lang/Class;", null, null);
            {
                Label start = new Label();
                Label end = new Label();
                Label handler = new Label();
                mv.visitTryCatchBlock(start, end, handler, "java/lang/ClassNotFoundException");
                mv.visitLabel(start);
                mv.visitVarInsn(ALOAD, 0);
                mv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName",
                        "(Ljava/lang/String;)Ljava/lang/Class;", false);
                mv.visitLabel(end);
                mv.visitInsn(ARETURN);
                mv.visitLabel(handler);
                mv.visitVarInsn(ASTORE, 1);
                mv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError");
                mv.visitInsn(DUP);
                mv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "<init>", "()V", false);
                mv.visitVarInsn(ALOAD, 1);
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NoClassDefFoundError", "initCause",
                        "(Ljava/lang/Throwable;)Ljava/lang/Throwable;", false);
                mv.visitInsn(ATHROW);
            }
            mv.visitMaxs(2, 2);
            mv.visitEnd();
        }

        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
            final ClassVisitor cv = this.cv;
            return new MethodVisitor(ASM7, mv) {
                /**
                 * Intercepts class instantiations to see whether they instantiate a StringBuilder. Those instructions were generated by javac for string concatenations. But
                 * StringBuilder is not available on JRE1.2, so we just replace it with StringBuffer.
                 */
                public void visitTypeInsn(int opcode, String type) {
                    if (opcode == NEW && "java/lang/StringBuilder".equals(type)) {
                        mv.visitTypeInsn(opcode, "java/lang/StringBuffer");
                    } else {
                        mv.visitTypeInsn(opcode, type);
                    }
                }

                /**
                 * Intercepts method invocations to see whether they do something with StringBuilder. Those instructions were generated by javac for string concatenations. But
                 * StringBuilder is not available on JRE1.2, so we just replace it with StringBuffer.
                 */
                public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
                    if ("java/lang/StringBuilder".equals(owner)) {
                        mv.visitMethodInsn(opcode, "java/lang/StringBuffer", name,
                                desc.replace("java/lang/StringBuilder", "java/lang/StringBuffer"), itf);
                    } else {
                        mv.visitMethodInsn(opcode, owner, name, desc, itf);
                    }
                }

                /**
                 * Intercepts LDC instructions and check whether they are used to load a class. This is not supported on Java 1.2, so we convert it to the same code used by the
                 * JDK8 javac:
                 * <ul>
                 * <li>create synthetic fields holding the resolved class objects
                 * <li>create a synthetic method called "class$" which does Class.forName
                 * </ul>
                 */
                public void visitLdcInsn(Object cst) {
                    if (cst instanceof Type) {
                        Type t = (Type) cst;
                        String syntheticField = "class$"
                                + t.getInternalName().replace('/', '$').replace("[", "");
                        if (!classLookupMethodGenerated) {
                            /* Emit the synthetic "class$" method, used to lookup classes via Class.forName() */
                            generateSyntheticClassLookupMethod();
                            classLookupMethodGenerated = true;
                        }
                        if (!fieldsGenerated.contains(syntheticField)) {
                            /* Generate a synthetic field holding the resolved Class object */
                            cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_SYNTHETIC, syntheticField,
                                    "Ljava/lang/Class;", null, null);
                            fieldsGenerated.add(syntheticField);
                        }
                        mv.visitFieldInsn(GETSTATIC, internalName, syntheticField, "Ljava/lang/Class;");
                        Label nonNull = new Label();
                        mv.visitJumpInsn(IFNONNULL, nonNull);
                        mv.visitLdcInsn(t.getInternalName().replace('/', '.'));
                        mv.visitMethodInsn(INVOKESTATIC, internalName, "class$",
                                "(Ljava/lang/String;)Ljava/lang/Class;", false);
                        mv.visitInsn(DUP);
                        mv.visitFieldInsn(PUTSTATIC, internalName, syntheticField, "Ljava/lang/Class;");
                        Label cnt = new Label();
                        mv.visitJumpInsn(GOTO, cnt);
                        mv.visitLabel(nonNull);
                        mv.visitFieldInsn(GETSTATIC, internalName, syntheticField, "Ljava/lang/Class;");
                        mv.visitLabel(cnt);
                    } else {
                        mv.visitLdcInsn(cst);
                    }
                }
            };
        }
    };
    cr.accept(cv, ClassReader.SKIP_FRAMES); // <- Frames are not used in Java 1.2, so skip them
    return cw.toByteArray();
}

From source file:Asm.java

License:Apache License

private static void modify(String clazz) throws Exception {
    ClassNode classNode = new ClassNode();
    ClassReader cr = new ClassReader(clazz);
    cr.accept(classNode, 0);/*from ww  w  .  ja v  a2s .c  om*/

    modify(classNode);

    ClassWriter cw = new ClassWriter(0);
    classNode.accept(cw);
    byte[] b = cw.toByteArray();
    OutputStream out = new FileOutputStream(clazz + ".out");
    out.write(b, 0, b.length);
    out.close();
}

From source file:IjarTests.java

License:Open Source License

@Test
public void testVerifyStripping() throws Exception {
    ZipFile zip = new ZipFile("third_party/ijar/test/interface_ijar_testlib.jar");
    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        ClassReader reader = new ClassReader(zip.getInputStream(entry));
        StripVerifyingVisitor verifier = new StripVerifyingVisitor();

        reader.accept(verifier, 0);/*from   ww w  .  j av  a2s  .  c o  m*/

        if (verifier.errors.size() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append("Verification of ");
            builder.append(entry.getName());
            builder.append(" failed: ");
            for (String msg : verifier.errors) {
                builder.append(msg);
                builder.append("\t");
            }
            fail(builder.toString());
        }
    }
}

From source file:allout58.mods.techtree.asm.TechTreeModClassTransformer.java

License:Open Source License

private byte[] apply(byte[] bytes, String name, int id) {
    Preconditions.checkNotNull(bytes);/*from  ww  w  . j av a 2s  .  co  m*/
    ClassReader reader = new ClassReader(bytes);
    ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES);
    ClassVisitor visitor = null;

    switch (id) {
    case 0:
        visitor = new CraftingContainerVisitor(name, writer);
        break;
    case 1:
        visitor = new CraftingPlayerVisitor(name, writer);
        break;
    }
    try {
        if (visitor != null)
            reader.accept(visitor, 0);
        return writer.toByteArray();
    } catch (Exception e) {
        FMLRelaunchLog.severe("Error transforming %s: %s", name, e);
        return bytes;
    }
}

From source file:analysis.ReferenceGenerator.java

License:Open Source License

/**
 * Create a {@link ClassNode} from an {@link Entry}
 * @param e entry//from w  w  w  .jav a 2s .  c  om
 * @return
 */
private static ClassNode classNodeFromEntry(Entry e) {
    ClassReader cr;
    ClassNode node;

    cr = new ClassReader(e.getData());
    node = new ClassNode();
    cr.accept(node, ClassReader.SKIP_FRAMES);
    return node;
}

From source file:apb.processors.NotNullInstrumentTask.java

License:Apache License

private void instrumentClass(@NotNull final String classPath) {
    final File classFile = new File(classPath);

    if (classFile.getName().endsWith(".class")) {
        try {//ww w .j a  va2  s . c o m
            final InputStream fis = new FileInputStream(classFile);

            try {
                final ClassReader reader = new ClassReader(fis);
                final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);

                final NotNullClassInstrumenter classInstrumenter = new NotNullClassInstrumenter(writer);
                reader.accept(classInstrumenter, 0);

                if (classInstrumenter.isModified()) {
                    logVerbose("Adding @NotNull assertions to " + classPath + "\n");
                    final OutputStream os = new FileOutputStream(classPath);

                    try {
                        os.write(writer.toByteArray());
                    } finally {
                        os.close();
                    }
                }
            } finally {
                fis.close();
            }
        } catch (IOException e) {
            logVerbose(
                    "Failed to instrument @NotNull assertion for " + classPath + ": " + e.getMessage() + "\n");
            e.printStackTrace();
        }
    }
}