[PATCH v2][next] container_of: add container_first() macro
From: Gustavo A. R. Silva
Date: Wed Jan 29 2025 - 00:26:14 EST
This is like container_of_const() but it contains an assert to
ensure that it's using the first member in the structure.
Co-developed-by: Dan Carpenter <dan.carpenter@xxxxxxxxxx>
Signed-off-by: Dan Carpenter <dan.carpenter@xxxxxxxxxx>
Signed-off-by: Gustavo A. R. Silva <gustavoars@xxxxxxxxxx>
---
I will be using this in my -Wflex-array-member-not-at-end patches. :)
Changes in v2:
- Base this on container_of_const().
v1:
- Link: https://lore.kernel.org/linux-hardening/Zu1vekikKNR5oUoM@elsanto/
include/linux/container_of.h | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/include/linux/container_of.h b/include/linux/container_of.h
index 713890c867be..1a5e5f32db92 100644
--- a/include/linux/container_of.h
+++ b/include/linux/container_of.h
@@ -35,4 +35,15 @@
default: ((type *)container_of(ptr, type, member)) \
)
+/**
+ * container_first - cast first member of a structure out to the containing
+ * structure and preserve the const-ness of the pointer.
+ * @ptr: the pointer to the member.
+ * @type: the type of the container struct this is embedded in.
+ * @member: the name of the member within the struct.
+ */
+#define container_first(ptr, type, member) ({ \
+ static_assert(offsetof(type, member) == 0, "not first member"); \
+ container_of_const(ptr, type, member); })
+
#endif /* _LINUX_CONTAINER_OF_H */
--
2.43.0