Example usage for org.objectweb.asm Opcodes F_FULL

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

Introduction

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

Prototype

int F_FULL

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

Click Source Link

Document

A compressed frame with complete frame data.

Usage

From source file:blockphysics.asm.BPTransformer.java

License:Open Source License

private byte[] transformBlockPhysics(byte[] bytes) {
    /*try//  ww w.  j  av  a 2s  .  c  o  m
    {
        FileOutputStream fos = new FileOutputStream("d:/BlockPhysics.orig.class");
        fos.write(bytes);
      fos.close();
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/

    try {
        Class.forName("org.bukkit.Bukkit");
        System.out.println("[BlockPhysics] Bukkit detected.");
    } catch (ClassNotFoundException e) {
        return bytes;
    }

    System.out.print("[BlockPhysics] Patching BlockPhysics.class ............");

    boolean ok = false;
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    MethodNode m;
    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        m = methods.next();
        if (m.name.equals("tickBlocksRandomMove") && m.desc.equals("(Ljr;)V")) {
            m.instructions.clear();
            m.localVariables.clear();

            InsnList toInject = new InsnList();

            toInject.add(new FieldInsnNode(GETSTATIC, "blockphysics/BlockPhysics", "skipMove", "Z"));
            LabelNode l0 = new LabelNode();
            toInject.add(new JumpInsnNode(IFEQ, l0));
            toInject.add(new InsnNode(RETURN));
            toInject.add(l0);
            toInject.add(new FrameNode(Opcodes.F_SAME, 0, null, 0, null));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new FieldInsnNode(GETFIELD, "jr", "G", "Lgnu/trove/map/hash/TLongShortHashMap;"));
            toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "gnu/trove/map/hash/TLongShortHashMap", "iterator",
                    "()Lgnu/trove/iterator/TLongShortIterator;"));
            toInject.add(new VarInsnNode(ASTORE, 1));
            LabelNode l1 = new LabelNode();
            toInject.add(l1);
            toInject.add(new FrameNode(Opcodes.F_APPEND, 1,
                    new Object[] { "gnu/trove/iterator/TLongShortIterator" }, 0, null));
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new MethodInsnNode(INVOKEINTERFACE, "gnu/trove/iterator/TLongShortIterator", "hasNext",
                    "()Z"));
            LabelNode l2 = new LabelNode();
            toInject.add(new JumpInsnNode(IFEQ, l2));
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(new MethodInsnNode(INVOKEINTERFACE, "gnu/trove/iterator/TLongShortIterator", "advance",
                    "()V"));
            toInject.add(new VarInsnNode(ALOAD, 1));
            toInject.add(
                    new MethodInsnNode(INVOKEINTERFACE, "gnu/trove/iterator/TLongShortIterator", "key", "()J"));
            toInject.add(new VarInsnNode(LSTORE, 2));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new InsnNode(POP));
            toInject.add(new VarInsnNode(LLOAD, 2));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "abv", "keyToX", "(J)I"));
            toInject.add(new VarInsnNode(ISTORE, 4));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new InsnNode(POP));
            toInject.add(new VarInsnNode(LLOAD, 2));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "abv", "keyToZ", "(J)I"));
            toInject.add(new VarInsnNode(ISTORE, 5));
            toInject.add(new VarInsnNode(ILOAD, 4));
            toInject.add(new IntInsnNode(BIPUSH, 16));
            toInject.add(new InsnNode(IMUL));
            toInject.add(new VarInsnNode(ISTORE, 6));
            toInject.add(new VarInsnNode(ILOAD, 5));
            toInject.add(new IntInsnNode(BIPUSH, 16));
            toInject.add(new InsnNode(IMUL));
            toInject.add(new VarInsnNode(ISTORE, 7));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new VarInsnNode(ILOAD, 4));
            toInject.add(new VarInsnNode(ILOAD, 5));
            toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "jr", "e", "(II)Ladq;"));
            toInject.add(new VarInsnNode(ASTORE, 8));
            toInject.add(new VarInsnNode(ALOAD, 8));
            toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "adq", "i", "()[Ladr;"));
            toInject.add(new VarInsnNode(ASTORE, 12));
            toInject.add(new VarInsnNode(ALOAD, 12));
            toInject.add(new InsnNode(ARRAYLENGTH));
            toInject.add(new VarInsnNode(ISTORE, 9));
            toInject.add(new InsnNode(ICONST_0));
            toInject.add(new VarInsnNode(ISTORE, 10));
            LabelNode l3 = new LabelNode();
            toInject.add(l3);
            toInject.add(new FrameNode(Opcodes.F_FULL, 12,
                    new Object[] { "jr", "gnu/trove/iterator/TLongShortIterator", Opcodes.LONG, Opcodes.INTEGER,
                            Opcodes.INTEGER, Opcodes.INTEGER, Opcodes.INTEGER, "adq", Opcodes.INTEGER,
                            Opcodes.INTEGER, Opcodes.TOP, "[Ladr;" },
                    0, new Object[] {}));
            toInject.add(new VarInsnNode(ILOAD, 10));
            toInject.add(new VarInsnNode(ILOAD, 9));
            LabelNode l4 = new LabelNode();
            toInject.add(new JumpInsnNode(IF_ICMPGE, l4));
            toInject.add(new VarInsnNode(ALOAD, 12));
            toInject.add(new VarInsnNode(ILOAD, 10));
            toInject.add(new InsnNode(AALOAD));
            toInject.add(new VarInsnNode(ASTORE, 13));
            toInject.add(new VarInsnNode(ALOAD, 13));
            LabelNode l5 = new LabelNode();
            toInject.add(new JumpInsnNode(IFNULL, l5));
            toInject.add(new InsnNode(ICONST_0));
            toInject.add(new VarInsnNode(ISTORE, 14));
            LabelNode l6 = new LabelNode();
            toInject.add(l6);
            toInject.add(new FrameNode(Opcodes.F_APPEND, 2, new Object[] { "adr", Opcodes.INTEGER }, 0, null));
            toInject.add(new VarInsnNode(ILOAD, 14));
            toInject.add(new InsnNode(ICONST_3));
            toInject.add(new JumpInsnNode(IF_ICMPGE, l5));
            toInject.add(new FieldInsnNode(GETSTATIC, "blockphysics/BlockPhysics", "updateLCG", "I"));
            toInject.add(new InsnNode(ICONST_3));
            toInject.add(new InsnNode(IMUL));
            toInject.add(new LdcInsnNode(new Integer(1013904223)));
            toInject.add(new InsnNode(IADD));
            toInject.add(new FieldInsnNode(PUTSTATIC, "blockphysics/BlockPhysics", "updateLCG", "I"));
            toInject.add(new FieldInsnNode(GETSTATIC, "blockphysics/BlockPhysics", "updateLCG", "I"));
            toInject.add(new InsnNode(ICONST_2));
            toInject.add(new InsnNode(ISHR));
            toInject.add(new VarInsnNode(ISTORE, 11));
            toInject.add(new VarInsnNode(ILOAD, 11));
            toInject.add(new IntInsnNode(BIPUSH, 15));
            toInject.add(new InsnNode(IAND));
            toInject.add(new VarInsnNode(ISTORE, 15));
            toInject.add(new VarInsnNode(ILOAD, 11));
            toInject.add(new IntInsnNode(BIPUSH, 8));
            toInject.add(new InsnNode(ISHR));
            toInject.add(new IntInsnNode(BIPUSH, 15));
            toInject.add(new InsnNode(IAND));
            toInject.add(new VarInsnNode(ISTORE, 16));
            toInject.add(new VarInsnNode(ILOAD, 11));
            toInject.add(new IntInsnNode(BIPUSH, 16));
            toInject.add(new InsnNode(ISHR));
            toInject.add(new IntInsnNode(BIPUSH, 15));
            toInject.add(new InsnNode(IAND));
            toInject.add(new VarInsnNode(ISTORE, 17));
            toInject.add(new VarInsnNode(ALOAD, 13));
            toInject.add(new VarInsnNode(ILOAD, 15));
            toInject.add(new VarInsnNode(ILOAD, 17));
            toInject.add(new VarInsnNode(ILOAD, 16));
            toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "adr", "a", "(III)I"));
            toInject.add(new VarInsnNode(ISTORE, 18));
            toInject.add(new VarInsnNode(ALOAD, 13));
            toInject.add(new VarInsnNode(ILOAD, 15));
            toInject.add(new VarInsnNode(ILOAD, 17));
            toInject.add(new VarInsnNode(ILOAD, 16));
            toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "adr", "b", "(III)I"));
            toInject.add(new VarInsnNode(ISTORE, 19));
            toInject.add(new FieldInsnNode(GETSTATIC, "blockphysics/BlockPhysics", "blockSet",
                    "[[Lblockphysics/BlockDef;"));
            toInject.add(new VarInsnNode(ILOAD, 18));
            toInject.add(new InsnNode(AALOAD));
            toInject.add(new VarInsnNode(ILOAD, 19));
            toInject.add(new InsnNode(AALOAD));
            toInject.add(new FieldInsnNode(GETFIELD, "blockphysics/BlockDef", "randomtick", "Z"));
            LabelNode l7 = new LabelNode();
            toInject.add(new JumpInsnNode(IFEQ, l7));
            toInject.add(new VarInsnNode(ALOAD, 0));
            toInject.add(new VarInsnNode(ILOAD, 15));
            toInject.add(new VarInsnNode(ILOAD, 6));
            toInject.add(new InsnNode(IADD));
            toInject.add(new VarInsnNode(ILOAD, 17));
            toInject.add(new VarInsnNode(ALOAD, 13));
            toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "adr", "d", "()I"));
            toInject.add(new InsnNode(IADD));
            toInject.add(new VarInsnNode(ILOAD, 16));
            toInject.add(new VarInsnNode(ILOAD, 7));
            toInject.add(new InsnNode(IADD));
            toInject.add(new VarInsnNode(ILOAD, 18));
            toInject.add(new VarInsnNode(ILOAD, 19));
            toInject.add(new InsnNode(ICONST_0));
            toInject.add(new MethodInsnNode(INVOKESTATIC, "blockphysics/BlockPhysics", "tryToMove",
                    "(Labv;IIIIIZ)Z"));
            toInject.add(new InsnNode(POP));
            toInject.add(l7);
            toInject.add(new FrameNode(Opcodes.F_FULL, 14,
                    new Object[] { "jr", "gnu/trove/iterator/TLongShortIterator", Opcodes.LONG, Opcodes.INTEGER,
                            Opcodes.INTEGER, Opcodes.INTEGER, Opcodes.INTEGER, "adq", Opcodes.INTEGER,
                            Opcodes.INTEGER, Opcodes.INTEGER, "[Ladr;", "adr", Opcodes.INTEGER },
                    0, new Object[] {}));
            toInject.add(new IincInsnNode(14, 1));
            toInject.add(new JumpInsnNode(GOTO, l6));
            toInject.add(l5);
            toInject.add(new FrameNode(Opcodes.F_FULL, 12,
                    new Object[] { "jr", "gnu/trove/iterator/TLongShortIterator", Opcodes.LONG, Opcodes.INTEGER,
                            Opcodes.INTEGER, Opcodes.INTEGER, Opcodes.INTEGER, "adq", Opcodes.INTEGER,
                            Opcodes.INTEGER, Opcodes.TOP, "[Ladr;" },
                    0, new Object[] {}));
            toInject.add(new IincInsnNode(10, 1));
            toInject.add(new JumpInsnNode(GOTO, l3));
            toInject.add(l4);
            toInject.add(new FrameNode(Opcodes.F_FULL, 2,
                    new Object[] { "jr", "gnu/trove/iterator/TLongShortIterator" }, 0, new Object[] {}));
            toInject.add(new JumpInsnNode(GOTO, l1));
            toInject.add(l2);
            toInject.add(new FrameNode(Opcodes.F_CHOP, 1, null, 0, null));
            toInject.add(new InsnNode(RETURN));

            m.instructions.add(toInject);

            ok = true;
            break;
        }
    }

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(cw);

    if (ok)
        System.out.println("OK");
    else
        System.out.println("Failed." + ok);

    /*try
    {
       FileOutputStream fos = new FileOutputStream("d:/BlockPhysics.class");
       fos.write(cw.toByteArray());
     fos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/

    return cw.toByteArray();
}

From source file:ch.sourcepond.utils.podescoin.internal.method.ReadObjectEnhancer.java

License:Apache License

protected void catchBlock() {
    visitJumpInsn(GOTO, l5);/*from w w w .j av a  2 s. c  o  m*/
    visitLabel(l2);
    visitFrame(
            Opcodes.F_FULL, 3, new Object[] { inspector.getInternalClassName(),
                    OBJECT_INPUT_STREAM_INTERNAL_NAME, CONTAINER_INTERNAL_NAME },
            1, new Object[] { EXCEPTION_INTERNAL_NAME });

    visitVarInsn(ASTORE, 3);
    visitVarInsn(ALOAD, 3);
    visitInsn(ATHROW);
    visitLabel(l3);
    visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { IO_EXCEPTION_INTERNAL_NAME });
    visitVarInsn(ASTORE, 3);
    visitVarInsn(ALOAD, 3);
    visitInsn(ATHROW);
    visitLabel(l4);
    visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { EXCEPTION_INTERNAL_NAME });
    visitVarInsn(ASTORE, 3);
    visitTypeInsn(NEW, IO_EXCEPTION_INTERNAL_NAME);
    visitInsn(DUP);
    visitVarInsn(ALOAD, 3);
    visitMethodInsn(INVOKEVIRTUAL, EXCEPTION_INTERNAL_NAME, GET_MESSAGE_NAME, GET_MESSAGE_DESC, false);
    visitVarInsn(ALOAD, 3);
    visitMethodInsn(INVOKESPECIAL, IO_EXCEPTION_INTERNAL_NAME, CONSTRUCTOR_NAME, CONSTRUCTOR_DESC, false);
    visitInsn(ATHROW);
    visitLabel(l5);
}

From source file:ch.sourcepond.utils.podescoin.internal.method.WriteObjectEnhancer.java

License:Apache License

@Override
protected void catchBlock() {
    visitJumpInsn(GOTO, l4);//from   w w  w.j  a v  a2s  .c  o  m
    visitLabel(l2);
    visitFrame(
            Opcodes.F_FULL, 3, new Object[] { inspector.getInternalClassName(),
                    OBJECT_OUTPUT_STREAM_INTERNAL_NAME, CONTAINER_INTERNAL_NAME },
            1, new Object[] { IO_EXCEPTION_INTERNAL_NAME });
    visitVarInsn(ASTORE, 3);
    visitVarInsn(ALOAD, 3);
    visitInsn(ATHROW);
    visitLabel(l3);
    visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { EXCEPTION_INTERNAL_NAME });
    visitVarInsn(ASTORE, 3);
    visitTypeInsn(NEW, IO_EXCEPTION_INTERNAL_NAME);
    visitInsn(DUP);
    visitVarInsn(ALOAD, 3);
    visitMethodInsn(INVOKEVIRTUAL, EXCEPTION_INTERNAL_NAME, GET_MESSAGE_NAME, GET_MESSAGE_DESC, false);
    visitVarInsn(ALOAD, 3);
    visitMethodInsn(INVOKESPECIAL, IO_EXCEPTION_INTERNAL_NAME, CONSTRUCTOR_NAME, CONSTRUCTOR_DESC, false);
    visitInsn(ATHROW);
    visitLabel(l4);
}

From source file:com.gargoylesoftware.js.nashorn.internal.ir.debug.NashornTextifier.java

License:Open Source License

@Override
public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack,
        final Object[] stack) {
    final StringBuilder sb = new StringBuilder();
    sb.append("frame ");
    switch (type) {
    case Opcodes.F_NEW:
    case Opcodes.F_FULL:
        sb.append("full [");
        appendFrameTypes(sb, nLocal, local);
        sb.append("] [");
        appendFrameTypes(sb, nStack, stack);
        sb.append(']');
        break;//w  w w. j  a v  a 2 s  . co m
    case Opcodes.F_APPEND:
        sb.append("append [");
        appendFrameTypes(sb, nLocal, local);
        sb.append(']');
        break;
    case Opcodes.F_CHOP:
        sb.append("chop ").append(nLocal);
        break;
    case Opcodes.F_SAME:
        sb.append("same");
        break;
    case Opcodes.F_SAME1:
        sb.append("same1 ");
        appendFrameTypes(sb, 1, stack);
        break;
    default:
        assert false;
        break;
    }
    sb.append('\n');
    sb.append('\n');
    addText(sb);
}

From source file:com.google.code.jconts.instrument.gen.AsyncMethodAdapter.java

License:Apache License

private void checkProlog() {
    // Generate only once (at the beginning)
    if (prologGenerated) {
        return;//  w  w w . j a  va  2 s  .com
    }
    prologGenerated = true;

    // try...catch around the whole body. Should be added last (after all
    // other try..catch blocks).
    // Actually, we are making an assumption that reader will emit
    // visitTryCatchBlock BEFORE generating any bytecode.
    // We cannot call visitTryCatchBlock at the end since it should
    // be called before all its labels are visited (which we generate
    // in this block).
    mv.visitTryCatchBlock(tryLabel, dispatchLabel, catchLabel, null);

    // Goto to table switch dispatcher
    mv.visitJumpInsn(Opcodes.GOTO, dispatchLabel);

    // Wrap the whole original body with try...catch that will invoke
    // cont.setException(Throwable t)
    mv.visitLabel(tryLabel);

    // Restore the frame as it was before changing method arguments
    Type[] locs = info.entryLocals;
    Object[] frame = new Object[info.isStatic() ? locs.length : locs.length + 1];

    // Frame
    if (!info.isStatic()) {
        frame[0] = info.owner;
    }

    int off = info.isStatic() ? 0 : 1;
    for (int i = 0; i < locs.length; ++i) {
        frame[off + i] = Frames.toFrameType(locs[i]);
    }

    mv.visitFrame(Opcodes.F_FULL, frame.length, frame, 0, new Object[0]);
    Label label = new Label();
    dispatchTable.add(label);
    mv.visitLabel(label);

    if (!info.isStatic()) {
        locals.add(Type.getObjectType(info.owner));
    }
    Collections.addAll(locals, locs);

    // Restore the original method arguments
    // argX = state.varX
    String[] names = info.entryLocalsVars;
    for (int i = 0; i < info.entryLocals.length; ++i) {
        // We go directly to target, introduced var used
        target.visitVarInsn(Opcodes.ALOAD, info.isStatic() ? 0 : 1);
        mv.visitFieldInsn(Opcodes.GETFIELD, info.stateClassName, names[i], info.entryLocals[i].getDescriptor());
        mv.visitVarInsn(info.entryLocals[i].getOpcode(Opcodes.ISTORE), info.isStatic() ? i : i + 1);

    }
}

From source file:com.google.code.jconts.instrument.gen.AsyncMethodAdapter.java

License:Apache License

@Override
public void visitFrame(int type, int nLocal, Object[] locs, int nStack, Object[] stack) {
    if (type == Opcodes.F_NEW) {
        throw new IllegalArgumentException("Expanded frames are not supported!");
    }//w w  w. j  a  v  a2s  .  co m

    mv.visitFrame(type, nLocal, locs, nStack, stack);

    if (type == Opcodes.F_APPEND) {
        for (int i = 0; i < nLocal; ++i) {
            locals.add(Frames.fromFrameType(locs[i]));
        }
    } else if (type == Opcodes.F_CHOP) {
        for (int i = 0; i < nLocal; ++i) {
            locals.remove(locals.size() - 1);
        }
    } else if (type == Opcodes.F_FULL) {
        locals.clear();
        for (int i = 0; i < nLocal; ++i) {
            locals.add(Frames.fromFrameType(locs[i]));
        }
    }
}

From source file:com.google.code.jconts.instrument.util.IntroduceLocalsAdapter.java

License:Apache License

@Override
public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
    if (type == Opcodes.F_FULL) {
        // FIXME:.... utils...
        Object[] newLocal = new Object[local.length + extraLocals.length];

        int off = 0;
        if (!isStatic) {
            newLocal[0] = local[0];//w  w w .j a  v a 2 s . c om
            off = 1;
        }
        System.arraycopy(extraLocals, 0, newLocal, off, extraLocals.length);
        System.arraycopy(local, off, newLocal, extraLocals.length + off, local.length - off);

        super.visitFrame(Opcodes.F_FULL, newLocal.length, newLocal, nStack, stack);
    } else {
        super.visitFrame(type, nLocal, local, nStack, stack);
    }
}

From source file:com.google.devtools.build.android.desugar.BytecodeTypeInference.java

License:Open Source License

@Override
public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
    switch (type) {
    case Opcodes.F_NEW:
        // Expanded form.
        previousFrame = FrameInfo.create(convertTypesInStackMapFrame(nLocal, local),
                convertTypesInStackMapFrame(nStack, stack));
        break;/*from  w  w  w  .j  a v a2 s .  co m*/
    case Opcodes.F_SAME:
        // This frame type indicates that the frame has exactly the same local variables as the
        // previous frame and that the operand stack is empty.
        previousFrame = FrameInfo.create(previousFrame.locals(), ImmutableList.of());
        break;
    case Opcodes.F_SAME1:
        // This frame type indicates that the frame has exactly the same local variables as the
        // previous frame and that the operand stack has one entry.
        previousFrame = FrameInfo.create(previousFrame.locals(), convertTypesInStackMapFrame(nStack, stack));
        break;
    case Opcodes.F_APPEND:
        // This frame type indicates that the frame has the same locals as the previous frame except
        // that k additional locals are defined, and that the operand stack is empty.
        previousFrame = FrameInfo.create(appendArrayToList(previousFrame.locals(), nLocal, local),
                ImmutableList.of());
        break;
    case Opcodes.F_CHOP:
        // This frame type indicates that the frame has the same local variables as the previous
        // frame except that the last k local variables are absent, and that the operand stack is
        // empty.
        previousFrame = FrameInfo.create(removeBackFromList(previousFrame.locals(), nLocal),
                ImmutableList.of());
        break;
    case Opcodes.F_FULL:
        previousFrame = FrameInfo.create(convertTypesInStackMapFrame(nLocal, local),
                convertTypesInStackMapFrame(nStack, stack));
        break;
    default:
        // continue below
    }
    // Update types for operand stack and local variables.
    operandStack.clear();
    operandStack.addAll(previousFrame.stack());
    localVariableSlots.clear();
    localVariableSlots.addAll(previousFrame.locals());
    super.visitFrame(type, nLocal, local, nStack, stack);
}

From source file:com.khubla.jvmbasic.jvmbasicc.JVMBasicCompiler.java

License:Open Source License

/**
 * generate void main(String[])//from  w  w w .ja v  a  2s. co  m
 * <p>
 * <code>
 * public static void main(String[] args) {
 *   ExampleProgram exampleProgram = new ExampleProgram();
 *  try {
 *       exampleProgram.inputStream = System.in;
 *       exampleProgram.outputStream = System.out;
 *       exampleProgram.program();
 *   } catch (Exception e) {
 *       e.printStackTrace();
 *    }
 *  }
 * </code>
 * </p>
 */
protected void generateMain(String classname, ClassWriter classWriter) throws Exception {
    try {
        /*
         * make method
         */
        final MethodVisitor methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC,
                "main", "([Ljava/lang/String;)V", null, null);
        methodVisitor.visitCode();
        final Label l0 = new Label();
        final Label l1 = new Label();
        final Label l2 = new Label();
        methodVisitor.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception");
        final Label l3 = new Label();
        methodVisitor.visitLabel(l3);
        /*
         * declare a local instance of the class in the void() main, store as variable 1.
         */
        methodVisitor.visitTypeInsn(Opcodes.NEW, classname);
        methodVisitor.visitInsn(Opcodes.DUP);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, classname, "<init>", "()V");
        methodVisitor.visitVarInsn(Opcodes.ASTORE, 1);
        /*
         * assign the input stream
         */
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "in", "Ljava/io/InputStream;");
        methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classname, "inputStream", "Ljava/io/InputStream;");
        /*
         * assign the output stream
         */
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classname, "outputStream", "Ljava/io/PrintStream;");
        /*
         * load the class instance from variable 1 and call "program"
         */
        methodVisitor.visitLabel(l0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classname, "program", "()V");
        methodVisitor.visitLabel(l1);
        final Label l4 = new Label();
        methodVisitor.visitJumpInsn(Opcodes.GOTO, l4);
        methodVisitor.visitLabel(l2);
        methodVisitor.visitFrame(Opcodes.F_FULL, 2, new Object[] { "[Ljava/lang/String;", classname }, 1,
                new Object[] { "java/lang/Exception" });
        methodVisitor.visitVarInsn(Opcodes.ASTORE, 2);
        final Label l5 = new Label();
        methodVisitor.visitLabel(l5);
        methodVisitor.visitLineNumber(21, l5);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Exception", "printStackTrace", "()V");
        /*
         * return
         */
        methodVisitor.visitLabel(l4);
        methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
        methodVisitor.visitInsn(Opcodes.RETURN);
        /*
         * declare the parameters
         */
        final Label l6 = new Label();
        methodVisitor.visitLabel(l6);
        methodVisitor.visitLocalVariable("args", "[Ljava/lang/String;", null, l3, l6, 0);
        methodVisitor.visitLocalVariable("exampleProgram", "L" + classname + ";", null, l0, l6, 1);
        methodVisitor.visitLocalVariable("e", "Ljava/lang/Exception;", null, l5, l4, 2);
        /*
         * done
         */
        methodVisitor.visitMaxs(2, 3);
        methodVisitor.visitEnd();
    } catch (final Exception e) {
        throw new Exception("Exception in generateMain", e);
    }
}

From source file:com.sixrr.metrics.profile.instanceHolder.MetricInstanceHolder.java

License:Apache License

private void loadMetricsFromProviders() {
    for (MetricProvider provider : MetricProvider.EXTENSION_POINT_NAME.getExtensions()) {
        final List<Class<? extends Metric>> classesForProvider = provider.getMetricClasses();

        for (Class<? extends Metric> aClass : classesForProvider) {
            try {
                myMetricInstances.put(aClass.getName(), aClass.newInstance());
            } catch (InstantiationException e) {
                MetricInstanceHolder.LOGGER.error(e);
            } catch (IllegalAccessException e) {
                MetricInstanceHolder.LOGGER.error(e);
            }// ww w  .j  a  v a2 s  .  c om
        }
    }

    for (Metric metric : Metric.EP_NAME.getExtensions()) {
        myMetricInstances.put(metric.getClass().getName(), metric);
    }

    // add some magic
    // in Profiles it stored by ClassName. Line Of code is can be handle without new metrics, need only extends  LinesOfCodeProjectMetric with
    // new name
    for (LineOfCodeFileTypeProviderEP ep : LineOfCodeFileTypeProviderEP.EP_NAME.getExtensions()) {
        FileType fileTypeByFileName = FileTypeRegistry.getInstance().findFileTypeByName(ep.fileType);

        if (fileTypeByFileName == null) {
            LOGGER.error("File type is unknown: " + ep.fileType);
            fileTypeByFileName = PlainTextFileType.INSTANCE;
        }
        String lineOfCodeClass = Type.getInternalName(LinesOfCodeProjectMetric.class);
        String className = lineOfCodeClass + "$" + ep.fileType;

        ClassWriter writer = new ClassWriter(Opcodes.F_FULL);
        writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, className, null, lineOfCodeClass, null);

        String desc = Type.getConstructorDescriptor(LinesOfCodeProjectMetric.class.getConstructors()[0]);
        MethodVisitor methodVisitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", desc, null, null);

        methodVisitor.visitMaxs(2, 2);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, lineOfCodeClass, "<init>", desc);
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitEnd();
        writer.visitEnd();

        Class<?> aClass = defineClass(className.replace("/", "."), writer.toByteArray());

        try {
            myMetricInstances.put(aClass.getName(),
                    (Metric) aClass.getConstructors()[0].newInstance(fileTypeByFileName));
        } catch (InstantiationException e) {
            LOGGER.error(e);
        } catch (IllegalAccessException e) {
            LOGGER.error(e);
        } catch (InvocationTargetException e) {
            LOGGER.error(e);
        }
    }
}