Example usage for org.objectweb.asm Opcodes ASTORE

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

Introduction

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

Prototype

int ASTORE

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

Click Source Link

Usage

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

License:Open Source License

public int storeInstance(final MethodVisitor mv, final int variable) {
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, className, InstrSupport.INITMETHOD_NAME,
            InstrSupport.INITMETHOD_DESC, false);
    mv.visitVarInsn(Opcodes.ASTORE, variable);
    return 1;/*from  www  .j ava 2 s.  c o m*/
}

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

License:Open Source License

@Override
public void visitVarInsn(final int opcode, final int var) {
    final Object t;
    switch (opcode) {
    case Opcodes.ALOAD:
        push(get(var));
        break;/*  ww  w .  j  a v a2 s  . c  o m*/
    case Opcodes.ILOAD:
        push(Opcodes.INTEGER);
        break;
    case Opcodes.FLOAD:
        push(Opcodes.FLOAT);
        break;
    case Opcodes.LLOAD:
        push(Opcodes.LONG);
        push(Opcodes.TOP);
        break;
    case Opcodes.DLOAD:
        push(Opcodes.DOUBLE);
        push(Opcodes.TOP);
        break;
    case Opcodes.ASTORE:
    case Opcodes.ISTORE:
    case Opcodes.FSTORE:
        t = pop();
        set(var, t);
        break;
    case Opcodes.LSTORE:
    case Opcodes.DSTORE:
        pop(1);
        t = pop();
        set(var, t);
        set(var + 1, Opcodes.TOP);
        break;
    default:
        throw new IllegalArgumentException();
    }
    mv.visitVarInsn(opcode, var);
}

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

License:Open Source License

public int storeInstance(final MethodVisitor mv, final boolean clinit, final int variable) {
    if (clinit) {
        final int maxStack = accessorGenerator.generateDataAccessor(classId, className, probeCount, mv);

        // Stack[0]: [Z

        mv.visitInsn(Opcodes.DUP);/*from   w  w w.  j  av a 2 s .  co m*/

        // Stack[1]: [Z
        // Stack[0]: [Z

        mv.visitFieldInsn(Opcodes.PUTSTATIC, className, InstrSupport.DATAFIELD_NAME,
                InstrSupport.DATAFIELD_DESC);

        // Stack[0]: [Z

        mv.visitVarInsn(Opcodes.ASTORE, variable);

        seenClinit = true;
        return Math.max(maxStack, 2);
    } else {
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, className, InstrSupport.INITMETHOD_NAME,
                InstrSupport.INITMETHOD_DESC, true);
        mv.visitVarInsn(Opcodes.ASTORE, variable);
        return 1;
    }
}

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

License:Open Source License

public int storeInstance(final MethodVisitor mv, final boolean clinit, final int variable) {
    final int maxStack = accessorGenerator.generateDataAccessor(classId, className, probeCount, mv);
    mv.visitVarInsn(Opcodes.ASTORE, variable);
    return maxStack;
}

From source file:org.jboss.byteman.agent.adapter.cfg.CFG.java

License:Open Source License

/**
 * return the index of the local var at which this monitorenter saved its lock object
 *//*from w w w . ja  v a 2  s .  co m*/
public int getSavedMonitorIdx(CodeLocation open) {
    // this should identify a monitorexit instruction preceded by an aload N instruction
    BBlock block = open.getBlock();
    int instructionIdx = open.getInstructionIdx();
    if (instructionIdx <= 0) {
        System.out.println("getSavedMonitorIdx : unexpected! close pair has invalid index " + instructionIdx
                + " in method " + methodName);
    }
    int instruction = block.getInstruction(instructionIdx);
    if (instruction != Opcodes.MONITORENTER) {
        System.out.println("getSavedMonitorIdx : unexpected! close pair instruction " + instruction
                + " is not MONITOREXIT in method " + methodName);
    }
    instructionIdx--;
    instruction = block.getInstruction(instructionIdx);
    // normally the monitorenter is preceded by a DUP ASTORE pair to save the monitor object
    // however, if an AT SYNCHRONIZE trigger has been injected before the MONITORENTER then
    // there may be a call to Rule.execute between the ASTORE and the MONITORENTER
    if (instruction == Opcodes.INVOKESTATIC) {
        // we can safely skip backwards to the last ASTORE because the trigger sequence will not
        // use an ASTORE
        while (instruction != Opcodes.ASTORE && instructionIdx > 0) {
            // skip backwards until we find the required ASTORE
            instructionIdx--;
            instruction = block.getInstruction(instructionIdx);
        }
    }
    if (instruction != Opcodes.ASTORE) {
        System.out.println("getSavedMonitorIdx : unexpected! close pair preceding instruction " + instruction
                + " is not ASTORE in method " + methodName);
        return -1;
    }
    int varIdx = block.getInstructionArg(instructionIdx, 0);
    if (varIdx < 0) {
        System.out.println(
                "getSavedMonitorIdx : unexpected! close pair preceding ASTORE instruction has invalid index "
                        + varIdx + " in method " + methodName);
    }
    return varIdx;
}

From source file:org.jboss.byteman.agent.adapter.cfg.CFG.java

License:Open Source License

/**
 * return true if the current block is a rethrow handler i.e. one which was created to close a monitor
 * exit instruction and then rethrow an exception. n.b. this must only be called when the next instruction
 * to be added to the byetcode sequence is an ATHROW
 * @return true if the current block is a rethrow handler
 *///from  ww w .j  ava 2s. com
public boolean inRethrowHandler() {
    int nextIdx = current.getInstructionCount();
    // a compiler generated rethrow block always has the same format
    // astore  N1
    // aload   N2
    // monitorexit
    // aload   N1
    // athrow
    if ((nextIdx >= 4) && current.getInstruction(nextIdx - 1) == Opcodes.ALOAD
            && current.getInstruction(nextIdx - 2) == Opcodes.MONITOREXIT
            && current.getInstruction(nextIdx - 3) == Opcodes.ALOAD
            && current.getInstruction(nextIdx - 4) == Opcodes.ASTORE
            && current.getInstructionArg(nextIdx - 1, 0) == current.getInstructionArg(nextIdx - 4, 0)) {
        return true;
    }

    // a rethrow block generated by byteman has the simpler format
    // aload   N1
    // monitorexit
    // athrow
    if ((nextIdx >= 2) && current.getInstruction(nextIdx - 1) == Opcodes.MONITOREXIT
            && current.getInstruction(nextIdx - 2) == Opcodes.ALOAD) {
        return true;
    }

    return false;
}

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

License:Open Source License

/**
 * override this so we can see track which local var slots are in use and avoid overwriting them
 * @param opcode/*  w ww  . j  a  va2  s . c o m*/
 * @param var
 */
public void visitVarInsn(final int opcode, final int var) {
    if (var >= nextLocal || localTypes.get(var) == null) {
        int size = 1;
        Type type = null;
        switch (opcode) {
        case Opcodes.ISTORE:
            type = Type.INT_TYPE;
            break;
        case Opcodes.LSTORE:
            type = Type.LONG_TYPE;
            size = 2;
            break;
        case Opcodes.FSTORE:
            type = Type.FLOAT_TYPE;
            break;
        case Opcodes.DSTORE:
            type = Type.DOUBLE_TYPE;
            size = 2;
            break;
        case Opcodes.ASTORE:
        // we don't know exactly what type this is but at least we know it is an object
        {
            String name = getTriggerClassName().replace('.', '/');
            type = Type.getType("L" + name + ";");
        }
            // type = Type.getType(Object.class);
            break;
        }
        if (var < nextLocal) {
            // just fill in the missing type
            localTypes.set(var, type);
        } else {

            // we may not have seen some of the locals so leave a blank spot for them in the types array
            for (int i = nextLocal; i < var; i++) {
                localTypes.add(null);
            }
            // now add entry for var

            localTypes.add(type);
            if (size > 1) {
                localTypes.add(null);
            }
            nextLocal = var + size;

            if (nextLocal > localHighWater) {
                localHighWater = nextLocal;
            }
        }
    }
    super.visitVarInsn(opcode, var);
}

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

License:Open Source License

/**
 * Reads the bytecode from the given {@link InsnCursor}'s <strong>current position</strong>, until
 * there is no further instruction to proceed. It is the responsability of the caller to set the
 * cursor position./*from w  w  w .j  a va  2 s. c o m*/
 * 
 * @param insnCursor the instruction cursor used to read the bytecode.
 * @param expressionStack the expression stack to put on or pop from.
 * @param localVariables the local variables
 * @return a {@link List} of {@link Statement} containing the {@link Statement}
 */
private List<Statement> readStatements(final InsnCursor insnCursor, final Stack<Expression> expressionStack,
        final List<CapturedArgument> capturedArguments, final LocalVariables localVariables) {
    final List<Statement> statements = new ArrayList<>();
    while (insnCursor.hasCurrent()) {
        final AbstractInsnNode currentInstruction = insnCursor.getCurrent();
        switch (currentInstruction.getType()) {
        case AbstractInsnNode.VAR_INSN:
            final VarInsnNode varInstruction = (VarInsnNode) currentInstruction;
            switch (currentInstruction.getOpcode()) {
            // load a reference onto the stack from a local variable
            case Opcodes.ALOAD:
            case Opcodes.ILOAD:
                // load an int value from a local variable
                // Note: The 'var' operand is the index of a local variable
                // all captured arguments come before the local variable in the method signature,
                // which means that the local variables table is empty on the first slots which are
                // "allocated"
                // for the captured arguments.
                if (varInstruction.var < capturedArguments.size()) {
                    // if the variable index matches a captured argument
                    // note: not using actual captured argument but rather, use a _reference_ to it.
                    final Object capturedArgumentValue = capturedArguments.get(varInstruction.var).getValue();
                    final Class<?> capturedArgumentValueType = capturedArgumentValue != null
                            ? capturedArgumentValue.getClass()
                            : Object.class;
                    final CapturedArgumentRef capturedArgumentRef = new CapturedArgumentRef(varInstruction.var,
                            capturedArgumentValueType);
                    expressionStack.add(capturedArgumentRef);
                } else {
                    // the variable index matches a local variable
                    final LocalVariableNode var = localVariables.load(varInstruction.var);
                    expressionStack.add(new LocalVariable(var.index, var.name, readSignature(var.desc)));
                }
                break;
            case Opcodes.ASTORE:
                // store a reference into a local variable
                localVariables.store(varInstruction.var);
                break;
            default:
                throw new AnalyzeException(
                        "Unexpected Variable instruction code: " + varInstruction.getOpcode());
            }
            break;
        case AbstractInsnNode.LDC_INSN:
            // let's move this instruction on top of the stack until it
            // is used as an argument during a method call
            final LdcInsnNode ldcInsnNode = (LdcInsnNode) currentInstruction;
            final Expression constant = ExpressionFactory.getExpression(ldcInsnNode.cst);
            LOGGER.trace("Stacking constant {}", constant);
            expressionStack.add(constant);
            break;
        case AbstractInsnNode.FIELD_INSN:
            final FieldInsnNode fieldInsnNode = (FieldInsnNode) currentInstruction;
            switch (fieldInsnNode.getOpcode()) {
            case Opcodes.GETSTATIC:
                final Type ownerType = Type.getType(fieldInsnNode.desc);
                final FieldAccess staticFieldAccess = new FieldAccess(new ClassLiteral(getType(ownerType)),
                        fieldInsnNode.name);
                expressionStack.add(staticFieldAccess);
                break;

            case Opcodes.GETFIELD:
                final Expression fieldAccessParent = expressionStack.pop();
                final FieldAccess fieldAccess = new FieldAccess(fieldAccessParent, fieldInsnNode.name);
                expressionStack.add(fieldAccess);
                break;
            case Opcodes.PUTFIELD:
                final Expression fieldAssignationValue = expressionStack.pop();
                final Expression parentSource = expressionStack.pop();
                final FieldAccess source = new FieldAccess(parentSource, fieldInsnNode.name);
                final Assignment assignmentExpression = new Assignment(source, fieldAssignationValue);
                statements.add(new ExpressionStatement(assignmentExpression));
                break;
            default:
                throw new AnalyzeException("Unexpected field instruction type: " + fieldInsnNode.getOpcode());

            }
            break;
        case AbstractInsnNode.METHOD_INSN:
            final MethodInsnNode methodInsnNode = (MethodInsnNode) currentInstruction;
            final Type[] argumentTypes = Type.getArgumentTypes(methodInsnNode.desc);
            final List<Expression> args = new ArrayList<>();
            final List<Class<?>> parameterTypes = new ArrayList<>();
            Stream.of(argumentTypes).forEach(argumentType -> {
                final Expression arg = expressionStack.pop();
                final String argumentClassName = argumentType.getClassName();
                args.add(castOperand(arg, argumentClassName));
                try {
                    parameterTypes.add(ClassUtils.getClass(argumentClassName));
                } catch (Exception e) {
                    throw new AnalyzeException("Failed to find class '" + argumentClassName + "'", e);
                }
            });
            // arguments appear in reverse order in the bytecode
            Collections.reverse(args);
            switch (methodInsnNode.getOpcode()) {
            case Opcodes.INVOKEINTERFACE:
            case Opcodes.INVOKEVIRTUAL:
            case Opcodes.INVOKESPECIAL:
                // object instantiation
                if (methodInsnNode.name.equals("<init>")) {
                    final ObjectInstanciation objectVariable = (ObjectInstanciation) expressionStack.pop();
                    objectVariable.setInitArguments(args);
                } else {
                    final Expression sourceExpression = expressionStack.pop();
                    final Method javaMethod = ReflectionUtils.findJavaMethod(sourceExpression.getJavaType(),
                            methodInsnNode.name, parameterTypes);
                    final Class<?> returnType = findReturnType(insnCursor, javaMethod);
                    final MethodInvocation invokedMethod = new MethodInvocation(sourceExpression, javaMethod,
                            returnType, args);
                    expressionStack.add(invokedMethod);
                }
                break;
            case Opcodes.INVOKESTATIC:
                final Type type = Type.getObjectType(methodInsnNode.owner);
                try {
                    final Class<?> sourceClass = Class.forName(type.getClassName());
                    final Method javaMethod = ReflectionUtils.findJavaMethod(sourceClass, methodInsnNode.name,
                            parameterTypes);
                    final Class<?> returnType = findReturnType(insnCursor, javaMethod);
                    final MethodInvocation invokedStaticMethod = new MethodInvocation(
                            new ClassLiteral(sourceClass), javaMethod, returnType, args);
                    expressionStack.add(invokedStaticMethod);
                } catch (ClassNotFoundException e) {
                    throw new AnalyzeException("Failed to retrieve class for " + methodInsnNode.owner, e);
                }
                break;
            default:
                throw new AnalyzeException("Unexpected method invocation type: " + methodInsnNode.getOpcode());
            }
            break;
        case AbstractInsnNode.INVOKE_DYNAMIC_INSN:
            final InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) currentInstruction;
            final Handle handle = (Handle) invokeDynamicInsnNode.bsmArgs[1];
            final int argNumber = Type.getArgumentTypes(invokeDynamicInsnNode.desc).length;
            final List<CapturedArgumentRef> lambdaArgs = new ArrayList<>();
            for (int i = 0; i < argNumber; i++) {
                final Expression expr = expressionStack.pop();
                if (expr.getExpressionType() != ExpressionType.CAPTURED_ARGUMENT_REF) {
                    throw new AnalyzeException("Unexpected argument type when following InvokeDynamic call: "
                            + expr.getExpressionType());
                }
                lambdaArgs.add((CapturedArgumentRef) expr); // , expr.getValue()
            }
            Collections.reverse(lambdaArgs);
            final EmbeddedSerializedLambdaInfo lambdaInfo = new EmbeddedSerializedLambdaInfo(handle.getOwner(),
                    handle.getName(), handle.getDesc(), lambdaArgs, capturedArguments);
            final LambdaExpression lambdaExpression = LambdaExpressionAnalyzer.getInstance()
                    .analyzeExpression(lambdaInfo);
            expressionStack.add(lambdaExpression);
            break;
        case AbstractInsnNode.JUMP_INSN:
            statements.addAll(
                    readJumpInstruction(insnCursor, expressionStack, capturedArguments, localVariables));
            return statements;
        case AbstractInsnNode.INT_INSN:
            readIntInstruction((IntInsnNode) currentInstruction, expressionStack, localVariables);
            break;
        case AbstractInsnNode.INSN:
            final List<Statement> instructionStatement = readInstruction(insnCursor, expressionStack,
                    capturedArguments, localVariables);
            statements.addAll(instructionStatement);
            break;
        case AbstractInsnNode.TYPE_INSN:
            readTypeInstruction((TypeInsnNode) currentInstruction, expressionStack, localVariables);
            break;
        default:
            throw new AnalyzeException(
                    "This is embarrassing... We've reached an unexpected instruction operator: "
                            + currentInstruction.getType());
        }
        insnCursor.next();
    }
    return statements;
}

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

License:Apache License

public static void store(ClassNode type, int idx, MethodVisitor mv) {
    if (type == double_TYPE) {
        mv.visitVarInsn(Opcodes.DSTORE, idx);
    } else if (type == float_TYPE) {
        mv.visitVarInsn(Opcodes.FSTORE, idx);
    } else if (type == long_TYPE) {
        mv.visitVarInsn(Opcodes.LSTORE, idx);
    } else if (type == boolean_TYPE || type == char_TYPE || type == byte_TYPE || type == int_TYPE
            || type == short_TYPE) {
        mv.visitVarInsn(Opcodes.ISTORE, idx);
    } else {/*from  w  w w . j a  v a 2s  .com*/
        mv.visitVarInsn(Opcodes.ASTORE, idx);
    }
}

From source file:org.mbte.groovypp.compiler.StaticCompiler.java

License:Apache License

private void tailRecursive(ResolvedMethodBytecodeExpr resolvedMethodBytecodeExpr) {
    Parameter[] parameters = methodNode.getParameters();

    int varIndex = methodNode.isStatic() ? 0 : 1;
    if (varIndex != 0) {
        resolvedMethodBytecodeExpr.getObject().visit(mv);
    }/*w  ww .  ja v  a2  s.c  o  m*/
    for (int i = 0; i != parameters.length; ++i) {
        BytecodeExpr be = (BytecodeExpr) resolvedMethodBytecodeExpr.getBargs().getExpressions().get(i);
        be.visit(mv);
        final ClassNode paramType = parameters[i].getType();
        final ClassNode type = be.getType();
        BytecodeExpr.box(type, mv);
        BytecodeExpr.cast(TypeUtil.wrapSafely(type), TypeUtil.wrapSafely(paramType), mv);
        BytecodeExpr.unbox(paramType, mv);

        varIndex += (paramType == ClassHelper.long_TYPE || paramType == ClassHelper.double_TYPE) ? 2 : 1;
    }

    for (int i = parameters.length - 1; i >= 0; --i) {
        final ClassNode paramType = parameters[i].getType();
        varIndex -= (paramType == ClassHelper.long_TYPE || paramType == ClassHelper.double_TYPE) ? 2 : 1;

        if (paramType == double_TYPE) {
            mv.visitVarInsn(Opcodes.DSTORE, varIndex);
        } else if (paramType == float_TYPE) {
            mv.visitVarInsn(Opcodes.FSTORE, varIndex);
        } else if (paramType == long_TYPE) {
            mv.visitVarInsn(Opcodes.LSTORE, varIndex);
        } else if (paramType == boolean_TYPE || paramType == char_TYPE || paramType == byte_TYPE
                || paramType == int_TYPE || paramType == short_TYPE) {
            mv.visitVarInsn(Opcodes.ISTORE, varIndex);
        } else {
            mv.visitVarInsn(Opcodes.ASTORE, varIndex);
        }
    }

    if (!methodNode.isStatic()) {
        mv.visitVarInsn(ASTORE, 0);
    }
    mv.visitJumpInsn(GOTO, startLabel);
    return;
}