Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/FuzzTargets/Engine.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AuditSupport42import Foundation43import QyvoraMath4445// The in-process fuzz loop run by a worker process (`qyfuzz worker`). The driver (`qyfuzz run`)46// supervises workers: a Swift trap kills the worker, so before every execution the worker copies47// the input into a memory-mapped status file that the driver reads after an abnormal exit.48//49// Feedback, honestly:50// - built with `-sanitize=address -sanitize-coverage=edge,inline-8bit-counters`, the engine keeps51// an input when it reaches a new control-flow edge or a new hit-count bucket of an edge52// (edge-coverage guidance over the instrumented engine modules — our own loop, not libFuzzer);53// - built without these flags it only sees outcome classes (accepted / the error case the harness54// reports): that mode is mutation-based and NOT coverage-guided.5556/// Memory-mapped status shared with the driver: executions (u64) ‖ new-coverage inputs (u32) ‖57/// covered edges (u32) ‖ input length (u32) ‖ phase (u32) ‖ input bytes.58public final class FuzzStatusFile {59 public static let headerSize = 2460 public static let capacity = 1 << 2061 let pointer: UnsafeMutableRawPointer62 let fd: Int326364 public init?(path: String) {65 fd = open(path, O_RDWR | O_CREAT, 0o644)66 guard fd >= 0, ftruncate(fd, off_t(Self.headerSize + Self.capacity)) == 0 else { return nil }67 guard let p = mmap(nil, Self.headerSize + Self.capacity, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0), p != MAP_FAILED else { return nil }68 pointer = p69 }7071 @inline(__always)72 func setInput(_ bytes: Bytes, executions: UInt64) {73 let n = min(bytes.count, Self.capacity)74 pointer.storeBytes(of: executions, toByteOffset: 0, as: UInt64.self)75 pointer.storeBytes(of: UInt32(n), toByteOffset: 16, as: UInt32.self)76 bytes.withUnsafeBytes { src in77 if n > 0 { memcpy(pointer + Self.headerSize, src.baseAddress!, n) }78 }79 }8081 func setProgress(added: UInt32, edges: UInt32, phase: UInt32) {82 pointer.storeBytes(of: added, toByteOffset: 8, as: UInt32.self)83 pointer.storeBytes(of: edges, toByteOffset: 12, as: UInt32.self)84 pointer.storeBytes(of: phase, toByteOffset: 20, as: UInt32.self)85 }8687 public struct Snapshot: Sendable {88 public let executions: UInt6489 public let added: UInt3290 public let edges: UInt3291 public let phase: UInt3292 public let input: Bytes93 }9495 /// Read by the driver from the file (not through the mapping of the worker).96 public static func read(path: String) -> Snapshot? {97 guard let d = FileManager.default.contents(atPath: path), d.count >= headerSize else { return nil }98 let b = Bytes(d.prefix(headerSize))99 func u32(_ o: Int) -> UInt32 { UInt32(b[o]) | UInt32(b[o + 1]) << 8 | UInt32(b[o + 2]) << 16 | UInt32(b[o + 3]) << 24 }100 var e: UInt64 = 0101 for i in (0..<8).reversed() { e = e << 8 | UInt64(b[i]) }102 let n = min(Int(u32(16)), d.count - headerSize)103 return Snapshot(executions: e, added: u32(8), edges: u32(12), phase: u32(20), input: Bytes(d[headerSize..<(headerSize + n)]))104 }105}106107public struct FuzzMutator {108 var rng: AuditRNG109 let target: FuzzTarget110 static let interesting8: [UInt8] = [0, 1, 2, 0x10, 0x20, 0x40, 0x7f, 0x80, 0x81, 0xfc, 0xfd, 0xfe, 0xff]111 static let interesting: [UInt64] = [112 0, 1, 0x7f, 0x80, 0xff, 0x100, 0x7fff, 0x8000, 0xffff, 0x1_0000, 0x7fff_ffff, 0x8000_0000, 0xffff_ffff, 0x1_0000_0000,113 0x7fff_ffff_ffff_ffff, 0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff, 2_100_000_000_000_000, 55, 56, 252, 253,114 ]115 /// Numbers that sit on the edges of the integer and floating-point conversions made by JSON consumers.116 static let textNumbers: [String] = [117 "0", "-1", "1", "255", "256", "65535", "65536", "2147483647", "2147483648", "4294967295", "4294967296", "9007199254740993",118 "9223372036854775807", "9223372036854775808", "18446744073709551615", "18446744073709551616", "2100000000000000", "2100000000000001",119 "1e19", "1e300", "-1e300", "1e-300", "0.5", "-0.0", "1e999", "340282366920938463463374607431768211456",120 "115792089237316195423570985008687907853269984665640564039457584007913129639935", "115792089237316195423570985008687907853269984665640564039457584007913129639936",121 ]122 static let textAlphabet = Bytes("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{}[]()<>\"':;,./\\#*-_+=| \n".utf8)123124 public init(seed: UInt64, target: FuzzTarget) {125 rng = AuditRNG(seed: seed)126 self.target = target127 }128129 mutating func position(_ n: Int) -> Int { n <= 1 ? 0 : rng.int(0...(n - 1)) }130131 mutating func randomByte() -> UInt8 {132 target.text && rng.int(0...9) < 8 ? Self.textAlphabet[position(Self.textAlphabet.count)] : UInt8(truncatingIfNeeded: rng.next())133 }134135 /// One mutation in place. `other` is another corpus entry for splicing.136 mutating func mutateOnce(_ b: inout Bytes, other: Bytes) {137 let choice = rng.int(0...15)138 switch choice {139 case 0 where !b.isEmpty: // bit flip140 b[position(b.count)] ^= 1 << UInt8(rng.int(0...7))141 case 1 where !b.isEmpty: // random byte142 b[position(b.count)] = randomByte()143 case 2 where !b.isEmpty: // interesting byte144 b[position(b.count)] = Self.interesting8[position(Self.interesting8.count)]145 case 3 where !b.isEmpty: // small arithmetic146 let i = position(b.count)147 b[i] = rng.bool() ? b[i] &+ UInt8(rng.int(1...4)) : b[i] &- UInt8(rng.int(1...4))148 case 4: // insert random bytes149 let n = rng.int(1...(rng.bool() ? 4 : 32))150 let at = position(b.count + 1)151 b.insert(contentsOf: (0..<n).map { _ in randomByte() }, at: at)152 case 5 where b.count > 1: // delete a block153 let n = rng.int(1...max(1, min(b.count - 1, rng.bool() ? 4 : 64)))154 let at = position(b.count - n + 1)155 b.removeSubrange(at..<(at + n))156 case 6 where !b.isEmpty: // duplicate a block157 let n = rng.int(1...min(b.count, 64))158 let from = position(b.count - n + 1)159 let block = Bytes(b[from..<(from + n)])160 b.insert(contentsOf: block, at: position(b.count + 1))161 case 7 where !b.isEmpty: // overwrite with an interesting integer, either byte order, 1/2/4/8 bytes162 let width = [1, 2, 4, 8][rng.int(0...3)]163 guard b.count >= width else { return }164 var v = Self.interesting[position(Self.interesting.count)]165 if rng.int(0...3) == 0 { v = v &+ UInt64(rng.int(0...2)) &- 1 }166 let at = position(b.count - width + 1)167 let big = rng.bool()168 for k in 0..<width {169 let shift = UInt64(big ? (width - 1 - k) * 8 : k * 8)170 b[at + k] = UInt8(truncatingIfNeeded: v >> shift)171 }172 case 8 where !other.isEmpty: // splice: head of this, tail of another entry173 let cut = position(b.count + 1), from = position(other.count)174 b = Bytes(b[0..<cut]) + Bytes(other[from...])175 case 9 where !other.isEmpty: // insert a block of another entry176 let n = rng.int(1...min(other.count, 128))177 let from = position(other.count - n + 1)178 b.insert(contentsOf: other[from..<(from + n)], at: position(b.count + 1))179 case 10 where !target.dictionary.isEmpty: // dictionary token: insert or overwrite180 let token = target.dictionary[position(target.dictionary.count)]181 let at = position(b.count + 1)182 if rng.bool() || at + token.count > b.count {183 b.insert(contentsOf: token, at: at)184 } else {185 b.replaceSubrange(at..<(at + token.count), with: token)186 }187 case 11 where b.count > 1: // truncate188 b.removeSubrange(position(b.count)...)189 case 12 where b.count > 1: // swap two bytes190 b.swapAt(position(b.count), position(b.count))191 case 13 where !b.isEmpty: // overwrite a run with one value192 let n = rng.int(1...min(b.count, 16))193 let at = position(b.count - n + 1)194 let v = rng.bool() ? Self.interesting8[position(Self.interesting8.count)] : randomByte()195 for k in 0..<n { b[at + k] = v }196 case 14 where target.text && !b.isEmpty: // decimal numbers found by scanning: one, a few or all replaced by edge values197 var runs = [Range<Int>]()198 var i = 0199 while i < b.count, runs.count < 64 {200 if b[i] >= 0x30, b[i] <= 0x39 {201 var end = i202 while end < b.count, b[end] >= 0x30, b[end] <= 0x39 { end += 1 }203 runs.append(i..<end)204 i = end205 } else {206 i += 1207 }208 }209 guard !runs.isEmpty else {210 b.insert(contentsOf: Self.textNumbers[position(Self.textNumbers.count)].utf8, at: position(b.count + 1))211 return212 }213 let same = rng.bool() ? Self.textNumbers[position(Self.textNumbers.count)] : nil214 let chosen: [Range<Int>]215 switch rng.int(0...3) {216 case 0: chosen = runs // every number217 case 1: chosen = (0..<min(runs.count, rng.int(2...4))).map { _ in runs[position(runs.count)] }218 default: chosen = [runs[position(runs.count)]]219 }220 // replace from the end so earlier ranges stay valid; a range picked twice is replaced once221 for r in Set(chosen.map(\.lowerBound)).sorted(by: >) {222 guard let run = runs.first(where: { $0.lowerBound == r }) else { continue }223 b.replaceSubrange(run, with: (same ?? Self.textNumbers[position(Self.textNumbers.count)]).utf8)224 }225 default:226 if b.isEmpty { b.append(randomByte()) } else { b[position(b.count)] = randomByte() }227 }228 }229230 public mutating func mutate(_ input: Bytes, other: Bytes) -> Bytes {231 var b = input232 let rounds = 1 << rng.int(0...4) // 1, 2, 4, 8 or 16 stacked mutations233 for _ in 0..<rng.int(1...rounds) { mutateOnce(&b, other: other) }234 if b.count > target.maxLength { b.removeSubrange(target.maxLength...) }235 return b236 }237}238239public struct FuzzWorkerOptions: Sendable {240 public var target: String241 public var seed: UInt64242 public var seconds: Double243 public var iterations: UInt64244 public var corpus: URL // committed seeds: <corpus>/<target>/245 public var work: URL // local growth: <work>/corpus/<target>/246 public var status: String247 public var maxSaved = 400248249 public init(target: String, seed: UInt64, seconds: Double, iterations: UInt64, corpus: URL, work: URL, status: String) {250 self.target = target251 self.seed = seed252 self.seconds = seconds253 self.iterations = iterations254 self.corpus = corpus255 self.work = work256 self.status = status257 }258}259260public struct FuzzWorkerSummary: Sendable {261 public var target = ""262 public var seed: UInt64 = 0263 public var executions: UInt64 = 0264 public var seconds = 0.0265 public var corpusLoaded = 0266 public var corpusAdded = 0267 public var coverageGuided = false268 public var edgesCovered = 0269 public var edgesTotal = 0270 public var outcomeClasses = 0271272 public var json: [String: Any] {273 [274 "target": target, "seed": String(seed), "executions": Int(executions), "seconds": (seconds * 100).rounded() / 100,275 "corpus_loaded": corpusLoaded, "corpus_added": corpusAdded, "coverage_guided": coverageGuided, "edges_covered": edgesCovered,276 "edges_total": edgesTotal, "outcome_classes": outcomeClasses,277 ]278 }279}280281public enum FuzzEngine {282 /// Executes one input: outcome reset, coverage reset, harness.283 @inline(__always)284 static func execute(_ target: FuzzTarget, _ input: Bytes) {285 FuzzOutcome.reset()286 if FuzzCoverage.available { FuzzCoverage.reset() }287 target.run(input)288 }289290 /// The fuzz loop of one worker. Returns when the time or iteration budget is spent; a trap ends the process.291 public static func run(_ options: FuzzWorkerOptions) -> FuzzWorkerSummary? {292 guard let target = FuzzRegistry.target(options.target), let status = FuzzStatusFile(path: options.status) else { return nil }293 var summary = FuzzWorkerSummary()294 summary.target = target.name295 summary.seed = options.seed296 summary.coverageGuided = FuzzCoverage.available297 summary.edgesTotal = FuzzCoverage.edgeCount298 status.setInput([], executions: 0)299 status.setProgress(added: 0, edges: 0, phase: 0)300301 // corpus: committed seeds and runtime seeds (the only inputs allowed to be "accepted"), then local growth302 let committed = FuzzFiles.load(options.corpus.appendingPathComponent(target.name)).map(\.bytes)303 let runtime = target.runtimeSeeds?() ?? []304 let workDir = options.work.appendingPathComponent("corpus").appendingPathComponent(target.name)305 let grown = FuzzFiles.load(workDir, limit: 4000).map(\.bytes)306 var trusted = Set<Bytes>()307 for s in committed + runtime { trusted.insert(s) }308 var corpus = [Bytes]()309 var known = Set<Bytes>()310 for s in committed + runtime + grown where !s.isEmpty && s.count <= target.maxLength && known.insert(s).inserted { corpus.append(s) }311 if corpus.isEmpty { corpus.append([0]) }312 summary.corpusLoaded = corpus.count313314 var seen = [UInt8](repeating: 0, count: FuzzCoverage.edgeCount)315 var outcomes = Set<UInt64>()316 var executions: UInt64 = 0317 var edges = 0318319 @inline(__always)320 func runOne(_ input: Bytes) -> Bool {321 executions += 1322 status.setInput(input, executions: executions)323 execute(target, input)324 if target.acceptOnlySeeds, FuzzOutcome.accepted, !trusted.contains(input) {325 fuzzFail("\(target.name): an input that is not a committed valid seed was accepted")326 }327 var interesting = outcomes.insert(FuzzOutcome.current).inserted328 if FuzzCoverage.available {329 let new = FuzzCoverage.collect(into: &seen)330 edges += new.edges331 interesting = new.features > 0 // coverage decides alone when it is available332 }333 return interesting334 }335336 status.setProgress(added: 0, edges: 0, phase: 1)337 for s in corpus { _ = runOne(s) }338 status.setProgress(added: 0, edges: UInt32(edges), phase: 2)339340 var mutator = FuzzMutator(seed: options.seed, target: target)341 let start = Date()342 var saved = 0343 var sinceCheck = 0344 while true {345 if options.iterations > 0, executions >= options.iterations + UInt64(summary.corpusLoaded) { break }346 sinceCheck += 1347 if sinceCheck >= 64 {348 sinceCheck = 0349 if options.seconds > 0, Date().timeIntervalSince(start) >= options.seconds { break }350 }351 // favour recent finds half of the time352 let pick = corpus.count > 16 && mutator.rng.bool() ? corpus.count - 1 - mutator.position(16) : mutator.position(corpus.count)353 let other = corpus[mutator.position(corpus.count)]354 let input = mutator.mutate(corpus[pick], other: other)355 if runOne(input), known.insert(input).inserted {356 corpus.append(input)357 if saved < options.maxSaved {358 FuzzFiles.save(input, in: workDir)359 saved += 1360 }361 status.setProgress(added: UInt32(saved), edges: UInt32(edges), phase: 2)362 }363 }364 status.setInput([], executions: executions)365 status.setProgress(added: UInt32(saved), edges: UInt32(edges), phase: 3)366 summary.executions = executions367 summary.seconds = Date().timeIntervalSince(start)368 summary.corpusAdded = corpus.count - summary.corpusLoaded369 summary.edgesCovered = edges370 summary.outcomeClasses = outcomes.count371 return summary372 }373374 /// Runs one input through a harness in this process (reproduction and replay tests).375 public static func replay(_ target: FuzzTarget, _ input: Bytes) -> (outcome: UInt64, accepted: Bool) {376 FuzzOutcome.reset()377 target.run(Bytes(input.prefix(target.maxLength)))378 return (FuzzOutcome.current, FuzzOutcome.accepted)379 }380}381