Skip to contentSkip to conversation

bpf/btf: fix u32 subtraction overflow in btf_sec_info_cmp

PATCH New Ibrahim Zein 2 participants 2 messages Mar 18 BPF

lore
Share & tools
lore
#0 lore raw

PATCH 1/2 bpf/btf: fix u32 subtraction overflow in btf_sec_info_cmp

The comparison function btf_sec_info_cmp() uses direct subtraction of u32 values cast to int, which can produce incorrect results due to integer overflow when values exceed 0x7FFFFFFF.

Replace with explicit comparisons to guarantee correct behavior across all u32 value ranges.

---
 kernel/bpf/btf.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
kernel/bpf/btf.c +5 -1
index 4872d2a..5b3e1af 100644
@@ -5548,7 +5548,11 @@ static int btf_sec_info_cmp(const void *a, const void *b)
 	const struct btf_sec_info *x = a;
 	const struct btf_sec_info *y = b;
 
-	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
+	if (x->off != y->off)
+		return x->off < y->off ? -1 : 1;
+	if (x->len != y->len)
+		return x->len < y->len ? -1 : 1;
+	return 0;
 }
 
 static int btf_check_sec_info(struct btf_verifier_env *env,
Signature · 1 line
2.51.0
#1 lore raw
Daniel Borkmann asked for a BPF selftest demonstrating the overflow behavior being fixed here. The v2 patch does not appear to include one. Was this feedback addressed separately?
Quoted 4 lines

kernel/bpf/btf.c static int btf_sec_info_cmp(const void *a, const void *b) · line 5556

Quoted 10 lines
kernel/bpf/btf.c +5 -1
@@ -5548,7 +5548,11 @@ static int btf_sec_info_cmp(const void *a, const void *b)
 	const struct btf_sec_info *x = a;
 	const struct btf_sec_info *y = b;
 
-	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
+	if (x->off != y->off)
+		return x->off < y->off ? -1 : 1;
+	if (x->len != y->len)
+		return x->len < y->len ? -1 : 1;
+	return 0;
 }

Daniel Borkmann asked for a BPF selftest demonstrating the overflow behavior being fixed here. The v2 patch does not appear to include one. Was this feedback addressed separately?

https://lore.kernel.org/bpf/[email protected]/

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23249633514