kmemcheck only in debug builds (DEBUG)

kmemcheck painted canaries around every kmalloc and recorded it in a
table under a global lock, and checked both on kfree: a cost on every
allocation of the driver. It is a heap debugging aid, so it now
compiles only with DEBUG defined. A release build keeps a small header
(the payload's size for ksize, and the allocation to free) and goes
straight to the allocator: no canaries, no tracking, no lock.
kmemcheck_enabled() returns 0 and the checks find nothing.
km_clear_sensitive (the wipe in kfree_sensitive) is unchanged.

The define reaches only linuxu sources, never upstream objects: the
dext's linuxu objects include a generated build/gen/mlg_build_mode.h
that `make lib-dext DEBUG=1` fills in (rewritten only when the mode
changes, so they rebuild), and Xcode's Debug configuration defines
DEBUG=1 and passes it to that make. The host library the offline tests
link is always a debug build, and the tests whose leak or corruption
checks rely on kmemcheck build its sources with DEBUG=1.

make check-release builds lib-dext in release and fails if it carries
kmemcheck's symbols (scripts/check-release.sh, whose patterns are first
checked against a debug build), then runs test_kmem_release in both
modes: sizes, alignment, zeroing, ksize, kmemdup and caches behave the
same, and only the debug build reports a write past an object.
This commit is contained in:
geramyloveless committed 2026-10-04 10:02:29 -07:00
1 parent c969e84507
commit d132e251e2
12 files changed
+227 -22

No files matched your search

+37
View File
@@ -46,6 +46,22 @@ include mk/dext.mk
BUILD := build
DRM := $(LINUX)/drivers/gpu/drm
# kmemcheck (canaries and tracking of every kmalloc, linuxu/src/kmem) is
# compiled in only with DEBUG=1, as Xcode's Debug configuration does:
# `make lib-dext DEBUG=1`. Without it the dext's linuxu objects contain
# none of it; `make check-release` verifies that. The define reaches only
# linuxu sources, never upstream objects, through a generated header
# rewritten when the mode changes (so the objects that include it
# rebuild). The host library the offline tests link is always a debug
# build: those tests check the heap with it.
DEBUG ?=
MLG_DEBUG := $(if $(filter 1 yes true,$(DEBUG)),1,0)
MLG_MODE_HEADER := $(BUILD)/gen/mlg_build_mode.h
MLG_MODE_TEXT := $(if $(filter 1,$(MLG_DEBUG)),\#define DEBUG 1,/* release build: DEBUG undefined */)
$(MLG_MODE_HEADER): FORCE
@mkdir -p $(dir $@)
@printf '%s\n' '$(MLG_MODE_TEXT)' | cmp -s - $@ 2>/dev/null || printf '%s\n' '$(MLG_MODE_TEXT)' > $@
AMD := $(DRM)/amd
# ---------------------------------------------------------------------------
@@ -190,6 +206,8 @@ $(addprefix $(BUILD)/driver/,$(FOLDED_ASSERT_OBJECTS)): HOSTCFLAGS += -O2 -fno-s
# Pinned generic FIFO helper expects the Linux allocator's core macro includes.
$(BUILD)/linuxu/shims/kfifo.o: HOSTCFLAGS += -include linux/kernel.h -include linux/bug.h
# The host library is a debug build (linuxu sources only; see DEBUG above).
$(addprefix $(BUILD)/linuxu/,$(LINUXU_SRCS:linuxu/src/%.c=%.o)): HOSTCFLAGS += -DDEBUG=1
$(BUILD)/linuxu/shims/sort.o: HOSTCFLAGS += -include linux/compiler.h -include linux/preempt.h
# ---------------------------------------------------------------------------
@@ -228,6 +246,10 @@ DK_CFLAGS += -include rt/device_string.h -mstrict-align \
# Changing the memory backend must rebuild every KMD object, including ones
# whose old depfiles predate the forced header.
$(DK_DRIVER_OBJS) $(DK_LINUXU_OBJS): linuxu/headers/rt/device_string.h
# linuxu objects follow DEBUG (the mode header), upstream objects never.
DK_LINUXU_SRC_OBJS := $(addprefix $(DK_BUILD)/linuxu/,$(LINUXU_SRCS:linuxu/src/%.c=%.o))
$(DK_LINUXU_SRC_OBJS): $(MLG_MODE_HEADER)
$(DK_LINUXU_SRC_OBJS): DK_CFLAGS += -include $(MLG_MODE_HEADER)
$(eval $(call compile_rules,$(DK_BUILD),DK_CFLAGS))
$(foreach h,$(UPSTREAM_HELPERS),$(eval $(call helper_rule,$(DK_BUILD),DK_CFLAGS,$(word 1,$(subst :, ,$(h))),$(word 2,$(subst :, ,$(h))))))
@@ -563,6 +585,15 @@ test-dext-alloc:
verify-source:
python3 scripts/verify-upstream.py
# A release build (DEBUG unset) of the dext's library, checked for kmemcheck
# (scripts/check-release.sh), and the allocator's tests in release mode.
check-release:
$(MAKE) DEBUG= lib-dext
bash scripts/check-release.sh $(DK_LIB)
bash scripts/test-kmem-release.sh
.PHONY: check-release
# What the driver is built from: the Linux tree alone (Mesa and llama.cpp,
# when checked out, are verified by verify-source and their own builds).
verify-linux:
@@ -641,6 +672,12 @@ test-rcu-dk:
$(CC) -std=gnu11 -g -O1 -w -D__KERNEL__ -DLINUXU_DEXT_DK=1 -fsanitize=address,undefined -Ilinuxu/headers linuxu/tests/test_rcu.c linuxu/src/rcu.c -Wl,-dead_strip -lpthread -o $(BUILD)/tests/test_rcu_dk
$(BUILD)/tests/test_rcu_dk
test-kmem-release:
bash scripts/test-kmem-release.sh
test: test-kmem-release
.PHONY: test-kmem-release
test-wait-event:
@mkdir -p $(BUILD)/tests
$(CC) -std=gnu11 -g -O1 -w -fsanitize=address,undefined -ffunction-sections -fdata-sections -Ilinuxu/headers linuxu/tests/test_wait_event.c linuxu/src/sync.c linuxu/src/delay.c linuxu/src/shims/task.c linuxu/src/shims/kthread.c linuxu/src/bug.c -Wl,-dead_strip -o $(BUILD)/tests/test_wait_event
+47 -16
View File
@@ -1,10 +1,13 @@
/* linuxu shim: kmemalloc — kmalloc/kfree family over libc malloc with
* kmemcheck canaries (REAL).
/* linuxu shim: kmemalloc — kmalloc/kfree family over libc malloc, with
* kmemcheck canaries and tracking in debug builds (DEBUG) only.
* Kernel arg order preserved (e.g. memcmp(dest, src, n)); kzalloc zeroes;
* __GFP_ZERO is honored; node affinity is unused in this single process.
*
* Every nonzero allocation carries a leading struct kmemcheck_hdr + canaries;
* see kmemcheck.c for the layout. */
* Every nonzero allocation carries a leading header: the payload's size
* (ksize) and the allocation to free (the payload is aligned inside it).
* Debug builds add kmemcheck's fields and canaries around the payload (see
* kmemcheck.c for the layout) and track every object, which costs a lock
* per kmalloc and kfree; release builds have neither. */
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
@@ -17,6 +20,7 @@
#include <linux/gfp.h>
#include <linux/string.h>
#if DEBUG
/* shared with kmemcheck.c (same directory, same translation unit set) */
struct kmemcheck_hdr {
uintptr_t user_ptr;
@@ -30,6 +34,23 @@ struct kmemcheck_hdr {
extern int kmemcheck_track(struct kmemcheck_hdr *hdr, size_t user_size);
extern int kmemcheck_untrack(struct kmemcheck_hdr *hdr);
extern int kmemcheck_scan(void);
#define KM_CANARY sizeof(uint64_t) /* a canary word on each side */
#else
struct kmemcheck_hdr {
uintptr_t user_ptr;
size_t size;
size_t alloc_size;
void *allocation;
};
#define KM_CANARY 0
#endif
/* The header of the payload at @user_ptr. */
static struct kmemcheck_hdr *km_hdr(const void *user_ptr)
{
return (struct kmemcheck_hdr *)((uintptr_t)user_ptr - KM_CANARY -
sizeof(struct kmemcheck_hdr));
}
#define KM_ALIGN 8u
static size_t km_align(size_t s)
@@ -40,7 +61,7 @@ static size_t km_align(size_t s)
/* total bytes to malloc for a payload of user_size */
static size_t km_total(size_t user_size, size_t alignment)
{
const size_t overhead = sizeof(struct kmemcheck_hdr) + 2 * sizeof(uint64_t);
const size_t overhead = sizeof(struct kmemcheck_hdr) + 2 * KM_CANARY;
if (!alignment || (alignment & (alignment - 1)) ||
alignment - 1 > SIZE_MAX - overhead ||
user_size > SIZE_MAX - overhead - (alignment - 1))
@@ -59,13 +80,17 @@ static void *km_alloc_aligned(size_t user_size, size_t alignment)
if (!raw)
return NULL;
user = ((uintptr_t)raw + sizeof(*hdr) + sizeof(uint64_t) + alignment - 1) &
user = ((uintptr_t)raw + sizeof(*hdr) + KM_CANARY + alignment - 1) &
~(uintptr_t)(alignment - 1);
hdr = (struct kmemcheck_hdr *)(user - sizeof(uint64_t) - sizeof(*hdr));
hdr = km_hdr((void *)user);
hdr->user_ptr = user;
hdr->alloc_size = total;
hdr->allocation = raw;
#if DEBUG
kmemcheck_track(hdr, user_size);
#else
hdr->size = user_size;
#endif
return (void *)hdr->user_ptr;
}
@@ -80,10 +105,10 @@ static void km_dealloc(void *user_ptr)
if (ZERO_OR_NULL_PTR(user_ptr))
return;
hdr = (struct kmemcheck_hdr *)
((unsigned char *)user_ptr - sizeof(uint64_t) -
sizeof(struct kmemcheck_hdr));
hdr = km_hdr(user_ptr);
#if DEBUG
kmemcheck_untrack(hdr);
#endif
free(hdr->allocation);
}
@@ -159,18 +184,26 @@ void kvfree_sensitive(const void *addr, size_t len)
kvfree(addr);
}
/* kmemcheck: the slab allocator (kmalloc/kfree) is kmemcheck-instrumented
* (canary words + per-size checksum around every object), so the check
* is always live. */
/* kmemcheck: in debug builds the slab allocator (kmalloc/kfree) is
* kmemcheck-instrumented (canary words + per-size checksum around every
* object); release builds track nothing, and the checks find nothing. */
int kmemcheck_enabled(void)
{
#if DEBUG
return 1;
#else
return 0;
#endif
}
/* Scan all live allocations; returns number of corrupted objects. */
int kmemcheck_verify_all(void)
{
#if DEBUG
return kmemcheck_scan();
#else
return 0;
#endif
}
/* ---- flexible-array ("obj") single-arg runtimes ----
@@ -417,9 +450,7 @@ size_t ksize(const void *p)
if (ZERO_OR_NULL_PTR(p))
return 0;
hdr = (struct kmemcheck_hdr *)
((unsigned char *)p - sizeof(uint64_t) -
sizeof(struct kmemcheck_hdr));
hdr = km_hdr(p);
return hdr->size;
}
+9 -2
View File
@@ -1,8 +1,9 @@
/* linuxu shim: kmemcheck — heap canary verification for kmalloc/kfree;
* strategy (offline test regime): REAL.
/* linuxu shim: kmemcheck — heap canary verification for kmalloc/kfree, in
* debug builds (DEBUG); a release build has none of it (kmemalloc.c).
* Every kmalloc object is allocated with a leading/trailing canary word and
* a per-size checksum so the P0 kmemcheck goal (corrupt a byte -> detect)
* is real. kmemcheck_verify scans all live allocations. */
#if DEBUG
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
@@ -186,3 +187,9 @@ size_t kmemcheck_live_bytes(void)
pthread_mutex_unlock(&kmemcheck_lock);
return total;
}
#else
#include <stddef.h>
/* Release builds track nothing: no object is live to the checker. */
size_t kmemcheck_live_bytes(void);
size_t kmemcheck_live_bytes(void) { return 0; }
#endif /* DEBUG */
+65
View File
@@ -0,0 +1,65 @@
/* The kmalloc family in both builds: release (DEBUG undefined: no kmemcheck,
* nothing tracked) and debug (kmemcheck canaries and tracking). Sizes,
* alignment, zeroing, ksize, kmemdup, caches and the sensitive wipe behave
* the same in both; only the debug build reports corruption. */
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <linux/slab.h>
#include <linux/gfp.h>
extern int kmemcheck_enabled(void);
extern int kmemcheck_verify_all(void);
int main(void)
{
#if DEBUG
assert(kmemcheck_enabled());
#else
assert(!kmemcheck_enabled());
#endif
for (size_t size = 1; size <= (1u << 20); size = size * 3 + 1) {
unsigned char *p = kzalloc(size, GFP_KERNEL);
assert(p && !((uintptr_t)p & (ARCH_DMA_MINALIGN - 1)));
for (size_t i = 0; i < size; i++)
assert(!p[i]);
memset(p, 0x5a, size);
assert(ksize(p) == size);
unsigned char *copy = kmemdup(p, size, GFP_KERNEL);
assert(copy && !memcmp(copy, p, size));
kfree(copy);
kfree(p);
}
assert(kmalloc(0, GFP_KERNEL) == ZERO_SIZE_PTR);
kfree(ZERO_SIZE_PTR);
kfree(NULL);
struct kmem_cache *cache = kmem_cache_create("release-test", 200, 64, 0, NULL);
assert(cache);
void *objects[64];
for (int i = 0; i < 64; i++) {
objects[i] = kmem_cache_alloc(cache, GFP_KERNEL);
assert(objects[i] && !((uintptr_t)objects[i] & 63));
memset(objects[i], i, 200);
}
for (int i = 0; i < 64; i++)
kmem_cache_free(cache, objects[i]);
kmem_cache_destroy(cache);
assert(kmemcheck_verify_all() == 0);
#if DEBUG
/* Only the debug build sees a write past the payload. */
unsigned char *q = kmalloc(32, GFP_KERNEL);
q[32] = 0xa5;
assert(kmemcheck_verify_all() == 1);
kfree(q);
assert(kmemcheck_verify_all() == 0);
#endif
#if DEBUG
puts("kmalloc family (debug build): sizes, alignment, zeroing, ksize, caches, kmemcheck passed");
#else
puts("kmalloc family (release build): sizes, alignment, zeroing, ksize, caches passed");
#endif
return 0;
}
+2 -1
View File
@@ -273,7 +273,7 @@
outputPaths = ();
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -eu\n# make runs scripts/bootstrap.sh first when setup is missing or stale\n# (pinned Linux submodule, patches/linux, locked firmware).\n/usr/bin/make -C \"$SRCROOT\" verify-source\n/usr/bin/make -C \"$SRCROOT\" -j4 lib-dext\n";
shellScript = "set -eu\n# make runs scripts/bootstrap.sh first when setup is missing or stale\n# (pinned Linux submodule, patches/linux, locked firmware).\n/usr/bin/make -C \"$SRCROOT\" verify-source\n# Debug builds compile the instrumentation in (DEBUG=1), release builds leave it out.\nif [ \"$CONFIGURATION\" = Debug ]; then mode=1; else mode=; fi\n/usr/bin/make -C \"$SRCROOT\" -j4 lib-dext DEBUG=$mode\n";
};
F00000000000000000000009 /* Bundle firmware */ = {
isa = PBXShellScriptBuildPhase;
@@ -379,6 +379,7 @@
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"LINUXU_DEXT=1",
"DEBUG=1",
);
HEADER_SEARCH_PATHS = (
"$(inherited)",
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
#
# scripts/check-release.sh FILE... — fail if a release build carries
# kmemcheck (make check-release passes the dext's library).
#
# kmemcheck (canaries and a table of every kmalloc, linuxu/src/kmem) is
# compiled in only with DEBUG defined (make DEBUG=1, Xcode's Debug
# configuration). Each FILE (an archive, object or dylib) must contain none
# of its symbols. First the patterns are checked against a debug build of
# kmemcheck, so a pattern that stopped matching fails here instead of
# passing silently.
set -euo pipefail
cd "$(dirname "$0")/.."
symbols='_kmemcheck_track|_kmemcheck_untrack|_kmemcheck_scan|_kmemcheck_recs|_kmemcheck_free_slots|_kmemcheck_pattern'
found() { # FILE -> prints the matching symbols
nm -a "$1" 2>/dev/null | awk '{print $NF}' | grep -E "^($symbols)$" | sort -u || true
}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
clang -std=gnu11 -w -g -DDEBUG=1 -D__KERNEL__ -include linux/autoconf.h -Ilinuxu/headers \
-c linuxu/src/kmem/kmemcheck.c -o "$work/kmemcheck.o"
if [ -z "$(found "$work/kmemcheck.o")" ]; then
echo "check-release: the patterns do not match a debug build of kmemcheck; update them" >&2
exit 1
fi
status=0
for file in "$@"; do
[ -f "$file" ] || { echo "check-release: $file is missing" >&2; status=1; continue; }
hits=$(found "$file")
if [ -n "$hits" ]; then
echo "check-release: $file carries kmemcheck:" >&2
printf ' %s\n' $hits >&2
status=1
else
echo "check-release: $file: no kmemcheck"
fi
done
exit $status
+2
View File
@@ -60,6 +60,8 @@ for source in "${sources[@]}"; do
object="$test_dir/$(echo "$source" | tr '/' '_').o"
extra=()
case "$source" in
# kmemcheck tracks the heap (the leak check below): debug build.
linuxu/src/kmem/kmemalloc.c|linuxu/src/kmem/kmemcheck.c) extra=(-DDEBUG=1) ;;
third_party/linux/lib/kfifo.c) extra=(-include linux/kernel.h -include linux/bug.h) ;;
third_party/linux/lib/sort.c) extra=(-include linux/compiler.h -include linux/preempt.h) ;;
*/kfd_device.c) extra=(-Dkfd_gtt_sa_allocate=upstream_kfd_gtt_sa_allocate
+2
View File
@@ -63,6 +63,8 @@ for source in "${sources[@]}"; do
extra=()
# Same per-object flags as the Makefile.
case "$source" in
# kmemcheck tracks the heap (the leak check below): debug build.
linuxu/src/kmem/kmemalloc.c|linuxu/src/kmem/kmemcheck.c) extra=(-DDEBUG=1) ;;
third_party/linux/lib/kfifo.c) extra=(-include linux/kernel.h -include linux/bug.h) ;;
third_party/linux/lib/sort.c) extra=(-include linux/compiler.h -include linux/preempt.h) ;;
# create_signal_event takes the user address of the event's slot even
+1 -1
View File
@@ -3,7 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
test_dir=$(mktemp -d)
trap 'rm -rf "$test_dir"' EXIT
flags=(-w -std=gnu11 -g -O1 -fsanitize=address,undefined
flags=(-w -std=gnu11 -g -O1 -DDEBUG=1 -fsanitize=address,undefined
-fno-sanitize-recover=all -Ilinuxu/headers -Ilinuxu/tests)
heap=(-Dmalloc=dext_test_malloc -Dcalloc=dext_test_calloc
-Drealloc=dext_test_realloc -Daligned_alloc=dext_test_aligned_alloc
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# The kmalloc family built as release (no DEBUG: no kmemcheck) and as debug
# (DEBUG=1: kmemcheck), from the production sources (linuxu/src/kmem).
set -euo pipefail
cd "$(dirname "$0")/.."
test_dir=$(mktemp -d)
trap 'rm -rf "$test_dir"' EXIT
flags=(-w -std=gnu11 -g -O1 -D__KERNEL__ -include linux/autoconf.h
-fsanitize=address,undefined -fno-sanitize-recover=all -Ilinuxu/headers)
for mode in release debug; do
mode_flags=()
[ "$mode" = debug ] && mode_flags=(-DDEBUG=1)
clang "${flags[@]}" "${mode_flags[@]}" linuxu/tests/test_kmem_release.c \
linuxu/src/kmem/{kmemalloc,kmemcheck}.c linuxu/src/shims/printk.c linuxu/src/spinlock.c \
-Wl,-dead_strip \
-o "$test_dir/test_kmem_$mode"
"$test_dir/test_kmem_$mode"
done
+1 -1
View File
@@ -3,7 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
work=$(mktemp -d "${TMPDIR:-/tmp}/memory-containers.XXXXXX")
trap 'rm -rf "$work"' EXIT
clang -w -std=gnu11 -g -O1 -fsanitize=address,undefined -fno-sanitize-recover=all \
clang -w -std=gnu11 -g -O1 -DDEBUG=1 -fsanitize=address,undefined -fno-sanitize-recover=all \
-ffunction-sections -fdata-sections -Ilinuxu/headers \
linuxu/tests/test_memory_containers.c linuxu/src/xarray.c linuxu/src/rcu.c linuxu/src/sync.c linuxu/src/llist.c \
linuxu/src/shims/interval_tree.c third_party/linux/lib/rbtree.c linuxu/src/kmem/{kmemalloc,kmemcheck}.c \
+1 -1
View File
@@ -3,7 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")/.."
test_dir=$(mktemp -d)
trap 'rm -rf "$test_dir"' EXIT
flags=(-w -std=gnu11 -g -O1 -fsanitize=address,undefined
flags=(-w -std=gnu11 -g -O1 -DDEBUG=1 -fsanitize=address,undefined
-fno-sanitize-recover=all -ffunction-sections -fdata-sections
-Ilinuxu/headers -Ilinuxu/tests)
heap=(-Dmalloc=dext_test_malloc -Dcalloc=dext_test_calloc