Example usage for org.objectweb.asm ClassVisitor ClassVisitor

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

Introduction

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

Prototype

public ClassVisitor(final int api, final ClassVisitor classVisitor) 

Source Link

Document

Constructs a new ClassVisitor .

Usage

From source file:com.appfour.codestripper.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("Usage: java " + Main.class.getCanonicalName() + " <source dir> <dest file>");
        System.exit(1);/*w  w  w  .java 2 s. co  m*/
    }

    File outFile = new File(args[1]);
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(outFile));
    zipOut.setLevel(9);
    Set<String> writtenEntries = new HashSet<String>();
    for (File file : new File(args[0]).listFiles()) {
        if (file.getName().toLowerCase(Locale.US).endsWith(".jar")) {
            System.err.println("Processing JAR: " + file.getPath());
            ZipInputStream zipIn = new ZipInputStream(new FileInputStream(file));
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {
                if (entry.isDirectory())
                    continue;
                if (entry.getName().toLowerCase(Locale.US).endsWith(".class")) {
                    if (writtenEntries.contains(entry.getName())) {
                        System.out.println("\tIgnoring duplicate CLASS: " + entry.getName());
                        continue;
                    }
                    writtenEntries.add(entry.getName());
                    System.out.println("\tProcessing CLASS: " + entry.getName());
                    ClassReader cr = new ClassReader(zipIn);
                    ClassWriter cw = new ClassWriter(0);
                    final boolean[] skip = new boolean[1];
                    ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
                        @Override
                        public void visit(int version, int access, String name, String signature,
                                String superName, String[] interfaces) {
                            if (!INCLUDE_PACKAGE_PRIVATE_CLASSES
                                    && (access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) == 0) {
                                skip[0] = true;
                            }
                            super.visit(version, access, name, signature, superName, interfaces);
                        }

                        @Override
                        public void visitSource(String source, String debug) {
                            // ignore
                        }

                        @Override
                        public FieldVisitor visitField(int access, String name, String desc, String signature,
                                Object value) {
                            if ((access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) == 0)
                                return null;
                            return super.visitField(access, name, desc, signature, value);
                        }

                        @Override
                        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                                String[] exceptions) {
                            if ((access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) == 0)
                                return null;
                            return new MethodVisitor(Opcodes.ASM5,
                                    super.visitMethod(access, name, desc, signature, exceptions)) {
                                @Override
                                public void visitCode() {
                                    // ignore
                                    super.visitCode();
                                    super.visitInsn(Opcodes.NOP);
                                }

                                @Override
                                public void visitFieldInsn(int opcode, String owner, String name, String desc) {
                                    // ignore
                                }

                                @Override
                                public void visitIincInsn(int var, int increment) {
                                    // ignore
                                }

                                @Override
                                public void visitFrame(int type, int nLocal, Object[] local, int nStack,
                                        Object[] stack) {
                                    // ignore
                                }

                                @Override
                                public void visitInsn(int opcode) {
                                    // ignore
                                }

                                @Override
                                public void visitJumpInsn(int opcode, Label label) {
                                    // ignore
                                }

                                @Override
                                public void visitLabel(Label label) {
                                    // ignore
                                }

                                @Override
                                public void visitLdcInsn(Object cst) {
                                    // ignore
                                }

                                @Override
                                public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
                                    // ignore
                                }

                                @Override
                                public void visitIntInsn(int opcode, int operand) {
                                    // ignore
                                }

                                @Override
                                public AnnotationVisitor visitInsnAnnotation(int typeRef, TypePath typePath,
                                        String desc, boolean visible) {
                                    // ignore
                                    return null;
                                }

                                @Override
                                public void visitInvokeDynamicInsn(String name, String desc, Handle bsm,
                                        Object... bsmArgs) {
                                    // ignore
                                }

                                @Override
                                public void visitMethodInsn(int opcode, String owner, String name,
                                        String desc) {
                                    // ignore
                                }

                                @Override
                                public void visitMultiANewArrayInsn(String desc, int dims) {
                                    // ignore
                                }

                                @Override
                                public void visitTableSwitchInsn(int min, int max, Label dflt,
                                        Label... labels) {
                                    // ignore
                                }

                                @Override
                                public AnnotationVisitor visitTryCatchAnnotation(int typeRef, TypePath typePath,
                                        String desc, boolean visible) {
                                    // ignore
                                    return null;
                                };

                                @Override
                                public void visitTryCatchBlock(Label start, Label end, Label handler,
                                        String type) {
                                    // ignore
                                }

                                @Override
                                public void visitLineNumber(int line, Label start) {
                                    // ignore
                                }

                                @Override
                                public AnnotationVisitor visitLocalVariableAnnotation(int typeRef,
                                        TypePath typePath, Label[] start, Label[] end, int[] index, String desc,
                                        boolean visible) {
                                    // ignore
                                    return null;
                                }

                                @Override
                                public void visitParameter(String name, int access) {
                                    // ignore
                                }

                                @Override
                                public AnnotationVisitor visitParameterAnnotation(int parameter, String desc,
                                        boolean visible) {
                                    // ignore
                                    return null;
                                }

                                @Override
                                public void visitTypeInsn(int opcode, String type) {
                                    // ignore
                                }

                                @Override
                                public void visitVarInsn(int opcode, int var) {
                                    // ignore
                                }

                            };
                        }

                        @Override
                        public void visitAttribute(Attribute attr) {
                            System.out.println("\t\tProcessing attr " + attr.type);
                            if (attr.isCodeAttribute())
                                return;

                            super.visitAttribute(attr);
                        }
                    };
                    cr.accept(cv, 0);
                    if (!skip[0]) {
                        byte[] b2 = cw.toByteArray(); // b2 represents the same class as b1
                        entry.setSize(b2.length);
                        entry.setCompressedSize(-1);
                        entry.setMethod(ZipEntry.DEFLATED);
                        zipOut.putNextEntry(entry);
                        new DataOutputStream(zipOut).write(b2);
                    }
                } else {
                    if (writtenEntries.contains(entry.getName())) {
                        System.out.println("\tIgnoring duplicate RESOURCE: " + entry.getName());
                        continue;
                    }
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    transfer(zipIn, bos, false);
                    writtenEntries.add(entry.getName());
                    System.out.println("\tProcessing RESOURCE: " + entry.getName());
                    entry.setSize(bos.size());
                    entry.setCompressedSize(-1);
                    entry.setMethod(ZipEntry.DEFLATED);
                    zipOut.putNextEntry(entry);
                    transfer(new ByteArrayInputStream(bos.toByteArray()), zipOut, false);
                }
            }
            zipIn.close();
        }
    }
    zipOut.close();
}

From source file:com.geeksaga.light.profiler.instrument.transformer.EntryPointTransformer.java

License:Apache License

private byte[] transform(final ClassLoader classLoader, final String className, byte[] classfileBuffer) {
    final MethodSelector methodSelector = getMethodSelectorOrNull(className);

    if (methodSelector != null) {
        ClassNodeWrapper classNodeWrapper = new ClassNodeWrapper();
        ClassReader reader = new ClassReaderWrapper(classfileBuffer);
        reader.accept(new ClassVisitor(Opcodes.ASM5, classNodeWrapper) {
            @Override//w  w  w. j ava2s. c o  m
            public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                    String[] exceptions) {
                MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

                if (!name.startsWith("<") && methodSelector.isSelected(name, desc)) {
                    logger.debug("Transform => {}.{}{}", className, name, desc);

                    return new EntryPointAdapter(access, name, desc, mv, ASMUtil.isStatic(access));
                }

                return mv;
            }
        }, ClassReader.EXPAND_FRAMES);

        return ASMUtil.toBytes(classNodeWrapper);
    }

    return null;
}

From source file:com.geeksaga.light.profiler.instrument.transformer.EntryPointTransformer.java

License:Apache License

private ClassNodeWrapper transform(final ClassLoader classLoader, byte[] classfileBuffer,
        final ClassNodeWrapper classNodeWrapper) {
    final MethodSelector methodSelector = getMethodSelectorOrNull(classNodeWrapper.getClassName());

    if (methodSelector != null) {
        ClassNodeWrapper newClassNodeWrapper = new ClassNodeWrapper();
        classNodeWrapper.accept(new ClassVisitor(Opcodes.ASM5, newClassNodeWrapper) {
            @Override/*from   www. java 2s.  com*/
            public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                    String[] exceptions) {
                MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

                if (!name.startsWith("<") && methodSelector.isSelected(name, desc)) {
                    logger.debug("Transform => {}.{}{}", classNodeWrapper.getClassName(), name, desc);

                    return new EntryPointAdapter(access, name, desc, mv, ASMUtil.isStatic(access));
                }

                return mv;
            }
        });

        byte[] hookedClassFileBuffer = ASMUtil.toBytes(newClassNodeWrapper);

        ClassFileDumper.dump(classNodeWrapper.getClassName(), classfileBuffer, hookedClassFileBuffer);

        return newClassNodeWrapper;
    }

    return classNodeWrapper;
}

From source file:com.geeksaga.light.profiler.instrument.transformer.MethodParameterTransformer.java

License:Apache License

@Override
public byte[] transform(ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (filter.allow(classLoader, className)) {
        logger.info("Transform => " + className);

        ClassNodeWrapper classNodeWrapper = new ClassNodeWrapper();
        ClassReader reader = new ClassReaderWrapper(classfileBuffer);
        reader.accept(new ClassVisitor(Opcodes.ASM5, classNodeWrapper) {
            @Override//from  w w  w.j a  v a2  s.  co  m
            public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                    String[] exceptions) {
                MethodVisitor methodVisitor = cv.visitMethod(access, name, desc, signature, exceptions);

                if (name.contains("<")) {
                    return methodVisitor;
                }

                return new MethodParameterVisitor(access, desc, methodVisitor, ASMUtil.isStatic(access));
            }
        }, ClassReader.EXPAND_FRAMES);

        if (classNodeWrapper.isInterface()) {
            return classfileBuffer;
        }

        byte[] bytes = ASMUtil.toBytes(classNodeWrapper);

        save(System.getProperty("user.dir") + File.separator + "Main.class", bytes);

        return bytes;
    }

    return classfileBuffer;
}

From source file:com.geeksaga.light.profiler.instrument.transformer.MethodReturnTransformer.java

License:Apache License

@Override
public byte[] transform(ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (filter.allow(classLoader, className)) {
        logger.info("Transform => " + className);

        try {/* w ww .j  a  va 2  s.c o  m*/
            ClassNodeWrapper classNodeWrapper = new ClassNodeWrapper();
            ClassReader reader = new ClassReaderWrapper(classfileBuffer);
            reader.accept(new ClassVisitor(Opcodes.ASM5, classNodeWrapper) {
                @Override
                public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                        String[] exceptions) {
                    MethodVisitor methodVisitor = cv.visitMethod(access, name, desc, signature, exceptions);

                    if (name.contains("<")) {
                        return methodVisitor;
                    }

                    return new MethodReturnVisitor(access, desc, methodVisitor, ASMUtil.isStatic(access));
                }
            }, ClassReader.EXPAND_FRAMES);

            if (classNodeWrapper.isInterface()) {
                return classfileBuffer;
            }

            return ASMUtil.toBytes(classNodeWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return classfileBuffer;
}

From source file:com.geeksaga.light.profiler.instrument.transformer.MethodTransformer.java

License:Apache License

@Override
public byte[] transform(ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (filter.allow(classLoader, className)) {
        ClassNodeWrapper classNodeWrapper = new ClassNodeWrapper();
        ClassReader reader = new ClassReaderWrapper(classfileBuffer);
        reader.accept(new ClassVisitor(Opcodes.ASM5, classNodeWrapper) {
            @Override//from w  ww  .  j  a va 2  s .c  o  m
            public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                    String[] exceptions) {
                MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
                return new MethodAdapter(access, name, desc, mv);
            }
        }, ClassReader.EXPAND_FRAMES);

        if (classNodeWrapper.isInterface()) {
            return classfileBuffer;
        }

        return ASMUtil.toBytes(classNodeWrapper);
    }

    return classfileBuffer;
}

From source file:com.geeksaga.light.profiler.util.ASMUtil.java

License:Apache License

private static ClassVisitor useJSRInlinerAdapter(ClassVisitor visitor) {
    return new ClassVisitor(Opcodes.ASM5, visitor) {
        @Override/*from   w  w w  .j  ava 2s .  c  om*/
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            return new JSRInlinerAdapter(super.visitMethod(access, name, desc, signature, exceptions), access,
                    name, desc, signature, exceptions);
        }
    };
}

From source file:com.github.antag99.retinazer.weaver.Weaver.java

License:Open Source License

/**
 * Returns a class visitor that creates the given class.
 *
 * @param internalName//  w ww. j a  va2  s  .  c o  m
 *            the internal name of the class.
 * @return
 *         the class visitor.
 */
ClassVisitor createClass(final String internalName) {
    return new ClassVisitor(Opcodes.ASM5, new ClassWriter(ClassWriter.COMPUTE_FRAMES)) {
        @Override
        public void visitEnd() {
            super.visitEnd();

            handler.saveClass(internalName, ((ClassWriter) cv).toByteArray());
        }
    };
}

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

License:Apache License

public static String getClassDump(byte[] code) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    TraceClassVisitor traceClassVisitor = new TraceClassVisitor(printWriter);
    ClassVisitor checkClassAdapter = new ClassVisitor(Opcodes.ASM5, traceClassVisitor) {
    };// w w  w  . j  a v  a2 s .co  m
    //ClassAdapter checkClassAdapter = new CheckClassAdapter(traceClassVisitor);
    ClassReader classReader;
    classReader = new ClassReader(code);
    classReader.accept(checkClassAdapter, 0);
    printWriter.flush();
    return stringWriter.toString();
}

From source file:com.github.megatronking.stringfog.plugin.ClassVisitorFactory.java

License:Apache License

private static ClassVisitor createEmpty(ClassWriter cw) {
    return new ClassVisitor(Opcodes.ASM5, cw) {
    };
}