-
Notifications
You must be signed in to change notification settings - Fork 9
/
bridge.go
527 lines (449 loc) · 11.2 KB
/
bridge.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package wasm
import (
"context"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"log"
"math"
"net/http"
"reflect"
"sync"
"syscall"
"time"
"unsafe"
"github.com/wasmerio/go-ext-wasm/wasmer"
)
var (
undefined = &struct{}{}
bridges = map[string]*Bridge{}
mu sync.RWMutex // to protect bridges
)
type bctx struct{ n string }
func getCtxData(b *Bridge) (*bctx, error) {
mu.Lock()
defer mu.Unlock()
if _, ok := bridges[b.name]; ok {
return nil, fmt.Errorf("bridge with name %s already exists", b.name)
}
bridges[b.name] = b
return &bctx{n: b.name}, nil
}
func getBridge(ctx unsafe.Pointer) *Bridge {
ictx := wasmer.IntoInstanceContext(ctx)
c := (ictx.Data()).(*bctx)
mu.RLock()
defer mu.RUnlock()
return bridges[c.n]
}
type Bridge struct {
name string
instance wasmer.Instance
exitCode int
valueIDX int
valueMap map[int]interface{}
refs map[interface{}]int
valuesMu sync.RWMutex
memory []byte
exited bool
cancF context.CancelFunc
}
func BridgeFromBytes(name string, bytes []byte, imports *wasmer.Imports) (*Bridge, error) {
b := new(Bridge)
if imports == nil {
imports = wasmer.NewImports()
}
b.name = name
err := b.addImports(imports)
if err != nil {
return nil, err
}
inst, err := wasmer.NewInstanceWithImports(bytes, imports)
if err != nil {
return nil, err
}
ctx, err := getCtxData(b)
if err != nil {
return nil, err
}
b.instance = inst
inst.SetContextData(ctx)
b.addValues()
b.refs = make(map[interface{}]int)
b.valueIDX = 8
return b, nil
}
func BridgeFromFile(name, file string, imports *wasmer.Imports) (*Bridge, error) {
bytes, err := wasmer.ReadBytes(file)
if err != nil {
return nil, err
}
return BridgeFromBytes(name, bytes, imports)
}
func (b *Bridge) addValues() {
var goObj *object
goObj = propObject("jsGo", map[string]interface{}{
"_makeFuncWrapper": Func(func(args []interface{}) (interface{}, error) {
return &funcWrapper{id: args[0]}, nil
}),
"_pendingEvent": nil,
})
b.valueMap = map[int]interface{}{
0: math.NaN(),
1: float64(0),
2: nil,
3: true,
4: false,
5: &object{
props: map[string]interface{}{
"Object": &object{name: "Object", new: func(args []interface{}) interface{} {
return &object{name: "ObjectInner", props: map[string]interface{}{}}
}},
"Array": arrayObject("Array"),
"Uint8Array": arrayObject("Uint8Array"),
"process": propObject("process", nil),
"Date": &object{name: "Date", new: func(args []interface{}) interface{} {
t := time.Now()
return &object{name: "DateInner", props: map[string]interface{}{
"time": t,
"getTimezoneOffset": Func(func(args []interface{}) (interface{}, error) {
_, offset := t.Zone()
// make it negative and return in minutes
offset = (offset / 60) * -1
return offset, nil
}),
}}
}},
"crypto": propObject("crypto", map[string]interface{}{
"getRandomValues": Func(func(args []interface{}) (interface{}, error) {
arr := args[0].(*array)
return rand.Read(arr.buf)
}),
}),
"AbortController": &object{name: "AbortController", new: func(args []interface{}) interface{} {
return &object{name: "AbortControllerInner", props: map[string]interface{}{
"signal": propObject("signal", map[string]interface{}{}),
}}
}},
"Headers": &object{name: "Headers", new: func(args []interface{}) interface{} {
headers := http.Header{}
obj := &object{name: "HeadersInner", props: map[string]interface{}{
"headers": headers,
"append": Func(func(args []interface{}) (interface{}, error) {
headers.Add(args[0].(string), args[1].(string))
return nil, nil
}),
}}
return obj
}},
"fetch": Func(func(args []interface{}) (interface{}, error) {
// Fixme(ved): implement fetch
log.Fatalln(args)
return nil, nil
}),
"fs": propObject("fs", map[string]interface{}{
"constants": propObject("constants", map[string]interface{}{
"O_WRONLY": syscall.O_WRONLY,
"O_RDWR": syscall.O_RDWR,
"O_CREAT": syscall.O_CREAT,
"O_TRUNC": syscall.O_TRUNC,
"O_APPEND": syscall.O_APPEND,
"O_EXCL": syscall.O_EXCL,
}),
"write": Func(func(args []interface{}) (interface{}, error) {
fd := int(args[0].(float64))
offset := int(args[2].(float64))
length := int(args[3].(float64))
buf := args[1].(*array).buf[offset : offset+length]
pos := args[4]
callback := args[5].(*funcWrapper)
var err error
var n int
if pos != nil {
position := int64(pos.(float64))
n, err = syscall.Pwrite(fd, buf, position)
} else {
n, err = syscall.Write(fd, buf)
}
if err != nil {
return nil, err
}
return b.makeFuncWrapper(callback.id, goObj, &[]interface{}{nil, n})
}),
}),
},
}, // global
6: goObj, // jsGo
}
}
func (b *Bridge) check() {
if b.exited {
panic("WASM instance already exited")
}
}
// Run start the wasm instance.
func (b *Bridge) Run(ctx context.Context, init chan error) {
b.check()
defer b.instance.Close()
run := b.instance.Exports["run"]
_, err := run(0, 0)
if err != nil {
init <- err
return
}
ctx, cancF := context.WithCancel(ctx)
b.cancF = cancF
init <- nil
select {
case <-ctx.Done():
log.Printf("stopping WASM[%s] instance...\n", b.name)
b.exited = true
return
}
}
func (b *Bridge) mem() []byte {
if b.memory == nil {
b.memory = b.instance.Memory.Data()
}
return b.memory
}
func (b *Bridge) getSP() int32 {
spFunc := b.instance.Exports["getsp"]
val, err := spFunc()
if err != nil {
panic("failed to get sp")
}
return val.ToI32()
}
func (b *Bridge) setUint8(offset int32, v uint8) {
mem := b.mem()
mem[offset] = byte(v)
}
func (b *Bridge) setInt64(offset int32, v int64) {
mem := b.mem()
binary.LittleEndian.PutUint64(mem[offset:], uint64(v))
}
func (b *Bridge) setInt32(offset int32, v int32) {
mem := b.mem()
binary.LittleEndian.PutUint32(mem[offset:], uint32(v))
}
func (b *Bridge) getInt64(offset int32) int64 {
mem := b.mem()
return int64(binary.LittleEndian.Uint64(mem[offset:]))
}
func (b *Bridge) getInt32(offset int32) int32 {
mem := b.mem()
return int32(binary.LittleEndian.Uint32(mem[offset:]))
}
func (b *Bridge) setUint32(offset int32, v uint32) {
mem := b.mem()
binary.LittleEndian.PutUint32(mem[offset:], v)
}
func (b *Bridge) setUint64(offset int32, v uint64) {
mem := b.mem()
binary.LittleEndian.PutUint64(mem[offset:], v)
}
func (b *Bridge) getUnit64(offset int32) uint64 {
mem := b.mem()
return binary.LittleEndian.Uint64(mem[offset+0:])
}
func (b *Bridge) setFloat64(offset int32, v float64) {
uf := math.Float64bits(v)
b.setUint64(offset, uf)
}
func (b *Bridge) getFloat64(offset int32) float64 {
uf := b.getUnit64(offset)
return math.Float64frombits(uf)
}
func (b *Bridge) getUint32(offset int32) uint32 {
return binary.LittleEndian.Uint32(b.mem()[offset+0:])
}
func (b *Bridge) loadSlice(addr int32) []byte {
mem := b.mem()
array := binary.LittleEndian.Uint64(mem[addr+0:])
length := binary.LittleEndian.Uint64(mem[addr+8:])
return mem[array : array+length]
}
func (b *Bridge) loadString(addr int32) string {
d := b.loadSlice(addr)
return string(d)
}
func (b *Bridge) loadSliceOfValues(addr int32) []interface{} {
arr := int(b.getInt64(addr + 0))
arrLen := int(b.getInt64(addr + 8))
vals := make([]interface{}, arrLen, arrLen)
for i := 0; i < int(arrLen); i++ {
vals[i] = b.loadValue(int32(arr + i*8))
}
return vals
}
func (b *Bridge) loadValue(addr int32) interface{} {
f := b.getFloat64(addr)
if f == 0 {
return undefined
}
if !math.IsNaN(f) {
return f
}
b.valuesMu.RLock()
defer b.valuesMu.RUnlock()
return b.valueMap[int(b.getUint32(addr))]
}
func (b *Bridge) storeValue(addr int32, v interface{}) {
const nanHead = 0x7FF80000
if i, ok := v.(int); ok {
v = float64(i)
}
if i, ok := v.(uint); ok {
v = float64(i)
}
if v, ok := v.(float64); ok {
if math.IsNaN(v) {
b.setUint32(addr+4, nanHead)
b.setUint32(addr, 0)
return
}
if v == 0 {
b.setUint32(addr+4, nanHead)
b.setUint32(addr, 1)
return
}
b.setFloat64(addr, v)
return
}
switch v {
case undefined:
b.setFloat64(addr, 0)
return
case nil:
b.setUint32(addr+4, nanHead)
b.setUint32(addr, 2)
return
case true:
b.setUint32(addr+4, nanHead)
b.setUint32(addr, 3)
return
case false:
b.setUint32(addr+4, nanHead)
b.setUint32(addr, 4)
return
}
rt := reflect.TypeOf(v)
if rt.Kind() == reflect.Ptr {
rt = rt.Elem()
}
rv := v
if !rt.Comparable() {
// since some types like Func cant be set as key, we will use their reflect value
// as key to insert for refs[key] so that we can avoid any duplicates
rv = reflect.ValueOf(v)
}
ref, ok := b.refs[rv]
if !ok {
b.valuesMu.RLock()
b.valueMap[b.valueIDX] = v
ref = b.valueIDX
b.refs[rv] = ref
b.valueIDX++
b.valuesMu.RUnlock()
}
typeFlag := 0
switch rt.Kind() {
case reflect.String:
typeFlag = 1
case reflect.Func:
typeFlag = 3
}
b.setUint32(addr+4, uint32(nanHead|typeFlag))
b.setUint32(addr, uint32(ref))
}
type object struct {
name string // for debugging
props map[string]interface{}
new func(args []interface{}) interface{}
}
func propObject(name string, prop map[string]interface{}) *object {
return &object{name: name, props: prop}
}
type array struct {
buf []byte
}
func arrayObject(name string) *object {
return &object{
name: name,
new: func(args []interface{}) interface{} {
l := int(args[0].(float64))
return &array{
buf: make([]byte, l, l),
}
},
}
}
// TODO make this a wrapper that takes an inner `this` js object
type Func func(args []interface{}) (interface{}, error)
func (b *Bridge) resume() error {
res := b.instance.Exports["resume"]
_, err := res()
return err
}
type funcWrapper struct {
id interface{}
}
func (b *Bridge) makeFuncWrapper(id, this interface{}, args *[]interface{}) (interface{}, error) {
goObj := this.(*object)
event := propObject("_pendingEvent", map[string]interface{}{
"id": id,
"this": goObj,
"args": args,
})
goObj.props["_pendingEvent"] = event
err := b.resume()
if err != nil {
return nil, err
}
return event.props["result"], nil
}
func (b *Bridge) CallFunc(fn string, args []interface{}) (interface{}, error) {
b.check()
b.valuesMu.RLock()
fw, ok := b.valueMap[5].(*object).props[fn]
if !ok {
return nil, fmt.Errorf("missing function: %v", fn)
}
this := b.valueMap[6]
b.valuesMu.RUnlock()
return b.makeFuncWrapper(fw.(*funcWrapper).id, this, &args)
}
func (b *Bridge) SetFunc(fname string, fn Func) error {
b.valuesMu.RLock()
defer b.valuesMu.RUnlock()
b.valueMap[5].(*object).props[fname] = &fn
return nil
}
func Bytes(v interface{}) ([]byte, error) {
arr, ok := v.(*array)
if !ok {
return nil, fmt.Errorf("got %T instead of bytes", v)
}
return arr.buf, nil
}
func String(v interface{}) (string, error) {
str, ok := v.(string)
if !ok {
return "", fmt.Errorf("got %t instead of string", v)
}
return str, nil
}
func Error(v interface{}) (errVal, err error) {
str, ok := v.(string)
if !ok {
return nil, fmt.Errorf("got %T instead of error", v)
}
return errors.New(str), nil
}
func FromBytes(v []byte) interface{} {
buf := make([]byte, len(v), len(v))
copy(buf, v)
return &array{buf: buf}
}