Example usage for org.objectweb.asm MethodVisitor visitFrame

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

Introduction

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

Prototype

public void visitFrame(final int type, final int numLocal, final Object[] local, final int numStack,
        final Object[] stack) 

Source Link

Document

Visits the current state of the local variables and operand stack elements.

Usage

From source file:org.fabric3.implementation.bytecode.proxy.common.ProxyFactoryImpl.java

License:Open Source License

public <T, D extends ProxyDispatcher> T createProxy(URI classLoaderKey, Class<T> type, Method[] methods,
        Class<D> dispatcherInt, Class<? extends D> dispatcherTmpl, boolean wrapped) throws ProxyException {

    String className = type.getName() + "_Proxy_" + dispatcherInt.getSimpleName(); // ensure multiple dispatchers can be defined for the same interface

    // check if the proxy class has already been created
    BytecodeClassLoader generationLoader = getClassLoader(classLoaderKey);
    try {/*from   www. j ava  2 s . c  om*/
        Class<T> proxyClass = (Class<T>) generationLoader.loadClass(className);
        return proxyClass.newInstance();
    } catch (ClassNotFoundException e) {
        // ignore
    } catch (InstantiationException e) {
        throw new ProxyException(e);
    } catch (IllegalAccessException e) {
        throw new ProxyException(e);
    }

    verifyTemplate(dispatcherTmpl);

    String classNameInternal = Type.getInternalName(type) + "_Proxy_" + dispatcherInt.getSimpleName();
    String thisDescriptor = "L" + classNameInternal + ";";
    String dispatcherIntName = Type.getInternalName(dispatcherInt);

    //Important to use class version of template class that will be copied. If class compiled with JDK 1.5 but copied 
    //to class version 1.7 there will be errors since 1.7 enforces frame stackmaps which were not present in 1.5

    int version = getClassVersion(generationLoader, dispatcherTmpl);
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    if (type.isInterface()) {
        String interfazeName = Type.getInternalName(type);
        cw.visit(version, ACC_PUBLIC + ACC_SUPER, classNameInternal, null, "java/lang/Object",
                new String[] { dispatcherIntName, interfazeName });
        cw.visitSource(type.getName() + "Proxy.java", null);
        String baseName = Type.getInternalName(Object.class);
        // write the ctor
        writeConstructor(baseName, thisDescriptor, cw);
    } else {
        verifyBaseClass(type, methods);
        String baseTypeName = Type.getInternalName(type);
        cw.visit(version, ACC_PUBLIC + ACC_SUPER, classNameInternal, null, baseTypeName,
                new String[] { dispatcherIntName });

        cw.visitSource(type.getName() + "Proxy.java", null);
        String baseName = Type.getInternalName(type);
        // write the ctor
        writeConstructor(baseName, thisDescriptor, cw);
    }

    copyTemplate(generationLoader, classNameInternal, dispatcherTmpl, cw);

    // write the methods
    int methodIndex = 0;
    for (Method method : methods) {
        //if the method is not overridable do not generate a bytecode method for it. This means any invocation of the class will directly act upon the 
        //the base class or proxy class but since these methods should not be visible anyway it shouldn't matter. The exception could be equals/hashcode/toString/clone 
        if (!isOverridableMethod(method)) {
            methodIndex++;
            continue;
        }
        String methodSignature = Type.getMethodDescriptor(method);
        String[] exceptions = new String[method.getExceptionTypes().length];
        for (int i = 0; i < exceptions.length; i++) {
            exceptions[i] = Type.getInternalName(method.getExceptionTypes()[i]);
        }
        int visibility = Modifier.isPublic(method.getModifiers()) ? ACC_PUBLIC
                : Modifier.isProtected(method.getModifiers()) ? ACC_PROTECTED : 0;
        mv = cw.visitMethod(visibility, method.getName(), methodSignature, null, exceptions);
        mv.visitCode();

        List<Label> exceptionLabels = new ArrayList<Label>();
        Label label2 = new Label();
        Label label3 = new Label();

        for (String exception : exceptions) {
            Label endLabel = new Label();
            exceptionLabels.add(endLabel);
            mv.visitTryCatchBlock(label2, label3, endLabel, exception);

        }

        mv.visitLabel(label2);
        mv.visitVarInsn(ALOAD, 0);

        // set the method index used to dispatch on
        if (methodIndex >= 0 && methodIndex <= 5) {
            // use an integer constant if within range
            mv.visitInsn(Opcodes.ICONST_0 + methodIndex);
        } else {
            mv.visitIntInsn(Opcodes.BIPUSH, methodIndex);
        }
        methodIndex++;

        int[] index = new int[1];
        index[0] = 0;
        int[] stack = new int[1];
        stack[0] = 1;

        if (method.getParameterTypes().length == 0) {
            // no params, load null
            mv.visitInsn(Opcodes.ACONST_NULL);
        } else {
            if (wrapped) {
                emitWrappedParameters(method, mv, index, stack);
            } else {
                emitUnWrappedParameters(method, mv, index, stack);
            }
        }

        mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, "_f3_invoke",
                "(ILjava/lang/Object;)Ljava/lang/Object;");

        // handle return values
        writeReturn(method, label3, mv);

        // implement catch blocks
        index[0] = 0;
        for (String exception : exceptions) {
            Label endLabel = exceptionLabels.get(index[0]);
            mv.visitLabel(endLabel);
            mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { exception });
            mv.visitVarInsn(ASTORE, wrapped ? stack[0] : 1);
            Label label6 = new Label();
            mv.visitLabel(label6);
            mv.visitVarInsn(ALOAD, wrapped ? stack[0] : 1);
            mv.visitInsn(ATHROW);
            index[0]++;
        }

        Label label7 = new Label();
        mv.visitLabel(label7);
        mv.visitMaxs(7, 5);
        mv.visitEnd();

    }
    cw.visitEnd();

    byte[] data = cw.toByteArray();
    //ClassReader classReader = new ClassReader(data);
    //classReader.accept(new org.objectweb.asm.util.TraceClassVisitor(null, new org.objectweb.asm.util.ASMifier(), new java.io.PrintWriter(System.out)), 0);
    Class<?> proxyClass = generationLoader.defineClass(className, data);
    try {
        return (T) proxyClass.newInstance();
    } catch (InstantiationException e) {
        throw new ProxyException(e);
    } catch (IllegalAccessException e) {
        throw new ProxyException(e);
    }

}

From source file:org.glowroot.advicegen.AdviceGenerator.java

License:Apache License

@RequiresNonNull("methodMetaInternalName")
private void addOnBeforeMethod(ClassWriter cw) {
    MethodVisitor mv = visitOnBeforeMethod(cw, "Lorg/glowroot/api/TraceEntry;");
    mv.visitCode();//from   w  w w. j  a  v a  2 s .  c o  m
    if (!config.traceEntryEnabledProperty().isEmpty()) {
        mv.visitFieldInsn(GETSTATIC, adviceInternalName, "entryEnabled",
                "Lorg/glowroot/api/PluginServices$BooleanProperty;");
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/PluginServices$BooleanProperty", "value", "()Z",
                true);
        Label label = new Label();
        mv.visitJumpInsn(IFNE, label);
        // entryEnabled is false, collect timer only
        mv.visitFieldInsn(GETSTATIC, adviceInternalName, "pluginServices", "Lorg/glowroot/api/PluginServices;");
        mv.visitFieldInsn(GETSTATIC, adviceInternalName, "timerName", "Lorg/glowroot/api/TimerName;");
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/api/PluginServices", "startTimer",
                "(Lorg/glowroot/api/TimerName;)Lorg/glowroot/api/Timer;", false);
        mv.visitInsn(ARETURN);
        mv.visitLabel(label);
        mv.visitFrame(F_SAME, 0, null, 0, null);
    }
    mv.visitFieldInsn(GETSTATIC, adviceInternalName, "pluginServices", "Lorg/glowroot/api/PluginServices;");
    if (config.isTransaction()) {
        String transactionType = config.transactionType();
        if (transactionType.isEmpty()) {
            mv.visitLdcInsn("<no transaction type provided>");
        } else {
            mv.visitLdcInsn(transactionType);
        }
        mv.visitVarInsn(ALOAD, 3);
        mv.visitMethodInsn(INVOKEVIRTUAL, methodMetaInternalName, "getTransactionNameTemplate",
                "()Lorg/glowroot/advicegen/MessageTemplate;", false);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitVarInsn(ALOAD, 2);
        mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/advicegen/GenericMessageSupplier", "create",
                "(Lorg/glowroot/advicegen/MessageTemplate;"
                        + "Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;)"
                        + "Lorg/glowroot/advicegen/GenericMessageSupplier;",
                false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/advicegen/GenericMessageSupplier", "getMessageText",
                "()Ljava/lang/String;", false);
    }
    mv.visitVarInsn(ALOAD, 3);
    mv.visitMethodInsn(INVOKEVIRTUAL, methodMetaInternalName, "getMessageTemplate",
            "()Lorg/glowroot/advicegen/MessageTemplate;", false);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/advicegen/GenericMessageSupplier", "create",
            "(Lorg/glowroot/advicegen/MessageTemplate;"
                    + "Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;)"
                    + "Lorg/glowroot/advicegen/GenericMessageSupplier;",
            false);
    mv.visitFieldInsn(GETSTATIC, adviceInternalName, "timerName", "Lorg/glowroot/api/TimerName;");
    if (config.isTransaction()) {
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/api/PluginServices", "startTransaction",
                "(Ljava/lang/String;Ljava/lang/String;"
                        + "Lorg/glowroot/api/MessageSupplier;Lorg/glowroot/api/TimerName;)"
                        + "Lorg/glowroot/api/TraceEntry;",
                false);
    } else {
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/api/PluginServices", "startTraceEntry",
                "(Lorg/glowroot/api/MessageSupplier;Lorg/glowroot/api/TimerName;)"
                        + "Lorg/glowroot/api/TraceEntry;",
                false);
    }
    addCodeForOptionalTraceAttributes(mv);
    mv.visitInsn(ARETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.glowroot.advicegen.AdviceGenerator.java

License:Apache License

private void addOnReturnMethod(ClassWriter cw) {
    boolean entryOrTimer = !config.traceEntryEnabledProperty().isEmpty();
    String travelerType = entryOrTimer ? "Ljava/lang/Object;" : "Lorg/glowroot/api/TraceEntry;";
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "onReturn",
            "(Lorg/glowroot/api/OptionalReturn;" + travelerType + ")V", null, null);
    mv.visitParameterAnnotation(0, "Lorg/glowroot/api/weaving/BindOptionalReturn;", true).visitEnd();
    mv.visitParameterAnnotation(1, "Lorg/glowroot/api/weaving/BindTraveler;", true).visitEnd();
    int travelerParamIndex = 1;
    mv.visitAnnotation("Lorg/glowroot/api/weaving/OnReturn;", true).visitEnd();
    mv.visitCode();/* ww  w  .j  a  v  a  2 s. c o m*/
    if (!config.traceEntryEnabledProperty().isEmpty()) {
        mv.visitVarInsn(ALOAD, travelerParamIndex);
        mv.visitTypeInsn(INSTANCEOF, "org/glowroot/api/Timer");
        Label label = new Label();
        mv.visitJumpInsn(IFEQ, label);
        mv.visitVarInsn(ALOAD, travelerParamIndex);
        mv.visitTypeInsn(CHECKCAST, "org/glowroot/api/Timer");
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/Timer", "stop", "()V", true);
        mv.visitInsn(RETURN);
        mv.visitLabel(label);
        mv.visitFrame(F_SAME, 0, null, 0, null);
    }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/OptionalReturn", "isVoid", "()Z", true);
    Label notVoidLabel = new Label();
    Label endIfLabel = new Label();
    mv.visitJumpInsn(IFEQ, notVoidLabel);
    mv.visitLdcInsn("void");
    mv.visitJumpInsn(GOTO, endIfLabel);
    mv.visitLabel(notVoidLabel);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/OptionalReturn", "getValue", "()Ljava/lang/Object;",
            true);
    mv.visitLabel(endIfLabel);
    mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/advicegen/GenericMessageSupplier", "updateWithReturnValue",
            "(Lorg/glowroot/api/TraceEntry;Ljava/lang/Object;)V", false);
    mv.visitVarInsn(ALOAD, travelerParamIndex);
    Long stackTraceThresholdMillis = config.traceEntryStackThresholdMillis();
    if (stackTraceThresholdMillis == null) {
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/TraceEntry", "end", "()V", true);
    } else {
        mv.visitLdcInsn(stackTraceThresholdMillis);
        mv.visitFieldInsn(GETSTATIC, "java/util/concurrent/TimeUnit", "MILLISECONDS",
                "Ljava/util/concurrent/TimeUnit;");
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/TraceEntry", "endWithStackTrace",
                "(JLjava/util/concurrent/TimeUnit;)V", true);
    }
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.glowroot.advicegen.AdviceGenerator.java

License:Apache License

private void addOnThrowMethod(ClassWriter cw) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "onThrow",
            "(Ljava/lang/Throwable;Lorg/glowroot/api/TraceEntry;)V", null, null);
    mv.visitAnnotation("Lorg/glowroot/api/weaving/OnThrow;", true).visitEnd();
    mv.visitParameterAnnotation(0, "Lorg/glowroot/api/weaving/BindThrowable;", true).visitEnd();
    mv.visitParameterAnnotation(1, "Lorg/glowroot/api/weaving/BindTraveler;", true).visitEnd();
    mv.visitCode();/*from   w  w  w . ja v a2  s. co m*/
    if (!config.traceEntryEnabledProperty().isEmpty()) {
        mv.visitVarInsn(ALOAD, 1);
        Label l0 = new Label();
        mv.visitJumpInsn(IFNONNULL, l0);
        mv.visitInsn(RETURN);
        mv.visitLabel(l0);
        mv.visitFrame(F_SAME, 0, null, 0, null);
    }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/api/ErrorMessage", "from",
            "(Ljava/lang/Throwable;)Lorg/glowroot/api/ErrorMessage;", false);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/TraceEntry", "endWithError",
            "(Lorg/glowroot/api/ErrorMessage;)V", true);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

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

License:Apache License

static LazyDefinedClass generateMoreHackedConstructorBytecode() throws Exception {

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    MethodVisitor mv;

    // 1.7+ since testing frames
    cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "MoreHackedConstructorBytecode", null,
            Test.class.getName().replace('.', '/'), new String[] {});

    {//from  w w  w .  j av  a2s  .co  m
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label trueLabel = new Label();
        mv.visitInsn(ICONST_0);
        mv.visitJumpInsn(IFEQ, trueLabel);
        mv.visitInsn(ACONST_NULL);
        mv.visitInsn(ATHROW);
        mv.visitLabel(trueLabel);
        mv.visitFrame(F_SAME, 0, null, 0, null);

        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, Test.class.getName().replace('.', '/'), "<init>", "()V", false);

        mv.visitInsn(RETURN);

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

    return ImmutableLazyDefinedClass.builder().type(Type.getObjectType("MoreHackedConstructorBytecode"))
            .bytes(cw.toByteArray()).build();
}

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

License:Apache License

@RequiresNonNull({ "type", "metaHolderInternalName", "loader" })
private void generateMetaHolder() throws Exception {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
    cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, metaHolderInternalName, null, "java/lang/Object", null);
    Type metaHolderType = Type.getObjectType(metaHolderInternalName);
    MethodVisitor mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
    mv.visitCode();// w w w  .ja  va2 s  .  c  o  m
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, "java/lang/ClassNotFoundException");
    mv.visitLabel(l0);
    for (Type classMetaType : classMetaTypes) {
        String classMetaInternalName = classMetaType.getInternalName();
        String classMetaFieldName = "glowroot$class$meta$" + classMetaInternalName.replace('/', '$');
        FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, classMetaFieldName,
                "L" + classMetaInternalName + ";", null, null);
        fv.visitEnd();
        mv.visitTypeInsn(NEW, classMetaInternalName);
        mv.visitInsn(DUP);
        loadType(mv, type, metaHolderType);
        mv.visitMethodInsn(INVOKESPECIAL, classMetaInternalName, "<init>", "(Ljava/lang/Class;)V", false);
        mv.visitFieldInsn(PUTSTATIC, metaHolderInternalName, classMetaFieldName,
                "L" + classMetaInternalName + ";");
    }
    for (MethodMetaGroup methodMetaGroup : methodMetaGroups) {
        for (Type methodMetaType : methodMetaGroup.methodMetaTypes()) {
            String methodMetaInternalName = methodMetaType.getInternalName();
            String methodMetaFieldName = "glowroot$method$meta$" + methodMetaGroup.uniqueNum() + '$'
                    + methodMetaInternalName.replace('/', '$');
            FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, methodMetaFieldName,
                    "L" + methodMetaInternalName + ";", null, null);
            fv.visitEnd();
            mv.visitTypeInsn(NEW, methodMetaInternalName);
            mv.visitInsn(DUP);
            loadType(mv, type, metaHolderType);
            mv.visitLdcInsn(methodMetaGroup.methodName());
            mv.visitIntInsn(BIPUSH, methodMetaGroup.methodParameterTypes().size());
            mv.visitTypeInsn(ANEWARRAY, "java/lang/Class");
            for (int i = 0; i < methodMetaGroup.methodParameterTypes().size(); i++) {
                mv.visitInsn(DUP);
                mv.visitIntInsn(BIPUSH, i);
                loadType(mv, methodMetaGroup.methodParameterTypes().get(i), metaHolderType);
                mv.visitInsn(AASTORE);
            }
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod",
                    "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
            mv.visitMethodInsn(INVOKESPECIAL, methodMetaInternalName, "<init>", "(Ljava/lang/reflect/Method;)V",
                    false);
            mv.visitFieldInsn(PUTSTATIC, metaHolderInternalName, methodMetaFieldName,
                    "L" + methodMetaInternalName + ";");
        }
    }
    // this is just try/catch ClassNotFoundException/re-throw AssertionError
    mv.visitLabel(l1);
    Label l3 = new Label();
    mv.visitJumpInsn(GOTO, l3);
    mv.visitLabel(l2);
    mv.visitFrame(F_SAME1, 0, null, 1, new Object[] { "java/lang/ClassNotFoundException" });
    mv.visitVarInsn(ASTORE, 0);
    mv.visitTypeInsn(NEW, "java/lang/AssertionError");
    mv.visitInsn(DUP);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/AssertionError", "<init>", "(Ljava/lang/Object;)V", false);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l3);
    mv.visitFrame(F_SAME, 0, null, 0, null);

    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
    cw.visitEnd();
    byte[] bytes = cw.toByteArray();
    ClassLoaders.defineClass(ClassNames.fromInternalName(metaHolderInternalName), bytes, loader);
}

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

License:Apache License

@RequiresNonNull({ "type", "metaHolderInternalName", "loader" })
private void generateMetaHolder() throws Exception {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
    cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, metaHolderInternalName, null, "java/lang/Object", null);
    Type metaHolderType = Type.getObjectType(metaHolderInternalName);
    MethodVisitor mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
    mv.visitCode();//from ww  w.j ava 2s  . co m
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, "java/lang/ClassNotFoundException");
    mv.visitLabel(l0);
    for (Type classMetaType : classMetaTypes) {
        String classMetaInternalName = classMetaType.getInternalName();
        String classMetaFieldName = "glowroot$class$meta$" + classMetaInternalName.replace('/', '$');
        FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, classMetaFieldName,
                "L" + classMetaInternalName + ";", null, null);
        fv.visitEnd();
        mv.visitTypeInsn(NEW, classMetaInternalName);
        mv.visitInsn(DUP);
        loadType(mv, type, metaHolderType);
        mv.visitMethodInsn(INVOKESPECIAL, classMetaInternalName, "<init>", "(Ljava/lang/Class;)V", false);
        mv.visitFieldInsn(PUTSTATIC, metaHolderInternalName, classMetaFieldName,
                "L" + classMetaInternalName + ";");
    }
    for (MethodMetaGroup methodMetaGroup : methodMetaGroups) {
        for (Type methodMetaType : methodMetaGroup.methodMetaTypes()) {
            String methodMetaInternalName = methodMetaType.getInternalName();
            String methodMetaFieldName = "glowroot$method$meta$" + methodMetaGroup.uniqueNum() + '$'
                    + methodMetaInternalName.replace('/', '$');
            FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, methodMetaFieldName,
                    "L" + methodMetaInternalName + ";", null, null);
            fv.visitEnd();
            mv.visitTypeInsn(NEW, methodMetaInternalName);
            mv.visitInsn(DUP);
            loadType(mv, type, metaHolderType);
            loadType(mv, methodMetaGroup.returnType(), metaHolderType);

            mv.visitIntInsn(BIPUSH, methodMetaGroup.parameterTypes().size());
            mv.visitTypeInsn(ANEWARRAY, "java/lang/Class");
            for (int i = 0; i < methodMetaGroup.parameterTypes().size(); i++) {
                mv.visitInsn(DUP);
                mv.visitIntInsn(BIPUSH, i);
                loadType(mv, methodMetaGroup.parameterTypes().get(i), metaHolderType);
                mv.visitInsn(AASTORE);
            }

            mv.visitMethodInsn(INVOKESPECIAL, methodMetaInternalName, "<init>",
                    "(Ljava/lang/Class;Ljava/lang/Class;[Ljava/lang/Class;)V", false);
            mv.visitFieldInsn(PUTSTATIC, metaHolderInternalName, methodMetaFieldName,
                    "L" + methodMetaInternalName + ";");
        }
    }
    // this is just try/catch ClassNotFoundException/re-throw AssertionError
    mv.visitLabel(l1);
    Label l3 = new Label();
    mv.visitJumpInsn(GOTO, l3);
    mv.visitLabel(l2);
    mv.visitFrame(F_SAME1, 0, null, 1, new Object[] { "java/lang/ClassNotFoundException" });
    mv.visitVarInsn(ASTORE, 0);
    mv.visitTypeInsn(NEW, "java/lang/AssertionError");
    mv.visitInsn(DUP);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/AssertionError", "<init>", "(Ljava/lang/Object;)V", false);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l3);
    mv.visitFrame(F_SAME, 0, null, 0, null);

    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
    cw.visitEnd();
    byte[] bytes = cw.toByteArray();
    ClassLoaders.defineClass(ClassNames.fromInternalName(metaHolderInternalName), bytes, loader);
}

From source file:org.jacoco.core.instr.ClassFileVersionsTest.java

License:Open Source License

/**
 * Creates a class that requires a frame before the return statement. Also
 * for this class instrumentation should insert another frame.
 *
 * <code><pre>/*from www  . j  ava 2 s  .  c  o m*/
 * public class Sample {
 *   public Sample(boolean b){
 *     if(b){
 *       toString();
 *     }
 *     return;
 *   }
 * }
 * </pre></code>
 */
private byte[] createClass(int version, boolean frames) {

    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(version, ACC_PUBLIC + ACC_SUPER, "org/jacoco/test/Sample", null, "java/lang/Object", null);

    mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(Z)V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mv.visitVarInsn(ILOAD, 1);
    Label l1 = new Label();
    mv.visitJumpInsn(IFEQ, l1);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;", false);
    mv.visitInsn(POP);
    mv.visitLabel(l1);
    if (frames) {
        mv.visitFrame(F_NEW, 2, new Object[] { "org/jacoco/test/Sample", Opcodes.INTEGER }, 0, new Object[] {});
    }
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    cw.visitEnd();

    return cw.toByteArray();
}

From source file:org.jacoco.core.internal.flow.FrameSnapshot.java

License:Open Source License

public void accept(final MethodVisitor mv) {
    if (locals != null) {
        mv.visitFrame(Opcodes.F_NEW, locals.length, locals, stack.length, stack);
    }//from w w w  .j  av  a  2  s .c  om
}

From source file:org.jacoco.core.internal.instr.ClassFieldProbeArrayStrategy.java

License:Open Source License

private void createInitMethod(final ClassVisitor cv, final int probeCount) {
    final MethodVisitor mv = cv.visitMethod(InstrSupport.INITMETHOD_ACC, InstrSupport.INITMETHOD_NAME,
            InstrSupport.INITMETHOD_DESC, null, null);
    mv.visitCode();//w  ww  .j av  a2  s.  c  o m

    // Load the value of the static data field:
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, InstrSupport.DATAFIELD_NAME, InstrSupport.DATAFIELD_DESC);
    mv.visitInsn(Opcodes.DUP);

    // Stack[1]: [Z
    // Stack[0]: [Z

    // Skip initialization when we already have a data array:
    final Label alreadyInitialized = new Label();
    mv.visitJumpInsn(Opcodes.IFNONNULL, alreadyInitialized);

    // Stack[0]: [Z

    mv.visitInsn(Opcodes.POP);
    final int size = genInitializeDataField(mv, probeCount);

    // Stack[0]: [Z

    // Return the class' probe array:
    if (withFrames) {
        mv.visitFrame(Opcodes.F_NEW, 0, FRAME_LOCALS_EMPTY, 1, FRAME_STACK_ARRZ);
    }
    mv.visitLabel(alreadyInitialized);
    mv.visitInsn(Opcodes.ARETURN);

    mv.visitMaxs(Math.max(size, 2), 0); // Maximum local stack size is 2
    mv.visitEnd();
}