A fast, safe, and efficient CBOR serialization library for Swift on any platform.
swiftpackageindex.com/thecoolwinter/CBOR/1.1.1/documentation/cbor
atproto
swift
cbor
1//
2// fuzz.swift
3// CBOR
4//
5// Created by Khan Winter on 8/29/25.
6//
7
8import CBOR
9#if canImport(FoundationEssentials)
10import FoundationEssentials
11#else
12import Foundation
13#endif
14
15@_optimize(none)
16func blackhole(_ val: some Any) { }
17
18/// Fuzzing entry point
19@_cdecl("LLVMFuzzerTestOneInput")
20public func fuzz(_ start: UnsafeRawPointer, _ count: Int) -> CInt {
21 let bytes = UnsafeRawBufferPointer(start: start, count: count)
22 let data = Data(bytes)
23
24 // Try decoding against a bunch of standard types.
25 // Each attempt is independent — errors are ignored, crashes are what fuzzing is for.
26 func tryDecode<T: Decodable>(_ type: T.Type) {
27 do {
28 blackhole(try CBORDecoder(rejectIndeterminateLengths: false).decode(T.self, from: data))
29 blackhole(try CBORDecoder(rejectIndeterminateLengths: true).decode(T.self, from: data))
30 blackhole(try CBORDecoder(rejectIndeterminateLengths: false).decodeMultiple(T.self, from: data))
31 blackhole(try CBORDecoder(rejectIndeterminateLengths: true).decodeMultiple(T.self, from: data))
32 } catch {
33 // ignore decode errors
34 }
35 }
36
37 // Scalars
38 tryDecode(Bool.self)
39 tryDecode(Int.self)
40 tryDecode(Int8.self)
41 tryDecode(Int16.self)
42 tryDecode(Int32.self)
43 tryDecode(Int64.self)
44 tryDecode(UInt.self)
45 tryDecode(UInt8.self)
46 tryDecode(UInt16.self)
47 tryDecode(UInt32.self)
48 tryDecode(UInt64.self)
49 tryDecode(Float.self)
50 tryDecode(Double.self)
51 tryDecode(String.self)
52 tryDecode(Data.self)
53
54 // Optionals
55 tryDecode(Optional<Int>.self)
56 tryDecode(Optional<String>.self)
57 tryDecode(Optional<Data>.self)
58
59 // Collections
60 tryDecode([Int].self)
61 tryDecode([String].self)
62 tryDecode([Data].self)
63 tryDecode([String: Int].self)
64 tryDecode([String: String].self)
65
66 // Nested combinations
67 tryDecode([[Int]].self)
68 tryDecode([String: [String: Int]].self)
69
70 // Any decodable
71 tryDecode(AnyDecodable.self)
72
73 // Encode
74 do {
75 try blackhole(CBOREncoder().encode(Data(bytes: start, count: count)))
76 try blackhole(DAGCBOREncoder().encode(Data(bytes: start, count: count)))
77 } catch {
78 print("Failed to encode")
79 return -1
80 }
81
82 return 0
83}