From 25714a3c9e6e91d1ea8b35bd7321b4c929d398c7 Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sun, 2 Aug 2026 17:43:52 +0200 Subject: [PATCH 01/13] Verify the trap message in assert_trap spec assertions The spec runner only checked that error assertions produced some error, so a module trapping for entirely the wrong reason counted as a pass. Carry wast2json's "text" field through and compare it against the trap message. The expected reason is matched as a prefix ending at a word boundary, which is the matching the reference interpreter performs: bulk.wast expects the same call_indirect trap as both "uninitialized element 2" and "uninitialized element", so no single message can match both exactly. This surfaced two spec violations: - call_indirect with an out-of-range table index reported "out of bounds table access". The spec distinguishes this from the table accessor instructions, which keep that wording; call_indirect traps with "undefined element". - Dividing the most negative integer by -1 reported "integer divide overflow" rather than the "integer overflow" the truncation traps already used. The two conditions now share one error. --- epsilon/numeric.go | 5 ++--- epsilon/vm.go | 6 +++++- internal/spec_tests/spec_test_runner.go | 27 +++++++++++++++++-------- internal/wabt/wast2json.go | 3 +++ 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/epsilon/numeric.go b/epsilon/numeric.go index 6f7d842..986156f 100644 --- a/epsilon/numeric.go +++ b/epsilon/numeric.go @@ -21,7 +21,6 @@ import ( var ( errIntegerDivideByZero = errors.New("integer divide by zero") - errIntegerDivideOverflow = errors.New("integer divide overflow") errIntegerOverflow = errors.New("integer overflow") errInvalidConversionToInteger = errors.New("invalid conversion to integer") ) @@ -48,7 +47,7 @@ func divS32(a, b int32) (int32, error) { return 0, errIntegerDivideByZero } if a == math.MinInt32 && b == -1 { - return 0, errIntegerDivideOverflow + return 0, errIntegerOverflow } return a / b, nil } @@ -58,7 +57,7 @@ func divS64(a, b int64) (int64, error) { return 0, errIntegerDivideByZero } if a == math.MinInt64 && b == -1 { - return 0, errIntegerDivideOverflow + return 0, errIntegerOverflow } return a / b, nil } diff --git a/epsilon/vm.go b/epsilon/vm.go index 8bb55ba..4c1f192 100644 --- a/epsilon/vm.go +++ b/epsilon/vm.go @@ -27,6 +27,7 @@ var ( errFuelExhausted = errors.New("fuel exhausted") errUnknownFunctionType = errors.New("unknown function type") errIndirectCallTypeMismatch = errors.New("indirect call type mismatch") + errUndefinedElement = errors.New("undefined element") errHostResultCountMismatch = errors.New("host func result count mismatch") ) @@ -1469,9 +1470,12 @@ func (vm *vm) handleCallIndirect(frame *callFrame) error { elementIndex := vm.stack.popInt32() + // An out-of-range table index traps as "undefined element" here, not as + // the "out of bounds table access" the table accessor instructions + // report for the same condition. tableElement, err := table.Get(elementIndex) if err != nil { - return err + return errUndefinedElement } if tableElement == NullReference { return fmt.Errorf("uninitialized element %d", elementIndex) diff --git a/internal/spec_tests/spec_test_runner.go b/internal/spec_tests/spec_test_runner.go index 0613cfe..d54d8e7 100644 --- a/internal/spec_tests/spec_test_runner.go +++ b/internal/spec_tests/spec_test_runner.go @@ -223,22 +223,33 @@ func (r *specTestRunner) handleAssertReturn(cmd wabt.Command) { } func (r *specTestRunner) handleAssertTrap(cmd wabt.Command) { + var err error if cmd.Filename != "" { // This is asserting that instantiating a module will trap. wasm := bytes.NewReader(r.wasmDict[cmd.Filename]) - _, err := r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) - if err == nil { - r.fatalf(cmd.Line, "expected trap during instantiation, but got no error") - } + _, err = r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) } else { // This is asserting that a function call will trap. - _, err := r.handleAction(cmd.Action) - if err == nil { - r.fatalf(cmd.Line, "expected trap, but got no error") - } + _, err = r.handleAction(cmd.Action) + } + + if err == nil { + r.fatalf(cmd.Line, "expected trap %q, but got no error", cmd.Text) + } + if !trapMatches(cmd.Text, err.Error()) { + r.fatalf(cmd.Line, "expected trap %q, but got: %v", cmd.Text, err) } } +// trapMatches reports whether a trap message satisfies the failure reason an +// assertion expects. Epsilon appends context to some trap messages (the +// offending element index, for instance), so the expected reason may stop +// short of the full message, but only at a word boundary. +func trapMatches(expected, actual string) bool { + rest, ok := strings.CutPrefix(actual, expected) + return ok && (rest == "" || rest[0] == ' ') +} + func (r *specTestRunner) handleAssertInvalid(cmd wabt.Command) { wasm := bytes.NewReader(r.wasmDict[cmd.Filename]) _, err := r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) diff --git a/internal/wabt/wast2json.go b/internal/wabt/wast2json.go index af35f83..9f833b0 100644 --- a/internal/wabt/wast2json.go +++ b/internal/wabt/wast2json.go @@ -36,6 +36,9 @@ type Command struct { Action *Action `json:"action,omitempty"` Expected []Value `json:"expected,omitempty"` As string `json:"as,omitempty"` + // Text is the failure reason an assertion expects, present on the + // assert_* commands. + Text string `json:"text,omitempty"` } type Action struct { From d63d9cc81ebb16edcf3e4eb8419fa79a4eaaed19 Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sun, 2 Aug 2026 17:47:45 +0200 Subject: [PATCH 02/13] Verify the message in the remaining instantiation-time spec assertions assert_uninstantiable and assert_unlinkable only checked that some error came back, and assert_exhaustion compared against a hardcoded string rather than the reason the assertion states. Route all three through the same check assert_trap uses. assert_uninstantiable (34 assertions) and assert_exhaustion (15) already reported the right reason. All 83 assert_unlinkable assertions were passing on the wrong message: epsilon named the offending import first and used its own vocabulary, so nothing distinguished an import that was missing from one that was present with the wrong type. The two conditions already had separate code paths, so this is wording only -- they now lead with the "unknown import" and "incompatible import type" reasons the spec states, keeping the import name and the specific mismatch as detail. assert_invalid and assert_malformed remain unchecked. --- epsilon/imports.go | 43 +++++++++++++------------ internal/spec_tests/spec_test_runner.go | 40 +++++++++-------------- 2 files changed, 37 insertions(+), 46 deletions(-) diff --git a/epsilon/imports.go b/epsilon/imports.go index 2fe9366..3db7d1e 100644 --- a/epsilon/imports.go +++ b/epsilon/imports.go @@ -86,7 +86,18 @@ func findImport( return obj, nil } } - return nil, fmt.Errorf("%s.%s not found in imports", module, name) + return nil, fmt.Errorf("unknown import %s.%s", module, name) +} + +// incompatibleImport reports an import that was found but whose provided value +// does not match the type the importing module declares. +func incompatibleImport(imp moduleImport, detail string) error { + return fmt.Errorf( + "incompatible import type for %s.%s: %s", + imp.moduleName, + imp.name, + detail, + ) } func resolveFunctionImport( @@ -103,9 +114,7 @@ func resolveFunctionImport( } if !f.GetType().Equal(functionType) { - return nil, fmt.Errorf( - "type mismatch for %s.%s", imp.moduleName, imp.name, - ) + return nil, incompatibleImport(imp, "signature mismatch") } return f, nil @@ -119,7 +128,7 @@ func resolveFunctionImport( }, nil } - return nil, fmt.Errorf("%s.%s not a function", imp.moduleName, imp.name) + return nil, incompatibleImport(imp, "not a function") } func resolveGlobalImport( @@ -130,7 +139,7 @@ func resolveGlobalImport( ) (*Global, error) { global, ok := obj.(*Global) if !ok { - return nil, fmt.Errorf("%s.%s not a global", imp.moduleName, imp.name) + return nil, incompatibleImport(imp, "not a global") } if global.owner != instance.vm { @@ -140,14 +149,10 @@ func resolveGlobalImport( } if global.Mutable != globalType.IsMutable { - return nil, fmt.Errorf( - "mutability mismatch for %s.%s", imp.moduleName, imp.name, - ) + return nil, incompatibleImport(imp, "mutability mismatch") } if global.Type != globalType.ValueType { - return nil, fmt.Errorf( - "value type mismatch for %s.%s", imp.moduleName, imp.name, - ) + return nil, incompatibleImport(imp, "value type mismatch") } return global, nil } @@ -160,7 +165,7 @@ func resolveMemoryImport( ) (*Memory, error) { memory, ok := obj.(*Memory) if !ok { - return nil, fmt.Errorf("%s.%s not a memory", imp.moduleName, imp.name) + return nil, incompatibleImport(imp, "not a memory") } if memory.owner != instance.vm { @@ -171,7 +176,7 @@ func resolveMemoryImport( provided := Limits{Min: uint32(memory.Size()), Max: memory.Limits.Max} if !limitsMatch(provided, memoryType.Limits) { - return nil, fmt.Errorf("limit mismatch for %s.%s", imp.moduleName, imp.name) + return nil, incompatibleImport(imp, "limit mismatch") } return memory, nil } @@ -184,7 +189,7 @@ func resolveTableImport( ) (*Table, error) { table, ok := obj.(*Table) if !ok { - return nil, fmt.Errorf("%s.%s not a table", imp.moduleName, imp.name) + return nil, incompatibleImport(imp, "not a table") } if table.owner != instance.vm { @@ -194,16 +199,12 @@ func resolveTableImport( } if table.Type.ReferenceType != tableType.ReferenceType { - return nil, fmt.Errorf( - "reference type mismatch for %s.%s", imp.moduleName, imp.name, - ) + return nil, incompatibleImport(imp, "reference type mismatch") } provided := Limits{Min: uint32(table.Size()), Max: table.Type.Limits.Max} if !limitsMatch(provided, tableType.Limits) { - return nil, fmt.Errorf( - "limit mismatch for %s.%s", imp.moduleName, imp.name, - ) + return nil, incompatibleImport(imp, "limit mismatch") } return table, nil } diff --git a/internal/spec_tests/spec_test_runner.go b/internal/spec_tests/spec_test_runner.go index d54d8e7..f4748e3 100644 --- a/internal/spec_tests/spec_test_runner.go +++ b/internal/spec_tests/spec_test_runner.go @@ -162,13 +162,7 @@ func (r *specTestRunner) run(commands []wabt.Command) { func (r *specTestRunner) handleAssertExhaustion(cmd wabt.Command) { _, err := r.handleAction(cmd.Action) - if err == nil { - r.fatalf(cmd.Line, "expected call stack exhaustion, but got no error") - } - - if err.Error() != "call stack exhausted" { - r.fatalf(cmd.Line, "expected call stack exhaustion, but got: %v", err) - } + r.assertFailedWithText(cmd, err) } func (r *specTestRunner) handleRegister(cmd wabt.Command) { @@ -232,24 +226,24 @@ func (r *specTestRunner) handleAssertTrap(cmd wabt.Command) { // This is asserting that a function call will trap. _, err = r.handleAction(cmd.Action) } + r.assertFailedWithText(cmd, err) +} +// assertFailedWithText reports a test failure unless err states the reason the +// assertion expects. Epsilon appends context to some messages (the offending +// element index, for instance), so the expected reason may stop short of the +// full message, but only at a word boundary. +func (r *specTestRunner) assertFailedWithText(cmd wabt.Command, err error) { + r.t.Helper() if err == nil { - r.fatalf(cmd.Line, "expected trap %q, but got no error", cmd.Text) + r.fatalf(cmd.Line, "expected %q, but got no error", cmd.Text) } - if !trapMatches(cmd.Text, err.Error()) { - r.fatalf(cmd.Line, "expected trap %q, but got: %v", cmd.Text, err) + rest, ok := strings.CutPrefix(err.Error(), cmd.Text) + if !ok || (rest != "" && rest[0] != ' ') { + r.fatalf(cmd.Line, "expected %q, but got: %v", cmd.Text, err) } } -// trapMatches reports whether a trap message satisfies the failure reason an -// assertion expects. Epsilon appends context to some trap messages (the -// offending element index, for instance), so the expected reason may stop -// short of the full message, but only at a word boundary. -func trapMatches(expected, actual string) bool { - rest, ok := strings.CutPrefix(actual, expected) - return ok && (rest == "" || rest[0] == ' ') -} - func (r *specTestRunner) handleAssertInvalid(cmd wabt.Command) { wasm := bytes.NewReader(r.wasmDict[cmd.Filename]) _, err := r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) @@ -275,17 +269,13 @@ func (r *specTestRunner) handleAssertMalformed(cmd wabt.Command) { func (r *specTestRunner) handleAssertUninstantiable(cmd wabt.Command) { wasm := bytes.NewReader(r.wasmDict[cmd.Filename]) _, err := r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) - if err == nil { - r.fatalf(cmd.Line, "expected uninstantiable module, it wasn't") - } + r.assertFailedWithText(cmd, err) } func (r *specTestRunner) handleAssertUnlinkable(cmd wabt.Command) { wasm := bytes.NewReader(r.wasmDict[cmd.Filename]) _, err := r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) - if err == nil { - r.fatalf(cmd.Line, "expected unlinkable module, it wasn't") - } + r.assertFailedWithText(cmd, err) } func (r *specTestRunner) handleAction(action *wabt.Action) ([]any, error) { From 7516f6c769cb39012ef73fa63fec124c3095a37d Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sun, 2 Aug 2026 18:03:34 +0200 Subject: [PATCH 03/13] Verify the message in assert_invalid spec assertions The runner accepted any error from a module an assertion expects the validator to reject, so a module rejected for an unrelated reason counted as a pass. Check the stated reason, as assert_trap already does. No module was wrongly accepted: all 2146 assertions were rejected already, 934 of them with the message the spec states. The rest reported the same failures in epsilon's own vocabulary, which the validator now states the spec way, keeping its detail as a suffix. The out-of-range index errors collapse into one unknownIndex helper, since the spec names the offending index in several of the messages. Three failures were being reported as the wrong condition rather than just the wrong wording: - memory.init and table.init checked their data or element segment before the memory or table the instruction addresses, so a module declaring neither blamed the segment. - A constant expression naming a global that is not an immutable import reported that a constant expression was required, whether the global was mutable or did not exist at all. - One "invalid limits" covered exceeding the spec's page ceiling, exceeding the host's configured ceiling, and a minimum above the maximum. The spec ceiling is now checked separately from the host's, so a host that configures a lower one is not reported as a spec violation. One assertion cannot be satisfied from the binary: select.wast expects "invalid result arity" for (select (result) ...), which wat2wasm encodes as the untyped select opcode, making the module byte-identical to the one the preceding assertion expects to fail with "type mismatch". The runner records that pair as indistinguishable rather than weakening the check. assert_malformed remains unchecked. --- epsilon/validation.go | 142 ++++++++++++++---------- internal/spec_tests/spec_test_runner.go | 39 +++++-- 2 files changed, 114 insertions(+), 67 deletions(-) diff --git a/epsilon/validation.go b/epsilon/validation.go index 9b20759..9a28e84 100644 --- a/epsilon/validation.go +++ b/epsilon/validation.go @@ -20,38 +20,42 @@ import ( ) var ( - errAlignmentTooLarge = errors.New("alignment too large") - errBrLabelArityMismatch = errors.New("br label arity mismatch") - errBrLabelIndexOutOfBounds = errors.New("br label index out of bounds") + errAlignmentTooLarge = errors.New("alignment must not be larger than natural") + errBrLabelArityMismatch = errors.New("type mismatch: br label arity mismatch") errControlStackEmpty = errors.New("control stack empty") - errDataCountNotSet = errors.New("data count not set") - errDataIndexOutOfBounds = errors.New("data index out of bounds") - errDuplicateExport = errors.New("duplicate export") - errElementIndexOutOfBounds = errors.New("element index out of bounds") + errDuplicateExport = errors.New("duplicate export name") errElseMustMatchIf = errors.New("else must match if") - errFunctionIndexOutOfBounds = errors.New("function index out of bounds") - errGlobalIndexOutOfBounds = errors.New("global index out of bounds") errGlobalIsImmutable = errors.New("global is immutable") - errInvalidCallIndirectType = errors.New("invalid call_indirect type") - errInvalidConstantExpression = errors.New("invalid constant expression") + errInvalidCallIndirectType = errors.New("unknown type") + errInvalidConstantExpression = errors.New("constant expression required") errInvalidLimits = errors.New("invalid limits") + errLimitsMinGreaterThanMax = errors.New("size minimum must not be greater than maximum") + errMemorySizeTooLarge = errors.New("memory size must be at most 65536 pages (4GiB)") errInvalidRefNullType = errors.New("invalid ref.null type") - errInvalidStartFunction = errors.New("invalid start function") - errInvalidTableType = errors.New("invalid table type") + errInvalidResultArity = errors.New("invalid result arity") + errInvalidStartFunction = errors.New("start function must have no parameters and no results") + errInvalidTableType = errors.New("type mismatch: table is not funcref") errInvalidBlockType = errors.New("invalid block type") - errLocalIndexOutOfBounds = errors.New("local index out of bounds") - errMemoryIndexOutOfBounds = errors.New("memory index out of bounds") errMultipleMemoriesNotEnabled = errors.New("multiple memories not enabled") errReturnTypeNotSet = errors.New("return type not set") - errSimdLaneIndexOutOfBounds = errors.New("simd lane index out of bounds") - errStackHeightMismatch = errors.New("stack height mismatch") - errTableIndexOutOfBounds = errors.New("table index out of bounds") + errSimdLaneIndexOutOfBounds = errors.New("invalid lane index") + errStackHeightMismatch = errors.New("type mismatch: stack height mismatch") errTypeMismatch = errors.New("type mismatch") errUnclosedControlFrame = errors.New("unclosed control frame") errUndeclaredFunctionReference = errors.New("undeclared function reference") - errValueStackUnderflow = errors.New("value stack underflow") + errValueStackUnderflow = errors.New("type mismatch: value stack underflow") ) +// unknownIndex reports an index immediate that is out of range for the module +// index space it addresses. The spec states these failures as "unknown ", +// and several assertions name the offending index too. +func unknownIndex(space string, index uint64) error { + return fmt.Errorf("unknown %s %d", space, index) +} + +// specMaxMemoryPages is the number of 64KiB pages a 32-bit memory may declare. +const specMaxMemoryPages = 65536 + type bottomType struct{} func (bottomType) isValueType() {} @@ -122,7 +126,7 @@ func (v *validator) validateModule(module *moduleDefinition) error { switch t := imp.importType.(type) { case functionTypeIndex: if uint32(t) >= uint32(len(v.typeDefs)) { - return errTypeMismatch + return unknownIndex("type", uint64(t)) } v.funcTypes = append(v.funcTypes, module.types[t]) @@ -135,7 +139,10 @@ func (v *validator) validateModule(module *moduleDefinition) error { } v.tableTypes = append(v.tableTypes, t) case MemoryType: - if err := validateLimits(t.Limits, v.config.MaxMemoryPages); err != nil { + if err := validateMemoryLimits( + t.Limits, + v.config.MaxMemoryPages, + ); err != nil { return err } v.memTypes = append(v.memTypes, t) @@ -147,7 +154,7 @@ func (v *validator) validateModule(module *moduleDefinition) error { for _, function := range module.funcs { if function.typeIndex >= uint32(len(module.types)) { - return errFunctionIndexOutOfBounds + return unknownIndex("type", uint64(function.typeIndex)) } v.funcTypes = append(v.funcTypes, module.types[function.typeIndex]) } @@ -161,7 +168,7 @@ func (v *validator) validateModule(module *moduleDefinition) error { } for _, memoryType := range module.memories { - err := validateLimits(memoryType.Limits, v.config.MaxMemoryPages) + err := validateMemoryLimits(memoryType.Limits, v.config.MaxMemoryPages) if err != nil { return err } @@ -352,8 +359,8 @@ func (v *validator) validateConstExpression( for v.pc < uint(len(v.code)) { op := opcode(v.next()) - if !v.isConstantOpcode(op) { - return errInvalidConstantExpression + if err := v.validateConstantOpcode(op); err != nil { + return err } // The order of the statements is important here. The validation for RefFunc @@ -375,16 +382,28 @@ func (v *validator) validateConstExpression( return nil } -func (v *validator) isConstantOpcode(op opcode) bool { +// validateConstantOpcode reports whether op may appear in a constant +// expression. Only an immutable imported global is in scope for global.get +// there, so any other global index names one that does not exist yet. +func (v *validator) validateConstantOpcode(op opcode) error { if op == globalGet { globalIndex := v.code[v.pc] if globalIndex >= uint64(len(v.importedTypes)) { - return false + return unknownIndex("global", globalIndex) } + if v.importedTypes[globalIndex].IsMutable { + return errInvalidConstantExpression + } + return nil + } - return !v.importedTypes[globalIndex].IsMutable + if isConstantOpcode(op) { + return nil } + return errInvalidConstantExpression +} +func isConstantOpcode(op opcode) bool { return op == i32Const || op == i64Const || op == f32Const || @@ -742,7 +761,7 @@ func (v *validator) validateEnd() error { func (v *validator) validateBr() error { labelIndex := uint32(v.next()) if labelIndex >= uint32(len(v.controlStack)) { - return errBrLabelIndexOutOfBounds + return unknownIndex("label", uint64(labelIndex)) } frameIndex := len(v.controlStack) - 1 - int(labelIndex) @@ -757,7 +776,7 @@ func (v *validator) validateBr() error { func (v *validator) validateBrIf() error { labelIndex := uint32(v.next()) if labelIndex >= uint32(len(v.controlStack)) { - return errBrLabelIndexOutOfBounds + return unknownIndex("label", uint64(labelIndex)) } if _, err := v.popExpectedValue(I32); err != nil { @@ -785,7 +804,7 @@ func (v *validator) validateBrTable() error { } if labelIndex >= uint32(len(v.controlStack)) { - return errBrLabelIndexOutOfBounds + return unknownIndex("label", uint64(labelIndex)) } frameIndex := len(v.controlStack) - 1 - int(labelIndex) @@ -794,7 +813,7 @@ func (v *validator) validateBrTable() error { for _, index := range table { if index >= uint64(len(v.controlStack)) { - return errBrLabelIndexOutOfBounds + return unknownIndex("label", index) } frameIndex := len(v.controlStack) - 1 - int(index) @@ -906,7 +925,7 @@ func (v *validator) validateSelect(t ValueType) error { func (v *validator) validateSelectT() error { size := v.next() if size != 1 { - return errTypeMismatch + return errInvalidResultArity } t := toValueType(v.next()) if t == bottom { @@ -945,7 +964,7 @@ func (v *validator) validateLocalSet() error { func (v *validator) validateGlobalGet() error { globalIndex := v.next() if globalIndex >= uint64(len(v.globalTypes)) { - return errGlobalIndexOutOfBounds + return unknownIndex("global", globalIndex) } v.pushValue(v.globalTypes[globalIndex].ValueType) return nil @@ -954,7 +973,7 @@ func (v *validator) validateGlobalGet() error { func (v *validator) validateGlobalSet() error { globalIndex := v.next() if globalIndex >= uint64(len(v.globalTypes)) { - return errGlobalIndexOutOfBounds + return unknownIndex("global", globalIndex) } globalType := v.globalTypes[globalIndex] @@ -1052,16 +1071,12 @@ func (v *validator) validateMemoryFill() error { func (v *validator) validateMemoryInit() error { dataIndex := uint32(v.next()) memoryIndex := uint32(v.next()) - if v.dataCount == nil { - return errDataCountNotSet - } - - if dataIndex >= *v.dataCount { - return errDataIndexOutOfBounds - } if err := v.validateMemoryExists(memoryIndex); err != nil { return err } + if err := v.validateDataSegmentExists(dataIndex); err != nil { + return err + } _, err := v.popExpectedValues([]ValueType{I32, I32, I32}) return err } @@ -1081,28 +1096,28 @@ func (v *validator) validateMemoryCopy() error { func (v *validator) validateFunctionTypeExists(index uint32) error { if index >= uint32(len(v.funcTypes)) { - return errFunctionIndexOutOfBounds + return unknownIndex("function", uint64(index)) } return nil } func (v *validator) validateTableExists(tableIndex uint32) error { if tableIndex >= uint32(len(v.tableTypes)) { - return errTableIndexOutOfBounds + return unknownIndex("table", uint64(tableIndex)) } return nil } func (v *validator) validateMemoryExists(memoryIndex uint32) error { if memoryIndex >= uint32(len(v.memTypes)) { - return errMemoryIndexOutOfBounds + return unknownIndex("memory", uint64(memoryIndex)) } return nil } func (v *validator) validateGlobalExists(globalIndex uint32) error { if globalIndex >= uint32(len(v.globalTypes)) { - return errGlobalIndexOutOfBounds + return unknownIndex("global", uint64(globalIndex)) } return nil } @@ -1200,12 +1215,12 @@ func (v *validator) validateTableSet() error { func (v *validator) validateTableInit() error { elemIndex := uint32(v.next()) tableIndex := uint32(v.next()) - if elemIndex >= uint32(len(v.elemTypes)) { - return errElementIndexOutOfBounds - } if err := v.validateTableExists(tableIndex); err != nil { return err } + if elemIndex >= uint32(len(v.elemTypes)) { + return unknownIndex("elem segment", uint64(elemIndex)) + } if _, err := v.popExpectedValues([]ValueType{I32, I32, I32}); err != nil { return err } @@ -1285,19 +1300,20 @@ func (v *validator) validateTableFill() error { func (v *validator) validateElemDrop() error { elemIndex := uint32(v.next()) if elemIndex >= uint32(len(v.elemTypes)) { - return errElementIndexOutOfBounds + return unknownIndex("elem segment", uint64(elemIndex)) } return nil } func (v *validator) validateDataDrop() error { - if v.dataCount == nil { - return errDataCountNotSet - } + return v.validateDataSegmentExists(uint32(v.next())) +} - dataIndex := uint32(v.next()) - if dataIndex >= *v.dataCount { - return errDataIndexOutOfBounds +// validateDataSegmentExists reports whether the module declares the given data +// segment. A module carrying no data count section declares none. +func (v *validator) validateDataSegmentExists(dataIndex uint32) error { + if v.dataCount == nil || dataIndex >= *v.dataCount { + return unknownIndex("data segment", uint64(dataIndex)) } return nil } @@ -1405,7 +1421,7 @@ func (v *validator) validateShuffle() error { func (v *validator) getLocalType(index uint64) (ValueType, error) { if index >= uint64(len(v.locals)) { - return nil, errLocalIndexOutOfBounds + return nil, unknownIndex("local", index) } return v.locals[index], nil } @@ -1566,6 +1582,16 @@ func toValueType(code uint64) ValueType { } } +// validateMemoryLimits checks a declared memory against the page count the +// spec permits before applying the host's own, possibly lower, ceiling. +func validateMemoryLimits(limits Limits, configuredMax uint32) error { + if limits.Min > specMaxMemoryPages || + (limits.Max != nil && *limits.Max > specMaxMemoryPages) { + return errMemorySizeTooLarge + } + return validateLimits(limits, configuredMax) +} + func validateLimits(limits Limits, maximumRange uint32) error { if limits.Min > maximumRange { return errInvalidLimits @@ -1580,7 +1606,7 @@ func validateLimits(limits Limits, maximumRange uint32) error { } if limits.Min > *limits.Max { - return errInvalidLimits + return errLimitsMinGreaterThanMax } return nil diff --git a/internal/spec_tests/spec_test_runner.go b/internal/spec_tests/spec_test_runner.go index f4748e3..c4ad7a1 100644 --- a/internal/spec_tests/spec_test_runner.go +++ b/internal/spec_tests/spec_test_runner.go @@ -229,27 +229,48 @@ func (r *specTestRunner) handleAssertTrap(cmd wabt.Command) { r.assertFailedWithText(cmd, err) } +// binaryIndistinguishableReasons maps a reason an assertion expects to one a +// runtime reading the binary format may report instead, for failures the +// encoding does not preserve the distinction between. +// +// select.wast expects "invalid result arity" from (select (result) …), but +// wat2wasm drops the empty result vector and emits the untyped select opcode, +// so that module is byte-identical to the one the assertion before it expects +// to fail with "type mismatch". Only the text format tells them apart. +var binaryIndistinguishableReasons = map[string]string{ + "invalid result arity": "type mismatch", +} + // assertFailedWithText reports a test failure unless err states the reason the -// assertion expects. Epsilon appends context to some messages (the offending -// element index, for instance), so the expected reason may stop short of the -// full message, but only at a word boundary. +// assertion expects. func (r *specTestRunner) assertFailedWithText(cmd wabt.Command, err error) { r.t.Helper() if err == nil { r.fatalf(cmd.Line, "expected %q, but got no error", cmd.Text) } - rest, ok := strings.CutPrefix(err.Error(), cmd.Text) - if !ok || (rest != "" && rest[0] != ' ') { - r.fatalf(cmd.Line, "expected %q, but got: %v", cmd.Text, err) + if statesReason(cmd.Text, err.Error()) { + return + } + alternative, ok := binaryIndistinguishableReasons[cmd.Text] + if ok && statesReason(alternative, err.Error()) { + return } + r.fatalf(cmd.Line, "expected %q, but got: %v", cmd.Text, err) +} + +// statesReason reports whether message opens with the failure reason an +// assertion expects. Epsilon appends context to some messages (the offending +// index, or which check within a broader category failed), so the reason may +// stop short of the full message, but only at a word boundary. +func statesReason(reason, message string) bool { + rest, ok := strings.CutPrefix(message, reason) + return ok && (rest == "" || rest[0] == ' ' || rest[0] == ':') } func (r *specTestRunner) handleAssertInvalid(cmd wabt.Command) { wasm := bytes.NewReader(r.wasmDict[cmd.Filename]) _, err := r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) - if err == nil { - r.fatalf(cmd.Line, "expected validation error, but got no error") - } + r.assertFailedWithText(cmd, err) } func (r *specTestRunner) handleAssertMalformed(cmd wabt.Command) { From 1333172e220cf69647cc1ca52dd01bd968374fc1 Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sun, 2 Aug 2026 18:44:10 +0200 Subject: [PATCH 04/13] Verify the message in assert_malformed spec assertions The last of the error assertions to check only that some error came back. Of the 1810 assertions, 719 run; the rest are text-format modules the runner cannot compile. Nothing was wrongly accepted, but only 88 stated the reason the spec gives. Most of the gap was vocabulary, one rename covering 528 assertions on its own, and four parse errors that buried the reason behind the context they were wrapped in. The rest were reported as the wrong condition: - The parser surfaced a bare EOF for every way a read can run out. It now states which: input ending outside a section, input ending part way through a declared payload, a read reaching the end of the section that bounds it, and a LEB128 needing more bytes than its section holds. This reports what the parser already knew at the point of failure and reads no further than before. - A sequence the input ran out of was reported as missing its end opcode, which is a different defect from being cut short. - Limits flags and the function type prefix were read as plain bytes, so an over-long LEB128 encoding of either passed as valid. - Bit 6 of a memarg selects an explicit memory index, which only multi-memory allows. It was accepted unconditionally. - An undefined opcode in a constant expression was reported as an instruction that may not appear there, rather than as no instruction at all. Three assertions expect what the reference interpreter reports after reading past a section's declared size, which binary.wast:93 says as much in a comment. Epsilon stops at the declared size and reports the boundary it hit, so those join the runner's list of reasons the binary cannot distinguish rather than that bound being relaxed to match. Four parser tests asserted the errors that gained a more precise reason. A fifth parsed a module with multi-memory off and validated it with the option on; the memarg check now rejects that at parse time, so it reads the module under the config it validates it with. --- epsilon/parser.go | 153 ++++++++++++++++-------- epsilon/parser_test.go | 13 +- epsilon/validation.go | 45 +++++-- epsilon/validation_test.go | 12 +- internal/spec_tests/spec_test_runner.go | 22 ++-- 5 files changed, 169 insertions(+), 76 deletions(-) diff --git a/epsilon/parser.go b/epsilon/parser.go index c5d166b..a416905 100644 --- a/epsilon/parser.go +++ b/epsilon/parser.go @@ -26,23 +26,26 @@ import ( ) var ( - errFunctionTypeMismatch = errors.New("function type count mismatch") - errInconsistentDataCount = errors.New("inconsistent data count") + errFunctionTypeMismatch = errors.New("function and code section have inconsistent lengths") + errInconsistentDataCount = errors.New("data count and data section have inconsistent lengths") errIntRepresentationTooLong = errors.New("integer representation too long") errIntegerTooLarge = errors.New("integer too large") errInvalidElementKind = errors.New("invalid element kind") errInvalidFunctionTypePrefix = errors.New("invalid function type prefix") - errInvalidGlobalMutability = errors.New("invalid global mutability") - errInvalidImportDescriptor = errors.New("invalid import descriptor") - errInvalidLimitsFormat = errors.New("invalid limits format") - errInvalidMagicNumber = errors.New("invalid magic number") - errInvalidReferenceType = errors.New("invalid reference type") - errInvalidUTF8 = errors.New("invalid UTF-8") + errInvalidGlobalMutability = errors.New("malformed mutability") + errInvalidImportDescriptor = errors.New("malformed import kind") + errInvalidMagicNumber = errors.New("magic header not detected") + errInvalidReferenceType = errors.New("malformed reference type") + errInvalidUTF8 = errors.New("malformed UTF-8 encoding") errMalformedMemopFlags = errors.New("malformed memop flags") errMissingEndOpcode = errors.New("missing end opcode") + errEndOpcodeExpected = errors.New("END opcode expected") errPrefixedOpcodeOutOfRange = errors.New("prefixed opcode out of range") errSectionSizeMismatch = errors.New("section size mismatch") errUnexpectedContent = errors.New("unexpected content after last section") + errUnexpectedEnd = errors.New("unexpected end") + errLengthOutOfBounds = errors.New("length out of bounds") + errSectionTruncated = errors.New("unexpected end of section or function") ) const ( @@ -116,7 +119,7 @@ func newParser(reader io.Reader, config Config) *parser { func (p *parser) Read(bytes []byte) (int, error) { if p.bytesRemaining == 0 { - return 0, io.EOF + return 0, errSectionTruncated } if p.bytesRemaining > 0 && int64(len(bytes)) > p.bytesRemaining { bytes = bytes[:p.bytesRemaining] @@ -125,18 +128,46 @@ func (p *parser) Read(bytes []byte) (int, error) { if p.bytesRemaining > 0 { p.bytesRemaining -= int64(n) } + if err == io.EOF && n < len(bytes) { + return n, p.outOfInput() + } return n, err } func (p *parser) ReadByte() (byte, error) { if p.bytesRemaining == 0 { - return 0, io.EOF + return 0, errSectionTruncated } b, err := p.reader.ReadByte() - if err == nil && p.bytesRemaining > 0 { + if err == io.EOF { + return 0, p.outOfInput() + } + if err != nil { + return 0, err + } + if p.bytesRemaining > 0 { p.bytesRemaining-- } - return b, err + return b, nil +} + +// discardRemaining consumes whatever is left of the bounded region the parser +// is reading. Reaching its end is the expected outcome here, not a failure. +func (p *parser) discardRemaining() error { + _, err := io.Copy(io.Discard, p) + if err == errSectionTruncated { + return nil + } + return err +} + +// outOfInput states why a read found no more input: bytes still owed to a +// section mean the section declared a longer payload than the module holds. +func (p *parser) outOfInput() error { + if p.bytesRemaining > 0 { + return errLengthOutOfBounds + } + return errUnexpectedEnd } // parse takes a byte slice and returns a Module. @@ -164,12 +195,12 @@ func (p *parser) parse() (*moduleDefinition, error) { for { sectionIdByte, err := p.ReadByte() - if err == io.EOF { + if err == errUnexpectedEnd { break } if err != nil { - return nil, fmt.Errorf("failed to read section ID: %w", err) + return nil, err } sectionId := sectionId(sectionIdByte) @@ -182,7 +213,7 @@ func (p *parser) parse() (*moduleDefinition, error) { payloadLen, err := p.parseUint32() if err != nil { - return nil, fmt.Errorf("failed to read payload length: %w", err) + return nil, err } p.bytesRemaining = int64(payloadLen) @@ -293,17 +324,24 @@ func (p *parser) parse() (*moduleDefinition, error) { } func (p *parser) parseHeader() error { - header := make([]byte, 8) - if _, err := io.ReadFull(p, header); err != nil { + // The magic number is checked before the version is read, so input too short + // to hold a header counts as truncated only while what it does hold still + // looks like WebAssembly. + magic := make([]byte, len(wasmMagicNumber)) + if _, err := io.ReadFull(p, magic); err != nil { return err } - - if !bytes.HasPrefix(header, []byte(wasmMagicNumber)) { + if !bytes.Equal(magic, []byte(wasmMagicNumber)) { return errInvalidMagicNumber } - version := int32(binary.LittleEndian.Uint32(header[4:8])) + + versionBytes := make([]byte, 4) + if _, err := io.ReadFull(p, versionBytes); err != nil { + return err + } + version := int32(binary.LittleEndian.Uint32(versionBytes)) if version != supportedWasmVersion { - return fmt.Errorf("unsupported WASM version: %d", version) + return fmt.Errorf("unknown binary version %d", version) } return nil } @@ -325,8 +363,7 @@ func (p *parser) parseCustomSection() error { } // Discard the remaining bytes of the section. - _, err = io.Copy(io.Discard, p) - return err + return p.discardRemaining() } func (p *parser) parseFunction() (function, error) { @@ -337,7 +374,7 @@ func (p *parser) parseFunction() (function, error) { sectionBytesRemaining := p.bytesRemaining if int64(size) > sectionBytesRemaining { - return function{}, io.ErrUnexpectedEOF + return function{}, errLengthOutOfBounds } p.bytesRemaining = int64(size) @@ -366,17 +403,20 @@ func (p *parser) parseFunction() (function, error) { result, err := p.readCode(size, nil) if err != nil { + if err == errSectionTruncated && sectionBytesRemaining > int64(size) { + return function{}, errEndOpcodeExpected + } return function{}, err } // Discard any bytes of the function body the parser didn't consume (e.g. // trailing bytes after an early end opcode) so the underlying reader is // positioned at the start of the next function. - if _, err := io.Copy(io.Discard, p); err != nil { + if err := p.discardRemaining(); err != nil { return function{}, err } if p.bytesRemaining != 0 { - return function{}, io.ErrUnexpectedEOF + return function{}, errSectionTruncated } p.bytesRemaining = sectionBytesRemaining - int64(size) @@ -414,7 +454,7 @@ func (p *parser) parseLocalVariables() (localEntry, error) { return localEntry{}, err } if count > math.MaxInt32 { - return localEntry{}, fmt.Errorf("too many local variables: %d", count) + return localEntry{}, fmt.Errorf("too many locals %d", count) } valueType, err := p.parseValueType() @@ -539,11 +579,11 @@ func (p *parser) parseDataSegment() (dataSegment, error) { } func (p *parser) parseFunctionType() (FunctionType, error) { - b, err := p.ReadByte() + prefix, err := p.readSleb128(1) if err != nil { return FunctionType{}, err } - if b != 0x60 { + if int64(prefix) != -0x20 { return FunctionType{}, errInvalidFunctionTypePrefix } @@ -637,7 +677,7 @@ func (p *parser) parseGlobalType() (GlobalType, error) { func (p *parser) parseElementSegment() (elementSegment, error) { flags, err := p.parseUint32() if err != nil { - return elementSegment{}, fmt.Errorf("failed to read element flags: %w", err) + return elementSegment{}, err } switch flags { @@ -802,26 +842,26 @@ func (p *parser) parseExpression() ([]uint64, error) { } func (p *parser) parseLimits() (Limits, error) { - b, err := p.ReadByte() + // The flags are a single-bit LEB128, so an over-long encoding or a value + // that does not fit is rejected as the malformed integer it is, before + // anything is read on its behalf. + flags, err := p.readUleb128(1) if err != nil { return Limits{}, err } + min, err := p.parseUint32() if err != nil { return Limits{}, err } - switch b { - case 0: + if flags == 0 { return Limits{Min: min}, nil - case 1: - max, err := p.parseUint32() - if err != nil { - return Limits{}, err - } - return Limits{Min: min, Max: &max}, nil - default: - return Limits{}, errInvalidLimitsFormat } + max, err := p.parseUint32() + if err != nil { + return Limits{}, err + } + return Limits{Min: min, Max: &max}, nil } func parseVector[T any](parser *parser, parse func() (T, error)) ([]T, error) { @@ -855,7 +895,7 @@ func (p *parser) parseUtf8String() (string, error) { } stringBytes, err := p.readN(uint64(length)) if err != nil { - return "", fmt.Errorf("failed to read string bytes: %w", err) + return "", err } if !utf8.Valid(stringBytes) { return "", errInvalidUTF8 @@ -926,9 +966,10 @@ type bytecodeResult struct { // block/if to its branch targets. // // Decoding stops at the first instruction for which isEnd returns true; a nil -// isEnd decodes until the reader reaches EOF, which a function body's bounded -// reader hits at the end of the body. A sequence that does not end with an end -// opcode is rejected with errMissingEndOpcode. +// isEnd decodes until the reader runs out, which a function body's bounded +// reader does at the end of the body. A sequence the input ran out of is +// rejected as truncated, one that merely lacks its end opcode with +// errMissingEndOpcode. // // sizeHint only seeds the bytecode buffer capacity to avoid regrowth: it is the // body's declared byte length, or 0 if unknown, and need not be accurate. @@ -948,11 +989,13 @@ func (p *parser) readCode( controlStack := []controlEntry{} var lastOp opcode + var truncation error for { opcodeVal, err := p.readOpcode() if err != nil { - if err == io.EOF { + if err == errSectionTruncated || err == errUnexpectedEnd { + truncation = err break } return bytecodeResult{}, err @@ -1203,6 +1246,11 @@ func (p *parser) readCode( } } + // Input that ran out mid-sequence is truncated, whatever it stopped inside; + // only a sequence that reads to completion can be missing its end opcode. + if truncation != nil && (lastOp != end || len(controlStack) > 0) { + return bytecodeResult{}, truncation + } if len(bytecode) == 0 || lastOp != end { return bytecodeResult{}, errMissingEndOpcode } @@ -1280,8 +1328,11 @@ func (p *parser) readMemArg() (uint64, uint64, uint64, error) { return 0, 0, 0, err } - // The alignment exponent must be < 32. - // We also have to remove bit 6, used for multi memory. + // The alignment exponent must be < 32. Bit 6 is not part of it: it marks an + // explicit memory index, which only multi-memory allows. + if align&sixthBitMask != 0 && !p.config.ExperimentalMultipleMemories { + return 0, 0, 0, errMalformedMemopFlags + } if (align & ^sixthBitMask) >= 32 { return 0, 0, 0, errMalformedMemopFlags } @@ -1351,6 +1402,9 @@ func (p *parser) readUleb128(bitWidth uint) (uint64, error) { for byteIndex := uint(0); byteIndex < maxBytes; byteIndex++ { b, err := p.ReadByte() if err != nil { + if byteIndex > 0 && err == errSectionTruncated { + return 0, errIntRepresentationTooLong + } return 0, err } @@ -1379,6 +1433,9 @@ func (p *parser) readSleb128(maxBytes int) (uint64, error) { for { b, err = p.ReadByte() if err != nil { + if bytesRead > 0 && err == errSectionTruncated { + return 0, errIntRepresentationTooLong + } return 0, err } bytesRead++ diff --git a/epsilon/parser_test.go b/epsilon/parser_test.go index 73502ca..a526835 100644 --- a/epsilon/parser_test.go +++ b/epsilon/parser_test.go @@ -17,7 +17,6 @@ package epsilon import ( "bytes" "errors" - "io" "math" "reflect" "slices" @@ -856,8 +855,8 @@ func TestParseTruncatedFunctionBody(t *testing.T) { if err == nil { t.Fatal("expected parse error for truncated function body, got nil") } - if err != errMissingEndOpcode { - t.Errorf("expected errMissingEndOpcode, got %v", err) + if err != errSectionTruncated { + t.Errorf("expected errSectionTruncated, got %v", err) } } @@ -873,7 +872,7 @@ func TestParseSectionPayloadBounds(t *testing.T) { { name: "content outside payload", section: []byte{byte(typeSectionId), 0x00, 0x00}, - wantErr: io.EOF, + wantErr: errSectionTruncated, }, { name: "payload shorter than declared", @@ -890,7 +889,7 @@ func TestParseSectionPayloadBounds(t *testing.T) { section: []byte{ byte(codeSectionId), 0x03, 0x01, 0x02, 0x00, }, - wantErr: io.ErrUnexpectedEOF, + wantErr: errLengthOutOfBounds, }, } @@ -916,8 +915,8 @@ func TestParseCustomSectionDoesNotReadPastPayload(t *testing.T) { } reader := bytes.NewReader(wasm) _, err := newParser(reader, DefaultConfig()).parse() - if err != io.EOF { - t.Fatalf("expected EOF, got %v", err) + if err != errSectionTruncated { + t.Fatalf("expected errSectionTruncated, got %v", err) } if reader.Len() != 3 { t.Fatalf( diff --git a/epsilon/validation.go b/epsilon/validation.go index 9a28e84..6a8ca1e 100644 --- a/epsilon/validation.go +++ b/epsilon/validation.go @@ -26,6 +26,7 @@ var ( errDuplicateExport = errors.New("duplicate export name") errElseMustMatchIf = errors.New("else must match if") errGlobalIsImmutable = errors.New("global is immutable") + errIllegalOpcode = errors.New("illegal opcode") errInvalidCallIndirectType = errors.New("unknown type") errInvalidConstantExpression = errors.New("constant expression required") errInvalidLimits = errors.New("invalid limits") @@ -37,6 +38,8 @@ var ( errInvalidTableType = errors.New("type mismatch: table is not funcref") errInvalidBlockType = errors.New("invalid block type") errMultipleMemoriesNotEnabled = errors.New("multiple memories not enabled") + errDataCountSectionRequired = errors.New("data count section required") + errZeroByteExpected = errors.New("zero byte expected") errReturnTypeNotSet = errors.New("return type not set") errSimdLaneIndexOutOfBounds = errors.New("invalid lane index") errStackHeightMismatch = errors.New("type mismatch: stack height mismatch") @@ -47,8 +50,8 @@ var ( ) // unknownIndex reports an index immediate that is out of range for the module -// index space it addresses. The spec states these failures as "unknown ", -// and several assertions name the offending index too. +// index space it addresses, in the "unknown " form the spec +// words these failures. func unknownIndex(space string, index uint64) error { return fmt.Errorf("unknown %s %d", space, index) } @@ -93,6 +96,7 @@ type validator struct { importedTypes []GlobalType // Only includes imported globals. elemTypes []ReferenceType dataCount *uint32 + hasDataSegments bool referencedFunctions map[uint32]bool config Config code []uint64 @@ -210,6 +214,7 @@ func (v *validator) validateModule(module *moduleDefinition) error { } v.dataCount = module.dataCount + v.hasDataSegments = len(module.dataSegments) > 0 for _, data := range module.dataSegments { if err := v.validateDataSegment(&data); err != nil { return err @@ -382,7 +387,7 @@ func (v *validator) validateConstExpression( return nil } -// validateConstantOpcode reports whether op may appear in a constant +// validateConstantOpcode rejects an opcode that may not appear in a constant // expression. Only an immutable imported global is in scope for global.get // there, so any other global index names one that does not exist yet. func (v *validator) validateConstantOpcode(op opcode) error { @@ -400,6 +405,12 @@ func (v *validator) validateConstantOpcode(op opcode) error { if isConstantOpcode(op) { return nil } + + // A byte that is no instruction at all is illegal wherever it appears, not + // merely an instruction a constant expression may not use. + if err := v.validate(op); errors.Is(err, errIllegalOpcode) { + return err + } return errInvalidConstantExpression } @@ -697,7 +708,7 @@ func (v *validator) validate(op opcode) error { case memoryFill: return v.validateMemoryFill() default: - return fmt.Errorf("unknown opcode %d", op) + return fmt.Errorf("%w %d", errIllegalOpcode, op) } } @@ -989,7 +1000,7 @@ func (v *validator) validateLoad(valueType ValueType, sizeBytes uint32) error { align, memoryIndex, _ := v.nextMemArg() if !v.config.ExperimentalMultipleMemories && memoryIndex != 0 { - return errMultipleMemoriesNotEnabled + return errZeroByteExpected } if err := v.validateMemoryExists(uint32(memoryIndex)); err != nil { @@ -1007,7 +1018,7 @@ func (v *validator) validateStore(valueType ValueType, sizeBytes uint32) error { align, memoryIndex, _ := v.nextMemArg() if !v.config.ExperimentalMultipleMemories && memoryIndex != 0 { - return errMultipleMemoriesNotEnabled + return errZeroByteExpected } if err := v.validateMemoryExists(uint32(memoryIndex)); err != nil { @@ -1037,7 +1048,7 @@ func (v *validator) validateMemArg(align uint64, nBytes uint32) error { func (v *validator) validateMemorySize() error { memoryIndex := uint32(v.next()) if !v.config.ExperimentalMultipleMemories && memoryIndex != 0 { - return errMultipleMemoriesNotEnabled + return errZeroByteExpected } if err := v.validateMemoryExists(memoryIndex); err != nil { @@ -1050,7 +1061,7 @@ func (v *validator) validateMemorySize() error { func (v *validator) validateMemoryGrow() error { memoryIndex := uint32(v.next()) if !v.config.ExperimentalMultipleMemories && memoryIndex != 0 { - return errMultipleMemoriesNotEnabled + return errZeroByteExpected } if err := v.validateMemoryExists(memoryIndex); err != nil { @@ -1309,10 +1320,18 @@ func (v *validator) validateDataDrop() error { return v.validateDataSegmentExists(uint32(v.next())) } -// validateDataSegmentExists reports whether the module declares the given data -// segment. A module carrying no data count section declares none. +// validateDataSegmentExists rejects a data segment the module does not +// declare. func (v *validator) validateDataSegmentExists(dataIndex uint32) error { - if v.dataCount == nil || dataIndex >= *v.dataCount { + if v.dataCount == nil { + // A data section without the count section that must accompany it is + // malformed; a module carrying neither declares no segments at all. + if v.hasDataSegments { + return errDataCountSectionRequired + } + return unknownIndex("data segment", uint64(dataIndex)) + } + if dataIndex >= *v.dataCount { return unknownIndex("data segment", uint64(dataIndex)) } return nil @@ -1365,7 +1384,7 @@ func (v *validator) validateVectorScalar(scalar ValueType) error { func (v *validator) validateSimdLoadLane(sizeBytes uint32) error { align, memoryIndex, _ := v.nextMemArg() if !v.config.ExperimentalMultipleMemories && memoryIndex != 0 { - return errMultipleMemoriesNotEnabled + return errZeroByteExpected } if err := v.validateMemoryExists(uint32(memoryIndex)); err != nil { return err @@ -1390,7 +1409,7 @@ func (v *validator) validateSimdLoadLane(sizeBytes uint32) error { func (v *validator) validateSimdStoreLane(sizeBytes uint32) error { align, memoryIndex, _ := v.nextMemArg() if !v.config.ExperimentalMultipleMemories && memoryIndex != 0 { - return errMultipleMemoriesNotEnabled + return errZeroByteExpected } if err := v.validateMemoryExists(uint32(memoryIndex)); err != nil { return err diff --git a/epsilon/validation_test.go b/epsilon/validation_test.go index 618ea6e..84d038d 100644 --- a/epsilon/validation_test.go +++ b/epsilon/validation_test.go @@ -148,7 +148,17 @@ func TestMemoryIndexValidation(t *testing.T) { 0x0b, // end } - module, err := newParser(bytes.NewReader(wasm), DefaultConfig()).parse() + // The explicit memory index only parses with multi-memory on, so the module + // has to be read under the same config it is validated under. + config := Config{ + MaxCallStackDepth: DefaultMaxCallStackDepth, + CallStackPreallocationSize: DefaultCallStackPreallocationSize, + MaxTableElements: DefaultMaxTableElements, + MaxMemoryPages: DefaultMaxMemoryPages, + MaxLocalsPerFunction: DefaultMaxLocalsPerFunction, + ExperimentalMultipleMemories: true, + } + module, err := newParser(bytes.NewReader(wasm), config).parse() if err != nil { t.Fatalf("failed to parse module: %v", err) } diff --git a/internal/spec_tests/spec_test_runner.go b/internal/spec_tests/spec_test_runner.go index c4ad7a1..5595aaf 100644 --- a/internal/spec_tests/spec_test_runner.go +++ b/internal/spec_tests/spec_test_runner.go @@ -229,16 +229,26 @@ func (r *specTestRunner) handleAssertTrap(cmd wabt.Command) { r.assertFailedWithText(cmd, err) } -// binaryIndistinguishableReasons maps a reason an assertion expects to one a -// runtime reading the binary format may report instead, for failures the -// encoding does not preserve the distinction between. +// binaryIndistinguishableReasons maps a reason an assertion expects to one +// epsilon reports instead, where the two cannot be told apart from the binary +// a module was compiled to. // // select.wast expects "invalid result arity" from (select (result) …), but // wat2wasm drops the empty result vector and emits the untyped select opcode, // so that module is byte-identical to the one the assertion before it expects // to fail with "type mismatch". Only the text format tells them apart. +// +// The rest are reasons the reference interpreter reaches by reading past a +// section's declared size and reporting whatever it then trips over: the byte +// beginning the next section, read as an end opcode, an instruction, or a name +// length. binary.wast:93 says as much in a comment. Epsilon stops at the size +// the section declared, so it reports the boundary it hit instead; matching the +// interpreter would mean letting a declared length be overrun. var binaryIndistinguishableReasons = map[string]string{ - "invalid result arity": "type mismatch", + "invalid result arity": "type mismatch", + "section size mismatch": "unexpected end of section or function", + "illegal opcode": "unexpected end of section or function", + "length out of bounds": "unexpected end of section or function", } // assertFailedWithText reports a test failure unless err states the reason the @@ -282,9 +292,7 @@ func (r *specTestRunner) handleAssertMalformed(cmd wabt.Command) { wasm := bytes.NewReader(r.wasmDict[cmd.Filename]) _, err := r.runtime.InstantiateModuleWithImports(wasm, r.buildImports()...) - if err == nil { - r.fatalf(cmd.Line, "expected validation error, but got no error") - } + r.assertFailedWithText(cmd, err) } func (r *specTestRunner) handleAssertUninstantiable(cmd wabt.Command) { From 51c54846b15606c3be6faedeb3d81ce3dc424ada Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sat, 8 Aug 2026 19:11:49 +0200 Subject: [PATCH 05/13] Reuse parser header buffer --- epsilon/parser.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/epsilon/parser.go b/epsilon/parser.go index a416905..4604dd7 100644 --- a/epsilon/parser.go +++ b/epsilon/parser.go @@ -327,7 +327,8 @@ func (p *parser) parseHeader() error { // The magic number is checked before the version is read, so input too short // to hold a header counts as truncated only while what it does hold still // looks like WebAssembly. - magic := make([]byte, len(wasmMagicNumber)) + var header [8]byte + magic := header[:len(wasmMagicNumber)] if _, err := io.ReadFull(p, magic); err != nil { return err } @@ -335,7 +336,7 @@ func (p *parser) parseHeader() error { return errInvalidMagicNumber } - versionBytes := make([]byte, 4) + versionBytes := header[len(wasmMagicNumber):] if _, err := io.ReadFull(p, versionBytes); err != nil { return err } From 8320763593a0f90ac6b03ea9aa363285c21fba6d Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sat, 8 Aug 2026 20:07:11 +0200 Subject: [PATCH 06/13] Avoid redundant work on the parser's hot paths Fold the multi-memory rejection into the branch that already tests bit 6, so an instruction without an explicit memory index pays one test for it instead of two. Decide truncation in readCode where the error surfaces, since lastOp and the control stack are already final there, keeping the extra state out of the decode loop. Skip discardRemaining's copy when the bounded region holds nothing, which is every function body the decoder consumed to its end. --- epsilon/parser.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/epsilon/parser.go b/epsilon/parser.go index 4604dd7..f16a731 100644 --- a/epsilon/parser.go +++ b/epsilon/parser.go @@ -154,6 +154,9 @@ func (p *parser) ReadByte() (byte, error) { // discardRemaining consumes whatever is left of the bounded region the parser // is reading. Reaching its end is the expected outcome here, not a failure. func (p *parser) discardRemaining() error { + if p.bytesRemaining == 0 { + return nil + } _, err := io.Copy(io.Discard, p) if err == errSectionTruncated { return nil @@ -990,13 +993,17 @@ func (p *parser) readCode( controlStack := []controlEntry{} var lastOp opcode - var truncation error for { opcodeVal, err := p.readOpcode() if err != nil { if err == errSectionTruncated || err == errUnexpectedEnd { - truncation = err + // Input that ran out mid-sequence is truncated, whatever it stopped + // inside; only a sequence that reads to completion can be missing its + // end opcode. + if lastOp != end || len(controlStack) > 0 { + return bytecodeResult{}, err + } break } return bytecodeResult{}, err @@ -1247,11 +1254,6 @@ func (p *parser) readCode( } } - // Input that ran out mid-sequence is truncated, whatever it stopped inside; - // only a sequence that reads to completion can be missing its end opcode. - if truncation != nil && (lastOp != end || len(controlStack) > 0) { - return bytecodeResult{}, truncation - } if len(bytecode) == 0 || lastOp != end { return bytecodeResult{}, errMissingEndOpcode } @@ -1331,17 +1333,15 @@ func (p *parser) readMemArg() (uint64, uint64, uint64, error) { // The alignment exponent must be < 32. Bit 6 is not part of it: it marks an // explicit memory index, which only multi-memory allows. - if align&sixthBitMask != 0 && !p.config.ExperimentalMultipleMemories { - return 0, 0, 0, errMalformedMemopFlags - } if (align & ^sixthBitMask) >= 32 { return 0, 0, 0, errMalformedMemopFlags } memoryIndex := uint64(0) - // If bit 6 is set, this instruction is using an explicit memory index. - // This is relevant in WASM 3. if align&sixthBitMask != 0 { + if !p.config.ExperimentalMultipleMemories { + return 0, 0, 0, errMalformedMemopFlags + } memoryIndex, err = p.readUint32() if err != nil { return 0, 0, 0, err From 511e072b056c678ee5f6952e41158f554d98cb6c Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sat, 8 Aug 2026 20:32:46 +0200 Subject: [PATCH 07/13] Trim the parser's per-byte bookkeeping Order the reader's error checks cheapest first: comparing against io.EOF loads the itab and data words of a package variable, while a nil check reads neither and a length check reads neither, so the interface comparison now runs only once the cheaper test has already selected for it. Let the byte counter run negative outside a bounded region instead of pinning it at -1. Nothing reads the sentinel's exact value, so the guard that kept it there can go and the counter can be decremented unconditionally, which takes a branch off the path every byte travels. --- epsilon/parser.go | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/epsilon/parser.go b/epsilon/parser.go index f16a731..996e57d 100644 --- a/epsilon/parser.go +++ b/epsilon/parser.go @@ -98,7 +98,10 @@ type wasmReader interface { // parser is a parser for WASM modules. type parser struct { - reader wasmReader + reader wasmReader + // bytesRemaining counts down the bytes still owed to the region being + // read. Any negative value means the parser is reading outside a bounded + // region and consumes whatever the input holds. bytesRemaining int64 config Config } @@ -125,10 +128,8 @@ func (p *parser) Read(bytes []byte) (int, error) { bytes = bytes[:p.bytesRemaining] } n, err := p.reader.Read(bytes) - if p.bytesRemaining > 0 { - p.bytesRemaining -= int64(n) - } - if err == io.EOF && n < len(bytes) { + p.bytesRemaining -= int64(n) + if n < len(bytes) && err == io.EOF { return n, p.outOfInput() } return n, err @@ -139,15 +140,13 @@ func (p *parser) ReadByte() (byte, error) { return 0, errSectionTruncated } b, err := p.reader.ReadByte() - if err == io.EOF { - return 0, p.outOfInput() - } if err != nil { + if err == io.EOF { + return 0, p.outOfInput() + } return 0, err } - if p.bytesRemaining > 0 { - p.bytesRemaining-- - } + p.bytesRemaining-- return b, nil } @@ -874,7 +873,7 @@ func parseVector[T any](parser *parser, parse func() (T, error)) ([]T, error) { return nil, err } items := make([]T, 0, min(count, maxInitialCapacity)) - for i := uint32(0); i < count; i++ { + for range count { parsed, err := parse() if err != nil { return nil, err From 0461e4069217439d0264627f4defa4cbd4e54a19 Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sat, 8 Aug 2026 21:47:52 +0200 Subject: [PATCH 08/13] Speed up parser bulk reads --- epsilon/parser.go | 43 +++++++++++++-------- epsilon/parser_benchmark_test.go | 52 +++++++++++++++++++++++++ epsilon/parser_test.go | 66 +++++++++++++++++++++++++++++++- 3 files changed, 144 insertions(+), 17 deletions(-) create mode 100644 epsilon/parser_benchmark_test.go diff --git a/epsilon/parser.go b/epsilon/parser.go index 996e57d..f154bc2 100644 --- a/epsilon/parser.go +++ b/epsilon/parser.go @@ -404,7 +404,7 @@ func (p *parser) parseFunction() (function, error) { } } - result, err := p.readCode(size, nil) + result, err := p.readCode(size, false) if err != nil { if err == errSectionTruncated && sectionBytesRemaining > int64(size) { return function{}, errEndOpcodeExpected @@ -542,7 +542,7 @@ func (p *parser) parseDataSegment() (dataSegment, error) { if err != nil { return dataSegment{}, err } - content, err := parseVector(p, p.ReadByte) + content, err := p.parseByteVector() if err != nil { return dataSegment{}, err } @@ -552,7 +552,7 @@ func (p *parser) parseDataSegment() (dataSegment, error) { offsetExpression: offsetExpression, }, nil case 1: - content, err := parseVector(p, p.ReadByte) + content, err := p.parseByteVector() if err != nil { return dataSegment{}, err } @@ -566,7 +566,7 @@ func (p *parser) parseDataSegment() (dataSegment, error) { if err != nil { return dataSegment{}, err } - content, err := parseVector(p, p.ReadByte) + content, err := p.parseByteVector() if err != nil { return dataSegment{}, err } @@ -835,9 +835,7 @@ func (p *parser) parseElementSegment() (elementSegment, error) { } func (p *parser) parseExpression() ([]uint64, error) { - result, err := p.readCode(0, func(instruction []uint64) bool { - return opcode(instruction[0]) == end - }) + result, err := p.readCode(0, true) if err != nil { return nil, err } @@ -891,6 +889,14 @@ func (p *parser) parseUint32() (uint32, error) { return uint32(val), nil } +func (p *parser) parseByteVector() ([]byte, error) { + length, err := p.parseUint32() + if err != nil { + return nil, err + } + return p.readN(uint64(length)) +} + func (p *parser) parseUtf8String() (string, error) { length, err := p.parseUint32() if err != nil { @@ -911,7 +917,15 @@ func (p *parser) parseUtf8String() (string, error) { // length cannot force a huge up-front allocation; the buffer grows as needed // and a short read surfaces as an error. func (p *parser) readN(length uint64) ([]byte, error) { - buf := bytes.NewBuffer(make([]byte, 0, min(length, maxInitialCapacity))) + if length <= maxInitialCapacity { + data := make([]byte, int(length)) + if _, err := io.ReadFull(p, data); err != nil { + return nil, err + } + return data, nil + } + + buf := bytes.NewBuffer(make([]byte, 0, maxInitialCapacity)) if _, err := io.CopyN(buf, p, int64(length)); err != nil { return nil, err } @@ -968,17 +982,15 @@ type bytecodeResult struct { // bytecode the VM executes, and returns it with the jump caches that map each // block/if to its branch targets. // -// Decoding stops at the first instruction for which isEnd returns true; a nil -// isEnd decodes until the reader runs out, which a function body's bounded -// reader does at the end of the body. A sequence the input ran out of is -// rejected as truncated, one that merely lacks its end opcode with -// errMissingEndOpcode. +// Decoding stops at the first end opcode when stopAtEnd is true, or when the +// reader runs out otherwise. A sequence the input ran out of is rejected as +// truncated, one that merely lacks its end opcode with errMissingEndOpcode. // // sizeHint only seeds the bytecode buffer capacity to avoid regrowth: it is the // body's declared byte length, or 0 if unknown, and need not be accurate. func (p *parser) readCode( sizeHint uint32, - isEnd func([]uint64) bool, + stopAtEnd bool, ) (bytecodeResult, error) { // sizeHint is attacker-controlled (the function body's declared size), so cap // the initial capacity at maxInitialCapacity. The buffer still grows via @@ -1009,7 +1021,6 @@ func (p *parser) readCode( } lastOp = opcodeVal - currentInstructionStart := len(bytecode) bytecode = append(bytecode, uint64(opcodeVal)) switch opcodeVal { @@ -1248,7 +1259,7 @@ func (p *parser) readCode( // No operands } - if isEnd != nil && isEnd(bytecode[currentInstructionStart:]) { + if stopAtEnd && opcodeVal == end { break } } diff --git a/epsilon/parser_benchmark_test.go b/epsilon/parser_benchmark_test.go new file mode 100644 index 0000000..a8fa3d8 --- /dev/null +++ b/epsilon/parser_benchmark_test.go @@ -0,0 +1,52 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package epsilon + +import ( + "bytes" + "os" + "testing" +) + +var benchmarkParsedModule *moduleDefinition + +func BenchmarkParse(b *testing.B) { + for _, name := range []string{ + "factorial", + "sorting", + "trigonometry", + "vector_math", + } { + wasm, err := os.ReadFile("../internal/benchmarks/wasm/" + name + ".wasm") + if err != nil { + b.Fatal(err) + } + + b.Run(name, func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(wasm))) + for b.Loop() { + module, err := newParser( + bytes.NewReader(wasm), + DefaultConfig(), + ).parse() + if err != nil { + b.Fatal(err) + } + benchmarkParsedModule = module + } + }) + } +} diff --git a/epsilon/parser_test.go b/epsilon/parser_test.go index a526835..a8b8b83 100644 --- a/epsilon/parser_test.go +++ b/epsilon/parser_test.go @@ -458,6 +458,29 @@ func TestReadUleb128(t *testing.T) { want uint64 wantErr error }{ + { + name: "u1 zero", + bitWidth: 1, + encoded: []byte{0x00}, + }, + { + name: "u1 one", + bitWidth: 1, + encoded: []byte{0x01}, + want: 1, + }, + { + name: "u1 too large", + bitWidth: 1, + encoded: []byte{0x02}, + wantErr: errIntegerTooLarge, + }, + { + name: "u32 one byte", + bitWidth: 32, + encoded: []byte{0x7f}, + want: 0x7f, + }, { name: "u32 maximum", bitWidth: 32, @@ -542,6 +565,47 @@ func TestReadUleb128(t *testing.T) { } } +func TestReadSleb128(t *testing.T) { + tests := []struct { + name string + maxBytes int + encoded []byte + want int64 + wantErr error + }{ + {name: "zero", maxBytes: 5, encoded: []byte{0x00}}, + {name: "positive one byte", maxBytes: 5, encoded: []byte{0x3f}, want: 63}, + {name: "negative one byte", maxBytes: 5, encoded: []byte{0x40}, want: -64}, + { + name: "positive two bytes", maxBytes: 5, + encoded: []byte{0xc0, 0x00}, want: 64, + }, + { + name: "negative two bytes", maxBytes: 5, + encoded: []byte{0xbf, 0x7f}, want: -65, + }, + { + name: "representation too long", + maxBytes: 1, + encoded: []byte{0x80, 0x00}, + wantErr: errIntRepresentationTooLong, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + parser := newParser(bytes.NewReader(test.encoded), DefaultConfig()) + got, err := parser.readSleb128(test.maxBytes) + if err != test.wantErr { + t.Fatalf("expected error %v, got %v", test.wantErr, err) + } + if int64(got) != test.want { + t.Fatalf("expected value %d, got %d", test.want, int64(got)) + } + }) + } +} + func TestReadCodeDecodesLaneIndexesAsBytes(t *testing.T) { shuffleEncoded := []byte{0xfd, 0x0d} shuffleEncoded = append( @@ -602,7 +666,7 @@ func TestReadCodeDecodesLaneIndexesAsBytes(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { parser := newParser(bytes.NewReader(test.encoded), DefaultConfig()) - result, err := parser.readCode(uint32(len(test.encoded)), nil) + result, err := parser.readCode(uint32(len(test.encoded)), false) if err != nil { t.Fatalf("readCode failed: %v", err) } From 014cc6888e9f9263fb03be48d25fc94b64882671 Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sat, 8 Aug 2026 21:55:02 +0200 Subject: [PATCH 09/13] refactor: cleanup parser.go code comments for consistent line wrapping --- epsilon/parser.go | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/epsilon/parser.go b/epsilon/parser.go index f154bc2..dc972d3 100644 --- a/epsilon/parser.go +++ b/epsilon/parser.go @@ -59,9 +59,9 @@ const ( ) // maxInitialCapacity caps the up-front allocation parseVector and similar -// callers perform from an attacker-controlled count. Real modules rarely -// exceed a few thousand items per vector, so this is the common-case exact -// size; pathological counts grow via append+EOF instead of OOMing on a +// callers perform from an attacker-controlled count. Real modules rarely exceed +// a few thousand items per vector, so this is the common-case exact size; +// pathological counts grow via append+EOF instead of OOMing on a // pre-allocation. const maxInitialCapacity = 4096 @@ -99,9 +99,9 @@ type wasmReader interface { // parser is a parser for WASM modules. type parser struct { reader wasmReader - // bytesRemaining counts down the bytes still owed to the region being - // read. Any negative value means the parser is reading outside a bounded - // region and consumes whatever the input holds. + // bytesRemaining counts down the bytes still owed to the region being read. + // Any negative value means the parser is reading outside a bounded region and + // consumes whatever the input holds. bytesRemaining int64 config Config } @@ -191,8 +191,8 @@ func (p *parser) parse() (*moduleDefinition, error) { var dataSegments []dataSegment var dataCount *uint32 - // We initialize lastSection to CustomSectionId since custom sections - // can be in any order. + // We initialize lastSection to CustomSectionId since custom sections can be + // in any order. lastSection := customSectionId for { @@ -843,9 +843,9 @@ func (p *parser) parseExpression() ([]uint64, error) { } func (p *parser) parseLimits() (Limits, error) { - // The flags are a single-bit LEB128, so an over-long encoding or a value - // that does not fit is rejected as the malformed integer it is, before - // anything is read on its behalf. + // The flags are a single-bit LEB128, so an over-long encoding or a value that + // does not fit is rejected as the malformed integer it is, before anything is + // read on its behalf. flags, err := p.readUleb128(1) if err != nil { return Limits{}, err @@ -912,10 +912,10 @@ func (p *parser) parseUtf8String() (string, error) { return string(stringBytes), nil } -// readN reads exactly length bytes from the reader. The initial buffer -// capacity is capped at maxInitialCapacity so an attacker-controlled -// length cannot force a huge up-front allocation; the buffer grows as needed -// and a short read surfaces as an error. +// readN reads exactly length bytes from the reader. The initial buffer capacity +// is capped at maxInitialCapacity so an attacker-controlled length cannot force +// a huge up-front allocation; the buffer grows as needed and a short read +// surfaces as an error. func (p *parser) readN(length uint64) ([]byte, error) { if length <= maxInitialCapacity { data := make([]byte, int(length)) @@ -997,8 +997,8 @@ func (p *parser) readCode( // append as real bytes are decoded; a bogus huge size cannot force a large // up-front allocation. bytecode := make([]uint64, 0, min(sizeHint, maxInitialCapacity)) - // The jump caches are allocated lazily: a function with no control flow - // never branches, so it needs neither map. + // The jump caches are allocated lazily: a function with no control flow never + // branches, so it needs neither map. var jumpCache map[uint32]uint32 var jumpElseCache map[uint32]uint32 From bd54d718316c86b9dbf998de9419c0593698b58b Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sat, 8 Aug 2026 21:57:17 +0200 Subject: [PATCH 10/13] Remove parser benchmark and extra decoder tests --- epsilon/parser_benchmark_test.go | 52 -------------------------- epsilon/parser_test.go | 64 -------------------------------- 2 files changed, 116 deletions(-) delete mode 100644 epsilon/parser_benchmark_test.go diff --git a/epsilon/parser_benchmark_test.go b/epsilon/parser_benchmark_test.go deleted file mode 100644 index a8fa3d8..0000000 --- a/epsilon/parser_benchmark_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2026 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package epsilon - -import ( - "bytes" - "os" - "testing" -) - -var benchmarkParsedModule *moduleDefinition - -func BenchmarkParse(b *testing.B) { - for _, name := range []string{ - "factorial", - "sorting", - "trigonometry", - "vector_math", - } { - wasm, err := os.ReadFile("../internal/benchmarks/wasm/" + name + ".wasm") - if err != nil { - b.Fatal(err) - } - - b.Run(name, func(b *testing.B) { - b.ReportAllocs() - b.SetBytes(int64(len(wasm))) - for b.Loop() { - module, err := newParser( - bytes.NewReader(wasm), - DefaultConfig(), - ).parse() - if err != nil { - b.Fatal(err) - } - benchmarkParsedModule = module - } - }) - } -} diff --git a/epsilon/parser_test.go b/epsilon/parser_test.go index a8b8b83..26db919 100644 --- a/epsilon/parser_test.go +++ b/epsilon/parser_test.go @@ -458,29 +458,6 @@ func TestReadUleb128(t *testing.T) { want uint64 wantErr error }{ - { - name: "u1 zero", - bitWidth: 1, - encoded: []byte{0x00}, - }, - { - name: "u1 one", - bitWidth: 1, - encoded: []byte{0x01}, - want: 1, - }, - { - name: "u1 too large", - bitWidth: 1, - encoded: []byte{0x02}, - wantErr: errIntegerTooLarge, - }, - { - name: "u32 one byte", - bitWidth: 32, - encoded: []byte{0x7f}, - want: 0x7f, - }, { name: "u32 maximum", bitWidth: 32, @@ -565,47 +542,6 @@ func TestReadUleb128(t *testing.T) { } } -func TestReadSleb128(t *testing.T) { - tests := []struct { - name string - maxBytes int - encoded []byte - want int64 - wantErr error - }{ - {name: "zero", maxBytes: 5, encoded: []byte{0x00}}, - {name: "positive one byte", maxBytes: 5, encoded: []byte{0x3f}, want: 63}, - {name: "negative one byte", maxBytes: 5, encoded: []byte{0x40}, want: -64}, - { - name: "positive two bytes", maxBytes: 5, - encoded: []byte{0xc0, 0x00}, want: 64, - }, - { - name: "negative two bytes", maxBytes: 5, - encoded: []byte{0xbf, 0x7f}, want: -65, - }, - { - name: "representation too long", - maxBytes: 1, - encoded: []byte{0x80, 0x00}, - wantErr: errIntRepresentationTooLong, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - parser := newParser(bytes.NewReader(test.encoded), DefaultConfig()) - got, err := parser.readSleb128(test.maxBytes) - if err != test.wantErr { - t.Fatalf("expected error %v, got %v", test.wantErr, err) - } - if int64(got) != test.want { - t.Fatalf("expected value %d, got %d", test.want, int64(got)) - } - }) - } -} - func TestReadCodeDecodesLaneIndexesAsBytes(t *testing.T) { shuffleEncoded := []byte{0xfd, 0x0d} shuffleEncoded = append( From 432f8ea5ba511082f5f1db085e58248b4316028e Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sat, 8 Aug 2026 23:59:10 +0200 Subject: [PATCH 11/13] more comments --- epsilon/validation.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/epsilon/validation.go b/epsilon/validation.go index 6a8ca1e..4df06ed 100644 --- a/epsilon/validation.go +++ b/epsilon/validation.go @@ -1320,8 +1320,7 @@ func (v *validator) validateDataDrop() error { return v.validateDataSegmentExists(uint32(v.next())) } -// validateDataSegmentExists rejects a data segment the module does not -// declare. +// validateDataSegmentExists rejects a data segment the module does not declare. func (v *validator) validateDataSegmentExists(dataIndex uint32) error { if v.dataCount == nil { // A data section without the count section that must accompany it is @@ -1601,8 +1600,8 @@ func toValueType(code uint64) ValueType { } } -// validateMemoryLimits checks a declared memory against the page count the -// spec permits before applying the host's own, possibly lower, ceiling. +// validateMemoryLimits checks a declared memory against the page count the spec +// permits before applying the host's own, possibly lower, ceiling. func validateMemoryLimits(limits Limits, configuredMax uint32) error { if limits.Min > specMaxMemoryPages || (limits.Max != nil && *limits.Max > specMaxMemoryPages) { From 02b370291abad2c151f182593ddb1e2fa0c609f6 Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sun, 9 Aug 2026 00:06:44 +0200 Subject: [PATCH 12/13] more more comments --- internal/spec_tests/spec_test_runner.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/internal/spec_tests/spec_test_runner.go b/internal/spec_tests/spec_test_runner.go index 5595aaf..8f0ac04 100644 --- a/internal/spec_tests/spec_test_runner.go +++ b/internal/spec_tests/spec_test_runner.go @@ -41,11 +41,10 @@ func newSpecRunner(t *testing.T, wasmDict map[string][]byte) *specTestRunner { importMemoryLimitMax := uint32(2) tableLimitMax := uint32(20) - // Spec tests intentionally declare resources at the WebAssembly spec - // maxima (e.g. tables with Max=2^32-1) to exercise edge cases. Set the - // configured ceilings to the spec maxima so the runner reflects what - // the engine validator must accept by spec, not what hosts ship by - // default. + // Spec tests intentionally declare resources at the WebAssembly spec maxima + // (e.g. tables with Max=2^32-1) to exercise edge cases. Set the configured + // ceilings to the spec maxima so the runner reflects what the engine + // validator must accept by spec, not what hosts ship by default. runtime := epsilon.NewRuntimeWithConfig(epsilon.Config{ MaxCallStackDepth: epsilon.DefaultMaxCallStackDepth, CallStackPreallocationSize: epsilon.DefaultCallStackPreallocationSize, @@ -427,9 +426,9 @@ func scalarMatches(raw, valueType string, actual any) (bool, error) { } const ( - // canonicalNaN32 is the f32 canonical NaN with the sign bit cleared; a - // NaN is arithmetic when its payload is at least the canonical one, i.e. - // when the most significant payload bit is set. + // canonicalNaN32 is the f32 canonical NaN with the sign bit cleared; a NaN is + // arithmetic when its payload is at least the canonical one, i.e. when the + // most significant payload bit is set. canonicalNaN32 = uint32(0x7fc00000) canonicalNaN64 = uint64(0x7ff8000000000000) ) From c5a24ef493a519c190e1bbcaec0821a8e5d8f9e9 Mon Sep 17 00:00:00 2001 From: Andrea Pivetta Date: Sun, 9 Aug 2026 00:16:31 +0200 Subject: [PATCH 13/13] more more comments --- epsilon/imports.go | 4 ++-- epsilon/numeric.go | 6 +++--- epsilon/vm.go | 6 +++--- internal/wabt/wast2json.go | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/epsilon/imports.go b/epsilon/imports.go index 3db7d1e..40599e1 100644 --- a/epsilon/imports.go +++ b/epsilon/imports.go @@ -23,8 +23,8 @@ type resolvedImports struct { globals []*Global } -// resolveImports resolves the imports declared in the given module against -// the provided map of available imports. +// resolveImports resolves the imports declared in the given module against the +// provided map of available imports. func resolveImports( module *moduleDefinition, instance *ModuleInstance, diff --git a/epsilon/numeric.go b/epsilon/numeric.go index 986156f..354077b 100644 --- a/epsilon/numeric.go +++ b/epsilon/numeric.go @@ -137,9 +137,9 @@ func sqrt[T wasmFloat](a T) T { // minF32 returns the wasm minimum of a and b. Go's min propagates an operand // NaN unchanged, which leaves a signaling NaN signaling and varies across -// architectures; the spec requires an arithmetic NaN, and the canonical NaN -// is one. Go's min also cannot be used for the zeros, where the sign decides -// the result rather than the comparison. +// architectures; the spec requires an arithmetic NaN, and the canonical NaN is +// one. Go's min also cannot be used for the zeros, where the sign decides the +// result rather than the comparison. func minF32(a, b float32) float32 { if a != a || b != b { return math.Float32frombits(canonicalNaNF32) diff --git a/epsilon/vm.go b/epsilon/vm.go index 4c1f192..8d2d66c 100644 --- a/epsilon/vm.go +++ b/epsilon/vm.go @@ -1470,9 +1470,9 @@ func (vm *vm) handleCallIndirect(frame *callFrame) error { elementIndex := vm.stack.popInt32() - // An out-of-range table index traps as "undefined element" here, not as - // the "out of bounds table access" the table accessor instructions - // report for the same condition. + // An out-of-range table index traps as "undefined element" here, not as the + // "out of bounds table access" the table accessor instructions report for the + // same condition. tableElement, err := table.Get(elementIndex) if err != nil { return errUndefinedElement diff --git a/internal/wabt/wast2json.go b/internal/wabt/wast2json.go index 9f833b0..ed9ae5a 100644 --- a/internal/wabt/wast2json.go +++ b/internal/wabt/wast2json.go @@ -36,8 +36,8 @@ type Command struct { Action *Action `json:"action,omitempty"` Expected []Value `json:"expected,omitempty"` As string `json:"as,omitempty"` - // Text is the failure reason an assertion expects, present on the - // assert_* commands. + // Text is the failure reason an assertion expects, present on the assert_* + // commands. Text string `json:"text,omitempty"` }