Example usage for org.objectweb.asm.tree AbstractInsnNode getOpcode

List of usage examples for org.objectweb.asm.tree AbstractInsnNode getOpcode

Introduction

In this page you can find the example usage for org.objectweb.asm.tree AbstractInsnNode getOpcode.

Prototype

public int getOpcode() 

Source Link

Document

Returns the opcode of this instruction.

Usage

From source file:pxb.android.dex2jar.optimize.c.DexInterpreter.java

License:Apache License

@Override
public Value naryOperation(AbstractInsnNode insn, List values) throws AnalyzerException {
    switch (insn.getOpcode()) {
    case INVOKESTATIC: {
        Type[] args = Type.getArgumentTypes(((MethodInsnNode) insn).desc);
        for (int i = 0; i < args.length; i++) {
            Value v = (Value) values.get(i);
            if (((CBasicValue) v).getType() == null) {
                ((CBasicValue) v).setType(args[i]);
            }//  w  w  w  .  j a va2s .  c  o m
        }
        break;
    }
    case INVOKEDYNAMIC:
    case INVOKEINTERFACE:
    case INVOKESPECIAL:
    case INVOKEVIRTUAL: {
        Type[] args = Type.getArgumentTypes(((MethodInsnNode) insn).desc);
        Value v = (Value) values.get(0);
        if (((CBasicValue) v).getType() == null) {
            ((CBasicValue) v).setType(Type.getType(((MethodInsnNode) insn).owner));
        }
        for (int i = 0; i < args.length; i++) {
            v = (Value) values.get(i + 1);
            if (((CBasicValue) v).getType() == null) {
                ((CBasicValue) v).setType(args[i]);
            }
        }
        break;
    }
    }

    if (insn.getOpcode() == MULTIANEWARRAY) {
        return newValue(Type.getType(((MultiANewArrayInsnNode) insn).desc));
    } else {
        return new CBasicValue(Type.getReturnType(((MethodInsnNode) insn).desc));
    }
}

From source file:pxb.android.dex2jar.optimize.D.java

License:Apache License

private void cut(MethodNode method) {
    InsnList insns = method.instructions;
    method.instructions = null;/*from  w ww  .j  av a2s . c o  m*/
    {
        AbstractInsnNode p = insns.getFirst();
        if (!(p instanceof LabelNode)) {
            insns.insertBefore(p, new LabelNode());
        }
        AbstractInsnNode q = insns.getLast();
        if (!(q instanceof LabelNode)) {
            insns.insert(q, new LabelNode());
        }
    }
    @SuppressWarnings("serial")
    Map<LabelNode, LabelNode> cloneMap = new HashMap<LabelNode, LabelNode>() {
        public LabelNode get(Object key) {

            LabelNode l = super.get(key);
            if (l == null) {
                l = new LabelNode();
                put((LabelNode) key, l);
            }
            return l;
        }
    };
    Map<LabelNode, Block> preBlockMap = new HashMap<LabelNode, Block>();
    int i = 0;
    LabelNode label = null;
    Block block = null;
    List<AbstractInsnNode> currentInsnList = null;
    for (AbstractInsnNode p = insns.getFirst(); p != null; p = p.getNext()) {
        final AbstractInsnNode cp = p.clone(cloneMap);
        switch (cp.getType()) {
        case AbstractInsnNode.LABEL: {
            if (label != null) {
                block = new Block(i++, label);
                block.insns = currentInsnList;
                block.next = (LabelNode) cp;
                addToMap(block);
            }
            currentInsnList = new ArrayList<AbstractInsnNode>();
            label = (LabelNode) cp;
            preBlockMap.put(label, block);
            break;
        }
        case AbstractInsnNode.JUMP_INSN:
        case AbstractInsnNode.LOOKUPSWITCH_INSN:
        case AbstractInsnNode.TABLESWITCH_INSN: {
            if (cp.getOpcode() == GOTO) {
                block = new Block(i++, label);
                block.next = (LabelNode) ((JumpInsnNode) cp).label;
            } else {//
                block = new BranchBlock(i++, label, cp);
                block.next = (LabelNode) getNextLabelNode(p, insns).clone(cloneMap);
            }
            block.insns = currentInsnList;
            addToMap(block);
            currentInsnList = null;
            label = null;
            break;
        }
        case AbstractInsnNode.FRAME:
        case AbstractInsnNode.LINE:
            // ignore
            break;
        default:
            switch (cp.getOpcode()) {
            case IRETURN:
            case LRETURN:
            case FRETURN:
            case DRETURN:
            case ARETURN:
            case RETURN:
            case ATHROW:
                block = new EndBlock(i++, label, cp);
                block.next = null;
                getNextLabelNode(p, insns);
                block.insns = currentInsnList;
                addToMap(block);
                currentInsnList = null;
                label = null;
                break;
            default:
                currentInsnList.add(cp);
            }

        }
    }

    for (Iterator<?> it = method.tryCatchBlocks.iterator(); it.hasNext();) {
        TryCatchBlockNode tcn = (TryCatchBlockNode) it.next();

        Block s = map.get((LabelNode) tcn.start.clone(cloneMap));
        Block e = map.get((LabelNode) tcn.end.clone(cloneMap));
        Block handler = map.get(tcn.handler.clone(cloneMap));
        TcbK key = new TcbK(s, e);

        Map<Block, String> handlers = tcbs.get(key);
        if (handlers == null) {
            handlers = new TreeMap<Block, String>(new Comparator<Block>() {
                @Override
                public int compare(Block o1, Block o2) {
                    return o1.id - o2.id;
                }
            });
            tcbs.put(key, handlers);
        }
        handlers.put(handler, tcn.type);
        tcn.start = s.label;
        tcn.end = e.label;
        tcn.handler = handler.label;
    }
}

From source file:pxb.android.dex2jar.optimize.Util.java

License:Apache License

public static boolean isEnd(AbstractInsnNode p) {
    switch (p.getOpcode()) {
    case ATHROW://  w  w  w .ja v a 2 s.  c  om
    case RETURN:
    case IRETURN:
    case LRETURN:
    case FRETURN:
    case DRETURN:
        return true;
    }
    return false;
}

From source file:rubah.bytecode.transformers.RedirectFieldManipulation.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, final String desc, String signature,
        String[] exceptions) {/*from w  w w. j  av  a  2s . com*/

    final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions);

    if (this.namespace.isBootstrap(this.thisClass))
        return methodVisitor;

    if (this.thisClass.getFqn().startsWith("java.io") || this.thisClass.getFqn().startsWith("sun.reflect")
            || this.thisClass.getFqn().startsWith("sun.misc")
            || this.thisClass.getFqn().startsWith("java.security")
            || this.thisClass.getFqn().startsWith("java.util.concurrent.locks")
            || this.thisClass.getFqn().startsWith("java.util.concurrent.atomic")
            || (this.thisClass.getFqn().startsWith("java.lang")
                    && !this.thisClass.getFqn().equals(Class.class.getName())))
        return methodVisitor;

    if (this.objectsMap != null) {
        Method m = (Method) objectsMap.get(name);

        if (m == null)
            return methodVisitor;

        if (m.getName().startsWith(AddGettersAndSetters.GETTER_PREFFIX)
                || m.getName().startsWith(AddGettersAndSetters.SETTER_PREFFIX))
            return methodVisitor;
    }

    MethodVisitor ret = new MethodNode(ASM5, access, name, desc, signature, exceptions) {
        private Frame<SourceValue>[] sourcesFrames;
        private boolean isStatic = Modifier.isStatic(access);

        @Override
        public void visitEnd() {
            Analyzer<SourceValue> sourceAnalyzer = new Analyzer<SourceValue>(new SourceInterpreter());

            try {
                sourceAnalyzer.analyze(thisClass.getASMType().getInternalName(), this);
            } catch (AnalyzerException e) {
                System.out.println(namespace.isBootstrap(thisClass));
                System.out.println(e.getMessage());
                this.sourcesFrames = sourceAnalyzer.getFrames();
                this.printAnalyzerResult();
                throw new Error(e);
            }

            this.sourcesFrames = sourceAnalyzer.getFrames();

            ListIterator<AbstractInsnNode> iter = this.instructions.iterator();
            HashMap<AbstractInsnNode, InsnList> instructionsToAddBefore = new HashMap<AbstractInsnNode, InsnList>();
            HashMap<AbstractInsnNode, InsnList> instructionsToAddAfter = new HashMap<AbstractInsnNode, InsnList>();
            HashMap<AbstractInsnNode, AbstractInsnNode> instructionsToReplace = new HashMap<AbstractInsnNode, AbstractInsnNode>();

            while (iter.hasNext()) {
                AbstractInsnNode insnNode = iter.next();

                int opcode;
                switch ((opcode = insnNode.getOpcode())) {
                case INVOKESPECIAL: {
                    MethodInsnNode methodNode = (MethodInsnNode) insnNode;

                    int receiverDepth = Type.getArgumentTypes(methodNode.desc).length;

                    if (!this.needsRedirect(insnNode, receiverDepth))
                        continue;

                    for (AbstractInsnNode source : this.getSources(insnNode, receiverDepth)) {
                        if (source.getOpcode() == AALOAD)
                            // Already instrumented, skip it
                            continue;
                        instructionsToAddAfter.put(source, this.ensureNotProxy(methodNode.owner));
                    }

                    break;
                }
                case INVOKEVIRTUAL: {
                    MethodInsnNode methodNode = (MethodInsnNode) insnNode;
                    MethodInvocationInfo m = new MethodInvocationInfo(methodNode.name, methodNode.owner,
                            methodNode.desc);

                    if (ensureNotProxyMethods.contains(m)) {
                        int receiverDepth = 0;
                        for (Type arg : Type.getArgumentTypes(methodNode.desc))
                            receiverDepth += arg.getSize();

                        if (!this.needsRedirect(insnNode, receiverDepth))
                            continue;

                        for (AbstractInsnNode source : this.getSources(insnNode, receiverDepth))
                            instructionsToAddAfter.put(source, this.ensureNotProxy());
                    }

                    break;
                }
                case GETFIELD: {
                    if (!this.needsRedirect(insnNode, 0))
                        continue;
                    FieldInsnNode fieldNode = (FieldInsnNode) insnNode;
                    Type fieldOwner = findActualFieldOwner(Type.getObjectType(fieldNode.owner), fieldNode.name);
                    opcode = (opcode == GETFIELD ? INVOKEVIRTUAL : INVOKESTATIC);
                    String methodName = AddGettersAndSetters.generateGetterName(version, fieldOwner,
                            fieldNode.name);
                    String methodDesc = Type.getMethodDescriptor(Type.getType(fieldNode.desc));
                    instructionsToReplace.put(insnNode,
                            new MethodInsnNode(opcode, fieldNode.owner, methodName, methodDesc, false));
                    break;
                }
                case PUTFIELD: {
                    if (!this.needsRedirect(insnNode, 1))
                        continue;
                    FieldInsnNode fieldNode = (FieldInsnNode) insnNode;
                    Type fieldOwner = findActualFieldOwner(Type.getObjectType(fieldNode.owner), fieldNode.name);
                    opcode = (opcode == PUTFIELD ? INVOKEVIRTUAL : INVOKESTATIC);
                    String methodName = AddGettersAndSetters.generateSetterName(version, fieldOwner,
                            fieldNode.name);
                    String methodDesc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(fieldNode.desc));
                    instructionsToReplace.put(insnNode,
                            new MethodInsnNode(opcode, fieldNode.owner, methodName, methodDesc, false));
                    break;
                }
                }
            }

            for (Entry<AbstractInsnNode, InsnList> entry : instructionsToAddBefore.entrySet())
                this.instructions.insertBefore(entry.getKey(), entry.getValue());

            for (Entry<AbstractInsnNode, InsnList> entry : instructionsToAddAfter.entrySet())
                this.instructions.insert(entry.getKey(), entry.getValue());

            // Destructive changes take place after constructive changes
            // so that the location nodes do not get destroyed too soon
            for (Entry<AbstractInsnNode, AbstractInsnNode> entry : instructionsToReplace.entrySet())
                this.instructions.set(entry.getKey(), entry.getValue());

            accept(methodVisitor);
        }

        private InsnList ensureNotProxy() {
            return this.ensureNotProxy(null);
        }

        private InsnList ensureNotProxy(String owner) {
            InsnList list = new InsnList();
            LabelNode label = new LabelNode();
            list.add(new InsnNode(DUP));
            list.add(new TypeInsnNode(INSTANCEOF, Type.getType(RubahProxy.class).getInternalName()));
            list.add(new JumpInsnNode(IFEQ, label));
            list.add(new TypeInsnNode(CHECKCAST, Type.getType(RubahProxy.class).getInternalName()));
            list.add(new MethodInsnNode(INVOKESTATIC, Type.getType(Rubah.class).getInternalName(),
                    "getConverted",
                    Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class)), false));
            if (owner != null)
                list.add(new TypeInsnNode(CHECKCAST, owner));
            list.add(label);

            return list;
        }

        /**
         *
         * @param idx
         * @return True if local var, false if argument
         */
        private boolean isLocalVar(int idx) {
            int lastVar = (this.isStatic ? 0 : 1);
            for (Type arg : Type.getArgumentTypes(desc))
                lastVar += arg.getSize();

            return idx >= lastVar;

        }

        private Set<AbstractInsnNode> getSources(AbstractInsnNode insnNode, int depth) {
            return this.getSources(insnNode, depth, new HashSet<AbstractInsnNode>(),
                    new HashSet<AbstractInsnNode>());
        }

        private Set<AbstractInsnNode> getSources(AbstractInsnNode insnNode, int depth,
                HashSet<AbstractInsnNode> allSources, HashSet<AbstractInsnNode> alreadySeen) {
            int idx = this.instructions.indexOf(insnNode);
            Frame<SourceValue> sourcesFrame = this.sourcesFrames[idx];
            if (sourcesFrame == null) {
                // Bug in the analyzer or unreachable code
                return new HashSet<AbstractInsnNode>();
            }
            Set<AbstractInsnNode> sources = sourcesFrame
                    .getStack(sourcesFrame.getStackSize() - 1 - depth).insns;

            for (AbstractInsnNode source : sources) {
                if (alreadySeen.contains(source))
                    continue;

                alreadySeen.add(source);

                switch (source.getOpcode()) {
                case CHECKCAST:
                case DUP:
                    allSources.addAll(this.getSources(source, 0, allSources, alreadySeen));
                    break;
                case ALOAD:
                    // Is this an argument?
                    VarInsnNode n = (VarInsnNode) source;
                    if (isLocalVar(n.var)) {
                        // Only ASTORE can save to local variables
                        for (AbstractInsnNode astore : sourcesFrame.getLocal(n.var).insns) {
                            allSources.addAll(this.getSources(astore, 0, allSources, alreadySeen));
                        }
                        continue;
                    }
                    // Explicit fall-through
                default:
                    allSources.add(source);
                    break;
                }
            }

            return allSources;
        }

        private void printAnalyzerResult() {
            Textifier t = new Textifier();
            TraceMethodVisitor mv = new TraceMethodVisitor(t);
            PrintWriter pw = new PrintWriter(System.out);

            pw.println(this.name + this.desc);
            for (int j = 0; j < this.instructions.size(); ++j) {
                this.instructions.get(j).accept(mv);

                StringBuffer s = new StringBuffer();
                Frame<SourceValue> f = this.sourcesFrames[j];
                if (f == null) {
                    s.append('?');
                } else {
                    for (int k = 0; k < f.getLocals(); ++k) {
                        for (AbstractInsnNode insn : f.getLocal(k).insns) {
                            s.append(this.instructions.indexOf(insn)).append(' ');
                        }
                    }
                    s.append(" : ");
                    for (int k = 0; k < f.getStackSize(); ++k) {
                        for (AbstractInsnNode insn : f.getStack(k).insns) {
                            s.append(this.instructions.indexOf(insn)).append(' ');
                        }
                    }
                }
                while (s.length() < this.maxStack + this.maxLocals + 1) {
                    s.append(' ');
                }
                pw.print(Integer.toString(j + 100000).substring(1));
                pw.print(" " + s + " : " + t.text.get(t.text.size() - 1));
            }
            for (int j = 0; j < this.tryCatchBlocks.size(); ++j) {
                this.tryCatchBlocks.get(j).accept(mv);
                pw.print(" " + t.text.get(t.text.size() - 1));
            }
            pw.println();
            pw.flush();
        }

        private boolean needsRedirect(AbstractInsnNode insnNode, int stackDepth) {
            boolean ret = false;

            for (AbstractInsnNode insn : this.getSources(insnNode, stackDepth)) {
                switch (insn.getOpcode()) {
                case NEW:
                    continue;
                case ALOAD:
                    if (((VarInsnNode) insn).var != 0 || this.isStatic)
                        ret = true;
                    break;
                default:
                    ret = true;
                    break;
                }
            }

            return ret;
        }

    };

    return ret;
}

From source file:soot.asm.AsmMethodSource.java

License:Open Source License

void setUnit(AbstractInsnNode insn, Unit u) {
    Unit o = units.put(insn, u);/* ww  w.j  av a 2  s  . c  o m*/
    if (o != null)
        throw new AssertionError(insn.getOpcode() + " already has a unit, " + o);
}

From source file:soot.asm.AsmMethodSource.java

License:Open Source License

private void convert() {
    ArrayDeque<Edge> worklist = new ArrayDeque<Edge>();
    for (LabelNode ln : trapHandlers.keySet())
        worklist.add(new Edge(ln, new ArrayList<Operand>()));
    worklist.add(new Edge(instructions.getFirst(), new ArrayList<Operand>()));
    conversionWorklist = worklist;//w  w  w .j  a v  a  2  s  .  c  o m
    edges = HashBasedTable.create(1, 1);
    do {
        Edge edge = worklist.pollLast();
        AbstractInsnNode insn = edge.insn;
        stack = edge.stack;
        edge.stack = null;
        do {
            int type = insn.getType();
            if (type == FIELD_INSN) {
                convertFieldInsn((FieldInsnNode) insn);
            } else if (type == IINC_INSN) {
                convertIincInsn((IincInsnNode) insn);
            } else if (type == INSN) {
                convertInsn((InsnNode) insn);
                int op = insn.getOpcode();
                if ((op >= IRETURN && op <= RETURN) || op == ATHROW) {
                    break;
                }
            } else if (type == INT_INSN) {
                convertIntInsn((IntInsnNode) insn);
            } else if (type == LDC_INSN) {
                convertLdcInsn((LdcInsnNode) insn);
            } else if (type == JUMP_INSN) {
                JumpInsnNode jmp = (JumpInsnNode) insn;
                convertJumpInsn(jmp);
                int op = jmp.getOpcode();
                if (op == JSR)
                    throw new UnsupportedOperationException("JSR!");
                if (op != GOTO) {
                    /* ifX opcode, i.e. two successors */
                    AbstractInsnNode next = insn.getNext();
                    addEdges(insn, next, Collections.singletonList(jmp.label));
                } else {
                    addEdges(insn, jmp.label, null);
                }
                break;
            } else if (type == LOOKUPSWITCH_INSN) {
                LookupSwitchInsnNode swtch = (LookupSwitchInsnNode) insn;
                convertLookupSwitchInsn(swtch);
                LabelNode dflt = swtch.dflt;
                addEdges(insn, dflt, swtch.labels);
                break;
            } else if (type == METHOD_INSN) {
                convertMethodInsn((MethodInsnNode) insn);
            } else if (type == MULTIANEWARRAY_INSN) {
                convertMultiANewArrayInsn((MultiANewArrayInsnNode) insn);
            } else if (type == TABLESWITCH_INSN) {
                TableSwitchInsnNode swtch = (TableSwitchInsnNode) insn;
                convertTableSwitchInsn(swtch);
                LabelNode dflt = swtch.dflt;
                addEdges(insn, dflt, swtch.labels);
            } else if (type == TYPE_INSN) {
                convertTypeInsn((TypeInsnNode) insn);
            } else if (type == VAR_INSN) {
                if (insn.getOpcode() == RET)
                    throw new UnsupportedOperationException("RET!");
                convertVarInsn((VarInsnNode) insn);
            } else if (type == LABEL) {
                convertLabel((LabelNode) insn);
            } else if (type == LINE || type == FRAME) {
                // we can ignore it
            } else
                throw new RuntimeException("Unknown instruction type: " + type);
        } while ((insn = insn.getNext()) != null);
    } while (!worklist.isEmpty());
    conversionWorklist = null;
    edges = null;
}

From source file:v6.java.preverifier.MethodRewriter.java

License:Open Source License

/**
 * Visit the specified instruction and do the right thing.
 * /*from  ww  w .j a  v a2s. co  m*/
 * @param method
 * @param region
 * @param insnNode
 * @throws AnalyzerException
 */
private void visitInstruction(MethodNode method, Region region, AbstractInsnNode insnNode)
        throws AnalyzerException {
    int opcode = insnNode.getOpcode();
    switch (opcode) {
    case Opcodes.JSR:
        visitJumpToSubroutine(method, region, (JumpInsnNode) insnNode);
        break;

    case Opcodes.IFEQ:
    case Opcodes.IFNE:
    case Opcodes.IFLT:
    case Opcodes.IFGE:
    case Opcodes.IFGT:
    case Opcodes.IFLE:
    case Opcodes.IF_ICMPEQ:
    case Opcodes.IF_ICMPNE:
    case Opcodes.IF_ICMPLT:
    case Opcodes.IF_ICMPGE:
    case Opcodes.IF_ICMPGT:
    case Opcodes.IF_ICMPLE:
    case Opcodes.IF_ACMPEQ:
    case Opcodes.IF_ACMPNE:
    case Opcodes.GOTO:
    case Opcodes.IFNULL:
    case Opcodes.IFNONNULL:
        visitJump(method, region, (JumpInsnNode) insnNode);
        break;

    case Opcodes.LOOKUPSWITCH:
        visitLookupSwitch(method, region, (LookupSwitchInsnNode) insnNode);
        break;

    case Opcodes.TABLESWITCH:
        visitTableSwitch(method, region, (TableSwitchInsnNode) insnNode);
        break;

    default:
        insnNode.accept(method);
    }
}

From source file:vazkii.quark.base.asm.ClassTransformer.java

License:Creative Commons License

private static byte[] transformModelBiped(byte[] basicClass) {
    log("Transforming ModelBiped");
    MethodSignature sig = new MethodSignature("setRotationAngles", "func_78087_a", "a",
            "(FFFFFFLnet/minecraft/entity/Entity;)V");

    return transform(basicClass, Pair.of(sig, combine((AbstractInsnNode node) -> { // Filter
        return node.getOpcode() == Opcodes.RETURN;
    }, (MethodNode method, AbstractInsnNode node) -> { // Action
        InsnList newInstructions = new InsnList();

        newInstructions.add(new VarInsnNode(Opcodes.ALOAD, 7));
        newInstructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ASM_HOOKS, "updateEmotes",
                "(Lnet/minecraft/entity/Entity;)V"));

        method.instructions.insertBefore(node, newInstructions);
        return true;
    })));/*from  w w w  .j  ava2 s .co m*/
}

From source file:vazkii.quark.base.asm.ClassTransformer.java

License:Creative Commons License

private static byte[] transformRenderItem(byte[] basicClass) {
    log("Transforming RenderItem");
    MethodSignature sig1 = new MethodSignature("renderItem", "func_180454_a", "a",
            "(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/renderer/block/model/IBakedModel;)V");
    MethodSignature sig2 = new MethodSignature("renderEffect", "func_191966_a", "a",
            "(Lnet/minecraft/client/renderer/block/model/IBakedModel;)V");

    byte[] transClass = basicClass;

    transClass = transform(transClass, Pair.of(sig1, combine((AbstractInsnNode node) -> { // Filter
        return true;
    }, (MethodNode method, AbstractInsnNode node) -> { // Action
        InsnList newInstructions = new InsnList();

        newInstructions.add(new VarInsnNode(Opcodes.ALOAD, 1));
        newInstructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ASM_HOOKS, "setColorRuneTargetStack",
                "(Lnet/minecraft/item/ItemStack;)V"));

        method.instructions.insertBefore(node, newInstructions);
        return true;
    })));/*from w  w  w .j  av a 2s .com*/

    transClass = transform(transClass, Pair.of(sig2, combine((AbstractInsnNode node) -> { // Filter
        return node.getOpcode() == Opcodes.LDC && ((LdcInsnNode) node).cst.equals(-8372020);
    }, (MethodNode method, AbstractInsnNode node) -> { // Action
        InsnList newInstructions = new InsnList();

        newInstructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ASM_HOOKS, "getRuneColor", "(I)I"));

        method.instructions.insert(node, newInstructions);
        return false;
    })));

    return transClass;
}

From source file:vazkii.quark.base.asm.ClassTransformer.java

License:Creative Commons License

private static byte[] transformLayerArmorBase(byte[] basicClass) {
    log("Transforming LayerArmorBase");
    MethodSignature sig1 = new MethodSignature("renderArmorLayer", "func_188361_a", "a",
            "(Lnet/minecraft/entity/EntityLivingBase;FFFFFFFLnet/minecraft/inventory/EntityEquipmentSlot;)V");
    MethodSignature sig2 = new MethodSignature("renderEnchantedGlint", "func_188364_a", "a",
            "(Lnet/minecraft/client/renderer/entity/RenderLivingBase;Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/client/model/ModelBase;FFFFFFF)V");

    byte[] transClass = basicClass;

    transClass = transform(transClass, Pair.of(sig1, combine((AbstractInsnNode node) -> { // Filter
        return node.getOpcode() == Opcodes.ASTORE;
    }, (MethodNode method, AbstractInsnNode node) -> { // Action
        InsnList newInstructions = new InsnList();

        newInstructions.add(new VarInsnNode(Opcodes.ALOAD, 10));
        newInstructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ASM_HOOKS, "setColorRuneTargetStack",
                "(Lnet/minecraft/item/ItemStack;)V"));

        method.instructions.insert(node, newInstructions);
        return true;
    })));/* w w w  .j ava 2 s  . c o m*/

    if (!hasOptifine(sig2.toString())) {
        invokestaticCount = 0;
        transClass = transform(transClass, Pair.of(sig2, combine((AbstractInsnNode node) -> { // Filter
            return node.getOpcode() == Opcodes.INVOKESTATIC && ((MethodInsnNode) node).desc.equals("(FFFF)V");
        }, (MethodNode method, AbstractInsnNode node) -> { // Action
            invokestaticCount++;

            InsnList newInstructions = new InsnList();

            newInstructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ASM_HOOKS, "applyRuneColor", "()V"));

            method.instructions.insert(node, newInstructions);
            return invokestaticCount == 2;
        })));
    }

    return transClass;
}