Example usage for org.objectweb.asm MethodVisitor MethodVisitor

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

Introduction

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

Prototype

public MethodVisitor(final int api, final MethodVisitor methodVisitor) 

Source Link

Document

Constructs a new MethodVisitor .

Usage

From source file:co.paralleluniverse.fibers.instrument.LabelSuspendableCallSitesClassVisitor.java

License:Open Source License

@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature,
        final String[] exceptions) {
    if ((access & Opcodes.ACC_NATIVE) == 0 && !isYieldMethod(className, name)) {
        // Bytecode-level AST of a method, being a MethodVisitor itself can be filled through delegation from another visitor
        // Analyze, fill and enqueue method ASTs
        final MethodVisitor outMV = super.visitMethod(access, name, desc, signature, exceptions);

        return new MethodVisitor(ASMAPI, outMV) {
            private int currLineNumber = -1;

            @Override//from  ww w  .ja v  a2  s. c om
            public void visitLineNumber(int i, Label label) {
                currLineNumber = i;
                super.visitLineNumber(i, label);
            }

            @Override
            public void visitMethodInsn(int opcode, String owner, String name, String desc,
                    boolean isInterface) {
                final int type = AbstractInsnNode.METHOD_INSN;
                if (InstrumentMethod.isSuspendableCall(db, type, opcode, owner, name, desc)) {
                    final Label l = new Label();
                    super.visitLabel(l);
                    super.visitLineNumber(currLineNumber, l); // Force label
                }
                super.visitMethodInsn(opcode, owner, name, desc, isInterface);
            }

            @Override
            public void visitInvokeDynamicInsn(String name, String desc, Handle handle, Object... objects) {
                final int type = AbstractInsnNode.INVOKE_DYNAMIC_INSN;
                final int opcode = Opcodes.INVOKEDYNAMIC;
                if (InstrumentMethod.isSuspendableCall(db, type, opcode, handle.getOwner(), name, desc)) {
                    final Label l = new Label();
                    super.visitLabel(l);
                    super.visitLineNumber(currLineNumber, l); // Force label
                }
                super.visitInvokeDynamicInsn(name, desc, handle, objects);
            }
        };
    }
    return super.visitMethod(access, name, desc, signature, exceptions);
}

From source file:co.paralleluniverse.fibers.instrument.SuspOffsetsAfterInstrClassVisitor.java

License:Open Source License

@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature,
        final String[] exceptions) {
    if ((access & Opcodes.ACC_NATIVE) == 0 && !isYieldMethod(className, name)) {
        // Bytecode-level AST of a method, being a MethodVisitor itself can be filled through delegation from another visitor
        final MethodNode mn = new MethodNode(access, name, desc, signature, exceptions);

        // Analyze, fill and enqueue method ASTs
        final MethodVisitor outMV = super.visitMethod(access, name, desc, signature, exceptions);

        return new MethodVisitor(ASMAPI, outMV) {
            private Label currLabel = null;
            private int prevOffset = -1;
            private boolean instrumented;
            private boolean optimized = false;
            private int methodStart = -1, methodEnd = -1;

            private List<Integer> suspOffsetsAfterInstrL = new ArrayList<>();
            private int[] suspCallSites = new int[0];

            @Override//from w w  w .  j  a v  a 2s  .  c  o m
            public AnnotationVisitor visitAnnotation(final String adesc, boolean visible) {
                if (Classes.INSTRUMENTED_DESC.equals(adesc)) {
                    instrumented = true;

                    return new AnnotationVisitor(ASMAPI) { // Only collect info
                        @Override
                        public void visit(String name, Object value) {
                            if (Instrumented.FIELD_NAME_METHOD_START.equals(name))
                                methodStart = (Integer) value;
                            else if (Instrumented.FIELD_NAME_METHOD_END.equals(name))
                                methodEnd = (Integer) value;
                            else if (Instrumented.FIELD_NAME_METHOD_OPTIMIZED.equals(name))
                                optimized = (Boolean) value;
                            else if (Instrumented.FIELD_NAME_SUSPENDABLE_CALL_SITES.equals(name))
                                suspCallSites = (int[]) value;
                            else //noinspection StatementWithEmptyBody
                            if (Instrumented.FIELD_NAME_SUSPENDABLE_CALL_SITES_OFFSETS_AFTER_INSTR.equals(name))
                                ; // Ignore, we're filling it
                            else
                                throw new RuntimeException("Unexpected `@Instrumented` field: " + name);
                        }
                    };
                }

                return super.visitAnnotation(adesc, visible);
            }

            @Override
            public void visitLocalVariable(String name, String desc, String sig, Label lStart, Label lEnd,
                    int slot) {
                super.visitLocalVariable(name, desc, sig, lStart, lEnd, slot);
            }

            @Override
            public void visitLabel(Label label) {
                if (instrumented) {
                    currLabel = label;
                }

                super.visitLabel(label);
            }

            @Override
            public void visitMethodInsn(int opcode, String owner, String name, String desc,
                    boolean isInterface) {
                if (instrumented) {
                    final int type = AbstractInsnNode.METHOD_INSN;
                    if (InstrumentMethod.isSuspendableCall(db, type, opcode, owner, name, desc)
                            && !Classes.STACK_NAME.equals(owner) && // postRestore
                    currLabel != null && currLabel.info instanceof Integer)
                        addLine();
                }

                super.visitMethodInsn(opcode, owner, name, desc, isInterface);
            }

            @Override
            public void visitInvokeDynamicInsn(String name, String desc, Handle handle, Object... objects) {
                if (instrumented) {
                    final int type = AbstractInsnNode.INVOKE_DYNAMIC_INSN;
                    final int opcode = Opcodes.INVOKEDYNAMIC;
                    if (InstrumentMethod.isSuspendableCall(db, type, opcode, handle.getOwner(), name, desc)
                            && !Classes.STACK_NAME.equals(handle.getOwner()) && // postRestore
                    currLabel != null && currLabel.info instanceof Integer)
                        addLine();
                }
                super.visitInvokeDynamicInsn(name, desc, handle, objects);
            }

            @Override
            public void visitEnd() {
                if (instrumented)
                    InstrumentMethod.emitInstrumentedAnn(db, outMV, mn, sourceName, className, optimized,
                            methodStart, methodEnd, suspCallSites, toIntArray(suspOffsetsAfterInstrL));

                super.visitEnd();
            }

            private void addLine() {
                final int currOffset = (Integer) currLabel.info;
                if (currOffset > prevOffset) {
                    suspOffsetsAfterInstrL.add(currOffset);
                    prevOffset = currOffset;
                }
            }
        };
    }

    return super.visitMethod(access, name, desc, signature, exceptions);
}

From source file:co.paralleluniverse.vtime.VirtualTimeClassTransformer.java

License:Open Source License

private ClassVisitor createVisitor(ClassVisitor next) {
    int api;//w w w .  j a  v  a 2 s.  co m
    if (System.getProperty("java.version").startsWith("1.8")) {
        api = Opcodes.ASM5;
    } else if (System.getProperty("java.version").startsWith("10")) {
        api = Opcodes.ASM6;
    } else {
        api = Opcodes.ASM7;
    }
    return new ClassVisitor(api, next) {
        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            return new MethodVisitor(api, super.visitMethod(access, name, desc, signature, exceptions)) {
                @Override
                public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
                    if (!captureTimeCall(owner, name, desc)) {
                        super.visitMethodInsn(opcode, owner, name, desc, itf);
                    }
                }

                private boolean captureTimeCall(String owner, String name, String desc) {
                    switch (owner) {
                    case "java/lang/Object":
                        if ("wait".equals(name)) {
                            return callClockMethod("Object_wait", instanceToStatic(owner, desc));
                        }
                        break;
                    case "java/lang/System":
                        switch (name) {
                        case "nanoTime":
                            return callClockMethod("System_nanoTime", desc);
                        case "currentTimeMillis":
                            return callClockMethod("System_currentTimeMillis", desc);
                        }
                        break;
                    case "java/lang/Thread":
                        if ("sleep".equals(name)) {
                            return callClockMethod("Thread_sleep", desc);
                        }
                        break;
                    case "sun/misc/Unsafe":
                        if ("park".equals(name)) {
                            return callClockMethod("Unsafe_park", instanceToStatic(owner, desc));
                        }
                        break;
                    case "java/lang/management/RuntimeMXBean":
                        if ("getStartTime".equals(name)) {
                            return callClockMethod("RuntimeMXBean_getStartTime", instanceToStatic(owner, desc));
                        }
                        break;
                    }
                    return false;
                }

                private boolean callClockMethod(String name, String desc) {
                    if (includedMethods == null || includedMethods.contains(name)) {
                        super.visitMethodInsn(Opcodes.INVOKESTATIC, CLOCK, name, desc, false);
                        return true;
                    } else {
                        return false;
                    }
                }

                private String instanceToStatic(String owner, String desc) {
                    return "(L" + owner + ";" + desc.substring(1);
                }
            };
        }
    };
}

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

License:Apache License

private static byte[] hotswapChange(byte[] inputClass) {
    ClassReader cr = new ClassReader(inputClass);
    ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES);
    ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
        @Override//from  ww  w . j  a v  a 2 s .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);
            return new MethodVisitor(Opcodes.ASM5, mv) {
                @Override
                public void visitCode() {
                    // add a useless logging to the method.
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
                    mv.visitLdcInsn("test changed !");
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println",
                            "(Ljava/lang/String;)V", false);
                    super.visitCode();
                }
            };
        }
    };
    cr.accept(cv, ClassReader.EXPAND_FRAMES);
    return cw.toByteArray();
}

From source file:com.android.build.gradle.shrinker.ClassStructureVisitor.java

License:Apache License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    final T method = mGraph.addMember(mClass, name, desc, access);

    MethodVisitor superVisitor = super.visitMethod(access, name, desc, signature, exceptions);
    return new MethodVisitor(Opcodes.ASM5, superVisitor) {
        @Override/*from   w ww.j a  v  a2s.  com*/
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            mGraph.addAnnotation(method, Type.getType(desc).getInternalName());
            return super.visitAnnotation(desc, visible);
        }
    };
}

From source file:com.android.build.gradle.shrinker.IncrementalRunVisitor.java

License:Apache License

@Override
public MethodVisitor visitMethod(int access, final String name, String desc, String signature,
        String[] exceptions) {/*from  w  w  w  .  j a  v  a  2 s  . c  o  m*/
    final T method = mGraph.getMemberReference(mClassName, name, desc);

    if (!mMethods.remove(method)) {
        throw new IncrementalShrinker.IncrementalRunImpossibleException(
                String.format("Method %s.%s:%s added.", mClassName, name, desc));
    }

    if (mGraph.getModifiers(method) != access) {
        throw new IncrementalShrinker.IncrementalRunImpossibleException(
                String.format("Method %s.%s:%s modifiers changed.", mClassName, name, desc));
    }

    final Set<String> memberAnnotations = Sets.newHashSet(mGraph.getAnnotations(method));
    MethodVisitor superVisitor = super.visitMethod(access, name, desc, signature, exceptions);
    return new MethodVisitor(Opcodes.ASM5, superVisitor) {
        @Override
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            checkForAddedAnnotation(desc, memberAnnotations, mClassName + "." + name);
            return super.visitAnnotation(desc, visible);
        }

        @Override
        public void visitEnd() {
            checkForRemovedAnnotation(memberAnnotations, mClassName + "." + name);
            super.visitEnd();
        }
    };
}

From source file:com.android.build.gradle.shrinker.RewriteOutputVisitor.java

License:Apache License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    signature = mRemapper.mapSignature(signature, false);

    if (!mMembers.contains(name + ":" + desc)) {
        return null;
    } else {/*w w  w  .j  a  v  a2s. c  om*/
        return new MethodVisitor(Opcodes.ASM5, super.visitMethod(access, name, desc, signature, exceptions)) {
            @Override
            public void visitLocalVariable(String name, String desc, String signature, Label start, Label end,
                    int index) {
                signature = mRemapper.mapSignature(signature, true);
                super.visitLocalVariable(name, desc, signature, start, end, index);
            }
        };
    }
}

From source file:com.android.builder.shrinker.ClassStructureVisitor.java

License:Apache License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    final T method = mGraph.addMember(mClass, name, desc, access);

    MethodVisitor superVisitor = super.visitMethod(access, name, desc, signature, exceptions);
    return new MethodVisitor(Opcodes.ASM5, superVisitor) {
        @Override//from w ww  . j  a  v a  2 s.  com
        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
            mGraph.addAnnotation(method, desc);
            return super.visitAnnotation(desc, visible);
        }
    };
}

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  ww.j av a  2  s  . com
    }

    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.blade.kit.AsmKit.java

License:Apache License

/**
 *
 * <p>/* w w  w.  ja  va  2s. com*/
 * ????
 * </p>
 *
 * @param m
 * @return
 */
public static String[] getMethodParamNames(final Method m) throws IOException {
    final String[] paramNames = new String[m.getParameterTypes().length];
    final String n = m.getDeclaringClass().getName();
    ClassReader cr = null;
    try {
        cr = new ClassReader(n);
    } catch (IOException e) {
        return null;
    }
    cr.accept(new ClassVisitor(Opcodes.ASM5) {
        @Override
        public MethodVisitor visitMethod(final int access, final String name, final String desc,
                final String signature, final String[] exceptions) {
            final Type[] args = Type.getArgumentTypes(desc);
            // ?????
            if (!name.equals(m.getName()) || !sameType(args, m.getParameterTypes())) {
                return super.visitMethod(access, name, desc, signature, exceptions);
            }
            MethodVisitor v = super.visitMethod(access, name, desc, signature, exceptions);
            return new MethodVisitor(Opcodes.ASM5, v) {
                @Override
                public void visitLocalVariable(String name, String desc, String signature, Label start,
                        Label end, int index) {
                    int i = index - 1;
                    // ???
                    // ???"this"???
                    if (Modifier.isStatic(m.getModifiers())) {
                        i = index;
                    }
                    if (i >= 0 && i < paramNames.length) {
                        paramNames[i] = name;
                    }
                    super.visitLocalVariable(name, desc, signature, start, end, index);
                }
            };
        }
    }, 0);
    return paramNames;
}