[PATCH RFC bpf-next 02/52] libbpf: try to load vmlinux BTF from the kernel first

Alexander Lobakin
2022-06-28T19:51:03Z

From: Larysa Zaremba <larysa.zaremba@intel.com>

Try to acquire vmlinux BTF the same way it's being done for module
BTFs. Use btf_load_next_with_info() and resort to the filesystem
lookup only if it fails.
Also, adjust debug messages in btf__load_vmlinux_btf() to reflect
that it actually tries to load vmlinux BTF.

Signed-off-by: Larysa Zaremba <larysa.zaremba@intel.com>
Signed-off-by: Alexander Lobakin <alexandr.lobakin@intel.com>
---
tools/lib/bpf/btf.c | 32 ++++++++++++++++++++++++++++++--
1 file changed, 30 insertions(+), 2 deletions(-)

diff --git a/tools/lib/bpf/btf.c b/tools/lib/bpf/btf.c
index 7e4dbf71fd52..8ecd50923fab 100644
--- a/tools/lib/bpf/btf.c
+++ b/tools/lib/bpf/btf.c
@@ -4927,6 +4927,25 @@ struct btf *btf_load_next_with_info(__u32 start_id, struct bpf_btf_info *info,
}
}

+static struct btf *btf_load_vmlinux_from_kernel(void)
+{
+ char name[BTF_NAME_BUF_LEN] = { };
+ struct bpf_btf_info info;
+ struct btf *btf;
+
+ memset(&info, 0, sizeof(info));
+ info.name = ptr_to_u64(name);
+ info.name_len = sizeof(name);
+
+ btf = btf_load_next_with_info(0, &info, NULL, true);
+ if (!libbpf_get_error(btf)) {
+ close(btf->fd);
+ btf__set_fd(btf, -1);
+ }
+
+ return btf;
+}
+
/*
* Probe few well-known locations for vmlinux kernel image and try to load BTF
* data out of it to use for target BTF.
@@ -4953,6 +4972,15 @@ struct btf *btf__load_vmlinux_btf(void)
struct btf *btf;
int i, err;

+ btf = btf_load_vmlinux_from_kernel();
+ err = libbpf_get_error(btf);
+ pr_debug("loading vmlinux BTF from kernel: %d\n", err);
+ if (!err)
+ return btf;
+
+ pr_info("failed to load vmlinux BTF from kernel: %d, will look through filesystem\n",
+ err);
+
uname(&buf);

for (i = 0; i < ARRAY_SIZE(locations); i++) {
@@ -4966,14 +4994,14 @@ struct btf *btf__load_vmlinux_btf(void)
else
btf = btf__parse_elf(path, NULL);
err = libbpf_get_error(btf);
- pr_debug("loading kernel BTF '%s': %d\n", path, err);
+ pr_debug("loading vmlinux BTF '%s': %d\n", path, err);
if (err)
continue;

return btf;
}

- pr_warn("failed to find valid kernel BTF\n");
+ pr_warn("failed to find valid vmlinux BTF\n");
return libbpf_err_ptr(-ESRCH);
}

--
2.36.1