libbpf, bpf: Utilize CO-RE for BPF program parameter presence, ordering
Subsystems (6)
v2 cover libbpf, bpf: Utilize CO-RE for BPF program parameter presence, ordering
Currently the BPF_PROG() family of macros greatly facilitates BPF tracing/LSM program writing by allowing specification of function, tracepoint or LSM hook arguments directly by name and type. These are then mapped to a context struct consisting of a u64 array, with one value for each argument, with by-value structs larger than 8 bytes taking more than one slot.
When an attach target gains, loses or reorders parameters across kernels, programs silently read the wrong argument or fail verification, and they have no way to check if an argument actually exists.
To bring a Compile Once - Run Everywhere (CO-RE) experience to parameters for programs, this series lets programs describe the parameters they need and any variants via a struct bpf_func_args___<flavor> which can contain
- parameters in any order, to support cases where a user might only use a subset of parameters in the associated program
- parameters that may exist for some kernels, where use is guarded by bpf_core_field_exists(ctx->field)
- renamed parameters, allowing the old and new names both to be present
- parameters whose type varies across kernels: a pointer can be read through the same struct either way, and bpf_core_type_matches() on a flavor with just that parameter tells which type it is
- __ret for the return value, for fexit, fmod_ret, fsession and LSM programs
For example, a program tracing a function foo() can declare just the parameters it needs, a, b and c, in any order, irrespective of their position in foo()'s signature. It can also declare a parameter "notsure" that only some kernels have, and check whether it exists, and both names of a parameter renamed from "old" to "new". Parameter "d" is a struct file * on some kernels and a void * on others: as any two pointers are compatible, it can be read through the same struct either way, and a flavor with just that parameter tells which it is. __ret is the return value.
struct bpf_func_args___foo {
__u64 c;
int b;
char a;
long notsure;
int old;
int new;
void *d;
int __ret;
} __attribute__((preserve_access_index));
struct bpf_func_args___foo_d_file {
struct file *d;
} __attribute__((preserve_access_index));
SEC("fexit/foo")
int fexit_foo(struct bpf_func_args___foo *ctx)
{
a = ctx->a;
b = ctx->b;
c = ctx->c;
if (bpf_core_field_exists(ctx->notsure))
notsure = ctx->notsure;
if (bpf_core_field_exists(ctx->new))
val = ctx->new;
else
val = ctx->old;
if (bpf_core_type_matches(struct bpf_func_args___foo_d_file))
file = (struct file *)ctx->d;
ret = ctx->__ret;
return 0;
}Other changes, e.g. a parameter of another integer width or a struct passed by value becoming a pointer, are covered in the libbpf overview. See also tools/testing/selftests/bpf/progs/func_args_core.c for more examples of usage.
Patch 1 allows loads of the low-order bytes of context slots on big-endian, where arguments smaller than 8 bytes are at the end of their slot.
Patch 2 adds the libbpf side.
Patch 3 adds the kernel side.
Patch 4 adds selftests.
Patch 5 adds documentation for libbpf/llvm reloc.
Changes since v1 [1]:
- Reworked as suggested by Alexei: rather than matching struct members against the attach target's parameters in relo_core.c, libbpf (and, for light skeletons, the kernel) builds a struct describing the program's context in a split BTF on top of the attach target's BTF, with one member per parameter at its context offset, plus __ret. This struct is the only CO-RE candidate, so relocations against it are ordinary CO-RE, and relo_core.c is unchanged.
- Structs are recognised by name, bpf_func_args___<flavor>, rather than by a BTF decl tag. This works the same with clang and GCC, so __bpf_func_args, __bpf_func_args_marker and __bpf_func_ret are gone. The return value is the member __ret. The flavor is everything after the first "___", so any flavor works.
- Dropped BPF_PROG_CORE(): it couldn't express the variants that are the main reason to relocate arguments (Alexei). Programs use the struct directly instead.
- Dropped bpf_func_args_supported() and the type-existence special
case: as the candidate is named after the program's struct, type-based relocations, including bpf_core_type_exists() and bpf_core_type_matches(), work as usual.
- Pointer parameters follow the usual CO-RE rules, where any two pointers are compatible, instead of a stricter pointer check. bpf_core_type_matches() on a flavor containing just the parameter tells which type it points to.
- Big-endian: arguments smaller than 8 bytes are placed at the end of their slot, and a new verifier patch (patch 1) allows loads of the low-order bytes of context slots there, rather than widening loads and poisoning signed ones. The s390x selftest restriction is gone.
- libbpf: an attach target that can't be found no longer fails bpf_object__prepare(); the struct just has no candidate, and the program fails to load if it is loaded. Once the object is prepared, bpf_program__set_type(), bpf_program__set_expected_attach_type() and bpf_program__set_attach_target() fail with -EBUSY for programs whose relocations depend on them (Andrey).
- Selftests: test the libbpf and light skeleton paths, the LSM test folded in, plus renamed and missing parameters, struct and type variants, integer resizing, and the prepare-time behaviour above.
- Docs: llvm_reloc.rst describes the relocation for loader implementers; the libbpf overview covers common cases (a subset of parameters in any order; parameters that are missing, renamed or of another type on some kernels) and limitations.
[1] https://lore.kernel.org/bpf/[email protected]/
Alan Maguire (5):
bpf: Allow loads of the low-order bytes of context slots on big-endian
libbpf: Support CO-RE relocation of tracing program arguments
bpf: Support CO-RE relocation of tracing program arguments selftests/bpf: Test CO-RE relocation of tracing program arguments Documentation/bpf: Describe CO-RE relocation of function arguments
Documentation/bpf/libbpf/libbpf_overview.rst | 123 +++++++ Documentation/bpf/llvm_reloc.rst | 72 ++++ include/linux/bpf.h | 2 + kernel/bpf/btf.c | 253 ++++++++++++- kernel/bpf/check_btf.c | 1 + tools/lib/bpf/libbpf.c | 333 ++++++++++++++++++ tools/lib/bpf/libbpf.h | 13 +- tools/testing/selftests/bpf/Makefile.skel | 2 +- .../selftests/bpf/prog_tests/func_args_core.c | 129 +++++++ .../selftests/bpf/progs/func_args_core.c | 178 ++++++++++ 10 files changed, 1099 insertions(+), 7 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/func_args_core.c create mode 100644 tools/testing/selftests/bpf/progs/func_args_core.c
Signature · 1 line
2.56.0
PATCH v2 1/5 bpf: Allow loads of the low-order bytes of context slots on big-endian
The context of LSM, struct_ops and tracing programs other than iterators is an array of u64 slots, and arguments and return values smaller than 8 bytes are in the low-order bytes of theirs. btf_ctx_access() only allows loads at the start of a slot: on little-endian, a load of fewer than 8 bytes there reads the argument (truncated to the size of the load), but on big-endian, it reads the high-order bytes instead, and the argument can't be loaded on its own.
On big-endian, also allow loads of part of a slot that end at its end, i.e. that read its low-order bytes. Such a load reads the same bytes as a load of the same size at the start of the slot does on little-endian, so the bounds the verifier assumes for it, such as the range of the return value of LSM programs, which is kept in the 32-bit bounds of 4-byte loads, hold. Loads at other offsets within a slot stay rejected, as these bounds wouldn't hold for them, and pointers can still only be loaded as a whole.
Loads at the start of a slot stay allowed, so that no program that loads today is rejected, and little-endian is unaffected. Iterators are
excluded: their context is a struct whose fields, such as the uid of struct bpf_iter__tcp, are at the start of their 8 bytes, followed by padding. As struct_ops programs keep the index of their member in expected_attach_type, the program type is checked too.
This lets programs that describe their context with a struct, such as struct bpf_func_args___<flavor>, which places such arguments at the end of their slot on big-endian, read them there.
--- kernel/bpf/btf.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-)
kernel/bpf/btf.c +15 -3
@@ -7503,10 +7503,22 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type,u32 nr_args, arg;int i, ret; +/* +* Loads start at an 8-byte boundary: the start of a u64 slot, or of a +* field of an iterator's context struct. Arguments and return values +* smaller than 8 bytes are in the low-order bytes of their slot, which +* on big-endian are at its end, so loads ending there are allowed too, +* except for iterators, whose fields are followed by padding. +*/ if (off %8 ) { -bpf_log (log,"func '%s' offset %d is not multiple of 8\n" , - tname, off); -return false; +bool iter = prog->type ==BPF_PROG_TYPE_TRACING && + prog->expected_attach_type ==BPF_TRACE_ITER ; + +if (!IS_ENABLED (CONFIG_CPU_BIG_ENDIAN ) || iter || off %8 !=8 - size) { +bpf_log (log,"func '%s' offset %d is not multiple of 8\n" , + tname, off); +return false; + } } arg =btf_ctx_arg_idx (btf, t, off); args = (const struct btf_param *)(t +1 );
Signature · 1 line
2.56.0
PATCH v2 2/5 libbpf: Support CO-RE relocation of tracing program arguments
In reply to Alan MaguireBPF_PROG() and friends access the arguments of fentry/fexit/tp_btf/LSM programs by fixed position in the u64 context array. When a traced function or tracepoint gains, loses or reorders parameters, programs silently read the wrong argument (or fail verification), and there is no way to check whether a given argument exists.
Let programs describe the arguments they need as a struct named bpf_func_args___<flavor>, with members named after the parameters of the attach target, in any order, and __ret for the return value:
struct bpf_func_args___unlink {
struct filename *name;
int dfd;
int __ret;
} __attribute__((preserve_access_index));
SEC("fexit/filename_unlinkat")
int handle(struct bpf_func_args___unlink *ctx)
{
if (bpf_core_field_exists(ctx->dfd))
bpf_printk("dfd %d", ctx->dfd);
...
}For relocations against such a struct, libbpf describes the program's context as a struct of the same name in a split BTF on top of the BTF of the attach target: one member per parameter, with its name and type, at its offset in the context as laid out by the kernel's btf_ctx_arg_idx() (structs passed by value take up multiple slots), followed by __ret for fexit, fmod_ret, fsession and LSM programs. This struct is the only candidate, so the relocations themselves are ordinary CO-RE: offsets are patched, bpf_core_field_exists() reports missing arguments, unguarded accesses to them are poisoned, and bpf_core_type_matches() on the whole struct can tell apart variants of a function's signature, e.g. a parameter changing from struct vm_area_struct * to struct mm_area *. No changes to relo_core.c are needed. The candidate depends on the program, so it is kept out of the object-wide candidate cache, and built for each relocation.
Clang uses the typedef as the root type of relocations against a struct accessed through one, so typedefs and modifiers are skipped to find the struct, and an anonymous struct takes its name from its typedef. The relocation is then made against the struct itself, so that type-based relocations match the candidate, unless the struct is anonymous, which relocations can't have as their root type: type-based relocations then need a named struct.
Unlike for other types, the flavor is everything after the first triple underscore, so that any flavor works, including ones that start with or contain underscores, e.g. when generated from a program's name: with the usual rule, the essential name of such a struct isn't bpf_func_args, so all of its members would silently appear to be missing. The candidate is named after the program's struct rather than bpf_func_args, so that the root type names compared by type-based relocations match whatever the flavor is.
btf_trace_xxx prototypes carry no parameter names, so for tp_btf programs the parameters are taken from the identically-typed __probestub_xxx() function (Linux 6.5+) or, failing that, __traceiter_xxx() (Linux 5.10+), without their first void *__data parameter. On older kernels there is no candidate: guarded accesses see the arguments as missing, and unguarded accesses fail to load.
The struct can only be used in entry programs (or inlined code), as a shared subprogram has no single attach target, and only with attach targets in kernel BTF. Its type ID can't be relocated to a kernel type ID, as it only exists in libbpf. Light skeletons need the kernel to apply these relocations, which a following patch adds.
The candidate is built from the attach target when the object is prepared, which for tracing programs was only done when they were loaded. If the target isn't found, there is no candidate instead of an error, as the program then fails to load anyway, and might never be loaded, e.g. if its load strategy is manual, so preparing the object doesn't fail because of it.
The relocations depend on the type, attach type and attach target of the program, so once the object is prepared, setting them with bpf_program__set_type(), bpf_program__set_expected_attach_type() or bpf_program__set_attach_target() fails with -EBUSY for programs using the struct, instead of leaving them relocated against another target.
On big-endian targets, arguments smaller than 8 bytes are at the end of their slot, so their members are placed there. The verifier allows loads of them from the previous patch on; on older kernels, programs reading them fail to load.
--- tools/lib/bpf/libbpf.c | 333 +++++++++++++++++++++++++++++++++++++++++ tools/lib/bpf/libbpf.h | 13 +- 2 files changed, 343 insertions(+), 3 deletions(-)
tools/lib/bpf/libbpf.c +333 -0
@@ -500,6 +500,8 @@ struct bpf_program {/* the program or a function that it calls has callx */ bool has_callx;bool mark_btf_static; +/* relocations against struct bpf_func_args___xyz were applied */ +bool func_args_relocated;enum bpf_prog_type type;enum bpf_attach_type expected_attach_type;int exception_cb_idx;
@@ -6256,6 +6258,107 @@ static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, intreturn NULL ; } +#define BPF_FUNC_ARGS "bpf_func_args" + +static int bpf_prog_func_args_btf (const struct bpf_program *prog,const char *name, +struct btf **res); + +/* +* Is the root type of a relocation 'struct bpf_func_args___xyz'? Clang uses +* the typedef as the root type of relocations against a struct accessed +* through one, so skip typedefs and modifiers, and take the name of an +* anonymous struct from its typedef. Returns the root type to relocate +* against in *res_id: the struct, unless it is anonymous. +* +* Unlike for other types, the flavor is everything after the first triple +* underscore, so that it can start with or contain underscores, e.g. when +* generated from a program's name. +*/ +static bool bpf_core_is_func_args (const struct btf *btf,__u32 id,__u32 *res_id) +{ +const char *name =NULL ; +const struct btf_type *t; +__u32 root_id = id; +int depth =32 ; + + t =btf__type_by_id (btf, id); +while (t && (btf_is_typedef (t) ||btf_is_mod (t)) && depth--) { +if (btf_is_typedef (t)) + name =btf__name_by_offset (btf, t->name_off); + id = t->type; + t =btf__type_by_id (btf, id); + } +if (!t || !btf_is_struct (t)) +return false; +/* relocations can't have an anonymous root type, keep its typedef */ +if (t->name_off) { + name =btf__name_by_offset (btf, t->name_off); + *res_id = id; + }else { + *res_id = root_id; + } + +return name && (strcmp (name,BPF_FUNC_ARGS ) ==0 || +str_has_pfx (name,BPF_FUNC_ARGS "___" )); +} + +/* +* Resolve a relocation against 'struct bpf_func_args___xyz', whose only +* candidate is the struct describing the context of the program, see +* bpf_prog_func_args_btf(). The candidate depends on the program, so it is +* kept out of the object-wide candidate cache. +*/ +static int bpf_core_resolve_func_args (struct bpf_program *prog, +const struct bpf_core_relo *relo,int relo_idx, +const struct btf *local_btf,const char *local_name, +__u32 struct_id,struct bpf_core_spec *specs_scratch, +struct bpf_core_relo_res *targ_res) +{ +struct bpf_core_cand_list cands = {}; +struct bpf_core_relo struct_relo; +struct bpf_core_cand cand; +const char *struct_name; +struct btf *btf; +int err; + +/* the type only exists in libbpf, not in the kernel */ +if (relo->kind ==BPF_CORE_TYPE_ID_TARGET ) { +pr_warn ("prog '%s': relo #%d: no kernel type ID for struct %s\n" , + prog->name, relo_idx, local_name); +return -EOPNOTSUPP ; + } + +/* the relocations now depend on the program's attach target */ + prog->func_args_relocated = true; + +/* +* Name the candidate after the program's struct, so that the names +* that type-based relocations compare match whatever its flavor is. +*/ + struct_name =btf__name_by_offset (local_btf, +btf__type_by_id (local_btf, struct_id)->name_off); + err =bpf_prog_func_args_btf (prog, struct_name, &btf); +if (err) { +pr_warn ("prog '%s': relo #%d: failed to find the arguments of the attach target for struct %s: %s\n" , + prog->name, relo_idx, local_name,errstr (err)); +return err; + } +if (btf) { + cand.btf = btf; + cand.id =btf__type_cnt (btf) -1 ; + cands.cands = &cand; + cands.len =1 ; + } + +/* type-based relocations need the root to be the struct, not a typedef */ + struct_relo = *relo; + struct_relo.type_id = struct_id; + err =bpf_core_calc_relo_insn (prog->name, &struct_relo, relo_idx, local_btf, &cands, + specs_scratch, targ_res); +btf__free (btf); +return err; +} + static int bpf_core_resolve_relo(struct bpf_program *prog, const struct bpf_core_relo *relo, int relo_idx,
@@ -6269,6 +6372,7 @@ static int bpf_core_resolve_relo(struct bpf_program *prog,const struct btf_type *local_type;const char *local_name;__u32 local_id = relo->type_id; +__u32 struct_id;int err; local_type =btf__type_by_id (local_btf, local_id);
@@ -6279,6 +6383,11 @@ static int bpf_core_resolve_relo(struct bpf_program *prog,if (!local_name)return -EINVAL ; +if (relo->kind !=BPF_CORE_TYPE_ID_LOCAL && +bpf_core_is_func_args (local_btf, local_id, &struct_id)) +return bpf_core_resolve_func_args (prog, relo, relo_idx, local_btf, local_name, + struct_id, specs_scratch, targ_res); +if (relo->kind !=BPF_CORE_TYPE_ID_LOCAL && !hashmap__find (cand_cache, local_id, &cands)) { cands =bpf_core_find_cands (prog->obj, local_btf, local_id);
@@ -10685,10 +10794,26 @@ static struct bpf_sec_def custom_fallback_def;static bool has_custom_fallback_def;static int last_custom_sec_def_handler_id; +/* +* Relocations against struct bpf_func_args___xyz depend on the type, attach +* type and attach target of the program, and are applied when the object is +* prepared, so these can't change afterwards. +*/ +static bool prog_func_args_relocated (const struct bpf_program *prog) +{ +if (prog->obj->state <OBJ_PREPARED || !prog->func_args_relocated) +return false; +pr_warn ("prog '%s': can't change the attach target of a program using struct %s once the object is prepared\n" , + prog->name,BPF_FUNC_ARGS ); +return true; +} +int bpf_program__set_type (struct bpf_program *prog,enum bpf_prog_type type) {if (prog->obj->state >=OBJ_LOADED )return libbpf_err (-EBUSY ); +if (prog->type != type &&prog_func_args_relocated (prog)) +return libbpf_err (-EBUSY );/* if type is not changed, do nothing */ if (prog->type == type)
@@ -10720,6 +10845,8 @@ int bpf_program__set_expected_attach_type(struct bpf_program *prog, {if (prog->obj->state >=OBJ_LOADED )return libbpf_err (-EBUSY ); +if (prog->expected_attach_type != type &&prog_func_args_relocated (prog)) +return libbpf_err (-EBUSY ); prog->expected_attach_type = type;return 0 ;
@@ -11641,6 +11768,210 @@ static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attacreturn 0 ; } +/* Find the BTF and type ID of the kernel attach target of a program */ +static int bpf_prog_attach_target (const struct bpf_program *prog, +struct btf **btf,int *btf_id) +{ +struct bpf_object *obj = prog->obj; +int btf_obj_fd =0 , i, err; +const char *attach_name; + +if (prog->attach_btf_id) { +/* set via bpf_program__set_attach_target() */ + btf_obj_fd = prog->attach_btf_obj_fd; + *btf_id = prog->attach_btf_id; + }else { + attach_name =strchr (prog->sec_name,'/' ); +if (!prog->sec_def || !(prog->sec_def->cookie &SEC_ATTACH_BTF ) || + !attach_name || !attach_name[1 ]) { +pr_debug ("prog '%s': struct %s needs an attach target in kernel BTF\n" , + prog->name,BPF_FUNC_ARGS ); +return -EINVAL ; + } + attach_name++; + err =find_kernel_btf_id (obj, attach_name, prog->expected_attach_type, + &btf_obj_fd, btf_id); +if (err) { +pr_debug ("prog '%s': failed to find kernel BTF type ID of '%s': %s\n" , + prog->name, attach_name,errstr (err)); +return err; + } + } + + *btf = btf_obj_fd ?NULL : obj->btf_vmlinux; +for (i =0 ; btf_obj_fd && i < obj->btf_module_cnt; i++) { +if (obj->btf_modules[i].fd == btf_obj_fd) { + *btf = obj->btf_modules[i].btf; +break ; + } + } +return *btf ?0 : -ESRCH ; +} + +/* +* Add a member for an argument or the return value to the struct being built. +* Each takes up a whole number of u64 slots in the context, as laid out by +* btf_ctx_arg_idx() in the kernel. +*/ +static int func_args_add (struct btf *btf,const struct btf *targ_btf, +const char *name,__u32 type_id,__u32 *off) +{ +const struct btf_type *t; +__u32 pad =0 ; +__s64 sz; +int err; + + t =skip_mods_and_typedefs (targ_btf, type_id,NULL ); + sz = t &&btf_is_ptr (t) ?8 :btf__resolve_size (targ_btf, type_id); +if (sz <=0 ) +return sz ?: -EINVAL ; +/* a small argument is in the low bytes of its slot */ +if (sz <8 &&btf__endianness (targ_btf) ==BTF_BIG_ENDIAN ) + pad =8 - sz; +/* unnamed parameters still take up their slots */ +if (!str_is_empty (name)) { + err =btf__add_field (btf, name, type_id, (*off + pad) *8 ,0 ); +if (err) +return err; + } + *off +=roundup (sz,8 ); +return 0 ; +} + +/* +* The context of tp_btf, fentry, fexit, fmod_ret, fsession and LSM programs +* is an array of u64 slots: the arguments of the attach target, then, where +* the program can see it, its return value. Describe it as +* +* struct bpf_func_args___xyz { +* <type of the parameter> <name of the parameter>; +* ... +* <return type> __ret; +* }; +* +* in a split BTF on top of the BTF of the attach target, with the same +* name as the program's own struct (the name argument), so that it matches +* whatever that struct's flavor is. This struct is then the only CO-RE +* candidate for the program's struct, and relocations against it are +* ordinary CO-RE. +* +* Sets *res to NULL, so that there is no candidate, if the attach target is +* not found, or is a tracepoint without parameter names in BTF (kernels +* before 5.10). +*/ +static int bpf_prog_func_args_btf (const struct bpf_program *prog,const char *name, +struct btf **res) +{ +int i, id, first =0 , err; +const struct btf_param *p; +const struct btf_type *t; +struct btf *targ_btf, *btf; +bool has_ret = false; +const char *tp_name; +__u32 off =0 ; + + *res =NULL ; + +/* shared subprogs have no single attach target */ +if (prog_is_subprog (prog->obj, prog)) { +pr_warn ("prog '%s': struct %s can only be used in entry programs\n" , + prog->name,BPF_FUNC_ARGS ); +return -EOPNOTSUPP ; + } +if ((prog->type !=BPF_PROG_TYPE_TRACING && prog->type !=BPF_PROG_TYPE_LSM ) || + prog->attach_prog_fd) { +pr_warn ("prog '%s': struct %s needs an attach target in kernel BTF\n" , + prog->name,BPF_FUNC_ARGS ); +return -EOPNOTSUPP ; + } + +switch (prog->expected_attach_type) { +case BPF_TRACE_FEXIT : +case BPF_MODIFY_RETURN : +case BPF_TRACE_FSESSION : +case BPF_LSM_MAC : +case BPF_LSM_CGROUP : + has_ret = true; +break ; +case BPF_TRACE_FENTRY : +case BPF_TRACE_RAW_TP : +break ; +default : +pr_warn ("prog '%s': struct %s is not supported for this attach type\n" , + prog->name,BPF_FUNC_ARGS ); +return -EOPNOTSUPP ; + } + +/* +* A missing attach target fails the load of the program anyway, so +* leave that to it instead of failing to prepare the object, as the +* program might not be loaded at all, e.g. if its load strategy is +* BPF_PROG_LOAD_STRATEGY_MANUAL. +*/ + err =bpf_prog_attach_target (prog, &targ_btf, &id); +if (err == -ENOMEM ) +return err; +if (err) { +pr_debug ("prog '%s': attach target not found, struct %s has no members\n" , + prog->name,BPF_FUNC_ARGS ); +return 0 ; + } + + t =btf__type_by_id (targ_btf, id); +if (t &&btf_is_typedef (t)) { +/* +* btf_trace_xyz has no names of parameters. __probestub_xyz() +* has (6.5+), and __traceiter_xyz() has (5.10+). Both take +* void *__data first, which is not in the context. +*/ + tp_name =btf__name_by_offset (targ_btf, t->name_off); +if (!tp_name || !str_has_pfx (tp_name,BTF_TRACE_PREFIX )) +return -EINVAL ; + tp_name +=sizeof (BTF_TRACE_PREFIX ) -1 ; + id =find_btf_by_prefix_kind (targ_btf,"__probestub_" , tp_name,BTF_KIND_FUNC ); +if (id == -ENOENT ) + id =find_btf_by_prefix_kind (targ_btf,"__traceiter_" , tp_name, +BTF_KIND_FUNC ); +if (id == -ENOENT ) { +pr_debug ("prog '%s': tracepoint '%s' has no parameter names in BTF, struct %s has no members\n" , + prog->name, tp_name,BPF_FUNC_ARGS ); +return 0 ; + } +if (id <0 ) +return id; + t =btf__type_by_id (targ_btf, id); + first =1 ; + } +if (!t || !btf_is_func (t)) +return -EINVAL ; + t =btf__type_by_id (targ_btf, t->type); +if (!t || !btf_is_func_proto (t)) +return -EINVAL ; + + btf =btf__new_empty_split (targ_btf); +if (!btf) +return -errno; + + id =btf__add_struct (btf, name,0 ); + err = id <0 ? id :0 ; + p =btf_params (t); +/* a trailing parameter of type void is '...' */ +for (i = first; !err && i <btf_vlen (t) && p[i].type; i++) + err =func_args_add (btf, targ_btf,btf__name_by_offset (targ_btf, p[i].name_off), + p[i].type, &off); +if (!err && has_ret && t->type) + err =func_args_add (btf, targ_btf,"__ret" , t->type, &off); +if (err) { +pr_warn ("prog '%s': failed to describe the arguments of the attach target: %s\n" , + prog->name,errstr (err)); +btf__free (btf); +return err; + } +btf_type_by_id (btf, id)->size = off; + *res = btf; +return 0 ; +} +int libbpf_attach_type_by_name (const char *name,enum bpf_attach_type *attach_type) {
@@ -15658,6 +15989,8 @@ int bpf_program__set_attach_target(struct bpf_program *prog,if (prog->obj->state >=OBJ_LOADED )return libbpf_err (-EINVAL ); +if (prog_func_args_relocated (prog)) +return libbpf_err (-EBUSY );if (attach_prog_fd && !attach_func_name) {/* Store attach_prog_fd. The BTF ID will be resolved later during
tools/lib/bpf/libbpf.h +10 -3
@@ -1015,7 +1015,9 @@ LIBBPF_API enum bpf_prog_type bpf_program__type(const struct bpf_program *prog);* @param prog BPF program to set the program type for * @param type program type to set the BPF map to have * @return error code; or 0 if no error. An error occurs -* if the object is already loaded. +* if the object is already loaded, or, with -EBUSY, if it is +* prepared and libbpf relocated accesses to the arguments of the +* program through struct bpf_func_args___xyz, which depend on it. * * This must be called before the BPF object is loaded, * otherwise it has no effect and an error is returned.
@@ -1033,7 +1035,9 @@ bpf_program__expected_attach_type(const struct bpf_program *prog);* @param prog BPF program to set the attach type for * @param type attach type to set the BPF map to have * @return error code; or 0 if no error. An error occurs -* if the object is already loaded. +* if the object is already loaded, or, with -EBUSY, if it is +* prepared and libbpf relocated accesses to the arguments of the +* program through struct bpf_func_args___xyz, which depend on it. * * This must be called before the BPF object is loaded, * otherwise it has no effect and an error is returned.
@@ -1127,7 +1131,10 @@ LIBBPF_API __u32 bpf_program__line_info_cnt(const struct bpf_program *prog);* attach_prog_fd to find destination BTF type ID in that BPF program, or * alone (no attach_prog_fd) to resolve kernel (vmlinux/module) BTF ID. * Must be provided if attach_prog_fd is 0. -* @return error code; or 0 if no error occurred. +* @return error code; or 0 if no error occurred. Fails with -EBUSY +* if the object is prepared and libbpf relocated accesses to the +* arguments of the program through struct bpf_func_args___xyz, which +* depend on its attach target. */ LIBBPF_API int bpf_program__set_attach_target(struct bpf_program *prog, int attach_prog_fd,
Signature · 1 line
2.56.0
PATCH v2 3/5 bpf: Support CO-RE relocation of tracing program arguments
In reply to Alan Maguirelibbpf relocates accesses to struct bpf_func_args___<flavor> against a struct of the same name describing the context of tracing programs: one member per parameter of the attach target, named and typed after it, at its offset in the context, followed by __ret where the program can see the return value. Light skeletons leave CO-RE relocations to the kernel, so do the same here for them.
For relocations against such a struct, bpf_core_apply() builds the struct in a minimal split BTF on top of the program's attach_btf, laid out as btf_ctx_arg_idx() expects, and uses it as the only candidate, so the relocations themselves are ordinary CO-RE and relo_core.c needs no changes. Member names refer to the strings of the attach target's BTF, so only the names of the struct and of __ret are added. The candidate depends on the program, so it bypasses the candidate cache; the program holds a reference to attach_btf, so cand_cache_mutex isn't needed either. bpf_core_ctx gains the program for this.
As in libbpf, typedefs and modifiers are skipped to find the struct, an anonymous struct takes its name from its typedef, and the relocation is made against the struct itself unless it is anonymous. The flavor is everything after the first triple underscore, and the candidate is named after the program's struct, whose name is copied into the candidate's strings along with __ret.
The rules match libbpf's: __ret is only present for fexit, fmod_ret, fsession and LSM programs, other attach types and BPF program targets are rejected, as is relocating the struct's type ID to a kernel type ID, and on big-endian, arguments smaller than 8 bytes are placed in the high addresses of their slot. For tp_btf programs, the parameters are those of __probestub_xxx(), without void *__data, as btf_trace_xxx has no parameter names; unlike libbpf, which supports older kernels, no fallback is needed here. As the kernel relocates each program with its subprograms already appended, accesses from subprograms are relocated against the program's attach target, where libbpf, which relocates shared subprogram code once, rejects them.
--- include/linux/bpf.h | 2 + kernel/bpf/btf.c | 235 +++++++++++++++++++++++++++++++++++++++++ kernel/bpf/check_btf.c | 1 + 3 files changed, 238 insertions(+)
include/linux/bpf.h +2 -0
@@ -3446,6 +3446,8 @@ int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,struct bpf_core_ctx {struct bpf_verifier_log *log;const struct btf *btf; +/* the prog being loaded, if any, for struct bpf_func_args */ +const struct bpf_prog *prog; }; bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
kernel/bpf/btf.c +235 -0
261 lines not on this page · raw message
kernel/bpf/check_btf.c +1 -0
@@ -352,6 +352,7 @@ int bpf_check_core_relo(struct bpf_verifier_env *env,struct bpf_core_ctx ctx = { .log = &env->log, .btf = btf, + .prog = prog, };bpfptr_t u_core_relo;int err;
Signature · 1 line
2.56.0
PATCH v2 4/5 selftests/bpf: Test CO-RE relocation of tracing program arguments
In reply to Alan MaguireTest struct bpf_func_args___<flavor> with both libbpf and light skeletons, i.e. with relocations applied by libbpf and by the kernel, across program types:
- fentry: arguments of bpf_fentry_test3() in a different order, an argument that doesn't exist, __ret, which isn't in the context of fentry programs, a field variant, reading another argument of the same size when one doesn't exist, and a u64 argument read as a __u32, as loads of unsigned integers are resized;
- fexit: an argument and __ret, through a typedef'd anonymous struct;
- fmod_ret: arguments of bpf_modify_return_test2() in a different order, __ret, and an int argument declared as a long, read with BPF_CORE_READ_BITFIELD(), as plain loads of signed integers of another size are poisoned;
- tp_btf: an argument of sys_enter, at its offset without void *__data, and bpf_core_type_matches() telling apart a matching and a mismatching pointer argument type, with the matching struct's flavor starting with and containing triple underscores, and a struct variant, reading an argument through whichever of two structs matches;
- LSM: dereferencing the struct file * argument of file_open, and __ret.
In the variants, the access that doesn't apply is poisoned, in a branch the verifier finds dead.
For the field variant, clang turns the two loads into one, from the context plus an offset set in each branch.
As test_progs runs tests in parallel, the programs only record what they see in the test's process. fmod_ret uses bpf_modify_return_test2() rather than bpf_modify_return_test(), as another test's fmod_ret program returns non-zero for every process there, which skips the following fmod_ret programs.
Also check that an unguarded access to a missing argument fails to load (with libbpf only, as light skeletons can't enable a program that is not loaded by default).
And check, with libbpf, that preparing an object with a manually loaded program whose attach target doesn't exist succeeds, while loading that program fails, and that the type, attach type and attach target of a program using the struct can't be changed once the object is prepared.
bpf_core_type_matches() compares the names of integer types too, and clang's "long" is "long int" in kernel BTF, so the structs checked with it only have pointer members.
--- tools/testing/selftests/bpf/Makefile.skel | 2 +- .../selftests/bpf/prog_tests/func_args_core.c | 129 +++++++++++++ .../selftests/bpf/progs/func_args_core.c | 178 ++++++++++++++++++ 3 files changed, 308 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/func_args_core.c create mode 100644 tools/testing/selftests/bpf/progs/func_args_core.c
tools/testing/selftests/bpf/Makefile.skel +1 -1
@@ -40,7 +40,7 @@ LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c # Generate both light skeleton and libbpf skeleton for these LSKELS_EXTRA := test_ksyms_module.c test_ksyms_weak.c kfunc_call_test.c \ - kfunc_call_test_subprog.c test_global_percpu_data.c + kfunc_call_test_subprog.c test_global_percpu_data.c func_args_core.c SKEL_BLACKLIST += $(LSKELS) $(LSKELS_SIGNED) test_static_linked.skel.h-deps := test_static_linked1.bpf.o test_static_linked2.bpf.o
tools/testing/selftests/bpf/prog_tests/func_args_core.c new file +129 -0
129 lines not on this page · raw message
tools/testing/selftests/bpf/progs/func_args_core.c new file +178 -0
178 lines not on this page · raw message
Signature · 1 line
2.56.0
PATCH v2 5/5 Documentation/bpf: Describe CO-RE relocation of function arguments
In reply to Alan MaguireDescribe struct bpf_func_args___<flavor> in the libbpf overview: how programs use it to access the arguments and return value of their attach target, how to handle common cases, i.e. using only some parameters in any order, and parameters that are missing, renamed or of another type on some kernels, and its limitations.
In llvm_reloc.rst, describe for loader implementers how relocations against such a struct are resolved: which names are recognised, typedef handling, the candidate named after the program's struct, its layout in the context, __ret, where tp_btf parameter names come from, and big-endian placement.
--- Documentation/bpf/libbpf/libbpf_overview.rst | 123 +++++++++++++++++++ Documentation/bpf/llvm_reloc.rst | 72 +++++++++++ 2 files changed, 195 insertions(+)
Documentation/bpf/libbpf/libbpf_overview.rst +123 -0
@@ -198,6 +198,129 @@ about the field that should be relocated on the target kernel. i.e, if the ``struct task_struct`` due to some new field added in front of it, libbpf will automatically adjust the actual offset to the proper value. +CO-RE for Function Arguments +---------------------------- + +The context of tp_btf, fentry, fexit, fmod_ret, fsession and LSM programs is +an array of u64 slots holding the arguments of the attach target, followed by +its return value where the program can see it. ``BPF_PROG()`` accesses them by +position, so when a traced function or tracepoint gains, loses or reorders +parameters, programs silently read the wrong argument. + +Instead, a program can describe the arguments it needs as a struct named +``bpf_func_args___<flavor>``, with members named after the parameters of the +attach target, in any order, and ``__ret`` for the return value: + +.. code-block:: C + + struct bpf_func_args___unlink { + struct filename *name; + int dfd; + int __ret; + } __attribute__((preserve_access_index)); + + SEC("fexit/filename_unlinkat") + int handle(struct bpf_func_args___unlink *ctx) + { + if (bpf_core_field_exists(ctx->dfd)) + bpf_printk("dfd %d", ctx->dfd); + bpf_printk("%s %d", ctx->name->name, ctx->__ret); + return 0; + } + +libbpf relocates accesses to such a struct against a struct of the same name +describing the context of the program, with one member per parameter of its +attach target, followed by ``__ret`` for fexit, fmod_ret, fsession and LSM +programs. For tp_btf programs, the parameters are those of the tracepoint, +without its ``void *__data``. Otherwise, these are ordinary CO-RE relocations, +and the usual CO-RE helpers apply. The struct can be accessed through a +typedef, and an anonymous struct takes its name from its typedef, but +type-based relocations such as ``bpf_core_type_exists()`` need a named struct. + +Common cases: + +- *Only some parameters are needed, regardless of their order.* Declare + just those, in any order: each member is relocated to wherever its + parameter is, so parameters added, removed or reordered elsewhere in the + signature don't matter. + +- *A parameter may not exist on every kernel.* ``bpf_core_field_exists()`` + tells whether it does. Unguarded accesses to a missing parameter fail to + load. Likewise, ``__ret`` only exists where the program sees the return + value. + +- *A parameter is renamed across kernels.* Declare both names in the same + struct, and read whichever exists: + + .. code-block:: C + + if (bpf_core_field_exists(ctx->new_name)) + val = ctx->new_name; + else + val = ctx->old_name; + +- *A parameter's type varies across kernels.* Declare it once, with the + same name, and: + + - for an unsigned integer whose width varies, declare it at the widest + width and read it as usual: the load is resized to the parameter, and + zero-extended; + - for a signed integer whose width varies, declare it at the widest width + and read it with ``BPF_CORE_READ_BITFIELD(ctx, name)``, which loads it + at its size on the running kernel and sign-extends it. A plain access + with another size is poisoned, as for other CO-RE relocations; + - for a pointer to a type that varies, read it as usual, as any two + pointers are compatible, and tell which type it points to with + ``bpf_core_type_matches()`` on another flavor of the struct, with just + that parameter: + + .. code-block:: C + + struct bpf_func_args___new { + struct mm_area *vma; + } __attribute__((preserve_access_index)); + + if (bpf_core_type_matches(struct bpf_func_args___new)) + mm = (struct mm_area *)ctx->vma; + else + vma = (struct vm_area_struct *)ctx->vma; + + ``bpf_core_type_matches()`` also compares the names of integer types, + which may differ between the compiler and kernel BTF (e.g., ``long`` and + ``long int``), so such flavors should only describe the parameters that + differ; + - for other changes, e.g. a struct passed by value becoming a pointer, + the parameter isn't compatible with one of the declarations, so it + appears to be missing from it: declare a flavor of the struct for each + variant, and read through the one where ``bpf_core_field_exists()`` + finds it. + +Limitations: + +- with libbpf applying the relocations, accesses need to be made from the + entry program (or inlined code), as a shared subprogram has no single + attach target; +- the attach target needs to be in kernel BTF: programs attached to BPF + programs and multi-attach programs are not supported; +- with libbpf applying the relocations, the type, attach type and attach + target of the program can't be changed once the object is prepared, as + the relocations depend on them; +- ``bpf_core_type_id_kernel()`` can't be used on such a struct, as it only + exists in libbpf; +- tracepoints only have parameter names in kernel BTF from Linux 5.10, so on + older kernels all arguments of tp_btf programs appear to be missing; +- clang can turn loads of members of the same size in alternative branches, + e.g. for a renamed parameter, into one load from the context plus an + offset set in each branch, and ``BPF_CORE_READ_BITFIELD()`` loads from + the context plus an offset too. The verifier only allows such loads from + Linux 7.1, so these programs can fail to load on older kernels; +- on big-endian targets, arguments smaller than 8 bytes are at the end of + their slot, where older kernels don't allow context loads, so programs + reading them fail to load there; +- light skeletons need the kernel to support these relocations. Older + kernels and older libbpf versions find no candidate, so all arguments + appear to be missing. + Getting Started with libbpf ===========================
Documentation/bpf/llvm_reloc.rst +72 -0
75 lines not on this page · raw message
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v2 bpf-next 2/5] libbpf: Support CO-RE relocation of tracing program arguments
In reply to Alan MaguireThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] libbpf: missing 8-byte pointer size on split BTF in bpf_prog_func_args_btf() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] libbpf: missing 8-byte pointer size on split BTF in bpf_prog_func_args_btf()
--
commit 48b370da5eb67f95ec57705bfbaef14039ba87cd
Author: Alan Maguire <[email protected]>
libbpf: Support CO-RE relocation of tracing program arguments
This commit adds CO-RE relocation support for tracing and LSM program arguments described through a struct bpf_func_args___<flavor> context type by synthesizing a matching candidate struct in a split BTF on top of the attach target's BTF.
Quoted 4 lines
tools/lib/bpf/libbpf.c +0
-0
[ ... ]
Quoted 4 lines
tools/lib/bpf/libbpf.c +0
-0@@ -11641,6 +11768,210 @@ static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attacreturn 0 ; }
[ ... ]
Quoted 15 lines
tools/lib/bpf/libbpf.c +15
-0+/* +* Add a member for an argument or the return value to the struct being built. +* Each takes up a whole number of u64 slots in the context, as laid out by +* btf_ctx_arg_idx() in the kernel. +*/ +static int func_args_add (struct btf *btf,const struct btf *targ_btf, +const char *name,__u32 type_id,__u32 *off) +{ +const struct btf_type *t; +__u32 pad =0 ; +__s64 sz; +int err; + + t =skip_mods_and_typedefs (targ_btf, type_id,NULL ); + sz = t &&btf_is_ptr (t) ?8 :btf__resolve_size (targ_btf, type_id);
[ ... ]
Quoted 3 lines
tools/lib/bpf/libbpf.c +3
-0+static int bpf_prog_func_args_btf (const struct bpf_program *prog,const char *name, +struct btf **res) +{
[ ... ]
tools/lib/bpf/libbpf.c static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attac · line 11953
Quoted 3 lines
tools/lib/bpf/libbpf.c +3
-0+ btf =btf__new_empty_split (targ_btf); +if (!btf) +return -errno;
[Severity: Medium]
Should bpf_prog_func_args_btf() call btf__set_pointer_size(btf, 8) on the split BTF?
btf__new_empty_split() initializes btf->ptr_sz to sizeof(void *), which is 4 on 32-bit hosts. While func_args_add() hardcodes pointer sizes to 8 when laying out context slots, bpf_core_calc_field_relo() later calls btf__resolve_size() on the candidate split BTF and resolves BTF_KIND_PTR fields to 4 bytes. That causes bpf_core_patch_insn() to downsize 8-byte BPF_DW context pointer loads to 4-byte BPF_W loads, which the kernel verifier rejects in btf_ctx_access() because pointer loads from the u64 context array must be 8 bytes.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH v2 bpf-next 5/5] Documentation/bpf: Describe CO-RE relocation of function arguments
In reply to Alan MaguireTL;DR: Nit only, in the documentation: the libbpf overview example assigns to two different undeclared variables (mm and vma) in its branches, so it may not show how to use the result.
Quoted 1 line
Documentation/bpf: Describe CO-RE relocation of function arguments
TL;DR: Nit only, in the documentation: the libbpf overview example assigns to two different undeclared variables (mm and vma) in its branches, so it may not show how to use the result.
Quoted 3 lines
Documentation/bpf/libbpf/libbpf_overview.rst +0
-0
[ ... ]
Documentation/bpf/libbpf/libbpf_overview.rst about the field that should be relocated on the target kernel. i.e, if the · line 287
Quoted 11 lines
Documentation/bpf/libbpf/libbpf_overview.rst +11
-0+ .. code-block:: C + + struct bpf_func_args___new { + struct mm_area *vma; + } __attribute__((preserve_access_index)); + + if (bpf_core_type_matches(struct bpf_func_args___new)) + mm = (struct mm_area *)ctx->vma; + else + vma = (struct vm_area_struct *)ctx->vma; +
This isn't a bug, but the two branches of this example assign to different variables, mm and vma, and neither is declared.
Should both branches assign to the same variable, or should each use its own typed pointer, so the snippet shows how to consume the result?
---
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/45664233836