Example usage for org.objectweb.asm Opcodes INVOKESPECIAL

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

Introduction

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

Prototype

int INVOKESPECIAL

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

Click Source Link

Usage

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

License:Open Source License

/**
 * Create the Java code for a given class instance creation expression. The new object reference will be pushed onto
 * the operand stack. //  w  w  w.  j a va2  s  .co m
 * 
 * @param cice the class instance creation expression
 * @param context 
 * @return JavaTypeName    
 * @throws JavaGenerationException
 */
private static JavaTypeName encodeClassInstanceCreationExpr(
        final JavaExpression.ClassInstanceCreationExpression cice, final GenerationContext context)
        throws JavaGenerationException {

    final MethodVisitor mv = context.getMethodVisitor();
    final JavaTypeName classType = cice.getClassName();
    if (classType instanceof JavaTypeName.Reference.Array) {

        final JavaTypeName.Reference.Array arrayType = (JavaTypeName.Reference.Array) classType;
        final int nSizedDims = cice.getNArgs();
        if (nSizedDims == 1) {

            //for example, new String[10][][] will hit this case since it has 1 sized dimension (even though a multi-dimensional array is 
            //being created

            //push the size of the dimension
            encodeExpr(cice.getArg(0), context);

            final JavaTypeName arrayElementType = arrayType.getIncrementalElementType();
            switch (arrayElementType.getTag()) {

            case JavaTypeName.VOID_TAG:
                throw new JavaGenerationException("Cannot have an array of with void element types.");

            case JavaTypeName.BOOLEAN_TAG:
            case JavaTypeName.BYTE_TAG:
            case JavaTypeName.SHORT_TAG:
            case JavaTypeName.CHAR_TAG:
            case JavaTypeName.INT_TAG:
            case JavaTypeName.LONG_TAG:
            case JavaTypeName.DOUBLE_TAG:
            case JavaTypeName.FLOAT_TAG: {
                //push the instruction to create a 1-dimensonal array of primitive values
                mv.visitIntInsn(Opcodes.NEWARRAY, getNewArrayArgCode(arrayElementType));
                break;
            }

            case JavaTypeName.ARRAY_TAG:
            case JavaTypeName.OBJECT_TAG: {
                //push the instruction to create a 1-dimensonal array of reference values
                mv.visitTypeInsn(Opcodes.ANEWARRAY, arrayElementType.getJVMInternalName());
                break;
            }

            default: {
                throw new IllegalArgumentException();
            }
            }

            return arrayType;

        } else {
            //the case of multi-dimensional arrays where more than 1 sizing dimension is supplied.

            // push args onto the stack
            for (int i = 0; i < nSizedDims; i++) {
                encodeExpr(cice.getArg(i), context);
            }

            mv.visitMultiANewArrayInsn(arrayType.getJVMInternalName(), nSizedDims);

            return arrayType;
        }

    } else if (classType instanceof JavaTypeName.Reference.Object) {

        String internalClassName = classType.getJVMInternalName();

        // create uninitialized object, duplicate the ref.
        mv.visitTypeInsn(Opcodes.NEW, internalClassName);
        mv.visitInsn(Opcodes.DUP);

        // push args onto the stack
        for (int i = 0, nArgs = cice.getNArgs(); i < nArgs; i++) {
            encodeExpr(cice.getArg(i), context);
        }

        //descriptor for the constructor
        StringBuilder descriptor = new StringBuilder("(");
        for (int i = 0, nArgs = cice.getNArgs(); i < nArgs; ++i) {
            descriptor.append(cice.getParamType(i).getJVMDescriptor());
        }
        descriptor.append(")V");

        // initialize - consumes the args and the duplicate reference.
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, internalClassName, "<init>", descriptor.toString());

        return classType;

    } else {
        throw new JavaGenerationException("cannot create a new instance of a primitive type.");
    }
}

From source file:org.parboiled.compiler.notNullVerification.MyMethodAdapter.java

License:Apache License

private void generateThrow(String exceptionClass, String descr, Label end) {
    String exceptionParamClass = "(Ljava/lang/String;)V";
    mv.visitTypeInsn(Opcodes.NEW, exceptionClass);
    mv.visitInsn(Opcodes.DUP);/*ww w .  j  a va 2  s .  c  o m*/
    mv.visitLdcInsn(descr);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, exceptionClass, NotNullVerifyingInstrumenter.CONSTRUCTOR_NAME,
            exceptionParamClass);
    mv.visitInsn(Opcodes.ATHROW);
    mv.visitLabel(end);

    instrumenter.myIsModification = true;
}

From source file:org.pareto4j.inspector.collections.InspectorMethodVisitor.java

License:Apache License

@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc) {
    if (opcode == Opcodes.INVOKESPECIAL && name.equals("<init>") /*&& seenNew*/) {
        for (DelegateTypes delegateTypes : Profile.modify) {
            if (owner.equals(delegateTypes.jdk)) {
                super.visitMethodInsn(Opcodes.INVOKESPECIAL, delegateTypes.delegate, "<init>", desc);
                seenNew = false;/*from ww w .  jav a2 s  .  c om*/
                return;
            }
        }
    }
    super.visitMethodInsn(opcode, owner, name, desc);
}

From source file:org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator.java

License:Apache License

private static ZeroOperandMutation areturnMutation() {
    return new ZeroOperandMutation() {

        public void apply(final int opCode, final MethodVisitor mv) {

            // Strategy translated from jumble BCEL code
            // if result is non-null make it null, otherwise hard case
            // for moment throw runtime exception
            final Label l1 = new Label();
            mv.visitJumpInsn(Opcodes.IFNONNULL, l1);
            mv.visitTypeInsn(Opcodes.NEW, "java/lang/RuntimeException");
            mv.visitInsn(Opcodes.DUP);/*from   w  w w .  j av a 2s.  c o m*/
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "()V", false);
            mv.visitInsn(Opcodes.ATHROW);
            mv.visitLabel(l1);
            mv.visitInsn(Opcodes.ACONST_NULL);
            mv.visitInsn(Opcodes.ARETURN);
        }

        public String decribe(final int opCode, final MethodInfo methodInfo) {
            return "mutated return of Object value for " + methodInfo.getDescription()
                    + " to ( if (x != null) null else throw new RuntimeException )";
        }

    };
}

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

License:Open Source License

@Test
public void test_invoke_instance_method() throws Exception {
    int[] opcodes = new int[] { Opcodes.INVOKESPECIAL, Opcodes.INVOKEVIRTUAL, Opcodes.INVOKEINTERFACE };
    for (int opcode : opcodes) {
        SymbolicValue thisSv = new SymbolicValue();
        ProgramState stateWithThis = ProgramState.EMPTY_STATE.stackValue(thisSv);
        ProgramState programState = execute(invokeMethod(opcode, "methodWithoutArgument", "()V"),
                stateWithThis);/*from  w  w  w. jav  a2  s  .c om*/
        assertEmptyStack(programState);
        assertThat(programState.getConstraints(thisSv).get(ObjectConstraint.class))
                .isEqualTo(ObjectConstraint.NOT_NULL);

        programState = execute(invokeMethod(opcode, "finalVoid", "()V"), stateWithThis);
        assertEmptyStack(programState);
        assertThat(programState.getConstraints(thisSv).get(ObjectConstraint.class))
                .isEqualTo(ObjectConstraint.NOT_NULL);

        programState = execute(invokeMethod(opcode, "booleanMethod", "()Z"), stateWithThis);
        assertStack(programState, new Constraint[] { null });
        assertThat(isDoubleOrLong(programState, programState.peekValue())).isFalse();

        SymbolicValue arg = new SymbolicValue();
        programState = execute(invokeMethod(opcode, "intMethodWithIntArgument", "(I)I"),
                stateWithThis.stackValue(arg));
        assertStack(programState, new Constraint[] { null });
        assertThat(programState.peekValue()).isNotEqualTo(arg);

        programState = execute(invokeMethod(opcode, "methodWithIntIntArgument", "(II)V"),
                stateWithThis.stackValue(arg).stackValue(arg));
        assertEmptyStack(programState);
        assertThatThrownBy(
                () -> execute(invokeMethod(opcode, "methodWithIntIntArgument", "(II)V"), stateWithThis))
                        .isInstanceOf(IllegalStateException.class);

        programState = execute(invokeMethod(opcode, "returningLong", "()J"), stateWithThis);
        assertThat(isDoubleOrLong(programState, programState.peekValue())).isTrue();
        programState = execute(invokeMethod(opcode, "returningDouble", "()D"), stateWithThis);
        assertThat(isDoubleOrLong(programState, programState.peekValue())).isTrue();
    }
}

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

License:Open Source License

@Test
public void test_nullness_check() throws Exception {
    SymbolicValue thisSv = new SymbolicValue();
    ProgramState startingState = ProgramState.EMPTY_STATE.stackValue(thisSv);
    ProgramState programState = execute(invokeMethod(Opcodes.INVOKESPECIAL, "methodWithoutArgument", "()V"),
            startingState);//from  ww  w .j  ava 2  s.c  o m
    assertThat(hasConstraint(thisSv, programState, ObjectConstraint.NOT_NULL)).isTrue();

    programState = execute(invokeStatic("staticBooleanMethod", "()Z"), startingState);
    assertStack(programState,
            new Constraint[][] { { ObjectConstraint.NOT_NULL, BooleanConstraint.FALSE }, { null } });

    programState = execute(invokeMethod(Opcodes.INVOKESPECIAL, "methodWithIntArgument", "(I)V"),
            startingState.stackValue(new SymbolicValue()));
    assertThat(hasConstraint(thisSv, programState, ObjectConstraint.NOT_NULL)).isTrue();
}

From source file:org.spongepowered.asm.mixin.injection.callback.CallbackInjector.java

License:MIT License

/**
 * Generates a method which throws an error
 * //  ww  w  . ja  v a 2 s .  com
 * @param callback callback handle
 * @param errorClass error class to throw
 * @param message message for the error
 * @return generated method
 */
private MethodNode generateErrorMethod(Callback callback, String errorClass, String message) {
    MethodNode method = this.info.addMethod(this.methodNode.access, this.methodNode.name + "$missing",
            callback.getDescriptor());
    method.maxLocals = ASMHelper.getFirstNonArgLocalIndex(Type.getArgumentTypes(callback.getDescriptor()),
            !this.isStatic);
    method.maxStack = 3;
    InsnList insns = method.instructions;
    insns.add(new TypeInsnNode(Opcodes.NEW, errorClass));
    insns.add(new InsnNode(Opcodes.DUP));
    insns.add(new LdcInsnNode(message));
    insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, "<init>", "(Ljava/lang/String;)V", false));
    insns.add(new InsnNode(Opcodes.ATHROW));
    return method;
}

From source file:org.spongepowered.asm.mixin.injection.callback.CallbackInjector.java

License:MIT License

/**
 * @param callback callback handle//  www  .j  a  va 2 s .c  o  m
 */
protected void invokeCallbackInfoCtor(final Callback callback) {
    callback.add(new LdcInsnNode(callback.target.method.name), true, false);
    callback.add(new InsnNode(this.cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0), true, false);

    if (callback.isAtReturn) {
        callback.add(
                new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ILOAD), callback.marshallVar));
        callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, callback.target.callbackInfoClass, Injector.CTOR,
                CallbackInfo.getConstructorDescriptor(callback.target.returnType), false));
    } else {
        callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, callback.target.callbackInfoClass, Injector.CTOR,
                CallbackInfo.getConstructorDescriptor(), false));
    }
}

From source file:org.spongepowered.asm.mixin.injection.code.Injector.java

License:MIT License

protected void invokeMethod(InsnList insns, MethodNode methodNode) {
    boolean isPrivate = (methodNode.access & Opcodes.ACC_PRIVATE) != 0;
    int invokeOpcode = this.isStatic ? Opcodes.INVOKESTATIC
            : isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL;
    insns.add(new MethodInsnNode(invokeOpcode, this.classNode.name, methodNode.name, methodNode.desc, false));
}

From source file:org.spongepowered.asm.mixin.transformer.MixinTargetContext.java

License:MIT License

/**
 * Handles "re-parenting" the method supplied, changes all references to the
 * mixin class to refer to the target class (for field accesses and method
 * invokations) and also handles fixing up the targets of INVOKESPECIAL
 * opcodes for mixins with detached targets.
 * //www .j av a 2 s .  c om
 * @param method Method to transform
 */
public void transformMethod(MethodNode method) {
    // Any method tagged with @SoftOverride must have an implementation visible from 
    if (ASMHelper.getInvisibleAnnotation(method, SoftOverride.class) != null) {
        Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false,
                Traversal.SUPER);
        if (superMethod == null || !superMethod.isInjected()) {
            throw new InvalidMixinException(this,
                    "Mixin method " + method.name + method.desc + " is tagged with @SoftOverride but no "
                            + "valid method was found in superclasses of " + this.targetClass.name);
        }
    }

    this.transformDescriptor(method);

    Iterator<AbstractInsnNode> iter = method.instructions.iterator();
    while (iter.hasNext()) {
        AbstractInsnNode insn = iter.next();

        if (insn instanceof MethodInsnNode) {
            MethodInsnNode methodInsn = (MethodInsnNode) insn;
            this.transformDescriptor(methodInsn);
            if (methodInsn.owner.equals(this.getClassRef())) {
                methodInsn.owner = this.targetClass.name;
            } else if ((this.detachedSuper || this.inheritsFromMixin)) {
                if (methodInsn.getOpcode() == Opcodes.INVOKESPECIAL) {
                    this.updateStaticBinding(method, methodInsn);
                } else if (methodInsn.getOpcode() == Opcodes.INVOKEVIRTUAL
                        && ClassInfo.forName(methodInsn.owner).isMixin()) {
                    this.updateDynamicBinding(method, methodInsn);
                }
            }
        } else if (insn instanceof FieldInsnNode) {
            FieldInsnNode fieldInsn = (FieldInsnNode) insn;
            if (MixinTargetContext.IMAGINARY_SUPER.equals(fieldInsn.name)) {
                this.processImaginarySuper(method, fieldInsn);
                iter.remove();
            }
            this.transformDescriptor(fieldInsn);
            if (fieldInsn.owner.equals(this.getClassRef())) {
                fieldInsn.owner = this.targetClass.name;
            }
        } else if (insn instanceof TypeInsnNode) {
            TypeInsnNode typeInsn = (TypeInsnNode) insn;
            if (typeInsn.desc.equals(this.getClassRef())) {
                typeInsn.desc = this.targetClass.name;
            }
            this.transformDescriptor(typeInsn);
        }
    }
}