[RFC][PATCH] overflow: Twiddle with struct_size()
From: Peter Zijlstra
Date: Wed Mar 05 2025 - 08:44:20 EST
Hi Kees,
I keep getting hit by the struct_size() brigade, and I keep having
trouble reading that macro.
I had a wee poke and ended up with the below, WDYT?
(I also tried to create a __must_be_flex_array(), but utterly failed :/)
---
diff --git a/include/linux/overflow.h b/include/linux/overflow.h
index 0c7e3dcfe867..2123d0e238bb 100644
--- a/include/linux/overflow.h
+++ b/include/linux/overflow.h
@@ -352,9 +352,10 @@ static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
* Return: number of bytes needed or SIZE_MAX on overflow.
*/
#define flex_array_size(p, member, count) \
- __builtin_choose_expr(__is_constexpr(count), \
- (count) * sizeof(*(p)->member) + __must_be_array((p)->member), \
- size_mul(count, sizeof(*(p)->member) + __must_be_array((p)->member)))
+ (__must_be_array((p)->member) + \
+ __builtin_choose_expr(__is_constexpr(count), \
+ sizeof(*(p)->member) * (count), \
+ size_mul(sizeof(*(p)->member), (count))))
/**
* struct_size() - Calculate size of structure with trailing flexible array.
@@ -367,10 +368,12 @@ static inline size_t __must_check size_sub(size_t minuend, size_t subtrahend)
*
* Return: number of bytes needed or SIZE_MAX on overflow.
*/
-#define struct_size(p, member, count) \
- __builtin_choose_expr(__is_constexpr(count), \
- sizeof(*(p)) + flex_array_size(p, member, count), \
- size_add(sizeof(*(p)), flex_array_size(p, member, count)))
+#define struct_size(p, member, count) \
+ (__must_be_array((p)->member) + \
+ __builtin_choose_expr(__is_constexpr(count), \
+ sizeof(*(p)) + (sizeof((p)->member) * (count)), \
+ size_add(sizeof(*(p)), \
+ size_mul(sizeof(*(p)->member), count))))
/**
* struct_size_t() - Calculate size of structure with trailing flexible array