Reputation: 104
Consider I have this java program.
public class Main {
public static void main(String []args){
String a = "Dad";
System.out.println(a);
}
Now I have a ASM code to traverse through the method nodes and can access the instruction in the method. Say I added the invoke method and a ldc for adding a simple print statement. [![enter image description here][1]][1]
for(Object methodNodeObj : classNode.methods) {
MethodNode methodNode = (MethodNode)methodNodeObj;
for(AbstractInsnNode abstractInsnNode : methodNode.instructions.toArray()) {
}
InsnList il = new InsnList();
il.add(new FieldInsnNode(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"));
il.add(new LdcInsnNode("Works!"));
il.add(new MethodInsnNode(INVOKEVIRTUAL, "java/io/PrintStream", "encode", "(Ljava/lang/String;)V"));
methodNode.instructions.insertBefore(abstractNode, il);
This helps in printing a statement... Suppose if I have a ALOAD statement that is, there is a variable usage, I want to call encode function call such that the variable is encoded during the usage.. So my plan is to add encode invoke stmt after the ALOAD statement. How to achieve this?
Upvotes: 2
Views: 1220
Reputation: 345
So you have to call encode method with string arg.
First of all you have to write method: public static String encode(String arg) { /* Some code */ }
Than you can call that method via asm
il.add(new FieldInsnNode(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"));
// 1 - first variable in non-static function
// 0 - first variable in static funcnion. Choose wisely.
il.add(new VarInsnNode(Opcodes.ALOAD, 1);
// itf must be true if full.path.to.Class is interface
il.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "full/path/to/Class", "encode", "(Ljava/lang/String;)Ljava/lang/String;", false);
il.add(new MethodInsnNode(INVOKEVIRTUAL, "java/io/PrintStream", "encode", "(Ljava/lang/String;)V"));
methodNode.instructions.insertBefore(abstractNode, il);
Upvotes: 0