Skip to contentSkip to conversation

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

PATCH Superseded Sasha Levin 2 participants 9 messages Jul 6

Subsystems (4)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

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

This series adds CONFIG_KALLSYMS_LINEINFO, which embeds source file:line information directly in the kernel image so that stack traces annotate every frame with the originating source location - no external tools, no debug symbols at runtime, and safe to use in NMI/panic context.

Motivation
==========

The recent "slowly decommission bugzilla?" thread surfaced a recurring
problem: when users encounter kernel crashes they see stack traces like func+0x1ec/0x240 but have no way to identify which subsystem or maintainer to contact. Richard Weinberger proposed building a database mapping symbols to source files using nm/DWARF. Linus pointed to scripts/decode_stacktrace.sh as the existing solution. But as the discussion progressed, it became clear that decode_stacktrace.sh has significant practical barriers that prevent it from being useful in the common case.

Problems with scripts/decode_stacktrace.sh
==========================================

- Requires debug symbols: the script needs vmlinux with DWARF debug info. Many distros don't retain debug symbols for older or security kernels, and even when available, asking users to obtain matching debuginfo packages is a significant hurdle.

- Requires toolchain: users need addr2line and nm installed.

- Version-matching requirement: debug symbols must exactly match the running kernel binary.

What this series does
=====================

Patch 1: CONFIG_KALLSYMS_LINEINFO

At build time, a host tool (scripts/gen_lineinfo) reads DWARF .debug_line from vmlinux, extracts address-to-file:line mappings, and embeds them as sorted lookup tables in .rodata. At runtime, kallsyms_lookup_lineinfo() binary-searches the table and sprint_backtrace() appends "(file:line)" to each stack frame. NMI/panic-safe (no locks, no allocations), KASLR-compatible.

Patch 2: CONFIG_KALLSYMS_LINEINFO_MODULES

Extends lineinfo to loadable modules. Each .ko gets .mod_lineinfo and .init.mod_lineinfo sections embedded at build time, each carrying one or more per-section sub-tables identified by an ELF relocation against the covered text section's symbol. The module loader's existing apply_relocations() pass resolves the anchor on load - no special-cased loader logic, no implicit MOD_TEXT-base assumption. Coverage extends to .text, .exit.text, and .init.text; the init blob is freed alongside init memory.

Patch 3: delta compression

Block-indexed delta-encoding with LEB128 varints, implementing the approach suggested by Juergen Gross in the RFC review. Reduces overhead from ~44 MiB to ~11 MiB (~3.7 bytes/entry), addressing the primary size concern from the RFC. Compression applies independently to each per-section table inside the module blobs.

Patch 4: KUnit tests

30 KUnit tests covering the lineinfo lookup paths, delta-decode logic, boundary conditions, the module-side multi-section format, and integration with the backtrace formatting APIs.

Example output
==============

  [   11.206749]  dump_stack_lvl+0x5d/0x80 (lib/dump_stack.c:94)
  [   11.207403]  vpanic+0x36e/0x620 (kernel/panic.c:650)
  [   11.209324]  panic+0xc9/0xd0 (kernel/panic.c:787)
  [   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)

Size impact
===========

Measured with a Debian kernel config:

- bzImage: +3.6 MiB (14 MiB -> 18 MiB, +26%)
- Runtime memory: +5.9 MiB (text+data+bss)
- Code overhead: +5.0 KiB (.text, lookup functions only)
- Data overhead: +5.9 MiB (.data, lineinfo tables)

The ~5.9 MiB is after 2.7x delta compression; uncompressed would be ~16 MiB. This is a fraction of the cost of shipping full DWARF debug info (hundreds of MiB), which distros must store and serve for every kernel version.

For distros, maintaining debug symbol repositories is expensive:
storage, mirrors, and CDN bandwidth for hundreds of MiB per kernel build add up quickly. A ~5.9 MiB increase in the kernel image itself is a modest cost that eliminates the need for users to find, download, and version-match debuginfo packages just to make a crash report useful.

For developers, the file:line annotations appear immediately in crash traces - no post-processing with decode_stacktrace.sh needed.

Changes since v5
================

- Rebased onto v7.2-rc2:

- scripts/Makefile.modfinal: adapt to the removal of if_changed_except in commit 7abef41afad05b ("kbuild/btf: Remove broken module relinking exclusion").

- Drop unrelated MAINTAINERS hunks that had leaked into patch 2 during v5 preparation; those updates are already upstream.

Changes since v4
================

- Replace mod->mem[MOD_TEXT].base derivation with an ELF relocation against the covered section's symbol; resolved by the module loader on load. (Suggested by Petr Pavlu)

- Cover .exit.text and .init.text in addition to .text. Init code lives in a parallel .init.mod_lineinfo blob (MOD_INIT_RODATA) that is revoked and freed alongside init memory.

- Switch the build step from objcopy --add-section to ld -r, so .rela.mod_lineinfo / .rela.init.mod_lineinfo ride along into the .ko.

- Pick up lineinfo sections via section_objs() (not any_section_objs) to validate SHF_ALLOC and avoid dangling pointers into the temporary load image.

- Drop the unused "reserved" placeholder field from mod_lineinfo_root and mod_lineinfo_header. (Suggested by Petr Pavlu)

- Guard the per-module fields with #ifdef CONFIG_KALLSYMS_LINEINFO_MODULES and expose them via inline reader accessors. (Suggested by Petr Pavlu)

- Update the per-section header layout comment to name struct fields. (Suggested by Petr Pavlu)

- Cap vmlinux-side captured DWARF addresses at _etext: sections placed after .rodata shift as the real lineinfo replaces the empty stub during the multi-pass link, so addresses outside the invariant .text window become stale in the final image.

- Append "(file:line)" only via sprint_backtrace*(), not plain sprint_symbol*() (which backs %ps); many format strings already follow %ps with literal "()" and would otherwise render as "foo (file:line)()". KUnit gains a sprint_with_lineinfo() helper.

- Build-side fixes in scripts/gen_lineinfo: apply 64-bit absolute relocations to .debug_line (libdw doesn't relocate ET_REL inputs); endian-safe writes for cross-builds; declare empty .text/.exit.text/.init.text stanzas so ld -r binds anchors to LOCAL rather than GLOBAL UND symbols.

Changes since v3
=================

- Remove redundant gen_lineinfo entry in scripts/Makefile for CONFIG_KALLSYMS_LINEINFO_MODULES (depends on CONFIG_KALLSYMS_LINEINFO which already builds it). (Reported by Petr Pavlu)

- Use R_* constants from <elf.h> instead of hardcoded relocation type values in r_type_abs32(). (Reported by Petr Pavlu)

- Simplify duplicated-path detection in make_relative(): replace loop over every '/' with a direct midpoint check, since true path duplication always splits at len/2. (Suggested by Petr Pavlu)

- Fix comment in process_dwarf(): sections in ET_REL objects have sh_addr == 0 and therefore overlapping address ranges; this is expected behavior, not a "may" situation. (Reported by Petr Pavlu)

- Use U32_MAX instead of UINT_MAX for the module raw_offset bounds check, matching the u32 type of the addrs array. (Reported by Petr Pavlu)

- Document the assumption that .text is at the start of the MOD_TEXT segment in module_lookup_lineinfo(). A proper fix using ELF relocations is planned for a future series.
(Reported by Petr Pavlu)

- Wrap -fno-inline-functions-called-once in $(call cc-option,...) for clang compatibility. Clang does not support this GCC-specific flag; the noinline attribute is sufficient.

Changes since v2
=================

- Replace #ifdef CONFIG_KALLSYMS_LINEINFO with IS_ENABLED() throughout, so the compiler checks the code for syntax errors regardless of configuration. (Suggested by Helge Deller)

- Replace zigzag + ULEB128 encoding of signed deltas with native SLEB128, removing the unnecessary zigzag transform layer.
(Suggested by Vivian Wang)

- Deduplicate the binary search and delta-decode logic: extract shared struct lineinfo_table and lineinfo_search() into mod_lineinfo.h instead of maintaining near-identical copies in kernel/kallsyms.c and kernel/module/kallsyms.c. (Suggested by Vivian Wang)

- Use .uleb128 / .sleb128 assembler directives in gen_lineinfo output instead of encoding varints in C and emitting .byte hex literals. (Suggested by Vivian Wang)

- Redesign module mod_lineinfo_header to use explicit (offset, size) pairs for each sub-array, similar to flattened devicetree layout. This makes bounds validation straightforward: offset + size <= section_size. (Suggested by Vivian Wang)

- Remove dead sym_start parameter from kallsyms_lookup_lineinfo() and module_lookup_lineinfo().

Changes since v1
=================

- Fix path stripping regression on architectures where DWARF comp_dir is a subdirectory (e.g. arch/parisc/kernel) rather than the source tree
root: paths now correctly show "kernel/traps.c:212" instead of bare "traps.c:212". Added kernel_dirs[] fallback scan and bare-filename recovery via comp_dir. (Reported by Helge Deller)

- Fix RST heading: overline/underline must be at least as long as the heading text in kallsyms-lineinfo.rst. (Reported by Randy Dunlap)

- Fix MAINTAINERS alphabetical ordering: move KALLSYMS LINEINFO entry before KASAN. (Reported by Randy Dunlap)

- Fix arch-portability of .debug_line relocation handling: replace hardcoded R_X86_64_32 with r_type_abs32() supporting x86, arm, arm64, riscv, s390, mips, ppc, loongarch, and parisc.

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                      |   17 +-
 include/linux/mod_lineinfo.h                  |  280 ++++
 include/linux/module.h                        |   39 +
 init/Kconfig                                  |   35 +
 kernel/kallsyms.c                             |   78 +-
 kernel/kallsyms_internal.h                    |   11 +
 kernel/module/kallsyms.c                      |  171 +++
 kernel/module/main.c                          |   26 +
 lib/Kconfig.debug                             |   10 +
 lib/tests/Makefile                            |    3 +
 lib/tests/lineinfo_kunit.c                    |  855 +++++++++++
 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                        | 1322 +++++++++++++++++
 scripts/kallsyms.c                            |   17 +
 scripts/link-vmlinux.sh                       |   43 +-
 22 files changed, 3102 insertions(+), 10 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

base-commit: 8cdeaa50eae8dad34885515f62559ee83e7e8dda

Signature · 1 line
2.53.0
#1 lore raw

PATCH v6 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 elfutils (libdw-dev) on the build host.

Memory footprint measured with a 1852-option x86_64 config:

Table: 4,597,583 entries from 4,841 source files

    lineinfo_addrs[]     4,597,583 x u32  = 17.5 MiB
    lineinfo_file_ids[]  4,597,583 x u16  =  8.8 MiB
    lineinfo_lines[]     4,597,583 x u32  = 17.5 MiB
    file_offsets + filenames              ~  0.1 MiB

Total .rodata increase: ~ 44.0 MiB

vmlinux (stripped): 529 MiB -> 573 MiB (+44 MiB / +8.3%)

The .config used for testing is a simple KVM guest configuration for local development and testing.

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                      |  17 +-
 init/Kconfig                                  |  20 +
 kernel/kallsyms.c                             |  76 ++-
 kernel/kallsyms_internal.h                    |   9 +
 scripts/.gitignore                            |   1 +
 scripts/Makefile                              |   3 +
 scripts/empty_lineinfo.S                      |  30 +
 scripts/gen_lineinfo.c                        | 557 ++++++++++++++++++
 scripts/kallsyms.c                            |  16 +
 scripts/link-vmlinux.sh                       |  43 +-
 13 files changed, 841 insertions(+), 10 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 cd28dfe91b0607..37456e08fe43cd 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 4a8b0fd665ce24..b98d57b1ee1d5b 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 +16 -1
index d5dd54c53ace61..7d4c9dca06c872 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,
+			      const char **file, unsigned int *line);
+
 #else /* !CONFIG_KALLSYMS */
 
 static inline unsigned long kallsyms_lookup_name(const char *name)
@@ -164,6 +172,13 @@ static inline int kallsyms_on_each_match_symbol(int (*fn)(void *, unsigned long)
 {
 	return -EOPNOTSUPP;
 }
+
+static inline bool kallsyms_lookup_lineinfo(unsigned long addr,
+					    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 5230d4879b1c84..f004cf9a69d40a 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 elfutils (libdw-dev/elfutils-devel) on the build host.
+	  Adds approximately 44MB to a typical kernel image (10 bytes per
+	  DWARF line-table entry, ~4.6M entries for a typical config).
+
+	  If unsure, say N.
+
 # end of the "standard kernel features (expert users)" menu
 
 config ARCH_HAS_MEMBARRIER_CALLBACKS
kernel/kallsyms.c +70 -6

120 lines not on this page · raw message

kernel/kallsyms_internal.h +9 -0
index 81a867dbe57d48..d7374ce444d811 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 4215c2208f7e41..e175714c18b616 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 3434a82a119f09..55244ce9557811 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 -lz)
 
 ifdef CONFIG_UNWINDER_ORC
 ifeq ($(ARCH),x86_64)
scripts/empty_lineinfo.S new file +30 -0
new file mode 100644
index 00000000000000..e058c411371237
@@ -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 +557 -0

557 lines not on this page · raw message

scripts/kallsyms.c +16 -0
index 37d5c095ad22a5..42662c4fbc6c94 100644
@@ -78,6 +78,17 @@ static char *sym_name(const struct sym_entry *s)
 
 static bool is_ignored_symbol(const char *name, char type)
 {
+	/* Ignore lineinfo symbols for kallsyms pass stability */
+	static const char * const lineinfo_syms[] = {
+		"lineinfo_addrs",
+		"lineinfo_file_ids",
+		"lineinfo_file_offsets",
+		"lineinfo_filenames",
+		"lineinfo_lines",
+		"lineinfo_num_entries",
+		"lineinfo_num_files",
+	};
+
 	if (type == 'u' || type == 'n')
 		return true;
 
@@ -90,6 +101,11 @@ static bool is_ignored_symbol(const char *name, char type)
 			return true;
 	}
 
+	for (size_t i = 0; i < ARRAY_SIZE(lineinfo_syms); i++) {
+		if (!strcmp(name, lineinfo_syms[i]))
+			return true;
+	}
+
 	return false;
 }
 
scripts/link-vmlinux.sh +40 -3

81 lines not on this page · raw message

Signature · 1 line
2.53.0
#3 lore raw

PATCH v6 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                  | 104 +++
 include/linux/module.h                        |  39 +
 init/Kconfig                                  |  19 +-
 kernel/kallsyms.c                             |  18 +-
 kernel/module/kallsyms.c                      | 181 ++++
 kernel/module/main.c                          |  26 +
 scripts/Makefile.modfinal                     |   6 +
 scripts/gen-mod-lineinfo.sh                   |  50 +
 scripts/gen_lineinfo.c                        | 854 ++++++++++++++++--
 11 files changed, 1250 insertions(+), 91 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 c8ec124394354e..dd264830c8d5bf 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 b98d57b1ee1d5b..d7e1c1de7998f5 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 +104 -0

104 lines not on this page · raw message

include/linux/module.h +39 -0
index 7566815fabbe8b..2bc0263b086d27 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,39 @@ 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,
+			    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 +17 -2
index f004cf9a69d40a..79975a6e67c21b 100644
@@ -2102,8 +2102,23 @@ config KALLSYMS_LINEINFO
 	    anon_vma_clone+0x2ed/0xcf0 (mm/rmap.c:412)
 
 	  This requires elfutils (libdw-dev/elfutils-devel) on the build host.
-	  Adds approximately 44MB to a typical kernel image (10 bytes per
-	  DWARF line-table entry, ~4.6M entries for a typical config).
+	  Adds approximately 10-15MB to a typical kernel image (~2-3 bytes
+	  per entry after delta compression, ~4.6M entries for a typical
+	  config).
+
+	  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.
+
+	  Requires elfutils (libdw-dev/elfutils-devel) on the build host.
+	  Increases .ko sizes by approximately 2-3 bytes per DWARF line
+	  entry after delta compression.
 
 	  If unsure, say N.
 
kernel/kallsyms.c +15 -3
index 1e3f527b13988b..d95387f51b4c08 100644
@@ -551,12 +551,24 @@ 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,
+							 &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,
+							       &li_file,
+							       &li_line);
+		}
 
-		if (kallsyms_lookup_lineinfo(address,
-					     &li_file, &li_line))
+		if (found)
 			len += snprintf(buffer + len, KSYM_SYMBOL_LEN - len,
 					" (%s:%u)", li_file, li_line);
 	}
kernel/module/kallsyms.c +181 -0

184 lines not on this page · raw message

kernel/module/main.c +26 -0
index 46dd8d25a6058e..46bb2bf799d1ee 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 01a37ec872b905..2cdd76becb4d52 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 +776 -78

1,012 lines not on this page · raw message

Signature · 1 line
2.53.0
#5 lore raw

PATCH v6 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 a defconfig+debug x86_64 build (3,017,154 entries, 4,822 source files, 47,144 blocks):

Before (flat arrays):

    lineinfo_addrs[]    12,068,616 bytes (u32 x 3.0M)
    lineinfo_file_ids[]  6,034,308 bytes (u16 x 3.0M)
    lineinfo_lines[]    12,068,616 bytes (u32 x 3.0M)
    Total:              30,171,540 bytes (28.8 MiB, 10.0 bytes/entry)

After (block-indexed delta + ULEB128):

    lineinfo_block_addrs[]    188,576 bytes (184 KiB)
    lineinfo_block_offsets[]  188,576 bytes (184 KiB)
    lineinfo_data[]        10,926,128 bytes (10.4 MiB)
    Total:                 11,303,280 bytes (10.8 MiB, 3.7 bytes/entry)

Savings: 18.0 MiB (2.7x reduction)

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 | 236 ++++++++++++++++++++++++++++++-----
 kernel/kallsyms.c            |  46 +++----
 kernel/kallsyms_internal.h   |   8 +-
 kernel/module/kallsyms.c     | 106 +++++++---------
 scripts/empty_lineinfo.S     |  20 ++-
 scripts/gen_lineinfo.c       | 185 ++++++++++++++++++---------
 scripts/kallsyms.c           |   7 +-
 7 files changed, 420 insertions(+), 188 deletions(-)
include/linux/mod_lineinfo.h +206 -30
index 9cda3263a07847..a3c71434330203 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
@@ -40,9 +51,12 @@
 #include <stdint.h>
 typedef uint32_t u32;
 typedef uint16_t u16;
+typedef uint8_t  u8;
 typedef uint64_t u64;
 #endif
 
+#define LINEINFO_BLOCK_ENTRIES 64
+
 /*
  * Per-section descriptor.  One entry per ELF text section covered by the
  * blob (.text, .exit.text, .init.text, ...).
@@ -66,39 +80,201 @@ struct mod_lineinfo_root {
 
 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)(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 .text base for modules).
+ *
+ * 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,
+				   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_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_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_file_id = cur_file_id;
+		best_line = cur_line;
+		found = true;
+	}
+
+	if (!found)
+		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 */
kernel/kallsyms.c +17 -29

64 lines not on this page · raw message

kernel/kallsyms_internal.h +5 -3
index d7374ce444d811..ffe4c658067ecc 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 +48 -58

154 lines not on this page · raw message

scripts/empty_lineinfo.S +14 -6
index e058c411371237..edd5b1092f0503 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 +126 -59

246 lines not on this page · raw message

scripts/kallsyms.c +4 -3
index 42662c4fbc6c94..94fbdad3df7c6e 100644
@@ -80,11 +80,12 @@ static bool is_ignored_symbol(const char *name, char type)
 {
 	/* Ignore lineinfo symbols for kallsyms pass stability */
 	static const char * const lineinfo_syms[] = {
-		"lineinfo_addrs",
-		"lineinfo_file_ids",
+		"lineinfo_block_addrs",
+		"lineinfo_block_offsets",
+		"lineinfo_data",
 		"lineinfo_file_offsets",
 		"lineinfo_filenames",
-		"lineinfo_lines",
+		"lineinfo_num_blocks",
 		"lineinfo_num_entries",
 		"lineinfo_num_files",
 	};
Signature · 1 line
2.53.0
#7 lore raw

PATCH v6 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 | 855 +++++++++++++++++++++++++++++++++++++
 4 files changed, 870 insertions(+)
 create mode 100644 lib/tests/lineinfo_kunit.c
kernel/kallsyms.c +2 -0
index 1f58b4123a8ae7..6ac2786cdcbcbd 100644
@@ -633,6 +633,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
@@ -653,6 +654,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 1244dcac2294ad..257b5ca442f327 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 4ead57602eac46..877416f5f70a3e 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 +855 -0

855 lines not on this page · raw message

Signature · 1 line
2.53.0
#6 lore raw

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

In reply to Sasha Levin
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] lineinfo_read_sleb128 contains a signed left shift that can overflow on malformed or large data…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] lineinfo_read_sleb128 contains a signed left shift that can overflow on malformed or large data, triggering a UBSAN splat in NMI/panic contexts. --

commit 3756e632dbdf4d6db79f0e2c8a39f6103ac6e8ad
Author: Sasha Levin <[email protected]>

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

This patch replaces the flat uncompressed parallel arrays for lineinfo with a block-indexed, delta-encoded, ULEB128/SLEB128 varint compressed format to significantly reduce size. Entries are grouped into blocks of 64 and decoded entirely on the stack to ensure safety during NMI or panic contexts.

Quoted 4 lines
include/linux/mod_lineinfo.h +0 -0
index 9cda3263a0784..a3c7143433020 100644

[ ... ]

include/linux/mod_lineinfo.h struct mod_lineinfo_root {

Quoted 11 lines
include/linux/mod_lineinfo.h +11 -0
+/* Read an SLEB128 varint. Same safety guarantees as above. */
+static inline int32_t lineinfo_read_sleb128(const u8 *data, u32 *pos, u32 end)
+{
+	int32_t result = 0;
+	unsigned int shift = 0;
+	u8 byte = 0;
+
+	while (*pos < end) {
+		byte = data[*pos];
+		(*pos)++;
+		result |= (int32_t)(byte & 0x7f) << shift;

[Severity: High]
Can this signed left shift trigger a UBSAN splat on malformed or large data?

For the 5th byte of an SLEB128 varint, shift will be 28. If the decoded byte has a value greater than 7 (e.g. 0x7F), 127 << 28 evaluates to 3409130496, which exceeds INT32_MAX.

Since left-shifting into or past the sign bit of a signed integer is undefined behavior in C, a corrupted or maliciously crafted .mod_lineinfo section could trigger a CONFIG_UBSAN_SHIFT splat.

If this function is called by lineinfo_search() during an NMI or panic context, would the resulting UBSAN splat attempt to take locks and call printk, potentially causing a deadlock or nested panic?

Perhaps the shift should be performed as unsigned:
result |= (int32_t)((u32)(byte & 0x7f) << shift);

Quoted 6 lines
include/linux/mod_lineinfo.h +6 -0
+		shift += 7;
+		if (!(byte & 0x80))
+			break;
+		if (shift >= 32) {
+			while (*pos < end && (data[*pos] & 0x80))
+				(*pos)++;

[ ... ]

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

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

In reply to Sasha Levin
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] `apply_debug_line_relocations()` ignores `.rel.debug_line` (SHT_REL), breaking module lineinfo on…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] apply_debug_line_relocations() ignores .rel.debug_line (SHT_REL), breaking module lineinfo on 32-bit architectures like i386 and ARM.
- [High] Misattribution of DWARF line entries for unhandled text sections pollutes .text lineinfo.
- [High] Hardcoded assembly padding creates an ABI mismatch with the C struct layout on architectures where alignof(u64) == 4 (e.g., 32-bit x86).
- [Medium] An integer overflow in relocation offset validation allows an out-of-bounds write in the gen_lineinfo build tool. --

commit a6a5ac22ccec63c8ea45f4ded1db6418cd100063
Author: Sasha Levin <[email protected]>
Subject: kallsyms: extend lineinfo to loadable modules

This commit extends the CONFIG_KALLSYMS_LINEINFO feature to loadable kernel modules. It post-processes modules at build time to generate per-section .mod_lineinfo binary tables mapping addresses to source lines. The tables are embedded in the module and searched during stack traces.

Quoted 4 lines
scripts/gen_lineinfo.c +0 -0
index 699e760178f09..e1e08469b4f2f 100644

[ ... ]

Quoted 10 lines
scripts/gen_lineinfo.c +10 -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 unsigned long long find_text_addr(Elf *elf) · line 577

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 (shdr.sh_type == SHT_SYMTAB)
+			symtab_scn = scn;
+	}
+
+	if (!debug_line_scn || !rela_debug_line_scn || !symtab_scn)
+		return;

[Severity: High]
Does apply_debug_line_relocations() skip .rel.debug_line sections?

On 32-bit architectures like i386 and ARM, relocations use SHT_REL and generate a .rel.debug_line section rather than .rela.debug_line.

If the function bails out here, synthetic biases are never added and DW_FORM_line_strp offsets remain un-relocated, which feeds zeros to libdw. Could this break the module lineinfo feature entirely on these architectures?

[ ... ]

scripts/gen_lineinfo.c static unsigned long long find_text_addr(Elf *elf) · line 642

Quoted 8 lines
scripts/gen_lineinfo.c +8 -0
+		if (module_mode) {
+			struct covered_section *cs;
+
+			cs = section_by_index(all_sections, ALL_SECTIONS,
+					      sym.st_shndx);
+			if (cs)
+				value += cs->bias;
+		}

[Severity: High]
Could unbiased text sections pollute the .text lineinfo?

Sections not listed in all_sections[], such as .noinstr.text, do not receive a synthetic bias here, leaving their relocated DWARF PCs starting at 0.

When classify_address() processes these entries:

classify_address() {
    ...
    if (addr < sections[i].bias)
        continue;
    if (addr >= sections[i].bias + sections[i].size)
        continue;
    ...
}

An address smaller than the size of .text will fall into the .text bucket, since .text has a bias of 0. Would this incorrectly merge line entries and corrupt the binary search invariant?

[ ... ]

scripts/gen_lineinfo.c static unsigned long long find_text_addr(Elf *elf) · line 651

Quoted 8 lines
scripts/gen_lineinfo.c +8 -0
+		if (!is_abs64)
+			value &= 0xffffffffULL;
+
+		if (rela.r_offset + width <= dl_data->d_size)
+			elf_write_uint((unsigned char *)dl_data->d_buf +
+					       rela.r_offset,
+				       value, width, target_le);
+	}

[Severity: Medium]
Is there a risk of an integer overflow in this bounds check?

If a maliciously crafted ELF file provides a huge r_offset value from the relocation section (such as UINT64_MAX), the addition of width could wrap around to a small positive integer and bypass the check. This might lead to an out-of-bounds write in elf_write_uint().

[ ... ]

Quoted 4 lines
scripts/gen_lineinfo.c +4 -0
+static void emit_blob(const char *output_section,
+		      const char *blob_tag,
+		      enum mod_lineinfo_blob blob)
+{

[ ... ]

scripts/gen_lineinfo.c static void output_assembly(void) · line 1037

Quoted 7 lines
scripts/gen_lineinfo.c +7 -0
+	printf("\t.section %s, \"a\"\n\n", output_section);
+
+	printf("\t.balign 8\n");
+	printf(".Lroot_%s:\n", blob_tag);
+	printf("\t.long %u\t\t/* num_sections */\n", active);
+	/* Pad to align the u64 anchor in sections[0] to 8 bytes. */
+	printf("\t.balign 8\n");

[Severity: High]
Does this hardcoded padding create an ABI mismatch with the mod_lineinfo_root C struct on some architectures?

The assembly forces an 8-byte alignment immediately following the 4-byte num_sections field. However, on 32-bit x86 architectures, the System V ABI sets alignof(u64) to 4.

Looking at include/linux/mod_lineinfo.h:

struct mod_lineinfo_root {
    u32 num_sections;
    struct mod_lineinfo_section sections[];
};

The C compiler will align the struct to 4 bytes, meaning the sections[] flexible array starts at offset 4, not offset 8. If the kernel reads this blob, could it parse the assembly padding as the start of the anchor field and corrupt the section descriptors?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#2 lore raw
In reply to Sasha Levin
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Assembly routines and other un-annotated symbols will be falsely annotated with the file and…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Assembly routines and other un-annotated symbols will be falsely annotated with the file and line number of the preceding C function because the binary search does not restrict lookups to the boundaries of the resolved symbol.
- [Low] Unchecked strdup return value causes a segmentation fault on memory allocation failure in the gen_lineinfo host tool.
--

commit 8ad0e66e84394fea4bf24efbedda7eb50bbe8269
Author: Sasha Levin <[email protected]>

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

This commit adds CONFIG_KALLSYMS_LINEINFO to embed an address-to-line lookup table in the kernel image. A new host tool extracts DWARF data at build time, allowing stack traces to directly include source file and line number information.

Quoted 11 lines
kernel/kallsyms.c +3 -0
index aec2f06858afd..1e3f527b13988 100644
@@ -497,6 +544,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

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

Quoted 10 lines
kernel/kallsyms.c +10 -0
+	 * literal "()" after %ps to indicate a function call ("foo()
+	 * replaced with bar()"); appending lineinfo there would produce a
+	 * 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,
+					     &li_file, &li_line))

[Severity: Medium]
Will this falsely annotate assembly routines or un-annotated symbols with the file and line number of the preceding C function?

The caller has access to the resolved symbol's size and offset but fails to pass this bounding information to kallsyms_lookup_lineinfo(). The binary search in kallsyms_lookup_lineinfo() does not restrict lookups to the boundaries of the resolved symbol, finding the closest preceding entry.

Since gen_lineinfo explicitly ignores DW_LNE_end_sequence markers, could this regression cause the search to bleed across symbol boundaries?

Quoted 13 lines
kernel/kallsyms.c +4 -0
+			len += snprintf(buffer + len, KSYM_SYMBOL_LEN - len,
+					" (%s:%u)", li_file, li_line);
+	}
+
 	return len;
 }
 
scripts/gen_lineinfo.c new file +0 -0
new file mode 100644
index 0000000000000..699e760178f09
@@ -0,0 +1,557 @@

[ ... ]

scripts/gen_lineinfo.c line 117

Quoted 9 lines
scripts/gen_lineinfo.c new file +9 -0
+	if (num_files >= files_capacity) {
+		files_capacity = files_capacity ? files_capacity * 2 : 4096;
+		files = realloc(files, files_capacity * sizeof(*files));
+		if (!files) {
+			fprintf(stderr, "out of memory\n");
+			exit(1);
+		}
+	}
+	files[num_files].name = strdup(name);

[Severity: Low]
Does this code handle memory allocation failures?

strdup() can return NULL on failure, which would be assigned directly to the files array here and could cause a segmentation fault when later dereferenced via strlen().

Quoted 9 lines
scripts/gen_lineinfo.c new file +9 -0
+	files[num_files].id = num_files;
+
+	/* Insert into hash table (points to files[] entry) */
+	file_hash[h].name = files[num_files].name;
+	file_hash[h].id = num_files;
+
+	num_files++;
+	return num_files - 1;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#8 lore raw

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

In reply to Sasha Levin
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Medium] Test failures on architectures using function descriptors - [Medium] Silently failing tests due…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] Test failures on architectures using function descriptors
- [Medium] Silently failing tests due to missing Kconfig dependency for module lineinfo
- [Medium] Test flakiness due to incorrect assumption about compiler optimization and function size
- [Medium] Missing NULL pointer check for test buffer allocation leading to potential kernel panic --

commit 799168a56f108698328a395b2e257d42cad0b5d4
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.

Quoted 4 lines
lib/Kconfig.debug +0 -0
index 1244dcac2294a..257b5ca442f32 100644

[ ... ]

lib/Kconfig.debug config LONGEST_SYM_KUNIT_TEST · line 3097

Quoted 7 lines
lib/Kconfig.debug +3 -0
@@ -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

[Severity: Medium]
If this test is built as a loadable module and CONFIG_KALLSYMS_LINEINFO_MODULES is disabled, will the module lineinfo tests fail at runtime? Should this Kconfig also depend on KALLSYMS_LINEINFO_MODULES when built as a module, or should the test suite gracefully skip module-specific tests if that configuration is not enabled?

Quoted 5 lines
lib/tests/lineinfo_kunit.c new file +0 -0
new file mode 100644
index 0000000000000..285d798cb6a3c

[ ... ]

lib/tests/lineinfo_kunit.c line 27

Quoted 4 lines
lib/tests/lineinfo_kunit.c new file +4 -0
+static char *alloc_sym_buf(struct kunit *test)
+{
+	return kunit_kzalloc(test, KSYM_SYMBOL_LEN, GFP_KERNEL);
+}

[Severity: Medium]
Can kunit_kzalloc() return NULL here and cause a kernel panic when callers unconditionally pass the buffer to sprint_with_lineinfo()? Would it be better to add a KUNIT_ASSERT_NOT_NULL() check here or validate the return value in the callers?

[ ... ]

Quoted 7 lines
lib/tests/lineinfo_kunit.c new file +7 -0
+static noinline int lineinfo_target_many_lines(void)
+{
+	int a = 0;
+
+	barrier();
+	a += 1;
+	a += 2;

[ ... ]

lib/tests/lineinfo_kunit.c line 154

Quoted 4 lines
lib/tests/lineinfo_kunit.c new file +4 -0
+	a += 10;
+	barrier();
+	return a;
+}

[Severity: Medium]
Is it possible that standard compiler optimizations will fold the arithmetic in this function away, causing it to compile to fewer than 8 bytes?

If that happens, wouldn't the test_many_lines_mid_function() test below fail because it adds 8 bytes to the start address and ends up looking outside the function bounds? Should WRITE_ONCE() or inline assembly be used here to prevent the arithmetic from being optimized out?

[ ... ]

lib/tests/lineinfo_kunit.c line 184

Quoted 4 lines
lib/tests/lineinfo_kunit.c new file +4 -0
+static void test_normal_function(struct kunit *test)
+{
+	char *buf = alloc_sym_buf(test);
+	unsigned long addr = (unsigned long)lineinfo_target_normal;

[Severity: Medium]
On architectures that use function descriptors (like PowerPC ELFv1 or ia64), will casting lineinfo_target_normal directly to unsigned long yield a data descriptor address instead of the instruction pointer?

Could this cause sprint_backtrace() to fail to resolve the symbol, breaking the tests unconditionally on those architectures? Does this require using dereference_symbol_descriptor() to get the actual instruction pointer?

[ ... ]

lib/tests/lineinfo_kunit.c line 374

Quoted 8 lines
lib/tests/lineinfo_kunit.c new file +8 -0
+static void test_pBb_format(struct kunit *test)
+{
+	char *buf = alloc_sym_buf(test);
+	/*
+	 * %pBb uses sprint_backtrace_build_id which subtracts 1 from the
+	 * address, so pass addr+1 to resolve back to the function.
+	 */
+	void *addr = (void *)((unsigned long)lineinfo_target_normal + 1);

[Severity: Medium]
Similarly, adding 1 to a function descriptor pointer instead of an instruction pointer creates a corrupt address. Will this cause snprintf() with %pBb to fail to format the backtrace correctly on architectures using function descriptors?

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