Auto-detect BPF fmodret targets
Subsystems (17)
v3 cover Auto-detect BPF fmodret targets
Due to recent changes in software development, security fixes and attack-surface hardening increasingly need to land on production systems _now_. BPF has proven really useful for producing mitigations, but its error-injection capabilities remain limited: the list of possible fmodret hooks is static, which no longer matches reality.
This series allows more kernel functions to be targeted by fmodret BPF programs. New functions are marked as fmodret-attachable _automatically_, if CONFIG_CLANG_PLUGIN_BPF_SCAN_IR is on. The latter is off by default, but can be enabled with CLANG >= 19 with a matching llvm-config and host C++ compiler. Supported archs are x86_64 and arm64. (The existing static lists are, of course, still supported.)
The decision on "if this function is safe to inject error" left to BPF program writers. The motivation/discussion can be found in the recent talk [1]. The safety/operation model of this new functionality can be briefly stated as "a trusted operator can already do this with live patch". However, the BPF approach is more flexible. See the recent talk on shirudo [2] for more details on how to build a trusted system managing such policies.
The changes introduced are as follows.
The first part of the series changes the way the lists of fmodret-attachable functions are passed to kernel, namely, now a function is considered as a fmodret target if it has a bpf_fmodret BTF tag. This tag is generated by the resolve_btfids tool. The sleepable hooks are in addition tagged with bpf_fmodret_sleepable. The old-style static hooks, explicitly defined in kernel/modules, also get the bpf_fmodret tag. The security_*, syscall, and error-injection hooks are _not_ all marked with the tag, and any new rules do not apply to them.
Currently static hooks are defined using sets (BTF_FMODRET_START/END). When the minimal versions of GCC and pahole will support tags, the sets will go away in favour of just declaring a proper tag.
The second part enables automatic search and usage of fmodret targets:
* The search is performed by a new compiler pass via a compiler plugin. The candidates are written into a new .BTF_fmodret_candidates section which is dropped later in the final object. Roughly speaking, a candidate is a function with a clean (side-effectless) path to "return -errno".
* After the compilation is done, the resolve_btfids tool scans the candidates, drops some of them (redefined weak, non-ftracable, etc.), and assigns proper BTF tags: bpf_fmodret/bpf_fmodret_sleepable and bpf_fmodret_retval. The latter lists all possible return values the analysis found. The verifier rejects the values outside this list. (An alternative approach, maybe a followup, is to auto-convert all negative error values returned by a BPF program with a value from this list.)
The following selftests are added:
* Test fmod_ret BTF decl tags and attach permission: the declared targets get the right tags, and fmod_ret programs attach only to tagged functions.
* Test fmod_ret candidates found by bpf_scan_ir: functions in bpf_testmod annotated with the values the analysis must find, checked against the generated tags. The verifier allows only these values on every path and rejects extensions and tail calls of such programs.
Finally, the last patch adds a new bpftool fmodret command to simplify listing the functions having bpf_fmodret* tags.
Planned follow ups, more or less in order:
* LLVM LTO support
* GCC support
* Allow injecting errors into functions returning pointers
* More complex logic to gather more candidates (mainly, error propagation, left out for now to reduce the number of commits in the series)
Build times with and without plugin enabled are nearly the same:
with: without:
real 5m48.377s real 5m47.543s
user 136m7.002s user 135m57.994s
sys 10m13.739s sys 10m12.635sLinks:
[1] Scaling BPF LSM hooks and error injection across the kernel,
https://lpc.events/event/20/contributions/2435/
[2] Shirudo: BPF live-patching infra for the agentic era,
https://lpc.events/event/20/contributions/2437/
v2 -> v3:
* verifier: accept a range in R0 at exit if all its values are allowed. Reason: in between v1 and v2 a change was merged:
the verifier now joins states, so two allowed constants which meet at one exit, like 0 and -1, became a range and the program was rejected. (bpf-ci bot)
* do not tag kfuncs with KF_IMPLICIT_ARGS, because the trampoline is built for the prototype without the implicit arguments and would not save them. (bpf-ci bot)
* count and log every function with a shared name (sashiko)
* fix a comment and rename a variable (bpf-ci bot)
* simplify code in bpf_scan_ir (bpf-ci bot)
* bpftool: fix man page (bpf-ci bot)
v1 -> v2: https://lore.kernel.org/bpf/[email protected]/
* Rebase onto bpf-next, as upstream removed mark_chain_precision()
* Move tests into their own bpf_test_retval.ko from bpf_testmod.ko.
The problem was with pahole, which can't properly find symbols in modules build from two or more objects (was only prominent with GCC, which reorders sections while linking objects together)
* Fix the fmodret/extension test for GCC (force a const return)
* resolve_btfids: dedup and cleanup code (bpf-ci bot)
* bpftool: drop dead code (bpf-ci bot)
* Rename two tests properly, remove dead code (bpf-ci bot)
* Exclude KCSAN and UBSAN instrumentation from tests (sashiko)
v1: https://lore.kernel.org/bpf/[email protected]/T/#t
Anton Protopopov (18):
bpf: Add BTF ID sets for fmod_ret targets
bpf: Add a btf_id_set8_entry helper
bpf: Build fmod_ret target sets from BTF decl tags selftests/bpf: Declare bpf_fentry_test1 in tracing tests
bpf: Declare fmod_ret targets with BTF_FMODRET sets selftests/bpf: Test fmod_ret BTF decl tags and attach permission
scripts: Add LLVM plugin infrastructure
bpf: Add the bpf_scan_ir LLVM plugin
bpf: Find fmod_ret candidates in bpf_scan_ir
bpf: Allow writes to private stack objects in bpf_scan_ir
bpf: Follow PHIs in bpf_scan_ir
bpf: Follow integer casts in bpf_scan_ir
bpf: Check the return values of fmod_ret programs on found targets
bpf: Require the JIT for fmod_ret programs on found 64-bit targets
resolve_btfids: Tag fmod_ret candidates as targets selftests/bpf: Test fmod_ret candidates found by bpf_scan_ir selftests/bpf: Enable bpf_scan_ir in the config
bpftool: List and show fmod_ret targets
MAINTAINERS | 10 + Makefile | 6 +- arch/Kconfig | 1 + arch/arm64/kernel/pi/Makefile | 1 + arch/x86/boot/startup/Makefile | 2 + arch/x86/um/vdso/Makefile | 2 +- drivers/firmware/efi/libstub/Makefile | 2 +- include/asm-generic/vmlinux.lds.h | 7 +- include/linux/bpf.h | 6 + include/linux/btf.h | 9 +- include/linux/btf_ids.h | 24 +- include/linux/compiler-version.h | 5 + kernel/bpf/btf.c | 124 +- kernel/bpf/syscall.c | 1 + kernel/bpf/verifier.c | 151 +++ lib/vdso/Makefile.include | 3 + net/bpf/test_run.c | 12 +- net/mptcp/bpf.c | 15 +- scripts/Makefile | 1 + scripts/Makefile.btf | 1 + scripts/Makefile.llvm-plugins | 10 + scripts/Makefile.modfinal | 1 + scripts/Makefile.vmlinux | 3 + scripts/bpf/fmodret.lds | 6 + scripts/bpf/fmodret_metadata.h | 29 + scripts/gen-btf.sh | 4 +- scripts/link-vmlinux.sh | 7 + scripts/llvm-plugins/Kconfig | 33 + scripts/llvm-plugins/Makefile | 21 + scripts/llvm-plugins/bpf_scan_ir.cpp | 363 +++++ scripts/mod/modpost.c | 1 + scripts/module.lds.S | 5 + .../bpftool/Documentation/bpftool-fmodret.rst | 111 ++ tools/bpf/bpftool/Documentation/bpftool.rst | 4 +- tools/bpf/bpftool/bash-completion/bpftool | 31 + tools/bpf/bpftool/fmodret.c | 896 ++++++++++++ tools/bpf/bpftool/main.c | 3 +- tools/bpf/bpftool/main.h | 1 + tools/bpf/resolve_btfids/Build | 1 + tools/bpf/resolve_btfids/fmodret.c | 1203 +++++++++++++++++ tools/bpf/resolve_btfids/fmodret.h | 28 + tools/bpf/resolve_btfids/main.c | 187 ++- tools/include/linux/btf_ids.h | 24 +- tools/objtool/check.c | 1 + tools/testing/selftests/bpf/Makefile | 2 +- tools/testing/selftests/bpf/config | 2 + .../selftests/bpf/prog_tests/fmodret_retval.c | 211 +++ .../selftests/bpf/prog_tests/fmodret_tags.c | 155 +++ .../selftests/bpf/progs/fmodret_retval.c | 254 ++++ .../selftests/bpf/progs/fmodret_retval_ext.c | 55 + .../selftests/bpf/progs/fsession_test.c | 2 + .../bpf/progs/get_func_ip_fsession_test.c | 2 + .../selftests/bpf/progs/tracing_multi_check.c | 2 +- .../testing/selftests/bpf/test_kmods/Makefile | 15 +- .../bpf/test_kmods/bpf_test_retval_main.c | 12 + .../selftests/bpf/test_kmods/bpf_testmod.c | 11 +- .../bpf/test_kmods/bpf_testmod_retval.c | 328 +++++ .../test_kmods/bpf_testmod_retval_strong.c | 28 + 58 files changed, 4353 insertions(+), 82 deletions(-) create mode 100644 scripts/Makefile.llvm-plugins create mode 100644 scripts/bpf/fmodret.lds create mode 100644 scripts/bpf/fmodret_metadata.h create mode 100644 scripts/llvm-plugins/Kconfig create mode 100644 scripts/llvm-plugins/Makefile create mode 100644 scripts/llvm-plugins/bpf_scan_ir.cpp create mode 100644 tools/bpf/bpftool/Documentation/bpftool-fmodret.rst create mode 100644 tools/bpf/bpftool/fmodret.c create mode 100644 tools/bpf/resolve_btfids/fmodret.c create mode 100644 tools/bpf/resolve_btfids/fmodret.h create mode 100644 tools/testing/selftests/bpf/prog_tests/fmodret_retval.c create mode 100644 tools/testing/selftests/bpf/prog_tests/fmodret_tags.c create mode 100644 tools/testing/selftests/bpf/progs/fmodret_retval.c create mode 100644 tools/testing/selftests/bpf/progs/fmodret_retval_ext.c create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_test_retval_main.c create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_testmod_retval.c create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_testmod_retval_strong.c
Signature · 1 line
2.43.0
PATCH v3 1/18 bpf: Add BTF ID sets for fmod_ret targets
Add BTF_SET8_FMODRET and the BTF_FMODRET_START() and BTF_FMODRET_END() macros to declare the functions BPF fmod_ret programs may attach to. They work like kfunc sets: each entry is a BTF_ID_FLAGS() line and KF_SLEEPABLE marks targets sleepable programs may attach to.
Teach resolve_btfids to find these sets and tag every listed function in BTF with a "bpf_fmodret" decl tag, plus "bpf_fmodret_sleepable" when KF_SLEEPABLE is set. The sleepable tag never comes without "bpf_fmodret" and readers of the tags may rely on that. Share the set walk with the kfunc collection. Any other flag is an error. Nothing in the code refers to the sets, so keep .BTF_ids in the linker script, or --gc-sections may discard them.
Nothing declares such sets yet and the kernel does not read the tags yet.
--- include/asm-generic/vmlinux.lds.h | 2 +- include/linux/btf_ids.h | 14 ++++ tools/bpf/resolve_btfids/main.c | 121 +++++++++++++++++++++++++----- tools/include/linux/btf_ids.h | 14 ++++ 4 files changed, 130 insertions(+), 21 deletions(-)
include/asm-generic/vmlinux.lds.h +1 -1
@@ -714,7 +714,7 @@BTF_INLINE_LINK \ . = ALIGN(PAGE_SIZE); \ .BTF_ids : AT(ADDR(.BTF_ids) - LOAD_OFFSET) { \ - *(.BTF_ids) \ + KEEP(*(.BTF_ids)) \ }#else #define BTF
include/linux/btf_ids.h +14 -0
@@ -13,6 +13,12 @@ struct btf_id_set {/* This flag implies BTF_SET8 holds kfunc(s) */ #define BTF_SET8_KFUNCS (1 << 0) +/* +* This flag implies BTF_SET8 holds functions which BPF fmod_ret, fentry and +* fexit programs may attach to. Per-function flags: KF_SLEEPABLE only. +*/ +#define BTF_SET8_FMODRET (1 << 1) +struct btf_id_set8 {u32 cnt;u32 flags;
@@ -215,6 +221,12 @@ __BTF_SET8_START(name, local, BTF_SET8_KFUNCS)#define BTF_KFUNCS_END (name) \ BTF_SET8_END(name) +#define BTF_FMODRET_START (name) \ +__BTF_SET8_START(name, local, BTF_SET8_FMODRET) + +#define BTF_FMODRET_END (name) \ +BTF_SET8_END(name) +#else #define BTF_ID_LIST (name) static u32 __maybe_unused name[128];
@@ -231,6 +243,8 @@ BTF_SET8_END(name)#define BTF_SET8_END (name)#define BTF_KFUNCS_START (name) static struct btf_id_set8 __maybe_unused name = { .flags = BTF_SET8_KFUNCS };#define BTF_KFUNCS_END (name) +#define BTF_FMODRET_START (name) static struct btf_id_set8 __maybe_unused name = { .flags = BTF_SET8_FMODRET }; +#define BTF_FMODRET_END (name)#endif /* CONFIG_DEBUG_INFO_BTF */
tools/bpf/resolve_btfids/main.c +101 -20
228 lines not on this page · raw message
tools/include/linux/btf_ids.h +14 -0
@@ -13,6 +13,12 @@ struct btf_id_set {/* This flag implies BTF_SET8 holds kfunc(s) */ #define BTF_SET8_KFUNCS (1 << 0) +/* +* This flag implies BTF_SET8 holds functions which BPF fmod_ret, fentry and +* fexit programs may attach to. Per-function flags: KF_SLEEPABLE only. +*/ +#define BTF_SET8_FMODRET (1 << 1) +struct btf_id_set8 {u32 cnt;u32 flags;
@@ -214,6 +220,12 @@ __BTF_SET8_START(name, local, BTF_SET8_KFUNCS)#define BTF_KFUNCS_END (name) \ BTF_SET8_END(name) +#define BTF_FMODRET_START (name) \ +__BTF_SET8_START(name, local, BTF_SET8_FMODRET) + +#define BTF_FMODRET_END (name) \ +BTF_SET8_END(name) +#else #define BTF_ID_LIST (name) static u32 __maybe_unused name[128];
@@ -230,6 +242,8 @@ BTF_SET8_END(name)#define BTF_SET8_END (name)#define BTF_KFUNCS_START (name) static struct btf_id_set8 __maybe_unused name = { .flags = BTF_SET8_KFUNCS };#define BTF_KFUNCS_END (name) +#define BTF_FMODRET_START (name) static struct btf_id_set8 __maybe_unused name = { .flags = BTF_SET8_FMODRET }; +#define BTF_FMODRET_END (name)#endif /* CONFIG_DEBUG_INFO_BTF */
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v3 bpf-next 01/18] bpf: Add BTF ID sets for fmod_ret targets
TL;DR: Comment nit only: the BTF_SET8_FMODRET comment (also in tools/include) says the set governs fentry/fexit attachment, but non-sleepable fentry/fexit never consult it. It could mislead readers.
Quoted 1 line
bpf: Add BTF ID sets for
fmod_rettargets
TL;DR: Comment nit only: the BTF_SET8_FMODRET comment (also in tools/include) says the set governs fentry/fexit attachment, but non-sleepable fentry/fexit never consult it. It could mislead readers.
Quoted 3 lines
include/linux/btf_ids.h +0
-0
[ ... ]
include/linux/btf_ids.h struct btf_id_set { · line 21
Quoted 10 lines
include/linux/btf_ids.h +6
-0@@ -13,6 +13,12 @@ struct btf_id_set {/* This flag implies BTF_SET8 holds kfunc(s) */ #define BTF_SET8_KFUNCS (1 << 0) +/* +* This flag implies BTF_SET8 holds functions which BPF fmod_ret, fentry and +* fexit programs may attach to. Per-function flags: KF_SLEEPABLE only. +*/ +#define BTF_SET8_FMODRET (1 << 1) +
This isn't a bug, but does this comment describe the set accurately? It says the set holds functions that fmod_ret, fentry and fexit programs may attach to, which reads as if the set controls fentry/fexit attachment.
The set is only read through btf_kfunc_is_modify_return(), which has two callers. bpf_check_attach_target() uses it for non-sleepable BPF_MODIFY_RETURN only:
} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
...
if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
!check_attach_modify_return(addr, tname))
ret = 0;and btf_id_allow_sleepable() uses it for sleepable programs only, and requires KF_SLEEPABLE:
u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog);
if (flags && (*flags & KF_SLEEPABLE))
return 0;Non-sleepable fentry and fexit programs never look at the set. This remains true through the end of the series (6dc8474f6891 has the same two callers).
The commit message ("the functions BPF fmod_ret programs may attach to ... KF_SLEEPABLE marks targets sleepable programs may attach to") and the resolve_btfids header comment ("the targets of BPF fmod_ret programs") describe it differently. Someone could read this comment and add a function to a BTF_FMODRET set to make fentry/fexit attach work, which would also allow fmod_ret programs to override its return value.
Could the wording be along the lines of "the set holds fmod_ret targets, and KF_SLEEPABLE additionally lets sleepable fentry, fexit and fmod_ret programs attach"? The identical comment in tools/include/linux/btf_ids.h has the same problem.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
Re: [PATCH v3 bpf-next 01/18] bpf: Add BTF ID sets for fmod_ret targets
Quoted 56 lines · On Wed, Nov 11, 2026 at 9:01 AM <[email protected]> wrote:
Quoted 2 lines
bpf: Add BTF ID sets for
fmod_rettargetsTL;DR: Comment nit only: the
BTF_SET8_FMODRETcomment (also intools/include) says the set governs fentry/fexit attachment, but non-sleepable fentry/fexit never consult it. It could mislead readers.Quoted 3 lines
include/linux/btf_ids.h +0
-0[ ... ]
include/linux/btf_ids.h struct btf_id_set { · line 21
Quoted 10 lines
include/linux/btf_ids.h +6
-0@@ -13,6 +13,12 @@ struct btf_id_set {/* This flag implies BTF_SET8 holds kfunc(s) */ #define BTF_SET8_KFUNCS (1 << 0) +/* +* This flag implies BTF_SET8 holds functions which BPF fmod_ret, fentry and +* fexit programs may attach to. Per-function flags: KF_SLEEPABLE only. +*/ +#define BTF_SET8_FMODRET (1 << 1) +This isn't a bug, but does this comment describe the set accurately? It says the set holds functions that
fmod_ret, fentry and fexit programs may attach to, which reads as if the set controls fentry/fexit attachment.The set is only read through
btf_kfunc_is_modify_return(), which has two callers.bpf_check_attach_target()uses it for non-sleepableBPF_MODIFY_RETURNonly:} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { ... if (btf_kfunc_is_modify_return(btf, btf_id, prog) || !check_attach_modify_return(addr, tname)) ret = 0;and
btf_id_allow_sleepable()uses it for sleepable programs only, and requiresKF_SLEEPABLE:u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog); if (flags && (*flags & KF_SLEEPABLE)) return 0;Non-sleepable fentry and fexit programs never look at the set. This remains true through the end of the series (
6dc8474f6891has the same two callers).The commit message ("the functions BPF
fmod_retprograms may attach to ...KF_SLEEPABLEmarks targets sleepable programs may attach to") and theresolve_btfidsheader comment ("the targets of BPFfmod_retprograms") describe it differently. Someone could read this comment and add a function to aBTF_FMODRETset to make fentry/fexit attach work, which would also allowfmod_retprograms to override its return value.
Quoted 4 lines
Could the wording be along the lines of "the set holds
fmod_rettargets, andKF_SLEEPABLEadditionally lets sleepable fentry, fexit andfmod_retprograms attach"? The identical comment intools/include/linux/btf_ids.hhas the same problem.
Yes, I will fix it, and send on the next occasion.
Quoted 6 lines
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.mdCI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
PATCH v3 2/18 bpf: Add a btf_id_set8_entry helper
In reply to Anton ProtopopovThe pairs of a struct btf_id_set8 have an anonymous type, and the btf_id_set8_contains() helper returns a void pointer to the pair it finds. All its users but one only check if a set contains an ID. The one which needs the flags, btf_kfunc_id_set_contains(), finds them as the word next to the ID.
Name the type struct btf_id_set8_pair, and add a btf_id_set8_entry() helper which returns a pointer to it. Make btf_id_set8_contains() return bool, like btf_id_set_contains() does, and use the new helper in btf_kfunc_id_set_contains().
The layout of the set doesn't change. Update the tools copy of btf_ids.h as well. A later patch uses the new helper to set the flags of a pair.
--- include/linux/btf.h | 8 +++++++- include/linux/btf_ids.h | 10 ++++++---- kernel/bpf/btf.c | 9 ++++----- tools/include/linux/btf_ids.h | 10 ++++++---- 4 files changed, 23 insertions(+), 14 deletions(-)
include/linux/btf.h +7 -1
@@ -558,11 +558,17 @@ static inline bool btf_id_set_contains(const struct btf_id_set *set, u32 id)return bsearch (&id, set->ids, set->cnt,sizeof (u32), btf_id_cmp_func) !=NULL ; } -static inline void *btf_id_set8_contains (const struct btf_id_set8 *set,u32 id) +static inline struct btf_id_set8_pair * +btf_id_set8_entry (const struct btf_id_set8 *set,u32 id) {return bsearch (&id, set->pairs, set->cnt,sizeof (set->pairs[0 ]), btf_id_cmp_func); } +static inline bool btf_id_set8_contains (const struct btf_id_set8 *set,u32 id) +{ +return btf_id_set8_entry (set, id) !=NULL ; +} +bool btf_param_match_suffix (const struct btf *btf,const struct btf_param *arg,const char *suffix);
include/linux/btf_ids.h +6 -4
@@ -19,13 +19,15 @@ struct btf_id_set {*/ #define BTF_SET8_FMODRET (1 << 1) +struct btf_id_set8_pair { +u32 id; +u32 flags; +}; +struct btf_id_set8 {u32 cnt;u32 flags; -struct { -u32 id; -u32 flags; - } pairs[]; +struct btf_id_set8_pair pairs[]; };#ifdef CONFIG_DEBUG_INFO_BTF
kernel/bpf/btf.c +4 -5
@@ -9973,8 +9973,8 @@ static u32 *btf_kfunc_id_set_contains(const struct btf *btf, enum btf_kfunc_hook hook, u32 kfunc_btf_id) { +struct btf_id_set8_pair *pair;struct btf_id_set8 *set; -u32 *id;if (hook >=BTF_KFUNC_HOOK_MAX )return NULL ;
@@ -9983,11 +9983,10 @@ static u32 *btf_kfunc_id_set_contains(const struct btf *btf, set = btf->kfunc_set_tab->sets[hook];if (!set)return NULL ; - id =btf_id_set8_contains (set, kfunc_btf_id); -if (!id) + pair =btf_id_set8_entry (set, kfunc_btf_id); +if (!pair)return NULL ; -/* The flags for BTF ID are located next to it */ -return id +1 ; +return &pair->flags; } static bool __btf_kfunc_is_allowed(const struct btf *btf,
tools/include/linux/btf_ids.h +6 -4
@@ -19,13 +19,15 @@ struct btf_id_set {*/ #define BTF_SET8_FMODRET (1 << 1) +struct btf_id_set8_pair { +u32 id; +u32 flags; +}; +struct btf_id_set8 {u32 cnt;u32 flags; -struct { -u32 id; -u32 flags; - } pairs[]; +struct btf_id_set8_pair pairs[]; };#ifdef CONFIG_DEBUG_INFO_BTF
Signature · 1 line
2.43.0
PATCH v3 3/18 bpf: Build fmod_ret target sets from BTF decl tags
In reply to Anton ProtopopovMark functions tagged with the "bpf_fmodret{,_sleepable}" decl tags (added by resolve_btfids) as fmodret targets. Add the KF_SLEEPABLE flag for the latter.
Do this for vmlinux at fs_initcall and for a module before its BTF becomes visible to anyone else, so nothing can look at the set while it is built.
The IDs come from the BTF after relocation, so they are final. Unlike the IDs of a set registered by a module, they must not be relocated, and the set is installed directly instead of through btf_populate_kfunc_set(). (The register_btf_fmodret_id_set() keeps working, it will be removed by a later patch.)
The set shares kfunc_set_tab with the kfunc sets, but its flags only say how a target may be attached. Skip it in btf_kfunc_check_flag(), so a kfunc which is also an fmod_ret target keeps its own flags, such as KF_IMPLICIT_ARGS. Otherwise btf_attach_func_proto() finds the flags of such a kfunc inconsistent and attaching to it fails.
--- kernel/bpf/btf.c | 114 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 113 insertions(+), 1 deletion(-)
kernel/bpf/btf.c +113 -1
@@ -9307,6 +9307,8 @@ enum { }; #ifdef CONFIG_DEBUG_INFO_BTF_MODULES +static int btf_register_fmodret_tags(struct btf *btf); + struct btf_module { struct list_head list; struct module *module;
@@ -9476,6 +9478,15 @@ static int btf_module_notify(struct notifier_block *nb, unsigned long op, } goto out; } +/* +* Do this before the BTF is visible to anyone else. A failure +* is not fatal: the module loads, but without fmod_ret targets. +*/ + err =btf_register_fmodret_tags (btf); +if (err) +pr_warn ("failed to register fmod_ret targets of module [%s]: %d\n" , + mod->name, err); + err =btf_alloc_id (btf);if (err) {btf_free (btf);
@@ -10100,7 +10111,9 @@ u32 *btf_kfunc_flags(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_p }/* -* Check a single KF_* @flag on a kfunc across all of its hook sets. +* Check a single KF_* @flag on a kfunc across all of its hook sets. The set of +* fmod_ret targets is not one of them: its flags only say how a target may be +* attached, and a kfunc which is also a target keeps its own flags. * Returns: * * 1 if @flag is set * * 0 if @flag is not set
@@ -10115,6 +10128,8 @@ int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag)u32 *flags;for (hook =0 ; hook <BTF_KFUNC_HOOK_MAX ; hook++) { +if (hook ==BTF_KFUNC_HOOK_FMODRET ) +continue ; flags =btf_kfunc_id_set_contains (btf, hook, kfunc_btf_id);if (!flags)continue ;
@@ -10182,6 +10197,103 @@ int register_btf_kfunc_id_set(enum bpf_prog_type prog_type, }EXPORT_SYMBOL_GPL (register_btf_kfunc_id_set); +/* +* Targets of fmod_ret programs are marked in BTF by resolve_btfids, see +* BTF_SET8_FMODRET. A "bpf_fmodret" decl tag on a function makes it a target. +* A target which sleepable programs may attach to also has a +* "bpf_fmodret_sleepable" tag, which never comes without "bpf_fmodret". +*/ +#define BTF_FMODRET_TAG "bpf_fmodret" +#define BTF_FMODRET_SLEEPABLE_TAG "bpf_fmodret_sleepable" + +/* Return the function which T tags with decl tag NAME, or 0 */ +static u32 btf_fmodret_tag_func (const struct btf *btf,const struct btf_type *t, +const char *name) +{ +const struct btf_type *func; + +if (!btf_type_is_decl_tag (t) ||btf_type_decl_tag (t)->component_idx !=-1 ) +return 0 ; +if (strcmp (btf_name_by_offset (btf, t->name_off), name)) +return 0 ; + func =btf_type_by_id (btf, t->type); +if (!func || !btf_type_is_func (func)) +return 0 ; +return t->type; +} + +/* Build the set of fmod_ret targets of BTF from its decl tags */ +static int btf_register_fmodret_tags (struct btf *btf) +{ +u32 id, func_id, nr_types =btf_nr_types (btf), cnt =0 ; +struct btf_kfunc_set_tab *tab; +struct btf_id_set8 *set; + +for (id =btf_start_id (btf); id < nr_types; id++) + cnt += !!btf_fmodret_tag_func (btf,btf_type_by_id (btf, id),BTF_FMODRET_TAG ); +if (!cnt) +return 0 ; + + set =kmalloc (struct_size (set, pairs, cnt),GFP_KERNEL | __GFP_NOWARN); +if (!set) +return -ENOMEM ; + set->flags =0 ; + set->cnt =0 ; +for (id =btf_start_id (btf); id < nr_types; id++) { + func_id =btf_fmodret_tag_func (btf,btf_type_by_id (btf, id),BTF_FMODRET_TAG ); +if (!func_id) +continue ; + set->pairs[set->cnt].id = func_id; + set->pairs[set->cnt].flags =0 ; + set->cnt++; + } +sort (set->pairs, set->cnt,sizeof (set->pairs[0 ]), btf_id_cmp_func,NULL ); + +/* Each sleepable tag marks a function which is already in the set */ +for (id =btf_start_id (btf); id < nr_types; id++) { +struct btf_id_set8_pair *pair; + + func_id =btf_fmodret_tag_func (btf,btf_type_by_id (btf, id), +BTF_FMODRET_SLEEPABLE_TAG ); +if (!func_id) +continue ; + pair =btf_id_set8_entry (set, func_id); +if (pair) + pair->flags |=KF_SLEEPABLE ; + } + + tab = btf->kfunc_set_tab; +if (!tab) { + tab =kzalloc_obj (*tab,GFP_KERNEL | __GFP_NOWARN); +if (!tab) { +kfree (set); +return -ENOMEM ; + } + btf->kfunc_set_tab = tab; + } +if (tab->sets[BTF_KFUNC_HOOK_FMODRET ]) { +kfree (set); +return -EEXIST ; + } + tab->sets[BTF_KFUNC_HOOK_FMODRET ] = set; +return 0 ; +} + +static int __init btf_fmodret_tags_init (void ) +{ +struct btf *btf; +int err; + + btf =btf_get_module_btf (NULL ); +if (IS_ERR_OR_NULL (btf)) +return PTR_ERR_OR_ZERO (btf); + + err =btf_register_fmodret_tags (btf); +btf_put (btf); +return err; +} +fs_initcall (btf_fmodret_tags_init); +/* This function must be invoked only from initcalls/module init functions */ int register_btf_fmodret_id_set (const struct btf_kfunc_id_set *kset) {
Signature · 1 line
2.43.0
PATCH v3 4/18 selftests/bpf: Declare bpf_fentry_test1 in tracing tests
In reply to Anton Protopopovbpftool puts bpf_fentry_test1 into vmlinux.h only because the function is in a kfunc set, which exists to let fmod_ret programs attach to it. A later patch moves it to an fmod_ret set, which does not make a function a kfunc, and the declaration disappears.
The tests only compare its address. Declare it explicitly, as get_func_ip_test.c does. The declaration matches the one in vmlinux.h, so it builds both before and after.
--- tools/testing/selftests/bpf/progs/fsession_test.c | 2 ++ tools/testing/selftests/bpf/progs/get_func_ip_fsession_test.c | 2 ++ tools/testing/selftests/bpf/progs/tracing_multi_check.c | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/progs/fsession_test.c +2 -0
@@ -4,6 +4,8 @@#include <bpf/bpf_helpers.h> #include <bpf/bpf_tracing.h> +extern int bpf_fentry_test1(int a) __ksym; + char _license[] SEC("license") = "GPL";__u64 test1_entry_result =0 ;
tools/testing/selftests/bpf/progs/get_func_ip_fsession_test.c +2 -0
@@ -3,6 +3,8 @@#include <bpf/bpf_helpers.h> #include <bpf/bpf_tracing.h> +extern int bpf_fentry_test1(int a) __ksym; + char _license[] SEC("license") = "GPL";__u64 test1_entry_result =0 ;
tools/testing/selftests/bpf/progs/tracing_multi_check.c +1 -1
@@ -8,7 +8,7 @@ char _license[] SEC("license") = "GPL";int pid =0 ;bool test_cookies = false; -/* bpf_fentry_test1 is exported as kfunc via vmlinux.h */ +extern int bpf_fentry_test1(int a) __ksym; extern const void bpf_fentry_test2 __ksym; extern const void bpf_fentry_test3 __ksym; extern const void bpf_fentry_test4 __ksym;
Signature · 1 line
2.43.0
PATCH v3 5/18 bpf: Declare fmod_ret targets with BTF_FMODRET sets
In reply to Anton ProtopopovMove the fmod_ret targets of the BPF test functions, MPTCP and bpf_testmod from registered kfunc sets to BTF_FMODRET sets. Attachment flags stay the
same: bpf_fentry_test1 is still the sleepable target.
These functions are no longer kfuncs, so the bpf_kfunc decl tag, and with it the vmlinux.h declaration, is gone. Only bpf_modify_return_test_tp() stays a kfunc, as it is also in the common_btf_ids kfunc set. Selftests which need bpf_fentry_test1 declare it themselves.
No code registers an fmod_ret set anymore, as the kernel builds them from BTF. Remove register_btf_fmodret_id_set(), so a module cannot register a second set next to the one from its BTF.
--- include/linux/btf.h | 1 - kernel/bpf/btf.c | 7 ------- net/bpf/test_run.c | 12 +++--------- net/mptcp/bpf.c | 15 ++------------- .../selftests/bpf/test_kmods/bpf_testmod.c | 11 ++--------- 5 files changed, 7 insertions(+), 39 deletions(-)
include/linux/btf.h +0 -1
@@ -632,7 +632,6 @@ u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog);int register_btf_kfunc_id_set (enum bpf_prog_type prog_type,const struct btf_kfunc_id_set *s); -int register_btf_fmodret_id_set (const struct btf_kfunc_id_set *kset);s32 btf_find_dtor_kfunc (struct btf *btf,u32 btf_id);int register_btf_id_dtor_kfuncs (const struct btf_id_dtor_kfunc *dtors,u32 add_cnt,struct module *owner);
kernel/bpf/btf.c +0 -7
@@ -10294,13 +10294,6 @@ static int __init btf_fmodret_tags_init(void) }fs_initcall (btf_fmodret_tags_init); -/* This function must be invoked only from initcalls/module init functions */ -int register_btf_fmodret_id_set (const struct btf_kfunc_id_set *kset) -{ -return __register_btf_kfunc_id_set (BTF_KFUNC_HOOK_FMODRET , kset); -} -EXPORT_SYMBOL_GPL (register_btf_fmodret_id_set); -s32 btf_find_dtor_kfunc (struct btf *btf,u32 btf_id) {struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
net/bpf/test_run.c +3 -9
@@ -643,17 +643,12 @@ CFI_NOSEAL(bpf_kfunc_call_memb_release_dtor);__bpf_kfunc_end_defs (); -BTF_KFUNCS_START (bpf_test_modify_return_ids) +BTF_FMODRET_START(bpf_test_modify_return_ids) BTF_ID_FLAGS(func, bpf_modify_return_test) BTF_ID_FLAGS(func, bpf_modify_return_test2) BTF_ID_FLAGS(func, bpf_modify_return_test_tp) BTF_ID_FLAGS(func, bpf_fentry_test1, KF_SLEEPABLE) -BTF_KFUNCS_END (bpf_test_modify_return_ids) - -static const struct btf_kfunc_id_set bpf_test_modify_return_set = { - .owner =THIS_MODULE , - .set = &bpf_test_modify_return_ids, -}; +BTF_FMODRET_END(bpf_test_modify_return_ids) BTF_KFUNCS_START(test_sk_check_kfunc_ids) BTF_ID_FLAGS(func, bpf_kfunc_call_test_release, KF_RELEASE)
@@ -1905,8 +1900,7 @@ static int __init bpf_prog_test_run_init(void) };int ret; - ret =register_btf_fmodret_id_set (&bpf_test_modify_return_set); - ret = ret ?:register_btf_kfunc_id_set (BPF_PROG_TYPE_SCHED_CLS , &bpf_prog_test_kfunc_set); + ret =register_btf_kfunc_id_set (BPF_PROG_TYPE_SCHED_CLS , &bpf_prog_test_kfunc_set); ret = ret ?:register_btf_kfunc_id_set (BPF_PROG_TYPE_TRACING , &bpf_prog_test_kfunc_set); ret = ret ?:register_btf_kfunc_id_set (BPF_PROG_TYPE_SYSCALL , &bpf_prog_test_kfunc_set); return ret ?: register_btf_id_dtor_kfuncs(bpf_prog_test_dtor_kfunc,
net/mptcp/bpf.c +2 -13
@@ -20,17 +20,6 @@ struct mptcp_sock *bpf_mptcp_sock_from_subflow(struct sock *sk)return NULL ; } -BTF_SET8_START (bpf_mptcp_fmodret_ids) +BTF_FMODRET_START(bpf_mptcp_fmodret_ids) BTF_ID_FLAGS(func, update_socket_protocol) -BTF_SET8_END (bpf_mptcp_fmodret_ids) - -static const struct btf_kfunc_id_set bpf_mptcp_fmodret_set = { - .owner =THIS_MODULE , - .set = &bpf_mptcp_fmodret_ids, -}; - -static int __init bpf_mptcp_kfunc_init (void ) -{ -return register_btf_fmodret_id_set (&bpf_mptcp_fmodret_set); -} -late_initcall (bpf_mptcp_kfunc_init); +BTF_FMODRET_END(bpf_mptcp_fmodret_ids)
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +2 -9
@@ -2607,15 +2607,9 @@ struct bpf_struct_ops testmod_multi_st_ops = {extern int bpf_fentry_test1 (int a); -BTF_KFUNCS_START (bpf_testmod_trampoline_count_ids) +BTF_FMODRET_START (bpf_testmod_trampoline_count_ids)BTF_ID_FLAGS (func ,bpf_testmod_trampoline_count_test ) -BTF_KFUNCS_END (bpf_testmod_trampoline_count_ids) - -static const struct -btf_kfunc_id_set bpf_testmod_trampoline_count_fmodret_set = { - .owner =THIS_MODULE , - .set = &bpf_testmod_trampoline_count_ids, -}; +BTF_FMODRET_END (bpf_testmod_trampoline_count_ids) static intbpf_testmod_init (void) {
@@ -2633,7 +2627,6 @@ static int bpf_testmod_init(void) ret = ret ?:register_btf_kfunc_id_set (BPF_PROG_TYPE_TRACING , &bpf_testmod_kfunc_set); ret = ret ?:register_btf_kfunc_id_set (BPF_PROG_TYPE_SYSCALL , &bpf_testmod_kfunc_set); ret = ret ?:register_btf_kfunc_id_set (BPF_PROG_TYPE_STRUCT_OPS , &bpf_testmod_kfunc_set); - ret = ret ?:register_btf_fmodret_id_set (&bpf_testmod_trampoline_count_fmodret_set); ret = ret ?:register_bpf_struct_ops (&bpf_bpf_testmod_ops, bpf_testmod_ops); ret = ret ?:register_bpf_struct_ops (&bpf_testmod_ops2, bpf_testmod_ops2); ret = ret ?:register_bpf_struct_ops (&bpf_testmod_ops3, bpf_testmod_ops3);
Signature · 1 line
2.43.0
PATCH v3 6/18 selftests/bpf: Test fmod_ret BTF decl tags and attach permission
In reply to Anton ProtopopovCheck that resolve_btfids tags the fmod_ret targets of vmlinux and of bpf_testmod with "bpf_fmodret", that only bpf_fentry_test1 has the "bpf_fmodret_sleepable" tag, and that a function which is not a target has none.
Load minimal fmod_ret programs to check that the kernel builds its target set from the tags: a target loads, a function which is not a target does not, and sleepable programs load only for the sleepable target.
--- .../selftests/bpf/prog_tests/fmodret_tags.c | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/fmodret_tags.c
tools/testing/selftests/bpf/prog_tests/fmodret_tags.c new file +155 -0
@@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <test_progs.h> +#include <linux/filter.h> +#include <bpf/btf.h> + +#define TAG_FMODRET "bpf_fmodret" +#define TAG_FMODRET_SLEEPABLE "bpf_fmodret_sleepable" + +static bool func_has_tag (const struct btf *btf,const char *func,const char *tag) +{ +int func_id, id, nr_types; + + func_id =btf__find_by_name_kind (btf, func,BTF_KIND_FUNC ); +if (func_id <0 ) +return false; + + nr_types =btf__type_cnt (btf); +for (id =1 ; id < nr_types; id++) { +const struct btf_type *t =btf__type_by_id (btf, id); + +if (!btf_is_decl_tag (t) || t->type != func_id || +btf_decl_tag (t)->component_idx !=-1 ) +continue ; +if (!strcmp (btf__name_by_offset (btf, t->name_off), tag)) +return true; + } + +return false; +} + +static void test_vmlinux_tags (void ) +{ +struct btf *btf; + + btf =btf__load_vmlinux_btf (); +if (!ASSERT_OK_PTR (btf,"btf__load_vmlinux_btf" )) +return ; + +ASSERT_TRUE (func_has_tag (btf,"bpf_modify_return_test" ,TAG_FMODRET ),"modify_return_test" ); +ASSERT_TRUE (func_has_tag (btf,"bpf_modify_return_test2" ,TAG_FMODRET ), +"modify_return_test2" ); +ASSERT_TRUE (func_has_tag (btf,"bpf_modify_return_test_tp" ,TAG_FMODRET ), +"modify_return_test_tp" ); +ASSERT_TRUE (func_has_tag (btf,"bpf_fentry_test1" ,TAG_FMODRET ),"fentry_test1" ); +ASSERT_TRUE (func_has_tag (btf,"update_socket_protocol" ,TAG_FMODRET ), +"update_socket_protocol" ); + +/* Only bpf_fentry_test1 is a sleepable target */ +ASSERT_TRUE (func_has_tag (btf,"bpf_fentry_test1" ,TAG_FMODRET_SLEEPABLE ), +"fentry_test1_sleepable" ); +ASSERT_FALSE (func_has_tag (btf,"bpf_modify_return_test" ,TAG_FMODRET_SLEEPABLE ), +"modify_return_test_sleepable" ); +ASSERT_FALSE (func_has_tag (btf,"bpf_modify_return_test2" ,TAG_FMODRET_SLEEPABLE ), +"modify_return_test2_sleepable" ); +ASSERT_FALSE (func_has_tag (btf,"bpf_modify_return_test_tp" ,TAG_FMODRET_SLEEPABLE ), +"modify_return_test_tp_sleepable" ); +ASSERT_FALSE (func_has_tag (btf,"update_socket_protocol" ,TAG_FMODRET_SLEEPABLE ), +"update_socket_protocol_sleepable" ); + +/* A function which is not a target has no tag */ +ASSERT_GT (btf__find_by_name_kind (btf,"bpf_fentry_test2" ,BTF_KIND_FUNC ),0 , +"fentry_test2_exists" ); +ASSERT_FALSE (func_has_tag (btf,"bpf_fentry_test2" ,TAG_FMODRET ),"fentry_test2" ); +ASSERT_FALSE (func_has_tag (btf,"bpf_fentry_test2" ,TAG_FMODRET_SLEEPABLE ), +"fentry_test2_sleepable" ); + +btf__free (btf); +} + +static void test_module_tags (void ) +{ +struct btf *vmlinux_btf, *module_btf; + +if (!env.has_testmod) { +test__skip (); +return ; + } + + vmlinux_btf =btf__load_vmlinux_btf (); +if (!ASSERT_OK_PTR (vmlinux_btf,"btf__load_vmlinux_btf" )) +return ; + module_btf =btf__load_module_btf ("bpf_testmod" , vmlinux_btf); +if (!module_btf && errno ==ENOENT ) { +printf ("%s:SKIP:bpf_testmod has no BTF\n" , __func__); +test__skip (); + goto out; + } +if (!ASSERT_OK_PTR (module_btf,"btf__load_module_btf" )) + goto out; + +ASSERT_TRUE (func_has_tag (module_btf,"bpf_testmod_trampoline_count_test" ,TAG_FMODRET ), +"trampoline_count_test" ); +ASSERT_FALSE (func_has_tag (module_btf,"bpf_testmod_trampoline_count_test" , +TAG_FMODRET_SLEEPABLE ),"trampoline_count_test_sleepable" ); +ASSERT_FALSE (func_has_tag (module_btf,"bpf_testmod_fentry_test1" ,TAG_FMODRET ), +"testmod_fentry_test1" ); + +btf__free (module_btf); +out: +btf__free (vmlinux_btf); +} + +/* Load a minimal fmod_ret program which attaches to function BTF_ID */ +static int load_fmod_ret (int btf_id,__u32 prog_flags) +{ +struct bpf_insn insns[] = { +BPF_MOV64_IMM (BPF_REG_0 ,0 ), +BPF_EXIT_INSN (), + }; +LIBBPF_OPTS (bpf_prog_load_opts, opts, + .expected_attach_type = BPF_MODIFY_RETURN, + .prog_flags = prog_flags, + .attach_btf_id = btf_id, + ); + +return bpf_prog_load (BPF_PROG_TYPE_TRACING ,NULL ,"GPL" , insns,ARRAY_SIZE (insns), &opts); +} + +static void check_load (const char *func,__u32 prog_flags,bool allowed,const char *name) +{ +int btf_id, fd; + + btf_id =libbpf_find_vmlinux_btf_id (func,BPF_MODIFY_RETURN ); +if (!ASSERT_GT (btf_id,0 , func)) +return ; + fd =load_fmod_ret (btf_id, prog_flags); +if (allowed) +ASSERT_GE (fd,0 , name); +else +ASSERT_LT (fd,0 , name); +if (fd >=0 ) +close (fd); +} + +static void test_attach_permission (void ) +{ +check_load ("bpf_modify_return_test" ,0 , true,"target" ); +check_load ("bpf_fentry_test1" ,0 , true,"sleepable_target" ); +check_load ("bpf_fentry_test2" ,0 , false,"not_a_target" ); + +check_load ("bpf_fentry_test1" ,BPF_F_SLEEPABLE , true,"sleepable_prog_sleepable_target" ); +check_load ("bpf_modify_return_test" ,BPF_F_SLEEPABLE , false, +"sleepable_prog_nonsleepable_target" ); +} + +void test_fmodret_tags (void ) +{ +if (test__start_subtest ("vmlinux" )) +test_vmlinux_tags (); +if (test__start_subtest ("module" )) +test_module_tags (); +if (test__start_subtest ("attach_permission" )) +test_attach_permission (); +}
Signature · 1 line
2.43.0
PATCH v3 7/18 scripts: Add LLVM plugin infrastructure
In reply to Anton ProtopopovAdd scripts/llvm-plugins and the corresponding Makefiles and Kconfig for LLVM IR passes loaded with -fpass-plugin, similar to the GCC plugins. Individual plugins register their configuration and shared objects separately. No plugin is added yet.
Use LLVM_CONFIG to obtain the host compiler and linker flags. Require llvm-config of the same major version as clang, which loads the plugins:
unlike GCC, clang does not provide the headers for its plugins. Require also a host C++ compiler which accepts the headers and flags of llvm-config.
Build plugins without linking LLVM component libraries; their LLVM symbols are resolved by the compiler loading the shared library. Include a generated header so objects are rebuilt when enabled plugins change. Track the headers of a plugin, LLVM ones included, with a dependency file, as the GCC plugins do.
Export LLVM_PLUGINS_CFLAGS so vDSO, EFI stub and early boot builds can exclude the plugins, as they exclude the GCC plugins.
Add the plugin infrastructure to the CLANG/LLVM BUILD SUPPORT entry in MAINTAINERS.
--- MAINTAINERS | 2 ++ Makefile | 6 +++++- arch/Kconfig | 1 + arch/arm64/kernel/pi/Makefile | 1 + arch/x86/boot/startup/Makefile | 2 ++ arch/x86/um/vdso/Makefile | 2 +- drivers/firmware/efi/libstub/Makefile | 2 +- include/linux/compiler-version.h | 5 +++++ lib/vdso/Makefile.include | 3 +++ scripts/Makefile | 1 + scripts/Makefile.llvm-plugins | 8 ++++++++ scripts/llvm-plugins/Kconfig | 17 +++++++++++++++++ scripts/llvm-plugins/Makefile | 21 +++++++++++++++++++++ 13 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 scripts/Makefile.llvm-plugins create mode 100644 scripts/llvm-plugins/Kconfig create mode 100644 scripts/llvm-plugins/Makefile
MAINTAINERS +2 -0
@@ -6562,7 +6562,9 @@ C: irc://irc.libera.chat/clangbuiltlinux F: Documentation/kbuild/llvm.rst F: include/linux/compiler-clang.h F: scripts/Makefile.clang +F: scripts/Makefile.llvm-plugins F: scripts/clang-tools/ +F: scripts/llvm-plugins/ K: \b(?i:clang|llvm)\b CLK API
Makefile +5 -1
@@ -457,10 +457,13 @@ endif HOSTCC = $(LLVM_PREFIX)clang$(LLVM_SUFFIX) HOSTCXX = $(LLVM_PREFIX)clang++$(LLVM_SUFFIX) +LLVM_CONFIG ?= $(LLVM_PREFIX)llvm-config$(LLVM_SUFFIX) else HOSTCC = gcc HOSTCXX = g++ +LLVM_CONFIG ?= llvm-config endif +export LLVM_CONFIG HOSTRUSTC = rustc HOSTPKG_CONFIG = pkg-config
@@ -1211,10 +1214,11 @@ include-$(CONFIG_AUTOFDO_CLANG) += scripts/Makefile.autofdo include-$(CONFIG_PROPELLER_CLANG) += scripts/Makefile.propeller include-$(CONFIG_WARN_CONTEXT_ANALYSIS) += scripts/Makefile.context-analysis include-$(CONFIG_GCC_PLUGINS) += scripts/Makefile.gcc-plugins +include-$(CONFIG_LLVM_PLUGINS) += scripts/Makefile.llvm-plugins include $(addprefix $(srctree)/, $(include-y)) -# scripts/Makefile.gcc-plugins is intentionally included last. +# The compiler plugin Makefiles are intentionally included last. # Do not add $(call cc-option,...) below this line. When you build the kernel # from the clean source tree, the GCC plugins do not exist at this point.
arch/Kconfig +1 -0
@@ -1772,6 +1772,7 @@ config HAVE_GENERIC_TIF_BITS source "kernel/gcov/Kconfig" source "scripts/gcc-plugins/Kconfig" +source "scripts/llvm-plugins/Kconfig" config FUNCTION_ALIGNMENT_4B bool
arch/arm64/kernel/pi/Makefile +1 -0
@@ -10,6 +10,7 @@ KBUILD_CFLAGS := $(subst $(CC_FLAGS_FTRACE),,$(KBUILD_CFLAGS)) -fpie \ -D__DISABLE_EXPORTS -ffreestanding -D__NO_FORTIFY \ -fno-asynchronous-unwind-tables -fno-unwind-tables \ $(CONFIG_CC_OPT_NO_ADDRSIG) +KBUILD_CFLAGS := $(filter-out $(LLVM_PLUGINS_CFLAGS),$(KBUILD_CFLAGS)) # this code may run with the MMU off so disable unaligned accesses CFLAGS_map_range.o += -mstrict-align
arch/x86/boot/startup/Makefile +2 -0
@@ -12,6 +12,8 @@ KBUILD_CFLAGS += -D__DISABLE_EXPORTS -mcmodel=small -fPIC \ # disable ftrace hooks and LTO KBUILD_CFLAGS := $(subst $(CC_FLAGS_FTRACE),,$(KBUILD_CFLAGS)) KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_LTO),$(KBUILD_CFLAGS)) +# LLVM plugins may add data with absolute addresses +KBUILD_CFLAGS := $(filter-out $(LLVM_PLUGINS_CFLAGS),$(KBUILD_CFLAGS)) KASAN_SANITIZE := n KCSAN_SANITIZE := n KMSAN_SANITIZE := n
arch/x86/um/vdso/Makefile +1 -1
@@ -37,7 +37,7 @@ CFL := $(PROFILING) -mcmodel=small -fPIC -O2 -fasynchronous-unwind-tables -m64 \ $(filter -g%,$(KBUILD_CFLAGS)) -fno-stack-protector \ -fno-omit-frame-pointer -foptimize-sibling-calls -$(vobjs): KBUILD_CFLAGS += $(CFL) +$(vobjs): KBUILD_CFLAGS := $(filter-out $(LLVM_PLUGINS_CFLAGS),$(KBUILD_CFLAGS)) $(CFL) # # vDSO code runs in userspace and -pg doesn't help with profiling anyway.
drivers/firmware/efi/libstub/Makefile +1 -1
@@ -6,7 +6,7 @@ # enabled, even if doing so doesn't break the build. # -cflags-y := $(KBUILD_CFLAGS) +cflags-y := $(filter-out $(LLVM_PLUGINS_CFLAGS),$(KBUILD_CFLAGS)) # x86 links the stub into the decompressor rather than the kernel proper, so # drop the kernel's code model, calling convention, and stack alignment, and
include/linux/compiler-version.h +5 -0
@@ -24,6 +24,11 @@#include <generated/gcc-plugins.h> #endif +/* Rebuild objects when an LLVM plugin changes. */ +#ifdef LLVM_PLUGINS +#include <generated/llvm-plugins.h> +#endif +/* * If the randstruct seed itself changes (whether for GCC plugins or * Clang), the entire tree needs to be rebuilt since the randomization of
lib/vdso/Makefile.include +3 -0
@@ -1,5 +1,8 @@ # SPDX-License-Identifier: GPL-2.0 +# vDSO code executes outside the kernel. +KBUILD_CFLAGS := $(filter-out $(LLVM_PLUGINS_CFLAGS),$(KBUILD_CFLAGS)) + GENERIC_VDSO_MK_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) GENERIC_VDSO_DIR := $(dir $(GENERIC_VDSO_MK_PATH))
scripts/Makefile +1 -0
@@ -66,6 +66,7 @@ hostprogs += unifdef gen_packed_field_checks targets += module.lds subdir-$(CONFIG_GCC_PLUGINS) += gcc-plugins +subdir-$(CONFIG_LLVM_PLUGINS) += llvm-plugins subdir-$(CONFIG_GENKSYMS) += genksyms subdir-$(CONFIG_GENDWARFKSYMS) += gendwarfksyms subdir-$(CONFIG_SECURITY_SELINUX) += selinux
scripts/Makefile.llvm-plugins new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-only + +LLVM_PLUGIN := $(llvm-plugin-y) +LLVM_PLUGINS_CFLAGS := $(strip $(addprefix -fpass-plugin=$(objtree)/scripts/llvm-plugins/, \ + $(LLVM_PLUGIN)) -DLLVM_PLUGINS) +export LLVM_PLUGIN LLVM_PLUGINS_CFLAGS + +KBUILD_CFLAGS += $(LLVM_PLUGINS_CFLAGS)
scripts/llvm-plugins/Kconfig new file +17 -0
@@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-only + +menuconfig LLVM_PLUGINS + bool "LLVM plugins" + depends on CC_IS_CLANG + depends on $(success,$(LLVM_CONFIG) --version) + # The plugins are built against the headers of llvm-config and loaded + # by clang, so both must come from the same LLVM release + depends on $(success,test "$(shell,$(LLVM_CONFIG) --version 2>/dev/null | cut -d. -f1)" = "$(shell,$(CC) -dumpversion | cut -d. -f1)") + # The host C++ compiler must accept the LLVM headers and flags + depends on $(success,echo '#include <llvm/Config/llvm-config.h>' | $(HOSTCXX) $(shell,$(LLVM_CONFIG) --cxxflags 2>/dev/null) -x c++ -fsyntax-only -) + default y + help + LLVM plugins add compiler passes to kernel and module builds. + Building them requires LLVM development headers and llvm-config + of the same major version as clang. Each plugin has its own option + below and is built only if that option is enabled.
scripts/llvm-plugins/Makefile new file +21 -0
@@ -0,0 +1,21 @@ +# SPDX-License-Identifier: GPL-2.0-only + +always-y += $(LLVM_PLUGIN) +targets += $(LLVM_PLUGIN) +clean-files += *.so + +# Run llvm-config only to build a plugin, not when this Makefile is parsed +llvm_cxxflags = $(shell $(LLVM_CONFIG) --cxxflags) +llvm_ldflags = $(shell $(LLVM_CONFIG) --ldflags) + +quiet_cmd_llvm_plugin = HOSTCXX $@ + cmd_llvm_plugin = $(HOSTCXX) -Wp,-MD,$(depfile) $(KBUILD_HOSTCXXFLAGS) \ + $(llvm_cxxflags) -fPIC -shared $(KBUILD_HOSTLDFLAGS) -o $@ $< \ + $(llvm_ldflags) + +$(obj)/%.so: $(src)/%.cpp FORCE + $(call if_changed_dep,llvm_plugin) + +$(obj)/../../include/generated/llvm-plugins.h: $(addprefix $(obj)/, $(LLVM_PLUGIN)) FORCE + $(call if_changed,touch) +always-y += ../../include/generated/llvm-plugins.h
Signature · 1 line
2.43.0
PATCH v3 8/18 bpf: Add the bpf_scan_ir LLVM plugin
In reply to Anton ProtopopovAdd a new bpf_scan_ir.cpp LLVM plugin selected by the new CONFIG_CLANG_PLUGIN_BPF_SCAN_IR option. The new plugin depends on DEBUG_INFO_BTF, as the information it produces eventually ends up in kernel/module BTF. It needs LLVM 19 or later and supports only x86_64 and arm64. For now LTO_CLANG is not supported. It is a planned follow-up. The new pass runs after optimization over the IR of the kernel and modules.
The purpose of this plugin is to gather information about functions, which can be targets for BPF fmodret programs (have paths without side effects which return errors). The records about functions are stored in the new .BTF_fmodret_candidates section which is created by plugin and later is processed by the resolve_btfids tool. The actual plugin logic is added in the following commits.
Keep .BTF_fmodret_candidates and its relocations in the temporary BTF link and discard it before the later links, so the build-only function references do not create runtime relocations. Keep it in modules until their BTF is generated and remove it then, also when BTF generation is skipped. Without module BTF, discard it at the module link. Let modpost accept the section. Let objtool skip its relocations in IBT validation:
a record has the address of its function, which is not an indirect branch target. The vDSO, the EFI stub and the early boot code are built without the plugins, so position-independent startup objects do not contain the absolute function pointers of the records.
The record format and the linker script are in scripts/bpf, so a future GCC plugin can share them.
--- MAINTAINERS | 7 ++ include/asm-generic/vmlinux.lds.h | 3 +- scripts/Makefile.llvm-plugins | 2 + scripts/Makefile.modfinal | 1 + scripts/Makefile.vmlinux | 3 + scripts/bpf/fmodret.lds | 6 ++ scripts/bpf/fmodret_metadata.h | 29 ++++++ scripts/gen-btf.sh | 4 +- scripts/link-vmlinux.sh | 7 ++ scripts/llvm-plugins/Kconfig | 16 ++++ scripts/llvm-plugins/bpf_scan_ir.cpp | 126 +++++++++++++++++++++++++++ scripts/mod/modpost.c | 1 + scripts/module.lds.S | 5 ++ tools/objtool/check.c | 1 + 14 files changed, 209 insertions(+), 2 deletions(-) create mode 100644 scripts/bpf/fmodret.lds create mode 100644 scripts/bpf/fmodret_metadata.h create mode 100644 scripts/llvm-plugins/bpf_scan_ir.cpp
MAINTAINERS +7 -0
@@ -5064,6 +5064,13 @@ S: Supported F: arch/x86/net/ X: arch/x86/net/bpf_jit_comp32.c +BPF [COMPILER PLUGINS] +M: Anton Protopopov <[email protected]> +L: [email protected] +S: Maintained +F: scripts/bpf/ +F: scripts/llvm-plugins/bpf_* + BPF [CORE] M: Alexei Starovoitov <[email protected]> M: Daniel Borkmann <[email protected]>
include/asm-generic/vmlinux.lds.h +2 -1
@@ -886,7 +886,8 @@ KLP_SYMID#define MODINFO \ - .modinfo (INFO) : { KEEP(*(.modinfo)) } + .modinfo (INFO) : { KEEP(*(.modinfo)) } \ + .BTF_fmodret_candidates 0 (INFO) : { KEEP(*(.BTF_fmodret_candidates)) }#ifdef CONFIG_GENERIC_BUG #define BUG_TABLE \
scripts/Makefile.llvm-plugins +2 -0
@@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only +llvm-plugin-$(CONFIG_CLANG_PLUGIN_BPF_SCAN_IR) += bpf_scan_ir.so + LLVM_PLUGIN := $(llvm-plugin-y) LLVM_PLUGINS_CFLAGS := $(strip $(addprefix -fpass-plugin=$(objtree)/scripts/llvm-plugins/, \ $(LLVM_PLUGIN)) -DLLVM_PLUGINS)
scripts/Makefile.modfinal +1 -0
@@ -42,6 +42,7 @@ quiet_cmd_btf_ko = BTF [M] $@ cmd_btf_ko = \ if [ ! -f $(objtree)/vmlinux ]; then \ printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \ + $(OBJCOPY) --remove-section=.BTF_fmodret_candidates $@; \ else \ $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \ fi;
scripts/Makefile.vmlinux +3 -0
@@ -73,6 +73,9 @@ vmlinux.unstripped: scripts/link-vmlinux.sh vmlinux.o .vmlinux.export.o $(KBUILD ifdef CONFIG_DEBUG_INFO_BTF vmlinux.unstripped: $(RESOLVE_BTFIDS) $(srctree)/scripts/gen-btf.sh endif +ifdef CONFIG_CLANG_PLUGIN_BPF_SCAN_IR +vmlinux.unstripped: $(srctree)/scripts/bpf/fmodret.lds +endif ifdef CONFIG_BUILDTIME_TABLE_SORT vmlinux.unstripped: scripts/sorttable
scripts/bpf/fmodret.lds new file +6 -0
@@ -0,0 +1,6 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +SECTIONS { + /DISCARD/ : { + *(.BTF_fmodret_candidates) + } +}
scripts/bpf/fmodret_metadata.h new file +29 -0
@@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef FMODRET_METADATA_H +#define FMODRET_METADATA_H + +/* +* The records which the BPF compiler plugins write to .BTF_fmodret_candidates +* for resolve_btfids, one for each function with values and for each weak +* definition. If a function has two weak definitions, the record of the one +* which loses the link would describe the body of the other, so both need a +* record to make the function ambiguous. A record is packed, target-endian and +* aligned to the target pointer size: +* +* u32 magic, version, size, flags; +* ptr function; +* u32 nr_values, reserved; +* s64 values[nr_values]; +* +* The values are the errors which clean paths of the function return, sorted +* and unique. +*/ +#define FMODRET_META_MAGIC 0x46524d32U +#define FMODRET_META_VERSION 1U +#define FMODRET_META_HEADER_SIZE (ptr_size) (24 + (ptr_size)) +#define FMODRET_META_VALUE_SIZE 8 + +#define FMODRET_FN_WEAK (1U << 0) +#define FMODRET_FN_RET64 (1U << 1) + +#endif
scripts/gen-btf.sh +3 -1
@@ -120,7 +120,9 @@ gen_btf_o() embed_btf_data() { - ${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF ${ELF_FILE} + # resolve_btfids has consumed the compiler plugin records of the module + ${OBJCOPY} --add-section .BTF=${ELF_FILE}.BTF \ + --remove-section=.BTF_fmodret_candidates ${ELF_FILE} # a module might not have a .BTF_ids or .BTF.base section btf_base="${ELF_FILE}.BTF.base"
scripts/link-vmlinux.sh +7 -0
@@ -89,6 +89,13 @@ vmlinux_link() ldlibs= fi + if is_enabled CONFIG_CLANG_PLUGIN_BPF_SCAN_IR; then + if [ "${output}" = ".tmp_vmlinux1" ]; then + ldflags="${ldflags} ${wl}--emit-relocs" + else + ldflags="${ldflags} ${wl}--script=${srctree}/scripts/bpf/fmodret.lds" + fi + fi ldflags="${ldflags} ${wl}--script=${objtree}/${KBUILD_LDS}" # The kallsyms linking does not need debug symbols included.
scripts/llvm-plugins/Kconfig +16 -0
@@ -15,3 +15,19 @@ menuconfig LLVM_PLUGINS Building them requires LLVM development headers and llvm-config of the same major version as clang. Each plugin has its own option below and is built only if that option is enabled. + +if LLVM_PLUGINS + +config CLANG_PLUGIN_BPF_SCAN_IR + bool "Scan optimized LLVM IR for BPF" + depends on X86_64 || ARM64 + depends on DEBUG_INFO_BTF + depends on !LTO_CLANG + depends on CLANG_VERSION >= 190000 + help + Find the functions which return errors on paths without side + effects and describe them in .BTF_fmodret_candidates for + resolve_btfids. The section is discarded from the final kernel + and modules. + +endif
scripts/llvm-plugins/bpf_scan_ir.cpp new file +126 -0
126 lines not on this page · raw message
scripts/mod/modpost.c +1 -0
@@ -772,6 +772,7 @@ static const char *const section_white_list[] =".llvm.call-graph-profile" ,/* call graph */ "__llvm_covfun" ,"__llvm_covmap" , +".BTF_fmodret_candidates" ,".klp.symid" ,/* objtool --klp-symids */ NULL };
scripts/module.lds.S +5 -0
@@ -27,6 +27,11 @@ SECTIONS { __ex_table 0 : ALIGN(4) { KEEP(*(__ex_table)) } __patchable_function_entries 0 : { *(__patchable_function_entries) } +#ifdef CONFIG_DEBUG_INFO_BTF_MODULES + .BTF_fmodret_candidates 0 (INFO) : { KEEP(*(.BTF_fmodret_candidates)) } +#else + /DISCARD/ : { *(.BTF_fmodret_candidates) } +#endif .init.klp_funcs 0 : ALIGN(8) { KEEP(*(.init.klp_funcs)) } .init.klp_objects 0 : ALIGN(8) { KEEP(*(.init.klp_objects)) }
tools/objtool/check.c +1 -0
@@ -4657,6 +4657,7 @@ static int validate_ibt(struct objtool_file *file) !strcmp (sec->name,"__jump_table" ) || !strcmp (sec->name,".init.klp_funcs" ) || !strcmp (sec->name,"__mcount_loc" ) || + !strcmp (sec->name,".BTF_fmodret_candidates" ) || !strcmp (sec->name,".llvm.call-graph-profile" ) || !strcmp (sec->name,".llvm_bb_addr_map" ) || !strcmp(sec->name, "__tracepoints") ||
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v3 bpf-next 08/18] bpf: Add the bpf_scan_ir LLVM plugin
TL;DR: Nit only: with the plugin enabled, link-vmlinux.sh adds --emit-relocs to the .tmp_vmlinux1 link, so two existing comments (top-level Makefile, vmlinux_link()) now say the opposite; they…
Quoted 1 line
bpf: Add the
bpf_scan_irLLVM plugin
TL;DR: Nit only: with the plugin enabled, link-vmlinux.sh adds --emit-relocs to the .tmp_vmlinux1 link, so two existing comments (top-level Makefile, vmlinux_link()) now say the opposite; they should be updated.
Quoted 4 lines
scripts/link-vmlinux.sh +0
-0
[ ... ]
scripts/link-vmlinux.sh vmlinux_link() · line 94
Quoted 7 lines
scripts/link-vmlinux.sh +3
-0@@ -89,6 +89,13 @@ vmlinux_link() ldlibs= fi + if is_enabled CONFIG_CLANG_PLUGIN_BPF_SCAN_IR; then + if [ "${output}" = ".tmp_vmlinux1" ]; then + ldflags="${ldflags} ${wl}--emit-relocs"
This isn't a bug, but two existing comments now say the opposite of what happens here.
The top-level Makefile says:
# --emit-relocs is added by scripts/link-vmlinux.sh, for the final link only.
and a few lines below this block, vmlinux_link() says:
# Only the final link actually requires the relocations.
With the plugin enabled, the .tmp_vmlinux1 link also gets --emit-relocs, and on arm64 it gets it without --discard-none.
Could both comments be updated to mention the .tmp_vmlinux1 case?
scripts/link-vmlinux.sh vmlinux_link() · line 100
Quoted 6 lines
scripts/link-vmlinux.sh +4
-0+ else + ldflags="${ldflags} ${wl}--script=${srctree}/scripts/bpf/fmodret.lds" + fi + fi ldflags="${ldflags} ${wl}--script=${objtree}/${KBUILD_LDS}"
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
Re: [PATCH v3 bpf-next 08/18] bpf: Add the bpf_scan_ir LLVM plugin
Quoted 6 lines · On Wed, Nov 11, 2026 at 9:21 AM <[email protected]> wrote:
Quoted 2 lines
bpf: Add the
bpf_scan_irLLVM pluginTL;DR: Nit only: with the plugin enabled,
link-vmlinux.shadds --emit-relocs to the .tmp_vmlinux1 link, so two existing comments (top-levelMakefile,vmlinux_link()) now say the opposite; they should be updated.
yes, updated
Quoted 44 lines
Quoted 4 lines
scripts/link-vmlinux.sh +0
-0[ ... ]
scripts/link-vmlinux.sh vmlinux_link() · line 94
Quoted 7 lines
scripts/link-vmlinux.sh +3
-0@@ -89,6 +89,13 @@ vmlinux_link() ldlibs= fi + if is_enabled CONFIG_CLANG_PLUGIN_BPF_SCAN_IR; then + if [ "${output}" = ".tmp_vmlinux1" ]; then + ldflags="${ldflags} ${wl}--emit-relocs"This isn't a bug, but two existing comments now say the opposite of what happens here.
The top-level
Makefilesays:# --emit-relocs is added by
scripts/link-vmlinux.sh, for the final link only.and a few lines below this block,
vmlinux_link()says:# Only the final link actually requires the relocations.
With the plugin enabled, the .tmp_vmlinux1 link also gets --emit-relocs, and on arm64 it gets it without --discard-none.
Could both comments be updated to mention the .tmp_vmlinux1 case?
scripts/link-vmlinux.sh vmlinux_link() · line 100
Quoted 6 lines
scripts/link-vmlinux.sh +4
-0+ else + ldflags="${ldflags} ${wl}--script=${srctree}/scripts/bpf/fmodret.lds" + fi + fi ldflags="${ldflags} ${wl}--script=${objtree}/${KBUILD_LDS}"---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.mdCI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
PATCH v3 9/18 bpf: Find fmod_ret candidates in bpf_scan_ir
In reply to Anton ProtopopovFind the functions which can become fmod_ret targets: functions which return a 32 or 64 bit integer and have a path from the entry without observable side effects (a clean path) which returns an error. A fmod_ret program which returns this error instead of calling the function then behaves like the path. List the errors in the record of the function, sorted and unique.
Take only the blocks which no dirty path reaches: after a dirty path joins a clean one, a branch may depend on what the dirty path did. Only the block of the return may also be reached by dirty paths, as it returns the same constant on all paths.
For now an error must be a constant returned by a clean path. The following changes find more of the errors.
--- scripts/llvm-plugins/bpf_scan_ir.cpp | 122 ++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 4 deletions(-)
scripts/llvm-plugins/bpf_scan_ir.cpp +118 -4
@@ -3,11 +3,17 @@ #include "../bpf/fmodret_metadata.h" +#include <algorithm> +#include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/Analysis.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/CFG.h" #include "llvm/IR/Constants.h" #include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/IR/PassManager.h" #include "llvm/Passes/PassBuilder.h"
@@ -22,9 +28,119 @@ using namespace llvm; namespace { +static constexpr int MaxErrno = 4095; + /* The errors which clean paths of a function return */ using ReturnValues = SmallVector<int64_t, 8>; +/* Return true and set N if C is an errno */ +static bool isErrno(const APInt &C, int64_t &N) +{ + if (C.getBitWidth() != 32 && C.getBitWidth() != 64) + return false; + N = C.getSExtValue(); + return N >= -MaxErrno && N < 0; +} + +/* Return true and set N if V is an errno constant */ +static bool errnoConstant(const Value *V, int64_t &N) +{ + auto *C = dyn_cast<ConstantInt>(V); + + return C && isErrno(C->getValue(), N); +} + +static bool cleanInstruction(const Instruction &I) +{ + if (auto *Intrinsic = dyn_cast<IntrinsicInst>(&I)) { + switch (Intrinsic->getIntrinsicID()) { + case Intrinsic::assume: + case Intrinsic::lifetime_start: + case Intrinsic::lifetime_end: + case Intrinsic::invariant_start: + case Intrinsic::invariant_end: + return true; + default: + break; + } + } + return !I.mayHaveSideEffects(); +} + +static bool cleanBB(BasicBlock *BB) +{ + for (Instruction &I : *BB) { + if (!cleanInstruction(I)) + return false; + } + return true; +} + +/* Add the errors which clean paths of F are known to return to VALUES */ +static void cleanReturnValues(Function &F, ReturnValues &Values) +{ + SmallPtrSet<BasicBlock *, 32> CleanBBs; + SmallVector<BasicBlock *, 32> Worklist; + bool Changed; + + /* The clean blocks which the entry reaches through clean blocks */ + if (cleanBB(&F.getEntryBlock())) { + CleanBBs.insert(&F.getEntryBlock()); + Worklist.push_back(&F.getEntryBlock()); + } + while (!Worklist.empty()) { + BasicBlock *BB = Worklist.pop_back_val(); + + for (BasicBlock *Successor : successors(BB)) { + if (!CleanBBs.contains(Successor) && cleanBB(Successor)) { + CleanBBs.insert(Successor); + Worklist.push_back(Successor); + } + } + } + + /* + * Keep the blocks which only clean paths reach: after a dirty path joins + * a clean one, a branch may depend on what the dirty path did + */ + do { + Changed = false; + for (BasicBlock &BB : F) { + if (!CleanBBs.contains(&BB)) + continue; + for (BasicBlock *Pred : predecessors(&BB)) { + if (!CleanBBs.contains(Pred)) { + CleanBBs.erase(&BB); + Changed = true; + break; + } + } + } + } while (Changed); + + /* + * The returns of the clean blocks which only clean paths reach or which + * one of them branches to. Dirty paths may also reach the latter, but + * the returned constant is the same on all paths. + */ + for (BasicBlock &BB : F) { + auto *Return = dyn_cast<ReturnInst>(BB.getTerminator()); + bool Entered = CleanBBs.contains(&BB); + int64_t N; + + if (!Return || !Return->getReturnValue() || !cleanBB(&BB)) + continue; + for (BasicBlock *Pred : predecessors(&BB)) + Entered |= CleanBBs.contains(Pred); + if (!Entered) + continue; + if (errnoConstant(Return->getReturnValue(), N)) + Values.push_back(N); + } + llvm::sort(Values); + Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); +} + struct FunctionDescription { Function *Fn; unsigned Flags;
@@ -86,10 +202,8 @@ public: Flags |= FMODRET_FN_WEAK; if (Ret->isIntegerTy(64)) Flags |= FMODRET_FN_RET64; - /* - * Nothing finds the values yet. A weak definition always - * has a record, see fmodret_metadata.h. - */ + cleanReturnValues(F, Values); + /* A weak definition always has a record, see fmodret_metadata.h */ if (!Values.empty() || (Flags & FMODRET_FN_WEAK)) Descriptions.push_back({&F, Flags, std::move(Values)}); }
Signature · 1 line
2.43.0
PATCH v3 10/18 bpf: Allow writes to private stack objects in bpf_scan_ir
In reply to Anton ProtopopovA write to a stack object of the function is not observable outside of it as long as the object has not escaped. Let such writes and memsets stay on a clean path. A write after the object may have been captured, a volatile or atomic one and a write to other memory still make the path dirty.
--- scripts/llvm-plugins/bpf_scan_ir.cpp | 85 +++++++++++++++++++++------- 1 file changed, 64 insertions(+), 21 deletions(-)
scripts/llvm-plugins/bpf_scan_ir.cpp +64 -21
@@ -4,13 +4,17 @@ #include "../bpf/fmodret_metadata.h" #include <algorithm> +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" +#include "llvm/Analysis/CaptureTracking.h" +#include "llvm/Analysis/ValueTracking.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/Analysis.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Constants.h" +#include "llvm/IR/Dominators.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h"
@@ -50,41 +54,76 @@ static bool errnoConstant(const Value *V, int64_t &N) return C && isErrno(C->getValue(), N); } -static bool cleanInstruction(const Instruction &I) -{ - if (auto *Intrinsic = dyn_cast<IntrinsicInst>(&I)) { - switch (Intrinsic->getIntrinsicID()) { - case Intrinsic::assume: - case Intrinsic::lifetime_start: - case Intrinsic::lifetime_end: - case Intrinsic::invariant_start: - case Intrinsic::invariant_end: - return true; - default: - break; +class CleanInstructions { + DominatorTree &DT; + DenseMap<const Instruction *, bool> PrivateWrites; + + bool privateDestination(const Value *Pointer, const Instruction &I) + { + auto It = PrivateWrites.find(&I); + if (It != PrivateWrites.end()) + return It->second; + auto *Allocation = dyn_cast<AllocaInst>(getUnderlyingObject(Pointer)); + bool Private = false; + + if (Allocation && Allocation->getFunction() == I.getFunction()) { + // A later call may receive the initialized object. Only captures + // that can precede this write make the write externally visible. +#if LLVM_VERSION_MAJOR >= 21 + Private = !PointerMayBeCapturedBefore(Allocation, true, &I, &DT, true, 256); +#else + Private = !PointerMayBeCapturedBefore(Allocation, true, true, &I, &DT, true, 256); +#endif } + PrivateWrites[&I] = Private; + return Private; } - return !I.mayHaveSideEffects(); -} -static bool cleanBB(BasicBlock *BB) +public: + explicit CleanInstructions(DominatorTree &DT) : DT(DT) {} + + bool isClean(const Instruction &I) + { + if (auto *Store = dyn_cast<StoreInst>(&I)) + return !Store->isVolatile() && !Store->isAtomic() && + privateDestination(Store->getPointerOperand(), I); + if (auto *Memory = dyn_cast<MemIntrinsic>(&I)) + return !Memory->isVolatile() && + privateDestination(Memory->getRawDest(), I); + if (auto *Intrinsic = dyn_cast<IntrinsicInst>(&I)) { + switch (Intrinsic->getIntrinsicID()) { + case Intrinsic::assume: + case Intrinsic::lifetime_start: + case Intrinsic::lifetime_end: + case Intrinsic::invariant_start: + case Intrinsic::invariant_end: + return true; + default: + break; + } + } + return !I.mayHaveSideEffects(); + } +}; + +static bool cleanBB(BasicBlock *BB, CleanInstructions &Clean) { for (Instruction &I : *BB) { - if (!cleanInstruction(I)) + if (!Clean.isClean(I)) return false; } return true; } /* Add the errors which clean paths of F are known to return to VALUES */ -static void cleanReturnValues(Function &F, ReturnValues &Values) +static void cleanReturnValues(Function &F, CleanInstructions &Clean, ReturnValues &Values) { SmallPtrSet<BasicBlock *, 32> CleanBBs; SmallVector<BasicBlock *, 32> Worklist; bool Changed; /* The clean blocks which the entry reaches through clean blocks */ - if (cleanBB(&F.getEntryBlock())) { + if (cleanBB(&F.getEntryBlock(), Clean)) { CleanBBs.insert(&F.getEntryBlock()); Worklist.push_back(&F.getEntryBlock()); }
@@ -92,7 +131,7 @@ static void cleanReturnValues(Function &F, ReturnValues &Values) BasicBlock *BB = Worklist.pop_back_val(); for (BasicBlock *Successor : successors(BB)) { - if (!CleanBBs.contains(Successor) && cleanBB(Successor)) { + if (!CleanBBs.contains(Successor) && cleanBB(Successor, Clean)) { CleanBBs.insert(Successor); Worklist.push_back(Successor); }
@@ -128,7 +167,7 @@ static void cleanReturnValues(Function &F, ReturnValues &Values) bool Entered = CleanBBs.contains(&BB); int64_t N; - if (!Return || !Return->getReturnValue() || !cleanBB(&BB)) + if (!Return || !Return->getReturnValue() || !cleanBB(&BB, Clean)) continue; for (BasicBlock *Pred : predecessors(&BB)) Entered |= CleanBBs.contains(Pred);
@@ -188,6 +227,7 @@ public: return PreservedAnalyses::all(); SmallVector<FunctionDescription, 32> Descriptions; + auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); for (Function &F : M) { if (F.isIntrinsic() || F.isDeclaration() || F.hasAvailableExternallyLinkage())
@@ -202,7 +242,10 @@ public: Flags |= FMODRET_FN_WEAK; if (Ret->isIntegerTy(64)) Flags |= FMODRET_FN_RET64; - cleanReturnValues(F, Values); + auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); + CleanInstructions Clean(DT); + + cleanReturnValues(F, Clean, Values); /* A weak definition always has a record, see fmodret_metadata.h */ if (!Values.empty() || (Flags & FMODRET_FN_WEAK)) Descriptions.push_back({&F, Flags, std::move(Values)});
Signature · 1 line
2.43.0
PATCH v3 11/18 bpf: Follow PHIs in bpf_scan_ir
In reply to Anton ProtopopovAn error often reaches the return through a PHI in the block of the return which joins it with the results of other paths, some of them dirty. Take the incoming values of such a PHI on the edges from the blocks which only clean paths reach. Do not follow a PHI in an earlier
block: a later branch may split its values between clean and dirty paths.
Take also the errors which LazyValueInfo knows exactly: an incoming value on its edge and a returned value at the return.
--- scripts/llvm-plugins/bpf_scan_ir.cpp | 68 ++++++++++++++++++++++++++-- 1 file changed, 63 insertions(+), 5 deletions(-)
scripts/llvm-plugins/bpf_scan_ir.cpp +63 -5
@@ -8,11 +8,13 @@ #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/CaptureTracking.h" +#include "llvm/Analysis/LazyValueInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/Analysis.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" +#include "llvm/IR/ConstantRange.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/GlobalVariable.h"
@@ -46,6 +48,21 @@ static bool isErrno(const APInt &C, int64_t &N) return N >= -MaxErrno && N < 0; } +/* Return true and set N if RANGE holds a single errno */ +static bool singleErrno(const ConstantRange &Range, int64_t &N) +{ + const APInt *C = Range.getSingleElement(); + + return C && isErrno(*C, N); +} + +/* Return true and set N if the value at use U is a single errno */ +static bool singleErrnoAtUse(const Use &U, LazyValueInfo &LVI, int64_t &N) +{ + return U.get()->getType()->isIntegerTy() && + singleErrno(LVI.getConstantRangeAtUse(U, false), N); +} + /* Return true and set N if V is an errno constant */ static bool errnoConstant(const Value *V, int64_t &N) {
@@ -54,6 +71,42 @@ static bool errnoConstant(const Value *V, int64_t &N) return C && isErrno(C->getValue(), N); } +/* + * Add the errors which V, the value returned in RET, is known to be on the + * edges to RET from CLEANBBS to VALUES. V may be a PHI in RET. A PHI in an + * earlier block is not followed: a later branch may split its values between + * clean and dirty paths. + */ +static void collectErrnos(Value *V, BasicBlock *Ret, LazyValueInfo &LVI, + const SmallPtrSetImpl<BasicBlock *> &CleanBBs, ReturnValues &Values) +{ + int64_t N; + + auto *Phi = dyn_cast<PHINode>(V); + + if (!Phi || Phi->getParent() != Ret) + return; + for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) { + Value *Incoming = Phi->getIncomingValue(i); + BasicBlock *Pred = Phi->getIncomingBlock(i); + + if (!CleanBBs.contains(Pred)) + continue; + if (errnoConstant(Incoming, N)) { + Values.push_back(N); + continue; + } + /* + * LazyValueInfo knows the ranges of integers only. On an edge it + * also uses the branch condition, as in "if (err == -EINVAL) goto + * out", where err is the error. + */ + if (Incoming->getType()->isIntegerTy() && + singleErrno(LVI.getConstantRangeOnEdge(Incoming, Pred, Ret), N)) + Values.push_back(N); + } +} + class CleanInstructions { DominatorTree &DT; DenseMap<const Instruction *, bool> PrivateWrites;
@@ -116,7 +169,8 @@ static bool cleanBB(BasicBlock *BB, CleanInstructions &Clean) } /* Add the errors which clean paths of F are known to return to VALUES */ -static void cleanReturnValues(Function &F, CleanInstructions &Clean, ReturnValues &Values) +static void cleanReturnValues(Function &F, LazyValueInfo &LVI, CleanInstructions &Clean, + ReturnValues &Values) { SmallPtrSet<BasicBlock *, 32> CleanBBs; SmallVector<BasicBlock *, 32> Worklist;
@@ -159,8 +213,7 @@ static void cleanReturnValues(Function &F, CleanInstructions &Clean, ReturnValue /* * The returns of the clean blocks which only clean paths reach or which - * one of them branches to. Dirty paths may also reach the latter, but - * the returned constant is the same on all paths. + * one of them branches to */ for (BasicBlock &BB : F) { auto *Return = dyn_cast<ReturnInst>(BB.getTerminator());
@@ -173,8 +226,11 @@ static void cleanReturnValues(Function &F, CleanInstructions &Clean, ReturnValue Entered |= CleanBBs.contains(Pred); if (!Entered) continue; - if (errnoConstant(Return->getReturnValue(), N)) + if (singleErrnoAtUse(Return->getOperandUse(0), LVI, N)) { Values.push_back(N); + continue; + } + collectErrnos(Return->getReturnValue(), &BB, LVI, CleanBBs, Values); } llvm::sort(Values); Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
@@ -242,10 +298,11 @@ public: Flags |= FMODRET_FN_WEAK; if (Ret->isIntegerTy(64)) Flags |= FMODRET_FN_RET64; + auto &LVI = FAM.getResult<LazyValueAnalysis>(F); auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); CleanInstructions Clean(DT); - cleanReturnValues(F, Clean, Values); + cleanReturnValues(F, LVI, Clean, Values); /* A weak definition always has a record, see fmodret_metadata.h */ if (!Values.empty() || (Flags & FMODRET_FN_WEAK)) Descriptions.push_back({&F, Flags, std::move(Values)});
@@ -258,6 +315,7 @@ public: PreservedAnalyses PA; PA.preserve<FunctionAnalysisManagerModuleProxy>(); PA.preserveSet<CFGAnalyses>(); + PA.preserve<LazyValueAnalysis>(); return PA; }
Signature · 1 line
2.43.0
PATCH v3 12/18 bpf: Follow integer casts in bpf_scan_ir
In reply to Anton ProtopopovFollow sign extensions and truncations between integers of at least 32 bits in the block of the return. They keep an error, for example an int error which a function returns as long.
--- scripts/llvm-plugins/bpf_scan_ir.cpp | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-)
scripts/llvm-plugins/bpf_scan_ir.cpp +25 -3
@@ -71,17 +71,39 @@ static bool errnoConstant(const Value *V, int64_t &N) return C && isErrno(C->getValue(), N); } +/* A sign extension or a truncation between integers of at least 32 bits */ +static bool preservesErrnoCast(const CastInst *Cast) +{ + Type *Src = Cast->getSrcTy(), *Dst = Cast->getDestTy(); + + if (Src->isIntegerTy() && Dst->isIntegerTy()) + return (Cast->getOpcode() == Instruction::SExt || + Cast->getOpcode() == Instruction::Trunc) && + Src->getIntegerBitWidth() >= 32 && Dst->getIntegerBitWidth() >= 32; + return false; +} + /* * Add the errors which V, the value returned in RET, is known to be on the - * edges to RET from CLEANBBS to VALUES. V may be a PHI in RET. A PHI in an - * earlier block is not followed: a later branch may split its values between - * clean and dirty paths. + * edges to RET from CLEANBBS to VALUES. Follow the casts in RET which keep the + * error to a PHI in RET. A PHI in an earlier block is not followed: a later + * branch may split its values between clean and dirty paths. */ static void collectErrnos(Value *V, BasicBlock *Ret, LazyValueInfo &LVI, const SmallPtrSetImpl<BasicBlock *> &CleanBBs, ReturnValues &Values) { int64_t N; + while (auto *Cast = dyn_cast<CastInst>(V)) { + if (Cast->getParent() != Ret || !preservesErrnoCast(Cast)) + return; + if (singleErrnoAtUse(Cast->getOperandUse(0), LVI, N)) { + Values.push_back(N); + return; + } + V = Cast->getOperand(0); + } + auto *Phi = dyn_cast<PHINode>(V); if (!Phi || Phi->getParent() != Ret)
Signature · 1 line
2.43.0
PATCH v3 13/18 bpf: Check the return values of fmod_ret programs on found targets
In reply to Anton ProtopopovA later patch lets resolve_btfids make the functions found by bpf_scan_ir fmod_ret targets. Each of them gets a "bpf_fmodret_retval:" decl tag with the values it returns on paths without side effects, for example "bpf_fmodret_retval:-22,-12". Returning such a value instead of calling the function looks to the callers like a real failure.
Read the tag when an fmod_ret program is loaded and check at every exit that the program returns 0 or one of these values.
A function which the static rules allow keeps today's behaviour. So do the functions declared in BTF_FMODRET sets, which have no such tag.
Only a kernel function has such a tag, so do not look for it when the target is a BPF program. Remember the values in the program, and do not let an extension replace an fmod_ret program with restricted return
values: it could return any value. Check this at load and when an extension is attached to another program later. Do not allow tail calls in such a program either: the program it jumps to returns for it, and a program array does not check the values it may return.
--- include/linux/bpf.h | 6 ++ kernel/bpf/syscall.c | 1 + kernel/bpf/verifier.c | 148 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 155 insertions(+)
include/linux/bpf.h +6 -0
@@ -1969,6 +1969,12 @@ struct bpf_prog_aux {const struct btf_type *attach_func_proto;/* function name for valid attach_btf_id */ const char *attach_func_name; +/* +* The values which an fmod_ret program may return besides 0, from the +* "bpf_fmodret_retval:" tag of its target, or NULL +*/ +s64 *fmodret_retvals; +u32 fmodret_retval_cnt;struct bpf_prog **func;struct bpf_prog_aux *main_prog_aux;/* main prog: there when the prog has timed may_goto */
kernel/bpf/syscall.c +1 -0
@@ -2490,6 +2490,7 @@ static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)module_put (prog->aux->mod);kfree (prog->aux->kfunc_tab);kfree (prog->aux->ctx_arg_info); +kfree (prog->aux->fmodret_retvals);if (prog->aux->attach_btf)btf_put (prog->aux->attach_btf);
kernel/bpf/verifier.c +148 -0
184 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v3 bpf-next 13/18] bpf: Check the return values of fmod_ret programs on found targets
TL;DR: Possible wrong behaviour: fmod_ret programs on 64-bit found targets don't require the JIT, so in the interpreter -14 may reach callers as 4294967282; a later commit fixes this, leaving a…
Quoted 1 line
bpf: Check the return values of
fmod_retprograms on found targets
TL;DR: Possible wrong behaviour: fmod_ret programs on 64-bit found targets don't require the JIT, so in the interpreter -14 may reach callers as 4294967282; a later commit fixes this, leaving a narrow gap here.
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 3 lines
kernel/bpf/verifier.c +3
-0+static int fmodret_retval_init (struct bpf_verifier_env *env,u32 btf_id, +unsigned long addr,const char *tname) +{
[ ... ]
kernel/bpf/verifier.c static int check_attach_modify_return(unsigned long addr, const char *func_name) · line 23886
Quoted 6 lines
kernel/bpf/verifier.c +6
-0+if (!cnt) + goto invalid; + + aux->fmodret_retvals = retvals; + aux->fmodret_retval_cnt = cnt; +return 0 ;
For a found target that returns a 64-bit integer (size == 8), check_fmodret_retval() accepts the full 64-bit R0, so "r0 = -14" is accepted as the s64 value -14. Nothing here makes such a program require the JIT.
If the program runs in the interpreter, prog->bpf_func is __bpf_prog_runN(), which is declared in kernel/bpf/core.c as:
static unsigned int PROG_NAME(stack_size)(const void *ctx,
const struct bpf_insn *insn)
so only the low 32 bits of R0 come back. The x86 trampoline handles interpreted programs, stores all of RAX and returns it to the caller of the traced function, so the caller of a long-returning found target would see 4294967282 instead of -14.
That value is non-zero, so the function body is skipped, but it is not an error value either. Callers would treat the skipped call as a success that returned a large positive value, which is the case the commit message says the check is meant to prevent ("Returning such a value instead of calling the function looks to the callers like a real failure").
Should fmodret_retval_init() set env->prog->jit_required = 1 when size == 8? A later commit in this series, c4a7eee0c4d7 ("bpf: Require the JIT for fmod_ret programs on found 64-bit targets"), adds
"if (size == 8) env->prog->jit_required = 1;" right after these assignments. No found target carries the tag until 8659bd72073c ("resolve_btfids: Tag fmod_ret candidates as targets"), which comes after that fix, so the window is narrow, but it is still a gap in this commit's own logic.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
Re: [PATCH v3 bpf-next 13/18] bpf: Check the return values of fmod_ret programs on found targets
Quoted 6 lines · On Wed, Nov 11, 2026 at 9:21 AM <[email protected]> wrote:
Quoted 2 lines
bpf: Check the return values of
fmod_retprograms on found targetsTL;DR: Possible wrong behaviour:
fmod_retprograms on 64-bit found targets don't require the JIT, so in the interpreter -14 may reach callers as 4294967282; a later commit fixes this, leaving a narrow gap here.
This won't apply anymore (see jit-related commit before)
Quoted 57 lines
Quoted 4 lines
kernel/bpf/verifier.c +0
-0[ ... ]
Quoted 3 lines
kernel/bpf/verifier.c +3
-0+static int fmodret_retval_init (struct bpf_verifier_env *env,u32 btf_id, +unsigned long addr,const char *tname) +{[ ... ]
kernel/bpf/verifier.c static int check_attach_modify_return(unsigned long addr, const char *func_name) · line 23886
Quoted 6 lines
kernel/bpf/verifier.c +6
-0+if (!cnt) + goto invalid; + + aux->fmodret_retvals = retvals; + aux->fmodret_retval_cnt = cnt; +return 0 ;For a found target that returns a 64-bit integer (size == 8),
check_fmodret_retval()accepts the full 64-bit R0, so "r0 = -14" is accepted as the s64 value -14. Nothing here makes such a program require the JIT.If the program runs in the interpreter,
prog->bpf_funcis__bpf_prog_runN(), which is declared inkernel/bpf/core.cas:static unsigned int PROG_NAME(stack_size)(const void *ctx,
const structbpf_insn*insn)so only the low 32 bits of R0 come back. The x86 trampoline handles interpreted programs, stores all of RAX and returns it to the caller of the traced function, so the caller of a long-returning found target would see 4294967282 instead of -14.
That value is non-zero, so the function body is skipped, but it is not an error value either. Callers would treat the skipped call as a success that returned a large positive value, which is the case the commit message says the check is meant to prevent ("Returning such a value instead of calling the function looks to the callers like a real failure").
Should
fmodret_retval_init()setenv->prog->jit_required= 1 when size == 8? A later commit in this series,c4a7eee0c4d7("bpf: Require the JIT forfmod_retprograms on found 64-bit targets"), adds
"if (size == 8)env->prog->jit_required= 1;" right after these assignments. No found target carries the tag until8659bd72073c("resolve_btfids: Tagfmod_retcandidates as targets"), which comes after that fix, so the window is narrow, but it is still a gap in this commit's own logic.---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.mdCI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
PATCH v3 14/18 bpf: Require the JIT for fmod_ret programs on found 64-bit targets
In reply to Anton ProtopopovThe interpreter returns only the low 32 bits of the return value of a program, while the trampoline passes all 64 bits to the caller of the function. If an fmod_ret program on a found target which returns long is interpreted, then a valid return value like -14 reaches the caller as 4294967282. This value is not 0, so the function is skipped, and it is not an error either.
Require the JIT for such programs, as for other features which the interpreter does not support. The caller of a function which returns int reads only the low 32 bits, so nothing changes for it.
--- kernel/bpf/verifier.c | 3 +++ 1 file changed, 3 insertions(+)
kernel/bpf/verifier.c +3 -0
@@ -23883,6 +23883,9 @@ static int fmodret_retval_init(struct bpf_verifier_env *env, u32 btf_id, aux->fmodret_retvals = retvals; aux->fmodret_retval_cnt = cnt; +/* The interpreter returns only 32 bits */ +if (size ==8 ) + env->prog->jit_required =1 ;return 0 ; invalid:
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v3 bpf-next 14/18] bpf: Require the JIT for fmod_ret programs on found 64-bit targets
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf: missing jit_required in fmodret_retval_init() for 32-bit int on ppc64 --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: missing jit_required in fmodret_retval_init() for 32-bit int on ppc64
--
commit be8ba9e6d31af4b7ee8b1ec3bc7241dc8e6ff517
Author: Anton Protopopov <[email protected]>
bpf: Require the JIT for fmod_ret programs on found 64-bit targets
This commit sets jit_required for fmod_ret programs attached to found targets with 8-byte return types so the BPF interpreter does not truncate 64-bit return values to 32 bits.
kernel/bpf/verifier.c static int fmodret_retval_init(struct bpf_verifier_env *env, u32 btf_id, · line 23888
Quoted 11 lines
kernel/bpf/verifier.c +3
-0@@ -23883,6 +23883,9 @@ static int fmodret_retval_init(struct bpf_verifier_env *env, u32 btf_id, aux->fmodret_retvals = retvals; aux->fmodret_retval_cnt = cnt; +/* The interpreter returns only 32 bits */ +if (size ==8 ) + env->prog->jit_required =1 ;
[Severity: Medium]
Does fmodret_retval_init() also need to set jit_required when size == 4?
On 64-bit PowerPC (which supports BPF trampolines without selecting ARCH_WANT_BPF_JIT_ALWAYS_ON), the ELF ABI requires a callee returning a 32-bit signed int to sign-extend r3 to 64 bits, and callers inspect all 64 bits of r3. DEFINE_BPF_PROG_RUN() defines the interpreter entry points as returning unsigned int, which zero-extends r3 to 64 bits.
In arch/powerpc/net/bpf_jit_comp.c, invoke_bpf_prog() and __arch_prepare_bpf_trampoline() save and restore all 64 bits of r3 without sign-extending 32-bit return values, so when the interpreter runs an fmod_ret program on a target returning int, a negative error return value is zero-extended to a positive 64-bit value in r3 while skipping the target function.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
Re: [PATCH v3 bpf-next 14/18] bpf: Require the JIT for fmod_ret programs on found 64-bit targets
Quoted 37 lines · On Tue, Nov 10, 2026 at 6:38 PM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: missingjit_requiredinfmodret_retval_init()for 32-bit int on ppc64
--commit
be8ba9e6d31af4b7ee8b1ec3bc7241dc8e6ff517
Author: Anton Protopopov <[email protected]>bpf: Require the JIT for
fmod_retprograms on found 64-bit targetsThis commit sets
jit_requiredforfmod_retprograms attached to found targets with 8-byte return types so the BPF interpreter does not truncate 64-bit return values to 32 bits.kernel/bpf/verifier.c static int fmodret_retval_init(struct bpf_verifier_env *env, u32 btf_id, · line 23888
Quoted 11 lines
kernel/bpf/verifier.c +3
-0@@ -23883,6 +23883,9 @@ static int fmodret_retval_init(struct bpf_verifier_env *env, u32 btf_id, aux->fmodret_retvals = retvals; aux->fmodret_retval_cnt = cnt; +/* The interpreter returns only 32 bits */ +if (size ==8 ) + env->prog->jit_required =1 ;[Severity: Medium]
Doesfmodret_retval_init()also need to setjit_requiredwhen size == 4?On 64-bit PowerPC (which supports BPF trampolines without selecting
ARCH_WANT_BPF_JIT_ALWAYS_ON), the ELF ABI requires a callee returning a 32-bit signed int to sign-extend r3 to 64 bits, and callers inspect all 64 bits of r3.DEFINE_BPF_PROG_RUN()defines the interpreter entry points as returning unsigned int, which zero-extends r3 to 64 bits.
Quoted 6 lines
In
arch/powerpc/net/bpf_jit_comp.c,invoke_bpf_prog()and__arch_prepare_bpf_trampoline()save and restore all 64 bits of r3 without sign-extending 32-bit return values, so when the interpreter runs anfmod_retprogram on a target returning int, a negative error return value is zero-extended to a positive 64-bit value in r3 while skipping the target function.
PowerPC is not part of this patchset. However, in fact, I think I will just remove this "if (size) == 8" and force jit for all new progs. This doesn't break any old functionality, only new functions are getting here.
Will send it for v4 or as follow-up.
Quoted 2 lines
--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
PATCH v3 15/18 resolve_btfids: Tag fmod_ret candidates as targets
In reply to Anton ProtopopovRead the records which bpf_scan_ir writes to .BTF_fmodret_candidates and choose the functions which can become fmod_ret targets. Map each record to its function through its relocation in a module or through its address in vmlinux. A record of a strong definition wins over the records of the weak definitions it overrides. A strong definition without values has no record, so use the record of a weak definition only if the symbol of the function is still weak after the link. Every weak definition has a record, so a function with two weak definitions is ambiguous.
Choose a function if the record lists at least one error, the function has an ftrace call site, is not init, exit or noinstr code, its name belongs to exactly one ELF function and one BTF FUNC and it returns an integer of the size the record describes.
Tag each chosen function with "bpf_fmodret" and with "bpf_fmodret_retval:" followed by the errors it returns on paths without side effects, for example "bpf_fmodret_retval:-22,-12". The values are signed decimal numbers, sorted and separated by commas. The verifier lets programs attached to such a function return only these values or 0.
A function in a BTF_FMODRET set keeps only its own tags.
Mark the range of patchable function entries in the linker script so the ftrace call sites in vmlinux can be told from the mcount ones. Take the ftrace call sites of a module from the section the kernel uses:
x86 also has call padding entries in __patchable_function_entries.
With -v, report what was found.
Add the new files to the BPF [COMPILER PLUGINS] entry in MAINTAINERS.
--- MAINTAINERS | 1 + include/asm-generic/vmlinux.lds.h | 2 + scripts/Makefile.btf | 1 + tools/bpf/resolve_btfids/Build | 1 + tools/bpf/resolve_btfids/fmodret.c | 1203 ++++++++++++++++++++++++++++ tools/bpf/resolve_btfids/fmodret.h | 28 + tools/bpf/resolve_btfids/main.c | 66 ++ 7 files changed, 1302 insertions(+) create mode 100644 tools/bpf/resolve_btfids/fmodret.c create mode 100644 tools/bpf/resolve_btfids/fmodret.h
MAINTAINERS +1 -0
@@ -5070,6 +5070,7 @@ L: [email protected] S: Maintained F: scripts/bpf/ F: scripts/llvm-plugins/bpf_* +F: tools/bpf/resolve_btfids/fmodret.* BPF [CORE] M: Alexei Starovoitov <[email protected]>
include/asm-generic/vmlinux.lds.h +2 -0
@@ -198,7 +198,9 @@#define MCOUNT_REC () . = ALIGN(8); \ __start_mcount_loc = .; \ KEEP(*(__mcount_loc)) \ + __start_patchable_function_entries = .; \ KEEP_PATCHABLE \ + __stop_patchable_function_entries = .; \ __stop_mcount_loc = .; \ FTRACE_STUB_HACK \ ftrace_ops_list_func = arch_ftrace_ops_list_func;
scripts/Makefile.btf +1 -0
@@ -35,5 +35,6 @@ resolve-btfids-flags-y := resolve-btfids-flags-$(CONFIG_WERROR) += --fatal_warnings resolve-btfids-flags-$(if $(KBUILD_EXTMOD),y) += --distill_base resolve-btfids-flags-$(if $(KBUILD_VERBOSE),y) += --verbose +resolve-btfids-flags-$(CONFIG_FTRACE_MCOUNT_USE_PATCHABLE_FUNCTION_ENTRY) += --patchable_ftrace export RESOLVE_BTFIDS_FLAGS := $(resolve-btfids-flags-y)
tools/bpf/resolve_btfids/Build +1 -0
@@ -1,6 +1,7 @@ hostprogs := resolve_btfids resolve_btfids-y += main.o +resolve_btfids-y += fmodret.o resolve_btfids-y += btf_colors.o resolve_btfids-y += rbtree.o resolve_btfids-y += zalloc.o
tools/bpf/resolve_btfids/fmodret.c new file +1203 -0
1,203 lines not on this page · raw message
tools/bpf/resolve_btfids/fmodret.h new file +28 -0
@@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef __RESOLVE_BTFIDS_FMODRET_H +#define __RESOLVE_BTFIDS_FMODRET_H + +#include <stdbool.h> +#include <stddef.h> +#include <libelf.h> +#include <linux/types.h> + +struct btf ; + +/* A function found by the analysis, and the values it may return */ +struct fmodret_retval { +__u32 btf_id; +char *values; +}; + +/* Sorted by BTF ID */ +struct fmodret_retvals { +struct fmodret_retval *retvals; +size_t cnt, cap; +}; + +int fmodret_collect (Elf *elf,const struct btf *btf,struct fmodret_retvals *result, +bool patchable_ftrace,int verbose); +void fmodret_free (struct fmodret_retvals *retvals); + +#endif
tools/bpf/resolve_btfids/main.c +66 -0
120 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v3 bpf-next 15/18] resolve_btfids: Tag fmod_ret candidates as targets
TL;DR: Nits only in resolve_btfids fmodret.c: the second branch in relocation_offset() looks unreachable or wrong, and record field offsets are hardcoded in three functions. No functional bugs…
Quoted 1 line
resolve_btfids: Tagfmod_retcandidates as targets
TL;DR: Nits only in resolve_btfids fmodret.c: the second branch in relocation_offset() looks unreachable or wrong, and record field offsets are hardcoded in three functions. No functional bugs reported.
Quoted 4 lines
tools/bpf/resolve_btfids/fmodret.c new file +0
-0
[ ... ]
Quoted 7 lines
tools/bpf/resolve_btfids/fmodret.c new file +7
-0+static bool relocation_offset (const GElf_Shdr *target,GElf_Addr offset, +size_t width,size_t *result) +{ +if (target->sh_size < width) +return false; +if (offset >= target->sh_addr && + offset - target->sh_addr <= target->sh_size - width) {
tools/bpf/resolve_btfids/fmodret.c line 166
Quoted 10 lines
tools/bpf/resolve_btfids/fmodret.c new file +10
-0+ *result = offset - target->sh_addr; +return true; + } +/* ET_REL relocation offsets are relative to their target section. */ +if (offset <= target->sh_size - width) { + *result = offset; +return true; + } +return false; +}
this isn't a bug, but when is the second branch in relocation_offset() taken?
For the module sections that use this helper, sh_addr is 0, so the first test already returns the section-relative offset, and with sh_addr == 0 the second condition cannot be true once the first has failed.
The second branch is reached only when sh_addr != 0 and offset < sh_addr, which would be a linked image whose r_offset lies below the target section. Treating that address as a section offset would be wrong there.
Would it be clearer to pick the interpretation from e_type, or to drop the fallback?
[ ... ]
Quoted 5 lines
tools/bpf/resolve_btfids/fmodret.c new file +5
-0+static char *format_values (const unsigned char *buf,size_t offset,size_t ptr_size, +unsigned int encoding) +{ +unsigned int nr =read_elf_value (buf + offset +16 + ptr_size,4 , encoding); +const unsigned char *p = buf + offset +FMODRET_META_HEADER_SIZE (ptr_size);
[ ... ]
Quoted 1 line
+static int choose_functions(struct
elf_function_list*functions, const struct btf *btf,
[ ... ]
tools/bpf/resolve_btfids/fmodret.c line 1057
Quoted 4 lines
tools/bpf/resolve_btfids/fmodret.c new file +4
-0+if (!read_elf_value (buf + record +16 + ptr_size,4 , encoding)) +continue ; + stats->with_values++; + flags =read_elf_value (buf + record +12 ,4 , encoding);
this isn't a bug, but the record field offsets (flags at 12, nr_values at 16 + ptr_size) are written out by hand in parse_records(), format_values() and choose_functions(). parse_records() has already decoded flags and nr_values, and the other two decode them again from the raw buffer at the same offsets.
fmodret_metadata.h has macros for the magic, the version and the header size, but none for the field offsets.
Would it be simpler to put the offsets in fmodret_metadata.h, or to have a small helper return flags and nr_values for a record, so that the three functions do not each repeat 12 and 16 + ptr_size?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
Re: [PATCH v3 bpf-next 15/18] resolve_btfids: Tag fmod_ret candidates as targets
Quoted 6 lines · On Wed, Nov 11, 2026 at 9:21 AM <[email protected]> wrote:
Quoted 2 lines
resolve_btfids: Tagfmod_retcandidates as targetsTL;DR: Nits only in
resolve_btfidsfmodret.c: the second branch inrelocation_offset()looks unreachable or wrong, and record field offsets are hardcoded in three functions. No functional bugs reported.
yes to both nits, will fix
Quoted 76 lines
Quoted 4 lines
tools/bpf/resolve_btfids/fmodret.c new file +0
-0[ ... ]
Quoted 7 lines
tools/bpf/resolve_btfids/fmodret.c new file +7
-0+static bool relocation_offset (const GElf_Shdr *target,GElf_Addr offset, +size_t width,size_t *result) +{ +if (target->sh_size < width) +return false; +if (offset >= target->sh_addr && + offset - target->sh_addr <= target->sh_size - width) {tools/bpf/resolve_btfids/fmodret.c line 166
Quoted 10 lines
tools/bpf/resolve_btfids/fmodret.c new file +10
-0+ *result = offset - target->sh_addr; +return true; + } +/* ET_REL relocation offsets are relative to their target section. */ +if (offset <= target->sh_size - width) { + *result = offset; +return true; + } +return false; +}this isn't a bug, but when is the second branch in
relocation_offset()taken?For the module sections that use this helper,
sh_addris 0, so the first test already returns the section-relative offset, and withsh_addr== 0 the second condition cannot be true once the first has failed.The second branch is reached only when
sh_addr!= 0 and offset <sh_addr, which would be a linked image whoser_offsetlies below the target section. Treating that address as a section offset would be wrong there.Would it be clearer to pick the interpretation from
e_type, or to drop the fallback?[ ... ]
Quoted 5 lines
tools/bpf/resolve_btfids/fmodret.c new file +5
-0+static char *format_values (const unsigned char *buf,size_t offset,size_t ptr_size, +unsigned int encoding) +{ +unsigned int nr =read_elf_value (buf + offset +16 + ptr_size,4 , encoding); +const unsigned char *p = buf + offset +FMODRET_META_HEADER_SIZE (ptr_size);[ ... ]
Quoted 1 line
+static int choose_functions(struct
elf_function_list*functions, const struct btf *btf,[ ... ]
tools/bpf/resolve_btfids/fmodret.c line 1057
Quoted 4 lines
tools/bpf/resolve_btfids/fmodret.c new file +4
-0+if (!read_elf_value (buf + record +16 + ptr_size,4 , encoding)) +continue ; + stats->with_values++; + flags =read_elf_value (buf + record +12 ,4 , encoding);this isn't a bug, but the record field offsets (flags at 12,
nr_valuesat 16 +ptr_size) are written out by hand inparse_records(),format_values()andchoose_functions().parse_records()has already decoded flags andnr_values, and the other two decode them again from the raw buffer at the same offsets.
fmodret_metadata.hhas macros for the magic, the version and the header size, but none for the field offsets.Would it be simpler to put the offsets in
fmodret_metadata.h, or to have a small helper return flags andnr_valuesfor a record, so that the three functions do not each repeat 12 and 16 +ptr_size?---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.mdCI run summary: https://github.com/kernel-patches/bpf/actions/runs/42981885558
PATCH v3 16/18 selftests/bpf: Test fmod_ret candidates found by bpf_scan_ir
In reply to Anton ProtopopovAdd bpf_testmod_retval.c with functions for bpf_scan_ir to a new module bpf_test_retval.ko. The "test_retval:" decl tag of each lists the values which bpf_scan_ir must find. An empty list means that the function must not become an fmod_ret target. Cover constant errors of both return widths, assumptions, private stack writes, PHIs, sign extensions, PTR_ERR() of an ERR_PTR() from an inlined helper, which is not recognized yet, errors which are not known exactly, observable effects, a notrace function, a function on the error injection list, a declared target, a weak definition with an error which a strong one without errors in bpf_testmod_retval_strong.c replaces and two weak definitions, of which the one with an error in bpf_testmod_retval_strong.c loses the link.
Build both files only with the plugin: their functions mean nothing without it and bpf_testmod_retval.c uses clang extensions such as __builtin_assume(). The module itself is always built so the selftests can install it.
The functions are not in bpf_testmod.ko because kbuild first links a module built from several objects with "ld -r" and GNU ld places .data..percpu after .debug_info there. pahole then attributes the per-CPU variables of bpf_testmod to .debug_info and drops them from its BTF. The functions can be merged back into bpf_testmod.ko once pahole looks up variables only in allocated sections.
Check that the tags in the module BTF match. Check that the verifier lets fmod_ret programs return only 0 or the listed values on every path, in the low 32 bits for an int function and in all 64 bits for an s64 one. Declared targets and the static rules stay unrestricted. Check that an extension cannot replace a function of an fmod_ret program with restricted return values, neither at load nor when it is attached later, and that such a program cannot use tail calls.
Skip the test when bpf_test_retval has no "test_retval:" tags, that is when it is built without the plugin.
--- tools/testing/selftests/bpf/Makefile | 2 +- .../selftests/bpf/prog_tests/fmodret_retval.c | 211 +++++++++++ .../selftests/bpf/progs/fmodret_retval.c | 254 ++++++++++++++ .../selftests/bpf/progs/fmodret_retval_ext.c | 55 +++ .../testing/selftests/bpf/test_kmods/Makefile | 15 +- .../bpf/test_kmods/bpf_test_retval_main.c | 12 + .../bpf/test_kmods/bpf_testmod_retval.c | 328 ++++++++++++++++++ .../test_kmods/bpf_testmod_retval_strong.c | 28 ++ 8 files changed, 903 insertions(+), 2 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/fmodret_retval.c create mode 100644 tools/testing/selftests/bpf/progs/fmodret_retval.c create mode 100644 tools/testing/selftests/bpf/progs/fmodret_retval_ext.c create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_test_retval_main.c create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_testmod_retval.c create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_testmod_retval_strong.c
tools/testing/selftests/bpf/Makefile +1 -1
@@ -47,7 +47,7 @@ TEST_PROGS_EXTENDED := \ ima_setup.sh verify_sig_setup.sh TEST_KMODS := bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \ - bpf_test_modorder_y.ko bpf_test_rqspinlock.ko + bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_retval.ko TEST_KMOD_TARGETS = $(addprefix $(OUTPUT)/,$(TEST_KMODS)) # Compile but not part of 'make run_tests'
tools/testing/selftests/bpf/prog_tests/fmodret_retval.c new file +211 -0
211 lines not on this page · raw message
tools/testing/selftests/bpf/progs/fmodret_retval.c new file +254 -0
254 lines not on this page · raw message
tools/testing/selftests/bpf/progs/fmodret_retval_ext.c new file +55 -0
55 lines not on this page · raw message
tools/testing/selftests/bpf/test_kmods/Makefile +14 -1
@@ -19,10 +19,23 @@ Q = @ endif MODULES = bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \ - bpf_test_modorder_y.ko bpf_test_rqspinlock.ko + bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_test_retval.ko $(foreach m,$(MODULES),$(eval obj-m += $(m:.ko=.o))) +bpf_test_retval-y := bpf_test_retval_main.o +# The functions for bpf_scan_ir use clang extensions and need the plugin +bpf_test_retval-$(CONFIG_CLANG_PLUGIN_BPF_SCAN_IR) += bpf_testmod_retval.o \ + bpf_testmod_retval_strong.o +# Instrumentation and branch profiling make every path of the fixtures dirty +GCOV_PROFILE_bpf_testmod_retval.o := n +KCOV_INSTRUMENT_bpf_testmod_retval.o := n +KMSAN_SANITIZE_bpf_testmod_retval.o := n +KASAN_SANITIZE_bpf_testmod_retval.o := n +KCSAN_SANITIZE_bpf_testmod_retval.o := n +UBSAN_SANITIZE_bpf_testmod_retval.o := n +CFLAGS_bpf_testmod_retval.o += -DDISABLE_BRANCH_PROFILING + CFLAGS_bpf_testmod.o = -I$(src) # When BPF_STRICT_BUILD != 0, a missing KDIR is fatal (the default).
tools/testing/selftests/bpf/test_kmods/bpf_test_retval_main.c new file +12 -0
@@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* A module for the functions of bpf_testmod_retval.c and +* bpf_testmod_retval_strong.c, see prog_tests/fmodret_retval.c. They are not +* in bpf_testmod: pahole drops the per-CPU variables of a module which GNU ld +* links from several objects. +*/ +#include <linux/module.h> + +MODULE_AUTHOR ("Anton Protopopov" ); +MODULE_DESCRIPTION ("BPF selftest module for fmod_ret targets found by bpf_scan_ir" ); +MODULE_LICENSE ("GPL" );
tools/testing/selftests/bpf/test_kmods/bpf_testmod_retval.c new file +328 -0
328 lines not on this page · raw message
tools/testing/selftests/bpf/test_kmods/bpf_testmod_retval_strong.c new file +28 -0
@@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Replaces the weak bpf_testmod_retval_overridden() of bpf_testmod_retval.c. +* This definition returns no errors, so the function must not become an +* fmod_ret target, see prog_tests/fmodret_retval.c. +* +* The weak bpf_testmod_retval_two_weak() here loses the link to the one of +* bpf_testmod_retval.c, so its error must not make the function a target +* either. +*/ +#include <linux/compiler.h> +#include <linux/errno.h> + +int bpf_testmod_retval_overridden (void ); + +noinline __attribute__((btf_decl_tag ("test_retval:" ))) +int bpf_testmod_retval_overridden(void) +{ +return 0 ; +} + +int bpf_testmod_retval_two_weak (void ); + +__weak noinline __attribute__((btf_decl_tag ("test_retval:" ))) +int bpf_testmod_retval_two_weak(void) +{ +return -EINVAL ; +}
Signature · 1 line
2.43.0
PATCH v3 17/18 selftests/bpf: Enable bpf_scan_ir in the config
In reply to Anton ProtopopovThe bpf_scan_ir plugin is off by default. Without it bpf_test_retval has no fixtures for the plugin and fmodret_retval skips. Enable the plugin in the selftests config, so the CI jobs which build the kernel with clang build and test it. Kconfig enables the plugin only on x86 and arm64 with clang 19 or newer and a matching llvm-config, so elsewhere bpf_test_retval is built without the fixtures and fmodret_retval skips.
--- tools/testing/selftests/bpf/config | 2 ++ 1 file changed, 2 insertions(+)
tools/testing/selftests/bpf/config +2 -0
@@ -11,6 +11,7 @@ CONFIG_BPF_STREAM_PARSER=y CONFIG_BPF_SYSCALL=y # CONFIG_BPF_UNPRIV_DEFAULT_OFF is not set CONFIG_CGROUP_BPF=y +CONFIG_CLANG_PLUGIN_BPF_SCAN_IR=y CONFIG_CRYPTO_HMAC=y CONFIG_CRYPTO_MLDSA=y CONFIG_CRYPTO_SHA256=y
@@ -56,6 +57,7 @@ CONFIG_IPV6_TUNNEL=y CONFIG_KEYS=y CONFIG_LIRC=y CONFIG_LIVEPATCH=y +CONFIG_LLVM_PLUGINS=y CONFIG_LWTUNNEL=y CONFIG_LWTUNNEL_BPF=y CONFIG_MEMCG=y
Signature · 1 line
2.43.0
PATCH v3 18/18 bpftool: List and show fmod_ret targets
In reply to Anton ProtopopovMost fmod_ret targets are now found by the kernel build and only exist as BTF decl tags. Add a bpftool fmodret command to see them.
The bpftool fmodret list command prints the functions tagged with "bpf_fmodret" in vmlinux and in the loaded modules, and marks the ones which sleepable programs may attach to.
The bpftool fmodret show command prints a function in detail: its prototype, if it was declared as a target or found by the build, and the values which fmod_ret programs may return. A function is given by name or BTF ID.
Both commands read BTF from /sys/kernel/btf or from a file and support JSON output.
Functions which the verifier allows by its static rules, such as the security hooks, may also have the tags and be listed. Even if they are listed, the restrictions of the tags do not apply to them. This may change in the future by either not listing them, or listing them without restrictions.
--- .../bpftool/Documentation/bpftool-fmodret.rst | 111 +++ tools/bpf/bpftool/Documentation/bpftool.rst | 4 +- tools/bpf/bpftool/bash-completion/bpftool | 31 + tools/bpf/bpftool/fmodret.c | 896 ++++++++++++++++++ tools/bpf/bpftool/main.c | 3 +- tools/bpf/bpftool/main.h | 1 + 6 files changed, 1044 insertions(+), 2 deletions(-) create mode 100644 tools/bpf/bpftool/Documentation/bpftool-fmodret.rst create mode 100644 tools/bpf/bpftool/fmodret.c
tools/bpf/bpftool/Documentation/bpftool-fmodret.rst new file +111 -0
@@ -0,0 +1,111 @@ +.. SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) + +=============== +bpftool-fmodret +=============== +------------------------------------------------------------------------------- +tool to inspect BPF fmod_ret targets +------------------------------------------------------------------------------- + +:Manual section: 8 + +.. include:: substitutions.rst + +SYNOPSIS +======== + +**bpftool** [*OPTIONS*] **fmodret** *COMMAND* + +*OPTIONS* := { |COMMON_OPTIONS| | { **-B** | **--base-btf** } *FILE* } + +*COMMANDS* := { **list** | **show** | **help** } + +FMODRET COMMANDS +================ + +| **bpftool** **fmodret list** [*OBJECT*] +| **bpftool** **fmodret show** *FUNC* [*OBJECT*] +| **bpftool** **fmodret help** +| +| *FUNC* := { **name** *NAME* | **id** *BTF_ID* } +| *OBJECT* := { **file** *FILE* | **vmlinux** | **module** *NAME* } + +DESCRIPTION +=========== + +bpftool fmodret list [*OBJECT*] + List the fmod_ret targets, the functions which the kernel build tags with + the **bpf_fmodret** BTF decl tag, in vmlinux and in loaded modules. Each + entry contains the BTF ID of the function, its name and the name of the + object it belongs to. Targets which sleepable programs may attach to are + marked **sleepable**. + + With **file**, read the BTF from *FILE* (for example a vmlinux image or a + **BTF** file) instead of the running kernel. With **vmlinux** or + **module**, list only the targets of vmlinux or of the module *NAME*. + + With **--json**, each entry contains **btf_id**, **name**, **owner** and + **sleepable** fields. + + The verifier also accepts functions by its static rules, such as the error + injection list or **security_** hooks. Such functions are listed only if + the kernel build tagged them. Even if they are listed, the restrictions of + their **bpf_fmodret_retval:** tags do not apply to them: programs may + return any value, and sleepable programs may attach to some of them without + the **sleepable** mark. This may change in the future by either not listing + them, or listing them without restrictions. Normal verifier and tracing + checks apply to all of them. + +bpftool fmodret show *FUNC* [*OBJECT*] + Show the function named *NAME* or with BTF ID *BTF_ID* in detail. It does + not have to be a target. A name may belong to several functions, for + example to functions of different modules. A BTF ID is looked up in + vmlinux, unless **module** or **file** is given. *OBJECT* is as for + **list**. + + Besides the BTF ID, the name and the object, show the prototype of the + function and if it is a target: **found by the kernel build**, **declared** + or **not tagged**. For a target show if sleepable programs may attach to it + and the values which programs may return: 0 and the values of its + **bpf_fmodret_retval:** tag with the names of the errors on the host, or + **any** for a declared target. A tag which the verifier would reject, + malformed, not the only one or with values which the return type cannot + hold, is shown as invalid. The values do not apply to a function which the + static rules allow, see **list**. For the running kernel, also show the + type of the entry of the function in the error injection list, if the list + is available in debugfs. + + With **--json**, each function contains **btf_id**, **name**, **owner**, + **prototype**, **target** (**found**, **declared** or **none**) and + **sleepable** fields, a **retval** array for a target found by the build + with the values programs may return, 0 included, or a **retval_error** + string if its tag is invalid, and an **error_injection** field if the + function is in the error injection list. A BTF ID gives one function, a + name an array of them. + +bpftool fmodret help + Print short help message. + +OPTIONS +======== + +.. include:: common_options.rst + +-B, --base-btf *FILE* + Pass the base BTF of a split BTF *FILE*, usually the BTF of vmlinux. Raw + BTF of a module needs it. A module image may carry the base it was built + against in its **.BTF.base** section instead, but its BTF IDs then differ + from those of the running kernel. + +EXAMPLES +======== + +**# bpftool fmodret show name bpf_testmod_retval_join module bpf_test_retval** + +:: + + 123456 bpf_testmod_retval_join (bpf_test_retval) + int bpf_testmod_retval_join(int *result, int value) + target: found by the kernel build + sleepable: no + retval: 0, -34 (ERANGE), -22 (EINVAL)
tools/bpf/bpftool/Documentation/bpftool.rst +3 -1
@@ -21,7 +21,7 @@ SYNOPSIS **bpftool** **version** *OBJECT* := { **map** | **prog** | **link** | **cgroup** | **perf** | **net** | **feature** | -**btf** | **gen** | **struct_ops** | **iter** } +**btf** | **gen** | **struct_ops** | **iter** | **fmodret** } *OPTIONS* := { { **-V** | **--version** } | |COMMON_OPTIONS| }
@@ -50,6 +50,8 @@ SYNOPSIS *ITER-COMMANDS* := { **pin** | **help** } +*FMODRET-COMMANDS* := { **list** | **show** | **help** } + DESCRIPTION =========== *bpftool* allows for inspection and simple modification of BPF objects on the
tools/bpf/bpftool/bash-completion/bpftool +31 -0
@@ -675,6 +675,37 @@ _bpftool() ;; esac ;; + fmodret) + case $command in + list|show) + case $prev in + file) + _filedir + ;; + module) + COMPREPLY=( $( compgen -W "$( command ls \ + /sys/kernel/btf 2>/dev/null | \ + command grep -vx -e vmlinux -e '.*\.inline' )" \ + -- "$cur" ) ) + ;; + name|id) + ;; + *) + if [[ $prev == show ]]; then + COMPREPLY=( $( compgen -W 'name id' -- "$cur" ) ) + else + _bpftool_one_of_list 'file vmlinux module' + fi + ;; + esac + return 0 + ;; + *) + [[ $prev == $object ]] && \ + COMPREPLY=( $( compgen -W 'help list show' -- "$cur" ) ) + ;; + esac + ;; map) case $command in show|list|dump|peek|pop|dequeue|freeze)
tools/bpf/bpftool/fmodret.c new file +896 -0
896 lines not on this page · raw message
tools/bpf/bpftool/main.c +2 -1
@@ -65,7 +65,7 @@ static int do_help(int argc, char **argv)" %s batch file FILE\n" " %s version\n" "\n" -" OBJECT := { prog | map | link | cgroup | perf | net | feature | btf | gen | struct_ops | iter | token }\n" +" OBJECT := { prog | map | link | cgroup | perf | net | feature | btf | gen | struct_ops | iter | fmodret | token }\n" " " HELP_SPEC_OPTIONS " |\n" " {-V|--version} }\n" "",
@@ -91,6 +91,7 @@ static const struct cmd commands[] = { { "gen", do_gen }, { "struct_ops", do_struct_ops }, { "iter", do_iter }, + { "fmodret", do_fmodret }, { "token", do_token }, { "version", do_version }, { 0 }
tools/bpf/bpftool/main.h +1 -0
@@ -178,6 +178,7 @@ int do_tracelog(int argc, char **arg) __weak;int do_feature (int argc,char **argv)__weak ;int do_struct_ops (int argc,char **argv)__weak ;int do_iter (int argc,char **argv)__weak ; +int do_fmodret (int argc,char **argv)__weak ;int do_token (int argc,char **argv)__weak ;int parse_u32_arg (int *argc,char ***argv,__u32 *val,const char *what);
Signature · 1 line
2.43.0