runners: Added stack/heap measurement functions

These have been battle-tested in external benchmarks, and have proven
useful for finding a runtime estimate on stack+heap usage.

Of course, to be realistic they need to be cross-compiled and run under
QEMU (which does work!), but even on x86_64 they provide a nice insight
into RAM usage. In practice the only real difference is pointer width
anyways.

---

Enabled by default for the bench runner, these are available if
TEST/BENCH_YES_HEAP and/or TEST/BENCH_YES_STACK are defined.

(This default is provided by the Makefile. At least heap measurements
rely on linker flags, so it probably doesn't make sense to default
enable in the bench runner itself.)

Stack vs heap rely on slightly different mechanisms:

- Stack: Uses GCC's __builtin_frame_address(0) to measure the current
  stack usage on entry to every bd operation.

- Heap: Relies on GCC's -Wl,--wrap flags to intercept every malloc/free
  call, to track the current heap usage.

These are available via bench/test macros:

- BENCH_STACK()         - Maximum stack usage of the current run
- BENCH_STACK_CURRENT() - Current stack usage
- BENCH_HEAP()          - Maximum heap usage of the current run
- BENCH_HEAP_CURRENT()  - Current heap usage

Note BENCH_STACK_CURRENT() can be useful for separating out the bench's
ctx from total stack usage, similarly to our static analysis.

---

One surprising outcome is that these heap hooks trivially implement a
memory leak detector. Maybe that could be useful in the test_runner as a
cheaper alternative to Valgrind?
This commit is contained in:
Christopher Haster
2026-01-26 03:54:03 -06:00
parent 23ac67bf34
commit 356d7065be
5 changed files with 866 additions and 43 deletions
+18
View File
@@ -99,9 +99,27 @@ CFLAGS += $(foreach d,$(filter LFS3_%,$(.VARIABLES)),-D$d=$($d))
TEST_CFLAGS += -Wno-unused-function
TEST_CFLAGS += -Wno-format-overflow
ifdef STACK
TEST_CFLAGS += -DTEST_YES_STACK
endif
ifdef HEAP
TEST_CFLAGS += -DTEST_YES_HEAP
TEST_CFLAGS += -Wl,--wrap=malloc
TEST_CFLAGS += -Wl,--wrap=free
TEST_CFLAGS += -Wl,--wrap=realloc
endif
BENCH_CFLAGS += -Wno-unused-function
BENCH_CFLAGS += -Wno-format-overflow
ifndef NO_STACK
BENCH_CFLAGS += -DBENCH_YES_STACK
endif
ifndef NO_HEAP
BENCH_CFLAGS += -DBENCH_YES_HEAP
BENCH_CFLAGS += -Wl,--wrap=malloc
BENCH_CFLAGS += -Wl,--wrap=free
BENCH_CFLAGS += -Wl,--wrap=realloc
endif
ifdef VERBOSE
CODEFLAGS += -v