tools/nolibc/types: Implement `offsetof()` and `container_of()` macro
authorAmmar Faizi <ammarfaizi2@gnuweeb.org>
Tue, 29 Mar 2022 10:17:34 +0000 (17:17 +0700)
committerPaul E. McKenney <paulmck@kernel.org>
Thu, 21 Apr 2022 00:05:46 +0000 (17:05 -0700)
Implement `offsetof()` and `container_of()` macro. The first use case
of these macros is for `malloc()`, `realloc()` and `free()`.

Acked-by: Willy Tarreau <w@1wt.eu>
Signed-off-by: Ammar Faizi <ammarfaizi2@gnuweeb.org>
Signed-off-by: Paul E. McKenney <paulmck@kernel.org>
tools/include/nolibc/types.h

index 357e60a..9599970 100644 (file)
@@ -191,4 +191,15 @@ struct stat {
 #define major(dev) ((unsigned int)(((dev) >> 8) & 0xfff))
 #define minor(dev) ((unsigned int)(((dev) & 0xff))
 
+#ifndef offsetof
+#define offsetof(TYPE, FIELD) ((size_t) &((TYPE *)0)->FIELD)
+#endif
+
+#ifndef container_of
+#define container_of(PTR, TYPE, FIELD) ({                      \
+       __typeof__(((TYPE *)0)->FIELD) *__FIELD_PTR = (PTR);    \
+       (TYPE *)((char *) __FIELD_PTR - offsetof(TYPE, FIELD)); \
+})
+#endif
+
 #endif /* _NOLIBC_TYPES_H */