diff --git a/epsilon/imports.go b/epsilon/imports.go index 2fe9366..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, @@ -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/epsilon/numeric.go b/epsilon/numeric.go index 6f7d842..354077b 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 } @@ -138,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/parser.go b/epsilon/parser.go index c5d166b..dc972d3 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 ( @@ -56,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 @@ -95,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 } @@ -116,27 +122,54 @@ 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] } n, err := p.reader.Read(bytes) - if p.bytesRemaining > 0 { - p.bytesRemaining -= int64(n) + p.bytesRemaining -= int64(n) + if n < len(bytes) && err == io.EOF { + 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 { - p.bytesRemaining-- + if err != nil { + if err == io.EOF { + return 0, p.outOfInput() + } + return 0, err + } + p.bytesRemaining-- + 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 { + if p.bytesRemaining == 0 { + return nil } - return b, err + _, 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. @@ -158,18 +191,18 @@ 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 { 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 +215,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 +326,25 @@ 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. + var header [8]byte + magic := header[: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 := header[len(wasmMagicNumber):] + 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 +366,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 +377,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) @@ -364,19 +404,22 @@ 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 + } 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 +457,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() @@ -499,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 } @@ -509,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 } @@ -523,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 } @@ -539,11 +582,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 +680,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 { @@ -792,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 } @@ -802,26 +843,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) { @@ -830,7 +871,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 @@ -848,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 { @@ -855,7 +904,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 @@ -863,12 +912,20 @@ 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) { - 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 } @@ -925,24 +982,23 @@ 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 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. +// 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 // 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 @@ -952,14 +1008,19 @@ func (p *parser) readCode( for { opcodeVal, err := p.readOpcode() if err != nil { - if err == io.EOF { + if err == errSectionTruncated || err == errUnexpectedEnd { + // 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 } lastOp = opcodeVal - currentInstructionStart := len(bytecode) bytecode = append(bytecode, uint64(opcodeVal)) switch opcodeVal { @@ -1198,7 +1259,7 @@ func (p *parser) readCode( // No operands } - if isEnd != nil && isEnd(bytecode[currentInstructionStart:]) { + if stopAtEnd && opcodeVal == end { break } } @@ -1280,16 +1341,17 @@ 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) >= 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 @@ -1351,6 +1413,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 +1444,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..26db919 100644 --- a/epsilon/parser_test.go +++ b/epsilon/parser_test.go @@ -17,7 +17,6 @@ package epsilon import ( "bytes" "errors" - "io" "math" "reflect" "slices" @@ -603,7 +602,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) } @@ -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 9b20759..4df06ed 100644 --- a/epsilon/validation.go +++ b/epsilon/validation.go @@ -20,38 +20,45 @@ 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") + errIllegalOpcode = errors.New("illegal opcode") + 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") + errDataCountSectionRequired = errors.New("data count section required") + errZeroByteExpected = errors.New("zero byte expected") 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, in the "unknown " form the spec +// words these failures. +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() {} @@ -89,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 @@ -122,7 +130,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 +143,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 +158,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 +172,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 } @@ -203,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 @@ -352,8 +364,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 +387,34 @@ func (v *validator) validateConstExpression( return nil } -func (v *validator) isConstantOpcode(op opcode) bool { +// 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 { 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 + } + + if isConstantOpcode(op) { + return nil + } - return !v.importedTypes[globalIndex].IsMutable + // 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 +} +func isConstantOpcode(op opcode) bool { return op == i32Const || op == i64Const || op == f32Const || @@ -678,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) } } @@ -742,7 +772,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 +787,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 +815,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 +824,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 +936,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 +975,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 +984,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] @@ -970,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 { @@ -988,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 { @@ -1018,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 { @@ -1031,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 { @@ -1052,16 +1082,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 +1107,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 +1226,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 +1311,27 @@ 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 { + return v.validateDataSegmentExists(uint32(v.next())) +} + +// validateDataSegmentExists rejects a data segment the module does not declare. +func (v *validator) validateDataSegmentExists(dataIndex uint32) error { if v.dataCount == nil { - return errDataCountNotSet + // 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)) } - - dataIndex := uint32(v.next()) if dataIndex >= *v.dataCount { - return errDataIndexOutOfBounds + return unknownIndex("data segment", uint64(dataIndex)) } return nil } @@ -1349,7 +1383,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 @@ -1374,7 +1408,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 @@ -1405,7 +1439,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 +1600,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 +1624,7 @@ func validateLimits(limits Limits, maximumRange uint32) error { } if limits.Min > *limits.Max { - return errInvalidLimits + return errLimitsMinGreaterThanMax } return nil 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/epsilon/vm.go b/epsilon/vm.go index 8bb55ba..8d2d66c 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..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, @@ -162,13 +161,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) { @@ -223,28 +216,70 @@ 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) } + r.assertFailedWithText(cmd, err) +} + +// 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", + "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 +// 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) + } + 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) { @@ -256,25 +291,19 @@ 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) { 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) { @@ -397,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) ) diff --git a/internal/wabt/wast2json.go b/internal/wabt/wast2json.go index af35f83..ed9ae5a 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 {