Example usage for org.objectweb.asm Opcodes DUP

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

Introduction

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

Prototype

int DUP

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

Click Source Link

Usage

From source file:lombok.patcher.MethodLogistics.java

License:Open Source License

/**
 * Generates an instruction to duplicate an object on the stack. The object is of the stated type, in JVM typespec, so
 * {@code I} refers to an integer, and {@code Ljava/lang/Object;} would refer to an object.
 * //  w w w  . j  av a2 s  .  co m
 * @param type A type spec in JVM format.
 * @param mv This visitor will be given the call to visit DUP2, DUP, or nothing dependent on the type name.
 */
public static void generateDupForType(String type, MethodVisitor mv) {
    switch (sizeOf(type)) {
    default:
    case 1:
        mv.visitInsn(Opcodes.DUP);
        break;
    case 2:
        mv.visitInsn(Opcodes.DUP2);
        break;
    case 0:
        //Do nothing
        break;
    }
}

From source file:net.lyonlancer5.mcmp.karasu.asm.KarasuTransformer.java

License:Apache License

private static void transformEntityLivingBase(ClassNode classNode) {
    Constants.LOGGER.info("======== Project Karasu ~ Water Walking Enchantment Patch ========");
    Constants.LOGGER.info("Patching net.minecraft.entity.EntityLivingBase");

    for (MethodNode method : classNode.methods) {
        if (method.desc.equals("(FF)V")) {

            AbstractInsnNode movefNode = null;
            AbstractInsnNode motionxNode = null;
            AbstractInsnNode motionzNode = null;
            AbstractInsnNode motionyNode = null;
            AbstractInsnNode[] moveList = method.instructions.toArray();
            int var11 = moveList.length;

            for (int var12 = 0; var12 < var11; ++var12) {
                AbstractInsnNode instruction = moveList[var12];
                if (instruction.getOpcode() == Opcodes.ALOAD) {
                    if (((VarInsnNode) instruction).var == 0 && instruction.getNext().getOpcode() == Opcodes.DUP
                            && motionxNode == null) {
                        motionxNode = instruction;
                    } else if (((VarInsnNode) instruction).var == 0
                            && instruction.getNext().getOpcode() == Opcodes.DUP && motionyNode == null) {
                        motionyNode = instruction;
                    } else if (((VarInsnNode) instruction).var == 0
                            && instruction.getNext().getOpcode() == Opcodes.DUP && motionzNode == null) {
                        motionzNode = instruction;
                    } else if (movefNode == null && ((VarInsnNode) instruction).var == 0
                            && instruction.getNext().getOpcode() == Opcodes.FLOAD
                            && ((VarInsnNode) instruction.getNext()).var == 1) {
                        movefNode = instruction;
                    }//from  w  w w  .jav  a 2  s .c om
                }
            }

            int var14;
            InsnList var15;

            if (method.name.equals("e")) {
                Constants.LOGGER.info("Found matching method: " + method.name + " " + method.desc + " - (Obf)");
                if (motionxNode != null) {
                    for (var14 = 0; var14 < 6; ++var14) {
                        motionxNode = motionxNode.getNext();
                        method.instructions.remove(motionxNode.getPrevious());
                    }
                    Constants.LOGGER.info("Patching sv.w");
                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new InsnNode(Opcodes.DUP));
                    var15.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/entity/EntityLivingBase", "w",
                            "D"));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyHorizontalVel",
                            "()D", false));
                    var15.add(new InsnNode(Opcodes.DMUL));
                    var15.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/entity/EntityLivingBase", "w",
                            "D"));
                    method.instructions.insertBefore(motionxNode, var15);
                    Constants.LOGGER.info("Patched sv.w");
                }

                if (motionzNode != null) {
                    for (var14 = 0; var14 < 6; ++var14) {
                        motionzNode = motionzNode.getNext();
                        method.instructions.remove(motionzNode.getPrevious());
                    }

                    Constants.LOGGER.info("Patching sv.y");
                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new InsnNode(Opcodes.DUP));
                    var15.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/entity/EntityLivingBase", "y",
                            "D"));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyHorizontalVel",
                            "()D", false));
                    var15.add(new InsnNode(Opcodes.DMUL));
                    var15.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/entity/EntityLivingBase", "y",
                            "D"));
                    method.instructions.insertBefore(motionzNode, var15);
                    Constants.LOGGER.info("Patched sv.y");
                }

                if (movefNode != null) {
                    for (var14 = 0; var14 < 14; ++var14) {
                        movefNode = movefNode.getNext();
                        method.instructions.remove(movefNode.getPrevious());
                    }

                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new VarInsnNode(Opcodes.FLOAD, 1));
                    var15.add(new VarInsnNode(Opcodes.FLOAD, 2));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyVerticalVel", "()F",
                            false));
                    var15.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "net/minecraft/entity/EntityLivingBase",
                            "a", "(FFF)V", false));
                    method.instructions.insertBefore(movefNode, var15);
                    Constants.LOGGER.info("Patching method -- sv.a (FFF)V");
                }

                Constants.LOGGER.info("Patch success!");
                return;
            } else if (method.name.equals("moveEntityWithHeading")) {
                Constants.LOGGER
                        .info("Found matching method: " + method.name + " " + method.desc + " - (Deobf)");
                if (motionxNode != null) {
                    for (var14 = 0; var14 < 6; ++var14) {
                        motionxNode = motionxNode.getNext();
                        method.instructions.remove(motionxNode.getPrevious());
                    }

                    Constants.LOGGER.info("Patching EntityLivingBase.motionX");
                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new InsnNode(Opcodes.DUP));
                    var15.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/entity/EntityLivingBase",
                            "motionX", "D"));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyHorizontalVel",
                            "()D", false));
                    var15.add(new InsnNode(Opcodes.DMUL));
                    var15.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/entity/EntityLivingBase",
                            "motionX", "D"));
                    method.instructions.insertBefore(motionxNode, var15);
                    Constants.LOGGER.info("Patched EntityLivingBase.motionX");
                }

                if (motionzNode != null) {
                    for (var14 = 0; var14 < 6; ++var14) {
                        motionzNode = motionzNode.getNext();
                        method.instructions.remove(motionzNode.getPrevious());
                    }

                    Constants.LOGGER.info("Patching EntityLivingBase.motionZ");
                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new InsnNode(Opcodes.DUP));
                    var15.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/entity/EntityLivingBase",
                            "motionZ", "D"));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyHorizontalVel",
                            "()D", false));
                    var15.add(new InsnNode(Opcodes.DMUL));
                    var15.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/entity/EntityLivingBase",
                            "motionZ", "D"));
                    method.instructions.insertBefore(motionzNode, var15);
                    Constants.LOGGER.info("Patched EntityLivingBase.motionZ");
                }

                if (movefNode != null) {
                    for (var14 = 0; var14 < 14; ++var14) {
                        movefNode = movefNode.getNext();
                        method.instructions.remove(movefNode.getPrevious());
                    }

                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new VarInsnNode(Opcodes.FLOAD, 1));
                    var15.add(new VarInsnNode(Opcodes.FLOAD, 2));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyVerticalVel", "()F",
                            false));
                    var15.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "net/minecraft/entity/EntityLivingBase",
                            "moveFlying", "(FFF)V", false));
                    method.instructions.insertBefore(movefNode, var15);
                    Constants.LOGGER.info("Patched method - EntityLivingBase.moveFlying (FFF)V");
                }

                Constants.LOGGER.info("Patch success!");
                return;
            } else if (method.name.equals("func_70612_e")) {
                Constants.LOGGER.info("Found matching method: " + method.name + " " + method.desc + " - (srg)");
                if (motionxNode != null) {
                    for (var14 = 0; var14 < 6; ++var14) {
                        motionxNode = motionxNode.getNext();
                        method.instructions.remove(motionxNode.getPrevious());
                    }

                    Constants.LOGGER.info("Patching EntityLivingBase.field_70159_w");
                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new InsnNode(Opcodes.DUP));
                    var15.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/entity/EntityLivingBase",
                            "field_70159_w", "D"));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyHorizontalVel",
                            "()D", false));
                    var15.add(new InsnNode(Opcodes.DMUL));
                    var15.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/entity/EntityLivingBase",
                            "field_70159_w", "D"));
                    method.instructions.insertBefore(motionxNode, var15);
                    Constants.LOGGER.info("Patched EntityLivingBase.field_70159_w");
                }

                if (motionzNode != null) {
                    for (var14 = 0; var14 < 6; ++var14) {
                        motionzNode = motionzNode.getNext();
                        method.instructions.remove(motionzNode.getPrevious());
                    }

                    Constants.LOGGER.info("Patching EntityLivingBase.field_70179_y");
                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new InsnNode(Opcodes.DUP));
                    var15.add(new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/entity/EntityLivingBase",
                            "field_70179_y", "D"));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyHorizontalVel",
                            "()D", false));
                    var15.add(new InsnNode(Opcodes.DMUL));
                    var15.add(new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/entity/EntityLivingBase",
                            "field_70179_y", "D"));
                    method.instructions.insertBefore(motionzNode, var15);
                    Constants.LOGGER.info("Patched EntityLivingBase.field_70179_y");
                }

                if (movefNode != null) {
                    for (var14 = 0; var14 < 14; ++var14) {
                        movefNode = movefNode.getNext();
                        method.instructions.remove(movefNode.getPrevious());
                    }

                    var15 = new InsnList();
                    var15.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    var15.add(new VarInsnNode(Opcodes.FLOAD, 1));
                    var15.add(new VarInsnNode(Opcodes.FLOAD, 2));
                    var15.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                            "net/lyonlancer5/mcmp/karasu/asm/KarasuFeatherMetadata", "modifyVerticalVel", "()F",
                            false));
                    var15.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "net/minecraft/entity/EntityLivingBase",
                            "func_70060_a", "(FFF)V", false));
                    method.instructions.insertBefore(movefNode, var15);
                    Constants.LOGGER.info("Patched method - EntityLivingBase.func_70060_a (FFF)V");
                }

                Constants.LOGGER.info("Patch success!");
                return;
            }
        }
    }
    // #OVERKILL
    throw new RuntimeException("Patch FAILED -- No matching method found");

}

From source file:net.orfjackal.retrolambda.requirenonnull.RequireNonNull.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    MethodVisitor next = super.visitMethod(access, name, desc, signature, exceptions);
    return new MethodVisitor(Opcodes.ASM5, next) {
        @Override// ww  w. j a  v a2s .  co m
        public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
            if (opcode == Opcodes.INVOKESTATIC && owner.equals("java/util/Objects")
                    && name.equals("requireNonNull") && desc.equals("(Ljava/lang/Object;)Ljava/lang/Object;")) {
                super.visitInsn(Opcodes.DUP);
                super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Object", "getClass",
                        "()Ljava/lang/Class;", false);
                super.visitInsn(Opcodes.POP);
            } else {
                super.visitMethodInsn(opcode, owner, name, desc, itf);
            }
        }
    };
}

From source file:net.sourceforge.cobertura.instrument.pass3.AbstractCodeProvider.java

License:GNU General Public License

/**
 * {@inheritDoc}<br/><br/>/*from www .j  av  a2  s  .c o m*/
 * <p/>
 * Generates method (named  {@link #COBERTURA_CLASSMAP_METHOD_NAME}) with such a signature:
 * __cobertura_classmap( {@link LightClassmapListener} listener).</br>
 * <p/>
 * The method informs the listener about all lines, jumps and switches found, and about all counters tracking
 * the constructions.
 */
public void generateCoberturaClassMapMethod(ClassVisitor cv, ClassMap classMap) {

    LinkedList<TouchPointDescriptor> touchPointDescriptors = new LinkedList<TouchPointDescriptor>(
            classMap.getTouchPointsInLineOrder());
    int parts = 0;
    for (int j = 0; touchPointDescriptors.size() > 0; j++) {
        List<TouchPointDescriptor> bufor = new LinkedList<TouchPointDescriptor>();
        for (int i = 0; i < 1000 && touchPointDescriptors.size() > 0; i++) {
            bufor.add(touchPointDescriptors.removeFirst());
        }
        classMapContent(cv, j, bufor);
        parts++;
    }

    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, COBERTURA_CLASSMAP_METHOD_NAME,
            "(" + Type.getType(LightClassmapListener.class).toString() + ")V", null, null);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);

    mv.visitInsn(Opcodes.DUP);
    mv.visitLdcInsn(classMap.getClassName());
    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "setClazz",
            "(Ljava/lang/String;)V");

    if (classMap.getSource() != null) {
        mv.visitInsn(Opcodes.DUP);
        mv.visitLdcInsn(classMap.getSource());
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "setSource",
                "(Ljava/lang/String;)V");
    }

    for (int i = 0; i < parts; i++) {
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, classMap.getClassName(),
                COBERTURA_CLASSMAP_METHOD_NAME + "_" + i,
                "(" + Type.getType(LightClassmapListener.class).toString() + ")V");
    }

    mv.visitInsn(Opcodes.POP);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(0, 0);//will be recalculated by writer
    mv.visitEnd();
}

From source file:net.sourceforge.cobertura.instrument.pass3.AbstractCodeProvider.java

License:GNU General Public License

private void classMapContent(ClassVisitor cv, int nr, List<TouchPointDescriptor> touchPointDescriptors) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            COBERTURA_CLASSMAP_METHOD_NAME + "_" + nr,
            "(" + Type.getType(LightClassmapListener.class).toString() + ")V", null, null);
    mv.visitCode();//from  w ww . ja v  a  2s .c  o  m
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    for (TouchPointDescriptor tpd : touchPointDescriptors) {
        mv.visitInsn(Opcodes.DUP);
        mv.visitLdcInsn(tpd.getLineNumber());
        if (tpd instanceof LineTouchPointDescriptor) {
            mv.visitLdcInsn(((LineTouchPointDescriptor) tpd).getCounterId());
            mv.visitLdcInsn(((LineTouchPointDescriptor) tpd).getMethodName());
            mv.visitLdcInsn(((LineTouchPointDescriptor) tpd).getMethodSignature());
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "putLineTouchPoint",
                    "(IILjava/lang/String;Ljava/lang/String;)V");
        } else if (tpd instanceof JumpTouchPointDescriptor) {
            mv.visitLdcInsn(((JumpTouchPointDescriptor) tpd).getCounterIdForTrue());
            mv.visitLdcInsn(((JumpTouchPointDescriptor) tpd).getCounterIdForFalse());
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "putJumpTouchPoint",
                    "(III)V");
        } else if (tpd instanceof SwitchTouchPointDescriptor) {
            SwitchTouchPointDescriptor stpd = (SwitchTouchPointDescriptor) tpd;
            final String enum_sign = ((SwitchTouchPointDescriptor) tpd).getEnumType();
            if (enum_sign == null) {
                mv.visitLdcInsn(Integer.MAX_VALUE);
            } else {
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, enum_sign, "values", "()[L" + enum_sign + ";");
                mv.visitInsn(Opcodes.ARRAYLENGTH);
            }
            Collection<Integer> ci = stpd.getCountersForLabels();
            mv.visitLdcInsn(ci.size());//Size of a new table
            mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
            int i = 0;
            for (Integer counterId : ci) {
                mv.visitInsn(Opcodes.DUP); //First for addition of items, second ad putSwitchTouchPoint parameter (or next loop iteration)
                mv.visitLdcInsn(i);
                mv.visitLdcInsn(counterId);
                mv.visitInsn(Opcodes.IASTORE);
                i++;
            }
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "putSwitchTouchPoint",
                    "(II[I)V");
        }
    }
    mv.visitInsn(Opcodes.POP);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(0, 0);//will be recalculated by writer
    mv.visitEnd();
}

From source file:net.sourceforge.cobertura.instrument.pass3.AtomicArrayCodeProvider.java

License:GNU General Public License

public void generateCINITmethod(MethodVisitor mv, String className, int counters_cnt) {
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    Label l1 = new Label();
    mv.visitJumpInsn(Opcodes.IFNONNULL, l1);

    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(AtomicIntegerArray.class));
    mv.visitInsn(Opcodes.DUP);
    mv.visitLdcInsn(counters_cnt);// www . ja va2s  . c om
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(AtomicIntegerArray.class), "<init>", "(I)V");
    mv.visitFieldInsn(Opcodes.PUTSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    generateRegisterClass(mv, className);
    mv.visitLabel(l1);
}

From source file:net.yrom.tools.WriteStyleablesProcessor.java

License:Apache License

private void writeClinit(ClassWriter writer) {
    Map<String, int[]> styleables = symbols.getStyleables();
    MethodVisitor clinit = writer.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
    clinit.visitCode();/*  w ww  .  ja v  a 2 s.  c o m*/

    for (Map.Entry<String, int[]> entry : styleables.entrySet()) {
        final String field = entry.getKey();
        final int[] value = entry.getValue();
        final int length = value.length;
        pushInt(clinit, length);
        clinit.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
        for (int i = 0; i < length; i++) {
            clinit.visitInsn(Opcodes.DUP); // dup
            pushInt(clinit, i);
            pushInt(clinit, value[i]);
            clinit.visitInsn(Opcodes.IASTORE); // iastore
        }
        clinit.visitFieldInsn(Opcodes.PUTSTATIC, RSymbols.R_STYLEABLES_CLASS_NAME, field, "[I");
    }
    clinit.visitInsn(Opcodes.RETURN);
    clinit.visitMaxs(0, 0); // auto compute
    clinit.visitEnd();
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Creates and loads the actor's proxy class.
 * @param actorClass the Actor class/* w w w .  j  av a 2  s. c  o  m*/
 * @param acd the actor's class descriptor
 * @throws ConfigurationException if the agent is not configured correctly
 */
@SuppressWarnings("unchecked")
private static Class<?> generateProxyClass(Class<?> actorClass, final ActorClassDescriptor acd)
        throws NoSuchMethodException {
    BeanClassDescriptor bcd = acd.getBeanClassDescriptor();

    String className = String.format("%s__ACTORPROXY", actorClass.getName());
    final String classNameInternal = className.replace('.', '/');
    String classNameDescriptor = "L" + classNameInternal + ";";

    final Type actorState = Type
            .getType(acd.getConcurrencyModel().isMultiThreadingCapable() ? MultiThreadedActorState.class
                    : SingleThreadedActorState.class);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, Type.getInternalName(actorClass),
            new String[] { "org/actorsguildframework/internal/ActorProxy" });

    cw.visitSource(null, null);

    {
        for (int i = 0; i < acd.getMessageCount(); i++)
            cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;",
                    "Lorg/actorsguildframework/internal/MessageCaller<*>;", null).visitEnd();

        cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "actorState__ACTORPROXY",
                actorState.getDescriptor(), null, null).visitEnd();
    }

    BeanCreator.writePropFields(bcd, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();

        for (int i = 0; i < acd.getMessageCount(); i++) {
            Class<?> caller = createMessageCaller(acd.getMessage(i).getOwnerClass(),
                    acd.getMessage(i).getMethod());
            String mcName = Type.getInternalName(caller);
            mv.visitTypeInsn(Opcodes.NEW, mcName);
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mcName, "<init>", "()V");
            mv.visitFieldInsn(Opcodes.PUTSTATIC, classNameInternal,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;");
        }
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    BeanCreator.writeConstructor(actorClass, bcd, classNameInternal, cw, new BeanCreator.SnippetWriter() {
        @Override
        public void write(MethodVisitor mv) {
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitTypeInsn(Opcodes.NEW, actorState.getInternalName());
            mv.visitInsn(Opcodes.DUP);
            mv.visitVarInsn(Opcodes.ALOAD, 1);
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, actorState.getInternalName(), "<init>",
                    "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Actor;)V");
            mv.visitFieldInsn(Opcodes.PUTFIELD, classNameInternal, "actorState__ACTORPROXY",
                    actorState.getDescriptor());
        }
    });

    BeanCreator.writePropAccessors(bcd, classNameInternal, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getState__ACTORPROXYMETHOD",
                "()Lorg/actorsguildframework/internal/ActorState;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    for (int i = 0; i < acd.getMessageCount(); i++) {
        MessageImplDescriptor mid = acd.getMessage(i);
        Method method = mid.getMethod();
        String simpleDescriptor = Type.getMethodDescriptor(method);
        String genericSignature = GenericTypeHelper.getSignature(method);

        writeProxyMethod(classNameInternal, classNameDescriptor, cw, i, actorState, acd.getConcurrencyModel(),
                mid, method, simpleDescriptor, genericSignature);

        writeSuperProxyMethod(actorClass, classNameDescriptor, cw, method, simpleDescriptor, genericSignature,
                !acd.getConcurrencyModel().isMultiThreadingCapable());
    }

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNCHRONIZED, "toString", "()Ljava/lang/String;",
                null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    try {
        return (Class<? extends ActorProxy>) GenerationUtils.loadClass(className, cw.toByteArray());
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading ActorProxy", e);
    }
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Writes a proxy method for messages.//from   w w  w  .  j  a v  a2 s .  co m
 * @param classNameInternal the internal class name
 * @param classNameDescriptor the class name descriptor
 * @param cw the ClassWriter
 * @param index the message index
 * @param type the ActorState type to use
 * @param concurrencyModel the concurrency model of the message
 * @param messageDescriptor the message's descriptor
 * @param method the method to override
 * @param simpleDescriptor a simple descriptor of the message
 * @param genericSignature the signature of the message
 */
private static void writeProxyMethod(String classNameInternal, String classNameDescriptor, ClassWriter cw,
        int index, Type actorState, ConcurrencyModel concurrencyModel, MessageImplDescriptor messageDescriptor,
        Method method, String simpleDescriptor, String genericSignature) throws NoSuchMethodException {
    MethodVisitor mv;
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), simpleDescriptor, genericSignature, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitIntInsn(Opcodes.BIPUSH, method.getParameterTypes().length);
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
        for (int j = 0; j < method.getParameterTypes().length; j++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.BIPUSH, j);
            Class<?> paraType = method.getParameterTypes()[j];
            if (paraType.isPrimitive()) {
                String wrapperClass = GenerationUtils.getWrapperInternalName(paraType);
                Type primType = Type.getType(paraType);
                mv.visitVarInsn(primType.getOpcode(Opcodes.ILOAD), j + 1);
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, wrapperClass, "valueOf",
                        "(" + primType.getDescriptor() + ")" + "L" + wrapperClass + ";");
            } else if (isArgumentFreezingRequired(method, j, paraType)) {
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(SerializableFreezer.class),
                        "freeze",
                        Type.getMethodDescriptor(SerializableFreezer.class.getMethod("freeze", Object.class)));
            } else if (paraType.isInterface()) {
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);
                mv.visitInsn(Opcodes.DUP);
                mv.visitTypeInsn(Opcodes.INSTANCEOF, "org/actorsguildframework/Actor");
                Label lEndif = new Label();
                mv.visitJumpInsn(Opcodes.IFNE, lEndif);
                mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ActorRuntimeException.class));
                mv.visitInsn(Opcodes.DUP);
                mv.visitLdcInsn(String.format(
                        "Argument %d is an non-Serializable interface, but you did not give an Actor. If a message's argument type is an interface that does not extend Serializable, only Actors are acceptable as argument.",
                        j));
                mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ActorRuntimeException.class),
                        "<init>", "(Ljava/lang/String;)V");
                mv.visitInsn(Opcodes.ATHROW);
                mv.visitLabel(lEndif);
            } else
                mv.visitVarInsn(Opcodes.ALOAD, j + 1);

            mv.visitInsn(Opcodes.AASTORE);
        }
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitVarInsn(Opcodes.ASTORE, method.getParameterTypes().length + 1); // method.getParameterTypes().length+1 ==> 'args' local variable
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitFieldInsn(Opcodes.GETSTATIC, classNameInternal,
                String.format(MESSAGE_CALLER_NAME_FORMAT, index),
                "Lorg/actorsguildframework/internal/MessageCaller;");
        mv.visitFieldInsn(Opcodes.GETSTATIC, "org/actorsguildframework/annotations/ThreadUsage",
                messageDescriptor.getThreadUsage().name(),
                "Lorg/actorsguildframework/annotations/ThreadUsage;");
        mv.visitVarInsn(Opcodes.ALOAD, method.getParameterTypes().length + 1);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, actorState.getInternalName(), "queueMessage",
                "(Lorg/actorsguildframework/internal/MessageCaller;Lorg/actorsguildframework/annotations/ThreadUsage;[Ljava/lang/Object;)Lorg/actorsguildframework/internal/AsyncResultImpl;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l4 = new Label();
        mv.visitLabel(l4);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l4, 0);
        for (int j = 0; j < method.getParameterTypes().length; j++)
            mv.visitLocalVariable("arg" + j, Type.getDescriptor(method.getParameterTypes()[j]),
                    GenericTypeHelper.getSignatureIfGeneric(method.getGenericParameterTypes()[j]), l0, l4,
                    j + 1);
        mv.visitLocalVariable("args", "[Ljava/lang/Object;", null, l1, l4,
                method.getParameterTypes().length + 1);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
}

From source file:org.actorsguildframework.internal.codegenerator.BeanCreator.java

License:Apache License

/**
 * Creates and loads the bean's factory class.
 * @param beanClass the Bean class/*w  w  w  . ja v a2s.c om*/
 * @param generatedBeanClassName the name of the class that this factory will produce
 * @param bcd the bean class descriptor
 * @param synchronizeInitializers true to synchronize the initializer invocations (actors
 *       do this), false otherwise
 * @return the new factory
 */
public static BeanFactory generateFactoryClass(Class<?> beanClass, String generatedBeanClassName,
        BeanClassDescriptor bcd, boolean synchronizeInitializers) {
    String className = String.format("%s__BEANFACTORY", beanClass.getName());
    String classNameInternal = className.replace('.', '/');

    String generatedBeanClassNameInternal = generatedBeanClassName.replace('.', '/');

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, "java/lang/Object",
            new String[] { Type.getInternalName(BeanFactory.class) });

    cw.visitSource(null, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
        mv.visitInsn(Opcodes.RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "createNewInstance",
                "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Props;)Ljava/lang/Object;",
                null, null);
        mv.visitCode();
        final int initCount = bcd.getInitializerCount();
        Label tryStart = new Label();
        Label tryEnd = new Label();
        Label tryFinally = new Label();
        Label tryFinallyEnd = new Label();
        if (synchronizeInitializers && (initCount > 0)) {
            mv.visitTryCatchBlock(tryStart, tryEnd, tryFinally, null);
            mv.visitTryCatchBlock(tryFinally, tryFinallyEnd, tryFinally, null);
        }

        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitTypeInsn(Opcodes.NEW, generatedBeanClassNameInternal);
        mv.visitInsn(Opcodes.DUP);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitVarInsn(Opcodes.ALOAD, 2);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, generatedBeanClassNameInternal, "<init>",
                "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Props;)V");

        if (synchronizeInitializers) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitInsn(Opcodes.MONITORENTER);
            mv.visitLabel(tryStart);
        }

        for (int i = 0; i < initCount; i++) {
            Method m = bcd.getInitializers(i);
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, generatedBeanClassNameInternal, m.getName(),
                    Type.getMethodDescriptor(m));
        }

        if (synchronizeInitializers) {
            if (initCount > 0) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitInsn(Opcodes.MONITOREXIT);
                mv.visitLabel(tryEnd);
                mv.visitJumpInsn(Opcodes.GOTO, tryFinallyEnd);
            }
            mv.visitLabel(tryFinally);
            mv.visitInsn(Opcodes.DUP);
            mv.visitInsn(Opcodes.MONITOREXIT);
            mv.visitLabel(tryFinallyEnd);
        }

        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitLocalVariable("controller", "Lorg/actorsguildframework/internal/Controller;", null, l0, l1, 1);
        mv.visitLocalVariable("props", "Lorg/actorsguildframework/Props;", null, l0, l1, 2);
        mv.visitLocalVariable("synchronizeInitializer", "Z", null, l0, l1, 3);
        mv.visitMaxs(4, 3);
        mv.visitEnd();
    }
    cw.visitEnd();

    Class<?> newClass = GenerationUtils.loadClass(className, cw.toByteArray());
    try {
        return (BeanFactory) newClass.newInstance();
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading ActorProxyFactory", e);
    }
}