Example usage for org.objectweb.asm Opcodes GETFIELD

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

Introduction

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

Prototype

int GETFIELD

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

Click Source Link

Usage

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

License:Open Source License

/**
 * Generates the instruction to push the value of a non static field on the
 * stack.//from   ww  w . j  a  v a  2 s .c om
 *
 * @param owner the class in which the field is defined.
 * @param name the name of the field.
 * @param type the type of the field.
 */
public void getField(final Type owner, final String name, final Type type) {
    fieldInsn(Opcodes.GETFIELD, owner, name, type);
}

From source file:org.jboss.byteman.rule.expression.FieldExpression.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 = (type.getNBytes() > 4 ? 2 : 1);

    if (indirectStatic != null) {
        // this is just wrapping a static field expression so compile it
        indirectStatic.compile(mv, compileContext);
    } else if (isArrayLength) {
        owner.compile(mv, compileContext);
        mv.visitInsn(Opcodes.ARRAYLENGTH);
        // we removed the owner and replaced with expected words
        compileContext.addStackCount(expected - 1);
    } else {//from w  ww.  j  a va 2s  .  com
        if (isPublicField) {
            // we can use GETFIELD to access a public field
            String ownerType = Type.internalName(field.getDeclaringClass());
            String fieldName = field.getName();
            String fieldType = Type.internalName(field.getType(), true);
            // compile the owner expression
            owner.compile(mv, compileContext);
            mv.visitFieldInsn(Opcodes.GETFIELD, ownerType, fieldName, fieldType);
            // we removed the owner and replaced with expected words
            compileContext.addStackCount(expected - 1);
        } else {
            // since this is a private field we need to do the access using reflection
            // stack the helper, owner and the field index
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            compileContext.addStackCount(1);
            owner.compile(mv, compileContext);
            mv.visitLdcInsn(fieldIndex);
            compileContext.addStackCount(1);
            // use the HelperAdapter method getAccessibleField to get the field value
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.internalName(HelperAdapter.class),
                    "getAccessibleField", "(Ljava/lang/Object;I)Ljava/lang/Object;");
            // we popped three words and added one object as result
            compileContext.addStackCount(-2);
            // convert Object to primitive or cast to subtype if required
            compileTypeConversion(Type.OBJECT, type, mv, compileContext);
        }
    }
    // check the stack height is ok
    if (compileContext.getStackCount() != currentStack + expected) {
        throw new CompileException("FieldExpression.compile : invalid stack height "
                + compileContext.getStackCount() + " expecting " + (currentStack + expected));
    }
}

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

License:Open Source License

/**
 * Inspects a class for the restriction violations.
 *///from   w w w.  j  a  v  a 2 s  . com
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 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 ww  w.  j  a  v  a  2  s . co  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.ClosureUtil.java

License:Apache License

public static void createClosureConstructor(final ClassNode newType, final Parameter[] constrParams,
        Expression superArgs, CompilerTransformer compiler) {

    final ClassNode superClass = newType.getSuperClass();

    final Parameter[] finalConstrParams;
    final ArgumentListExpression superCallArgs = new ArgumentListExpression();
    if (superArgs != null) {
        final ArgumentListExpression args = (ArgumentListExpression) superArgs;
        if (args.getExpressions().size() > 0) {
            Parameter[] newParams = new Parameter[constrParams.length + args.getExpressions().size()];
            System.arraycopy(constrParams, 0, newParams, 0, constrParams.length);
            for (int i = 0; i != args.getExpressions().size(); ++i) {
                final Parameter parameter = new Parameter(args.getExpressions().get(i).getType(),
                        "$super$param$" + i);
                newParams[i + constrParams.length] = parameter;
                superCallArgs.addExpression(new VariableExpression(parameter));
            }/* w w w .jav  a  2s.c o  m*/
            finalConstrParams = newParams;
        } else
            finalConstrParams = constrParams;
    } else {
        if (superClass == ClassHelper.CLOSURE_TYPE) {
            if (constrParams.length > 0) {
                superCallArgs.addExpression(new VariableExpression(constrParams[0]));
                superCallArgs.addExpression(new VariableExpression(constrParams[0]));
            } else if (compiler.methodNode.isStatic() && !compiler.classNode.getName().endsWith("$TraitImpl")) {
                ClassNode cn = compiler.classNode;
                superCallArgs.addExpression(new ClassExpression(cn));
                superCallArgs.addExpression(new ClassExpression(getOutermostClass(cn)));
            } else {
                superCallArgs.addExpression(ConstantExpression.NULL);
                superCallArgs.addExpression(ConstantExpression.NULL);
            }
        }
        finalConstrParams = constrParams;
    }

    ConstructorCallExpression superCall = new ConstructorCallExpression(ClassNode.SUPER, superCallArgs);

    BytecodeSequence fieldInit = new BytecodeSequence(new BytecodeInstruction() {
        public void visit(MethodVisitor mv) {
            for (int i = 0, k = 1; i != constrParams.length; i++) {
                mv.visitVarInsn(Opcodes.ALOAD, 0);

                final ClassNode type = constrParams[i].getType();
                if (ClassHelper.isPrimitiveType(type)) {
                    if (type == ClassHelper.long_TYPE) {
                        mv.visitVarInsn(Opcodes.LLOAD, k++);
                        k++;
                    } else if (type == ClassHelper.double_TYPE) {
                        mv.visitVarInsn(Opcodes.DLOAD, k++);
                        k++;
                    } else if (type == ClassHelper.float_TYPE) {
                        mv.visitVarInsn(Opcodes.FLOAD, k++);
                    } else {
                        mv.visitVarInsn(Opcodes.ILOAD, k++);
                    }
                } else {
                    mv.visitVarInsn(Opcodes.ALOAD, k++);
                }
                mv.visitFieldInsn(Opcodes.PUTFIELD, BytecodeHelper.getClassInternalName(newType),
                        constrParams[i].getName(), BytecodeHelper.getTypeDescription(type));
            }
            mv.visitInsn(Opcodes.RETURN);
        }
    });

    BlockStatement code = new BlockStatement();
    code.addStatement(new ExpressionStatement(superCall));

    ConstructorNode cn = new ConstructorNode(Opcodes.ACC_PUBLIC, finalConstrParams, ClassNode.EMPTY_ARRAY,
            code);
    newType.addConstructor(cn);

    code.addStatement(fieldInit);

    CleaningVerifier.getCleaningVerifier().visitClass(newType);

    compiler.replaceMethodCode(newType, cn);

    if (newType.getOuterClass() != null && newType.getMethods("methodMissing").isEmpty()) {
        final ClassNode this0Type = (!compiler.methodNode.isStatic()
                || compiler.classNode.getName().endsWith("$TraitImpl")) ? newType.getOuterClass()
                        : ClassHelper.CLASS_Type;
        newType.addMethod("methodMissing", Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE,
                new Parameter[] { new Parameter(ClassHelper.STRING_TYPE, "name"),
                        new Parameter(ClassHelper.OBJECT_TYPE, "args") },
                ClassNode.EMPTY_ARRAY, new BytecodeSequence(new BytecodeInstruction() {
                    public void visit(MethodVisitor mv) {
                        mv.visitVarInsn(Opcodes.ALOAD, 0);
                        mv.visitFieldInsn(Opcodes.GETFIELD, BytecodeHelper.getClassInternalName(newType),
                                "this$0", BytecodeHelper.getTypeDescription(this0Type));
                        mv.visitVarInsn(Opcodes.ALOAD, 1);
                        mv.visitVarInsn(Opcodes.ALOAD, 2);
                        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/codehaus/groovy/runtime/InvokerHelper",
                                "invokeMethod",
                                "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;");
                        mv.visitInsn(Opcodes.ARETURN);
                    }
                }));
    }
}

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

License:Apache License

public static void instantiateClass(ClassNode type, CompilerTransformer compiler, Parameter[] constrParams,
        Expression superArgs, MethodVisitor mv) {
    TraitASTTransformFinal.improveAbstractMethods(type);
    type.getModule().addClass(type);/*from   w ww. j  a  v a  2  s.com*/

    final String classInternalName = BytecodeHelper.getClassInternalName(type);
    mv.visitTypeInsn(Opcodes.NEW, classInternalName);
    mv.visitInsn(Opcodes.DUP);

    final ConstructorNode constructorNode = type.getDeclaredConstructors().get(0);

    for (int i = 0; i != constrParams.length; i++) {
        String name = constrParams[i].getName();

        if ("this$0".equals(name)) {
            mv.visitVarInsn(Opcodes.ALOAD, 0);
        } else {
            final Register var = compiler.compileStack.getRegister(name, false);
            if (var != null) {
                FieldNode field = type.getDeclaredField(name);
                BytecodeExpr.load(field.getType(), var.getIndex(), mv);
                if (!constrParams[i].getType().equals(var.getType())
                        && !ClassHelper.isPrimitiveType(field.getType())) {
                    BytecodeExpr.checkCast(constrParams[i].getType(), mv);
                }
            } else {
                FieldNode field = compiler.methodNode.getDeclaringClass().getDeclaredField(name);
                mv.visitVarInsn(Opcodes.ALOAD, 0);
                if (field == null) // @Field
                    name = compiler.methodNode.getName() + "$" + name;
                mv.visitFieldInsn(Opcodes.GETFIELD,
                        BytecodeHelper.getClassInternalName(compiler.methodNode.getDeclaringClass()), name,
                        BytecodeHelper.getTypeDescription(constrParams[i].getType()));
            }
        }
    }

    if (superArgs != null) {
        final List<Expression> list = ((ArgumentListExpression) superArgs).getExpressions();
        for (int i = 0; i != list.size(); ++i)
            ((BytecodeExpr) list.get(i)).visit(mv);
    }

    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, classInternalName, "<init>",
            BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, constructorNode.getParameters()));
}

From source file:org.mutabilitydetector.checkers.CollectionTypeWrappedInUnmodifiableIdiomCheckerTest.java

License:Apache License

@Test(expected = IllegalArgumentException.class)
public void requiresTheFieldInstructionNodeToBeAPutFieldInstruction() throws Exception {
    FieldInsnNode insnNode = new FieldInsnNode(Opcodes.GETFIELD, "some/type/Name", "fieldName",
            "the/field/Type");
    new CollectionTypeWrappedInUnmodifiableIdiomChecker(insnNode, null);
}

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

License:Apache License

private boolean isGetfieldForVariable(final AbstractInsnNode insn) {
    boolean result = false;
    if (Opcodes.GETFIELD == insn.getOpcode()) {
        final FieldInsnNode getfield = (FieldInsnNode) insn;
        result = variableName.equals(getfield.name);
    }/*from w w w  . j  a  v  a2s . c  o m*/
    return result;
}

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

License:Open Source License

/**
 * Creates the code that references a Java field within an expression. 
 * @param javaField the java field //from www .j a  v  a 2 s.  c  o  m
 * @param context   
 * @return JavaTypeName the type of the javaField argument.
 * @throws JavaGenerationException
 */
private static JavaTypeName encodeJavaFieldExpr(JavaField javaField, GenerationContext context)
        throws JavaGenerationException {

    if (javaField instanceof JavaField.This) {
        //the special 'this' field.
        return encodeThis(context);
    }

    MethodVisitor mv = context.getMethodVisitor();

    if (javaField instanceof JavaField.Instance) {

        JavaField.Instance javaInstanceField = (JavaField.Instance) javaField;
        JavaExpression instance = javaInstanceField.getInstance();
        JavaTypeName instanceType;
        if (instance == null) {
            //use 'this' as the instance expression, so if the field is 'foo', then it is 'this.foo'.
            instanceType = encodeThis(context);

        } else {
            instanceType = encodeExpr(instance, context);
        }

        JavaTypeName fieldType = javaField.getFieldType();

        mv.visitFieldInsn(Opcodes.GETFIELD, instanceType.getJVMInternalName(), javaField.getFieldName(),
                fieldType.getJVMDescriptor());

        return fieldType;
    }

    if (javaField instanceof JavaField.Static) {

        JavaField.Static javaStaticField = (JavaField.Static) javaField;
        JavaTypeName fieldType = javaField.getFieldType();

        mv.visitFieldInsn(Opcodes.GETSTATIC, javaStaticField.getInvocationClass().getJVMInternalName(),
                javaField.getFieldName(), fieldType.getJVMDescriptor());

        return fieldType;
    }

    throw new IllegalStateException();
}

From source file:org.pitest.mutationtest.engine.gregor.mutators.experimental.extended.UOIMutator1.java

License:Apache License

@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
    // GETFIELD I,F,L,D + B,S
    if ((opcode == Opcodes.GETFIELD)) {
        if (desc.equals("I")) {
            if (this.shouldMutate("Incremented (a++) integer field " + name)) {
                // Assuming we have the reference to [this] on the stack
                mv.visitInsn(Opcodes.DUP); // dup [this]
                mv.visitFieldInsn(opcode, owner, name, desc); // stack = [this] [this.field]
                mv.visitInsn(Opcodes.DUP_X1); // stack = [this.field] [this] [this.field]
                mv.visitInsn(Opcodes.ICONST_1);
                mv.visitInsn(Opcodes.IADD); // stack = [this.field] [this] [this.field +1]
                mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc);
                return;
            }//from  w  ww .  ja  va2 s  .  c om
        }
        if (desc.equals("F")) {
            if (this.shouldMutate("Incremented (a++) float field " + name)) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP_X1);
                mv.visitInsn(Opcodes.FCONST_1);
                mv.visitInsn(Opcodes.FADD);
                mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc);
                return;
            }
        }
        if (desc.equals("J")) {
            if (this.shouldMutate("Incremented (a++) long field " + name)) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP2_X1);
                mv.visitInsn(Opcodes.LCONST_1);
                mv.visitInsn(Opcodes.LADD);
                mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc);
                return;
            }
        }
        if (desc.equals("D")) {
            if (this.shouldMutate("Incremented (a++) double field " + name)) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP2_X1);
                mv.visitInsn(Opcodes.DCONST_1);
                mv.visitInsn(Opcodes.DADD);
                mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc);
                return;
            }
        }
        if (desc.equals("B")) {
            if (this.shouldMutate("Incremented (a++) byte field " + name)) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP_X1);
                mv.visitInsn(Opcodes.ICONST_1);
                mv.visitInsn(Opcodes.IADD);
                mv.visitInsn(Opcodes.I2B);
                mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc);
                return;
            }
        }
        if (desc.equals("S")) {
            if (this.shouldMutate("Incremented (a++) short field " + name)) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP_X1);
                mv.visitInsn(Opcodes.ICONST_1);
                mv.visitInsn(Opcodes.IADD);
                mv.visitInsn(Opcodes.I2S);
                mv.visitFieldInsn(Opcodes.PUTFIELD, owner, name, desc);
                return;
            }
        }
    }

    // GETSTATIC I,F,L,D + B,S
    if (opcode == Opcodes.GETSTATIC) {
        if (desc.equals("I")) {
            if (this.shouldMutate("Incremented (a++) static integer field " + name)) {
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP);
                mv.visitInsn(Opcodes.ICONST_1);
                mv.visitInsn(Opcodes.IADD);
                mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc);
                return;
            }
        }
        if (desc.equals("F")) {
            if (this.shouldMutate("Incremented (a++) static float field " + name)) {
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP);
                mv.visitInsn(Opcodes.FCONST_1);
                mv.visitInsn(Opcodes.FADD);
                mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc);
                return;
            }
        }
        if (desc.equals("J")) {
            if (this.shouldMutate("Incremented (a++) static long field " + name)) {
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP2);
                mv.visitInsn(Opcodes.LCONST_1);
                mv.visitInsn(Opcodes.LADD);
                mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc);
                return;
            }
        }
        if (desc.equals("D")) {
            if (this.shouldMutate("Incremented (a++) static double field " + name)) {
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP2);
                mv.visitInsn(Opcodes.DCONST_1);
                mv.visitInsn(Opcodes.DADD);
                mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc);
                return;
            }
        }
        if (desc.equals("B")) {
            if (this.shouldMutate("Incremented (a++) static byte field " + name)) {
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP);
                mv.visitInsn(Opcodes.ICONST_1);
                mv.visitInsn(Opcodes.IADD);
                mv.visitInsn(Opcodes.I2B);
                mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc);
                return;
            }
        }
        if (desc.equals("S")) {
            if (this.shouldMutate("Incremented (a++) static short field " + name)) {
                mv.visitFieldInsn(opcode, owner, name, desc);
                mv.visitInsn(Opcodes.DUP);
                mv.visitInsn(Opcodes.ICONST_1);
                mv.visitInsn(Opcodes.IADD);
                mv.visitInsn(Opcodes.I2S);
                mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, desc);
                return;
            }
        }
    }
    mv.visitFieldInsn(opcode, owner, name, desc);
}