Debian Codegraph @

internal/integration_test/spectest/spectest.go

raw
1 package spectest
2
3 import (
4 "context"
5 "embed"
6 "encoding/json"
7 "fmt"
8 "math"
9 "strconv"
10 "strings"
11 "testing"
12
13 "github.com/tetratelabs/wazero"
14 "github.com/tetratelabs/wazero/api"
15 "github.com/tetratelabs/wazero/internal/moremath"
16 "github.com/tetratelabs/wazero/internal/testing/require"
17 "github.com/tetratelabs/wazero/internal/wasm"
18 "github.com/tetratelabs/wazero/internal/wasmruntime"
19 )
20
21 type (
22 testbase struct {
23 SourceFile string `json:"source_filename"`
24 Commands []command `json:"commands"`
25 }
26 command struct {
27 CommandType string `json:"type"`
28 Line int `json:"line"`
29
30 // Set when type == "module" || "register"
31 Name string `json:"name,omitempty"`
32
33 // Set when type == "module" || "assert_uninstantiable" || "assert_malformed"
34 Filename string `json:"filename,omitempty"`
35
36 // Set when type == "register"
37 As string `json:"as,omitempty"`
38
39 // Set when type == "assert_return" || "action"
40 Action commandAction `json:"action,omitempty"`
41 Exps []commandActionVal `json:"expected"`
42
43 // Set when type == "assert_malformed"
44 ModuleType string `json:"module_type"`
45
46 // Set when type == "assert_trap"
47 Text string `json:"text"`
48 }
49
50 commandAction struct {
51 ActionType string `json:"type"`
52 Args []commandActionVal `json:"args"`
53
54 // Set when ActionType == "invoke"
55 Field string `json:"field,omitempty"`
56 Module string `json:"module,omitempty"`
57 }
58
59 commandActionVal struct {
60 ValType string `json:"type"`
61 // LaneType is not empty if ValueType == "v128"
62 LaneType laneType `json:"lane_type"`
63 Value interface{} `json:"value"`
64 }
65 )
66
67 // laneType is a type of each lane of vector value.
68 //
69 // See https://github.com/WebAssembly/wabt/blob/main/docs/wast2json.md#const
70 type laneType = string
71
72 const (
73 laneTypeI8 laneType = "i8"
74 laneTypeI16 laneType = "i16"
75 laneTypeI32 laneType = "i32"
76 laneTypeI64 laneType = "i64"
77 laneTypeF32 laneType = "f32"
78 laneTypeF64 laneType = "f64"
79 )
80
81 func (c commandActionVal) String() string {
82 var v string
83 valTypeStr := c.ValType
84 switch c.ValType {
85 case "i32":
86 v = c.Value.(string)
87 case "f32":
88 str := c.Value.(string)
89 if strings.Contains(str, "nan") {
90 v = str
91 } else {
92 ret, _ := strconv.ParseUint(str, 10, 32)
93 v = fmt.Sprintf("%f", math.Float32frombits(uint32(ret)))
94 }
95 case "i64":
96 v = c.Value.(string)
97 case "f64":
98 str := c.Value.(string)
99 if strings.Contains(str, "nan") {
100 v = str
101 } else {
102 ret, _ := strconv.ParseUint(str, 10, 64)
103 v = fmt.Sprintf("%f", math.Float64frombits(ret))
104 }
105 case "externref":
106 if c.Value == "null" {
107 v = "null"
108 } else {
109 original, _ := strconv.ParseUint(c.Value.(string), 10, 64)
110 // In wazero, externref is opaque pointer, so "0" is considered as null.
111 // So in order to treat "externref 0" in spectest non nullref, we increment the value.
112 v = fmt.Sprintf("%d", original+1)
113 }
114 case "funcref":
115 // All the in and out funcref params are null in spectest (cannot represent non-null as it depends on runtime impl).
116 v = "null"
117 case "exnref":
118 v = "null"
119 case "v128":
120 simdValues, ok := c.Value.([]interface{})
121 if !ok {
122 panic("BUG")
123 }
124 var strs []string
125 for _, v := range simdValues {
126 strs = append(strs, v.(string))
127 }
128 v = strings.Join(strs, ",")
129 valTypeStr = fmt.Sprintf("v128[lane=%s]", c.LaneType)
130 }
131 return fmt.Sprintf("{type: %s, value: %v}", valTypeStr, v)
132 }
133
134 func (c command) String() string {
135 msg := fmt.Sprintf("line: %d, type: %s", c.Line, c.CommandType)
136 switch c.CommandType {
137 case "register":
138 msg += fmt.Sprintf(", name: %s, as: %s", c.Name, c.As)
139 case "module":
140 if c.Name != "" {
141 msg += fmt.Sprintf(", name: %s, filename: %s", c.Name, c.Filename)
142 } else {
143 msg += fmt.Sprintf(", filename: %s", c.Filename)
144 }
145 case "assert_return", "action":
146 msg += fmt.Sprintf(", action type: %s", c.Action.ActionType)
147 if c.Action.Module != "" {
148 msg += fmt.Sprintf(", module: %s", c.Action.Module)
149 }
150 msg += fmt.Sprintf(", field: %s", c.Action.Field)
151 msg += fmt.Sprintf(", args: %v, expected: %v", c.Action.Args, c.Exps)
152 case "assert_malformed":
153 // TODO:
154 case "assert_trap":
155 msg += fmt.Sprintf(", args: %v, error text: %s", c.Action.Args, c.Text)
156 case "assert_invalid":
157 // TODO:
158 case "assert_exhaustion":
159 // TODO:
160 case "assert_unlinkable":
161 // TODO:
162 case "assert_uninstantiable":
163 // TODO:
164 }
165 return "{" + msg + "}"
166 }
167
168 func (c command) getAssertReturnArgs() []uint64 {
169 var args []uint64
170 for _, arg := range c.Action.Args {
171 args = append(args, arg.toUint64s()...)
172 }
173 return args
174 }
175
176 func (c command) getAssertReturnArgsExps() (args []uint64, exps []uint64) {
177 for _, arg := range c.Action.Args {
178 args = append(args, arg.toUint64s()...)
179 }
180 for _, exp := range c.Exps {
181 exps = append(exps, exp.toUint64s()...)
182 }
183 return
184 }
185
186 func (c commandActionVal) toUint64s() (ret []uint64) {
187 if c.ValType == "v128" {
188 strValues, ok := c.Value.([]interface{})
189 if !ok {
190 panic("BUG")
191 }
192 var width, valNum int
193 switch c.LaneType {
194 case "i8":
195 width, valNum = 8, 16
196 case "i16":
197 width, valNum = 16, 8
198 case "i32":
199 width, valNum = 32, 4
200 case "i64":
201 width, valNum = 64, 2
202 case "f32":
203 width, valNum = 32, 4
204 case "f64":
205 width, valNum = 64, 2
206 default:
207 panic("BUG")
208 }
209 lo, hi := buildLaneUint64(strValues, width, valNum)
210 return []uint64{lo, hi}
211 } else {
212 return []uint64{c.toUint64()}
213 }
214 }
215
216 func buildLaneUint64(raw []interface{}, width, valNum int) (lo, hi uint64) {
217 for i := 0; i < valNum; i++ {
218 str := raw[i].(string)
219
220 var v uint64
221 var err error
222 if strings.Contains(str, "nan") {
223 v = getNaNBits(str, width == 32)
224 } else {
225 v, err = strconv.ParseUint(str, 10, width)
226 if err != nil {
227 panic(err)
228 }
229 }
230
231 if half := valNum / 2; i < half {
232 lo |= v << (i * width)
233 } else {
234 hi |= v << ((i - half) * width)
235 }
236 }
237 return
238 }
239
240 func getNaNBits(strValue string, is32bit bool) (ret uint64) {
241 // Note: nan:canonical, nan:arithmetic only appears on the expected values.
242 if is32bit {
243 switch strValue {
244 case "nan:canonical":
245 ret = uint64(moremath.F32CanonicalNaNBits)
246 case "nan:arithmetic":
247 ret = uint64(moremath.F32ArithmeticNaNBits)
248 default:
249 panic("BUG")
250 }
251 } else {
252 switch strValue {
253 case "nan:canonical":
254 ret = moremath.F64CanonicalNaNBits
255 case "nan:arithmetic":
256 ret = moremath.F64ArithmeticNaNBits
257 default:
258 panic("BUG")
259 }
260 }
261 return
262 }
263
264 func (c commandActionVal) toUint64() (ret uint64) {
265 if c.Value == nil || c.Value == "null" {
266 return 0
267 }
268 strValue := c.Value.(string)
269 if strings.Contains(strValue, "nan") {
270 ret = getNaNBits(strValue, c.ValType == "f32")
271 } else if c.ValType == "externref" {
272 if c.Value == "null" {
273 ret = 0
274 } else {
275 original, _ := strconv.ParseUint(strValue, 10, 64)
276 // In wazero, externref is opaque pointer, so "0" is considered as null.
277 // So in order to treat "externref 0" in spectest non nullref, we increment the value.
278 ret = original + 1
279 }
280 } else if strings.Contains(c.ValType, "32") {
281 // wasm-tools may output signed decimals (e.g. "-1"); handle both.
282 if strings.HasPrefix(strValue, "-") {
283 v, _ := strconv.ParseInt(strValue, 10, 32)
284 ret = uint64(uint32(int32(v)))
285 } else {
286 ret, _ = strconv.ParseUint(strValue, 10, 32)
287 }
288 } else {
289 if strings.HasPrefix(strValue, "-") {
290 v, _ := strconv.ParseInt(strValue, 10, 64)
291 ret = uint64(v)
292 } else {
293 ret, _ = strconv.ParseUint(strValue, 10, 64)
294 }
295 }
296 return
297 }
298
299 // expectedError returns the expected runtime error when the command type equals assert_trap
300 // which expects engines to emit the errors corresponding command.Text field.
301 func (c command) expectedError() (err error) {
302 if c.CommandType != "assert_trap" {
303 panic("unreachable")
304 }
305 switch c.Text {
306 case "expected shared memory":
307 err = wasmruntime.ErrRuntimeExpectedSharedMemory
308 case "out of bounds memory access":
309 err = wasmruntime.ErrRuntimeOutOfBoundsMemoryAccess
310 case "indirect call type mismatch", "indirect call":
311 err = wasmruntime.ErrRuntimeIndirectCallTypeMismatch
312 case "undefined element", "undefined", "out of bounds table access":
313 err = wasmruntime.ErrRuntimeInvalidTableAccess
314 case "integer overflow":
315 err = wasmruntime.ErrRuntimeIntegerOverflow
316 case "invalid conversion to integer":
317 err = wasmruntime.ErrRuntimeInvalidConversionToInteger
318 case "integer divide by zero":
319 err = wasmruntime.ErrRuntimeIntegerDivideByZero
320 case "unaligned atomic":
321 err = wasmruntime.ErrRuntimeUnalignedAtomic
322 case "unreachable":
323 err = wasmruntime.ErrRuntimeUnreachable
324 case "uncaught exception":
325 err = wasmruntime.ErrRuntimeUncaughtException
326 case "null", "null reference", "null function reference", "null function":
327 err = wasmruntime.ErrRuntimeNullReference
328 default:
329 if strings.HasPrefix(c.Text, "uninitialized") {
330 err = wasmruntime.ErrRuntimeInvalidTableAccess
331 }
332 }
333 return
334 }
335
336 // spectestWasm was generated by the following:
337 //
338 // cd testdata; wat2wasm --debug-names spectest.wat
339 //
340 // This module is required by some test cases, and must be instantiated before running cases.
341 // See https://github.com/WebAssembly/spec/blob/1c5e5d178bd75c79b7a12881c529098beaee2a05/test/core/imports.wast
342 // See https://github.com/WebAssembly/spec/blob/1c5e5d178bd75c79b7a12881c529098beaee2a05/interpreter/script/js.ml#L33-L50
343 //
344 //go:embed testdata/spectest.wasm
345 var spectestWasm []byte
346
347 // Run runs all the test inside the testDataFS file system where all the cases are described
348 // via JSON files created from wast2json.
349 func Run(t *testing.T, testDataFS embed.FS, ctx context.Context, config wazero.RuntimeConfig) {
350 files, err := testDataFS.ReadDir("testdata")
351 require.NoError(t, err)
352
353 caseNames := make([]string, 0, len(files))
354 for _, f := range files {
355 filename := f.Name()
356 if strings.HasSuffix(filename, ".json") {
357 caseNames = append(caseNames, strings.TrimSuffix(filename, ".json"))
358 }
359 }
360
361 // If the go:embed path resolution was wrong, this fails.
362 // https://github.com/tetratelabs/wazero/issues/247
363 require.True(t, len(caseNames) > 0, "len(caseNames)=%d (not greater than zero)", len(caseNames))
364
365 for _, f := range caseNames {
366 RunCase(t, testDataFS, f, ctx, config, -1, 0, math.MaxInt)
367 }
368 }
369
370 // RunCase runs the test case described by the given spectest file name (without .wast!) in the testDataFS file system.
371 // lineBegin and lineEnd are the line numbers to run. If lineBegin == 0 and lineEnd == math.MaxInt, all the lines are run.
372 //
373 // For example, if you want to run memory_grow.wast:66 to 70, you can do:
374 //
375 // RunCase(t, testDataFS, "memory_grow", ctx, config, mandatoryLine, 66, 70)
376 //
377 // where mandatoryLine is the line number which can be run regardless of the lineBegin and lineEnd. It is useful when
378 // we only want to run specific command while running "module" command to instantiate a module. If you don't need it,
379 // just pass -1.
380 func RunCase(t *testing.T, testDataFS embed.FS, f string, ctx context.Context, config wazero.RuntimeConfig, mandatoryLine, lineBegin, lineEnd int) {
381 raw, err := testDataFS.ReadFile(testdataPath(f + ".json"))
382 require.NoError(t, err)
383
384 var base testbase
385 require.NoError(t, json.Unmarshal(raw, &base))
386
387 wastName := basename(base.SourceFile)
388
389 t.Run(wastName, func(t *testing.T) {
390 r := wazero.NewRuntimeWithConfig(ctx, config)
391 defer func() {
392 require.NoError(t, r.Close(ctx))
393 }()
394
395 _, err := r.InstantiateWithConfig(ctx, spectestWasm, wazero.NewModuleConfig())
396 require.NoError(t, err)
397
398 modules := make(map[string]api.Module)
399 var lastInstantiatedModule api.Module
400 for i := 0; i < len(base.Commands); i++ {
401 c := &base.Commands[i]
402 line := c.Line
403 if mandatoryLine > -1 && c.Line == mandatoryLine {
404 } else if line < lineBegin || line > lineEnd {
405 continue
406 }
407 t.Run(fmt.Sprintf("%s/line:%d", c.CommandType, c.Line), func(t *testing.T) {
408 msg := fmt.Sprintf("%s:%d %s", wastName, c.Line, c.CommandType)
409 switch c.CommandType {
410 case "module":
411 buf, err := testDataFS.ReadFile(testdataPath(c.Filename))
412 require.NoError(t, err, msg)
413
414 var registeredName string
415 if next := i + 1; next < len(base.Commands) && base.Commands[next].CommandType == "register" {
416 registeredName = base.Commands[next].As
417 i++ // Skip the entire "register" command.
418 }
419 mod, err := r.InstantiateWithConfig(ctx, buf, wazero.NewModuleConfig().WithName(registeredName))
420 require.NoError(t, err, msg)
421 if c.Name != "" {
422 modules[c.Name] = mod
423 }
424 lastInstantiatedModule = mod
425 case "assert_return", "action":
426 m := lastInstantiatedModule
427 if c.Action.Module != "" {
428 m = modules[c.Action.Module]
429 }
430 switch c.Action.ActionType {
431 case "invoke":
432 args, exps := c.getAssertReturnArgsExps()
433 msg = fmt.Sprintf("%s invoke %s (%s)", msg, c.Action.Field, c.Action.Args)
434 if c.Action.Module != "" {
435 msg += " in module " + c.Action.Module
436 }
437 fn := m.ExportedFunction(c.Action.Field)
438 results, err := fn.Call(ctx, args...)
439 require.NoError(t, err, msg)
440 require.Equal(t, len(exps), len(results), msg)
441 laneTypes := map[int]string{}
442 skipIndices := map[int]bool{}
443 for i, expV := range c.Exps {
444 if expV.ValType == "v128" {
445 laneTypes[i] = expV.LaneType
446 }
447 // When value is nil for ref types, it means "any ref" — skip comparison.
448 if expV.Value == nil && (expV.ValType == "funcref" || expV.ValType == "externref" || expV.ValType == "exnref") {
449 skipIndices[i] = true
450 }
451 }
452 matched, valuesMsg := valuesEq(results, exps, wasm.FromApiValueType(fn.Definition().ResultTypes()), laneTypes, skipIndices)
453 require.True(t, matched, msg+"\n"+valuesMsg)
454 case "get":
455 _, exps := c.getAssertReturnArgsExps()
456 require.Equal(t, 1, len(exps))
457 msg = fmt.Sprintf("%s invoke %s (%s)", msg, c.Action.Field, c.Action.Args)
458 if c.Action.Module != "" {
459 msg += " in module " + c.Action.Module
460 }
461 global := m.ExportedGlobal(c.Action.Field)
462 require.NotNil(t, global)
463 require.Equal(t, exps[0], global.Get(), msg)
464 default:
465 t.Fatalf("unsupported action type type: %v", c)
466 }
467 case "assert_malformed":
468 if c.ModuleType != "text" {
469 // We don't support direct loading of wast yet.
470 buf, err := testDataFS.ReadFile(testdataPath(c.Filename))
471 require.NoError(t, err, msg)
472 _, err = r.InstantiateWithConfig(ctx, buf, wazero.NewModuleConfig())
473 require.Error(t, err, msg)
474 }
475 case "assert_trap":
476 m := lastInstantiatedModule
477 if c.Action.Module != "" {
478 m = modules[c.Action.Module]
479 }
480 switch c.Action.ActionType {
481 case "invoke":
482 args := c.getAssertReturnArgs()
483 msg = fmt.Sprintf("%s invoke %s (%s)", msg, c.Action.Field, c.Action.Args)
484 if c.Action.Module != "" {
485 msg += " in module " + c.Action.Module
486 }
487 _, err := m.ExportedFunction(c.Action.Field).Call(ctx, args...)
488 require.ErrorIs(t, err, c.expectedError(), msg)
489 default:
490 t.Fatalf("unsupported action type type: %v", c)
491 }
492 case "assert_invalid":
493 if c.ModuleType == "text" {
494 // We don't support direct loading of wast yet.
495 t.Skip()
496 }
497 buf, err := testDataFS.ReadFile(testdataPath(c.Filename))
498 require.NoError(t, err, msg)
499 _, err = r.InstantiateWithConfig(ctx, buf, wazero.NewModuleConfig())
500 require.Error(t, err, msg)
501 case "assert_exhaustion":
502 switch c.Action.ActionType {
503 case "invoke":
504 args := c.getAssertReturnArgs()
505 msg = fmt.Sprintf("%s invoke %s (%s)", msg, c.Action.Field, c.Action.Args)
506 if c.Action.Module != "" {
507 msg += " in module " + c.Action.Module
508 }
509 _, err := lastInstantiatedModule.ExportedFunction(c.Action.Field).Call(ctx, args...)
510 require.ErrorIs(t, err, wasmruntime.ErrRuntimeStackOverflow, msg)
511 default:
512 t.Fatalf("unsupported action type type: %v", c)
513 }
514 case "assert_unlinkable":
515 if c.ModuleType == "text" {
516 // We don't support direct loading of wast yet.
517 t.Skip()
518 }
519 buf, err := testDataFS.ReadFile(testdataPath(c.Filename))
520 require.NoError(t, err, msg)
521 _, err = r.InstantiateWithConfig(ctx, buf, wazero.NewModuleConfig())
522 require.Error(t, err, msg)
523 case "assert_exception":
524 m := lastInstantiatedModule
525 if c.Action.Module != "" {
526 m = modules[c.Action.Module]
527 }
528 switch c.Action.ActionType {
529 case "invoke":
530 args := c.getAssertReturnArgs()
531 msg = fmt.Sprintf("%s invoke %s (%s)", msg, c.Action.Field, c.Action.Args)
532 if c.Action.Module != "" {
533 msg += " in module " + c.Action.Module
534 }
535 _, err := m.ExportedFunction(c.Action.Field).Call(ctx, args...)
536 require.ErrorIs(t, err, wasmruntime.ErrRuntimeUncaughtException, msg)
537 default:
538 t.Fatalf("unsupported action type type: %v", c)
539 }
540 case "assert_uninstantiable":
541 buf, err := testDataFS.ReadFile(testdataPath(c.Filename))
542 require.NoError(t, err, msg)
543 _, err = r.InstantiateWithConfig(ctx, buf, wazero.NewModuleConfig())
544 if c.Text == "out of bounds table access" {
545 // This is not actually an instantiation error, but assert_trap in the original wast, but wast2json translates it to assert_uninstantiable.
546 // Anyway, this spectest case expects the error due to active element offset ouf of bounds
547 // "after" instantiation while retaining function instances used for elements.
548 // https://github.com/WebAssembly/spec/blob/d39195773112a22b245ffbe864bab6d1182ccb06/test/core/linking.wast#L264-L274
549 //
550 // In practice, such a module instance can be used for invoking functions without any issue. In addition, we have to
551 // retain functions after the expected "instantiation" failure, so in wazero we choose to not raise error in that case.
552 require.NoError(t, err, msg)
553 } else {
554 require.Error(t, err, msg)
555 }
556 default:
557 t.Fatalf("unsupported command type: %s", c)
558 }
559 })
560 }
561 })
562 }
563
564 // basename avoids filepath.Base to ensure a forward slash is used even in Windows.
565 // See https://pkg.go.dev/embed#hdr-Directives
566 func basename(path string) string {
567 lastSlash := strings.LastIndexByte(path, '/')
568 return path[lastSlash+1:]
569 }
570
571 // testdataPath avoids filepath.Join to ensure a forward slash is used even in Windows.
572 // See https://pkg.go.dev/embed#hdr-Directives
573 func testdataPath(filename string) string {
574 return fmt.Sprintf("testdata/%s", filename)
575 }
576
577 // valuesEq returns true if all the actual result matches exps which are all expressed as uint64.
578 // - actual,exps: comparison target values which are all represented as uint64, meaning that if valTypes = [V128,I32], then
579 // we have actual/exp = [(lower-64bit of the first V128), (higher-64bit of the first V128), I32].
580 // - valTypes holds the wasm.ValueType(s) of the original values in Wasm.
581 // - laneTypes maps the index of valueTypes to laneType if valueTypes[i] == wasm.ValueTypeV128.
582 //
583 // Also, if matched == false this returns non-empty valuesMsg which can be used to augment the test failure message.
584 func valuesEq(actual, exps []uint64, valTypes []wasm.ValueType, laneTypes map[int]laneType, skipIndices map[int]bool) (matched bool, valuesMsg string) {
585 matched = true
586
587 var msgExpValuesStrs, msgActualValuesStrs []string
588 var uint64RepPos int // the index to actual and exps slice.
589 for i, tp := range valTypes {
590 if skipIndices[i] {
591 // Skip comparison for this result (e.g., "any funcref").
592 if tp == wasm.ValueTypeV128 {
593 uint64RepPos += 2
594 } else {
595 uint64RepPos++
596 }
597 msgExpValuesStrs = append(msgExpValuesStrs, "*")
598 msgActualValuesStrs = append(msgActualValuesStrs, "*")
599 continue
600 }
601 switch tp {
602 case wasm.ValueTypeI32:
603 msgExpValuesStrs = append(msgExpValuesStrs, fmt.Sprintf("%d", uint32(exps[uint64RepPos])))
604 msgActualValuesStrs = append(msgActualValuesStrs, fmt.Sprintf("%d", uint32(actual[uint64RepPos])))
605 matched = matched && uint32(exps[uint64RepPos]) == uint32(actual[uint64RepPos])
606 uint64RepPos++
607 case wasm.ValueTypeI64, wasm.ValueTypeExternref, wasm.ValueTypeFuncref:
608 msgExpValuesStrs = append(msgExpValuesStrs, fmt.Sprintf("%d", exps[uint64RepPos]))
609 msgActualValuesStrs = append(msgActualValuesStrs, fmt.Sprintf("%d", actual[uint64RepPos]))
610 matched = matched && exps[uint64RepPos] == actual[uint64RepPos]
611 uint64RepPos++
612 case wasm.ValueTypeF32:
613 a := math.Float32frombits(uint32(actual[uint64RepPos]))
614 e := math.Float32frombits(uint32(exps[uint64RepPos]))
615 msgExpValuesStrs = append(msgExpValuesStrs, fmt.Sprintf("%f", e))
616 msgActualValuesStrs = append(msgActualValuesStrs, fmt.Sprintf("%f", a))
617 matched = matched && f32Equal(e, a)
618 uint64RepPos++
619 case wasm.ValueTypeF64:
620 e := math.Float64frombits(exps[uint64RepPos])
621 a := math.Float64frombits(actual[uint64RepPos])
622 msgExpValuesStrs = append(msgExpValuesStrs, fmt.Sprintf("%f", e))
623 msgActualValuesStrs = append(msgActualValuesStrs, fmt.Sprintf("%f", a))
624 matched = matched && f64Equal(e, a)
625 uint64RepPos++
626 case wasm.ValueTypeV128:
627 actualLo, actualHi := actual[uint64RepPos], actual[uint64RepPos+1]
628 expLo, expHi := exps[uint64RepPos], exps[uint64RepPos+1]
629 switch laneTypes[i] {
630 case laneTypeI8:
631 msgExpValuesStrs = append(msgExpValuesStrs,
632 fmt.Sprintf("i8x16(%#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x)",
633 byte(expLo), byte(expLo>>8), byte(expLo>>16), byte(expLo>>24),
634 byte(expLo>>32), byte(expLo>>40), byte(expLo>>48), byte(expLo>>56),
635 byte(expHi), byte(expHi>>8), byte(expHi>>16), byte(expHi>>24),
636 byte(expHi>>32), byte(expHi>>40), byte(expHi>>48), byte(expHi>>56),
637 ),
638 )
639 msgActualValuesStrs = append(msgActualValuesStrs,
640 fmt.Sprintf("i8x16(%#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x)",
641 byte(actualLo), byte(actualLo>>8), byte(actualLo>>16), byte(actualLo>>24),
642 byte(actualLo>>32), byte(actualLo>>40), byte(actualLo>>48), byte(actualLo>>56),
643 byte(actualHi), byte(actualHi>>8), byte(actualHi>>16), byte(actualHi>>24),
644 byte(actualHi>>32), byte(actualHi>>40), byte(actualHi>>48), byte(actualHi>>56),
645 ),
646 )
647 matched = matched && (expLo == actualLo) && (expHi == actualHi)
648 case laneTypeI16:
649 msgExpValuesStrs = append(msgExpValuesStrs,
650 fmt.Sprintf("i16x8(%#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x)",
651 uint16(expLo), uint16(expLo>>16), uint16(expLo>>32), uint16(expLo>>48),
652 uint16(expHi), uint16(expHi>>16), uint16(expHi>>32), uint16(expHi>>48),
653 ),
654 )
655 msgActualValuesStrs = append(msgActualValuesStrs,
656 fmt.Sprintf("i16x8(%#x, %#x, %#x, %#x, %#x, %#x, %#x, %#x)",
657 uint16(actualLo), uint16(actualLo>>16), uint16(actualLo>>32), uint16(actualLo>>48),
658 uint16(actualHi), uint16(actualHi>>16), uint16(actualHi>>32), uint16(actualHi>>48),
659 ),
660 )
661 matched = matched && (expLo == actualLo) && (expHi == actualHi)
662 case laneTypeI32:
663 msgExpValuesStrs = append(msgExpValuesStrs,
664 fmt.Sprintf("i32x4(%#x, %#x, %#x, %#x)", uint32(expLo), uint32(expLo>>32), uint32(expHi), uint32(expHi>>32)),
665 )
666 msgActualValuesStrs = append(msgActualValuesStrs,
667 fmt.Sprintf("i32x4(%#x, %#x, %#x, %#x)", uint32(actualLo), uint32(actualLo>>32), uint32(actualHi), uint32(actualHi>>32)),
668 )
669 matched = matched && (expLo == actualLo) && (expHi == actualHi)
670 case laneTypeI64:
671 msgExpValuesStrs = append(msgExpValuesStrs,
672 fmt.Sprintf("i64x2(%#x, %#x)", expLo, expHi),
673 )
674 msgActualValuesStrs = append(msgActualValuesStrs,
675 fmt.Sprintf("i64x2(%#x, %#x)", actualLo, actualHi),
676 )
677 matched = matched && (expLo == actualLo) && (expHi == actualHi)
678 case laneTypeF32:
679 msgExpValuesStrs = append(msgExpValuesStrs,
680 fmt.Sprintf("f32x4(%f, %f, %f, %f)",
681 math.Float32frombits(uint32(expLo)), math.Float32frombits(uint32(expLo>>32)),
682 math.Float32frombits(uint32(expHi)), math.Float32frombits(uint32(expHi>>32)),
683 ),
684 )
685 msgActualValuesStrs = append(msgActualValuesStrs,
686 fmt.Sprintf("f32x4(%f, %f, %f, %f)",
687 math.Float32frombits(uint32(actualLo)), math.Float32frombits(uint32(actualLo>>32)),
688 math.Float32frombits(uint32(actualHi)), math.Float32frombits(uint32(actualHi>>32)),
689 ),
690 )
691 matched = matched &&
692 f32Equal(math.Float32frombits(uint32(expLo)), math.Float32frombits(uint32(actualLo))) &&
693 f32Equal(math.Float32frombits(uint32(expLo>>32)), math.Float32frombits(uint32(actualLo>>32))) &&
694 f32Equal(math.Float32frombits(uint32(expHi)), math.Float32frombits(uint32(actualHi))) &&
695 f32Equal(math.Float32frombits(uint32(expHi>>32)), math.Float32frombits(uint32(actualHi>>32)))
696 case laneTypeF64:
697 msgExpValuesStrs = append(msgExpValuesStrs,
698 fmt.Sprintf("f64x2(%f, %f)", math.Float64frombits(expLo), math.Float64frombits(expHi)),
699 )
700 msgActualValuesStrs = append(msgActualValuesStrs,
701 fmt.Sprintf("f64x2(%f, %f)", math.Float64frombits(actualLo), math.Float64frombits(actualHi)),
702 )
703 matched = matched &&
704 f64Equal(math.Float64frombits(expLo), math.Float64frombits(actualLo)) &&
705 f64Equal(math.Float64frombits(expHi), math.Float64frombits(actualHi))
706 default:
707 panic("BUG")
708 }
709 uint64RepPos += 2
710 default:
711 panic("BUG")
712 }
713 }
714
715 if !matched {
716 valuesMsg = fmt.Sprintf("\thave [%s]\n\twant [%s]",
717 strings.Join(msgActualValuesStrs, ", "),
718 strings.Join(msgExpValuesStrs, ", "))
719 }
720 return
721 }
722
723 func f32Equal(expected, actual float32) (matched bool) {
724 if expBit := math.Float32bits(expected); expBit == moremath.F32CanonicalNaNBits {
725 matched = math.Float32bits(actual)&moremath.F32CanonicalNaNBitsMask == moremath.F32CanonicalNaNBits
726 } else if expBit == moremath.F32ArithmeticNaNBits {
727 b := math.Float32bits(actual)
728 matched = b&moremath.F32ExponentMask == moremath.F32ExponentMask && // Indicates that exponent part equals of NaN.
729 b&moremath.F32ArithmeticNaNPayloadMSB == moremath.F32ArithmeticNaNPayloadMSB
730 } else if math.IsNaN(float64(expected)) { // NaN cannot be compared with themselves, so we have to use IsNaN
731 matched = math.IsNaN(float64(actual))
732 } else {
733 // Compare the bit patterns directly, rather than == on float32 since in Go, -0 and 0 equals,
734 // but in the Wasm spec, they are treated as different.
735 matched = math.Float32bits(expected) == math.Float32bits(actual)
736 }
737 return
738 }
739
740 func f64Equal(expected, actual float64) (matched bool) {
741 if expBit := math.Float64bits(expected); expBit == moremath.F64CanonicalNaNBits {
742 matched = math.Float64bits(actual)&moremath.F64CanonicalNaNBitsMask == moremath.F64CanonicalNaNBits
743 } else if expBit == moremath.F64ArithmeticNaNBits {
744 b := math.Float64bits(actual)
745 matched = b&moremath.F64ExponentMask == moremath.F64ExponentMask && // Indicates that exponent part equals of NaN.
746 b&moremath.F64ArithmeticNaNPayloadMSB == moremath.F64ArithmeticNaNPayloadMSB
747 } else if math.IsNaN(expected) { // NaN cannot be compared with themselves, so we have to use IsNaN
748 matched = math.IsNaN(actual)
749 } else {
750 // Compare the bit patterns directly, rather than == on float64 since in Go, -0 and 0 equals,
751 // but in the Wasm spec, they are treated as different.
752 matched = math.Float64bits(expected) == math.Float64bits(actual)
753 }
754 return
755 }