Skip to contentSkip to conversation

kallsyms: Add KALLSYMS_QUERY_BY_NAME and KALLSYMS_QUERY_BY_ADDR ioctls

PATCH In review Samuel Wu 6 participants 18 messages Nov 13 – Nov 20

Subsystems (8)
Documentation VFS Kselftest BPF +4 more subsystems
lore
Share & tools
lore

Samuel Wu

author
#0 lore raw

v3 cover kallsyms: Add KALLSYMS_QUERY_BY_NAME and KALLSYMS_QUERY_BY_ADDR ioctls

/proc/kallsyms is the primary interface for userspace to query the kernel symbol table. However, resolving even a handful of symbols or addresses requires reading and parsing the entire text file, which is often several megabytes and takes thousands of read() syscalls.

This patchseries adds two ioctl() commands to interface /proc/kallsyms:
1. KALLSYMS_QUERY_BY_NAME: Finds a symbol by name, or be prefix with the KALLSYMS_QUERY_NAME_PREFIX flag. The default is to search vmlinux followed by modules, but userspace can specify a specific section with the optional module_filter. Each call returns one match along with the match position, such that subsequent ioctl() calls can continue with a (position + 1) call.
2. KALLSYMS_QUERY_BY_ADDR: Finds the symbol that covers query_addr. A caller that needs an exact match can compare input, query_addr, with the output, sym_addr.

Both commands fill a shared struct kallsyms_query_sym, with fields:
address, size, and optional name and module buffers. Buffer lengths are in/out; on -ENAMETOOLONG the required sizes are still returned. As with the text file, return values adhere to the same permissions (such as at open() time), otherwise the ioctls fails with -EPERM.

For version compatibility, each struct carries its own size, so the command values do not change when the structs grow.

libbpf uses KALLSYMS_QUERY_BY_NAME to resolve typeless ksyms. It matches exact names plus "<name>.llvm." prefixes, as well as indicates if there is name ambiguitiy; this keeps the semantics identical, while still getting the performance benefit.

1. libbpf typeless ksym (8CPU Cuttlefish VM, BPF):

   Metric                      Text parse  KALLSYMS_QUERY   Change
   --------------------------  ----------  ---------------  ------------
   Resolve 11 typeless ksyms   152.6 ms    4.41 ms          ~35x

2. Perfetto symbolization (8CPU x86-64 VM, 175k-line):

   Metric                      Text parse  KALLSYMS_QUERY   Change
   --------------------------  ----------  ---------------  -------
   Init                        131.0 ms    0.04 ms          ~3000x
   50k symbolizations          28.6 ms     3.5 ms           ~8x
   traced_probes VmRSS         15.0 MB     4.5 MB           -70%
   traced_probes VmHWM         23.7 MB     4.5 MB           -80%

Note: Main reason v3 numbers are slower than v2 is that ambiguity resolution in libbpf requires extra ioctl() calls.

Changes in v3:
- Add new and missing ioctls in ioctl-number.rst (Randy)
- Split into two ioctls() BY_NAME and BY_ADDR (Andrii, David)
- Add shared struct for both commands (Andrii)
- Add optional name and module inputs (Andrii)
- Encode size 0 in commands and keep the sizes in structs (Andrii)
- Add an optional module_filter (Andrii)
- BY_NAME searches vmlinux, modules, ftrace, BPF JIT and kprobes (Andrii)
- Add one-by-one pagination for BY_NAME (Andrii, David)
- Add prefix matching (David)
- Do not return hidden BPF JIT symbols (bpf-ci)
- libbpf: retain semantics (match ".llvm", fail on ambiguous matches) and fall back to text parser on error (bpf-ci, Andrii)
- Added module_kallsyms_find_name() as a separate patch
- Selftests: report skips with a reason (sashiko)
- v2 link: https://lore.kernel.org/all/[email protected]/

Changes in v2:
- Replaced the BPF syscall approach in libbpf with the more generalizable KALLSYMS_QUERY ioctl() on /proc/kallsyms, per Andrii
- Added KALLSYMS_QUERY_BY_ADDR for address-to-symbol lookup
- Added proc and bpf selftests and procfs documentation
- v1 link: https://lore.kernel.org/all/[email protected]/

Samuel Wu (9):
Documentation: ioctl-number: Add PROCFS_IOCTL_MAGIC range 0x10-0x11
module: Add module_kallsyms_find_name()
kallsyms: Add KALLSYMS_QUERY_BY_NAME ioctl to /proc/kallsyms
kallsyms: Add KALLSYMS_QUERY_BY_ADDR ioctl to /proc/kallsyms docs/procfs: Document KALLSYMS_QUERY_* ioctls on /proc/kallsyms
tools: Copy KALLSYMS_QUERY_* definitions to linux/fs.h selftests/proc: Add KALLSYMS_QUERY_* ioctl tests
libbpf: Resolve typeless ksyms via KALLSYMS_QUERY_BY_NAME ioctl selftests/bpf: Test typeless module ksym resolution

 Documentation/filesystems/proc.rst            |   9 +
 .../userspace-api/ioctl/ioctl-number.rst      |   2 +
 include/linux/kallsyms.h                      |   7 +
 include/linux/module.h                        |  13 +
 include/uapi/linux/fs.h                       |  56 +++
 kernel/kallsyms.c                             | 379 ++++++++++++++++++
 kernel/module/kallsyms.c                      |  57 +++
 tools/include/uapi/linux/fs.h                 |  56 +++
 tools/lib/bpf/libbpf.c                        |  99 ++++-
 .../testing/selftests/bpf/prog_tests/ksyms.c  |   9 +
 .../testing/selftests/bpf/progs/test_ksyms.c  |   4 +
 tools/testing/selftests/proc/.gitignore       |   1 +
 tools/testing/selftests/proc/Makefile         |   1 +
 .../selftests/proc/proc-kallsyms-query.c      | 248 ++++++++++++
 14 files changed, 939 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/selftests/proc/proc-kallsyms-query.c
Signature · 1 line
2.56.0.679.gc527c65306-goog
author
#1 lore raw

PATCH v3 1/9 Documentation: ioctl-number: Add PROCFS_IOCTL_MAGIC range 0x10-0x11

PAGEMAP_SCAN (0x10) and PROCMAP_QUERY (0x11) use PROCFS_IOCTL_MAGIC. ext4 uses the same numbers on other files, so mark the row as a conflict.

---
 Documentation/userspace-api/ioctl/ioctl-number.rst | 1 +
 1 file changed, 1 insertion(+)
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
index dbe462040999..fbc3537fc9ee 100644
@@ -248,6 +248,7 @@ Code  Seq#    Include File                                             Comments
 'f'   00-0F  fs/ext4/ext4.h                                            conflict!
 'f'   00-0F  linux/fs.h                                                conflict!
 'f'   00-0F  fs/ocfs2/ocfs2_fs.h                                       conflict!
+'f'   10-11  linux/fs.h                                                conflict! procfs ioctls (PROCFS_IOCTL_MAGIC)
 'f'   13-27  linux/fscrypt.h
 'f'   81-8F  linux/fsverity.h
 'g'   00-0F  linux/usb/gadgetfs.h
Signature · 1 line
2.56.0.679.gc527c65306-goog
reviewer Reviewed-by on v3 1/9
#2 lore raw

Re: [PATCH bpf-next v3 1/9] Documentation: ioctl-number: Add PROCFS_IOCTL_MAGIC range 0x10-0x11

Quoted 6 lines · Samuel Wu

PAGEMAP_SCAN (0x10) and PROCMAP_QUERY (0x11) use PROCFS_IOCTL_MAGIC. ext4 uses the same numbers on other files, so mark the row as a conflict.

Thanks.

Quoted 16 lines
---
 Documentation/userspace-api/ioctl/ioctl-number.rst | 1 +
 1 file changed, 1 insertion(+)
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
index dbe462040999..fbc3537fc9ee 100644
@@ -248,6 +248,7 @@ Code  Seq#    Include File                                             Comments
 'f'   00-0F  fs/ext4/ext4.h                                            conflict!
 'f'   00-0F  linux/fs.h                                                conflict!
 'f'   00-0F  fs/ocfs2/ocfs2_fs.h                                       conflict!
+'f'   10-11  linux/fs.h                                                conflict! procfs ioctls (PROCFS_IOCTL_MAGIC)
 'f'   13-27  linux/fscrypt.h
 'f'   81-8F  linux/fsverity.h
 'g'   00-0F  linux/usb/gadgetfs.h
Signature · 1 line
~Randy
#3 lore raw

Re: [PATCH bpf-next v3 1/9] Documentation: ioctl-number: Add PROCFS_IOCTL_MAGIC range 0x10-0x11

In reply to Samuel Wu
Quoted 1 line · Samuel Wu

+'f' 10-11 linux/fs.h conflict! procfs ioctls (PROCFS_IOCTL_MAGIC)

Those are PAGEMAP_SCAN (16) and PROCMAP_QUERY (17) which are already in the tree. The two ioctls this series adds are 48 and 49, i.e., 'f' 30-31, and they aren't registered here at all. Please add them as well.

author
#4 lore raw

Re: [PATCH bpf-next v3 1/9] Documentation: ioctl-number: Add PROCFS_IOCTL_MAGIC range 0x10-0x11

Quoted 8 lines · Christian Brauner
Quoted 1 line · Samuel Wu

+'f' 10-11 linux/fs.h conflict! procfs ioctls (PROCFS_IOCTL_MAGIC)

Those are PAGEMAP_SCAN (16) and PROCMAP_QUERY (17) which are already in the tree. The two ioctls this series adds are 48 and 49, i.e., 'f' 30-31, and they aren't registered here at all. Please add them as well.

Patch 1/9 here only backfills the existing PAGEMAP_SCAN (16) and PROCMAP_QUERY (17) entries. 'f' 30-31 for 48 and 49 are respectively in patches 3/9 and 4/9, where their functionalities are added.

Patch 1/9 is standalone, so it can be picked up independently (or I can resend it separately).

Thanks!
Sam

author
#5 lore raw

PATCH v3 2/9 module: Add module_kallsyms_find_name()

In reply to Samuel Wu

KALLSYMS_QUERY_BY_NAME, added later in this series, needs to find a symbol name or prefix across module symbols in one pass. module_get_kallsym() walks the module list from the head and runs an export bsearch() for every symbol index.

Add module_kallsyms_find_name(), and put the shared query struct in linux/kallsyms.h, so we have a more efficient linear walk.

---
 include/linux/kallsyms.h |  7 +++++
 include/linux/module.h   | 13 +++++++++
 kernel/module/kallsyms.c | 57 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 77 insertions(+)
include/linux/kallsyms.h +7 -0
index d5dd54c53ace..d31f2f436159 100644
@@ -24,6 +24,13 @@
 struct cred;
 struct module;
 
+/* Exact or prefix name query, optionally in one module. */
+struct kallsyms_name_query {
+	const char *name;
+	size_t cmp_len;		/* bytes to compare; includes NUL if exact */
+	const char *modname;	/* NULL matches any module */
+};
+
 static inline int is_kernel_text(unsigned long addr)
 {
 	if (__is_kernel_text(addr))
include/linux/module.h +13 -0
index 76f4f3596477..07d5a74ecfcc 100644
@@ -42,6 +42,7 @@ struct modversion_info {
 
 struct module;
 struct exception_table_entry;
+struct kallsyms_name_query;
 
 struct module_kobject {
 	struct kobject kobj;
@@ -978,6 +979,10 @@ int lookup_module_symbol_attrs(unsigned long addr,
  */
 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
 		       char *name, char *module_name, int *exported);
+int module_kallsyms_find_name(unsigned int *symnum,
+			      const struct kallsyms_name_query *q,
+			      unsigned long *value, char *name,
+			      char *module_name);
 
 /* Look for this name: can be of form module:name. */
 unsigned long module_kallsyms_lookup_name(const char *name);
@@ -1016,6 +1021,14 @@ static inline int module_get_kallsym(unsigned int symnum, unsigned long *value,
 	return -ERANGE;
 }
 
+static inline int module_kallsyms_find_name(unsigned int *symnum,
+					    const struct kallsyms_name_query *q,
+					    unsigned long *value, char *name,
+					    char *module_name)
+{
+	return -ENOENT;
+}
+
 static inline unsigned long module_kallsyms_lookup_name(const char *name)
 {
 	return 0;
kernel/module/kallsyms.c +57 -0

63 lines not on this page · raw message

Signature · 1 line
2.56.0.679.gc527c65306-goog
author
#6 lore raw

PATCH v3 3/9 kallsyms: Add KALLSYMS_QUERY_BY_NAME ioctl to /proc/kallsyms

In reply to Samuel Wu

To find a few kernel symbols, users such as libbpf parse all of /proc/kallsyms, which is several MB and text based.

Add the KALLSYMS_QUERY_BY_NAME ioctl. It finds a symbol by exact name or by prefix in the entries of /proc/kallsyms, with vmlinux matches first, and optionally in a single module with module_filter, or all modules by default. Each call returns one match and its position; pos + 1 continues the search, until -ENOENT. The output returns the address, the size, and optional name and module buffers. A buffer that is too small gives -ENAMETOOLONG and the required size.

vmlinux symbols are found with a lower-bound binary search on the sorted names, module symbols in one pass, and ftrace, BPF, and kprobe symbols with the per-index getters that read() uses.

For versioning, the struct carries their sizes, so the command does not change when the struct grows.

The command uses 'f' 0x30; register 0x30 in ioctl-number.rst.

---
 .../userspace-api/ioctl/ioctl-number.rst      |   1 +
 include/uapi/linux/fs.h                       |  43 +++
 kernel/kallsyms.c                             | 319 ++++++++++++++++++
 3 files changed, 363 insertions(+)
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
index fbc3537fc9ee..f5dbb597257a 100644
@@ -250,6 +250,7 @@ Code  Seq#    Include File                                             Comments
 'f'   00-0F  fs/ocfs2/ocfs2_fs.h                                       conflict!
 'f'   10-11  linux/fs.h                                                conflict! procfs ioctls (PROCFS_IOCTL_MAGIC)
 'f'   13-27  linux/fscrypt.h
+'f'   30     linux/fs.h                                                procfs kallsyms ioctls (PROCFS_IOCTL_MAGIC)
 'f'   81-8F  linux/fsverity.h
 'g'   00-0F  linux/usb/gadgetfs.h
 'g'   20-2F  linux/usb/g_printer.h
include/uapi/linux/fs.h +43 -0

49 lines not on this page · raw message

kernel/kallsyms.c +319 -0

336 lines not on this page · raw message

Signature · 1 line
2.56.0.679.gc527c65306-goog
#7 lore raw

Re: [PATCH bpf-next v3 3/9] kallsyms: Add KALLSYMS_QUERY_BY_NAME ioctl to /proc/kallsyms

TL;DR: - KALLSYMS_QUERY_BY_NAME may scan BPF ksyms quadratically in one syscall with no cond_resched(), possibly cancelling the speedup - module_filter may return -ENOENT for init symbols that the…
Quoted 1 line

kallsyms: Add KALLSYMS_QUERY_BY_NAME ioctl to /proc/kallsyms

TL;DR:
- KALLSYMS_QUERY_BY_NAME may scan BPF ksyms quadratically in one syscall with no cond_resched(), possibly cancelling the speedup
- module_filter may return -ENOENT for init symbols that the unfiltered query finds via the ftrace section

Quoted 3 lines
kernel/kallsyms.c +0 -0

[ ... ]

Quoted 4 lines
kernel/kallsyms.c +4 -0
+static int kallsyms_find_name_other(unsigned int sec, unsigned int *idx,
+				    const struct kallsyms_name_query *q,
+				    struct kallsyms_sym_match *m)
+{

[ ... ]

kernel/kallsyms.c const char *kdb_walk_kallsyms(loff_t *pos) · line 1114

Quoted 13 lines
kernel/kallsyms.c +13 -0
+	do {
+		if (sec == KSYM_SEC_BPF)
+			err = bpf_get_kallsym(*idx, &m->addr, &type, m->name);
+		else if (sec == KSYM_SEC_KPROBE)
+			err = kprobe_get_kallsym(*idx, &m->addr, &type, m->name);
+		else
+			err = ftrace_mod_get_kallsym(*idx, &m->addr, &type,
+						     m->name, m->modname,
+						     &exported);
+		if (!err && !strncmp(m->name, q->name, q->cmp_len))
+			return 0;
+		(*idx)++;
+	} while (!err);

Is this loop quadratic in the number of BPF ksyms, with no reschedule point?

bpf_get_kallsym() restarts from the list head on every call and walks forward to the index:

    list_for_each_entry_rcu(ksym, &bpf_kallsyms, lnode) {
        if (it++ != symnum)
            continue;

So one ioctl that scans the BPF section without a match does n(n+1)/2 list steps inside a single syscall. Every exhaustive query gets there, since even a query whose matches are all in vmlinux or modules still scans the ftrace, BPF and kprobe sections on the call that returns -ENOENT.

The uapi comment tells users to keep calling with pos + 1 until -ENOENT, and the libbpf user later in this series (822e9da9a9b7 "libbpf: Resolve typeless ksyms via KALLSYMS_QUERY_BY_NAME ioctl") does this twice per typeless extern, once for the exact name and once for the "<name>.llvm." prefix.

With read() of /proc/kallsyms the same getter cost is spread across syscalls, because seq_read fills at most one seq_file buffer per call. Here all of it lands in each call that reaches the BPF section. On hosts with thousands of BPF programs and trampolines, does this cancel the speedup the commit message describes?

On kernels without ARCH_HAS_PREEMPT_LAZY, or with ARCH_NO_PREEMPT, it is also a long run with no reschedule, whereas kallsyms_on_each_symbol() and kallsyms_on_each_match_symbol() in this file call cond_resched().

Would a helper that walks bpf_kallsyms once from a start index be better, or at least a cond_resched() in this loop? ftrace_mod_get_kallsym() has the same restart-from-the-beginning pattern, although its lists are usually small.

[ ... ]

kernel/kallsyms.c const char *kdb_walk_kallsyms(loff_t *pos) · line 1213

Quoted 13 lines
kernel/kallsyms.c +13 -0
+	if (karg.module_filter) {
+		len = kallsyms_copy_str_from_user(bufs->module_filter,
+						  sizeof(bufs->module_filter),
+						  karg.module_filter);
+		if (len < 0)
+			return len;
+		if (!strcmp(bufs->module_filter, "vmlinux")) {
+			end_sec = KSYM_SEC_VMLINUX + 1;
+		} else {
+			first_sec = KSYM_SEC_MODULE;
+			end_sec = KSYM_SEC_MODULE + 1;
+			q.modname = bufs->module_filter;
+		}

Can module_filter return -ENOENT for a symbol that the unfiltered query finds in the same module?

When a module name is given, only KSYM_SEC_MODULE is searched. But /proc/kallsyms also lists entries for a loaded module from the ftrace section. ftrace_free_mem(), called from do_init_module() for the module's init text, runs allocate_ftrace_mod_map() when any ftrace_ops is registered, and ftrace_mod_get_kallsym() returns those entries with strscpy(module_name, mod_map->mod->name, ...). They appear as, for example:

    ffffffffc0a01000 T foo_init [foo]

and remain until the module is unloaded, because ftrace_release_mod() frees the map then. After init, mod->kallsyms has switched to core_kallsyms, so these init symbols are no longer in the module section. That gives:

    BY_NAME("foo_init", module_filter = NULL)  -> match, sym_module = "foo"
    BY_NAME("foo_init", module_filter = "foo") -> -ENOENT

The uapi comment says the ioctl finds a symbol "in the entries of /proc/kallsyms", so the filtered result does not look like the unfiltered result limited to [foo]. kallsyms_find_name_other() does not check q->modname for the ftrace section, so extending end_sec alone would not be enough.

Should the filtered case also search KSYM_SEC_FTRACE and skip entries whose m->modname differs from q->modname, or should the uapi comment document that module_filter only covers the module's own symbol table?

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

author
#8 lore raw

PATCH v3 4/9 kallsyms: Add KALLSYMS_QUERY_BY_ADDR ioctl to /proc/kallsyms

In reply to Samuel Wu

Symbolizers such as Perfetto read all of /proc/kallsyms and keep a sorted copy in memory to resolve addresses.

Add the KALLSYMS_QUERY_BY_ADDR ioctl. It returns the symbol that covers an address, from the same sources and in the same order as %pS. BPF JIT symbols are hidden when /proc/kallsyms hides them. query_flags must be 0; it is reserved for other modes.

The command uses 'f' 0x31; register 0x31 in ioctl-number.rst.

---
 .../userspace-api/ioctl/ioctl-number.rst      |  2 +-
 include/uapi/linux/fs.h                       | 13 ++++
 kernel/kallsyms.c                             | 60 +++++++++++++++++++
 3 files changed, 74 insertions(+), 1 deletion(-)
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -1
index f5dbb597257a..d9b66e7a29b7 100644
@@ -250,7 +250,7 @@ Code  Seq#    Include File                                             Comments
 'f'   00-0F  fs/ocfs2/ocfs2_fs.h                                       conflict!
 'f'   10-11  linux/fs.h                                                conflict! procfs ioctls (PROCFS_IOCTL_MAGIC)
 'f'   13-27  linux/fscrypt.h
-'f'   30     linux/fs.h                                                procfs kallsyms ioctls (PROCFS_IOCTL_MAGIC)
+'f'   30-31  linux/fs.h                                                procfs kallsyms ioctls (PROCFS_IOCTL_MAGIC)
 'f'   81-8F  linux/fsverity.h
 'g'   00-0F  linux/usb/gadgetfs.h
 'g'   20-2F  linux/usb/g_printer.h
include/uapi/linux/fs.h +13 -0
index 987569dcdbea..c1a63c8560e2 100644
@@ -676,6 +676,7 @@ struct procmap_query {
 
 /* /proc/kallsyms ioctls. -EPERM if the opener cannot see kernel addresses. */
 #define KALLSYMS_QUERY_BY_NAME	_IOC(_IOC_READ | _IOC_WRITE, PROCFS_IOCTL_MAGIC, 48, 0)
+#define KALLSYMS_QUERY_BY_ADDR	_IOC(_IOC_READ | _IOC_WRITE, PROCFS_IOCTL_MAGIC, 49, 0)
 
 enum kallsyms_query_flags {
 	/* Match query_name as a prefix. */
@@ -717,6 +718,18 @@ struct kallsyms_query_by_name {
 	__u64 sym_struct_size;	/* in - sizeof(struct kallsyms_query_sym) */
 };
 
+/*
+ * Find the /proc/kallsyms entry that covers query_addr, or return -ENOENT.
+ * ftrace trampolines and kprobe pages are not resolved yet.
+ */
+struct kallsyms_query_by_addr {
+	__u64 size;		/* in - sizeof(struct kallsyms_query_by_addr) */
+	__u64 query_flags;	/* in - must be 0 */
+	__u64 query_addr;	/* in - kernel address */
+	__u64 sym;		/* in - user ptr to struct kallsyms_query_sym */
+	__u64 sym_struct_size;	/* in - sizeof(struct kallsyms_query_sym) */
+};
+
 /*
  * Shutdown the filesystem.
  */
kernel/kallsyms.c +60 -0

72 lines not on this page · raw message

Signature · 1 line
2.56.0.679.gc527c65306-goog
author
#9 lore raw

PATCH v3 5/9 docs/procfs: Document KALLSYMS_QUERY_* ioctls on /proc/kallsyms

In reply to Samuel Wu

Add kallsyms to the /proc file table, and a short section that refers to the KALLSYMS_QUERY_* definitions in include/uapi/linux/fs.h.

---
 Documentation/filesystems/proc.rst | 9 +++++++++
 1 file changed, 9 insertions(+)
Documentation/filesystems/proc.rst +9 -0
index fa7a468e8edf..442aae9ebd9e 100644
@@ -761,6 +761,7 @@ files are there, and which are missing.
  ioports      I/O port usage
  irq 	      Masks for irq to cpu affinity			(2.4)(smp?)
  isapnp       ISA PnP (Plug&Play) Info				(2.4)
+ kallsyms     All kernel symbols (see text)
  kcore        Kernel core image (can be ELF or A.OUT(deprecated in 2.4))
  kmsg         Kernel messages
  ksyms        Kernel symbol table
@@ -1368,6 +1369,14 @@ Provides counts of softirq handlers serviced since boot time, for each CPU.
     HRTIMER:         0          0          0          0
 	RCU:      1678       1769       2178       2250
 
+kallsyms
+~~~~~~~~
+
+Lists the kernel symbols of vmlinux, loaded modules, and dynamic sources such
+as BPF JIT images. The ``KALLSYMS_QUERY_BY_NAME`` and ``KALLSYMS_QUERY_BY_ADDR``
+ioctls find one symbol by name or by address without parsing the text. See
+``include/uapi/linux/fs.h`` for their structs and errors.
+
 1.3 Networking info in /proc/net
 --------------------------------
 
Signature · 1 line
2.56.0.679.gc527c65306-goog
author
#10 lore raw

PATCH v3 6/9 tools: Copy KALLSYMS_QUERY_* definitions to linux/fs.h

In reply to Samuel Wu

Copy the KALLSYMS_QUERY_* definitions from include/uapi/linux/fs.h for the proc selftests.

---
 tools/include/uapi/linux/fs.h | 56 +++++++++++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)
tools/include/uapi/linux/fs.h +56 -0
index f0a26309b6d5..286e82c61189 100644
@@ -567,4 +567,60 @@ struct procmap_query {
 	__u64 build_id_addr;		/* in */
 };
 
+/* /proc/kallsyms ioctls. -EPERM if the opener cannot see kernel addresses. */
+#define KALLSYMS_QUERY_BY_NAME	_IOC(_IOC_READ | _IOC_WRITE, PROCFS_IOCTL_MAGIC, 48, 0)
+#define KALLSYMS_QUERY_BY_ADDR	_IOC(_IOC_READ | _IOC_WRITE, PROCFS_IOCTL_MAGIC, 49, 0)
+
+enum kallsyms_query_flags {
+	/* Match query_name as a prefix. */
+	KALLSYMS_QUERY_NAME_PREFIX = 0x01,
+};
+
+/*
+ * Symbol returned by a query. Each buffer pointer and its *_len must both be
+ * set or both be 0. When set, the kernel sets *_len to the string size
+ * including the NUL, even if the buffer is too small and the ioctl fails with
+ * -ENAMETOOLONG. The module name of a vmlinux symbol is "".
+ */
+struct kallsyms_query_sym {
+	__u64 sym_addr;		/* out - start address */
+	__u64 sym_size;		/* out - bytes to next symbol, 0 if unknown */
+	__u64 sym_name;		/* in - user ptr to name buffer, or 0 */
+	__u64 sym_name_len;	/* in/out - buffer size / string size */
+	__u64 sym_module;	/* in - user ptr to module name buffer, or 0 */
+	__u64 sym_module_len;	/* in/out - buffer size / string size */
+};
+
+/*
+ * Find a symbol by exact name, or by prefix with KALLSYMS_QUERY_NAME_PREFIX,
+ * in the entries of /proc/kallsyms, except undefined module symbols. vmlinux
+ * matches come first. A module_filter of "vmlinux" selects the core kernel.
+ *
+ * Each call returns one match and sets pos to its position, even on
+ * -ENAMETOOLONG. Start with pos 0 and use pos + 1 for the next match, until
+ * -ENOENT. Use pos only with the same query. Matches can be skipped or
+ * repeated if symbols change between calls.
+ */
+struct kallsyms_query_by_name {
+	__u64 size;		/* in - sizeof(struct kallsyms_query_by_name) */
+	__u64 query_flags;	/* in - enum kallsyms_query_flags */
+	__u64 query_name;	/* in - user ptr to name or prefix */
+	__u64 module_filter;	/* in - user ptr to loaded module name, or 0 */
+	__u64 pos;		/* in/out - start position / match position */
+	__u64 sym;		/* in - user ptr to struct kallsyms_query_sym */
+	__u64 sym_struct_size;	/* in - sizeof(struct kallsyms_query_sym) */
+};
+
+/*
+ * Find the /proc/kallsyms entry that covers query_addr, or return -ENOENT.
+ * ftrace trampolines and kprobe pages are not resolved yet.
+ */
+struct kallsyms_query_by_addr {
+	__u64 size;		/* in - sizeof(struct kallsyms_query_by_addr) */
+	__u64 query_flags;	/* in - must be 0 */
+	__u64 query_addr;	/* in - kernel address */
+	__u64 sym;		/* in - user ptr to struct kallsyms_query_sym */
+	__u64 sym_struct_size;	/* in - sizeof(struct kallsyms_query_sym) */
+};
+
 #endif /* _UAPI_LINUX_FS_H */
Signature · 1 line
2.56.0.679.gc527c65306-goog
author
#11 lore raw

PATCH v3 7/9 selftests/proc: Add KALLSYMS_QUERY_* ioctl tests

In reply to Samuel Wu

Test KALLSYMS_QUERY_BY_NAME and KALLSYMS_QUERY_BY_ADDR against the /proc/kallsyms text: exact and prefix names, iteration with pos and retry after -ENAMETOOLONG, module_filter, vmlinux and module symbols, struct size extension, and invalid input. Skip if the ioctls are missing or addresses are hidden.

---
 tools/testing/selftests/proc/.gitignore       |   1 +
 tools/testing/selftests/proc/Makefile         |   1 +
 .../selftests/proc/proc-kallsyms-query.c      | 248 ++++++++++++++++++
 3 files changed, 250 insertions(+)
 create mode 100644 tools/testing/selftests/proc/proc-kallsyms-query.c
tools/testing/selftests/proc/.gitignore +1 -0
index 9c9735570abf..1762c28f524c 100644
@@ -4,6 +4,7 @@
 /fd-003-kthread
 /proc-2-is-kthread
 /proc-fsconfig-hidepid
+/proc-kallsyms-query
 /proc-loadavg-001
 /proc-maps-race
 /proc-multiple-procfs
tools/testing/selftests/proc/Makefile +1 -0
index a7de2bb6d8be..dc3c28e6b83b 100644
@@ -29,6 +29,7 @@ TEST_GEN_PROGS += setns-sysvipc
 TEST_GEN_PROGS += thread-self
 TEST_GEN_PROGS += proc-multiple-procfs
 TEST_GEN_PROGS += proc-fsconfig-hidepid
+TEST_GEN_PROGS += proc-kallsyms-query
 TEST_GEN_PROGS += proc-pidns
 
 include ../lib.mk
tools/testing/selftests/proc/proc-kallsyms-query.c new file +248 -0

248 lines not on this page · raw message

Signature · 1 line
2.56.0.679.gc527c65306-goog
#12 lore raw

Re: [PATCH bpf-next v3 7/9] selftests/proc: Add KALLSYMS_QUERY_* ioctl tests

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] selftests/proc: main() bypasses kselftest reporting and harness helpers --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] selftests/proc: main() bypasses kselftest reporting and harness helpers
--

commit cea94aa72f17dbd75f99a6a582f1fe997f0b838e
Author: Samuel Wu <[email protected]>

selftests/proc: Add KALLSYMS_QUERY_* ioctl tests

This commit adds a selftest for the KALLSYMS_QUERY_BY_NAME and KALLSYMS_QUERY_BY_ADDR ioctls on /proc/kallsyms.

Quoted 5 lines
tools/testing/selftests/proc/proc-kallsyms-query.c new file +0 -0
new file mode 100644
index 0000000000000..7788cb0f30f83

[ ... ]

Quoted 41 lines
tools/testing/selftests/proc/proc-kallsyms-query.c new file +41 -0
+int main(void)
+{
+	struct {
+		struct kallsyms_query_by_name q;
+		__u64 extra;
+	} qx = {};
+	struct {
+		struct kallsyms_query_sym s;
+		__u64 extra;
+	} sx = {};
+	struct kallsyms_query_by_addr qa;
+	struct kallsyms_query_by_name q;
+	struct kallsyms_query_sym sym;
+	unsigned int cnt = 0;
+	__u64 first_pos = 0;
+	char name[512];
+	__u64 size;
+	__u64 len;
+	int err;
+	int fd;
+
+	fd = open("/proc/kallsyms", O_RDONLY | O_CLOEXEC);
+	if (fd < 0)
+		ksft_exit_skip("open(/proc/kallsyms): %s\n", strerror(errno));
+	scan_text();
+	if (!ref.vfs_read_found)
+		ksft_exit_skip("vfs_read is not in /proc/kallsyms\n");
+
+	/* Exact name in vmlinux, with name and module buffers */
+	sym = bufs(sizeof(name_buf), sizeof(mod_buf));
+	q = name_q("vfs_read", "vmlinux", &sym);
+	err = by_name(fd, &q);
+	if (err == -ENOTTY)
+		ksft_exit_skip("KALLSYMS_QUERY_BY_NAME is not supported\n");
+	if (!ref.vfs_read_addr) {
+		qa = addr_q(0, &sym);
+		assert(err == -EPERM && by_addr(fd, &qa) == -EPERM);
+		ksft_exit_skip("kallsyms addresses are hidden\n");
+	}
+	assert(!err);
+	assert(sym.sym_addr == ref.vfs_read_addr && sym.sym_size > 0);

[ ... ]

tools/testing/selftests/proc/proc-kallsyms-query.c line 248

Quoted 3 lines
tools/testing/selftests/proc/proc-kallsyms-query.c new file +3 -0
+	close(fd);
+	return 0;
+}

[Severity: Low]
Could this test use kselftest_harness.h (FIXTURE(), TEST_F(), and the ASSERT_*/EXPECT_* macros) or the kselftest.h result helpers (ksft_print_header(), ksft_set_plan(), ksft_test_result_*(), and ksft_finished()) instead of running sequential raw assert() checks in main() and exiting with a bare return 0? As written, a normal run emits no KTAP plan or result lines, and any failed check aborts the process with SIGABRT rather than reporting which subtest failed.

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

PATCH v3 8/9 libbpf: Resolve typeless ksyms via KALLSYMS_QUERY_BY_NAME ioctl

In reply to Samuel Wu

libbpf parses all of /proc/kallsyms to resolve typeless ksyms.

Use KALLSYMS_QUERY_BY_NAME instead: exact names, plus "<name>.llvm." prefix matches. Ambiguous matches at different addresses fail the load. A missing strong extern still fails and a missing weak extern is 0, without a text scan.

On any other error (e.g. -ENOTTY on older kernels, or -EPERM), fall back to the text parser.

---
 tools/lib/bpf/libbpf.c | 99 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 97 insertions(+), 2 deletions(-)
tools/lib/bpf/libbpf.c +97 -2
index 44134421bd7d..f3f3475a64d3 100644
@@ -59,6 +59,34 @@
 #define BPF_FS_MAGIC		0xcafe4a11
 #endif
 
+#ifndef KALLSYMS_QUERY_BY_NAME
+/* 'f' is PROCFS_IOCTL_MAGIC */
+#define KALLSYMS_QUERY_BY_NAME	_IOC(_IOC_READ | _IOC_WRITE, 'f', 48, 0)
+
+enum kallsyms_query_flags {
+	KALLSYMS_QUERY_NAME_PREFIX = 0x01,
+};
+
+struct kallsyms_query_sym {
+	__u64 sym_addr;
+	__u64 sym_size;
+	__u64 sym_name;
+	__u64 sym_name_len;
+	__u64 sym_module;
+	__u64 sym_module_len;
+};
+
+struct kallsyms_query_by_name {
+	__u64 size;
+	__u64 query_flags;
+	__u64 query_name;
+	__u64 module_filter;
+	__u64 pos;
+	__u64 sym;
+	__u64 sym_struct_size;
+};
+#endif
+
 #define MAX_EVENT_NAME_LEN	64
 
 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
@@ -9421,8 +9449,75 @@ static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
 	return 0;
 }
 
-static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
+static int query_ksym_by_name(int fd, struct extern_desc *ext, bool lto_prefix)
+{
+	struct kallsyms_query_sym sym = {};
+	struct kallsyms_query_by_name q = {
+		.size = sizeof(q),
+		.query_flags = lto_prefix ? KALLSYMS_QUERY_NAME_PREFIX : 0,
+		.query_name = ptr_to_u64(ext->name),
+		.sym = ptr_to_u64(&sym),
+		.sym_struct_size = sizeof(sym),
+	};
+	char prefix_buf[512];
+	int n;
+
+	if (lto_prefix) {
+		n = snprintf(prefix_buf, sizeof(prefix_buf), "%s.llvm.", ext->name);
+		if (n < 0 || n >= sizeof(prefix_buf))
+			return 0;
+		q.query_name = ptr_to_u64(prefix_buf);
+	}
+
+	while (!ioctl(fd, KALLSYMS_QUERY_BY_NAME, &q)) {
+		if (!ext->is_set) {
+			ext->is_set = true;
+			ext->ksym.addr = sym.sym_addr;
+			pr_debug("extern (ksym) '%s': set to 0x%llx\n",
+				 ext->name, ext->ksym.addr);
+		} else if (sym.sym_addr != ext->ksym.addr) {
+			pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
+				ext->name, ext->ksym.addr,
+				(unsigned long long)sym.sym_addr);
+			return -EADDRNOTAVAIL;
+		}
+		q.pos++;
+	}
+
+	return errno == ENOENT ? 0 : -errno;
+}
+
+static int bpf_object__resolve_typeless_ksyms(struct bpf_object *obj)
 {
+	struct extern_desc *ext;
+	int err = 0;
+	int fd;
+	int i;
+
+	fd = open("/proc/kallsyms", O_RDONLY | O_CLOEXEC);
+	if (fd < 0) {
+		err = -errno;
+		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
+		return err;
+	}
+
+	for (i = 0; i < obj->nr_extern && !err; i++) {
+		ext = &obj->externs[i];
+		if (ext->type != EXT_KSYM || ext->ksym.type_id)
+			continue;
+
+		/* Check exact name and then LTO .llvm.<hash> prefix */
+		err = query_ksym_by_name(fd, ext, false);
+		if (!err)
+			err = query_ksym_by_name(fd, ext, true);
+	}
+	close(fd);
+	if (!err || err == -EADDRNOTAVAIL)
+		return err;
+
+	/* Other errors (e.g. -ENOTTY, -EPERM): parse the text file */
+	pr_debug("KALLSYMS_QUERY_BY_NAME failed (%s), falling back to /proc/kallsyms\n",
+		 errstr(err));
 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
 }
 
@@ -9699,7 +9794,7 @@ static int bpf_object__resolve_externs(struct bpf_object *obj,
 			return -EINVAL;
 	}
 	if (need_kallsyms) {
-		err = bpf_object__read_kallsyms_file(obj);
+		err = bpf_object__resolve_typeless_ksyms(obj);
 		if (err)
 			return -EINVAL;
 	}
Signature · 1 line
2.56.0.679.gc527c65306-goog
author
#14 lore raw

PATCH v3 9/9 selftests/bpf: Test typeless module ksym resolution

In reply to Samuel Wu

The module ksym tests use typed ksyms, which libbpf resolves through BTF. Add a weak typeless module ksym to the ksyms test, to cover the module path of KALLSYMS_QUERY_BY_NAME.

---
 tools/testing/selftests/bpf/prog_tests/ksyms.c | 9 +++++++++
 tools/testing/selftests/bpf/progs/test_ksyms.c | 4 ++++
 2 files changed, 13 insertions(+)
tools/testing/selftests/bpf/prog_tests/ksyms.c +9 -0
index dc7aab532fb1..801d38560473 100644
@@ -11,6 +11,7 @@ void test_ksyms(void)
 	struct test_ksyms *skel;
 	struct test_ksyms__data *data;
 	__u64 link_fops_addr, per_cpu_start_addr;
+	__u64 testmod_ksym_addr = 0;
 	struct stat st;
 	__u64 btf_size;
 	int err;
@@ -27,6 +28,12 @@ void test_ksyms(void)
 	if (!ASSERT_NEQ(err, -ENOENT, "__per_cpu_start: ksym_find"))
 		return;
 
+	if (env.has_testmod &&
+	    !ASSERT_OK(kallsyms_find("bpf_testmod_ksym_percpu",
+				     &testmod_ksym_addr),
+		       "bpf_testmod_ksym_percpu: kallsyms_find"))
+		return;
+
 	if (!ASSERT_OK(stat(btf_path, &st), "stat_btf"))
 		return;
 	btf_size = st.st_size;
@@ -47,6 +54,8 @@ void test_ksyms(void)
 	ASSERT_EQ(data->out__bpf_link_fops1, 0, "bpf_link_fops1");
 	ASSERT_EQ(data->out__btf_size, btf_size, "btf_size");
 	ASSERT_EQ(data->out__per_cpu_start, per_cpu_start_addr, "__per_cpu_start");
+	ASSERT_EQ(data->out__bpf_testmod_ksym_percpu, testmod_ksym_addr,
+		  "bpf_testmod_ksym_percpu");
 
 cleanup:
 	test_ksyms__destroy(skel);
tools/testing/selftests/bpf/progs/test_ksyms.c +4 -0
index 6c9cbb5a3bdf..0506bb574c4a 100644
@@ -9,6 +9,7 @@ __u64 out__bpf_link_fops = -1;
 __u64 out__bpf_link_fops1 = -1;
 __u64 out__btf_size = -1;
 __u64 out__per_cpu_start = -1;
+__u64 out__bpf_testmod_ksym_percpu = -1;
 
 extern const void bpf_link_fops __ksym;
 extern const void __start_BTF __ksym;
@@ -16,6 +17,8 @@ extern const void __stop_BTF __ksym;
 extern const void __per_cpu_start __ksym;
 /* non-existing symbol, weak, default to zero */
 extern const void bpf_link_fops1 __ksym __weak;
+/* module symbol, weak, zero if bpf_testmod is not loaded */
+extern const void bpf_testmod_ksym_percpu __ksym __weak;
 
 SEC("raw_tp/sys_enter")
 int handler(const void *ctx)
@@ -25,6 +28,7 @@ int handler(const void *ctx)
 	out__per_cpu_start = (__u64)&__per_cpu_start;
 
 	out__bpf_link_fops1 = (__u64)&bpf_link_fops1;
+	out__bpf_testmod_ksym_percpu = (__u64)&bpf_testmod_ksym_percpu;
 
 	return 0;
 }
Signature · 1 line
2.56.0.679.gc527c65306-goog
#15 lore raw
In reply to Samuel Wu
Quoted 4 lines · On Fri, 13 Nov 2026 14:12:45 -0800 Samuel Wu <[email protected]> wrote:

/proc/kallsyms is the primary interface for userspace to query the kernel symbol table. However, resolving even a handful of symbols or addresses requires reading and parsing the entire text file, which is often several megabytes and takes thousands of read() syscalls.

Separate from this, I've wondered about separating out the /proc/kallsyms code from the code that actually handles the symbol table itself. The two parts are pretty much separate.
IIRC it uses a static function to get the symbol type (which does most of the work of getting the name - which it also wants) so it isn't completely trivial.

I'm pretty sure all (well almost all) the changes will be lower down the file than my changes and won't cause (hard) conflicts.

I've been compiling kernel/kallsyms.c and kernel_kallsyms_selftests.c in userspace for testing both, but had to cut the bottom off kallsyms.c to get it to compile with a sane number of definitions.

David

author
#16 lore raw
Quoted 16 lines · David Laight
Quoted 4 lines · On Fri, 13 Nov 2026 14:12:45 -0800 Samuel Wu <[email protected]> wrote:

/proc/kallsyms is the primary interface for userspace to query the kernel symbol table. However, resolving even a handful of symbols or addresses requires reading and parsing the entire text file, which is often several megabytes and takes thousands of read() syscalls.

Separate from this, I've wondered about separating out the /proc/kallsyms code from the code that actually handles the symbol table itself. The two parts are pretty much separate.
IIRC it uses a static function to get the symbol type (which does most of the work of getting the name - which it also wants) so it isn't completely trivial.

Quoted 8 lines

I'm pretty sure all (well almost all) the changes will be lower down the file than my changes and won't cause (hard) conflicts.

I've been compiling kernel/kallsyms.c and kernel_kallsyms_selftests.c in userspace for testing both, but had to cut the bottom off kallsyms.c to get it to compile with a sane number of definitions.

David

You mean separating the core symbol code (top of file) from the procfs interface (bottom of file) into two separate files, right? If so, seems reasonable to me, especially since the file is approaching 1000 lines even before our changes.

And agree, even with both our patches, most functions can remain static in their new homes.

#17 lore raw
Quoted 27 lines · On Mon, 16 Nov 2026 19:15:11 -0800 Samuel Wu <[email protected]> wrote:
Quoted 16 lines · David Laight
Quoted 4 lines · On Fri, 13 Nov 2026 14:12:45 -0800 Samuel Wu <[email protected]> wrote:

/proc/kallsyms is the primary interface for userspace to query the kernel symbol table. However, resolving even a handful of symbols or addresses requires reading and parsing the entire text file, which is often several megabytes and takes thousands of read() syscalls.

Separate from this, I've wondered about separating out the /proc/kallsyms code from the code that actually handles the symbol table itself. The two parts are pretty much separate.
IIRC it uses a static function to get the symbol type (which does most of the work of getting the name - which it also wants) so it isn't completely trivial.

Quoted 8 lines

I'm pretty sure all (well almost all) the changes will be lower down the file than my changes and won't cause (hard) conflicts.

I've been compiling kernel/kallsyms.c and kernel_kallsyms_selftests.c in userspace for testing both, but had to cut the bottom off kallsyms.c to get it to compile with a sane number of definitions.

David

Quoted 7 lines

You mean separating the core symbol code (top of file) from the procfs interface (bottom of file) into two separate files, right? If so, seems reasonable to me, especially since the file is approaching 1000 lines even before our changes.

And agree, even with both our patches, most functions can remain static in their new homes.

I just tried it (on 7.4-rc1).
Only had to make kallsymbols_get_symbol_type(), kallsymbols_expand_symbol() and get_symbol_offset() non-static (added to kallsyms_internal.h) and split the file before the definition of kallysms_iter.
Then tidied up a few #includes.

I've found a much bigger problem though.
All the sprint_symbol() functions do unchecked writes into the caller supplied buffer (no length is passed).
While the buffer is (usually) long enough for the name, there isn't guaranteed to be enough space for the "+0xoffset [modulename buildid]" that might easily be another 60 characters.

Some of the people who have modified that code recently really ought to have fixed it.

David