jvm 第5章 jvm 指令集和解释器
1,https://github.com/zxh0/jvmgo-book提供的源代码
package main
import "fmt"
import "jvmgo/ch05/classfile"
import "jvmgo/ch05/instructions"
import "jvmgo/ch05/instructions/base"
import "jvmgo/ch05/rtda"
func interpret(methodInfo *classfile.MemberInfo) {
codeAttr := methodInfo.CodeAttribute()
maxLocals := codeAttr.MaxLocals()
maxStack := codeAttr.MaxStack()
bytecode := codeAttr.Code()
fmt.Printf("IMF code: %v\n",bytecode)
thread := rtda.NewThread()
frame := thread.NewFrame(maxLocals, maxStack)
thread.PushFrame(frame)
defer catchErr(frame)
loop(thread, bytecode)
}
func catchErr(frame *rtda.Frame) {
if r := recover(); r != nil {
fmt.Printf("LocalVars:%v\n", frame.LocalVars())
fmt.Printf("OperandStack:%v\n", frame.OperandStack())
panic(r)
}
}
func loop(thread *rtda.Thread, bytecode []byte) {
frame := thread.PopFrame()
reader := &base.BytecodeReader{}
for {
pc := frame.NextPC()
thread.SetPC(pc)
// decode
reader.Reset(bytecode, pc)
opcode := reader.ReadUint8()
fmt.Printf("IMF opcode: %v\n",opcode)
inst := instructions.NewInstruction(opcode)
inst.FetchOperands(reader)
frame.SetNextPC(reader.PC())
// execute
fmt.Printf("pc:%2d inst:%T %v\n", pc, inst, inst)
inst.Execute(frame)
}
}
2,写一个简单的java代码
package jvmgo.book.ch05;
public class Ch05addTest {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <=2; i++) {
sum += i;
}
System.out.println(sum);
}
}
3,jvavc 编译成Ch05addTest.class
4, go jvm 运行结果: