tinycodinglm / lang /lang-0028.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.97 kB
opencode trace
System You are an expert Java bytecode engineer specializing in ASM, bytecode manipulation, and class transformation.

You are an expert Java bytecode engineer specializing in ASM, bytecode manipulation, and class transformation.

User

How do I use MethodVisitor to add instructions to a method? Show me examples of visiting different instruction types and manipulating the operand stack.

Assistant

MethodVisitor allows you to visit and modify individual instructions within a method:

import org.objectweb.asm.*;

public class MethodVisitorExample {
public static void main(String[] args) {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cw.visit(Opcodes.V11, Opcodes.ACC_PUBLIC, "Example", null, "java/lang/Object", null);
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "doWork", "()V", null, null);
mv.visitCode();

markdown
mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    mv.visitLdcInsn("Hello, ASM!");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);

    mv.visitInsn(Opcodes.ICONST_2);
    mv.visitInsn(Opcodes.ICONST_3);
    mv.visitInsn(Opcodes.IADD);
    mv.visitVarInsn(Opcodes.ISTORE, 1);

    Label label = new Label();
    mv.visitVarInsn(Opcodes.ILOAD, 1);
    mv.visitJumpInsn(Opcodes.IF_ICMPGE, label);
    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    mv.visitLdcInsn("Less than 5");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
    mv.visitLabel(label);

    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(2, 2);
    mv.visitEnd();
    cw.visitEnd();
}

}

Key instruction categories:

  • visitCode() starts the method bytecode
  • visitInsn(opcode) executes zero-operand instructions (IADD, ICONST_0..5, RETURN, POP, DUP, etc.)
  • visitIntInsn(opcode, operand) for BIPUSH and SIPUSH
  • visitVarInsn(opcode, var) for local variable load/store (ILOAD, ISTORE, ALOAD, ASTORE, etc.)
  • visitLdcInsn(cst) loads constants (strings, int/long/float/double, class references, method handles)
  • visitFieldInsn(opcode, owner, name, desc) for field access (GETFIELD, PUTFIELD, GETSTATIC, PUTSTATIC)
  • visitMethodInsn(opcode, owner, name, desc, isInterface) for method calls (INVOKEVIRTUAL, INVOKESTATIC, INVOKEINTERFACE, INVOKESPECIAL)
  • visitJumpInsn(opcode, label) for conditional and unconditional jumps
  • visitLabel(label) marks a bytecode position as a jump target
  • visitMaxs(maxStack, maxLocals) must be called even with COMPUTE_FRAMES (placeholder)