Example usage for org.objectweb.asm Opcodes PUTFIELD

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

Introduction

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

Prototype

int PUTFIELD

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

Click Source Link

Usage

From source file:org.gradle.api.internal.model.DefaultObjectFactory.java

License:Apache License

private ClassGeneratingLoader loaderFor(Class<?> publicClass) {
    ////from ww w . ja  va2  s  . c  om
    // Generate implementation class
    //

    FormattingValidationProblemCollector problemCollector = new FormattingValidationProblemCollector(
            "Named implementation class", ModelType.of(publicClass));
    visitFields(publicClass, problemCollector);
    if (problemCollector.hasProblems()) {
        throw new GradleException(problemCollector.format());
    }

    AsmClassGenerator generator = new AsmClassGenerator(publicClass, "$Impl");
    Type implementationType = generator.getGeneratedType();
    ClassWriter visitor = generator.getVisitor();
    Type publicType = Type.getType(publicClass);

    Type superClass;
    String[] interfaces;
    if (publicClass.isInterface()) {
        superClass = OBJECT;
        interfaces = new String[] { publicType.getInternalName() };
    } else {
        superClass = publicType;
        interfaces = EMPTY_STRINGS;
    }

    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, implementationType.getInternalName(), null,
            superClass.getInternalName(), interfaces);

    //
    // Add name field
    //

    visitor.visitField(ACC_PRIVATE, NAME_FIELD, STRING.getDescriptor(), null, null);

    //
    // Add constructor
    //

    MethodVisitor methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING,
            null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID, false);
    // Set this.name = param1
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `getName()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "getName", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `toString()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "toString", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    generator.define();

    //
    // Generate factory class
    //

    generator = new AsmClassGenerator(publicClass, "$Factory");
    visitor = generator.getVisitor();
    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, generator.getGeneratedType().getInternalName(), null,
            Type.getType(ClassGeneratingLoader.class).getInternalName(), EMPTY_STRINGS);

    //
    // Add constructor
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
            Type.getType(ClassGeneratingLoader.class).getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID, false);
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add factory method
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "load", Type.getMethodDescriptor(OBJECT, STRING), null,
            EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call return new <implClass>(param1)
    methodVisitor.visitTypeInsn(Opcodes.NEW, implementationType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, implementationType.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID_FROM_STRING, false);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    Class<Object> factoryClass = generator.define();
    try {
        return (ClassGeneratingLoader) (factoryClass.newInstance());
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.gradle.api.internal.model.NamedObjectInstantiator.java

License:Apache License

private ClassGeneratingLoader loaderFor(Class<?> publicClass) {
    ///*  w  ww .  j a v  a 2  s  .  c om*/
    // Generate implementation class
    //

    FormattingValidationProblemCollector problemCollector = new FormattingValidationProblemCollector(
            "Named implementation class", ModelType.of(publicClass));
    visitFields(publicClass, problemCollector);
    if (problemCollector.hasProblems()) {
        throw new GradleException(problemCollector.format());
    }

    AsmClassGenerator generator = new AsmClassGenerator(publicClass, "$Impl");
    Type implementationType = generator.getGeneratedType();
    ClassWriter visitor = generator.getVisitor();
    Type publicType = Type.getType(publicClass);

    Type superClass;
    String[] interfaces;
    if (publicClass.isInterface()) {
        superClass = OBJECT;
        interfaces = new String[] { publicType.getInternalName(), MANAGED.getInternalName() };
    } else {
        superClass = publicType;
        interfaces = INTERFACES_FOR_ABSTRACT_CLASS;
    }

    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, implementationType.getInternalName(), null,
            superClass.getInternalName(), interfaces);

    //
    // Add name field
    //

    visitor.visitField(ACC_PRIVATE, NAME_FIELD, STRING.getDescriptor(), null, null);

    //
    // Add constructor
    //

    MethodVisitor methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING,
            null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID, false);
    // Set this.name = param1
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `getName()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "getName", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `toString()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "toString", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    generator.define();

    //
    // Generate factory class
    //

    generator = new AsmClassGenerator(publicClass, "$Factory");
    visitor = generator.getVisitor();
    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, generator.getGeneratedType().getInternalName(), null,
            CLASS_GENERATING_LOADER.getInternalName(), EMPTY_STRINGS);

    //
    // Add constructor
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, CLASS_GENERATING_LOADER.getInternalName(),
            CONSTRUCTOR_NAME, RETURN_VOID, false);
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add factory method
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "load", RETURN_OBJECT_FROM_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call return new <implClass>(param1)
    methodVisitor.visitTypeInsn(Opcodes.NEW, implementationType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, implementationType.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID_FROM_STRING, false);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    Class<Object> factoryClass = generator.define();
    try {
        return (ClassGeneratingLoader) factoryClass.getConstructor().newInstance();
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.gradle.initialization.ExceptionDecoratingClassGenerator.java

License:Apache License

private <T> Class<? extends T> doGenerate(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = StringUtils.substringBeforeLast(type.getName(), ".") + ".LocationAware"
            + type.getSimpleName();/*w  w  w .  ja va2s .c  o m*/
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);

    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(),
            new String[] { Type.getType(LocationAwareException.class).getInternalName() });

    Type helperType = Type.getType(ExceptionHelper.class);
    Type throwableType = Type.getType(Throwable.class);
    Type scriptSourceType = Type.getType(ScriptSource.class);
    Type integerType = Type.getType(Integer.class);

    // GENERATE private ExceptionHelper helper;
    visitor.visitField(Opcodes.ACC_PRIVATE, "helper", helperType.getDescriptor(), null, null);

    // GENERATE <init>(<type> target, ScriptSource source, Integer lineNumber)

    String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE,
            new Type[] { superclassType, scriptSourceType, integerType });
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();

    boolean noArgsConstructor;
    try {
        type.getConstructor(type);
        noArgsConstructor = false;
    } catch (NoSuchMethodException e) {
        try {
            type.getConstructor();
            noArgsConstructor = true;
        } catch (NoSuchMethodException e1) {
            throw new IllegalArgumentException(String.format(
                    "Cannot create subtype for exception '%s'. It needs a zero-args or copy constructor.",
                    type.getName()));
        }
    }

    if (noArgsConstructor) {
        // GENERATE super()
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]));
        // END super()
    } else {
        // GENERATE super(target)
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { superclassType }));
        // END super(target)
    }

    // GENERATE helper = new ExceptionHelper(this, target, source, lineNumber)
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);

    methodVisitor.visitTypeInsn(Opcodes.NEW, helperType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, helperType.getInternalName(), "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE,
                    new Type[] { throwableType, throwableType, scriptSourceType, integerType }));

    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), "helper",
            helperType.getDescriptor());

    // END helper = new ExceptionHelper(target)

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // END <init>(<type> target, ScriptSource source, Integer lineNumber)

    for (Method method : ExceptionHelper.class.getDeclaredMethods()) {
        // GENERATE public <type> <method>() { return helper.<method>(); }
        methodDescriptor = Type.getMethodDescriptor(Type.getType(method.getReturnType()), new Type[0]);
        methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), methodDescriptor, null,
                new String[0]);
        methodVisitor.visitCode();

        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), "helper",
                helperType.getDescriptor());
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, helperType.getInternalName(), method.getName(),
                methodDescriptor);

        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
        // END public <type> <method>() { return helper.<method>(); }
    }

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    return (Class<T>) ReflectionUtil.invoke(type.getClassLoader(), "defineClass",
            new Object[] { typeName, bytecode, 0, bytecode.length });
}

From source file:org.hua.ast.visitors.BytecodeGeneratorASTVisitor.java

@Override
public void visit(AccessorExpression node) throws ASTVisitorException {
    node.getExpression().accept(this);
    //function access
    if (node.getExpressions() != null) {

        node.getExpressions().accept(this);

        //if expressionS length is 0, no args privided
        Type returnType;//w w  w .j a  va2s.c  o  m
        Type exprClass = ASTUtils.getSafeType(node.getExpression());
        SymTable<SymTableEntry> sTable = ASTUtils.getSafeEnv(node);
        SymTableEntry lookup = sTable.lookup(node.getIdentifier());
        System.out.println(
                "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$4 " + node.getIdentifier());
        if (lookup != null) {
            mn.instructions.add(
                    new MethodInsnNode(Opcodes.INVOKEVIRTUAL, exprClass.getInternalName(), node.getIdentifier(),
                            Type.getMethodDescriptor(lookup.getType(), lookup.getParametersTypes()), false));
        } else {
            Map<Type, SymTable<SymTableEntry>> classes = Registry.getInstance().getClasses();
            Iterator<Map.Entry<Type, SymTable<SymTableEntry>>> entries = classes.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<Type, SymTable<SymTableEntry>> entry = entries.next();
                if (entry.getValue().lookup(node.getIdentifier()) != null) {
                    SymTableEntry lookup1 = entry.getValue().lookup(node.getIdentifier());
                    System.out.println("entry key: " + entry.getKey().getDescriptor());
                    mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL,
                            entry.getKey().getInternalName(), node.getIdentifier(),
                            Type.getMethodDescriptor(lookup1.getType(), lookup1.getParametersTypes()), false));
                    break;
                }
            }
        }
    }
    //field access
    else {
        System.out.println("+++++++++++++++++++++++++> HEY " + node.getIdentifier());
        if (node.getExpression().getClass() != IdentifierExpression.class && previousIsIdentifier) {
            System.out.println("+++++++++++++++++++++++++++++++++++++++++++---> " + node.getIdentifier());
            mn.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, cn.name, node.getIdentifier(),
                    ASTUtils.getSafeType(node).getDescriptor()));
        } else {
            mn.instructions.add(new FieldInsnNode(Opcodes.PUTFIELD, cn.name, node.getIdentifier(),
                    ASTUtils.getSafeType(node).getDescriptor()));
        }

    }
}

From source file:org.jacoco.core.internal.analysis.filter.KotlinCoroutineFilterTest.java

License:Open Source License

/**
 * <pre>/*  w w  w. j ava 2 s.c  o m*/
 *     suspend fun example() {
 *         suspendingFunction()
 *         nop()
 *     }
 * </pre>
 */
@Test
public void should_filter_suspending_functions() {
    final MethodNode m = new MethodNode(InstrSupport.ASM_API_VERSION, Opcodes.ACC_STATIC, "example",
            "(Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", null, null);
    context.classAnnotations.add(KotlinGeneratedFilter.KOTLIN_METADATA_DESC);

    final int continuationArgumentIndex = 0;
    final int continuationIndex = 2;

    m.visitVarInsn(Opcodes.ALOAD, continuationArgumentIndex);
    final Range range1 = new Range();
    range1.fromInclusive = m.instructions.getLast();
    m.visitTypeInsn(Opcodes.INSTANCEOF, "ExampleKt$example$1");
    final Label createStateInstance = new Label();
    m.visitJumpInsn(Opcodes.IFEQ, createStateInstance);

    m.visitVarInsn(Opcodes.ALOAD, continuationArgumentIndex);
    m.visitTypeInsn(Opcodes.CHECKCAST, "ExampleKt$example$1");
    m.visitVarInsn(Opcodes.ASTORE, continuationIndex);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "label", "I");

    m.visitLdcInsn(Integer.valueOf(Integer.MIN_VALUE));
    m.visitInsn(Opcodes.IAND);
    m.visitJumpInsn(Opcodes.IFEQ, createStateInstance);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitInsn(Opcodes.DUP);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "label", "I");

    m.visitLdcInsn(Integer.valueOf(Integer.MIN_VALUE));
    m.visitInsn(Opcodes.ISUB);
    m.visitFieldInsn(Opcodes.PUTFIELD, "ExampleKt$example$1", "label", "I");

    final Label afterCoroutineStateCreated = new Label();
    m.visitJumpInsn(Opcodes.GOTO, afterCoroutineStateCreated);

    m.visitLabel(createStateInstance);

    m.visitTypeInsn(Opcodes.NEW, "ExampleKt$example$1");
    m.visitInsn(Opcodes.DUP);
    m.visitVarInsn(Opcodes.ALOAD, continuationArgumentIndex);
    m.visitMethodInsn(Opcodes.INVOKESPECIAL, "ExampleKt$example$1", "<init>",
            "(Lkotlin/coroutines/Continuation;)V", false);

    m.visitVarInsn(Opcodes.ASTORE, continuationIndex);

    m.visitLabel(afterCoroutineStateCreated);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "result", "Ljava/lang/Object;");
    m.visitVarInsn(Opcodes.ASTORE, 1);

    m.visitMethodInsn(Opcodes.INVOKESTATIC, "kotlin/coroutines/intrinsics/IntrinsicsKt",
            "getCOROUTINE_SUSPENDED", "()Ljava/lang/Object;", false);

    // line of "fun"
    m.visitVarInsn(Opcodes.ASTORE, 3);

    m.visitVarInsn(Opcodes.ALOAD, continuationIndex);
    m.visitFieldInsn(Opcodes.GETFIELD, "ExampleKt$example$1", "label", "I");
    final Label dflt = new Label();
    final Label state0 = new Label();
    final Label state1 = new Label();
    m.visitTableSwitchInsn(0, 1, dflt, state0, state1);

    m.visitLabel(state0);

    {
        m.visitVarInsn(Opcodes.ALOAD, 1);
        m.visitInsn(Opcodes.DUP);
        m.visitTypeInsn(Opcodes.INSTANCEOF, "kotlin/Result$Failure");
        Label label = new Label();
        m.visitJumpInsn(Opcodes.IFEQ, label);
        m.visitTypeInsn(Opcodes.CHECKCAST, "kotlin/Result$Failure");
        m.visitFieldInsn(Opcodes.GETFIELD, "kotlin/Result$Failure", "exception", "Ljava/lang/Throwable");
        m.visitInsn(Opcodes.ATHROW);
        m.visitInsn(Opcodes.POP);
        range1.toInclusive = m.instructions.getLast();
        m.visitLabel(label);
    }

    // line of "suspendingFunction"
    m.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "", "suspendingFunction",
            "(Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", false);

    m.visitInsn(Opcodes.DUP);
    final Range range2 = new Range();
    range2.fromInclusive = m.instructions.getLast();
    m.visitVarInsn(Opcodes.ALOAD, 3);
    final Label continuationLabelAfterLoadedResult = new Label();
    m.visitJumpInsn(Opcodes.IF_ACMPNE, continuationLabelAfterLoadedResult);
    // line of "fun"
    m.visitVarInsn(Opcodes.ALOAD, 3);
    m.visitInsn(Opcodes.ARETURN);

    m.visitLabel(state1);

    {
        m.visitVarInsn(Opcodes.ALOAD, 1);
        m.visitInsn(Opcodes.DUP);
        m.visitTypeInsn(Opcodes.INSTANCEOF, "kotlin/Result$Failure");
        final Label label = new Label();
        m.visitJumpInsn(Opcodes.IFEQ, label);
        m.visitTypeInsn(Opcodes.CHECKCAST, "kotlin/Result$Failure");
        m.visitFieldInsn(Opcodes.GETFIELD, "kotlin/Result$Failure", "exception", "Ljava/lang/Throwable");
        m.visitInsn(Opcodes.ATHROW);
        m.visitInsn(Opcodes.POP);
        m.visitLabel(label);
    }
    m.visitVarInsn(Opcodes.ALOAD, 1);
    range2.toInclusive = m.instructions.getLast();
    m.visitLabel(continuationLabelAfterLoadedResult);

    // line after "suspendingFunction"
    m.visitInsn(Opcodes.NOP);
    m.visitInsn(Opcodes.ARETURN);

    m.visitLabel(dflt);
    final Range range0 = new Range();
    range0.fromInclusive = m.instructions.getLast();
    m.visitTypeInsn(Opcodes.NEW, "java/lang/IllegalStateException");
    m.visitInsn(Opcodes.DUP);
    m.visitLdcInsn("call to 'resume' before 'invoke' with coroutine");
    m.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/IllegalStateException", "<init>",
            "(Ljava/lang/String;)V", false);
    m.visitInsn(Opcodes.ATHROW);
    range0.toInclusive = m.instructions.getLast();

    filter.filter(m, context, output);

    assertIgnored(range0, range1, range2);
}

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

License:Open Source License

@Override
public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {
    final Type t = Type.getType(desc);
    switch (opcode) {
    case Opcodes.PUTSTATIC:
        pop(t);/*from   w  w  w .ja  v  a2s .  co  m*/
        break;
    case Opcodes.PUTFIELD:
        pop(t);
        pop(1);
        break;
    case Opcodes.GETSTATIC:
        push(t);
        break;
    case Opcodes.GETFIELD:
        pop(1);
        push(t);
        break;
    default:
        throw new IllegalArgumentException();
    }
    mv.visitFieldInsn(opcode, owner, name, desc);
}

From source file:org.jacoco.core.runtime.ExecutionDataAccessTest.java

License:Open Source License

@Test
public void testGenerateAccessCall() throws Exception {
    final boolean[] data = store.get(Long.valueOf(1234), "Sample", 5).getData();

    final ClassWriter writer = new ClassWriter(0);
    writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Sample", null, "java/lang/Object",
            new String[] { Type.getInternalName(Callable.class) });

    // Constructor
    MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "(Ljava/lang/Object;)V", null,
            new String[0]);
    mv.visitCode();//from  w  w w . j a va 2  s.  c  o m
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitFieldInsn(Opcodes.PUTFIELD, "Sample", "access", "Ljava/lang/Object;");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    // call()
    mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "call", "()Ljava/lang/Object;", null, new String[0]);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "Sample", "access", "Ljava/lang/Object;");
    ExecutionDataAccess.generateAccessCall(1234, "Sample", 5, mv);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(6, 1);
    mv.visitEnd();

    writer.visitField(Opcodes.ACC_PRIVATE, "access", "Ljava/lang/Object;", null, null);

    writer.visitEnd();
    final TargetLoader loader = new TargetLoader("Sample", writer.toByteArray());
    Callable<?> callable = (Callable<?>) loader.getTargetClass().getConstructor(Object.class)
            .newInstance(access);
    assertSame(data, callable.call());
}

From source file:org.jacoco.core.runtime.RuntimeDataTest.java

License:Open Source License

@Test
public void testGenerateAccessCall() throws Exception {
    final boolean[] probes = data.getExecutionData(Long.valueOf(1234), "Sample", 5).getProbes();

    final ClassWriter writer = new ClassWriter(0);
    writer.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "Sample", null, "java/lang/Object",
            new String[] { Type.getInternalName(Callable.class) });

    // Constructor
    MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "(Ljava/lang/Object;)V", null,
            new String[0]);
    mv.visitCode();/*from   www .j a v a2s.c  o  m*/
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitFieldInsn(Opcodes.PUTFIELD, "Sample", "access", "Ljava/lang/Object;");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(2, 2);
    mv.visitEnd();

    // call()
    mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "call", "()Ljava/lang/Object;", null, new String[0]);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "Sample", "access", "Ljava/lang/Object;");
    RuntimeData.generateAccessCall(1234, "Sample", 5, mv);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(6, 1);
    mv.visitEnd();

    writer.visitField(Opcodes.ACC_PRIVATE, "access", "Ljava/lang/Object;", null, null);

    writer.visitEnd();
    final TargetLoader loader = new TargetLoader("Sample", writer.toByteArray());
    Callable<?> callable = (Callable<?>) loader.getTargetClass().getConstructor(Object.class).newInstance(data);
    assertSame(probes, callable.call());
}

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

License:Open Source License

/**
 * Generates the instruction to store the top stack value in a non static
 * field.//w  w w.java 2s  .  co  m
 *
 * @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 putField(final Type owner, final String name, final Type type) {
    fieldInsn(Opcodes.PUTFIELD, owner, name, type);
}

From source file:org.jboss.byteman.rule.expression.FieldExpression.java

License:Open Source License

@Override
public void compileAssign(MethodVisitor mv, CompileContext compileContext) throws CompileException {
    if (indirectStatic != null) {
        // this is just wrapping a static field expression so compile it
        indirectStatic.compileAssign(mv, compileContext);
    } else {//from  w  ww .  jav a  2  s  . c o  m
        // make sure we are at the right source line
        compileContext.notifySourceLine(line);

        int currentStack = compileContext.getStackCount();
        int size = (type.getNBytes() > 4 ? 2 : 1);

        // copy the value so we leave it as a result
        if (size == 1) {
            // this means at the maximum we add 1 to the current stack
            // [.. val] ==> [.. val val]
            mv.visitInsn(Opcodes.DUP);
        } else {
            // [.. val1 val2] ==> [.. val1 val2 val1 val2]
            mv.visitInsn(Opcodes.DUP2);
        }
        compileContext.addStackCount(size);
        // compile the owner expression and swap with the value
        owner.compile(mv, compileContext);
        if (size == 1) {
            // [.. val val owner] ==> [.. val owner val]
            mv.visitInsn(Opcodes.SWAP);
        } else {
            // we have to use a DUP_X2 and a POP to insert the owner below the two word value
            // i.e. [.. val1 val2 val1 val2] ==> [.. val1 val2 val1 val2 owner] ==>
            //              [.. val1 val2 owner val1 val2 owner] ==> [.. val1 val2 owner val1 val2]
            mv.visitInsn(Opcodes.DUP_X2);
            compileContext.addStackCount(1);
            mv.visitInsn(Opcodes.POP);
            compileContext.addStackCount(-1);
        }
        if (isPublicField) {
            // now compile a field update
            String ownerType = Type.internalName(field.getDeclaringClass());
            String fieldName = field.getName();
            String fieldType = Type.internalName(field.getType(), true);
            mv.visitFieldInsn(Opcodes.PUTFIELD, ownerType, fieldName, fieldType);
            // we removed the owner and the value
            compileContext.addStackCount(-(1 + size));
        } else {
            // since this is a private field we need to do the update using reflection
            // box the value to an object if necessary
            if (type.isPrimitive()) {
                compileBox(Type.boxType(type), mv, compileContext);
            }
            // stack the helper and then dupx2 it so it goes under the owner and value
            // [.. val(s) owner  valObj ==> val(s) owner valObj helper ]
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            // [.. val(s) owner  valObj helper ==> val(s) helper owner valObj helper ]
            mv.visitInsn(Opcodes.DUP_X2);
            // stack now has 2 more words so count them
            compileContext.addStackCount(2);
            // now pop the redundant top word and stack the field index instead
            // [.. val(s) helper owner valObj helper ==> val(s) helper owner valObj index ]
            mv.visitInsn(Opcodes.POP);
            mv.visitLdcInsn(fieldIndex);
            // use the HelperAdapter method setAccessibleField to set the field value
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.internalName(HelperAdapter.class),
                    "setAccessibleField", "(Ljava/lang/Object;Ljava/lang/Object;I)V");
            // we popped four args
            compileContext.addStackCount(-4);
        }

        // check the stack height is ok
        if (compileContext.getStackCount() != currentStack) {
            throw new CompileException("FieldExpression.compileAssign : invalid stack height "
                    + compileContext.getStackCount() + " expecting " + (currentStack));
        }
    }
}