Example usage for org.objectweb.asm Opcodes INVOKEVIRTUAL

List of usage examples for org.objectweb.asm Opcodes INVOKEVIRTUAL

Introduction

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

Prototype

int INVOKEVIRTUAL

To view the source code for org.objectweb.asm Opcodes INVOKEVIRTUAL.

Click Source Link

Usage

From source file:org.evosuite.instrumentation.MethodCallReplacementMethodAdapter.java

License:Open Source License

/** {@inheritDoc} */
@Override//  w w w  .  ja va 2 s .  c  o  m
public void visitMethodInsn(int opcode, String owner, String name, String desc) {

    boolean isReplaced = false;
    // static replacement methods
    for (MethodCallReplacement replacement : replacementCalls) {
        if (replacement.isTarget(owner, name, desc)) {
            isReplaced = true;
            replacement.insertMethodCall(this, Opcodes.INVOKESTATIC);
            break;
        }
    }

    // for constructors
    if (!isReplaced) {
        for (MethodCallReplacement replacement : specialReplacementCalls) {
            if (replacement.isTarget(owner, name, desc) && opcode == Opcodes.INVOKESPECIAL) {
                isReplaced = true;
                boolean isSelf = false;
                if (needToWaitForSuperConstructor) {
                    String originalClassNameWithDots = owner.replace('/', '.');
                    if (originalClassNameWithDots.equals(superClassName)) {
                        isSelf = true;
                    }
                }
                if (replacement.methodName.equals("<init>"))
                    replacement.insertConstructorCall(this, replacement, isSelf);
                else
                    replacement.insertMethodCall(this, Opcodes.INVOKESPECIAL);
                break;
            }
        }
    }

    // non-static replacement methods
    if (!isReplaced) {
        for (MethodCallReplacement replacement : virtualReplacementCalls) {
            if (replacement.isTarget(owner, name, desc)) {
                isReplaced = true;
                replacement.insertMethodCall(this, Opcodes.INVOKEVIRTUAL);
                break;
            }
        }
    }

    if (!isReplaced) {
        super.visitMethodInsn(opcode, owner, name, desc);
    }
    if (needToWaitForSuperConstructor) {
        if (opcode == Opcodes.INVOKESPECIAL) {
            String originalClassNameWithDots = owner.replace('/', '.');
            if (originalClassNameWithDots.equals(superClassName)) {
                needToWaitForSuperConstructor = false;
            }
        }
    }

}

From source file:org.evosuite.instrumentation.mutation.DeleteStatement.java

License:Open Source License

/** {@inheritDoc} */
@Override//from  w  w w . j a  v  a 2 s  . co  m
public List<Mutation> apply(MethodNode mn, String className, String methodName, BytecodeInstruction instruction,
        Frame frame) {

    List<Mutation> mutations = new LinkedList<Mutation>();

    MethodInsnNode node = (MethodInsnNode) instruction.getASMNode();
    Type returnType = Type.getReturnType(node.desc);

    // insert mutation into bytecode with conditional
    InsnList mutation = new InsnList();
    logger.info("Mutation deletestatement for statement " + node.name + node.desc);
    for (Type argType : Type.getArgumentTypes(node.desc)) {
        if (argType.getSize() == 0)
            logger.info("Ignoring parameter of type " + argType);
        else if (argType.getSize() == 2) {
            mutation.insert(new InsnNode(Opcodes.POP2));
            logger.debug("Deleting parameter of 2 type " + argType);
        } else {
            logger.debug("Deleting parameter of 1 type " + argType);
            mutation.insert(new InsnNode(Opcodes.POP));
        }
    }
    if (node.getOpcode() == Opcodes.INVOKEVIRTUAL) {
        logger.debug("Deleting callee of type " + node.owner);
        mutation.add(new InsnNode(Opcodes.POP));
    } else if (node.getOpcode() == Opcodes.INVOKEINTERFACE) {
        boolean isStatic = false;
        try {
            Class<?> clazz = Class.forName(node.owner.replace('/', '.'), false,
                    DeleteStatement.class.getClassLoader());
            for (java.lang.reflect.Method method : clazz.getMethods()) {
                if (method.getName().equals(node.name)) {
                    if (Type.getMethodDescriptor(method).equals(node.desc)) {
                        if (Modifier.isStatic(method.getModifiers()))
                            isStatic = true;
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            logger.warn("Could not find class: " + node.owner + ", this is likely a severe problem");
        }
        if (!isStatic) {
            logger.info("Deleting callee of type " + node.owner);
            mutation.add(new InsnNode(Opcodes.POP));
        }
    }
    mutation.add(getDefault(returnType));

    // insert mutation into pool
    Mutation mutationObject = MutationPool.addMutation(className, methodName,
            NAME + " " + node.name + node.desc, instruction, mutation, Mutation.getDefaultInfectionDistance());

    mutations.add(mutationObject);
    return mutations;
}

From source file:org.evosuite.instrumentation.PurityAnalysisMethodVisitor.java

License:Open Source License

@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {

    String targetClassName = owner.replace('/', '.');
    if (targetClassName.equals(org.evosuite.runtime.Random.class.getCanonicalName())
            || !BytecodeInstrumentation.checkIfEvoSuitePackage(targetClassName)) {
        //Only ignore EvoSuite callbacks
        if (opcode == Opcodes.INVOKESTATIC) {
            this.purityAnalyzer.addStaticCall(classNameWithDots, methodName, descriptor, targetClassName, name,
                    desc);//from   w w  w .j a v  a 2  s . c  o  m
        } else if (opcode == Opcodes.INVOKEVIRTUAL) {
            this.purityAnalyzer.addVirtualCall(classNameWithDots, methodName, descriptor, targetClassName, name,
                    desc);

        } else if (opcode == Opcodes.INVOKEINTERFACE) {
            this.purityAnalyzer.addInterfaceCall(classNameWithDots, methodName, descriptor, targetClassName,
                    name, desc);

        } else if (opcode == Opcodes.INVOKESPECIAL) {
            this.purityAnalyzer.addSpecialCall(classNameWithDots, methodName, descriptor, targetClassName, name,
                    desc);
        }
    }
    super.visitMethodInsn(opcode, owner, name, desc, itf);
}

From source file:org.evosuite.runtime.instrumentation.LoopCounterMethodAdapter.java

License:Open Source License

private void addInstrumentation() {

    int index = LoopCounter.getInstance().getNewIndex();

    mv.visitMethodInsn(Opcodes.INVOKESTATIC, LOOP_COUNTER, "getInstance", "()L" + LOOP_COUNTER + ";", false);

    mv.visitLdcInsn(index);//from w  ww.j a  v  a  2s.  c om

    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LOOP_COUNTER, "checkLoop", "(I)V", false);
}

From source file:org.evosuite.runtime.instrumentation.MethodCallReplacementCache.java

License:Open Source License

private MethodCallReplacementCache() {

    if (RuntimeSettings.mockJVMNonDeterminism) {

        // java.lang.*
        addJavaLangCalls();/* w  ww . j a  v a2s . c o  m*/

        // javax.swing.JComponent.getPreferredSize()
        addReplacementCall(new MethodCallReplacement("javax/swing/JComponent", "getPreferredSize",
                "()Ljava/awt/Dimension;", Opcodes.INVOKEVIRTUAL,
                PackageInfo.getNameWithSlash(org.evosuite.runtime.mock.javax.swing.MockJComponent.class),
                "getPreferredSize", "()Ljava/awt/Dimension;", true, false));

        addExtraceExceptionReplacements();

    }

    handleMockList();

}

From source file:org.evosuite.runtime.instrumentation.MethodCallReplacementCache.java

License:Open Source License

/**
 * Ideally, all mocking should be handled by either OverrideMock or
 * StaticReplacementMock. However, even in such cases, we would not be able
 * to get mocks from classes that are not instrumented (eg, other Java API
 * classes we do not mock). In theory, we should mock all of them. The
 * problem raises for "Exceptions", as they are used everywhere, and would
 * require to mock the full Java API (which is not going to happen...).
 * Solution is, beside using OverrideMock for them, to also a further static
 * replacement (implemented in this method).
 * <p/>/*from  www. j a v  a  2  s  .  com*/
 * <p/>
 * Note: why not just using static replacement instead of OverrideMock?
 * Because static replacement will not work if an exception instance is used
 * in a non-instrumented class, whereas OverrideMock would. Still, it could
 * be tedious to prepare OverrideMock for every single type of exception, so
 * the static replacement here could be a temporary workaround
 */
private void addExtraceExceptionReplacements() {

    List<Class<? extends Throwable>> classes = Arrays.asList(IOException.class,
            // following java.lang
            Throwable.class, ArithmeticException.class, ArrayIndexOutOfBoundsException.class,
            ArrayStoreException.class, ClassCastException.class, ClassNotFoundException.class,
            CloneNotSupportedException.class, EnumConstantNotPresentException.class, Exception.class,
            IllegalAccessException.class, IllegalArgumentException.class, IllegalMonitorStateException.class,
            IllegalStateException.class, IllegalThreadStateException.class, IndexOutOfBoundsException.class,
            InstantiationException.class, InterruptedException.class, NegativeArraySizeException.class,
            NoSuchFieldException.class, NoSuchMethodException.class, NullPointerException.class,
            NumberFormatException.class, ReflectiveOperationException.class, RuntimeException.class,
            SecurityException.class, StringIndexOutOfBoundsException.class, TypeNotPresentException.class,
            UnsupportedOperationException.class, AbstractMethodError.class, AssertionError.class,
            BootstrapMethodError.class, ClassCircularityError.class, ClassFormatError.class, Error.class,
            ExceptionInInitializerError.class, IllegalAccessError.class, IncompatibleClassChangeError.class,
            InstantiationError.class, InternalError.class, LinkageError.class, NoClassDefFoundError.class,
            NoSuchFieldError.class, NoSuchMethodError.class, OutOfMemoryError.class, StackOverflowError.class,
            ThreadDeath.class, UnknownError.class, UnsatisfiedLinkError.class,
            UnsupportedClassVersionError.class, VerifyError.class, VirtualMachineError.class);

    for (Class<?> k : classes) {

        String jvmOriginal = k.getName().replace('.', '/');
        String jvmMock = MockThrowable.class.getName().replace('.', '/');

        addReplacementCall(new MethodCallReplacement(jvmOriginal, "getStackTrace",
                "()[Ljava/lang/StackTraceElement;", Opcodes.INVOKEVIRTUAL, jvmMock, "replacement_getStackTrace",
                "(Ljava/lang/Throwable;)[Ljava/lang/StackTraceElement;", false, false));

        addReplacementCall(new MethodCallReplacement(jvmOriginal, "printStackTrace", "(Ljava/io/PrintStream;)V",
                Opcodes.INVOKEVIRTUAL, jvmMock, "replacement_printStackTrace",
                "(Ljava/lang/Throwable;Ljava/io/PrintStream;)V", false, false));

        addReplacementCall(new MethodCallReplacement(jvmOriginal, "printStackTrace", "(Ljava/io/PrintWriter;)V",
                Opcodes.INVOKEVIRTUAL, jvmMock, "replacement_printStackTrace",
                "(Ljava/lang/Throwable;Ljava/io/PrintWriter;)V", false, false));
    }

}

From source file:org.evosuite.runtime.instrumentation.MethodCallReplacementCache.java

License:Open Source License

private void addJavaLangCalls() {

    // java/lang/System
    addReplacementCall(new MethodCallReplacement("java/lang/System", "exit", "(I)V", Opcodes.INVOKESTATIC,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.System.class), "exit", "(I)V", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/System", "currentTimeMillis", "()J",
            Opcodes.INVOKESTATIC, PackageInfo.getNameWithSlash(org.evosuite.runtime.System.class),
            "currentTimeMillis", "()J", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/System", "nanoTime", "()J", Opcodes.INVOKESTATIC,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.System.class), "nanoTime", "()J", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/System", "identityHashCode",
            "(Ljava/lang/Object;)I", Opcodes.INVOKESTATIC, "org/evosuite/runtime/System", "identityHashCode",
            "(Ljava/lang/Object;)I", false, false));

    // java/lang/Object
    addReplacementCall(new MethodCallReplacement("java/lang/Object", "hashCode", "()I", Opcodes.INVOKEVIRTUAL,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.System.class), "identityHashCode",
            "(Ljava/lang/Object;)I", false, false));

    addReplacementCall(new MethodCallReplacement("java/lang/Object", "toString", "()Ljava/lang/String;",
            Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.System.class), "toString",
            "(Ljava/lang/Object;)Ljava/lang/String;", false, false));

    addReplacementCall(new MethodCallReplacement("java/lang/Math", "random", "()D", Opcodes.INVOKESTATIC,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.Random.class), "nextDouble", "()D", false,
            false));/*from  w ww . ja  va 2 s  . c om*/

    // java/lang/Class
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getClasses", "()[Ljava/lang/Class;",
            Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
            "getClasses", "(Ljava/lang/Class;)[Ljava/lang/Class;", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getAnnotations",
            "()[Ljava/lang/annotation/Annotation;", Opcodes.INVOKEVIRTUAL,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class), "getAnnotations",
            "(Ljava/lang/Class;)[Ljava/lang/annotation/Annotation;", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getFields", "()[Ljava/lang/reflect/Field;",
            Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
            "getFields", "(Ljava/lang/Class;)[Ljava/lang/reflect/Field;", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getConstructors",
            "()[Ljava/lang/reflect/Constructor;", Opcodes.INVOKEVIRTUAL,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class), "getConstructors",
            "(Ljava/lang/Class;)[Ljava/lang/reflect/Constructor;", false, false));
    addReplacementCall(
            new MethodCallReplacement("java/lang/Class", "getMethods", "()[Ljava/lang/reflect/Method;",
                    Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
                    "getMethods", "(Ljava/lang/Class;)[Ljava/lang/reflect/Method;", false, false));
    addReplacementCall(
            new MethodCallReplacement("java/lang/Class", "getDeclaredClasses", "()[Ljava/lang/Class;",
                    Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
                    "getDeclaredClasses", "(Ljava/lang/Class;)[Ljava/lang/Class;", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getDeclaredAnnotations",
            "()[Ljava/lang/annotation/Annotation;", Opcodes.INVOKEVIRTUAL,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class), "getDeclaredAnnotations",
            "(Ljava/lang/Class;)[Ljava/lang/annotation/Annotation;", false, false));
    addReplacementCall(
            new MethodCallReplacement("java/lang/Class", "getDeclaredFields", "()[Ljava/lang/reflect/Field;",
                    Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
                    "getDeclaredFields", "(Ljava/lang/Class;)[Ljava/lang/reflect/Field;", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getDeclaredConstructors",
            "()[Ljava/lang/reflect/Constructor;", Opcodes.INVOKEVIRTUAL,
            PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class), "getDeclaredConstructors",
            "(Ljava/lang/Class;)[Ljava/lang/reflect/Constructor;", false, false));
    addReplacementCall(
            new MethodCallReplacement("java/lang/Class", "getDeclaredMethods", "()[Ljava/lang/reflect/Method;",
                    Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
                    "getDeclaredMethods", "(Ljava/lang/Class;)[Ljava/lang/reflect/Method;", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getInterfaces", "()[Ljava/lang/Class;",
            Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
            "getInterfaces", "(Ljava/lang/Class;)[Ljava/lang/Class;", false, false));
    addReplacementCall(new MethodCallReplacement("java/lang/Class", "getModifiers", "()I",
            Opcodes.INVOKEVIRTUAL, PackageInfo.getNameWithSlash(org.evosuite.runtime.Reflection.class),
            "getModifiers", "(Ljava/lang/Class;)I", false, false));

    /*
     * 
     * FIXME: it is unclear why getResource was mocked away by always
     * returning null. At least at a first look, it seems quite wrong, and
     * it breaks quite a few static initializers (eg in Liferay). If it led
     * to some unstable tests, then we could just mock it properly
     * 
     * //java/lang/ClassLoader addReplacementCall(new
     * MethodCallReplacement("java/lang/ClassLoader", "getResource",
     * "(Ljava/lang/String;)Ljava/net/URL;", Opcodes.INVOKEVIRTUAL,
     * "org/evosuite/runtime/ResourceLoader", "getResource",
     * "(Ljava/lang/String;)Ljava/net/URL;", true, false));
     */
}

From source file:org.evosuite.runtime.instrumentation.MethodCallReplacementCache.java

License:Open Source License

private void replaceAllInstanceMethodsWithStatic(Class<?> mockClass, Class<?> target) {

    /*/* w w w. j  a v a 2 s  . com*/
     * replace "fooInstance.bar(x)" with "MockFooClass.bar(fooInstance,x)"
     */

    for (Method m : ReflectionUtils.getMethods(target)) {
        if (Modifier.isStatic(m.getModifiers())) {
            continue;
        }

        /*
         * TODO: should check Object methods, and see if they were mocked.
         * If not, we could just skip them. If other methods are not mocked,
         * should throw an exception?
         */
        Class<?>[] parameters = new Class<?>[m.getParameterCount() + 1];
        parameters[0] = target;
        int numParam = 1;
        for (Class<?> paramClass : m.getParameterTypes()) {
            parameters[numParam++] = paramClass;
        }

        try {
            mockClass.getMethod(m.getName(), parameters);
        } catch (NoSuchMethodException e) {
            logger.debug("Skipping method " + m.getName());
            continue;
        }

        String desc = Type.getMethodDescriptor(m);
        Type[] argumentTypes = Type.getArgumentTypes(m);
        Type[] mockedArgumentTypes = new Type[argumentTypes.length + 1];
        mockedArgumentTypes[0] = Type.getType(target);
        for (int i = 0; i < argumentTypes.length; i++)
            mockedArgumentTypes[i + 1] = argumentTypes[i];
        String mockedDesc = Type.getMethodDescriptor(Type.getReturnType(m), mockedArgumentTypes);
        addReplacementCall(new MethodCallReplacement(target.getCanonicalName().replace('.', '/'), m.getName(),
                desc, Opcodes.INVOKEVIRTUAL, mockClass.getCanonicalName().replace('.', '/'), m.getName(),
                mockedDesc, false, false));
    }
}

From source file:org.evosuite.testcarver.instrument.Instrumenter.java

License:Open Source License

/**
 *    public int myMethod(int i)// w ww .  j a v a2  s .  c o  m
   {
 try
 {
    return _sw_prototype_original_myMethod(i)
 }
 finally
 {
    Capturer.enable();
 }
   }
        
 * @param classNode
 * @param className
 * @param methodNode
 */
@SuppressWarnings("unchecked")
private MethodNode wrapMethod(final ClassNode classNode, final String className, final MethodNode methodNode) {
    methodNode.maxStack += 4;

    // create wrapper for original method
    final MethodNode wrappingMethodNode = new MethodNode(methodNode.access, methodNode.name, methodNode.desc,
            methodNode.signature,
            (String[]) methodNode.exceptions.toArray(new String[methodNode.exceptions.size()]));
    wrappingMethodNode.maxStack = methodNode.maxStack;

    // assign annotations to wrapping method
    wrappingMethodNode.visibleAnnotations = methodNode.visibleAnnotations;
    wrappingMethodNode.visibleParameterAnnotations = methodNode.visibleParameterAnnotations;

    // remove annotations from wrapped method to avoid wrong behavior controlled by annotations
    methodNode.visibleAnnotations = null;
    methodNode.visibleParameterAnnotations = null;

    // rename original method
    methodNode.access = TransformerUtil.modifyVisibility(methodNode.access, Opcodes.ACC_PRIVATE);

    final LabelNode l0 = new LabelNode();
    final LabelNode l1 = new LabelNode();
    final LabelNode l2 = new LabelNode();

    final InsnList wInstructions = wrappingMethodNode.instructions;

    if ("<init>".equals(methodNode.name)) {
        // wrap a constructor 

        methodNode.name = WRAP_NAME_PREFIX + "init" + WRAP_NAME_PREFIX;

        // move call to other constructors to new method
        AbstractInsnNode ins = null;
        ListIterator<AbstractInsnNode> iter = methodNode.instructions.iterator();

        int numInvokeSpecials = 0; // number of invokespecial calls before actual constructor call

        while (iter.hasNext()) {
            ins = iter.next();
            iter.remove();
            wInstructions.add(ins);

            if (ins instanceof MethodInsnNode) {
                MethodInsnNode mins = (MethodInsnNode) ins;
                if (ins.getOpcode() == Opcodes.INVOKESPECIAL) {
                    if (mins.name.startsWith("<init>")) {
                        if (numInvokeSpecials == 0) {
                            break;
                        } else {
                            numInvokeSpecials--;
                        }
                    }
                }
            } else if (ins instanceof TypeInsnNode) {
                TypeInsnNode typeIns = (TypeInsnNode) ins;
                if (typeIns.getOpcode() == Opcodes.NEW || typeIns.getOpcode() == Opcodes.NEWARRAY) {
                    numInvokeSpecials++;
                }
            }
        }
    } else {
        methodNode.name = WRAP_NAME_PREFIX + methodNode.name;
    }

    int varReturnValue = 0;

    final Type returnType = Type.getReturnType(methodNode.desc);

    if (returnType.equals(Type.VOID_TYPE)) {
        wrappingMethodNode.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l1, "java/lang/Throwable"));

    } else {

        wrappingMethodNode.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l2, "java/lang/Throwable"));

        //--- create "Object returnValue = null;"

        if (!TransformerUtil.isStatic(methodNode.access)) {
            // load "this"
            varReturnValue++;
        }

        // consider method arguments to find right variable index
        final Type[] argTypes = Type.getArgumentTypes(methodNode.desc);
        for (int i = 0; i < argTypes.length; i++) {
            varReturnValue++;

            // long/double take two registers
            if (argTypes[i].equals(Type.LONG_TYPE) || argTypes[i].equals(Type.DOUBLE_TYPE)) {
                varReturnValue++;
            }
        }

        // push NULL on the stack and initialize variable for return value for it
        wInstructions.add(new InsnNode(Opcodes.ACONST_NULL));
        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, varReturnValue));
    }

    int var = 0;

    // --- L0
    wInstructions.add(l0);

    wInstructions.add(this.addCaptureCall(TransformerUtil.isStatic(methodNode.access), className,
            wrappingMethodNode.name, wrappingMethodNode.desc, Type.getArgumentTypes(methodNode.desc)));

    // --- construct call to wrapped methode

    if (!TransformerUtil.isStatic(methodNode.access)) {
        // load "this" to call method
        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
        var++;
    }

    final Type[] argTypes = Type.getArgumentTypes(methodNode.desc);
    for (int i = 0; i < argTypes.length; i++) {
        this.addLoadInsn(wInstructions, argTypes[i], var++);

        // long/double take two registers
        if (argTypes[i].equals(Type.LONG_TYPE) || argTypes[i].equals(Type.DOUBLE_TYPE)) {
            var++;
        }
    }

    if (TransformerUtil.isStatic(methodNode.access)) {
        wInstructions.add(
                new MethodInsnNode(Opcodes.INVOKESTATIC, classNode.name, methodNode.name, methodNode.desc));
    } else {
        wInstructions.add(
                new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classNode.name, methodNode.name, methodNode.desc));
    }

    var++;

    if (returnType.equals(Type.VOID_TYPE)) {
        wInstructions.add(new JumpInsnNode(Opcodes.GOTO, l2));

        // --- L1

        wInstructions.add(l1);

        wInstructions.add(new FrameNode(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/lang/Throwable" }));

        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, --var));

        this.addCaptureEnableStatement(className, methodNode, wInstructions, -1);

        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, var));
        wInstructions.add(new InsnNode(Opcodes.ATHROW));

        // FIXME <--- DUPLICATE CODE

        // --- L2

        wInstructions.add(l2);
        wInstructions.add(new FrameNode(Opcodes.F_SAME, 0, null, 0, null));

        this.addCaptureEnableStatement(className, methodNode, wInstructions, -1);

        wInstructions.add(new InsnNode(Opcodes.RETURN));
    } else {
        // construct store of the wrapped method call's result

        this.addBoxingStmt(wInstructions, returnType);

        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, varReturnValue));
        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, varReturnValue));

        this.addUnBoxingStmt(wInstructions, returnType);

        final int storeOpcode = returnType.getOpcode(Opcodes.ISTORE);
        wInstructions.add(new VarInsnNode(storeOpcode, ++var)); // might be only var

        // --- L1

        wInstructions.add(l1);

        this.addCaptureEnableStatement(className, methodNode, wInstructions, varReturnValue);

        // construct load of the wrapped method call's result
        int loadOpcode = returnType.getOpcode(Opcodes.ILOAD);
        wInstructions.add(new VarInsnNode(loadOpcode, var));

        // construct return of the wrapped method call's result
        this.addReturnInsn(wInstructions, returnType);

        //---- L2

        wInstructions.add(l2);

        wInstructions.add(
                new FrameNode(Opcodes.F_FULL, 2, new Object[] { className, this.getInternalName(returnType) },
                        1, new Object[] { "java/lang/Throwable" }));
        wInstructions.add(new VarInsnNode(Opcodes.ASTORE, --var));

        this.addCaptureEnableStatement(className, methodNode, wInstructions, varReturnValue);

        wInstructions.add(new VarInsnNode(Opcodes.ALOAD, var));
        wInstructions.add(new InsnNode(Opcodes.ATHROW));
    }
    transformWrapperCalls(methodNode);
    return wrappingMethodNode;
}

From source file:org.evosuite.testcarver.instrument.Instrumenter.java

License:Open Source License

private void addUnBoxingStmt(final InsnList il, final Type type) {
    if (type.equals(Type.BOOLEAN_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"));
    } else if (type.equals(Type.CHAR_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"));
    } else if (type.equals(Type.BYTE_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B"));
    } else if (type.equals(Type.SHORT_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S"));
    } else if (type.equals(Type.INT_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I"));
    } else if (type.equals(Type.FLOAT_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F"));
    } else if (type.equals(Type.LONG_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J"));
    } else if (type.equals(Type.DOUBLE_TYPE)) {
        il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D"));
    }//from  ww w.jav a 2s. c o  m
}