/
init_expr.go
83 lines (76 loc) · 1.69 KB
/
init_expr.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
package wasmgo
import (
"bytes"
"encoding/binary"
"io"
"github.com/eosspark/eos-go/wasmgo/wagon/wasm/leb128"
ops "github.com/eosspark/eos-go/wasmgo/wagon/wasm/operators"
)
// readU32 reads an unsigned 32-bit integer from a reader.
func readU32(r io.Reader) (uint32, error) {
var buf [4]byte
_, err := io.ReadFull(r, buf[:])
if err != nil {
return 0, err
}
return binary.LittleEndian.Uint32(buf[:]), nil
}
// readU64 reads an unsigned 64-bit integer from a reader.
func readU64(r io.Reader) (uint64, error) {
var buf [8]byte
_, err := io.ReadFull(r, buf[:])
if err != nil {
return 0, err
}
return binary.LittleEndian.Uint64(buf[:]), nil
}
// executeInitExpr executes and returns the result of a WebAssembly init expression.
func execInitExpr(expr []byte, globals []int64) int64 {
var stack []int64
r := bytes.NewReader(expr)
for {
b, err := r.ReadByte()
if err == io.EOF {
break
} else if err != nil {
panic(err)
}
switch b {
case ops.I32Const:
i, err := leb128.ReadVarint32(r)
if err != nil {
panic(err)
}
stack = append(stack, int64(i))
case ops.I64Const:
i, err := leb128.ReadVarint64(r)
if err != nil {
panic(err)
}
stack = append(stack, int64(i))
case ops.F32Const:
i, err := readU32(r)
if err != nil {
panic(err)
}
stack = append(stack, int64(i))
case ops.F64Const:
i, err := readU64(r)
if err != nil {
panic(err)
}
stack = append(stack, int64(i))
case ops.GetGlobal:
index, err := leb128.ReadVarUint32(r)
if err != nil {
panic(err)
}
stack = append(stack, globals[int(index)])
case ops.End:
break
default:
panic("invalid opcode in init expr")
}
}
return stack[len(stack)-1]
}