All of lore.kernel.org
 help / color / mirror / Atom feed
* [RFC][PATCH] overflow: Twiddle with struct_size()
@ 2025-03-05 13:43 Peter Zijlstra
  2025-03-06  7:13 ` Kees Cook
  0 siblings, 1 reply; 3+ messages in thread
From: Peter Zijlstra @ 2025-03-05 13:43 UTC (permalink / raw)
  To: Kees Cook, linux-kernel; +Cc: Borislav Petkov

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

^ permalink raw reply related	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2025-03-06  8:40 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-03-05 13:43 [RFC][PATCH] overflow: Twiddle with struct_size() Peter Zijlstra
2025-03-06  7:13 ` Kees Cook
2025-03-06  8:40   ` Peter Zijlstra

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.