Example usage for org.objectweb.asm Opcodes GOTO

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

Introduction

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

Prototype

int GOTO

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

Click Source Link

Usage

From source file:org.jboss.byteman.rule.expression.LogicalExpression.java

License:Open Source License

public void compile(MethodVisitor mv, CompileContext compileContext) throws CompileException {
    // make sure we are at the right source line
    compileContext.notifySourceLine(line);

    Expression oper0 = getOperand(0);
    Expression oper1 = getOperand(1);

    int currentStack = compileContext.getStackCount();

    // compile the first expression and make sure it is a boolean -- adds 1 to stack height
    oper0.compile(mv, compileContext);/*  w  w w .  ja va 2s .co  m*/
    if (oper0.getType() == Type.BOOLEAN) {
        compileBooleanConversion(Type.BOOLEAN, type.Z, mv, compileContext);
    }
    // plant a test and branch
    Label nextLabel = new Label();
    Label endLabel = new Label();
    if (oper == AND) {
        // only try next if we got true here
        mv.visitJumpInsn(Opcodes.IFNE, nextLabel);
        // ok, the first branch was false so stack a false for the result and skip to the end
        mv.visitLdcInsn(false);
        mv.visitJumpInsn(Opcodes.GOTO, endLabel);
    } else {
        // only try next if we got false here
        mv.visitJumpInsn(Opcodes.IFEQ, nextLabel);
        // ok, the first branch was true so stack a true for the result and skip to the end
        mv.visitLdcInsn(true);
        mv.visitJumpInsn(Opcodes.GOTO, endLabel);
    }
    // in either case if we get here the if test removed 1 from the stack
    compileContext.addStackCount(-1);
    // the else branch -- adds 1 to stack height
    mv.visitLabel(nextLabel);
    oper1.compile(mv, compileContext);
    if (oper0.getType() == Type.BOOLEAN) {
        compileBooleanConversion(Type.BOOLEAN, type.Z, mv, compileContext);
    }
    // the final result is the result of the second oper which is on the stack already
    // This is the end, my beau-tiful friend
    mv.visitLabel(endLabel);
    // in either case if we get here we should have one extra value on the stack
    // check stack height
    if (compileContext.getStackCount() != currentStack + 1) {
        throw new CompileException("LogicalExpression.compile : invalid stack height "
                + compileContext.getStackCount() + " expecting " + (currentStack + 1));
    }
}

From source file:org.jboss.byteman.rule.RuleElement.java

License:Open Source License

protected void compileStringConversion(Type fromType, Type toType, MethodVisitor mv,
        CompileContext compileContext) throws CompileException {
    assert toType == Type.STRING;
    if (fromType.isObject() || fromType.isArray() || (fromType.isNumeric() && !fromType.isPrimitive())) {
        // use the toString method if the object is non null otherwise just replace it with null
        Label elseLabel = new Label();
        Label endLabel = new Label();
        // if (object == null)
        mv.visitInsn(Opcodes.DUP);//  ww w  . j a va2  s  .  c  o  m
        // the above dup bumps the stack height
        compileContext.addStackCount(1);
        mv.visitJumpInsn(Opcodes.IFNONNULL, elseLabel);
        compileContext.addStackCount(-1);
        // then string = "null"
        mv.visitInsn(Opcodes.POP);
        mv.visitInsn(Opcodes.ACONST_NULL);
        mv.visitJumpInsn(Opcodes.GOTO, endLabel);
        // else string = object.toString()
        mv.visitLabel(elseLabel);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
        mv.visitLabel(endLabel);
    } else if (fromType == Type.Z) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "toString", "(Z)Ljava/lang/String;");
    } else if (fromType == Type.B) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Byte", "toString", "(B)Ljava/lang/String;");
    } else if (fromType == Type.S) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Short", "toString", "(S)Ljava/lang/String;");
    } else if (fromType == Type.C) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Character", "toString", "(C)Ljava/lang/String;");
    } else if (fromType == Type.I) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "toString", "(I)Ljava/lang/String;");
    } else if (fromType == Type.J) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Long", "toString", "(J)Ljava/lang/String;");
        compileContext.addStackCount(-1);
    } else if (fromType == Type.F) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Float", "toString", "(F)Ljava/lang/String;");
    } else if (fromType == Type.D) {
        // use the toString method
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Double", "toString", "(D)Ljava/lang/String;");
        compileContext.addStackCount(-1);
    }
}

From source file:org.jtsan.InstrumentCalls.java

License:Apache License

private void genTryCatchBlock(MethodMapping.HandlerInfo target, Label startExceptionRegion,
        Label endExceptionRegion) {
    Label startCatchRegion = new Label();
    Label labelSkip = new Label();
    Label labelAfter = new Label();

    boolean isStatic = (opcode == Opcodes.INVOKESTATIC);

    gen.visitJumpInsn(Opcodes.GOTO, labelAfter);

    gen.visitLabel(startCatchRegion);/*from   w  ww.ja v a2s .  co  m*/

    // TODO(vors): Handle static method exceptions incorrectly: we don't check class
    if (!isStatic) {
        // Skip the event if 'this' is not a child of the base class.
        saverThis.loadStack();
        gen.instanceOf(Type.getObjectType(target.getWatchedClass()));
        gen.visitJumpInsn(Opcodes.IFEQ, labelSkip);
    }

    // Restore stack to invoke exception handler.
    // dup() exception object.
    gen.dup();
    if (!isStatic) {
        saverThis.loadStack();
        gen.swap();
    }
    gen.push(cb.codePosition());

    cb.listenerCall(target.getHandler(),
            (isStatic ? "(" : ("(L" + target.getWatchedClass()) + ";") + "Ljava/lang/Throwable;J)V");

    gen.visitLabel(labelSkip);
    // throw exception object to next handler in exception table.
    gen.throwException();

    gen.visitLabel(labelAfter);

    // Mark try catch region with highest priority to all Exceptions.
    cb.topVisitTryCatchBlock(startExceptionRegion, endExceptionRegion, startCatchRegion, "java/lang/Throwable");

}

From source file:org.jtsan.InstrumentCalls.java

License:Apache License

private void genListenerCalls(List<MethodMapping.HandlerInfo> targets, boolean saveRet) {
    boolean returns = false;
    if (saveRet && saver.hasReturnValue()) {
        returns = true;//w  w  w.j av  a2s  .  c  o m
    }
    if (returns) {
        saver.saveReturnValue();
    }
    for (MethodMapping.HandlerInfo target : targets) {
        Label labelSkip = new Label();
        Label labelAfter = new Label();
        boolean exact = target.isExact();
        boolean callGenerated = false;
        boolean listenStatic = (opcode == Opcodes.INVOKESTATIC);
        if (!listenStatic) {
            saverThis.loadStack();
        }
        // Shape the listener method's descriptor.
        String tailReplacement = "J)V";
        int idx = desc.indexOf(")");
        if (returns) {
            String retType = desc.substring(idx + 1, desc.length());
            tailReplacement = retType + tailReplacement;
        }
        String actualDesc = desc.substring(0, idx) + tailReplacement;
        if (!listenStatic) {
            actualDesc = addClassAsFirstArgument(target.getWatchedClass(), actualDesc);
        }

        // Insert type match checking and the listener call.
        if (!exact && !listenStatic) {
            // Skip the event if 'this' is not a child of the base class.
            gen.dup();
            gen.instanceOf(Type.getObjectType(target.getWatchedClass()));
            gen.visitJumpInsn(Opcodes.IFEQ, labelSkip);
            gen.checkCast(Type.getObjectType(target.getWatchedClass()));
        }
        if (!exact || target.getWatchedClass().equals(owner)) {
            saver.loadStack();
            if (returns) {
                saver.loadReturnValue();
            }
            gen.push(cb.codePosition());
            cb.listenerCall(target.getHandler(), actualDesc);
            callGenerated = true;
        }
        if (callGenerated && !listenStatic) {
            gen.visitJumpInsn(Opcodes.GOTO, labelAfter);
            gen.visitLabel(labelSkip);
            gen.pop();
            gen.visitLabel(labelAfter);
        }
    }
    if (returns) {
        saver.loadReturnValue();
    }
}

From source file:org.lambdamatic.analyzer.ast.LambdaExpressionReader.java

License:Open Source License

/**
 * The {@link AbstractInsnNode#getOpcode()} value should be one of {@code IFEQ}, {@code IFNE},
 * {@code IFLT}, {@code IFGE}, {@code IFGT}, {@code IFLE}, {@code IFLT}, {@code IFGE},
 * {@code IFGT},{@code IF_ICMPEQ}, {@code IF_ICMPNE}, {@code IF_ICMPLT}, {@code IF_ICMPGE},
 * {@code IF_ICMPGT}, {@code IF_ICMPLE}, {@code IF_ACMPEQ}, {@code IF_ACMPNE}, {@code GOTO},
 * {@code JSR}, {@code IFNULL} or {@code IFNONNULL}.
 * // w  w w . j  a  va 2 s .c  o  m
 * 
 * @param instructionCursor the cursor for the current instruction to read
 * @param expressionStack the stack of Expressions
 * @param capturedArguments the captured arguments
 * @param localVariables the local variables
 * @return the list of statements read from the jump instruction
 */
private List<Statement> readJumpInstruction(final InsnCursor instructionCursor,
        final Stack<Expression> expressionStack, final List<CapturedArgument> capturedArguments,
        final LocalVariables localVariables) {
    final JumpInsnNode jumpInsnNode = (JumpInsnNode) instructionCursor.getCurrent();
    final LabelNode jumpLabel = jumpInsnNode.label;
    // FIXME: add support for LCMP:
    // Takes two two-word long integers off the stack and compares them. If
    // the two integers are the same, the int 0 is pushed onto the stack. If
    // value2 is greater than value1, the int 1 is pushed onto the stack. If
    // value1 is greater than value2, the int -1 is pushed onto the stack.
    switch (jumpInsnNode.getOpcode()) {
    case Opcodes.IFEQ:
    case Opcodes.IFNE:
    case Opcodes.IFLE:
    case Opcodes.IFLT:
    case Opcodes.IFGE:
    case Opcodes.IFGT:
    case Opcodes.IF_ICMPEQ:
    case Opcodes.IF_ICMPNE:
    case Opcodes.IF_ICMPLE:
    case Opcodes.IF_ICMPLT:
    case Opcodes.IF_ICMPGE:
    case Opcodes.IF_ICMPGT:
    case Opcodes.IF_ACMPEQ:
    case Opcodes.IF_ACMPNE:
        return Arrays.asList(buildControlFlowStatement(instructionCursor, expressionStack, capturedArguments,
                localVariables));
    case Opcodes.GOTO:
        final InsnCursor jumpInstructionCursor = instructionCursor.duplicate();
        jumpInstructionCursor.move(jumpLabel.getLabel());
        return readStatements(jumpInstructionCursor, expressionStack, capturedArguments, localVariables);
    default:
        throw new AnalyzeException("Unexpected JumpInsnNode OpCode: " + jumpInsnNode.getOpcode());
    }
}

From source file:org.mbte.groovypp.compiler.asm.StoringMethodVisitor.java

License:Apache License

public void redirect() {
    Redirects redirects = new Redirects();

    Label curLabel = null;//from ww  w.  ja v  a  2 s  .c o m
    for (Iterator<AsmInstr> i = operations.iterator(); i.hasNext();) {
        AsmInstr ii = i.next();

        if (ii instanceof VisitLabel) {
            VisitLabel visitLabel = (VisitLabel) ii;
            if (curLabel != null) {
                redirects.put(visitLabel.label, curLabel);
                i.remove();
            } else {
                curLabel = visitLabel.label;
            }
        } else {
            curLabel = null;
        }
    }

    for (AsmInstr i : operations) {
        if (i instanceof VisitJumpInsn) {
            VisitJumpInsn jumpInsn = (VisitJumpInsn) i;
            jumpInsn.label = redirects.redirect(jumpInsn.label);
            continue;
        }

        if (i instanceof VisitLocalVariable) {
            VisitLocalVariable localVariable = (VisitLocalVariable) i;
            localVariable.start = redirects.redirect(localVariable.start);
            localVariable.end = redirects.redirect(localVariable.end);
            continue;
        }

        if (i instanceof VisitTryCatchBlock) {
            VisitTryCatchBlock tryCatchBlock = (VisitTryCatchBlock) i;
            tryCatchBlock.start = redirects.redirect(tryCatchBlock.start);
            tryCatchBlock.end = redirects.redirect(tryCatchBlock.end);
            tryCatchBlock.handler = redirects.redirect(tryCatchBlock.handler);
            continue;
        }

        if (i instanceof VisitLineNumber) {
            VisitLineNumber lineNumber = (VisitLineNumber) i;
            lineNumber.label = redirects.redirect(lineNumber.label);
            continue;
        }
    }

    redirects.clear();

    for (int i = 1; i < operations.size(); ++i) {
        AsmInstr instr = operations.get(i);
        if (instr instanceof VisitJumpInsn) {
            VisitJumpInsn jumpInsn = (VisitJumpInsn) instr;
            if (jumpInsn.opcode == Opcodes.GOTO) {
                AsmInstr prevInstr = operations.get(i - 1);
                if (prevInstr instanceof VisitLabel) {
                    redirects.put(((VisitLabel) prevInstr).label, jumpInsn.label);
                }
            }
        }
    }

    if (redirects.size() > 0) {
        for (AsmInstr instr : operations) {
            if (instr instanceof VisitJumpInsn) {
                VisitJumpInsn jumpInsn = (VisitJumpInsn) instr;
                jumpInsn.label = redirects.redirect(jumpInsn.label);
            }
        }
    }
}

From source file:org.mbte.groovypp.compiler.bytecode.BytecodeExpr.java

License:Apache License

/**
 * convert boolean to Boolean// www . j  a  v  a  2s . c o  m
 * @param mv
 */
public void boxBoolean(MethodVisitor mv) {
    Label l0 = new Label();
    mv.visitJumpInsn(Opcodes.IFEQ, l0);
    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;");
    Label l1 = new Label();
    mv.visitJumpInsn(Opcodes.GOTO, l1);
    mv.visitLabel(l0);
    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;");
    mv.visitLabel(l1);
}

From source file:org.mbte.groovypp.compiler.bytecode.BytecodeExpr.java

License:Apache License

/**
 * negate a boolean on stack. true->false, false->true
 * @param mv// w ww.  j ava  2s  . c o  m
 */
public void negateBoolean(MethodVisitor mv) {
    // code to negate the primitive boolean
    Label endLabel = new Label();
    Label falseLabel = new Label();
    mv.visitJumpInsn(Opcodes.IFNE, falseLabel);
    mv.visitInsn(Opcodes.ICONST_1);
    mv.visitJumpInsn(Opcodes.GOTO, endLabel);
    mv.visitLabel(falseLabel);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitLabel(endLabel);
}

From source file:org.mutabilitydetector.checkers.settermethod.AssignmentGuardFinder.java

License:Apache License

private static boolean isConditionCheckInstruction(final AbstractInsnNode insn) {
    final int opcode = insn.getOpcode();
    return AbstractInsnNode.JUMP_INSN == insn.getType() && opcode != Opcodes.GOTO && opcode != Opcodes.JSR
            && opcode != Opcodes.RET;
}

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

License:Open Source License

/**
 * Add the <clinit> method. This initializes the static fields that have initializers.
 * @param classRep/*from w w w  .  ja  v  a  2 s  .c om*/
 * @param cv
 * @param initializeForAsserts
 * @throws JavaGenerationException
 */
private static void encodeClassInitializer(JavaClassRep classRep, ClassVisitor cv, boolean initializeForAsserts)
        throws JavaGenerationException {

    // Add initializers for the statically-initialized fields.
    final int nFields = classRep.getNFieldDeclarations();

    if (!classRep.hasInitializedStaticField() && !initializeForAsserts) {
        //we don't need to bother adding a static initializer if there are no static fields to initialize.
        //note that javac also has this optimization.
        return;
    }

    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);

    // Start the method's code.
    mv.visitCode();

    final JavaTypeName classRepTypeName = classRep.getClassName();

    /*
     * If this class contains assert statements we need to initialize the static final synthetic boolean field
     * '$assertionsDisabled'.
     * This is done by loading the Class constant for the top level class. The method 'desiredAssertionStatus()'
     * is then invoked on this Class object and the returned value is used to initialize $assertionsDisabled. 
     */
    if (initializeForAsserts) {
        // Get the fully-qualified internal class  name.    
        final String className = classRepTypeName.getJVMInternalName();

        // Get the top level class name.
        String topLevelClassName = getTopLevelClassJVMInternalName(className);

        // Load the Class constant for the top level class
        mv.visitLdcInsn(Type.getType("L" + topLevelClassName + ";"));

        // Now that we have the Class constant for the top level class we invoke the method
        // desiredAssertionStatus on it and use the resulting value to initialize the static field $assertionsDisabled in this class.
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "desiredAssertionStatus", "()Z");
        Label l0 = new Label();
        mv.visitJumpInsn(Opcodes.IFNE, l0);
        mv.visitInsn(Opcodes.ICONST_1);
        Label l1 = new Label();
        mv.visitJumpInsn(Opcodes.GOTO, l1);
        mv.visitLabel(l0);
        mv.visitInsn(Opcodes.ICONST_0);
        mv.visitLabel(l1);
        mv.visitFieldInsn(Opcodes.PUTSTATIC, className, "$assertionsDisabled", "Z");
    }

    for (int i = 0; i < nFields; ++i) {

        JavaFieldDeclaration fieldDecl = classRep.getFieldDeclaration(i);
        JavaExpression initializer = fieldDecl.getInitializer();

        if (initializer != null && Modifier.isStatic(fieldDecl.getModifiers())) {

            GenerationContext context = new GenerationContext(new HashMap<String, JavaTypeName>(),
                    new HashMap<String, Integer>(), 0, mv, classRepTypeName);

            //evaluate the initializer
            encodeExpr(initializer, context);

            //do the assignment
            mv.visitFieldInsn(Opcodes.PUTSTATIC, classRep.getClassName().getJVMInternalName(),
                    fieldDecl.getFieldName(), fieldDecl.getFieldType().getJVMDescriptor());
        }
    }

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

    //mark the end of the method with a call to visitMaxs
    mv.visitMaxs(0, 0);

    // End the method.
    mv.visitEnd();
}