Search code examples
javacode-injectionjavassist

Javassist no such field when variable clearly exists


I am trying to inject code into the minecraft 1.8 jar using javassist. The insertBefore & insertAfter methods work perfectly fine. But the insert at method does not work as expected. I am getting this error: https://gist.github.com/czaarek99/dda36426318f331ce6b0

Here is the code that handles the injection:

if (className.equals(mappingManager.getMapping(CommonMappings.MINECRAFT_CLASS))) {

    CtClass ctClass = classPool.get(mappingManager.getMapping(CommonMappings.MINECRAFT_CLASS, true)); //returns "bsu"

    CtMethod tickMethod = ctClass.getDeclaredMethod(mappingManager.getMapping(CommonMappings.RUN_TICK_METHOD)); //returns "r"
    tickMethod.insertBefore("EventManager.call(new TickEvent(TickEvent.PRE_UPDATE));");
    tickMethod.insertAfter("EventManager.call(new TickEvent(TickEvent.POST_UPDATE));");

    String varName = mappingManager.getMapping(CommonMappings.KEYBOARD_KEYCODE_VARIABLE); //returns "var1"

    int lineToInsertAt = Integer.valueOf(mappingManager.getMapping(CommonMappings.KEYBOARD_NEXT_LINE)); //returns "1372"
    tickMethod.insertAt(lineToInsertAt, true, "KeyPressEvent keyPressEvent = new KeyPressEvent("+ varName +");EventManager.call(keyPressEvent);");;

    CtMethod runGameMethod = ctClass.getDeclaredMethod(mappingManager.getMapping(CommonMappings.START_GAME_METHOD)); //returns "aj"
    runGameMethod.insertAfter("InjectClient.getInstance().loadModules();");

    byte[] newCode = ctClass.toBytecode(); //line that throws the error
    ctClass.detach();

    return newCode;
} 

I have commented the lines where it grabs a mapping, essentially these are minecraft obfuscated variable & function names since this is what I will be inserting to.

Alright, so the logical explanation is that var1 does not exist? That's not true. If we have a look at the code for the obfuscated bsu class we can see this: enter image description here


Solution

  • Alright I figured it out. Turns out javassist does not know if a local variable is defined and it assumed var1 was a field. I solved it by just creating my own variable and setting the it to the same value as var1 has.

    Source: http://jboss-javassist.github.io/javassist/tutorial/tutorial2.html