Skip to content

Commit 07293bf

Browse files
WasmParser: Fix result type index parsing to use 33-bit signed leb128
1 parent a2f13a3 commit 07293bf

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

Sources/WasmParser/LEB.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func decodeLEB128<IntType, Stream>(
3535

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

5656
// When we don't have enough bit width
57-
if shift > (IntType.bitWidth - 7) {
58-
let remainingBitWidth = IntType.bitWidth - Int(shift)
57+
if shift > (bitWidth - 7) {
58+
let remainingBitWidth = bitWidth - Int(shift)
5959
let continuationBit = (byte & 0b1000_0000) != 0
6060
// When a next byte is expected
6161
if continuationBit {

Sources/WasmParser/WasmParser.swift

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,10 @@ extension WasmParserError.Message {
316316
@usableFromInline static func invalidResultArity(expected: Int, actual: Int) -> Self {
317317
Self("invalid result arity: expected \(expected) but got \(actual)")
318318
}
319+
320+
@usableFromInline static func invalidFunctionType(_ index: Int64) -> Self {
321+
Self("invalid function type index: \(index), expected a unsigned 32-bit integer")
322+
}
319323
}
320324

321325
/// > Note:
@@ -344,6 +348,11 @@ extension ByteStream {
344348
func parseSigned<T: FixedWidthInteger & RawSignedInteger>() throws -> T {
345349
try decodeLEB128(stream: self)
346350
}
351+
352+
@usableFromInline
353+
func parseVarSigned33() throws -> Int64 {
354+
try decodeLEB128(stream: self, bitWidth: 33)
355+
}
347356
}
348357

349358
/// > Note:
@@ -452,7 +461,11 @@ extension Parser {
452461
case 0x7C...0x7F, 0x70, 0x6F:
453462
return try .type(parseValueType())
454463
default:
455-
return try .funcType(TypeIndex(stream.consumeAny()))
464+
let rawIndex = try stream.parseVarSigned33()
465+
guard let index = TypeIndex(exactly: rawIndex) else {
466+
throw makeError(.invalidFunctionType(rawIndex))
467+
}
468+
return .funcType(index)
456469
}
457470
}
458471

0 commit comments

Comments
 (0)