/
vm.go
650 lines (557 loc) · 16.3 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
643
644
645
646
647
648
649
650
/*
* Copyright (C) 2019 The onyxchain Authors
* This file is part of The onyxchain library.
*
* The onyxchain is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The onyxchain is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The onyxchain. If not, see <http://www.gnu.org/licenses/>.
*/
// 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 (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"github.com/OnyxPay/OnyxChain/common"
"github.com/OnyxPay/OnyxChain/vm/wasmvm/disasm"
"github.com/OnyxPay/OnyxChain/vm/wasmvm/exec/internal/compile"
"github.com/OnyxPay/OnyxChain/vm/wasmvm/memory"
"github.com/OnyxPay/OnyxChain/vm/wasmvm/wasm"
ops "github.com/OnyxPay/OnyxChain/vm/wasmvm/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
pc int64
curFunc int64
}
//store env call message
type EnvCall struct {
envParams []uint64
envReturns bool
envPreCtx context
Message []interface{} //the 'Message' field is for the EOS contract like parameters
}
func (ec *EnvCall) GetParams() []uint64 {
return ec.envParams
}
func (ec *EnvCall) GetReturns() bool {
return ec.envReturns
}
// VM is the execution context for executing WebAssembly bytecode.
type VM struct {
ctx context
module *wasm.Module
globals []uint64
compiledFuncs []compiledFunction
funcTable [256]func()
Services map[string]func(engine *ExecutionEngine) (bool, error)
memory *memory.VMmemory
//store the env call parameters
envCall *EnvCall
//store a engine pointer
ContractAddress common.Address
Caller common.Address
Engine *ExecutionEngine
VMCode []byte
}
// 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
// NewVM creates a new VM from a given module. If the module defines a
// start function, it will be executed.
func NewVM(module *wasm.Module) (*VM, error) {
var vm VM
err := vm.loadModule(module)
if err != nil {
return nil, err
}
return &vm, nil
}
//alloc memory and return the first index
func (vm *VM) Malloc(size int) (int, error) {
return vm.memory.Malloc(size)
}
//alloc memory for pointer and return the first index
func (vm *VM) MallocPointer(size int, ptype memory.PType) (int, error) {
return vm.memory.MallocPointer(size, ptype)
}
func (vm *VM) GetPointerMemSize(addr uint64) int {
return vm.memory.GetPointerMemSize(addr)
}
//when wasm returns a pointer, call this function to get the pointed memory
func (vm *VM) GetPointerMemory(addr uint64) ([]byte, error) {
return vm.memory.GetPointerMemory(addr)
}
//alloc memory for any pointer type
func (vm *VM) SetPointerMemory(val interface{}) (int, error) {
return vm.memory.SetPointerMemory(val)
}
//alloc memory for struct
//todo move to the SetPointerMemory
func (vm *VM) SetStructMemory(val interface{}) (int, error) {
return vm.memory.SetStructMemory(val)
}
func (vm *VM) GetEnvCall() *EnvCall {
return vm.envCall
}
func (vm *VM) RestoreCtx() bool {
if vm.envCall != nil {
vm.ctx = vm.envCall.envPreCtx
}
return true
}
//SetMessage
//for further extension
//support EOS like message
func (vm *VM) SetMessage(message []interface{}) {
if message != nil {
if vm.envCall == nil {
vm.envCall = &EnvCall{}
}
vm.envCall.Message = message
}
}
//GetMessageBytes
//for further extension
func (vm *VM) GetMessageBytes() ([]byte, error) {
if vm.envCall.Message == nil || len(vm.envCall.Message) == 0 {
return nil, nil
}
bytesbuf := bytes.NewBuffer(nil)
for _, m := range vm.envCall.Message {
switch m.(type) {
case string:
bytesbuf.WriteString(m.(string))
case int:
tmp := make([]byte, 4)
binary.LittleEndian.PutUint32(tmp, uint32(m.(int)))
bytesbuf.Write(tmp)
case int64:
tmp := make([]byte, 8)
binary.LittleEndian.PutUint64(tmp, uint64(m.(int64)))
bytesbuf.Write(tmp)
case float32:
bits := math.Float32bits(m.(float32))
tmp := make([]byte, 4)
binary.LittleEndian.PutUint32(tmp, bits)
bytesbuf.Write(tmp)
case float64:
bits := math.Float64bits(m.(float64))
tmp := make([]byte, 8)
binary.LittleEndian.PutUint64(tmp, uint64(bits))
bytesbuf.Write(tmp)
default:
//todo need support array types???
return nil, errors.New("[GetMessageBytes] unsupported type")
}
}
return bytesbuf.Bytes(), nil
}
func (vm *VM) SetMemory(val interface{}) (int, error) {
return vm.memory.SetMemory(val)
}
func (vm *VM) GetMemory() *memory.VMmemory {
return vm.memory
}
func (vm *VM) PushResult(res uint64) {
vm.pushUint64(res)
}
// Memory returns the linear memory space for the VM.
func (vm *VM) Memory() []byte {
return vm.memory.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) {
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.
//insideCall :true (call contract)
func (vm *VM) ExecCode(insideCall bool, fnIndex int64, args ...uint64) (interface{}, error) {
if int(fnIndex) > len(vm.compiledFuncs) {
return nil, InvalidFunctionIndexError(fnIndex)
}
if len(vm.module.GetFunction(int(fnIndex)).Sig.ParamTypes) != len(args) {
return nil, ErrInvalidArgumentCount
}
compiled := vm.compiledFuncs[fnIndex]
if len(vm.ctx.stack) < compiled.maxDepth {
vm.ctx.stack = make([]uint64, 0, compiled.maxDepth)
}
vm.ctx.locals = make([]uint64, compiled.totalLocalVars)
vm.ctx.pc = 0
vm.ctx.code = compiled.code
vm.ctx.curFunc = fnIndex
for i, arg := range args {
vm.ctx.locals[i] = arg
}
var rtrn interface{}
res := vm.execCode(insideCall, compiled)
// for the call contract case
if insideCall {
return res, nil
}
if compiled.returns {
rtrnType := vm.module.GetFunction(int(fnIndex)).Sig.ReturnTypes[0]
switch rtrnType {
case wasm.ValueTypeI32:
rtrn = uint32(res)
case wasm.ValueTypeI64:
rtrn = uint64(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(isinside bool, compiled compiledFunction) uint64 {
outer:
for int(vm.ctx.pc) < len(vm.ctx.code) {
op := vm.ctx.code[vm.ctx.pc]
vm.ctx.pc++
switch op {
case ops.Return:
break outer
case compile.OpJmp:
vm.ctx.pc = vm.fetchInt64()
continue
case compile.OpJmpZ:
target := vm.fetchInt64()
if vm.popUint32() == 0 {
vm.ctx.pc = target
continue
}
case compile.OpJmpNz:
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:
index := vm.fetchInt64()
label := vm.popInt32()
table := vm.compiledFuncs[vm.ctx.curFunc].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:
place := vm.fetchInt64()
if len(vm.ctx.stack)-int(place) > 0 {
vm.ctx.stack = vm.ctx.stack[:len(vm.ctx.stack)-int(place)]
}
case compile.OpDiscardPreserveTop:
top := vm.ctx.stack[len(vm.ctx.stack)-1]
place := vm.fetchInt64()
if len(vm.ctx.stack)-int(place) > 0 {
vm.ctx.stack = vm.ctx.stack[:len(vm.ctx.stack)-int(place)]
}
vm.pushUint64(top)
default:
vm.funcTable[op]()
}
}
if compiled.returns {
return vm.ctx.stack[len(vm.ctx.stack)-1]
}
return 0
}
//CallContract
//start a new vm
//this method is replaced with wasm_service :callContract
func (vm *VM) CallContract(caller common.Address, contractAddress common.Address, module *wasm.Module, actionName []byte, arg []byte) (uint64, error) {
methodName := CONTRACT_METHOD_NAME
//1. exec the method code
entry, ok := module.Export.Entries[methodName]
if ok == false {
return uint64(0), errors.New("Method:" + methodName + " does not exist!")
}
//get entry index
index := int64(entry.Index)
//new vm
newvm, err := NewVM(module)
if err != nil {
return uint64(0), err
}
newvm.Caller = caller
newvm.ContractAddress = contractAddress
newvm.Services = vm.Services
engine := vm.Engine
newvm.Engine = engine
engine.SetNewVM(newvm)
actionIdx, err := newvm.SetPointerMemory(actionName)
if err != nil {
return uint64(0), err
}
argIdx, err := newvm.SetPointerMemory(arg)
if err != nil {
return uint64(0), err
}
res, err := newvm.ExecCode(true, int64(index), uint64(actionIdx), uint64(argIdx))
if err != nil {
return uint64(0), err
}
resBytes, err := newvm.GetPointerMemory(res.(uint64))
if err != nil {
return uint64(0), err
}
//copy memory if need!!!
engine.RestoreVM()
idx, err := vm.SetPointerMemory(resBytes)
if err != nil {
return uint64(0), err
}
return uint64(idx), nil
}
func (vm *VM) loadModule(module *wasm.Module) error {
vm.memory = &memory.VMmemory{}
if module.Memory != nil && len(module.Memory.Entries) != 0 {
if len(module.Memory.Entries) > 1 {
return ErrMultipleLinearMemories
}
vm.memory.Memory = make([]byte, uint(module.Memory.Entries[0].Limits.Initial)*wasmPageSize)
copy(vm.memory.Memory, module.LinearMemoryIndexSpace[0])
} else if len(module.LinearMemoryIndexSpace) > 0 {
//add imported memory ,all mem access will be on the imported mem
vm.memory.Memory = module.LinearMemoryIndexSpace[0]
}
//give a default memory even if no memory section exist in wasm file
if vm.memory.Memory == nil {
vm.memory.Memory = make([]byte, 1*wasmPageSize)
}
vm.memory.MemPoints = make(map[uint64]*memory.TypeLength) //init the pointer map
//solve the Data section
//this section is for some const strings, just like heap
if module.Data != nil {
var tmpIdx int
for _, entry := range module.Data.Entries {
if entry.Index != 0 {
return errors.New("invalid data index")
}
val, err := module.ExecInitExpr(entry.Offset)
if err != nil {
return err
}
offset, ok := val.(int32)
tmpIdx += int(offset) + len(entry.Data)
if !ok {
return errors.New("invalid data index")
}
// for the case of " (data (get_global 0) "init\00init success!\00add\00int"))"
if bytes.Contains(entry.Data, []byte{byte(0)}) {
splited := bytes.Split(entry.Data, []byte{byte(0)})
var tmpoffset = int(offset)
for _, tmp := range splited {
vm.memory.MemPoints[uint64(tmpoffset)] = &memory.TypeLength{Ptype: memory.PString, Length: len(tmp) + 1}
tmpoffset += len(tmp) + 1
}
} else {
vm.memory.MemPoints[uint64(offset)] = &memory.TypeLength{Ptype: memory.PString, Length: len(entry.Data)}
}
}
//
vm.memory.AllocedMemIdex = tmpIdx
vm.memory.PointedMemIndex = (len(vm.memory.Memory) + tmpIdx) / 2
} else {
//default pointed memory
vm.memory.AllocedMemIdex = -1
vm.memory.PointedMemIndex = len(vm.memory.Memory) / 2 //the second half memory is reserved for the pointed objects,string,array,structs
}
vm.compiledFuncs = make([]compiledFunction, len(module.FunctionIndexSpace))
vm.globals = make([]uint64, len(module.GlobalIndexSpace))
vm.newFuncTable()
vm.module = module
for i, fn := range module.FunctionIndexSpace {
disassembly, err := disasm.Disassemble(fn, module)
if err != nil {
return err
}
totalLocalVars := 0
totalLocalVars += len(fn.Sig.ParamTypes)
for _, entry := range fn.Body.Locals {
totalLocalVars += int(entry.Count)
}
code, table := compile.Compile(disassembly.Code)
if fn.IsEnvFunc {
vm.compiledFuncs[i] = compiledFunction{
code: code,
branchTables: table,
maxDepth: disassembly.MaxDepth,
totalLocalVars: totalLocalVars,
args: len(fn.Sig.ParamTypes),
returns: len(fn.Sig.ReturnTypes) != 0,
isEnv: true,
name: fn.Name,
}
} else {
vm.compiledFuncs[i] = compiledFunction{
code: code,
branchTables: table,
maxDepth: disassembly.MaxDepth,
totalLocalVars: totalLocalVars,
args: len(fn.Sig.ParamTypes),
returns: len(fn.Sig.ReturnTypes) != 0,
}
}
}
for i, global := range module.GlobalIndexSpace {
val, err := 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))
}
}
if module.Start != nil {
_, err := vm.ExecCode(false, int64(module.Start.Index))
if err != nil {
return err
}
}
return nil
}