I need to use ASM to find a local variable inside a method, which is:
String var4 = "hello!";
I have created three classes. One that does the transformation, one that extends ClassVisitor, and one that extends MethodVisitor, like so:
Transformer entry point (Transformationer.java)
package RainbowBansTransAgent;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import org.objectweb.asm.*;
public class Transformationer implements ClassFileTransformer {
public byte[] transform(String arg1, byte[] arg2){
ClassReader cr = new ClassReader(arg2);
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES);
cr.accept(cw, 0);
return cw.toByteArray();
}
@Override
public byte[] transform(ClassLoader arg0, String className, Class<?> arg2,
ProtectionDomain arg3, byte[] arg4)
throws IllegalClassFormatException {
BooleanKeys.transformer_loaded = true;
byte[] b = null;
String realName = className.replaceAll("/", ".");
if(realName.equals("joebkt.PlayerList")){
if(BooleanKeys.returned_bytes){
return null;
}else{
BooleanKeys.found_class = true;
b = transform(realName, arg4);
if(b !=null){
BooleanKeys.returned_bytes = true;
}
}
}
else System.out.println("Class name " + realName + " is not what we're looking for!");
return b;
}
}
ClassVisior Extender (RBClassVisitor.java)
package RainbowBansTransAgent;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
public class RBClassVisitor extends ClassVisitor{
public RBClassVisitor() {
super(Opcodes.ASM5);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature,
exceptions);
return new RBMethodVisitor(mv);
}
}
MethodVisitor Extender (RBMethodVisitor.java)
package RainbowBansTransAgent;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
public class RBMethodVisitor extends MethodVisitor {
MethodVisitor mv;
public RBMethodVisitor(MethodVisitor mv) {
super(Opcodes.ASM5, mv);
this.mv = mv;
}
public void visitLineNumber(int line, Label start){
if(line == 409){
mv.visitCode();
}
}
public void visitCode(){
}
}
As you can see, my visitCode() method is empty. I understand this is the method where the bytecode manipulation is supposed to happen.
I saw that MethodVisitor has a
mv.visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index);
method, but I have no idea how to use the Label class correctly.
My transformer will read a file, and change the variable to the contents of the file. Using ASM, how do I do that?
EDIT: My bytecode for the thing I want to change says: ldc "hello!" (java.lang.String)
and I want to change it to:
ldc "goodbye!" (java.lang.String)