-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathengine.go
1501 lines (1347 loc) · 55.2 KB
/
engine.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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package compiler
import (
"context"
"errors"
"fmt"
"reflect"
"runtime"
"sort"
"sync"
"unsafe"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/experimental"
"github.com/tetratelabs/wazero/internal/asm"
"github.com/tetratelabs/wazero/internal/filecache"
"github.com/tetratelabs/wazero/internal/platform"
"github.com/tetratelabs/wazero/internal/version"
"github.com/tetratelabs/wazero/internal/wasm"
"github.com/tetratelabs/wazero/internal/wasmdebug"
"github.com/tetratelabs/wazero/internal/wasmruntime"
"github.com/tetratelabs/wazero/internal/wazeroir"
)
// NOTE: The offset of many of the struct fields defined here are referenced from
// assembly using the constants below such as moduleEngineFunctionsOffset.
// If changing a struct, update the constant and associated tests as needed.
type (
// engine is a Compiler implementation of wasm.Engine
engine struct {
enabledFeatures api.CoreFeatures
codes map[wasm.ModuleID]*compiledModule // guarded by mutex.
fileCache filecache.Cache
mux sync.RWMutex
// setFinalizer defaults to runtime.SetFinalizer, but overridable for tests.
setFinalizer func(obj interface{}, finalizer interface{})
wazeroVersion string
}
// moduleEngine implements wasm.ModuleEngine
moduleEngine struct {
// See note at top of file before modifying this struct.
// functions are the functions in a module instances.
// The index is module instance-scoped. We intentionally avoid using map
// as the underlying memory region is accessed by assembly directly by using
// codesElement0Address.
functions []function
}
// callEngine holds context per moduleEngine.Call, and shared across all the
// function calls originating from the same moduleEngine.Call execution.
//
// This implements api.Function.
callEngine struct {
// See note at top of file before modifying this struct.
// These contexts are read and written by compiled code.
// Note: structs are embedded to reduce the costs to access fields inside them. Also, this eases field offset
// calculation.
moduleContext
stackContext
exitContext
archContext
// The following fields are not accessed by compiled code directly.
// stack is the go-allocated stack for holding values and call frames.
// Note: We never edit len or cap in compiled code, so we won't get screwed when GC comes in.
//
// At any point of execution, say currently executing function F2 which was called by F1, then
// the stack should look like like:
//
// [..., arg0, arg1, ..., argN, _, _, _, v1, v2, v3, ....
// ^ { }
// | F1's callFrame
// |
// stackBasePointer
//
// where
// - callFrame is the F1's callFrame which called F2. It contains F1's return address, F1's base pointer, and F1's *function.
// - stackBasePointer is the stack base pointer stored at (callEngine stackContext.stackBasePointerInBytes)
// - arg0, ..., argN are the function parameters, and v1, v2, v3,... are the local variables
// including the non-function param locals as well as the temporary variable produced by instructions (e.g i32.const).
//
// If the F2 makes a function call to F3 which takes two arguments, then the stack will become:
//
// [..., arg0, arg1, ..., argN, _, _, _, v1, v2, v3, _, _, _
// { } ^ { }
// F1's callFrame | F2's callFrame
// |
// stackBasePointer
// where
// - F2's callFrame is pushed above the v2 and v3 (arguments for F3).
// - The previous stackBasePointer (pointed at arg0) was saved inside the F2's callFrame.
//
// Then, if F3 returns one result, say w1, then the result will look like:
//
// [..., arg0, arg1, ..., argN, _, _, _, v1, w1, ...
// ^ { }
// | F1's callFrame
// |
// stackBasePointer
//
// where
// - stackBasePointer was reverted to the position at arg0
// - The result from F3 was pushed above v1
//
// If the number of parameters is smaller than that of return values, then the empty slots are reserved
// below the callFrame to store the results on teh return.
// For example, if F3 takes no parameter but returns N(>0) results, then the stack
// after making a call against F3 will look like:
//
// [..., arg0, arg1, ..., argN, _, _, _, v1, v2, v3, res_1, _, res_N, _, _, _
// { } ^ { }
// F1's callFrame | F2's callFrame
// |
// stackBasePointer
// where res_1, ..., res_N are the reserved slots below the call frame. In general,
// the number of reserved slots equals max(0, len(results)-len(params).
//
// This reserved slots are necessary to save the result values onto the stack while not destroying
// the callFrame value on function returns.
stack []uint64
// initialFn is the initial function for this call engine.
initialFn *function
// ctx is the context.Context passed to all the host function calls.
// This is modified when there's a function listener call, otherwise it's always the context.Context
// passed to the Call API.
ctx context.Context
// contextStack is a stack of contexts which is pushed and popped by function listeners.
// This is used and modified when there are function listeners.
contextStack *contextStack
// stackIterator provides a way to iterate over the stack for Listeners.
// It is setup and valid only during a call to a Listener hook.
stackIterator stackIterator
ensureTermination bool
}
// contextStack is a stack of context.Context.
contextStack struct {
// See note at top of file before modifying this struct.
self context.Context
prev *contextStack
}
// moduleContext holds the per-function call specific module information.
// This is subject to be manipulated from compiled native code whenever we make function calls.
moduleContext struct {
// See note at top of file before modifying this struct.
// fn holds the currently executed *function.
fn *function
// moduleInstance is the address of module instance from which we initialize
// the following fields. This is set whenever we enter a function or return from function calls.
//
// On the entry to the native code, this must be initialized to zero to let native code preamble know
// that this is the initial function call (which leads to moduleContext initialization pass).
moduleInstance *wasm.ModuleInstance //lint:ignore U1000 This is only used by Compiler code.
// globalElement0Address is the address of the first element in the global slice,
// i.e. &ModuleInstance.Globals[0] as uintptr.
globalElement0Address uintptr
// memoryElement0Address is the address of the first element in the global slice,
// i.e. &ModuleInstance.Memory.Buffer[0] as uintptr.
memoryElement0Address uintptr
// memorySliceLen is the length of the memory buffer, i.e. len(ModuleInstance.Memory.Buffer).
memorySliceLen uint64
// memoryInstance holds the memory instance for this module instance.
memoryInstance *wasm.MemoryInstance
// tableElement0Address is the address of the first item in the tables slice,
// i.e. &ModuleInstance.Tables[0] as uintptr.
tablesElement0Address uintptr
// functionsElement0Address is &moduleContext.functions[0] as uintptr.
functionsElement0Address uintptr
// typeIDsElement0Address holds the &ModuleInstance.TypeIDs[0] as uintptr.
typeIDsElement0Address uintptr
// dataInstancesElement0Address holds the &ModuleInstance.DataInstances[0] as uintptr.
dataInstancesElement0Address uintptr
// elementInstancesElement0Address holds the &ModuleInstance.ElementInstances[0] as uintptr.
elementInstancesElement0Address uintptr
}
// stackContext stores the data to access engine.stack.
stackContext struct {
// See note at top of file before modifying this struct.
// stackPointer on .stack field which is accessed by stack[stackBasePointer+stackBasePointerInBytes*8].
//
// Note: stackPointer is not used in assembly since the native code knows exact position of
// each variable in the value stack from the info from compilation.
// Therefore, only updated when native code exit from the Compiler world and go back to the Go function.
stackPointer uint64
// stackBasePointerInBytes is updated whenever we make function calls.
// Background: Functions might be compiled as if they use the stack from the bottom.
// However, in reality, they have to use it from the middle of the stack depending on
// when these function calls are made. So instead of accessing stack via stackPointer alone,
// functions are compiled, so they access the stack via [stackBasePointer](fixed for entire function) + [stackPointer].
// More precisely, stackBasePointer is set to [callee's stack pointer] + [callee's stack base pointer] - [caller's params].
// This way, compiled functions can be independent of the timing of functions calls made against them.
stackBasePointerInBytes uint64
// stackElement0Address is &engine.stack[0] as uintptr.
// Note: this is updated when growing the stack in builtinFunctionGrowStack.
stackElement0Address uintptr
// stackLenInBytes is len(engine.stack[0]) * 8 (bytes).
// Note: this is updated when growing the stack in builtinFunctionGrowStack.
stackLenInBytes uint64
}
// exitContext will be manipulated whenever compiled native code returns into the Go function.
exitContext struct {
// See note at top of file before modifying this struct.
// Where we store the status code of Compiler execution.
statusCode nativeCallStatusCode
// Set when statusCode == compilerStatusCallBuiltInFunction
// Indicating the function call index.
builtinFunctionCallIndex wasm.Index
// returnAddress is the return address which the engine jumps into
// after executing a builtin function or host function.
returnAddress uintptr
// callerModuleInstance holds the caller's wasm.ModuleInstance, and is only valid if currently executing a host function.
callerModuleInstance *wasm.ModuleInstance
}
// callFrame holds the information to which the caller function can return.
// This is mixed in callEngine.stack with other Wasm values just like any other
// native program (where the stack is the system stack though), and we retrieve the struct
// with unsafe pointer casts.
callFrame struct {
// See note at top of file before modifying this struct.
// returnAddress is the return address to which the engine jumps when the callee function returns.
returnAddress uintptr
// returnStackBasePointerInBytes is the stack base pointer to set on stackContext.stackBasePointerInBytes
// when the callee function returns.
returnStackBasePointerInBytes uint64
// function is the caller *function, and is used to retrieve the stack trace.
// Note: should be possible to revive *function from returnAddress, but might be costly.
function *function
}
// Function corresponds to function instance in Wasm, and is created from `code`.
function struct {
// See note at top of file before modifying this struct.
// codeInitialAddress is the pre-calculated pointer pointing to the initial byte of .codeSegment slice.
// That mean codeInitialAddress always equals uintptr(unsafe.Pointer(&.codeSegment[0]))
// and we cache the value (uintptr(unsafe.Pointer(&.codeSegment[0]))) to this field,
// so we don't need to repeat the calculation on each function call.
codeInitialAddress uintptr
// moduleInstance holds the address of source.ModuleInstance.
moduleInstance *wasm.ModuleInstance
// typeID is the corresponding wasm.FunctionTypeID for funcType.
typeID wasm.FunctionTypeID
// index is the function Index in this module.
index wasm.Index
// funcType is the function type for this function. Created during compilation.
funcType *wasm.FunctionType
// def is the api.Function for this function. Created during compilation.
def api.FunctionDefinition
// parent holds code from which this is created.
parent *compiledFunction
}
compiledModule struct {
executable []byte
functions []compiledFunction
source *wasm.Module
ensureTermination bool
}
// compiledFunction corresponds to a function in a module (not instantiated one). This holds the machine code
// compiled by wazero compiler.
compiledFunction struct {
// codeSegment is holding the compiled native code as a byte slice.
executableOffset int
// See the doc for codeStaticData type.
// stackPointerCeil is the max of the stack pointer this function can reach. Lazily applied via maybeGrowStack.
stackPointerCeil uint64
goFunc interface{}
listener experimental.FunctionListener
parent *compiledModule
sourceOffsetMap sourceOffsetMap
}
// sourceOffsetMap holds the information to retrieve the original offset in the Wasm binary from the
// offset in the native binary.
sourceOffsetMap struct {
// See note at top of file before modifying this struct.
// irOperationOffsetsInNativeBinary is index-correlated with irOperationSourceOffsetsInWasmBinary,
// and maps each index (corresponding to each IR Operation) to the offset in the compiled native code.
irOperationOffsetsInNativeBinary []uint64
// irOperationSourceOffsetsInWasmBinary is index-correlated with irOperationOffsetsInNativeBinary.
// See wazeroir.CompilationResult irOperationOffsetsInNativeBinary.
irOperationSourceOffsetsInWasmBinary []uint64
}
)
// Native code reads/writes Go's structs with the following constants.
// See TestVerifyOffsetValue for how to derive these values.
const (
// Offsets for moduleEngine.functions
moduleEngineFunctionsOffset = 0
// Offsets for callEngine moduleContext.
callEngineModuleContextFnOffset = 0
callEngineModuleContextModuleInstanceOffset = 8
callEngineModuleContextGlobalElement0AddressOffset = 16
callEngineModuleContextMemoryElement0AddressOffset = 24
callEngineModuleContextMemorySliceLenOffset = 32
callEngineModuleContextMemoryInstanceOffset = 40
callEngineModuleContextTablesElement0AddressOffset = 48
callEngineModuleContextFunctionsElement0AddressOffset = 56
callEngineModuleContextTypeIDsElement0AddressOffset = 64
callEngineModuleContextDataInstancesElement0AddressOffset = 72
callEngineModuleContextElementInstancesElement0AddressOffset = 80
// Offsets for callEngine stackContext.
callEngineStackContextStackPointerOffset = 88
callEngineStackContextStackBasePointerInBytesOffset = 96
callEngineStackContextStackElement0AddressOffset = 104
callEngineStackContextStackLenInBytesOffset = 112
// Offsets for callEngine exitContext.
callEngineExitContextNativeCallStatusCodeOffset = 120
callEngineExitContextBuiltinFunctionCallIndexOffset = 124
callEngineExitContextReturnAddressOffset = 128
callEngineExitContextCallerModuleInstanceOffset = 136
// Offsets for function.
functionCodeInitialAddressOffset = 0
functionModuleInstanceOffset = 8
functionTypeIDOffset = 16
functionSize = 56
// Offsets for wasm.ModuleInstance.
moduleInstanceGlobalsOffset = 32
moduleInstanceMemoryOffset = 56
moduleInstanceTablesOffset = 64
moduleInstanceEngineOffset = 88
moduleInstanceTypeIDsOffset = 104
moduleInstanceDataInstancesOffset = 128
moduleInstanceElementInstancesOffset = 152
// Offsets for wasm.TableInstance.
tableInstanceTableOffset = 0
tableInstanceTableLenOffset = 8
// Offsets for wasm.MemoryInstance.
memoryInstanceBufferOffset = 0
memoryInstanceBufferLenOffset = 8
// Offsets for wasm.GlobalInstance.
globalInstanceValueOffset = 8
// Offsets for Go's interface.
// https://research.swtch.com/interfaces
// https://github.com/golang/go/blob/release-branch.go1.20/src/runtime/runtime2.go#L207-L210
interfaceDataOffset = 8
// Consts for wasm.DataInstance.
dataInstanceStructSize = 24
// Consts for wasm.ElementInstance.
elementInstanceStructSize = 32
// pointerSizeLog2 satisfies: 1 << pointerSizeLog2 = sizeOf(uintptr)
pointerSizeLog2 = 3
// callFrameDataSizeInUint64 is the size of callFrame struct per 8 bytes (= size of uint64).
callFrameDataSizeInUint64 = 24 / 8
)
// nativeCallStatusCode represents the result of `nativecall`.
// This is set by the native code.
type nativeCallStatusCode uint32
const (
// nativeCallStatusCodeReturned means the nativecall reaches the end of function, and returns successfully.
nativeCallStatusCodeReturned nativeCallStatusCode = iota
// nativeCallStatusCodeCallGoHostFunction means the nativecall returns to make a host function call.
nativeCallStatusCodeCallGoHostFunction
// nativeCallStatusCodeCallBuiltInFunction means the nativecall returns to make a builtin function call.
nativeCallStatusCodeCallBuiltInFunction
// nativeCallStatusCodeUnreachable means the function invocation reaches "unreachable" instruction.
nativeCallStatusCodeUnreachable
// nativeCallStatusCodeInvalidFloatToIntConversion means an invalid conversion of integer to floats happened.
nativeCallStatusCodeInvalidFloatToIntConversion
// nativeCallStatusCodeMemoryOutOfBounds means an out-of-bounds memory access happened.
nativeCallStatusCodeMemoryOutOfBounds
// nativeCallStatusCodeInvalidTableAccess means either offset to the table was out of bounds of table, or
// the target element in the table was uninitialized during call_indirect instruction.
nativeCallStatusCodeInvalidTableAccess
// nativeCallStatusCodeTypeMismatchOnIndirectCall means the type check failed during call_indirect.
nativeCallStatusCodeTypeMismatchOnIndirectCall
nativeCallStatusIntegerOverflow
nativeCallStatusIntegerDivisionByZero
nativeCallStatusModuleClosed
)
// causePanic causes a panic with the corresponding error to the nativeCallStatusCode.
func (s nativeCallStatusCode) causePanic() {
var err error
switch s {
case nativeCallStatusIntegerOverflow:
err = wasmruntime.ErrRuntimeIntegerOverflow
case nativeCallStatusIntegerDivisionByZero:
err = wasmruntime.ErrRuntimeIntegerDivideByZero
case nativeCallStatusCodeInvalidFloatToIntConversion:
err = wasmruntime.ErrRuntimeInvalidConversionToInteger
case nativeCallStatusCodeUnreachable:
err = wasmruntime.ErrRuntimeUnreachable
case nativeCallStatusCodeMemoryOutOfBounds:
err = wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess
case nativeCallStatusCodeInvalidTableAccess:
err = wasmruntime.ErrRuntimeInvalidTableAccess
case nativeCallStatusCodeTypeMismatchOnIndirectCall:
err = wasmruntime.ErrRuntimeIndirectCallTypeMismatch
}
panic(err)
}
func (s nativeCallStatusCode) String() (ret string) {
switch s {
case nativeCallStatusCodeReturned:
ret = "returned"
case nativeCallStatusCodeCallGoHostFunction:
ret = "call_host_function"
case nativeCallStatusCodeCallBuiltInFunction:
ret = "call_builtin_function"
case nativeCallStatusCodeUnreachable:
ret = "unreachable"
case nativeCallStatusCodeInvalidFloatToIntConversion:
ret = "invalid float to int conversion"
case nativeCallStatusCodeMemoryOutOfBounds:
ret = "memory out of bounds"
case nativeCallStatusCodeInvalidTableAccess:
ret = "invalid table access"
case nativeCallStatusCodeTypeMismatchOnIndirectCall:
ret = "type mismatch on indirect call"
case nativeCallStatusIntegerOverflow:
ret = "integer overflow"
case nativeCallStatusIntegerDivisionByZero:
ret = "integer division by zero"
case nativeCallStatusModuleClosed:
ret = "module closed"
default:
panic("BUG")
}
return
}
// releaseCompiledModule is a runtime.SetFinalizer function that munmaps the compiledModule.executable.
func releaseCompiledModule(cm *compiledModule) {
e := cm.executable
if e == nil {
return // already released
}
// Setting this to nil allows tests to know the correct finalizer function was called.
cm.executable = nil
if err := platform.MunmapCodeSegment(e); err != nil {
// munmap failure cannot recover, and happen asynchronously on the finalizer thread. While finalizer
// functions can return errors, they are ignored.
panic(fmt.Errorf("compiler: failed to munmap code segment: %w", err))
}
}
// CompiledModuleCount implements the same method as documented on wasm.Engine.
func (e *engine) CompiledModuleCount() uint32 {
return uint32(len(e.codes))
}
// DeleteCompiledModule implements the same method as documented on wasm.Engine.
func (e *engine) DeleteCompiledModule(module *wasm.Module) {
e.deleteCompiledModule(module)
}
// Close implements the same method as documented on wasm.Engine.
func (e *engine) Close() (err error) {
e.mux.Lock()
defer e.mux.Unlock()
// Releasing the references to compiled codes including the memory-mapped machine codes.
e.codes = nil
return
}
// CompileModule implements the same method as documented on wasm.Engine.
func (e *engine) CompileModule(_ context.Context, module *wasm.Module, listeners []experimental.FunctionListener, ensureTermination bool) error {
if _, ok, err := e.getCompiledModule(module, listeners); ok { // cache hit!
return nil
} else if err != nil {
return err
}
irCompiler, err := wazeroir.NewCompiler(e.enabledFeatures, callFrameDataSizeInUint64, module, ensureTermination)
if err != nil {
return err
}
var withGoFunc bool
localFuncs, importedFuncs := len(module.FunctionSection), module.ImportFunctionCount
cm := &compiledModule{
functions: make([]compiledFunction, localFuncs),
ensureTermination: ensureTermination,
source: module,
}
if localFuncs == 0 {
return e.addCompiledModule(module, cm, withGoFunc)
}
bodies := make([][]byte, localFuncs)
// As this uses mmap, we need to munmap on the compiled machine code when it's GCed.
e.setFinalizer(cm, releaseCompiledModule)
ln := len(listeners)
cmp := newCompiler()
for i := range module.CodeSection {
typ := &module.TypeSection[module.FunctionSection[i]]
var lsn experimental.FunctionListener
if i < ln {
lsn = listeners[i]
}
funcIndex := wasm.Index(i)
compiledFn := &cm.functions[i]
var body []byte
if codeSeg := &module.CodeSection[i]; codeSeg.GoFunc != nil {
cmp.Init(typ, nil, lsn != nil)
withGoFunc = true
if body, err = compileGoDefinedHostFunction(cmp); err != nil {
def := module.FunctionDefinitionSection[funcIndex+importedFuncs]
return fmt.Errorf("error compiling host go func[%s]: %w", def.DebugName(), err)
}
compiledFn.goFunc = codeSeg.GoFunc
} else {
ir, err := irCompiler.Next()
if err != nil {
return fmt.Errorf("failed to lower func[%d]: %v", i, err)
}
cmp.Init(typ, ir, lsn != nil)
body, compiledFn.stackPointerCeil, compiledFn.sourceOffsetMap, err = compileWasmFunction(cmp, ir)
if err != nil {
def := module.FunctionDefinitionSection[funcIndex+importedFuncs]
return fmt.Errorf("error compiling wasm func[%s]: %w", def.DebugName(), err)
}
}
// The `body` here is the view owned by assembler and will be overridden by the next iteration, so copy the body here.
bodyCopied := make([]byte, len(body))
copy(bodyCopied, body)
bodies[i] = bodyCopied
compiledFn.listener = lsn
compiledFn.parent = cm
}
var executableOffset int
for i, b := range bodies {
cm.functions[i].executableOffset = executableOffset
// Align 16-bytes boundary.
executableOffset = (executableOffset + len(b) + 15) &^ 15
}
executable, err := platform.MmapCodeSegment(executableOffset)
if err != nil {
return err
}
for i, b := range bodies {
offset := cm.functions[i].executableOffset
copy(executable[offset:], b)
}
if runtime.GOARCH == "arm64" {
// On arm64, we cannot give all of rwx at the same time, so we change it to exec.
if err = platform.MprotectRX(executable); err != nil {
return err
}
}
cm.executable = executable
return e.addCompiledModule(module, cm, withGoFunc)
}
// NewModuleEngine implements the same method as documented on wasm.Engine.
func (e *engine) NewModuleEngine(module *wasm.Module, instance *wasm.ModuleInstance) (wasm.ModuleEngine, error) {
me := &moduleEngine{
functions: make([]function, len(module.FunctionSection)+int(module.ImportFunctionCount)),
}
// Note: imported functions are resolved in moduleEngine.ResolveImportedFunction.
cm, ok, err := e.getCompiledModule(module,
// listeners arg is not needed here since NewModuleEngine is called after CompileModule which
// ensures the association of listener with *code.
nil)
if !ok {
return nil, errors.New("source module must be compiled before instantiation")
} else if err != nil {
return nil, err
}
for i := range cm.functions {
c := &cm.functions[i]
offset := int(module.ImportFunctionCount) + i
typeIndex := module.FunctionSection[i]
me.functions[offset] = function{
codeInitialAddress: uintptr(unsafe.Pointer(&cm.executable[c.executableOffset])),
moduleInstance: instance,
index: wasm.Index(offset),
typeID: instance.TypeIDs[typeIndex],
funcType: &module.TypeSection[typeIndex],
def: &module.FunctionDefinitionSection[offset],
parent: c,
}
}
return me, nil
}
// ResolveImportedFunction implements wasm.ModuleEngine.
func (e *moduleEngine) ResolveImportedFunction(index, indexInImportedModule wasm.Index, importedModuleEngine wasm.ModuleEngine) {
imported := importedModuleEngine.(*moduleEngine)
// Copies the content from the import target moduleEngine.
e.functions[index] = imported.functions[indexInImportedModule]
// Update the .index field to the value in this Module.
e.functions[index].index = index
}
// FunctionInstanceReference implements the same method as documented on wasm.ModuleEngine.
func (e *moduleEngine) FunctionInstanceReference(funcIndex wasm.Index) wasm.Reference {
return uintptr(unsafe.Pointer(&e.functions[funcIndex]))
}
func (e *moduleEngine) NewFunction(index wasm.Index) api.Function {
// Note: The input parameters are pre-validated, so a compiled function is only absent on close. Updates to
// code on close aren't locked, neither is this read.
compiled := &e.functions[index]
initStackSize := initialStackSize
if initialStackSize < compiled.parent.stackPointerCeil {
initStackSize = compiled.parent.stackPointerCeil * 2
}
return e.newCallEngine(initStackSize, compiled)
}
// LookupFunction implements the same method as documented on wasm.ModuleEngine.
func (e *moduleEngine) LookupFunction(t *wasm.TableInstance, typeId wasm.FunctionTypeID, tableOffset wasm.Index) (idx wasm.Index, err error) {
if tableOffset >= uint32(len(t.References)) || t.Type != wasm.RefTypeFuncref {
err = wasmruntime.ErrRuntimeInvalidTableAccess
return
}
rawPtr := t.References[tableOffset]
if rawPtr == 0 {
err = wasmruntime.ErrRuntimeInvalidTableAccess
return
}
tf := functionFromUintptr(rawPtr)
if tf.typeID != typeId {
err = wasmruntime.ErrRuntimeIndirectCallTypeMismatch
return
}
idx = tf.index
return
}
// functionFromUintptr resurrects the original *function from the given uintptr
// which comes from either funcref table or OpcodeRefFunc instruction.
func functionFromUintptr(ptr uintptr) *function {
// Wraps ptrs as the double pointer in order to avoid the unsafe access as detected by race detector.
//
// For example, if we have (*function)(unsafe.Pointer(ptr)) instead, then the race detector's "checkptr"
// subroutine wanrs as "checkptr: pointer arithmetic result points to invalid allocation"
// https://github.com/golang/go/blob/1ce7fcf139417d618c2730010ede2afb41664211/src/runtime/checkptr.go#L69
var wrapped *uintptr = &ptr
return *(**function)(unsafe.Pointer(wrapped))
}
// Definition implements the same method as documented on wasm.ModuleEngine.
func (ce *callEngine) Definition() api.FunctionDefinition {
return ce.initialFn.def
}
// Call implements the same method as documented on wasm.ModuleEngine.
func (ce *callEngine) Call(ctx context.Context, params ...uint64) (results []uint64, err error) {
m := ce.initialFn.moduleInstance
if ce.ensureTermination {
select {
case <-ctx.Done():
// If the provided context is already done, close the call context
// and return the error.
m.CloseWithCtxErr(ctx)
return nil, m.FailIfClosed()
default:
}
}
tp := ce.initialFn.funcType
paramCount := len(params)
if tp.ParamNumInUint64 != paramCount {
return nil, fmt.Errorf("expected %d params, but passed %d", ce.initialFn.funcType.ParamNumInUint64, paramCount)
}
// We ensure that this Call method never panics as
// this Call method is indirectly invoked by embedders via store.CallFunction,
// and we have to make sure that all the runtime errors, including the one happening inside
// host functions, will be captured as errors, not panics.
defer func() {
err = ce.deferredOnCall(recover())
if err == nil {
// If the module closed during the call, and the call didn't err for another reason, set an ExitError.
err = m.FailIfClosed()
}
}()
ce.initializeStack(tp, params)
if ce.ensureTermination {
done := m.CloseModuleOnCanceledOrTimeout(ctx)
defer done()
}
ce.execWasmFunction(ctx, m)
// This returns a safe copy of the results, instead of a slice view. If we
// returned a re-slice, the caller could accidentally or purposefully
// corrupt the stack of subsequent calls
if resultCount := tp.ResultNumInUint64; resultCount > 0 {
results = make([]uint64, resultCount)
copy(results, ce.stack[:resultCount])
}
return
}
// initializeStack initializes callEngine.stack before entering native code.
//
// The stack must look like, if len(params) < len(results):
//
// [arg0, arg1, ..., argN, 0, 0, 0, ...
// { } ^
// callFrame |
// |
// stackPointer
//
// else:
//
// [arg0, arg1, ..., argN, _, _, _, 0, 0, 0, ...
// | | { } ^
// |reserved| callFrame |
// | | |
// |--------> stackPointer
// len(results)-len(params)
//
// where we reserve the slots below the callframe with the length len(results)-len(params).
//
// Note: callFrame { } is zeroed to indicate that the initial "caller" is this callEngine, not the Wasm function.
//
// See callEngine.stack as well.
func (ce *callEngine) initializeStack(tp *wasm.FunctionType, args []uint64) {
for _, v := range args {
ce.pushValue(v)
}
ce.stackPointer = uint64(callFrameOffset(tp))
for i := 0; i < callFrameDataSizeInUint64; i++ {
ce.stack[ce.stackPointer] = 0
ce.stackPointer++
}
}
// callFrameOffset returns the offset of the call frame from the stack base pointer.
//
// See the diagram in callEngine.stack.
func callFrameOffset(funcType *wasm.FunctionType) (ret int) {
ret = funcType.ResultNumInUint64
if ret < funcType.ParamNumInUint64 {
ret = funcType.ParamNumInUint64
}
return
}
// deferredOnCall takes the recovered value `recovered`, and wraps it
// with the call frame stack traces when not nil. This also resets
// the state of callEngine so that it can be used for the subsequent calls.
//
// This is defined for testability.
func (ce *callEngine) deferredOnCall(recovered interface{}) (err error) {
if recovered != nil {
builder := wasmdebug.NewErrorBuilder()
// Unwinds call frames from the values stack, starting from the
// current function `ce.fn`, and the current stack base pointer `ce.stackBasePointerInBytes`.
fn := ce.fn
pc := uint64(ce.returnAddress)
stackBasePointer := int(ce.stackBasePointerInBytes >> 3)
for {
def := fn.def
// sourceInfo holds the source code information corresponding to the frame.
// It is not empty only when the DWARF is enabled.
var sources []string
if p := fn.parent; p.parent.executable != nil {
if len(fn.parent.sourceOffsetMap.irOperationSourceOffsetsInWasmBinary) != 0 {
offset := fn.getSourceOffsetInWasmBinary(pc)
sources = p.parent.source.DWARFLines.Line(offset)
}
}
builder.AddFrame(def.DebugName(), def.ParamTypes(), def.ResultTypes(), sources)
callFrameOffset := callFrameOffset(fn.funcType)
if stackBasePointer != 0 {
frame := *(*callFrame)(unsafe.Pointer(&ce.stack[stackBasePointer+callFrameOffset]))
fn = frame.function
pc = uint64(frame.returnAddress)
stackBasePointer = int(frame.returnStackBasePointerInBytes >> 3)
} else { // base == 0 means that this was the last call frame stacked.
break
}
}
err = builder.FromRecovered(recovered)
}
// Allows the reuse of CallEngine.
ce.stackBasePointerInBytes, ce.stackPointer, ce.moduleInstance = 0, 0, nil
ce.moduleContext.fn = ce.initialFn
return
}
// getSourceOffsetInWasmBinary returns the corresponding offset in the original Wasm binary's code section
// for the given pc (which is an absolute address in the memory).
// If needPreviousInstr equals true, this returns the previous instruction's offset for the given pc.
func (f *function) getSourceOffsetInWasmBinary(pc uint64) uint64 {
srcMap := &f.parent.sourceOffsetMap
n := len(srcMap.irOperationOffsetsInNativeBinary) + 1
// Calculate the offset in the compiled native binary.
pcOffsetInNativeBinary := pc - uint64(f.codeInitialAddress)
// Then, do the binary search on the list of offsets in the native binary for all the IR operations.
// This returns the index of the *next* IR operation of the one corresponding to the origin of this pc.
// See sort.Search.
index := sort.Search(n, func(i int) bool {
if i == n-1 {
return true
}
return srcMap.irOperationOffsetsInNativeBinary[i] >= pcOffsetInNativeBinary
})
if index == n || index == 0 { // This case, somehow pc is not found in the source offset map.
return 0
} else {
return srcMap.irOperationSourceOffsetsInWasmBinary[index-1]
}
}
func NewEngine(_ context.Context, enabledFeatures api.CoreFeatures, fileCache filecache.Cache) wasm.Engine {
return newEngine(enabledFeatures, fileCache)
}
func newEngine(enabledFeatures api.CoreFeatures, fileCache filecache.Cache) *engine {
return &engine{
enabledFeatures: enabledFeatures,
codes: map[wasm.ModuleID]*compiledModule{},
setFinalizer: runtime.SetFinalizer,
fileCache: fileCache,
wazeroVersion: version.GetWazeroVersion(),
}
}
// Do not make this variable as constant, otherwise there would be
// dangerous memory access from native code.
//
// Background: Go has a mechanism called "goroutine stack-shrink" where Go
// runtime shrinks Goroutine's stack when it is GCing. Shrinking means that
// all the contents on the goroutine stack will be relocated by runtime,
// Therefore, the memory address of these contents change undeterministically.
// Not only shrinks, but also Go runtime grows the goroutine stack at any point
// of function call entries, which also might end up relocating contents.
//
// On the other hand, we hold pointers to the data region of value stack and
// call-frame stack slices and use these raw pointers from native code.
// Therefore, it is dangerous if these two stacks are allocated on stack
// as these stack's address might be changed by Goroutine which we cannot
// detect.
//
// By declaring these values as `var`, slices created via `make([]..., var)`
// will never be allocated on stack [1]. This means accessing these slices via
// raw pointers is safe: As of version 1.18, Go's garbage collector never relocates
// heap-allocated objects (aka no compaction of memory [2]).
//
// On Go upgrades, re-validate heap-allocation via `go build -gcflags='-m' ./internal/engine/compiler/...`.
//
// [1] https://github.com/golang/go/blob/68ecdc2c70544c303aa923139a5f16caf107d955/src/cmd/compile/internal/escape/utils.go#L206-L208
// [2] https://github.com/golang/go/blob/68ecdc2c70544c303aa923139a5f16caf107d955/src/runtime/mgc.go#L9
// [3] https://mayurwadekar2.medium.com/escape-analysis-in-golang-ee40a1c064c1
// [4] https://medium.com/@yulang.chu/go-stack-or-heap-2-slices-which-keep-in-stack-have-limitation-of-size-b3f3adfd6190
var initialStackSize uint64 = 512
func (e *moduleEngine) newCallEngine(stackSize uint64, fn *function) *callEngine {
ce := &callEngine{
stack: make([]uint64, stackSize),
archContext: newArchContext(),
initialFn: fn,
moduleContext: moduleContext{fn: fn},
ensureTermination: fn.parent.parent.ensureTermination,
}
stackHeader := (*reflect.SliceHeader)(unsafe.Pointer(&ce.stack))
ce.stackContext = stackContext{
stackElement0Address: stackHeader.Data,
stackLenInBytes: uint64(stackHeader.Len) << 3,
}
return ce
}
func (ce *callEngine) popValue() (ret uint64) {
ce.stackContext.stackPointer--
ret = ce.stack[ce.stackTopIndex()]
return
}
func (ce *callEngine) pushValue(v uint64) {
ce.stack[ce.stackTopIndex()] = v
ce.stackContext.stackPointer++
}
func (ce *callEngine) stackTopIndex() uint64 {
return ce.stackContext.stackPointer + (ce.stackContext.stackBasePointerInBytes >> 3)
}
const (
builtinFunctionIndexMemoryGrow wasm.Index = iota
builtinFunctionIndexGrowStack
builtinFunctionIndexTableGrow
builtinFunctionIndexFunctionListenerBefore
builtinFunctionIndexFunctionListenerAfter
builtinFunctionIndexCheckExitCode
// builtinFunctionIndexBreakPoint is internal (only for wazero developers). Disabled by default.
builtinFunctionIndexBreakPoint
)
func (ce *callEngine) execWasmFunction(ctx context.Context, m *wasm.ModuleInstance) {
codeAddr := ce.initialFn.codeInitialAddress
modAddr := ce.initialFn.moduleInstance
ce.ctx = ctx
entry:
{
// Call into the native code.
nativecall(codeAddr, uintptr(unsafe.Pointer(ce)), modAddr)
// Check the status code from Compiler code.
switch status := ce.exitContext.statusCode; status {
case nativeCallStatusCodeReturned:
case nativeCallStatusCodeCallGoHostFunction:
calleeHostFunction := ce.moduleContext.fn
base := int(ce.stackBasePointerInBytes >> 3)
// In the compiler engine, ce.stack has enough capacity for the
// max of param or result length, so we don't need to grow when
// there are more results than parameters.
stackLen := calleeHostFunction.funcType.ParamNumInUint64
if resultLen := calleeHostFunction.funcType.ResultNumInUint64; resultLen > stackLen {
stackLen = resultLen
}
stack := ce.stack[base : base+stackLen]
fn := calleeHostFunction.parent.goFunc
switch fn := fn.(type) {
case api.GoModuleFunction:
fn.Call(ce.ctx, ce.callerModuleInstance, stack)
case api.GoFunction:
fn.Call(ce.ctx, stack)
}
codeAddr, modAddr = ce.returnAddress, ce.moduleInstance
goto entry
case nativeCallStatusCodeCallBuiltInFunction:
caller := ce.moduleContext.fn