Example usage for org.objectweb.asm Opcodes INVOKEVIRTUAL

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

Introduction

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

Prototype

int INVOKEVIRTUAL

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

Click Source Link

Usage

From source file:lucee.transformer.bytecode.literal.LitStringImpl.java

License:Open Source License

/**
 * @see lucee.transformer.expression.Expression#_writeOut(org.objectweb.asm.commons.GeneratorAdapter, int)
 *//*w w w  .  j a v  a  2  s .  c o  m*/
private static Type _writeOut(BytecodeContext bc, int mode, String str) throws TransformerException {
    // write to a file instead to the bytecode
    // str(0,10);
    //print.ds(str);
    int externalizeStringGTE = ((ConfigImpl) bc.getConfig()).getExternalizeStringGTE();

    if (externalizeStringGTE > -1 && str.length() > externalizeStringGTE
            && StringUtil.indexOfIgnoreCase(bc.getMethod().getName(), "call") != -1) {
        try {
            GeneratorAdapter ga = bc.getAdapter();
            Page page = bc.getPage();
            Range range = page.registerString(bc, str);
            if (range != null) {
                ga.visitVarInsn(Opcodes.ALOAD, 0);
                ga.visitVarInsn(Opcodes.ALOAD, 1);
                ga.push(range.from);
                ga.push(range.to);
                ga.visitMethodInsn(Opcodes.INVOKEVIRTUAL, bc.getClassName(), "str",
                        "(Llucee/runtime/PageContext;II)Ljava/lang/String;");
                return Types.STRING;
            }
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
        }
    }

    if (toBig(str)) {
        _toExpr(bc.getFactory(), str).writeOut(bc, mode);
    } else {
        bc.getAdapter().push(str);
    }
    return Types.STRING;
}

From source file:lucee.transformer.bytecode.Page.java

License:Open Source License

/**
 * result byte code as binary array/*from  w w  w . j av a2  s  .c  o  m*/
 * @param classFile 
 * @return byte code
 * @throws IOException 
 * @throws TemplateException 
 */
public byte[] execute(PageSource source, Resource classFile) throws BytecodeException {
    /*
    // this is done that the Page can be executed more than once
    if(initFunctions==null)
       initFunctions=(ArrayList<IFunction>) functions.clone();
    else
       functions=initFunctions;
    if(initThreads==null)
       initThreads=(ArrayList<TagThread>) threads.clone();
    else
       threads=initThreads;
    methodCount=0;
    off=0;
    staticTextLocation=null;
            
            
    print.e(this.functions);
    print.e(this.threads);*/

    Resource p = classFile.getParentResource().getRealResource(classFile.getName() + ".txt");

    List<LitString> keys = new ArrayList<LitString>();
    ClassWriter cw = ASMUtil.getClassWriter();

    ArrayList<String> imports = new ArrayList<String>();
    getImports(imports, this);

    // parent
    String parent = "lucee/runtime/PagePlus";
    if (isComponent())
        parent = "lucee/runtime/ComponentPage";
    else if (isInterface())
        parent = "lucee/runtime/InterfacePage";

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, name, null, parent, null);
    cw.visitSource(this.pageSource.getPhyscalFile().getAbsolutePath(),
            "rel:" + this.pageSource.getFullRealpath()); // when adding more use ; as delimiter
    //

    // static constructor
    //GeneratorAdapter statConstrAdapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC,STATIC_CONSTRUCTOR,null,null,cw);
    BytecodeContext statConstr = null;//new BytecodeContext(null,null,this,externalizer,keys,cw,name,statConstrAdapter,STATIC_CONSTRUCTOR,writeLog(),suppressWSbeforeArg);

    // constructor
    GeneratorAdapter constrAdapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, CONSTRUCTOR_PS, null, null, cw);
    BytecodeContext constr = new BytecodeContext(source, null, null, this, keys, cw, name, constrAdapter,
            CONSTRUCTOR_PS, writeLog(), suppressWSbeforeArg, output);
    constrAdapter.loadThis();
    Type t = Types.PAGE_PLUS;
    if (isComponent())
        t = Types.COMPONENT_PAGE;
    else if (isInterface())
        t = Types.INTERFACE_PAGE;

    constrAdapter.invokeConstructor(t, CONSTRUCTOR);

    // call _init()
    constrAdapter.visitVarInsn(Opcodes.ALOAD, 0);
    constrAdapter.visitMethodInsn(Opcodes.INVOKEVIRTUAL, constr.getClassName(), "initKeys", "()V");

    // private static  ImportDefintion[] test=new ImportDefintion[]{...};
    {
        FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "imports",
                "[Llucee/runtime/component/ImportDefintion;", null, null);
        fv.visitEnd();

        constrAdapter.visitVarInsn(Opcodes.ALOAD, 0);
        ArrayVisitor av = new ArrayVisitor();
        av.visitBegin(constrAdapter, Types.IMPORT_DEFINITIONS, imports.size());
        int index = 0;
        Iterator<String> it = imports.iterator();
        while (it.hasNext()) {
            av.visitBeginItem(constrAdapter, index++);
            constrAdapter.push(it.next());
            ASMConstants.NULL(constrAdapter);
            constrAdapter.invokeStatic(Types.IMPORT_DEFINITIONS_IMPL, ID_GET_INSTANCE);
            av.visitEndItem(constrAdapter);
        }
        av.visitEnd();
        constrAdapter.visitFieldInsn(Opcodes.PUTFIELD, name, "imports",
                "[Llucee/runtime/component/ImportDefintion;");

    }

    // getVersion
    GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, VERSION, null, null,
            cw);
    adapter.push(version);
    adapter.returnValue();
    adapter.endMethod();

    // public ImportDefintion[] getImportDefintions()
    if (imports.size() > 0) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, GET_IMPORT_DEFINITIONS, null,
                null, cw);
        adapter.visitVarInsn(Opcodes.ALOAD, 0);
        adapter.visitFieldInsn(Opcodes.GETFIELD, name, "imports", "[Llucee/runtime/component/ImportDefintion;");
        adapter.returnValue();
        adapter.endMethod();
    } else {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, GET_IMPORT_DEFINITIONS, null,
                null, cw);
        adapter.visitInsn(Opcodes.ICONST_0);
        adapter.visitTypeInsn(Opcodes.ANEWARRAY, "lucee/runtime/component/ImportDefintion");
        adapter.returnValue();
        adapter.endMethod();
    }

    // getSourceLastModified
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, LAST_MOD, null, null, cw);
    adapter.push(lastModifed);
    adapter.returnValue();
    adapter.endMethod();

    // getCompileTime
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, COMPILE_TIME, null, null, cw);
    adapter.push(System.currentTimeMillis());
    adapter.returnValue();
    adapter.endMethod();

    // newInstance/initComponent/call
    if (isComponent()) {
        Tag component = getComponent();
        writeOutNewComponent(statConstr, constr, keys, cw, component);
        writeOutInitComponent(statConstr, constr, keys, cw, component);
    } else if (isInterface()) {
        Tag interf = getInterface();
        writeOutNewInterface(statConstr, constr, keys, cw, interf);
        writeOutInitInterface(statConstr, constr, keys, cw, interf);
    } else {
        writeOutCall(statConstr, constr, keys, cw);
    }

    // udfCall     
    Function[] functions = getFunctions();
    ConditionVisitor cv;
    DecisionIntVisitor div;
    // less/equal than 10 functions
    if (isInterface()) {
    } else if (functions.length <= 10) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_CALL, null,
                new Type[] { Types.THROWABLE }, cw);
        BytecodeContext bc = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                UDF_CALL, writeLog(), suppressWSbeforeArg, output);
        if (functions.length == 0) {
        } else if (functions.length == 1) {
            ExpressionUtil.visitLine(bc, functions[0].getStart());
            functions[0].getBody().writeOut(bc);
            ExpressionUtil.visitLine(bc, functions[0].getEnd());
        } else
            writeOutUdfCallInner(bc, functions, 0, functions.length);
        adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();
    }
    // more than 10 functions
    else {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_CALL, null,
                new Type[] { Types.THROWABLE }, cw);
        BytecodeContext bc = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                UDF_CALL, writeLog(), suppressWSbeforeArg, output);
        cv = new ConditionVisitor();
        cv.visitBefore();
        int count = 0;
        for (int i = 0; i < functions.length; i += 10) {
            cv.visitWhenBeforeExpr();
            div = new DecisionIntVisitor();
            div.visitBegin();
            adapter.loadArg(2);
            div.visitLT();
            adapter.push(i + 10);
            div.visitEnd(bc);
            cv.visitWhenAfterExprBeforeBody(bc);

            adapter.visitVarInsn(Opcodes.ALOAD, 0);
            adapter.visitVarInsn(Opcodes.ALOAD, 1);
            adapter.visitVarInsn(Opcodes.ALOAD, 2);
            adapter.visitVarInsn(Opcodes.ILOAD, 3);
            adapter.visitMethodInsn(Opcodes.INVOKEVIRTUAL, name, createFunctionName(++count),
                    "(Llucee/runtime/PageContext;Llucee/runtime/type/UDF;I)Ljava/lang/Object;");
            adapter.visitInsn(Opcodes.ARETURN);//adapter.returnValue();
            cv.visitWhenAfterBody(bc);
        }
        cv.visitAfter(bc);

        adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();

        count = 0;
        Method innerCall;
        for (int i = 0; i < functions.length; i += 10) {
            innerCall = new Method(createFunctionName(++count), Types.OBJECT,
                    new Type[] { Types.PAGE_CONTEXT, USER_DEFINED_FUNCTION, Types.INT_VALUE });

            adapter = new GeneratorAdapter(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, innerCall, null,
                    new Type[] { Types.THROWABLE }, cw);
            writeOutUdfCallInner(
                    new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter, innerCall,
                            writeLog(), suppressWSbeforeArg, output),
                    functions, i, i + 10 > functions.length ? functions.length : i + 10);

            adapter.visitInsn(Opcodes.ACONST_NULL);
            adapter.returnValue();
            adapter.endMethod();
        }
    }

    // threadCall
    TagThread[] threads = getThreads();
    if (true) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, THREAD_CALL, null,
                new Type[] { Types.THROWABLE }, cw);
        if (threads.length > 0)
            writeOutThreadCallInner(new BytecodeContext(source, statConstr, constr, this, keys, cw, name,
                    adapter, THREAD_CALL, writeLog(), suppressWSbeforeArg, output), threads, 0, threads.length);
        //adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();
    }

    // udfDefaultValue
    // less/equal than 10 functions
    if (isInterface()) {
    } else if (functions.length <= 10) {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_DEFAULT_VALUE, null,
                new Type[] { Types.PAGE_EXCEPTION }, cw);
        if (functions.length > 0)
            writeUdfDefaultValueInner(
                    new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                            UDF_DEFAULT_VALUE, writeLog(), suppressWSbeforeArg, output),
                    functions, 0, functions.length);

        adapter.loadArg(DEFAULT_VALUE);
        adapter.returnValue();
        adapter.endMethod();
    } else {
        adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, UDF_DEFAULT_VALUE, null,
                new Type[] { Types.PAGE_EXCEPTION }, cw);
        BytecodeContext bc = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                UDF_DEFAULT_VALUE, writeLog(), suppressWSbeforeArg, output);
        cv = new ConditionVisitor();
        cv.visitBefore();
        int count = 0;
        for (int i = 0; i < functions.length; i += 10) {
            cv.visitWhenBeforeExpr();
            div = new DecisionIntVisitor();
            div.visitBegin();
            adapter.loadArg(1);
            div.visitLT();
            adapter.push(i + 10);
            div.visitEnd(bc);
            cv.visitWhenAfterExprBeforeBody(bc);

            adapter.visitVarInsn(Opcodes.ALOAD, 0);
            adapter.visitVarInsn(Opcodes.ALOAD, 1);
            adapter.visitVarInsn(Opcodes.ILOAD, 2);
            adapter.visitVarInsn(Opcodes.ILOAD, 3);
            adapter.visitVarInsn(Opcodes.ALOAD, 4);

            adapter.visitMethodInsn(Opcodes.INVOKEVIRTUAL, name, "udfDefaultValue" + (++count),
                    "(Llucee/runtime/PageContext;IILjava/lang/Object;)Ljava/lang/Object;");
            adapter.visitInsn(Opcodes.ARETURN);//adapter.returnValue();

            cv.visitWhenAfterBody(bc);
        }
        cv.visitAfter(bc);

        adapter.visitInsn(Opcodes.ACONST_NULL);
        adapter.returnValue();
        adapter.endMethod();

        count = 0;
        Method innerDefaultValue;
        for (int i = 0; i < functions.length; i += 10) {
            innerDefaultValue = new Method("udfDefaultValue" + (++count), Types.OBJECT,
                    new Type[] { Types.PAGE_CONTEXT, Types.INT_VALUE, Types.INT_VALUE, Types.OBJECT });
            adapter = new GeneratorAdapter(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, innerDefaultValue, null,
                    new Type[] { Types.PAGE_EXCEPTION }, cw);
            writeUdfDefaultValueInner(
                    new BytecodeContext(source, statConstr, constr, this, keys, cw, name, adapter,
                            innerDefaultValue, writeLog(), suppressWSbeforeArg, output),
                    functions, i, i + 10 > functions.length ? functions.length : i + 10);

            adapter.loadArg(DEFAULT_VALUE);
            //adapter.visitInsn(Opcodes.ACONST_NULL);
            adapter.returnValue();
            adapter.endMethod();
        }

    }

    // register fields
    {
        GeneratorAdapter aInit = new GeneratorAdapter(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, _INIT, null,
                null, cw);
        BytecodeContext bcInit = new BytecodeContext(source, statConstr, constr, this, keys, cw, name, aInit,
                _INIT, writeLog(), suppressWSbeforeArg, output);
        registerFields(bcInit, keys);
        aInit.returnValue();
        aInit.endMethod();
    }

    //setPageSource(pageSource);
    constrAdapter.visitVarInsn(Opcodes.ALOAD, 0);
    constrAdapter.visitVarInsn(Opcodes.ALOAD, 1);
    constrAdapter.invokeVirtual(t, SET_PAGE_SOURCE);

    constrAdapter.returnValue();
    constrAdapter.endMethod();

    return cw.toByteArray();

}

From source file:net.doubledoordev.inventorylock.asm.Transformer.java

License:Open Source License

@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(basicClass);
    classReader.accept(classNode, READER_FLAGS);

    boolean isPlayer = transformedName.equals(ENTITY_PLAYER_OWNER_NAME);
    if (isPlayer)
        LOGGER.info("Found EntityPlayer");

    for (MethodNode method : classNode.methods) {
        InsnList list = method.instructions;
        if (isPlayer && INSTANCE.mapMethodDesc(method.desc).equals(ENTITY_PLAYER_DESC)
                && INSTANCE.mapMethodName(name, method.name, method.desc).equals(ENTITY_PLAYER_TARGET)) {
            final LabelNode newLabel = new LabelNode();
            LOGGER.info("Found canOpen");
            AbstractInsnNode node = list.getFirst();
            while (node.getOpcode() != IRETURN && node != list.getLast()) {
                if (node.getOpcode() == IFEQ)
                    ((JumpInsnNode) node).label = newLabel;
                node = node.getNext();//ww w  . j a  v a2s  .c  o  m
            }
            if (node.getOpcode() != IRETURN)
                throw new RuntimeException("ASM failed. (return not found)");
            final AbstractInsnNode target = node;
            while (node.getType() != LABEL && node != list.getLast())
                node = node.getNext();
            if (node.getType() != LABEL)
                throw new RuntimeException("ASM failed. (label not found)");
            final LabelNode label = ((LabelNode) node);

            //Adding "else if (code instanceof BetterLockCode) return ((BetterLockCode) code).contains(this.getUniqueID());"
            InsnList inject = new InsnList();

            inject.add(newLabel);
            inject.add(new VarInsnNode(ALOAD, 1));
            inject.add(new TypeInsnNode(INSTANCEOF, BETTER_LOCK_TYPE));
            inject.add(new JumpInsnNode(IFEQ, label));
            inject.add(new VarInsnNode(ALOAD, 1));
            inject.add(new TypeInsnNode(CHECKCAST, BETTER_LOCK_TYPE));
            inject.add(new VarInsnNode(ALOAD, 0));
            //inject.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, ENTITY_PLAYER_OWNER, ENTITY_PLAYER_GET_UUID, ENTITY_PLATER_GET_UUID_DESC, false));
            inject.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, BETTER_LOCK_TYPE, BETTER_LOCK_CONTAINS,
                    BETTER_LOCK_CONTAINS_DESC, false));
            inject.add(new InsnNode(IRETURN));

            list.insert(target, inject);
            LOGGER.info("Injected elseif into EntityPlayer's canOpen");
        }
        for (AbstractInsnNode node = list.getFirst(); node != list.getLast(); node = node.getNext()) {
            if (node.getOpcode() != INVOKESTATIC)
                continue;
            MethodInsnNode methodInsnNode = ((MethodInsnNode) node);
            //                if (transformedName.equals("net.minecraft.tileentity.TileEntityLockable"))
            //                    LOGGER.info("In {} ({}) Method {}.{}{} Translated {}.{}{}", name, transformedName,
            //                            methodInsnNode.owner, methodInsnNode.name, methodInsnNode.desc,
            //                            INSTANCE.map(methodInsnNode.owner), INSTANCE.mapMethodName(methodInsnNode.owner, methodInsnNode.name, methodInsnNode.desc), INSTANCE.mapMethodDesc(methodInsnNode.desc).equals(LOCK_CODE_DESC));
            if (INSTANCE.map(methodInsnNode.owner).equals(LOCK_CODE_OWNER)
                    && INSTANCE.mapMethodDesc(methodInsnNode.desc).equals(LOCK_CODE_DESC)
                    && INSTANCE.mapMethodName(methodInsnNode.owner, methodInsnNode.name, methodInsnNode.desc)
                            .equals(LOCK_CODE_TARGET)) {
                methodInsnNode.owner = LOCK_CODE_OWNER_REPLACE;
                methodInsnNode.name = LOCK_CODE_NAME;
                LOGGER.info("Replaced call in class {} ({}), method {}{}", name, transformedName, method.name,
                        method.desc);
            }
        }
    }

    final ClassWriter writer = new ClassWriter(WRITER_FLAGS);
    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 ww. j  av  a 2  s  .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.minecraftforge.fml.common.asm.transformers.FieldRedirectTransformer.java

License:Open Source License

@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
    if (!this.clsName.equals(transformedName))
        return basicClass;

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(basicClass);
    classReader.accept(classNode, 0);//w w w.j  a  v  a  2 s  .  co  m

    FieldNode fieldRef = null;
    for (FieldNode f : classNode.fields) {
        if (this.TYPE.equals(f.desc) && fieldRef == null) {
            fieldRef = f;
        } else if (this.TYPE.equals(f.desc)) {
            throw new RuntimeException("Error processing " + clsName + " - found a duplicate holder field");
        }
    }
    if (fieldRef == null) {
        throw new RuntimeException("Error processing " + clsName
                + " - no holder field declared (is the code somehow obfuscated?)");
    }

    MethodNode getMethod = null;
    for (MethodNode m : classNode.methods) {
        if (m.name.equals(this.bypass))
            continue;
        if (this.DESC.equals(m.desc) && getMethod == null) {
            getMethod = m;
        } else if (this.DESC.equals(m.desc)) {
            throw new RuntimeException("Error processing " + clsName + " - duplicate get method found");
        }
    }
    if (getMethod == null) {
        throw new RuntimeException(
                "Error processing " + clsName + " - no get method found (is the code somehow obfuscated?)");
    }

    for (MethodNode m : classNode.methods) {
        if (m.name.equals(this.bypass))
            continue;
        for (ListIterator<AbstractInsnNode> it = m.instructions.iterator(); it.hasNext();) {
            AbstractInsnNode insnNode = it.next();
            if (insnNode.getType() == AbstractInsnNode.FIELD_INSN) {
                FieldInsnNode fi = (FieldInsnNode) insnNode;
                if (fieldRef.name.equals(fi.name) && fi.getOpcode() == Opcodes.GETFIELD) {
                    it.remove();
                    MethodInsnNode replace = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classNode.name,
                            getMethod.name, getMethod.desc, false);
                    it.add(replace);
                }
            }
        }
    }
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
}

From source file:net.minecraftforge.fml.common.asm.transformers.SoundEngineFixTransformer.java

License:Open Source License

@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
    if (transformedName.equals("paulscode.sound.Source")) {
        ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(basicClass);
        classReader.accept(classNode, 0);

        classNode.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "removed", "Z", null, null)); // adding field 'public boolean removed;'

        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        classNode.accept(writer);/*from   w  ww  .  j  ava2 s .  c  om*/
        return writer.toByteArray();
    } else if (transformedName.equals("paulscode.sound.Library")) {
        ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(basicClass);
        classReader.accept(classNode, 0);

        MethodNode method = null;
        for (MethodNode m : classNode.methods) {
            if (m.name.equals("removeSource") && m.desc.equals("(Ljava/lang/String;)V")) // trying to find paulscode.sound.Library.removeSource(String)
            {
                method = m;
                break;
            }
        }
        if (method == null)
            throw new RuntimeException(
                    "Error processing " + transformedName + " - no removeSource method found");

        AbstractInsnNode referenceNode = null;

        for (Iterator<AbstractInsnNode> iterator = method.instructions.iterator(); iterator.hasNext();) {
            AbstractInsnNode insn = iterator.next();
            if (insn instanceof MethodInsnNode && ((MethodInsnNode) insn).owner.equals("paulscode/sound/Source") // searching for mySource.cleanup() node (line 1086)
                    && ((MethodInsnNode) insn).name.equals("cleanup")) {
                referenceNode = insn;
                break;
            }
        }

        if (referenceNode != null) {
            LabelNode after = (LabelNode) referenceNode.getNext();

            AbstractInsnNode beginning = referenceNode.getPrevious();

            int varIndex = ((VarInsnNode) beginning).var;

            method.instructions.insertBefore(beginning, new VarInsnNode(Opcodes.ALOAD, varIndex)); // adding extra if (mySource.toStream)
            method.instructions.insertBefore(beginning,
                    new FieldInsnNode(Opcodes.GETFIELD, "paulscode/sound/Source", "toStream", "Z"));
            LabelNode elseNode = new LabelNode();
            method.instructions.insertBefore(beginning, new JumpInsnNode(Opcodes.IFEQ, elseNode)); // if fails (else) -> go to mySource.cleanup();

            method.instructions.insertBefore(beginning, new VarInsnNode(Opcodes.ALOAD, varIndex)); // if (mySource.toStream) { mySource.removed = true; }
            method.instructions.insertBefore(beginning, new InsnNode(Opcodes.ICONST_1));
            method.instructions.insertBefore(beginning,
                    new FieldInsnNode(Opcodes.PUTFIELD, "paulscode/sound/Source", "removed", "Z"));

            method.instructions.insertBefore(beginning, new JumpInsnNode(Opcodes.GOTO, after)); // still inside if -> jump to sourceMap.remove( sourcename );

            method.instructions.insertBefore(beginning, elseNode);
        }

        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        classNode.accept(writer);
        return writer.toByteArray();
    } else if (transformedName.equals("paulscode.sound.StreamThread")) {
        ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(basicClass);
        classReader.accept(classNode, 0);

        MethodNode method = null;
        for (MethodNode m : classNode.methods) {
            if (m.name.equals("run") && m.desc.equals("()V")) // trying to find paulscode.sound.StreamThread.run();
            {
                method = m;
                break;
            }
        }
        if (method == null)
            throw new RuntimeException("Error processing " + transformedName + " - no run method found");

        AbstractInsnNode referenceNode = null;

        for (Iterator<AbstractInsnNode> iterator = method.instructions.iterator(); iterator.hasNext();) {
            AbstractInsnNode insn = iterator.next();
            if (insn instanceof MethodInsnNode && ((MethodInsnNode) insn).owner.equals("java/util/ListIterator") // searching for 'src = iter.next();' node (line 110)
                    && ((MethodInsnNode) insn).name.equals("next")) {
                referenceNode = insn.getNext().getNext();
                break;
            }
        }

        if (referenceNode != null) {
            int varIndex = ((VarInsnNode) referenceNode).var;

            LabelNode after = (LabelNode) referenceNode.getNext();
            method.instructions.insertBefore(after, new VarInsnNode(Opcodes.ALOAD, varIndex)); // add if(removed)
            method.instructions.insertBefore(after,
                    new FieldInsnNode(Opcodes.GETFIELD, "paulscode/sound/Source", "removed", "Z"));
            method.instructions.insertBefore(after, new JumpInsnNode(Opcodes.IFEQ, after));

            // if the source has been marked as removed, clean it up and set the variable to null so it will be removed from the list
            method.instructions.insertBefore(after, new VarInsnNode(Opcodes.ALOAD, varIndex)); // src.cleanup();
            method.instructions.insertBefore(after, new MethodInsnNode(Opcodes.INVOKEVIRTUAL,
                    "paulscode/sound/Source", "cleanup", "()V", false));
            method.instructions.insertBefore(after, new InsnNode(Opcodes.ACONST_NULL)); // src = null;
            method.instructions.insertBefore(after, new VarInsnNode(Opcodes.ASTORE, varIndex));
        }

        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        classNode.accept(writer);
        return writer.toByteArray();
    }

    return basicClass;
}

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  w w .jav a2  s  .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.orfjackal.retrolambda.trywithresources.SwallowSuppressedExceptions.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(ASM5, next) {
        @Override/*from   ww  w  .j ava  2 s.  c o  m*/
        public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
            if (opcode == Opcodes.INVOKEVIRTUAL && owner.equals("java/lang/Throwable")
                    && name.equals("addSuppressed") && desc.equals("(Ljava/lang/Throwable;)V")) {
                super.visitInsn(Opcodes.POP); // the suppressed exception
                super.visitInsn(Opcodes.POP); // the original exception
            } else {
                super.visitMethodInsn(opcode, owner, name, desc, itf);
            }
        }
    };
}

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

License:Apache License

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

    if (obfuscated == true)
        targetMethodName = "b";
    else//from  www.j  av a  2s. co  m
        targetMethodName = "tick";
    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 INVOKEVIRTUAL_COUNT = 0;
            while (iter.hasNext()) {
                index++;
                currentNode = iter.next();
                if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
                    INVOKEVIRTUAL_COUNT++;
                    if (INVOKEVIRTUAL_COUNT == 9) {
                        targetNode = currentNode;
                        invok_index = index;
                        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 a1 = new MethodInsnNode(Opcodes.INVOKESPECIAL, "net/minecraft/world/WorldServer",
                    "resetRainAndThunder", "()V", false);

            method.instructions.set(p1, a1);
            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 ww. j  a va2s.  c  o m*/
        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();
}