Skip to contentSkip to conversation

stddef: Introduce TRAILING_OVERLAP() helper macro

PATCH Applied Gustavo A. R. Silva 2 participants 2 messages Jun 17, 2025 – Jun 18, 2025

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 stddef: Introduce TRAILING_OVERLAP() helper macro

Add new TRAILING_OVERLAP() helper macro to create a union between a flexible-array member (FAM) and a set of members that would otherwise follow it. This overlays the trailing members onto the FAM while preserving the original memory layout.

---
Changes in v2:
- Use __offset_of_##FAM instead of __offset_of_fam for the offset variable.
- Update changelog text.

v1:
- Link: https://lore.kernel.org/linux-hardening/aFDIBBeYgRSx1ekO@kspp/

 include/linux/stddef.h | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
include/linux/stddef.h +20 -0
index 929d67710cc5..dab49e2ec8c0 100644
@@ -93,4 +93,24 @@ enum {
 #define DECLARE_FLEX_ARRAY(TYPE, NAME) \
 	__DECLARE_FLEX_ARRAY(TYPE, NAME)
 
+/**
+ * TRAILING_OVERLAP() - Overlap a flexible-array member with trailing members.
+ *
+ * Creates a union between a flexible-array member (FAM) in a struct and a set
+ * of additional members that would otherwise follow it.
+ *
+ * @TYPE: Flexible structure type name, including "struct" keyword.
+ * @NAME: Name for a variable to define.
+ * @FAM: The flexible-array member within @TYPE
+ * @MEMBERS: Trailing overlapping members.
+ */
+#define TRAILING_OVERLAP(TYPE, NAME, FAM, MEMBERS)				\
+	union {									\
+		TYPE NAME;							\
+		struct {							\
+			unsigned char __offset_to_##FAM[offsetof(TYPE, FAM)];	\
+			MEMBERS							\
+		};								\
+	}
+
 #endif
Signature · 1 line
2.43.0
Applied
#1 lore raw
Quoted 6 lines · Gustavo A. R. Silva

Add new TRAILING_OVERLAP() helper macro to create a union between a flexible-array member (FAM) and a set of members that would otherwise follow it. This overlays the trailing members onto the FAM while preserving the original memory layout.

Applied to for-next/hardening, thanks!

[1/1] stddef: Introduce TRAILING_OVERLAP() helper macro

      https://git.kernel.org/kees/c/29bb79e9dbf1

Take care,

Signature · 1 line
Kees Cook