Example usage for org.objectweb.asm Opcodes NEW

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

Introduction

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

Prototype

int NEW

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

Click Source Link

Usage

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

License:Open Source License

private void frame(MethodVisitor mv) {
    mv.visitFrame(Opcodes.NEW, 1, new Object[] { Opcodes.INTEGER }, 0, new Object[0]);
}

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 .  j ava 2  s. co  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.jacoco.core.runtime.URLStreamHandlerRuntime.java

License:Open Source License

public int generateDataAccessor(final long classid, final String classname, final int probecount,
        final MethodVisitor mv) {

    // The data accessor performs the following steps:
    ///* w  ww  . ja  v a  2s .  co m*/
    // final URL url = new URL(protocol, null, "");
    // final URLConnection connection = url.openConnection();
    // final Object[] args = new Object[3];
    // args[0] = Long.valueOf(classid);
    // args[1] = classname;
    // args[2] = Integer.valueOf(probecount);
    // connection.equals(args);
    // final byte[] probedata = (byte[]) args[0];

    RuntimeData.generateArgumentArray(classid, classname, probecount, mv);
    mv.visitInsn(Opcodes.DUP);

    // Stack[1]: [Ljava/lang/Object;
    // Stack[0]: [Ljava/lang/Object;

    mv.visitTypeInsn(Opcodes.NEW, "java/net/URL");
    mv.visitInsn(Opcodes.DUP);
    mv.visitLdcInsn(protocol);
    mv.visitInsn(Opcodes.ACONST_NULL);
    mv.visitLdcInsn("");
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/net/URL", "<init>",
            "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");

    // Stack[2]: [Ljava/net/URL;
    // Stack[1]: [Ljava/lang/Object;
    // Stack[0]: [Ljava/lang/Object;

    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/net/URL", "openConnection", "()Ljava/net/URLConnection;");

    // Stack[2]: [Ljava/net/URLConnection;
    // Stack[1]: [Ljava/lang/Object;
    // Stack[0]: [Ljava/lang/Object;

    mv.visitInsn(Opcodes.SWAP);

    // Stack[2]: [Ljava/lang/Object;
    // Stack[1]: [Ljava/net/URLConnection;
    // Stack[0]: [Ljava/lang/Object;

    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z");

    // Stack[1]: Z;
    // Stack[0]: [Ljava/lang/Object;

    mv.visitInsn(Opcodes.POP);

    // Stack[0]: [Ljava/lang/Object;

    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitInsn(Opcodes.AALOAD);
    mv.visitTypeInsn(Opcodes.CHECKCAST, InstrSupport.DATAFIELD_DESC);

    return 7;
}

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

License:Open Source License

/**
 * Generates the instruction to create a new object.
 *
 * @param type the class of the object to be created.
 *///  w w  w .  j av a 2 s  .  com
public void newInstance(final Type type) {
    typeInsn(Opcodes.NEW, type);
}

From source file:org.jboss.byteman.rule.expression.NewExpression.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);

    int currentStack = compileContext.getStackCount();
    int expected = 1;
    int extraParams = 0;

    if (arrayDimCount == 0) {
        // ok, we need to create the new instance and then initialise it.

        // create the new instance -- adds 1 to stack
        String instantiatedClassName = type.getInternalName();
        mv.visitTypeInsn(Opcodes.NEW, instantiatedClassName);
        compileContext.addStackCount(1);
        // copy the exception so we can init it
        mv.visitInsn(Opcodes.DUP);/*from w  ww . jav a 2 s  .  co  m*/
        compileContext.addStackCount(1);

        int argCount = arguments.size();

        // stack each of the arguments to the constructor
        for (int i = 0; i < argCount; i++) {
            Type argType = argumentTypes.get(i);
            Type paramType = paramTypes.get(i);
            int paramCount = (paramType.getNBytes() > 4 ? 2 : 1);

            // track extra storage used after type conversion
            extraParams += (paramCount);
            arguments.get(i).compile(mv, compileContext);
            compileTypeConversion(argType, paramType, mv, compileContext);
        }

        // construct the exception
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, instantiatedClassName, "<init>", getDescriptor());

        // modify the stack height to account for the removed exception and params
        compileContext.addStackCount(-(extraParams + 1));
    } else {
        // TODO !!! implement compilation for array types !!!
        if (arrayDimCount == 1) {
            // we can use a NEWARRAY or ANEWARRAY
            Type baseType = type.getBaseType();
            // compile first array dimension adds 1 to stack
            arrayDims.get(0).compile(mv, compileContext);
            // compile new array op -- pops 1 and adds 1 to stack
            if (baseType.isObject()) {
                mv.visitTypeInsn(Opcodes.ANEWARRAY, baseType.getInternalName());
                // } else if (baseType.isArray()) {  // cannot happen!!!
            } else {
                int operand = 0;
                if (baseType.equals(Type.Z)) {
                    operand = Opcodes.T_BOOLEAN;
                } else if (baseType.equals(Type.B)) {
                    operand = Opcodes.T_BYTE;
                } else if (baseType.equals(Type.S)) {
                    operand = Opcodes.T_SHORT;
                } else if (baseType.equals(Type.C)) {
                    operand = Opcodes.T_CHAR;
                } else if (baseType.equals(Type.I)) {
                    operand = Opcodes.T_INT;
                } else if (baseType.equals(Type.J)) {
                    operand = Opcodes.T_LONG;
                } else if (baseType.equals(Type.F)) {
                    operand = Opcodes.T_FLOAT;
                } else if (baseType.equals(Type.D)) {
                    operand = Opcodes.T_DOUBLE;
                }
                mv.visitIntInsn(Opcodes.NEWARRAY, operand);
            }
        } else {
            // we need to use MULTIANEWARRAY

            for (int i = 0; i < arrayDimDefinedCount; i++) {
                // compile next array dimension adds 1 to stack
                arrayDims.get(i).compile(mv, compileContext);
            }
            // execute the MULTIANEWARRAY operation -- pops arrayDims operands and pushes 1
            mv.visitMultiANewArrayInsn(type.getInternalName(), arrayDimDefinedCount);
            compileContext.addStackCount(1 - arrayDimDefinedCount);
        }
    }

    if (compileContext.getStackCount() != currentStack + expected) {
        throw new CompileException("NewExpression.compile : invalid stack height "
                + compileContext.getStackCount() + " expecting " + (currentStack + expected));
    }
}

From source file:org.jboss.byteman.rule.expression.ReturnExpression.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);

    Type valueType = (returnValue == null ? Type.VOID : returnValue.getType());
    int currentStack = compileContext.getStackCount();
    int expected = 1;

    // ok, we need to create the EarlyReturnException instance and then
    // initialise it using the appropriate return value or null if no
    // return value is needed. strictly we should maybe delay the
    // new until after computing the return expression so we avoid a new
    // if the expression throws an error. but that means we end up doing
    // stack manipulations so lets do it the easy way.

    // create am EarlyReturnException -- adds 1 to stack
    String exceptionClassName = Type.internalName(EarlyReturnException.class);
    mv.visitTypeInsn(Opcodes.NEW, exceptionClassName);
    compileContext.addStackCount(1);/*from  ww  w. ja  v  a2  s . c o m*/
    // copy the exception so we can initialise it -- adds 1 to stack
    mv.visitInsn(Opcodes.DUP);
    compileContext.addStackCount(1);
    // stack a string constant to initialise the exception with -- adds 1 to stack
    mv.visitLdcInsn("return from " + rule.getName());
    compileContext.addStackCount(1);
    // stack any required return value or null -- adds 1 to stack but may use 2 slots
    if (returnValue != null) {
        returnValue.compile(mv, compileContext);
        // we may need to convert from the value type to the return type
        if (valueType != type) {
            compileTypeConversion(valueType, type, mv, compileContext);
        }
        if (type.isPrimitive()) {
            // we need an object not a primitive
            compileBox(Type.boxType(type), mv, compileContext);
        }
    } else {
        // just push null
        mv.visitInsn(Opcodes.ACONST_NULL);
        compileContext.addStackCount(1);
    }
    // construct the exception -- pops 3
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, exceptionClassName, "<init>",
            "(Ljava/lang/String;Ljava/lang/Object;)V");
    compileContext.addStackCount(-3);

    // check current stack and increment max stack if necessary
    if (compileContext.getStackCount() != currentStack + expected) {
        throw new CompileException("ReturnExpression.compile : invalid stack height "
                + compileContext.getStackCount() + " expecting " + (currentStack + expected));
    }

    // now insert the throw instruction and decrement the stack height accordingly

    mv.visitInsn(Opcodes.ATHROW);
    compileContext.addStackCount(-1);
}

From source file:org.jboss.byteman.rule.expression.ThrowExpression.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);

    int currentStack = compileContext.getStackCount();
    int expected = 1;
    int extraParams = 0;

    // ok, we need to create the thrown exception instance and then
    // initialise it.

    // create the thrown exception instance -- adds 1 to stack
    String exceptionClassName = type.getInternalName();
    mv.visitTypeInsn(Opcodes.NEW, exceptionClassName);
    compileContext.addStackCount(1);/*from  w ww . ja va 2 s.  c o m*/
    // copy the exception so we can init it
    mv.visitInsn(Opcodes.DUP);
    compileContext.addStackCount(1);

    int argCount = arguments.size();

    // stack each of the arguments to the constructor
    for (int i = 0; i < argCount; i++) {
        Type argType = argumentTypes.get(i);
        Type paramType = paramTypes.get(i);
        int paramCount = (paramType.getNBytes() > 4 ? 2 : 1);

        // track extra storage used after type conversion
        extraParams += (paramCount);
        arguments.get(i).compile(mv, compileContext);
        compileTypeConversion(argType, paramType, mv, compileContext);
    }

    // construct the exception
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, exceptionClassName, "<init>", getDescriptor());

    // modify the stack height to account for the removed exception and params
    compileContext.addStackCount(-(extraParams + 1));

    if (compileContext.getStackCount() != currentStack + expected) {
        throw new CompileException("ThrowExpression.compile : invalid stack height "
                + compileContext.getStackCount() + " expecting " + (currentStack + expected));
    }
    // now create a ThrowException to wrap the user exception
    // create the thrown exception instance -- adds 1 to stack [UE] --> [UE, THE]
    exceptionClassName = "org/jboss/byteman/rule/exception/ThrowException";
    mv.visitTypeInsn(Opcodes.NEW, exceptionClassName);
    compileContext.addStackCount(1);
    // copy the ThrowException so we can init it [UE, THE] --> [THE, UE, THE]
    mv.visitInsn(Opcodes.DUP_X1);
    compileContext.addStackCount(1);
    // reverse the order of the top two words  [THE, UE, THE] --> [THE, THE, UE]
    mv.visitInsn(Opcodes.SWAP);
    // construct the exception [THE, THE, UE] --> [UE]
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, exceptionClassName, "<init>", "(Ljava/lang/Throwable;)V");
    // we should now have just the ThrowException on the stack
    compileContext.addStackCount(-2);
    if (compileContext.getStackCount() != currentStack + expected) {
        throw new CompileException("ThrowExpression.compile : invalid stack height "
                + compileContext.getStackCount() + " expecting " + (currentStack + expected));
    }

    // now throw the exception and decrement the stack height

    mv.visitInsn(Opcodes.ATHROW);
    compileContext.addStackCount(-1);
}

From source file:org.jooby.internal.apitool.BytecodeRouteParser.java

License:Apache License

@SuppressWarnings("unchecked")
private List<Object> kotlinSource(final ClassLoader loader, final ClassNode owner) {
    List<Object> result = kotlinLambdas(loader, owner);

    if (result.size() == 0) {
        // Try main
        List<MethodNode> methods = owner.methods;
        methods.stream().filter(method("main", String.class.getName() + "[]")).findFirst().ifPresent(main -> {
            log.debug("found main method: {}.main", owner.name);
            new Insns(main).on(joobyRun(loader), n -> {
                log.debug("found run(::Type, *args)");
                n.prev().filter(and(is(FieldInsnNode.class), opcode(GETSTATIC))).findFirst()
                        .map(FieldInsnNode.class::cast).ifPresent(f -> {
                            ClassNode mainOwner = loadClass(f.owner);
                            log.debug("found ::{}", mainOwner.name);
                            mainOwner.methods.stream().filter(kotlinRouteHandler()).findFirst().ifPresent(m -> {
                                log.debug("{}.invoke({})", mainOwner.name, ((MethodNode) m).desc);
                                new Insns((MethodNode) m)
                                        .on(is(TypeInsnNode.class).and(opcode(Opcodes.NEW)), it -> {
                                            ClassNode lambda = loadClass(it.node.desc);
                                            log.debug("source {}", lambda.name);
                                            result.addAll(kotlinLambdas(loader, lambda));
                                        }).forEach();
                            });//  ww  w .ja  v a  2s  .co m
                        });
            }).forEach();
        });
    }
    return result;
}

From source file:org.kohsuke.accmod.impl.Checker.java

License:Open Source License

/**
 * Inspects a class for the restriction violations.
 *///from ww  w .  java2  s . c  o  m
public void checkClass(File clazz) throws IOException {
    FileInputStream in = new FileInputStream(clazz);
    try {
        ClassReader cr = new ClassReader(in);
        cr.accept(new ClassVisitor(Opcodes.ASM5) {
            private String className;
            private String methodName, methodDesc;
            private int line;

            @Override
            public void visit(int version, int access, String name, String signature, String superName,
                    String[] interfaces) {
                this.className = name;

                if (superName != null)
                    getRestrictions(superName).usedAsSuperType(currentLocation, errorListener);

                if (interfaces != null) {
                    for (String intf : interfaces)
                        getRestrictions(intf).usedAsInterface(currentLocation, errorListener);
                }
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                    String[] exceptions) {
                this.methodName = name;
                this.methodDesc = desc;
                return new MethodVisitor(Opcodes.ASM5) {
                    @Override
                    public void visitLineNumber(int _line, Label start) {
                        line = _line;
                    }

                    public void visitTypeInsn(int opcode, String type) {
                        switch (opcode) {
                        case Opcodes.NEW:
                            getRestrictions(type).instantiated(currentLocation, errorListener);
                        }
                    }

                    @Override
                    public void visitMethodInsn(int opcode, String owner, String name, String desc,
                            boolean itf) {
                        getRestrictions(owner + '.' + name + desc).invoked(currentLocation, errorListener);
                    }

                    @Override
                    public void visitFieldInsn(int opcode, String owner, String name, String desc) {
                        Restrictions r = getRestrictions(owner + '.' + name);
                        switch (opcode) {
                        case Opcodes.GETSTATIC:
                        case Opcodes.GETFIELD:
                            r.read(currentLocation, errorListener);
                            break;
                        case Opcodes.PUTSTATIC:
                        case Opcodes.PUTFIELD:
                            r.written(currentLocation, errorListener);
                            break;
                        }
                        super.visitFieldInsn(opcode, owner, name, desc);
                    }
                };
            }

            /**
             * Constant that represents the current location.
             */
            private final Location currentLocation = new Location() {
                public String getClassName() {
                    return className.replace('/', '.');
                }

                public String getMethodName() {
                    return methodName;
                }

                public String getMethodDescriptor() {
                    return methodDesc;
                }

                public int getLineNumber() {
                    return line;
                }

                public String toString() {
                    return className + ':' + line;
                }

                public ClassLoader getDependencyClassLoader() {
                    return dependencies;
                }

                public boolean isInTheSameModuleAs(RestrictedElement e) {
                    // TODO
                    throw new UnsupportedOperationException();
                }
            };
        }, SKIP_FRAMES);
    } finally {
        in.close();
    }
}

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

License:Open Source License

/**
 * Reads the given {@link TypeInsnNode} instruction.
 * //from   w  w w  .ja va  2 s  . c om
 * @param typeInsnNode the instruction to read
 * @param expressionStack the expression stack to put on or pop from.
 * @param localVariables the local variables
 */
private static void readTypeInstruction(final TypeInsnNode typeInsnNode,
        final Stack<Expression> expressionStack, final LocalVariables localVariables) {
    switch (typeInsnNode.getOpcode()) {
    case Opcodes.NEW:
        final Type instanceType = Type.getObjectType(typeInsnNode.desc);
        final ObjectInstanciation objectVariable = new ObjectInstanciation(getType(instanceType));
        expressionStack.push(objectVariable);
        break;
    case Opcodes.ANEWARRAY:
        final Type parameterType = Type.getObjectType(typeInsnNode.desc);
        final NumberLiteral arrayLength = (NumberLiteral) expressionStack.pop();
        final ArrayVariable arrayVariable = new ArrayVariable(getArrayType(parameterType),
                arrayLength.getValue().intValue());
        expressionStack.push(arrayVariable);
        break;
    default:
        LOGGER.warn("TypeInsnNode with OpCode {} was ignored.", typeInsnNode.getOpcode());
    }
}