A library that makes it easy to print bytecode instructions * including * parameters

I am looking for a library that will easily allow me to see the method provided by the bytecode. Example:

ALOAD 0 INVOKEVIRTUAL ns/cm ()I IRETURN 

I tried both:

  • ASM: I could get him to print instructions and parameters, but I have difficulties wrapping my head around the whole paradigm of visitors, that is, the best I did was beautifully print the whole class.
  • BCEL: Can it print instructions, but without parameters.
  • JavaAssist: can force it to print instructions, but no parameters.
+4
source share
2 answers

Take a look at the ASM source of TraceClassVisitor and TraceMethodVisitor for an example of printing bytecode data.

Here is a simple test class:

 import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import org.objectweb.asm.ClassReader; import org.objectweb.asm.util.TraceClassVisitor; public class Main { public static void main(String[] args) throws Exception { if (1 > args.length) { System.err.println("No arguments."); return; } InputStream is = Main.class.getResourceAsStream(args[0]); ClassReader cr = new ClassReader(is); cr.accept(new TraceClassVisitor(new PrintWriter(System.out)), 0); } } 

What are the outputs (when passed Main.class as an argument):

 // class version 50.0 (50) // access flags 0x21 public class Main { // compiled from: Main.java // access flags 0x1 public <init>()V L0 LINENUMBER 11 L0 ALOAD 0 INVOKESPECIAL java/lang/Object.<init> ()V RETURN MAXSTACK = 1 MAXLOCALS = 1 // access flags 0x9 public static main([Ljava/lang/String;)V throws java/lang/Exception L0 LINENUMBER 13 L0 ICONST_1 ALOAD 0 ARRAYLENGTH IF_ICMPLE L1 L2 LINENUMBER 14 L2 GETSTATIC java/lang/System.err : Ljava/io/PrintStream; LDC "No arguments." INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V L3 LINENUMBER 15 L3 RETURN L1 LINENUMBER 17 L1 FRAME SAME LDC LMain;.class ALOAD 0 ICONST_0 AALOAD INVOKEVIRTUAL java/lang/Class.getResourceAsStream (Ljava/lang/String;)Ljava/io/InputStream; ASTORE 1 L4 LINENUMBER 18 L4 NEW org/objectweb/asm/ClassReader DUP ALOAD 1 INVOKESPECIAL org/objectweb/asm/ClassReader.<init> (Ljava/io/InputStream;)V ASTORE 2 L5 LINENUMBER 19 L5 ALOAD 2 NEW org/objectweb/asm/util/TraceClassVisitor DUP NEW java/io/PrintWriter DUP GETSTATIC java/lang/System.out : Ljava/io/PrintStream; INVOKESPECIAL java/io/PrintWriter.<init> (Ljava/io/OutputStream;)V INVOKESPECIAL org/objectweb/asm/util/TraceClassVisitor.<init> (Ljava/io/PrintWriter;)V ICONST_0 INVOKEVIRTUAL org/objectweb/asm/ClassReader.accept (Lorg/objectweb/asm/ClassVisitor;I)V L6 LINENUMBER 28 L6 RETURN MAXSTACK = 6 MAXLOCALS = 3 } 
+4
source

Of these, ASM is the only one that supports the latest version of Java. As for visitors, you can read this tutorial . It was written for an older version of the ASM API, but visitor concepts are the same.

+1
source

Source: https://habr.com/ru/post/1379442/


All Articles