Example usage for org.objectweb.asm.commons Method Method

List of usage examples for org.objectweb.asm.commons Method Method

Introduction

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

Prototype

public Method(final String name, final String descriptor) 

Source Link

Document

Constructs a new Method .

Usage

From source file:org.glowroot.agent.weaving.WeavingClassVisitor.java

License:Apache License

@RequiresNonNull("type")
private void overrideAndWeaveInheritedMethod(AnalyzedMethod inheritedMethod) {
    String superName = analyzedClass.superName();
    // superName is null only for java.lang.Object which doesn't inherit anything
    // so safe to assume superName not null here
    checkNotNull(superName);/*  w w w.  ja  va2s .co  m*/
    String[] exceptions = new String[inheritedMethod.exceptions().size()];
    for (int i = 0; i < inheritedMethod.exceptions().size(); i++) {
        exceptions[i] = ClassNames.toInternalName(inheritedMethod.exceptions().get(i));
    }
    MethodVisitor mv = visitMethodWithAdvice(ACC_PUBLIC, inheritedMethod.name(), inheritedMethod.getDesc(),
            inheritedMethod.signature(), exceptions, inheritedMethod.advisors());
    checkNotNull(mv);
    GeneratorAdapter mg = new GeneratorAdapter(mv, ACC_PUBLIC, inheritedMethod.name(),
            inheritedMethod.getDesc());
    mg.visitCode();
    mg.loadThis();
    mg.loadArgs();
    Type superType = Type.getObjectType(ClassNames.toInternalName(superName));
    // method is called invokeConstructor, but should really be called invokeSpecial
    Method method = new Method(inheritedMethod.name(), inheritedMethod.getDesc());
    mg.invokeConstructor(superType, method);
    mg.returnValue();
    mg.endMethod();
}

From source file:org.glowroot.weaving.WeavingClassVisitor.java

License:Apache License

@RequiresNonNull("type")
private WeavingMethodVisitor wrapWithSyntheticTimerMarkerMethods(int outerAccess, String outerName, String desc,
        @Nullable String signature, String /*@Nullable*/[] exceptions, Iterable<Advice> matchingAdvisors,
        @Nullable Integer methodMetaUniqueNum) {
    int innerAccess = ACC_PRIVATE + ACC_FINAL + (outerAccess & ACC_STATIC);
    MethodVisitor outerMethodVisitor = null;
    String currMethodName = outerName;
    int currMethodAccess = outerAccess;
    for (Advice advice : matchingAdvisors) {
        String timerName = advice.pointcut().timerName();
        if (timerName.isEmpty()) {
            continue;
        }/*from  w w  w . j  a va2  s .c  om*/
        if (!timerNameCharMatcher.matchesAllOf(timerName)) {
            logInvalidTimerNameWarningOnce(timerName);
            timerName = timerNameCharMatcher.negate().replaceFrom(timerName, '_');
        }
        String nextMethodName = outerName + "$glowroot$timer$" + timerName.replace(' ', '$') + '$'
                + innerMethodCounter++;
        int access = outerMethodVisitor == null ? outerAccess : innerAccess;
        MethodVisitor mv = cv.visitMethod(access, currMethodName, desc, signature, exceptions);
        checkNotNull(mv);
        GeneratorAdapter mg = new GeneratorAdapter(mv, access, nextMethodName, desc);
        if (!Modifier.isStatic(outerAccess)) {
            mg.loadThis();
            mg.loadArgs();
            mg.invokeVirtual(type, new Method(nextMethodName, desc));
        } else {
            mg.loadArgs();
            mg.invokeStatic(type, new Method(nextMethodName, desc));
        }
        mg.returnValue();
        mg.endMethod();
        currMethodName = nextMethodName;
        currMethodAccess = innerAccess;
        if (outerMethodVisitor == null) {
            outerMethodVisitor = mg;
        }
    }
    MethodVisitor mv = cv.visitMethod(currMethodAccess, currMethodName, desc, signature, exceptions);
    checkNotNull(mv);
    return new WeavingMethodVisitor(mv, currMethodAccess, currMethodName, desc, type, matchingAdvisors,
            metaHolderInternalName, methodMetaUniqueNum, loader == null, outerMethodVisitor);
}

From source file:org.glowroot.weaving.WeavingClassVisitor.java

License:Apache License

@RequiresNonNull("type")
private void overrideAndWeaveInheritedMethod(AnalyzedClass analyzedClass, AnalyzedMethod inheritedMethod,
        Collection<Advice> matchingAdvisors) {
    String superName = analyzedClass.superName();
    // superName is null only for java.lang.Object which doesn't inherit anything
    // so safe to assume superName not null here
    checkNotNull(superName);//from  w  w  w. ja  v  a 2s.  co  m
    String[] exceptions = new String[inheritedMethod.exceptions().size()];
    for (int i = 0; i < inheritedMethod.exceptions().size(); i++) {
        exceptions[i] = ClassNames.toInternalName(inheritedMethod.exceptions().get(i));
    }
    MethodVisitor mv = visitMethodWithAdvice(ACC_PUBLIC, inheritedMethod.name(), inheritedMethod.getDesc(),
            inheritedMethod.signature(), exceptions, matchingAdvisors);
    checkNotNull(mv);
    GeneratorAdapter mg = new GeneratorAdapter(mv, ACC_PUBLIC, inheritedMethod.name(),
            inheritedMethod.getDesc());
    mg.visitCode();
    mg.loadThis();
    mg.loadArgs();
    Type superType = Type.getObjectType(ClassNames.toInternalName(superName));
    // method is called invokeConstructor, but should really be called invokeSpecial
    Method method = new Method(inheritedMethod.name(), inheritedMethod.getDesc());
    mg.invokeConstructor(superType, method);
    mg.returnValue();
    mg.endMethod();
}

From source file:org.jacoco.core.runtime.OfflineInstrumentationAccessGeneratorTest.java

License:Open Source License

/**
 * Creates a new class with the given id, loads this class and instantiates
 * it. The constructor of the generated class will request the probe array
 * from the access generator under test.
 */// ww w .j a  v  a 2s  .  c  o  m
private ITarget generateAndInstantiateClass(int classid) throws InstantiationException, IllegalAccessException {

    final String className = "org/jacoco/test/targets/RuntimeTestTarget_" + classid;
    Type classType = Type.getObjectType(className);

    final ClassWriter writer = new ClassWriter(0);
    writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object",
            new String[] { Type.getInternalName(ITarget.class) });

    writer.visitField(InstrSupport.DATAFIELD_ACC, InstrSupport.DATAFIELD_NAME, InstrSupport.DATAFIELD_DESC,
            null, null);

    // Constructor
    GeneratorAdapter gen = new GeneratorAdapter(
            writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, new String[0]), Opcodes.ACC_PUBLIC,
            "<init>", "()V");
    gen.visitCode();
    gen.loadThis();
    gen.invokeConstructor(Type.getType(Object.class), new Method("<init>", "()V"));
    gen.loadThis();
    final int size = generator.generateDataAccessor(classid, className, 2, gen);
    gen.putStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC));
    gen.returnValue();
    gen.visitMaxs(size + 1, 0);
    gen.visitEnd();

    // get()
    gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "get", "()[Z", null, new String[0]),
            Opcodes.ACC_PUBLIC, "get", "()[Z");
    gen.visitCode();
    gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC));
    gen.returnValue();
    gen.visitMaxs(1, 0);
    gen.visitEnd();

    writer.visitEnd();

    final TargetLoader loader = new TargetLoader(className.replace('/', '.'), writer.toByteArray());
    return (ITarget) loader.newTargetInstance();
}

From source file:org.jacoco.core.runtime.RuntimeTestBase.java

License:Open Source License

/**
 * Creates a new class with the given id, loads this class and instantiates
 * it. The constructor of the generated class will request the probe array
 * from the runtime under test.//from w w  w  . jav a2 s. com
 */
private ITarget generateAndInstantiateClass(int classid) throws InstantiationException, IllegalAccessException {

    final String className = "org/jacoco/test/targets/RuntimeTestTarget_" + classid;
    Type classType = Type.getObjectType(className);

    final ClassWriter writer = new ClassWriter(0);
    writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object",
            new String[] { Type.getInternalName(ITarget.class) });

    writer.visitField(InstrSupport.DATAFIELD_ACC, InstrSupport.DATAFIELD_NAME, InstrSupport.DATAFIELD_DESC,
            null, null);

    // Constructor
    GeneratorAdapter gen = new GeneratorAdapter(
            writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, new String[0]), Opcodes.ACC_PUBLIC,
            "<init>", "()V");
    gen.visitCode();
    gen.loadThis();
    gen.invokeConstructor(Type.getType(Object.class), new Method("<init>", "()V"));
    gen.loadThis();
    final int size = runtime.generateDataAccessor(classid, className, 2, gen);
    gen.putStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC));
    gen.returnValue();
    gen.visitMaxs(size + 1, 0);
    gen.visitEnd();

    // get()
    gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "get", "()[Z", null, new String[0]),
            Opcodes.ACC_PUBLIC, "get", "()[Z");
    gen.visitCode();
    gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC));
    gen.returnValue();
    gen.visitMaxs(1, 0);
    gen.visitEnd();

    // a()
    gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "a", "()V", null, new String[0]),
            Opcodes.ACC_PUBLIC, "a", "()V");
    gen.visitCode();
    gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC));
    gen.push(0);
    gen.push(1);
    gen.arrayStore(Type.BOOLEAN_TYPE);
    gen.returnValue();
    gen.visitMaxs(3, 0);
    gen.visitEnd();

    // b()
    gen = new GeneratorAdapter(writer.visitMethod(Opcodes.ACC_PUBLIC, "b", "()V", null, new String[0]),
            Opcodes.ACC_PUBLIC, "b", "()V");
    gen.visitCode();
    gen.getStatic(classType, InstrSupport.DATAFIELD_NAME, Type.getObjectType(InstrSupport.DATAFIELD_DESC));
    gen.push(1);
    gen.push(1);
    gen.arrayStore(Type.BOOLEAN_TYPE);
    gen.returnValue();
    gen.visitMaxs(3, 0);
    gen.visitEnd();

    writer.visitEnd();

    final TargetLoader loader = new TargetLoader(className.replace('/', '.'), writer.toByteArray());
    return (ITarget) loader.newTargetInstance();
}

From source file:org.jetbrains.jet.compiler.WriteSignatureTest.java

License:Apache License

@NotNull
private ActualSignature readSignature(String className, final String methodName) throws Exception {
    // ugly unreadable code begin
    FileInputStream classInputStream = new FileInputStream(
            tmpdir + "/" + className.replace('.', '/') + ".class");
    try {/*from  ww w  .j av a  2s .com*/
        class Visitor extends EmptyVisitor {
            ActualSignature readSignature;

            @Override
            public MethodVisitor visitMethod(int access, String name, final String desc, final String signature,
                    String[] exceptions) {
                if (name.equals(methodName)) {

                    final int parameterCount = new Method(name, desc).getArgumentTypes().length;

                    return new EmptyVisitor() {
                        String typeParameters = "";
                        String returnType;
                        String[] parameterTypes = new String[parameterCount];

                        @Override
                        public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                            if (desc.equals(JvmStdlibNames.JET_METHOD.getDescriptor())) {
                                return new EmptyVisitor() {
                                    @Override
                                    public void visit(String name, Object value) {
                                        if (name.equals(JvmStdlibNames.JET_METHOD_TYPE_PARAMETERS_FIELD)) {
                                            typeParameters = (String) value;
                                        } else if (name.equals(JvmStdlibNames.JET_METHOD_RETURN_TYPE_FIELD)) {
                                            returnType = (String) value;
                                        }
                                    }

                                    @Override
                                    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                                        return new EmptyVisitor();
                                    }

                                    @Override
                                    public AnnotationVisitor visitArray(String name) {
                                        return new EmptyVisitor();
                                    }
                                };
                            } else {
                                return new EmptyVisitor();
                            }
                        }

                        @Override
                        public AnnotationVisitor visitParameterAnnotation(final int parameter, String desc,
                                boolean visible) {
                            if (desc.equals(JvmStdlibNames.JET_VALUE_PARAMETER.getDescriptor())) {
                                return new EmptyVisitor() {
                                    @Override
                                    public void visit(String name, Object value) {
                                        if (name.equals(JvmStdlibNames.JET_VALUE_PARAMETER_TYPE_FIELD)) {
                                            parameterTypes[parameter] = (String) value;
                                        }
                                    }

                                    @Override
                                    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                                        return new EmptyVisitor();
                                    }

                                    @Override
                                    public AnnotationVisitor visitArray(String name) {
                                        return new EmptyVisitor();
                                    }
                                };
                            } else {
                                return new EmptyVisitor();
                            }
                        }

                        @Override
                        public AnnotationVisitor visitAnnotationDefault() {
                            return new EmptyVisitor();
                        }

                        @Nullable
                        private String makeKotlinSignature() {
                            boolean allNulls = true;

                            StringBuilder sb = new StringBuilder();
                            sb.append(typeParameters);
                            if (typeParameters != null && typeParameters.length() > 0) {
                                allNulls = false;
                            }
                            sb.append("(");
                            for (String parameterType : parameterTypes) {
                                sb.append(parameterType);
                                if (parameterType != null) {
                                    allNulls = false;
                                }
                            }
                            sb.append(")");
                            sb.append(returnType);
                            if (returnType != null) {
                                allNulls = false;
                            }
                            if (allNulls) {
                                return null;
                            } else {
                                return sb.toString();
                            }
                        }

                        @Override
                        public void visitEnd() {
                            Assert.assertNull(readSignature);
                            readSignature = new ActualSignature(desc, signature, makeKotlinSignature());
                        }
                    };
                }
                return super.visitMethod(access, name, desc, signature, exceptions);
            }
        }

        Visitor visitor = new Visitor();

        new ClassReader(classInputStream).accept(visitor,
                ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);

        Assert.assertNotNull("method not found: " + className + "::" + methodName, visitor.readSignature);

        return visitor.readSignature;
    } finally {
        Closeables.closeQuietly(classInputStream);
    }
    // ugly unreadable code end
}

From source file:pt.minha.kernel.instrument.SyncToMonitorClassVisitor.java

License:Open Source License

public void makeStub(int access, String name, String desc, String signature, String[] exceptions) {
    Method m = new Method(name, desc);

    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
    mv.visitCode();/*from   w  w w.  ja va  2 s  . c om*/

    Label begin = new Label();
    Label pre_invoke = new Label();
    Label pos_leave = new Label();
    Label in_catch = new Label();
    Label pre_rethrow = new Label();
    Label end = new Label();

    mv.visitTryCatchBlock(pre_invoke, pos_leave, in_catch, null);
    mv.visitTryCatchBlock(in_catch, pre_rethrow, in_catch, null);

    mv.visitLabel(begin);

    int offset;
    if ((access & Opcodes.ACC_STATIC) == 0) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        offset = 1;
    } else {
        mv.visitFieldInsn(Opcodes.GETSTATIC, clz, "_fake_class",
                "L" + ClassConfig.fake_prefix + "java/lang/Object;");
        offset = 0;
    }

    int length = 0;
    for (Type t : m.getArgumentTypes())
        length += t.getSize();

    mv.visitInsn(Opcodes.DUP);
    mv.visitVarInsn(Opcodes.ASTORE, offset + length);
    mv.visitInsn(Opcodes.MONITORENTER);

    mv.visitLabel(pre_invoke);

    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitVarInsn(Opcodes.ALOAD, 0);

    int i = offset;
    for (Type t : m.getArgumentTypes()) {
        // t.getOpcode() should work for long and double too... :-( 
        if (t.getClassName().equals("long"))
            mv.visitVarInsn(Opcodes.LLOAD, i);
        else if (t.getClassName().equals("double"))
            mv.visitVarInsn(Opcodes.DLOAD, i);
        else
            mv.visitVarInsn(t.getOpcode(Opcodes.ILOAD), i);
        i += t.getSize();
    }

    boolean itf = (access & Opcodes.ACC_INTERFACE) != 0;
    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, clz, "_" + name, desc, itf);
    else
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, clz, "_" + name, desc, itf);

    mv.visitVarInsn(Opcodes.ALOAD, offset + length);
    mv.visitInsn(Opcodes.MONITOREXIT);

    mv.visitLabel(pos_leave);

    if (m.getReturnType().equals(Type.VOID_TYPE))
        mv.visitInsn(Opcodes.RETURN);
    else
        mv.visitInsn(m.getReturnType().getOpcode(Opcodes.IRETURN));

    mv.visitLabel(in_catch);

    mv.visitVarInsn(Opcodes.ALOAD, offset + length);
    mv.visitInsn(Opcodes.MONITOREXIT);

    mv.visitLabel(pre_rethrow);
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(end);

    i = 0;
    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitLocalVariable("this", "L" + clz + ";", null, begin, end, i++);
    for (Type t : m.getArgumentTypes())
        mv.visitLocalVariable("arg" + i, t.getDescriptor(), null, begin, end, i++);

    mv.visitMaxs(0, 0);
    mv.visitEnd();
}