[PATCH v1 3/8] tools headers: Update offsetof and container_of

Ian Rogers posted 8 patches 1 year ago
There is a newer version of this series
[PATCH v1 3/8] tools headers: Update offsetof and container_of
Posted by Ian Rogers 1 year ago
Update to match kernel definitions in `include/linux/stddef.h` and
`include/linux/container_of.h`.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/include/linux/kernel.h | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/tools/include/linux/kernel.h b/tools/include/linux/kernel.h
index 07cfad817d53..10f74f021d55 100644
--- a/tools/include/linux/kernel.h
+++ b/tools/include/linux/kernel.h
@@ -21,9 +21,8 @@
 #define PERF_ALIGN(x, a)	__PERF_ALIGN_MASK(x, (typeof(x))(a)-1)
 #define __PERF_ALIGN_MASK(x, mask)	(((x)+(mask))&~(mask))
 
-#ifndef offsetof
-#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
-#endif
+#undef offsetof
+#define offsetof(TYPE, MEMBER)	__builtin_offsetof(TYPE, MEMBER)
 
 #ifndef container_of
 /**
@@ -32,10 +31,14 @@
  * @type:	the type of the container struct this is embedded in.
  * @member:	the name of the member within the struct.
  *
+ * WARNING: any const qualifier of @ptr is lost.
  */
-#define container_of(ptr, type, member) ({			\
-	const typeof(((type *)0)->member) * __mptr = (ptr);	\
-	(type *)((char *)__mptr - offsetof(type, member)); })
+#define container_of(ptr, type, member) ({				\
+	void *__mptr = (void *)(ptr);					\
+	static_assert(__same_type(*(ptr), ((type *)0)->member) ||	\
+		      __same_type(*(ptr), void),			\
+		      "pointer type mismatch in container_of()");	\
+	((type *)(__mptr - offsetof(type, member))); })
 #endif
 
 #ifndef max
-- 
2.47.1.613.gc27f4b7a9f-goog
Re: [PATCH v1 3/8] tools headers: Update offsetof and container_of
Posted by Kuan-Wei Chiu 1 year ago
On Fri, Dec 13, 2024 at 01:04:20PM -0800, Ian Rogers wrote:
> Update to match kernel definitions in `include/linux/stddef.h` and
> `include/linux/container_of.h`.
> 
> Signed-off-by: Ian Rogers <irogers@google.com>

Reviewed-by: Kuan-Wei Chiu <visitorckw@gmail.com>

Regards,
Kuan-Wei