-
Notifications
You must be signed in to change notification settings - Fork 1
/
load.go
119 lines (95 loc) · 2.28 KB
/
load.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package mruby
import (
"bytes"
"encoding/binary"
"errors"
"io"
"github.com/elct9620/mruby-go/insn"
)
var (
ErrSectionOverSize = errors.New("section size larger than binary size")
)
// LoadString execute string
func (s *State) LoadString(code string) (Value, error) {
compiled, err := Compile(bytes.NewBufferString(code))
if err != nil {
return nil, err
}
return s.LoadIRep(bytes.NewBufferString(string(compiled)))
}
// Load execute RITE binary
func (mrb *State) LoadIRep(r io.Reader) (Value, error) {
proc, err := readIRep(mrb, r)
if err != nil {
return nil, err
}
return mrb.TopRun(proc, mrb.TopSelf())
}
func readIRep(mrb *State, r io.Reader) (RProc, error) {
var header binaryHeader
err := binaryRead(r, &header)
if err != nil {
return nil, err
}
var irep *insn.Representation
remain := header.Size - binaryHeaderSize
for remain > sectionHeaderSize {
header, err := readSectionHeader(r, remain)
switch header.String() {
case sectionTypeIRep:
irep, err = readSectionIRep(mrb, r, header.Size)
case sectionTypeDebug:
err = noopSection(r, header.Size)
case sectionTypeLv:
err = noopSection(r, header.Size)
case sectionTypeEof:
break
}
if err != nil {
return nil, err
}
remain -= header.Size
}
return &proc{
body: irep,
}, nil
}
func readSectionHeader(r io.Reader, remain uint32) (*sectionHeader, error) {
var header sectionHeader
err := binaryRead(r, &header)
if err != nil {
return nil, err
}
isOverSize := header.Size > remain
if isOverSize {
return nil, ErrSectionOverSize
}
return &header, nil
}
func readSectionIRep(mrb *State, r io.Reader, size uint32) (*insn.Representation, error) {
var riteVersion [4]byte
err := binaryRead(r, &riteVersion)
if err != nil {
return nil, err
}
irepSize := size - sectionHeaderSize - 4
binary := make([]byte, irepSize)
_, err = r.Read(binary)
if err != nil {
return nil, err
}
sizeStripped := binary[4:]
reader := insn.NewBinaryReader(bytes.NewReader(sizeStripped))
return insn.NewRepresentation(mrb, reader)
}
func noopSection(r io.Reader, size uint32) error {
buffer := make([]byte, size-sectionHeaderSize)
_, err := r.Read(buffer)
if err != nil {
return err
}
return nil
}
func binaryRead(r io.Reader, data any) error {
return binary.Read(r, binary.BigEndian, data)
}