-
Notifications
You must be signed in to change notification settings - Fork 244
/
func_validation.go
2340 lines (2255 loc) · 87.8 KB
/
func_validation.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 wasm
import (
"bytes"
"errors"
"fmt"
"strconv"
"strings"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/experimental"
"github.com/tetratelabs/wazero/internal/leb128"
)
// The wazero specific limitation described at RATIONALE.md.
const maximumValuesOnStack = 1 << 27
// validateFunction validates the instruction sequence of a function.
// following the specification https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#instructions%E2%91%A2.
//
// * idx is the index in the FunctionSection
// * functions are the function index, which is prefixed by imports. The value is the TypeSection index.
// * globals are the global index, which is prefixed by imports.
// * memory is the potentially imported memory and can be nil.
// * table is the potentially imported table and can be nil.
// * declaredFunctionIndexes is the set of function indexes declared by declarative element segments which can be acceed by OpcodeRefFunc instruction.
//
// Returns an error if the instruction sequence is not valid,
// or potentially it can exceed the maximum number of values on the stack.
func (m *Module) validateFunction(sts *stacks, enabledFeatures api.CoreFeatures, idx Index, functions []Index,
globals []GlobalType, memory *Memory, tables []Table, declaredFunctionIndexes map[Index]struct{}, br *bytes.Reader,
) error {
return m.validateFunctionWithMaxStackValues(sts, enabledFeatures, idx, functions, globals, memory, tables, maximumValuesOnStack, declaredFunctionIndexes, br)
}
func readMemArg(pc uint64, body []byte) (align, offset uint32, read uint64, err error) {
align, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
err = fmt.Errorf("read memory align: %v", err)
return
}
read += num
offset, num, err = leb128.LoadUint32(body[pc+num:])
if err != nil {
err = fmt.Errorf("read memory offset: %v", err)
return
}
read += num
return align, offset, read, nil
}
// validateFunctionWithMaxStackValues is like validateFunction, but allows overriding maxStackValues for testing.
//
// * stacks is to track the state of Wasm value and control frame stacks at anypoint of execution, and reused to reduce allocation.
// * maxStackValues is the maximum height of values stack which the target is allowed to reach.
func (m *Module) validateFunctionWithMaxStackValues(
sts *stacks,
enabledFeatures api.CoreFeatures,
idx Index,
functions []Index,
globals []GlobalType,
memory *Memory,
tables []Table,
maxStackValues int,
declaredFunctionIndexes map[Index]struct{},
br *bytes.Reader,
) error {
nonStaticLocals := make(map[Index]struct{})
if len(m.NonStaticLocals) > 0 {
m.NonStaticLocals[idx] = nonStaticLocals
}
functionType := &m.TypeSection[m.FunctionSection[idx]]
code := &m.CodeSection[idx]
body := code.Body
localTypes := code.LocalTypes
sts.reset(functionType)
valueTypeStack := &sts.vs
// We start with the outermost control block which is for function return if the code branches into it.
controlBlockStack := &sts.cs
// Now start walking through all the instructions in the body while tracking
// control blocks and value types to check the validity of all instructions.
for pc := uint64(0); pc < uint64(len(body)); pc++ {
op := body[pc]
if false {
var instName string
if op == OpcodeMiscPrefix {
instName = MiscInstructionName(body[pc+1])
} else if op == OpcodeVecPrefix {
instName = VectorInstructionName(body[pc+1])
} else if op == OpcodeAtomicPrefix {
instName = AtomicInstructionName(body[pc+1])
} else {
instName = InstructionName(op)
}
fmt.Printf("handling %s, stack=%s, blocks: %v\n", instName, valueTypeStack.stack, controlBlockStack)
}
if len(controlBlockStack.stack) == 0 {
return fmt.Errorf("unexpected end of function at pc=%#x", pc)
}
if OpcodeI32Load <= op && op <= OpcodeI64Store32 {
if memory == nil {
return fmt.Errorf("memory must exist for %s", InstructionName(op))
}
pc++
align, _, read, err := readMemArg(pc, body)
if err != nil {
return err
}
pc += read - 1
switch op {
case OpcodeI32Load:
if 1<<align > 32/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI32)
case OpcodeF32Load:
if 1<<align > 32/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeF32)
case OpcodeI32Store:
if 1<<align > 32/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeF32Store:
if 1<<align > 32/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeI64Load:
if 1<<align > 64/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI64)
case OpcodeF64Load:
if 1<<align > 64/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeF64)
case OpcodeI64Store:
if 1<<align > 64/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeF64Store:
if 1<<align > 64/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeI32Load8S:
if 1<<align > 1 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI32Load8U:
if 1<<align > 1 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64Load8S, OpcodeI64Load8U:
if 1<<align > 1 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI64)
case OpcodeI32Store8:
if 1<<align > 1 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeI64Store8:
if 1<<align > 1 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeI32Load16S, OpcodeI32Load16U:
if 1<<align > 16/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64Load16S, OpcodeI64Load16U:
if 1<<align > 16/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI64)
case OpcodeI32Store16:
if 1<<align > 16/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeI64Store16:
if 1<<align > 16/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
case OpcodeI64Load32S, OpcodeI64Load32U:
if 1<<align > 32/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI64)
case OpcodeI64Store32:
if 1<<align > 32/8 {
return fmt.Errorf("invalid memory alignment")
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return err
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
}
} else if OpcodeMemorySize <= op && op <= OpcodeMemoryGrow {
if memory == nil {
return fmt.Errorf("memory must exist for %s", InstructionName(op))
}
pc++
val, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read immediate: %v", err)
}
if val != 0 || num != 1 {
return fmt.Errorf("memory instruction reserved bytes not zero with 1 byte")
}
switch Opcode(op) {
case OpcodeMemoryGrow:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return err
}
valueTypeStack.push(ValueTypeI32)
case OpcodeMemorySize:
valueTypeStack.push(ValueTypeI32)
}
pc += num - 1
} else if OpcodeI32Const <= op && op <= OpcodeF64Const {
pc++
switch Opcode(op) {
case OpcodeI32Const:
_, num, err := leb128.LoadInt32(body[pc:])
if err != nil {
return fmt.Errorf("read i32 immediate: %s", err)
}
pc += num - 1
valueTypeStack.push(ValueTypeI32)
case OpcodeI64Const:
_, num, err := leb128.LoadInt64(body[pc:])
if err != nil {
return fmt.Errorf("read i64 immediate: %v", err)
}
valueTypeStack.push(ValueTypeI64)
pc += num - 1
case OpcodeF32Const:
valueTypeStack.push(ValueTypeF32)
pc += 3
case OpcodeF64Const:
valueTypeStack.push(ValueTypeF64)
pc += 7
}
} else if OpcodeLocalGet <= op && op <= OpcodeGlobalSet {
pc++
index, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read immediate: %v", err)
}
pc += num - 1
switch op {
case OpcodeLocalGet:
inputLen := uint32(len(functionType.Params))
if l := uint32(len(localTypes)) + inputLen; index >= l {
return fmt.Errorf("invalid local index for %s %d >= %d(=len(locals)+len(parameters))",
OpcodeLocalGetName, index, l)
}
if index < inputLen {
valueTypeStack.push(functionType.Params[index])
} else {
valueTypeStack.push(localTypes[index-inputLen])
}
case OpcodeLocalSet:
inputLen := uint32(len(functionType.Params))
if l := uint32(len(localTypes)) + inputLen; index >= l {
return fmt.Errorf("invalid local index for %s %d >= %d(=len(locals)+len(parameters))",
OpcodeLocalSetName, index, l)
}
nonStaticLocals[index] = struct{}{}
var expType ValueType
if index < inputLen {
expType = functionType.Params[index]
} else {
expType = localTypes[index-inputLen]
}
if err := valueTypeStack.popAndVerifyType(expType); err != nil {
return err
}
case OpcodeLocalTee:
inputLen := uint32(len(functionType.Params))
if l := uint32(len(localTypes)) + inputLen; index >= l {
return fmt.Errorf("invalid local index for %s %d >= %d(=len(locals)+len(parameters))",
OpcodeLocalTeeName, index, l)
}
nonStaticLocals[index] = struct{}{}
var expType ValueType
if index < inputLen {
expType = functionType.Params[index]
} else {
expType = localTypes[index-inputLen]
}
if err := valueTypeStack.popAndVerifyType(expType); err != nil {
return err
}
valueTypeStack.push(expType)
case OpcodeGlobalGet:
if index >= uint32(len(globals)) {
return fmt.Errorf("invalid index for %s", OpcodeGlobalGetName)
}
valueTypeStack.push(globals[index].ValType)
case OpcodeGlobalSet:
if index >= uint32(len(globals)) {
return fmt.Errorf("invalid global index")
} else if !globals[index].Mutable {
return fmt.Errorf("%s when not mutable", OpcodeGlobalSetName)
} else if err := valueTypeStack.popAndVerifyType(
globals[index].ValType); err != nil {
return err
}
}
} else if op == OpcodeBr {
pc++
index, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read immediate: %v", err)
} else if int(index) >= len(controlBlockStack.stack) {
return fmt.Errorf("invalid %s operation: index out of range", OpcodeBrName)
}
pc += num - 1
// Check type soundness.
target := &controlBlockStack.stack[len(controlBlockStack.stack)-int(index)-1]
var targetResultType []ValueType
if target.op == OpcodeLoop {
targetResultType = target.blockType.Params
} else {
targetResultType = target.blockType.Results
}
if err = valueTypeStack.popResults(op, targetResultType, false); err != nil {
return err
}
// br instruction is stack-polymorphic.
valueTypeStack.unreachable()
} else if op == OpcodeBrIf {
pc++
index, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read immediate: %v", err)
} else if int(index) >= len(controlBlockStack.stack) {
return fmt.Errorf(
"invalid ln param given for %s: index=%d with %d for the current label stack length",
OpcodeBrIfName, index, len(controlBlockStack.stack))
}
pc += num - 1
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the required operand for %s", OpcodeBrIfName)
}
// Check type soundness.
target := &controlBlockStack.stack[len(controlBlockStack.stack)-int(index)-1]
var targetResultType []ValueType
if target.op == OpcodeLoop {
targetResultType = target.blockType.Params
} else {
targetResultType = target.blockType.Results
}
if err := valueTypeStack.popResults(op, targetResultType, false); err != nil {
return err
}
// Push back the result
for _, t := range targetResultType {
valueTypeStack.push(t)
}
} else if op == OpcodeBrTable {
pc++
br.Reset(body[pc:])
nl, num, err := leb128.DecodeUint32(br)
if err != nil {
return fmt.Errorf("read immediate: %w", err)
}
list := make([]uint32, nl)
for i := uint32(0); i < nl; i++ {
l, n, err := leb128.DecodeUint32(br)
if err != nil {
return fmt.Errorf("read immediate: %w", err)
}
num += n
list[i] = l
}
ln, n, err := leb128.DecodeUint32(br)
if err != nil {
return fmt.Errorf("read immediate: %w", err)
} else if int(ln) >= len(controlBlockStack.stack) {
return fmt.Errorf(
"invalid ln param given for %s: ln=%d with %d for the current label stack length",
OpcodeBrTableName, ln, len(controlBlockStack.stack))
}
pc += n + num - 1
// Check type soundness.
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the required operand for %s", OpcodeBrTableName)
}
lnLabel := &controlBlockStack.stack[len(controlBlockStack.stack)-1-int(ln)]
var defaultLabelType []ValueType
// Below, we might modify the slice in case of unreachable. Therefore,
// we have to copy the content of block result types, otherwise the original
// function type might result in invalid value types if the block is the outermost label
// which equals the function's type.
if lnLabel.op != OpcodeLoop { // Loop operation doesn't require results since the continuation is the beginning of the loop.
defaultLabelType = make([]ValueType, len(lnLabel.blockType.Results))
copy(defaultLabelType, lnLabel.blockType.Results)
} else {
defaultLabelType = make([]ValueType, len(lnLabel.blockType.Params))
copy(defaultLabelType, lnLabel.blockType.Params)
}
if enabledFeatures.IsEnabled(api.CoreFeatureReferenceTypes) {
// As of reference-types proposal, br_table on unreachable state
// can choose unknown types for expected parameter types for each label.
// https://github.com/WebAssembly/reference-types/pull/116
for i := range defaultLabelType {
index := len(defaultLabelType) - 1 - i
exp := defaultLabelType[index]
actual, err := valueTypeStack.pop()
if err != nil {
return err
}
if actual == valueTypeUnknown {
// Re-assign the expected type to unknown.
defaultLabelType[index] = valueTypeUnknown
} else if actual != exp {
return typeMismatchError(true, OpcodeBrTableName, actual, exp, i)
}
}
} else {
if err = valueTypeStack.popResults(op, defaultLabelType, false); err != nil {
return err
}
}
for _, l := range list {
if int(l) >= len(controlBlockStack.stack) {
return fmt.Errorf("invalid l param given for %s", OpcodeBrTableName)
}
label := &controlBlockStack.stack[len(controlBlockStack.stack)-1-int(l)]
var tableLabelType []ValueType
if label.op != OpcodeLoop {
tableLabelType = label.blockType.Results
} else {
tableLabelType = label.blockType.Params
}
if len(defaultLabelType) != len(tableLabelType) {
return fmt.Errorf("inconsistent block type length for %s at %d; %v (ln=%d) != %v (l=%d)", OpcodeBrTableName, l, defaultLabelType, ln, tableLabelType, l)
}
for i := range defaultLabelType {
if defaultLabelType[i] != valueTypeUnknown && defaultLabelType[i] != tableLabelType[i] {
return fmt.Errorf("incosistent block type for %s at %d", OpcodeBrTableName, l)
}
}
}
// br_table instruction is stack-polymorphic.
valueTypeStack.unreachable()
} else if op == OpcodeCall {
pc++
index, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read immediate: %v", err)
}
pc += num - 1
if int(index) >= len(functions) {
return fmt.Errorf("invalid function index")
}
funcType := &m.TypeSection[functions[index]]
for i := 0; i < len(funcType.Params); i++ {
if err := valueTypeStack.popAndVerifyType(funcType.Params[len(funcType.Params)-1-i]); err != nil {
return fmt.Errorf("type mismatch on %s operation param type: %v", OpcodeCallName, err)
}
}
for _, exp := range funcType.Results {
valueTypeStack.push(exp)
}
} else if op == OpcodeCallIndirect {
pc++
typeIndex, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read immediate: %v", err)
}
pc += num
if int(typeIndex) >= len(m.TypeSection) {
return fmt.Errorf("invalid type index at %s: %d", OpcodeCallIndirectName, typeIndex)
}
tableIndex, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read table index: %v", err)
}
pc += num - 1
if tableIndex != 0 {
if err := enabledFeatures.RequireEnabled(api.CoreFeatureReferenceTypes); err != nil {
return fmt.Errorf("table index must be zero but was %d: %w", tableIndex, err)
}
}
if tableIndex >= uint32(len(tables)) {
return fmt.Errorf("unknown table index: %d", tableIndex)
}
table := tables[tableIndex]
if table.Type != RefTypeFuncref {
return fmt.Errorf("table is not funcref type but was %s for %s", RefTypeName(table.Type), OpcodeCallIndirectName)
}
if err = valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the offset in table for %s", OpcodeCallIndirectName)
}
funcType := &m.TypeSection[typeIndex]
for i := 0; i < len(funcType.Params); i++ {
if err = valueTypeStack.popAndVerifyType(funcType.Params[len(funcType.Params)-1-i]); err != nil {
return fmt.Errorf("type mismatch on %s operation input type", OpcodeCallIndirectName)
}
}
for _, exp := range funcType.Results {
valueTypeStack.push(exp)
}
} else if OpcodeI32Eqz <= op && op <= OpcodeI64Extend32S {
switch op {
case OpcodeI32Eqz:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeI32EqzName, err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI32Eq, OpcodeI32Ne, OpcodeI32LtS,
OpcodeI32LtU, OpcodeI32GtS, OpcodeI32GtU, OpcodeI32LeS,
OpcodeI32LeU, OpcodeI32GeS, OpcodeI32GeU:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the 1st i32 operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the 2nd i32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64Eqz:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeI64EqzName, err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64Eq, OpcodeI64Ne, OpcodeI64LtS,
OpcodeI64LtU, OpcodeI64GtS, OpcodeI64GtU,
OpcodeI64LeS, OpcodeI64LeU, OpcodeI64GeS, OpcodeI64GeU:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the 1st i64 operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the 2nd i64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeF32Eq, OpcodeF32Ne, OpcodeF32Lt, OpcodeF32Gt, OpcodeF32Le, OpcodeF32Ge:
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the 1st f32 operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the 2nd f32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeF64Eq, OpcodeF64Ne, OpcodeF64Lt, OpcodeF64Gt, OpcodeF64Le, OpcodeF64Ge:
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the 1st f64 operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the 2nd f64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI32Clz, OpcodeI32Ctz, OpcodeI32Popcnt:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the i32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI32Add, OpcodeI32Sub, OpcodeI32Mul, OpcodeI32DivS,
OpcodeI32DivU, OpcodeI32RemS, OpcodeI32RemU, OpcodeI32And,
OpcodeI32Or, OpcodeI32Xor, OpcodeI32Shl, OpcodeI32ShrS,
OpcodeI32ShrU, OpcodeI32Rotl, OpcodeI32Rotr:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the 1st operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the 2nd operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64Clz, OpcodeI64Ctz, OpcodeI64Popcnt:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the i64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI64)
case OpcodeI64Add, OpcodeI64Sub, OpcodeI64Mul, OpcodeI64DivS,
OpcodeI64DivU, OpcodeI64RemS, OpcodeI64RemU, OpcodeI64And,
OpcodeI64Or, OpcodeI64Xor, OpcodeI64Shl, OpcodeI64ShrS,
OpcodeI64ShrU, OpcodeI64Rotl, OpcodeI64Rotr:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the 1st i64 operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the 2nd i64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI64)
case OpcodeF32Abs, OpcodeF32Neg, OpcodeF32Ceil,
OpcodeF32Floor, OpcodeF32Trunc, OpcodeF32Nearest,
OpcodeF32Sqrt:
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the 1st f32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF32)
case OpcodeF32Add, OpcodeF32Sub, OpcodeF32Mul,
OpcodeF32Div, OpcodeF32Min, OpcodeF32Max,
OpcodeF32Copysign:
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the 1st f32 operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the 2nd f32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF32)
case OpcodeF64Abs, OpcodeF64Neg, OpcodeF64Ceil,
OpcodeF64Floor, OpcodeF64Trunc, OpcodeF64Nearest,
OpcodeF64Sqrt:
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the 1st f64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF64)
case OpcodeF64Add, OpcodeF64Sub, OpcodeF64Mul,
OpcodeF64Div, OpcodeF64Min, OpcodeF64Max,
OpcodeF64Copysign:
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the 1st f64 operand for %s: %v", InstructionName(op), err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the 2nd f64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF64)
case OpcodeI32WrapI64:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeI32WrapI64Name, err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI32TruncF32S, OpcodeI32TruncF32U:
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the f32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI32TruncF64S, OpcodeI32TruncF64U:
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the f64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64ExtendI32S, OpcodeI64ExtendI32U:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the i32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI64)
case OpcodeI64TruncF32S, OpcodeI64TruncF32U:
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the f32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI64)
case OpcodeI64TruncF64S, OpcodeI64TruncF64U:
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the f64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeI64)
case OpcodeF32ConvertI32S, OpcodeF32ConvertI32U:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the i32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF32)
case OpcodeF32ConvertI64S, OpcodeF32ConvertI64U:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the i64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF32)
case OpcodeF32DemoteF64:
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeF32DemoteF64Name, err)
}
valueTypeStack.push(ValueTypeF32)
case OpcodeF64ConvertI32S, OpcodeF64ConvertI32U:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the i32 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF64)
case OpcodeF64ConvertI64S, OpcodeF64ConvertI64U:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the i64 operand for %s: %v", InstructionName(op), err)
}
valueTypeStack.push(ValueTypeF64)
case OpcodeF64PromoteF32:
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeF64PromoteF32Name, err)
}
valueTypeStack.push(ValueTypeF64)
case OpcodeI32ReinterpretF32:
if err := valueTypeStack.popAndVerifyType(ValueTypeF32); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeI32ReinterpretF32Name, err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64ReinterpretF64:
if err := valueTypeStack.popAndVerifyType(ValueTypeF64); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeI64ReinterpretF64Name, err)
}
valueTypeStack.push(ValueTypeI64)
case OpcodeF32ReinterpretI32:
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeF32ReinterpretI32Name, err)
}
valueTypeStack.push(ValueTypeF32)
case OpcodeF64ReinterpretI64:
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", OpcodeF64ReinterpretI64Name, err)
}
valueTypeStack.push(ValueTypeF64)
case OpcodeI32Extend8S, OpcodeI32Extend16S:
if err := enabledFeatures.RequireEnabled(api.CoreFeatureSignExtensionOps); err != nil {
return fmt.Errorf("%s invalid as %v", instructionNames[op], err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", instructionNames[op], err)
}
valueTypeStack.push(ValueTypeI32)
case OpcodeI64Extend8S, OpcodeI64Extend16S, OpcodeI64Extend32S:
if err := enabledFeatures.RequireEnabled(api.CoreFeatureSignExtensionOps); err != nil {
return fmt.Errorf("%s invalid as %v", instructionNames[op], err)
}
if err := valueTypeStack.popAndVerifyType(ValueTypeI64); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", instructionNames[op], err)
}
valueTypeStack.push(ValueTypeI64)
default:
return fmt.Errorf("invalid numeric instruction 0x%x", op)
}
} else if op >= OpcodeRefNull && op <= OpcodeRefFunc {
if err := enabledFeatures.RequireEnabled(api.CoreFeatureReferenceTypes); err != nil {
return fmt.Errorf("%s invalid as %v", instructionNames[op], err)
}
switch op {
case OpcodeRefNull:
pc++
switch reftype := body[pc]; reftype {
case ValueTypeExternref:
valueTypeStack.push(ValueTypeExternref)
case ValueTypeFuncref:
valueTypeStack.push(ValueTypeFuncref)
default:
return fmt.Errorf("unknown type for ref.null: 0x%x", reftype)
}
case OpcodeRefIsNull:
tp, err := valueTypeStack.pop()
if err != nil {
return fmt.Errorf("cannot pop the operand for ref.is_null: %v", err)
} else if !isReferenceValueType(tp) && tp != valueTypeUnknown {
return fmt.Errorf("type mismatch: expected reference type but was %s", ValueTypeName(tp))
}
valueTypeStack.push(ValueTypeI32)
case OpcodeRefFunc:
pc++
index, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read function index for ref.func: %v", err)
}
if _, ok := declaredFunctionIndexes[index]; !ok {
return fmt.Errorf("undeclared function index %d for ref.func", index)
}
pc += num - 1
valueTypeStack.push(ValueTypeFuncref)
}
} else if op == OpcodeTableGet || op == OpcodeTableSet {
if err := enabledFeatures.RequireEnabled(api.CoreFeatureReferenceTypes); err != nil {
return fmt.Errorf("%s is invalid as %v", InstructionName(op), err)
}
pc++
tableIndex, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("read immediate: %v", err)
}
if tableIndex >= uint32(len(tables)) {
return fmt.Errorf("table of index %d not found", tableIndex)
}
refType := tables[tableIndex].Type
if op == OpcodeTableGet {
if err := valueTypeStack.popAndVerifyType(api.ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the operand for table.get: %v", err)
}
valueTypeStack.push(refType)
} else {
if err := valueTypeStack.popAndVerifyType(refType); err != nil {
return fmt.Errorf("cannot pop the operand for table.set: %v", err)
}
if err := valueTypeStack.popAndVerifyType(api.ValueTypeI32); err != nil {
return fmt.Errorf("cannot pop the operand for table.set: %v", err)
}
}
pc += num - 1
} else if op == OpcodeMiscPrefix {
pc++
// A misc opcode is encoded as an unsigned variable 32-bit integer.
miscOp32, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read misc opcode: %v", err)
}
pc += num - 1
miscOpcode := byte(miscOp32)
// If the misc opcode is beyond byte range, it is highly likely this is an invalid binary, or
// it is due to the new opcode from a new proposal. In the latter case, we have to
// change the alias type of OpcodeMisc (which is currently byte) to uint32.
if uint32(byte(miscOp32)) != miscOp32 {
return fmt.Errorf("invalid misc opcode: %#x", miscOp32)
}
if miscOpcode >= OpcodeMiscI32TruncSatF32S && miscOpcode <= OpcodeMiscI64TruncSatF64U {
if err := enabledFeatures.RequireEnabled(api.CoreFeatureNonTrappingFloatToIntConversion); err != nil {
return fmt.Errorf("%s invalid as %v", miscInstructionNames[miscOpcode], err)
}
var inType, outType ValueType
switch miscOpcode {
case OpcodeMiscI32TruncSatF32S, OpcodeMiscI32TruncSatF32U:
inType, outType = ValueTypeF32, ValueTypeI32
case OpcodeMiscI32TruncSatF64S, OpcodeMiscI32TruncSatF64U:
inType, outType = ValueTypeF64, ValueTypeI32
case OpcodeMiscI64TruncSatF32S, OpcodeMiscI64TruncSatF32U:
inType, outType = ValueTypeF32, ValueTypeI64
case OpcodeMiscI64TruncSatF64S, OpcodeMiscI64TruncSatF64U:
inType, outType = ValueTypeF64, ValueTypeI64
}
if err := valueTypeStack.popAndVerifyType(inType); err != nil {
return fmt.Errorf("cannot pop the operand for %s: %v", miscInstructionNames[miscOpcode], err)
}
valueTypeStack.push(outType)
} else if miscOpcode >= OpcodeMiscMemoryInit && miscOpcode <= OpcodeMiscTableCopy {
if err := enabledFeatures.RequireEnabled(api.CoreFeatureBulkMemoryOperations); err != nil {
return fmt.Errorf("%s invalid as %v", miscInstructionNames[miscOpcode], err)
}
var params []ValueType
// Handle opcodes added in bulk-memory-operations/WebAssembly 2.0.
switch miscOpcode {
case OpcodeMiscDataDrop:
if m.DataCountSection == nil {
return fmt.Errorf("%s requires data count section", MiscInstructionName(miscOpcode))
}
// We need to read the index to the data section.
pc++
index, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read data segment index for %s: %v", MiscInstructionName(miscOpcode), err)
}
if int(index) >= len(m.DataSection) {
return fmt.Errorf("index %d out of range of data section(len=%d)", index, len(m.DataSection))
}
pc += num - 1
case OpcodeMiscMemoryInit, OpcodeMiscMemoryCopy, OpcodeMiscMemoryFill:
if memory == nil {
return fmt.Errorf("memory must exist for %s", MiscInstructionName(miscOpcode))
}
params = []ValueType{ValueTypeI32, ValueTypeI32, ValueTypeI32}
if miscOpcode == OpcodeMiscMemoryInit {
if m.DataCountSection == nil {
return fmt.Errorf("%s requires data count section", MiscInstructionName(miscOpcode))
}
// We need to read the index to the data section.
pc++
index, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read data segment index for %s: %v", MiscInstructionName(miscOpcode), err)
}
if int(index) >= len(m.DataSection) {
return fmt.Errorf("index %d out of range of data section(len=%d)", index, len(m.DataSection))
}
pc += num - 1
}
pc++
val, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read memory index for %s: %v", MiscInstructionName(miscOpcode), err)
}
if val != 0 || num != 1 {
return fmt.Errorf("%s reserved byte must be zero encoded with 1 byte", MiscInstructionName(miscOpcode))
}
if miscOpcode == OpcodeMiscMemoryCopy {
pc++
// memory.copy needs two memory index which are reserved as zero.
val, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read memory index for %s: %v", MiscInstructionName(miscOpcode), err)
}
if val != 0 || num != 1 {
return fmt.Errorf("%s reserved byte must be zero encoded with 1 byte", MiscInstructionName(miscOpcode))
}
}
case OpcodeMiscTableInit:
params = []ValueType{ValueTypeI32, ValueTypeI32, ValueTypeI32}
pc++
elementIndex, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read element segment index for %s: %v", MiscInstructionName(miscOpcode), err)
}
if int(elementIndex) >= len(m.ElementSection) {
return fmt.Errorf("index %d out of range of element section(len=%d)", elementIndex, len(m.ElementSection))
}
pc += num
tableIndex, num, err := leb128.LoadUint32(body[pc:])
if err != nil {
return fmt.Errorf("failed to read source table index for %s: %v", MiscInstructionName(miscOpcode), err)
}
if tableIndex != 0 {
if err := enabledFeatures.RequireEnabled(api.CoreFeatureReferenceTypes); err != nil {
return fmt.Errorf("source table index must be zero for %s as %v", MiscInstructionName(miscOpcode), err)