这些Java字节偏移是如何计算的?

时间:2015-05-14 14:38:51

标签: java jvm bytecode

我有以下Java代码:

public int sign(int a) {
  if(a<0) return -1;
  else if (a>0) return 1;
  else return 0;
}

编译时生成以下字节码:

public int sign(int);
  Code:
     0: iload_1
     1: ifge          6
     4: iconst_m1
     5: ireturn
     6: iload_1
     7: ifle          12
    10: iconst_1
    11: ireturn
    12: iconst_0
    13: ireturn

我想知道如何计算字节偏移计数(第一列),特别是当所有其他指令都是3字节时,为什么ifgeifle指令的字节数是单字节指令?

2 个答案:

答案 0 :(得分:5)

正如评论中已经指出的那样:ifgeifle指令有额外的偏移量。

Java Virtual Machine Instruction Set specification for ifge and ifle包含相关提示:

  

格式

if<cond>
branchbyte1
branchbyte2

这表示该指令有两个附加字节,即“分支字节”。这些字节由单个short值组成,以确定偏移量 - 即,当条件满足时,指令指针应该“跳转”多远。

  

编辑:

评论让我很好奇:offset被定义为签名的 16位值,将跳转限制在+/- 32k的范围内。这不包括may contain up to 65535 bytes according to the code_length in the class file的可能方法的整个范围。

所以我创建了一个测试类,看看会发生什么。这个类看起来像这样:

class FarJump
{
    public static void main(String args[])
    {
        call(0, 1);
    }

    public static void call(int x, int y)
    {
        if (x < y)
        {
            y++;
            y++;

            ... (10921 times) ...

            y++;
            y++;
        }
        System.out.println(y);
    }

}

每个y++行将被转换为iinc指令,由3个字节组成。所以生成的字节码是

public static void call(int, int);
    Code:
       0: iload_0
       1: iload_1
       2: if_icmpge     32768
       5: iinc          1, 1
       8: iinc          1, 1

       ...(10921 times) ...

    32762: iinc          1, 1
    32765: iinc          1, 1
    32768: getstatic     #3             // Field java/lang/System.out:Ljava/io/PrintStream;
    32771: iload_1
    32772: invokevirtual #4             // Method java/io/PrintStream.println:(I)V
    32775: return

可以看到它仍然使用if_icmpge指令,偏移量为32768(编辑:它是绝对偏移。相对偏移量是32766.另见this question

通过在原始代码中再添加一个y++,编译后的代码突然变为

public static void call(int, int);
    Code:
       0: iload_0
       1: iload_1
       2: if_icmplt     10
       5: goto_w        32781
      10: iinc          1, 1
      13: iinc          1, 1
      ....
    32770: iinc          1, 1
    32773: iinc          1, 1
    32776: goto_w        32781
    32781: getstatic     #3             // Field java/lang/System.out:Ljava/io/PrintStream;
    32784: iload_1
    32785: invokevirtual #4             // Method java/io/PrintStream.println:(I)V
    32788: return

因此它将条件从if_icmpge反转为if_icmplt,并使用goto_w指令处理远跳,该指令包含四个分支字节,因此可以覆盖(超过)一个完整的方法范围。

答案 1 :(得分:2)

可以通过将前面每条指令的大小相加来轻松计算字节偏移量。指令大小记录在JVM specs

if<cond>指令占用的空间比其他指令多,因为除了单字节操作码之外,它们还有两个额外的字节,指定跳转到的条件,如果条件为真。

如果你想进一步试验,你可以尝试在你的代码中使用更大的常量(例如,20)。您将看到加载这些内容的指令也将使用额外的字节来存储常量值。常用的小数字具有单字节编码(例如iconst_1)以提高效率。