Blob Blame History Raw
From: Andrii Nakryiko <andriin@fb.com>
Date: Fri, 13 Dec 2019 17:47:09 -0800
Subject: bpftool: Generate externs datasec in BPF skeleton
Patch-mainline: v5.6-rc1
Git-commit: 2ad97d473db57ab866f0756806bb94515f7f2551
References: bsc#1177028

Add support for generation of mmap()-ed read-only view of libbpf-provided
extern variables. As externs are not supposed to be provided by user code
(that's what .data, .bss, and .rodata is for), don't mmap() it initially. Only
after skeleton load is performed, map .extern contents as read-only memory.

Signed-off-by: Andrii Nakryiko <andriin@fb.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Link: https://lore.kernel.org/bpf/20191214014710.3449601-4-andriin@fb.com
Acked-by: Gary Lin <glin@suse.com>
---
 tools/bpf/bpftool/gen.c |    4 ++++
 tools/lib/bpf/libbpf.c  |   10 +++++-----
 2 files changed, 9 insertions(+), 5 deletions(-)

--- a/tools/bpf/bpftool/gen.c
+++ b/tools/bpf/bpftool/gen.c
@@ -82,6 +82,8 @@ static const char *get_map_ident(const s
 		return "rodata";
 	else if (str_has_suffix(name, ".bss"))
 		return "bss";
+	else if (str_has_suffix(name, ".extern"))
+		return "externs"; /* extern is a C keyword */
 	else
 		return NULL;
 }
@@ -109,6 +111,8 @@ static int codegen_datasec_def(struct bp
 		sec_ident = "bss";
 	else if (strcmp(sec_name, ".rodata") == 0)
 		sec_ident = "rodata";
+	else if (strcmp(sec_name, ".extern") == 0)
+		sec_ident = "externs"; /* extern is a C keyword */
 	else
 		return 0;
 
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -6850,7 +6850,8 @@ int bpf_object__open_skeleton(struct bpf
 			return -ESRCH;
 		}
 
-		if (mmaped)
+		/* externs shouldn't be pre-setup from user code */
+		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_EXTERN)
 			*mmaped = (*map)->mmaped;
 	}
 
@@ -6883,7 +6884,6 @@ int bpf_object__load_skeleton(struct bpf
 		size_t mmap_sz = bpf_map_mmap_sz(map);
 		int prot, map_fd = bpf_map__fd(map);
 		void **mmaped = s->maps[i].mmaped;
-		void *remapped;
 
 		if (!mmaped)
 			continue;
@@ -6908,9 +6908,9 @@ int bpf_object__load_skeleton(struct bpf
 		 * as per normal clean up procedure, so we don't need to worry
 		 * about it from skeleton's clean up perspective.
 		 */
-		remapped = mmap(*mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED,
-				map_fd, 0);
-		if (remapped == MAP_FAILED) {
+		*mmaped = mmap(map->mmaped, mmap_sz, prot,
+				MAP_SHARED | MAP_FIXED, map_fd, 0);
+		if (*mmaped == MAP_FAILED) {
 			err = -errno;
 			*mmaped = NULL;
 			pr_warning("failed to re-mmap() map '%s': %d\n",