Example usage for org.objectweb.asm Opcodes INVOKESTATIC

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

Introduction

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

Prototype

int INVOKESTATIC

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

Click Source Link

Usage

From source file:net.dv8tion.ClassTransformer.java

License:Apache License

/**
 * Helper method to modify the getAllUsernames method in ServerConfigurationManager.
 * Takes into account obfuscated method names based on boolean.
 * //  ww  w . ja v a2 s .c  o m
 * Replaces the call "return astring" at the end of ServerConfigurationManager's
 * getAllUsernames method with "return NameLoader.loadNames(astring)"
 * Because of how The JVM and ByteCode work with arrays, we do not need to
 * remove any instructions, only inject code. The array "astring" in the
 * call "return astring" will be provided as the param for the loadNames method.
 * 
 * @param className
 *            The class name, proceeded by the package it is in, if it is in one.
 * @param classData
 *            The byte code of the class.
 * @param obfuscated
 *            Is the code obfuscated?
 * @return
 *         Returns the modified byte code of the class.
 */
public byte[] patchClassWithASM(String className, byte[] classData, boolean obfuscated) {
    String methodName = obfuscated ? "d" : "getAllUsernames";

    ClassNode classNode = new ClassNode(Opcodes.ASM4);
    ClassReader classReader = new ClassReader(classData);
    classReader.accept(classNode, ClassReader.EXPAND_FRAMES);

    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        MethodNode m = methods.next();
        int arrayReturn_index = -1;

        if ((m.name.equals(methodName) && m.desc.equals("()[Ljava/lang/String;"))) {
            AbstractInsnNode currentNode = null;
            Iterator<AbstractInsnNode> iter = m.instructions.iterator();

            int index = -1;

            while (iter.hasNext()) {
                index++;
                currentNode = iter.next();

                if (currentNode.getOpcode() == Opcodes.ARETURN) {
                    arrayReturn_index = index;
                }
            }

            //Calls NameLoader.loadNames(String[]) 
            m.instructions.insertBefore(m.instructions.get(arrayReturn_index),
                    new MethodInsnNode(Opcodes.INVOKESTATIC, "net/dv8tion/NameLoader", "loadNames",
                            "([Ljava/lang/String;)[Ljava/lang/String;"));

            System.out.println("[IRC NameBridge] Patching Complete!");
            break;
        }
    }
    //ASM specific for cleaning up and returning the final bytes for JVM processing.
    //Use 0 here instead of like ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS because
    //We need to have ASM recalculate things.  
    ClassWriter writer = new ClassWriter(0);
    classNode.accept(writer);
    return writer.toByteArray();
}

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. j  a va  2s . c o m*/
                }
            }

            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/*from  w  ww  .ja  v  a 2s . 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.petercashel.jmsDd.util.ASMTransformer.java

License:Apache License

public static byte[] transform(String name, byte[] bytes) {
    if (debug)/*from  w ww  . j a v a  2  s  .c o m*/
        System.out.println(bytes.length);
    ClassNode classNode = new ClassNode();
    String classNameASM = name.replace('.', '/');
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);
    boolean DoModInit = false;
    boolean HasInit = false;
    String initDesc = "()V";
    boolean lockDesc = false;

    try {
        try {
            for (int i = 0; i < classNode.visibleAnnotations.size(); i++) {
                AnnotationNode ann = (AnnotationNode) classNode.visibleAnnotations.get(i);
                if (ann.desc.equalsIgnoreCase("Lnet/petercashel/jmsDd/module/Module;")) {
                    try {
                        if (debug)
                            System.out.println("ANNOTE!");
                        DoModInit = true;
                        Map<String, Object> values = asmList2Map(ann.values);
                        ModuleSystem.modulesToLoad.put(
                                values.get("ModuleName").toString().replace("[", "").replace("]", ""),
                                classNode.name.replace("/", "."));
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                }
            }
        } catch (Exception e) {
        }

        try {
            if (DoModInit) {

                for (int i = 0; i < classNode.methods.size(); i++) {
                    MethodNode m = (MethodNode) classNode.methods.get(i);
                    if (m.name.contentEquals("<init>")) {
                        initDesc = m.desc;
                        if (m.desc.contentEquals("()V")) {
                            HasInit = true;
                            if (debug)
                                System.out.println("Found <init>");
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (debug)
        System.out.println("Still alive?");
    try {

        //          L0
        //             LINENUMBER 43 L0
        //             ALOAD 0
        //             INVOKESPECIAL // CLASSNAME FOR ASM  // ()V    ////// This is effectically a super() call but to the discovered constructor
        //            L1
        //             LINENUMBER 44 L1
        //             INVOKESTATIC net/petercashel/jmsDd/API/API$Impl.getAPI ()Lnet/petercashel/jmsDd/API/API;
        //             ALOAD 0
        //             INVOKEINTERFACE net/petercashel/jmsDd/API/API.registerEventBus (Ljava/lang/Object;)V
        //            L2
        //             LINENUMBER 46 L2
        //             RETURN
        //            L3
        //             LOCALVARIABLE this // "L" + CLASSNAME FOR ASM + ";" // L0 L3 0
        //             LOCALVARIABLE e Lnet/petercashel/jmsDd/event/module/DummyEvent; L0 L3 1
        //             MAXSTACK = 2
        //             MAXLOCALS = 2
        if (DoModInit) {
            if (HasInit) {
                if (debug)
                    System.out.println("Adding Extra Constructor to " + name);
                MethodNode constructor = new MethodNode(Opcodes.ACC_PUBLIC, "<init>",
                        "(Lnet/petercashel/jmsDd/event/module/DummyEvent;)V", null, null);

                Label L0 = new Label();
                constructor.visitLabel(L0);
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, classNameASM, "<init>", initDesc);

                Label L1 = new Label();
                constructor.visitLabel(L1);
                constructor.visitMethodInsn(Opcodes.INVOKESTATIC, "net/petercashel/jmsDd/API/API$Impl",
                        "getAPI", "()Lnet/petercashel/jmsDd/API/API;");
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                constructor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "net/petercashel/jmsDd/API/API",
                        "registerEventBus", "(Ljava/lang/Object;)V");

                Label L2 = new Label();
                constructor.visitLabel(L2);
                constructor.visitInsn(Opcodes.RETURN);

                Label L3 = new Label();
                constructor.visitLabel(L3);
                constructor.visitLocalVariable("this", "L" + classNameASM + ";", null, L0, L3, 0);
                constructor.visitLocalVariable("e", "Lnet/petercashel/jmsDd/event/module/DummyEvent;", null, L0,
                        L3, 1);
                constructor.visitMaxs(2, 2);
                constructor.visitEnd();
                classNode.methods.add(constructor);

            } else {
                System.err.println("WARNING! " + name
                        + " Doesn't have a default no-args constructor.  Module loader cannot chain load the constructor. \n If you are recieving this error and your module has no constructors defined, or a no-args constructor defined, \n please report the bug to the author of JMSDd.");
                MethodNode constructor = new MethodNode(Opcodes.ACC_PUBLIC, "<init>",
                        "(Lnet/petercashel/jmsDd/event/module/DummyEvent;)V", null, null);

                Label L0 = new Label();
                constructor.visitLabel(L0);
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                //INVOKESPECIAL java/lang/Object.<init> ()V ////// There is no other constructor, call super() to Object.
                constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");

                Label L1 = new Label();
                constructor.visitLabel(L1);
                constructor.visitMethodInsn(Opcodes.INVOKESTATIC, "net/petercashel/jmsDd/API/API$Impl",
                        "getAPI", "()Lnet/petercashel/jmsDd/API/API;");
                constructor.visitVarInsn(Opcodes.ALOAD, 0);
                constructor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "net/petercashel/jmsDd/API/API",
                        "registerEventBus", "(Ljava/lang/Object;)V");

                Label L2 = new Label();
                constructor.visitLabel(L2);
                constructor.visitInsn(Opcodes.RETURN);

                Label L3 = new Label();
                constructor.visitLabel(L3);
                constructor.visitLocalVariable("this", "L" + classNameASM + ";", null, L0, L3, 0);
                constructor.visitLocalVariable("e", "Lnet/petercashel/jmsDd/event/module/DummyEvent;", null, L0,
                        L3, 1);
                constructor.visitMaxs(2, 2);
                constructor.visitEnd();
                classNode.methods.add(constructor);
            }
            classNode.visitEnd();
            ClassWriter wr = new ClassWriter(0);
            classNode.accept(wr);

            bytes = wr.toByteArray();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (debug)
        System.out.println("Still alive.");
    if (debug)
        System.out.println(bytes.length);
    if (plugins.size() > 0) {
        for (ASMPlugin p : plugins) {
            try {
                bytes = p.transform(name, bytes);
            } catch (Exception e) {

            }
        }
    }

    return bytes;
}

From source file:net.roryclaasen.asm.rorysmodcore.transformer.EntityPlayerTransformer.java

License:Apache License

public byte[] patchOnUpdate(String name, byte[] bytes, boolean obfuscated) {
    RMLog.info("[EntityPlayer] [onUpdate] Patching", true);
    String targetMethodName = "";

    if (obfuscated == true)
        targetMethodName = "h";
    else// ww  w .  j a v  a2s .  c o  m
        targetMethodName = "onUpdate";
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        MethodNode method = methods.next();
        int invok_index = -1;
        if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
            AbstractInsnNode currentNode = null;
            AbstractInsnNode targetNode = null;

            Iterator<AbstractInsnNode> iter = method.instructions.iterator();

            int index = -1;

            int GETFIELD_COUNT = 0;
            while (iter.hasNext()) {
                index++;
                currentNode = iter.next();
                if (currentNode.getOpcode() == Opcodes.GETFIELD) {
                    GETFIELD_COUNT++;
                    if (GETFIELD_COUNT == 13) {
                        targetNode = currentNode;
                        invok_index = index;
                        break;
                    }
                }
            }
            if (targetNode == null || invok_index == -1) {
                RMLog.info("[EntityPlayer] Did not find all necessary target nodes! ABANDON CLASS!", true);
                return bytes;
            }
            /*
             * mv.visitLineNumber(305, l19);
             * mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
             * mv.visitVarInsn(ALOAD, 0);
             * -- mv.visitFieldInsn(GETFIELD, "net/minecraft/entity/player/EntityPlayer", "worldObj", "Lnet/minecraft/world/World;");
             * mv.visitFieldInsn(GETFIELD, "net/minecraft/world/World", "isRemote", "Z");
             * Label l21 = new Label();
             * mv.visitJumpInsn(IFNE, l21);
             */
            @SuppressWarnings("unused")
            AbstractInsnNode p1, p2, p3;
            p1 = method.instructions.get(invok_index - 1); // mv.visitVarInsn(ALOAD, 0);
            p2 = method.instructions.get(invok_index); // mv.visitFieldInsn(GETFIELD, "net/minecraft/entity/player/EntityPlayer", "worldObj", "Lnet/minecraft/world/World;");
            p3 = method.instructions.get(invok_index + 1); // mv.visitFieldInsn(GETFIELD, "net/minecraft/world/World", "isRemote", "Z");

            //method.instructions.remove(p1);
            //method.instructions.remove(p2);
            //method.instructions.remove(p3);

            MethodInsnNode m1 = new MethodInsnNode(Opcodes.INVOKESTATIC,
                    "net/roryclaasen/asm/rorysmodcore/transformer/StaticClass", "shouldWakeUp",
                    "(Lnet/minecraft/entity/player/EntityPlayer;)Z", false);

            method.instructions.set(p2, m1);
            method.instructions.remove(p3);
            break;
        }
    }
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
}

From source file:net.roryclaasen.asm.rorysmodcore.transformer.WorldServerTransformer.java

License:Apache License

public byte[] patchWakeAllPlayers(String name, byte[] bytes, boolean obfuscated) {
    RMLog.info("[WorldServer] [wakeAllPlayers] Patching", true);
    String targetMethodName = "";

    if (obfuscated == true)
        targetMethodName = "d";
    else/* w w  w.j a  v a  2s  .c om*/
        targetMethodName = "wakeAllPlayers";

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

    Iterator<MethodNode> methods = classNode.methods.iterator();
    while (methods.hasNext()) {
        MethodNode method = methods.next();
        int invok_index = -1;
        if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
            AbstractInsnNode currentNode = null;
            AbstractInsnNode targetNode = null;

            Iterator<AbstractInsnNode> iter = method.instructions.iterator();
            int index = -1;
            while (iter.hasNext()) {
                index++;
                currentNode = iter.next();
                if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
                    invok_index = index;
                    targetNode = currentNode;
                    break;
                }
            }
            if (targetNode == null || invok_index == -1) {
                RMLog.info("[WorldServer] Did not find all necessary target nodes! ABANDON CLASS!", true);
                return bytes;
            }
            AbstractInsnNode p1 = method.instructions.get(invok_index);
            MethodInsnNode p2 = new MethodInsnNode(Opcodes.INVOKESTATIC,
                    "net/roryclaasen/asm/rorysmodcore/transformer/StaticClass", "shouldWakeUp", "()Z", false);

            method.instructions.set(p1, p2);
            method.instructions.remove(method.instructions.get(invok_index - 1));
            break;
        }
    }
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
}

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

License:GNU General Public License

/**
 * {@inheritDoc}//from  w w w. java  2s  . c  o m
 * <p/>
 * The code injected by this implementation just registers the class using {@link TouchCollector#registerClass(Class)}. This way, during the
 * execution, touch collector knows that is responsible to ask the class after execution about a current status of the counters.
 */
protected void generateRegisterClass(MethodVisitor mv, String className) {
    mv.visitLdcInsn(className);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(TouchCollector.class), "registerClass",
            "(Ljava/lang/String;)V");
}

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

License:GNU General Public License

/**
 * {@inheritDoc}<br/><br/>/*from w  w w .  j  av  a 2s.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();/*ww w . ja  va  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.AbstractCodeProvider.java

License:GNU General Public License

public void generateCallCoberturaInitMethod(MethodVisitor mv, String className) {
    mv.visitCode(); // Since we are using the ASM Check Adapter, we need to visit the code before visiting any instructions.
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, className, COBERTURA_INIT_METHOD_NAME, "()V");
}