Skip to contentSkip to conversation

kallsyms: embed source file:line info in kernel stack traces

PATCH New Sasha Levin 2 participants 9 messages Aug 1

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v8 cover kallsyms: embed source file:line info in kernel stack traces

CONFIG_KALLSYMS_LINEINFO embeds a compact address-to-line lookup table in the kernel image so stack traces print source locations directly, without decode_stacktrace.sh or a vmlinux with debug info at runtime:

  default_idle+0x9/0x10 (arch/x86/kernel/process.c:768)
  default_idle_call+0x2e/0x100 (kernel/sched/idle.c:122)
  do_idle+0x20b/0x2b0 (kernel/sched/idle.c:199)
  cpu_startup_entry+0x24/0x30 (kernel/sched/idle.c:453)
  rest_init+0xbc/0xc0 (init/main.c:717)
  common_startup_64+0x13e/0x158 (arch/x86/kernel/head_64.S:418)

Patch 2 extends this to loadable modules, patch 3 delta-compresses the tables, patch 4 adds KUnit coverage.

Changes since v7
================

Two bugs turned up while working through Petr's review:

- Module lineinfo blobs were malformed. emit_section_table() emitted the .Lhdr label before its .balign 4, so the kernel read each sub-table header 1-3 bytes early. 5 of the 7 modules with two covered text sections were affected here, kvm-intel.ko among them, which silently lost .exit.text annotation. Fixed in 2/4, with IS_ALIGNED() rejects on the kernel side so a bad blob degrades instead of faulting in NMI context.

- v7's symbol-boundary check over-corrected, dropping annotation for 5017 functions -- 1542 .cold fragments, all __probestub_*, the __ia32_sys_* compat wrappers -- which v6 printed correctly. gen_lineinfo now keeps an entry at every symbol start and synthesizes one where the compiler emitted none, gated so that __pfx_* padding stubs and __SCT__* trampolines stay unannotated. Costs +0.12% entries.

From Petr Pavlu's review of 1/4:

- Size figures were measured on an unstripped vmlinux. Redone with x86_64_defconfig + CONFIG_DEBUG_INFO, recipe stated inline:
51.1 -> 69.1 MiB before the compression in 3/4, 51.1 -> 59.1 MiB with it.
- Paths are made relative to $objtree/$srctree/$srcroot (read with getenv(), so no Makefile change) rather than by scanning for well-known top-level directory names; kernel_dirs[] stays as a fallback.
- Private hash map replaced with scripts/include/hashtable.h.
- xalloc.h for every allocation; the unchecked strdup() is gone.
- ELF_C_READ_MMAP, and ELF_C_READ_MMAP_PRIVATE for modules, which lets module mode drop O_RDWR.
- Error handling unified on warn()/error(); main() no longer unwinds.
- Statistics output moved behind -v / KBUILD_VERBOSE.
- libelf named alongside libdw everywhere; Arch package corrected.
- raw_offset/raw_min narrowed to unsigned long.
- Dropped the unused -lz from HOSTLDLIBS_gen_lineinfo.
- ARRAY_SIZE() instead of open-coded sizeof/sizeof.

Also:

- 2/4 no longer documents the delta compression that 3/4 introduces.
- scripts/kallsyms.c matches the lineinfo symbols by prefix; two of them had been leaking into /proc/kallsyms.
- alloc_sym_buf() asserts on allocation failure, and a new KUnit case pins the symbol-boundary contract the generator relies on.

Testing
=======

x86_64_defconfig + CONFIG_DEBUG_INFO, booted under QEMU/KVM:

- KUnit, CONFIG_LINEINFO_KUNIT_TEST=y builtin:
31 passed, 0 failed, 1 skipped
- KUnit, =m with CONFIG_KALLSYMS_LINEINFO_MODULES=y:
30 passed, 0 failed, 2 skipped
- KUnit, =m with CONFIG_KALLSYMS_LINEINFO_MODULES=n:
12 passed, 0 failed, 20 skipped (skips rather than fails, as intended)
- SysRq-l backtraces annotated, including .S frames and header inlines
- Module frames annotated, e.g.:

    test_dump_stack_no_crash+0xd/0xe80 [lineinfo_kunit]
      (lib/tests/lineinfo_kunit.c:681)

- Every .ko sub-table header 4-byte aligned (8 modules with 2 descriptors); was 5 of 7 misaligned before
- Coverage cross-checked against addr2line
- Each of the four patches builds standalone (vmlinux + modules), and 1/4 alone boots with working annotations
- ARCH=i386 W=2 build of kernel/kallsyms.o and kernel/module/kallsyms.o is clean, covering the 32-bit paths touched here

Sasha Levin (4):
kallsyms: embed source file:line info in kernel stack traces
kallsyms: extend lineinfo to loadable modules
kallsyms: delta-compress lineinfo tables for ~2.7x size reduction
kallsyms: add KUnit tests for lineinfo feature

 Documentation/admin-guide/index.rst           |    1 +
 .../admin-guide/kallsyms-lineinfo.rst         |   97 +
 MAINTAINERS                                   |    9 +
 include/linux/kallsyms.h                      |   18 +-
 include/linux/mod_lineinfo.h                  |  312 +++
 include/linux/module.h                        |   40 +
 init/Kconfig                                  |   35 +
 kernel/kallsyms.c                             |  103 +-
 kernel/kallsyms_internal.h                    |   11 +
 kernel/module/kallsyms.c                      |  191 ++
 kernel/module/main.c                          |   26 +
 lib/Kconfig.debug                             |   10 +
 lib/tests/Makefile                            |    3 +
 lib/tests/lineinfo_kunit.c                    | 1040 +++++++++
 scripts/.gitignore                            |    1 +
 scripts/Makefile                              |    3 +
 scripts/Makefile.modfinal                     |    6 +
 scripts/empty_lineinfo.S                      |   38 +
 scripts/gen-mod-lineinfo.sh                   |   50 +
 scripts/gen_lineinfo.c                        | 1930 +++++++++++++++++
 scripts/kallsyms.c                            |   11 +
 scripts/link-vmlinux.sh                       |   43 +-
 22 files changed, 3967 insertions(+), 11 deletions(-)
 create mode 100644 Documentation/admin-guide/kallsyms-lineinfo.rst
 create mode 100644 include/linux/mod_lineinfo.h
 create mode 100644 lib/tests/lineinfo_kunit.c
 create mode 100644 scripts/empty_lineinfo.S
 create mode 100644 scripts/gen-mod-lineinfo.sh
 create mode 100644 scripts/gen_lineinfo.c
Signature · 1 line
2.53.0
#1 lore raw

PATCH v8 1/4 kallsyms: embed source file:line info in kernel stack traces

Add CONFIG_KALLSYMS_LINEINFO, which embeds a compact address-to-line lookup table in the kernel image so stack traces directly print source file and line number information:

  root@localhost:~# echo c > /proc/sysrq-trigger
  [   11.201987] sysrq: Trigger a crash
  [   11.202831] Kernel panic - not syncing: sysrq triggered crash
  [   11.206218] Call Trace:
  [   11.206501]  <TASK>
  [   11.206749]  dump_stack_lvl+0x5d/0x80 (lib/dump_stack.c:94)
  [   11.207403]  vpanic+0x36e/0x620 (kernel/panic.c:650)
  [   11.208565]  ? __lock_acquire+0x465/0x2240 (kernel/locking/lockdep.c:4674)
  [   11.209324]  panic+0xc9/0xd0 (kernel/panic.c:787)
  [   11.211873]  ? find_held_lock+0x2b/0x80 (kernel/locking/lockdep.c:5350)
  [   11.212597]  ? lock_release+0xd3/0x300 (kernel/locking/lockdep.c:5535)
  [   11.213312]  sysrq_handle_crash+0x1a/0x20 (drivers/tty/sysrq.c:154)
  [   11.214005]  __handle_sysrq.cold+0x66/0x256 (drivers/tty/sysrq.c:611)
  [   11.214712]  write_sysrq_trigger+0x65/0x80 (drivers/tty/sysrq.c:1221)
  [   11.215424]  proc_reg_write+0x1bd/0x3c0 (fs/proc/inode.c:330)
  [   11.216061]  vfs_write+0x1c6/0xff0 (fs/read_write.c:686)
  [   11.218848]  ksys_write+0xfa/0x200 (fs/read_write.c:740)
  [   11.222394]  do_syscall_64+0xf3/0x690 (arch/x86/entry/syscall_64.c:63)
  [   11.223942]  entry_SYSCALL_64_after_hwframe+0x77/0x7f (arch/x86/entry/entry_64.S:121)

At build time, a new host tool (scripts/gen_lineinfo) reads DWARF .debug_line from vmlinux using libdw (elfutils), extracts all address-to-file:line mappings, and generates an assembly file with sorted parallel arrays (offsets from _text, file IDs, and line numbers). These are linked into vmlinux as .rodata.

At runtime, kallsyms_lookup_lineinfo() does a binary search on the table and __sprint_symbol() appends "(file:line)" to each stack frame. The lookup uses offsets from _text so it works with KASLR, requires no locks or allocations, and is safe in any context including panic.

The feature requires CONFIG_DEBUG_INFO (for DWARF data) and libelf and libdw (from elfutils) on the build host.

Memory footprint, measured with:

  make ARCH=x86_64 O=$B defconfig
  ./scripts/config --file $B/.config -e DEBUG_INFO \
                                     -e DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT
  make ARCH=x86_64 O=$B olddefconfig && make ARCH=x86_64 O=$B -j$(nproc)
  strip -g $B/vmlinux -o vmlinux.nodbg && stat -c %s vmlinux.nodbg

Table: 1,794,950 entries from 4,232 source files

    lineinfo_addrs[]     1,794,950 x u32  =  6.8 MiB
    lineinfo_file_ids[]  1,794,950 x u16  =  3.4 MiB
    lineinfo_lines[]     1,794,950 x u32  =  6.8 MiB
    file_offsets + filenames              =  0.1 MiB
    Total .rodata increase:               = 17.2 MiB

vmlinux (stripped): 51.1 MiB -> 69.1 MiB (+18.0 MiB / +35.3%)

That is the cost of the uncompressed format introduced here; the delta compression added later in this series brings it down to +8.0 MiB (+15.7%) on the same config.

Assisted-by Claude:claude-opus-4-6
---
 Documentation/admin-guide/index.rst           |   1 +
 .../admin-guide/kallsyms-lineinfo.rst         |  72 ++
 MAINTAINERS                                   |   6 +
 include/linux/kallsyms.h                      |  18 +-
 init/Kconfig                                  |  20 +
 kernel/kallsyms.c                             | 101 +-
 kernel/kallsyms_internal.h                    |   9 +
 scripts/.gitignore                            |   1 +
 scripts/Makefile                              |   3 +
 scripts/empty_lineinfo.S                      |  30 +
 scripts/gen_lineinfo.c                        | 969 ++++++++++++++++++
 scripts/kallsyms.c                            |  11 +
 scripts/link-vmlinux.sh                       |  43 +-
 13 files changed, 1273 insertions(+), 11 deletions(-)
 create mode 100644 Documentation/admin-guide/kallsyms-lineinfo.rst
 create mode 100644 scripts/empty_lineinfo.S
 create mode 100644 scripts/gen_lineinfo.c
Documentation/admin-guide/index.rst +1 -0
index cd28dfe91b06..37456e08fe43 100644
@@ -73,6 +73,7 @@ problems and bugs in particular.
    ramoops
    dynamic-debug-howto
    init
+   kallsyms-lineinfo
    kdump/index
    perf/index
    pstore-blk
Documentation/admin-guide/kallsyms-lineinfo.rst new file +72 -0

72 lines not on this page · raw message

MAINTAINERS +6 -0
index 4a8b0fd665ce..b98d57b1ee1d 100644
@@ -13931,6 +13931,12 @@ S:	Maintained
 F:	Documentation/hwmon/k8temp.rst
 F:	drivers/hwmon/k8temp.c
 
+KALLSYMS LINEINFO
+M:	Sasha Levin <[email protected]>
+S:	Maintained
+F:	Documentation/admin-guide/kallsyms-lineinfo.rst
+F:	scripts/gen_lineinfo.c
+
 KASAN
 M:	Andrey Ryabinin <[email protected]>
 R:	Alexander Potapenko <[email protected]>
include/linux/kallsyms.h +17 -1
index d5dd54c53ace..53cc25a6e85d 100644
@@ -16,10 +16,15 @@
 #include <asm/sections.h>
 
 #define KSYM_NAME_LEN 512
+
+/* Extra space for " (path/to/file.c:12345)" suffix when lineinfo is enabled */
+#define KSYM_LINEINFO_LEN (IS_ENABLED(CONFIG_KALLSYMS_LINEINFO) ? 128 : 0)
+
 #define KSYM_SYMBOL_LEN (sizeof("%s+%#lx/%#lx [%s %s]") + \
 			(KSYM_NAME_LEN - 1) + \
 			2*(BITS_PER_LONG*3/10) + (MODULE_NAME_LEN - 1) + \
-			(BUILD_ID_SIZE_MAX * 2) + 1)
+			(BUILD_ID_SIZE_MAX * 2) + 1 + \
+			KSYM_LINEINFO_LEN)
 
 struct cred;
 struct module;
@@ -96,6 +101,9 @@ extern int sprint_backtrace_build_id(char *buffer, unsigned long address);
 
 int lookup_symbol_name(unsigned long addr, char *symname);
 
+bool kallsyms_lookup_lineinfo(unsigned long addr, unsigned long sym_start,
+			      const char **file, unsigned int *line);
+
 #else /* !CONFIG_KALLSYMS */
 
 static inline unsigned long kallsyms_lookup_name(const char *name)
@@ -164,6 +172,14 @@ static inline int kallsyms_on_each_match_symbol(int (*fn)(void *, unsigned long)
 {
 	return -EOPNOTSUPP;
 }
+
+static inline bool kallsyms_lookup_lineinfo(unsigned long addr,
+					    unsigned long sym_start,
+					    const char **file,
+					    unsigned int *line)
+{
+	return false;
+}
 #endif /*CONFIG_KALLSYMS*/
 
 static inline void print_ip_sym(const char *loglvl, unsigned long ip)
init/Kconfig +20 -0
index 5230d4879b1c..635305ec0594 100644
@@ -2087,6 +2087,26 @@ config KALLSYMS_ALL
 
 	  Say N unless you really need all symbols, or kernel live patching.
 
+config KALLSYMS_LINEINFO
+	bool "Embed source file:line information in stack traces"
+	depends on KALLSYMS && DEBUG_INFO
+	help
+	  Embeds an address-to-source-line mapping table in the kernel
+	  image so that stack traces directly include file:line information,
+	  similar to what scripts/decode_stacktrace.sh provides but without
+	  needing external tools or a vmlinux with debug info at runtime.
+
+	  When enabled, stack traces will look like:
+
+	    kmem_cache_alloc_noprof+0x60/0x630 (mm/slub.c:3456)
+	    anon_vma_clone+0x2ed/0xcf0 (mm/rmap.c:412)
+
+	  This requires libelf and libdw (from elfutils) on the build host.
+	  Costs 10 bytes per DWARF line-table entry; for x86_64_defconfig
+	  with CONFIG_DEBUG_INFO that is about 18MB.
+
+	  If unsure, say N.
+
 # end of the "standard kernel features (expert users)" menu
 
 config ARCH_HAS_MEMBARRIER_CALLBACKS
kernel/kallsyms.c +94 -7

154 lines not on this page · raw message

kernel/kallsyms_internal.h +9 -0
index 81a867dbe57d..d7374ce444d8 100644
@@ -15,4 +15,13 @@ extern const u16 kallsyms_token_index[];
 extern const unsigned int kallsyms_markers[];
 extern const u8 kallsyms_seqs_of_names[];
 
+extern const u32 lineinfo_num_entries;
+extern const u32 lineinfo_addrs[];
+extern const u16 lineinfo_file_ids[];
+extern const u32 lineinfo_lines[];
+extern const u32 lineinfo_num_files;
+extern const u32 lineinfo_file_offsets[];
+extern const u32 lineinfo_filenames_size;
+extern const char lineinfo_filenames[];
+
 #endif // LINUX_KALLSYMS_INTERNAL_H_
scripts/.gitignore +1 -0
index 4215c2208f7e..e175714c18b6 100644
@@ -1,5 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 /asn1_compiler
+/gen_lineinfo
 /gen_packed_field_checks
 /generate_rust_target
 /insert-sys-cert
scripts/Makefile +3 -0
index 3434a82a119f..976c607c8d96 100644
@@ -4,6 +4,7 @@
 # the kernel for the build process.
 
 hostprogs-always-$(CONFIG_KALLSYMS)			+= kallsyms
+hostprogs-always-$(CONFIG_KALLSYMS_LINEINFO)		+= gen_lineinfo
 hostprogs-always-$(BUILD_C_RECORDMCOUNT)		+= recordmcount
 hostprogs-always-$(CONFIG_BUILDTIME_TABLE_SORT)		+= sorttable
 hostprogs-always-$(CONFIG_ASN1)				+= asn1_compiler
@@ -37,6 +38,8 @@ HOSTCFLAGS_asn1_compiler.o = -I$(srctree)/include
 HOSTCFLAGS_sign-file.o = $(shell $(HOSTPKG_CONFIG) --cflags libcrypto 2> /dev/null)
 HOSTCFLAGS_sign-file.o += -I$(srctree)/tools/include/uapi/
 HOSTLDLIBS_sign-file = $(shell $(HOSTPKG_CONFIG) --libs libcrypto 2> /dev/null || echo -lcrypto)
+HOSTCFLAGS_gen_lineinfo.o = $(shell $(HOSTPKG_CONFIG) --cflags libdw 2> /dev/null)
+HOSTLDLIBS_gen_lineinfo = $(shell $(HOSTPKG_CONFIG) --libs libdw 2> /dev/null || echo -ldw -lelf)
 
 ifdef CONFIG_UNWINDER_ORC
 ifeq ($(ARCH),x86_64)
scripts/empty_lineinfo.S new file +30 -0
new file mode 100644
index 000000000000..e058c4113712
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2026 Sasha Levin <[email protected]>
+ *
+ * Empty lineinfo stub for the initial vmlinux link.
+ * The real lineinfo is generated from .tmp_vmlinux1 by gen_lineinfo.
+ */
+	.section .rodata, "a"
+	.globl lineinfo_num_entries
+	.balign 4
+lineinfo_num_entries:
+	.long 0
+	.globl lineinfo_num_files
+	.balign 4
+lineinfo_num_files:
+	.long 0
+	.globl lineinfo_addrs
+lineinfo_addrs:
+	.globl lineinfo_file_ids
+lineinfo_file_ids:
+	.globl lineinfo_lines
+lineinfo_lines:
+	.globl lineinfo_file_offsets
+lineinfo_file_offsets:
+	.globl lineinfo_filenames_size
+	.balign 4
+lineinfo_filenames_size:
+	.long 0
+	.globl lineinfo_filenames
+lineinfo_filenames:
scripts/gen_lineinfo.c new file +969 -0

969 lines not on this page · raw message

scripts/kallsyms.c +11 -0
index 37d5c095ad22..e11f101b743b 100644
@@ -90,6 +90,17 @@ static bool is_ignored_symbol(const char *name, char type)
 			return true;
 	}
 
+	/*
+	 * The generated lineinfo tables (scripts/gen_lineinfo, stubbed by
+	 * scripts/empty_lineinfo.S) are read-only data whose size and
+	 * addresses change between kallsyms passes.  Match them by prefix so
+	 * the set cannot drift as the table layout evolves.  Text symbols are
+	 * exempt, so lib/tests/lineinfo_kunit.c's lineinfo_target_*() stay
+	 * resolvable -- the test looks them up by name.
+	 */
+	if (toupper(type) != 'T' && !strncmp(name, "lineinfo_", 9))
+		return true;
+
 	return false;
 }
 
scripts/link-vmlinux.sh +40 -3

81 lines not on this page · raw message

Signature · 1 line
2.53.0
#2 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Use of `snprintf` violates `sprint_symbol` API contract and causes trace buffer inflation. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Use of snprintf violates sprint_symbol API contract and causes trace buffer inflation. --

--- Patch [1]: [PATCH v8 1/4] kallsyms: embed source file:line info in kernel stack traces --- commit 8a14a0edefef69e5b032ac47662777d287f71164
Author: Sasha Levin <[email protected]>

kallsyms: embed source file:line info in kernel stack traces

Add CONFIG_KALLSYMS_LINEINFO, which embeds a compact address-to-line lookup table in the kernel image so stack traces directly print source file and line number information.

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

[ ... ]

Quoted 9 lines
kernel/kallsyms.c +5 -0
@@ -497,6 +567,23 @@ static int __sprint_symbol(char *buffer, unsigned long address,
 		len += sprintf(buffer + len, "]");
 	}
 
+	/*
+	 * Append "(file:line)" only for stack-backtrace consumers.  Plain
+	 * sprint_symbol() backs %ps, and many existing format strings tack
+	 * literal "()" after %ps to indicate a function call ("foo()
+	 * replaced with bar()"); appending lineinfo there would produce a

kernel/kallsyms.c static int __sprint_symbol(char *buffer, unsigned long address, · line 584

Quoted 10 lines
kernel/kallsyms.c +10 -0
+	 * confusing "foo (file:line)()".
+	 */
+	if (add_lineinfo && IS_ENABLED(CONFIG_KALLSYMS_LINEINFO) && !modname) {
+		const char *li_file;
+		unsigned int li_line;
+
+		if (kallsyms_lookup_lineinfo(address, sym_start,
+					     &li_file, &li_line))
+			len += snprintf(buffer + len, KSYM_SYMBOL_LEN - len,
+					" (%s:%u)", li_file, li_line);

[Severity: Medium]
Is it safe to use snprintf() here instead of scnprintf()?

The API contract for sprint_symbol() specifies it returns the number of bytes stored. If the source file path is very long and truncation occurs, snprintf() will return the un-truncated length.

This can cause caller logic errors. For example, if a kprobe triggers on a symbol with a long source path, fetch_store_symstrlen() will allocate buffer space based on this inflated return value. When fetch_store_symstring() writes the truncated string, the tail of the allocated ring buffer remains uninitialized. Future callers attempting pointer advancement via buf += sprint_symbol(...) could also be exposed to out-of-bounds writes.

Could this be changed to use scnprintf() to ensure it returns the actual number of bytes written?

Quoted 4 lines
kernel/kallsyms.c +2 -0
+	}
+
 	return len;
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

PATCH v8 2/4 kallsyms: extend lineinfo to loadable modules

In reply to Sasha Levin

Add CONFIG_KALLSYMS_LINEINFO_MODULES, which extends the CONFIG_KALLSYMS_LINEINFO feature to loadable kernel modules.

At build time, each .ko is post-processed by scripts/gen-mod-lineinfo.sh (modeled on gen-btf.sh) which runs scripts/gen_lineinfo --module on the .ko, generates per-section .mod_lineinfo and .init.mod_lineinfo sections containing compact binary tables of section-relative offsets, file IDs, line numbers, and filenames, and embeds them back into the .ko via a partial link (ld -r).

At runtime, module_lookup_lineinfo() walks the section descriptors in each blob, finds the one whose runtime range contains the queried address, and binary-searches that section's table. The lookup is NMI/panic-safe (no locks, no allocations) — the data lives in read-only module memory and is freed automatically when the module (or its init memory) is unloaded.

The gen_lineinfo tool gains --module mode which:
- Walks an allowlist of text-like sections (.text, .exit.text, .init.text), gating each on its presence in the .ko.
- Uses an ELF relocation against each covered section's symbol as the runtime "anchor", resolved by the module loader's standard apply_relocations() pass — no implicit base derivation from mod->mem[].base, no special-cased loader logic.
- Disambiguates DWARF addresses across sections that all share sh_addr == 0 in ET_REL files via per-section synthetic biases applied inside apply_debug_line_relocations() (handles both abs32 and abs64 width relocs).
- Handles libdw's ET_REL path-doubling quirk in make_relative().
- Declares empty section stanzas in its output assembly so the resulting lineinfo.o has LOCAL SECTION symbols rather than GLOBAL UND ones; otherwise ld -r would not bind the relocation to the .ko's existing section symbol of the same name and depmod would warn.

The build pipeline runs gen-mod-lineinfo.sh after the existing modfinal step:

  gen_lineinfo --module ${KO} > ${KO}.lineinfo.S
  ${CC} -c -o ${KO}.lineinfo.o ${KO}.lineinfo.S
  ${LD} -r ${KO}.lineinfo.o ${KO} -o ${KO}.tmp && mv ${KO}.tmp ${KO}

Order matters: lineinfo.o must come first so its zero-byte text contributions stay at offset 0 of the merged sections.

The init blob lives in MOD_INIT_RODATA and is revoked via WRITE_ONCE in do_init_module() before do_free_init() releases the memory; the module_init_lineinfo_data() reader uses READ_ONCE so concurrent lookups either see the old pointer (still valid until do_free_init's synchronize_rcu) or NULL.

The struct module fields are guarded by
#ifdef CONFIG_KALLSYMS_LINEINFO_MODULES and accessed through inline reader accessors so callers don't duplicate the guard.

Per-module overhead is approximately 14 bytes per DWARF line entry plus a small fixed cost per covered section descriptor. The next patch in this series delta-compresses the per-section streams to ~3-4 bytes per entry.

Assisted-by Claude:claude-opus-4-6
---
 .../admin-guide/kallsyms-lineinfo.rst         |   41 +-
 MAINTAINERS                                   |    3 +
 include/linux/mod_lineinfo.h                  |  122 ++
 include/linux/module.h                        |   40 +
 init/Kconfig                                  |   13 +
 kernel/kallsyms.c                             |   19 +-
 kernel/module/kallsyms.c                      |  209 +++
 kernel/module/main.c                          |   26 +
 scripts/Makefile.modfinal                     |    6 +
 scripts/gen-mod-lineinfo.sh                   |   50 +
 scripts/gen_lineinfo.c                        | 1134 +++++++++++++++--
 11 files changed, 1531 insertions(+), 132 deletions(-)
 create mode 100644 include/linux/mod_lineinfo.h
 create mode 100644 scripts/gen-mod-lineinfo.sh
Documentation/admin-guide/kallsyms-lineinfo.rst +33 -8
index 4c5de44e68fc..152037e62216 100644
@@ -51,22 +51,47 @@ With ``CONFIG_KALLSYMS_LINEINFO``::
 Note that assembly routines (such as ``entry_SYSCALL_64_after_hwframe``) are
 not annotated because they lack DWARF debug information.
 
+Module Support
+==============
+
+``CONFIG_KALLSYMS_LINEINFO_MODULES`` extends the feature to loadable kernel
+modules.  When enabled, each ``.ko`` is post-processed at build time to embed
+a ``.mod_lineinfo`` section containing the same kind of address-to-source
+mapping.
+
+Enable in addition to the base options::
+
+    CONFIG_MODULES=y
+    CONFIG_KALLSYMS_LINEINFO_MODULES=y
+
+Stack traces from module code will then include annotations::
+
+    my_driver_func+0x30/0x100 [my_driver] (drivers/foo/bar.c:123)
+
+The ``.mod_lineinfo`` section is loaded into read-only module memory alongside
+the module text.  No additional runtime memory allocation is required; the data
+is freed when the module is unloaded.
+
 Memory Overhead
 ===============
 
-The lineinfo tables are stored in ``.rodata`` and typically add approximately
-44 MiB to the kernel image for a standard configuration (~4.6 million DWARF
-line entries, ~10 bytes per entry after deduplication).
+The vmlinux lineinfo tables are stored in ``.rodata`` and typically add
+approximately 10-15 MiB to the kernel image for a standard configuration
+(~4.6 million DWARF line entries, ~2-3 bytes per entry after delta
+compression).
+
+Per-module lineinfo adds approximately 2-3 bytes per DWARF line entry to each
+``.ko`` file.
 
 Known Limitations
 =================
 
-- **vmlinux only**: Only symbols in the core kernel image are annotated.
-  Module symbols are not covered.
-- **4 GiB offset limit**: Address offsets from ``_text`` are stored as 32-bit
-  values.  Entries beyond 4 GiB from ``_text`` are skipped at build time with
-  a warning.
+- **4 GiB offset limit**: Address offsets from ``_text`` (vmlinux) or
+  ``.text`` base (modules) are stored as 32-bit values.  Entries beyond
+  4 GiB are skipped at build time with a warning.
 - **65535 file limit**: Source file IDs are stored as 16-bit values.  Builds
   with more than 65535 unique source files will fail with an error.
 - **No assembly annotations**: Functions implemented in assembly that lack
   DWARF ``.debug_line`` data are not annotated.
+- **No init text**: For modules, functions in ``.init.text`` are not annotated
+  because that memory is freed after module initialization.
MAINTAINERS +3 -0
index b98d57b1ee1d..d7e1c1de7998 100644
@@ -13935,6 +13935,9 @@ KALLSYMS LINEINFO
 M:	Sasha Levin <[email protected]>
 S:	Maintained
 F:	Documentation/admin-guide/kallsyms-lineinfo.rst
+F:	include/linux/mod_lineinfo.h
+F:	lib/tests/lineinfo_kunit.c
+F:	scripts/gen-mod-lineinfo.sh
 F:	scripts/gen_lineinfo.c
 
 KASAN
include/linux/mod_lineinfo.h new file +122 -0

122 lines not on this page · raw message

include/linux/module.h +40 -0
index 7566815fabbe..8ae14bb56abf 100644
@@ -507,6 +507,12 @@ struct module {
 	void *btf_data;
 	void *btf_base_data;
 #endif
+#ifdef CONFIG_KALLSYMS_LINEINFO_MODULES
+	void *lineinfo_data;		/* .mod_lineinfo section in MOD_RODATA */
+	unsigned int lineinfo_data_size;
+	void *init_lineinfo_data;	/* .init.mod_lineinfo, NULL after init runs */
+	unsigned int init_lineinfo_data_size;
+#endif
 #ifdef CONFIG_JUMP_LABEL
 	struct jump_entry *jump_entries;
 	unsigned int num_jump_entries;
@@ -1020,6 +1026,40 @@ static inline unsigned long find_kallsyms_symbol_value(struct module *mod,
 
 #endif  /* CONFIG_MODULES && CONFIG_KALLSYMS */
 
+bool module_lookup_lineinfo(struct module *mod, unsigned long addr,
+			    unsigned long sym_start,
+			    const char **file, unsigned int *line);
+
+/*
+ * Reader accessors so callers don't need to duplicate the
+ * CONFIG_KALLSYMS_LINEINFO_MODULES guard around mod->lineinfo_data /
+ * mod->init_lineinfo_data field access.  Setters/clearers in the loader
+ * use the field directly under a matching #ifdef.
+ */
+static inline void *module_lineinfo_data(const struct module *mod,
+					 unsigned int *size)
+{
+#ifdef CONFIG_KALLSYMS_LINEINFO_MODULES
+	*size = mod->lineinfo_data_size;
+	return mod->lineinfo_data;
+#else
+	*size = 0;
+	return NULL;
+#endif
+}
+
+static inline void *module_init_lineinfo_data(const struct module *mod,
+					      unsigned int *size)
+{
+#ifdef CONFIG_KALLSYMS_LINEINFO_MODULES
+	*size = READ_ONCE(mod->init_lineinfo_data_size);
+	return READ_ONCE(mod->init_lineinfo_data);
+#else
+	*size = 0;
+	return NULL;
+#endif
+}
+
 /* Define __free(module_put) macro for struct module *. */
 DEFINE_FREE(module_put, struct module *, if (_T) module_put(_T))
 
init/Kconfig +13 -0
index 635305ec0594..8c5cf00cb3ae 100644
@@ -2107,6 +2107,19 @@ config KALLSYMS_LINEINFO
 
 	  If unsure, say N.
 
+config KALLSYMS_LINEINFO_MODULES
+	bool "Embed source file:line information in module stack traces"
+	depends on KALLSYMS_LINEINFO && MODULES
+	help
+	  Extends KALLSYMS_LINEINFO to loadable kernel modules.  Each .ko
+	  gets a lineinfo table generated from its DWARF data at build time,
+	  so stack traces from module code include (file.c:123) annotations.
+
+	  This requires libelf and libdw (from elfutils) on the build host.
+	  Costs 10 bytes per DWARF line entry in each .ko.
+
+	  If unsure, say N.
+
 # end of the "standard kernel features (expert users)" menu
 
 config ARCH_HAS_MEMBARRIER_CALLBACKS
kernel/kallsyms.c +16 -3
index baf52e81118b..07cfc30c7ad6 100644
@@ -574,12 +574,25 @@ static int __sprint_symbol(char *buffer, unsigned long address,
 	 * replaced with bar()"); appending lineinfo there would produce a
 	 * confusing "foo (file:line)()".
 	 */
-	if (add_lineinfo && IS_ENABLED(CONFIG_KALLSYMS_LINEINFO) && !modname) {
+	if (add_lineinfo && IS_ENABLED(CONFIG_KALLSYMS_LINEINFO)) {
 		const char *li_file;
 		unsigned int li_line;
+		bool found = false;
+
+		if (!modname) {
+			found = kallsyms_lookup_lineinfo(address, sym_start,
+							 &li_file, &li_line);
+		} else if (IS_ENABLED(CONFIG_KALLSYMS_LINEINFO_MODULES)) {
+			struct module *mod = __module_address(address);
+
+			if (mod)
+				found = module_lookup_lineinfo(mod, address,
+							       sym_start,
+							       &li_file,
+							       &li_line);
+		}
 
-		if (kallsyms_lookup_lineinfo(address, sym_start,
-					     &li_file, &li_line))
+		if (found)
 			len += snprintf(buffer + len, KSYM_SYMBOL_LEN - len,
 					" (%s:%u)", li_file, li_line);
 	}
kernel/module/kallsyms.c +209 -0

212 lines not on this page · raw message

kernel/module/main.c +26 -0
index 46dd8d25a605..46bb2bf799d1 100644
@@ -2712,6 +2712,19 @@ static int find_module_sections(struct module *mod, struct load_info *info)
 	mod->btf_base_data = any_section_objs(info, ".BTF.base", 1,
 					      &mod->btf_base_data_size);
 #endif
+#ifdef CONFIG_KALLSYMS_LINEINFO_MODULES
+	/*
+	 * Use section_objs() (not any_section_objs) — both blobs carry an
+	 * ELF anchor relocation that the module loader resolves via its
+	 * standard apply_relocations() pass, which only walks SHF_ALLOC
+	 * sections.  Picking up a non-ALLOC section here would also leave
+	 * the pointer dangling into the temporary load image once freed.
+	 */
+	mod->lineinfo_data = section_objs(info, ".mod_lineinfo", 1,
+					  &mod->lineinfo_data_size);
+	mod->init_lineinfo_data = section_objs(info, ".init.mod_lineinfo", 1,
+					       &mod->init_lineinfo_data_size);
+#endif
 #ifdef CONFIG_JUMP_LABEL
 	mod->jump_entries = section_objs(info, "__jump_table",
 					sizeof(*mod->jump_entries),
@@ -3165,6 +3178,19 @@ static noinline int do_init_module(struct module *mod)
 	/* .BTF is not SHF_ALLOC and will get removed, so sanitize pointers */
 	mod->btf_data = NULL;
 	mod->btf_base_data = NULL;
+#endif
+#ifdef CONFIG_KALLSYMS_LINEINFO_MODULES
+	/*
+	 * .init.mod_lineinfo lives in MOD_INIT_RODATA which do_free_init() is
+	 * about to release.  Clear the pointer so concurrent stack-trace
+	 * lookups stop dereferencing it; do_free_init()'s synchronize_rcu()
+	 * then waits out any reader that already captured the old pointer.
+	 * WRITE_ONCE pairs with the READ_ONCE inside module_init_lineinfo_data()
+	 * so the compiler can't tear or reorder the revocation across the
+	 * llist_add() that follows.
+	 */
+	WRITE_ONCE(mod->init_lineinfo_data, NULL);
+	WRITE_ONCE(mod->init_lineinfo_data_size, 0);
 #endif
 	/*
 	 * We want to free module_init, but be aware that kallsyms may be
scripts/Makefile.modfinal +6 -0
index 01a37ec872b9..2cdd76becb4d 100644
@@ -46,11 +46,17 @@ quiet_cmd_btf_ko = BTF [M] $@
 		$(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \
 	fi;
 
+quiet_cmd_lineinfo_ko = LINEINFO [M] $@
+      cmd_lineinfo_ko = $(CONFIG_SHELL) $(srctree)/scripts/gen-mod-lineinfo.sh $@
+
 # Re-generate module BTFs if either module's .ko or vmlinux changed
 %.ko: %.o %.mod.o .module-common.o $(objtree)/scripts/module.lds $(and $(CONFIG_DEBUG_INFO_BTF_MODULES),$(KBUILD_BUILTIN),$(objtree)/vmlinux) FORCE
 	+$(call if_changed,ld_ko_o)
 ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 	+$(if $(newer-prereqs),$(call cmd,btf_ko))
+endif
+ifdef CONFIG_KALLSYMS_LINEINFO_MODULES
+	+$(if $(newer-prereqs),$(call cmd,lineinfo_ko))
 endif
 	+$(call cmd,check_tracepoint)
 
scripts/gen-mod-lineinfo.sh new file +50 -0

50 lines not on this page · raw message

scripts/gen_lineinfo.c +1013 -121

1,398 lines not on this page · raw message

Signature · 1 line
2.53.0
#4 lore raw

Re: [PATCH v8 2/4] kallsyms: extend lineinfo to loadable modules

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Integer overflow in `mod_lineinfo_filenames_off()` and `module_lookup_lineinfo_section()` size…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Integer overflow in mod_lineinfo_filenames_off() and module_lookup_lineinfo_section() size calculations bypasses bounds checks, leading to out-of-bounds memory accesses in NMI/panic context.
- [Medium] gen_lineinfo fails to apply .debug_info relocations, causing dwarf_getsrclines to read the wrong line program for all CUs except the first in an ET_REL module. --

--- Patch [2]: [PATCH v8 2/4] kallsyms: extend lineinfo to loadable modules --- commit 4466d01d38fe10716b6638bf8ed427b3c7f20a03
Author: Sasha Levin <[email protected]>
Subject: kallsyms: extend lineinfo to loadable modules

This commit extends CONFIG_KALLSYMS_LINEINFO to loadable kernel modules. It post-processes each .ko at build time to embed a lineinfo section, which is used at runtime to annotate stack traces from module code.

Quoted 6 lines
include/linux/mod_lineinfo.h new file +0 -0
new file mode 100644
index 0000000000000..75d0bfba6ce57
@@ -0,0 +1,122 @@

[ ... ]

Quoted 28 lines
include/linux/mod_lineinfo.h new file +28 -0
+static inline u32 mod_lineinfo_addrs_off(void)
+{
+	return sizeof(struct mod_lineinfo_header);
+}
+
+static inline u32 mod_lineinfo_file_ids_off(u32 num_entries)
+{
+	return mod_lineinfo_addrs_off() + num_entries * sizeof(u32);
+}
+
+static inline u32 mod_lineinfo_lines_off(u32 num_entries)
+{
+	/* u16 file_ids[] may need 2-byte padding to align lines[] to 4 bytes */
+	u32 off = mod_lineinfo_file_ids_off(num_entries) +
+		  num_entries * sizeof(u16);
+	return (off + 3) & ~3u;
+}
+
+static inline u32 mod_lineinfo_file_offsets_off(u32 num_entries)
+{
+	return mod_lineinfo_lines_off(num_entries) + num_entries * sizeof(u32);
+}
+
+static inline u32 mod_lineinfo_filenames_off(u32 num_entries, u32 num_files)
+{
+	return mod_lineinfo_file_offsets_off(num_entries) +
+	       num_files * sizeof(u32);
+}

[ ... ]

Quoted 4 lines
kernel/module/kallsyms.c +0 -0
index f23126d804b25..b0e703e29708b 100644

[ ... ]

Quoted 7 lines
kernel/module/kallsyms.c +7 -0
+static bool module_lookup_lineinfo_section(const void *blob, u32 blob_size,
+					   u32 hdr_offset,
+					   unsigned int section_offset,
+					   unsigned int min_offset,
+					   const char **file,
+					   unsigned int *line)
+{

[ ... ]

Quoted 7 lines
kernel/module/kallsyms.c +7 -0
+	/*
+	 * Validate counts before multiplying — sizing arithmetic could
+	 * otherwise overflow on 32-bit with a malformed blob.  Each entry
+	 * contributes one u32 (addrs), one u16 (file_ids), and one u32
+	 * (lines); each file contributes one u32 (file_offsets).
+	 */
+	{

kernel/module/kallsyms.c int module_kallsyms_on_each_symbol(const char *modname, · line 559

Quoted 10 lines
kernel/module/kallsyms.c +10 -0
+		u32 avail = blob_size - hdr_offset;
+		u32 needed = mod_lineinfo_filenames_off(num_entries, num_files);
+
+		if (num_entries > U32_MAX / sizeof(u32))
+			return false;
+		if (num_files > U32_MAX / sizeof(u32))
+			return false;
+		if (needed > avail || filenames_size > avail - needed)
+			return false;
+	}

[Severity: High]
Can the needed calculation overflow before the bounds check is evaluated?

If num_entries is maliciously large (e.g., 0x33333334), the calculation in mod_lineinfo_filenames_off() sums the array offsets using 32-bit unsigned arithmetic (around 10 bytes per entry). This would wrap around modulo 2^32, resulting in a small needed value that bypasses the needed > avail check. A later binary search on addrs could then access out-of-bounds memory.

The division check on num_entries above only guards against a single u32 array's size, not the combined 10 bytes per entry.

Quoted 4 lines
scripts/gen_lineinfo.c +0 -0
index a3ee54eaad05d..725a8dfbf011a 100644

[ ... ]

Quoted 2 lines
scripts/gen_lineinfo.c +2 -0
+static void apply_debug_line_relocations(Elf *elf)
+{

[ ... ]

Quoted 9 lines
scripts/gen_lineinfo.c +9 -0
+	/* Find the relevant sections */
+	while ((scn = elf_nextscn(elf, scn)) != NULL) {
+		const char *name;
+
+		if (!gelf_getshdr(scn, &shdr))
+			continue;
+		name = elf_strptr(elf, shstrndx, shdr.sh_name);
+		if (!name)
+			continue;

scripts/gen_lineinfo.c static void collect_symbol_starts(Elf *elf, unsigned long long text_addr) · line 1038

Quoted 10 lines
scripts/gen_lineinfo.c +10 -0
+
+		if (!strcmp(name, ".debug_line"))
+			debug_line_scn = scn;
+		else if (!strcmp(name, ".rela.debug_line"))
+			rela_debug_line_scn = scn;
+		else if (!strcmp(name, ".rel.debug_line"))
+			rel_debug_line_scn = scn;
+		else if (shdr.sh_type == SHT_SYMTAB)
+			symtab_scn = scn;
+	}

[Severity: Medium]
Does this miss relocations for ET_REL modules that contain multiple object files?

This loop collects and applies relocations for .debug_line, but appears to omit .rela.debug_info and .rel.debug_info entirely.

Without the relocations applied to .debug_info, the DW_AT_stmt_list attribute for all compile units might remain at offset 0.

Quoted 4 lines
scripts/gen_lineinfo.c +3 -0
+static void process_dwarf(Dwarf *dwarf, unsigned long long text_addr,
+			  struct covered_section *sections,
+			  unsigned int num_sections)
 {

[ ... ]

scripts/gen_lineinfo.c

Quoted 2 lines
scripts/gen_lineinfo.c +2 -0
+		if (dwarf_getsrclines(&cudie, &lines, &nlines) != 0)
+			goto next;

When dwarf_getsrclines() is later called in process_dwarf(), will it repeatedly read the line program of only the first compile unit, leaving most module functions without line info?

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

PATCH v8 3/4 kallsyms: delta-compress lineinfo tables for ~2.7x size reduction

In reply to Sasha Levin

Replace the flat uncompressed parallel arrays (lineinfo_addrs[], lineinfo_file_ids[], lineinfo_lines[]) with a block-indexed, delta-encoded, ULEB128 varint compressed format.

The sorted address array has small deltas between consecutive entries (typically 1-50 bytes), file IDs have high locality (delta often 0, same file), and line numbers change slowly. Delta-encoding followed by ULEB128 varint compression shrinks most values from 4 bytes to 1.

Entries are grouped into blocks of 64. A small uncompressed block index (first addr + byte offset per block) enables O(log(N/64)) binary search, followed by sequential decode of at most 64 varints within the matching block. All decode state lives on the stack -- zero allocations, still safe for NMI/panic context.

Measured on x86_64_defconfig + CONFIG_DEBUG_INFO (same recipe as patch 1/4; 1,795,278 entries, 4,233 source files, 28,052 blocks):

Before (flat arrays):

    lineinfo_addrs[]     7,179,800 bytes (u32 x 1.79M)
    lineinfo_file_ids[]  3,589,900 bytes (u16 x 1.79M)
    lineinfo_lines[]     7,179,800 bytes (u32 x 1.79M)
    Total:              17,949,500 bytes (17.1 MiB, 10.00 bytes/entry)

After (block-indexed delta + ULEB128):

    lineinfo_block_addrs[]    112,208 bytes (110 KiB)
    lineinfo_block_offsets[]  112,208 bytes (110 KiB)
    lineinfo_data[]         6,529,411 bytes (6.2 MiB)
    Total:                  6,753,827 bytes (6.4 MiB, 3.76 bytes/entry)

Savings: 10.7 MiB (2.66x reduction)

file_offsets[] and filenames[] are unchanged by this patch and are excluded from both totals above.

Whole-image effect, measured the same way as patch 1/4:

  vmlinux (stripped), no lineinfo:      51.1 MiB
  vmlinux (stripped), before this fix:  69.1 MiB  (+18.0 MiB / +35.3%)
  vmlinux (stripped), after this fix:   59.1 MiB  ( +8.0 MiB / +15.7%)

Booted in QEMU and verified with SysRq-l that annotations still work:

  default_idle+0x9/0x10 (arch/x86/kernel/process.c:767)
  default_idle_call+0x6c/0xb0 (kernel/sched/idle.c:122)
  do_idle+0x335/0x490 (kernel/sched/idle.c:191)
  cpu_startup_entry+0x4e/0x60 (kernel/sched/idle.c:429)
  rest_init+0x1aa/0x1b0 (init/main.c:760)
Assisted-by Claude:claude-opus-4-6
---
 include/linux/mod_lineinfo.h | 250 ++++++++++++++++++++++++++++++-----
 init/Kconfig                 |   8 +-
 kernel/kallsyms.c            |  53 +++-----
 kernel/kallsyms_internal.h   |   8 +-
 kernel/module/kallsyms.c     | 110 +++++++--------
 scripts/empty_lineinfo.S     |  20 ++-
 scripts/gen_lineinfo.c       | 185 ++++++++++++++++++--------
 7 files changed, 437 insertions(+), 197 deletions(-)
include/linux/mod_lineinfo.h +220 -30
index 75d0bfba6ce5..47277f9d7e4f 100644
@@ -3,9 +3,9 @@
  * mod_lineinfo.h - Binary format for per-module source line information
  *
  * This header defines the layout of the .mod_lineinfo and
- * .init.mod_lineinfo sections embedded in loadable kernel modules.  It
- * is dual-use: included from both the kernel and the userspace
- * gen_lineinfo tool.
+ * .init.mod_lineinfo sections embedded in loadable kernel modules.  It is
+ * dual-use: included from both the kernel and the userspace gen_lineinfo
+ * tool.
  *
  * Top-level layout (all values in target-native endianness):
  *
@@ -20,16 +20,27 @@
  * If the relocation fails to resolve (e.g. unknown reloc type), .anchor
  * stays zero and lookups silently degrade to "no annotation".
  *
- * Each per-section sub-table is laid out as a stand-alone
- * mod_lineinfo_header followed by parallel arrays:
+ * Each per-section sub-table is laid out exactly as a stand-alone
+ * mod_lineinfo_header followed by its arrays:
  *
- *   struct mod_lineinfo_header     (16 bytes)
- *   u32 addrs[num_entries]         -- offsets from this section's base, sorted
- *   u16 file_ids[num_entries]      -- parallel to addrs
- *   <2-byte pad if num_entries is odd>
- *   u32 lines[num_entries]         -- parallel to addrs
+ *   struct mod_lineinfo_header
+ *   u32 block_addrs[num_blocks]    -- first addr per block, for binary search
+ *   u32 block_offsets[num_blocks]  -- byte offset into compressed data stream
+ *   u8  data[data_size]            -- LEB128 delta-compressed entries
  *   u32 file_offsets[num_files]    -- byte offset into filenames[]
  *   char filenames[filenames_size] -- concatenated NUL-terminated strings
+ *
+ * Each sub-array is located by an explicit (offset, size) pair in the
+ * header, similar to a flattened devicetree.  All offsets in the per-section
+ * header are relative to that header itself, so a sub-table is fully
+ * self-describing.
+ *
+ * Compressed stream format (per block of LINEINFO_BLOCK_ENTRIES entries):
+ *   Entry 0: file_id (ULEB128), line (ULEB128)
+ *            addr is in block_addrs[]
+ *   Entry 1..N: addr_delta (ULEB128),
+ *               file_id_delta (SLEB128),
+ *               line_delta (SLEB128)
  */
 #ifndef _LINUX_MOD_LINEINFO_H
 #define _LINUX_MOD_LINEINFO_H
@@ -44,6 +55,7 @@
 #include <stdint.h>
 typedef uint32_t u32;
 typedef uint16_t u16;
+typedef uint8_t  u8;
 typedef uint64_t u64;
 #ifndef __aligned
 #define __aligned(x)	__attribute__((__aligned__(x)))
@@ -53,6 +65,8 @@ typedef uint64_t u64;
 #endif
 #endif
 
+#define LINEINFO_BLOCK_ENTRIES 64
+
 /*
  * Per-section descriptor.  One entry per ELF text section covered by the
  * blob (.text, .exit.text, .init.text, ...).
@@ -84,39 +98,215 @@ static_assert(sizeof(struct mod_lineinfo_section) == 16,
 
 struct mod_lineinfo_header {
 	u32 num_entries;
+	u32 num_blocks;
 	u32 num_files;
-	u32 filenames_size;	/* total bytes of concatenated filenames */
+	u32 blocks_offset;	/* offset to block_addrs[] from this header */
+	u32 blocks_size;	/* bytes: num_blocks * 2 * sizeof(u32) */
+	u32 data_offset;	/* offset to compressed stream */
+	u32 data_size;		/* bytes of compressed data */
+	u32 files_offset;	/* offset to file_offsets[] */
+	u32 files_size;		/* bytes: num_files * sizeof(u32) */
+	u32 filenames_offset;
+	u32 filenames_size;
 };
 
-/* Offset helpers: compute byte offset from the per-section header to each array. */
+/*
+ * Descriptor for a lineinfo table, used by the shared lookup function.
+ * Callers populate this from either linker globals (vmlinux) or a
+ * validated mod_lineinfo_header (modules).
+ */
+struct lineinfo_table {
+	const u32 *blk_addrs;
+	const u32 *blk_offsets;
+	const u8  *data;
+	u32 data_size;
+	const u32 *file_offsets;
+	const char *filenames;
+	u32 num_entries;
+	u32 num_blocks;
+	u32 num_files;
+	u32 filenames_size;
+};
 
-static inline u32 mod_lineinfo_addrs_off(void)
+/*
+ * Read a ULEB128 varint from a byte stream.
+ * Returns the decoded value and advances *pos past the encoded bytes.
+ * If *pos would exceed 'end', returns 0 and sets *pos = end (safe for
+ * NMI/panic context: no crash, just a missed annotation).
+ */
+static inline u32 lineinfo_read_uleb128(const u8 *data, u32 *pos, u32 end)
 {
-	return sizeof(struct mod_lineinfo_header);
-}
+	u32 result = 0;
+	unsigned int shift = 0;
 
-static inline u32 mod_lineinfo_file_ids_off(u32 num_entries)
-{
-	return mod_lineinfo_addrs_off() + num_entries * sizeof(u32);
+	while (*pos < end) {
+		u8 byte = data[*pos];
+		(*pos)++;
+		result |= (u32)(byte & 0x7f) << shift;
+		if (!(byte & 0x80))
+			return result;
+		shift += 7;
+		if (shift >= 32) {
+			/* Malformed: skip remaining continuation bytes */
+			while (*pos < end && (data[*pos] & 0x80))
+				(*pos)++;
+			if (*pos < end)
+				(*pos)++;
+			return result;
+		}
+	}
+	return result;
 }
 
-static inline u32 mod_lineinfo_lines_off(u32 num_entries)
+/* Read an SLEB128 varint. Same safety guarantees as above. */
+static inline int32_t lineinfo_read_sleb128(const u8 *data, u32 *pos, u32 end)
 {
-	/* u16 file_ids[] may need 2-byte padding to align lines[] to 4 bytes */
-	u32 off = mod_lineinfo_file_ids_off(num_entries) +
-		  num_entries * sizeof(u16);
-	return (off + 3) & ~3u;
-}
+	int32_t result = 0;
+	unsigned int shift = 0;
+	u8 byte = 0;
 
-static inline u32 mod_lineinfo_file_offsets_off(u32 num_entries)
-{
-	return mod_lineinfo_lines_off(num_entries) + num_entries * sizeof(u32);
+	while (*pos < end) {
+		byte = data[*pos];
+		(*pos)++;
+		result |= (int32_t)((u32)(byte & 0x7f) << shift);
+		shift += 7;
+		if (!(byte & 0x80))
+			break;
+		if (shift >= 32) {
+			while (*pos < end && (data[*pos] & 0x80))
+				(*pos)++;
+			if (*pos < end)
+				(*pos)++;
+			return result;
+		}
+	}
+
+	/* Sign-extend if the high bit of the last byte was set */
+	if (shift < 32 && (byte & 0x40))
+		result |= -(1 << shift);
+
+	return result;
 }
 
-static inline u32 mod_lineinfo_filenames_off(u32 num_entries, u32 num_files)
+/*
+ * Search a lineinfo table for the source file and line corresponding to a
+ * given offset (from _text for vmlinux, from the covered section's base for
+ * modules).  @min_offset is the containing symbol's start in the same offset
+ * space: entries below it belong to a preceding symbol and are rejected.
+ *
+ * Safe for NMI and panic context: no locks, no allocations, all state on stack.
+ * Returns true and sets @file and @line on success; false on any failure.
+ */
+static inline bool lineinfo_search(const struct lineinfo_table *tbl,
+				   unsigned int offset,
+				   unsigned int min_offset,
+				   const char **file, unsigned int *line)
 {
-	return mod_lineinfo_file_offsets_off(num_entries) +
-	       num_files * sizeof(u32);
+	unsigned int low, high, mid, block;
+	unsigned int cur_addr, cur_file_id, cur_line;
+	unsigned int best_addr = 0, best_file_id = 0, best_line = 0;
+	unsigned int block_entries, data_end;
+	bool found = false;
+	u32 pos;
+
+	if (!tbl->num_entries || !tbl->num_blocks)
+		return false;
+
+	/* Binary search on blk_addrs[] to find the right block */
+	low = 0;
+	high = tbl->num_blocks;
+	while (low < high) {
+		mid = low + (high - low) / 2;
+		if (tbl->blk_addrs[mid] <= offset)
+			low = mid + 1;
+		else
+			high = mid;
+	}
+
+	if (low == 0)
+		return false;
+	block = low - 1;
+
+	/* How many entries in this block? */
+	block_entries = LINEINFO_BLOCK_ENTRIES;
+	if (block == tbl->num_blocks - 1) {
+		unsigned int remaining = tbl->num_entries -
+					block * LINEINFO_BLOCK_ENTRIES;
+
+		if (remaining < block_entries)
+			block_entries = remaining;
+	}
+
+	/* Determine end of this block's data in the compressed stream */
+	if (block + 1 < tbl->num_blocks)
+		data_end = tbl->blk_offsets[block + 1];
+	else
+		data_end = tbl->data_size;
+
+	/* Clamp data_end to actual data size */
+	if (data_end > tbl->data_size)
+		data_end = tbl->data_size;
+
+	/* Decode entry 0: addr from blk_addrs, file_id and line from stream */
+	pos = tbl->blk_offsets[block];
+	if (pos >= data_end)
+		return false;
+
+	cur_addr = tbl->blk_addrs[block];
+	cur_file_id = lineinfo_read_uleb128(tbl->data, &pos, data_end);
+	cur_line = lineinfo_read_uleb128(tbl->data, &pos, data_end);
+
+	/* Check entry 0 */
+	if (cur_addr <= offset) {
+		best_addr = cur_addr;
+		best_file_id = cur_file_id;
+		best_line = cur_line;
+		found = true;
+	}
+
+	/* Decode entries 1..N */
+	for (unsigned int i = 1; i < block_entries; i++) {
+		unsigned int addr_delta;
+		int32_t file_delta, line_delta;
+
+		addr_delta = lineinfo_read_uleb128(tbl->data, &pos, data_end);
+		file_delta = lineinfo_read_sleb128(tbl->data, &pos, data_end);
+		line_delta = lineinfo_read_sleb128(tbl->data, &pos, data_end);
+
+		cur_addr += addr_delta;
+		cur_file_id = (unsigned int)((int32_t)cur_file_id + file_delta);
+		cur_line = (unsigned int)((int32_t)cur_line + line_delta);
+
+		if (cur_addr > offset)
+			break;
+
+		best_addr = cur_addr;
+		best_file_id = cur_file_id;
+		best_line = cur_line;
+		found = true;
+	}
+
+	if (!found)
+		return false;
+
+	/*
+	 * The best entry is the closest one at or below @offset; reject it
+	 * if it lies below the resolved symbol's start, so a symbol without
+	 * line entries of its own does not inherit the preceding symbol's
+	 * annotation.
+	 */
+	if (best_addr < min_offset)
+		return false;
+
+	if (best_file_id >= tbl->num_files)
+		return false;
+
+	if (tbl->file_offsets[best_file_id] >= tbl->filenames_size)
+		return false;
+
+	*file = &tbl->filenames[tbl->file_offsets[best_file_id]];
+	*line = best_line;
+	return true;
 }
 
 #endif /* _LINUX_MOD_LINEINFO_H */
init/Kconfig +5 -3
index 8c5cf00cb3ae..041084efabf7 100644
@@ -2102,8 +2102,9 @@ config KALLSYMS_LINEINFO
 	    anon_vma_clone+0x2ed/0xcf0 (mm/rmap.c:412)
 
 	  This requires libelf and libdw (from elfutils) on the build host.
-	  Costs 10 bytes per DWARF line-table entry; for x86_64_defconfig
-	  with CONFIG_DEBUG_INFO that is about 18MB.
+	  Costs about 3.8 bytes per DWARF line-table entry after delta
+	  compression; for x86_64_defconfig with CONFIG_DEBUG_INFO that is
+	  about 8MB.
 
 	  If unsure, say N.
 
@@ -2116,7 +2117,8 @@ config KALLSYMS_LINEINFO_MODULES
 	  so stack traces from module code include (file.c:123) annotations.
 
 	  This requires libelf and libdw (from elfutils) on the build host.
-	  Costs 10 bytes per DWARF line entry in each .ko.
+	  Costs about 3.8 bytes per DWARF line entry in each .ko after
+	  delta compression.
 
 	  If unsure, say N.
 
kernel/kallsyms.c +20 -33

76 lines not on this page · raw message

kernel/kallsyms_internal.h +5 -3
index d7374ce444d8..ffe4c658067e 100644
@@ -16,10 +16,12 @@ extern const unsigned int kallsyms_markers[];
 extern const u8 kallsyms_seqs_of_names[];
 
 extern const u32 lineinfo_num_entries;
-extern const u32 lineinfo_addrs[];
-extern const u16 lineinfo_file_ids[];
-extern const u32 lineinfo_lines[];
 extern const u32 lineinfo_num_files;
+extern const u32 lineinfo_num_blocks;
+extern const u32 lineinfo_block_addrs[];
+extern const u32 lineinfo_block_offsets[];
+extern const u32 lineinfo_data_size;
+extern const u8  lineinfo_data[];
 extern const u32 lineinfo_file_offsets[];
 extern const u32 lineinfo_filenames_size;
 extern const char lineinfo_filenames[];
kernel/module/kallsyms.c +46 -64

160 lines not on this page · raw message

scripts/empty_lineinfo.S +14 -6
index e058c4113712..edd5b1092f05 100644
@@ -14,12 +14,20 @@ lineinfo_num_entries:
 	.balign 4
 lineinfo_num_files:
 	.long 0
-	.globl lineinfo_addrs
-lineinfo_addrs:
-	.globl lineinfo_file_ids
-lineinfo_file_ids:
-	.globl lineinfo_lines
-lineinfo_lines:
+	.globl lineinfo_num_blocks
+	.balign 4
+lineinfo_num_blocks:
+	.long 0
+	.globl lineinfo_block_addrs
+lineinfo_block_addrs:
+	.globl lineinfo_block_offsets
+lineinfo_block_offsets:
+	.globl lineinfo_data_size
+	.balign 4
+lineinfo_data_size:
+	.long 0
+	.globl lineinfo_data
+lineinfo_data:
 	.globl lineinfo_file_offsets
 lineinfo_file_offsets:
 	.globl lineinfo_filenames_size
scripts/gen_lineinfo.c +127 -58

249 lines not on this page · raw message

Signature · 1 line
2.53.0
#6 lore raw

Re: [PATCH v8 3/4] kallsyms: delta-compress lineinfo tables for ~2.7x size reduction

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Missing alignment validation for inner offsets `blocks_offset` and `files_offset` from the…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Missing alignment validation for inner offsets blocks_offset and files_offset from the module lineinfo header, risking fatal alignment traps. --

--- Patch [3]: [PATCH v8 3/4] kallsyms: delta-compress lineinfo tables for ~2.7x size reduction --- commit cc36cd56474b921c9564d160db461d97e0550634
Author: Sasha Levin <[email protected]>

kallsyms: delta-compress lineinfo tables for ~2.7x size reduction

This commit replaces the flat uncompressed parallel arrays in kallsyms lineinfo with a block-indexed, delta-encoded, ULEB128 varint compressed format to significantly reduce the memory footprint.

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

[ ... ]

Quoted 31 lines
kernel/module/kallsyms.c +7 -13
@@ -540,80 +535,63 @@ static bool module_lookup_lineinfo_section(const void *blob, u32 blob_size,
 		return false;
 
 	base = (const u8 *)blob + hdr_offset;
-	hdr = (const struct mod_lineinfo_header *)base;
-	num_entries = hdr->num_entries;
-	num_files = hdr->num_files;
-	filenames_size = hdr->filenames_size;
+	hdr = base;
 
-	if (num_entries == 0)
+	if (hdr->num_entries == 0 || hdr->num_blocks == 0)
 		return false;
 
-	/*
-	 * Validate counts before multiplying — sizing arithmetic could
-	 * otherwise overflow on 32-bit with a malformed blob.  Each entry
-	 * contributes one u32 (addrs), one u16 (file_ids), and one u32
-	 * (lines); each file contributes one u32 (file_offsets).
-	 */
 	/* Validate each sub-array fits within the remaining blob bytes */
 	{
 		u32 avail = blob_size - hdr_offset;
-		u32 needed = mod_lineinfo_filenames_off(num_entries, num_files);
 
-		if (num_entries > U32_MAX / sizeof(u32))
+		if (hdr->blocks_offset > avail ||
+		    hdr->blocks_size > avail - hdr->blocks_offset)
+			return false;
+		if (hdr->data_offset > avail ||
+		    hdr->data_size > avail - hdr->data_offset)

kernel/module/kallsyms.c static bool module_lookup_lineinfo_section(const void *blob, u32 blob_size, · line 559

Quoted 10 lines
kernel/module/kallsyms.c +4 -2
 			return false;
-		if (num_files > U32_MAX / sizeof(u32))
+		if (hdr->files_offset > avail ||
+		    hdr->files_size > avail - hdr->files_offset)
 			return false;
-		if (needed > avail || filenames_size > avail - needed)
+		if (hdr->filenames_offset > avail ||
+		    hdr->filenames_size > avail - hdr->filenames_offset)
 			return false;
 	}

[Severity: Medium]
Could these inner offsets (like hdr->blocks_offset and hdr->files_offset) be unaligned in a malformed blob?

The code validates the bounds correctly here, but misses an alignment check before these offsets are later added to the base pointer and assigned to the u32 arrays.

If the offsets are not multiples of 4, wouldn't dereferencing tbl.blk_addrs or tbl.file_offsets trigger an alignment exception on strict-alignment architectures? If this happens during an NMI or panic, it seems like it could cause a recursive fault and permanently lose the backtrace.

[ ... ]

Quoted 14 lines
kernel/module/kallsyms.c +13 -0
+	tbl.blk_addrs	= base + hdr->blocks_offset;
+	tbl.blk_offsets	= base + hdr->blocks_offset +
+			  hdr->num_blocks * sizeof(u32);
+	tbl.data	= base + hdr->data_offset;
+	tbl.data_size	= hdr->data_size;
+	tbl.file_offsets = base + hdr->files_offset;
+	tbl.filenames	= base + hdr->filenames_offset;
+	tbl.num_entries	= hdr->num_entries;
+	tbl.num_blocks	= hdr->num_blocks;
+	tbl.num_files	= hdr->num_files;
+	tbl.filenames_size = hdr->filenames_size;
+
+	return lineinfo_search(&tbl, section_offset, min_offset, file, line);
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#7 lore raw

PATCH v8 4/4 kallsyms: add KUnit tests for lineinfo feature

In reply to Sasha Levin

Add a KUnit test module (CONFIG_LINEINFO_KUNIT_TEST) that verifies the kallsyms lineinfo feature produces correct source file:line annotations in stack traces.

Export sprint_backtrace() and sprint_backtrace_build_id() as GPL symbols so the test module can exercise the backtrace APIs.

Assisted-by Claude:claude-opus-4-6
---
 kernel/kallsyms.c          |    2 +
 lib/Kconfig.debug          |   10 +
 lib/tests/Makefile         |    3 +
 lib/tests/lineinfo_kunit.c | 1040 ++++++++++++++++++++++++++++++++++++
 4 files changed, 1055 insertions(+)
 create mode 100644 lib/tests/lineinfo_kunit.c
kernel/kallsyms.c +2 -0
index b5eff2ba8e5d..b0475f1e7f79 100644
@@ -656,6 +656,7 @@ int sprint_backtrace(char *buffer, unsigned long address)
 {
 	return __sprint_symbol(buffer, address, -1, 1, 0, 1);
 }
+EXPORT_SYMBOL_GPL(sprint_backtrace);
 
 /**
  * sprint_backtrace_build_id - Look up a backtrace symbol and return it in a text buffer
@@ -676,6 +677,7 @@ int sprint_backtrace_build_id(char *buffer, unsigned long address)
 {
 	return __sprint_symbol(buffer, address, -1, 1, 1, 1);
 }
+EXPORT_SYMBOL_GPL(sprint_backtrace_build_id);
 
 /* To avoid using get_symbol_offset for every symbol, we carry prefix along. */
 struct kallsym_iter {
lib/Kconfig.debug +10 -0
index 1244dcac2294..257b5ca442f3 100644
@@ -3092,6 +3092,16 @@ config LONGEST_SYM_KUNIT_TEST
 
 	  If unsure, say N.
 
+config LINEINFO_KUNIT_TEST
+	tristate "KUnit tests for kallsyms lineinfo" if !KUNIT_ALL_TESTS
+	depends on KUNIT && KALLSYMS_LINEINFO
+	default KUNIT_ALL_TESTS
+	help
+	  KUnit tests for the kallsyms source line info feature.
+	  Verifies that stack traces include correct (file.c:line) annotations.
+
+	  If unsure, say N.
+
 config HW_BREAKPOINT_KUNIT_TEST
 	bool "Test hw_breakpoint constraints accounting" if !KUNIT_ALL_TESTS
 	depends on HAVE_HW_BREAKPOINT
lib/tests/Makefile +3 -0
index 4ead57602eac..877416f5f70a 100644
@@ -37,6 +37,9 @@ obj-$(CONFIG_LIVEUPDATE_TEST) += liveupdate.o
 CFLAGS_longest_symbol_kunit.o += $(call cc-disable-warning, missing-prototypes)
 obj-$(CONFIG_LONGEST_SYM_KUNIT_TEST) += longest_symbol_kunit.o
 
+CFLAGS_lineinfo_kunit.o += $(call cc-option,-fno-inline-functions-called-once)
+obj-$(CONFIG_LINEINFO_KUNIT_TEST) += lineinfo_kunit.o
+
 obj-$(CONFIG_MEMCPY_KUNIT_TEST) += memcpy_kunit.o
 obj-$(CONFIG_MIN_HEAP_KUNIT_TEST) += min_heap_kunit.o
 CFLAGS_overflow_kunit.o = $(call cc-disable-warning, tautological-constant-out-of-range-compare)
lib/tests/lineinfo_kunit.c new file +1040 -0

1,040 lines not on this page · raw message

Signature · 1 line
2.53.0
#8 lore raw

Re: [PATCH v8 4/4] kallsyms: add KUnit tests for lineinfo feature

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

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

New issues:
- [Medium] The KUnit test test_sprint_symbol_format unconditionally fails because it mistakenly expects +0x for a zero offset.

Pre-existing issues:
- [High] kallsyms_lookup_buildid() can return negative error codes like -E2BIG, leading to a stack buffer underflow in __sprint_symbol(). --

--- Patch [4]: [PATCH v8 4/4] kallsyms: add KUnit tests for lineinfo feature --- commit 337c29ff08b7b23d898a00240203617a93c2c906
Author: Sasha Levin <[email protected]>

kallsyms: add KUnit tests for lineinfo feature

Add a KUnit test module (CONFIG_LINEINFO_KUNIT_TEST) that verifies the kallsyms lineinfo feature produces correct source file:line annotations in stack traces.

kernel/kallsyms.c

Quoted 4 lines
kernel/kallsyms.c +0 -0
index b5eff2ba8e5d7..b0475f1e7f791 100644

[Severity: High]
This is a pre-existing issue, but could this lead to a stack buffer underflow?

In kernel/kallsyms.c:__sprint_symbol():

    len = kallsyms_lookup_buildid(address, &size, &offset, &modname, &buildid,
                                   buffer);
    if (!len)
        return sprintf(buffer, "0x%lx", address - symbol_offset);
    
    ...
    if (add_offset)
        len += sprintf(buffer + len, "+%#lx/%#lx", offset, size);

If a loadable module or BPF program contains a symbol name that exceeds KSYM_NAME_LEN, functions like module_address_lookup() return -E2BIG (-7). This negative value propagates up through kallsyms_lookup_buildid() and bypasses the 'if (!len)' check.

Would 'buffer + len' then point before the allocated buffer, causing an out-of-bounds write during the subsequent sprintf?

[ ... ]

Quoted 6 lines
lib/tests/lineinfo_kunit.c new file +0 -0
new file mode 100644
index 0000000000000..2e66e8ebb3124
@@ -0,0 +1,1040 @@

[ ... ]

lib/tests/lineinfo_kunit.c line 345

Quoted 10 lines
lib/tests/lineinfo_kunit.c new file +10 -0
+static void test_sprint_symbol_format(struct kunit *test)
+{
+	char *buf = alloc_sym_buf(test);
+	unsigned long addr = target_addr(lineinfo_target_normal);
+
+	sprint_symbol(buf, addr);
+
+	/* Should contain +0x and /0x for offset/size */
+	KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(buf, "+0x"),
+				  "Missing offset in: %s", buf);

[Severity: Medium]
Will this assertion fail unconditionally due to standard C formatting rules?

Since test_sprint_symbol_format() passes the exact start address of lineinfo_target_normal, the resulting offset is 0.

When __sprint_symbol() formats a zero offset using '+%#lx/%#lx', the '%#lx' specifier omits the '0x' prefix for a zero value, resulting in '+0/' instead of '+0x0/'.

Does this cause strstr(buf, "+0x") to always return NULL and break the test?

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