Example usage for org.objectweb.asm Opcodes INVOKEINTERFACE

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

Introduction

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

Prototype

int INVOKEINTERFACE

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

Click Source Link

Usage

From source file:org.codehaus.groovy.runtime.callsite.CallSiteGenerator.java

License:Apache License

private static MethodVisitor writeMethod(ClassWriter cw, String name, int argumentCount,
        final String superClass, CachedMethod cachedMethod, String receiverType, String parameterDescription,
        boolean useArray) {
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "call" + name,
            "(L" + receiverType + ";" + parameterDescription + ")Ljava/lang/Object;", null, null);
    mv.visitCode();/*  w w w  .  j a v  a2  s.  c o m*/

    final Label tryStart = new Label();
    mv.visitLabel(tryStart);

    // call for checking if method is still valid
    for (int i = 0; i < argumentCount; ++i)
        mv.visitVarInsn(Opcodes.ALOAD, i);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, superClass, "checkCall",
            "(Ljava/lang/Object;" + parameterDescription + ")Z", false);
    Label l0 = new Label();
    mv.visitJumpInsn(Opcodes.IFEQ, l0);

    // valid method branch

    Class callClass = cachedMethod.getDeclaringClass().getTheClass();
    boolean useInterface = callClass.isInterface();

    String type = BytecodeHelper.getClassInternalName(callClass.getName());
    String descriptor = BytecodeHelper.getMethodDescriptor(cachedMethod.getReturnType(),
            cachedMethod.getNativeParameterTypes());

    // prepare call
    int invokeMethodCode = Opcodes.INVOKEVIRTUAL;
    if (cachedMethod.isStatic()) {
        invokeMethodCode = Opcodes.INVOKESTATIC;
    } else {
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        BytecodeHelper.doCast(mv, callClass);
        if (useInterface)
            invokeMethodCode = Opcodes.INVOKEINTERFACE;
    }

    Class<?>[] parameters = cachedMethod.getPT();
    int size = parameters.length;
    for (int i = 0; i < size; i++) {
        if (useArray) {
            // unpack argument from Object[]
            mv.visitVarInsn(Opcodes.ALOAD, 2);
            BytecodeHelper.pushConstant(mv, i);
            mv.visitInsn(Opcodes.AALOAD);
        } else {
            mv.visitVarInsn(Opcodes.ALOAD, i + 2);
        }

        // cast argument to parameter class, inclusive unboxing
        // for methods with primitive types
        BytecodeHelper.doCast(mv, parameters[i]);
    }

    // make call
    mv.visitMethodInsn(invokeMethodCode, type, cachedMethod.getName(), descriptor, useInterface);

    // produce result
    BytecodeHelper.box(mv, cachedMethod.getReturnType());
    if (cachedMethod.getReturnType() == void.class) {
        mv.visitInsn(Opcodes.ACONST_NULL);
    }

    // return
    mv.visitInsn(Opcodes.ARETURN);

    // fall back after method change
    mv.visitLabel(l0);
    for (int i = 0; i < argumentCount; ++i)
        mv.visitVarInsn(Opcodes.ALOAD, i);
    if (!useArray) {
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/ArrayUtil", "createArray",
                "(" + parameterDescription + ")[Ljava/lang/Object;", false);
    }
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/callsite/CallSiteArray",
            "defaultCall" + name, "(Lorg/codehaus/groovy/runtime/callsite/CallSite;L" + receiverType
                    + ";[Ljava/lang/Object;)Ljava/lang/Object;",
            false);
    mv.visitInsn(Opcodes.ARETURN);

    // exception unwrapping for stackless exceptions
    final Label tryEnd = new Label();
    mv.visitLabel(tryEnd);
    final Label catchStart = new Label();
    mv.visitLabel(catchStart);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/ScriptBytecodeAdapter", "unwrap",
            "(Lgroovy/lang/GroovyRuntimeException;)Ljava/lang/Throwable;", false);
    mv.visitInsn(Opcodes.ATHROW);
    mv.visitTryCatchBlock(tryStart, tryEnd, catchStart, "groovy/lang/GroovyRuntimeException");

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

From source file:org.compass.core.util.reflection.asm.AsmReflectionMethodGenerator.java

License:Apache License

/**
 * Creates the method invoking wrapper method.
 *///from w ww.  j  a  v  a2s .  co  m
private static void createMethod(Class clazz, String name, Method refMethod, ClassWriter cw, String methodName,
        String desc, boolean argsParams, boolean returnValue, Class... parameterTypes) {

    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_VARARGS, methodName, desc, null, null);

    boolean isStatic = Modifier.isStatic(refMethod.getModifiers());
    boolean isInteface = Modifier.isInterface(refMethod.getDeclaringClass().getModifiers());

    final int invokeCode;
    if (isStatic) {
        invokeCode = Opcodes.INVOKESTATIC;
    } else {
        invokeCode = isInteface ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL;
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(clazz));
    }

    if (argsParams) {
        for (int i = 0; i < parameterTypes.length; ++i) {
            mv.visitVarInsn(Opcodes.ALOAD, 2);
            mv.visitIntInsn(Opcodes.BIPUSH, i);
            mv.visitInsn(Opcodes.AALOAD);
            prepareParameter(mv, Type.getType(parameterTypes[i]));
        }
    } else {
        for (int i = 0; i < parameterTypes.length; ++i) {
            mv.visitVarInsn(Opcodes.ALOAD, i + 2);
            prepareParameter(mv, Type.getType(parameterTypes[i]));
        }
    }

    mv.visitMethodInsn(invokeCode, Type.getInternalName(clazz), name, Type.getMethodDescriptor(refMethod));

    if (returnValue) {
        prepareResult(mv, refMethod);
        mv.visitInsn(Opcodes.ARETURN);
    } else {
        mv.visitInsn(Opcodes.RETURN);
    }

    mv.visitMaxs(1, 1); // ignored since ClassWriter set as ClassWriter.COMPUTE_MAXS
    mv.visitEnd();
}

From source file:org.decojer.cavaj.readers.asm.ReadMethodVisitor.java

License:Open Source License

@Override
public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc,
        final boolean itf) {
    if (owner == null || name == null || desc == null) {
        log.warn(getM() + ": Cannot read invoke operation with method name '" + owner + "." + name
                + "' and descriptor '" + desc + "'!");
        return;/*from w w  w .  j  a va2s . co m*/
    }
    switch (opcode) {
    /**********
     * INVOKE *
     **********/
    case Opcodes.INVOKEINTERFACE:
    case Opcodes.INVOKESPECIAL:
        // Constructor or supermethod (any super) or private method callout.
    case Opcodes.INVOKESTATIC:
    case Opcodes.INVOKEVIRTUAL: {
        final T ownerT = getDu().getT(owner);
        if (opcode == Opcodes.INVOKEINTERFACE) {
            ownerT.setInterface(true); // static also possible in interface since JVM 8
        }
        assert opcode != Opcodes.INVOKEINTERFACE || itf;

        final M refM = ownerT.getM(name, desc);
        refM.setStatic(opcode == Opcodes.INVOKESTATIC);
        add(new INVOKE(this.ops.size(), opcode, this.line, refM, opcode == Opcodes.INVOKESPECIAL));
        break;
    }
    default:
        log.warn(getM() + ": Unknown method insn opcode '" + opcode + "'!");
    }
}

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

License:Open Source License

protected InsnList getDispatchCode(MethodNode method, int joinPointId, int boundMethodId) {
    InsnList instructions = new InsnList();

    // teams = TeamManager.getTeams(joinpointId)
    instructions.add(createLoadIntConstant(joinPointId));

    instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ClassNames.TEAM_MANAGER_SLASH,
            ConstantMembers.getTeams.getName(), ConstantMembers.getTeams.getSignature(), false));

    instructions.add(createInstructionsToCheackTeams(method));

    // get the first team
    instructions.add(new InsnNode(Opcodes.DUP));
    instructions.add(new InsnNode(Opcodes.ICONST_0));
    instructions.add(new InsnNode(Opcodes.AALOAD));
    instructions.add(new InsnNode(Opcodes.SWAP));
    if (isStatic) {
        instructions.add(new InsnNode(Opcodes.ACONST_NULL));
    } else {/*from ww  w .  j a va2s .  c o m*/
        // put "this" on the stack and cast it to IBoundBase2
        instructions.add(new IntInsnNode(Opcodes.ALOAD, 0));
        instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, ClassNames.I_BOUND_BASE_SLASH));
    }
    instructions.add(new InsnNode(Opcodes.SWAP));
    // start index
    instructions.add(new InsnNode(Opcodes.ICONST_0));

    // TeamManager.getCallinIds(joinpointId)
    instructions.add(createLoadIntConstant(joinPointId));

    instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ClassNames.TEAM_MANAGER_SLASH,
            ConstantMembers.getCallinIds.getName(), ConstantMembers.getCallinIds.getSignature(), false));

    instructions.add(createLoadIntConstant(boundMethodId));
    args = Type.getArgumentTypes(method.desc);

    // box the arguments
    instructions.add(getBoxedArguments(args));

    instructions.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, ClassNames.ITEAM_SLASH,
            ConstantMembers.callAllBindingsTeam.getName(), ConstantMembers.callAllBindingsTeam.getSignature(),
            true));

    Type returnType = Type.getReturnType(method.desc);
    instructions.add(getUnboxingInstructionsForReturnValue(returnType));

    return instructions;
}

From source file:org.elasticsearch.plan.a.Caster.java

License:Apache License

void writeTransform(final MethodVisitor visitor, final Transform transform) {
    final Class clazz = transform.method.owner.clazz;
    final java.lang.reflect.Method method = transform.method.method;

    final String name = method.getName();
    final String internal = transform.method.owner.internal;
    final String descriptor = transform.method.descriptor;

    final Type upcast = transform.upcast;
    final Type downcast = transform.downcast;

    if (upcast != null) {
        visitor.visitTypeInsn(Opcodes.CHECKCAST, upcast.internal);
    }/*  www.  ja v a2  s  .c  o  m*/

    if (java.lang.reflect.Modifier.isStatic(method.getModifiers())) {
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, internal, name, descriptor, false);
    } else if (java.lang.reflect.Modifier.isInterface(clazz.getModifiers())) {
        visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, internal, name, descriptor, true);
    } else {
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internal, name, descriptor, false);
    }

    if (downcast != null) {
        visitor.visitTypeInsn(Opcodes.CHECKCAST, downcast.internal);
    }
}

From source file:org.evosuite.graphs.cfg.BytecodeInstructionPool.java

License:Open Source License

/**
 * Determine how many bytes the current instruction occupies together with
 * its operands/* ww w  . ja v  a 2 s.co m*/
 * 
 * @return
 */
private int getBytecodeIncrement(AbstractInsnNode instructionNode) {
    int opcode = instructionNode.getOpcode();
    switch (opcode) {
    case Opcodes.ALOAD: // index
    case Opcodes.ASTORE: // index
    case Opcodes.DLOAD:
    case Opcodes.DSTORE:
    case Opcodes.FLOAD:
    case Opcodes.FSTORE:
    case Opcodes.ILOAD:
    case Opcodes.ISTORE:
    case Opcodes.LLOAD:
    case Opcodes.LSTORE:
        VarInsnNode varNode = (VarInsnNode) instructionNode;
        if (varNode.var > 3)
            return 1;
        else
            return 0;
    case Opcodes.BIPUSH: // byte
    case Opcodes.NEWARRAY:
    case Opcodes.RET:
        return 1;
    case Opcodes.LDC:
        LdcInsnNode ldcNode = (LdcInsnNode) instructionNode;
        if (ldcNode.cst instanceof Double || ldcNode.cst instanceof Long)
            return 2; // LDC2_W
        else
            return 1;
    case 19: //LDC_W
    case 20: //LDC2_W
        return 2;
    case Opcodes.ANEWARRAY: // indexbyte1, indexbyte2
    case Opcodes.CHECKCAST: // indexbyte1, indexbyte2
    case Opcodes.GETFIELD:
    case Opcodes.GETSTATIC:
    case Opcodes.GOTO:
    case Opcodes.IF_ACMPEQ:
    case Opcodes.IF_ACMPNE:
    case Opcodes.IF_ICMPEQ:
    case Opcodes.IF_ICMPNE:
    case Opcodes.IF_ICMPGE:
    case Opcodes.IF_ICMPGT:
    case Opcodes.IF_ICMPLE:
    case Opcodes.IF_ICMPLT:
    case Opcodes.IFLE:
    case Opcodes.IFLT:
    case Opcodes.IFGE:
    case Opcodes.IFGT:
    case Opcodes.IFNE:
    case Opcodes.IFEQ:
    case Opcodes.IFNONNULL:
    case Opcodes.IFNULL:
    case Opcodes.IINC:
    case Opcodes.INSTANCEOF:
    case Opcodes.INVOKESPECIAL:
    case Opcodes.INVOKESTATIC:
    case Opcodes.INVOKEVIRTUAL:
    case Opcodes.JSR:
    case Opcodes.NEW:
    case Opcodes.PUTFIELD:
    case Opcodes.PUTSTATIC:
    case Opcodes.SIPUSH:
        // case Opcodes.LDC_W
        // case Opcodes.LDC2_W

        return 2;
    case Opcodes.MULTIANEWARRAY:
        return 3;
    case Opcodes.INVOKEDYNAMIC:
    case Opcodes.INVOKEINTERFACE:
        return 4;

    case Opcodes.LOOKUPSWITCH:
    case Opcodes.TABLESWITCH:
        // TODO: Could be more
        return 4;
    // case Opcodes.GOTO_W 
    // case Opcodes.JSR_W
    }
    return 0;
}

From source file:org.evosuite.instrumentation.error.NullPointerExceptionInstrumentation.java

License:Open Source License

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

    // If non-static, add a null check
    // TODO: Do we need to also check INVOKESPECIAL?
    if (opcode == Opcodes.INVOKEVIRTUAL || opcode == Opcodes.INVOKEINTERFACE) {
        Type[] args = Type.getArgumentTypes(desc);
        Map<Integer, Integer> to = new HashMap<Integer, Integer>();
        for (int i = args.length - 1; i >= 0; i--) {
            int loc = mv.newLocal(args[i]);
            mv.storeLocal(loc);/*from w w  w  . j  av a2s . c o m*/
            to.put(i, loc);
        }

        mv.dup();//callee
        insertBranch(Opcodes.IFNONNULL, "java/lang/NullPointerException");

        for (int i = 0; i < args.length; i++) {
            mv.loadLocal(to.get(i));
        }
    }
}

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

License:Open Source License

/** {@inheritDoc} */
@Override//from  w  ww. ja v  a  2 s  . c o  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);//w w  w  .  j av a  2 s.co  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.formulacompiler.compiler.internal.bytecode.MethodCompiler.java

License:Open Source License

final void compileInputGetterCall(CallFrame _callChainToCall) throws CompilerException {
    final CallFrame[] frames = _callChainToCall.getFrames();
    final boolean isStatic = Modifier.isStatic(frames[0].getMethod().getModifiers());

    if (!isStatic) {
        mv().loadThis();// w w  w.  j  a  v a2s. c  o m
        mv().getField(section().classType(), ByteCodeEngineCompiler.INPUTS_MEMBER_NAME, section().inputType());
    }

    Class contextClass = section().inputClass();
    for (CallFrame frame : frames) {
        final Method method = frame.getMethod();
        final Object[] args = frame.getArgs();
        if (null != args) {
            final Class[] types = method.getParameterTypes();
            for (int i = 0; i < args.length; i++) {
                final Object arg = args[i];
                final Class type = types[i];
                if (arg instanceof CellModel) {
                    final CellModel argCell = (CellModel) arg;
                    final ExpressionCompiler ex = expressionCompilerFor(type);
                    ex.compileRef(argCell);
                    ex.compileConversionTo(type);
                } else {
                    pushConstParam(type, arg);
                }
            }
        }
        final int opcode;
        if (contextClass.isInterface())
            opcode = Opcodes.INVOKEINTERFACE;
        else if (isStatic)
            opcode = Opcodes.INVOKESTATIC;
        else
            opcode = Opcodes.INVOKEVIRTUAL;

        mv().visitMethodInsn(opcode, Type.getType(contextClass).getInternalName(), method.getName(),
                Type.getMethodDescriptor(method));

        contextClass = method.getReturnType();
    }
}