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:com.github.malamut2.low.AllocationMethodAdapter.java

License:Apache License

private void dupStackElementBeforeSignatureArgs(final String sig) {
    final Label beginScopeLabel = new Label();
    final Label endScopeLabel = new Label();
    super.visitLabel(beginScopeLabel);

    Type[] argTypes = Type.getArgumentTypes(sig);
    int[] args = new int[argTypes.length];

    for (int i = argTypes.length - 1; i >= 0; --i) {
        args[i] = newLocal(argTypes[i], beginScopeLabel, endScopeLabel);
        super.visitVarInsn(argTypes[i].getOpcode(Opcodes.ISTORE), args[i]);
    }//from w  w  w . java  2s.c  o  m
    super.visitInsn(Opcodes.DUP);
    for (int i = 0; i < argTypes.length; ++i) {
        int op = argTypes[i].getOpcode(Opcodes.ILOAD);
        super.visitVarInsn(op, args[i]);
        if (op == Opcodes.ALOAD) {
            super.visitInsn(Opcodes.ACONST_NULL);
            super.visitVarInsn(Opcodes.ASTORE, args[i]);
        }
    }
    super.visitLabel(endScopeLabel);
}

From source file:com.github.wreulicke.bean.validation.ASMMethodParameterValidationInjector.java

License:Open Source License

private void inject(MethodNode node, ClassNode clazzNode) {
    if (Modifier.isStatic(node.access) || Modifier.isAbstract(node.access) || Modifier.isAbstract(node.access)
            || "<init>".equals(node.name) || "<clinit>".equals(node.name)) {
        return;//w  w  w  .  java2 s  .c o m
    }

    InsnList list = new InsnList();
    int index = node.localVariables.size();
    list.add(new MethodInsnNode(INVOKESTATIC, "javax/validation/Validation", "buildDefaultValidatorFactory",
            "()Ljavax/validation/ValidatorFactory;", false));
    list.add(new MethodInsnNode(INVOKEINTERFACE, "javax/validation/ValidatorFactory", "getValidator",
            "()Ljavax/validation/Validator;", true));
    list.add(new MethodInsnNode(INVOKEINTERFACE, "javax/validation/Validator", "forExecutables",
            "()Ljavax/validation/executable/ExecutableValidator;", true));

    list.add(new VarInsnNode(Opcodes.ASTORE, index));
    list.add(new VarInsnNode(Opcodes.ALOAD, index));
    list.add(new VarInsnNode(Opcodes.ALOAD, 0));

    list.add(new LdcInsnNode(Type.getType("L" + clazzNode.name + ";")));
    list.add(new LdcInsnNode(node.name));

    @SuppressWarnings("unchecked")
    List<LocalVariableNode> variables = node.localVariables;
    Type[] args = Type.getArgumentTypes(node.desc);

    list.add(new LdcInsnNode(args.length));
    list.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Class"));

    for (int i = 0; i < args.length; i++) {
        int paramIndex = 1 + i;
        list.add(new InsnNode(Opcodes.DUP));
        list.add(new LdcInsnNode(i));
        list.add(new LdcInsnNode(Type.getType(variables.get(paramIndex).desc)));
        list.add(new InsnNode(Opcodes.AASTORE));
    }

    list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getMethod",
            "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false));

    list.add(new LdcInsnNode(args.length));
    list.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object"));
    for (int i = 0; i < args.length; i++) {
        int paramIndex = i + 1;
        list.add(new InsnNode(Opcodes.DUP));
        list.add(new LdcInsnNode(i));
        list.add(new VarInsnNode(Opcodes.ALOAD, paramIndex));
        list.add(new InsnNode(Opcodes.AASTORE));
    }
    list.add(new InsnNode(Opcodes.ICONST_0));
    list.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Class"));
    list.add(new MethodInsnNode(INVOKEINTERFACE, "javax/validation/executable/ExecutableValidator",
            "validateParameters",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;[Ljava/lang/Class;)Ljava/util/Set;",
            true));
    list.add(new MethodInsnNode(INVOKESTATIC, "com/github/wreulicke/bean/validation/Constraints",
            "throwIfNeeded", "(Ljava/util/Set;)V", false));
    node.instructions.insert(list);
}

From source file:com.google.devtools.build.android.desugar.BytecodeTypeInference.java

License:Open Source License

@Override
public void visitVarInsn(int opcode, int var) {
    switch (opcode) {
    case Opcodes.ILOAD:
        push(InferredType.INT);//from  w ww  . j  a va2s  .c om
        break;
    case Opcodes.LLOAD:
        push(InferredType.LONG);
        push(InferredType.TOP);
        break;
    case Opcodes.FLOAD:
        push(InferredType.FLOAT);
        break;
    case Opcodes.DLOAD:
        push(InferredType.DOUBLE);
        push(InferredType.TOP);
        break;
    case Opcodes.ALOAD:
        push(getLocalVariableType(var));
        break;
    case Opcodes.ISTORE:
    case Opcodes.FSTORE:
    case Opcodes.ASTORE: {
        InferredType type = pop();
        setLocalVariableTypes(var, type);
        break;
    }
    case Opcodes.LSTORE:
    case Opcodes.DSTORE: {
        InferredType type = pop(2);
        setLocalVariableTypes(var, type);
        setLocalVariableTypes(var + 1, InferredType.TOP);
        break;
    }
    case Opcodes.RET:
        throw new RuntimeException("The instruction RET is not supported");
    default:
        throw new RuntimeException("Unhandled opcode " + opcode);
    }
    super.visitVarInsn(opcode, var);
}

From source file:com.google.devtools.build.wireless.testing.java.injector.TypeDescriptorTest.java

License:Apache License

/**
 * Test method for {@link TypeDescriptor#getStoreOpcode()}.
 *//*from  ww  w. j ava2s  .c o  m*/
public void testGetStoreOpcode() {
    try {
        TypeDescriptor.VOID.getStoreOpcode();
        fail("Void should have thrown an exception!");
    } catch (IllegalStateException e) {
        // OK!
    }
    assertEquals("Wrong STORE instruction", Opcodes.ISTORE, TypeDescriptor.BOOLEAN.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.ISTORE, TypeDescriptor.BYTE.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.ISTORE, TypeDescriptor.CHAR.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.ISTORE, TypeDescriptor.SHORT.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.ISTORE, TypeDescriptor.INTEGER.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.LSTORE, TypeDescriptor.LONG.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.FSTORE, TypeDescriptor.FLOAT.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.DSTORE, TypeDescriptor.DOUBLE.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.ASTORE, TypeDescriptor.CLASS.getStoreOpcode());
    assertEquals("Wrong STORE instruction", Opcodes.ASTORE, TypeDescriptor.ARRAY.getStoreOpcode());
}

From source file:com.google.monitoring.runtime.instrumentation.adapters.AllocationMethodAdapter.java

License:Apache License

private void pushProductOfIntArrayOnStack() {
    final Label beginScopeLabel = new Label();
    final Label endScopeLabel = new Label();

    final int dimsArrayIndex = newLocal("[I", beginScopeLabel, endScopeLabel);
    final int counterIndex = newLocal("I", beginScopeLabel, endScopeLabel);
    final int productIndex = newLocal("I", beginScopeLabel, endScopeLabel);
    final Label loopLabel = new Label();
    final Label endLabel = new Label();

    super.visitLabel(beginScopeLabel);

    // stack: ... intArray
    super.visitVarInsn(Opcodes.ASTORE, dimsArrayIndex);
    // -> stack: ...

    // counter = 0
    super.visitInsn(Opcodes.ICONST_0);
    super.visitVarInsn(Opcodes.ISTORE, counterIndex);
    // product = 1
    super.visitInsn(Opcodes.ICONST_1);
    super.visitVarInsn(Opcodes.ISTORE, productIndex);
    // loop:/*from   ww w .j a  v  a  2 s  .com*/
    super.visitLabel(loopLabel);
    // if index >= arraylength goto end:
    super.visitVarInsn(Opcodes.ILOAD, counterIndex);
    super.visitVarInsn(Opcodes.ALOAD, dimsArrayIndex);
    super.visitInsn(Opcodes.ARRAYLENGTH);
    super.visitJumpInsn(Opcodes.IF_ICMPGE, endLabel);
    // product = product * max(array[counter],1)
    super.visitVarInsn(Opcodes.ALOAD, dimsArrayIndex);
    super.visitVarInsn(Opcodes.ILOAD, counterIndex);
    super.visitInsn(Opcodes.IALOAD);
    super.visitInsn(Opcodes.DUP);
    final Label nonZeroDimension = new Label();
    super.visitJumpInsn(Opcodes.IFNE, nonZeroDimension);
    super.visitInsn(Opcodes.POP);
    super.visitInsn(Opcodes.ICONST_1);
    super.visitLabel(nonZeroDimension);
    super.visitVarInsn(Opcodes.ILOAD, productIndex);
    super.visitInsn(Opcodes.IMUL); // if overflow happens it happens.
    super.visitVarInsn(Opcodes.ISTORE, productIndex);
    // iinc counter 1
    super.visitIincInsn(counterIndex, 1);
    // goto loop
    super.visitJumpInsn(Opcodes.GOTO, loopLabel);
    // end:
    super.visitLabel(endLabel);
    // re-push dimensions array
    super.visitVarInsn(Opcodes.ALOAD, dimsArrayIndex);
    // push product
    super.visitVarInsn(Opcodes.ILOAD, productIndex);

    super.visitLabel(endScopeLabel);
}

From source file:com.google.monitoring.runtime.instrumentation.adapters.AllocationMethodAdapter.java

License:Apache License

/**
 * Reflection-based allocation (@see java.lang.reflect.Array#newInstance) is
 * triggered with a static method call (INVOKESTATIC), so we hook it here.
 * Class initialization is triggered with a constructor call (INVOKESPECIAL)
 * so we hook that here too as a proxy for the new bytecode which leaves an
 * uninitialized object on the stack that we're not allowed to touch.
 * {@link java.lang.Object#clone} is also a call to INVOKESPECIAL,
 * and is hooked here.  {@link java.lang.Class#newInstance} and
 * {@link java.lang.reflect.Constructor#newInstance} are both
 * INVOKEVIRTUAL calls, so they are hooked here, as well.
 *//*from   w w  w  . ja v a2s.c om*/
@Override
public void visitMethodInsn(final int opcode, final String owner, final String name, final String signature,
        final boolean itf) {
    if (opcode == Opcodes.INVOKESTATIC &&
    // Array does its own native allocation.  Grr.
            owner.equals("java/lang/reflect/Array") && name.equals("newInstance")) {
        if (signature.equals("(Ljava/lang/Class;I)Ljava/lang/Object;")) {

            final Label beginScopeLabel = new Label();
            final Label endScopeLabel = new Label();
            super.visitLabel(beginScopeLabel);

            // stack: ... class count
            final int countIndex = newLocal("I", beginScopeLabel, endScopeLabel);
            super.visitVarInsn(Opcodes.ISTORE, countIndex);
            // -> stack: ... class
            pushClassNameOnStack();
            // -> stack: ... class className
            final int typeNameIndex = newLocal("Ljava/lang/String;", beginScopeLabel, endScopeLabel);
            super.visitVarInsn(Opcodes.ASTORE, typeNameIndex);
            // -> stack: ... class
            super.visitVarInsn(Opcodes.ILOAD, countIndex);
            // -> stack: ... class count
            super.visitMethodInsn(opcode, owner, name, signature, itf);
            // -> stack: ... newobj
            super.visitInsn(Opcodes.DUP);
            // -> stack: ... newobj newobj
            super.visitVarInsn(Opcodes.ILOAD, countIndex);
            // -> stack: ... newobj newobj count
            super.visitInsn(Opcodes.SWAP);
            // -> stack: ... newobj count newobj
            super.visitVarInsn(Opcodes.ALOAD, typeNameIndex);
            super.visitLabel(endScopeLabel);
            // -> stack: ... newobj count newobj className
            super.visitInsn(Opcodes.SWAP);
            // -> stack: ... newobj count className newobj
            super.visitMethodInsn(Opcodes.INVOKESTATIC, recorderClass, recorderMethod, RECORDER_SIGNATURE,
                    false);
            // -> stack: ... newobj
            return;
        } else if (signature.equals("(Ljava/lang/Class;[I)Ljava/lang/Object;")) {
            final Label beginScopeLabel = new Label();
            final Label endScopeLabel = new Label();
            super.visitLabel(beginScopeLabel);

            final int dimsArrayIndex = newLocal("[I", beginScopeLabel, endScopeLabel);
            // stack: ... class dimsArray
            pushProductOfIntArrayOnStack();
            // -> stack: ... class dimsArray product
            final int productIndex = newLocal("I", beginScopeLabel, endScopeLabel);
            super.visitVarInsn(Opcodes.ISTORE, productIndex);
            // -> stack: ... class dimsArray

            super.visitVarInsn(Opcodes.ASTORE, dimsArrayIndex);
            // -> stack: ... class
            pushClassNameOnStack();
            // -> stack: ... class className
            final int typeNameIndex = newLocal("Ljava/lang/String;", beginScopeLabel, endScopeLabel);
            super.visitVarInsn(Opcodes.ASTORE, typeNameIndex);
            // -> stack: ... class
            super.visitVarInsn(Opcodes.ALOAD, dimsArrayIndex);
            // -> stack: ... class dimsArray
            super.visitMethodInsn(opcode, owner, name, signature, itf);
            // -> stack: ... newobj

            super.visitInsn(Opcodes.DUP);
            // -> stack: ... newobj newobj
            super.visitVarInsn(Opcodes.ILOAD, productIndex);
            // -> stack: ... newobj newobj product
            super.visitInsn(Opcodes.SWAP);
            // -> stack: ... newobj product newobj
            super.visitVarInsn(Opcodes.ALOAD, typeNameIndex);
            super.visitLabel(endScopeLabel);
            // -> stack: ... newobj product newobj className
            super.visitInsn(Opcodes.SWAP);
            // -> stack: ... newobj product className newobj
            super.visitMethodInsn(Opcodes.INVOKESTATIC, recorderClass, recorderMethod, RECORDER_SIGNATURE,
                    false);
            // -> stack: ... newobj
            return;
        }
    }

    if (opcode == Opcodes.INVOKEVIRTUAL) {
        if ("clone".equals(name) && owner.startsWith("[")) {
            super.visitMethodInsn(opcode, owner, name, signature, itf);

            int i = 0;
            while (i < owner.length()) {
                if (owner.charAt(i) != '[') {
                    break;
                }
                i++;
            }
            if (i > 1) {
                // -> stack: ... newobj
                super.visitTypeInsn(Opcodes.CHECKCAST, owner);
                // -> stack: ... arrayref
                calculateArrayLengthAndDispatch(owner.substring(i), i);
            } else {
                // -> stack: ... newobj
                super.visitInsn(Opcodes.DUP);
                // -> stack: ... newobj newobj
                super.visitTypeInsn(Opcodes.CHECKCAST, owner);
                // -> stack: ... newobj arrayref
                super.visitInsn(Opcodes.ARRAYLENGTH);
                // -> stack: ... newobj length
                super.visitInsn(Opcodes.SWAP);
                // -> stack: ... length newobj
                invokeRecordAllocation(owner.substring(i));
            }
            return;
        } else if ("newInstance".equals(name)) {
            if ("java/lang/Class".equals(owner) && "()Ljava/lang/Object;".equals(signature)) {
                super.visitInsn(Opcodes.DUP);
                // -> stack: ... Class Class
                super.visitMethodInsn(opcode, owner, name, signature, itf);
                // -> stack: ... Class newobj
                super.visitInsn(Opcodes.DUP_X1);
                // -> stack: ... newobj Class newobj
                super.visitMethodInsn(Opcodes.INVOKESTATIC, recorderClass, recorderMethod, CLASS_RECORDER_SIG,
                        false);
                // -> stack: ... newobj
                return;
            } else if ("java/lang/reflect/Constructor".equals(owner)
                    && "([Ljava/lang/Object;)Ljava/lang/Object;".equals(signature)) {
                buildRecorderFromObject(opcode, owner, name, signature, itf);
                return;
            }
        }
    }

    if (opcode == Opcodes.INVOKESPECIAL) {
        if ("clone".equals(name) && "java/lang/Object".equals(owner)) {
            buildRecorderFromObject(opcode, owner, name, signature, itf);
            return;
        } else if ("<init>".equals(name) && outstandingAllocs > 0) {
            // Tricky because superclass initializers mean there can be more calls
            // to <init> than calls to NEW; hence outstandingAllocs.
            --outstandingAllocs;

            // Most of the time (i.e. in bytecode generated by javac) it is the case
            // that following an <init> call the top of the stack has a reference ot
            // the newly-initialized object.  But nothing in the JVM Spec requires
            // this, so we need to play games with the stack to make an explicit
            // extra copy (and then discard it).

            dupStackElementBeforeSignatureArgs(signature);
            super.visitMethodInsn(opcode, owner, name, signature, itf);
            super.visitLdcInsn(-1);
            super.visitInsn(Opcodes.SWAP);
            invokeRecordAllocation(owner);
            super.visitInsn(Opcodes.POP);
            return;
        }
    }

    super.visitMethodInsn(opcode, owner, name, signature, itf);
}

From source file:com.google.monitoring.runtime.instrumentation.adapters.AllocationMethodAdapter.java

License:Apache License

private void dupStackElementBeforeSignatureArgs(final String sig) {
    final Label beginScopeLabel = new Label();
    final Label endScopeLabel = new Label();
    super.visitLabel(beginScopeLabel);

    final Type[] argTypes = Type.getArgumentTypes(sig);
    final int[] args = new int[argTypes.length];

    for (int i = argTypes.length - 1; i >= 0; --i) {
        args[i] = newLocal(argTypes[i], beginScopeLabel, endScopeLabel);
        super.visitVarInsn(argTypes[i].getOpcode(Opcodes.ISTORE), args[i]);
    }// w  w w . ja v  a2s. c o  m
    super.visitInsn(Opcodes.DUP);
    for (int i = 0; i < argTypes.length; ++i) {
        final int op = argTypes[i].getOpcode(Opcodes.ILOAD);
        super.visitVarInsn(op, args[i]);
        if (op == Opcodes.ALOAD) {
            super.visitInsn(Opcodes.ACONST_NULL);
            super.visitVarInsn(Opcodes.ASTORE, args[i]);
        }
    }
    super.visitLabel(endScopeLabel);
}

From source file:com.google.template.soy.jbcsrc.TemplateFactoryCompiler.java

License:Apache License

/**
 * Generates a static initializer that references the CompiledTemplate class to force eager
 * classloading (and thus verification errors). For example, <pre>{@code
 *   static {//  w w  w  .  j  a  v  a 2s  . com
 *     Class<?> clz = GeneratedTemplateClass.class;
 *   }}</pre>
 */
private void generateStaticInitializer(ClassVisitor cv) {
    if (Flags.DEBUG) {
        new Statement() {
            @Override
            void doGen(CodeBuilder adapter) {
                adapter.pushType(template.typeInfo().type());
                adapter.visitVarInsn(Opcodes.ASTORE, 0);
                adapter.returnValue();
            }
        }.writeMethod(Opcodes.ACC_STATIC, BytecodeUtils.CLASS_INIT, cv);
    }
}

From source file:com.google.test.metric.asm.MethodVisitorBuilder.java

License:Apache License

public void visitVarInsn(final int opcode, final int var) {
    switch (opcode) {
    case Opcodes.ILOAD:
        load(var, JavaType.INT);
        break;/* w  w w. j  a  v a2s  .c  o  m*/
    case Opcodes.LLOAD:
        load(var, JavaType.LONG);
        break;
    case Opcodes.FLOAD:
        load(var, JavaType.FLOAT);
        break;
    case Opcodes.DLOAD:
        load(var, JavaType.DOUBLE);
        break;
    case Opcodes.ALOAD:
        load(var, JavaType.OBJECT);
        break;

    case Opcodes.ISTORE:
        store(var, JavaType.INT);
        break;
    case Opcodes.LSTORE:
        store(var, JavaType.LONG);
        break;
    case Opcodes.FSTORE:
        store(var, JavaType.FLOAT);
        break;
    case Opcodes.DSTORE:
        store(var, JavaType.DOUBLE);
        break;
    case Opcodes.ASTORE:
        store(var, JavaType.OBJECT);
        break;

    case Opcodes.RET:
        recorder.add(new Runnable() {
            public void run() {
                block.addOp(new RetSub(lineNumber));
            }
        });
        break;
    default:
        throw new UnsupportedOperationException("opcode: " + opcode);
    }
}

From source file:com.khubla.jvmbasic.jvmbasicc.function.impl.rule.variableassignmentRule.java

License:Open Source License

@Override
public boolean execute(GenerationContext generationContext) throws Exception {
    try {//from w ww .  j  a  v a2s  .co m
        /*
         * the tree should have 3 sub nodes like this "variableassignment : vardecl EQ exprlist"
         */
        String variableName = null;
        if (generationContext.getParseTree().getChildCount() == 3) {
            /*
             * get the variable name
             */
            variableName = VariableNameUtil
                    .getVariableName((VardeclContext) generationContext.getParseTree().getChild(0));
            /*
             * get the tree for the value. this should push the value onto the ExecutionContextStack
             */
            final ExprlistContext exprlistContext = (ExprlistContext) generationContext.getParseTree()
                    .getChild(2);
            final GenerationContext subGenerationContext = new GenerationContext(generationContext,
                    exprlistContext);
            Dispatcher.dispatch(subGenerationContext);
        } else {
            throw new Exception(
                    "Invalid number of arguments '" + generationContext.getParseTree().getChildCount() + "'");
        }
        /*
         * store the top of the stack into slot 1
         */
        generationContext.getMethodVisitor().visitVarInsn(Opcodes.ALOAD, 0);
        generationContext.getMethodVisitor().visitFieldInsn(Opcodes.GETFIELD, generationContext.getClassName(),
                RTLHelper.EXECUTIONCONTEXT_NAME, RTLHelper.JASIC_RUNTIME_EXECUTIONCONTEXT_TYPE);
        generationContext.getMethodVisitor().visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                RTLHelper.JASIC_RUNTIME_EXECUTIONCONTEXT, "pop", "()Lcom/khubla/jvmbasic/jvmbasicrt/Value;");
        generationContext.getMethodVisitor().visitVarInsn(Opcodes.ASTORE, 1);
        /*
         * put the value in slot 1 into the variable in the execution context
         */
        generationContext.getMethodVisitor().visitVarInsn(Opcodes.ALOAD, 0);
        generationContext.getMethodVisitor().visitFieldInsn(Opcodes.GETFIELD, generationContext.getClassName(),
                RTLHelper.EXECUTIONCONTEXT_NAME, RTLHelper.JASIC_RUNTIME_EXECUTIONCONTEXT_TYPE);
        generationContext.getMethodVisitor().visitLdcInsn(variableName);
        generationContext.getMethodVisitor().visitVarInsn(Opcodes.ALOAD, 1);
        generationContext.getMethodVisitor().visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                RTLHelper.JASIC_RUNTIME_EXECUTIONCONTEXT, "setVariable",
                "(Ljava/lang/String;Lcom/khubla/jvmbasic/jvmbasicrt/Value;)V");
        return true;
    } catch (final Exception e) {
        throw new Exception("Exception in execute", e);
    }
}