OSDN Git Service

libbpf: Ensure that BPF syscall fds are never 0, 1, or 2
authorKumar Kartikeya Dwivedi <memxor@gmail.com>
Thu, 28 Oct 2021 06:34:57 +0000 (12:04 +0530)
committerAlexei Starovoitov <ast@kernel.org>
Thu, 28 Oct 2021 23:30:07 +0000 (16:30 -0700)
commit549a63238603103fa33cecd49487cf6c0f52e503
treeb85e528f00cb0c7950487cbdbe58029356a617af
parent585a3571981d8a93e2211e1ac835d31a63e68cd8
libbpf: Ensure that BPF syscall fds are never 0, 1, or 2

Add a simple wrapper for passing an fd and getting a new one >= 3 if it
is one of 0, 1, or 2. There are two primary reasons to make this change:
First, libbpf relies on the assumption a certain BPF fd is never 0 (e.g.
most recently noticed in [0]). Second, Alexei pointed out in [1] that
some environments reset stdin, stdout, and stderr if they notice an
invalid fd at these numbers. To protect against both these cases, switch
all internal BPF syscall wrappers in libbpf to always return an fd >= 3.
We only need to modify the syscall wrappers and not other code that
assumes a valid fd by doing >= 0, to avoid pointless churn, and because
it is still a valid assumption. The cost paid is two additional syscalls
if fd is in range [0, 2].

  [0]: e31eec77e4ab ("bpf: selftests: Fix fd cleanup in get_branch_snapshot")
  [1]: https://lore.kernel.org/bpf/CAADnVQKVKY8o_3aU8Gzke443+uHa-eGoM0h7W4srChMXU1S4Bg@mail.gmail.com

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: Song Liu <songliubraving@fb.com>
Acked-by: Andrii Nakryiko <andrii@kernel.org>
Link: https://lore.kernel.org/bpf/20211028063501.2239335-5-memxor@gmail.com
tools/lib/bpf/bpf.c
tools/lib/bpf/libbpf_internal.h