[PATCH] bpf: btf: reject division by zero in btf_struct_walk for zero-size flex array elements

Dudu Lu
2026-04-13T08:50:39Z

btf_struct_walk() computes `off = (off - moff) % t->size` when handling
access to a flexible array member. If the element type is a zero-size
struct (e.g., `struct B {}`), t->size is 0 and this causes a division-
by-zero exception. On x86 this triggers a #DE fault resulting in a
kernel panic.

The BTF validator does not reject zero-size structs: btf_struct_check_meta()
passes trivially for vlen=0 structs, and btf_array_resolve() skips the
overflow check for flex arrays (nelems=0). This allows a user to load
crafted BTF containing `struct B {}; struct A { int x; struct B flex[]; }`
and then trigger the crash when the verifier calls btf_struct_walk()
during program load.

Fix this by adding a check for t->size == 0 before the modulo operation.
When a zero-size element type is encountered in a flex array, return
-EINVAL to reject the access.

Note: ARM64 is not affected because its `udiv` instruction returns 0
for division by zero (no exception). However, the resulting incorrect
offset computation would still be a logic bug.

Fixes: 1dc92851849c ("bpf: kernel side support for BTF Var and DataSec")
Signed-off-by: Dudu Lu <phx0fer@gmail.com>
---
kernel/bpf/btf.c | 7 +++++++
1 file changed, 7 insertions(+)

diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 71f9143fe90f..f25009ea0d89 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -7103,6 +7103,13 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
if (!btf_type_is_struct(t))
goto error;

+ /* Zero-size element type (e.g., empty struct) would cause
+ * division by zero below. Reject the access.
+ */
+ if (t->size == 0) {
+ bpf_log(log, "zero-size type in flex array\n");
+ goto error;
+ }
off = (off - moff) % t->size;
goto again;

--
2.39.3 (Apple Git-145)