diff mbox series

[bpf-next,v3,17/21] tools/libpf: add offsetof/container_of macro in bpf_helpers.h

Message ID 20200507053935.1545181-1-yhs@fb.com
State Changes Requested
Delegated to: BPF Maintainers
Headers show
Series bpf: implement bpf iterator for kernel data | expand

Commit Message

Yonghong Song May 7, 2020, 5:39 a.m. UTC
These two helpers will be used later in bpf_iter bpf program
bpf_iter_netlink.c. Put them in bpf_helpers.h since they could
be useful in other cases.

Signed-off-by: Yonghong Song <yhs@fb.com>
---
 tools/lib/bpf/bpf_helpers.h | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

Comments

Andrii Nakryiko May 8, 2020, 7:48 p.m. UTC | #1
On Wed, May 6, 2020 at 10:40 PM Yonghong Song <yhs@fb.com> wrote:
>
> These two helpers will be used later in bpf_iter bpf program
> bpf_iter_netlink.c. Put them in bpf_helpers.h since they could
> be useful in other cases.
>
> Signed-off-by: Yonghong Song <yhs@fb.com>
> ---

Not sure #ifndef/#endif guards are needed, but won't hurt either.

Acked-by: Andrii Nakryiko <andriin@fb.com>

>  tools/lib/bpf/bpf_helpers.h | 14 ++++++++++++++
>  1 file changed, 14 insertions(+)
>

[...]
diff mbox series

Patch

diff --git a/tools/lib/bpf/bpf_helpers.h b/tools/lib/bpf/bpf_helpers.h
index da00b87aa199..f67dce2af802 100644
--- a/tools/lib/bpf/bpf_helpers.h
+++ b/tools/lib/bpf/bpf_helpers.h
@@ -36,6 +36,20 @@ 
 #define __weak __attribute__((weak))
 #endif
 
+/*
+ * Helper macro to manipulate data structures
+ */
+#ifndef offsetof
+#define offsetof(TYPE, MEMBER)  ((size_t)&((TYPE *)0)->MEMBER)
+#endif
+#ifndef container_of
+#define container_of(ptr, type, member)				\
+	({							\
+		void *__mptr = (void *)(ptr);			\
+		((type *)(__mptr - offsetof(type, member)));	\
+	})
+#endif
+
 /*
  * Helper structure used by eBPF C program
  * to describe BPF map attributes to libbpf loader