Example usage for org.objectweb.asm Opcodes INSTANCEOF

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

Introduction

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

Prototype

int INSTANCEOF

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

Click Source Link

Usage

From source file:org.evosuite.instrumentation.testability.transformer.InstanceOfTransformer.java

License:Open Source License

@Override
protected AbstractInsnNode transformTypeInsnNode(MethodNode mn, TypeInsnNode typeNode) {
    if (typeNode.getOpcode() == Opcodes.INSTANCEOF) {
        TransformationStatistics.transformInstanceOf();

        // Depending on the class version we need a String or a Class
        // TODO: This needs to be class version of the class that's loaded, not cn!
        //ClassReader reader;
        int version = 48;
        /*/* w w  w  .  j  av  a 2 s  . c o  m*/
        String name = typeNode.desc.replace('/', '.');
        try {
           reader = new ClassReader(name);
           ClassNode parent = new ClassNode();
           reader.accept(parent, ClassReader.SKIP_CODE);
           version = parent.version;
        } catch (IOException e) {
           TestabilityTransformation.logger.info("Error reading class " + name);
        }
        */
        if (version >= 49) {
            if (!typeNode.desc.startsWith("[")) {
                LdcInsnNode lin = new LdcInsnNode(Type.getType("L" + typeNode.desc + ";"));
                mn.instructions.insertBefore(typeNode, lin);
            } else {
                LdcInsnNode lin = new LdcInsnNode(Type.getType(typeNode.desc + ";"));
                mn.instructions.insertBefore(typeNode, lin);
            }
        } else {
            LdcInsnNode lin = new LdcInsnNode(typeNode.desc.replace('/', '.'));
            mn.instructions.insertBefore(typeNode, lin);
            MethodInsnNode n = new MethodInsnNode(Opcodes.INVOKESTATIC, Type.getInternalName(Class.class),
                    "forName", Type.getMethodDescriptor(Type.getType(Class.class),
                            new Type[] { Type.getType(String.class) }));
            mn.instructions.insertBefore(typeNode, n);
        }
        MethodInsnNode n = new MethodInsnNode(Opcodes.INVOKESTATIC, Type.getInternalName(BooleanHelper.class),
                "instanceOf", Type.getMethodDescriptor(Type.INT_TYPE,
                        new Type[] { Type.getType(Object.class), Type.getType(Class.class) }));
        mn.instructions.insertBefore(typeNode, n);
        mn.instructions.remove(typeNode);
        return n;
    }
    return typeNode;
}

From source file:org.evosuite.seeding.CastClassAnalyzer.java

License:Open Source License

/**
 * Add all possible calls for a given method
 * /*from w w  w .j  av  a2 s.c o  m*/
 * @param callGraph
 * @param mn
 */
@SuppressWarnings("unchecked")
public void handleMethodNode(ClassNode cn, MethodNode mn, int depth) {

    if (mn.signature != null) {
        logger.debug("Visiting signature: " + mn.signature);
        CollectParameterTypesVisitor visitor = new CollectParameterTypesVisitor(cn.name);
        new SignatureReader(mn.signature).accept(visitor);
        for (Type castType : visitor.getClasses()) {
            if (!castClassMap.containsKey(castType)) {
                logger.debug("Adding new cast class from signature visitor: " + castType);
                castClassMap.put(castType, depth + 1);
            }
        }
    }

    InsnList instructions = mn.instructions;
    Iterator<AbstractInsnNode> iterator = instructions.iterator();

    // TODO: This really shouldn't be here but in its own class
    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn.getOpcode() == Opcodes.CHECKCAST) {
            TypeInsnNode typeNode = (TypeInsnNode) insn;
            Type castType = Type.getObjectType(typeNode.desc);
            while (castType.getSort() == Type.ARRAY) {
                castType = castType.getElementType();
            }
            logger.debug("Adding new cast class from cast: " + castType);
            if (!castClassMap.containsKey(castType))
                castClassMap.put(castType, depth + 1);
        } else if (insn.getOpcode() == Opcodes.INSTANCEOF) {
            TypeInsnNode typeNode = (TypeInsnNode) insn;
            Type castType = Type.getObjectType(typeNode.desc);
            while (castType.getSort() == Type.ARRAY) {
                castType = castType.getElementType();
            }
            logger.debug("Adding new cast class from instanceof: " + castType);
            if (!castClassMap.containsKey(castType))
                castClassMap.put(castType, depth + 1);
        } else if (insn.getOpcode() == Opcodes.LDC) {
            LdcInsnNode ldcNode = (LdcInsnNode) insn;
            if (ldcNode.cst instanceof Type) {
                Type type = (Type) ldcNode.cst;
                while (type.getSort() == Type.ARRAY) {
                    type = type.getElementType();
                }
                if (!castClassMap.containsKey(type))
                    castClassMap.put(type, depth + 1);
            }

        }
    }
}

From source file:org.jacoco.core.internal.analysis.filter.KotlinCoroutineFilterTest.java

License:Open Source License

/**
 * <pre>//w  ww  .  j a  v  a  2 s  .c  om
 *     runBlocking {
 *         val x = 42
 *         nop(x)
 *         suspendingFunction()
 *         nop(x)
 *     }
 * </pre>
 */
@Test
public void should_filter_suspending_lambdas() {
    final MethodNode m = new MethodNode(InstrSupport.ASM_API_VERSION, 0, "invokeSuspend",
            "(Ljava/lang/Object;)Ljava/lang/Object;", null, null);
    context.classAnnotations.add(KotlinGeneratedFilter.KOTLIN_METADATA_DESC);

    m.visitLabel(new Label());
    final Range range1 = new Range();
    range1.fromInclusive = m.instructions.getLast();
    m.visitMethodInsn(Opcodes.INVOKESTATIC, "kotlin/coroutines/intrinsics/IntrinsicsKt",
            "getCOROUTINE_SUSPENDED", "()Ljava/lang/Object;", false);
    m.visitVarInsn(Opcodes.ASTORE, 4);

    m.visitVarInsn(Opcodes.ALOAD, 0);
    // line of "runBlocking"
    m.visitFieldInsn(Opcodes.GETFIELD, "Target", "label", "I");
    final Label dflt = new Label();
    final Label state0 = new Label();
    final Label state1 = new Label();
    m.visitTableSwitchInsn(0, 1, dflt, state0, state1);

    m.visitLabel(state0);

    {
        m.visitVarInsn(Opcodes.ALOAD, 1);
        m.visitInsn(Opcodes.DUP);
        m.visitTypeInsn(Opcodes.INSTANCEOF, "kotlin/Result$Failure");
        Label label = new Label();
        m.visitJumpInsn(Opcodes.IFEQ, label);
        m.visitTypeInsn(Opcodes.CHECKCAST, "kotlin/Result$Failure");
        m.visitFieldInsn(Opcodes.GETFIELD, "kotlin/Result$Failure", "exception", "Ljava/lang/Throwable");
        m.visitInsn(Opcodes.ATHROW);
        m.visitInsn(Opcodes.POP);
        range1.toInclusive = m.instructions.getLast();
        m.visitLabel(label);
    }

    // line before "suspendingFunction"
    m.visitInsn(Opcodes.NOP);

    // line of "suspendingFunction"
    m.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "", "suspendingFunction",
            "(Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", false);

    m.visitInsn(Opcodes.DUP);
    final Range range2 = new Range();
    range2.fromInclusive = m.instructions.getLast();
    m.visitVarInsn(Opcodes.ALOAD, 4);
    final Label continuationLabelAfterLoadedResult = new Label();
    m.visitJumpInsn(Opcodes.IF_ACMPNE, continuationLabelAfterLoadedResult);
    // line of "runBlocking"
    m.visitVarInsn(Opcodes.ALOAD, 4);
    m.visitInsn(Opcodes.ARETURN);

    m.visitLabel(state1);

    m.visitVarInsn(Opcodes.ALOAD, 0);
    m.visitFieldInsn(Opcodes.GETFIELD, "Target", "I$0", "I");
    m.visitVarInsn(Opcodes.ISTORE, 3);

    {
        m.visitVarInsn(Opcodes.ALOAD, 1);
        m.visitInsn(Opcodes.DUP);
        m.visitTypeInsn(Opcodes.INSTANCEOF, "kotlin/Result$Failure");
        final Label label = new Label();
        m.visitJumpInsn(Opcodes.IFEQ, label);
        m.visitTypeInsn(Opcodes.CHECKCAST, "kotlin/Result$Failure");
        m.visitFieldInsn(Opcodes.GETFIELD, "kotlin/Result$Failure", "exception", "Ljava/lang/Throwable");
        m.visitInsn(Opcodes.ATHROW);
        m.visitInsn(Opcodes.POP);
        m.visitLabel(label);
    }
    m.visitVarInsn(Opcodes.ALOAD, 1);
    range2.toInclusive = m.instructions.getLast();
    m.visitLabel(continuationLabelAfterLoadedResult);

    // line after "suspendingFunction"
    m.visitInsn(Opcodes.NOP);
    m.visitInsn(Opcodes.ARETURN);

    m.visitLabel(dflt);
    final Range range0 = new Range();
    range0.fromInclusive = m.instructions.getLast();
    m.visitTypeInsn(Opcodes.NEW, "java/lang/IllegalStateException");
    m.visitInsn(Opcodes.DUP);
    m.visitLdcInsn("call to 'resume' before 'invoke' with coroutine");
    m.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/IllegalStateException", "<init>",
            "(Ljava/lang/String;)V", false);
    m.visitInsn(Opcodes.ATHROW);
    range0.toInclusive = m.instructions.getLast();

    filter.filter(m, context, output);

    assertIgnored(range0, range1, range2);
}

From source file:org.jacoco.core.internal.analysis.filter.KotlinCoroutineFilterTest.java

License:Open Source License

/**
 * <pre>//from www.  j a  v a 2s .  c  o m
 *     suspend fun example() {
 *         suspendingFunction()
 *         nop()
 *     }
 * </pre>
 */
@Test
public void should_filter_suspending_functions() {
    final MethodNode m = new MethodNode(InstrSupport.ASM_API_VERSION, Opcodes.ACC_STATIC, "example",
            "(Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", null, null);
    context.classAnnotations.add(KotlinGeneratedFilter.KOTLIN_METADATA_DESC);

    final int continuationArgumentIndex = 0;
    final int continuationIndex = 2;

    m.visitVarInsn(Opcodes.ALOAD, continuationArgumentIndex);
    final Range range1 = new Range();
    range1.fromInclusive = m.instructions.getLast();
    m.visitTypeInsn(Opcodes.INSTANCEOF, "ExampleKt$example$1");
    final Label createStateInstance = new Label();
    m.visitJumpInsn(Opcodes.IFEQ, createStateInstance);

    m.visitVarInsn(Opcodes.ALOAD, continuationArgumentIndex);
    m.visitTypeInsn(Opcodes.CHECKCAST, "ExampleKt$example$1");
    m.visitVarInsn(Opcodes.ASTORE, continuationIndex);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "label", "I");

    m.visitLdcInsn(Integer.valueOf(Integer.MIN_VALUE));
    m.visitInsn(Opcodes.IAND);
    m.visitJumpInsn(Opcodes.IFEQ, createStateInstance);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitInsn(Opcodes.DUP);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "label", "I");

    m.visitLdcInsn(Integer.valueOf(Integer.MIN_VALUE));
    m.visitInsn(Opcodes.ISUB);
    m.visitFieldInsn(Opcodes.PUTFIELD, "ExampleKt$example$1", "label", "I");

    final Label afterCoroutineStateCreated = new Label();
    m.visitJumpInsn(Opcodes.GOTO, afterCoroutineStateCreated);

    m.visitLabel(createStateInstance);

    m.visitTypeInsn(Opcodes.NEW, "ExampleKt$example$1");
    m.visitInsn(Opcodes.DUP);
    m.visitVarInsn(Opcodes.ALOAD, continuationArgumentIndex);
    m.visitMethodInsn(Opcodes.INVOKESPECIAL, "ExampleKt$example$1", "<init>",
            "(Lkotlin/coroutines/Continuation;)V", false);

    m.visitVarInsn(Opcodes.ASTORE, continuationIndex);

    m.visitLabel(afterCoroutineStateCreated);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "result", "Ljava/lang/Object;");
    m.visitVarInsn(Opcodes.ASTORE, 1);

    m.visitMethodInsn(Opcodes.INVOKESTATIC, "kotlin/coroutines/intrinsics/IntrinsicsKt",
            "getCOROUTINE_SUSPENDED", "()Ljava/lang/Object;", false);

    // line of "fun"
    m.visitVarInsn(Opcodes.ASTORE, 3);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "label", "I");
    final Label dflt = new Label();
    final Label state0 = new Label();
    final Label state1 = new Label();
    m.visitTableSwitchInsn(0, 1, dflt, state0, state1);

    m.visitLabel(state0);

    {
        m.visitVarInsn(Opcodes.ALOAD, 1);
        m.visitInsn(Opcodes.DUP);
        m.visitTypeInsn(Opcodes.INSTANCEOF, "kotlin/Result$Failure");
        Label label = new Label();
        m.visitJumpInsn(Opcodes.IFEQ, label);
        m.visitTypeInsn(Opcodes.CHECKCAST, "kotlin/Result$Failure");
        m.visitFieldInsn(Opcodes.GETFIELD, "kotlin/Result$Failure", "exception", "Ljava/lang/Throwable");
        m.visitInsn(Opcodes.ATHROW);
        m.visitInsn(Opcodes.POP);
        range1.toInclusive = m.instructions.getLast();
        m.visitLabel(label);
    }

    // line of "suspendingFunction"
    m.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "", "suspendingFunction",
            "(Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", false);

    m.visitInsn(Opcodes.DUP);
    final Range range2 = new Range();
    range2.fromInclusive = m.instructions.getLast();
    m.visitVarInsn(Opcodes.ALOAD, 3);
    final Label continuationLabelAfterLoadedResult = new Label();
    m.visitJumpInsn(Opcodes.IF_ACMPNE, continuationLabelAfterLoadedResult);
    // line of "fun"
    m.visitVarInsn(Opcodes.ALOAD, 3);
    m.visitInsn(Opcodes.ARETURN);

    m.visitLabel(state1);

    {
        m.visitVarInsn(Opcodes.ALOAD, 1);
        m.visitInsn(Opcodes.DUP);
        m.visitTypeInsn(Opcodes.INSTANCEOF, "kotlin/Result$Failure");
        final Label label = new Label();
        m.visitJumpInsn(Opcodes.IFEQ, label);
        m.visitTypeInsn(Opcodes.CHECKCAST, "kotlin/Result$Failure");
        m.visitFieldInsn(Opcodes.GETFIELD, "kotlin/Result$Failure", "exception", "Ljava/lang/Throwable");
        m.visitInsn(Opcodes.ATHROW);
        m.visitInsn(Opcodes.POP);
        m.visitLabel(label);
    }
    m.visitVarInsn(Opcodes.ALOAD, 1);
    range2.toInclusive = m.instructions.getLast();
    m.visitLabel(continuationLabelAfterLoadedResult);

    // line after "suspendingFunction"
    m.visitInsn(Opcodes.NOP);
    m.visitInsn(Opcodes.ARETURN);

    m.visitLabel(dflt);
    final Range range0 = new Range();
    range0.fromInclusive = m.instructions.getLast();
    m.visitTypeInsn(Opcodes.NEW, "java/lang/IllegalStateException");
    m.visitInsn(Opcodes.DUP);
    m.visitLdcInsn("call to 'resume' before 'invoke' with coroutine");
    m.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/IllegalStateException", "<init>",
            "(Ljava/lang/String;)V", false);
    m.visitInsn(Opcodes.ATHROW);
    range0.toInclusive = m.instructions.getLast();

    filter.filter(m, context, output);

    assertIgnored(range0, range1, range2);
}

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

License:Open Source License

@Override
public void visitTypeInsn(final int opcode, final String type) {
    switch (opcode) {
    case Opcodes.NEW:
        final Label label = new Label();
        mv.visitLabel(label);/*from  w w w.jav  a  2s.  c  o m*/
        push(label);
        break;
    case Opcodes.ANEWARRAY:
        pop(1);
        push('[' + Type.getObjectType(type).getDescriptor());
        break;
    case Opcodes.CHECKCAST:
        pop(1);
        push(type);
        break;
    case Opcodes.INSTANCEOF:
        pop(1);
        push(Opcodes.INTEGER);
        break;
    default:
        throw new IllegalArgumentException();
    }
    mv.visitTypeInsn(opcode, type);
}

From source file:org.jboss.byteman.agent.adapter.RuleGeneratorAdapter.java

License:Open Source License

/**
 * Generates the instruction to test if the top stack value is of the given
 * type.//w w  w  .jav  a  2 s  .  com
 *
 * @param type a class or interface type.
 */
public void instanceOf(final Type type) {
    typeInsn(Opcodes.INSTANCEOF, type);
}

From source file:org.openquark.cal.internal.javamodel.AsmJavaBytecodeGenerator.java

License:Open Source License

/**
 * Create the Java code for a given instanceof expression, pushing the result onto the operand stack.
 *   /*from  w w  w  . ja  v  a 2  s.c o  m*/
 * @param instanceOf the instanceof expression
 * @param context 
 * @return JavaTypeName the type of the result on the operand stack.
 * @throws JavaGenerationException               
 */
private static JavaTypeName encodeInstanceOfExpr(JavaExpression.InstanceOf instanceOf,
        GenerationContext context) throws JavaGenerationException {

    //push the expression to test onto the operand stack
    encodeExpr(instanceOf.getJavaExpression(), context);

    //endcode the INSTANCEOF instruction
    context.getMethodVisitor().visitTypeInsn(Opcodes.INSTANCEOF,
            instanceOf.getReferenceType().getJVMInternalName());

    return JavaTypeName.BOOLEAN;
}

From source file:org.sonar.java.bytecode.se.BytecodeEGWalkerExecuteTest.java

License:Open Source License

@Test
public void test_instanceof() throws Exception {
    SymbolicValue sv = new SymbolicValue();
    ProgramState programState = execute(new Instruction(Opcodes.INSTANCEOF),
            ProgramState.EMPTY_STATE.stackValue(sv));
    SymbolicValue result = programState.peekValue();
    assertThat(result).isInstanceOf(SymbolicValue.InstanceOfSymbolicValue.class);
    assertThat(result.computedFrom().get(0)).isEqualTo(sv);

    assertThatThrownBy(() -> execute(new Instruction(Opcodes.INSTANCEOF)))
            .hasMessage("INSTANCEOF needs 1 values on stack");
}

From source file:org.springsource.loaded.test.infra.MethodPrinter.java

License:Apache License

public void visitTypeInsn(int opcode, String type) {
    if (opcode == Opcodes.NEW) { // 187
        to.println("    NEW " + type);
    } else if (opcode == Opcodes.ANEWARRAY) { // 189
        to.println("    ANEWARRAY " + type);
    } else if (opcode == Opcodes.CHECKCAST) { // 192
        to.println("    CHECKCAST " + type);
    } else if (opcode == Opcodes.INSTANCEOF) { // 193
        to.println("    INSTANCEOF " + type);
    } else {/*from   w ww.j  a v a 2s.  c  om*/
        throw new IllegalStateException(":" + opcode);
    }
}

From source file:serianalyzer.JVMImpl.java

License:Open Source License

/**
 * @param opcode/*from  w w w .  jav a  2  s . c  o m*/
 * @param type
 * @param s
 */
static void handleJVMTypeInsn(int opcode, String type, JVMStackState s) {
    BaseType o;
    switch (opcode) {
    case Opcodes.NEW:
        s.push(new ObjectReferenceConstant(false, Type.getObjectType(type), type.replace('/', '.')));
        break;
    case Opcodes.ANEWARRAY:
        s.pop();
        if (type.charAt(0) == '[') {
            s.push(new BasicVariable(Type.getObjectType("[" + type), "array", false)); //$NON-NLS-1$//$NON-NLS-2$
        } else {
            s.push(new BasicVariable(Type.getObjectType("[L" + type + ";"), "array", false)); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
        }
        break;
    case Opcodes.CHECKCAST:
        if (log.isDebugEnabled()) {
            log.debug("Checkcast " + type); //$NON-NLS-1$
        }
        o = s.pop();
        if (o != null) {
            o.addAlternativeType(Type.getObjectType(type));
            s.push(o);
        } else {
            s.clear();
        }
        break;
    case Opcodes.INSTANCEOF:
        o = s.pop();
        if (o != null) {
            o.addAlternativeType(Type.getObjectType(type));
        }
        s.push(new BasicConstant(Type.BOOLEAN_TYPE, "typeof " + o + " = " + type, //$NON-NLS-1$//$NON-NLS-2$
                !(o != null) || o.isTainted()));
        break;
    }
}