jvm 字节码的执行
javap class文件的反汇编工具
package javap; /** * @Package Name : ${PACKAG_NAME} * @Author : [email protected] * @Creation Date : 2018年06月30日下午5:55 * @Function : todo */ public class Calc { public int calc() { int a = 500; int b = 200; int c = 50; return (a + b) / c; } }
javap –verbose Calc
Warning: File ./Calc.class does not contain class Calc
Classfile /Users/dongfucai/dongpractice/target/classes/javap/Calc.class
Last modified 2018年6月30日; size 393 bytes
MD5 checksum b24b3aa73990f1c1ef0c28bd1643c9c0
Compiled from "Calc.java"
public class javap.Calc
minor version: 0
major version: 52
flags: (0x0021) ACC_PUBLIC, ACC_SUPER
this_class: #2 // javap/Calc
super_class: #3 // java/lang/Object
interfaces: 0, fields: 0, methods: 2, attributes: 1
Constant pool:
#1 = Methodref #3.#19 // java/lang/Object."<init>":()V
#2 = Class #20 // javap/Calc
#3 = Class #21 // java/lang/Object
#4 = Utf8 <init>
#5 = Utf8 ()V
#6 = Utf8 Code
#7 = Utf8 LineNumberTable
#8 = Utf8 LocalVariableTable
#9 = Utf8 this
#10 = Utf8 Ljavap/Calc;
#11 = Utf8 calc
#12 = Utf8 ()I
#13 = Utf8 a
#14 = Utf8 I
#15 = Utf8 b
#16 = Utf8 c
#17 = Utf8 SourceFile
#18 = Utf8 Calc.java
#19 = NameAndType #4:#5 // "<init>":()V
#20 = Utf8 javap/Calc
#21 = Utf8 java/lang/Object
{
public javap.Calc();
descriptor: ()V
flags: (0x0001) ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 9: 0
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this Ljavap/Calc;
public int calc();
descriptor: ()I
flags: (0x0001) ACC_PUBLIC
Code:
stack=2, locals=4, args_size=1
0: sipush 500
3: istore_1
4: sipush 200
7: istore_2
8: bipush 50
10: istore_3
11: iload_1
12: iload_2
13: iadd
14: iload_3
15: idiv
16: ireturn
LineNumberTable:
line 11: 0
line 12: 4
line 13: 8
line 14: 11
LocalVariableTable:
Start Length Slot Name Signature
0 17 0 this Ljavap/Calc;
4 13 1 a I
8 9 2 b I
11 6 3 c I
}
SourceFile: "Calc.java"
------------------
Code:
stack=2, locals=4, args_size=1
0: sipush 500
3: istore_1
4: sipush 200
7: istore_2
8: bipush 50
10: istore_3
11: iload_1
12: iload_2
13: iadd
14: iload_3
15: idiv
16: ireturn
0 3 4 表示偏移量
--------------------------
简单的字节码执行过程
每一次方法调用创建一个帧,并压栈。
sipush:500入栈
istore_1 //弹出操作数栈栈顶元素,保存到局部变量表第1个位置
当int取值-1~5采用iconst指令,取值-128~127采用bipush指令,取值-32768~32767采用sipush指令,取值-2147483648~2147483647采用 ldc 指令。
当int取值-1~5采用iconst指令,取值-128~127采用bipush指令,取值-32768~32767采用sipush指令,取值-2147483648~2147483647采用 ldc 指令。
iload_1第一个局部变量压栈
iadd 2个数出栈 相加,和 入栈
idiv 2元素出栈 结果入栈
ireturn将栈顶的整数返回
---------------------------------------
字节码指令为一个byte整数
nop = 0, // 0x00
_aconst_null = 1, // 0x01
_iconst_0 = 3, // 0x03
_iconst_1 = 4, // 0x04
_dconst_1 = 15, // 0x0f
_bipush = 16, // 0x10
_iload_0 = 26, // 0x1a
_iload_1 = 27, // 0x1b
_aload_0 = 42, // 0x2a
_istore = 54, // 0x36
_pop = 87, // 0x57
_imul = 104, // 0x68
_idiv = 108, // 0x6c