/src/swift-protobuf/FuzzTesting/Sources/FuzzBinaryDelimited/main.swift
Line | Count | Source |
1 | | // Copyright (c) 2014 - 2024 Apple Inc. and the project authors |
2 | | // Licensed under Apache License v2.0 with Runtime Library Exception |
3 | | // |
4 | | // See LICENSE.txt for license information: |
5 | | // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt |
6 | | // |
7 | | // ----------------------------------------------------------------------------- |
8 | | |
9 | | import Foundation |
10 | | import FuzzCommon |
11 | | import SwiftProtobuf |
12 | | |
13 | | // Put a limit on how many messages will be read because oss-fuzz seems |
14 | | // occational timeouts on really large input sets, likely because there is just |
15 | | // too much garbage so things just keep failing to parse. Just need to exercise |
16 | | // things enough to read a few messages in a row. |
17 | | private let kMaxMessages = 50 |
18 | | |
19 | | @_cdecl("LLVMFuzzerTestOneInput") |
20 | 21.6k | public func FuzzDelimited(_ start: UnsafeRawPointer, _ count: Int) -> CInt { |
21 | 21.6k | // No decoding options here, a leading zero is actually valid (zero length message), |
22 | 21.6k | // so we rely on the other Binary fuzz tester to test options, and just let this |
23 | 21.6k | // one focus on issue around framing of the messages on the stream. |
24 | 21.6k | let bytes = UnsafeRawBufferPointer(start: start, count: count) |
25 | 21.6k | let istream = InputStream(data: Data(bytes)) |
26 | 21.6k | istream.open() |
27 | 21.6k | var msgCount = 0 |
28 | 84.5k | while msgCount < kMaxMessages { |
29 | 84.5k | let msg: SwiftProtoTesting_Fuzz_Message? |
30 | 84.5k | do { |
31 | 84.5k | msg = try BinaryDelimited.parse( |
32 | 84.5k | messageType: SwiftProtoTesting_Fuzz_Message.self, |
33 | 84.5k | from: istream, |
34 | 84.5k | extensions: SwiftProtoTesting_Fuzz_FuzzTesting_Extensions |
35 | 84.5k | ) |
36 | 62.8k | msgCount += 1 |
37 | 62.8k | } catch { |
38 | 21.6k | // Error parsing are to be expected since not all input will be well formed. |
39 | 21.6k | break |
40 | 62.8k | } |
41 | 62.8k | // Test serialization for completeness. |
42 | 62.8k | // If a message was parsed, it should not fail to serialize, so assert as such. |
43 | 62.8k | if let msg = msg { |
44 | 62.8k | // Could use one stream for all messages, but since fuzz tests have |
45 | 62.8k | // memory limits, attempt to avoid hitting that limit with a new stream |
46 | 62.8k | // for each output attempt. |
47 | 62.8k | let ostream = OutputStream.toMemory() |
48 | 62.8k | ostream.open() |
49 | 62.8k | try! BinaryDelimited.serialize(message: msg, to: ostream) |
50 | 62.8k | } |
51 | 62.8k | } |
52 | 21.6k | |
53 | 21.6k | return 0 |
54 | 21.6k | } |