diff --git a/USAGE.md b/USAGE.md index f494e9a..6146b4b 100644 --- a/USAGE.md +++ b/USAGE.md @@ -25,6 +25,10 @@ OPTIONS: -z, --zon Optional: export parsed module to .zon format. -s, --seed Optional seed file path (default: fuzzer.seed). -e, --entry Optional harness function name (default: AbsolutionTestOneInput). + --no-post-check Do not assert check_invariant() after the harness returns. + -Z, --zero-symbols ... Zero-symbol list(s); unmatched selectors are reported. + --lenient-zero-symbols ... Shared zero-symbol list(s); unmatched selectors are silent. + -O, --domain-overrides ... Override file(s); unmatched lines are fatal. ... C compiler flags after '--' (e.g. -I path -DFOO -fshort-enums). ``` @@ -319,8 +323,50 @@ LibFuzzer entrypoint that: The generated file does `#undef NDEBUG` before ``, so release flags cannot compile the check out. +The post-condition assumes the harness keeps the globals inside the sampled +domain. A harness that drives the program forward on purpose (for example a +multi-step session started from a reset state) leaves them outside it on every +run. Pass `--no-post-check` (CMake: `NO_POST_CHECK`) to drop the assertion. + ## Tips +### Zero lists and domain overrides + +Most projects only need a few tweaks on top of the discovered model. Instead +of exporting, editing and re-importing a `.zon`, pass them in the same run: + +```bash +absolution -t app.c -o fuzzer.c -r fuzzer.redef \ + -Z zero-symbols.txt --lenient-zero-symbols sdk-zero-symbols.txt \ + -O domain-overrides.txt -- -Iinclude +``` + +A zero list has one selector per line (`#` comments). `g_ctx` matches every +global named `g_ctx`; `g_ctx@src/feature.c` only the one whose source path +contains `src/feature.c`. Matched globals get one all-zero value, so they no +longer consume input bytes. + +An override file has one line per field, applied after the zero lists. A +comment takes a whole line: + +``` +# whole scalar global +appState. = values \x00 \x01 \x02 +txContext.txType = values \x00 \x02 +# re-open a zeroed field +g_ctx.metadata.op_type = top +# every enumerator of a C enum +G_context.state = enum app_state_t +``` + +The selector splits on the first dot (`g.a.b` is field `.a.b` of `g`). Values +are byte strings with `\xNN` escapes, zero-padded to the field element size. +`enum T` takes the enumerators of the C enum `T` (tag or typedef name) found in +the parsed sources. +The order is: `--invariant`, then zero lists, then overrides. `--zon` exports +the tuned model. In CMake, pass `ZERO_SYMBOLS`, `LENIENT_ZERO_SYMBOLS` and +`DOMAIN_OVERRIDES`; editing any of these files regenerates the driver. + ### Exporting and editing invariants ```bash diff --git a/cmake/AbsolutionFuzzer.cmake b/cmake/AbsolutionFuzzer.cmake index 5f40412..442c201 100644 --- a/cmake/AbsolutionFuzzer.cmake +++ b/cmake/AbsolutionFuzzer.cmake @@ -19,8 +19,16 @@ # NAME (required) — name of the fuzzer executable target. # TARGETS (required) — C source files whose globals will be fuzzed. # HARNESS (optional) — C file containing the user's test function. +# EXTRA_SOURCES — more harness-side C files (glue, generated tables): +# linked into the fuzzer, never sampled. # ENTRY (optional) — harness function name (default: AbsolutionTestOneInput). # INVARIANT (optional) — .zon constraint file. +# ZERO_SYMBOLS — zero-symbol list(s); matched globals get one all-zero +# value. Selectors that match nothing are reported. +# LENIENT_ZERO_SYMBOLS — zero-symbol list(s) shared across projects (e.g. an +# SDK list); selectors that match nothing are silent. +# DOMAIN_OVERRIDES — override file(s), '. = values ...|top|enum ', +# applied after the zero lists. Unmatched lines fail. # INCLUDE_DIRECTORIES — extra -I paths for compiling targets. # COMPILE_DEFINITIONS — preprocessor defines (NAME or NAME=VALUE). # COMPILE_OPTIONS — extra compiler flags for compiling targets. @@ -31,6 +39,8 @@ # Non-target names (e.g. -lm) and IMPORTED targets are # linked normally. # SANITIZERS — sanitizer list (default: fuzzer,address). +# NO_POST_CHECK — flag: do not assert check_invariant() after the +# harness (it may leave globals outside the domain). # # Created targets: # ${NAME}_objs — OBJECT library containing compiled target sources. @@ -150,6 +160,33 @@ function(_absolution_collect_all set(${_visited} "${_vis}" PARENT_SCOPE) endfunction() +# ── Model inputs of the generate step ─────────────────────────────────────── +# Resolves the invariant / zero lists / overrides to absolute paths and returns +# the -D arguments for RunAbsolution.cmake plus the files the generate step +# must depend on (editing any of them regenerates the driver). +function(_absolution_model_args _prefix _out_defs _out_deps) + set(_deps "") + set(_inv "") + if(${_prefix}_INVARIANT) + get_filename_component(_inv "${${_prefix}_INVARIANT}" ABSOLUTE) + list(APPEND _deps "${_inv}") + endif() + set(_defs "-DINVARIANT=${_inv}") + foreach(_kind ZERO_SYMBOLS LENIENT_ZERO_SYMBOLS DOMAIN_OVERRIDES) + set(_files "") + foreach(_f ${${_prefix}_${_kind}}) + get_filename_component(_af "${_f}" ABSOLUTE) + list(APPEND _files "${_af}") + list(APPEND _deps "${_af}") + endforeach() + # Lists cross the -P boundary comma-joined. + string(REPLACE ";" "," _csv "${_files}") + list(APPEND _defs "-D${_kind}=${_csv}") + endforeach() + set(${_out_defs} "${_defs}" PARENT_SCOPE) + set(${_out_deps} "${_deps}" PARENT_SCOPE) +endfunction() + # ── Objects the OBJECT library will produce ───────────────────────────────── # $ is only known at generate time, but the renamed copies the # fuzzer links must be named at configure time: count the sources that compile @@ -176,9 +213,9 @@ endfunction() function(absolution_add_fuzzer) cmake_parse_arguments( FUZZ - "" + "NO_POST_CHECK" "NAME;HARNESS;INVARIANT;ENTRY;SANITIZERS" - "TARGETS;COMPILE_OPTIONS;INCLUDE_DIRECTORIES;COMPILE_DEFINITIONS;LINK_LIBRARIES" + "TARGETS;EXTRA_SOURCES;COMPILE_OPTIONS;INCLUDE_DIRECTORIES;COMPILE_DEFINITIONS;LINK_LIBRARIES;ZERO_SYMBOLS;LENIENT_ZERO_SYMBOLS;DOMAIN_OVERRIDES" ${ARGN} ) @@ -290,10 +327,7 @@ $,\n> " ) - set(_abs_inv "") - if(FUZZ_INVARIANT) - get_filename_component(_abs_inv "${FUZZ_INVARIANT}" ABSOLUTE) - endif() + _absolution_model_args(FUZZ _model_defs _model_deps) set(_GENERATE_TARGET "${FUZZ_NAME}_generate") @@ -306,11 +340,12 @@ $,\n> "-DREDEF=${_REDEF_FILE}" "-DSEED=${_SEED_FILE}" "-DENTRY=${FUZZ_ENTRY}" - "-DINVARIANT=${_abs_inv}" + "-DNO_POST_CHECK=${FUZZ_NO_POST_CHECK}" + ${_model_defs} "-DFLAGS_FILE=${_FLAGS_FILE}" "-DWORK_DIR=${CMAKE_SOURCE_DIR}" -P "${_ABSOLUTION_MODULE_DIR}/RunAbsolution.cmake" - DEPENDS "${ABSOLUTION_EXECUTABLE}" ${_ABS_TARGETS} $ "${_FLAGS_FILE}" "${_TARGETS_FILE}" + DEPENDS "${ABSOLUTION_EXECUTABLE}" ${_ABS_TARGETS} $ "${_FLAGS_FILE}" "${_TARGETS_FILE}" ${_model_deps} WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" COMMENT "[absolution] Generating harness for ${FUZZ_NAME}" VERBATIM @@ -381,6 +416,9 @@ $,\n> if(FUZZ_HARNESS) target_sources(${FUZZ_NAME} PRIVATE "${FUZZ_HARNESS}") endif() + if(FUZZ_EXTRA_SOURCES) + target_sources(${FUZZ_NAME} PRIVATE ${FUZZ_EXTRA_SOURCES}) + endif() target_compile_options(${FUZZ_NAME} PRIVATE -g "-fsanitize=${FUZZ_SANITIZERS}") target_link_options(${FUZZ_NAME} PRIVATE "-fsanitize=${FUZZ_SANITIZERS}") diff --git a/cmake/RunAbsolution.cmake b/cmake/RunAbsolution.cmake index 59e8a99..4f4bf2b 100644 --- a/cmake/RunAbsolution.cmake +++ b/cmake/RunAbsolution.cmake @@ -8,6 +8,9 @@ # SEED — output .seed path # ENTRY — entry function name # INVARIANT — (optional) invariant file path +# ZERO_SYMBOLS / LENIENT_ZERO_SYMBOLS / DOMAIN_OVERRIDES +# — (optional) comma-joined file lists +# NO_POST_CHECK— (optional) TRUE to pass --no-post-check # FLAGS_FILE — one compiler flag per line (-Ipath, -DFOO, -std=c99 …) # WORK_DIR — CMAKE_SOURCE_DIR (absolution resolves targets relative to this) @@ -28,6 +31,17 @@ list(APPEND _cmd if(INVARIANT) list(APPEND _cmd -i "${INVARIANT}") endif() +foreach(_pair "ZERO_SYMBOLS;-Z" "LENIENT_ZERO_SYMBOLS;--lenient-zero-symbols" "DOMAIN_OVERRIDES;-O") + list(GET _pair 0 _var) + list(GET _pair 1 _opt) + string(REPLACE "," ";" _files "${${_var}}") + foreach(_f ${_files}) + list(APPEND _cmd "${_opt}" "${_f}") + endforeach() +endforeach() +if(NO_POST_CHECK) + list(APPEND _cmd --no-post-check) +endif() list(APPEND _cmd --) foreach(_f ${_flags}) list(APPEND _cmd "${_f}") diff --git a/src/Parser.zig b/src/Parser.zig index a568111..a23ac6d 100644 --- a/src/Parser.zig +++ b/src/Parser.zig @@ -13,6 +13,8 @@ const type_flatten = @import("type_flatten.zig"); pub const Domain = ir.Domain; pub const Field = ir.Field; pub const Global = ir.Global; +/// Enumerator values by enum tag and by typedef name. +pub const EnumTable = std.StringHashMapUnmanaged([]const i128); const ParseError = std.mem.Allocator.Error; const FieldsBuilder = std.ArrayListUnmanaged(Field); @@ -32,6 +34,8 @@ toolchain: aro.Toolchain, builtin_source: aro.Source = undefined, command_line_source: aro.Source = undefined, compat_source: aro.Source = undefined, +/// Filled by `collectGlobals`, owned by `arena`. +enums: EnumTable = .empty, /// Initialize the parser, discover the toolchain, and prime diagnostics. /// Args: @@ -217,9 +221,42 @@ pub fn collectGlobals(p: *Parser, paths: []const []const u8) !std.ArrayList(Glob var tree = try pp.parse(); defer tree.deinit(); + try collectEnumsFromTree(p, tree); return try collectGlobalsFromTree(p.toolchain.driver.comp, tree, p.gpa); } +/// Record every complete enum reachable from a top-level declaration, under its +/// tag and under each typedef name that aliases it. +fn collectEnumsFromTree(p: *Parser, tree: aro.Tree) !void { + const comp = tree.comp; + for (tree.root_decls.items) |idx| { + const node = idx.get(&tree); + const qt, const alias: ?[]const u8 = switch (node) { + .enum_decl => |d| .{ d.container_qt, null }, + .typedef => |t| .{ t.qt, tree.tokSlice(t.name_tok) }, + else => continue, + }; + const e = switch (qt.base(comp).type) { + .@"enum" => |e| e, + else => continue, + }; + if (e.incomplete) continue; + const decl = switch (e.decl_node.get(&tree)) { + .enum_decl => |d| d, + else => continue, + }; + + const name = alias orelse if (e.isAnonymous(comp)) continue else e.name.lookup(comp); + const vals = try p.arena.alloc(i128, decl.fields.len); + const complete = for (decl.fields, vals) |field_node, *v| { + const val = tree.value_map.get(field_node) orelse break false; + v.* = val.toInt(i128, comp) orelse break false; + } else true; + if (!complete) continue; + try p.enums.put(p.arena, try p.arena.dupe(u8, name), vals); + } +} + /// Go through an entire Tree and extracts its globals. /// Non-static globals that have already been seen (tracked via `seen_globals`) /// are skipped to avoid duplicate extern declarations in the generated fuzzer. diff --git a/src/Tuning.zig b/src/Tuning.zig new file mode 100644 index 0000000..41c1aba --- /dev/null +++ b/src/Tuning.zig @@ -0,0 +1,393 @@ +//! Build-time tuning of the discovered model: zero lists and domain overrides. +//! +//! Both are applied to the parsed globals in the same run that generates the +//! harness, after the optional `.zon` invariant, so the sampler and the exported +//! `.zon` already carry the tuned domains. No second generate-and-rebuild pass. +//! +//! Zero list (one selector per line, `#` comments): +//! +//! g_ctx every global named g_ctx +//! g_ctx@src/feature.c only the one whose source path contains src/feature.c +//! +//! A matched global gets a single all-zero `whole_values` candidate on every +//! field, so it leaves the fuzzable prefix without consuming input bytes. +//! +//! Domain overrides (one per line, `#` comments): +//! +//! appState. = values \x00 \x01 \x02 +//! txContext.txType = values \x00 \x01 \x02 \x04 \xc0 +//! challenge. = top +//! G_context.state = enum app_state_t +//! +//! The selector splits on the first dot: `g.a.b` is field `.a.b` of global `g`, +//! `g.` is the whole scalar. Each value is a byte string (`\xNN` escapes); the +//! emitter zero-pads values shorter than the field element. `enum T` takes the +//! enumerators of the C enum `T` (tag or typedef name) found in the parsed +//! sources, encoded little-endian at the field's width. + +const std = @import("std"); +const ir = @import("cgen/ir.zig"); +const Parser = @import("Parser.zig"); + +pub const ZeroSymbol = struct { + name: []const u8, + source: ?[]const u8, + /// Selectors from a lenient list are not reported when they match nothing. + lenient: bool, +}; + +pub const Override = struct { + global: []const u8, + field: []const u8, + domain: ir.Domain, + /// Set for `= enum T`; `apply` resolves it into a `values` domain. + enum_type: ?[]const u8 = null, + file: []const u8, + line: usize, +}; + +pub const ParseError = error{InvalidOverride} || std.mem.Allocator.Error; + +/// Parse a zero-symbol list. +pub fn parseZeroSymbols(arena: std.mem.Allocator, text: []const u8, lenient: bool) ![]ZeroSymbol { + var out: std.ArrayList(ZeroSymbol) = .empty; + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0 or line[0] == '#') continue; + if (std.mem.indexOfScalar(u8, line, '@')) |at| { + try out.append(arena, .{ + .name = std.mem.trim(u8, line[0..at], " \t"), + .source = std.mem.trim(u8, line[at + 1 ..], " \t"), + .lenient = lenient, + }); + } else { + try out.append(arena, .{ .name = line, .source = null, .lenient = lenient }); + } + } + return out.toOwnedSlice(arena); +} + +/// Decode one value token: `\xNN` and `\\` escapes, every other byte literal. +pub fn decodeValue(arena: std.mem.Allocator, token: []const u8) ParseError![]const u8 { + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < token.len) { + if (token[i] == '\\' and i + 1 < token.len) { + if (token[i + 1] == 'x') { + if (i + 4 > token.len) return error.InvalidOverride; + const byte = std.fmt.parseInt(u8, token[i + 2 .. i + 4], 16) catch return error.InvalidOverride; + try out.append(arena, byte); + i += 4; + continue; + } + if (token[i + 1] == '\\') { + try out.append(arena, '\\'); + i += 2; + continue; + } + } + try out.append(arena, token[i]); + i += 1; + } + return out.toOwnedSlice(arena); +} + +/// Parse a domain-overrides file. `file` is kept for diagnostics. +pub fn parseOverrides(arena: std.mem.Allocator, text: []const u8, file: []const u8) ParseError![]Override { + var out: std.ArrayList(Override) = .empty; + var lines = std.mem.splitScalar(u8, text, '\n'); + var line_no: usize = 0; + while (lines.next()) |raw| { + line_no += 1; + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0 or line[0] == '#') continue; + + const eq = std.mem.indexOfScalar(u8, line, '=') orelse { + std.debug.print("{s}:{d}: error: expected '. = values ...|top|enum '\n", .{ file, line_no }); + return error.InvalidOverride; + }; + const selector = std.mem.trim(u8, line[0..eq], " \t"); + const dot = std.mem.indexOfScalar(u8, selector, '.') orelse { + std.debug.print("{s}:{d}: error: selector '{s}' has no '.' (use '{s}.' for the whole global)\n", .{ file, line_no, selector, selector }); + return error.InvalidOverride; + }; + const global = selector[0..dot]; + const field = try std.fmt.allocPrint(arena, ".{s}", .{selector[dot + 1 ..]}); + + var rhs = std.mem.tokenizeAny(u8, line[eq + 1 ..], " \t"); + const kind = rhs.next() orelse { + std.debug.print("{s}:{d}: error: missing domain after '='\n", .{ file, line_no }); + return error.InvalidOverride; + }; + + var domain: ir.Domain = undefined; + var enum_type: ?[]const u8 = null; + if (std.mem.eql(u8, kind, "top")) { + if (rhs.next() != null) { + std.debug.print("{s}:{d}: error: 'top' takes no values\n", .{ file, line_no }); + return error.InvalidOverride; + } + domain = .top; + } else if (std.mem.eql(u8, kind, "values")) { + var vals: std.ArrayList([]const u8) = .empty; + while (rhs.next()) |tok| { + const v = decodeValue(arena, tok) catch { + std.debug.print("{s}:{d}: error: bad value '{s}'\n", .{ file, line_no, tok }); + return error.InvalidOverride; + }; + try vals.append(arena, v); + } + if (vals.items.len == 0) { + std.debug.print("{s}:{d}: error: 'values' needs at least one value\n", .{ file, line_no }); + return error.InvalidOverride; + } + domain = .{ .values = try vals.toOwnedSlice(arena) }; + } else if (std.mem.eql(u8, kind, "enum")) { + enum_type = rhs.next(); + if (enum_type == null or rhs.next() != null) { + std.debug.print("{s}:{d}: error: 'enum' takes exactly one type name\n", .{ file, line_no }); + return error.InvalidOverride; + } + domain = .top; + } else { + std.debug.print("{s}:{d}: error: unknown domain '{s}' (expected 'values', 'top' or 'enum')\n", .{ file, line_no, kind }); + return error.InvalidOverride; + } + + try out.append(arena, .{ + .global = global, + .field = field, + .domain = domain, + .enum_type = enum_type, + .file = file, + .line = line_no, + }); + } + return out.toOwnedSlice(arena); +} + +pub const Report = struct { + total: usize, + zeroed: usize, + overridden: usize, + /// Strict zero selectors that matched no global (misspelled or renamed). + stale_zeros: []const ZeroSymbol, + /// Overrides that matched no field. The caller treats these as fatal. + unmatched: []const Override, +}; + +fn zeroMatches(z: ZeroSymbol, g: Parser.Global) bool { + if (!std.mem.eql(u8, z.name, g.name)) return false; + const src = z.source orelse return true; + return std.mem.indexOf(u8, g.source_file, src) != null; +} + +/// One little-endian `width`-byte value per distinct enumerator. +fn enumDomain(arena: std.mem.Allocator, values: []const i128, width: usize) !ir.Domain { + var out: std.ArrayList([]const u8) = .empty; + next: for (values) |v| { + const b = try arena.alloc(u8, width); + var x: u128 = @bitCast(v); + for (b) |*byte| { + byte.* = @truncate(x); + x >>= 8; + } + for (out.items) |seen| if (std.mem.eql(u8, seen, b)) continue :next; + try out.append(arena, b); + } + return .{ .values = try out.toOwnedSlice(arena) }; +} + +/// Apply zero lists, then overrides (overrides win), to `globals` in place. +/// `enums` resolves `= enum T` overrides. +pub fn apply( + arena: std.mem.Allocator, + globals: []Parser.Global, + zeros: []const ZeroSymbol, + overrides: []const Override, + enums: *const Parser.EnumTable, +) !Report { + const zero_hit = try arena.alloc(bool, zeros.len); + @memset(zero_hit, false); + const override_hit = try arena.alloc(bool, overrides.len); + @memset(override_hit, false); + + var zeroed: usize = 0; + for (globals) |*g| { + var matched = false; + for (zeros, 0..) |z, zi| { + if (zeroMatches(z, g.*)) { + zero_hit[zi] = true; + matched = true; + } + } + if (!matched) continue; + zeroed += 1; + for (g.fields) |*f| { + if (f.is_padding) continue; + const blob = try arena.alloc(u8, ir.wholeFieldBytes(f.*)); + @memset(blob, 0); + const blobs = try arena.alloc([]const u8, 1); + blobs[0] = blob; + f.domain = .{ .whole_values = blobs }; + } + } + + var overridden: usize = 0; + for (overrides, 0..) |o, oi| { + const enum_vals = if (o.enum_type) |t| enums.get(t) orelse { + std.debug.print("{s}:{d}: error: enum '{s}' not found in the parsed sources\n", .{ o.file, o.line, t }); + return error.UnknownEnum; + } else null; + for (globals) |*g| { + if (!std.mem.eql(u8, g.name, o.global)) continue; + for (g.fields) |*f| { + if (f.is_padding or !std.mem.eql(u8, f.name, o.field)) continue; + const domain = if (enum_vals) |vals| try enumDomain(arena, vals, ir.elementBytes(f.*)) else o.domain; + try f.updateDomain(arena, domain); + override_hit[oi] = true; + overridden += 1; + } + } + } + + var stale: std.ArrayList(ZeroSymbol) = .empty; + for (zeros, zero_hit) |z, hit| { + if (!hit and !z.lenient) try stale.append(arena, z); + } + var unmatched: std.ArrayList(Override) = .empty; + for (overrides, override_hit) |o, hit| { + if (!hit) try unmatched.append(arena, o); + } + + return .{ + .total = globals.len, + .zeroed = zeroed, + .overridden = overridden, + .stale_zeros = try stale.toOwnedSlice(arena), + .unmatched = try unmatched.toOwnedSlice(arena), + }; +} + +fn testGlobal(alloc: std.mem.Allocator, name: []const u8, src: []const u8, field_names: []const []const u8) !Parser.Global { + const fields = try alloc.alloc(Parser.Field, field_names.len); + for (field_names, 0..) |fname, i| { + fields[i] = .{ .name = try alloc.dupe(u8, fname), .bit_width = 8, .domain = .top }; + } + return .{ + .name = try alloc.dupe(u8, name), + .source_file = try alloc.dupe(u8, src), + .size_bytes = field_names.len, + .is_static = false, + .dims = &.{}, + .fields = fields, + }; +} + +test "decodeValue handles hex escapes and literals" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try std.testing.expectEqualSlices(u8, &.{ 0x00, 0xc0 }, try decodeValue(a, "\\x00\\xc0")); + try std.testing.expectEqualSlices(u8, "ab", try decodeValue(a, "ab")); + try std.testing.expectEqualSlices(u8, "\\", try decodeValue(a, "\\\\")); + try std.testing.expectError(error.InvalidOverride, decodeValue(a, "\\xZZ")); + try std.testing.expectError(error.InvalidOverride, decodeValue(a, "\\x0")); +} + +test "parseOverrides splits the selector on the first dot" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ovs = try parseOverrides(a, + \\# comment + \\appState. = values \x00 \x01 + \\g_ctx.metadata.op_type = top + , "test"); + try std.testing.expectEqual(@as(usize, 2), ovs.len); + try std.testing.expectEqualStrings("appState", ovs[0].global); + try std.testing.expectEqualStrings(".", ovs[0].field); + try std.testing.expectEqual(@as(usize, 2), ovs[0].domain.values.len); + try std.testing.expectEqualStrings("g_ctx", ovs[1].global); + try std.testing.expectEqualStrings(".metadata.op_type", ovs[1].field); + try std.testing.expect(ovs[1].domain == .top); +} + +test "parseOverrides rejects unknown domains" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + try std.testing.expectError(error.InvalidOverride, parseOverrides(arena.allocator(), "g. = maybe", "test")); + try std.testing.expectError(error.InvalidOverride, parseOverrides(arena.allocator(), "g. = enum", "test")); + try std.testing.expectError(error.InvalidOverride, parseOverrides(arena.allocator(), "g. = enum a b", "test")); +} + +test "apply resolves enum overrides at the field width" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + + var globals = [_]Parser.Global{try testGlobal(a, "g_ctx", "src/app.c", &.{ ".state", ".mode" })}; + globals[0].fields[0].bit_width = 16; + + var enums: Parser.EnumTable = .empty; + try enums.put(a, "state_t", &.{ 0, 0x102, 0x102, -1 }); + + const ovs = try parseOverrides(a, + \\g_ctx.state = enum state_t + \\g_ctx.mode = enum state_t + , "test"); + try std.testing.expectEqualStrings("state_t", ovs[0].enum_type.?); + _ = try apply(a, &globals, &.{}, ovs, &enums); + + // Duplicates collapse; values are little-endian at each field's width. + const st = globals[0].fields[0].domain.values; + try std.testing.expectEqual(@as(usize, 3), st.len); + try std.testing.expectEqualSlices(u8, &.{ 0x00, 0x00 }, st[0]); + try std.testing.expectEqualSlices(u8, &.{ 0x02, 0x01 }, st[1]); + try std.testing.expectEqualSlices(u8, &.{ 0xff, 0xff }, st[2]); + try std.testing.expectEqual(@as(usize, 3), globals[0].fields[1].domain.values.len); + + const bad = try parseOverrides(a, "g_ctx.state = enum nope_t", "test"); + try std.testing.expectError(error.UnknownEnum, apply(a, &globals, &.{}, bad, &enums)); +} + +test "apply zeroes, then overrides, and reports leftovers" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + + var globals = [_]Parser.Global{ + try testGlobal(a, "g_state", "src/app.c", &.{"."}), + try testGlobal(a, "g_ctx", "src/feature.c", &.{ ".a", ".b" }), + try testGlobal(a, "g_ctx", "src/other.c", &.{ ".a", ".b" }), + }; + + const zeros = try parseZeroSymbols(a, + \\g_ctx@src/feature.c + \\g_missing + , false); + const lenient = try parseZeroSymbols(a, "g_not_in_this_app", true); + const all_zeros = try std.mem.concat(a, ZeroSymbol, &.{ zeros, lenient }); + + const ovs = try parseOverrides(a, + \\g_state. = values \x00 \x01 + \\g_ctx.b = top + \\g_ctx.nope = top + , "test"); + + const rep = try apply(a, &globals, all_zeros, ovs, &.empty); + + try std.testing.expectEqual(@as(usize, 1), rep.zeroed); + try std.testing.expect(globals[0].fields[0].domain == .values); + // feature.c's g_ctx: .a zeroed, .b re-opened by the override. + try std.testing.expect(globals[1].fields[0].domain == .whole_values); + try std.testing.expect(globals[1].fields[1].domain == .top); + // other.c's g_ctx is not zeroed. + try std.testing.expect(globals[2].fields[0].domain == .top); + + try std.testing.expectEqual(@as(usize, 1), rep.stale_zeros.len); + try std.testing.expectEqualStrings("g_missing", rep.stale_zeros[0].name); + try std.testing.expectEqual(@as(usize, 1), rep.unmatched.len); + try std.testing.expectEqualStrings(".nope", rep.unmatched[0].field); +} diff --git a/src/cgen/emit.zig b/src/cgen/emit.zig index d714388..054e6cb 100644 --- a/src/cgen/emit.zig +++ b/src/cgen/emit.zig @@ -240,6 +240,7 @@ fn emitDomainTables(io: std.Io, globals: []const Parser.Global, file: *std.Io.Fi /// Generate the complete fuzzer C file and `objcopy` redefinition file. /// Writes includes, extern/weak declarations, sampler, checker, and libFuzzer entrypoint. +/// `post_check` emits the `check_invariant()` assertion after the harness call. pub fn writeFuzzerC( allocator: std.mem.Allocator, io: std.Io, @@ -249,6 +250,7 @@ pub fn writeFuzzerC( redef_path: []const u8, entry_name: []const u8, func_symbols: []const []const u8, + post_check: bool, ) !void { var file = try std.Io.Dir.cwd().createFile(io, out_path, .{ .truncate = true }); defer file.close(io); @@ -305,7 +307,7 @@ pub fn writeFuzzerC( try emitDomainTables(io, globals, &file); try emitSampler(allocator, io, globals, &file); try emitChecker(allocator, io, globals, &file); - try emitEntrypoint(allocator, io, &file, entry_name); + try emitEntrypoint(allocator, io, &file, entry_name, post_check); } /// Emit `sample_invariant()` — reads fuzzer input bytes and hydrates globals @@ -773,7 +775,9 @@ fn emitChecker(allocator: std.mem.Allocator, io: std.Io, globals: []const Parser } /// Emit the libFuzzer entrypoint that wires sampling, harness, and checks. -fn emitEntrypoint(allocator: std.mem.Allocator, io: std.Io, file: *std.Io.File, entry_name: []const u8) !void { +/// Without `post_check` the harness may leave the globals outside the sampled +/// domain (e.g. a multi-step session that drives the app forward). +fn emitEntrypoint(allocator: std.mem.Allocator, io: std.Io, file: *std.Io.File, entry_name: []const u8, post_check: bool) !void { try file.writeStreamingAll(io, \\int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { \\ ptrdiff_t consumed = sample_invariant(data, size); @@ -787,12 +791,20 @@ fn emitEntrypoint(allocator: std.mem.Allocator, io: std.Io, file: *std.Io.File, defer allocator.free(call_line); try file.writeStreamingAll(io, call_line); - try file.writeStreamingAll(io, - \\ if (res == -1) return 0; - \\ assert(check_invariant() == 0); - \\ return 0; - \\} - ); + if (post_check) { + try file.writeStreamingAll(io, + \\ if (res == -1) return 0; + \\ assert(check_invariant() == 0); + \\ return 0; + \\} + ); + } else { + try file.writeStreamingAll(io, + \\ (void)res; + \\ return 0; + \\} + ); + } } fn readTmpFile(tmp: *std.testing.TmpDir, name: []const u8, buf: []u8) ![]const u8 { @@ -1485,7 +1497,7 @@ test "emitEntrypoint generates LLVMFuzzerTestOneInput" { defer tmp.cleanup(); var file = try createTmpFile(&tmp, "t.c"); defer file.close(io); - try emitEntrypoint(alloc, io, &file, "MyHarness"); + try emitEntrypoint(alloc, io, &file, "MyHarness", true); var buf: [2048]u8 = undefined; const out = try readTmpFile(&tmp, "t.c", &buf); try std.testing.expect(std.mem.indexOf(u8, out, "LLVMFuzzerTestOneInput") != null); @@ -1494,6 +1506,20 @@ test "emitEntrypoint generates LLVMFuzzerTestOneInput" { try std.testing.expect(std.mem.indexOf(u8, out, "check_invariant()") != null); } +test "emitEntrypoint without post_check skips check_invariant" { + const io = std.testing.io; + const alloc = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var file = try createTmpFile(&tmp, "t.c"); + defer file.close(io); + try emitEntrypoint(alloc, io, &file, "MyHarness", false); + var buf: [2048]u8 = undefined; + const out = try readTmpFile(&tmp, "t.c", &buf); + try std.testing.expect(std.mem.indexOf(u8, out, "MyHarness(data, size)") != null); + try std.testing.expect(std.mem.indexOf(u8, out, "check_invariant()") == null); +} + test "writeFuzzerC end-to-end produces valid output" { const io = std.testing.io; const alloc = std.testing.allocator; @@ -1530,7 +1556,7 @@ test "writeFuzzerC end-to-end produces valid output" { .fields = fields, }}; - try writeFuzzerC(alloc, io, globals, 4, out_path, redef_path, "TestHarness", &.{}); + try writeFuzzerC(alloc, io, globals, 4, out_path, redef_path, "TestHarness", &.{}, true); var buf: [16384]u8 = undefined; const out = try readTmpFile(&tmp, "fuzzer.c", &buf); @@ -1570,7 +1596,7 @@ test "writeFuzzerC with static global writes redef file" { .fields = fields, }}; - try writeFuzzerC(alloc, io, globals, 1, out_path, redef_path, "TestEntry", &.{}); + try writeFuzzerC(alloc, io, globals, 1, out_path, redef_path, "TestEntry", &.{}, true); var buf: [4096]u8 = undefined; const redef_out = try readTmpFile(&tmp, "fuzzer2.redef", &buf); @@ -1594,7 +1620,7 @@ test "writeFuzzerC with func_symbols emits extern declarations" { defer alloc.free(redef_path); const globals: []const Parser.Global = &.{}; - try writeFuzzerC(alloc, io, globals, 0, out_path, redef_path, "Entry", &.{"my_handler"}); + try writeFuzzerC(alloc, io, globals, 0, out_path, redef_path, "Entry", &.{"my_handler"}, true); var buf: [8192]u8 = undefined; const c_out = try readTmpFile(&tmp, "fuzzer3.c", &buf); diff --git a/src/main.zig b/src/main.zig index b589fba..0137a76 100644 --- a/src/main.zig +++ b/src/main.zig @@ -23,6 +23,9 @@ pub fn main(init: std.process.Init) !void { const opts = parseArgs(gpa, io, init.minimal.args) catch return; defer gpa.free(opts.targets); defer gpa.free(opts.cflags); + defer gpa.free(opts.zero_symbols); + defer gpa.free(opts.lenient_zero_symbols); + defer gpa.free(opts.domain_overrides); // Parser setup var parser = try absolution.Parser.init(gpa, arena, io, opts.cflags); @@ -50,13 +53,17 @@ pub fn main(init: std.process.Init) !void { func_symbols = res.func_symbols; } + if (opts.zero_symbols.len + opts.lenient_zero_symbols.len + opts.domain_overrides.len > 0) { + try applyTuning(gpa, io, arena, globals.items, &parser.enums, opts); + } + try ir.validateGlobalsDomains(globals.items); // Compute needed bytes const needed_bytes = seed.neededBytesFromGlobals(globals.items); // Code generation - try emit.writeFuzzerC(gpa, io, globals.items, needed_bytes, opts.out_c, opts.redef, opts.entry, func_symbols); + try emit.writeFuzzerC(gpa, io, globals.items, needed_bytes, opts.out_c, opts.redef, opts.entry, func_symbols, opts.post_check); // Optional: Save invariant to file if (opts.zon) |zon_path| try writeInvariant(gpa, io, globals.items, zon_path); @@ -65,6 +72,50 @@ pub fn main(init: std.process.Init) !void { if (opts.seed) |seed_path| try seed.writeSeed(io, seed_path, needed_bytes); } +fn readAll(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, path: []const u8) ![]const u8 { + const bytes = std.Io.Dir.cwd().readFileAllocOptions(io, path, gpa, .unlimited, .@"1", null) catch |err| { + std.debug.print("error: cannot read {s}: {s}\n", .{ path, @errorName(err) }); + return err; + }; + defer gpa.free(bytes); + return arena.dupe(u8, bytes); +} + +/// Zero lists and domain overrides, applied in this run so the emitted sampler +/// and the exported `.zon` are already tuned. +fn applyTuning(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, globals: []Global, enums: *const absolution.Parser.EnumTable, opts: Options) !void { + const Tuning = absolution.Tuning; + var zeros: std.ArrayList(Tuning.ZeroSymbol) = .empty; + for (opts.zero_symbols) |path| { + try zeros.appendSlice(arena, try Tuning.parseZeroSymbols(arena, try readAll(gpa, io, arena, path), false)); + } + for (opts.lenient_zero_symbols) |path| { + try zeros.appendSlice(arena, try Tuning.parseZeroSymbols(arena, try readAll(gpa, io, arena, path), true)); + } + var overrides: std.ArrayList(Tuning.Override) = .empty; + for (opts.domain_overrides) |path| { + try overrides.appendSlice(arena, try Tuning.parseOverrides(arena, try readAll(gpa, io, arena, path), path)); + } + + const rep = try Tuning.apply(arena, globals, zeros.items, overrides.items, enums); + std.debug.print("tuning: {d} globals ({d} zeroed, {d} fuzzable), {d} override(s) applied\n", .{ + rep.total, rep.zeroed, rep.total - rep.zeroed, rep.overridden, + }); + for (rep.stale_zeros) |z| { + if (z.source) |src| { + std.debug.print("warning: zero symbol '{s}@{s}' matched no global\n", .{ z.name, src }); + } else { + std.debug.print("warning: zero symbol '{s}' matched no global\n", .{z.name}); + } + } + if (rep.unmatched.len > 0) { + for (rep.unmatched) |o| { + std.debug.print("{s}:{d}: error: override '{s}{s}' matched no field\n", .{ o.file, o.line, o.global, o.field }); + } + return error.UnmatchedOverride; + } +} + fn writeInvariant(allocator: std.mem.Allocator, io: std.Io, globals: []const Global, zon_path: []const u8) !void { var aw: std.Io.Writer.Allocating = .init(allocator); try std.zon.stringify.serialize(globals, .{ .whitespace = true }, &aw.writer); @@ -84,6 +135,10 @@ const Options = struct { zon: ?[]const u8, seed: ?[]const u8, entry: []const u8, + post_check: bool, + zero_symbols: []const []const u8, + lenient_zero_symbols: []const []const u8, + domain_overrides: []const []const u8, cflags: []const []const u8, }; @@ -96,6 +151,10 @@ const cli = clap.parseParamsComptime( \\-z, --zon Optional zon output path. \\-s, --seed Optional seed output path (default: fuzzer.seed). \\-e, --entry Optional harness function name (default: AbsolutionTestOneInput). + \\--no-post-check Do not assert check_invariant() after the harness returns (for harnesses that drive the globals out of the sampled domain, e.g. multi-step sessions). + \\-Z, --zero-symbols ... Zero-symbol list(s): matched globals get a single all-zero value. Unmatched selectors are reported. + \\--lenient-zero-symbols ... Zero-symbol list(s) shared across projects: unmatched selectors are not reported. + \\-O, --domain-overrides ... Domain override file(s) ('. = values ...|top|enum '), applied after the zero lists. Unmatched overrides are fatal. \\... C compiler flags after '--' (e.g. -I path -DFOO -fshort-enums). \\ ); @@ -140,6 +199,13 @@ fn parseArgs(allocator: std.mem.Allocator, io: std.Io, args: std.process.Args) ! const cflags = try allocator.dupe([]const u8, res.positionals[0]); errdefer allocator.free(cflags); + const zero_symbols = try allocator.dupe([]const u8, res.args.@"zero-symbols"); + errdefer allocator.free(zero_symbols); + const lenient_zero_symbols = try allocator.dupe([]const u8, res.args.@"lenient-zero-symbols"); + errdefer allocator.free(lenient_zero_symbols); + const domain_overrides = try allocator.dupe([]const u8, res.args.@"domain-overrides"); + errdefer allocator.free(domain_overrides); + return .{ .targets = targets, .redef = redef_path, @@ -148,6 +214,10 @@ fn parseArgs(allocator: std.mem.Allocator, io: std.Io, args: std.process.Args) ! .zon = res.args.zon, .seed = res.args.seed orelse "fuzzer.seed", .entry = res.args.entry orelse "AbsolutionTestOneInput", + .post_check = res.args.@"no-post-check" == 0, + .zero_symbols = zero_symbols, + .lenient_zero_symbols = lenient_zero_symbols, + .domain_overrides = domain_overrides, .cflags = cflags, }; } diff --git a/src/root.zig b/src/root.zig index d8c4ff6..29c45b0 100644 --- a/src/root.zig +++ b/src/root.zig @@ -4,15 +4,18 @@ //! - `Parser`: Parses C translation units and extracts global variables //! - `cgen`: Generates libFuzzer harness C code //! - `Invariant`: Loads and applies `.zon` invariant specifications +//! - `Tuning`: Applies zero lists and domain overrides to the discovered model pub const Parser = @import("Parser.zig"); pub const seed = @import("seed.zig"); pub const Invariant = @import("Invariant.zig"); +pub const Tuning = @import("Tuning.zig"); pub const emit = @import("cgen/emit.zig"); pub const ir = @import("cgen/ir.zig"); test { _ = @import("Invariant.zig"); + _ = @import("Tuning.zig"); _ = @import("cgen/ir.zig"); _ = @import("cgen/emit.zig"); _ = @import("seed.zig");