This repository has been archived by the owner on Mar 16, 2023. It is now read-only.
/
vm.go
642 lines (547 loc) · 15.6 KB
/
vm.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
// Copyright 2017 The go-interpreter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package exec provides functions for executing WebAssembly bytecode.
package exec
import (
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"math/big"
"github.com/Ankr-network/wagon/disasm"
vmevent "github.com/Ankr-network/wagon/exec/event"
"github.com/Ankr-network/wagon/exec/gas"
"github.com/Ankr-network/wagon/exec/internal/compile"
"github.com/Ankr-network/wagon/log"
"github.com/Ankr-network/wagon/wasm"
ops "github.com/Ankr-network/wagon/wasm/operators"
)
var (
// ErrMultipleLinearMemories is returned by (*VM).NewVM when the module
// has more then one entries in the linear memory space.
ErrMultipleLinearMemories = errors.New("exec: more than one linear memories in module")
// ErrInvalidArgumentCount is returned by (*VM).ExecCode when an invalid
// number of arguments to the WebAssembly function are passed to it.
ErrInvalidArgumentCount = errors.New("exec: invalid number of arguments to function")
)
// InvalidReturnTypeError is returned by (*VM).ExecCode when the module
// specifies an invalid return type value for the executed function.
type InvalidReturnTypeError int8
func (e InvalidReturnTypeError) Error() string {
return fmt.Sprintf("Function has invalid return value_type: %d", int8(e))
}
// InvalidFunctionIndexError is returned by (*VM).ExecCode when the function
// index provided is invalid.
type InvalidFunctionIndexError int64
func (e InvalidFunctionIndexError) Error() string {
return fmt.Sprintf("Invalid index to function index space: %d", int64(e))
}
type context struct {
stack []uint64
locals []uint64
code []byte
asm []asmBlock
pc int64
curFunc int64
}
// VM is the execution context for executing WebAssembly bytecode.
type VM struct {
ctx context
module *wasm.Module
globals []uint64
memory []byte
funcs []function
funcTable [256]func()
// RecoverPanic controls whether the `ExecCode` method
// recovers from a panic and returns it as an error
// instead.
// A panic can occur either when executing an invalid VM
// or encountering an invalid instruction, e.g. `unreachable`.
RecoverPanic bool
abort bool // Flag for host functions to terminate execution
nativeBackend *nativeCompiler
log log.Logger
contrInvoker ContractInvoker
contractAddr string
ownerAddr string
callerAddr string
vmContext *VMContext
}
// As per the WebAssembly spec: https://github.com/WebAssembly/design/blob/27ac254c854994103c24834a994be16f74f54186/Semantics.md#linear-memory
const wasmPageSize = 65536 // (64 KB)
var endianess = binary.LittleEndian
type config struct {
EnableAOT bool
}
// VMOption describes a customization that can be applied to the VM.
type VMOption func(c *config)
// EnableAOT enables ahead-of-time compilation of supported opcodes
// into runs of native instructions, if wagon supports native compilation
// for the current architecture.
func EnableAOT(v bool) VMOption {
return func(c *config) {
c.EnableAOT = v
}
}
// NewVM creates a new VM from a given module and options. If the module defines
// a start function, it will be executed.
func NewVM(contractAddr string, ownerAddr string, callerAddr string, metric gas.GasMetric, publisher vmevent.Publisher, module *wasm.Module, opts ...VMOption) (*VM, error) {
var vm VM
var options config
for _, opt := range opts {
opt(&options)
}
vm.funcs = make([]function, len(module.FunctionIndexSpace))
vm.globals = make([]uint64, len(module.GlobalIndexSpace))
vm.newFuncTable()
vm.module = module
vm.vmContext = NewVMContext()
vm.contractAddr = contractAddr
vm.ownerAddr = ownerAddr
vm.callerAddr = callerAddr
vm.vmContext.SetGasMetric(metric)
vm.vmContext.SetPublisher(publisher)
if module.Memory != nil && len(module.Memory.Entries) != 0 {
if len(module.Memory.Entries) > 1 {
return nil, ErrMultipleLinearMemories
}
err := vm.initMemory()
if err != nil {
return nil, err
}
}
nNatives := 0
for i, fn := range module.FunctionIndexSpace {
// Skip native methods as they need not be
// disassembled; simply add them at the end
// of the `funcs` array as is, as specified
// in the spec. See the "host functions"
// section of:
// https://webassembly.github.io/spec/core/exec/modules.html#allocation
if fn.IsHost() {
vm.funcs[i] = goFunction{
typ: fn.Host.Type(),
val: fn.Host,
}
nNatives++
continue
}
disassembly, err := disasm.NewDisassembly(fn, module)
if err != nil {
return nil, err
}
totalLocalVars := 0
totalLocalVars += len(fn.Sig.ParamTypes)
for _, entry := range fn.Body.Locals {
totalLocalVars += int(entry.Count)
}
code, meta := compile.Compile(disassembly.Code)
vm.funcs[i] = compiledFunction{
codeMeta: meta,
code: code,
branchTables: meta.BranchTables,
maxDepth: disassembly.MaxDepth,
totalLocalVars: totalLocalVars,
args: len(fn.Sig.ParamTypes),
returns: len(fn.Sig.ReturnTypes) != 0,
}
}
if err := vm.resetGlobals(); err != nil {
return nil, err
}
if module.Start != nil {
_, err := vm.ExecCode(int64(module.Start.Index), "")
if err != nil {
return nil, err
}
}
if options.EnableAOT {
supportedBackend, backend := nativeBackend()
if supportedBackend {
vm.nativeBackend = backend
if err := vm.tryNativeCompile(); err != nil {
return nil, err
}
}
}
return &vm, nil
}
func (vm *VM) resetGlobals() error {
for i, global := range vm.module.GlobalIndexSpace {
val, err := vm.module.ExecInitExpr(global.Init)
if err != nil {
return err
}
switch v := val.(type) {
case int32:
vm.globals[i] = uint64(v)
case int64:
vm.globals[i] = uint64(v)
case float32:
vm.globals[i] = uint64(math.Float32bits(v))
case float64:
vm.globals[i] = uint64(math.Float64bits(v))
}
}
return nil
}
// Memory returns the linear memory space for the VM.
func (vm *VM) Memory() []byte {
return vm.memory
}
func (vm *VM) pushBool(v bool) {
if v {
vm.pushUint64(1)
} else {
vm.pushUint64(0)
}
}
func (vm *VM) fetchBool() bool {
return vm.fetchInt8() != 0
}
func (vm *VM) fetchInt8() int8 {
i := int8(vm.ctx.code[vm.ctx.pc])
vm.ctx.pc++
return i
}
func (vm *VM) fetchUint32() uint32 {
v := endianess.Uint32(vm.ctx.code[vm.ctx.pc:])
vm.ctx.pc += 4
return v
}
func (vm *VM) fetchInt32() int32 {
return int32(vm.fetchUint32())
}
func (vm *VM) fetchFloat32() float32 {
return math.Float32frombits(vm.fetchUint32())
}
func (vm *VM) fetchUint64() uint64 {
v := endianess.Uint64(vm.ctx.code[vm.ctx.pc:])
vm.ctx.pc += 8
return v
}
func (vm *VM) fetchInt64() int64 {
return int64(vm.fetchUint64())
}
func (vm *VM) fetchFloat64() float64 {
return math.Float64frombits(vm.fetchUint64())
}
func (vm *VM) popUint64() uint64 {
i := vm.ctx.stack[len(vm.ctx.stack)-1]
vm.ctx.stack = vm.ctx.stack[:len(vm.ctx.stack)-1]
return i
}
func (vm *VM) popInt64() int64 {
return int64(vm.popUint64())
}
func (vm *VM) popFloat64() float64 {
return math.Float64frombits(vm.popUint64())
}
func (vm *VM) popUint32() uint32 {
return uint32(vm.popUint64())
}
func (vm *VM) popInt32() int32 {
return int32(vm.popUint32())
}
func (vm *VM) popFloat32() float32 {
return math.Float32frombits(vm.popUint32())
}
func (vm *VM) pushUint64(i uint64) {
if debugStackDepth {
if len(vm.ctx.stack) >= cap(vm.ctx.stack) {
panic("stack exceeding max depth: " + fmt.Sprintf("len=%d,cap=%d", len(vm.ctx.stack), cap(vm.ctx.stack)))
}
}
vm.ctx.stack = append(vm.ctx.stack, i)
}
func (vm *VM) pushInt64(i int64) {
vm.pushUint64(uint64(i))
}
func (vm *VM) pushFloat64(f float64) {
vm.pushUint64(math.Float64bits(f))
}
func (vm *VM) pushUint32(i uint32) {
vm.pushUint64(uint64(i))
}
func (vm *VM) pushInt32(i int32) {
vm.pushUint64(uint64(i))
}
func (vm *VM) pushFloat32(f float32) {
vm.pushUint32(math.Float32bits(f))
}
// ExecCode calls the function with the given index and arguments.
// fnIndex should be a valid index into the function index space of
// the VM's module.
func (vm *VM) ExecCode(fnIndex int64, rtnType string, args ...uint64) (rtrn interface{}, err error) {
// If used as a library, client code should set vm.RecoverPanic to true
// in order to have an error returned.
if vm.RecoverPanic {
defer func() {
if r := recover(); r != nil {
switch e := r.(type) {
case error:
err = e
default:
err = fmt.Errorf("exec: %v", e)
}
}
}()
}
if int(fnIndex) > len(vm.funcs) {
return nil, InvalidFunctionIndexError(fnIndex)
}
if len(vm.module.GetFunction(int(fnIndex)).Sig.ParamTypes) != len(args) {
return nil, ErrInvalidArgumentCount
}
compiled, ok := vm.funcs[fnIndex].(compiledFunction)
if !ok {
panic(fmt.Sprintf("exec: function at index %d is not a compiled function", fnIndex))
}
depth := compiled.maxDepth + 1
if cap(vm.ctx.stack) < depth {
vm.ctx.stack = make([]uint64, 0, depth)
} else {
vm.ctx.stack = vm.ctx.stack[:0]
}
vm.ctx.locals = make([]uint64, compiled.totalLocalVars)
vm.ctx.pc = 0
vm.ctx.code = compiled.code
vm.ctx.asm = compiled.asm
vm.ctx.curFunc = fnIndex
for i, arg := range args {
vm.ctx.locals[i] = arg
}
vm.vmContext.runningVM = vm
res := vm.execCode(compiled)
if compiled.returns {
rtrnType := vm.module.GetFunction(int(fnIndex)).Sig.ReturnTypes[0]
switch rtrnType {
case wasm.ValueTypeI32:
if rtnType == "string" {
rtrn, _ = vm.vmContext.runningVM.ReadString(int64(int32(res)))
}else {
rtrn = int32(res)
}
case wasm.ValueTypeI64:
if rtnType == "string" {
rtrn, _ = vm.vmContext.runningVM.ReadString(int64(res))
}else {
rtrn = int64(res)
}
case wasm.ValueTypeF32:
rtrn = math.Float32frombits(uint32(res))
case wasm.ValueTypeF64:
rtrn = math.Float64frombits(res)
default:
return nil, InvalidReturnTypeError(rtrnType)
}
}
return rtrn, nil
}
func (vm *VM) execCode(compiled compiledFunction) uint64 {
outer:
for int(vm.ctx.pc) < len(vm.ctx.code) && !vm.abort {
op := vm.ctx.code[vm.ctx.pc]
vm.ctx.pc++
switch op {
case ops.Return:
gasUsed := new(big.Int).SetUint64(gas.OpsGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
break outer
case compile.OpJmp:
gasUsed := new(big.Int).SetUint64(gas.CompileGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
vm.ctx.pc = vm.fetchInt64()
continue
case compile.OpJmpZ:
gasUsed := new(big.Int).SetUint64(gas.CompileGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
target := vm.fetchInt64()
if vm.popUint32() == 0 {
vm.ctx.pc = target
continue
}
case compile.OpJmpNz:
gasUsed := new(big.Int).SetUint64(gas.CompileGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
target := vm.fetchInt64()
preserveTop := vm.fetchBool()
discard := vm.fetchInt64()
if vm.popUint32() != 0 {
vm.ctx.pc = target
var top uint64
if preserveTop {
top = vm.ctx.stack[len(vm.ctx.stack)-1]
}
vm.ctx.stack = vm.ctx.stack[:len(vm.ctx.stack)-int(discard)]
if preserveTop {
vm.pushUint64(top)
}
continue
}
case ops.BrTable:
gasUsed := new(big.Int).SetUint64(gas.OpsGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
index := vm.fetchInt64()
label := vm.popInt32()
cf, ok := vm.funcs[vm.ctx.curFunc].(compiledFunction)
if !ok {
panic(fmt.Sprintf("exec: function at index %d is not a compiled function", vm.ctx.curFunc))
}
table := cf.branchTables[index]
var target compile.Target
if label >= 0 && label < int32(len(table.Targets)) {
target = table.Targets[int32(label)]
} else {
target = table.DefaultTarget
}
if target.Return {
break outer
}
vm.ctx.pc = target.Addr
var top uint64
if target.PreserveTop {
top = vm.ctx.stack[len(vm.ctx.stack)-1]
}
vm.ctx.stack = vm.ctx.stack[:len(vm.ctx.stack)-int(target.Discard)]
if target.PreserveTop {
vm.pushUint64(top)
}
continue
case compile.OpDiscard:
gasUsed := new(big.Int).SetUint64(gas.CompileGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
place := vm.fetchInt64()
vm.ctx.stack = vm.ctx.stack[:len(vm.ctx.stack)-int(place)]
case compile.OpDiscardPreserveTop:
gasUsed := new(big.Int).SetUint64(gas.CompileGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
top := vm.ctx.stack[len(vm.ctx.stack)-1]
place := vm.fetchInt64()
vm.ctx.stack = vm.ctx.stack[:len(vm.ctx.stack)-int(place)]
vm.pushUint64(top)
case ops.WagonNativeExec:
gasUsed := new(big.Int).SetUint64(gas.OpsGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
i := vm.fetchUint32()
vm.nativeCodeInvocation(i)
default:
gasUsed := new(big.Int).SetUint64(gas.OpsGasTable[op])
if !vm.vmContext.gasMetric.SpendGas(gasUsed) {
panic("OutOfGas, vm execCode terminated")
}
vm.funcTable[op]()
}
}
if compiled.returns {
return vm.ctx.stack[len(vm.ctx.stack)-1]
}
return 0
}
// Restart readies the VM for another run.
func (vm *VM) Restart() {
vm.resetGlobals()
vm.ctx.locals = make([]uint64, 0)
vm.abort = false
}
// Close frees any resources managed by the VM.
func (vm *VM) Close() error {
vm.abort = true // prevents further use.
if vm.nativeBackend != nil {
if err := vm.nativeBackend.Close(); err != nil {
return err
}
}
return nil
}
func (vm *VM) SetLogger(log log.Logger) {
vm.log = log
}
func (vm *VM) Logger() log.Logger {
return vm.log
}
func (vm *VM) SetContrInvoker(contrInvoker ContractInvoker){
vm.contrInvoker = contrInvoker
}
func (vm *VM) ContrInvoker() ContractInvoker{
return vm.contrInvoker
}
func (vm *VM) Module() *wasm.Module {
return vm.module
}
func (vm *VM) ContractAddr() string {
return vm.contractAddr
}
func (vm *VM) OwnerAddr() string {
return vm.ownerAddr
}
func (vm *VM) CallerAddr() string {
return vm.callerAddr
}
// Process is a proxy passed to host functions in order to access
// things such as memory and control.
type Process struct {
vmContext *VMContext
}
// NewProcess creates a VM interface object for host functions
func NewProcess(vm *VM) *Process {
return &Process{vmContext: vm.vmContext}
}
// ReadAt implements the ReaderAt interface: it copies into p
// the content of memory at offset off.
func (proc *Process) ReadAt(p []byte, off int64) (int, error) {
return proc.vmContext.runningVM.ReadAt(p, off)
}
func (proc *Process) ReadString(off int64) (string, error) {
return proc.vmContext.runningVM.ReadString(off)
}
// WriteAt implements the WriterAt interface: it writes the content of p
// into the VM memory at offset off.
func (proc *Process) WriteAt(p []byte, off int64) (int, error) {
mem := proc.vmContext.runningVM.Memory()
var length int
if len(mem) < len(p)+int(off) {
length = len(mem) - int(off)
} else {
length = len(p)
}
copy(mem[off:], p[:length])
var err error
if length < len(p) {
err = io.ErrShortWrite
}
mem[off+int64(length)] = byte(0)
return length, err
}
// MemSize returns the current allocated memory size in bytes.
func (proc *Process) MemSize() int {
return len(proc.vmContext.runningVM.Memory())
}
func (proc *Process) VM() *VM {
return proc.vmContext.runningVM
}
// Terminate stops the execution of the current module.
func (proc *Process) Terminate() {
proc.vmContext.runningVM.abort = true
}
func (proc *Process) VMContext() *VMContext{
return proc.vmContext
}