Example usage for org.objectweb.asm Opcodes ACONST_NULL

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

Introduction

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

Prototype

int ACONST_NULL

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

Click Source Link

Usage

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

License:Open Source License

private void instrumentPUTXXXFieldAccesses(final ClassNode cn, final String internalClassName,
        final MethodNode methodNode) {
    final InsnList instructions = methodNode.instructions;

    AbstractInsnNode ins = null;//  w ww.  j  av  a2  s  .c o  m
    FieldInsnNode fieldIns = null;

    // needed get right receiver var in case of PUTFIELD

    for (int i = 0; i < instructions.size(); i++) {
        ins = instructions.get(i);
        if (ins instanceof FieldInsnNode) {
            fieldIns = (FieldInsnNode) ins;

            /*
             * Is field referencing outermost instance? if yes, ignore it
             * http://tns-www.lcs.mit.edu/manuals/java-1.1.1/guide/innerclasses/spec/innerclasses.doc10.html
             */
            if (fieldIns.name.endsWith("$0")) {
                continue;
            }

            final int opcode = ins.getOpcode();
            if (opcode == Opcodes.PUTFIELD || opcode == Opcodes.PUTSTATIC) {
                // construction of  
                //   Capturer.capture(final Object receiver, final String methodName, final Object[] methodParams)
                // call
                final InsnList il = new InsnList();

                if (opcode == Opcodes.PUTFIELD) {
                    Type fieldType = Type.getType(fieldIns.desc);
                    if (fieldType.getSize() == 1) {
                        instructions.insertBefore(fieldIns, new InsnNode(Opcodes.DUP2));
                        il.add(new InsnNode(Opcodes.POP));
                    } else if (fieldType.getSize() == 2) {
                        InsnList uglyList = new InsnList();
                        // v, w
                        uglyList.add(new InsnNode(Opcodes.DUP2_X1));
                        // w, v, w
                        uglyList.add(new InsnNode(Opcodes.POP2));
                        // w, v
                        uglyList.add(new InsnNode(Opcodes.DUP));
                        // w, v, v
                        uglyList.add(new InsnNode(Opcodes.DUP2_X2));
                        // v, v, w, v, v
                        uglyList.add(new InsnNode(Opcodes.POP2));
                        // v, v, w
                        instructions.insertBefore(fieldIns, uglyList);
                        // PUTFIELD
                        // v
                    }
                } else
                    il.add(new InsnNode(Opcodes.ACONST_NULL));

                il.add(new LdcInsnNode(this.captureId));
                il.add(new LdcInsnNode(fieldIns.owner));
                il.add(new LdcInsnNode(fieldIns.name));
                il.add(new LdcInsnNode(fieldIns.desc));

                il.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                        PackageInfo.getNameWithSlash(FieldRegistry.class), "notifyModification",
                        "(Ljava/lang/Object;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"));

                // PUTFIELDRegistry.notifyModification also adds corresponding GETFIELD capture instructions
                this.captureId++;
                i += il.size();

                instructions.insert(fieldIns, il);
                this.captureId++;
            }
        }
    }
}

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

License:Open Source License

/**
 *    public int myMethod(int i)//from   w  w w.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.testcase.ConstructorStatement.java

License:Open Source License

/** {@inheritDoc} */
@Override/*  w w  w  . j a  v a 2 s.  c  o  m*/
public void getBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals, Throwable exception) {
    logger.debug("Invoking constructor");
    Label start = mg.newLabel();
    Label end = mg.newLabel();

    // if(exception != null)
    mg.mark(start);

    mg.newInstance(Type.getType(retval.getVariableClass()));
    mg.dup();
    int num = 0;
    for (VariableReference parameter : parameters) {
        parameter.loadBytecode(mg, locals);
        if (constructor.getConstructor().getParameterTypes()[num].isPrimitive()) {
            if (parameter.getGenericClass().isWrapperType()) {
                mg.unbox(Type.getType(parameter.getGenericClass().getUnboxedType()));
            } else if (!parameter.getGenericClass().isPrimitive()) {
                Class<?> parameterClass = new GenericClass(constructor.getParameterTypes()[num]).getBoxedType();
                Type parameterType = Type.getType(parameterClass);
                mg.checkCast(parameterType);
                mg.unbox(Type.getType(constructor.getConstructor().getParameterTypes()[num]));
            }

            if (!constructor.getParameterTypes()[num].equals(parameter.getVariableClass())) {
                logger.debug("Types don't match - casting {} to {}", parameter.getVariableClass().getName(),
                        constructor.getConstructor().getParameterTypes()[num].getName());
                mg.cast(Type.getType(parameter.getVariableClass()),
                        Type.getType(constructor.getConstructor().getParameterTypes()[num]));
            }
        } else if (parameter.getVariableClass().isPrimitive()) {
            mg.box(Type.getType(parameter.getVariableClass()));
        }
        num++;
    }
    mg.invokeConstructor(Type.getType(retval.getVariableClass()),
            Method.getMethod(constructor.getConstructor()));
    logger.debug("Storing result");
    retval.storeBytecode(mg, locals);

    // if(exception != null) {
    mg.mark(end);
    Label l = mg.newLabel();
    mg.goTo(l);
    // mg.catchException(start, end,
    // Type.getType(getExceptionClass(exception)));
    mg.catchException(start, end, Type.getType(Throwable.class));
    mg.pop(); // Pop exception from stack
    if (!retval.isVoid()) {
        Class<?> clazz = retval.getVariableClass();
        if (clazz.equals(boolean.class))
            mg.push(false);
        else if (clazz.equals(char.class))
            mg.push(0);
        else if (clazz.equals(int.class))
            mg.push(0);
        else if (clazz.equals(short.class))
            mg.push(0);
        else if (clazz.equals(long.class))
            mg.push(0L);
        else if (clazz.equals(float.class))
            mg.push(0.0F);
        else if (clazz.equals(double.class))
            mg.push(0.0);
        else if (clazz.equals(byte.class))
            mg.push(0);
        else if (clazz.equals(String.class))
            mg.push("");
        else
            mg.visitInsn(Opcodes.ACONST_NULL);

        retval.storeBytecode(mg, locals);
    }
    mg.mark(l);
    // }

}

From source file:org.evosuite.testcase.FieldStatement.java

License:Open Source License

/** {@inheritDoc} */
@Override//from   w w w.ja va 2  s .c  om
public void getBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals, Throwable exception) {

    Label start = mg.newLabel();
    Label end = mg.newLabel();

    // if(exception != null)
    mg.mark(start);

    if (!isStatic()) {
        source.loadBytecode(mg, locals);
    }
    if (isStatic())
        mg.getStatic(Type.getType(field.getField().getDeclaringClass()), field.getName(),
                Type.getType(field.getField().getType()));
    else {
        if (!source.getVariableClass().isInterface()) {
            mg.getField(Type.getType(source.getVariableClass()), field.getName(),
                    Type.getType(field.getField().getType()));
        } else {
            mg.getField(Type.getType(field.getField().getDeclaringClass()), field.getName(),
                    Type.getType(field.getField().getType()));
        }
    }

    if (!retval.getVariableClass().equals(field.getField().getType())) {
        if (!retval.getVariableClass().isPrimitive()) {
            if (field.getField().getType().isPrimitive()) {
                mg.box(Type.getType(field.getField().getType()));
            }
            mg.checkCast(Type.getType(retval.getVariableClass()));
        } else {
            mg.cast(Type.getType(field.getField().getType()), Type.getType(retval.getVariableClass()));
        }
    }
    retval.storeBytecode(mg, locals);

    // if(exception != null) {
    mg.mark(end);
    Label l = mg.newLabel();
    mg.goTo(l);
    // mg.catchException(start, end, Type.getType(exception.getClass()));
    mg.catchException(start, end, Type.getType(Throwable.class));
    mg.pop(); // Pop exception from stack
    if (!retval.isVoid()) {
        Class<?> clazz = retval.getVariableClass();
        if (clazz.equals(boolean.class))
            mg.push(false);
        else if (clazz.equals(char.class))
            mg.push(0);
        else if (clazz.equals(int.class))
            mg.push(0);
        else if (clazz.equals(short.class))
            mg.push(0);
        else if (clazz.equals(long.class))
            mg.push(0L);
        else if (clazz.equals(float.class))
            mg.push(0.0F);
        else if (clazz.equals(double.class))
            mg.push(0.0);
        else if (clazz.equals(byte.class))
            mg.push(0);
        else if (clazz.equals(String.class))
            mg.push("");
        else
            mg.visitInsn(Opcodes.ACONST_NULL);

        retval.storeBytecode(mg, locals);
    }
    mg.mark(l);
    // }
}

From source file:org.evosuite.testcase.MethodStatement.java

License:Open Source License

/** {@inheritDoc} */
@Override/*  www. j av  a 2 s. co m*/
public void getBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals, Throwable exception) {
    Label start = mg.newLabel();
    Label end = mg.newLabel();

    // if(exception != null)
    mg.mark(start);

    if (!isStatic()) {
        callee.loadBytecode(mg, locals);
        if (!method.getMethod().getDeclaringClass().equals(callee.getVariableClass())) {
            logger.debug("Types don't match - casting!");
            mg.cast(Type.getType(callee.getVariableClass()),
                    Type.getType(method.getMethod().getDeclaringClass()));
        }
    }
    int num = 0;
    for (VariableReference parameter : parameters) {
        parameter.loadBytecode(mg, locals);
        if (method.getMethod().getParameterTypes()[num].isPrimitive()) {
            if (parameter.getGenericClass().isWrapperType()) {
                mg.unbox(Type.getType(parameter.getGenericClass().getUnboxedType()));
            } else if (!parameter.getGenericClass().isPrimitive()) {
                Class<?> parameterClass = new GenericClass(method.getParameterTypes()[num]).getBoxedType();
                Type parameterType = Type.getType(parameterClass);
                mg.checkCast(parameterType);
                mg.unbox(Type.getType(method.getMethod().getParameterTypes()[num]));
            }

            if (!method.getParameterTypes()[num].equals(parameter.getVariableClass())) {
                logger.debug("Types don't match - casting!");
                mg.cast(Type.getType(parameter.getVariableClass()),
                        Type.getType(method.getMethod().getParameterTypes()[num]));
            }
        } else if (parameter.getVariableClass().isPrimitive()) {
            mg.box(Type.getType(parameter.getVariableClass()));
        }
        num++;
    }
    logger.debug("Invoking method");
    // if(exception != null) {
    //
    // mg.visitTryCatchBlock(start, end, handler,
    // exception.getClass().getName().replace('.', '/'));
    // }
    if (isStatic())
        mg.invokeStatic(Type.getType(method.getMethod().getDeclaringClass()),
                org.objectweb.asm.commons.Method.getMethod(method.getMethod()));
    else {
        if (!callee.getVariableClass().isInterface()) {
            mg.invokeVirtual(Type.getType(callee.getVariableClass()),
                    org.objectweb.asm.commons.Method.getMethod(method.getMethod()));
        } else {
            mg.invokeInterface(Type.getType(callee.getVariableClass()),
                    org.objectweb.asm.commons.Method.getMethod(method.getMethod()));
        }
    }

    if (!retval.isVoid()) {
        if (!retval.getVariableClass().equals(method.getReturnType())) {
            if (!retval.getVariableClass().isPrimitive()) {
                mg.checkCast(Type.getType(retval.getVariableClass()));
            } else {
                mg.cast(Type.getType(method.getMethod().getReturnType()),
                        Type.getType(retval.getVariableClass()));
            }
        }
        retval.storeBytecode(mg, locals);
    }

    // if(exception != null) {
    mg.mark(end);
    Label l = mg.newLabel();
    mg.goTo(l);
    // mg.catchException(start, end,
    // Type.getType(getExceptionClass(exception)));
    mg.catchException(start, end, Type.getType(Throwable.class));
    mg.pop(); // Pop exception from stack
    if (!retval.isVoid()) {
        Class<?> clazz = retval.getVariableClass();
        if (clazz.equals(boolean.class))
            mg.push(false);
        else if (clazz.equals(char.class))
            mg.push(0);
        else if (clazz.equals(int.class))
            mg.push(0);
        else if (clazz.equals(short.class))
            mg.push(0);
        else if (clazz.equals(long.class))
            mg.push(0L);
        else if (clazz.equals(float.class))
            mg.push(0.0F);
        else if (clazz.equals(double.class))
            mg.push(0.0);
        else if (clazz.equals(byte.class))
            mg.push(0);
        else if (clazz.equals(String.class))
            mg.push("");
        else
            mg.visitInsn(Opcodes.ACONST_NULL);

        retval.storeBytecode(mg, locals);
    }
    mg.mark(l);
    // }
}

From source file:org.evosuite.testcase.NullStatement.java

License:Open Source License

/** {@inheritDoc} */
@Override/*w  w w.  jav a  2  s.com*/
public void getBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals, Throwable exception) {
    mg.visitInsn(Opcodes.ACONST_NULL);
    retval.storeBytecode(mg, locals);
}

From source file:org.evosuite.testcase.variable.VariableReferenceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override//from w  w w.j a  va 2  s .c o m
public void loadBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals) {

    logger.debug("Loading variable in bytecode: " + getStPosition());
    if (getStPosition() < 0) {
        mg.visitInsn(Opcodes.ACONST_NULL);
    } else
        mg.loadLocal(locals.get(getStPosition()), org.objectweb.asm.Type.getType(type.getRawClass()));
}

From source file:org.evosuite.testcase.VariableReferenceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override/*from w  ww .  j  ava  2 s .  c  o  m*/
public void loadBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals) {

    logger.debug("Loading variable in bytecode: {}", getStPosition());
    if (getStPosition() < 0) {
        mg.visitInsn(Opcodes.ACONST_NULL);
    } else
        mg.loadLocal(locals.get(getStPosition()), org.objectweb.asm.Type.getType(type.getRawClass()));
}

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  w  ww  .  ja v  a2 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.reflection.BytecodeConsumerInvokerFactory.java

License:Open Source License

private void writeReturn(Class<?> returnType, MethodVisitor mv) {
    if (Void.TYPE.equals(returnType)) {
        mv.visitInsn(Opcodes.ACONST_NULL);
        mv.visitInsn(Opcodes.ARETURN);//from  ww  w . j a v  a2s. c  om
    } else if (returnType.isPrimitive()) {
        if (Integer.TYPE.equals(returnType)) {
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;");
            mv.visitInsn(Opcodes.ARETURN);
        } else if (Boolean.TYPE.equals(returnType)) {
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;");
            mv.visitInsn(Opcodes.ARETURN);
        } else if (Double.TYPE.equals(returnType)) {
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;");
            mv.visitInsn(Opcodes.ARETURN);
        } else if (Long.TYPE.equals(returnType)) {
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;");
            mv.visitInsn(Opcodes.ARETURN);
        } else if (Float.TYPE.equals(returnType)) {
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;");
            mv.visitInsn(Opcodes.ARETURN);
        } else if (Short.TYPE.equals(returnType)) {
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;");
            mv.visitInsn(Opcodes.ARETURN);
        } else if (Byte.TYPE.equals(returnType)) {
            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;");
            mv.visitInsn(Opcodes.ARETURN);
        }
    } else {
        mv.visitInsn(Opcodes.ARETURN);
    }
}