Skip to contentSkip to conversation

bpf/btf: fix u32 subtraction overflow in btf_sec_info_cmp

PATCH In review ibrahim zein 2 participants 2 messages Mar 18 BPF

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 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.

---
 btf.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
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
maintainer
#1 lore raw
Quoted 9 lines · ibrahim zein

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.

Ibrahim, you've been asked previously to only send patches with a related BPF selftest which demonstrate/exercise the problematic behavior that is being fixed. Recent example of a fix with accompanying BPF selftest:

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

Thanks,
Daniel