Skip to contentSkip to conversation

bpf: Support struct_ops in light skeletons

PATCH Superseded Siddharth Nayyar 3 participants 7 messages Nov 30 – Dec 1

Subsystems (6)
Kselftest BPF BPF selftests BPF core +2 more subsystems

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover bpf: Support struct_ops in light skeletons

BPF light skeletons (bpftool gen skeleton -L) compile BPF object loading into a self-contained BPF_PROG_TYPE_SYSCALL loader program (gen_loader) embedded in a C header, removing any runtime dependency on libbpf or userspace BTF parsing. Currently, light skeletons do not support BPF_MAP_TYPE_STRUCT_OPS maps or BPF_PROG_TYPE_STRUCT_OPS programs because preparing a struct_ops map normally relies on libbpf parsing the target vmlinux or kernel module BTF in userspace to resolve type IDs, struct sizes, member byte offsets, and member indices.

Since the kernel already has access to both the BPF object's BTF (loaded by the light skeleton via btf_fd) and vmlinux/module BTFs, the loader can pass static object-BTF metadata known at skeleton generation time and let the kernel match the target struct_ops type and members by name. This avoids adding a new BPF helper or kfunc, eliminates runtime BTF queries and module BTF FD management from the loader program, and avoids pre-allocating a fixed-size kernel value buffer in the loader blob.

This series adds BPF_MAP_TYPE_STRUCT_OPS support for link-based (SEC(".struct_ops.link")) maps in light skeletons across both vmlinux and kernel module BTF targets:

- Patch 1 teaches the kernel to resolve BPF_MAP_TYPE_STRUCT_OPS maps and BPF_PROG_TYPE_STRUCT_OPS attach targets from the BPF object's BTF by name (stripping any CO-RE ___flavor suffix). BPF_MAP_CREATE accepts a local struct btf_value_type_id and value_size, BPF_PROG_LOAD accepts the object BTF FD in attach_btf_obj_fd with the local struct ID and member index, and BPF_MAP_UPDATE_ELEM validates and copies the local struct layout into the kernel struct_ops value buffer.
- Patch 2 updates libbpf's gen_loader to record local struct_ops type IDs and member indices, retain btf_value_type_id on BPF_MAP_CREATE, pass the object btf_fd in attach_btf_obj_fd on BPF_PROG_LOAD, and emit bpf_gen__struct_ops_update_elem() to populate callback FDs and issue BPF_MAP_UPDATE_ELEM.
- Patch 3 teaches bpftool to generate per-map skel_link_create() attach functions and skel__attach() / skel__detach() plumbing for BPF_F_LINK struct_ops maps in light skeletons, skips gen_st_ops_shadow() so the light skeleton ctx layout is preserved, and rejects non-link struct_ops maps.
- Patch 4 adds light skeleton struct_ops selftests covering both vmlinux (tcp_congestion_ops) and bpf_testmod (bpf_testmod_ops, including a reordered subset struct bpf_testmod_ops___v2 with a zeroed member absent from the kernel, shared callbacks, scalar fields, detach, and per-map re-attachment).

Non-link struct_ops support
===========================
Non-link struct_ops maps (SEC(".struct_ops") without BPF_F_LINK) remain rejected in light skeletons for now. Because BPF_MAP_UPDATE_ELEM runs inside the loader program during skel__load(), a non-link struct_ops map would register and activate callbacks before skel__attach() is called, prevent re-attaching after detach, and leak an active registration if a later loader step fails. Supporting non-link struct_ops can be added as follow-up work by deferring BPF_MAP_UPDATE_ELEM to userspace skel__attach().

AI assistance and testing
=========================
This series (code, selftests, commit messages, and cover letter) was developed interactively with an AI coding assistant (Google Gemini), with me guiding the design step by step across each patch and reviewing all changes.

The series was built with clang/LLVM and tested in a QEMU x86_64 VM using test_progs (covering the new struct_ops_lskel selftests for both vmlinux tcp_congestion_ops and bpf_testmod_ops, as well as existing struct_ops and light skeleton tests).

---
Changes in v2:
- Replaced the BPF helper approach from v1 with kernel-side object-BTF
name matching as suggested by Alexei Starovoitov, replacing patches
1-5 with two patches (kernel and libbpf).
- Added kernel validation for local member BTF kind/func-ptr matching,
non-zero padding holes, and non-kernel btf_fd, and synced
st_ops->progs from st_ops->data in libbpf.
- Updated bpftool light skeleton skel__detach() to zero detached
struct_ops link FDs.
- Updated struct_ops_lskel selftests to assert detached link FDs are
zeroed and to test skipping a zeroed field absent from the kernel.
- Dropped the RFC prefix.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Siddharth Nayyar (4):
bpf: Support struct_ops with object BTF
libbpf: Support struct_ops in light skeleton loader
bpftool: Generate attach and detach for struct_ops in light skeletons selftests/bpf: Add light skeleton struct_ops tests

 include/linux/bpf.h                                |  14 ++
 include/uapi/linux/bpf.h                           |  17 +-
 kernel/bpf/bpf_struct_ops.c                        | 236 ++++++++++++++++++++-
 kernel/bpf/syscall.c                               |  14 +-
 tools/bpf/bpftool/gen.c                            |  72 ++++++-
 tools/include/uapi/linux/bpf.h                     |  17 +-
 tools/lib/bpf/bpf_gen_internal.h                   |   3 +
 tools/lib/bpf/gen_loader.c                         |  35 +++
 tools/lib/bpf/libbpf.c                             | 110 +++++++++-
 tools/testing/selftests/bpf/Makefile.skel          |   3 +-
 .../selftests/bpf/prog_tests/struct_ops_lskel.c    | 122 +++++++++++
 tools/testing/selftests/bpf/progs/struct_ops_mod.c |  52 +++++
 .../selftests/bpf/progs/struct_ops_vmlinux.c       |  42 ++++
 13 files changed, 715 insertions(+), 22 deletions(-)

---
base-commit: b7a509bd447085118d03dd962d2cca308e283b57
change-id: 20261102-lskel-struct-ops-03090424cfa2

Best regards,

Signature · 1 line
Siddharth Nayyar <[email protected]>
#1 lore raw

PATCH v2 1/4 bpf: Support struct_ops with object BTF

Currently, creating and populating a BPF_MAP_TYPE_STRUCT_OPS map and loading its BPF_PROG_TYPE_STRUCT_OPS programs require userspace to parse vmlinux or module BTF to resolve kernel type IDs, wrapper struct sizes, member indices, and member byte offsets. Light skeleton loaders ship a pre-generated BPF object BTF and loader program without userspace BTF parsing, while the kernel already has access to both the BPF object's BTF (via btf_fd) and vmlinux/module BTFs.

Allow BPF_MAP_TYPE_STRUCT_OPS and BPF_PROG_TYPE_STRUCT_OPS to specify their target struct and members using the BPF object's own BTF, with the kernel resolving the corresponding kernel struct_ops type and members by name (stripping any CO-RE ___flavor suffix):

- BPF_MAP_CREATE: Accept btf_value_type_id and value_size describing the local struct in btf_fd when btf_vmlinux_value_type_id is 0. Resolve bpf_struct_ops_<name> in vmlinux or module BTF, pin any owning module, and record local_btf and local_type on the map so other map operations (such as BPF_MAP_LOOKUP_ELEM) continue to see a standard struct_ops map.
- BPF_PROG_LOAD: When attach_btf_obj_fd refers to the BPF object's BTF for a BPF_PROG_TYPE_STRUCT_OPS program, resolve attach_btf_id and the local member index in expected_attach_type to the matching kernel BTF, type ID, and member index.
- BPF_MAP_UPDATE_ELEM: When local_type is set on the map, accept a value with the local struct's size and layout, validate member types, sizes, and zeroed padding holes, skip zeroed members absent from the running kernel, and copy each member into the kernel struct_ops value buffer.

Existing users passing kernel BTF IDs are unaffected.

---
 include/linux/bpf.h            |  14 +++
 include/uapi/linux/bpf.h       |  17 ++-
 kernel/bpf/bpf_struct_ops.c    | 236 +++++++++++++++++++++++++++++++++++++++--
 kernel/bpf/syscall.c           |  14 ++-
 tools/include/uapi/linux/bpf.h |  17 ++-
 5 files changed, 284 insertions(+), 14 deletions(-)
include/linux/bpf.h +14 -0
index 4f9c2bf64643..74cf542464fb 100644
@@ -2444,6 +2444,8 @@ void bpf_struct_ops_put(const void *kdata);
 int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff);
 int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,
 				       void *value);
+u32 bpf_struct_ops_map_update_size(const struct bpf_map *map);
+int bpf_struct_ops_resolve_attach(struct btf **btf, union bpf_attr *attr);
 int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,
 				      struct bpf_tramp_node *node,
 				      const struct btf_func_model *model,
@@ -2522,6 +2524,18 @@ static inline int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map,
 {
 	return -EINVAL;
 }
+
+static inline u32 bpf_struct_ops_map_update_size(const struct bpf_map *map)
+{
+	return map->value_size;
+}
+
+static inline int bpf_struct_ops_resolve_attach(struct btf **btf,
+						union bpf_attr *attr)
+{
+	return -EOPNOTSUPP;
+}
+
 static inline int bpf_struct_ops_link_create(union bpf_attr *attr)
 {
 	return -EOPNOTSUPP;
include/uapi/linux/bpf.h +16 -1
index 28904c6f0787..5d44bce55d5e 100644
@@ -1599,6 +1599,14 @@ union bpf_attr {
 						   * struct stored as the
 						   * map value
 						   */
+		/*
+		 * BPF_MAP_TYPE_STRUCT_OPS takes one of the two ids.
+		 * btf_value_type_id is a struct in btf_fd, e.g.
+		 * tcp_congestion_ops, and value_size is its size. The kernel
+		 * finds its struct_ops and the members by name.
+		 * BPF_MAP_UPDATE_ELEM takes the struct of btf_fd.
+		 * BPF_MAP_LOOKUP_ELEM returns the struct of the kernel.
+		 */
 		/* Any per-map-type extra fields
 		 *
 		 * BPF_MAP_TYPE_BLOOM_FILTER - the lowest 4 bits indicate the
@@ -1686,7 +1694,14 @@ union bpf_attr {
 		union {
 			/* valid prog_fd to attach to bpf prog */
 			__u32		attach_prog_fd;
-			/* or valid module BTF object fd or 0 to attach to vmlinux */
+			/*
+			 * or valid module BTF object fd or 0 to attach to
+			 * vmlinux. BPF_PROG_TYPE_STRUCT_OPS takes the BTF of
+			 * the bpf object too. Then attach_btf_id is a struct
+			 * in that BTF and expected_attach_type is the index
+			 * of its member. The kernel finds its struct_ops and
+			 * the member by name.
+			 */
 			__u32		attach_btf_obj_fd;
 		};
 		__u32		core_relo_cnt;	/* number of bpf_core_relo */
kernel/bpf/bpf_struct_ops.c +229 -7

304 lines not on this page · raw message

kernel/bpf/syscall.c +9 -5
index 198438b95849..3a8c25285236 100644
@@ -1899,6 +1899,8 @@ static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
 	}
 
 	value_size = bpf_map_value_size(map, attr->flags);
+	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS)
+		value_size = bpf_struct_ops_map_update_size(map);
 	value = kvmemdup_bpfptr(uvalue, value_size);
 	if (IS_ERR(value)) {
 		err = PTR_ERR(value);
@@ -3044,12 +3046,14 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
 				goto put_token;
 			}
 			if (!btf_is_kernel(attach_btf)) {
-				/* attaching through specifying bpf_prog's BTF
-				 * objects directly might be supported eventually
-				 */
-				btf_put(attach_btf);
+				/* only struct_ops can name its target in the BTF of the object */
 				err = -ENOTSUPP;
-				goto put_token;
+				if (type == BPF_PROG_TYPE_STRUCT_OPS)
+					err = bpf_struct_ops_resolve_attach(&attach_btf, attr);
+				if (err) {
+					btf_put(attach_btf);
+					goto put_token;
+				}
 			}
 		}
 	} else if (attr->attach_btf_id || multi_func) {
tools/include/uapi/linux/bpf.h +16 -1
index 28904c6f0787..5d44bce55d5e 100644
@@ -1599,6 +1599,14 @@ union bpf_attr {
 						   * struct stored as the
 						   * map value
 						   */
+		/*
+		 * BPF_MAP_TYPE_STRUCT_OPS takes one of the two ids.
+		 * btf_value_type_id is a struct in btf_fd, e.g.
+		 * tcp_congestion_ops, and value_size is its size. The kernel
+		 * finds its struct_ops and the members by name.
+		 * BPF_MAP_UPDATE_ELEM takes the struct of btf_fd.
+		 * BPF_MAP_LOOKUP_ELEM returns the struct of the kernel.
+		 */
 		/* Any per-map-type extra fields
 		 *
 		 * BPF_MAP_TYPE_BLOOM_FILTER - the lowest 4 bits indicate the
@@ -1686,7 +1694,14 @@ union bpf_attr {
 		union {
 			/* valid prog_fd to attach to bpf prog */
 			__u32		attach_prog_fd;
-			/* or valid module BTF object fd or 0 to attach to vmlinux */
+			/*
+			 * or valid module BTF object fd or 0 to attach to
+			 * vmlinux. BPF_PROG_TYPE_STRUCT_OPS takes the BTF of
+			 * the bpf object too. Then attach_btf_id is a struct
+			 * in that BTF and expected_attach_type is the index
+			 * of its member. The kernel finds its struct_ops and
+			 * the member by name.
+			 */
 			__u32		attach_btf_obj_fd;
 		};
 		__u32		core_relo_cnt;	/* number of bpf_core_relo */
Signature · 1 line
2.56.1.839.g22a8290db9-goog
#2 lore raw

Re: [PATCH bpf-next v2 1/4] bpf: Support struct_ops with object BTF

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] bpf: out-of-bounds heap read in local_to_kern_value() on crafted local BTF - [Medium] bpf: unlocked…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] bpf: out-of-bounds heap read in local_to_kern_value() on crafted local BTF
- [Medium] bpf: unlocked struct_ops_tab access in find_desc_by_local_type()
--

commit 358556cdd1778df7a46e8f700b565dd624b3828f
Author: Siddharth Nayyar <[email protected]>

bpf: Support struct_ops with object BTF

This commit allows BPF_MAP_TYPE_STRUCT_OPS maps and BPF_PROG_TYPE_STRUCT_OPS programs to specify their target struct and members using the BPF object's own BTF, resolving the corresponding kernel struct_ops type and members by name.

Quoted 4 lines
kernel/bpf/bpf_struct_ops.c +0 -0
index 3d334cd526c03..96eca8493892a 100644

[ ... ]

Quoted 1 line
kernel/bpf/bpf_struct_ops.c +0 -0
@@ -729,8 +736,152 @@ static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map)

[ ... ]

Quoted 43 lines
kernel/bpf/bpf_struct_ops.c +43 -0
+/*
+ * 'id' is a local struct, e.g. tcp_congestion_ops or tcp_congestion_ops___v2.
+ * Find bpf_struct_ops_tcp_congestion_ops in the BTF of vmlinux or of a module.
+ * A module can have it for a struct of vmlinux. The caller does btf_put(*kern_btf).
+ */
+static const struct bpf_struct_ops_desc *
+find_desc_by_local_type(const struct btf *btf, u32 id, struct btf **kern_btf)
+{
+	const struct btf_type *t = btf_type_by_id(btf, id);
+	const struct bpf_struct_ops_desc *st_ops_desc;
+	char name[KSYM_NAME_LEN];
+	const char *tname;
+	s32 value_id;
+
+	if (!t || !__btf_type_is_struct(t))
+		return ERR_PTR(-EINVAL);
+	tname = btf_name_by_offset(btf, t->name_off);
+	if (snprintf(name, sizeof(name), VALUE_PREFIX "%.*s",
+		     (int)bpf_core_essential_name_len(tname), tname) >= sizeof(name))
+		return ERR_PTR(-EINVAL);
+	value_id = bpf_find_btf_id(name, BTF_KIND_STRUCT, kern_btf);
+	if (value_id < 0)
+		return ERR_PTR(value_id);
+	st_ops_desc = bpf_struct_ops_find_value(*kern_btf, value_id);
+	if (!st_ops_desc) {
+		btf_put(*kern_btf);
+		return ERR_PTR(-EOPNOTSUPP);
+	}
+	return st_ops_desc;
+}
+
+/*
+ * attach_btf_id is a local struct and expected_attach_type is the index of its
+ * member. Replace them, and the BTF, with what the kernel has under the same names.
+ */
+int bpf_struct_ops_resolve_attach(struct btf **btf, union bpf_attr *attr)
+{
+	const struct bpf_struct_ops_desc *st_ops_desc;
+	const struct btf_member *member;
+	const struct btf_type *t;
+	struct btf *kern_btf;
+
+	st_ops_desc = find_desc_by_local_type(*btf, attr->attach_btf_id, &kern_btf);

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map) · line 806

Quoted 10 lines
kernel/bpf/bpf_struct_ops.c +10 -0
+	if (IS_ERR(st_ops_desc))
+		return PTR_ERR(st_ops_desc);
+	t = btf_type_by_id(*btf, attr->attach_btf_id);
+	if (attr->expected_attach_type >= btf_type_vlen(t)) {
+		btf_put(kern_btf);
+		return -EINVAL;
+	}
+	member = btf_type_member(t) + attr->expected_attach_type;
+	member = find_member(kern_btf, st_ops_desc->type,
+			     btf_name_by_offset(*btf, member->name_off));

[Severity: Medium]
Can find_desc_by_local_type() race with btf_add_struct_ops() and trigger a use-after-free on (*kern_btf)->struct_ops_tab?

When a module loads, btf_module_notify() publishes the module BTF in btf_idr on MODULE_STATE_COMING before the module's init function runs and before BTF_MODULE_F_LIVE is set on MODULE_STATE_LIVE. While init runs, register_bpf_struct_ops() calls btf_add_struct_ops(), which reallocates btf->struct_ops_tab via krealloc() once tab->cnt reaches tab->capacity:

CPU0 CPU1
module_init()
register_bpf_struct_ops()

    btf_add_struct_ops()
                                      bpf_struct_ops_resolve_attach()
                                        find_desc_by_local_type()
                                          bpf_find_btf_id()
                                          bpf_struct_ops_find_value()
      krealloc(btf->struct_ops_tab)
                                        find_member(..., st_ops_desc->type)
                                          <-- use-after-free

Existing struct_ops paths (such as check_struct_ops_btf_id() and the BPF_F_VTYPE_BTF_OBJ_FD branch in bpf_struct_ops_map_alloc()) guard against this by calling btf_try_get_module() to verify BTF_MODULE_F_LIVE before calling bpf_struct_ops_find() or bpf_struct_ops_find_value(). Here, bpf_struct_ops_resolve_attach() never calls btf_try_get_module(), and local_to_kern_attr() calls it only after find_desc_by_local_type() has already searched struct_ops_tab and cached st_ops_desc.

Quoted 58 lines
kernel/bpf/bpf_struct_ops.c +58 -0
+	if (!member) {
+		btf_put(kern_btf);
+		return -ENOENT;
+	}
+	attr->attach_btf_id = st_ops_desc->type_id;
+	attr->expected_attach_type = member - btf_type_member(st_ops_desc->type);
+	btf_put(*btf);
+	*btf = kern_btf;
+	return 0;
+}
+
+u32 bpf_struct_ops_map_update_size(const struct bpf_map *map)
+{
+	const struct bpf_struct_ops_map *st_map = (const struct bpf_struct_ops_map *)map;
+
+	return st_map->local_type ? st_map->local_type->size : map->value_size;
+}
+
+/*
+ * 'data' has the layout of the local struct. Copy every member to the place
+ * of the member with the same name in the struct of the kernel.
+ */
+static void *local_to_kern_value(const struct bpf_struct_ops_map *st_map, const void *data)
+{
+	const struct btf_type *t = st_map->local_type, *kern_t = st_map->st_ops_desc->type;
+	const struct btf *btf = st_map->local_btf, *kern_btf = st_map->btf;
+	const struct btf_member *member, *kern_member;
+	const struct btf_type *mtype, *kern_mtype;
+	struct bpf_struct_ops_value *value;
+	u32 i, size, kern_size;
+	int err = -EINVAL;
+
+	value = kvzalloc(st_map->map.value_size, GFP_USER);
+	if (!value)
+		return ERR_PTR(-ENOMEM);
+
+	for_each_member(i, t, member) {
+		const void *src = data + __btf_member_bit_offset(t, member) / 8;
+
+		if (__btf_member_bitfield_size(t, member) ||
+		    IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, member->type), &size)))
+			goto err;
+		kern_member = find_member(kern_btf, kern_t,
+					  btf_name_by_offset(btf, member->name_off));
+		if (!kern_member) {
+			/* This kernel doesn't have the member. That's fine when it's not in use. */
+			if (!memchr_inv(src, 0, size))
+				continue;
+			err = -ENOENT;
+			goto err;
+		}
+		if (__btf_member_bitfield_size(kern_t, kern_member) ||
+		    IS_ERR(btf_resolve_size(kern_btf,
+					    btf_type_by_id(kern_btf, kern_member->type),
+					    &kern_size)) ||
+		    size != kern_size)
+			goto err;
+		mtype = btf_type_skip_modifiers(btf, member->type, NULL);

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map) · line 874

Quoted 10 lines
kernel/bpf/bpf_struct_ops.c +10 -0
+		kern_mtype = btf_type_skip_modifiers(kern_btf, kern_member->type, NULL);
+		if (BTF_INFO_KIND(mtype->info) != BTF_INFO_KIND(kern_mtype->info))
+			goto err;
+		if (btf_type_is_ptr(mtype) &&
+		    !!btf_type_resolve_func_ptr(btf, member->type, NULL) !=
+		    !!btf_type_resolve_func_ptr(kern_btf, kern_member->type, NULL))
+			goto err;
+		memcpy(value->data + __btf_member_bit_offset(kern_t, kern_member) / 8, src, size);
+	}
+	err = check_zero_holes(btf, t, data);

[Severity: High]
Can a crafted local BTF cause local_to_kern_value() to read past the end of data?

map_update_elem() allocates data with size st_map->local_type->size (t->size). Unlike kernel BTF, a user-loaded BTF validated by BPF_BTF_LOAD allows a BTF_KIND_INT member where member_type->size exceeds the remaining bytes in t->size: btf_int_check_meta() only requires BITS_ROUNDUP_BYTES(nr_bits) <= t->size, and btf_int_check_member() checks struct_size - bytes_offset >= BITS_ROUNDUP_BYTES(nr_copy_bits) rather than member_type->size, while btf_resolve_size() returns size = member_type->size. Because neither local_to_kern_value() nor check_zero_holes() verifies that moff + size <= t->size, memchr_inv(src, 0, size) on an absent member (or memcpy() on a matched member) can read out of bounds on the kernel heap.

Also, __btf_member_bitfield_size(t, member) returns 0 whenever !btf_type_kflag(t), so non-kflag bitfields and non-byte-aligned bit offsets (__btf_member_bit_offset(t, member) % 8 != 0) are not rejected. And because btf_struct_check_meta() only checks that member offsets are non-decreasing rather than non-overlapping (moff >= prev_mend), overlapping members in t can move prev_mend backwards in check_zero_holes() and bypass padding hole checks.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

Re: [PATCH bpf-next v2 1/4] bpf: Support struct_ops with object BTF

In reply to Siddharth Nayyar

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map) · line 848

Quoted 10 lines · Siddharth Nayyar

- BPF_MAP_UPDATE_ELEM: When local_type is set on the map, accept a value with the local struct's size and layout, validate member types, sizes, and zeroed padding holes, skip zeroed members absent from the running kernel, and copy each member into the kernel struct_ops value buffer.

kernel/bpf/bpf_struct_ops.c +5 -0
+		const void *src = data + __btf_member_bit_offset(t, member) / 8;
+
+		if (__btf_member_bitfield_size(t, member) ||
+		    IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, member->type), &size)))
+			goto err;

My diff had this bug and the next one, sorry.
The size is compared with the size of the kernel member only. Nothing checks that the member fits into the local struct.

btf_int_check_member() bounds an int by nr_bits, not by its size. BPF_BTF_LOAD accepts this:

INT 'u64' size=8 nr_bits=8
STRUCT 'sched_ext_ops' size=192

    'name'         char[128]  bits_offset=0
    'hotplug_seq'  u64        bits_offset=1528

Then CAP_BPF reads the kernel heap:

  map_update_elem()       kvmemdup_bpfptr(uvalue, 192)
  local_to_kern_value()   src = data + 191, size = 8, kern_size = 8
    memcpy()              copies 7 bytes past the end of data
  BPF_MAP_LOOKUP_ELEM     returns them in hotplug_seq

When the kernel doesn't have the member the size can be anything. memchr_inv(src, 0, size) runs off the buffer as well. Reject size > t->size - offset before src is read.

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map) · line 777

Quoted 4 lines
kernel/bpf/bpf_struct_ops.c +4 -0
+	value_id = bpf_find_btf_id(name, BTF_KIND_STRUCT, kern_btf);
+	if (value_id < 0)
+		return ERR_PTR(value_id);
+	st_ops_desc = bpf_struct_ops_find_value(*kern_btf, value_id);

This races with module init.
bpf_find_btf_id() sees the BTF of a module since MODULE_STATE_COMING. struct_ops_tab starts with 4 slots. bpf_testmod registers 5 struct_ops.

bpf_struct_ops_resolve_attach() bpf_testmod_init()
st_ops_desc = &tab->ops[0]
btf_add_struct_ops()
krealloc(tab)
st_ops_desc->type <- use after free

check_struct_ops_btf_id() and bpf_struct_ops_map_alloc() call btf_try_get_module() first.
Do it in find_desc_by_local_type() before the lookup.

kernel/bpf/bpf_struct_ops.c static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map) · line 874

Quoted 6 lines
kernel/bpf/bpf_struct_ops.c +5 -0
+		if (btf_type_is_ptr(mtype) &&
+		    !!btf_type_resolve_func_ptr(btf, member->type, NULL) !=
+		    !!btf_type_resolve_func_ptr(kern_btf, kern_member->type, NULL))
+			goto err;
 
+	err = check_zero_holes(btf, t, data);

No need for these two.
The holes of the local struct are not copied. __bpf_struct_ops_map_update_elem() checks pointers by the kernel type. A NULL 'void *' callback loads with a regular skeleton and fails here.

pw-bot: cr

#4 lore raw

PATCH v2 2/4 libbpf: Support struct_ops in light skeleton loader

In reply to Siddharth Nayyar

Teach libbpf's gen_loader to create, load, and populate BPF_MAP_TYPE_STRUCT_OPS maps and BPF_PROG_TYPE_STRUCT_OPS programs using the BPF object's own BTF, relying on the kernel to resolve the target struct_ops type and members by name:

- In bpf_object__init_kern_struct_ops_maps(), sync callback pointers from st_ops->data, validate callback programs, and record the local struct type ID and member index in prog->attach_btf_id and prog->expected_attach_type when generating a loader program.
- Keep create_attr.btf_value_type_id set in bpf_object__create_map() so bpf_gen__map_create() passes the local struct's BTF type ID and size along with the object's btf_fd.
- In bpf_gen__prog_load(), populate attach_btf_obj_fd from btf_fd on the loader stack for BPF_PROG_TYPE_STRUCT_OPS programs.
- Add bpf_gen__struct_ops_update_elem() and wire it up in bpf_object_prepare_struct_ops() to embed the local struct value (with userspace bpf_program pointers zeroed out), copy initial_value when unsigned, write each loaded callback's FD at its local member offset, and emit BPF_MAP_UPDATE_ELEM.

---
 tools/lib/bpf/bpf_gen_internal.h |   3 ++
 tools/lib/bpf/gen_loader.c       |  35 +++++++++++++
 tools/lib/bpf/libbpf.c           | 110 +++++++++++++++++++++++++++++++++++++--
 3 files changed, 145 insertions(+), 3 deletions(-)
tools/lib/bpf/bpf_gen_internal.h +3 -0
index c30e05b66abc..6fc3eb02f173 100644
@@ -76,6 +76,9 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
 			struct bpf_prog_load_opts *load_attr, int prog_idx);
 void bpf_gen__map_update_elem(struct bpf_gen *gen, int map_idx, void *value, __u32 value_size,
 			      __u64 flags);
+void bpf_gen__struct_ops_update_elem(struct bpf_gen *gen, int map_idx, void *value,
+				     __u32 value_size, const __u32 *fd_offs,
+				     const int *prog_idxs, int cnt);
 void bpf_gen__map_freeze(struct bpf_gen *gen, int map_idx);
 int bpf_gen__func_ptr_map_create(struct bpf_gen *gen, const char *map_name, int obj_map_idx,
 				 void *value, __u32 value_size, const __u32 *ptr_offs,
tools/lib/bpf/gen_loader.c +35 -0
index 27b4bc9e55ac..749a86c43e7f 100644
@@ -1093,6 +1093,10 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
 	/* populate union bpf_attr with btf_fd saved in the stack earlier */
 	move_stack2blob(gen, attr_field(prog_load_attr, prog_btf_fd), 4,
 			stack_off(btf_fd));
+	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS)
+		/* attach_btf_id is a struct in the BTF of the object */
+		move_stack2blob(gen, attr_field(prog_load_attr, attach_btf_obj_fd), 4,
+				stack_off(btf_fd));
 	if (gen->attach_kind) {
 		emit_find_attach_target(gen);
 		/* populate union bpf_attr with btf_id and btf_obj_fd found by helper */
@@ -1198,6 +1202,37 @@ void bpf_gen__map_update_elem(struct bpf_gen *gen, int map_idx, void *pvalue,
 	emit_map_update_elem(gen, map_idx, &attr, attr_size, key, value, value_size);
 }
 
+/*
+ * pvalue is the struct as the object has it. The kernel moves the members to
+ * where it has them. The fds of the programs prog_idxs go to fd_offs.
+ */
+void bpf_gen__struct_ops_update_elem(struct bpf_gen *gen, int map_idx, void *pvalue,
+				     __u32 value_size, const __u32 *fd_offs,
+				     const int *prog_idxs, int cnt)
+{
+	int attr_size = offsetofend(union bpf_attr, flags);
+	int value, key, zero = 0, i;
+	union bpf_attr attr;
+
+	memset(&attr, 0, attr_size);
+	value = add_data(gen, pvalue, value_size);
+	key = add_data(gen, &zero, sizeof(zero));
+
+	/* see bpf_gen__map_update_elem() */
+	if (!OPTS_GET(gen->opts, gen_hash, false))
+		emit_copy_initial_value(gen, map_idx, value, value_size, 0);
+
+	for (i = 0; i < cnt; i++) {
+		emit2(gen, BPF_LD_IMM64_RAW_FULL(BPF_REG_2, BPF_PSEUDO_MAP_IDX_VALUE,
+						 0, 0, 0, blob_prog_fd_off(gen, prog_idxs[i])));
+		emit(gen, BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_2, 0));
+		emit2(gen, BPF_LD_IMM64_RAW_FULL(BPF_REG_1, BPF_PSEUDO_MAP_IDX_VALUE,
+						 0, 0, 0, value + fd_offs[i]));
+		emit(gen, BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_0, 0));
+	}
+	emit_map_update_elem(gen, map_idx, &attr, attr_size, key, value, value_size);
+}
+
 void bpf_gen__populate_outer_map(struct bpf_gen *gen, int outer_map_idx, int slot,
 				 int inner_map_idx)
 {
tools/lib/bpf/libbpf.c +107 -3

140 lines not on this page · raw message

Signature · 1 line
2.56.1.839.g22a8290db9-goog
#5 lore raw

PATCH v2 3/4 bpftool: Generate attach and detach for struct_ops in light skeletons

In reply to Siddharth Nayyar

Update codegen_attach_detach() to iterate over BPF_MAP_TYPE_STRUCT_OPS maps with BPF_F_LINK set. Generate dedicated per-map attach functions calling skel_link_create(), chain them in skel__attach(), and close and zero the corresponding link FDs in skel__detach().

Also skip gen_st_ops_shadow() when generating light skeletons so skel->struct_ops is not emitted between skel->maps and skel->progs, preserving the ctx layout expected by bpf_gen__finish().

Finally, reject struct_ops maps without BPF_F_LINK in light skeletons. Because the loader program runs BPF_MAP_UPDATE_ELEM during skel__load(), non-link struct_ops maps would register prematurely before skel__attach() and leak in the kernel if a later load step fails.

---
 tools/bpf/bpftool/gen.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 68 insertions(+), 4 deletions(-)
tools/bpf/bpftool/gen.c +68 -4
index ee680f7c2116..da5f7c9d99ab 100644
@@ -569,6 +569,8 @@ static void codegen_asserts(struct bpf_object *obj, const char *obj_name)
 static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
 {
 	struct bpf_program *prog;
+	struct bpf_map *map;
+	char ident[256];
 
 	bpf_object__for_each_program(prog, obj) {
 		const char *tp_name;
@@ -608,6 +610,30 @@ static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
 			", bpf_program__name(prog));
 	}
 
+	bpf_object__for_each_map(map, obj) {
+		if (!get_map_ident(map, ident, sizeof(ident)))
+			continue;
+		if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
+			continue;
+		if (!(bpf_map__map_flags(map) & BPF_F_LINK))
+			continue;
+
+		codegen("\
+			\n\
+			\n\
+			static inline int					    \n\
+			%1$s__%2$s__attach(struct %1$s *skel)			    \n\
+			{							    \n\
+				int map_fd = skel->maps.%2$s.map_fd;		    \n\
+				int fd = skel_link_create(map_fd, 0, BPF_STRUCT_OPS);\n\
+										    \n\
+				if (fd > 0)					    \n\
+					skel->links.%2$s_fd = fd;		    \n\
+				return fd;					    \n\
+			}							    \n\
+			", obj_name, ident);
+	}
+
 	codegen("\
 		\n\
 									    \n\
@@ -625,6 +651,20 @@ static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
 			", obj_name, bpf_program__name(prog));
 	}
 
+	bpf_object__for_each_map(map, obj) {
+		if (!get_map_ident(map, ident, sizeof(ident)))
+			continue;
+		if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
+			continue;
+		if (!(bpf_map__map_flags(map) & BPF_F_LINK))
+			continue;
+
+		codegen("\
+			\n\
+				ret = ret < 0 ? ret : %1$s__%2$s__attach(skel);   \n\
+			", obj_name, ident);
+	}
+
 	codegen("\
 		\n\
 			return ret < 0 ? ret : 0;			    \n\
@@ -642,6 +682,21 @@ static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
 			", bpf_program__name(prog));
 	}
 
+	bpf_object__for_each_map(map, obj) {
+		if (!get_map_ident(map, ident, sizeof(ident)))
+			continue;
+		if (bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
+			continue;
+		if (!(bpf_map__map_flags(map) & BPF_F_LINK))
+			continue;
+
+		codegen("\
+			\n\
+				skel_closenz(skel->links.%1$s_fd);	    \n\
+				skel->links.%1$s_fd = 0;		    \n\
+			", ident);
+	}
+
 	codegen("\
 		\n\
 		}							    \n\
@@ -1323,8 +1378,15 @@ static int do_skeleton(int argc, char **argv)
 			continue;
 		}
 
-		if (bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS)
+		if (bpf_map__type(map) == BPF_MAP_TYPE_STRUCT_OPS) {
+			if (use_loader && !(bpf_map__map_flags(map) & BPF_F_LINK)) {
+				p_err("struct_ops map '%s' requires BPF_F_LINK for light skeleton",
+				      bpf_map__name(map));
+				err = -ENOTSUP;
+				goto out;
+			}
 			attach_map_cnt++;
+		}
 
 		map_cnt++;
 	}
@@ -1385,9 +1447,11 @@ static int do_skeleton(int argc, char **argv)
 	}
 
 	btf = bpf_object__btf(obj);
-	err = gen_st_ops_shadow(obj_name, btf, obj);
-	if (err)
-		goto out;
+	if (!use_loader) {
+		err = gen_st_ops_shadow(obj_name, btf, obj);
+		if (err)
+			goto out;
+	}
 
 	if (prog_cnt) {
 		printf("\tstruct {\n");
Signature · 1 line
2.56.1.839.g22a8290db9-goog
#6 lore raw

PATCH v2 4/4 selftests/bpf: Add light skeleton struct_ops tests

In reply to Siddharth Nayyar

Add selftests exercising BPF_MAP_TYPE_STRUCT_OPS support in light skeletons across both vmlinux and kernel module BTF targets:

- struct_ops_vmlinux.c defines a SEC(".struct_ops.link") tcp_congestion_ops map in vmlinux BTF, testing open/load, link attachment, callback invocation over a loopback TCP connection, and unregistration upon detach.
- struct_ops_mod.c defines two SEC(".struct_ops.link") maps targeting bpf_testmod_ops in module BTF (including a reordered struct bpf_testmod_ops___v2 with a zeroed field absent from the kernel and a shared callback), testing kernel-side object-BTF resolution, scalar member copying, detach, and per-map re-attachment.

---
 tools/testing/selftests/bpf/Makefile.skel          |   3 +-
 .../selftests/bpf/prog_tests/struct_ops_lskel.c    | 122 +++++++++++++++++++++
 tools/testing/selftests/bpf/progs/struct_ops_mod.c |  52 +++++++++
 .../selftests/bpf/progs/struct_ops_vmlinux.c       |  42 +++++++
 4 files changed, 218 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/Makefile.skel +2 -1
index 45e4ce5dca4d..334342928d01 100644
@@ -34,7 +34,8 @@ LINKED_SKELS := test_static_linked.skel.h linked_funcs.skel.h		\
 LSKELS := fexit_sleep.c trace_printk.c trace_vprintk.c map_ptr_kern.c 	\
 	core_kern.c core_kern_overflow.c test_ringbuf.c			\
 	test_ringbuf_n.c test_ringbuf_map_key.c test_ringbuf_write.c    \
-	test_ringbuf_overwrite.c callx_rodata.c many_progs.c
+	test_ringbuf_overwrite.c callx_rodata.c many_progs.c		\
+	struct_ops_vmlinux.c struct_ops_mod.c
 
 LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c
 
tools/testing/selftests/bpf/prog_tests/struct_ops_lskel.c new file +122 -0

122 lines not on this page · raw message

tools/testing/selftests/bpf/progs/struct_ops_mod.c new file +52 -0

52 lines not on this page · raw message

tools/testing/selftests/bpf/progs/struct_ops_vmlinux.c new file +42 -0

42 lines not on this page · raw message

Signature · 1 line
2.56.1.839.g22a8290db9-goog