Jump to content

Using CPW Tweak Class


charsmud

Recommended Posts

Hello.  I am looking into using a coremod to inject code into a class.  After digging around a bit, I saw the Tweak class under the cpw package.  I have a few questions:  What exactly does the cpw Tweak class do, and is it a possible way for me to inject code into a class using something in Forge (possibly the tweak class, if that is what it does)? 

Link to comment
Share on other sites

Thanks, I've managed to get a basic coremod that recognizes the class and method working.  However, I cannot seem to figure out how to get the ASM part working.  Here is my ClassTransformer:

 

package timeTraveler.core;

import static org.objectweb.asm.Opcodes.FDIV;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.tree.AbstractInsnNode.METHOD_INSN;

import java.util.Iterator;

import net.minecraft.launchwrapper.IClassTransformer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;

public class TTClassTransformer implements IClassTransformer 
{

@Override
public byte[] transform(String arg0, String arg1, byte[] arg2) 
{
	//System.out.println(arg0);
	if (arg0.equals("aqz"))
	{
		System.out.println("********* INSIDE OBFUSCATED BLOCK TRANSFORMER ABOUT TO PATCH: " + arg0);
		return patchClassASM(arg0, arg2, true);
        }
	if (arg0.equals("net.minecraft.block.Block"))
	{
		System.out.println("********* INSIDE BLOCK TRANSFORMER ABOUT TO PATCH: " + arg0);
		return patchClassASM(arg0, arg2, false);
        }
        return arg2;
}

 public byte[] patchClassASM(String name, byte[] bytes, boolean obfuscated)
 {
	 	String targetMethodName = "";
        if(obfuscated == true)
        {
        	targetMethodName ="a";
        	System.out.println("******** Using obfuscated method");
        }
        else
        {
        	targetMethodName ="onBlockPlaced";
        	System.out.println("******** Using unobfuscated method");
        }
        //set up ASM class manipulation stuff. Consult the ASM docs for details
	    ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(bytes);
        classReader.accept(classNode, 0);

        //Now we loop over all of the methods declared inside the Block class until we get to the targetMethodName "onBlockPlaced"
        // find method to inject into
        @SuppressWarnings("unchecked")
        Iterator<MethodNode> methods = classNode.methods.iterator();
        while(methods.hasNext())
        {
            MethodNode m = methods.next();
            System.out.println("********* Method Name: "+m.name + " Desc:" + m.desc);
            int fdiv_index = -1;
            //Check if this is onBlockPlaced and it's method signature is (Lnet/minecraft/world/World;IIIIFFFI)I
            if ((m.name.equals(targetMethodName) && m.desc.equals("(Lnet/minecraft/world/World;IIIIFFFI)I")))
            {
                System.out.println("********* Inside target method!");
                // find interesting instructions in method, there is a single FDIV instruction we use as target
                //System.out.println("m.instructions.size = " + m.instructions.size());

                InsnList toInject = new InsnList();
                //TODO: NEED TO CONVERT THIS TO JAVA CODE TO INJECT
                //LINENUMBER 87 L0
    				//NEW timeTraveler/mechanics/BlockPlaceEvent
    				//DUP
				//ALOAD 0
				//ILOAD 2
				//ILOAD 3
				//ILOAD 4
				//INVOKESPECIAL timeTraveler/mechanics/BlockPlaceEvent.<init> (Lnet/minecraft/block/Block;III)V
				//ASTORE 5
				//L1
				//LINENUMBER 88 L1
				//GETSTATIC net/minecraftforge/common/MinecraftForge.EVENT_BUS : Lnet/minecraftforge/event/EventBus;
				//ALOAD 5
				//INVOKEVIRTUAL net/minecraftforge/event/EventBus.post (Lnet/minecraftforge/event/Event;)Z
				//POP
				//L2
                /*
                //To add new instructions, such as calling a static method can be done like so:
                
                // make new instruction list
                InsnList toInject = new InsnList();
               
				toInject.add(new VarInsnNode(ALOAD, 0));
                    toInject.add(new MethodInsnNode(INVOKESTATIC, "mod/culegooner/MyStaticClass", "myStaticMethod", "()V"));
                
                // inject new instruction list into method instruction list
                m.instructions.insert(targetNode, toInject);
                */
                
                AbstractInsnNode currentNode = null;
                AbstractInsnNode targetNode = null;

                @SuppressWarnings("unchecked")
                Iterator<AbstractInsnNode> iter = m.instructions.iterator();
                int index = -1;

                //Loop over the instruction set and find the instruction FDIV which does the division of 1/explosionSize
                while (iter.hasNext())
                {
                    index++;
                    currentNode = iter.next();
                    System.out.println("********* index : " + index + " currentNode.getOpcode() = " + currentNode.getOpcode());
                    //Found it! save the index location of instruction FDIV and the node for this instruction
                    if (currentNode.getOpcode() == FDIV)
                    {
                    	targetNode = currentNode;
                        fdiv_index = index;
                    }
                }
                System.out.println("********* fdiv_index should be 336 -> " + fdiv_index);
                if (targetNode == null)
                {
                    System.out.println("Did not find all necessary target nodes! ABANDON CLASS!");
                    return bytes;
                }
                if (fdiv_index == -1)
                {
                    System.out.println("Did not find all necessary target nodes! ABANDON CLASS!");
                    return bytes;
                }
                /*
                 //now we want the save nods that load the variable explosionSize and the division instruction:

                 The line in Explosion.java that we want to modify is:
                 
                 var25.dropBlockAsItemWithChance(this.worldObj, var4, var5, var6, this.worldObj.getBlockMetadata(var4, var5, var6), 1.0F / this.explosionSize, 0);
                 
                 The code we are looking for is the following in bytecode:
                 
                 mv.visitInsn(FCONST_1);
				 mv.visitVarInsn(ALOAD, 0);
                     mv.visitFieldInsn(GETFIELD, "net/minecraft/src/Explosion", "explosionSize", "F");
                     mv.visitInsn(FDIV);
                     mv.visitInsn(ICONST_0);
                     mv.visitMethodInsn(INVOKEVIRTUAL, "net/minecraft/src/Block", "dropBlockAsItemWithChance", "(Lnet/minecraft/src/World;IIIIFI)V");
                     */
                AbstractInsnNode remNode1 = m.instructions.get(fdiv_index-2); // mv.visitVarInsn(ALOAD, 0);
                AbstractInsnNode remNode2 = m.instructions.get(fdiv_index-1); // mv.visitFieldInsn(GETFIELD, "net/minecraft/src/Explosion", "explosionSize", "F");
                AbstractInsnNode remNode3 = m.instructions.get(fdiv_index);   // mv.visitInsn(FDIV);
                //This part is just to show how if the opcode we are looking for is an invokevirtual
                AbstractInsnNode invVirt = m.instructions.get(fdiv_index+2);
                if(invVirt.getOpcode() == INVOKEVIRTUAL)
                {
                	if(invVirt.getType() == METHOD_INSN){
                		 System.out.println("INVOKEVIRTUAL opcode is  " + invVirt.getOpcode() + " METHOD_INSN type is " + invVirt.getType()  );

                		 MethodInsnNode testMethod = (MethodInsnNode)invVirt; //only do this cast if the getType match to a MethodInsnNode!! look at the javadoc for the other types!
                		 System.out.println("INVOKEVIRTUAL :" + testMethod.owner + " , " +  testMethod.name + " , " + testMethod.desc );
                	}
                }
                //just remove these nodes from the instruction set, this will prevent the instruction FCONST_1 to be divided.
                m.instructions.remove(remNode1);
                m.instructions.remove(remNode2);
                m.instructions.remove(remNode3);
                //in this commented section, i'll just illustrate how to inject a call to a static method if your instruction is a little more advanced than just removing a couple of instruction:

                /*
                //To add new instructions, such as calling a static method can be done like so:
                
                // make new instruction list
                InsnList toInject = new InsnList();
               
				toInject.add(new VarInsnNode(ALOAD, 0));
                    toInject.add(new MethodInsnNode(INVOKESTATIC, "mod/culegooner/MyStaticClass", "myStaticMethod", "()V"));
                
                // inject new instruction list into method instruction list
                m.instructions.insert(targetNode, toInject);
                */
                System.out.println("Patching Complete!");
                break;
            }
        }
        //ASM specific for cleaning up and returning the final bytes for JVM processing.
        ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
        classNode.accept(writer);
        return writer.toByteArray();
      }
}

 

Any ideas?  (Note:  I'm following a tutorial, but it doesn't explain the actual ASM part very well). 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Slot Bank BRI atau Daftar slot Bank BRI bisa anda lakukan pada situs Museumbola kapanpun dan dimanapun, Bermodalkan Hp saja anda bisa mengakses chat ke agen kami selama 24 jam full. keuntungan bergabung bersama kami di Museumbola adalah anda akan mendapatkan bonus 50% khusus member baru yang bergabung dan deposit. Tidak perlu banyak, 10 ribu rupiah saja anda sudah bisa bermain bersama kami di Museumbola. Tunggu apa lagi ? Segera Klik DAFTAR dan anda akan jadi Jutawan dalam semalam.    
    • Museumbola adalah situs judi slot BANK BCA tergacor 2024 dengan minimal deposit  10 ribu rupiah saja anda sudah bisa spin slot gacor di Museumbola. Mulai dari Pragmatic, Pg Soft, Habanero, Playstar, Spadegaming, dan masih banyak lagi. Pilihan slot yang begitu banyak tidak akan membuat anda bosan. Segera daftarkan BANK BCA anda dan jadi member aktif Museumbola. anda akan diberi kesempatan mendapatkan bonus deposit harian setiap hari. Segera Klik DAFTAR sekarang juga sebelum terlambat.  
    • Slot BANK BCA adalah pilihan tergacor untuk memulai bermain slot judi Online dimuka bumi saat ini. Jika anda mempunyai BANK BCA, Anda berkesempatan mendapatkan Akun Pro atau ID pro untuk bermain slot. Tunggu apa lagi? Segera daftarkan diri anda sekarang dan dapatkan kemewahan menang maxwin di Museumbola.
    • SLOT SCATTER HITAM : SLOT MAHJONG SCATTER HITAM - MAHJONG WAYS SCATTER HITAM - SLOT PRAGMATIC SCATTER HITAM KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << SITUS SLOT GACOR 88 MAXWIN X500 HARI INI TERBAIK DAN TERPERCAYA GAMPANG MENANG Dunia Game gacor terus bertambah besar seiring berjalannya waktu, dan sudah tentu dunia itu terus berkembang serta merta bersamaan dengan berkembangnya SLOT GACOR sebagai website number #1 yang pernah ada dan tidak pernah mengecewakan sekalipun. Dengan banyaknya member yang sudah mempercayakan untuk terus menghasilkan uang bersama dengan SLOT GACOR pastinya mereka sudah percaya untuk bermain Game online bersama dengan kami dengan banyaknya testimoni yang sudah membuktikan betapa seringnya member mendapatkan jackpot besar yang bisa mencapai ratusan juta rupiah. Best online Game website that give you more money everyday, itu lah slogan yang tepat untuk bermain bersama SLOT GACOR yang sudah pasti menang setiap harinya dan bisa menjadikan bandar ini sebagai patokan untuk mendapatkan penghasilan tambahan yang efisien dan juga sesuatu hal yang fix setiap hari nya. Kami juga mendapatkan julukan sebagai Number #1 website bocor yang berarti terus memberikan member uang asli dan jackpot setiap hari nya, tidak lupa bocor itu juga bisa diartikan dalam bentuk berbagi promosi untuk para official member yang terus setia bermain bersama dengan kami. Berbagai provider Game terus bertambah banyak setiap harinya dan terus melakukan support untuk membuat para official member terus bisa menang dan terus maxwin dalam bentuk apapun maka itu langsung untuk feel free to try yourself, play with SLOT GACOR now or never !
    • SLOT 1000 : SLOT1000 DEPOSIT 1000 VIA DANA - SLOT 1000 VIA QRIS - SLOT DEPOSIT QRIS 1000 - SLOT DEPO 1K - SLOT 1000 BET KECIL KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << KLIK DISINI DAFTAR DISINI SLOT VVIP << SITUS SLOT GACOR 88 MAXWIN X500 HARI INI TERBAIK DAN TERPERCAYA GAMPANG MENANG Dunia Game gacor terus bertambah besar seiring berjalannya waktu, dan sudah tentu dunia itu terus berkembang serta merta bersamaan dengan berkembangnya SLOT GACOR sebagai website number #1 yang pernah ada dan tidak pernah mengecewakan sekalipun. Dengan banyaknya member yang sudah mempercayakan untuk terus menghasilkan uang bersama dengan SLOT GACOR pastinya mereka sudah percaya untuk bermain Game online bersama dengan kami dengan banyaknya testimoni yang sudah membuktikan betapa seringnya member mendapatkan jackpot besar yang bisa mencapai ratusan juta rupiah. Best online Game website that give you more money everyday, itu lah slogan yang tepat untuk bermain bersama SLOT GACOR yang sudah pasti menang setiap harinya dan bisa menjadikan bandar ini sebagai patokan untuk mendapatkan penghasilan tambahan yang efisien dan juga sesuatu hal yang fix setiap hari nya. Kami juga mendapatkan julukan sebagai Number #1 website bocor yang berarti terus memberikan member uang asli dan jackpot setiap hari nya, tidak lupa bocor itu juga bisa diartikan dalam bentuk berbagi promosi untuk para official member yang terus setia bermain bersama dengan kami. Berbagai provider Game terus bertambah banyak setiap harinya dan terus melakukan support untuk membuat para official member terus bisa menang dan terus maxwin dalam bentuk apapun maka itu langsung untuk feel free to try yourself, play with SLOT GACOR now or never !
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.