kallsyms: embed source file:line info in kernel stack traces
Subsystems (4)
v10 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+0x6e/0xb0 (kernel/sched/idle.c:122) do_idle+0x38f/0x660 (kernel/sched/idle.c:199) cpu_startup_entry+0x4e/0x60 (kernel/sched/idle.c:453) rest_init+0x277/0x280 (init/main.c:732) 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.
Why this is useful
==================
A stack trace in a bug report is usually all you get. The reporter has already rebooted, the machine belongs to a customer, or the failure came out of an automated run that tore its environment down an hour ago. What lands in the report is a list of symbol+offset frames:
ext4_do_update_inode+0x2a1/0x4c0 ext4_mark_iloc_dirty+0x5f/0x210 __ext4_mark_inode_dirty+0x9c/0x330
Turning that into source locations requires the exact vmlinux that produced it, with debug info, fed to decode_stacktrace.sh or addr2line. In practice that artifact is the thing that is missing:
- Distributions strip the shipped kernel and put debug info in a separate package of a few hundred megabytes that is not installed by default. Fetching it after the fact only helps if it still matches the build that crashed, and on a machine that has been updated since, it does not.
- A reporter who rebuilds "the same" kernel to decode the trace does not get the same offsets. A different compiler version, one changed config option, or a different link order moves symbols around. The decode then yields plausible but wrong line numbers, which is worse than yielding none, because nothing flags it as wrong.
- Panics captured through pstore/ramoops, a serial console, a photograph of a screen, or a customer's ticket system arrive as text. There is no binary left to go back to.
The usual answer, "please rebuild with CONFIG_DEBUG_INFO and reproduce", quietly ends a good share of investigations: the reproducer is rare, the machine is in production, or the reporter has moved on. With the table embedded, the trace above decodes itself at the point it is printed, on the machine that crashed, with no second artifact to find.
Two cases go beyond convenience, because symbol+offset cannot express them at all:
- Inlining. A frame names the outermost function that survived inlining, so an oops inside a static helper or a header inline reports the caller. The offset is the only clue about which inlined body faulted, and it is not a clue anyone can follow without the binary. A file:line points into the header the code actually came from.
- Assembly. Frames in .S files have no useful decode in a plain trace; here they resolve like any other, for instance arch/x86/entry/entry_64.S:121.
Module frames are the worst case today, since decoding them needs the matching .ko, built with debug info and kept from the build that ran. Patch 2 makes them self-annotating, which matters most for out-of-tree and vendor modules, where the person reading the trace rarely has that.
For anyone triaging at scale, syzbot-style pipelines, distribution crash aggregation, kdump fleets, traces that carry file:line can be clustered by source location instead of by symbol+offset, which changes from build to build. The same trace text stays comparable across kernel versions for far longer.
The feature is opt-in and bounded. On x86_64 defconfig + CONFIG_DEBUG_INFO the stripped image grows 8.0 MiB (52.2 -> 60.2 MiB, +15.3%) with the compression in 3/4. There is no cost on any hot path: the tables are read-only data, consulted when formatting offset-bearing symbols, with no locks and no allocations, so the lookup is safe from NMI and panic context. Lookups use offsets from _text, so KASLR does not disturb them, and nothing is needed at runtime: no debuginfod, no symbol server, no network.
The information all of this rests on already exists at build time. Today it is discarded at the end of the build and asked for again, months later, from whoever hit the bug. This series keeps 8 MiB of it instead.
Changes since v9
================
- Rebase on v7.4-rc1.
- Regenerate the vmlinux table only when text below _etext moves. The table stops at _etext, but the check also compared .init.text, which follows .rodata and moves whenever the real table replaces the stub, so every x86 build took the extra link and generation pass.
- Export sprint_backtrace() and sprint_backtrace_build_id() with EXPORT_SYMBOL_IF_KUNIT() instead of EXPORT_SYMBOL_GPL().
- From the sashiko.dev review of v9: wrap-safe bounds checks on relocation offsets, an sh_entsize check in find_vmlinux_sym(), and freeing the remaining arrays at exit.
- Relink vmlinux when scripts/gen_lineinfo changes, as modules already did.
- Keep the end row of a sequence that ends exactly at _etext, without which the last function below _etext could lose its annotation.
- Skip a module debug section with no data (SHT_NOBITS) rather than writing through a null buffer.
- Documentation: assembly frames are annotated, which the example output and the limitations list said they were not.
- Drop the Assisted-by tags. Tool use is described below instead.
v9: https://lore.kernel.org/all/[email protected]/
Tool use
========
LLM coding assistants were used throughout this series: for parts of the implementation, for review passes over each version, and to build the DWARF fixtures and checking scripts behind the testing below.
Testing
=======
v10 on v7.4-rc1, x86_64 defconfig + CONFIG_DEBUG_INFO, booted under QEMU/KVM:
- KUnit, CONFIG_LINEINFO_KUNIT_TEST=y builtin:
33 passed, 0 failed, 1 skipped
- KUnit, =m with CONFIG_KALLSYMS_LINEINFO_MODULES=y:
32 passed, 0 failed, 2 skipped
- KUnit, =m with CONFIG_KALLSYMS_LINEINFO_MODULES=n:
8 passed, 0 failed, 26 skipped (skips rather than fails, as intended)
- SysRq-l backtraces annotated
- Run on the same vmlinux and on each of the 16 modules in the build, gen_lineinfo emits the same tables as v9's, so the v9 results below still apply to the generator
- Each of the four patches builds standalone with no warnings; arm64 defconfig and ARCH=i386 defconfig build clean
From v9, on v7.3-rc3 with a distribution-style config:
- Every entry of four built modules diffed against addr2line: 100,725 entries agree. 16,098 addresses probed across them in the other two
directions: none annotated where DWARF has no location, none left unannotated where it has one
- The vmlinux table checked the same three ways: 4,000 sampled entries agree with addr2line, and of 4,001 probed addresses none is wrong in either direction. Repeated on a build with -ffunction-sections, where one compile unit's sequences do end up adjacent, which is the case the row-selection rule for shared addresses turns on
- SysRq-l backtraces annotated, including .S frames and header inlines
- Every .ko sub-table header 4-byte aligned, 14 modules with a blob, 9 of them with two or more section descriptors
- Multi-object coverage checked by dumping the blobs: kvm.ko now names all 30 of its source files, where before it named one
- Compressed debug info: -gz=zlib and -gz=zstd objects give tables identical to an uncompressed build
- Relinking a module with only LDFLAGS_MODULE changed keeps its table
- A module relinked with a stale table object planted in the build tree ignores it and emits the same section, byte for byte
- MIPS64, SPARC64 and Hexagon objects checked directly: MIPS64 matches llvm-addr2line, the other two are refused rather than mis-generated
- arm64 defconfig, ARCH=arm multi_v7_defconfig (943 modules), ARCH=i386 defconfig, and x86_64 with LLVM=1: all clean, no warnings
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 | 100 + MAINTAINERS | 9 + include/linux/kallsyms.h | 18 +- include/linux/mod_lineinfo.h | 321 +++ include/linux/module.h | 40 + init/Kconfig | 35 + kernel/kallsyms.c | 110 +- kernel/kallsyms_internal.h | 11 + kernel/module/kallsyms.c | 200 ++ kernel/module/main.c | 26 + lib/Kconfig.debug | 10 + lib/tests/Makefile | 4 + lib/tests/lineinfo_kunit.c | 1110 +++++++ lib/tests/lineinfo_kunit.h | 21 + lib/tests/lineinfo_kunit_second.c | 21 + scripts/.gitignore | 1 + scripts/Makefile | 3 + scripts/Makefile.modfinal | 41 +- scripts/Makefile.vmlinux | 4 + scripts/empty_lineinfo.S | 38 + scripts/gen-mod-lineinfo.sh | 45 + scripts/gen_lineinfo.c | 2543 +++++++++++++++++ scripts/kallsyms.c | 11 + scripts/link-vmlinux.sh | 91 +- 25 files changed, 4802 insertions(+), 12 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 lib/tests/lineinfo_kunit.h create mode 100644 lib/tests/lineinfo_kunit_second.c create mode 100644 scripts/empty_lineinfo.S create mode 100755 scripts/gen-mod-lineinfo.sh create mode 100644 scripts/gen_lineinfo.c
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
Signature · 1 line
2.53.0
PATCH v10 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 suffix is appended for every symbol variant that already prints an offset, so %pS, %pSb and the %pB backtrace forms all carry it: arm64 prints frames with %pSb and the generic stack_trace_print() uses %pS. sprint_symbol_no_offset(), which backs lowercase %ps, stays bare because callers suffix it with a literal "()".
A line program emits several rows per address, and every row but the last covers zero bytes, so the generator keeps the last row at each address. That is the row addr2line reports, and for an inlined call it names the inlined body rather than the call site.
Rows the compiler marks with line 0 declare that no source location applies from there on (DWARF5 6.2.2), and the end of a line program's sequence says the same of the bytes past it. Both are kept, as entries whose line is zero that the lookup reads as "no annotation", so an address the compiler deliberately left unattributed reports nothing instead of inheriting the line above it.
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.nodbgTable: 1,657,663 entries from 4,234 source files
lineinfo_addrs[] 1,657,663 x u32 = 6.3 MiB
lineinfo_file_ids[] 1,657,663 x u16 = 3.2 MiB
lineinfo_lines[] 1,657,663 x u32 = 6.3 MiB
file_offsets + filenames = 0.1 MiB
Total .rodata increase: = 15.9 MiBvmlinux (stripped): 52.2 MiB -> 68.2 MiB (+16.0 MiB / +30.6%)
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.3%) on the same config.
--- Documentation/admin-guide/index.rst | 1 + .../admin-guide/kallsyms-lineinfo.rst | 73 + MAINTAINERS | 6 + include/linux/kallsyms.h | 18 +- init/Kconfig | 20 + kernel/kallsyms.c | 113 +- kernel/kallsyms_internal.h | 9 + scripts/.gitignore | 1 + scripts/Makefile | 3 + scripts/Makefile.vmlinux | 4 + scripts/empty_lineinfo.S | 30 + scripts/gen_lineinfo.c | 1291 +++++++++++++++++ scripts/kallsyms.c | 11 + scripts/link-vmlinux.sh | 91 +- 14 files changed, 1660 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
@@ -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 +73 -0
73 lines not on this page · raw message
MAINTAINERS +6 -0
@@ -14341,6 +14341,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 + KANDOU KB9002 PCIE RETIMER HWMON DRIVER M: Andy Chung <[email protected]> L: [email protected]
include/linux/kallsyms.h +17 -1
@@ -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
@@ -1939,6 +1939,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 +106 -7
166 lines not on this page · raw message
kernel/kallsyms_internal.h +9 -0
@@ -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
@@ -1,6 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only /asn1_compiler /gen_init_cpio +/gen_lineinfo /gen_packed_field_checks /generate_rust_target /insert-sys-cert
scripts/Makefile +3 -0
@@ -4,6 +4,7 @@ # the kernel for the build process. hostprogs-always-y += 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
@@ -40,6 +41,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/Makefile.vmlinux +4 -0
@@ -78,6 +78,10 @@ ifdef CONFIG_BUILDTIME_TABLE_SORT vmlinux.unstripped: scripts/sorttable endif +ifdef CONFIG_KALLSYMS_LINEINFO +vmlinux.unstripped: scripts/gen_lineinfo +endif + # vmlinux # ---------------------------------------------------------------------------
scripts/empty_lineinfo.S new file +30 -0
@@ -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 +1291 -0
1,291 lines not on this page · raw message
scripts/kallsyms.c +11 -0
@@ -137,6 +137,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 +88 -3
135 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Medium] kallsyms: gen_lineinfo excludes STT_NOTYPE and unsized symbols in sym_starts - [Medium]…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] kallsyms: gen_lineinfo excludes STT_NOTYPE and unsized symbols in sym_starts
- [Medium] kallsyms: collect_symbol_starts() includes SHN_ABS and mapping symbols
- [Medium] kallsyms: line-0 entries overwrite valid coverage in deduplicate()
- [Low] scripts: missing libelf in pkg-config query for gen_lineinfo in Makefile --
commit 939ac5438a3c14ba3c356cc9994f3c7b50467285
Author: Sasha Levin <[email protected]>
kallsyms: embed source file:line info in kernel stack traces
This commit adds CONFIG_KALLSYMS_LINEINFO and a host tool (scripts/gen_lineinfo) to extract DWARF .debug_line address-to-source-line mappings into vmlinux .rodata so stack traces include (file:line) annotations.
Quoted 13 lines
scripts/Makefile +1
-0@@ -4,6 +4,7 @@ # the kernel for the build process. hostprogs-always-y += 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
scripts/Makefile HOSTCFLAGS_asn1_compiler.o = -I$(srctree)/include · line 45
Quoted 5 lines
scripts/Makefile +2
-0@@ -40,6 +41,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)
[Severity: Low]
Should HOSTCFLAGS_gen_lineinfo.o and HOSTLDLIBS_gen_lineinfo in scripts/Makefile query pkg-config for both libdw and libelf?
scripts/gen_lineinfo.c directly includes <elf.h> and <gelf.h> and calls libelf APIs in main(), collect_symbol_starts(), and find_vmlinux_sym() (such as elf_version(), elf_begin(), elf_nextscn(), gelf_getshdr(), elf_getdata(), gelf_getsym(), elf_strptr(), elf_errmsg(), elf_errno(), and elf_end()).
In elfutils, libdw.pc lists libelf under Requires.private rather than Requires. When pkg-config is installed on the host, running:
$(HOSTPKG_CONFIG) --libs libdw
succeeds with exit status 0 and outputs only -ldw, which prevents the "|| echo -ldw -lelf" fallback from running. On toolchains that default to --no-copy-dt-needed-entries where libdw.so is a symlink to libdw.so.1 rather than a linker script, linking scripts/gen_lineinfo can fail with undefined references to the libelf symbols.
Would querying "$(HOSTPKG_CONFIG) --cflags libdw libelf" and "$(HOSTPKG_CONFIG) --libs libdw libelf" avoid this build failure?
Quoted 5 lines
scripts/gen_lineinfo.c new file +0
-0
[ ... ]
Quoted 74 lines
scripts/gen_lineinfo.c new file +74
-0+static void collect_symbol_starts (Elf *elf,unsigned long long text_addr) +{ +Elf_Scn *scn =NULL ; +GElf_Shdr shdr; + +while ((scn =elf_nextscn (elf, scn)) !=NULL ) { +Elf_Data *data; +size_t nsyms; + +if (!gelf_getshdr (scn, &shdr)) +continue ; +if (shdr.sh_type !=SHT_SYMTAB || !shdr.sh_entsize) +continue ; + + data =elf_getdata (scn,NULL ); +if (!data) +continue ; + + nsyms = shdr.sh_size / shdr.sh_entsize; +for (size_t i =0 ; i < nsyms; i++) { +GElf_Sym sym; +unsigned long long raw; + +if (!gelf_getsym (data, i, &sym)) +continue ; +switch (GELF_ST_TYPE (sym.st_info)) { +case STT_FUNC : +case STT_NOTYPE : +break ; +default : +continue ; + } +if (sym.st_value < text_addr) +continue ; +if (text_end_addr && sym.st_value >= text_end_addr) +continue ; + + raw = sym.st_value - text_addr; +if (raw >UINT_MAX ) +continue ; + +if (num_sym_starts >= sym_starts_capacity) { + sym_starts_capacity = sym_starts_capacity ? + sym_starts_capacity *2 :16384 ; + sym_starts =xrealloc (sym_starts, + sym_starts_capacity * +sizeof (*sym_starts)); + } +if (num_text_starts >= text_starts_capacity) { + text_starts_capacity = text_starts_capacity ? + text_starts_capacity *2 :16384 ; + text_starts =xrealloc (text_starts, + text_starts_capacity * +sizeof (*text_starts)); + } + text_starts[num_text_starts].offset = (unsigned int )raw; + text_starts[num_text_starts].size = + sym.st_size >UINT_MAX ?UINT_MAX : + (unsigned int )sym.st_size; + num_text_starts++; + +if (GELF_ST_TYPE (sym.st_info) !=STT_FUNC ) +continue ; + + sym_starts[num_sym_starts].offset = (unsigned int )raw; + sym_starts[num_sym_starts].size = + sym.st_size >UINT_MAX ?UINT_MAX : + (unsigned int )sym.st_size; + num_sym_starts++; + } + } + +sort_starts (sym_starts, &num_sym_starts); +sort_starts (text_starts, &num_text_starts);
scripts/gen_lineinfo.c
Quoted 10 lines
scripts/gen_lineinfo.c new file +10
-0+ +/* +* An unsized label reaches the next symbol, and a sequence beginning +* there cannot run past it. +*/ +for (unsigned int i =1 ; i < num_text_starts; i++) { +if (!text_starts[i -1 ].size) + text_starts[i -1 ].size = text_starts[i -1 ].offset ? + text_starts[i].offset - + text_starts[i -1 ].offset :0 ;
[Severity: Medium]
Can unfiltered ELF symbols in collect_symbol_starts() in scripts/gen_lineinfo.c corrupt the symbol extents in text_starts[]?
In collect_symbol_starts(), every STT_FUNC and STT_NOTYPE symbol in SHT_SYMTAB whose st_value falls in [text_addr, text_end_addr) is added to text_starts[] without checking sym.st_shndx or the symbol name:
- SHN_ABS symbols (such as __kcfi_typeid_* hashes) whose values happen to fall in [text_addr, text_end_addr) are included.
- Architecture mapping symbols ($x, $d on arm64/arm/riscv/loongarch) and assembler local labels (.L*) are included.
When the loop at the end of collect_symbol_starts() backfills sizes for unsized entries:
for (unsigned int i = 1; i < num_text_starts; i++) {
if (!text_starts[i - 1].size)
text_starts[i - 1].size = text_starts[i].offset -
text_starts[i - 1].offset;
}an internal .L* or $x label inside an unsized assembly routine truncates that routine's extent at the first internal label, while an unsized mapping or SHN_ABS symbol at a sequence boundary is given a non-zero size reaching to the next symbol, which can cause starts_new_sequence() and resolve_cu_row_groups() to misclassify DWARF sequence boundaries.
Additionally, why does collect_symbol_starts() exclude STT_NOTYPE and unsized symbols from sym_starts[]?
At runtime, __sprint_symbol() -> kallsyms_lookup_buildid() resolves symbols using the kallsyms table, which includes STT_NOTYPE code symbols and unsized assembly labels (such as Clang .cold subfunctions, SYM_CODE_START routines, SYM_INNER_LABEL entry points like entry_SYSCALL_64_after_hwframe, and CONFIG_PROPELLER_CLANG basic-block symbols), and passes sym_start to kallsyms_lookup_lineinfo():
if (lineinfo_addrs[low] < min_offset) return false;
Because collect_symbol_starts() skips GELF_ST_TYPE(sym.st_info) != STT_FUNC when populating sym_starts[] and never backfills zero sizes in sym_starts[], synthesize_symbol_starts() skips those symbols (or rejects st_size == 0 at "if (end <= start) continue;") and deduplicate() sets at_symbol_start = false at their start offsets. Any frame inside those symbols before a new file:line transition will then fail the min_offset check in kallsyms_lookup_lineinfo() and lose its annotation.
[ ... ]
Quoted 95 lines
scripts/gen_lineinfo.c new file +95
-0+static void synthesize_symbol_starts (void ) +{ +unsigned int base_entries = num_entries; +unsigned int cursor =0 ; + +if (!base_entries || !num_sym_starts) +return ; + +sort_unique (seq_ends, &num_seq_ends); +qsort (asm_spans, num_asm_spans,sizeof (*asm_spans), compare_asm_spans); + +for (unsigned int i =0 ; i < num_sym_starts; i++) { +unsigned int start = sym_starts[i].offset; +unsigned int end = start + sym_starts[i].size; + +while (cursor +1 < base_entries && + entries[cursor +1 ].offset <= start) + cursor++; + +if (entries[cursor].offset > start) +continue ;/* nothing covers this symbol */ +if (entries[cursor].offset == start) +continue ;/* already has its own entry */ +if (seq_end_between (entries[cursor].offset, start)) +continue ;/* coverage stopped before here */ + +if (end <= start) +continue ;/* size overflowed */ + +/* +* A row reaching over a symbol with none inside it is padding +* or a split-out fragment in C, carrying the line of whatever +* it came from. In assembly it is one macro expanding to a +* function per invocation, which the row does describe. +*/ +if (!in_asm_span (start) && + (cursor +1 >= base_entries || + entries[cursor +1 ].offset >= end)) +continue ; + +add_entry (start, entries[cursor].file_id, entries[cursor].line); + } +} + +static void deduplicate (void ) +{ +unsigned int sym_cursor =0 ; +unsigned int i, j; + +if (num_entries <2 ) +return ; + +/* Sort by offset, then file_id, then line for stability */ +qsort (entries, num_entries,sizeof (*entries), compare_entries); + +synthesize_symbol_starts (); +qsort (entries, num_entries,sizeof (*entries), compare_entries); + +/* +* Remove duplicate entries: +* - Same offset: keep last. Earlier rows at that address cover no +* bytes, so the final one is what describes the instruction, and +* it is what addr2line reports. For an inlined call that is the +* inlined body rather than the call site. +* - Same file:line as previous kept entry: redundant for binary +* search -- any address between them resolves to the earlier one +* +* Entries sitting on a symbol start are exempt from the second rule: +* they are the only thing standing between that symbol and the +* kernel's boundary check. +*/ + j =0 ; +for (i =1 ; i < num_entries; i++) { +bool at_symbol_start; + +if (entries[i].offset == entries[j].offset) { +/* +* Rows from different compile units can share an +* address, and coverage is their union: a real +* location beats another unit's no-coverage marker. +* Within one unit resolve_cu_row_groups() has already +* picked the row that describes the address. +*/ +if (entries[i].line || !entries[j].line) + entries[j] = entries[i]; +continue ; + } + +while (sym_cursor < num_sym_starts && + sym_starts[sym_cursor].offset < entries[i].offset) + sym_cursor++; + at_symbol_start = sym_cursor < num_sym_starts && + sym_starts[sym_cursor].offset == entries[i].offset; + + if (!at_symbol_start &&
scripts/gen_lineinfo.c line 1121
Quoted 10 lines
scripts/gen_lineinfo.c new file +10
-0+ entries[i].file_id == entries[j].file_id && + entries[i].line == entries[j].line) + continue; + + j++; +if (j != i) + entries[j] = entries[i]; + } + num_entries = j +1 ; +}
[Severity: Medium]
Can line-0 end_sequence entries overwrite valid source coverage in synthesize_symbol_starts() and deduplicate() in scripts/gen_lineinfo.c?
There appear to be three ways a line-0 entry can clobber a valid line entry across compile units:
1. deduplicate() calls synthesize_symbol_starts() before collapsing same-offset entries across compile units. When an earlier CU emits a valid row (line > 0) at offset X and a later CU emits an end_sequence row (line == 0) at the same offset X, the line-0 entry has a higher seq and sorts last at offset X. In synthesize_symbol_starts(), the cursor loop:
while (cursor + 1 < base_entries && entries[cursor + 1].offset <= start) cursor++;
advances to the last entry at offset X, picking the line-0 entry instead of the valid line entry.
2. In process_dwarf(), every sequence end passed to record_seq_end() also emits a line-0 entry into entries[] at that same offset. Because cursor in synthesize_symbol_starts() stops at the largest entry offset <= start, there can never be a sequence end strictly between entries[cursor].offset and start without a corresponding entry in entries[] that would have advanced cursor to it. Thus seq_end_between(entries[cursor].offset, start) never triggers, and because synthesize_symbol_starts() does not check whether entries[cursor].line == 0, a line-0 sequence-end entry at entries[cursor].offset gets copied to start.
3. In deduplicate(), same-offset union resolution is interleaved with adjacent (file_id, line) deduplication. Suppose entries[j] is at offset A with (file_id=1, line=10), and at offset B > A (not a symbol start) CU1 has (file_id=1, line=10) followed by CU2 having an end_sequence (file_id=0, line=0) at the same offset B:
- For CU1's entry at offset B, entries[i].offset != entries[j].offset, and since (file_id, line) matches entries[j], the loop hits continue without updating entries[j].offset to B.
- For CU2's line-0 entry at offset B, entries[i].offset (B) != entries[j].offset (A), so it misses the "if (entries[i].offset == entries[j].offset)" union check and is appended as a new entry at offset B with line 0, cutting off valid coverage from offset B onward.
Would collapsing same-offset entries across CUs in a separate pass before running synthesize_symbol_starts() and before collapsing adjacent identical (file_id, line) entries (and checking entries[cursor].line != 0 in synthesize_symbol_starts()) avoid losing coverage here?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
On Tue, Nov 03, 2026 at 11:15:24AM +0000, [email protected] wrote:
[...]
Quoted 2 lines
In elfutils, libdw.pc lists libelf under Requires.private rather than Requires.
It's under Requires, so pkg-config prints "-ldw -lelf".
[...]
Quoted 2 lines
Can unfiltered ELF symbols in
collect_symbol_starts()inscripts/gen_lineinfo.ccorrupt the symbol extents in text_starts[]?
No. Filtering them changes nothing on x86, arm64, riscv or powerpc. On arm it drops three $a symbols that start line-program sequences with no named symbol, and those addresses lose their annotation.
[...]
Quoted 2 lines
Additionally, why does
collect_symbol_starts()excludeSTT_NOTYPEand unsized symbols from sym_starts[]?
Without a size there is no way to check that a covering row belongs to the symbol. Untyped labels that start code are almost all in assembly, which gets a row per instruction anyway.
--
Thanks,
Sasha
PATCH v10 2/4 kallsyms: extend lineinfo to loadable modules
In reply to Sasha LevinAdd 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.
- Applies the relocations libdw does not: in an ET_REL .ko a compile unit's DW_AT_abbrev_offset and DW_AT_stmt_list, its DW_FORM_strp names and the DW_LNE_set_address PCs are all relocations, and libdw reads zero for every one of them. Only the first compile unit -- whose offsets genuinely are zero -- would otherwise decode, leaving a module built from several objects with line info for just one of them. apply_debug_relocations() patches .debug_line, .debug_info, .debug_str_offsets, .debug_addr, .debug_rnglists and .debug_loclists in the mutable ELF copy before dwarf_begin_elf() sees it.
- Disambiguates DWARF addresses across sections that all share sh_addr == 0 in ET_REL files via per-section synthetic biases applied to .debug_line relocations (handles both abs32 and abs64 width relocs).
- Expands SHF_COMPRESSED debug sections before patching them. With CONFIG_DEBUG_INFO_COMPRESSED_* the section data is compressed while relocation offsets address the uncompressed contents, so patching without expanding first corrupts the stream.
- Applies the arithmetic relocation pairs RISC-V and LoongArch use for label differences (R_RISCV_ADD16/SUB16 and friends), which clang emits for line-program address advances even with -mno-relax. Any relocation left unapplied in a patched debug section aborts the object instead of shipping line numbers shifted by the gap.
- 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 table describes the module's own section layout, so modfinal builds it from a partial link and merges it in the link that produces the .ko rather than post-processing a finished module:
${LD} -r ${KBUILD_LDFLAGS} ${layout_flags} -T module.lds \
-o ${KO}.lineinfo_pre $(filter %.o, $^)
gen-mod-lineinfo.sh ${KO}.lineinfo_pre ${KO}.lineinfo.o
${LD} -r ${KBUILD_LDFLAGS} ${last_flags} -T module.lds -o ${KO} \
${KO}.lineinfo.o ${KO}.lineinfo_preOnly --be8 and --build-id are held back for the second link: the first converts the object to a form the linker will not read again, and the second has to cover the module that ships. Everything else runs in the first link, where the table is measured, since text linked ahead of the module would move the code the table describes away from its anchor.
KBUILD_LDFLAGS carries the target linker emulation, without which an ARCH=i386 build on a biarch host links the 32-bit objects with the host's default 64-bit emulation and fails, and -z noexecstack, which the generated object has no note of its own for.
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 CONFIG_KALLSYMS_LINEINFO_MODULES and accessed through inline reader accessors so callers don't duplicate the guard.
Per-module overhead is approximately 10 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.
--- .../admin-guide/kallsyms-lineinfo.rst | 43 +- MAINTAINERS | 3 + include/linux/mod_lineinfo.h | 130 ++ include/linux/module.h | 40 + init/Kconfig | 13 + kernel/kallsyms.c | 19 +- kernel/module/kallsyms.c | 213 +++ kernel/module/main.c | 26 + scripts/Makefile.modfinal | 41 +- scripts/gen-mod-lineinfo.sh | 45 + scripts/gen_lineinfo.c | 1473 +++++++++++++++-- 11 files changed, 1889 insertions(+), 157 deletions(-) create mode 100644 include/linux/mod_lineinfo.h create mode 100755 scripts/gen-mod-lineinfo.sh
Documentation/admin-guide/kallsyms-lineinfo.rst +35 -8
@@ -52,22 +52,49 @@ Assembly routines such as ``entry_SYSCALL_64_after_hwframe`` are annotated too, from the line information the assembler emits when debug info is enabled. +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``. On an x86_64 ``defconfig`` -with ``CONFIG_DEBUG_INFO`` they hold 1.66 million entries and grow the -stripped image by 16 MiB, about 10 bytes per entry after deduplication. +The vmlinux lineinfo tables are stored in ``.rodata``. On an x86_64 +``defconfig`` with ``CONFIG_DEBUG_INFO`` they hold 1.66 million entries and +grow the stripped image by 16 MiB, about 10 bytes per entry after +deduplication. + +Per-module lineinfo adds about 10 bytes per entry to each ``.ko`` file, plus +a small fixed cost per covered section. 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. - **Code without line information**: Functions that no DWARF ``.debug_line`` row covers are not annotated. +- **Module init text**: A module's ``.init.text`` is annotated from a separate + ``.init.mod_lineinfo`` section, which is released along with the module's + init memory. Traces taken after the module has finished initializing carry + no annotation for those addresses.
MAINTAINERS +3 -0
@@ -14345,6 +14345,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 KANDOU KB9002 PCIE RETIMER HWMON DRIVER
include/linux/mod_lineinfo.h new file +130 -0
130 lines not on this page · raw message
include/linux/module.h +40 -0
@@ -507,6 +507,12 @@ struct module {unsigned int btf_inline_data_size;void *btf_inline_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;
@@ -1029,6 +1035,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
@@ -1959,6 +1959,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
@@ -586,12 +586,25 @@ static int __sprint_symbol(char *buffer, unsigned long address,* onto that to denote a call ("foo() replaced with bar()"), which * "foo (file:line)()" would render unreadable. */ -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 +=scnprintf (buffer + len,KSYM_SYMBOL_LEN - len," (%s:%u)" , li_file, li_line); }
kernel/module/kallsyms.c +213 -0
216 lines not on this page · raw message
kernel/module/main.c +26 -0
@@ -2739,6 +2739,19 @@ static int find_module_sections(struct module *mod, struct load_info *info) mod->btf_inline_data =any_section_objs (info,".BTF.inline" ,1 , &mod->btf_inline_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),
@@ -3195,6 +3208,19 @@ static noinline int do_init_module(struct module *mod)#endif #if IS_ENABLED (CONFIG_DEBUG_INFO_BTF_INLINE ) mod->btf_inline_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 +40 -1
48 lines not on this page · raw message
scripts/gen-mod-lineinfo.sh new file +45 -0
45 lines not on this page · raw message
scripts/gen_lineinfo.c +1328 -145
1,843 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v10 2/4] kallsyms: extend lineinfo to loadable modules
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] kbuild: running module.lds twice in cmd_ld_ko_o breaks alloc_tags and arm64 - [Medium]…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] kbuild: running module.lds twice in cmd_ld_ko_o breaks alloc_tags and arm64
- [Medium] scripts/gen_lineinfo: early return in deduplicate() leaves stale n_entries
- [Medium] scripts/gen_lineinfo: zero bias in resolve_covered_sections() aliases .text
- [Medium] scripts/gen_lineinfo: resolve_covered_sections() leaves zero bias gap --
commit 576d6bd5b277b6e1ee712d143954da5c356b15a1
Author: Sasha Levin <[email protected]>
kallsyms: extend lineinfo to loadable modules
This commit adds CONFIG_KALLSYMS_LINEINFO_MODULES to embed source file and line number lookup tables (.mod_lineinfo and .init.mod_lineinfo) into loadable kernel modules via a two-stage partial link in Makefile.modfinal and a new --module mode in scripts/gen_lineinfo.
Quoted 8 lines
scripts/Makefile.modfinal +0
-0@@ -46,8 +46,47 @@ quiet_cmd_btf_ko = BTF [M] $@ $(CONFIG_SHELL) $(srctree)/scripts/gen-btf.sh --btf_base $(objtree)/vmlinux $@; \ fi;
[ ... ]
Quoted 8 lines
scripts/Makefile.modfinal +8
-0+ifdef CONFIG_KALLSYMS_LINEINFO_MODULES +lineinfo_ldflags_all = $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) +lineinfo_ldflags_last = $(filter --be8 --build-id --build-id=%, \ + $(lineinfo_ldflags_all)) + + cmd_ld_ko_o = \ + rm -f [email protected]_pre [email protected]; \ + $(LD) -r $(KBUILD_LDFLAGS) \
scripts/Makefile.modfinal quiet_cmd_btf_ko = BTF [M] $@ · line 84
Quoted 10 lines
scripts/Makefile.modfinal +10
-0+ $(filter-out $(lineinfo_ldflags_last), \ + $(lineinfo_ldflags_all)) \ + -T $(objtree)/scripts/module.lds \ + -o [email protected]_pre $(filter %.o, $^); \ + $(CONFIG_SHELL) $(srctree)/scripts/gen-mod-lineinfo.sh \ + [email protected]_pre [email protected]; \ + $(LD) -r $(KBUILD_LDFLAGS) $(lineinfo_ldflags_last) \ + -T $(objtree)/scripts/module.lds -o $@ \ + $$(test -f [email protected] && echo [email protected]) \ + [email protected]_pre; \
[Severity: Critical]
Does passing -T $(objtree)/scripts/module.lds to both ld -r passes in cmd_ld_ko_o break CONFIG_MEM_ALLOC_PROFILING and arm64 module loading?
Under CONFIG_MEM_ALLOC_PROFILING, scripts/module.lds.S expands MOD_SEPARATE_CODETAG_SECTIONS() from include/asm-generic/codetag.lds.h into:
.codetag.alloc_tags 0 : {
. = ALIGN(8);
__start_alloc_tags = .;
KEEP(*(alloc_tags))
__stop_alloc_tags = .;
}In the first ld -r pass, input alloc_tags sections from the module's .o files are renamed into the output section .codetag.alloc_tags in [email protected]_pre. When the second ld -r pass runs with -T scripts/module.lds on [email protected]_pre, there are no longer any input sections named alloc_tags, so KEEP(*(alloc_tags)) matches nothing and resets both __start_alloc_tags and __stop_alloc_tags to offset 0 before orphan placement appends .codetag.alloc_tags.
At module load time, move_module() allocates .codetag.alloc_tags with each struct alloc_tag.counters initialized to NULL, while codetag_module_init() in lib/codetag.c sees:
/* Ignore empty ranges */ if (range.start == range.stop) return 0;
and skips calling mm/alloc_tag.c:load_module() to allocate per-CPU counters. The first instrumented allocation in the module then dereferences tag->counters == NULL in alloc_tag_ref_set().
In addition, on arm64, arch/arm64/include/asm/module.lds.h defines:
.text.ftrace_trampoline 0 : {
BYTE(0)
}which creates a 1-byte writable (SHF_ALLOC | SHF_WRITE) section in [email protected]_pre during the first link. In the second link with -T scripts/module.lds, the earlier rule in scripts/module.lds.S:
.text 0 : {
*(.text .text.[0-9a-zA-Z_]*)
}matches .text.ftrace_trampoline from [email protected]_pre and merges it into .text. That gives .text SHF_WRITE | SHF_EXECINSTR flags (and grows .text by 1 byte), causing module_enforce_rwx_sections() in kernel/module/strict_rwx.c to reject every module load with -ENOEXEC when CONFIG_STRICT_MODULE_RWX is enabled.
Quoted 4 lines
scripts/gen_lineinfo.c +0
-0
[ ... ]
Quoted 1 line
scripts/gen_lineinfo.c +0
-0@@ -635,12 +732,728 @@ static void collect_symbol_starts(Elf *elf, unsigned long long text_addr)
[ ... ]
scripts/gen_lineinfo.c static void collect_symbol_starts(Elf *elf, unsigned long long text_addr) · line 758
Quoted 8 lines
scripts/gen_lineinfo.c +8
-0+static void resolve_covered_sections (Elf *elf, +struct covered_section *sections, +unsigned int num_sections) +{ +Elf_Scn *scn =NULL ; +GElf_Shdr shdr; +size_t shstrndx; +unsigned long long cursor =0 ;
[Severity: Medium]
When cursor starts at 0 in resolve_covered_sections(), the first present covered section in all_sections[] (normally .text) gets sections[0].bias = 0, giving it the synthetic range [0, size).
In an ET_REL module object produced by ld -r -T scripts/module.lds, functions in sections discarded by /DISCARD/ (such as .discard.*) or discarded COMDAT groups have their .debug_line DW_LNE_set_address relocations zeroed or pointed at STN_UNDEF (st_shndx == SHN_UNDEF, st_value == 0). In apply_one_debug_reloc(), section_by_index() returns NULL for SHN_UNDEF, so no bias is added and those discarded sequences remain at [0, seq_len).
Won't classify_address() in process_dwarf() then match those [0, seq_len) addresses against sections[0] and merge discarded line entries into .text?
[ ... ]
Quoted 4 lines
scripts/gen_lineinfo.c +4
-0+/* Pack present sections into non-overlapping bias ranges. */ +for (unsigned int i =0 ; i < num_sections; i++) { +if (!sections[i].present) +continue ;
scripts/gen_lineinfo.c static void collect_symbol_starts(Elf *elf, unsigned long long text_addr) · line 825
Quoted 10 lines
scripts/gen_lineinfo.c +10
-0+ sections[i].bias = cursor; + cursor += sections[i].size; + cursor = (cursor +15 ) & ~15ULL ;/* pad for separation */ + } +for (unsigned int i =0 ; i < num_extra_sections; i++) { + extra_sections[i].bias = cursor; + cursor += extra_sections[i].size; + cursor = (cursor +15 ) & ~15ULL ; + } +}
[Severity: Medium]
Does (cursor + 15) & ~15ULL in resolve_covered_sections() actually provide a separation gap when a section's size is 0 or a multiple of 16 bytes?
Because text sections on architectures such as x86_64, arm64, riscv, s390, and loongarch are commonly 16-byte aligned in size (or 0 bytes when empty, since covered sections do not require shdr.sh_size != 0 to set present = true), cursor + sections[i].size is already a multiple of 16. In that case, (cursor + 15) & ~15ULL adds 0 bytes of padding and leaves sections[next].bias == sections[i].bias + sections[i].size.
If an empty DWARF sequence starts at offset 0 of sections[next] (with an end_sequence row at addr == sections[next].bias), process_dwarf() and classify_seq_end() query classify_address() at addr - 1, which lands at sections[i].bias + sections[i].size - 1 and misclassifies the row into sections[i]. Likewise, any non-end_sequence address at offset == sections[i].size lands on sections[next].bias and is classified as offset 0 of sections[next].
[ ... ]
Quoted 1 line
scripts/gen_lineinfo.c +0
-0@@ -1049,16 +1919,19 @@ static void synthesize_symbol_starts(void)
[ ... ]
scripts/gen_lineinfo.c static void synthesize_symbol_starts(void)
Quoted 9 lines
scripts/gen_lineinfo.c +2
-1-static void deduplicate (void ) +static void deduplicate (struct covered_section *sections, +unsigned int num_sections) {unsigned int sym_cursor =0 ;unsigned int i, j;if (num_entries <2 )return ;
[Severity: Medium]
What happens in module mode if resolve_cu_row_groups() collapses a compile unit's rows down to num_entries == 1 before deduplicate() is called?
In process_dwarf(), sections[sec_id].n_entries is incremented for every raw DWARF line row before add_entry():
loffset = (unsigned int)sec_off; sections[sec_id].n_entries++;
At the end of the compile unit, resolve_cu_row_groups() collapses rows sharing the same (section_id, offset) and shrinks num_entries = j without adjusting sections[sec_id].n_entries.
If num_entries is 1 when deduplicate(all_sections, ALL_SECTIONS) is called, this early return skips both synthesize_symbol_starts() and the loop at the end of deduplicate() that resets and recomputes sections[k].n_entries from entries[0 .. num_entries - 1]:
if (sections) {
for (unsigned int k = 0; k < num_sections; k++)
sections[k].n_entries = 0;
for (i = 0; i < num_entries; i++)
sections[entries[i].section_id].n_entries++;
}When emit_blob() -> emit_section_table() then iterates count = all_sections[i].n_entries (>= 2) times, won't it read past num_entries into stale entries[1 .. count - 1] that were discarded by resolve_cu_row_groups()?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v10 3/4 kallsyms: delta-compress lineinfo tables for ~2.7x size reduction
In reply to Sasha LevinReplace 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 entries 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,657,997 entries, 4,235 source files, 25,907 blocks):
Before (flat arrays):
lineinfo_addrs[] 6,631,988 bytes (u32 x 1.66M)
lineinfo_file_ids[] 3,315,994 bytes (u16 x 1.66M)
lineinfo_lines[] 6,631,988 bytes (u32 x 1.66M)
Total: 16,579,970 bytes (15.8 MiB, 10.00 bytes/entry)After (block-indexed delta + ULEB128):
lineinfo_block_addrs[] 103,628 bytes (101 KiB)
lineinfo_block_offsets[] 103,628 bytes (101 KiB)
lineinfo_data[] 6,070,158 bytes (5.8 MiB)
Total: 6,277,414 bytes (6.0 MiB, 3.79 bytes/entry)Savings: 9.8 MiB (2.64x 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: 52.2 MiB vmlinux (stripped), before this fix: 68.2 MiB (+16.0 MiB / +30.6%) vmlinux (stripped), after this fix: 60.2 MiB ( +8.0 MiB / +15.3%)
Booted in QEMU and verified with SysRq-l that annotations still work:
default_idle+0x9/0x10 (arch/x86/kernel/process.c:768) default_idle_call+0x6e/0xb0 (kernel/sched/idle.c:122) do_idle+0x38f/0x660 (kernel/sched/idle.c:199) cpu_startup_entry+0x4e/0x60 (kernel/sched/idle.c:453) rest_init+0x277/0x280 (init/main.c:732)
--- .../admin-guide/kallsyms-lineinfo.rst | 6 +- include/linux/mod_lineinfo.h | 265 +++++++++++++++--- init/Kconfig | 8 +- kernel/kallsyms.c | 60 ++-- kernel/kallsyms_internal.h | 8 +- kernel/module/kallsyms.c | 127 ++++----- scripts/empty_lineinfo.S | 20 +- scripts/gen_lineinfo.c | 185 ++++++++---- 8 files changed, 459 insertions(+), 220 deletions(-)
Documentation/admin-guide/kallsyms-lineinfo.rst +3 -3
@@ -78,10 +78,10 @@ Memory Overhead The vmlinux lineinfo tables are stored in ``.rodata``. On an x86_64 ``defconfig`` with ``CONFIG_DEBUG_INFO`` they hold 1.66 million entries and -grow the stripped image by 16 MiB, about 10 bytes per entry after -deduplication. +grow the stripped image by 8 MiB, about 3.8 bytes per entry after delta +compression. -Per-module lineinfo adds about 10 bytes per entry to each ``.ko`` file, plus +Per-module lineinfo adds about 4 bytes per entry to each ``.ko`` file, plus a small fixed cost per covered section. Known Limitations
include/linux/mod_lineinfo.h +228 -37
312 lines not on this page · raw message
init/Kconfig +5 -3
@@ -1954,8 +1954,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.
@@ -1968,7 +1969,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 -40
83 lines not on this page · raw message
kernel/kallsyms_internal.h +5 -3
@@ -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 +57 -70
175 lines not on this page · raw message
scripts/empty_lineinfo.S +14 -6
@@ -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
PATCH v10 4/4 kallsyms: add KUnit tests for lineinfo feature
In reply to Sasha LevinAdd 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() with EXPORT_SYMBOL_IF_KUNIT() so the test module can exercise the backtrace APIs.
test_cross_file_inline() pins the row-selection rule: a header helper is inlined into a caller in another file, and some address inside that caller has to resolve to the header. Picking any row but the last at a given address reports the call site instead, which no test that only looks at its own file can notice.
The test module is built from two objects. A single-object module cannot distinguish relocated per-compile-unit DWARF references from unrelocated ones -- its only compile unit sits at offset 0, which is what an unrelocated reference reads -- so test_second_object_lineinfo() resolves a target in the second object to cover the general case.
--- kernel/kallsyms.c | 4 + lib/Kconfig.debug | 10 + lib/tests/Makefile | 4 + lib/tests/lineinfo_kunit.c | 1110 +++++++++++++++++++++++++++++ lib/tests/lineinfo_kunit.h | 21 + lib/tests/lineinfo_kunit_second.c | 21 + 6 files changed, 1170 insertions(+) create mode 100644 lib/tests/lineinfo_kunit.c create mode 100644 lib/tests/lineinfo_kunit.h create mode 100644 lib/tests/lineinfo_kunit_second.c
kernel/kallsyms.c +4 -0
@@ -32,6 +32,8 @@#include <linux/bsearch.h> #include <linux/btf_ids.h> +#include <kunit/visibility.h> +#include "kallsyms_internal.h" /*
@@ -661,6 +663,7 @@ int sprint_backtrace(char *buffer, unsigned long address) {return __sprint_symbol (buffer, address,-1 ,1 ,0 ,1 ); } +EXPORT_SYMBOL_IF_KUNIT (sprint_backtrace);/** * sprint_backtrace_build_id - Look up a backtrace symbol and return it in a text buffer
@@ -681,6 +684,7 @@ int sprint_backtrace_build_id(char *buffer, unsigned long address) {return __sprint_symbol (buffer, address,-1 ,1 ,1 ,1 ); } +EXPORT_SYMBOL_IF_KUNIT (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
@@ -3126,6 +3126,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 +4 -0
@@ -39,6 +39,10 @@ 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_test.o +lineinfo_kunit_test-y := lineinfo_kunit.o lineinfo_kunit_second.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 +1110 -0
1,110 lines not on this page · raw message
lib/tests/lineinfo_kunit.h new file +21 -0
@@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LIB_TESTS_LINEINFO_KUNIT_H +#define _LIB_TESTS_LINEINFO_KUNIT_H + +#include <linux/compiler.h> + +int lineinfo_target_second_file (int x); + +/* +* Inlined into lineinfo_cross_file_caller() in lineinfo_kunit.c, so the +* addresses it covers must resolve to this header rather than to the +* caller's file. __always_inline because the test object is built with +* -fno-inline-functions-called-once. +*/ +static __always_inline int lineinfo_header_helper(int x) +{ +barrier (); +return x +1 ; +} + +#endif /* _LIB_TESTS_LINEINFO_KUNIT_H */
lib/tests/lineinfo_kunit_second.c new file +21 -0
@@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Second translation unit of the lineinfo KUnit test module. +* +* Copyright (c) 2026 Sasha Levin <[email protected]> +* +* A module built from one object file cannot tell whether per-compile-unit +* DWARF references were relocated: its only compile unit sits at offset 0, +* which is exactly what an unrelocated reference reads. Keeping a target +* function in a second object makes the test cover the general case. +*/ + +#include <linux/compiler.h> + +#include "lineinfo_kunit.h" + +noinline int lineinfo_target_second_file(int x) +{ +barrier (); +return x +1 ; +}
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v10 4/4] kallsyms: add KUnit tests for lineinfo feature
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [Medium] kallsyms: identical bodies in lineinfo_kunit targets allow IPA-ICF folding - [Low] kallsyms…
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Medium] kallsyms: identical bodies in lineinfo_kunit targets allow IPA-ICF folding
- [Low] kallsyms: unreachable failure path in test_assembly_no_lineinfo()
- [Low] kallsyms: missing has_lineinfo() assertion in test_many_lines_mid_function()
- [Low] kallsyms: inaccurate lineinfo comments in sprint_with_lineinfo() and test
- [Low] kallsyms: test_static_function() duplicates test_short_function() --
commit fbb509d58818b09aeb1b086d5f710841ca770e58
Author: Sasha Levin <[email protected]>
kallsyms: add KUnit tests for lineinfo feature
This commit adds a KUnit test module (CONFIG_LINEINFO_KUNIT_TEST) to verify kallsyms source file and line annotations in stack traces, and exports sprint_backtrace() and sprint_backtrace_build_id() for KUnit testing.
Quoted 6 lines
lib/tests/lineinfo_kunit.c new file +0
-0@@ -0,0 +1,1110 @@
[ ... ]
Quoted 4 lines
lib/tests/lineinfo_kunit.c new file +4
-0+/* +* Format a symbol with lineinfo annotation. Lineinfo is appended only +* via the sprint_backtrace*() entry points (kernel/kallsyms.c only adds +* the "(file:line)" suffix in stack-trace context — sprint_symbol() is
lib/tests/lineinfo_kunit.c line 72
Quoted 10 lines
lib/tests/lineinfo_kunit.c new file +10
-0+* used by %ps and many existing format strings tack literal "()" after +* %ps, where the annotation would render as "foo (file:line)()"). +* +* sprint_backtrace() subtracts 1 from the address to handle tail-call +* return-address corrections; pass @addr + 1 to recover the original. +*/ +static int sprint_with_lineinfo (char *buf,unsigned long addr) +{ +return sprint_backtrace (buf, addr +1 ); +}
[Severity: Low]
Is the comment above sprint_with_lineinfo() still accurate?
In kernel/kallsyms.c, sprint_symbol() and sprint_symbol_build_id() also pass add_lineinfo = 1 (backing %pS and %pSb), while sprint_symbol_no_offset() backs lowercase %ps and passes add_lineinfo = 0. Later in this file, test_sprint_symbol_format() and test_pS_format() also assert that sprint_symbol() and %pS include lineinfo.
[ ... ]
Quoted 5 lines
lib/tests/lineinfo_kunit.c new file +5
-0+static noinline int lineinfo_target_with_arg(int x) +{ +barrier (); +return x +1 ; +}
[ ... ]
lib/tests/lineinfo_kunit.c line 206
Quoted 4 lines
lib/tests/lineinfo_kunit.c new file +4
-0+static noinline int lineinfo_cross_file_caller(int x) +{ +return lineinfo_header_helper (x); +}
[Severity: Medium]
Can GCC's identical-code folding (IPA-ICF) merge lineinfo_cross_file_caller() into lineinfo_target_with_arg() and cause test_cross_file_inline() to fail?
Unlike the 0-argument target functions which return distinct constants (42, 1, 99, 10), lineinfo_target_with_arg(), lineinfo_header_helper() in lib/tests/lineinfo_kunit.h (inlined into lineinfo_cross_file_caller()), and lineinfo_target_second_file() in lib/tests/lineinfo_kunit_second.c all share the exact same signature and body:
barrier(); return x + 1;
After __always_inline expansion of lineinfo_header_helper() into lineinfo_cross_file_caller(), lineinfo_target_with_arg() and lineinfo_cross_file_caller() are two static noinline functions in the same translation unit with identical GIMPLE bodies. When built with GCC at -O2 or -Os without -fno-optimize-sibling-calls (for example when CONFIG_FRAME_POINTER=n), -fipa-icf-functions merges lineinfo_cross_file_caller() into lineinfo_target_with_arg() and replaces lineinfo_cross_file_caller() with a tail-call thunk whose DWARF .debug_line entry only references lib/tests/lineinfo_kunit.c.
When that happens, test_cross_file_inline() finds no address in lineinfo_cross_file_caller() resolving to lineinfo_kunit.h and fails. Would giving each function a distinct return expression (such as x + 1, x + 2, x + 3) or marking them __noipa prevent the compiler from folding them?
[ ... ]
Quoted 11 lines
lib/tests/lineinfo_kunit.c new file +11
-0+static void test_static_function (struct kunit *test) +{ +char *buf =alloc_sym_buf (test); +unsigned long addr =target_addr (lineinfo_target_short); + +skip_without_module_lineinfo (test); + +sprint_with_lineinfo (buf, addr); +KUNIT_EXPECT_TRUE_MSG (test,has_lineinfo (buf), +"No lineinfo in: %s" , buf); +}
[ ... ]
lib/tests/lineinfo_kunit.c line 320
Quoted 11 lines
lib/tests/lineinfo_kunit.c new file +11
-0+static void test_short_function (struct kunit *test) +{ +char *buf =alloc_sym_buf (test); +unsigned long addr =target_addr (lineinfo_target_short); + +skip_without_module_lineinfo (test); + +sprint_with_lineinfo (buf, addr); +KUNIT_EXPECT_TRUE_MSG (test,has_lineinfo (buf), +"No lineinfo for short function in: %s" , buf); +}
[Severity: Low]
Does test_static_function() duplicate test_short_function()? Both functions resolve target_addr(lineinfo_target_short) with sprint_with_lineinfo(buf, addr) and check has_lineinfo(buf), and all of the local target functions in lib/tests/lineinfo_kunit.c are already static.
[ ... ]
Quoted 10 lines
lib/tests/lineinfo_kunit.c new file +10
-0+static void test_symbol_start_addr (struct kunit *test) +{ +char *buf =alloc_sym_buf (test); +unsigned long addr =target_addr (lineinfo_target_normal); + +skip_without_module_lineinfo (test); + +/* +* sprint_backtrace() subtracts 1 from the input and reports offset +* relative to the (decremented) address, so an exact "+0x0/" can't
lib/tests/lineinfo_kunit.c line 512
Quoted 10 lines
lib/tests/lineinfo_kunit.c new file +10
-0+* be expected here. Verify the symbol resolves and carries lineinfo. +*/ +sprint_with_lineinfo (buf, addr); +KUNIT_EXPECT_TRUE_MSG (test, +strnstr (buf,"lineinfo_target_normal" , +KSYM_SYMBOL_LEN ) !=NULL , +"Didn't resolve to expected function: %s" , buf); +KUNIT_EXPECT_TRUE_MSG (test,has_lineinfo (buf), +"No lineinfo at function start: %s" , buf); +}
[Severity: Low]
In test_symbol_start_addr(), is the comment about how sprint_backtrace() computes the offset accurate?
In __sprint_symbol(), symbol_offset (-1) is added to address for the lookup and then subtracted back from offset:
address += symbol_offset; len = kallsyms_lookup_buildid(address, &size, &offset, &modname, &buildid, buffer); ... sym_start = address - offset; offset -= symbol_offset;
Because sprint_with_lineinfo() passes addr + 1 to sprint_backtrace(), __sprint_symbol() looks up addr (offset 0) and then adjusts offset to +0x1/ (the undecremented input offset), whereas calling sprint_symbol(buf, addr) directly would report +0x0/ with lineinfo.
[ ... ]
Quoted 10 lines
lib/tests/lineinfo_kunit.c new file +10
-0+static void test_assembly_no_lineinfo (struct kunit *test) +{ +#if IS_BUILTIN (CONFIG_LINEINFO_KUNIT_TEST ) +char *buf =alloc_sym_buf (test); +unsigned long addr = (unsigned long )_text; + +sprint_with_lineinfo (buf, addr); +/* +* _text is typically an asm entry point with no DWARF line info. +* If it has lineinfo, it's a C-based entry — skip in that case.
lib/tests/lineinfo_kunit.c line 579
Quoted 10 lines
lib/tests/lineinfo_kunit.c new file +10
-0+*/ +if (has_lineinfo (buf)) +kunit_skip (test,"_text has lineinfo (C entry?): %s" , buf); + +KUNIT_EXPECT_FALSE_MSG (test,has_lineinfo (buf), +"Unexpected lineinfo for asm symbol: %s" , buf); +#else +kunit_skip (test,"_text not accessible from modules" ); +#endif +}
[Severity: Low]
Can the KUNIT_EXPECT_FALSE_MSG(test, has_lineinfo(buf), ...) assertion in test_assembly_no_lineinfo() ever fail?
If has_lineinfo(buf) is true, the preceding if (has_lineinfo(buf)) check calls kunit_skip(), which aborts the test via kunit_try_catch_throw(), so has_lineinfo(buf) is always false when KUNIT_EXPECT_FALSE_MSG() is reached. Also, since CONFIG_KALLSYMS_LINEINFO depends on CONFIG_DEBUG_INFO (which passes -g in KBUILD_AFLAGS), assembler .S entry points at _text normally have DWARF line info as well, causing this test to always skip.
[ ... ]
Quoted 30 lines
lib/tests/lineinfo_kunit.c new file +30
-0+static void test_many_lines_mid_function (struct kunit *test) +{ +char *buf =alloc_sym_buf (test); +unsigned long addr =target_addr (lineinfo_target_many_lines); +unsigned int line; +unsigned long mid_addr; + +skip_without_module_lineinfo (test); + +/* Get function size from sprint_with_lineinfo output */ +sprint_with_lineinfo (buf, addr); +KUNIT_ASSERT_TRUE (test,has_lineinfo (buf)); + +/* +* Try an address 8 bytes into the function (past prologue). Hide +* the base from the compiler so this does not become a static +* mid-function relocation (sym+8), which objtool flags as a +* relocation to !ENDBR with CONFIG_X86_KERNEL_IBT. +*/ +OPTIMIZER_HIDE_VAR (addr); + mid_addr = addr +8 ; +sprint_with_lineinfo (buf, mid_addr); + +/* +* Should still resolve to lineinfo_target_many_lines. +* Lineinfo should be present with a plausible line number. +*/ + KUNIT_EXPECT_TRUE_MSG(test, + strnstr(buf, "lineinfo_target_many_lines", + KSYM_SYMBOL_LEN) != NULL,
lib/tests/lineinfo_kunit.c line 1050
Quoted 10 lines
lib/tests/lineinfo_kunit.c new file +10
-0+"Mid-function addr resolved to wrong symbol: %s" , + buf); +if (has_lineinfo (buf)) { + line =extract_line (buf); +KUNIT_EXPECT_GE_MSG (test, line, (unsigned int )50 , +"Line %u too low for mid-function" , line); +KUNIT_EXPECT_LE_MSG (test, line, (unsigned int )700 , +"Line %u too high for mid-function" , line); + } +}
[Severity: Low]
In test_many_lines_mid_function(), if sprint_with_lineinfo(buf, mid_addr) fails to produce lineinfo, won't the test silently pass because the line-number checks are guarded by if (has_lineinfo(buf)) instead of asserting KUNIT_ASSERT_TRUE(test, has_lineinfo(buf))?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Re: [PATCH v10 4/4] kallsyms: add KUnit tests for lineinfo feature
On Tue, Nov 03, 2026 at 11:15:28AM +0000, [email protected] wrote:
[...]
Quoted 2 lines
Can GCC's identical-code folding (IPA-ICF) merge
lineinfo_cross_file_caller()intolineinfo_target_with_arg()and causetest_cross_file_inline()to fail?
No. GCC 14, 15 and 16 keep them separate on x86_64, and so does GCC 15 on arm64. The test did fail on arm64, but because all of the caller's rows land on a single instruction.
--
Thanks,
Sasha