Skip to content

Commit

Permalink
WasmParser: Fix result type index parsing to use 33-bit signed leb128
Browse files Browse the repository at this point in the history
  • Loading branch information
kateinoigakukun committed Jan 4, 2025
1 parent a2f13a3 commit 07293bf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
6 changes: 3 additions & 3 deletions Sources/WasmParser/LEB.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func decodeLEB128<IntType, Stream>(

@inlinable
func decodeLEB128<IntType, Stream>(
stream: Stream
stream: Stream, bitWidth: Int = IntType.bitWidth
) throws -> IntType where IntType: FixedWidthInteger, IntType: RawSignedInteger, Stream: ByteStream {
let firstByte = try stream.consumeAny()
var result = IntType.Unsigned(firstByte & 0b0111_1111)
Expand All @@ -54,8 +54,8 @@ func decodeLEB128<IntType, Stream>(
result |= slice << shift

// When we don't have enough bit width
if shift > (IntType.bitWidth - 7) {
let remainingBitWidth = IntType.bitWidth - Int(shift)
if shift > (bitWidth - 7) {
let remainingBitWidth = bitWidth - Int(shift)
let continuationBit = (byte & 0b1000_0000) != 0
// When a next byte is expected
if continuationBit {
Expand Down
15 changes: 14 additions & 1 deletion Sources/WasmParser/WasmParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,10 @@ extension WasmParserError.Message {
@usableFromInline static func invalidResultArity(expected: Int, actual: Int) -> Self {
Self("invalid result arity: expected \(expected) but got \(actual)")
}

@usableFromInline static func invalidFunctionType(_ index: Int64) -> Self {
Self("invalid function type index: \(index), expected a unsigned 32-bit integer")
}
}

/// > Note:
Expand Down Expand Up @@ -344,6 +348,11 @@ extension ByteStream {
func parseSigned<T: FixedWidthInteger & RawSignedInteger>() throws -> T {
try decodeLEB128(stream: self)
}

@usableFromInline
func parseVarSigned33() throws -> Int64 {
try decodeLEB128(stream: self, bitWidth: 33)
}
}

/// > Note:
Expand Down Expand Up @@ -452,7 +461,11 @@ extension Parser {
case 0x7C...0x7F, 0x70, 0x6F:
return try .type(parseValueType())
default:
return try .funcType(TypeIndex(stream.consumeAny()))
let rawIndex = try stream.parseVarSigned33()
guard let index = TypeIndex(exactly: rawIndex) else {
throw makeError(.invalidFunctionType(rawIndex))
}
return .funcType(index)
}
}

Expand Down

0 comments on commit 07293bf

Please sign in to comment.