Skip to contentSkip to conversation

Handle duplicate kprobe symbols

PATCH Superseded Andrey Grodzovsky 4 participants 10 messages Mar 2 – Mar 9

Subsystems (5)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v4 cover Handle duplicate kprobe symbols

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

This series implements a fallback mechanism that, on such failures, resolves the vmlinux address through /proc/kallsyms - filtering out module symbols - and retries probe attachment using the absolute address, bypassing kernel symbol name validation.

Patch 1: Core libbpf changes - kallsyms parser restructuring, duplicate
symbol detection, and address-based retry logic.
Patch 2: Selftests with bpf_testmod_dup_sym.ko test module validating
kprobe attachment across all four attach modes.

Changes since v3 [1]:
- Set err = -ENOENT when kallsyms parse succeeds but the symbol is not found in vmlinux, preventing err == 0 from propagating to the caller via err_out (CI bot review)

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

Andrey Grodzovsky (2):
libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts selftests/bpf: Add tests for duplicate kprobe symbol handling

 tools/lib/bpf/libbpf.c                        | 155 ++++++++++++++++--
 tools/testing/selftests/bpf/Makefile          |   2 +-
 .../selftests/bpf/prog_tests/attach_probe.c   |  63 +++++++
 .../testing/selftests/bpf/test_kmods/Makefile |   2 +-
 .../bpf/test_kmods/bpf_testmod_dup_sym.c      |  48 ++++++
 5 files changed, 250 insertions(+), 20 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_testmod_dup_sym.c
Signature · 1 line
2.34.1
#1 lore raw

PATCH v4 1/2 libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

Implement a fallback mechanism that, on such failures, resolves the vmlinux address through /proc/kallsyms - filtering out module symbols - and retries probe attachment using the absolute address, bypassing kernel symbol name validation.

Changes:
- Restructure libbpf_kallsyms_parse() to accept a bool skip_if_module parameter that filters module symbols before invoking the callback.
- Add find_kaddr_cb() callback and find_kaddr_ctx struct to resolve vmlinux text symbol addresses from /proc/kallsyms.
- Detect duplicate symbol errors (-EADDRNOTAVAIL for perf_event_open, -EINVAL for legacy tracefs) and retry with resolved KADDR.
- Fix NULL pointer in gen_probe_legacy_event_name() when using absolute address by passing func_name instead of optional_func_name.
- Fix NULL pointer in pr_warn() calls within perf_event_kprobe_open_legacy() by using ternary fallback.
- Fix memory leak of legacy_probe buffer on retry path.

---
 tools/lib/bpf/libbpf.c | 155 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 137 insertions(+), 18 deletions(-)
tools/lib/bpf/libbpf.c +137 -18
index 0be7017800fe..e725e3c98ee2 100644
@@ -8460,9 +8460,11 @@ static int bpf_object__sanitize_maps(struct bpf_object *obj)
 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
 			     const char *sym_name, void *ctx);
 
-static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
+static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx,
+				bool skip_if_module)
 {
 	char sym_type, sym_name[500];
+	char module_name[128];
 	unsigned long long sym_addr;
 	int ret, err = 0;
 	FILE *f;
@@ -8475,21 +8477,39 @@ static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
 	}
 
 	while (true) {
-		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
-			     &sym_addr, &sym_type, sym_name);
-		if (ret == EOF && feof(f))
+		int n = 0;
+
+		/*
+		 * Format tries to match both vmlinux and module kallsyms
+		 * entries in one call. Module entries have the form:
+		 *   addr type name [module]
+		 * %n fires only if the closing ']' literal is matched.
+		 */
+		ret = fscanf(f, "%llx %c %499s [%127[^] \t\n\r\v\f]] %n",
+			     &sym_addr, &sym_type, sym_name, module_name, &n);
+
+		/* EOF or malformed line - handle after the loop */
+		if (ret != 3 && ret != 4)
 			break;
-		if (ret != 3) {
-			pr_warn("failed to read kallsyms entry: %d\n", ret);
-			err = -EINVAL;
+
+		/* ret == 4 && n == 0: scanset matched but ']' didn't */
+		if (ret == 4 && n == 0)
 			break;
-		}
+
+		if (ret == 4 && skip_if_module)
+			continue;
 
 		err = cb(sym_addr, sym_type, sym_name, ctx);
 		if (err)
 			break;
 	}
 
+	/* !err: don't overwrite callback errors with -EINVAL */
+	if (!feof(f) && !err) {
+		pr_warn("failed to read kallsyms entry: ret=%d\n", ret);
+		err = -EINVAL;
+	}
+
 	fclose(f);
 	return err;
 }
@@ -8529,7 +8549,7 @@ static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
 
 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
 {
-	return libbpf_kallsyms_parse(kallsyms_cb, obj);
+	return libbpf_kallsyms_parse(kallsyms_cb, obj, false);
 }
 
 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
@@ -11527,10 +11547,20 @@ static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
 				   const char *kfunc_name, size_t offset)
 {
-	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
-			      retprobe ? 'r' : 'p',
-			      retprobe ? "kretprobes" : "kprobes",
-			      probe_name, kfunc_name, offset);
+	/* When kfunc_name is NULL, use absolute address format (0xADDR),
+	 * otherwise use symbol+offset format (SYMBOL+0xOFF)
+	 */
+	if (kfunc_name) {
+		return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
+				      retprobe ? 'r' : 'p',
+				      retprobe ? "kretprobes" : "kprobes",
+				      probe_name, kfunc_name, offset);
+	} else {
+		return append_to_file(tracefs_kprobe_events(), "%c:%s/%s 0x%zx",
+				      retprobe ? 'r' : 'p',
+				      retprobe ? "kretprobes" : "kprobes",
+				      probe_name, offset);
+	}
 }
 
 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
@@ -11559,7 +11589,7 @@ static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
 	if (err < 0) {
 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
-			kfunc_name, offset,
+			kfunc_name ? kfunc_name : "(abs_addr)", offset,
 			errstr(err));
 		return err;
 	}
@@ -11567,7 +11597,7 @@ static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
 	if (type < 0) {
 		err = type;
 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
-			kfunc_name, offset,
+			kfunc_name ? kfunc_name : "(abs_addr)", offset,
 			errstr(err));
 		goto err_clean_legacy;
 	}
@@ -11651,6 +11681,44 @@ int probe_kern_syscall_wrapper(int token_fd)
 	}
 }
 
+/* Context structure for finding vmlinux kernel symbol address */
+struct find_kaddr_ctx {
+	const char *func_name;
+	unsigned long long kaddr;
+};
+
+/* Callback to find vmlinux kernel text symbol address */
+static int find_kaddr_cb(unsigned long long sym_addr, char sym_type,
+			 const char *sym_name, void *ctx)
+{
+	struct find_kaddr_ctx *data = ctx;
+
+	/* Only match text section symbols ('T' or 't') */
+	if (toupper(sym_type) != 'T')
+		return 0;
+
+	/* Check if this is the symbol we're looking for */
+	if (strcmp(sym_name, data->func_name) == 0) {
+
+		/*
+		 * If we already have an address, we've encountered a
+		 * duplicate symbol name. Reject such symbols to avoid
+		 * ambiguous resolution.
+		 */
+		if (data->kaddr && data->kaddr != sym_addr) {
+			pr_warn("kernel symbol '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
+			sym_name, data->kaddr, sym_addr);
+			return -EINVAL;
+		}
+
+		data->kaddr = sym_addr;
+		pr_debug("found kernel symbol %s at address 0x%llx\n",
+			 sym_name, data->kaddr);
+	}
+
+	return 0;
+}
+
 struct bpf_link *
 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
 				const char *func_name,
@@ -11663,6 +11731,8 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
 	size_t offset;
 	bool retprobe, legacy;
 	int pfd, err;
+	const char *optional_func_name = func_name;
+	struct find_kaddr_ctx kaddr_ctx = { .kaddr = 0 };
 
 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
 		return libbpf_err_ptr(-EINVAL);
@@ -11693,9 +11763,10 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
 		return libbpf_err_ptr(-EINVAL);
 	}
 
+retry_create:
 	if (!legacy) {
 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
-					    func_name, offset,
+					    optional_func_name, offset,
 					    -1 /* pid */, 0 /* ref_ctr_off */);
 	} else {
 		char probe_name[MAX_EVENT_NAME_LEN];
@@ -11707,7 +11778,7 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
 		if (!legacy_probe)
 			return libbpf_err_ptr(-ENOMEM);
 
-		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
+		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, optional_func_name,
 						    offset, -1 /* pid */);
 	}
 	if (pfd < 0) {
@@ -11716,6 +11787,54 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
 			prog->name, retprobe ? "kretprobe" : "kprobe",
 			func_name, offset,
 			errstr(err));
+
+		/*
+		 * If attachment fails with EADDRNOTAVAIL (or EINVAL in
+		 * legacy mode) and we used non-NULL func_name, try to
+		 * find function address in /proc/kallsyms and retry
+		 * using KADDR instead of ambiguous symbol. Legacy
+		 * tracefs API converts EADDRNOTAVAIL to EINVAL, so
+		 * we need to check for both.
+		 */
+		if ((err == -EADDRNOTAVAIL || (legacy && err == -EINVAL)) && optional_func_name) {
+			pr_debug("kallsyms lookup for %s\n",
+				 func_name);
+
+			kaddr_ctx.func_name = func_name;
+			kaddr_ctx.kaddr = 0;
+
+			/*
+			 * Drop the function symbol and add the resolved
+			 * KADDR to the offset.
+			 * This avoids kallsyms validation for duplicate
+			 * symbols in the kernel. See attr.config2 in
+			 * perf_event_open_probe and kernel code in
+			 * perf_kprobe_init/create_local_trace_kprobe.
+			 */
+			optional_func_name = NULL;
+
+			err = libbpf_kallsyms_parse(find_kaddr_cb, &kaddr_ctx, true);
+			if (err) {
+				pr_warn("failed to get addr for %s\n",
+					func_name);
+				goto err_out;
+			}
+
+			if (kaddr_ctx.kaddr) {
+				pr_debug("retrying %s using kaddr 0x%llx\n",
+					 func_name, kaddr_ctx.kaddr);
+
+				offset += kaddr_ctx.kaddr;
+				free(legacy_probe);
+				legacy_probe = NULL;
+				goto retry_create;
+			}
+
+			pr_warn("symbol '%s' not found in vmlinux\n",
+				func_name);
+			err = -ENOENT;
+		}
+
 		goto err_out;
 	}
 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
@@ -11931,7 +12050,7 @@ static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
 	data.syms = syms;
 	data.res = res;
 	data.cnt = cnt;
-	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
+	libbpf_kallsyms_parse(avail_kallsyms_cb, &data, false);
 
 	if (res->cnt == 0)
 		err = -ENOENT;
Signature · 1 line
2.34.1
#2 lore raw

Re: [PATCH bpf-next v4 1/2] libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

Should the continuation line be indented one more tab to align closer to the opening parenthesis? The pr_debug() a few lines below in the same function aligns it properly:
Quoted 3 lines
tools/lib/bpf/libbpf.c +0 -0

[ ... ]

Quoted 4 lines
tools/lib/bpf/libbpf.c +4 -0
+static int find_kaddr_cb(unsigned long long sym_addr, char sym_type,
+			 const char *sym_name, void *ctx)
+{
+	struct find_kaddr_ctx *data = ctx;

[ ... ]

tools/lib/bpf/libbpf.c int probe_kern_syscall_wrapper(int token_fd) · line 11710

Quoted 3 lines
tools/lib/bpf/libbpf.c +3 -0
+		if (data->kaddr && data->kaddr != sym_addr) {
+			pr_warn("kernel symbol '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
+			sym_name, data->kaddr, sym_addr);
                ^^^^^^^^

Should the continuation line be indented one more tab to align closer to the opening parenthesis? The pr_debug() a few lines below in the same function aligns it properly:

			pr_debug("found kernel symbol %s at address 0x%llx\n",
				 sym_name, data->kaddr);

tools/lib/bpf/libbpf.c

Quoted 2 lines
tools/lib/bpf/libbpf.c +2 -0
+			return -EINVAL;
+		}

[ ... ]

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

#3 lore raw

Re: [PATCH bpf-next v4 1/2] libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

In reply to Andrey Grodzovsky
Quoted 5 lines · Andrey Grodzovsky

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

If the same symbol name resolves to multiple addresses, that's an ambiguity that libbpf has no business resolving. It should be on user to resolve and use attachment by address, which libbpf supports through bpf_kprobe_opts or multi-kprobe opts.

pw-bot: cr

Quoted 282 lines

Implement a fallback mechanism that, on such failures, resolves the vmlinux address through /proc/kallsyms - filtering out module symbols - and retries probe attachment using the absolute address, bypassing kernel symbol name validation.

Changes:
- Restructure libbpf_kallsyms_parse() to accept a bool skip_if_module parameter that filters module symbols before invoking the callback.
- Add find_kaddr_cb() callback and find_kaddr_ctx struct to resolve vmlinux text symbol addresses from /proc/kallsyms.
- Detect duplicate symbol errors (-EADDRNOTAVAIL for perf_event_open, -EINVAL for legacy tracefs) and retry with resolved KADDR.
- Fix NULL pointer in gen_probe_legacy_event_name() when using absolute address by passing func_name instead of optional_func_name.
- Fix NULL pointer in pr_warn() calls within perf_event_kprobe_open_legacy() by using ternary fallback.
- Fix memory leak of legacy_probe buffer on retry path.

---
 tools/lib/bpf/libbpf.c | 155 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 137 insertions(+), 18 deletions(-)
tools/lib/bpf/libbpf.c +137 -19
index 0be7017800fe..e725e3c98ee2 100644
@@ -8460,9 +8460,11 @@ static int bpf_object__sanitize_maps(struct bpf_object *obj)
 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
                             const char *sym_name, void *ctx);
 
-static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
+static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx,
+                               bool skip_if_module)
 {
        char sym_type, sym_name[500];
+       char module_name[128];
        unsigned long long sym_addr;
        int ret, err = 0;
        FILE *f;
@@ -8475,21 +8477,39 @@ static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
        }
 
        while (true) {
-               ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
-                            &sym_addr, &sym_type, sym_name);
-               if (ret == EOF && feof(f))
+               int n = 0;
+
+               /*
+                * Format tries to match both vmlinux and module kallsyms
+                * entries in one call. Module entries have the form:
+                *   addr type name [module]
+                * %n fires only if the closing ']' literal is matched.
+                */
+               ret = fscanf(f, "%llx %c %499s [%127[^] \t\n\r\v\f]] %n",
+                            &sym_addr, &sym_type, sym_name, module_name, &n);
+
+               /* EOF or malformed line - handle after the loop */
+               if (ret != 3 && ret != 4)
                        break;
-               if (ret != 3) {
-                       pr_warn("failed to read kallsyms entry: %d\n", ret);
-                       err = -EINVAL;
+
+               /* ret == 4 && n == 0: scanset matched but ']' didn't */
+               if (ret == 4 && n == 0)
                        break;
-               }
+
+               if (ret == 4 && skip_if_module)
+                       continue;
 
                err = cb(sym_addr, sym_type, sym_name, ctx);
                if (err)
                        break;
        }
 
+       /* !err: don't overwrite callback errors with -EINVAL */
+       if (!feof(f) && !err) {
+               pr_warn("failed to read kallsyms entry: ret=%d\n", ret);
+               err = -EINVAL;
+       }
+
        fclose(f);
        return err;
 }
@@ -8529,7 +8549,7 @@ static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
 
 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
 {
-       return libbpf_kallsyms_parse(kallsyms_cb, obj);
+       return libbpf_kallsyms_parse(kallsyms_cb, obj, false);
 }
 
 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
@@ -11527,10 +11547,20 @@ static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
                                   const char *kfunc_name, size_t offset)
 {
-       return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
-                             retprobe ? 'r' : 'p',
-                             retprobe ? "kretprobes" : "kprobes",
-                             probe_name, kfunc_name, offset);
+       /* When kfunc_name is NULL, use absolute address format (0xADDR),
+        * otherwise use symbol+offset format (SYMBOL+0xOFF)
+        */
+       if (kfunc_name) {
+               return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
+                                     retprobe ? 'r' : 'p',
+                                     retprobe ? "kretprobes" : "kprobes",
+                                     probe_name, kfunc_name, offset);
+       } else {
+               return append_to_file(tracefs_kprobe_events(), "%c:%s/%s 0x%zx",
+                                     retprobe ? 'r' : 'p',
+                                     retprobe ? "kretprobes" : "kprobes",
+                                     probe_name, offset);
+       }
 }
 
 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
@@ -11559,7 +11589,7 @@ static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
        err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
        if (err < 0) {
                pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
-                       kfunc_name, offset,
+                       kfunc_name ? kfunc_name : "(abs_addr)", offset,
                        errstr(err));
                return err;
        }
@@ -11567,7 +11597,7 @@ static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
        if (type < 0) {
                err = type;
                pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
-                       kfunc_name, offset,
+                       kfunc_name ? kfunc_name : "(abs_addr)", offset,
                        errstr(err));
                goto err_clean_legacy;
        }
@@ -11651,6 +11681,44 @@ int probe_kern_syscall_wrapper(int token_fd)
        }
 }
 
+/* Context structure for finding vmlinux kernel symbol address */
+struct find_kaddr_ctx {
+       const char *func_name;
+       unsigned long long kaddr;
+};
+
+/* Callback to find vmlinux kernel text symbol address */
+static int find_kaddr_cb(unsigned long long sym_addr, char sym_type,
+                        const char *sym_name, void *ctx)
+{
+       struct find_kaddr_ctx *data = ctx;
+
+       /* Only match text section symbols ('T' or 't') */
+       if (toupper(sym_type) != 'T')
+               return 0;
+
+       /* Check if this is the symbol we're looking for */
+       if (strcmp(sym_name, data->func_name) == 0) {
+
+               /*
+                * If we already have an address, we've encountered a
+                * duplicate symbol name. Reject such symbols to avoid
+                * ambiguous resolution.
+                */
+               if (data->kaddr && data->kaddr != sym_addr) {
+                       pr_warn("kernel symbol '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
+                       sym_name, data->kaddr, sym_addr);
+                       return -EINVAL;
+               }
+
+               data->kaddr = sym_addr;
+               pr_debug("found kernel symbol %s at address 0x%llx\n",
+                        sym_name, data->kaddr);
+       }
+
+       return 0;
+}
+
 struct bpf_link *
 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                                const char *func_name,
@@ -11663,6 +11731,8 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
        size_t offset;
        bool retprobe, legacy;
        int pfd, err;
+       const char *optional_func_name = func_name;
+       struct find_kaddr_ctx kaddr_ctx = { .kaddr = 0 };
 
        if (!OPTS_VALID(opts, bpf_kprobe_opts))
                return libbpf_err_ptr(-EINVAL);
@@ -11693,9 +11763,10 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                return libbpf_err_ptr(-EINVAL);
        }
 
+retry_create:
        if (!legacy) {
                pfd = perf_event_open_probe(false /* uprobe */, retprobe,
-                                           func_name, offset,
+                                           optional_func_name, offset,
                                            -1 /* pid */, 0 /* ref_ctr_off */);
        } else {
                char probe_name[MAX_EVENT_NAME_LEN];
@@ -11707,7 +11778,7 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                if (!legacy_probe)
                        return libbpf_err_ptr(-ENOMEM);
 
-               pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
+               pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, optional_func_name,
                                                    offset, -1 /* pid */);
        }
        if (pfd < 0) {
@@ -11716,6 +11787,54 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                        prog->name, retprobe ? "kretprobe" : "kprobe",
                        func_name, offset,
                        errstr(err));
+
+               /*
+                * If attachment fails with EADDRNOTAVAIL (or EINVAL in
+                * legacy mode) and we used non-NULL func_name, try to
+                * find function address in /proc/kallsyms and retry
+                * using KADDR instead of ambiguous symbol. Legacy
+                * tracefs API converts EADDRNOTAVAIL to EINVAL, so
+                * we need to check for both.
+                */
+               if ((err == -EADDRNOTAVAIL || (legacy && err == -EINVAL)) && optional_func_name) {
+                       pr_debug("kallsyms lookup for %s\n",
+                                func_name);
+
+                       kaddr_ctx.func_name = func_name;
+                       kaddr_ctx.kaddr = 0;
+
+                       /*
+                        * Drop the function symbol and add the resolved
+                        * KADDR to the offset.
+                        * This avoids kallsyms validation for duplicate
+                        * symbols in the kernel. See attr.config2 in
+                        * perf_event_open_probe and kernel code in
+                        * perf_kprobe_init/create_local_trace_kprobe.
+                        */
+                       optional_func_name = NULL;
+
+                       err = libbpf_kallsyms_parse(find_kaddr_cb, &kaddr_ctx, true);
+                       if (err) {
+                               pr_warn("failed to get addr for %s\n",
+                                       func_name);
+                               goto err_out;
+                       }
+
+                       if (kaddr_ctx.kaddr) {
+                               pr_debug("retrying %s using kaddr 0x%llx\n",
+                                        func_name, kaddr_ctx.kaddr);
+
+                               offset += kaddr_ctx.kaddr;
+                               free(legacy_probe);
+                               legacy_probe = NULL;
+                               goto retry_create;
+                       }
+
+                       pr_warn("symbol '%s' not found in vmlinux\n",
+                               func_name);
+                       err = -ENOENT;
+               }
+
                goto err_out;
        }
        link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
@@ -11931,7 +12050,7 @@ static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
        data.syms = syms;
        data.res = res;
        data.cnt = cnt;
-       libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
+       libbpf_kallsyms_parse(avail_kallsyms_cb, &data, false);
 
        if (res->cnt == 0)
                err = -ENOENT;
--

2.34.1

#4 lore raw

Re: [External] Re: [PATCH bpf-next v4 1/2] libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

Quoted 9 lines · Andrii Nakryiko
Quoted 5 lines · Andrey Grodzovsky

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

Quoted 7 lines

If the same symbol name resolves to multiple addresses, that's an ambiguity that libbpf has no business resolving. It should be on user to resolve and use attachment by address, which libbpf supports through bpf_kprobe_opts or multi-kprobe opts.

pw-bot: cr

I understand the concern about libbpf making policy decisions on ambiguous symbol resolution. But I think the skeleton-based auto-attach workflow makes this impractical for the user to handle.

The recommended upstream pattern is:

  skel = my_prog__open_and_load();
  my_prog__attach(skel);

So it's something along the lines of

our_skeleteon_bpf__attach(skel)
→ bpf_object__attach_skeleton(skel->skeleton)
→ prog->sec_def->prog_attach_fn() [= attach_kprobe()]
→ bpf_program__attach_kprobe_opts(prog, func, &opts)
→ perf_event_open_probe(name=func, offset=0)
→ perf_event_open() → EADDRNOTAVAIL

So bpf_object__attach_skeleton(), which iterates over all programs and calls attach_kprobe() internally. That function extracts the symbol name from the ELF section name (SEC("kprobe/func_name")) and passes it to bpf_program__attach_kprobe_opts(). The user has no control point in this chain - no callback, no option struct, no way to intercept a failed attach and supply an address instead.

If a kernel module happens to export a symbol with the same name as a vmlinux function the user is probing, the attach fails with EADDRNOTAVAIL and the user has no recovery path within the skeleton API. The only options would be:

1. Abandon skeleton auto-attach entirely for any kprobe program that might hit a duplicate, and manually call bpf_program__attach_kprobe_opts() with a resolved address for each one. This defeats the purpose of skeletons.

2. Proactively scan /proc/kallsyms before every attach to detect potential duplicates, set prog->autoattach = false for affected programs, and manually attach those. But autoattach is not exposed in the public skeleton API either.

Since a kernel module can be loaded at any time, any kprobe could potentially become ambiguous. Pushing resolution to the user effectively means the skeleton auto-attach pattern cannot be reliably used for kprobes.

The fallback in this patch is intentionally conservative - it only triggers on the specific error codes that indicate duplicate symbols (EADDRNOTAVAIL for perf_event_open, EINVAL for legacy), and it resolves strictly to the vmlinux text symbol, skipping module symbols. This seems like the only reasonable behavior for auto-attach, where the user has expressed intent to probe a specific function by name.

Would it make sense to limit this fallback to the auto-attach path (attach_kprobe) rather than the explicit attach_kprobe_opts API? That way users who call attach_kprobe_opts directly still get the raw error and can handle it themselves, while the skeleton workflow has a reasonable default.

Happy to hear alternative suggestions on how to make this work within the existing API.

Andrey

Quoted 283 lines
Quoted 283 lines

Implement a fallback mechanism that, on such failures, resolves the vmlinux address through /proc/kallsyms - filtering out module symbols - and retries probe attachment using the absolute address, bypassing kernel symbol name validation.

Changes:
- Restructure libbpf_kallsyms_parse() to accept a bool skip_if_module parameter that filters module symbols before invoking the callback.
- Add find_kaddr_cb() callback and find_kaddr_ctx struct to resolve vmlinux text symbol addresses from /proc/kallsyms.
- Detect duplicate symbol errors (-EADDRNOTAVAIL for perf_event_open, -EINVAL for legacy tracefs) and retry with resolved KADDR.
- Fix NULL pointer in gen_probe_legacy_event_name() when using absolute address by passing func_name instead of optional_func_name.
- Fix NULL pointer in pr_warn() calls within perf_event_kprobe_open_legacy() by using ternary fallback.
- Fix memory leak of legacy_probe buffer on retry path.

---
 tools/lib/bpf/libbpf.c | 155 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 137 insertions(+), 18 deletions(-)
tools/lib/bpf/libbpf.c +137 -19
index 0be7017800fe..e725e3c98ee2 100644
@@ -8460,9 +8460,11 @@ static int bpf_object__sanitize_maps(struct bpf_object *obj)
 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
                             const char *sym_name, void *ctx);
 
-static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
+static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx,
+                               bool skip_if_module)
 {
        char sym_type, sym_name[500];
+       char module_name[128];
        unsigned long long sym_addr;
        int ret, err = 0;
        FILE *f;
@@ -8475,21 +8477,39 @@ static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
        }
 
        while (true) {
-               ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
-                            &sym_addr, &sym_type, sym_name);
-               if (ret == EOF && feof(f))
+               int n = 0;
+
+               /*
+                * Format tries to match both vmlinux and module kallsyms
+                * entries in one call. Module entries have the form:
+                *   addr type name [module]
+                * %n fires only if the closing ']' literal is matched.
+                */
+               ret = fscanf(f, "%llx %c %499s [%127[^] \t\n\r\v\f]] %n",
+                            &sym_addr, &sym_type, sym_name, module_name, &n);
+
+               /* EOF or malformed line - handle after the loop */
+               if (ret != 3 && ret != 4)
                        break;
-               if (ret != 3) {
-                       pr_warn("failed to read kallsyms entry: %d\n", ret);
-                       err = -EINVAL;
+
+               /* ret == 4 && n == 0: scanset matched but ']' didn't */
+               if (ret == 4 && n == 0)
                        break;
-               }
+
+               if (ret == 4 && skip_if_module)
+                       continue;
 
                err = cb(sym_addr, sym_type, sym_name, ctx);
                if (err)
                        break;
        }
 
+       /* !err: don't overwrite callback errors with -EINVAL */
+       if (!feof(f) && !err) {
+               pr_warn("failed to read kallsyms entry: ret=%d\n", ret);
+               err = -EINVAL;
+       }
+
        fclose(f);
        return err;
 }
@@ -8529,7 +8549,7 @@ static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
 
 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
 {
-       return libbpf_kallsyms_parse(kallsyms_cb, obj);
+       return libbpf_kallsyms_parse(kallsyms_cb, obj, false);
 }
 
 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
@@ -11527,10 +11547,20 @@ static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
                                   const char *kfunc_name, size_t offset)
 {
-       return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
-                             retprobe ? 'r' : 'p',
-                             retprobe ? "kretprobes" : "kprobes",
-                             probe_name, kfunc_name, offset);
+       /* When kfunc_name is NULL, use absolute address format (0xADDR),
+        * otherwise use symbol+offset format (SYMBOL+0xOFF)
+        */
+       if (kfunc_name) {
+               return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
+                                     retprobe ? 'r' : 'p',
+                                     retprobe ? "kretprobes" : "kprobes",
+                                     probe_name, kfunc_name, offset);
+       } else {
+               return append_to_file(tracefs_kprobe_events(), "%c:%s/%s 0x%zx",
+                                     retprobe ? 'r' : 'p',
+                                     retprobe ? "kretprobes" : "kprobes",
+                                     probe_name, offset);
+       }
 }
 
 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
@@ -11559,7 +11589,7 @@ static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
        err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
        if (err < 0) {
                pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
-                       kfunc_name, offset,
+                       kfunc_name ? kfunc_name : "(abs_addr)", offset,
                        errstr(err));
                return err;
        }
@@ -11567,7 +11597,7 @@ static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
        if (type < 0) {
                err = type;
                pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
-                       kfunc_name, offset,
+                       kfunc_name ? kfunc_name : "(abs_addr)", offset,
                        errstr(err));
                goto err_clean_legacy;
        }
@@ -11651,6 +11681,44 @@ int probe_kern_syscall_wrapper(int token_fd)
        }
 }
 
+/* Context structure for finding vmlinux kernel symbol address */
+struct find_kaddr_ctx {
+       const char *func_name;
+       unsigned long long kaddr;
+};
+
+/* Callback to find vmlinux kernel text symbol address */
+static int find_kaddr_cb(unsigned long long sym_addr, char sym_type,
+                        const char *sym_name, void *ctx)
+{
+       struct find_kaddr_ctx *data = ctx;
+
+       /* Only match text section symbols ('T' or 't') */
+       if (toupper(sym_type) != 'T')
+               return 0;
+
+       /* Check if this is the symbol we're looking for */
+       if (strcmp(sym_name, data->func_name) == 0) {
+
+               /*
+                * If we already have an address, we've encountered a
+                * duplicate symbol name. Reject such symbols to avoid
+                * ambiguous resolution.
+                */
+               if (data->kaddr && data->kaddr != sym_addr) {
+                       pr_warn("kernel symbol '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
+                       sym_name, data->kaddr, sym_addr);
+                       return -EINVAL;
+               }
+
+               data->kaddr = sym_addr;
+               pr_debug("found kernel symbol %s at address 0x%llx\n",
+                        sym_name, data->kaddr);
+       }
+
+       return 0;
+}
+
 struct bpf_link *
 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                                const char *func_name,
@@ -11663,6 +11731,8 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
        size_t offset;
        bool retprobe, legacy;
        int pfd, err;
+       const char *optional_func_name = func_name;
+       struct find_kaddr_ctx kaddr_ctx = { .kaddr = 0 };
 
        if (!OPTS_VALID(opts, bpf_kprobe_opts))
                return libbpf_err_ptr(-EINVAL);
@@ -11693,9 +11763,10 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                return libbpf_err_ptr(-EINVAL);
        }
 
+retry_create:
        if (!legacy) {
                pfd = perf_event_open_probe(false /* uprobe */, retprobe,
-                                           func_name, offset,
+                                           optional_func_name, offset,
                                            -1 /* pid */, 0 /* ref_ctr_off */);
        } else {
                char probe_name[MAX_EVENT_NAME_LEN];
@@ -11707,7 +11778,7 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                if (!legacy_probe)
                        return libbpf_err_ptr(-ENOMEM);
 
-               pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
+               pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, optional_func_name,
                                                    offset, -1 /* pid */);
        }
        if (pfd < 0) {
@@ -11716,6 +11787,54 @@ bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
                        prog->name, retprobe ? "kretprobe" : "kprobe",
                        func_name, offset,
                        errstr(err));
+
+               /*
+                * If attachment fails with EADDRNOTAVAIL (or EINVAL in
+                * legacy mode) and we used non-NULL func_name, try to
+                * find function address in /proc/kallsyms and retry
+                * using KADDR instead of ambiguous symbol. Legacy
+                * tracefs API converts EADDRNOTAVAIL to EINVAL, so
+                * we need to check for both.
+                */
+               if ((err == -EADDRNOTAVAIL || (legacy && err == -EINVAL)) && optional_func_name) {
+                       pr_debug("kallsyms lookup for %s\n",
+                                func_name);
+
+                       kaddr_ctx.func_name = func_name;
+                       kaddr_ctx.kaddr = 0;
+
+                       /*
+                        * Drop the function symbol and add the resolved
+                        * KADDR to the offset.
+                        * This avoids kallsyms validation for duplicate
+                        * symbols in the kernel. See attr.config2 in
+                        * perf_event_open_probe and kernel code in
+                        * perf_kprobe_init/create_local_trace_kprobe.
+                        */
+                       optional_func_name = NULL;
+
+                       err = libbpf_kallsyms_parse(find_kaddr_cb, &kaddr_ctx, true);
+                       if (err) {
+                               pr_warn("failed to get addr for %s\n",
+                                       func_name);
+                               goto err_out;
+                       }
+
+                       if (kaddr_ctx.kaddr) {
+                               pr_debug("retrying %s using kaddr 0x%llx\n",
+                                        func_name, kaddr_ctx.kaddr);
+
+                               offset += kaddr_ctx.kaddr;
+                               free(legacy_probe);
+                               legacy_probe = NULL;
+                               goto retry_create;
+                       }
+
+                       pr_warn("symbol '%s' not found in vmlinux\n",
+                               func_name);
+                       err = -ENOENT;
+               }
+
                goto err_out;
        }
        link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
@@ -11931,7 +12050,7 @@ static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
        data.syms = syms;
        data.res = res;
        data.cnt = cnt;
-       libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
+       libbpf_kallsyms_parse(avail_kallsyms_cb, &data, false);
 
        if (res->cnt == 0)
                err = -ENOENT;
--

2.34.1

reviewer
#5 lore raw

Re: [External] Re: [PATCH bpf-next v4 1/2] libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

Quoted 11 lines · Andrey Grodzovsky
Quoted 9 lines · Andrii Nakryiko
Quoted 5 lines · Andrey Grodzovsky

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

Quoted 4 lines
Quoted 4 lines

If the same symbol name resolves to multiple addresses, that's an ambiguity that libbpf has no business resolving. It should be on user to resolve and use attachment by address, which libbpf supports through bpf_kprobe_opts or multi-kprobe opts.

Hi Andrey, see my comments below.

TL;DR is that I agree with Andrii here. The proposed mechanism with a fallback and kallsyms parsing just doesn't fit in libbpf, especially given that a user-side workaround is feasible (even if inconvenient).

The first point that seems obvious to me is that modules shouldn't shadow kernel symbols. If your module does it accidentally: fix your module. If it's on purpose: sorry, you're on your own then.

But let's set that aside for now. After all the module may be an external dependency of whatever system you're building or tracing.

Quoted 22 lines
Quoted 3 lines

pw-bot: cr

I understand the concern about libbpf making policy decisions on ambiguous symbol resolution. But I think the skeleton-based auto-attach workflow makes this impractical for the user to handle.

The recommended upstream pattern is:

  skel = my_prog__open_and_load();
  my_prog__attach(skel);

So it's something along the lines of

our_skeleteon_bpf__attach(skel)
→ bpf_object__attach_skeleton(skel->skeleton)
→ prog->sec_def->prog_attach_fn() [= attach_kprobe()]
→ bpf_program__attach_kprobe_opts(prog, func, &opts)
→ perf_event_open_probe(name=func, offset=0)
→ perf_event_open() → EADDRNOTAVAIL

Quoted 6 lines

So bpf_object__attach_skeleton(), which iterates over all programs and calls attach_kprobe() internally. That function extracts the symbol name from the ELF section name (SEC("kprobe/func_name")) and passes it to bpf_program__attach_kprobe_opts(). The user has no control point in this chain - no callback, no option struct, no way to intercept a failed attach and supply an address instead.

You are right that the skeleton auto-attach path doesn't have a direct interception point, but this is solvable without libbpf changes.

The workaround is essentially what Andrii suggested: resolve the address yourself before attaching. I vibe-coded a change on top of your selftest patch to demonstrate it, pasted at the bottom. It works.

But even ignoring the workaround, I think there are conceptual issues with the proposed approach, regardless of whether the fallback is in attach_kprobe_opts or limited to auto-attach.

The fallback unconditionally prefers vmlinux over module symbols. If someone legitimately wants to probe a module function that shadows a vmlinux name, this silently attaches to the wrong target with no opt-out.

The EINVAL catch in legacy mode is overly broad. EINVAL can come from many conditions (bad offset, bad probe name, write errors), not just duplicate symbols. The func_name != NULL guard helps but doesn't eliminate false positives that trigger unnecessary kallsyms parsing.

kprobe_multi is not covered. libbpf_available_kallsyms_parse() resolves symbols by name via glob_match() without module filtering. The same duplicate-symbol issue exists there.

Every retry parses all of /proc/kallsyms linearly (that's 100k+ symbols). If multiple probes fail in sequence, the cost compounds.

Quoted 16 lines

If a kernel module happens to export a symbol with the same name as a vmlinux function the user is probing, the attach fails with EADDRNOTAVAIL and the user has no recovery path within the skeleton API. The only options would be:

1. Abandon skeleton auto-attach entirely for any kprobe program that might hit a duplicate, and manually call bpf_program__attach_kprobe_opts() with a resolved address for each one. This defeats the purpose of skeletons.

2. Proactively scan /proc/kallsyms before every attach to detect potential duplicates, set prog->autoattach = false for affected programs, and manually attach those. But autoattach is not exposed in the public skeleton API either.

Quoted 4 lines

Since a kernel module can be loaded at any time, any kprobe could potentially become ambiguous. Pushing resolution to the user effectively means the skeleton auto-attach pattern cannot be reliably used for kprobes.

To that I'd say that you can not *reliably* use kprobes. Period. There is a whole can of worms with inlining and functions being optimized away etc.

Handling a case when your userspace+BPF system smartly handles symbol changes due to module loads is not libbpf or kernel's business IMO.

Quoted 8 lines

The fallback in this patch is intentionally conservative - it only triggers on the specific error codes that indicate duplicate symbols (EADDRNOTAVAIL for perf_event_open, EINVAL for legacy), and it resolves strictly to the vmlinux text symbol, skipping module symbols. This seems like the only reasonable behavior for auto-attach, where the user has expressed intent to probe a specific function by name.

Quoted 8 lines

Would it make sense to limit this fallback to the auto-attach path (attach_kprobe) rather than the explicit attach_kprobe_opts API? That way users who call attach_kprobe_opts directly still get the raw error and can handle it themselves, while the skeleton workflow has a reasonable default.

Happy to hear alternative suggestions on how to make this work within the existing API.

I think we can reframe the issue in terms of "how to make this more convenient".

It looks to me that the main issue here is in number_of_same_symbols() (in trace_kprobe.c). When no module qualifier is given, it counts matching symbols across vmlinux AND all loaded modules. There is no mechanism to scope the check only to kernel AFAIU. So any module that exports a matching symbol makes the vmlinux symbol unattachable by name.

It may be worth a discussion whether a "I want a kernel symbol" mechanism could be introduced for kprobes, since the kernel already supports MOD:SYM qualification.

With a kernel side change like that, the skeleton auto-attach path will just work, no libbpf changes needed at all.

Thanks,
Ihor

And here is the workaround example patch:

tools/testing/selftests/bpf/prog_tests/attach_probe.c +81 -0
index 75c22af2f1b3..c20a1510b4d1 100644
@@ -5,6 +5,7 @@
 #include "test_attach_probe.skel.h"
 #include "kprobe_write_ctx.skel.h"
 #include "testing_helpers.h"
+#include "trace_helpers.h"
 
 /* this is how USDT semaphore is actually defined, except volatile modifier */
 volatile unsigned short uprobe_ref_ctr __attribute__((unused)) __attribute((section(".probes")));
@@ -177,6 +178,83 @@ static void test_attach_probe_dup_sym(enum probe_attach_mode attach_mode)
 	unload_module("bpf_testmod_dup_sym", false);
 }
 
+/* Workaround for duplicate kprobe symbols without libbpf changes.
+ *
+ * When a module exports a symbol with the same name as a vmlinux function,
+ * attaching by name fails with EADDRNOTAVAIL. The fix does NOT belong in
+ * libbpf. Instead, the user can:
+ *
+ *   1. Resolve the vmlinux address via /proc/kallsyms using kallsyms_find(),
+ *      which returns the first match -- vmlinux symbols precede module symbols
+ *      in kallsyms output (module symbols are annotated with [modname]).
+ *   2. Attach with func_name=NULL and opts.offset=absolute_address, bypassing
+ *      the kernel's duplicate-symbol check entirely.
+ *
+ * This demonstrates that no libbpf changes are needed; resolution of the
+ * ambiguity is the caller's responsibility.
+ */
+static void test_attach_probe_dup_sym_workaround(void)
+{
+	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
+	struct bpf_link *kprobe_link, *kretprobe_link;
+	struct test_attach_probe_manual *skel;
+	unsigned long long kaddr = 0;
+	int err;
+
+	/* Load module with duplicate symbol */
+	err = load_module("bpf_testmod_dup_sym.ko", false);
+	if (!ASSERT_OK(err, "load_bpf_testmod_dup_sym")) {
+		test__skip();
+		return;
+	}
+
+	/*
+	 * Resolve the vmlinux address of the target function.  kallsyms_find()
+	 * stops at the first match; vmlinux entries precede module entries, so
+	 * this gives us the vmlinux address even when a module shadows the name.
+	 */
+	err = kallsyms_find(SYS_NANOSLEEP_KPROBE_NAME, &kaddr);
+	if (!ASSERT_OK(err, "kallsyms_find_nanosleep"))
+		goto unload_module;
+	if (!ASSERT_NEQ(kaddr, 0, "kaddr_nonzero"))
+		goto unload_module;
+
+	skel = test_attach_probe_manual__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_dup_sym_workaround_open_and_load"))
+		goto unload_module;
+
+	/*
+	 * Attach by absolute address (func_name=NULL, offset=kaddr).
+	 * The kernel receives no symbol name to validate, so the duplicate
+	 * symbol in the module does not cause EADDRNOTAVAIL.
+	 */
+	kprobe_opts.retprobe = false;
+	kprobe_opts.offset = kaddr;
+	kprobe_link = bpf_program__attach_kprobe_opts(skel->progs.handle_kprobe,
+						      NULL, &kprobe_opts);
+	if (!ASSERT_OK_PTR(kprobe_link, "attach_kprobe_dup_sym_workaround"))
+		goto cleanup;
+	skel->links.handle_kprobe = kprobe_link;
+
+	kprobe_opts.retprobe = true;
+	kretprobe_link = bpf_program__attach_kprobe_opts(skel->progs.handle_kretprobe,
+							 NULL, &kprobe_opts);
+	if (!ASSERT_OK_PTR(kretprobe_link, "attach_kretprobe_dup_sym_workaround"))
+		goto cleanup;
+	skel->links.handle_kretprobe = kretprobe_link;
+
+	/* trigger & validate kprobe && kretprobe */
+	usleep(1);
+
+	ASSERT_EQ(skel->bss->kprobe_res, 1, "check_kprobe_dup_sym_workaround_res");
+	ASSERT_EQ(skel->bss->kretprobe_res, 2, "check_kretprobe_dup_sym_workaround_res");
+
+cleanup:
+	test_attach_probe_manual__destroy(skel);
+unload_module:
+	unload_module("bpf_testmod_dup_sym", false);
+}
+
 /* attach uprobe/uretprobe long event name testings */
 static void test_attach_uprobe_long_event_name(void)
 {
@@ -480,6 +558,9 @@ void test_attach_probe(void)
 	if (test__start_subtest("dup-sym-link"))
 		test_attach_probe_dup_sym(PROBE_ATTACH_MODE_LINK);
 
+	if (test__start_subtest("dup-sym-workaround"))
+		test_attach_probe_dup_sym_workaround();
+
 	if (test__start_subtest("auto"))
 		test_attach_probe_auto(skel);
 	if (test__start_subtest("kprobe-sleepable"))
Signature · 1 line
2.52.0
Quoted 5 lines

Andrey

Quoted 1 line

[...]

#6 lore raw

Re: [External] Re: [PATCH bpf-next v4 1/2] libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

Quoted 60 lines · Ihor Solodrai
Quoted 11 lines · Andrey Grodzovsky
Quoted 9 lines · Andrii Nakryiko
Quoted 5 lines · Andrey Grodzovsky

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

Quoted 4 lines
Quoted 4 lines

If the same symbol name resolves to multiple addresses, that's an ambiguity that libbpf has no business resolving. It should be on user to resolve and use attachment by address, which libbpf supports through bpf_kprobe_opts or multi-kprobe opts.

Hi Andrey, see my comments below.

TL;DR is that I agree with Andrii here. The proposed mechanism with a fallback and kallsyms parsing just doesn't fit in libbpf, especially given that a user-side workaround is feasible (even if inconvenient).

The first point that seems obvious to me is that modules shouldn't shadow kernel symbols. If your module does it accidentally: fix your module. If it's on purpose: sorry, you're on your own then.

But let's set that aside for now. After all the module may be an external dependency of whatever system you're building or tracing.

Quoted 22 lines
Quoted 3 lines

pw-bot: cr

I understand the concern about libbpf making policy decisions on ambiguous symbol resolution. But I think the skeleton-based auto-attach workflow makes this impractical for the user to handle.

The recommended upstream pattern is:

  skel = my_prog__open_and_load();
  my_prog__attach(skel);

So it's something along the lines of

our_skeleteon_bpf__attach(skel)
→ bpf_object__attach_skeleton(skel->skeleton)
→ prog->sec_def->prog_attach_fn() [= attach_kprobe()]
→ bpf_program__attach_kprobe_opts(prog, func, &opts)
→ perf_event_open_probe(name=func, offset=0)
→ perf_event_open() → EADDRNOTAVAIL

Quoted 6 lines

So bpf_object__attach_skeleton(), which iterates over all programs and calls attach_kprobe() internally. That function extracts the symbol name from the ELF section name (SEC("kprobe/func_name")) and passes it to bpf_program__attach_kprobe_opts(). The user has no control point in this chain - no callback, no option struct, no way to intercept a failed attach and supply an address instead.

Quoted 7 lines

You are right that the skeleton auto-attach path doesn't have a direct interception point, but this is solvable without libbpf changes.

The workaround is essentially what Andrii suggested: resolve the address yourself before attaching. I vibe-coded a change on top of your selftest patch to demonstrate it, pasted at the bottom. It works.

Just to clarify, the offending function is unknown, and since we go through bpf_object__attach_skeleton, which bulk iterates all our programs, we have no way to relate the returned error to the program that caused it. Although i do see a hacky way, libbpf logging reports and error at this point and does specifiy which function failed to attach, so this would allow us to avoid libbpf cnages... But it's obviously hacky...

Quoted 77 lines

But even ignoring the workaround, I think there are conceptual issues with the proposed approach, regardless of whether the fallback is in attach_kprobe_opts or limited to auto-attach.

The fallback unconditionally prefers vmlinux over module symbols. If someone legitimately wants to probe a module function that shadows a vmlinux name, this silently attaches to the wrong target with no opt-out.

The EINVAL catch in legacy mode is overly broad. EINVAL can come from many conditions (bad offset, bad probe name, write errors), not just duplicate symbols. The func_name != NULL guard helps but doesn't eliminate false positives that trigger unnecessary kallsyms parsing.

kprobe_multi is not covered. libbpf_available_kallsyms_parse() resolves symbols by name via glob_match() without module filtering. The same duplicate-symbol issue exists there.

Every retry parses all of /proc/kallsyms linearly (that's 100k+ symbols). If multiple probes fail in sequence, the cost compounds.

Quoted 16 lines

If a kernel module happens to export a symbol with the same name as a vmlinux function the user is probing, the attach fails with EADDRNOTAVAIL and the user has no recovery path within the skeleton API. The only options would be:

1. Abandon skeleton auto-attach entirely for any kprobe program that might hit a duplicate, and manually call bpf_program__attach_kprobe_opts() with a resolved address for each one. This defeats the purpose of skeletons.

2. Proactively scan /proc/kallsyms before every attach to detect potential duplicates, set prog->autoattach = false for affected programs, and manually attach those. But autoattach is not exposed in the public skeleton API either.

Quoted 4 lines

Since a kernel module can be loaded at any time, any kprobe could potentially become ambiguous. Pushing resolution to the user effectively means the skeleton auto-attach pattern cannot be reliably used for kprobes.

To that I'd say that you can not *reliably* use kprobes. Period. There is a whole can of worms with inlining and functions being optimized away etc.

Handling a case when your userspace+BPF system smartly handles symbol changes due to module loads is not libbpf or kernel's business IMO.

Quoted 8 lines

The fallback in this patch is intentionally conservative - it only triggers on the specific error codes that indicate duplicate symbols (EADDRNOTAVAIL for perf_event_open, EINVAL for legacy), and it resolves strictly to the vmlinux text symbol, skipping module symbols. This seems like the only reasonable behavior for auto-attach, where the user has expressed intent to probe a specific function by name.

Quoted 8 lines

Would it make sense to limit this fallback to the auto-attach path (attach_kprobe) rather than the explicit attach_kprobe_opts API? That way users who call attach_kprobe_opts directly still get the raw error and can handle it themselves, while the skeleton workflow has a reasonable default.

Happy to hear alternative suggestions on how to make this work within the existing API.

I think we can reframe the issue in terms of "how to make this more convenient".

It looks to me that the main issue here is in number_of_same_symbols() (in trace_kprobe.c). When no module qualifier is given, it counts matching symbols across vmlinux AND all loaded modules. There is no mechanism to scope the check only to kernel AFAIU. So any module that exports a matching symbol makes the vmlinux symbol unattachable by name.

Quoted 3 lines

It may be worth a discussion whether a "I want a kernel symbol" mechanism could be introduced for kprobes, since the kernel already supports MOD:SYM qualification.

Thanks, that's a good point! I might look into this route as an alternative.

Quoted 51 lines

With a kernel side change like that, the skeleton auto-attach path will just work, no libbpf changes needed at all.

Thanks,
Ihor

And here is the workaround example patch:

tools/testing/selftests/bpf/prog_tests/attach_probe.c +27 -0
index 75c22af2f1b3..c20a1510b4d1 100644
@@ -5,6 +5,7 @@
 #include "test_attach_probe.skel.h"
 #include "kprobe_write_ctx.skel.h"
 #include "testing_helpers.h"
+#include "trace_helpers.h"
 
 /* this is how USDT semaphore is actually defined, except volatile modifier */
 volatile unsigned short uprobe_ref_ctr __attribute__((unused)) __attribute((section(".probes")));
@@ -177,6 +178,83 @@ static void test_attach_probe_dup_sym(enum probe_attach_mode attach_mode)
        unload_module("bpf_testmod_dup_sym", false);
 }
 
+/* Workaround for duplicate kprobe symbols without libbpf changes.
+ *
+ * When a module exports a symbol with the same name as a vmlinux function,
+ * attaching by name fails with EADDRNOTAVAIL. The fix does NOT belong in
+ * libbpf. Instead, the user can:
+ *
+ *   1. Resolve the vmlinux address via /proc/kallsyms using kallsyms_find(),
+ *      which returns the first match -- vmlinux symbols precede module symbols
+ *      in kallsyms output (module symbols are annotated with [modname]).
+ *   2. Attach with func_name=NULL and opts.offset=absolute_address, bypassing
+ *      the kernel's duplicate-symbol check entirely.
+ *
+ * This demonstrates that no libbpf changes are needed; resolution of the
+ * ambiguity is the caller's responsibility.
+ */
+static void test_attach_probe_dup_sym_workaround(void)
+{
+       DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
+       struct bpf_link *kprobe_link, *kretprobe_link;
+       struct test_attach_probe_manual *skel;
+       unsigned long long kaddr = 0;
+       int err;
+
+       /* Load module with duplicate symbol */
+       err = load_module("bpf_testmod_dup_sym.ko", false);
+       if (!ASSERT_OK(err, "load_bpf_testmod_dup_sym")) {

tools/testing/selftests/bpf/prog_tests/attach_probe.c static void test_attach_probe_dup_sym(enum probe_attach_mode attach_mode) · line 216

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/attach_probe.c +10 -0
+               test__skip();
+               return;
+       }
+
+       /*
+        * Resolve the vmlinux address of the target function.  kallsyms_find()
+        * stops at the first match; vmlinux entries precede module entries, so
+        * this gives us the vmlinux address even when a module shadows the name.
+        */
+       err = kallsyms_find(SYS_NANOSLEEP_KPROBE_NAME, &kaddr);

Just to reiterate my issue - i don't know that SYS_NANOSLEEP is the one which casued it. Could be any random function we attach, at any point of time, depdendant on currently loaded moudles in the system.

Thanks,
Andrey

Quoted 66 lines
tools/testing/selftests/bpf/prog_tests/attach_probe.c +44 -1
+       if (!ASSERT_OK(err, "kallsyms_find_nanosleep"))
+               goto unload_module;
+       if (!ASSERT_NEQ(kaddr, 0, "kaddr_nonzero"))
+               goto unload_module;
+
+       skel = test_attach_probe_manual__open_and_load();
+       if (!ASSERT_OK_PTR(skel, "skel_dup_sym_workaround_open_and_load"))
+               goto unload_module;
+
+       /*
+        * Attach by absolute address (func_name=NULL, offset=kaddr).
+        * The kernel receives no symbol name to validate, so the duplicate
+        * symbol in the module does not cause EADDRNOTAVAIL.
+        */
+       kprobe_opts.retprobe = false;
+       kprobe_opts.offset = kaddr;
+       kprobe_link = bpf_program__attach_kprobe_opts(skel->progs.handle_kprobe,
+                                                     NULL, &kprobe_opts);
+       if (!ASSERT_OK_PTR(kprobe_link, "attach_kprobe_dup_sym_workaround"))
+               goto cleanup;
+       skel->links.handle_kprobe = kprobe_link;
+
+       kprobe_opts.retprobe = true;
+       kretprobe_link = bpf_program__attach_kprobe_opts(skel->progs.handle_kretprobe,
+                                                        NULL, &kprobe_opts);
+       if (!ASSERT_OK_PTR(kretprobe_link, "attach_kretprobe_dup_sym_workaround"))
+               goto cleanup;
+       skel->links.handle_kretprobe = kretprobe_link;
+
+       /* trigger & validate kprobe && kretprobe */
+       usleep(1);
+
+       ASSERT_EQ(skel->bss->kprobe_res, 1, "check_kprobe_dup_sym_workaround_res");
+       ASSERT_EQ(skel->bss->kretprobe_res, 2, "check_kretprobe_dup_sym_workaround_res");
+
+cleanup:
+       test_attach_probe_manual__destroy(skel);
+unload_module:
+       unload_module("bpf_testmod_dup_sym", false);
+}
+
 /* attach uprobe/uretprobe long event name testings */
 static void test_attach_uprobe_long_event_name(void)
 {
@@ -480,6 +558,9 @@ void test_attach_probe(void)
        if (test__start_subtest("dup-sym-link"))
                test_attach_probe_dup_sym(PROBE_ATTACH_MODE_LINK);
 
+       if (test__start_subtest("dup-sym-workaround"))
+               test_attach_probe_dup_sym_workaround();
+
        if (test__start_subtest("auto"))
                test_attach_probe_auto(skel);
        if (test__start_subtest("kprobe-sleepable"))
--

2.52.0

Quoted 5 lines

Andrey

Quoted 1 line

[...]

#7 lore raw

Re: [External] Re: [PATCH bpf-next v4 1/2] libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

In reply to Andrey Grodzovsky
Quoted 50 lines · Andrey Grodzovsky
Quoted 9 lines · Andrii Nakryiko
Quoted 5 lines · Andrey Grodzovsky

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

Quoted 7 lines

If the same symbol name resolves to multiple addresses, that's an ambiguity that libbpf has no business resolving. It should be on user to resolve and use attachment by address, which libbpf supports through bpf_kprobe_opts or multi-kprobe opts.

pw-bot: cr

I understand the concern about libbpf making policy decisions on ambiguous symbol resolution. But I think the skeleton-based auto-attach workflow makes this impractical for the user to handle.

The recommended upstream pattern is:

  skel = my_prog__open_and_load();
  my_prog__attach(skel);

So it's something along the lines of

our_skeleteon_bpf__attach(skel)
→ bpf_object__attach_skeleton(skel->skeleton)
→ prog->sec_def->prog_attach_fn() [= attach_kprobe()]
→ bpf_program__attach_kprobe_opts(prog, func, &opts)
→ perf_event_open_probe(name=func, offset=0)
→ perf_event_open() → EADDRNOTAVAIL

So bpf_object__attach_skeleton(), which iterates over all programs and calls attach_kprobe() internally. That function extracts the symbol name from the ELF section name (SEC("kprobe/func_name")) and passes it to bpf_program__attach_kprobe_opts(). The user has no control point in this chain - no callback, no option struct, no way to intercept a failed attach and supply an address instead.

If a kernel module happens to export a symbol with the same name as a vmlinux function the user is probing, the attach fails with EADDRNOTAVAIL and the user has no recovery path within the skeleton API. The only options would be:

Quoted 4 lines

1. Abandon skeleton auto-attach entirely for any kprobe program that might hit a duplicate, and manually call bpf_program__attach_kprobe_opts() with a resolved address for each one. This defeats the purpose of skeletons.

No it doesn't. And there are many purposes to skeletons, convenient auto-attach of everything is but one of them (when everything can be declaratively defined and attached).

But even for the auto-attach functionality. bpf_program__set_autoattach(prog, false), attach explicitly however your application logic demands and set resulting link into skeleton's slot (skel->links.<prog>). You'll get the same auto-detach clean up as if your program was auto-attached. It's pretty flexible. Sure it's nice when everything just works out of the box, but ambiguous target symbol is not a typical out-of-the-box-working situation, unfortunately.

Quoted 5 lines

2. Proactively scan /proc/kallsyms before every attach to detect potential duplicates, set prog->autoattach = false for affected programs, and manually attach those. But autoattach is not exposed in the public skeleton API either.

see above, bpf_program__set_autoattach() is a public API. Skeleton is just a convenience wrapper around bpf_object, you still have full access to bpf_map, bpf_program, bpf_object, etc. Skeleton's first and foremost unique added feature is convenient memory-mapped access to global variables (and embedding BPF object file for nicer production deployment), other than that it's doing its best to help but not get in the way.

Quoted 5 lines

Since a kernel module can be loaded at any time, any kprobe could potentially become ambiguous. Pushing resolution to the user effectively means the skeleton auto-attach pattern cannot be reliably used for kprobes.

you are overexaggerating how common this problem is

Quoted 8 lines

The fallback in this patch is intentionally conservative - it only triggers on the specific error codes that indicate duplicate symbols (EADDRNOTAVAIL for perf_event_open, EINVAL for legacy), and it resolves strictly to the vmlinux text symbol, skipping module symbols. This seems like the only reasonable behavior for auto-attach, where the user has expressed intent to probe a specific function by name.

Quoted 8 lines

Would it make sense to limit this fallback to the auto-attach path (attach_kprobe) rather than the explicit attach_kprobe_opts API? That way users who call attach_kprobe_opts directly still get the raw error and can handle it themselves, while the skeleton workflow has a reasonable default.

Happy to hear alternative suggestions on how to make this work within the existing API.

Realistically, just use multi-kprobe. It will attach to all matching kernel functions (unless unique match is requested).

Quoted 29 lines

Andrey

Quoted 25 lines
Quoted 25 lines

Implement a fallback mechanism that, on such failures, resolves the vmlinux address through /proc/kallsyms - filtering out module symbols - and retries probe attachment using the absolute address, bypassing kernel symbol name validation.

Changes:
- Restructure libbpf_kallsyms_parse() to accept a bool skip_if_module parameter that filters module symbols before invoking the callback.
- Add find_kaddr_cb() callback and find_kaddr_ctx struct to resolve vmlinux text symbol addresses from /proc/kallsyms.
- Detect duplicate symbol errors (-EADDRNOTAVAIL for perf_event_open, -EINVAL for legacy tracefs) and retry with resolved KADDR.
- Fix NULL pointer in gen_probe_legacy_event_name() when using absolute address by passing func_name instead of optional_func_name.
- Fix NULL pointer in pr_warn() calls within perf_event_kprobe_open_legacy() by using ternary fallback.
- Fix memory leak of legacy_probe buffer on retry path.

---
 tools/lib/bpf/libbpf.c | 155 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 137 insertions(+), 18 deletions(-)

[...]

#8 lore raw

Re: [External] Re: [PATCH bpf-next v4 1/2] libbpf: Handle duplicate kprobe symbols in attach_kprobe_opts

Quoted 107 lines · Andrii Nakryiko
Quoted 50 lines · Andrey Grodzovsky
Quoted 9 lines · Andrii Nakryiko
Quoted 5 lines · Andrey Grodzovsky

When a kernel module exports a symbol with the same name as an existing vmlinux symbol, kprobe attachment via bpf_program__attach_kprobe_opts() fails with EADDRNOTAVAIL (perf_event_open path) or EINVAL (legacy tracefs path).

Quoted 7 lines

If the same symbol name resolves to multiple addresses, that's an ambiguity that libbpf has no business resolving. It should be on user to resolve and use attachment by address, which libbpf supports through bpf_kprobe_opts or multi-kprobe opts.

pw-bot: cr

I understand the concern about libbpf making policy decisions on ambiguous symbol resolution. But I think the skeleton-based auto-attach workflow makes this impractical for the user to handle.

The recommended upstream pattern is:

  skel = my_prog__open_and_load();
  my_prog__attach(skel);

So it's something along the lines of

our_skeleteon_bpf__attach(skel)
→ bpf_object__attach_skeleton(skel->skeleton)
→ prog->sec_def->prog_attach_fn() [= attach_kprobe()]
→ bpf_program__attach_kprobe_opts(prog, func, &opts)
→ perf_event_open_probe(name=func, offset=0)
→ perf_event_open() → EADDRNOTAVAIL

So bpf_object__attach_skeleton(), which iterates over all programs and calls attach_kprobe() internally. That function extracts the symbol name from the ELF section name (SEC("kprobe/func_name")) and passes it to bpf_program__attach_kprobe_opts(). The user has no control point in this chain - no callback, no option struct, no way to intercept a failed attach and supply an address instead.

If a kernel module happens to export a symbol with the same name as a vmlinux function the user is probing, the attach fails with EADDRNOTAVAIL and the user has no recovery path within the skeleton API. The only options would be:

Quoted 4 lines

1. Abandon skeleton auto-attach entirely for any kprobe program that might hit a duplicate, and manually call bpf_program__attach_kprobe_opts() with a resolved address for each one. This defeats the purpose of skeletons.

No it doesn't. And there are many purposes to skeletons, convenient auto-attach of everything is but one of them (when everything can be declaratively defined and attached).

But even for the auto-attach functionality. bpf_program__set_autoattach(prog, false), attach explicitly however your application logic demands and set resulting link into skeleton's slot (skel->links.<prog>). You'll get the same auto-detach clean up as if your program was auto-attached. It's pretty flexible. Sure it's nice when everything just works out of the box, but ambiguous target symbol is not a typical out-of-the-box-working situation, unfortunately.

Quoted 5 lines

2. Proactively scan /proc/kallsyms before every attach to detect potential duplicates, set prog->autoattach = false for affected programs, and manually attach those. But autoattach is not exposed in the public skeleton API either.

see above, bpf_program__set_autoattach() is a public API. Skeleton is just a convenience wrapper around bpf_object, you still have full access to bpf_map, bpf_program, bpf_object, etc. Skeleton's first and foremost unique added feature is convenient memory-mapped access to global variables (and embedding BPF object file for nicer production deployment), other than that it's doing its best to help but not get in the way.

Quoted 5 lines

Since a kernel module can be loaded at any time, any kprobe could potentially become ambiguous. Pushing resolution to the user effectively means the skeleton auto-attach pattern cannot be reliably used for kprobes.

you are overexaggerating how common this problem is

Quoted 14 lines

The fallback in this patch is intentionally conservative - it only triggers on the specific error codes that indicate duplicate symbols (EADDRNOTAVAIL for perf_event_open, EINVAL for legacy), and it resolves strictly to the vmlinux text symbol, skipping module symbols. This seems like the only reasonable behavior for auto-attach, where the user has expressed intent to probe a specific function by name.

Would it make sense to limit this fallback to the auto-attach path (attach_kprobe) rather than the explicit attach_kprobe_opts API? That way users who call attach_kprobe_opts directly still get the raw error and can handle it themselves, while the skeleton workflow has a reasonable default.

Quoted 5 lines
Quoted 2 lines

Happy to hear alternative suggestions on how to make this work within the existing API.

Realistically, just use multi-kprobe. It will attach to all matching kernel functions (unless unique match is requested).

Thanks Andrii, I already replied to Ihor so I will not repeat same replies here to not spam the mailing list. In genral I understand the issues you guys are having with this approach. Ihor suggested a kernel level solution which seems like a great idea and I will look into it.

Andrey

Quoted 32 lines
Quoted 30 lines

Andrey

Quoted 25 lines
Quoted 25 lines

Implement a fallback mechanism that, on such failures, resolves the vmlinux address through /proc/kallsyms - filtering out module symbols - and retries probe attachment using the absolute address, bypassing kernel symbol name validation.

Changes:
- Restructure libbpf_kallsyms_parse() to accept a bool skip_if_module parameter that filters module symbols before invoking the callback.
- Add find_kaddr_cb() callback and find_kaddr_ctx struct to resolve vmlinux text symbol addresses from /proc/kallsyms.
- Detect duplicate symbol errors (-EADDRNOTAVAIL for perf_event_open, -EINVAL for legacy tracefs) and retry with resolved KADDR.
- Fix NULL pointer in gen_probe_legacy_event_name() when using absolute address by passing func_name instead of optional_func_name.
- Fix NULL pointer in pr_warn() calls within perf_event_kprobe_open_legacy() by using ternary fallback.
- Fix memory leak of legacy_probe buffer on retry path.

---
 tools/lib/bpf/libbpf.c | 155 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 137 insertions(+), 18 deletions(-)

[...]

#9 lore raw

PATCH v4 2/2 selftests/bpf: Add tests for duplicate kprobe symbol handling

In reply to Andrey Grodzovsky

Add bpf_testmod_dup_sym.ko test module that creates a duplicate nanosleep symbols to test kprobe attachment when a module exports a symbol with the same name as a vmlinux symbol.

Add test_attach_probe_dup_sym() to attach_probe tests that loads the duplicate symbol module and validates kprobe attachment across all four attach modes: auto-attach, explicit symbol, legacy with offset, and perf_event_open with offset.

---
 tools/testing/selftests/bpf/Makefile          |  2 +-
 .../selftests/bpf/prog_tests/attach_probe.c   | 63 +++++++++++++++++++
 .../testing/selftests/bpf/test_kmods/Makefile |  2 +-
 .../bpf/test_kmods/bpf_testmod_dup_sym.c      | 48 ++++++++++++++
 4 files changed, 113 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/test_kmods/bpf_testmod_dup_sym.c
tools/testing/selftests/bpf/Makefile +1 -1
index 72a9ba41f95e..2915d46c74e0 100644
@@ -121,7 +121,7 @@ TEST_PROGS_EXTENDED := \
 	test_bpftool.py
 
 TEST_KMODS := bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \
-	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko
+	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_testmod_dup_sym.ko
 TEST_KMOD_TARGETS = $(addprefix $(OUTPUT)/,$(TEST_KMODS))
 
 # Compile but not part of 'make run_tests'
tools/testing/selftests/bpf/prog_tests/attach_probe.c +63 -0

81 lines not on this page · raw message

tools/testing/selftests/bpf/test_kmods/Makefile +1 -1
index 63c4d3f6a12f..938c462a103b 100644
@@ -8,7 +8,7 @@ Q = @
 endif
 
 MODULES = bpf_testmod.ko bpf_test_no_cfi.ko bpf_test_modorder_x.ko \
-	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko
+	bpf_test_modorder_y.ko bpf_test_rqspinlock.ko bpf_testmod_dup_sym.ko
 
 $(foreach m,$(MODULES),$(eval obj-m += $(m:.ko=.o)))
 
tools/testing/selftests/bpf/test_kmods/bpf_testmod_dup_sym.c new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.34.1