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:edu.illinois.nondex.instr.WeakHashMapShufflingAdder.java

License:Open Source License

public void addNextEntry() {
    MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC, "nextEntry", "()Ljava/util/WeakHashMap$Entry;",
            "()Ljava/util/WeakHashMap$Entry<TK;TV;>;", null);
    mv.visitCode();//from  ww w.j a va2  s .  co  m
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap$HashIterator", "this$0",
            "Ljava/util/WeakHashMap;");
    mv.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap", "modCount", "I");
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap$HashIterator", "expectedModCount", "I");
    Label l0 = new Label();
    mv.visitJumpInsn(Opcodes.IF_ICMPEQ, l0);
    mv.visitTypeInsn(Opcodes.NEW, "java/util/ConcurrentModificationException");
    mv.visitInsn(Opcodes.DUP);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/ConcurrentModificationException", "<init>", "()V",
            false);
    mv.visitInsn(Opcodes.ATHROW);
    mv.visitLabel(l0);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap$HashIterator", "iter", "Ljava/util/Iterator;");
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Iterator", "next", "()Ljava/lang/Object;", true);
    mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/WeakHashMap$Entry");
    mv.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "lastReturned",
            "Ljava/util/WeakHashMap$Entry;");
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap$HashIterator", "lastReturned",
            "Ljava/util/WeakHashMap$Entry;");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/WeakHashMap$Entry", "get", "()Ljava/lang/Object;",
            false);
    mv.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "currentKey",
            "Ljava/lang/Object;");
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap$HashIterator", "lastReturned",
            "Ljava/util/WeakHashMap$Entry;");
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(2, 1);
    mv.visitEnd();
}

From source file:edu.illinois.nondex.instr.WeakHashMapShufflingAdder.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if ("hasNext".equals(name)) {
        return super.visitMethod(access, "originalHasNext", desc, signature, exceptions);
    }/*from   w w w . ja va2  s  .  co  m*/
    if ("nextEntry".equals(name)) {
        return super.visitMethod(access, "originalNextEntry", desc, signature, exceptions);
    }
    if ("<init>".equals(name)) {
        return new MethodVisitor(Opcodes.ASM5, super.visitMethod(access, name, desc, signature, exceptions)) {
            @Override
            public void visitInsn(int opcode) {
                if (opcode == Opcodes.RETURN) {
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitVarInsn(Opcodes.ALOAD, 1);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "this$0",
                            "Ljava/util/WeakHashMap;");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitInsn(Opcodes.ACONST_NULL);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "entry",
                            "Ljava/util/WeakHashMap$Entry;");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitInsn(Opcodes.ACONST_NULL);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "lastReturned",
                            "Ljava/util/WeakHashMap$Entry;");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap$HashIterator", "this$0",
                            "Ljava/util/WeakHashMap;");
                    super.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap", "modCount", "I");
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator",
                            "expectedModCount", "I");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitInsn(Opcodes.ACONST_NULL);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "nextKey",
                            "Ljava/lang/Object;");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitInsn(Opcodes.ACONST_NULL);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "currentKey",
                            "Ljava/lang/Object;");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitInsn(Opcodes.ACONST_NULL);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "iter",
                            "Ljava/util/Iterator;");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitVarInsn(Opcodes.ALOAD, 1);
                    super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/WeakHashMap", "isEmpty", "()Z",
                            false);
                    Label l0 = new Label();
                    super.visitJumpInsn(Opcodes.IFEQ, l0);
                    super.visitInsn(Opcodes.ICONST_0);
                    Label l1 = new Label();
                    super.visitJumpInsn(Opcodes.GOTO, l1);
                    super.visitLabel(l0);
                    super.visitFrame(Opcodes.F_FULL, 2,
                            new Object[] { "java/util/WeakHashMap$HashIterator", "java/util/WeakHashMap" }, 1,
                            new Object[] { "java/util/WeakHashMap$HashIterator" });
                    super.visitVarInsn(Opcodes.ALOAD, 1);
                    super.visitFieldInsn(Opcodes.GETFIELD, "java/util/WeakHashMap", "table",
                            "[Ljava/util/WeakHashMap$Entry;");
                    super.visitInsn(Opcodes.ARRAYLENGTH);
                    super.visitLabel(l1);
                    super.visitFrame(Opcodes.F_FULL, 2,
                            new Object[] { "java/util/WeakHashMap$HashIterator", "java/util/WeakHashMap" }, 2,
                            new Object[] { "java/util/WeakHashMap$HashIterator", Opcodes.INTEGER });
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "index", "I");
                    super.visitTypeInsn(Opcodes.NEW, "java/util/ArrayList");
                    super.visitInsn(Opcodes.DUP);
                    super.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/ArrayList", "<init>", "()V", false);
                    super.visitVarInsn(Opcodes.ASTORE, 2);
                    Label l2 = new Label();
                    super.visitLabel(l2);
                    super.visitFrame(Opcodes.F_APPEND, 1, new Object[] { "java/util/List" }, 0, null);
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/WeakHashMap$HashIterator",
                            "originalHasNext", "()Z", false);
                    Label l3 = new Label();
                    super.visitJumpInsn(Opcodes.IFEQ, l3);
                    super.visitVarInsn(Opcodes.ALOAD, 2);
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/WeakHashMap$HashIterator",
                            "originalNextEntry", "()Ljava/util/WeakHashMap$Entry;", false);
                    super.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "add",
                            "(Ljava/lang/Object;)Z", true);
                    super.visitInsn(Opcodes.POP);
                    super.visitJumpInsn(Opcodes.GOTO, l2);
                    super.visitLabel(l3);
                    super.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                    super.visitVarInsn(Opcodes.ALOAD, 2);
                    super.visitMethodInsn(Opcodes.INVOKESTATIC,
                            "edu/illinois/nondex/shuffling/ControlNondeterminism", "shuffle",
                            "(Ljava/util/List;)Ljava/util/List;", false);
                    super.visitVarInsn(Opcodes.ASTORE, 2);
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitVarInsn(Opcodes.ALOAD, 2);
                    super.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "iterator",
                            "()Ljava/util/Iterator;", true);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "iter",
                            "Ljava/util/Iterator;");
                    super.visitVarInsn(Opcodes.ALOAD, 0);
                    super.visitInsn(Opcodes.ACONST_NULL);
                    super.visitFieldInsn(Opcodes.PUTFIELD, "java/util/WeakHashMap$HashIterator", "lastReturned",
                            "Ljava/util/WeakHashMap$Entry;");
                }
                super.visitInsn(opcode);
            }
        };
    }
    return super.visitMethod(access, name, desc, signature, exceptions);
}

From source file:edu.mit.streamjit.impl.common.MessageConstraint.java

License:Open Source License

/**
 * Parse the given getHandle() call instruction and preceding instructions
 * into a WorkerData.  This is a rather brittle pattern-matching job and
 * will fail on obfuscated bytecodes./*from w w  w.  j a va  2s .c  om*/
 * @param call
 * @return
 */
private static WorkerData dataFromCall(Class<?> klass, MethodInsnNode call) {
    //Latency is either an integer constant or a getfield on this.
    Field latencyField = null;
    int constantLatency = Integer.MIN_VALUE;
    AbstractInsnNode latencyInsn = call.getPrevious();
    if (latencyInsn instanceof FieldInsnNode) {
        FieldInsnNode fieldInsn = (FieldInsnNode) latencyInsn;
        if (fieldInsn.getOpcode() != Opcodes.GETFIELD)
            throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                    + ": latency field insn opcode " + fieldInsn.getOpcode());
        if (!fieldInsn.desc.equals(Type.INT_TYPE.getDescriptor()))
            throw new IllegalStreamGraphException(
                    "Unsupported getHandle() use in " + klass + ": latency field desc " + fieldInsn.desc);
        if (!fieldInsn.owner.equals(Type.getType(klass).getInternalName()))
            throw new IllegalStreamGraphException(
                    "Unsupported getHandle() use in " + klass + ": latency field owner " + fieldInsn.owner);

        //Move latencyInsn to sync up with the other else-if branches.
        latencyInsn = latencyInsn.getPrevious();
        //We must be loading from this.
        if (latencyInsn.getOpcode() != Opcodes.ALOAD)
            throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                    + ": getfield subject opcode " + latencyInsn.getOpcode());
        int varIdx = ((VarInsnNode) latencyInsn).var;
        if (varIdx != 0)
            throw new IllegalStreamGraphException(
                    "Unsupported getHandle() use in " + klass + ": getfield not from this but from " + varIdx);

        //Check the field we're loading from is constant (final).
        //A static field is okay here since it isn't a reference parameter.
        try {
            latencyField = klass.getDeclaredField(fieldInsn.name);
            if (!Modifier.isFinal(latencyField.getModifiers()))
                throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                        + ": latency field not final: " + latencyField.toGenericString());
        } catch (NoSuchFieldException ex) {
            throw new IllegalStreamGraphException(
                    "Unsupported getHandle() use in " + klass + ": getfield not from this but from " + varIdx);
        }
    } else if (latencyInsn instanceof LdcInsnNode) {
        Object constant = ((LdcInsnNode) latencyInsn).cst;
        if (!(constant instanceof Integer))
            throw new IllegalStreamGraphException(
                    "Unsupported getHandle() use in " + klass + ": ldc " + constant);
        constantLatency = ((Integer) constant);
    } else
        switch (latencyInsn.getOpcode()) {
        case Opcodes.ICONST_M1:
            constantLatency = -1;
            break;
        case Opcodes.ICONST_0:
            constantLatency = 0;
            break;
        case Opcodes.ICONST_1:
            constantLatency = 1;
            break;
        case Opcodes.ICONST_2:
            constantLatency = 2;
            break;
        case Opcodes.ICONST_3:
            constantLatency = 3;
            break;
        case Opcodes.ICONST_4:
            constantLatency = 4;
            break;
        case Opcodes.ICONST_5:
            constantLatency = 5;
            break;
        case Opcodes.BIPUSH:
        case Opcodes.SIPUSH:
            constantLatency = ((IntInsnNode) latencyInsn).operand;
            break;
        default:
            throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                    + ": latencyInsn opcode " + latencyInsn.getOpcode());
        }
    //Finally, we've parsed the latency parameter.

    //Next is an aload_0 for the sender parameter.
    AbstractInsnNode senderInsn = latencyInsn.getPrevious();
    if (senderInsn.getOpcode() != Opcodes.ALOAD || ((VarInsnNode) senderInsn).var != 0)
        throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass + ": bad sender");

    //Finally, a getfield of this for a final Portal instance field.
    AbstractInsnNode portalInsn = senderInsn.getPrevious();
    if (!(portalInsn instanceof FieldInsnNode))
        throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                + ": portal getfield opcode " + portalInsn.getOpcode());
    FieldInsnNode fieldInsn = (FieldInsnNode) portalInsn;
    if (fieldInsn.getOpcode() != Opcodes.GETFIELD)
        throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                + ": portal field insn opcode " + fieldInsn.getOpcode());
    if (!fieldInsn.desc.equals(Type.getType(Portal.class).getDescriptor()))
        throw new IllegalStreamGraphException(
                "Unsupported getHandle() use in " + klass + ": portal field desc " + fieldInsn.desc);
    if (!fieldInsn.owner.equals(Type.getType(klass).getInternalName()))
        throw new IllegalStreamGraphException(
                "Unsupported getHandle() use in " + klass + ": portal field owner " + fieldInsn.owner);

    portalInsn = portalInsn.getPrevious();
    //We must be loading from this.
    if (portalInsn.getOpcode() != Opcodes.ALOAD)
        throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                + ": portal getfield subject opcode " + portalInsn.getOpcode());
    int varIdx = ((VarInsnNode) portalInsn).var;
    if (varIdx != 0)
        throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                + ": portal getfield not from this but from " + varIdx);

    //Check the field we're loading from is constant (final) and nonstatic.
    Field portalField;
    try {
        portalField = klass.getDeclaredField(fieldInsn.name);
        if (!Modifier.isFinal(portalField.getModifiers()))
            throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                    + ": portal field not final: " + portalField.toGenericString());
        if (Modifier.isStatic(portalField.getModifiers()))
            throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                    + ": portal field is static: " + portalField.toGenericString());
    } catch (NoSuchFieldException ex) {
        throw new IllegalStreamGraphException("Unsupported getHandle() use in " + klass
                + ": portal getfield not from this but from " + varIdx);
    }

    return latencyField != null ? new WorkerData(portalField, latencyField)
            : new WorkerData(portalField, constantLatency);
}

From source file:edu.mit.streamjit.util.bytecode.MethodResolver.java

License:Open Source License

private void interpret(FieldInsnNode insn, FrameState frame, BBInfo block) {
    Klass k = getKlassByInternalName(insn.owner);
    Field f = k.getField(insn.name);
    switch (insn.getOpcode()) {
    case Opcodes.GETSTATIC:
        LoadInst li = new LoadInst(f);
        block.block.instructions().add(li);
        frame.stack.push(li);/*  w  ww  . j  a  v  a  2  s. c  o m*/
        break;
    case Opcodes.GETFIELD:
        LoadInst li2 = new LoadInst(f, frame.stack.pop());
        block.block.instructions().add(li2);
        frame.stack.push(li2);
        break;
    case Opcodes.PUTSTATIC:
        StoreInst si = new StoreInst(f, frame.stack.pop());
        block.block.instructions().add(si);
        break;
    case Opcodes.PUTFIELD:
        StoreInst si2 = new StoreInst(f, frame.stack.pop(), frame.stack.pop());
        block.block.instructions().add(si2);
        break;
    default:
        throw new UnsupportedOperationException("" + insn.getOpcode());
    }
}

From source file:edu.mit.streamjit.util.bytecode.MethodUnresolver.java

License:Open Source License

private void emit(LoadInst i, InsnList insns) {
    Value location = i.getLocation();//  ww  w  . ja  va  2 s. c  om
    if (location instanceof LocalVariable) {
        load(location, insns);
        store(i, insns);
    } else {
        Field f = (Field) location;
        if (!f.isStatic())
            load(i.getInstance(), insns);
        insns.add(new FieldInsnNode(f.isStatic() ? Opcodes.GETSTATIC : Opcodes.GETFIELD,
                internalName(f.getParent()), f.getName(), f.getType().getFieldType().getDescriptor()));
        store(i, insns);
    }
}

From source file:edu.ubc.mirrors.holograms.HologramClassGenerator.java

License:Open Source License

@Override
public void visitEnd() {
    // Generate the static field used to store the corresponding ClassMirror
    int staticAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC;
    super.visitField(staticAccess, "classMirror", classMirrorType.getDescriptor(), null, null);

    // Generate the constructor that takes a mirror instance as an Object parameter
    String constructorDesc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class));
    if (name.equals(getHologramType(Type.getType(Throwable.class), true).getInternalName())) {
        // This doesn't extend ObjectHologram so we have to set the field directly
        super.visitField(Opcodes.ACC_PUBLIC, "mirror", objectMirrorType.getDescriptor(), null, null);

        MethodVisitor methodVisitor = super.visitMethod(Opcodes.ACC_PUBLIC, "<init>", constructorDesc, null,
                null);/*from  ww w  . j a  v  a  2 s.c  o m*/
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superName, "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE));
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, objectMirrorType.getInternalName());
        methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, name, "mirror", Type.getDescriptor(ObjectMirror.class));
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitMaxs(2, 2);
        methodVisitor.visitEnd();

        methodVisitor = super.visitMethod(Opcodes.ACC_PUBLIC, "getMirror",
                Type.getMethodDescriptor(objectMirrorType), null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, name, "mirror", Type.getDescriptor(ObjectMirror.class));
        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(1, 1);
        methodVisitor.visitEnd();
    } else if (!isInterface) {
        MethodVisitor methodVisitor = super.visitMethod(Opcodes.ACC_PUBLIC, "<init>", constructorDesc, null,
                null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superName, "<init>", constructorDesc);
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitMaxs(2, 2);
        methodVisitor.visitEnd();
    }

    // Add a class initialization method to initialize the static fields,
    // if one doesn't exist already.
    if (!hasClinit) {
        InstructionAdapter mv = new InstructionAdapter(
                super.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "<clinit>", "()V", null, null));
        mv.visitCode();
        HologramMethodGenerator.initializeStaticFields(Type.getObjectType(this.name), mv);
        mv.areturn(Type.VOID_TYPE);
        mv.visitMaxs(2, 2);
        mv.visitEnd();
    }

    super.visitEnd();
}

From source file:edu.umd.cs.findbugs.ba.XFactory.java

License:Open Source License

public static XField createReferencedXField(DismantleBytecode visitor) {
    int seen = visitor.getOpcode();
    if (seen != Opcodes.GETFIELD && seen != Opcodes.GETSTATIC && seen != Opcodes.PUTFIELD
            && seen != Opcodes.PUTSTATIC) {
        throw new IllegalArgumentException("Not at a field reference");
    }//from  www  .j av  a  2  s . c o m
    return createXFieldUsingSlashedClassName(visitor.getClassConstantOperand(),
            visitor.getNameConstantOperand(), visitor.getSigConstantOperand(), visitor.getRefFieldIsStatic());
}

From source file:edu.umd.cs.guitar.testcase.plugin.edg.ClassDBVisitor.java

License:Open Source License

@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
    currentMethod.setEmpty(false);/*w  ww.ja  v a  2s  . com*/
    Class c;
    Field f;
    switch (opcode) {
    case Opcodes.GETFIELD:
    case Opcodes.GETSTATIC:
        c = getClass(owner);
        f = getField(c, name);
        f.setDesc(desc);
        // read after write is not a real read
        // if (!currentMethod.hasWrite(f)){
        currentMethod.addRead(f);
        labelReads.add(f);
        // }
        break;
    case Opcodes.PUTFIELD:
    case Opcodes.PUTSTATIC:
        c = getClass(owner);
        f = getField(c, name);
        f.setDesc(desc);
        currentMethod.addWrite(f);
        labelWrites.add(f);
        break;
    }
}

From source file:erjang.ETuple.java

License:Apache License

private static void create_tuple_nth(int n_cells, ClassAdapter cw, String this_class_name) {
    MethodVisitor mv;/*from   w ww.j  a  v a 2s .  c om*/
    mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "elm", "(I)" + ETERM_TYPE.getDescriptor(), null, null);
    mv.visitCode();

    Label dflt = new Label();
    Label[] labels = new Label[n_cells];
    for (int i = 0; i < n_cells; i++) {
        labels[i] = new Label();
    }

    mv.visitVarInsn(Opcodes.ILOAD, 1);
    mv.visitTableSwitchInsn(1, n_cells, dflt, labels);

    for (int zbase = 0; zbase < n_cells; zbase++) {

        mv.visitLabel(labels[zbase]);

        mv.visitVarInsn(Opcodes.ALOAD, 0); // load this
        String field = "elem" + (zbase + 1);

        mv.visitFieldInsn(Opcodes.GETFIELD, this_class_name, field, ETERM_TYPE.getDescriptor());
        mv.visitInsn(Opcodes.ARETURN);
    }

    mv.visitLabel(dflt);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ILOAD, 1);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, ETUPLE_NAME, "bad_nth", "(I)" + ETERM_TYPE.getDescriptor());
    mv.visitInsn(Opcodes.ARETURN); // make compiler happy

    mv.visitMaxs(3, 2);
    mv.visitEnd();
}

From source file:gnu.classpath.tools.rmic.ClassRmicCompiler.java

License:Open Source License

private void generateStub() throws IOException {
    stubname = fullclassname + "_Stub";
    String stubclassname = classname + "_Stub";
    File file = new File((destination == null ? "." : destination) + File.separator
            + stubname.replace('.', File.separatorChar) + ".class");

    if (verbose)// w w  w.jav a  2 s  . c  om
        System.out.println("[Generating class " + stubname + "]");

    final ClassWriter stub = new ClassWriter(true);
    classInternalName = stubname.replace('.', '/');
    final String superInternalName = Type.getType(RemoteStub.class).getInternalName();

    String[] remoteInternalNames = internalNameArray((Class[]) mRemoteInterfaces.toArray(new Class[] {}));
    stub.visit(Opcodes.V1_2, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, classInternalName, null, superInternalName,
            remoteInternalNames);

    if (need12Stubs) {
        stub.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "serialVersionUID",
                Type.LONG_TYPE.getDescriptor(), null, new Long(2L));
    }

    if (need11Stubs) {
        stub.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "interfaceHash",
                Type.LONG_TYPE.getDescriptor(), null, new Long(RMIHashes.getInterfaceHash(clazz)));

        if (need12Stubs) {
            stub.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC, "useNewInvoke",
                    Type.BOOLEAN_TYPE.getDescriptor(), null, null);
        }

        stub.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "operations",
                Type.getDescriptor(Operation[].class), null, null);
    }

    // Set of method references.
    if (need12Stubs) {
        for (int i = 0; i < remotemethods.length; i++) {
            Method m = remotemethods[i].meth;
            String slotName = "$method_" + m.getName() + "_" + i;
            stub.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC, slotName,
                    Type.getDescriptor(Method.class), null, null);
        }
    }

    MethodVisitor clinit = stub.visitMethod(Opcodes.ACC_STATIC, "<clinit>",
            Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}), null, null);

    if (need11Stubs) {
        fillOperationArray(clinit);
        if (!need12Stubs)
            clinit.visitInsn(Opcodes.RETURN);
    }

    if (need12Stubs) {
        // begin of try
        Label begin = new Label();

        // beginning of catch
        Label handler = new Label();
        clinit.visitLabel(begin);

        // Initialize the methods references.
        if (need11Stubs) {
            /*
             * RemoteRef.class.getMethod("invoke", new Class[] {
             *   Remote.class, Method.class, Object[].class, long.class })
             */
            generateClassConstant(clinit, RemoteRef.class);
            clinit.visitLdcInsn("invoke");
            generateClassArray(clinit, new Class[] { Remote.class, Method.class, Object[].class, long.class });
            clinit.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Class.class), "getMethod",
                    Type.getMethodDescriptor(Type.getType(Method.class),
                            new Type[] { Type.getType(String.class), Type.getType(Class[].class) }));

            // useNewInvoke = true
            clinit.visitInsn(Opcodes.ICONST_1);
            clinit.visitFieldInsn(Opcodes.PUTSTATIC, classInternalName, "useNewInvoke",
                    Type.BOOLEAN_TYPE.getDescriptor());
        }

        generateStaticMethodObjs(clinit);

        // jump past handler
        clinit.visitInsn(Opcodes.RETURN);
        clinit.visitLabel(handler);
        if (need11Stubs) {
            // useNewInvoke = false
            clinit.visitInsn(Opcodes.ICONST_0);
            clinit.visitFieldInsn(Opcodes.PUTSTATIC, classInternalName, "useNewInvoke",
                    Type.BOOLEAN_TYPE.getDescriptor());
            clinit.visitInsn(Opcodes.RETURN);
        } else {
            // throw NoSuchMethodError
            clinit.visitTypeInsn(Opcodes.NEW, typeArg(NoSuchMethodError.class));
            clinit.visitInsn(Opcodes.DUP);
            clinit.visitLdcInsn("stub class initialization failed");
            clinit.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(NoSuchMethodError.class),
                    "<init>",
                    Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(String.class) }));
            clinit.visitInsn(Opcodes.ATHROW);
        }

        clinit.visitTryCatchBlock(begin, handler, handler, Type.getInternalName(NoSuchMethodException.class));

    }

    clinit.visitMaxs(-1, -1);

    generateClassForNamer(stub);

    // Constructors
    if (need11Stubs) {
        // no arg public constructor
        MethodVisitor code = stub.visitMethod(Opcodes.ACC_PUBLIC, "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}), null, null);
        code.visitVarInsn(Opcodes.ALOAD, 0);
        code.visitMethodInsn(Opcodes.INVOKESPECIAL, superInternalName, "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}));
        code.visitInsn(Opcodes.RETURN);

        code.visitMaxs(-1, -1);
    }

    // public RemoteRef constructor
    MethodVisitor constructor = stub.visitMethod(Opcodes.ACC_PUBLIC, "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(RemoteRef.class) }), null, null);
    constructor.visitVarInsn(Opcodes.ALOAD, 0);
    constructor.visitVarInsn(Opcodes.ALOAD, 1);
    constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, superInternalName, "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(RemoteRef.class) }));
    constructor.visitInsn(Opcodes.RETURN);
    constructor.visitMaxs(-1, -1);

    // Method implementations
    for (int i = 0; i < remotemethods.length; i++) {
        Method m = remotemethods[i].meth;
        Class[] sig = m.getParameterTypes();
        Class returntype = m.getReturnType();
        Class[] except = sortExceptions((Class[]) remotemethods[i].exceptions.toArray(new Class[0]));

        MethodVisitor code = stub.visitMethod(Opcodes.ACC_PUBLIC, m.getName(),
                Type.getMethodDescriptor(Type.getType(returntype), typeArray(sig)), null,
                internalNameArray(typeArray(except)));

        final Variables var = new Variables();

        // this and parameters are the declared vars
        var.declare("this");
        for (int j = 0; j < sig.length; j++)
            var.declare(param(m, j), size(sig[j]));

        Label methodTryBegin = new Label();
        code.visitLabel(methodTryBegin);

        if (need12Stubs) {
            Label oldInvoke = new Label();
            if (need11Stubs) {
                // if not useNewInvoke jump to old invoke
                code.visitFieldInsn(Opcodes.GETSTATIC, classInternalName, "useNewInvoke",
                        Type.getDescriptor(boolean.class));
                code.visitJumpInsn(Opcodes.IFEQ, oldInvoke);
            }

            // this.ref
            code.visitVarInsn(Opcodes.ALOAD, var.get("this"));
            code.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(RemoteObject.class), "ref",
                    Type.getDescriptor(RemoteRef.class));

            // "this" is first arg to invoke
            code.visitVarInsn(Opcodes.ALOAD, var.get("this"));

            // method object is second arg to invoke
            String methName = "$method_" + m.getName() + "_" + i;
            code.visitFieldInsn(Opcodes.GETSTATIC, classInternalName, methName,
                    Type.getDescriptor(Method.class));

            // args to remote method are third arg to invoke
            if (sig.length == 0)
                code.visitInsn(Opcodes.ACONST_NULL);
            else {
                // create arg Object[] (with boxed primitives) and push it
                code.visitLdcInsn(new Integer(sig.length));
                code.visitTypeInsn(Opcodes.ANEWARRAY, typeArg(Object.class));

                var.allocate("argArray");
                code.visitVarInsn(Opcodes.ASTORE, var.get("argArray"));

                for (int j = 0; j < sig.length; j++) {
                    int size = size(sig[j]);
                    int insn = loadOpcode(sig[j]);
                    Class box = sig[j].isPrimitive() ? box(sig[j]) : null;

                    code.visitVarInsn(Opcodes.ALOAD, var.get("argArray"));
                    code.visitLdcInsn(new Integer(j));

                    // put argument on stack
                    if (box != null) {
                        code.visitTypeInsn(Opcodes.NEW, typeArg(box));
                        code.visitInsn(Opcodes.DUP);
                        code.visitVarInsn(insn, var.get(param(m, j)));
                        code.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(box), "<init>",
                                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(sig[j]) }));
                    } else
                        code.visitVarInsn(insn, var.get(param(m, j)));

                    code.visitInsn(Opcodes.AASTORE);
                }

                code.visitVarInsn(Opcodes.ALOAD, var.deallocate("argArray"));
            }

            // push remote operation opcode
            code.visitLdcInsn(new Long(remotemethods[i].hash));
            code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(RemoteRef.class), "invoke",
                    Type.getMethodDescriptor(Type.getType(Object.class),
                            new Type[] { Type.getType(Remote.class), Type.getType(Method.class),
                                    Type.getType(Object[].class), Type.LONG_TYPE }));

            if (!returntype.equals(Void.TYPE)) {
                int retcode = returnOpcode(returntype);
                Class boxCls = returntype.isPrimitive() ? box(returntype) : null;
                code.visitTypeInsn(Opcodes.CHECKCAST, typeArg(boxCls == null ? returntype : boxCls));
                if (returntype.isPrimitive()) {
                    // unbox
                    code.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getType(boxCls).getInternalName(),
                            unboxMethod(returntype),
                            Type.getMethodDescriptor(Type.getType(returntype), new Type[] {}));
                }

                code.visitInsn(retcode);
            } else
                code.visitInsn(Opcodes.RETURN);

            if (need11Stubs)
                code.visitLabel(oldInvoke);
        }

        if (need11Stubs) {

            // this.ref.newCall(this, operations, index, interfaceHash)
            code.visitVarInsn(Opcodes.ALOAD, var.get("this"));
            code.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(RemoteObject.class), "ref",
                    Type.getDescriptor(RemoteRef.class));

            // "this" is first arg to newCall
            code.visitVarInsn(Opcodes.ALOAD, var.get("this"));

            // operations is second arg to newCall
            code.visitFieldInsn(Opcodes.GETSTATIC, classInternalName, "operations",
                    Type.getDescriptor(Operation[].class));

            // method index is third arg
            code.visitLdcInsn(new Integer(i));

            // interface hash is fourth arg
            code.visitFieldInsn(Opcodes.GETSTATIC, classInternalName, "interfaceHash",
                    Type.LONG_TYPE.getDescriptor());

            code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(RemoteRef.class), "newCall",
                    Type.getMethodDescriptor(Type.getType(RemoteCall.class),
                            new Type[] { Type.getType(RemoteObject.class), Type.getType(Operation[].class),
                                    Type.INT_TYPE, Type.LONG_TYPE }));

            // store call object on stack and leave copy on stack
            var.allocate("call");
            code.visitInsn(Opcodes.DUP);
            code.visitVarInsn(Opcodes.ASTORE, var.get("call"));

            Label beginArgumentTryBlock = new Label();
            code.visitLabel(beginArgumentTryBlock);

            // ObjectOutput out = call.getOutputStream();
            code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(RemoteCall.class),
                    "getOutputStream",
                    Type.getMethodDescriptor(Type.getType(ObjectOutput.class), new Type[] {}));

            for (int j = 0; j < sig.length; j++) {
                // dup the ObjectOutput
                code.visitInsn(Opcodes.DUP);

                // get j'th arg to remote method
                code.visitVarInsn(loadOpcode(sig[j]), var.get(param(m, j)));

                Class argCls = sig[j].isPrimitive() ? sig[j] : Object.class;

                // out.writeFoo
                code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(ObjectOutput.class),
                        writeMethod(sig[j]),
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(argCls) }));
            }

            // pop ObjectOutput
            code.visitInsn(Opcodes.POP);

            Label iohandler = new Label();
            Label endArgumentTryBlock = new Label();
            code.visitJumpInsn(Opcodes.GOTO, endArgumentTryBlock);
            code.visitLabel(iohandler);

            // throw new MarshalException(msg, ioexception);
            code.visitVarInsn(Opcodes.ASTORE, var.allocate("exception"));
            code.visitTypeInsn(Opcodes.NEW, typeArg(MarshalException.class));
            code.visitInsn(Opcodes.DUP);
            code.visitLdcInsn("error marshalling arguments");
            code.visitVarInsn(Opcodes.ALOAD, var.deallocate("exception"));
            code.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(MarshalException.class), "<init>",
                    Type.getMethodDescriptor(Type.VOID_TYPE,
                            new Type[] { Type.getType(String.class), Type.getType(Exception.class) }));
            code.visitInsn(Opcodes.ATHROW);

            code.visitLabel(endArgumentTryBlock);
            code.visitTryCatchBlock(beginArgumentTryBlock, iohandler, iohandler,
                    Type.getInternalName(IOException.class));

            // this.ref.invoke(call)
            code.visitVarInsn(Opcodes.ALOAD, var.get("this"));
            code.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(RemoteObject.class), "ref",
                    Type.getDescriptor(RemoteRef.class));
            code.visitVarInsn(Opcodes.ALOAD, var.get("call"));
            code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(RemoteRef.class), "invoke",
                    Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(RemoteCall.class) }));

            // handle return value
            boolean needcastcheck = false;

            Label beginReturnTryCatch = new Label();
            code.visitLabel(beginReturnTryCatch);

            int returncode = returnOpcode(returntype);

            if (!returntype.equals(Void.TYPE)) {
                // call.getInputStream()
                code.visitVarInsn(Opcodes.ALOAD, var.get("call"));
                code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(RemoteCall.class),
                        "getInputStream",
                        Type.getMethodDescriptor(Type.getType(ObjectInput.class), new Type[] {}));

                Class readCls = returntype.isPrimitive() ? returntype : Object.class;
                code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(ObjectInput.class),
                        readMethod(returntype), Type.getMethodDescriptor(Type.getType(readCls), new Type[] {}));

                boolean castresult = false;

                if (!returntype.isPrimitive()) {
                    if (!returntype.equals(Object.class))
                        castresult = true;
                    else
                        needcastcheck = true;
                }

                if (castresult)
                    code.visitTypeInsn(Opcodes.CHECKCAST, typeArg(returntype));

                // leave result on stack for return
            }

            // this.ref.done(call)
            code.visitVarInsn(Opcodes.ALOAD, var.get("this"));
            code.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(RemoteObject.class), "ref",
                    Type.getDescriptor(RemoteRef.class));
            code.visitVarInsn(Opcodes.ALOAD, var.deallocate("call"));
            code.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(RemoteRef.class), "done",
                    Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(RemoteCall.class) }));

            // return; or return result;
            code.visitInsn(returncode);

            // exception handler
            Label handler = new Label();
            code.visitLabel(handler);
            code.visitVarInsn(Opcodes.ASTORE, var.allocate("exception"));

            // throw new UnmarshalException(msg, e)
            code.visitTypeInsn(Opcodes.NEW, typeArg(UnmarshalException.class));
            code.visitInsn(Opcodes.DUP);
            code.visitLdcInsn("error unmarshalling return");
            code.visitVarInsn(Opcodes.ALOAD, var.deallocate("exception"));
            code.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(UnmarshalException.class),
                    "<init>", Type.getMethodDescriptor(Type.VOID_TYPE,
                            new Type[] { Type.getType(String.class), Type.getType(Exception.class) }));
            code.visitInsn(Opcodes.ATHROW);

            Label endReturnTryCatch = new Label();

            // catch IOException
            code.visitTryCatchBlock(beginReturnTryCatch, handler, handler,
                    Type.getInternalName(IOException.class));

            if (needcastcheck) {
                // catch ClassNotFoundException
                code.visitTryCatchBlock(beginReturnTryCatch, handler, handler,
                        Type.getInternalName(ClassNotFoundException.class));
            }
        }

        Label rethrowHandler = new Label();
        code.visitLabel(rethrowHandler);
        // rethrow declared exceptions
        code.visitInsn(Opcodes.ATHROW);

        boolean needgeneral = true;
        for (int j = 0; j < except.length; j++) {
            if (except[j] == Exception.class)
                needgeneral = false;
        }

        for (int j = 0; j < except.length; j++) {
            code.visitTryCatchBlock(methodTryBegin, rethrowHandler, rethrowHandler,
                    Type.getInternalName(except[j]));
        }

        if (needgeneral) {
            // rethrow unchecked exceptions
            code.visitTryCatchBlock(methodTryBegin, rethrowHandler, rethrowHandler,
                    Type.getInternalName(RuntimeException.class));

            Label generalHandler = new Label();
            code.visitLabel(generalHandler);
            String msg = "undeclared checked exception";

            // throw new java.rmi.UnexpectedException(msg, e)
            code.visitVarInsn(Opcodes.ASTORE, var.allocate("exception"));
            code.visitTypeInsn(Opcodes.NEW, typeArg(UnexpectedException.class));
            code.visitInsn(Opcodes.DUP);
            code.visitLdcInsn(msg);
            code.visitVarInsn(Opcodes.ALOAD, var.deallocate("exception"));
            code.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(UnexpectedException.class),
                    "<init>", Type.getMethodDescriptor(Type.VOID_TYPE,
                            new Type[] { Type.getType(String.class), Type.getType(Exception.class) }));
            code.visitInsn(Opcodes.ATHROW);

            code.visitTryCatchBlock(methodTryBegin, rethrowHandler, generalHandler,
                    Type.getInternalName(Exception.class));
        }

        code.visitMaxs(-1, -1);
    }

    stub.visitEnd();
    byte[] classData = stub.toByteArray();
    if (!noWrite) {
        if (file.exists())
            file.delete();
        if (file.getParentFile() != null)
            file.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(classData);
        fos.flush();
        fos.close();
    }
}