-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpreter.go
81 lines (70 loc) · 1.78 KB
/
interpreter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"JVM/rtdz"
"fmt"
"JVM/instructions/base"
"JVM/instructions"
"JVM/rtdz/heap"
)
func interpret(method *heap.Method, logInst bool, args []string) {
thread := rtdz.NewThread()
frame := thread.NewFrame(method)
thread.PushFrame(frame)
jArgs := createArgsArray(method.Class().Loader(), args)
frame.LocalVars().SetRef(0, jArgs)
defer catch(thread)
loop(thread, logInst)
}
func createArgsArray(loader *heap.ClassLoader, args []string) *heap.Object {
stringKls := loader.LoadClass("java/lang/String")
argsArr := stringKls.ArrayClass().NewArray(uint(len(args)))
jArgs := argsArr.Refs()
for i, arg := range args {
jArgs[i] = heap.JString(loader, arg)
}
return argsArr
}
func catch(thread *rtdz.Thread) {
if r := recover(); r != nil {
logFrames(thread)
panic(r)
}
}
func loop(thread *rtdz.Thread, logInst bool) {
reader := &base.BytecodeReader{}
for {
frame := thread.CurrentFrame()
pc := frame.NextPC()
thread.SetPC(pc)
//decode
reader.Reset(frame.Method().Code(), pc)
opcode := reader.ReadUint8()
inst := instructions.NewInstruction(opcode)
inst.FetchOperands(reader)
frame.SetNextPC(reader.PC())
if logInst {
logInstruction(frame, inst)
}
//exec
inst.Execute(frame)
if thread.IsStackEmpty() {
break
}
}
}
func logInstruction(frame *rtdz.Frame, inst base.Instruction) {
method := frame.Method()
className := method.Class().Name()
methodName := method.Name()
pc := frame.Thread().PC()
fmt.Printf("%v.%v() #%2d %T %v\n", className, methodName, pc, inst, inst)
}
func logFrames(thread *rtdz.Thread) {
for !thread.IsStackEmpty() {
frame := thread.PopFrame()
method := frame.Method()
className := method.Class().Name()
fmt.Printf(">> pc:%4d %v.%v%v \n",
frame.NextPC(), className, method.Name(), method.Descriptor())
}
}