Writing a benchmark¶
A benchmark is the program under test: C source that marks its injection window with fim_init() and fim_exit(). Its directory holds that code and its own build files only. The variables whose final values decide whether a run was correct are named in the campaigns, usually in one file under campaigns/ that every campaign of the benchmark includes. hfim build compiles the benchmark into the ELF that campaigns inject into.
Layout¶
benchmarks/<name>/
├── main.c program under test
├── src/ optional: more .c files, compiled in
└── build/ written by hfim build
└── <name>_<arch>.elf
campaigns/<name>/
└── <name>.yaml what every campaign of <name> shares: benchmark: <name>, observable_outputs
The directory name is the benchmark name. A campaign selects it with benchmark: <name>, directly or through a file it includes. A Zephyr application keeps its CMakeLists.txt and prj.conf in the benchmark directory too: they are its build files.
Minimal example¶
This is fibonacci from the Nezha C906 template.
1. benchmarks/fibonacci/main.c
#include "hfim.h"
#define N 64
volatile unsigned long result[N];
int main(void) {
fim_init();
result[0] = 0;
result[1] = 1;
for (int i = 2; i < N; i++) {
result[i] = result[i - 1] + result[i - 2];
}
fim_exit(0);
}
2. campaigns/fibonacci/fibonacci.yaml, what every campaign of fibonacci shares:
benchmark: fibonacci
observable_outputs:
comparison: exact
variables:
- name: result
3. Build.
hfim build benchmarks/fibonacci
Output: benchmarks/fibonacci/build/fibonacci_riscv64.elf.
4. Run a campaign against it.
# campaigns/fibonacci/register.yaml
include: fibonacci.yaml
campaign_name: fibonacci-register
simulator_backend: qemu
seed: 7
num_injections: 10
target_types: [register]
target_registers: [x10, x11, x12, x13, x14, x15]
fault_model: single_bit_flip
injection_mode: icount
timeout: auto
output_dir: results
hfim run campaigns/fibonacci/register.yaml
hfim run builds the benchmark itself when the ELF is missing or the sources changed, so step 3 is optional. Details: Running campaigns.
The injection window¶
| Call | Effect |
|---|---|
fim_init() |
opens the injection window; faults land only between this call and fim_exit(). Also the usual checkpoint anchor |
fim_exit(int code) |
closes the window; HFIM reads the observable variables here; ends the simulation. Never returns |
fim_breakpoint() |
marks one fixed program counter for a campaign to break at, for benchmarks where instruction counts are not a stable clock (see Feeder-driven benchmarks) |
All three are declared in hfim.h from hfim-sdk. They are compiled non-inline, so each has a stable address in the symbol table for the debugger to break on. Place fim_init() after initialisation and before the computation under test.
Exit codes¶
The argument of fim_exit() is the benchmark's own verdict, and it decides the outcome.
| The program ends with | Constant | Outcome |
|---|---|---|
fim_exit(0) |
FIM_EXIT_SUCCESS |
masked or sdc, after comparing the observable variables with the golden run |
fim_exit(1) |
FIM_EXIT_FAILURE |
detected; observables are not compared |
fim_exit(2) or above, or no fim_exit |
FIM_EXIT_CRASH (2) |
crash, or timeout if it never ends |
A benchmark with no error detection of its own only calls fim_exit(0), and its injections are never detected. Full outcome rules: Fault classification.
Measuring an error-detection scheme¶
The benchmark calls fim_exit(1) when its own check fires. Example with duplicated execution (DMR):
#include "hfim.h"
#define N 64
volatile int result[N]; /* the observable, in observable_outputs */
static int copy_a[N], copy_b[N];
static void compute(int *out) {
for (int i = 0; i < N; i++)
out[i] = i * i + 3;
}
int main(void) {
fim_init();
compute(copy_a); /* run the work twice */
compute(copy_b);
for (int i = 0; i < N; i++) {
if (copy_a[i] != copy_b[i])
fim_exit(FIM_EXIT_FAILURE); /* copies disagree: detected */
result[i] = copy_a[i];
}
fim_exit(FIM_EXIT_SUCCESS); /* copies agree: masked, or sdc if wrong */
}
A fault in one copy is detected. A fault that corrupts both copies alike, or lands after the comparison, ends as sdc when result is wrong. The remaining sdc rate measures the scheme. Checksums and CRCs follow the same pattern.
A program that cannot end with a code (an operating system that keeps running) prints a message instead, named in the campaign or a file it includes:
detection_string: "DMR MISMATCH"
A run whose console output contains the string is detected. A crash takes precedence: a program that prints the string and then crashes before fim_exit(1) is crash.
What a correct run produces¶
What a campaign compares at fim_exit is part of the campaign, not of the benchmark directory. The keys below usually sit in campaigns/<name>/<name>.yaml, which every campaign of the benchmark includes, so all of them judge correctness the same way. A key a campaign sets itself wins over the included one. The golden run log names each included file and the keys it gave:
Using included file campaigns/fibonacci/fibonacci.yaml: benchmark, observable_outputs
The file says nothing about how to inject: fault, fault_model and the other injection keys belong to each campaign. Any key in it is checked as a campaign key is: a key that is no setting is refused, naming the file. How include: works: Sharing settings with include.
Keys that describe the benchmark¶
| Key | Purpose |
|---|---|
benchmark |
the directory name under benchmarks/ |
observable_outputs |
the variables or memory regions compared with the golden run |
detection_string |
console text that ends a run as detected |
state_capture_function |
the function at whose entry the observable state is read; default fim_exit |
serial_pty, serial_feeder_cmd |
how the benchmark talks to the world; see Feeder-driven benchmarks |
elf_path, firmware_path, sd_image_path |
the files a template's own build leaves, when the template builds with its own command |
observable_outputs¶
| Key | Values | Default |
|---|---|---|
comparison |
exact, tolerance |
exact |
variables[].name |
symbol name in the ELF | required |
variables[].type |
a C type; only when the type read from the ELF is wrong, or for a pointer whose target is compared | from the ELF |
variables[].tolerance |
non-negative number, for floating-point comparison | |
memory_regions[].name |
label | required |
memory_regions[].address |
integer or hex string | required |
memory_regions[].size |
bytes, positive integer | required |
At least one of variables or memory_regions is required. A variable's address and size come from the ELF symbol table, so the name is enough.
An observable variable must be:
- At file scope (a global, or
staticoutside any function). A local variable has no symbol-table entry. Astaticinside a function gets a compiler-chosen name such ascompute.counter. volatile. Otherwise the compiler can keep the value in a register and never store it. HFIM reads memory, so it would compare a location the program never wrote and report nosdc.
Every injection is masked
Check the observable variable first:
nm benchmarks/<name>/build/<name>_riscv64.elf | grep <variable>
Build keys¶
How a benchmark is built is a campaign's to say, like any other key, and it usually sits in the file every campaign of the benchmark includes. hfim run passes the values to build.sh as --optflag, --toolchain and --runtime, and the build record names that command, so changing a key rebuilds. build.sh reads no file of the benchmark directory: run by hand (hfim build benchmarks/<name> with no option), it builds with the defaults below, or with what OPTFLAG, RISCV_CC and AARCH64_CC in the environment say.
| Key | Values | Default |
|---|---|---|
build_optflag |
O0, O1, O2, Og, ... (-O2 is the same as O2) |
O1 |
build_toolchain |
a name resolved in the SDK's toolchains/ folder, then on PATH |
first RISC-V GCC found |
build_runtime |
nostdlib, newlib (riscv64 only), zephyr |
nostdlib |
Where each value comes from in hfim run:
| Setting | Source |
|---|---|
build_optflag |
the campaign or a file it includes; else OPTFLAG in the environment; else O1. A run where OPTFLAG disagrees with a value a file states is refused, naming both |
build_toolchain, build_runtime |
the campaign or a file it includes; else the default |
| the compiler | RISCV_CC or AARCH64_CC in the environment when set, else the toolchain named; the build record identifies it by its content |
A campaign that sets a build key needs hfim-sdk 1.2 or later; an older SDK cannot receive it, so the build is refused rather than run without the setting. A template that builds with its own command (build: in hfim.yaml) takes no build keys and refuses a campaign that sets one.
build_runtime: zephyr compiles nothing: it copies a prebuilt zephyr.elf from the benchmark directory to the output ELF.
Building¶
hfim build benchmarks/<name> [--arch riscv64|aarch64] [--target qemu-bare|gem5-se] [--startup <dir>]
[--optflag <level>] [--toolchain <name>] [--runtime <name>]
hfim build runs the command that hfim.yaml names under build:, or the registered SDK's build.sh, and passes every argument after the benchmark directory through.
| Target | Output | Startup code | Compiler |
|---|---|---|---|
qemu-bare (default) |
build/<name>_<arch>.elf, freestanding |
required | riscv64-unknown-elf-gcc |
gem5-se |
build/<name>_<arch>_gem5.elf, static Linux userspace |
none | riscv64-linux-gnu-gcc |
A gem5-se build links libc and an SE-mode fim_init/fim_exit that call exit(). Print with printf(); gem5 captures it as standard output.
Sources¶
| Benchmark contains | Built as |
|---|---|
main.c |
main.c plus every .c, .s and .S in src/ |
exactly one top-level .c, .s or .S |
that file plus src/ |
several top-level .c, .s or .S and no main.c |
error |
Cargo.toml |
Rust: cargo build --release --target riscv64gc-unknown-none-elf (or aarch64-unknown-none) |
A whole program may arrive as one top-level .s, main included, for example the output of a tool that rewrites the code under test. A .s file is assembled as it is and a .S file goes through the C preprocessor first; build_optflag changes neither, since there is nothing left to optimise.
Assembly generated by LLVM (clang -S) must carry DWARF 4 debug information. The GNU assembler in the SDK's toolchain (binutils 2.40) rejects the DWARF 5 directives LLVM emits by default. Generate it with -gdwarf-4.
Compiler flags¶
RISC-V 64, qemu-bare, nostdlib:
-O1 -g -march=rv64imafdc -mabi=lp64d -mcmodel=medany -nostdlib -static -ffreestanding
| Flag | Reason |
|---|---|
-O1 |
realistic instruction mix; -O2 register allocation makes debugger variable reads unreliable, -O0 inflates the instruction count 3 to 5 times |
-g |
DWARF debug information, needed to read observable state |
-mcmodel=medany |
PC-relative addressing; RAM starts at 0x80000000 |
-nostdlib -ffreestanding |
bare metal, no libc, no default startup files |
The SDK links a freestanding memcpy, memset, memcmp and string routines, so -nostdlib benchmarks that use them link without libc.
Startup code¶
A qemu-bare build needs a start.S and a linker script, which belong to the board and come from the template. The first match is used:
--startup <dir>- the
HFIM_STARTUPenvironment variable startup/<arch>/in the repository holding the benchmark, thenstartup/
Inside a campaign directory created by hfim init, case 3 applies with no configuration. The startup code enables the FPU, zeroes .bss, sets the stack pointer and calls main.
Memory layout of the Nezha C906 template
| Property | Value | |---|---| | RAM origin (RISC-V) | `0x80000000` | | RAM length | 64 MB | | Section order | `.text`, `.rodata`, `.data`, `.bss`, stack | | Stack | 16 KB (`0x4000`), 16-byte aligned, no guard page | | Symbols | `__bss_start`, `__bss_end`, `__stack_bottom`, `__stack_top` | The built ELF is authoritative. Check addresses with `nm` or `readelf -S`.Incremental builds¶
The build is skipped when the hash of these files matches build/.build_hash_<arch>:
- benchmark:
*.c,*.s,*.S,*.h,*.rs,Cargo.toml, a prebuiltzephyr.elf - startup and SDK:
start.S,link.ld,hfim.h, the SDK instrumentation and string sources
hfim run applies the same rule to benchmarks/<name>/ plus the files hfim.yaml lists under build_inputs, and a rebuild triggers a new golden run.
no RISC-V GCC found
With no RISC-V compiler on `PATH`, `build.sh` re-runs itself inside the `hfim-sim-qemu` Docker image, which carries both toolchains. That image exists after `hfim sim install`. Otherwise set `RISCV_CC` to a compiler, or install `riscv64-unknown-elf-gcc`.
no startup code for riscv64
The build found no `start.S`. Run `hfim build` from inside a campaign directory that has `startup/`, or pass `--startup Each ELF carries a .fim_provenance section with the commit, branch and dirty flag of the repository that holds the benchmark. It is not loaded at run time.
Targeting a section¶
memory_start and memory_end accept a section name, resolved from the ELF at run time. For fibonacci, .bss is exactly result[]:
target_types: [memory]
memory_start: .bss
memory_end: .bss
A benchmark can define its own section:
volatile unsigned char dead_pad[4096] __attribute__((section(".dead_pad")));
memory_start: .dead_pad
memory_end: .dead_pad # the range extends to the section size
A section the program never reads gives a campaign in which every injection must be masked, a check on the classifier. Every way to select memory: Memory.
Feeder-driven benchmarks¶
A benchmark that exchanges data with an external process over its serial port (for example a control loop fed by a physics simulator) declares the feeder in the campaign:
serial_pty: true # QEMU attaches the UART to a PTY
serial_feeder_cmd: "python3 feeder.py {pty}" # {pty}: the device QEMU allocated
injection_mode: breakpoint
inject_at_symbol: work_step
| Key | Effect |
|---|---|
serial_pty |
QEMU allocates a pseudo-terminal for the UART |
serial_feeder_cmd |
command started for each injection; {pty} is replaced with the device path. Same slot as coprocess.injection |
injection_mode: breakpoint |
inject on a program counter, not an instruction count |
inject_at_symbol |
the function whose address is the breakpoint |
The program waits for input, so its instruction count depends on wall-clock time and varies between runs. An instruction count then names a different instant in each run; a program counter does not. Use breakpoint mode with a function in the work loop, or call fim_breakpoint() there and name it.
The feeder runs on the host, so its Python dependencies must be installed in the environment that runs the campaign.