kallsyms: embed source file:line info in kernel stack traces
Subsystems (4)
v9 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 v8
================
- Rebase on v7.3-rc3; size and entry-count figures re-measured.
- Keep the last line-program row at an address rather than the first, so an inlined call resolves to the inlined body and not to the call site.
- Annotate %pS and %pSb as well, not only the sprint_backtrace*() forms.
- Expand SHF_COMPRESSED debug sections before applying relocations to them.
- Apply RISC-V and LoongArch ADD/SUB relocation pairs, and refuse an object that leaves any relocation in a patched debug section unapplied.
- Emit line-0 and end_sequence rows as "no annotation" markers instead of dropping them, so an address DWARF leaves unattributed reports nothing.
- Resolve rows sharing an address: a line-0 row wins where the line program puts it last, a sequence end yields to a sequence beginning there, and across compile units coverage is the union.
- Give a function an entry at its own first byte where one row covers several, which is an assembly macro; in C such a row is padding or a split-out fragment, so the unit's language decides.
- CONFIG_CPU_ENDIAN_BE8: build the table from an unconverted partial link and hold back only --be8 and --build-id for the link that produces the module.
- Guard EM_LOONGARCH and R_LARCH_*, which glibc gained only in 2.36.
- Regenerate lineinfo when the final vmlinux link moves text.
- Decode MIPS n64 r_info by its own layout rather than with GELF_R_*.
- Refuse architectures with no known absolute relocation type, instead of generating a table from unrelocated DWARF.
- Fold module table generation into the link command, so a relink caused by a command-line change alone cannot drop the table.
- Relocate every debug section libdw reads: a module built from several objects carried line info for the first one only.
- Pass KBUILD_LDFLAGS to the module ld -r, without which ARCH=i386 fails at its first module and 32-bit ARM warns on every one.
- Check the actual bounds in the init-text KUnit case, which UML fails.
- 4/4 builds the KUnit module from two objects and covers the inline-site and second-object paths, neither of which a single-object module can reach.
- From the sashiko.dev review of v8: scnprintf() in __sprint_symbol(), u64 sums in the blob offset helpers, and an alignment check on blocks_offset and files_offset.
v8: https://lore.kernel.org/all/[email protected]/
Testing
=======
A distribution-style config with 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)
- 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 rule above 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
Builds:
- Each of the four patches builds standalone on x86_64 defconfig + CONFIG_DEBUG_INFO, 0 objtool warnings at every point
- 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 | 99 + MAINTAINERS | 9 + include/linux/kallsyms.h | 18 +- include/linux/mod_lineinfo.h | 319 +++ include/linux/module.h | 40 + init/Kconfig | 35 + kernel/kallsyms.c | 108 +- 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 | 1109 ++++++++ lib/tests/lineinfo_kunit.h | 21 + lib/tests/lineinfo_kunit_second.c | 21 + scripts/.gitignore | 1 + scripts/Makefile | 3 + scripts/Makefile.modfinal | 41 +- scripts/empty_lineinfo.S | 38 + scripts/gen-mod-lineinfo.sh | 45 + scripts/gen_lineinfo.c | 2534 +++++++++++++++++ scripts/kallsyms.c | 11 + scripts/link-vmlinux.sh | 88 +- 24 files changed, 4780 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
Signature · 1 line
2.53.0
PATCH v9 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 | 72 + 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/empty_lineinfo.S | 30 + scripts/gen_lineinfo.c | 1283 +++++++++++++++++ scripts/kallsyms.c | 11 + scripts/link-vmlinux.sh | 88 +- 13 files changed, 1644 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 +72 -0
72 lines not on this page · raw message
MAINTAINERS +6 -0
@@ -14023,6 +14023,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
@@ -2132,6 +2132,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,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
@@ -4,6 +4,7 @@ # the kernel for the build process. hostprogs-always-$(CONFIG_KALLSYMS) += kallsyms +hostprogs-always-$(CONFIG_KALLSYMS_LINEINFO) += gen_lineinfo hostprogs-always-$(BUILD_C_RECORDMCOUNT) += recordmcount hostprogs-always-$(CONFIG_BUILDTIME_TABLE_SORT) += sorttable hostprogs-always-$(CONFIG_ASN1) += asn1_compiler
@@ -37,6 +38,8 @@ HOSTCFLAGS_asn1_compiler.o = -I$(srctree)/include HOSTCFLAGS_sign-file.o = $(shell $(HOSTPKG_CONFIG) --cflags libcrypto 2> /dev/null) HOSTCFLAGS_sign-file.o += -I$(srctree)/tools/include/uapi/ HOSTLDLIBS_sign-file = $(shell $(HOSTPKG_CONFIG) --libs libcrypto 2> /dev/null || echo -lcrypto) +HOSTCFLAGS_gen_lineinfo.o = $(shell $(HOSTPKG_CONFIG) --cflags libdw 2> /dev/null) +HOSTLDLIBS_gen_lineinfo = $(shell $(HOSTPKG_CONFIG) --libs libdw 2> /dev/null || echo -ldw -lelf) ifdef CONFIG_UNWINDER_ORC ifeq ($(ARCH),x86_64)
scripts/empty_lineinfo.S new file +30 -0
@@ -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 +1283 -0
1,283 lines not on this page · raw message
scripts/kallsyms.c +11 -0
@@ -90,6 +90,17 @@ static bool is_ignored_symbol(const char *name, char type)return true; } +/* +* The generated lineinfo tables (scripts/gen_lineinfo, stubbed by +* scripts/empty_lineinfo.S) are read-only data whose size and +* addresses change between kallsyms passes. Match them by prefix so +* the set cannot drift as the table layout evolves. Text symbols are +* exempt, so lib/tests/lineinfo_kunit.c's lineinfo_target_*() stay +* resolvable -- the test looks them up by name. +*/ +if (toupper (type) !='T' && !strncmp (name,"lineinfo_" ,9 )) +return true; +return false; }
scripts/link-vmlinux.sh +85 -3
132 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 2 potential issue(s) to consider: - [Low] scripts: division by zero in find_vmlinux_sym() due to missing sh_entsize check - [Low] scripts…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Low] scripts: division by zero in find_vmlinux_sym() due to missing sh_entsize check
- [Low] scripts: memory leak of dynamically allocated arrays at exit
--
commit 37641e6c997ac852eedac002b430b40b946dc18d
Author: Sasha Levin <[email protected]>
Subject: kallsyms: embed source file:line info in kernel stack traces
This commit adds CONFIG_KALLSYMS_LINEINFO, which embeds DWARF-derived address-to-line mappings directly into the kernel image. A new host tool (scripts/gen_lineinfo) extracts this info from vmlinux using libdw. The stack traces will then directly print file and line numbers.
Quoted 4 lines
scripts/gen_lineinfo.c new file +0
-0
[ ... ]
Quoted 11 lines
scripts/gen_lineinfo.c new file +11
-0+static unsigned long long find_vmlinux_sym (Elf *elf,const char *name, +unsigned long long fallback, +bool required) +{ +size_t nsyms, i; +Elf_Scn *scn =NULL ; +GElf_Shdr shdr; + +while ((scn =elf_nextscn (elf, scn)) !=NULL ) { +Elf_Data *data; +
scripts/gen_lineinfo.c line 398
Quoted 10 lines
scripts/gen_lineinfo.c new file +10
-0+if (!gelf_getshdr (scn, &shdr)) +continue ; +if (shdr.sh_type !=SHT_SYMTAB ) +continue ; + + data =elf_getdata (scn,NULL ); +if (!data) +continue ; + + nsyms = shdr.sh_size / shdr.sh_entsize;
[Severity: Low]
Can this division cause a crash if a malformed ELF file is encountered?
If the vmlinux ELF file is malformed and contains an SHT_SYMTAB section where shdr.sh_entsize is zero, this will result in a division by zero and a SIGFPE crash. Other functions in this file, such as collect_symbol_starts(), appear to validate !shdr.sh_entsize before performing this division. Should this loop skip sections with a zero sh_entsize as well?
[ ... ]
Quoted 2 lines
scripts/gen_lineinfo.c new file +2
-0+int main (int argc,char *argv[]) +{
[ ... ]
scripts/gen_lineinfo.c line 1283
Quoted 10 lines
scripts/gen_lineinfo.c new file +10
-0+/* Cleanup */ +free (entries); +free (sym_starts); +free (seq_ends); +for (unsigned int i =0 ; i < num_files; i++) +free (files[i]); +free (files); + +return 0 ; +}
[Severity: Low]
Does this cleanup block miss some dynamically allocated arrays?
The main() function allocates text_starts, asm_spans, and cu_row_seq_end during execution, but omits freeing them here. While the OS reclaims memory upon process exit (making the leak relatively harmless for a short-lived build tool), the presence of a dedicated cleanup block implies an intent to achieve a clean memory leak check. Could text_starts, asm_spans, and cu_row_seq_end be added to this cleanup section?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v9 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
#ifdef 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 | 1462 +++++++++++++++-- 11 files changed, 1883 insertions(+), 152 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
@@ -51,22 +51,49 @@ 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``. 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. - **No assembly annotations**: Functions implemented in assembly that lack DWARF ``.debug_line`` data 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
@@ -14027,6 +14027,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
@@ -503,6 +503,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;
@@ -1016,6 +1022,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
@@ -2152,6 +2152,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
@@ -2723,6 +2723,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),
@@ -3176,6 +3189,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 +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 +1322 -140
1,832 lines not on this page · raw message
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v9 2/4] kallsyms: extend lineinfo to loadable modules
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] scripts: gen_lineinfo: integer overflow in relocation bounds check allows OOB access --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] scripts: gen_lineinfo: integer overflow in relocation bounds check allows OOB access --
commit 39f395f93fb90faf7a6d102ff862dc9fb6013c84
Author: Sasha Levin <[email protected]>
kallsyms: extend lineinfo to loadable modules
This commit adds CONFIG_KALLSYMS_LINEINFO_MODULES to extend the lineinfo feature to loadable kernel modules. It post-processes each .ko file at build time to embed binary tables containing section-relative offsets, file IDs, line numbers, and filenames.
Quoted 3 lines
scripts/gen_lineinfo.c +0
-0
[ ... ]
Quoted 7 lines
scripts/gen_lineinfo.c +7
-0+static void apply_one_debug_reloc (Elf_Data *dl_data,Elf_Data *sym_data, +bool target_le,const GElf_Ehdr *ehdr, +unsigned int abs32_type, +unsigned int abs64_type,GElf_Xword r_info, +GElf_Addr r_offset,GElf_Sxword addend, +bool has_addend,bool bias) +{
[ ... ]
scripts/gen_lineinfo.c static void collect_symbol_starts(Elf *elf, unsigned long long text_addr) · line 1156
Quoted 5 lines
scripts/gen_lineinfo.c +5
-0+if (arith_width) { +uint64_t cur; + +if (r_offset + arith_width > dl_data->d_size) +return ;
[Severity: Medium]
Could an integer overflow occur here? If a malformed ELF relocation has an r_offset near UINT64_MAX, r_offset + arith_width could wrap around to a small value and incorrectly pass this bounds check.
Since the tool subsequently does pointer arithmetic using r_offset:
(unsigned char *)dl_data->d_buf + r_offset
Would this allow an out-of-bounds read and write on the section buffer?
Quoted 7 lines
scripts/gen_lineinfo.c +7
-0+/* +* A delta, not an address: the section bias would appear in +* the ADD and cancel in the matching SUB, so leave it out. +*/ + cur =elf_read_uint ((unsigned char *)dl_data->d_buf + r_offset, + arith_width, target_le); + value = (uint64_t )(sym.st_value + addend);
scripts/gen_lineinfo.c static void collect_symbol_starts(Elf *elf, unsigned long long text_addr) · line 1173
Quoted 10 lines
scripts/gen_lineinfo.c +10
-0+ cur = is_sub ? cur - value : cur + value; +elf_write_uint ((unsigned char *)dl_data->d_buf + r_offset, + cur, arith_width, target_le); +return ; + } + + width = is_abs64 ?8 :4 ; + +if (r_offset + width > dl_data->d_size) +return ;
[Severity: Medium]
Similarly, can r_offset + width overflow here? A crafted .ko or .o file might bypass this validation due to wrapping, leading to the same out-of-bounds access on the dl_data->d_buf buffer further down.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
PATCH v9 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 | 263 +++++++++++++++--- 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, 457 insertions(+), 220 deletions(-)
Documentation/admin-guide/kallsyms-lineinfo.rst +3 -3
@@ -77,10 +77,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 +226 -37
310 lines not on this page · raw message
init/Kconfig +5 -3
@@ -2147,8 +2147,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.
@@ -2161,7 +2162,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 v9 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() as GPL symbols 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 | 2 + lib/Kconfig.debug | 10 + lib/tests/Makefile | 4 + lib/tests/lineinfo_kunit.c | 1109 +++++++++++++++++++++++++++++ lib/tests/lineinfo_kunit.h | 21 + lib/tests/lineinfo_kunit_second.c | 21 + 6 files changed, 1167 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 +2 -0
@@ -661,6 +661,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
@@ -681,6 +682,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
@@ -3063,6 +3063,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
@@ -37,6 +37,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 +1109 -0
1,109 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