Example usage for org.objectweb.asm MethodVisitor visitIntInsn

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

Introduction

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

Prototype

public void visitIntInsn(final int opcode, final int operand) 

Source Link

Document

Visits an instruction with a single int operand.

Usage

From source file:org.diorite.inject.impl.utils.AsmUtils.java

License:Open Source License

public static void storeInt(MethodVisitor mv, int i) {
    switch (i) {/* w  w  w . j  ava  2s .  c o  m*/
    case 0:
        mv.visitInsn(ICONST_0);
        break;
    case 1:
        mv.visitInsn(ICONST_1);
        break;
    case 2:
        mv.visitInsn(ICONST_2);
        break;
    case 3:
        mv.visitInsn(ICONST_3);
        break;
    case 4:
        mv.visitInsn(ICONST_4);
        break;
    default:
        mv.visitIntInsn(BIPUSH, i);
        break;
    }

}

From source file:org.eclipse.m2m.atl.emftvm.jit.CodeBlockJIT.java

License:Open Source License

/**
 * Generates an optimised instruction for pushing a constant integer <code>value</code>
 * onto the stack.//from  w  w w  .  ja va  2 s.  c  om
 * @param value the constant integer value to push
 */
static void generatePushInt(final MethodVisitor mv, final int value) {
    if (value >= -1 && value <= 5) {
        switch (value) {
        case -1:
            mv.visitInsn(ICONST_M1);
            break;
        case 0:
            mv.visitInsn(ICONST_0);
            break;
        case 1:
            mv.visitInsn(ICONST_1);
            break;
        case 2:
            mv.visitInsn(ICONST_2);
            break;
        case 3:
            mv.visitInsn(ICONST_3);
            break;
        case 4:
            mv.visitInsn(ICONST_4);
            break;
        default:
            mv.visitInsn(ICONST_5);
            assert value == 5;
            break;
        }
    } else if (value < Byte.MAX_VALUE && value > Byte.MIN_VALUE) {
        mv.visitIntInsn(BIPUSH, value);
    } else if (value < Short.MAX_VALUE && value > Short.MIN_VALUE) {
        mv.visitIntInsn(SIPUSH, value);
    } else {
        mv.visitLdcInsn(value);
    }
}

From source file:org.eclipse.objectteams.otredyn.bytecode.asm.AddImplicitActivationAdapter.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if (isCandidateForImplicitActivation(name, desc, access)) {
        final MethodVisitor methodVisitor = cv.visitMethod(access, name, desc, null, null);
        final String enclTeamDesc = clazz.isRole()
                ? 'L' + clazz.getEnclosingClass().getName().replace('.', '/') + ';'
                : null;//from w  w  w .  j av  a 2  s  .  c o  m
        final int nesting = clazz.nestingDepth() - 1;
        return new AdviceAdapter(this.api, methodVisitor, access, name, desc) {
            @Override
            protected void onMethodEnter() {
                if (clazz.isTeam()) {
                    methodVisitor.visitIntInsn(Opcodes.ALOAD, 0);
                    methodVisitor.visitMethodInsn(INVOKEINTERFACE, TARGET_CLASS_NAME,
                            IMPLICIT_ACTIVATE_METHOD_NAME, METHOD_DESC, true);
                }
                if (clazz.isRole()) {
                    // TODO(SH): respect nesting depth (this$n)
                    methodVisitor.visitIntInsn(Opcodes.ALOAD, 0);
                    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, clazz.getName().replace('.', '/'),
                            "this$" + nesting, enclTeamDesc);
                    methodVisitor.visitMethodInsn(INVOKEINTERFACE, TARGET_CLASS_NAME,
                            IMPLICIT_ACTIVATE_METHOD_NAME, METHOD_DESC, true);
                }
            }

            @Override
            protected void onMethodExit(int opcode) {
                if (clazz.isTeam()) {
                    methodVisitor.visitIntInsn(Opcodes.ALOAD, 0);
                    methodVisitor.visitMethodInsn(INVOKEINTERFACE, TARGET_CLASS_NAME,
                            IMPLICIT_DEACTIVATE_METHOD_NAME, METHOD_DESC, true);
                }
                if (clazz.isRole()) {
                    // TODO(SH): respect nesting depth (this$n)
                    methodVisitor.visitIntInsn(Opcodes.ALOAD, 0);
                    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, clazz.getName().replace('.', '/'),
                            "this$" + nesting, enclTeamDesc);
                    methodVisitor.visitMethodInsn(INVOKEINTERFACE, TARGET_CLASS_NAME,
                            IMPLICIT_DEACTIVATE_METHOD_NAME, METHOD_DESC, true);
                }
            }

            @Override
            public void endMethod() {
                if (clazz.isTeam() || clazz.isRole())
                    methodVisitor.visitMaxs(0, 0);
            }
        };
    }
    return null;
}

From source file:org.eclipse.objectteams.otredyn.bytecode.asm.AddThreadNotificationAdapter.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String methodName, String desc, String signature,
        String[] exceptions) {//from  ww w .  ja va2  s.c  om
    if (INIT.equals(methodName)) {
        // into each constructor ...
        final MethodVisitor methodVisitor = cv.visitMethod(access, methodName, desc, null, null);
        return new AdviceAdapter(this.api, methodVisitor, access, methodName, desc) {
            @Override
            public void invokeConstructor(Type type, Method method) {
                super.invokeConstructor(type, method);
                // ... that contains a super(..) call (rather than this(..)):
                if (type.getInternalName().equals(clazz.getInternalSuperClassName())) {
                    // insert:
                    // this._OT$creationThread = Thread.currentThread();
                    methodVisitor.visitIntInsn(Opcodes.ALOAD, 0);
                    methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, ClassNames.THREAD_SLASH, CURRENT_THREAD,
                            CURRENT_THREAD_DESC, false);
                    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, clazz.getInternalName(), CREATION_THREAD,
                            THREAD_DESC);
                }
            }
        };
    } else if (RUN.equals(methodName) && RUN_DESC.equals(desc)) {
        final MethodVisitor methodVisitor = cv.visitMethod(access, methodName, desc, null, null);
        return new AdviceAdapter(this.api, methodVisitor, access, methodName, desc) {

            Label start = new Label(); // start of method (scope of new local)
            Label end = new Label(); // end of method
            int isThreadStartIdx; // new local: boolean _OT$isThreadStart

            @Override
            protected void onMethodEnter() {
                methodVisitor.visitLabel(start);
                isThreadStartIdx = newLocal(Type.BOOLEAN_TYPE);
                methodVisitor.visitLocalVariable("_OT$isThreadStart", "Z", null, start, end, isThreadStartIdx);
                // TeamThreadManager.newThreadStarted(false, this._OT$creationThread)
                methodVisitor.visitInsn(Opcodes.ICONST_0);
                methodVisitor.visitIntInsn(Opcodes.ALOAD, 0);
                methodVisitor.visitFieldInsn(Opcodes.GETFIELD, clazz.getInternalName(), CREATION_THREAD,
                        THREAD_DESC);
                methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, ClassNames.TEAM_THREAD_MANAGER_SLASH,
                        NEW_THREAD_STARTED, NEW_THREAD_STARTED_DESC, false);
                methodVisitor.visitIntInsn(Opcodes.ISTORE, isThreadStartIdx);
                // this._OT$creationThread = null; // avoid leak
                methodVisitor.visitIntInsn(Opcodes.ALOAD, 0);
                methodVisitor.visitInsn(Opcodes.ACONST_NULL);
                methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, clazz.getInternalName(), CREATION_THREAD,
                        THREAD_DESC);
            }

            @Override
            protected void onMethodExit(int opcode) {
                insertThreadEndedNotification();
            }

            @Override
            public void endMethod() {
                methodVisitor.visitLabel(end);

                // insert another threadEnded notification as a handler for Throwable
                Label handler = new Label();
                methodVisitor.visitLabel(handler);
                insertThreadEndedNotification();
                methodVisitor.visitInsn(Opcodes.ATHROW); // rethrow caught exception

                methodVisitor.visitTryCatchBlock(start, end, handler, ClassNames.THROWABLE_SLASH);
                methodVisitor.visitMaxs(0, 0);
            }

            void insertThreadEndedNotification() {
                Label skip = new Label();
                // insert:
                // if (_OT$isThreadStart) TeamThreadManager.threadEnded();
                methodVisitor.visitIntInsn(Opcodes.ILOAD, isThreadStartIdx);
                methodVisitor.visitJumpInsn(Opcodes.IFEQ, skip);
                methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, ClassNames.TEAM_THREAD_MANAGER_SLASH,
                        THREAD_ENDED, THREAD_ENDED_DESC, false);
                methodVisitor.visitLabel(skip);
            }
        };
    }
    return null;
}

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 {/*  www  . j  a v a 2  s  .c  o m*/
        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.fabric3.implementation.bytecode.proxy.common.ProxyFactoryImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public void emitWrappedParameters(Method method, MethodVisitor mv, int[] index, int[] stack) {
    int numberOfParameters = method.getParameterTypes().length;

    // create the Object[] used to pass the parameters to _f3_invoke and push it on the stack
    if (numberOfParameters >= 0 && numberOfParameters <= 5) {
        // use an integer constant if within range
        mv.visitInsn(Opcodes.ICONST_0 + numberOfParameters);
    } else {//from ww  w.j  av a 2 s.c  o m
        mv.visitIntInsn(Opcodes.BIPUSH, numberOfParameters);
    }
    mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
    mv.visitInsn(DUP);

    for (Class<?> param : method.getParameterTypes()) {
        if (Integer.TYPE.equals(param)) {
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(Opcodes.ILOAD, stack[0]);
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;");
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
        } else if (Float.TYPE.equals(param)) {
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(Opcodes.FLOAD, stack[0]);
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;");
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
        } else if (Boolean.TYPE.equals(param)) {
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(Opcodes.ILOAD, stack[0]);
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;");
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
        } else if (Short.TYPE.equals(param)) {
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(Opcodes.ILOAD, stack[0]);
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;");
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
        } else if (Byte.TYPE.equals(param)) {
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(Opcodes.ILOAD, stack[0]);
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;");
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
        } else if (Double.TYPE.equals(param)) {
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(Opcodes.DLOAD, stack[0]);
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;");
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
            stack[0]++; // double occupies two positions

        } else if (Long.TYPE.equals(param)) {
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(Opcodes.LLOAD, stack[0]);
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;");
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
            stack[0]++; // long occupies two positions
        } else {
            // object type
            mv.visitInsn(Opcodes.ICONST_0 + index[0]);
            mv.visitVarInsn(ALOAD, stack[0]);
            mv.visitInsn(AASTORE);
            if (index[0] < numberOfParameters - 1) {
                mv.visitInsn(DUP);
            }
        }
        index[0]++;
    }
    // TODO other primitive types
    stack[0]++;

}

From source file:org.fabric3.monitor.impl.proxy.BytecodeMonitorProxyService.java

License:Open Source License

/**
 * Pushes an integer onto the stack//w w w  .  ja  v  a  2  s .c o m
 *
 * @param value the value to push
 * @param mv    the method visitor
 */
private void pushInteger(int value, MethodVisitor mv) {
    if (value == 0) {
        mv.visitInsn(ICONST_0);
    } else if (value == 1) {
        mv.visitInsn(ICONST_1);
    } else if (value == 2) {
        mv.visitInsn(ICONST_2);
    } else if (value == 3) {
        mv.visitInsn(ICONST_3);
    } else if (value == 4) {
        mv.visitInsn(ICONST_4);
    } else if (value == 5) {
        mv.visitInsn(ICONST_5);
    } else {
        mv.visitIntInsn(BIPUSH, value);
    }
}

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

License:Apache License

private void addCodeForOptionalTransactionAttributes(MethodVisitor mv) {
    if (!config.transactionType().isEmpty() && !config.isTransaction()) {
        mv.visitVarInsn(ALOAD, 0);//from w  ww.  j  a va 2  s .  co  m
        mv.visitLdcInsn(config.transactionType());
        mv.visitIntInsn(BIPUSH, Priority.USER_CONFIG);
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/ThreadContext", "setTransactionType",
                "(Ljava/lang/String;I)V", true);
    }
    if (!config.transactionNameTemplate().isEmpty() && !config.isTransaction()) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 4);
        // methodMetaInternalName is non-null when transactionNameTemplate is non-empty
        checkNotNull(methodMetaInternalName);
        mv.visitMethodInsn(INVOKEVIRTUAL, methodMetaInternalName, "getTransactionNameTemplate",
                "()Lorg/glowroot/agent/advicegen/MessageTemplate;", false);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitVarInsn(ALOAD, 2);
        mv.visitVarInsn(ALOAD, 3);
        mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/agent/advicegen/GenericMessageSupplier", "create",
                "(Lorg/glowroot/agent/advicegen/MessageTemplate;Ljava/lang/Object;"
                        + "Ljava/lang/String;[Ljava/lang/Object;)"
                        + "Lorg/glowroot/agent/advicegen/GenericMessageSupplier;",
                false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/agent/advicegen/GenericMessageSupplier",
                "getMessageText", "()Ljava/lang/String;", false);
        mv.visitIntInsn(BIPUSH, Priority.USER_CONFIG);
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/ThreadContext", "setTransactionName",
                "(Ljava/lang/String;I)V", true);
    }
    if (!config.transactionUserTemplate().isEmpty()) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 4);
        // methodMetaInternalName is non-null when transactionUserTemplate is non-empty
        checkNotNull(methodMetaInternalName);
        mv.visitMethodInsn(INVOKEVIRTUAL, methodMetaInternalName, "getTransactionUserTemplate",
                "()Lorg/glowroot/agent/advicegen/MessageTemplate;", false);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitVarInsn(ALOAD, 2);
        mv.visitVarInsn(ALOAD, 3);
        mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/agent/advicegen/GenericMessageSupplier", "create",
                "(Lorg/glowroot/agent/advicegen/MessageTemplate;Ljava/lang/Object;"
                        + "Ljava/lang/String;[Ljava/lang/Object;)"
                        + "Lorg/glowroot/agent/advicegen/GenericMessageSupplier;",
                false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/agent/advicegen/GenericMessageSupplier",
                "getMessageText", "()Ljava/lang/String;", false);
        mv.visitIntInsn(BIPUSH, Priority.USER_CONFIG);
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/ThreadContext", "setTransactionUser",
                "(Ljava/lang/String;I)V", true);
    }
    int i = 0;
    for (String attrName : config.transactionAttributeTemplates().keySet()) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitLdcInsn(attrName);
        mv.visitVarInsn(ALOAD, 4);
        // methodMetaInternalName is non-null when transactionAttributeTemplates is
        // non-empty
        checkNotNull(methodMetaInternalName);
        mv.visitMethodInsn(INVOKEVIRTUAL, methodMetaInternalName, "getTransactionAttributeTemplate" + i++,
                "()Lorg/glowroot/agent/advicegen/MessageTemplate;", false);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitVarInsn(ALOAD, 2);
        mv.visitVarInsn(ALOAD, 3);
        mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/agent/advicegen/GenericMessageSupplier", "create",
                "(Lorg/glowroot/agent/advicegen/MessageTemplate;"
                        + "Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;)"
                        + "Lorg/glowroot/agent/advicegen/GenericMessageSupplier;",
                false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/agent/advicegen/GenericMessageSupplier",
                "getMessageText", "()Ljava/lang/String;", false);
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/ThreadContext",
                "addTransactionAttribute", "(Ljava/lang/String;Ljava/lang/String;)V", true);
    }
    Integer slowThresholdMillis = config.transactionSlowThresholdMillis();
    if (slowThresholdMillis != null) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitLdcInsn(slowThresholdMillis.longValue());
        mv.visitFieldInsn(GETSTATIC, "java/util/concurrent/TimeUnit", "MILLISECONDS",
                "Ljava/util/concurrent/TimeUnit;");
        mv.visitIntInsn(BIPUSH, Priority.USER_CONFIG);
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/ThreadContext",
                "setTransactionSlowThreshold", "(JLjava/util/concurrent/TimeUnit;I)V", true);

    }
}

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

License:Apache License

static LazyDefinedClass generateHackedConstructorBytecode() throws Exception {

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

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

    {//from  w  ww .ja v  a2  s .co  m
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitInsn(ICONST_1);
        mv.visitIntInsn(NEWARRAY, T_BOOLEAN);
        mv.visitVarInsn(ASTORE, 1);

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

        mv.visitVarInsn(ALOAD, 1);
        mv.visitInsn(ICONST_0);
        mv.visitInsn(ICONST_1);
        mv.visitInsn(BASTORE);

        mv.visitInsn(RETURN);

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

    return ImmutableLazyDefinedClass.builder().type(Type.getObjectType("HackedConstructorBytecode"))
            .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();/* ww  w  .  ja v  a 2  s . c om*/
    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);
}