Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid crash when parsing an empty repeated [packed=true] for fixed-length types #3044

Merged
merged 2 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,12 @@ public final class ProtoReader {
private func decode<T>(into array: inout [T], decode: () throws -> T?) throws {
switch state {
case let .lengthDelimited(length):
guard length > 0 else {
// If the array is empty, there's nothing to do.
state = .tag
return
}

// Preallocate space for the unpacked data.
// It's allowable to have a packed field spread across multiple places
// in the buffer, so add to the existing capacity.
Expand Down
44 changes: 44 additions & 0 deletions wire-runtime-swift/src/test/swift/ProtoReaderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,50 @@ final class ProtoReaderTests: XCTestCase {
}
}

func testDecodePackedRepeatedFixedUInt32Empty() throws {
let data = Foundation.Data(hexEncoded: """
0A // (Tag 1 | Length Delimited)
00 // Length 0
""")!

try test(data: data) { reader in
var values: [UInt64] = []
try reader.decode(tag: 1) { try reader.decode(into: &values, encoding: .fixed) }

XCTAssertEqual(values, [])
}
}

func testDecodePackedRepeatedFixedUInt64() throws {
let data = Foundation.Data(hexEncoded: """
0A // (Tag 1 | Length Delimited)
10 // Length 16
0100000000000000 // Value 1
FFFFFFFFFFFFFFFF // Value UInt64.max
""")!

try test(data: data) { reader in
var values: [UInt64] = []
try reader.decode(tag: 1) { try reader.decode(into: &values, encoding: .fixed) }

XCTAssertEqual(values, [1, .max])
}
}

func testDecodePackedRepeatedFixedUInt64Empty() throws {
let data = Foundation.Data(hexEncoded: """
0A // (Tag 1 | Length Delimited)
00 // Length 0
""")!

try test(data: data) { reader in
var values: [UInt64] = []
try reader.decode(tag: 1) { try reader.decode(into: &values, encoding: .fixed) }

XCTAssertEqual(values, [])
}
}

func testDecodeRepeatedVarintUInt32() throws {
let data = Foundation.Data(hexEncoded: """
08 // (Tag 1 | Varint)
Expand Down