libbpf: Add support for extracting kernel symbol addresses
authorAndrii Nakryiko <andriin@fb.com>
Fri, 19 Jun 2020 23:16:56 +0000 (16:16 -0700)
committerAlexei Starovoitov <ast@kernel.org>
Tue, 23 Jun 2020 00:01:48 +0000 (17:01 -0700)
commit1c0c7074fefd769f62dda155e881ca90c9e3e75a
tree7d74539e6f3b1894f2cff9ea88d38c58d887b91e
parent2e33efe32e019328916ce653dc1265d637261993
libbpf: Add support for extracting kernel symbol addresses

Add support for another (in addition to existing Kconfig) special kind of
externs in BPF code, kernel symbol externs. Such externs allow BPF code to
"know" kernel symbol address and either use it for comparisons with kernel
data structures (e.g., struct file's f_op pointer, to distinguish different
kinds of file), or, with the help of bpf_probe_user_kernel(), to follow
pointers and read data from global variables. Kernel symbol addresses are
found through /proc/kallsyms, which should be present in the system.

Currently, such kernel symbol variables are typeless: they have to be defined
as `extern const void <symbol>` and the only operation you can do (in C code)
with them is to take its address. Such extern should reside in a special
section '.ksyms'. bpf_helpers.h header provides __ksym macro for this. Strong
vs weak semantics stays the same as with Kconfig externs. If symbol is not
found in /proc/kallsyms, this will be a failure for strong (non-weak) extern,
but will be defaulted to 0 for weak externs.

If the same symbol is defined multiple times in /proc/kallsyms, then it will
be error if any of the associated addresses differs. In that case, address is
ambiguous, so libbpf falls on the side of caution, rather than confusing user
with randomly chosen address.

In the future, once kernel is extended with variables BTF information, such
ksym externs will be supported in a typed version, which will allow BPF
program to read variable's contents directly, similarly to how it's done for
fentry/fexit input arguments.

Signed-off-by: Andrii Nakryiko <andriin@fb.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Reviewed-by: Hao Luo <haoluo@google.com>
Link: https://lore.kernel.org/bpf/20200619231703.738941-3-andriin@fb.com
tools/lib/bpf/bpf_helpers.h
tools/lib/bpf/btf.h
tools/lib/bpf/libbpf.c