Question

I am wondering why the line numbers of Java Bytecode are not consecutive.

What happens for example in the (not listed) lines 2 and 3 of the following getter?

public java.lang.String getX();

Code:
0:   aload_0
1:   getfield        #2; //Field x:Ljava/lang/String;
4:   areturn

I'm using the ASM framework to work on bytecode. When visiting the code of a method using the tree API I get these "hidden" instructions as well (however with opcode -1). I would like to know what they are for.

Was it helpful?

Solution

I don't think that 0, 1, 4 are linenumbers but byte offsets in the bytecode.

  • aload_0 is one byte
  • getfield is three bytes (one opcode, one "index" arg with two bytes"
  • areturn is one byte

So 2 and 3 are simply part of the getfield operation.

OTHER TIPS

A little explanation

The size of the array of local variables is determined at compile time and is dependent on the number and size of local variables and formal method parameters. The operand stack is a LIFO stack used to push and pop values. Its size is also determined at compile time. Certain opcode instructions push values onto the operand stack; others take operands from the stack, manipulate them, and push the result. The operand stack is also used to receive return values from methods.

public String getBar(){ 
    return bar; 
  }

  public java.lang.String getBar();
    Code:
      0:   aload_0
      1:   getfield        #2; //Field bar:Ljava/lang/String;
      4:   areturn

The bytecode for the method above consists of three opcode instructions. The first opcode, aload_0, pushes the value from index 0 of the local variable table onto the operand stack. The this reference is always stored at location 0 of the local variable table for constructors and instance methods. The next opcode instruction, getfield, is used to fetch a field from an object. The last instruction, areturn, returns a reference from a method.

Each method has a corresponding bytecode array. Looking at a .class file with a hex editor, you would see the following values in the bytecode array:

That said, the bytecode for getBar method is 2A B4 00 02 B0. The code 2A corresponds to aload_0 instruction, and B0 corresponds to areturn. It might seem strange that the bytecode of the method has 3 instructions, but the byte array holds 5 elements. This is because the getfield (B4) requires 2 parameters to be supplied (00 02), and those parameters occupy positions 2 and 3 in the array, hence the array size is 5 and areturn instruction is shifted to the position 4.

Source

Java bytecode instruction listings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top