Skip to content
Open
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
46 changes: 46 additions & 0 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ OPTIONS:
-z, --zon <str> Optional: export parsed module to .zon format.
-s, --seed <str> Optional seed file path (default: fuzzer.seed).
-e, --entry <str> Optional harness function name (default: AbsolutionTestOneInput).
--no-post-check Do not assert check_invariant() after the harness returns.
-Z, --zero-symbols <str>... Zero-symbol list(s); unmatched selectors are reported.
--lenient-zero-symbols <str>... Shared zero-symbol list(s); unmatched selectors are silent.
-O, --domain-overrides <str>... Override file(s); unmatched lines are fatal.

<str>... C compiler flags after '--' (e.g. -I path -DFOO -fshort-enums).
```
Expand Down Expand Up @@ -319,8 +323,50 @@ LibFuzzer entrypoint that:
The generated file does `#undef NDEBUG` before `<assert.h>`, 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's discuss this.
I do agree but the interest of forcing the first generation is that you have an absolute expression of all invariants 🤔

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
Expand Down
54 changes: 46 additions & 8 deletions cmake/AbsolutionFuzzer.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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), '<global>.<field> = values ...|top|enum <T>',
# 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.
Expand All @@ -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.
Expand Down Expand Up @@ -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 ─────────────────────────────────
# $<TARGET_OBJECTS> is only known at generate time, but the renamed copies the
# fuzzer links must be named at configure time: count the sources that compile
Expand All @@ -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}
)

Expand Down Expand Up @@ -290,10 +327,7 @@ $<JOIN:$<TARGET_PROPERTY:${_OBJ_LIB},COMPILE_OPTIONS>,\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")

Expand All @@ -306,11 +340,12 @@ $<JOIN:$<TARGET_PROPERTY:${_OBJ_LIB},COMPILE_OPTIONS>,\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} $<TARGET_OBJECTS:${_OBJ_LIB}> "${_FLAGS_FILE}" "${_TARGETS_FILE}"
DEPENDS "${ABSOLUTION_EXECUTABLE}" ${_ABS_TARGETS} $<TARGET_OBJECTS:${_OBJ_LIB}> "${_FLAGS_FILE}" "${_TARGETS_FILE}" ${_model_deps}
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
COMMENT "[absolution] Generating harness for ${FUZZ_NAME}"
VERBATIM
Expand Down Expand Up @@ -381,6 +416,9 @@ $<JOIN:$<TARGET_PROPERTY:${_OBJ_LIB},COMPILE_OPTIONS>,\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}")
Expand Down
14 changes: 14 additions & 0 deletions cmake/RunAbsolution.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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}")
Expand Down
37 changes: 37 additions & 0 deletions src/Parser.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading