[PATCH v2 09/20] Implement offsetof(), sizeof_member(), typeof_member(), and container_of() in terms of memberof()

From: Alejandro Colomar
Date: Sat Nov 20 2021 - 08:01:41 EST


Signed-off-by: Alejandro Colomar <alx.manpages@xxxxxxxxx>
---
include/linux/container_of.h | 3 ++-
include/linux/offsetof.h | 4 +++-
include/linux/sizeof_field.h | 5 ++++-
include/linux/typeof_member.h | 5 ++++-
4 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/include/linux/container_of.h b/include/linux/container_of.h
index 03809348f333..d1a66e72d246 100644
--- a/include/linux/container_of.h
+++ b/include/linux/container_of.h
@@ -5,6 +5,7 @@

#include <linux/build_bug.h>
#include <linux/err.h>
+#include <linux/memberof.h>
#include <linux/typeof_member.h>


@@ -17,7 +18,7 @@
*/
#define container_of(ptr, type, member) ({ \
void *__mptr = (void *)(ptr); \
- static_assert(__same_type(*(ptr), ((type *)0)->member) || \
+ static_assert(__same_type(*(ptr), memberof(type, member)) || \
__same_type(*(ptr), void), \
"pointer type mismatch in container_of()"); \
((type *)(__mptr - offsetof(type, member))); })
diff --git a/include/linux/offsetof.h b/include/linux/offsetof.h
index 3db431197687..656c758479e8 100644
--- a/include/linux/offsetof.h
+++ b/include/linux/offsetof.h
@@ -5,12 +5,14 @@

#include <uapi/linux/stddef.h>

+#include <linux/memberof.h>
+

#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(T, m) __compiler_offsetof(T, m)
#else
-#define offsetof(T, m) ((size_t)&((T *)0)->m)
+#define offsetof(T, m) ((size_t)&memberof(T, m))
#endif


diff --git a/include/linux/sizeof_field.h b/include/linux/sizeof_field.h
index 15dc10fce8f3..a64accc76055 100644
--- a/include/linux/sizeof_field.h
+++ b/include/linux/sizeof_field.h
@@ -3,13 +3,16 @@
#define _LINUX_SIZEOF_FIELD_H


+#include <linux/memberof.h>
+
+
/**
* sizeof_field() - Report the size of a struct field in bytes
*
* @T: The structure containing the field of interest
* @m: The field (member) to return the size of
*/
-#define sizeof_field(T, m) sizeof((((T *)0)->m))
+#define sizeof_field(T, m) sizeof(memberof(T, m))


#endif /* _LINUX_SIZEOF_FIELD_H */
diff --git a/include/linux/typeof_member.h b/include/linux/typeof_member.h
index 1f3bfb3c17d2..529535a55d40 100644
--- a/include/linux/typeof_member.h
+++ b/include/linux/typeof_member.h
@@ -3,7 +3,10 @@
#define _LINUX_TYPEOF_MEMBER_H


-#define typeof_member(T, m) typeof(((T *)0)->m)
+#include <linux/memberof.h>
+
+
+#define typeof_member(T, m) typeof(memberof(T, m))


#endif /* _LINUX_TYPEOF_MEMBER_H */
--
2.33.1