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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
|
package wasm
import (
"fmt"
"strings"
"github.com/tetratelabs/wazero"
)
// patchWasm rewrites the WASM binary to convert the imported shared memory
// (import "env" "memory") into a locally-defined memory section, so that
// the "env" host module only needs to export functions.
func patchWasm(data []byte) ([]byte, error) {
if len(data) < 8 {
return nil, fmt.Errorf("wasm too short")
}
p := &wparser{data: data, pos: 8}
out := append([]byte{}, data[:8]...)
var memFlags, memMin, memMax uint32
foundMem := false
for p.pos < len(p.data) {
sid := p.data[p.pos]
p.pos++
secSize := p.uleb32()
secStart := p.pos
secEnd := p.pos + int(secSize)
switch sid {
case 2: // import section — strip the memory import
count := p.uleb32()
var kept []byte
keptCount := uint32(0)
for i := uint32(0); i < count; i++ {
start := p.pos
// module name
mlen := p.uleb32()
p.pos += int(mlen)
// field name
flen := p.uleb32()
fname := string(p.data[p.pos : p.pos+int(flen)])
p.pos += int(flen)
kind := p.data[p.pos]
p.pos++
switch kind {
case 0x00: // function — skip type index
p.uleb32()
case 0x01: // table — skip reftype + limits
p.pos++ // reftype
flags := p.uleb32()
p.uleb32() // min
if flags&0x01 != 0 {
p.uleb32()
} // max
case 0x02: // memory
flags := p.uleb32()
mn := p.uleb32()
mx := mn
if flags&0x01 != 0 {
mx = p.uleb32()
}
if fname != "memory" {
return nil, fmt.Errorf("unexpected memory import field: %q", fname)
}
memFlags = flags
memMin = mn
memMax = mx
foundMem = true
continue // drop from output
case 0x03: // global — skip valtype + mut
p.pos += 2
}
kept = append(kept, p.data[start:p.pos]...)
keptCount++
}
// Rebuild import section.
payload := appendULEB(nil, keptCount)
payload = append(payload, kept...)
out = append(out, 2)
out = appendULEB(out, uint32(len(payload)))
out = append(out, payload...)
case 5: // existing memory section — skip (shouldn't exist)
p.pos = secEnd
default:
out = append(out, sid)
out = appendULEB(out, secSize)
out = append(out, p.data[secStart:secEnd]...)
}
p.pos = secEnd
}
if !foundMem {
return nil, fmt.Errorf("no (import \"env\" \"memory\") found")
}
// Build a memory section payload: 1 memory, shared, min=memMin, max=memMax.
memPay := appendULEB(nil, 1) // count
memPay = appendULEB(memPay, memFlags)
memPay = appendULEB(memPay, memMin)
if memFlags&0x01 != 0 {
memPay = appendULEB(memPay, memMax)
}
// Insert memory section (id=5) before the first section with id >= 3.
// Scan the output sections and splice it in.
final := append([]byte{}, out[:8]...)
q := &wparser{data: out, pos: 8}
inserted := false
for q.pos < len(q.data) {
sid := q.data[q.pos]
if !inserted && sid >= 3 {
final = append(final, 5)
final = appendULEB(final, uint32(len(memPay)))
final = append(final, memPay...)
inserted = true
}
q.pos++
sz := q.uleb32()
start := q.pos
q.pos += int(sz)
final = append(final, sid)
final = appendULEB(final, sz)
final = append(final, q.data[start:q.pos]...)
}
if !inserted {
final = append(final, 5)
final = appendULEB(final, uint32(len(memPay)))
final = append(final, memPay...)
}
return final, nil
}
type wparser struct {
data []byte
pos int
}
func (p *wparser) uleb32() uint32 {
v, shift := uint32(0), uint(0)
for {
b := p.data[p.pos]
p.pos++
v |= uint32(b&0x7f) << shift
shift += 7
if b&0x80 == 0 {
return v
}
}
}
func appendULEB(b []byte, v uint32) []byte {
for {
byt := byte(v & 0x7f)
v >>= 7
if v != 0 {
b = append(b, byt|0x80)
} else {
return append(b, byt)
}
}
}
// parseHostTableEntries returns a map of table slot → import name for every
// "env" import that appears in the WASM function table (__indirect_function_table).
//
// It works in two steps:
// 1. Build funcIndex → importName for all "env" imports using the public
// CompiledModule API (no binary parsing needed).
// 2. Parse the element section of the WASM binary to find which table slots
// those function indices occupy.
//
// Emscripten always emits a single active element segment with an i32.const
// offset (typically 1, reserving slot 0 as null). Each entry in Init[] is a
// function index; tableSlot = offset + position.
func parseHostTableEntries(wasmBytes []byte, compiled wazero.CompiledModule) (map[uint32]string, error) {
// Step 1 — build funcIndex → "<module>:<name>" for all host imports that
// may appear in the function table. We track both "env" and "lix_store"
// imports so that invoke_* calls to lix_store.call are dispatched directly
// rather than falling through to the wazero trampoline (which crashes for
// non-env imports).
envByIndex := map[uint32]string{}
for _, fn := range compiled.ImportedFunctions() {
mod, name, _ := fn.Import()
if mod == "env" {
envByIndex[fn.Index()] = name
} else if mod == "lix_store" {
// Encode as "lix_store:name" so dispatchHostTableEntry can route it.
envByIndex[fn.Index()] = "lix_store:" + name
}
}
// Step 2 — parse element section (id=9) from the binary.
if len(wasmBytes) < 8 {
return nil, fmt.Errorf("wasm too short")
}
p := &wparser{data: wasmBytes, pos: 8}
result := map[uint32]string{}
for p.pos < len(p.data) {
sid := p.data[p.pos]
p.pos++
secSize := p.uleb32()
secEnd := p.pos + int(secSize)
if sid != 9 { // not the element section
p.pos = secEnd
continue
}
// Element section: count of segments.
segCount := p.uleb32()
for s := uint32(0); s < segCount; s++ {
prefix := p.uleb32()
// We only handle the two active-with-funcref-value-vector forms:
// prefix 0: legacy active, table 0, i32.const offset, vec(funcindex)
// prefix 2: active, explicit table index, i32.const offset, elemkind=0, vec(funcindex)
// Other forms (passive, declarative, const-expr vectors) are skipped.
switch prefix {
case 0: // legacy: opcode + offset data + vec(funcindex)
offset, ok := parseConstExprI32(p)
if !ok {
p.pos = secEnd
break
}
count := p.uleb32()
for i := uint32(0); i < count; i++ {
funcIdx := p.uleb32()
slot := offset + i
if name, ok := envByIndex[funcIdx]; ok {
result[slot] = name
}
}
case 2: // active with explicit table index
p.uleb32() // table index (ignore)
offset, ok := parseConstExprI32(p)
if !ok {
p.pos = secEnd
break
}
// elemkind byte (must be 0x00 for funcref)
if p.pos >= len(p.data) {
p.pos = secEnd
break
}
p.pos++ // skip elemkind
count := p.uleb32()
for i := uint32(0); i < count; i++ {
funcIdx := p.uleb32()
slot := offset + i
if name, ok := envByIndex[funcIdx]; ok {
result[slot] = name
}
}
default:
// passive / declarative / const-expr forms — skip the rest of this section
p.pos = secEnd
}
}
p.pos = secEnd
}
return result, nil
}
// parseConstExprI32 reads a WASM constant expression that must be i32.const N
// followed by the end opcode (0x0b). Returns the value and true on success.
func parseConstExprI32(p *wparser) (uint32, bool) {
if p.pos >= len(p.data) {
return 0, false
}
opcode := p.data[p.pos]
p.pos++
if opcode != 0x41 { // i32.const
return 0, false
}
val := p.uleb32()
if p.pos >= len(p.data) || p.data[p.pos] != 0x0b { // end
return 0, false
}
p.pos++ // consume end
return val, true
}
// invokeVariantNeeded reports whether an "env" import name is an invoke_*
// variant that we need to register ourselves.
func invokeVariantNeeded(name string) bool {
return strings.HasPrefix(name, "invoke_")
}
|