Skip to contentSkip to conversation

resolve_btfids: Discover kfuncs from BTF ID sets

PATCH Applied Ihor Solodrai 6 participants 31 messages Jul 22 – Jul 30

Subsystems (3)
lore
Share & tools
lore

Ihor Solodrai

author reviewer
#0 lore raw

cover resolve_btfids: Discover kfuncs from BTF ID sets

This series develops resolve_btfids in preparation for bringing kernel-specific BTF transformations in tree, which will reduce kbuild dependency on pahole's features.

resolve_btfids currently identifies kfuncs by reading the "bpf_kfunc" decl tags pahole emits into vmlinux BTF. The series switches the source of truth to the BTF ID sets registered with BTF_KFUNCS_START()/END() in the kernel, which is the mechanism BPF verifier uses.

The series is based on patches #5 and #6 from the original "resolve_btfids: Implement BTF tags emission for kfuncs" series [1], and includes a few significant additions. Particularly the build time enforcement of kfunc flags consistency [2].

The series consists of:
- patches #1-#3 implement supporting infrastructure for the proper kfunc discovery and deduplication
- patches #4-#5 expose btf__find_by_name_kind_own() and use it to fix a latent bug in _impl func lookup
- patch #6 fixes inconsistent kfunc flags for HID kfuncs
- patch #7 implements kfunc discovery from BTF ID sets
- patch #8 adds enforcement of kfunc flags consistency

The resolve_btfids selftests patches have landed earlier [3].

[1] https://lore.kernel.org/bpf/[email protected]/
[2] https://lore.kernel.org/bpf/[email protected]/
[3] https://lore.kernel.org/bpf/[email protected]/

---

Changes compared to [1]:
- Drop the idempotency (ensure_*) machinery: assume valid input BTF (Andrii)
- Use rbtree to store the kfuncs (Andrii)
- Enforce full KF_* flag consistency as a build error (Eduard)
- Various cleanups and nits (Andrii, Emil, Jiri)

---

Ihor Solodrai (8):
resolve_btfids: Implement generic ensure_mem() to grow arrays
resolve_btfids: Index BTF ID symbols by address
resolve_btfids: Keep collected kfuncs in a rbtree
libbpf: Export btf__find_by_name_kind_own()
resolve_btfids: Fix the _impl lookup for module BTF
HID: bpf: Make syscall kfunc flags match the struct_ops set
resolve_btfids: Discover kfuncs from BTF ID sets
resolve_btfids: Enforce consistent kfunc flags across BTF ID sets

 drivers/hid/bpf/hid_bpf_dispatch.c |  10 +-
 tools/bpf/resolve_btfids/main.c    | 275 ++++++++++++++++++-----------
 tools/lib/bpf/btf.h                |   2 +
 tools/lib/bpf/libbpf.map           |   1 +
 tools/lib/bpf/libbpf_internal.h    |   2 -
 5 files changed, 181 insertions(+), 109 deletions(-)
Signature · 1 line
2.55.0
author reviewer
#1 lore raw

PATCH 1/8 resolve_btfids: Implement generic ensure_mem() to grow arrays

push_*() helpers in resolve_btfids contain copy-pasted array growth logic. Factor it out into ensure_mem() - a simplified variant of libbpf_ensure_mem(), and use it in the helpers.

---
 tools/bpf/resolve_btfids/main.c | 55 ++++++++++++++++++++-------------
 1 file changed, 33 insertions(+), 22 deletions(-)
tools/bpf/resolve_btfids/main.c +33 -22
index f8a91fa7584f..183466ddc5f9 100644
@@ -201,6 +201,35 @@ static int eprintf(int level, int var, const char *fmt, ...)
 #define pr_info(fmt, ...) \
 	eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
 
+/*
+ * Grow *data so it can hold at least cnt elements of elem_sz bytes each.
+ * *cap is the capacity in elements and is updated on growth.
+ */
+static int __ensure_mem(void **data, u32 *cap, u32 cnt, size_t elem_sz)
+{
+	u32 new_cap, old_cap = *cap;
+	void *arr;
+
+	if (cnt <= old_cap)
+		return 0;
+
+	new_cap = max(old_cap + 256, old_cap * 2);
+	if (new_cap < cnt)
+		new_cap = cnt;
+
+	arr = realloc(*data, elem_sz * new_cap);
+	if (!arr)
+		return -ENOMEM;
+
+	*data = arr;
+	*cap = new_cap;
+
+	return 0;
+}
+
+#define ensure_mem(arr_ptr, cap_ptr, cnt) \
+	__ensure_mem((void **)(arr_ptr), (cap_ptr), (cnt), sizeof(**(arr_ptr)))
+
 static bool is_btf_id(const char *name)
 {
 	return name && !strncmp(name, BTF_ID_PREFIX, sizeof(BTF_ID_PREFIX) - 1);
@@ -890,17 +919,8 @@ static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf, s3
 
 static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
 {
-	u32 *arr = ctx->decl_tags;
-	u32 cap = ctx->max_decl_tags;
-
-	if (ctx->nr_decl_tags + 1 > cap) {
-		cap = max(cap + 256, cap * 2);
-		arr = realloc(arr, sizeof(u32) * cap);
-		if (!arr)
-			return -ENOMEM;
-		ctx->max_decl_tags = cap;
-		ctx->decl_tags = arr;
-	}
+	if (ensure_mem(&ctx->decl_tags, &ctx->max_decl_tags, ctx->nr_decl_tags + 1))
+		return -ENOMEM;
 
 	ctx->decl_tags[ctx->nr_decl_tags++] = decl_tag_id;
 
@@ -909,17 +929,8 @@ static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
 
 static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
 {
-	struct kfunc *arr = ctx->kfuncs;
-	u32 cap = ctx->max_kfuncs;
-
-	if (ctx->nr_kfuncs + 1 > cap) {
-		cap = max(cap + 256, cap * 2);
-		arr = realloc(arr, sizeof(struct kfunc) * cap);
-		if (!arr)
-			return -ENOMEM;
-		ctx->max_kfuncs = cap;
-		ctx->kfuncs = arr;
-	}
+	if (ensure_mem(&ctx->kfuncs, &ctx->max_kfuncs, ctx->nr_kfuncs + 1))
+		return -ENOMEM;
 
 	ctx->kfuncs[ctx->nr_kfuncs++] = *kfunc;
 
Signature · 1 line
2.55.0
author reviewer
#5 lore raw

PATCH 2/8 resolve_btfids: Index BTF ID symbols by address

In reply to Ihor Solodrai

Keep an address-sorted index of parsed .BTF_ids symbols so that the original BTF_ID symbol name can be recovered from an entry address.

Use the index in find_kfunc_flags() to scan BTF_SET8_KFUNCS entries directly and match each entry back to the requested kfunc.

---
 tools/bpf/resolve_btfids/main.c | 96 ++++++++++++++++++++++++---------
 1 file changed, 72 insertions(+), 24 deletions(-)
tools/bpf/resolve_btfids/main.c +72 -24
index 183466ddc5f9..3198198b03a7 100644
@@ -119,6 +119,11 @@ struct btf_id {
 	Elf64_Addr	 addr[ADDR_CNT];
 };
 
+struct addr_sym {
+	Elf64_Addr	 addr;
+	const char	*name;
+};
+
 struct object {
 	const char *path;
 	const char *btf_path;
@@ -150,6 +155,10 @@ struct object {
 	int nr_structs;
 	int nr_unions;
 	int nr_typedefs;
+
+	struct addr_sym *addr_syms;
+	u32 addr_syms_cnt;
+	u32 addr_syms_cap;
 };
 
 #define KF_IMPLICIT_ARGS (1 << 16)
@@ -509,6 +518,40 @@ static int elf_collect(struct object *obj)
 	return 0;
 }
 
+static int push_addr_sym(struct object *obj, Elf64_Addr addr, const char *name)
+{
+	if (ensure_mem(&obj->addr_syms, &obj->addr_syms_cap, obj->addr_syms_cnt + 1))
+		return -ENOMEM;
+
+	obj->addr_syms[obj->addr_syms_cnt++] = (struct addr_sym){
+		.addr = addr,
+		.name = name,
+	};
+
+	return 0;
+}
+
+static int cmp_addr_sym(const void *a, const void *b)
+{
+	Elf64_Addr aa = ((const struct addr_sym *)a)->addr;
+	Elf64_Addr ab = ((const struct addr_sym *)b)->addr;
+
+	return (aa > ab) - (aa < ab);
+}
+
+static const char *find_name_by_addr(struct object *obj, Elf64_Addr addr)
+{
+	struct addr_sym key = { .addr = addr };
+	struct addr_sym *res;
+
+	if (!obj->addr_syms_cnt)
+		return NULL;
+
+	res = bsearch(&key, obj->addr_syms, obj->addr_syms_cnt,
+		      sizeof(*obj->addr_syms), cmp_addr_sym);
+	return res ? res->name : NULL;
+}
+
 static int symbols_collect(struct object *obj)
 {
 	Elf_Scn *scn = NULL;
@@ -602,8 +645,15 @@ static int symbols_collect(struct object *obj)
 			return -1;
 		}
 		id->addr[id->addr_cnt++] = sym.st_value;
+
+		if (push_addr_sym(obj, sym.st_value, id->name))
+			return -1;
 	}
 
+	if (obj->addr_syms_cnt)
+		qsort(obj->addr_syms, obj->addr_syms_cnt,
+		      sizeof(*obj->addr_syms), cmp_addr_sym);
+
 	return 0;
 }
 
@@ -957,43 +1007,40 @@ static int collect_decl_tags(struct btf2btf_context *ctx)
 }
 
 /*
- * To find the kfunc flags having its struct btf_id (with ELF addresses)
- * we need to find the address that is in range of a set8.
- * If a set8 is found, then the flags are located at addr + 4 bytes.
+ * To find kfunc flags, scan BTF_SET8_KFUNCS entries and use the entry
+ * address to recover the corresponding BTF_ID symbol name.
  * Return 0 (no flags!) if not found.
  */
 static u32 find_kfunc_flags(struct object *obj, struct btf_id *kfunc_id)
 {
-	const u32 *elf_data_ptr = obj->efile.idlist->d_buf;
-	u64 set_lower_addr, set_upper_addr, addr;
+	Elf_Data *idlist = obj->efile.idlist;
 	struct btf_id *set_id;
 	struct rb_node *next;
-	u32 flags;
-	u64 idx;
 
 	for (next = rb_first(&obj->sets); next; next = rb_next(next)) {
+		struct btf_id_set8 *set8;
+		u64 set_addr;
+
 		set_id = rb_entry(next, struct btf_id, rb_node);
 		if (set_id->kind != BTF_ID_KIND_SET8 || set_id->addr_cnt != 1)
 			continue;
 
-		set_lower_addr = set_id->addr[0];
-		set_upper_addr = set_lower_addr + set_id->cnt * sizeof(u64);
+		set_addr = set_id->addr[0];
+		set8 = idlist->d_buf + (set_addr - obj->efile.idlist_addr);
+		if (!(set8->flags & BTF_SET8_KFUNCS))
+			continue;
 
-		for (u32 i = 0; i < kfunc_id->addr_cnt; i++) {
-			addr = kfunc_id->addr[i];
-			/*
-			 * Lower bound is exclusive to skip the 8-byte header of the set.
-			 * Upper bound is inclusive to capture the last entry at offset 8*cnt.
-			 */
-			if (set_lower_addr < addr && addr <= set_upper_addr) {
-				pr_debug("found kfunc %s in BTF_ID_FLAGS %s\n",
-					 kfunc_id->name, set_id->name);
-				idx = addr - obj->efile.idlist_addr;
-				idx = idx / sizeof(u32) + 1;
-				flags = elf_data_ptr[idx];
-
-				return flags;
-			}
+		for (u32 i = 0; i < set_id->cnt; i++) {
+			size_t off = (char *)&set8->pairs[i] - (char *)set8;
+			const char *name = find_name_by_addr(obj, set_addr + off);
+
+			if (!name || strcmp(name, kfunc_id->name) != 0)
+				continue;
+
+			pr_debug("found kfunc %s in BTF_ID_FLAGS %s\n",
+				 kfunc_id->name, set_id->name);
+
+			return set8->pairs[i].flags;
 		}
 	}
 
@@ -1586,6 +1633,7 @@ int main(int argc, const char **argv)
 	btf_id__free_all(&obj.typedefs);
 	btf_id__free_all(&obj.funcs);
 	btf_id__free_all(&obj.sets);
+	free(obj.addr_syms);
 	if (obj.efile.elf) {
 		elf_end(obj.efile.elf);
 		close(obj.efile.fd);
Signature · 1 line
2.55.0
author reviewer
#7 lore raw

PATCH 3/8 resolve_btfids: Keep collected kfuncs in a rbtree

In reply to Ihor Solodrai

Store collected kfuncs in a rbtree keyed by BTF ID instead of a dynamically grown array. This allows for efficient deduplication for kfuncs declared in multiple sets, which is needed for subsequent patches [1].

[1] https://lore.kernel.org/bpf/CAEf4BzaLzX3mXvQzxv+gbmZOh84XvYofLjMSWFYghNjS-ohEZg@mail.gmail.com/

---
 tools/bpf/resolve_btfids/main.c | 50 +++++++++++++++++++++++++++------
 1 file changed, 42 insertions(+), 8 deletions(-)
tools/bpf/resolve_btfids/main.c +42 -8
index 3198198b03a7..de4986e1bc3d 100644
@@ -165,6 +165,7 @@ struct object {
 #define KF_IMPL_SUFFIX "_impl"
 
 struct kfunc {
+	struct rb_node rb_node;
 	const char *name;
 	u32 btf_id;
 	u32 flags;
@@ -175,9 +176,7 @@ struct btf2btf_context {
 	u32 *decl_tags;
 	u32 nr_decl_tags;
 	u32 max_decl_tags;
-	struct kfunc *kfuncs;
-	u32 nr_kfuncs;
-	u32 max_kfuncs;
+	struct rb_root kfuncs;
 };
 
 static int verbose;
@@ -979,14 +978,48 @@ static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
 
 static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
 {
-	if (ensure_mem(&ctx->kfuncs, &ctx->max_kfuncs, ctx->nr_kfuncs + 1))
+	struct rb_node **p = &ctx->kfuncs.rb_node;
+	struct rb_node *parent = NULL;
+	struct kfunc *k;
+
+	/* Dedup by BTF ID: collecting the same kfunc twice is a no-op. */
+	while (*p) {
+		parent = *p;
+		k = rb_entry(parent, struct kfunc, rb_node);
+
+		if (kfunc->btf_id < k->btf_id)
+			p = &(*p)->rb_left;
+		else if (kfunc->btf_id > k->btf_id)
+			p = &(*p)->rb_right;
+		else
+			return 0;
+	}
+
+	k = zalloc(sizeof(*k));
+	if (!k)
 		return -ENOMEM;
 
-	ctx->kfuncs[ctx->nr_kfuncs++] = *kfunc;
+	*k = *kfunc;
+	rb_link_node(&k->rb_node, parent, p);
+	rb_insert_color(&k->rb_node, &ctx->kfuncs);
 
 	return 0;
 }
 
+static void free_kfuncs(struct rb_root *root)
+{
+	struct rb_node *next;
+	struct kfunc *kfunc;
+
+	next = rb_first(root);
+	while (next) {
+		kfunc = rb_entry(next, struct kfunc, rb_node);
+		next = rb_next(&kfunc->rb_node);
+		rb_erase(&kfunc->rb_node, root);
+		free(kfunc);
+	}
+}
+
 static int collect_decl_tags(struct btf2btf_context *ctx)
 {
 	const u32 type_cnt = btf__type_cnt(ctx->btf);
@@ -1272,14 +1305,15 @@ static int process_kfunc_with_implicit_args(struct btf2btf_context *ctx, struct
 static int btf2btf(struct object *obj)
 {
 	struct btf2btf_context ctx = {};
+	struct rb_node *next;
 	int err;
 
 	err = build_btf2btf_context(obj, &ctx);
 	if (err)
 		goto out;
 
-	for (u32 i = 0; i < ctx.nr_kfuncs; i++) {
-		struct kfunc *kfunc = &ctx.kfuncs[i];
+	for (next = rb_first(&ctx.kfuncs); next; next = rb_next(next)) {
+		struct kfunc *kfunc = rb_entry(next, struct kfunc, rb_node);
 
 		if (!(kfunc->flags & KF_IMPLICIT_ARGS))
 			continue;
@@ -1292,7 +1326,7 @@ static int btf2btf(struct object *obj)
 	err = 0;
 out:
 	free(ctx.decl_tags);
-	free(ctx.kfuncs);
+	free_kfuncs(&ctx.kfuncs);
 
 	return err;
 }
Signature · 1 line
2.55.0
author reviewer
#11 lore raw

PATCH 4/8 libbpf: Export btf__find_by_name_kind_own()

In reply to Ihor Solodrai

btf__find_by_name_kind() searches the base BTF before the split BTF, so in case of a name collision between base and split it always returns a base type. Tools that process split BTF may need to restrict a lookup to the split's own types.

The internal helper btf__find_by_name_kind_own() already does exactly that. Make it a public API.

---
 tools/lib/bpf/btf.h             | 2 ++
 tools/lib/bpf/libbpf.map        | 1 +
 tools/lib/bpf/libbpf_internal.h | 2 --
 3 files changed, 3 insertions(+), 2 deletions(-)
tools/lib/bpf/btf.h +2 -0
index 1a31f2da947f..587172c0de08 100644
@@ -172,6 +172,8 @@ LIBBPF_API __s32 btf__find_by_name(const struct btf *btf,
 				   const char *type_name);
 LIBBPF_API __s32 btf__find_by_name_kind(const struct btf *btf,
 					const char *type_name, __u32 kind);
+LIBBPF_API __s32 btf__find_by_name_kind_own(const struct btf *btf,
+					    const char *type_name, __u32 kind);
 LIBBPF_API __u32 btf__type_cnt(const struct btf *btf);
 LIBBPF_API const struct btf *btf__base_btf(const struct btf *btf);
 LIBBPF_API const struct btf_type *btf__type_by_id(const struct btf *btf,
tools/lib/bpf/libbpf.map +1 -0
index b731df19ae69..08ab2ea881fb 100644
@@ -460,5 +460,6 @@ LIBBPF_1.8.0 {
 	global:
 		bpf_program__attach_tracing_multi;
 		bpf_program__clone;
+		btf__find_by_name_kind_own;
 		btf__new_empty_opts;
 } LIBBPF_1.7.0;
tools/lib/bpf/libbpf_internal.h +0 -2
index d5b7db703b3f..7a74abb904f8 100644
@@ -596,8 +596,6 @@ typedef int (*type_id_visit_fn)(__u32 *type_id, void *ctx);
 typedef int (*str_off_visit_fn)(__u32 *str_off, void *ctx);
 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx);
 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx);
-__s32 btf__find_by_name_kind_own(const struct btf *btf, const char *type_name,
-				 __u32 kind);
 
 /* handle direct returned errors */
 static inline int libbpf_err(int ret)
Signature · 1 line
2.55.0
author reviewer
#15 lore raw

PATCH 5/8 resolve_btfids: Fix the _impl lookup for module BTF

In reply to Ihor Solodrai

process_kfunc_with_implicit_args() skips generating <name>_impl function when one already exists for backwards compatibility.

It uses btf__find_by_name_kind(), which searches the base BTF before the split BTF. When resolve_btfids processes a module, a same-named _impl in vmlinux would be found and the module's own counterpart would not be created.

Fix by using btf__find_by_name_kind_own() for the lookup.

---
 tools/bpf/resolve_btfids/main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/bpf/resolve_btfids/main.c +1 -1
index de4986e1bc3d..ab3ab3045592 100644
@@ -1232,7 +1232,7 @@ static int process_kfunc_with_implicit_args(struct btf2btf_context *ctx, struct
 		return -E2BIG;
 	}
 
-	if (btf__find_by_name_kind(btf, tmp_name, BTF_KIND_FUNC) > 0) {
+	if (btf__find_by_name_kind_own(btf, tmp_name, BTF_KIND_FUNC) > 0) {
 		pr_debug("resolve_btfids: function %s already exists in BTF\n", tmp_name);
 		goto add_new_proto;
 	}
Signature · 1 line
2.55.0
author reviewer
#18 lore raw

PATCH 6/8 HID: bpf: Make syscall kfunc flags match the struct_ops set

In reply to Ihor Solodrai

Update kfunc flags for hid_bpf_syscall_kfunc_ids set to exactly match hid_bpf_kfunc_ids set by adding KF_SLEEPABLE flag.

The syscall set omitted the flag because syscall programs are always sleepable (the verifier rejects a non-sleepable syscall program).

However the upcoming resolve_btfids change enforces per-kfunc flag consistency across BTF ID sets at build time, which is why this change is necessary.

---
 drivers/hid/bpf/hid_bpf_dispatch.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/hid/bpf/hid_bpf_dispatch.c +5 -5
index 536f6d01fd14..44671dbdeca8 100644
@@ -590,11 +590,11 @@ static const struct btf_kfunc_id_set hid_bpf_kfunc_set = {
 
 /* for syscall HID-BPF */
 BTF_KFUNCS_START(hid_bpf_syscall_kfunc_ids)
-BTF_ID_FLAGS(func, hid_bpf_allocate_context, KF_ACQUIRE | KF_RET_NULL)
-BTF_ID_FLAGS(func, hid_bpf_release_context, KF_RELEASE)
-BTF_ID_FLAGS(func, hid_bpf_hw_request)
-BTF_ID_FLAGS(func, hid_bpf_hw_output_report)
-BTF_ID_FLAGS(func, hid_bpf_input_report)
+BTF_ID_FLAGS(func, hid_bpf_allocate_context, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_release_context, KF_RELEASE | KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_hw_request, KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_hw_output_report, KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_input_report, KF_SLEEPABLE)
 BTF_KFUNCS_END(hid_bpf_syscall_kfunc_ids)
 
 static const struct btf_kfunc_id_set hid_bpf_syscall_kfunc_set = {
Signature · 1 line
2.55.0
author reviewer
#22 lore raw

PATCH 7/8 resolve_btfids: Discover kfuncs from BTF ID sets

In reply to Ihor Solodrai

collect_kfuncs() currently uses bpf_kfunc decl tags to identify the list of kfuncs. The decl tags are generated by pahole, which makes current implementation implicitly rely on those tags being generated.

The authoritative source, used by the the BPF verifier for kfunc registration, of functions being BPF kfuncs are BTF_KFUNCS_START()/END() declarations. These are BTF_ID_SET8 under the hood. Currently resolve_btfids reads kfunc flags from these sets, and populates them with BTF IDs.

Implement kfunc discovery from BTF_ID_SET8 symbols in resolve_btfids, removing the dependency on pahole's emmission of decl tags.

Walk BTF_ID_KIND_SET8 sets, and use the address-to-symbol index to look up set entry's BTF_ID symbol name (before .BTF_ids is patched), recording the paired flags directly. This makes find_kfunc_flags() helper unnecessary, so it's removed.

---
 tools/bpf/resolve_btfids/main.c | 89 +++++++++++----------------------
 1 file changed, 29 insertions(+), 60 deletions(-)
tools/bpf/resolve_btfids/main.c +29 -60
index ab3ab3045592..338d0c0a8e58 100644
@@ -1039,19 +1039,18 @@ static int collect_decl_tags(struct btf2btf_context *ctx)
 	return 0;
 }
 
-/*
- * To find kfunc flags, scan BTF_SET8_KFUNCS entries and use the entry
- * address to recover the corresponding BTF_ID symbol name.
- * Return 0 (no flags!) if not found.
- */
-static u32 find_kfunc_flags(struct object *obj, struct btf_id *kfunc_id)
+static int collect_kfuncs(struct object *obj, struct btf2btf_context *ctx)
 {
 	Elf_Data *idlist = obj->efile.idlist;
-	struct btf_id *set_id;
+	struct btf *btf = ctx->btf;
 	struct rb_node *next;
 
+	if (!idlist || !idlist->d_buf)
+		return 0;
+
 	for (next = rb_first(&obj->sets); next; next = rb_next(next)) {
 		struct btf_id_set8 *set8;
+		struct btf_id *set_id;
 		u64 set_addr;
 
 		set_id = rb_entry(next, struct btf_id, rb_node);
@@ -1066,64 +1065,34 @@ static u32 find_kfunc_flags(struct object *obj, struct btf_id *kfunc_id)
 		for (u32 i = 0; i < set_id->cnt; i++) {
 			size_t off = (char *)&set8->pairs[i] - (char *)set8;
 			const char *name = find_name_by_addr(obj, set_addr + off);
+			struct kfunc kfunc;
+			s32 func_id;
+			int err;
 
-			if (!name || strcmp(name, kfunc_id->name) != 0)
+			if (!name) {
+				pr_err("WARN: resolve_btfids: no BTF ID symbol for %s entry %u\n",
+				       set_id->name, i);
+				warnings++;
 				continue;
+			}
 
-			pr_debug("found kfunc %s in BTF_ID_FLAGS %s\n",
-				 kfunc_id->name, set_id->name);
-
-			return set8->pairs[i].flags;
-		}
-	}
-
-	return 0;
-}
-
-static int collect_kfuncs(struct object *obj, struct btf2btf_context *ctx)
-{
-	const char *tag_name, *func_name;
-	struct btf *btf = ctx->btf;
-	const struct btf_type *t;
-	u32 flags, func_id;
-	struct kfunc kfunc;
-	struct btf_id *id;
-	int err;
-
-	if (ctx->nr_decl_tags == 0)
-		return 0;
-
-	for (u32 i = 0; i < ctx->nr_decl_tags; i++) {
-		t = btf__type_by_id(btf, ctx->decl_tags[i]);
-		if (btf_kflag(t) || btf_decl_tag(t)->component_idx != -1)
-			continue;
-
-		tag_name = btf__name_by_offset(btf, t->name_off);
-		if (strcmp(tag_name, "bpf_kfunc") != 0)
-			continue;
-
-		func_id = t->type;
-		t = btf__type_by_id(btf, func_id);
-		if (!btf_is_func(t))
-			continue;
-
-		func_name = btf__name_by_offset(btf, t->name_off);
-		if (!func_name)
-			continue;
-
-		id = btf_id__find(&obj->funcs, func_name);
-		if (!id || id->kind != BTF_ID_KIND_SYM)
-			continue;
-
-		flags = find_kfunc_flags(obj, id);
+			func_id = btf__find_by_name_kind_own(btf, name, BTF_KIND_FUNC);
+			if (func_id < 0) {
+				pr_err("WARN: resolve_btfids: no BTF func for kfunc %s in %s\n",
+				       name, set_id->name);
+				warnings++;
+				continue;
+			}
 
-		kfunc.name = id->name;
-		kfunc.btf_id = func_id;
-		kfunc.flags = flags;
+			pr_debug("found kfunc %s in %s\n", name, set_id->name);
 
-		err = push_kfunc(ctx, &kfunc);
-		if (err)
-			return err;
+			kfunc.name = name;
+			kfunc.btf_id = func_id;
+			kfunc.flags = set8->pairs[i].flags;
+			err = push_kfunc(ctx, &kfunc);
+			if (err)
+				return err;
+		}
 	}
 
 	return 0;
Signature · 1 line
2.55.0
author reviewer
#26 lore raw

PATCH 8/8 resolve_btfids: Enforce consistent kfunc flags across BTF ID sets

In reply to Ihor Solodrai

A kfunc may be listed in several BTF ID sets, which is expected because different kfuncs are available to BPF programs depending on their type.

However kfunc flags across different BTF ID sets must be consistent [1]. The flags should be considered a part of the kfunc declaration, because they influence its BTF representation and verifier handling.

Enforce the kfunc flag consistency in resolve_btifds by hard failing on error and blocking kernel (or module) build.

[1] https://lore.kernel.org/bpf/[email protected]/

---
 tools/bpf/resolve_btfids/main.c | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)
tools/bpf/resolve_btfids/main.c +13 -4
index 338d0c0a8e58..85488935909d 100644
@@ -982,17 +982,26 @@ static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
 	struct rb_node *parent = NULL;
 	struct kfunc *k;
 
-	/* Dedup by BTF ID: collecting the same kfunc twice is a no-op. */
+	/*
+	 * Dedup by BTF ID: collecting the same kfunc twice is a no-op,
+	 * UNLESS the kfunc flags are inconsistent, in which case we
+	 * fail hard because it indicates a bug in a kfunc set declaration.
+	 */
 	while (*p) {
 		parent = *p;
 		k = rb_entry(parent, struct kfunc, rb_node);
 
-		if (kfunc->btf_id < k->btf_id)
+		if (kfunc->btf_id < k->btf_id) {
 			p = &(*p)->rb_left;
-		else if (kfunc->btf_id > k->btf_id)
+		} else if (kfunc->btf_id > k->btf_id) {
 			p = &(*p)->rb_right;
-		else
+		} else if (k->flags == kfunc->flags) {
 			return 0;
+		} else {
+			pr_err("ERROR: resolve_btfids: kfunc %s has inconsistent flags across BTF ID sets: 0x%x != 0x%x\n",
+			       kfunc->name, k->flags, kfunc->flags);
+			return -EINVAL;
+		}
 	}
 
 	k = zalloc(sizeof(*k));
Signature · 1 line
2.55.0
#12 lore raw

Re: [PATCH bpf-next v1 4/8] libbpf: Export btf__find_by_name_kind_own()

In reply to Ihor Solodrai
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The newly exposed public libbpf API `btf__find_by_name_kind_own()` lacks the `libbpf_err()`…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The newly exposed public libbpf API btf__find_by_name_kind_own() lacks the libbpf_err() wrapper on its error return path. --

--- Patch [4]: [PATCH bpf-next v1 4/8] libbpf: Export btf__find_by_name_kind_own() --- commit 60b04eac1753190ac945126aaca0759082942bc0
Author: Ihor Solodrai <[email protected]>

libbpf: Export btf__find_by_name_kind_own()

btf__find_by_name_kind() searches the base BTF before the split BTF, so in case of a name collision between base and split it always returns a base type. Tools that process split BTF may need to restrict a lookup to the split's own types.

The internal helper btf__find_by_name_kind_own() already does exactly that. Make it a public API.

tools/lib/bpf/btf.h LIBBPF_API __s32 btf__find_by_name(const struct btf *btf, · line 176

Quoted 10 lines
tools/lib/bpf/btf.h +2 -0
index 1a31f2da947f8..587172c0de089 100644
@@ -172,6 +172,8 @@ LIBBPF_API __s32 btf__find_by_name(const struct btf *btf,
 				   const char *type_name);
 LIBBPF_API __s32 btf__find_by_name_kind(const struct btf *btf,
 					const char *type_name, __u32 kind);
+LIBBPF_API __s32 btf__find_by_name_kind_own(const struct btf *btf,
+					    const char *type_name, __u32 kind);

[Severity: Medium]
Since btf__find_by_name_kind_own() is now a public API, shouldn't its return path in tools/lib/bpf/btf.c be updated to use libbpf_err()?

Currently, it returns the value from the internal helper directly:

tools/lib/bpf/btf.c:btf__find_by_name_kind_own() {
	return btf_find_by_name_kind(btf, btf->start_id, type_name, kind);
}

The libbpf public API error handling contract requires all public API functions to set errno using libbpf_err() directly on their return statements. While the internal helper btf_find_by_name_kind() currently sets errno indirectly, relying on it could cause issues if the internal helper is later fixed to return raw error codes.

Should this be updated to return libbpf_err(btf_find_by_name_kind(...))?

Quoted 2 lines
tools/lib/bpf/btf.h +0 -0
 LIBBPF_API __u32 btf__type_cnt(const struct btf *btf);
 LIBBPF_API const struct btf *btf__base_btf(const struct btf *btf);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#2 lore raw

Re: [PATCH bpf-next v1 1/8] resolve_btfids: Implement generic ensure_mem() to grow arrays

In reply to Ihor Solodrai
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Strict aliasing violation via `void **` casting leading to potential Use-After-Free. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Strict aliasing violation via void ** casting leading to potential Use-After-Free. --

--- Patch [1]: [PATCH bpf-next v1 1/8] resolve_btfids: Implement generic ensure_mem() to grow arrays --- commit b5970d9bf6b1262c4ad812706df67f4a14ee5411
Author: Ihor Solodrai <[email protected]>

resolve_btfids: Implement generic ensure_mem() to grow arrays

This commit factors out array growth logic from push_*() helpers into a generic ensure_mem() macro and function. It uses a void ** cast to update the array pointer upon reallocation.

Quoted 19 lines
tools/bpf/resolve_btfids/main.c +11 -0
index f8a91fa7584f4..183466ddc5f97 100644
@@ -201,6 +201,35 @@ static int eprintf(int level, int var, const char *fmt, ...)
 #define pr_info(fmt, ...) \
 	eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
 
+/*
+ * Grow *data so it can hold at least cnt elements of elem_sz bytes each.
+ * *cap is the capacity in elements and is updated on growth.
+ */
+static int __ensure_mem(void **data, u32 *cap, u32 cnt, size_t elem_sz)
+{
+	u32 new_cap, old_cap = *cap;
+	void *arr;
+
+	if (cnt <= old_cap)
+		return 0;

tools/bpf/resolve_btfids/main.c static int eprintf(int level, int var, const char *fmt, ...) · line 224

Quoted 10 lines
tools/bpf/resolve_btfids/main.c +10 -0
+
+	new_cap = max(old_cap + 256, old_cap * 2);
+	if (new_cap < cnt)
+		new_cap = cnt;
+
+	arr = realloc(*data, elem_sz * new_cap);
+	if (!arr)
+		return -ENOMEM;
+
+	*data = arr;

[Severity: Medium]
Will this assignment violate strict aliasing rules? Because void * and u32 * are incompatible types, modifying the pointer through a void ** pointer violates C strict aliasing.

While core kernel code is compiled with -fno-strict-aliasing, programs under tools/ are compiled with standard optimizations including -fstrict-aliasing. If __ensure_mem() is inlined, could the compiler assume that this assignment does not modify the original typed pointer?

tools/bpf/resolve_btfids/main.c static int eprintf(int level, int var, const char *fmt, ...) · line 231

Quoted 7 lines
tools/bpf/resolve_btfids/main.c +7 -0
+	*cap = new_cap;
+
+	return 0;
+}
+
+#define ensure_mem(arr_ptr, cap_ptr, cnt) \
+	__ensure_mem((void **)(arr_ptr), (cap_ptr), (cnt), sizeof(**(arr_ptr)))

[Severity: Medium]
Does casting a typed double pointer (like &ctx->decl_tags which is u32 **) to void ** here set up the strict aliasing violation mentioned above?

[ ... ]

Quoted 9 lines
tools/bpf/resolve_btfids/main.c +0 -5
@@ -890,17 +919,8 @@ static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf, s3
 
 static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
 {
-	u32 *arr = ctx->decl_tags;
-	u32 cap = ctx->max_decl_tags;
-
-	if (ctx->nr_decl_tags + 1 > cap) {
-		cap = max(cap + 256, cap * 2);

tools/bpf/resolve_btfids/main.c static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf, s3 · line 925

Quoted 10 lines
tools/bpf/resolve_btfids/main.c +2 -6
-		arr = realloc(arr, sizeof(u32) * cap);
-		if (!arr)
-			return -ENOMEM;
-		ctx->max_decl_tags = cap;
-		ctx->decl_tags = arr;
-	}
+	if (ensure_mem(&ctx->decl_tags, &ctx->max_decl_tags, ctx->nr_decl_tags + 1))
+		return -ENOMEM;
 
 	ctx->decl_tags[ctx->nr_decl_tags++] = decl_tag_id;

[Severity: Medium]
Could this assignment result in a use-after-free? If the compiler's strict aliasing optimization assumes ctx->decl_tags was not modified by ensure_mem(), it might use a cached pointer that was freed by realloc() during the array assignment.

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

Re: [PATCH bpf-next v1 6/8] HID: bpf: Make syscall kfunc flags match the struct_ops set

In reply to Ihor Solodrai
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] TOCTOU NULL pointer dereference in dispatch_hid_bpf_device_event during dynamic HID-BPF attachment. --

--- Patch [6]: [PATCH bpf-next v1 6/8] HID: bpf: Make syscall kfunc flags match the struct_ops set ---
Note: The format of this review is altered to provide a free-form summary
due to text recitation restrictions. No direct patch diff quoting is used.

commit 460380780bad5817b193c7927dc05e04ce9f5480
Author: Ihor Solodrai <[email protected]>
Subject: HID: bpf: Make syscall kfunc flags match the struct_ops set

This commit updates the kfunc flags for hid_bpf_syscall_kfunc_ids to match the hid_bpf_kfunc_ids set by adding the KF_SLEEPABLE flag. This ensures per-kfunc flag consistency across BTF ID sets at build time.

[Severity: High]
This isn't a regression introduced by this patch, but while reviewing the HID-BPF event dispatching code, a potential time-of-check to time-of-use issue was noticed in drivers/hid/bpf/hid_bpf_dispatch.c.

Could this sequence lead to a null pointer dereference when a HID-BPF program is concurrently attached while a device is flooded with input reports?

In dispatch_hid_bpf_device_event(), the first lockless read of the device data happens during context initialization:

    .data = hdev->bpf.device_data,

Shortly after, a second lockless read is used as a guard:

    if (!hdev->bpf.device_data)
        return data;

If __hid_bpf_allocate_data() is concurrently executed during a program attachment, it updates these pointers without memory barriers or taking the driver_input_lock:

    *data = alloc_data;
    *size = alloc_size;

If the allocation completes exactly between the two reads in dispatch_hid_bpf_device_event(), the first read could evaluate to null while the second read sees the newly allocated pointer and evaluates to true. This would allow the code to bypass the guard and execute memset(ctx_kern.data, 0, hdev->bpf.allocated_data) with a null pointer.

Would it be beneficial to use READ_ONCE() or proper synchronization here to ensure consistent evaluation of the device data pointer?

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

Re: [PATCH bpf-next v1 3/8] resolve_btfids: Keep collected kfuncs in a rbtree

In reply to Ihor Solodrai
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Silent dismissal of inconsistent kfunc flags during deduplication. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Silent dismissal of inconsistent kfunc flags during deduplication. --

--- Patch [3]: [PATCH bpf-next v1 3/8] resolve_btfids: Keep collected kfuncs in a rbtree --- commit d91e5d0dd32a660902e686ef89cb30a196dda160
Author: Ihor Solodrai <[email protected]>

resolve_btfids: Keep collected kfuncs in a rbtree

This commit changes the storage of collected kfuncs from a dynamically grown array to an rbtree keyed by BTF ID. This allows for efficient deduplication when kfuncs are declared in multiple sets.

Quoted 4 lines
tools/bpf/resolve_btfids/main.c +0 -0
index 3198198b03a78..de4986e1bc3d1 100644

[ ... ]

Quoted 10 lines
tools/bpf/resolve_btfids/main.c +5 -1
@@ -979,14 +978,48 @@ static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
 
 static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
 {
-	if (ensure_mem(&ctx->kfuncs, &ctx->max_kfuncs, ctx->nr_kfuncs + 1))
+	struct rb_node **p = &ctx->kfuncs.rb_node;
+	struct rb_node *parent = NULL;
+	struct kfunc *k;
+
+	/* Dedup by BTF ID: collecting the same kfunc twice is a no-op. */

tools/bpf/resolve_btfids/main.c static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id) · line 995

Quoted 10 lines
tools/bpf/resolve_btfids/main.c +10 -0
+	while (*p) {
+		parent = *p;
+		k = rb_entry(parent, struct kfunc, rb_node);
+
+		if (kfunc->btf_id < k->btf_id)
+			p = &(*p)->rb_left;
+		else if (kfunc->btf_id > k->btf_id)
+			p = &(*p)->rb_right;
+		else
+			return 0;

[Severity: Medium]
Does this silent return effectively ignore conflicting flags from subsequent declarations?

If the same kfunc is mistakenly declared in multiple BTF sets with different flags (such as KF_ACQUIRE vs none), returning 0 here without checking if k->flags == kfunc->flags will silently discard the incoming flags.

Could this cause critical security flags like KF_ACQUIRE or KF_TRUSTED_ARGS to be unexpectedly dropped depending on the processing order?

Quoted 5 lines
tools/bpf/resolve_btfids/main.c +4 -0
+	}
+
+	k = zalloc(sizeof(*k));
+	if (!k)
 		return -ENOMEM;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#27 lore raw

Re: [PATCH bpf-next v1 8/8] resolve_btfids: Enforce consistent kfunc flags across BTF ID sets

In reply to Ihor Solodrai
This isn't a bug, but should 'resolve_btifds' here be 'resolve_btfids' to match the tool name?
Quoted 2 lines

Enforce the kfunc flag consistency in resolve_btifds by hard failing on error and blocking kernel (or module) build.

This isn't a bug, but should 'resolve_btifds' here be 'resolve_btfids' to match the tool name?

Quoted 3 lines

[1] https://lore.kernel.org/bpf/[email protected]/

---
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/29967476366

#23 lore raw
In reply to Ihor Solodrai
This isn't a bug, but there are a couple of small typos in the changelog: "used by the the BPF verifier" has a duplicated "the", and "pahole's emmission of decl tags" should be "emission".
Quoted 13 lines

collect_kfuncs() currently uses bpf_kfunc decl tags to identify the list of kfuncs. The decl tags are generated by pahole, which makes current implementation implicitly rely on those tags being generated.

The authoritative source, used by the the BPF verifier for kfunc registration, of functions being BPF kfuncs are BTF_KFUNCS_START()/END() declarations. These are BTF_ID_SET8 under the hood. Currently resolve_btfids reads kfunc flags from these sets, and populates them with BTF IDs.

Implement kfunc discovery from BTF_ID_SET8 symbols in resolve_btfids, removing the dependency on pahole's emmission of decl tags.

Quoted 6 lines

Walk BTF_ID_KIND_SET8 sets, and use the address-to-symbol index to look up set entry's BTF_ID symbol name (before .BTF_ids is patched), recording the paired flags directly. This makes find_kfunc_flags() helper unnecessary, so it's removed.

This isn't a bug, but there are a couple of small typos in the
changelog: "used by the the BPF verifier" has a duplicated "the", and "pahole's emmission of decl tags" should be "emission".

---
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/29967476366

author reviewer
#13 lore raw

Re: [PATCH bpf-next v1 4/8] libbpf: Export btf__find_by_name_kind_own()

In reply to [email protected]
Quoted 39 lines · On 7/22/26 4:43 PM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The newly exposed public libbpf API btf__find_by_name_kind_own() lacks the libbpf_err() wrapper on its error return path. --

--- Patch [4]: [PATCH bpf-next v1 4/8] libbpf: Export btf__find_by_name_kind_own() --- commit 60b04eac1753190ac945126aaca0759082942bc0
Author: Ihor Solodrai <[email protected]>

libbpf: Export btf__find_by_name_kind_own()

btf__find_by_name_kind() searches the base BTF before the split BTF, so in case of a name collision between base and split it always returns a base type. Tools that process split BTF may need to restrict a lookup to the split's own types.

The internal helper btf__find_by_name_kind_own() already does exactly that. Make it a public API.

tools/lib/bpf/btf.h LIBBPF_API __s32 btf__find_by_name(const struct btf *btf, · line 176

Quoted 10 lines
tools/lib/bpf/btf.h +2 -0
index 1a31f2da947f8..587172c0de089 100644
@@ -172,6 +172,8 @@ LIBBPF_API __s32 btf__find_by_name(const struct btf *btf,
 				   const char *type_name);
 LIBBPF_API __s32 btf__find_by_name_kind(const struct btf *btf,
 					const char *type_name, __u32 kind);
+LIBBPF_API __s32 btf__find_by_name_kind_own(const struct btf *btf,
+					    const char *type_name, __u32 kind);

[Severity: Medium]
Since btf__find_by_name_kind_own() is now a public API, shouldn't its return path in tools/lib/bpf/btf.c be updated to use libbpf_err()?

Currently, it returns the value from the internal helper directly:

tools/lib/bpf/btf.c:btf__find_by_name_kind_own() {
	return btf_find_by_name_kind(btf, btf->start_id, type_name, kind);
}
Quoted 7 lines

The libbpf public API error handling contract requires all public API functions to set errno using libbpf_err() directly on their return statements. While the internal helper btf_find_by_name_kind() currently sets errno indirectly, relying on it could cause issues if the internal helper is later fixed to return raw error codes.

Should this be updated to return libbpf_err(btf_find_by_name_kind(...))?

Ok clanker, this is embarrassing. Read the code around the diff before posting.

btf__find_by_name_kind_own() mirrors btf__find_by_name_kind(), and both return btf_find_by_name_kind() directly.

And btf_find_by_name_kind() helper already sets errno via libbpf_err() on its error paths.

Quoted 4 lines
Quoted 3 lines
tools/lib/bpf/btf.h +0 -0
 LIBBPF_API __u32 btf__type_cnt(const struct btf *btf);
 LIBBPF_API const struct btf *btf__base_btf(const struct btf *btf);
#16 lore raw

Re: [PATCH bpf-next v1 5/8] resolve_btfids: Fix the _impl lookup for module BTF

In reply to Ihor Solodrai
The btf__find_by_name_kind() call being changed here was introduced along with process_kfunc_with_implicit_args() itself. Should this carry a Fixes: tag?
Quoted 5 lines

resolve_btfids: Fix the _impl lookup for module BTF

process_kfunc_with_implicit_args() skips generating <name>_impl function when one already exists for backwards compatibility.

Quoted 8 lines

It uses btf__find_by_name_kind(), which searches the base BTF before the split BTF. When resolve_btfids processes a module, a same-named _impl in vmlinux would be found and the module's own counterpart would not be created.

Fix by using btf__find_by_name_kind_own() for the lookup.

The btf__find_by_name_kind() call being changed here was introduced along with process_kfunc_with_implicit_args() itself. Should this carry a Fixes: tag?

Fixes 9d199965990c ("resolve_btfids: Support for KF_IMPLICIT_ARGS")

---
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/29967476366

author reviewer
#3 lore raw

Re: [PATCH bpf-next v1 1/8] resolve_btfids: Implement generic ensure_mem() to grow arrays

In reply to [email protected]
Quoted 49 lines · On 7/22/26 4:48 PM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Strict aliasing violation via void ** casting leading to potential Use-After-Free. --

--- Patch [1]: [PATCH bpf-next v1 1/8] resolve_btfids: Implement generic ensure_mem() to grow arrays --- commit b5970d9bf6b1262c4ad812706df67f4a14ee5411
Author: Ihor Solodrai <[email protected]>

resolve_btfids: Implement generic ensure_mem() to grow arrays

This commit factors out array growth logic from push_*() helpers into a generic ensure_mem() macro and function. It uses a void ** cast to update the array pointer upon reallocation.

Quoted 19 lines
tools/bpf/resolve_btfids/main.c +11 -0
index f8a91fa7584f4..183466ddc5f97 100644
@@ -201,6 +201,35 @@ static int eprintf(int level, int var, const char *fmt, ...)
 #define pr_info(fmt, ...) \
 	eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
 
+/*
+ * Grow *data so it can hold at least cnt elements of elem_sz bytes each.
+ * *cap is the capacity in elements and is updated on growth.
+ */
+static int __ensure_mem(void **data, u32 *cap, u32 cnt, size_t elem_sz)
+{
+	u32 new_cap, old_cap = *cap;
+	void *arr;
+
+	if (cnt <= old_cap)
+		return 0;

tools/bpf/resolve_btfids/main.c static int eprintf(int level, int var, const char *fmt, ...) · line 224

Quoted 10 lines
tools/bpf/resolve_btfids/main.c +10 -0
+
+	new_cap = max(old_cap + 256, old_cap * 2);
+	if (new_cap < cnt)
+		new_cap = cnt;
+
+	arr = realloc(*data, elem_sz * new_cap);
+	if (!arr)
+		return -ENOMEM;
+
+	*data = arr;

[Severity: Medium]
Will this assignment violate strict aliasing rules? Because void * and u32 * are incompatible types, modifying the pointer through a void ** pointer violates C strict aliasing.

Quoted 4 lines

While core kernel code is compiled with -fno-strict-aliasing, programs under tools/ are compiled with standard optimizations including -fstrict-aliasing. If __ensure_mem() is inlined, could the compiler assume that this assignment does not modify the original typed pointer?

ensure_mem() is modeled on libbpf's own libbpf_ensure_mem(), which is called exactly this way throughout libbpf with typed pointers cast to (void **), built under the same tools/ flags.

The pattern is long-established and hasn't caused issues in practice. Callers re-read the struct member after the call. Wontfix.

Quoted 11 lines
Quoted 8 lines
tools/bpf/resolve_btfids/main.c +7 -0
+	*cap = new_cap;
+
+	return 0;
+}
+
+#define ensure_mem(arr_ptr, cap_ptr, cnt) \
+	__ensure_mem((void **)(arr_ptr), (cap_ptr), (cnt), sizeof(**(arr_ptr)))

[...]

author reviewer
#9 lore raw

Re: [PATCH bpf-next v1 3/8] resolve_btfids: Keep collected kfuncs in a rbtree

In reply to [email protected]
Quoted 35 lines · On 7/22/26 4:50 PM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Silent dismissal of inconsistent kfunc flags during deduplication. --

--- Patch [3]: [PATCH bpf-next v1 3/8] resolve_btfids: Keep collected kfuncs in a rbtree --- commit d91e5d0dd32a660902e686ef89cb30a196dda160
Author: Ihor Solodrai <[email protected]>

resolve_btfids: Keep collected kfuncs in a rbtree

This commit changes the storage of collected kfuncs from a dynamically grown array to an rbtree keyed by BTF ID. This allows for efficient deduplication when kfuncs are declared in multiple sets.

Quoted 4 lines
tools/bpf/resolve_btfids/main.c +0 -0
index 3198198b03a78..de4986e1bc3d1 100644

[ ... ]

Quoted 16 lines
tools/bpf/resolve_btfids/main.c +11 -1
@@ -979,14 +978,48 @@ static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
 
 static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
 {
-	if (ensure_mem(&ctx->kfuncs, &ctx->max_kfuncs, ctx->nr_kfuncs + 1))
+	struct rb_node **p = &ctx->kfuncs.rb_node;
+	struct rb_node *parent = NULL;
+	struct kfunc *k;
+
+	/* Dedup by BTF ID: collecting the same kfunc twice is a no-op. */
+	while (*p) {
+		parent = *p;
+		k = rb_entry(parent, struct kfunc, rb_node);
+
+		if (kfunc->btf_id < k->btf_id)
+			p = &(*p)->rb_left;
Quoted 8 lines

tools/bpf/resolve_btfids/main.c static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id) · line 995

Quoted 4 lines
tools/bpf/resolve_btfids/main.c +4 -0
+		else if (kfunc->btf_id > k->btf_id)
+			p = &(*p)->rb_right;
+		else
+			return 0;

[Severity: Medium]
Does this silent return effectively ignore conflicting flags from subsequent declarations?

This is deliberate here. Flags are checked for in the patch #8

Quoted 14 lines

If the same kfunc is mistakenly declared in multiple BTF sets with different flags (such as KF_ACQUIRE vs none), returning 0 here without checking if k->flags == kfunc->flags will silently discard the incoming flags.

Could this cause critical security flags like KF_ACQUIRE or KF_TRUSTED_ARGS to be unexpectedly dropped depending on the processing order?

Quoted 5 lines
tools/bpf/resolve_btfids/main.c +4 -0
+	}
+
+	k = zalloc(sizeof(*k));
+	if (!k)
 		return -ENOMEM;
author reviewer
#20 lore raw

Re: [PATCH bpf-next v1 6/8] HID: bpf: Make syscall kfunc flags match the struct_ops set

In reply to [email protected]
Quoted 14 lines · On 7/22/26 4:49 PM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] TOCTOU NULL pointer dereference in dispatch_hid_bpf_device_event during dynamic HID-BPF attachment. --

--- Patch [6]: [PATCH bpf-next v1 6/8] HID: bpf: Make syscall kfunc flags match the struct_ops set ---
Note: The format of this review is altered to provide a free-form summary
due to text recitation restrictions. No direct patch diff quoting is used.

commit 460380780bad5817b193c7927dc05e04ce9f5480
Author: Ihor Solodrai <[email protected]>
Subject: HID: bpf: Make syscall kfunc flags match the struct_ops set

Quoted 6 lines

This commit updates the kfunc flags for hid_bpf_syscall_kfunc_ids to match the hid_bpf_kfunc_ids set by adding the KF_SLEEPABLE flag. This ensures per-kfunc flag consistency across BTF ID sets at build time.

[Severity: High]
This isn't a regression introduced by this patch, but while reviewing the

Not relevant to the change.

However HID maintainers may be interested, adding them to cc.

Quoted 33 lines

HID-BPF event dispatching code, a potential time-of-check to time-of-use issue was noticed in drivers/hid/bpf/hid_bpf_dispatch.c.

Could this sequence lead to a null pointer dereference when a HID-BPF program is concurrently attached while a device is flooded with input reports?

In dispatch_hid_bpf_device_event(), the first lockless read of the device data happens during context initialization:

    .data = hdev->bpf.device_data,

Shortly after, a second lockless read is used as a guard:

    if (!hdev->bpf.device_data)
        return data;

If __hid_bpf_allocate_data() is concurrently executed during a program attachment, it updates these pointers without memory barriers or taking the driver_input_lock:

    *data = alloc_data;
    *size = alloc_size;

If the allocation completes exactly between the two reads in dispatch_hid_bpf_device_event(), the first read could evaluate to null while the second read sees the newly allocated pointer and evaluates to true. This would allow the code to bypass the guard and execute memset(ctx_kern.data, 0, hdev->bpf.allocated_data) with a null pointer.

Would it be beneficial to use READ_ONCE() or proper synchronization here to ensure consistent evaluation of the device data pointer?

author reviewer
#24 lore raw
In reply to [email protected]
Quoted 18 lines · On 7/22/26 5:32 PM, [email protected] wrote:
Quoted 18 lines

collect_kfuncs() currently uses bpf_kfunc decl tags to identify the list of kfuncs. The decl tags are generated by pahole, which makes current implementation implicitly rely on those tags being generated.

The authoritative source, used by the the BPF verifier for kfunc registration, of functions being BPF kfuncs are BTF_KFUNCS_START()/END() declarations. These are BTF_ID_SET8 under the hood. Currently resolve_btfids reads kfunc flags from these sets, and populates them with BTF IDs.

Implement kfunc discovery from BTF_ID_SET8 symbols in resolve_btfids, removing the dependency on pahole's emmission of decl tags.

Walk BTF_ID_KIND_SET8 sets, and use the address-to-symbol index to look up set entry's BTF_ID symbol name (before .BTF_ids is patched), recording the paired flags directly. This makes find_kfunc_flags() helper unnecessary, so it's removed.

Quoted 5 lines
Quoted 1 line

This isn't a bug, but there are a couple of small typos in the
changelog: "used by the the BPF verifier" has a duplicated "the", and "pahole's emmission of decl tags" should be "emission".

I guess typos don't count as proof-of-human-typing, because AI can be instructed to make typos :) Will fix.

Quoted 7 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.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/29967476366

maintainer Reviewed-by on v1 1/8
#4 lore raw

Re: [PATCH bpf-next v1 1/8] resolve_btfids: Implement generic ensure_mem() to grow arrays

In reply to Ihor Solodrai
Quoted 6 lines · Ihor Solodrai

push_*() helpers in resolve_btfids contain copy-pasted array growth logic. Factor it out into ensure_mem() - a simplified variant of libbpf_ensure_mem(), and use it in the helpers.

---

...

maintainer Reviewed-by on v1 2/8
#6 lore raw

Re: [PATCH bpf-next v1 2/8] resolve_btfids: Index BTF ID symbols by address

In reply to Ihor Solodrai
Quoted 9 lines · Ihor Solodrai

Keep an address-sorted index of parsed .BTF_ids symbols so that the original BTF_ID symbol name can be recovered from an entry address.

Use the index in find_kfunc_flags() to scan BTF_SET8_KFUNCS entries directly and match each entry back to the requested kfunc.

---

...

maintainer Reviewed-by on v1 3/8
#10 lore raw

Re: [PATCH bpf-next v1 3/8] resolve_btfids: Keep collected kfuncs in a rbtree

In reply to Ihor Solodrai
Quoted 9 lines · Ihor Solodrai

Store collected kfuncs in a rbtree keyed by BTF ID instead of a dynamically grown array. This allows for efficient deduplication for kfuncs declared in multiple sets, which is needed for subsequent patches [1].

[1] https://lore.kernel.org/bpf/CAEf4BzaLzX3mXvQzxv+gbmZOh84XvYofLjMSWFYghNjS-ohEZg@mail.gmail.com/

---

...

maintainer Reviewed-by on v1 4/8
#14 lore raw

Re: [PATCH bpf-next v1 4/8] libbpf: Export btf__find_by_name_kind_own()

In reply to Ihor Solodrai
Quoted 10 lines · Ihor Solodrai

btf__find_by_name_kind() searches the base BTF before the split BTF, so in case of a name collision between base and split it always returns a base type. Tools that process split BTF may need to restrict a lookup to the split's own types.

The internal helper btf__find_by_name_kind_own() already does exactly that. Make it a public API.

---

...

tools/lib/bpf/btf.h LIBBPF_API __s32 btf__find_by_name(const struct btf *btf, · line 176

Quoted 7 lines

+++ b/tools/lib/bpf/btf.h

tools/lib/bpf/btf.h +2 -0
@@ -172,6 +172,8 @@ LIBBPF_API __s32 btf__find_by_name(const struct btf *btf,
 				   const char *type_name);
 LIBBPF_API __s32 btf__find_by_name_kind(const struct btf *btf,
 					const char *type_name, __u32 kind);
+LIBBPF_API __s32 btf__find_by_name_kind_own(const struct btf *btf,
+					    const char *type_name, __u32 kind);

Nit: please add a docstring.

...

maintainer Reviewed-by on v1 5/8
#17 lore raw

Re: [PATCH bpf-next v1 5/8] resolve_btfids: Fix the _impl lookup for module BTF

In reply to Ihor Solodrai
Quoted 8 lines · Ihor Solodrai

process_kfunc_with_implicit_args() skips generating <name>_impl function when one already exists for backwards compatibility.

It uses btf__find_by_name_kind(), which searches the base BTF before the split BTF. When resolve_btfids processes a module, a same-named _impl in vmlinux would be found and the module's own counterpart would not be created.

Quoted 4 lines

Fix by using btf__find_by_name_kind_own() for the lookup.

---

...

maintainer Reviewed-by on v1 6/8
#21 lore raw

Re: [PATCH bpf-next v1 6/8] HID: bpf: Make syscall kfunc flags match the struct_ops set

In reply to Ihor Solodrai
Quoted 6 lines · Ihor Solodrai

Update kfunc flags for hid_bpf_syscall_kfunc_ids set to exactly match hid_bpf_kfunc_ids set by adding KF_SLEEPABLE flag.

The syscall set omitted the flag because syscall programs are always sleepable (the verifier rejects a non-sleepable syscall program).

Quoted 6 lines

However the upcoming resolve_btfids change enforces per-kfunc flag consistency across BTF ID sets at build time, which is why this change is necessary.

---

Benjamin, Jiri, could you please take a look?

Quoted 24 lines
 drivers/hid/bpf/hid_bpf_dispatch.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/hid/bpf/hid_bpf_dispatch.c +5 -5
index 536f6d01fd14..44671dbdeca8 100644
@@ -590,11 +590,11 @@ static const struct btf_kfunc_id_set hid_bpf_kfunc_set = {
 
 /* for syscall HID-BPF */
 BTF_KFUNCS_START(hid_bpf_syscall_kfunc_ids)
-BTF_ID_FLAGS(func, hid_bpf_allocate_context, KF_ACQUIRE | KF_RET_NULL)
-BTF_ID_FLAGS(func, hid_bpf_release_context, KF_RELEASE)
-BTF_ID_FLAGS(func, hid_bpf_hw_request)
-BTF_ID_FLAGS(func, hid_bpf_hw_output_report)
-BTF_ID_FLAGS(func, hid_bpf_input_report)
+BTF_ID_FLAGS(func, hid_bpf_allocate_context, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_release_context, KF_RELEASE | KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_hw_request, KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_hw_output_report, KF_SLEEPABLE)
+BTF_ID_FLAGS(func, hid_bpf_input_report, KF_SLEEPABLE)
 BTF_KFUNCS_END(hid_bpf_syscall_kfunc_ids)
 
 static const struct btf_kfunc_id_set hid_bpf_syscall_kfunc_set = {
maintainer Reviewed-by on v1 7/8
#25 lore raw
In reply to Ihor Solodrai
Quoted 13 lines · Ihor Solodrai

collect_kfuncs() currently uses bpf_kfunc decl tags to identify the list of kfuncs. The decl tags are generated by pahole, which makes current implementation implicitly rely on those tags being generated.

The authoritative source, used by the the BPF verifier for kfunc registration, of functions being BPF kfuncs are BTF_KFUNCS_START()/END() declarations. These are BTF_ID_SET8 under the hood. Currently resolve_btfids reads kfunc flags from these sets, and populates them with BTF IDs.

Implement kfunc discovery from BTF_ID_SET8 symbols in resolve_btfids, removing the dependency on pahole's emmission of decl tags.

Quoted 7 lines

Walk BTF_ID_KIND_SET8 sets, and use the address-to-symbol index to look up set entry's BTF_ID symbol name (before .BTF_ids is patched), recording the paired flags directly. This makes find_kfunc_flags() helper unnecessary, so it's removed.

---

...

maintainer Reviewed-by on v1 8/8
#28 lore raw

Re: [PATCH bpf-next v1 8/8] resolve_btfids: Enforce consistent kfunc flags across BTF ID sets

In reply to Ihor Solodrai
Quoted 8 lines · Ihor Solodrai

A kfunc may be listed in several BTF ID sets, which is expected because different kfuncs are available to BPF programs depending on their type.

However kfunc flags across different BTF ID sets must be consistent [1]. The flags should be considered a part of the kfunc declaration, because they influence its BTF representation and verifier handling.

Quoted 7 lines

Enforce the kfunc flag consistency in resolve_btifds by hard failing on error and blocking kernel (or module) build.

[1] https://lore.kernel.org/bpf/[email protected]/

---

...

Tested-by on the v1 series
#29 lore raw
In reply to Ihor Solodrai
Quoted 24 lines · Ihor Solodrai

This series develops resolve_btfids in preparation for bringing kernel-specific BTF transformations in tree, which will reduce kbuild dependency on pahole's features.

resolve_btfids currently identifies kfuncs by reading the "bpf_kfunc" decl tags pahole emits into vmlinux BTF. The series switches the source of truth to the BTF ID sets registered with BTF_KFUNCS_START()/END() in the kernel, which is the mechanism BPF verifier uses.

The series is based on patches #5 and #6 from the original "resolve_btfids: Implement BTF tags emission for kfuncs" series [1], and includes a few significant additions. Particularly the build time enforcement of kfunc flags consistency [2].

The series consists of:
- patches #1-#3 implement supporting infrastructure for the proper kfunc discovery and deduplication
- patches #4-#5 expose btf__find_by_name_kind_own() and use it to fix a latent bug in _impl func lookup
- patch #6 fixes inconsistent kfunc flags for HID kfuncs
- patch #7 implements kfunc discovery from BTF ID sets
- patch #8 adds enforcement of kfunc flags consistency

Quoted 1 line

The resolve_btfids selftests patches have landed earlier [3].

I tested these changes and all looks good, so feel free to add

to the series.

Quoted 32 lines

[1] https://lore.kernel.org/bpf/[email protected]/
[2] https://lore.kernel.org/bpf/[email protected]/
[3] https://lore.kernel.org/bpf/[email protected]/

---

Changes compared to [1]:
- Drop the idempotency (ensure_*) machinery: assume valid input BTF (Andrii)
- Use rbtree to store the kfuncs (Andrii)
- Enforce full KF_* flag consistency as a build error (Eduard)
- Various cleanups and nits (Andrii, Emil, Jiri)

---

Ihor Solodrai (8):
resolve_btfids: Implement generic ensure_mem() to grow arrays
resolve_btfids: Index BTF ID symbols by address
resolve_btfids: Keep collected kfuncs in a rbtree
libbpf: Export btf__find_by_name_kind_own()
resolve_btfids: Fix the _impl lookup for module BTF
HID: bpf: Make syscall kfunc flags match the struct_ops set
resolve_btfids: Discover kfuncs from BTF ID sets
resolve_btfids: Enforce consistent kfunc flags across BTF ID sets

 drivers/hid/bpf/hid_bpf_dispatch.c |  10 +-
 tools/bpf/resolve_btfids/main.c    | 275 ++++++++++++++++++-----------
 tools/lib/bpf/btf.h                |   2 +
 tools/lib/bpf/libbpf.map           |   1 +
 tools/lib/bpf/libbpf_internal.h    |   2 -
 5 files changed, 181 insertions(+), 109 deletions(-)
#30 lore raw
In reply to Ihor Solodrai
This series was applied to bpf/bpf-next.git (master) by Andrii Nakryiko <[email protected]>:

Hello:

This series was applied to bpf/bpf-next.git (master) by Andrii Nakryiko <[email protected]>:

Quoted 11 lines · On Wed, 22 Jul 2026 16:35:10 -0700 you wrote:

This series develops resolve_btfids in preparation for bringing kernel-specific BTF transformations in tree, which will reduce kbuild dependency on pahole's features.

resolve_btfids currently identifies kfuncs by reading the "bpf_kfunc" decl tags pahole emits into vmlinux BTF. The series switches the source of truth to the BTF ID sets registered with BTF_KFUNCS_START()/END() in the kernel, which is the mechanism BPF verifier uses.

[...]

Here is the summary with links:
- [bpf-next,v1,1/8] resolve_btfids: Implement generic ensure_mem() to grow arrays

    https://git.kernel.org/bpf/bpf-next/c/47d62db55043
  - [bpf-next,v1,2/8] resolve_btfids: Index BTF ID symbols by address
    https://git.kernel.org/bpf/bpf-next/c/c5ab68a5fa92
  - [bpf-next,v1,3/8] resolve_btfids: Keep collected kfuncs in a rbtree
    https://git.kernel.org/bpf/bpf-next/c/e4293c31a320
  - [bpf-next,v1,4/8] libbpf: Export btf__find_by_name_kind_own()
    https://git.kernel.org/bpf/bpf-next/c/ef242559eb48
  - [bpf-next,v1,5/8] resolve_btfids: Fix the _impl lookup for module BTF
    https://git.kernel.org/bpf/bpf-next/c/91efe50e3042
  - [bpf-next,v1,6/8] HID: bpf: Make syscall kfunc flags match the struct_ops set
    https://git.kernel.org/bpf/bpf-next/c/5c4923172dae
  - [bpf-next,v1,7/8] resolve_btfids: Discover kfuncs from BTF ID sets
    https://git.kernel.org/bpf/bpf-next/c/f9f60d41ba2c
  - [bpf-next,v1,8/8] resolve_btfids: Enforce consistent kfunc flags across BTF ID sets
    https://git.kernel.org/bpf/bpf-next/c/140a3479ef66

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html