All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v2][next] container_of: add container_first() macro
@ 2025-01-29  5:26 Gustavo A. R. Silva
  2025-01-29  5:54 ` Greg KH
  0 siblings, 1 reply; 14+ messages in thread
From: Gustavo A. R. Silva @ 2025-01-29  5:26 UTC (permalink / raw)
  To: Greg KH, Dan Carpenter; +Cc: linux-kernel, Gustavo A. R. Silva, linux-hardening

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@linaro.org>
Signed-off-by: Dan Carpenter <dan.carpenter@linaro.org>
Signed-off-by: Gustavo A. R. Silva <gustavoars@kernel.org>
---

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


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

end of thread, other threads:[~2025-01-30  6:23 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-01-29  5:26 [PATCH v2][next] container_of: add container_first() macro Gustavo A. R. Silva
2025-01-29  5:54 ` Greg KH
2025-01-29  7:29   ` Dan Carpenter
2025-01-29  7:33     ` Dan Carpenter
2025-01-29  8:04       ` Greg KH
2025-01-29  8:05   ` Gustavo A. R. Silva
2025-01-29  8:34     ` Greg KH
2025-01-29 10:39       ` Dan Carpenter
2025-01-29 13:14         ` Greg KH
2025-01-29 14:06           ` Dan Carpenter
2025-01-29 16:08             ` Greg KH
2025-01-29 23:36               ` Gustavo A. R. Silva
2025-01-30  6:14                 ` Greg KH
2025-01-30  6:23                   ` Dan Carpenter

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.