unwind: Minimal DWARF CFI unwinding for user and kernel space
Subsystems (22)
Ian Rogers
reviewerv2 cover unwind: Minimal DWARF CFI unwinding for user and kernel space
Overview
========
This RFC v2 series introduces Minimal DWARF Call Frame Information (CFI) stack unwinding in the Linux kernel for both user-space deferred callchains (unwind_user / PERF_RECORD_CALLCHAIN_DEFERRED) and kernel-space stack traces (stacktrace.h / HAVE_RELIABLE_STACKTRACE) across x86-64, ARM64, and RISC-V, paired with an optional standalone C build-time .eh_frame minifier (scripts/min_eh_frame.c).
It enables reliable stack unwinding across kernel and user-space binaries compiled with or without frame pointers (-fomit-frame-pointer), without introducing duplicate .sframe sections in user-space ELF files or requiring new compiler, assembler, or dynamic-loader formats.
Changes in v2
=============
Addressed review findings from Sashiko and BPF CI on RFC v1:
- Cross-config & non-UNWIND_USER build fixes: Guard default unwind_user_frame_pointer() with CONFIG_HAVE_UNWIND_USER_FP (fixes s390/loongarch builds); guard x86 is_rethook_trampoline() with CONFIG_RETHOOK; guard RISC-V struct mod_arch_specific with CONFIG_HAVE_MOD_ARCH_SPECIFIC; guard live KUnit stack walk with CONFIG_STACKTRACE; fix UNWINDER_DWARF_CFI_MINIFY Kconfig dependencies and unlock LATENCYTOP / FAULT_INJECTION_STACKTRACE_FILTER.
- Core interpreter & module hardening (dwarf_cfi.c): Mask DW_EH_PE_SIGNED on slow-path FDE pc_range decoding; switch module table allocation to kvmalloc()/kvfree_rcu_mightsleep(); mark kernel unwind entry points noinstr; add kmsan_unpoison_memory() on outputs under KMSAN_SANITIZE := n; clarify DW_EH_PE_indirect wording; and add KUnit coverage for CALLER_ADDR0/1, 32-bit vdso32 sigreturn, negative sdata4 ranges, and dwarf_cfi_scan_eh_frame_kmem().
- User-space SP tracking & compat fixes: Track DW_CFA_offset on sp_reg so 32-bit x86 vdso32 __kernel_rt_sigreturn recovers %esp from sigcontext; track state->sp_valid (unwind_user_fp_sets_sp() == false on ARM64) across mixed CFI -> FP -> CFI walks and ARM64 sigreturn; strip Thumb bit 0 in ARM64 compat unwind_user_strip_pac(); drop redundant get_user_word() wrapper checks; and skip unwind_user_cfi gracefully on 32-bit ARM EHABI binaries lacking PT_GNU_EH_FRAME.
- Architecture kernel unwinder fixes: Reject in-kernel pt_regs frames in x86 arch_stack_walk_reliable() under CONFIG_UNWINDER_DWARF_CFI (where inline asm such as pushf; pop lacks .cfi_adjust_cfa_offset) and align kernel/trace/ ftrace stack-skip calibration with ORC; replace eager CFI walks in ARM64 and RISC-V perf_arch_fetch_caller_regs() with fast inline markers resolved lazily during callchain walks; preserve -fno-omit-frame-pointer in the ARM64 user vDSO; fix ARM64 ftrace_caller epilogue matching via fregs->sp; save RV_REG_RA unconditionally in RV64 BPF JIT prologues under UNWINDER_DWARF_CFI; add -fno-optimize-sibling-calls to RISC-V stacktrace.o; and accept size == 0 at exact stack top in riscv_stack_bounds().
- Host tools & MAINTAINERS: Add tools/unwind/verify_cfi (optional standalone libLLVM verifier cross-checking kernel/unwind/dwarf_cfi.c against reference DWARF, multi-arch CFG instruction execution, and x86-64 .orc_unwind), add /min_eh_frame to scripts/.gitignore, use explicit little-endian ELF field accessors in scripts/min_eh_frame.c for big-endian build hosts, fix i386 DRAP register set, malformed SLEB128 handling, and .o/.ko summary formatting in eh_frame_min.py, and add a MAINTAINERS entry for DWARF CFI stack unwinding (plus arch/*/include/asm/unwind_user*.h under USERSPACE STACK UNWINDING).
Motivation
==========
1. Limitations of Frame-Pointer-Only Unwinding
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Ecosystem defaults: Many Linux distributions (e.g., Debian, RHEL, Alpine), language toolchains, and prebuilt third-party shared libraries compile with -fomit-frame-pointer by default. A single frameless shared library in a call path breaks frame-pointer walks.
- Completeness and reliability: Even with -fno-omit-frame-pointer, frame-pointer chains miss callers inside leaf functions, function prologues/epilogues, and hand-written assembly routines (such as libc string/math/crypto primitives), and cannot guarantee reliable kernel stack traces across asynchronous boundaries without external validation such as objtool.
2. Drawbacks of SFrame (PT_GNU_SFRAME)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SFrame was proposed as a simplified out-of-band unwind format to avoid placing a full DWARF .eh_frame virtual machine in the kernel. In practice, introducing a second unwind format carries substantial costs:
- ~2x user-space unwind metadata bloat: User-space ELF executables and shared libraries must already ship .eh_frame and .eh_frame_hdr (PT_GNU_EH_FRAME) for C++ exceptions, Rust panics, pthread_cancel forced unwinding, and _Unwind_Backtrace(). Because SFrame omits callee-saved register locations, personality routines, and LSDA pointers, it cannot replace .eh_frame. On binaries built with GNU Binutils 2.47 (SFRAME_VERSION_3), .sframe is nearly the same size as .eh_frame + .eh_frame_hdr combined (e.g., +123.9 KB atop 124.1 KB in /bin/bash, and +164.5 KB atop 163.5 KB in aarch64-linux-gnu-gcc-15), roughly doubling unwind table footprint on disk.
- Toolchain and architecture gaps: SFrame has gone through incompatible binary format revisions (v1 -> v2 -> v3), lacks upstream Clang/LLVM support, lacks RISC-V -mrelax linker-relaxation support in standard binutils, and requires new build flags (-Wa,--gsframe) across the entire user-space ecosystem before profiling benefits materialize.
- Expressiveness gaps and dropped FDEs: SFrame cannot represent dynamically realigned DRAP stack frames (CFA = *(fp + off), e.g., 64-byte aligned locals in mm/vmscan.c:shrink_lruvec()), and GNU as --gsframe silently omits .sframe FDEs when hand-written assembly uses non-standard CFI patterns (for example, warning "no SFrame FDE emitted; FP without RA on stack" on ARM64's return_to_handler).
3. Core Insight of Minimal DWARF CFI
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Historically, in-kernel DWARF .eh_frame unwinding was rejected for two reasons:
1. Execution context (predating deferred stack traces): Earlier proposals predated deferred user-space stack tracing for perf and BPF (unwind_deferred / PERF_RECORD_CALLCHAIN_DEFERRED). When user callchains could only be captured synchronously inside NMI/atomic context under pagefault_disable(), the kernel could neither take mmap_lock to locate PT_GNU_EH_FRAME VMAs nor fault in cold .eh_frame pages (forcing perf --call-graph dwarf to copy 8-64 KB of raw user stack per sample). Upstream's deferred task_work unwind infrastructure now solves that faultability barrier for any table-based user unwinder.
2. Unrestricted DWARF state-machine complexity: Full DWARF permits Turing-complete DW_OP_* expressions, arbitrary N-register tracking arrays, DW_CFA_set_loc backward PC jumps, and DW_EH_PE_indirect pointer dereferences.
With deferred unwinding solving (1) for user space (while kernel .eh_frame tables remain pinned in RAM for NMI/atomic walks), (2) is solved if an in-kernel .eh_frame_hdr / .eh_frame interpreter restricts its state machine to the exact state model of SFrame -- tracking only CFA, SP (for signal frames), Frame Pointer (FP), and Return Address (RA), plus link-register leaf state, ARM64 PAC-RET signing (0x2d), a 4-entry remember_state stack, and a fixed 3-byte pattern match for DRAP/sigreturn frames while decoding and discarding general callee-saved GPR spill opcodes:
- O(1) stack memory, zero heap allocations, zero locks in the core interpreter, and strictly bounded single-pass execution;
- Smaller unwind metadata than SFrame by construction: SFrame stores materialized table rows (re-emitting full CFA/FP/RA offsets on every FRE, plus an explicit PC+0 entry FRE per function because there is no shared CIE), whereas DWARF encodes delta-compressed bytecodes (6-bit packed PC advances, alignment-scaled LEB128 deltas for only the rule that changed, 1-byte remember/restore_state, and a single 20-24 B CIE shared across ~70,000 FDEs). Once unneeded GPR spill ops are stripped, minified DWARF is naturally smaller than SFrame;
- Immediate compatibility with existing unmodified Linux binaries and libc.so.6 across x86 (64/32-bit), ARM64 (AArch64/AArch32), and RISC-V (RV64/RV32) built with either GCC or Clang/LLVM;
- 100.00% FDE coverage across x86_64, arm64, and riscv vmlinux builds (195,019 / 195,019 functions).
(ARM64 already has in-tree precedent in arch/arm64/kernel/pi/patch-scs.c, which parses .eh_frame CIEs/FDEs in ~180 lines with zero allocations; this series preserves __pi___eh_frame_* so Dynamic Shadow Call Stack boot-time patching continues to work unchanged.)
Comparison with Related Upstream .eh_frame Proposals
====================================================
Two recent upstream RFC series independently arrived at DWARF .eh_frame as a practical alternative to SFrame:
1. Jens Remus -- unwind_user .eh_frame Handling (x86-64, s390)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Jens's 24-patch RFC v2 shares the same core user-space motivation and safety model: reusing existing .eh_frame_hdr / .eh_frame sections over deferred unwind_user without a general DWARF expression VM, evaluating only CFA/SP/FP/RA rules and fixed-pattern expressions (such as x86 DRAP and PLT entries). Key differences in this series:
- Unified user and kernel engine: Jens's series targets user-space deferred unwinding only (x86-64 and s390). This series uses a single noinstr-safe core interpreter (kernel/unwind/dwarf_cfi.c) across both user-space and kernel-space (NMI/IRQ and HAVE_RELIABLE_STACKTRACE) unwinding on x86-64, ARM64, and RISC-V, paired with build-time minification (scripts/min_eh_frame.c) and static multi-oracle verification (tools/unwind/verify_cfi).
- Zero-registration VMA lookup vs. mm maple tree + prctl(): Following earlier sframe_register() designs, Jens's series registers executable .eh_frame_hdr sections in fs/binfmt_elf.c into a per-mm maple tree (mm->eh_frame_mt, duplicated across fork/clone) and adds UAPI prctl(PR_REGISTER_EH_FRAME / PR_UNREGISTER_EH_FRAME), requiring dynamic-linker (ld.so) patches before shared libraries can be unwound. Here, kernel/unwind/user_cfi.c resolves PT_GNU_EH_FRAME directly from mapped ELF VMAs (vm_pgoff == 0) on demand with a 4-slot per-walk VMA cache -- requiring zero mm_struct state, zero fork/clone duplication, zero new UAPI, and zero libc/ld.so changes to unwind unmodified shared libraries today.
- Signal frames, 32-bit compat, and per-frame FP fallback: Jens's RFC v2 leaves signal frames and 32-bit compat as future work and caps remember_state depth at 1. This series unwinds signal frames across x86-64, 32-bit vdso32, ARM64, and RISC-V (including SA_ONSTACK and interrupted leaf functions), supports 32-bit compat tasks (IA-32, AArch32, RV32), supports 4-deep remember_state stacks, and falls back per frame (CFI -> FP -> CFI) across anonymous JIT code. Conversely, Jens's s390 port (CFA = SP_callsite + 160) and 11-byte x86 PLT expression pattern are clean additions that fit naturally into this model.
2. Dylan Hatch -- ARM64 .lr_unwind Reliable Stacktrace
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dylan's 12-patch RFC (with Weinan Liu) also builds ARM64 from compiler .eh_frame tables rather than SFrame for Clang/LLVM compatibility, factoring arch/arm64/kernel/pi/patch-scs.c's parser into <asm/eh_frame.h> and distilling .eh_frame at build time (scripts/gen_lr_unwind) into custom .lr_unwind_fde / .lr_unwind_ranges sections (~800-935 KiB). Key differences and trade-offs:
- Frameless (-fomit-frame-pointer) multi-arch unwinder vs. ARM64 FP companion table: .lr_unwind retains -fno-omit-frame-pointer across the ARM64 kernel and encodes only 3 exception-boundary states (LIVE x30, [x29], or [sp + sp_off]) to step across pt_regs before handing off to standard x29 frame-pointer walks (omitting frameless x30-spilling functions). This series eliminates the frame-pointer overhead across x86-64, ARM64, and RISC-V (-fomit-frame-pointer), keeps standard minified .eh_frame + .eh_frame_hdr (~2.72 MB on ARM64 vmlinux, preserving gdb/crash compatibility without a custom section format or sorttable pass), covers 100.00% of vmlinux FDEs, and shares the same interpreter with user-space unwinding.
- Asynchronous pt_regs exception boundaries and CFI verification:
.lr_unwind specifically targets reliable stacktraces across in-kernel pt_regs interrupt boundaries on ARM64 (including annotating crypto/lib leaf assembly via SYM_LEAF_FUNC_START), whereas this series conservatively rejects in-kernel pt_regs boundaries in arch_stack_walk_reliable() today. Notably, running our CFG instruction-execution verifier (tools/unwind/verify_cfi) on ARM64 vmlinux shows why instruction-level validation is needed before trusting pt_regs boundaries for livepatching: GCC 15.2 mis-schedules epilogue .cfi directives on certain __builtin_frame_address(0) frames with outgoing stack arguments (affecting .eh_frame, .sframe, and .eh_frame-derived tables such as .lr_unwind alike). Dylan's leaf assembly CFI annotations and kunwind_next_cfi()'s existing live-LR vs. stack-LR handling at KUNWIND_SOURCE_REGS_PC are directly complementary once compiler and assembly asynchronous CFI passes verify_cfi.
Benefits vs. Drawbacks and Trade-offs
=====================================
Benefits
~~~~~~~~
1. Zero duplicate user-space metadata: Reuses existing PT_GNU_EH_FRAME tables already present in standard ELF binaries (~50% smaller total unwind metadata than shipping both .eh_frame* and .sframe).
2. Toolchain and ecosystem readiness: Works out of the box with GCC and Clang/LLVM, C and Rust kernel code, RISC-V -mrelax linker relaxation, x86 IA32 and ARM32/RV32 compat user binaries, and existing distro root filesystems.
3. Smaller kernel unwind tables: With build-time .eh_frame minification (scripts/min_eh_frame.c), kernel .eh_frame tables are 18%-28% smaller than SFrame v3 (.sframe) in .o objects and 26.5% smaller than x86-64 ORC (~3.16 MB for .eh_frame + .eh_frame_hdr vs. ~4.30 MB for .orc_unwind* on x86-64 vmlinux). On ARM64 vmlinux, even combined minified .eh_frame + .eh_frame_hdr (2.72 MB) is smaller than linked .sframe alone (2.80 MB).
4. Full frame-shape coverage: Unwinds SP-based frames, VLA/alloca FP frames, 64-byte DRAP stack-realigned frames, shrink-wrapped prologues/epilogues, ARM64 PAC-RET frames, signal trampolines (including SA_ONSTACK, 32-bit vdso32 sigreturn, and interrupted leaf functions), and mixed CFI + JIT frame-pointer stacks.
Drawbacks and Limitations
~~~~~~~~~~~~~~~~~~~~~~~~~
1. Higher per-frame CPU cost than FP, ORC, or SFrame: Interpreting linear FDE CFA bytecodes from function entry to target PC takes ~47-51 ns/frame (~185-202 cycles) in the hardened C interpreter, compared to ~1 ns/frame for frame pointers and ~19 ns/frame for fixed-record SFrame/ORC lookups. This is negligible for crash/oops dumps, /proc/<tid>/stack, livepatch transitions, and amortized task_work user walks, though slightly costlier than ORC if kernel callchains are sampled at very high PMU NMI frequencies.
2. User-space CFI requires deferred task_work context (not NMI): Just like user-space SFrame, user .eh_frame* sections live in cold, demand-paged user VMAs that cannot be faulted in or VMA-resolved under NMI/IRQ (pagefault_disable() / mmap_lock). Synchronous perf_callchain_user() in NMI remains FP-only; user CFI runs via PERF_RECORD_CALLCHAIN_DEFERRED on return to user space. If an NMI fires mid-syscall before execve(), munmap()/dlclose(), or pending signal delivery, exit-time user state can differ slightly from NMI-time state. (Note: the kernel also must not auto-enable defer_callchain behind unaware perf_event_open() callers, as doing so alters the PERF_RECORD_SAMPLE ips[] ABI; defaulting belongs in user-space tools/perf after probing kernel support.)
3. Build-time minifier host pass and stripped GPR rules: Achieving smaller-than-SFrame kernel .eh_frame sizes uses a fast host C pass (scripts/min_eh_frame.c) on .o files until compilers offer an optional -funwind-tables=minimal flag under -fno-exceptions. When minification is enabled on vmlinux, PC/SP/FP backtraces in gdb/crash work normally, but inspecting spilled callee-saved GPRs in outer frames requires .debug_frame (or leaving CONFIG_UNWINDER_DWARF_CFI_MINIFY disabled on debug builds).
4. Reliance on compiler and assembly .cfi_* annotations: Unlike x86 objtool (which validates machine instructions directly), .eh_frame (like .sframe) trusts compiler -fasynchronous-unwind-tables output and manual .cfi_* annotations in hand-written .S / inline-asm code. For this reason, arch_stack_walk_reliable() across x86-64, ARM64, and RISC-V conservatively rejects stacks containing in-kernel asynchronous exception/preemption pt_regs boundaries (matching Documentation/livepatch/reliable-stacktrace.rst), while unwinding normal sleeping/synchronous tasks reliably without frame pointers.
5. Hard interpreter bounds: Pathological FDEs with > 4,096 bytes of bytecode or DW_CFA_remember_state depth > 4 are rejected with -EINVAL (falling back to FP in user space). Across all 195,019 vmlinux FDEs on x86-64, ARM64, and RISC-V, 0 FDEs hit the size bound and the maximum observed remember_state depth is 1.
Execution Contexts and Fallback Mechanics
=========================================
1. When Kernel-Space vs. User-Space CFI Can Run
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Context Kernel CFI User CFI Notes
-------------------------- ----------- ----------- -------------------
PMU NMI (in_nmi()) Yes (direct) No (defer) Pinned vmlinux/RCU
mod vs. cold VMAs
Hardirq / Softirq / BPF Yes (direct) No (defer) bpf_get_stack[id];
user sync = FP-only
Return-to-user task_work Yes Yes (faults) mmap_read_lock then
copy_from_user()
Cross-task /proc/tid/stack Yes No current->mm only
Livepatch reliable walk Yes (all 3) N/A Kernel-only API
Kernel threads / x86 VM86 Yes (kthd) No mm == NULL / 16-bitWhenever user-space CFI cannot run synchronously (for example, non-deferred perf_callchain_user() or atomic bpf_get_stack() / bpf_get_stackid() with BPF_F_USER_STACK in NMI, IRQ, or preempt-disabled context), the kernel falls back to the existing synchronous frame-pointer user stack walk (arch_stack_walk_user()) just as it does today. When deferred user unwinding is requested in NMI, unwind_deferred_request() takes ~10-20 ns and emits [PERF_CONTEXT_USER_DEFERRED, cookie]; even if dozens of PMU NMIs fire during a slow syscall, unwind_user_faultable() walks the user stack at most once on return to user space.
2. Per-Frame User-Space Fallback (CFI -> FP -> CFI)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~unwind_user_next() (kernel/unwind/user.c) evaluates each frame independently rather than locking an entire walk to one unwinder:
1. Architectural signal trampoline hook (unwind_user_sigreturn()):
Checked first (bounded to UNWIND_USER_MAX_SIGNALS = 4 per walk so SA_ONSTACK switches cannot loop). On ARM64 (__kernel_rt_sigreturn) and RISC-V (__vdso_rt_sigreturn), where vDSO trampolines omit .eh_frame register rules for libgcc compatibility, recovers pc, sp, fp, and lr/ra (with ra_valid = true, sp_valid = true) from rt_sigframe. On x86-64 and 32-bit vdso32, .cfi_signal_frame ('S' augmentation, including CFI_OFFSET esp) is handled directly by CFI.
2. Minimal DWARF CFI (highest priority):
Resolves PT_GNU_EH_FRAME via a 4-slot per-walk VMA cache (or under mmap_read_lock_killable(), dropped before copy_from_user()):
- Explicit bottom of stack (DW_CFA_undefined on RA, or RA == 0):
sets state->done = true and stops cleanly without FP fallback.
- Missing PT_GNU_EH_FRAME / FDE (-ENOENT, e.g. anonymous RX JIT code) or unsupported/SP-invalid bytecode (-EINVAL/-EFAULT):
caches a negative VMA entry when no PT_GNU_EH_FRAME exists, leaves state->done = false, and falls through to FP for this frame.
3. Frame pointer fallback: Steps out of the JIT/non-CFI frame via FP
(tracking state->sp_valid via unwind_user_fp_sets_sp()).
4. Automatic return to CFI: On the next frame, unwind_user_next() tries Minimal DWARF CFI first again, unwinding mixed stacks seamlessly as CFI -> FP -> CFI -> FP -> CFI.
Compatibility with Kernel Livepatching (HAVE_RELIABLE_STACKTRACE)
=================================================================
All three architectures support arch_stack_walk_reliable() for kernel livepatching under CONFIG_UNWINDER_DWARF_CFI, even when compiled with -fomit-frame-pointer:
- x86-64 (arch/x86/kernel/unwind_dwarf.c & stacktrace.c): Unwinds vmlinux and RCU module .eh_frame tables, recovers CFA-keyed ftrace_graph and rethook return addresses, sets state->error on any missing or invalid FDE, and rejects stacks containing in-kernel pt_regs boundaries in arch_stack_walk_reliable() (matching CONFIG_FRAME_POINTER because inline asm such as pushf; pop adjusts %rsp without .cfi_adjust_cfa_offset across preemption).
- ARM64 (arch/arm64/kernel/stacktrace.c): Preserves ARM64's existing HAVE_RELIABLE_STACKTRACE and HAVE_LIVEPATCH guarantees without frame pointers. Normal sleeping tasks unwind via kunwind_next_cfi() down to the SP-verified FRAME_META_TYPE_FINAL entry boundary. Every non-CFI fallback (live x30 guess or AArch64 frame-record fallback for JITed eBPF code) sets state->unreliable = true, and in-kernel exception boundaries set KUNWIND_SOURCE_REGS_PC -- both of which are rejected with -EINVAL by arch_reliable_kunwind_consume_entry(). Compared to ARM64 SFrame proposals (and complementing .lr_unwind as noted above), Minimal DWARF CFI works with both Clang/LLVM and GCC today and achieves 100.00% FDE coverage (including entry-ftrace.S's return_to_handler where GNU as omits .sframe). Moreover, kunwind_next_cfi() already distinguishes live LR (DWARF_CFI_RULE_SAME) vs. stack-saved LR (DWARF_CFI_RULE_OFFSET) at regs->pc, so if asynchronous epilogue/.S CFI is audited across ARM64 in the future, reliable traversal across KUNWIND_SOURCE_REGS_PC requires no format changes.
- RISC-V (arch/riscv/kernel/stacktrace.c): Selects HAVE_RELIABLE_STACKTRACE under CONFIG_UNWINDER_DWARF_CFI. walk_stackframe_cfi(..., require_reliable = true) verifies every step via .eh_frame CFI and SP-keyed ftrace_graph/rethook recovery while rejecting handle_exception pt_regs frames and non-CFI fallbacks with -EINVAL.
Compatibility with User Space and Kernel Subsystems
===================================================
- C++ exceptions, Rust panics, and pthread_cancel: 100% unchanged. The kernel only reads PT_GNU_EH_FRAME in user ELF mappings, skipping 'zPLR' personality ('P') and LSDA ('L') augmentations and ignoring callee-saved GPR opcodes. ARM64 and RISC-V vDSO sigreturn trampolines are untouched so libgcc's instruction-matching fallback is preserved.
- Debugging (gdb, lldb, kdump/crash): User debugging is untouched. Kernel backtraces (bt), .debug_line, and .debug_info work normally.
- Hardware security, sanitizers, and eBPF: Supports ARM64 PAC-RET + BTI (-mbranch-protection=standard), ARM64 Dynamic Shadow Call Stack (patch-scs.c), x86 Kernel IBT (objtool skips .eh_frame* relocations), SW-tag KASAN (__hwasan_tag_mismatch .cfi_* annotations), KMSAN output unpoisoning, Spectre v1 / v1.1 nospec bounds clamping, and JITed eBPF programs (bpf_get_stack, bpf_get_stackid).
Worked Examples
===============
Example 1: Single-Function Encoding (Raw vs. Minified .eh_frame vs. SFrame)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For a 64-byte C function compiled with gcc -O2 -fomit-frame-pointer -fasynchronous-unwind-tables -Wa,--gsframe (3 GPR spills: r15, r14, rbx):
Raw .eh_frame (30 B FDE + 8 B .eh_frame_hdr entry = 38 B; 1 shared CIE):
42 0e 10 [8f 02] # +2: CFA=rsp+16, [r15 at cfa-16 -> ignored]
45 0e 18 [8e 03] # +5: CFA=rsp+24, [r14 at cfa-24 -> ignored]
44 0e 20 [83 04] # +4: CFA=rsp+32, [rbx at cfa-32 -> ignored]
47 0e 30 # +7: CFA=rsp+48
66 0e 20 | 41 0e 18 | 42 0e 10 | 42 0e 08 # epilogue popsMinified .eh_frame (24 B FDE + 8 B .eh_frame_hdr entry = 32 B):
42 0e 10 | 45 0e 18 | 44 0e 20 | 47 0e 30
66 0e 20 | 41 0e 18 | 42 0e 10 | 42 0e 08SFrame v3 .sframe (27 B FREs + 5 B FRE hdr + 16 B FDE index = 48 B):
00 03 08 | 02 03 10 | 07 03 18 | 0b 03 20 | 12 03 30
38 03 20 | 39 03 18 | 3b 03 10 | 3d 03 08 # no shared CIE: +PC=0 FREExample 2: Kernel-Space Walk (eBPF + DRAP Module + kretprobe on ARM64)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Context: JITed eBPF raw_tracepoint("sched_switch") -> bpf_get_stack()]
Frame 0: bpf_prog_<tag> (JITed eBPF text, no .eh_frame)
-> .eh_frame lookup: -ENOENT -> falls back to FP record [x29, x29+16]
(sets state->unreliable = true; allowed for non-reliable bpf walk)
-> Recovers caller PC in tracepoint hook, resumes CFI on Frame 1 Frame 1: __schedule (vmlinux .text, built with -fomit-frame-pointer)
-> Binary search __start_eh_frame_hdr at lookup_pc = pc - 4
-> Evaluates FDE (skips x19..x28 spills, toggles ra_signed on 0x2d):
row = { cfa = SP + 144, fp = *(CFA - 144), ra = *(CFA - 136), pac }
-> Reads saved x30, strips PAC via ptrauth_strip_kernel_insn_pac() Frame 2: mod_unwind_drap [test_unwind_mod] (64B stack-realigned DRAP)
-> RCU lookup in mod->arch.dwarf_cfi_index matches 3-byte expression
[DW_OP_breg(fp), -40, DW_OP_deref] -> CFA = *(fp - 40) Frame 3: mod_krp_inner [test_unwind_mod] (hijacked by kretprobe)
-> Stack RA == &__kretprobe_trampoline ->
kunwind_recover_return_address() matches entry SP == CFA on
kretprobe shadow list -> restores real PC Frame N: el0t_64_sync_handler (EL0 -> EL1 syscall boundary)
-> .eh_frame: -ENOENT -> SP-verified FRAME_META_TYPE_FINAL (clean stop)
Example 3: User-Space Deferred Walk (Signal + SA_ONSTACK + Leaf + JIT)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[Step A -- In PMU NMI]:
unwind_deferred_request() emits [PERF_CONTEXT_USER_DEFERRED, cookie] and queues TWA_NMI_CURRENT task_work (~15 ns).
[Step B -- Return to User Space (unwind_user_faultable())]:
Frame 0: nanosleep() in libc.so.6 (frameless leaf, topmost = true)
-> Caches libc PT_GNU_EH_FRAME (slot 0), drops mmap_read_lock
-> FDE at exact ip: CFA = SP + 0, RA = SAME -> consumes live LR
-> sigusr1_handler + 0x24; clears state->ra_valid = false
Frame 1: sigusr1_handler (on SA_ONSTACK sigaltstack)
-> Caches binary PT_GNU_EH_FRAME (slot 1); reads RA = vDSO sigreturn
Frame 2: [vdso] rt_sigreturn trampoline
-> unwind_user_sigreturn() reads uc_mcontext from rt_sigframe,
pivots SP back to main stack, restores ip = dso_leaf_tgkill + 8
and live LR (ra_valid = true, signal = true, nr_signals = 1)
Frame 3: dso_leaf_tgkill in libcleanup.so (interrupted frameless leaf)
-> signal == true -> exact ip lookup; RA = SAME consumes restored LR
Frame 4: c_dso_trigger in libcleanup.so ('zPLR' C++ CIE, frameless)
-> Skips personality/LSDA augmentation -> unwinds to jit_bridge
Frame 5: Anonymous PROT_READ|PROT_EXEC JIT stub (no ELF header, has FP)
-> Negative VMA cache hit (slot 3) -> CFI returns -ENOENT -> FP step
Frames 6..9: 64B DRAP -> alloca() VLA -> main -> _start
-> CFI resumes automatically after JIT frame; _start hits
DW_CFA_undefined on RA -> state->done = true (clean stop).Empirical Size and Latency Comparisons
======================================
1. Kernel Unwind Table Sizes (x86_64, arm64, riscv)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Target .text ORC .sframe Min .eh Min .eh+_hdr
------------------ -------- -------- -------- -------- ------------
x86_64 mm/vmscan.o 40.6 KB 14,240 B 7,840 B* 6,432 B --
x86_64 ext4/inode.o 60.3 KB 12,980 B 7,486 B 5,840 B --
x86_64 vmlinux 20.09 MB ~4.30 MB -- 2.62 MB 3.16 MB
arm64 kernel/fork.o 18.5 KB -- 2,617 B 2,040 B 2,548 B
arm64 mm/vmscan.o 28.4 KB -- 2,423 B 1,744 B 2,136 B
arm64 vmlinux 17.64 MB -- 2.80 MB 2.19 MB 2.72 MB
riscv kernel/fork.o 19.8 KB -- -- 2,860 B 3,496 B
riscv mm/vmscan.o 35.3 KB -- -- 5,916 B 7,168 B
riscv vmlinux 11.49 MB -- -- 1.93 MB 2.35 MB
(* SFrame omits DRAP FDEs in x86_64 mm/vmscan.o and ARM64 entry-ftrace.S;
Minimal DWARF covers 100%: 69,958 x86 + 69,765 arm64 + 55,296 riscv.)2. User-Space ELF Unwind Metadata Sizes (GCC 15.2 / Binutils 2.47)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Binary .text Raw .eh* Min .eh* .sframe .eh*+.sf ------------------------ ------- -------- -------- ------- -------- 4,038-fn benchmark (x86) 302 KB 162.4 KB 151.4 KB 137.4 K 299.8 KB /bin/bash (Debian x86) 887 KB 124.1 KB 116.5 KB 123.9 K 248.0 KB aarch64-linux-gnu-gcc-15 911 KB 163.5 KB -- 164.5 K 328.0 KB libc.so.6 (x86-64) 1.47 MB 181.7 KB 171.3 KB -- -- /usr/bin/python3 (x86-64) 3.39 MB 548.7 KB 512.5 KB -- --
3. Unwind Speed (17-Frame Mixed SP/VLA/Shrink-Wrap Walk, 4,038-FDE Binary)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unwinder Implementation 17-Frame Walk ns/Frame Cyc/Frm --------------------------------------- ------------- -------- ------- Frame Pointer (-fno-omit-frame-pointer) 16.3 ns 0.96 ns 2.1 c SFrame v3 (.sframe) 321.3 ns 18.90 ns 74.7 c Hardened kernel dwarf_cfi.c (Min .eh) 795.9 ns 46.82 ns 185.4 c Hardened kernel dwarf_cfi.c (Raw .eh) 860.5 ns 50.62 ns 201.8 c Full DWARF (libgcc _Unwind_Backtrace) 1,476.2 ns 86.83 ns 342.2 c
Testing and Verification
========================
- Static, style, and edge-config checks: 0 errors/warnings from scripts/checkpatch.pl, scripts/kernel-doc -Werror -none, and scripts/spdxcheck.py across all 30 patches, plus cross-config build verification across CONFIG_RETHOOK=n, CONFIG_MODULES=n, CONFIG_PERF_EVENTS=n, CONFIG_STACKTRACE=n, and non-UNWIND_USER headers.
- Multi-architecture libLLVM static verification & x86 ORC cross-check (tools/unwind/verify_cfi):
* Reference DWARF equivalence (Oracle 1): 0 mismatches between libLLVM's reference DWARFUnwindTable and kernel/unwind/dwarf_cfi.c (both user stream and kmem paths) across 207,450 vmlinux FDEs and 2,575,276 transition PCs on x86_64 (73,627/73,627), arm64 (78,116/78,116), and riscv64 (55,707/55,707), plus 0 mismatches across libc.so.6, libstdc++.so.6, libcrypto.so.3, and /bin/bash.
* CFG machine-instruction abstract execution (Oracle 2): 100.00% instruction-clean across riscv64 vmlinux (55,411/55,411 functions; 3,970,473 reachable instructions; 0 CFA/RA/FP diffs) and user libraries (libc.so.6 2,270/2,270, libstdc++.so.6 3,984/3,984, libcrypto.so.3 5,878/5,878); 99.34% on x86_64 vmlinux (69,207/ 69,665; 0 RA/FP diffs, remaining inline-asm pushfq/popq and call_on_stack() IRQ stack pivots); and 98.83% on arm64 vmlinux (76,830/77,741; 0 FP diffs, identifying a GCC 15.2 AArch64 epilogue .cfi scheduling bug on __builtin_frame_address(0) frames with outgoing stack arguments that affects .sframe identically, plus 1 assembly routine missing .cfi_register).
* Direct x86-64 .orc_unwind cross-check (Oracle 3): 99.9823% exact instruction match (4,467,361 / 4,468,154 ORC_TYPE_CALL instructions with FDEs; 0 BP diffs; all 793 CFA instruction diffs confined to inline-asm pushfq/iret sequences lacking .cfi_adjust_cfa_offset).
- Differential equivalence & fuzzing: 100.00% match across 905,231+ ASan+UBSan PC probes against reference DWARF evaluation across x86-64, ARM64 (PAC-RET), and RISC-V (-mrelax), plus 500,000 ASan+UBSan fuzzer iterations on kernel/unwind/dwarf_cfi.c and 5,000 mutated ELF .o fuzzer iterations on scripts/min_eh_frame.c with 0 findings.
- Live multi-architecture QEMU testing (qemu-system-x86_64, qemu-system-aarch64 -M virt -cpu max with PAC-RET + BTI, and qemu-system-riscv64 -M virt -cpu rv64 with RVC):
Passed 8/8 KUnit tests (including CALLER_ADDR0/1, vdso32 sigreturn, negative sdata4 range rejection, and scan_eh_frame_kmem), backtracetest, 10x module load/unload cycles with DRAP + nested kretprobes/rethook + arch_stack_walk_reliable(), 50x cross-task /proc/<tid>/stack walks, JITed eBPF bpf_get_stack() + bpf_get_stackid(), unwind_user_cfi kselftest (clobbered FP, VLA, DRAP, shrink-wrap, anonymous RX JIT >16B CFI->FP->CFI fallback), -m32 IA32 compat (including live SIGUSR1 vdso32 rt_sigreturn), 'zPLR' DSO + SA_ONSTACK SIGUSR1 rt_sigreturn across interrupted leaf functions, and 4-thread hostile ELF VMA fault injection with 0 failures and clean dmesg across all three architectures.
Tool-Assistance Disclosure
==========================
Per Documentation/process/generated-content.rst and Documentation/process/coding-assistants.rst:
- Tools used: Gemini (AI coding assistant), used interactively across an extended engineering session; RFC v1 also received automated AI patch reviews from upstream Sashiko and BPF CI.
- Scope of assistance: Prototyping and refining the bounded DWARF CFA interpreter, user-space PT_GNU_EH_FRAME VMA unwinder, build-time scripts/min_eh_frame.c minifier, x86-64/ARM64/RISC-V kernel and user-space unwinder integrations, standalone tools/unwind/verify_cfi verifier, KUnit/kselftest suites, differential fuzzers, QEMU multi-arch test harnesses, v2 review fixes, and series documentation.
Ian Rogers (30):
unwind: Add Minimal DWARF CFI bytecode interpreter
unwind: Add KUnit tests for Minimal DWARF CFI interpreter
unwind_user: Support Minimal DWARF CFI user-space unwinding
x86: unwind_user: Support Minimal DWARF CFI user unwinding
scripts: Add min_eh_frame build-time .eh_frame minifier
kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY object pass objtool/ibt: Ignore .eh_frame relocations during ENDBR validation vmlinux.lds.h: Allow architectures to emit custom RO_DATA sections efi/libstub: Disable unwind tables in x86 and RISC-V EFI stubs
tracing: Skip internal ftrace frames under CONFIG_UNWINDER_DWARF_CFI
x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook x86/unwind: Add Minimal DWARF CFI kernel unwinder lib/Kconfig.debug: Allow LATENCYTOP and fault-injection filter with
DWARF CFI
arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding
arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN arm64/unwind: Add Minimal DWARF CFI kernel unwinder
riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding
riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF
JIT
riscv/unwind: Add Minimal DWARF CFI kernel unwinder selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test
scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer tools headers: Add linux/kmsan-checks.h copy from the kernel sources tools headers: Add linux/nospec.h copy from the kernel sources tools headers: Add linux/unwind_dwarf_cfi.h copy from the kernel
sources
tools include: Add linux/uaccess.h stub for userspace tools tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier tools/unwind: Add multi-arch symbolic instruction lifters for
verify_cfi
tools/unwind: Add CFG instruction abstract execution oracle to
verify_cfi
tools/unwind: Add x86-64 ORC cross-check oracle to verify_cfi
MAINTAINERS: Add DWARF CFI stack unwinding entry
MAINTAINERS | 16 + arch/Kconfig | 31 + arch/arm64/Kconfig | 7 +- arch/arm64/Kconfig.debug | 32 + arch/arm64/Makefile | 5 + arch/arm64/include/asm/ftrace.h | 18 +- arch/arm64/include/asm/module.h | 16 + arch/arm64/include/asm/module.lds.h | 2 +- arch/arm64/include/asm/perf_event.h | 2 + arch/arm64/include/asm/stacktrace/frame.h | 6 + arch/arm64/include/asm/unwind_user.h | 145 ++ arch/arm64/kernel/Makefile | 6 + arch/arm64/kernel/efi-rt-wrapper.S | 22 + arch/arm64/kernel/entry-ftrace.S | 35 +- arch/arm64/kernel/entry.S | 22 + arch/arm64/kernel/ftrace.c | 12 +- arch/arm64/kernel/module.c | 17 +- arch/arm64/kernel/probes/kprobes.c | 14 +- arch/arm64/kernel/signal.c | 55 + arch/arm64/kernel/stacktrace.c | 477 +++- arch/arm64/kernel/vdso/Makefile | 7 +- arch/arm64/kernel/vmlinux.lds.S | 21 +- arch/arm64/kvm/hyp/nvhe/Makefile | 1 + arch/arm64/lib/kasan_sw_tags.S | 16 + arch/arm64/net/bpf_jit_comp.c | 9 +- arch/arm64/net/bpf_timed_may_goto.S | 19 + arch/riscv/Kconfig | 7 +- arch/riscv/Kconfig.debug | 16 + arch/riscv/Makefile | 15 +- arch/riscv/include/asm/ftrace.h | 1 + arch/riscv/include/asm/module.h | 22 + arch/riscv/include/asm/perf_event.h | 2 + arch/riscv/include/asm/signal32.h | 9 + arch/riscv/include/asm/stacktrace.h | 11 + arch/riscv/include/asm/unwind_user.h | 82 + arch/riscv/kernel/Makefile | 9 + arch/riscv/kernel/compat_signal.c | 45 + arch/riscv/kernel/entry.S | 2 + arch/riscv/kernel/mcount-dyn.S | 6 +- arch/riscv/kernel/mcount.S | 34 +- arch/riscv/kernel/module.c | 9 + arch/riscv/kernel/probes/rethook.c | 13 +- arch/riscv/kernel/probes/rethook_trampoline.S | 30 + arch/riscv/kernel/signal.c | 57 + arch/riscv/kernel/stacktrace.c | 650 +++++- arch/riscv/kernel/vmlinux.lds.S | 13 + arch/riscv/net/bpf_jit_comp64.c | 6 +- arch/riscv/purgatory/Makefile | 3 +- arch/x86/Kconfig | 3 +- arch/x86/Kconfig.debug | 13 + arch/x86/Makefile | 7 + arch/x86/boot/startup/Makefile | 1 + arch/x86/entry/calling.h | 17 + arch/x86/include/asm/dwarf2.h | 6 +- arch/x86/include/asm/frame.h | 42 +- arch/x86/include/asm/module.h | 5 + arch/x86/include/asm/unwind.h | 15 +- arch/x86/include/asm/unwind_user.h | 47 + arch/x86/kernel/Makefile | 4 + arch/x86/kernel/ftrace_64.S | 44 +- arch/x86/kernel/module.c | 11 +- arch/x86/kernel/rethook.c | 92 +- arch/x86/kernel/stacktrace.c | 8 +- arch/x86/kernel/unwind_dwarf.c | 674 ++++++ arch/x86/kernel/vmlinux.lds.S | 16 + arch/x86/net/bpf_jit_comp.c | 12 +- arch/x86/purgatory/Makefile | 1 + drivers/firmware/efi/libstub/Makefile | 7 +- include/asm-generic/vmlinux.lds.h | 5 + include/linux/unwind_dwarf_cfi.h | 181 ++ include/linux/unwind_user.h | 104 + include/linux/unwind_user_types.h | 101 +- kernel/trace/trace.c | 4 +- kernel/trace/trace_events_trigger.c | 2 +- kernel/trace/trace_functions.c | 4 +- kernel/unwind/Makefile | 14 +- kernel/unwind/dwarf_cfi.c | 1923 +++++++++++++++++ kernel/unwind/dwarf_cfi_kunit.c | 767 +++++++ kernel/unwind/user.c | 169 +- kernel/unwind/user_cfi.c | 392 ++++ lib/Kconfig.debug | 4 +- rust/Makefile | 4 +- scripts/.gitignore | 1 + scripts/Makefile | 1 + scripts/Makefile.build | 12 +- scripts/Makefile.lib | 13 +- scripts/Makefile.vmlinux_o | 8 +- scripts/eh_frame_min.py | 961 ++++++++ scripts/min_eh_frame.c | 1845 ++++++++++++++++ tools/Makefile | 13 +- tools/include/linux/kernel.h | 1 + tools/include/linux/kmsan-checks.h | 98 + tools/include/linux/nospec.h | 74 + tools/include/linux/uaccess.h | 9 + tools/include/linux/unwind_dwarf_cfi.h | 181 ++ tools/objtool/check.c | 1 + tools/perf/check-headers.sh | 3 + .../testing/selftests/perf_events/.gitignore | 1 + tools/testing/selftests/perf_events/Makefile | 4 +- .../selftests/perf_events/unwind_user_cfi.c | 482 +++++ tools/unwind/.gitignore | 4 + tools/unwind/Makefile | 126 ++ tools/unwind/dwarf_cfi_host.c | 80 + tools/unwind/dwarf_cfi_host.h | 42 + tools/unwind/verify_cfi.cpp | 789 +++++++ tools/unwind/verify_cfi.hpp | 147 ++ tools/unwind/verify_insn.cpp | 360 +++ tools/unwind/verify_insn.hpp | 103 + tools/unwind/verify_insn_arch.cpp | 757 +++++++ tools/unwind/verify_orc.cpp | 205 ++ 110 files changed, 12930 insertions(+), 145 deletions(-) create mode 100644 arch/arm64/include/asm/unwind_user.h create mode 100644 arch/riscv/include/asm/unwind_user.h create mode 100644 arch/x86/kernel/unwind_dwarf.c create mode 100644 include/linux/unwind_dwarf_cfi.h create mode 100644 kernel/unwind/dwarf_cfi.c create mode 100644 kernel/unwind/dwarf_cfi_kunit.c create mode 100644 kernel/unwind/user_cfi.c create mode 100755 scripts/eh_frame_min.py create mode 100644 scripts/min_eh_frame.c create mode 100644 tools/include/linux/kmsan-checks.h create mode 100644 tools/include/linux/nospec.h create mode 100644 tools/include/linux/uaccess.h create mode 100644 tools/include/linux/unwind_dwarf_cfi.h create mode 100644 tools/testing/selftests/perf_events/unwind_user_cfi.c create mode 100644 tools/unwind/.gitignore create mode 100644 tools/unwind/Makefile create mode 100644 tools/unwind/dwarf_cfi_host.c create mode 100644 tools/unwind/dwarf_cfi_host.h create mode 100644 tools/unwind/verify_cfi.cpp create mode 100644 tools/unwind/verify_cfi.hpp create mode 100644 tools/unwind/verify_insn.cpp create mode 100644 tools/unwind/verify_insn.hpp create mode 100644 tools/unwind/verify_insn_arch.cpp create mode 100644 tools/unwind/verify_orc.cpp
base-commit: 4843f6873f7c4835e62f2c73ba0fd538e57a2f22
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 1/30 unwind: Add Minimal DWARF CFI bytecode interpreter
Add a strictly bounded DWARF Call Frame Information (.eh_frame / .eh_frame_hdr) interpreter (CONFIG_UNWIND_DWARF_CFI) matching SFrame's stack-unwinding state model and security properties, without requiring new toolchain sections or duplicating user-space unwind metadata.
Instead of implementing a general DWARF expression virtual machine or tracking arbitrary architectural register arrays, struct dwarf_cfi_row tracks only:
- CFA = (SP | FP | prologue scratch reg) + cfa_off, or fixed-pattern indirect CFA *(FP + off) (DRAP stack realignment) / *(SP + off) (signal trampolines)
- Stack pointer save rule (SAME or *(CFA + off)) for signal frames that save SP in sigcontext (such as 32-bit x86 vdso32 __kernel_rt_sigreturn)
- Frame pointer save rule (SAME, *(CFA + off), *(FP + off), *(SP + off))
- Return address save rule (SAME in link register, *(CFA + off), *(SP + off), or UNDEFINED for bottom-of-stack termination), plus AArch64 PAC-RET signing state (DW_CFA_AARCH64_negate_ra_state)
Callee-saved general-purpose register spill/restore opcodes are decoded and ignored in O(1) space. General DW_OP_* expressions, DW_CFA_set_loc backward PC jumps, and DW_CFA_register rules on {SP, FP, RA} are rejected with -EINVAL; DW_EH_PE_indirect encodings are rejected whenever an encoded address is evaluated (while unused 'P'/'L' CIE augmentation fields are skipped by encoded width without dereferencing). CIEs (<= 128 B), FDEs (<= 4096 B), LEB128 operands (<= 5 B), and DW_CFA_remember_state nesting (<= 4 entries) execute in a single forward pass with zero dynamic memory allocations, zero locks, KMSAN output unpoisoning, noinstr kernel-memory entry points, and Spectre v1 / v1.1 nospec hardening (array_index_nospec() and barrier_nospec()).
Also provide shared RCU-safe loadable-module .eh_frame indexing helpers using kvmalloc()/kvfree_rcu_mightsleep() (dwarf_cfi_mod_alloc(), dwarf_cfi_mod_free_rcu(), dwarf_cfi_mod_eval()).
--- arch/Kconfig | 6 + arch/arm64/Kconfig | 3 - include/linux/unwind_dwarf_cfi.h | 181 +++ kernel/unwind/Makefile | 12 +- kernel/unwind/dwarf_cfi.c | 1923 ++++++++++++++++++++++++++++++ 5 files changed, 2121 insertions(+), 4 deletions(-) create mode 100644 include/linux/unwind_dwarf_cfi.h create mode 100644 kernel/unwind/dwarf_cfi.c
arch/Kconfig +6 -0
@@ -500,6 +500,12 @@ config HAVE_HARDLOCKUP_DETECTOR_ARCH It uses the same command line parameters, and sysctl interface, as the generic hardlockup detectors. +config UNWIND_TABLES + bool + +config UNWIND_DWARF_CFI + bool + config UNWIND_USER bool
arch/arm64/Kconfig +0 -3
@@ -413,9 +413,6 @@ config KASAN_SHADOW_OFFSET default 0xeffffff800000000 if ARM64_VA_BITS_36 && KASAN_SW_TAGS default 0xffffffffffffffff -config UNWIND_TABLES - bool - source "arch/arm64/Kconfig.platforms" menu "Kernel Features"
include/linux/unwind_dwarf_cfi.h new file +181 -0
181 lines not on this page · raw message
kernel/unwind/Makefile +11 -1
@@ -1 +1,11 @@ - obj-$(CONFIG_UNWIND_USER) += user.o deferred.o +ifdef CONFIG_FUNCTION_TRACER +CFLAGS_REMOVE_dwarf_cfi.o = $(CC_FLAGS_FTRACE) +endif +KASAN_SANITIZE_dwarf_cfi.o := n +KCSAN_SANITIZE_dwarf_cfi.o := n +UBSAN_SANITIZE_dwarf_cfi.o := n +KMSAN_SANITIZE_dwarf_cfi.o := n +KCOV_INSTRUMENT_dwarf_cfi.o := n + +obj-$(CONFIG_UNWIND_DWARF_CFI) += dwarf_cfi.o +obj-$(CONFIG_UNWIND_USER) += user.o deferred.o
kernel/unwind/dwarf_cfi.c new file +1923 -0
1,923 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 01/30] unwind: Add Minimal DWARF CFI bytecode interpreter
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] unwind: dwarf_cfi: noinstr violations via kmsan_unpoison_memory() and likely() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] unwind: dwarf_cfi: noinstr violations via kmsan_unpoison_memory() and likely()
--
commit a47eb90bddad018f7c1af29e002c5e94dbaf8bab
Author: Ian Rogers <[email protected]>
unwind: Add Minimal DWARF CFI bytecode interpreter
This commit adds a bounded DWARF Call Frame Information (.eh_frame and .eh_frame_hdr) bytecode interpreter for kernel, module, and user-space stack unwinding.
Quoted 22 lines
kernel/unwind/Makefile +11
-1@@ -1 +1,11 @@ - obj-$(CONFIG_UNWIND_USER) += user.o deferred.o +ifdef CONFIG_FUNCTION_TRACER +CFLAGS_REMOVE_dwarf_cfi.o = $(CC_FLAGS_FTRACE) +endif +KASAN_SANITIZE_dwarf_cfi.o := n +KCSAN_SANITIZE_dwarf_cfi.o := n +UBSAN_SANITIZE_dwarf_cfi.o := n +KMSAN_SANITIZE_dwarf_cfi.o := n +KCOV_INSTRUMENT_dwarf_cfi.o := n + +obj-$(CONFIG_UNWIND_DWARF_CFI) += dwarf_cfi.o +obj-$(CONFIG_UNWIND_USER) += user.o deferred.okernel/unwind/dwarf_cfi.c new file +0
-0
[ ... ]
Quoted 8 lines
kernel/unwind/dwarf_cfi.c new file +8
-0+static __always_inline int +dwarf_cfi_eval_fde_streams (struct dwarf_cfi_stream *cie_s, +struct dwarf_cfi_stream *fde_s, +unsigned long pc, +const struct dwarf_cfi_arch *arch, +struct dwarf_cfi_row *out_row, +bool is_user) +{
[ ... ]
Quoted 4 lines
kernel/unwind/dwarf_cfi.c new file +4
-0+ *out_row = row; +kmsan_unpoison_memory (out_row,sizeof (*out_row)); +return 0 ; +}
[ ... ]
Quoted 5 lines
kernel/unwind/dwarf_cfi.c new file +5
-0+noinstr int dwarf_cfi_eval_fde_kmem(const u8 *fde, const u8 *eh_start, +const u8 *eh_end,unsigned long pc, +const struct dwarf_cfi_arch *arch, +struct dwarf_cfi_row *out_row) +{
[ ... ]
kernel/unwind/dwarf_cfi.c line 1418
Quoted 3 lines
kernel/unwind/dwarf_cfi.c new file +3
-0+return dwarf_cfi_eval_fde_streams (&cie_s, &fde_s, pc, arch, out_row, +/*is_user=*/ false); +}
[Severity: Medium]
Can the noinstr functions in dwarf_cfi.c call into instrumented .text when CONFIG_KMSAN or CONFIG_TRACE_BRANCH_PROFILING is enabled?
dwarf_cfi_eval_fde_kmem() is marked noinstr and inlines dwarf_cfi_eval_fde_streams(), which calls kmsan_unpoison_memory(). Because kmsan_unpoison_memory() in include/linux/kmsan-checks.h is gated on CONFIG_KMSAN rather than __SANITIZE_MEMORY__, KMSAN_SANITIZE_dwarf_cfi.o := n does not stub it out, leaving a direct call from .noinstr.text to .text.
In addition, neither kernel/unwind/Makefile nor dwarf_cfi.c defines DISABLE_BRANCH_PROFILING, so under CONFIG_TRACE_BRANCH_PROFILING=y every likely() and unlikely() in the noinstr functions and their inlined helpers expands to a call to ftrace_likely_update() in .text, triggering objtool noinstr warnings and running instrumented code in noinstr contexts.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [RFC PATCH v2 01/30] unwind: Add Minimal DWARF CFI bytecode interpreter
In reply to Ian RogersTL;DR: Nits only: duplicated DWARF CFI parsing, register-check and CIE-lookup code could share helpers, and the UNWIND_TABLES Kconfig move may belong in a later patch or be explained. No bugs found.
Quoted 1 line
unwind: Add Minimal DWARF CFI bytecode interpreter
TL;DR: Nits only: duplicated DWARF CFI parsing, register-check and CIE-lookup code could share helpers, and the UNWIND_TABLES Kconfig move may belong in a later patch or be explained. No bugs found.
Quoted 5 lines
arch/Kconfig +0
-0@@ -500,6 +500,12 @@ config HAVE_HARDLOCKUP_DETECTOR_ARCH It uses the same command line parameters, and sysctl interface,
arch/Kconfig config HAVE_HARDLOCKUP_DETECTOR_ARCH · line 510
Quoted 10 lines
arch/Kconfig +6
-0as the generic hardlockup detectors. +config UNWIND_TABLES + bool + +config UNWIND_DWARF_CFI + bool + config UNWIND_USER bool
This isn't a bug, but could the move of UNWIND_TABLES into arch/Kconfig go in the patch that first selects it from another architecture, or could the changelog say why it is needed here?
[ ... ]
Quoted 3 lines
kernel/unwind/dwarf_cfi.c new file +0
-0
[ ... ]
Quoted 35 lines
kernel/unwind/dwarf_cfi.c new file +35
-0+static __always_inline int +cfi_parse_indirect_cfa_expr (struct dwarf_cfi_stream *s,u32 expr_len, +const struct dwarf_cfi_arch *arch, +struct dwarf_cfi_row *row,bool is_user) +{ +struct dwarf_cfi_stream es; +u8 expr_buf[8 ], op0, op_end; +enum dwarf_cfi_base base; +s32 off; +int err; + +if (expr_len <3 || expr_len >7 ) +return -EINVAL ; +/* Prevent Spectre v1.1 speculative stack overflow of expr_buf[8] */ +barrier_nospec (); + + err =cfi_read_bytes (s, expr_buf, expr_len, is_user); +if (err) +return err; + +cfi_stream_init_kmem (&es, expr_buf, expr_len -1 ); + err =cfi_read_u8 (&es, &op0,/*is_user=*/ false); +if (err) +return err; + +if (arch->fp_reg <=31 && op0 == (u8)(DW_OP_breg0 + arch->fp_reg)) + base =DWARF_CFI_BASE_FP_INDIRECT ; +else if (arch->sp_reg <=31 && op0 == (u8)(DW_OP_breg0 + arch->sp_reg)) + base =DWARF_CFI_BASE_SP_INDIRECT ; +else +return -EINVAL ; + + err =cfi_read_sleb128_s32 (&es, &off,/*is_user=*/ false); +if (err || !cfi_stream_empty (&es,/*is_user=*/ false)) +return -EINVAL ;
[ ... ]
Quoted 19 lines
kernel/unwind/dwarf_cfi.c new file +19
-0+static __always_inline int +cfi_parse_reg_expr (struct dwarf_cfi_stream *s,u32 reg,u32 expr_len, +const struct dwarf_cfi_arch *arch,u8 ra_reg, +struct dwarf_cfi_row *row,bool is_user) +{ +struct dwarf_cfi_stream es; +u8 expr_buf[8 ], op0; +enum dwarf_cfi_rule rule; +s32 off; +int err; + +if (expr_len <2 || expr_len >6 ) +return -EINVAL ; +/* Prevent Spectre v1.1 speculative stack overflow of expr_buf[8] */ +barrier_nospec (); + + err =cfi_read_bytes (s, expr_buf, expr_len, is_user); +if (err) +return err;
kernel/unwind/dwarf_cfi.c line 651
Quoted 10 lines
kernel/unwind/dwarf_cfi.c new file +10
-0+ +cfi_stream_init_kmem (&es, expr_buf, expr_len); + err =cfi_read_u8 (&es, &op0,/*is_user=*/ false); +if (err) +return err; + +if (arch->fp_reg <=31 && op0 == (u8)(DW_OP_breg0 + arch->fp_reg)) + rule =DWARF_CFI_RULE_FP_OFFSET ; +else if (arch->sp_reg <=31 && op0 == (u8)(DW_OP_breg0 + arch->sp_reg)) + rule =DWARF_CFI_RULE_SP_OFFSET ;
This isn't a bug, but cfi_parse_indirect_cfa_expr() and cfi_parse_reg_expr() share almost the same DW_OP_breg decode sequence, including the barrier_nospec() bounds handling.
Could they use one helper that decodes the breg operand and offset, so each caller only adds its own trailing check?
[ ... ]
Quoted 5 lines
kernel/unwind/dwarf_cfi.c new file +5
-0+if (hi ==0x80 ) { +/* DW_CFA_offset */ + err =cfi_read_uleb128_u32 (s, &uval, is_user); +if (err) +return err;
kernel/unwind/dwarf_cfi.c line 794
Quoted 10 lines
kernel/unwind/dwarf_cfi.c new file +10
-0+if (lo == arch->fp_reg || lo == cie->ra_reg || + lo == arch->sp_reg) { + err =cfi_factored_offset (uval, cie->data_align, &off); +if (err) +return err; +cfi_apply_reg_rule (lo,DWARF_CFI_RULE_OFFSET , + off, arch, cie->ra_reg, row); + } +continue ; + }
This isn't a bug, but could the repeated fp/ra/sp check in dwarf_cfi_exec_insns() become a small inline helper such as cfi_reg_is_tracked(reg, arch, cie->ra_reg)?
The same three-way test appears in the DW_CFA_offset, DW_CFA_offset_extended, DW_CFA_offset_extended_sf, DW_CFA_GNU_negative_offset_extended, DW_CFA_register, DW_CFA_val_offset, DW_CFA_val_offset_sf, DW_CFA_expression and DW_CFA_val_expression cases, so the set of tracked registers would be defined in one place.
[ ... ]
Quoted 11 lines
kernel/unwind/dwarf_cfi.c new file +11
-0+ }else { +while (lo < hi) { +u32 mid = lo + (hi - lo) /2 ; +const u8 *ent = table + (size_t )mid * ent_sz; +unsigned long e_pc = (unsigned long )ent + + (long )(s32 )get_unaligned_le32 (ent); + +if (e_pc <= pc) + lo = mid +1 ; +else + hi = mid;
kernel/unwind/dwarf_cfi.c line 1540
Quoted 10 lines
kernel/unwind/dwarf_cfi.c new file +10
-0+ } +if (!lo) +return -ENOENT ; + { +const u8 *fent = table + (size_t )(lo -1 ) * ent_sz +4 ; + + fde_addr = (unsigned long )fent + + (long )(s32 )get_unaligned_le32 (fent); + } + }
This isn't a bug, but could the kernel lookup in dwarf_cfi_unwind_eh_frame_hdr() use eh_hdr_entry_addr() in one binary-search loop, the way dwarf_cfi_unwind_user_eh_frame_hdr() does, rather than two hand-written loops and the bare block around fent?
[ ... ]
Quoted 4 lines
kernel/unwind/dwarf_cfi.c new file +4
-0+if (cie_delta <4 || + (size_t )((p +4 ) - eh_start) < cie_delta) +return -EINVAL ; + cie = (p +4 ) - cie_delta;
kernel/unwind/dwarf_cfi.c line 1637
Quoted 10 lines
kernel/unwind/dwarf_cfi.c new file +10
-0+if (cie < eh_start || cie >= eh_end || + (size_t )(eh_end - cie) <8 ) +return -EINVAL ; + cie_len =get_unaligned_le32 (cie); +if (cie_len <=4 || cie_len >DWARF_CFI_MAX_CIE_LEN || + (size_t )(eh_end - cie) -4 < (size_t )cie_len || +get_unaligned_le32 (cie +4 ) !=0 ) +return -EINVAL ; + +cfi_stream_init_kmem (&cie_s, cie +8 , cie_len -4 );
This isn't a bug, but could the CIE resolution here in dwarf_cfi_scan_eh_frame_kmem() and the one in dwarf_cfi_eval_fde_kmem() share a small __always_inline helper?
That way the module index scan and the evaluator could not drift apart on which CIEs they accept.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 2/30 unwind: Add KUnit tests for Minimal DWARF CFI interpreter
In reply to Ian RogersAdd a built-in KUnit test suite (CONFIG_UNWIND_DWARF_CFI_KUNIT_TEST) in kernel/unwind/dwarf_cfi_kunit.c exercising the Minimal DWARF CFI interpreter across:
- SP-based and FP-based stack frames and ignored callee-saved GPR spills
- Shrink-wrapped DW_CFA_remember_state / DW_CFA_restore_state stacks
- DRAP stack realignment and 64-bit / 32-bit vdso32 sigreturn frames
- ARM64 PAC-RET (DW_CFA_AARCH64_negate_ra_state) and RISC-V leaf frames
- Malformed bytecode, negative sdata4 range, and overflow rejections
- Linear .eh_frame scanning (dwarf_cfi_scan_eh_frame_kmem()) and live CALLER_ADDR0/1 and kernel stack walks
--- arch/Kconfig | 10 + kernel/unwind/Makefile | 1 + kernel/unwind/dwarf_cfi_kunit.c | 767 ++++++++++++++++++++++++++++++++ 3 files changed, 778 insertions(+) create mode 100644 kernel/unwind/dwarf_cfi_kunit.c
arch/Kconfig +10 -0
@@ -506,6 +506,16 @@ config UNWIND_TABLES config UNWIND_DWARF_CFI bool +config UNWIND_DWARF_CFI_KUNIT_TEST + bool "KUnit tests for Minimal DWARF CFI unwinder" if !KUNIT_ALL_TESTS + depends on KUNIT=y && UNWIND_DWARF_CFI + default KUNIT_ALL_TESTS + help + Builds KUnit tests for the Minimal DWARF Call Frame Information (CFI) + bytecode interpreter and stack unwinder. Covers SP/FP-based frames, + callee-saved GPR opcode skipping, shrink-wrapped state stacks, DRAP + stack realignment, malformed bytecode rejections, and live walks. + config UNWIND_USER bool
kernel/unwind/Makefile +1 -0
@@ -9,3 +9,4 @@ KCOV_INSTRUMENT_dwarf_cfi.o := n obj-$(CONFIG_UNWIND_DWARF_CFI) += dwarf_cfi.o obj-$(CONFIG_UNWIND_USER) += user.o deferred.o +obj-$(CONFIG_UNWIND_DWARF_CFI_KUNIT_TEST) += dwarf_cfi_kunit.o
kernel/unwind/dwarf_cfi_kunit.c new file +767 -0
767 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 02/30] unwind: Add KUnit tests for Minimal DWARF CFI interpreter
TL;DR: Nit only, in the KUnit tests: the same blob-derived arguments are repeated in about 26 dwarf_cfi_eval_fde_kmem() calls; a small eval_blob() helper could make them easier to scan.
Quoted 1 line
unwind: Add KUnit tests for Minimal DWARF CFI interpreter
TL;DR: Nit only, in the KUnit tests: the same blob-derived arguments are repeated in about 26 dwarf_cfi_eval_fde_kmem() calls; a small eval_blob() helper could make them easier to scan.
Quoted 4 lines
kernel/unwind/dwarf_cfi_kunit.c new file +0
-0
[ ... ]
Quoted 2 lines
kernel/unwind/dwarf_cfi_kunit.c new file +2
-0+static void test_cfi_drap_realigned_frame (struct kunit *test) +{
[ ... ]
kernel/unwind/dwarf_cfi_kunit.c line 294
Quoted 7 lines
kernel/unwind/dwarf_cfi_kunit.c new file +7
-0+build_test_eh_blob (&blob,"zR" ,0x04 ,0x2800 ,0x40 , insns,sizeof (insns)); + +/* Transient prologue at 0x2806: DWARF_CFI_BASE_REG (r10) */ +KUNIT_ASSERT_EQ (test,0 , +dwarf_cfi_eval_fde_kmem (blob.buf + blob.fde_off, blob.buf, + blob.buf + blob.total_len,0x2806 , + &test_x86_64_arch, &row));
this isn't a bug, but would a small helper such as eval_blob(&blob, pc, arch, &row) make these tests easier to scan?
The same three blob-derived arguments (blob.buf + blob.fde_off, blob.buf, blob.buf + blob.total_len) are spelled out in every dwarf_cfi_eval_fde_kmem() call, across test_cfi_drap_realigned_frame(), test_cfi_sigreturn_frame() and test_cfi_arm64_pac_and_riscv_leaf(), and about 26 times in the file. Only the PC and the arch descriptor vary between the calls.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 3/30 unwind_user: Support Minimal DWARF CFI user-space unwinding
In reply to Ian RogersExtend the generic user-space unwinder (kernel/unwind/user.c) with UNWIND_USER_TYPE_CFI (CONFIG_HAVE_UNWIND_USER_CFI), resolving ELF PT_GNU_EH_FRAME headers across executable VMAs in kernel/unwind/user_cfi.c.
Key design details:
- Find the executable VMA and its base ELF mapping (vm_pgoff == 0) under mmap_read_lock_killable(), then drop mmap_read_lock() before issuing any faultable copy_from_user() reads.
- Cache VMA -> PT_GNU_EH_FRAME lookups (including negative lookups for anonymous/JIT VMAs so unwind_user_next() falls back per frame to FP) in a 4-slot per-walk cache on struct unwind_user_state.
- Track stack-pointer validity (state->sp_valid and unwind_user_fp_sets_sp()) across mixed CFI -> FP -> CFI walks so architectures whose FP step does not recover exact caller SP reject SP-based rules until an outer FP-based FDE or sigreturn restores SP, and support signal-frame SP recovery from *(CFA + sp_off).
- Provide overridable unwind_user_frame_pointer() (guarded by CONFIG_HAVE_UNWIND_USER_FP), unwind_user_fp_sets_sp(), and unwind_user_sigreturn() hooks alongside unwind_user_link_register() and unwind_user_strip_pac(), and allow up to UNWIND_USER_MAX_SIGNALS signal frames per walk to switch stacks (SA_ONSTACK).
- Support link-register leaf frames, DRAP/sigframe indirect CFA rules, and clean bottom-of-stack termination on DW_CFA_undefined or zero RA.
--- arch/Kconfig | 5 + include/linux/unwind_user.h | 104 ++++++++ include/linux/unwind_user_types.h | 101 +++++++- kernel/unwind/Makefile | 1 + kernel/unwind/user.c | 169 +++++++++++-- kernel/unwind/user_cfi.c | 392 ++++++++++++++++++++++++++++++ 6 files changed, 753 insertions(+), 19 deletions(-) create mode 100644 kernel/unwind/user_cfi.c
arch/Kconfig +5 -0
@@ -523,6 +523,11 @@ config HAVE_UNWIND_USER_FP bool select UNWIND_USER +config HAVE_UNWIND_USER_CFI + bool + select UNWIND_USER + select UNWIND_DWARF_CFI + config HAVE_PERF_REGS bool help
include/linux/unwind_user.h +104 -0
122 lines not on this page · raw message
include/linux/unwind_user_types.h +96 -5
137 lines not on this page · raw message
kernel/unwind/Makefile +1 -0
@@ -9,4 +9,5 @@ KCOV_INSTRUMENT_dwarf_cfi.o := n obj-$(CONFIG_UNWIND_DWARF_CFI) += dwarf_cfi.o obj-$(CONFIG_UNWIND_USER) += user.o deferred.o +obj-$(CONFIG_HAVE_UNWIND_USER_CFI) += user_cfi.o obj-$(CONFIG_UNWIND_DWARF_CFI_KUNIT_TEST) += dwarf_cfi_kunit.o
kernel/unwind/user.c +155 -14
277 lines not on this page · raw message
kernel/unwind/user_cfi.c new file +392 -0
392 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 03/30] unwind_user: Support Minimal DWARF CFI user-space unwinding
TL;DR: - Possible misclassification of executable private /dev/zero mappings as ELF bases in user_cfi.c; likely harmless (extra user read, or CFI from user-written bytes if ELF-like) - Commit…
Quoted 1 line
unwind_user: Support Minimal DWARF CFI user-space unwinding
TL;DR:
- Possible misclassification of executable private /dev/zero mappings as ELF bases in user_cfi.c; likely harmless (extra user read, or CFI from user-written bytes if ELF-like)
- Commit message nit: explain why CFI unwinding is needed
Quoted 10 lines
unwind_user: Support Minimal DWARF CFI user-space unwindingExtend the generic user-space unwinder (
kernel/unwind/user.c) withUNWIND_USER_TYPE_CFI(CONFIG_HAVE_UNWIND_USER_CFI), resolving ELFPT_GNU_EH_FRAMEheaders across executable VMAs inkernel/unwind/user_cfi.c. Key design details:
- Find the executable VMA and its base ELF mapping (vm_pgoff== 0) undermmap_read_lock_killable(), then dropmmap_read_lock()before issuing any faultablecopy_from_user()reads.
[ ... ]
this isn't a bug, but could the changelog say briefly why CFI-based user unwinding is needed, for example what fails with frame pointers alone, before it lists the design details?
Quoted 5 lines
kernel/unwind/user_cfi.c new file +0
-0@@ -0,0 +1,392 @@
[ ... ]
Quoted 6 lines
kernel/unwind/user_cfi.c new file +6
-0+static bool lookup_vma_elf_base_locked (struct mm_struct *mm,unsigned long ip, +unsigned long *vma_start, +unsigned long *vma_end, +unsigned long *elf_base) +{ +struct vm_area_struct *vma =vma_lookup (mm, ip);
[ ... ]
kernel/unwind/user_cfi.c line 177
Quoted 6 lines
kernel/unwind/user_cfi.c new file +6
-0+if (vma_is_anonymous (vma) || !vma->vm_file) { +if (vma->vm_pgoff ==0 ) { +/* Special mappings such as [vdso] */ + *elf_base = vma->vm_start; +return true; + }
A subsystem pattern flags this as potentially concerning: this branch is entered for vma_is_anonymous(vma) || !vma->vm_file, and vm_pgoff == 0 is then taken to mean a special mapping such as [vdso].
For a purely anonymous VMA, vm_pgoff equals vm_start >> PAGE_SHIFT, so that works. A private /dev/zero mapping is also vma_is_anonymous(), but vm_file is set and vm_pgoff holds the file offset passed to mmap(), usually 0.
Can an executable MAP_PRIVATE /dev/zero region at offset 0 be classified as an ELF base here, so that *elf_base = vma->vm_start is returned and find_user_eh_frame_hdr() parses the first bytes of the region as an ELF header instead of negative-caching it?
The guide's safe forms are to test vma_is_anonymous(vma) && !vma->vm_file, or to use vma_start_anon_pgoff() for the anonymous offset.
On the other side, the misclassified region is the task's own memory and is only read through copy_from_user(). JIT code at vm_start would normally fail the ELF magic check, so parse_user_elf64_eh_hdr() or parse_user_elf32_eh_hdr() would return -EINVAL, the slot would stay negative-cached and unwind_user_next() would fall back to FP. The visible effect would be one extra user read per walk, or CFI evaluated from user-written bytes if the region happens to start with an ELF header.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 4/30 x86: unwind_user: Support Minimal DWARF CFI user unwinding
In reply to Ian RogersProvide unwind_user_cfi_arch() in arch/x86/include/asm/unwind_user.h for both 64-bit x86-64 (%rsp=7, %rbp=6, %rip=16) and 32-bit IA-32 compat (%esp=4, %ebp=5, %eip=8) user tasks, and select HAVE_UNWIND_USER_CFI on X86_64.
--- arch/x86/Kconfig | 1 + arch/x86/include/asm/unwind_user.h | 47 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+)
arch/x86/Kconfig +1 -0
@@ -300,6 +300,7 @@ config X86 select HAVE_SYSCALL_TRACEPOINTS select HAVE_UACCESS_VALIDATION if HAVE_OBJTOOL select HAVE_UNSTABLE_SCHED_CLOCK + select HAVE_UNWIND_USER_CFI if X86_64 select HAVE_UNWIND_USER_FP if X86_64 select HAVE_USER_RETURN_NOTIFIER select VDSO_GETRANDOM if X86_64
arch/x86/include/asm/unwind_user.h +47 -0
78 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 04/30] x86: unwind_user: Support Minimal DWARF CFI user unwinding
TL;DR: Nit only: unrelated comment additions in this x86 CFI patch aren't in the changelog; suggests moving them to a separate documentation patch.
Quoted 1 line
x86:
unwind_user: Support Minimal DWARF CFI user unwinding
TL;DR: Nit only: unrelated comment additions in this x86 CFI patch aren't in the changelog; suggests moving them to a separate documentation patch.
Quoted 3 lines
arch/x86/include/asm/unwind_user.h +0
-0
[ ... ]
Quoted 8 lines
+/**
+ *unwind_user_word_size()- Return the user-space word size in bytes on x86
+ * @regs: User-mode register state.
+ *
+ * Return: 8 for 64-bit user mode, 4 for 32-bit IA-32/compat mode, or 0 for
+ * VM86 mode stacks which cannot be unwound.
+ */
static inline intunwind_user_word_size(struct pt_regs *regs)
[ ... ]
Quoted 2 lines
+/* Standard x86 frame record: {
saved_bp,ret_addr} at [bp, bp + 2 * ws). */
#defineARCH_INIT_USER_FP_FRAME(ws)\
[ ... ]
Quoted 2 lines
+/* At function entry before push %rbp: return address is at [sp, sp + ws). */
#defineARCH_INIT_USER_FP_ENTRY_FRAME(ws)\
[ ... ]
Quoted 7 lines
+/**
+ *unwind_user_at_function_start()- Check if @regs is at a function entry point
+ * @regs: User-mode register state.
+ *
+ * Return: true if stopped on an entry uprobe before the frame prologue ran.
+ */
static inline boolunwind_user_at_function_start(struct pt_regs *regs)
This isn't a bug, but the new comments on unwind_user_word_size(), the ARCH_INIT_USER_FP_* macros and unwind_user_at_function_start() don't look related to adding CFI support, and the changelog doesn't mention them.
Would they fit better in a separate documentation patch, so this one only carries the x86 CFI register mapping and the Kconfig select?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 5/30 scripts: Add min_eh_frame build-time .eh_frame minifier
In reply to Ian RogersAdd a standalone C build-time ELF relocatable (.o) .eh_frame minifier (scripts/min_eh_frame.c, built under CONFIG_UNWINDER_DWARF_CFI_MINIFY) supporting x86-64, ARM64, and RISC-V with explicit little-endian ELF field accessors for big-endian cross-build hosts and zero external library dependencies.
scripts/min_eh_frame rewrites .eh_frame (both SHT_PROGBITS and SHT_X86_64_UNWIND) in place to:
- Strip callee-saved GPR spill/restore opcodes (%rbx/%r12-%r15 on x86-64, x19-x28 on ARM64, s1-s11 on RISC-V) and DW_CFA_GNU_args_size while preserving CFA, SP, FP, RA, shrink-wrap state-stack, DRAP, and ARM64 DW_CFA_AARCH64_negate_ra_state (0x2d) transitions.
- Normalize CIEs and coalesce consecutive unrelocated PC-advance instructions while remapping sorted .rela.eh_frame relocations (including RISC-V R_RISCV_SET6/SUB6 and ADD32/SUB32 relaxation pairs).
--- arch/Kconfig | 10 + scripts/.gitignore | 1 + scripts/Makefile | 1 + scripts/min_eh_frame.c | 1845 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 1857 insertions(+) create mode 100644 scripts/min_eh_frame.c
arch/Kconfig +10 -0
@@ -528,6 +528,16 @@ config HAVE_UNWIND_USER_CFI select UNWIND_USER select UNWIND_DWARF_CFI +config UNWINDER_DWARF_CFI_MINIFY + bool "Minify .eh_frame tables at build time" + depends on UNWIND_TABLES && UNWIND_DWARF_CFI && !FRAME_POINTER + default y + help + Strip unneeded callee-saved register opcodes and coalesce PC-advance + bytecodes in .eh_frame sections at build time, reducing kernel unwind + table memory usage while ensuring only Minimal DWARF CFA bytecodes + remain in vmlinux and modules. + config HAVE_PERF_REGS bool help
scripts/.gitignore +1 -0
@@ -5,6 +5,7 @@ /generate_rust_target /insert-sys-cert /kallsyms +/min_eh_frame /module.lds /recordmcount /rustdoc_test_builder
scripts/Makefile +1 -0
@@ -12,6 +12,7 @@ hostprogs-always-$(CONFIG_SYSTEM_EXTRA_CERTIFICATE) += insert-sys-cert hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS) += rustdoc_test_builder hostprogs-always-$(CONFIG_RUST_KERNEL_DOCTESTS) += rustdoc_test_gen hostprogs-always-$(CONFIG_TRACEPOINTS) += tracepoint-update +hostprogs-always-$(CONFIG_UNWINDER_DWARF_CFI_MINIFY) += min_eh_frame kallsyms-objs := kallsyms.o kallsyms-sysmap.o elf-parse.o sorttable-objs := sorttable.o elf-parse.o
scripts/min_eh_frame.c new file +1845 -0
1,845 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 05/30] scripts: Add min_eh_frame build-time .eh_frame minifier
TL;DR: Nits only, none described as bugs, in scripts/min_eh_frame.c: use a named enum instead of bare rule numbers (which differ from the kernel's), and share the duplicated register-rule and…
Quoted 1 line
scripts: Add
min_eh_framebuild-time .eh_frame minifier
TL;DR: Nits only, none described as bugs, in scripts/min_eh_frame.c: use a named enum instead of bare rule numbers (which differ from the kernel's), and share the duplicated register-rule and cleanup code.
Quoted 5 lines
scripts/min_eh_frame.c new file +0
-0
[ ... ]
Quoted 2 lines
scripts/min_eh_frame.c new file +2
-0+static bool rows_equal (const struct min_row *a,const struct min_row *b) +{
[ ... ]
scripts/min_eh_frame.c line 366
Quoted 6 lines
scripts/min_eh_frame.c new file +6
-0+if ((a->fp_rule ==1 || a->fp_rule ==2 || a->fp_rule ==4 ) && + a->fp_off != b->fp_off) +return false; +if ((a->ra_rule ==1 || a->ra_rule ==4 ) && + a->ra_off != b->ra_off) +return false;
This isn't a bug, but would a small local enum for the rule and CFA-kind codes make rows_equal() and the restore paths easier to check?
struct min_row documents fp_rule as 0=same, 1=cfa_off, 2=fp_off, 3=undef, 4=sp_off, and these bare numbers are tested about 38 times in the file.
The kernel interpreter in include/linux/unwind_dwarf_cfi.h numbers the same concepts differently (DWARF_CFI_RULE_SP_OFFSET is 3 and DWARF_CFI_RULE_UNDEFINED is 4), so "fp_rule == 4" means different things on each side. Matching the dwarf_cfi_rule numbering would avoid that.
[ ... ]
scripts/min_eh_frame.c line 713
Quoted 10 lines
scripts/min_eh_frame.c new file +10
-0+if (reg == arch->fp_reg) { + row.fp_rule =1 ; + row.fp_off = off; + }else if (reg == cie->ra_reg) { + row.ra_rule =1 ; + row.ra_off = off; + }else { + row.sp_rule =1 ; + row.sp_off = off; + }
This isn't a bug, but could these fp/ra/sp assignment blocks share a small helper, along the lines of cfi_apply_reg_rule() in kernel/unwind/dwarf_cfi.c?
The same ladder appears in minify_insns() for DW_CFA_offset_extended, DW_CFA_offset_extended_sf, DW_CFA_GNU_negative_offset_extended, DW_CFA_undefined and DW_CFA_same_value, differing only in the rule value and offset. The restore paths (DW_CFA_restore and DW_CFA_restore_extended) repeat a similar three-way copy from cie_base, which cfi_restore_reg() covers on the kernel side.
[ ... ]
Quoted 5 lines
scripts/min_eh_frame.c new file +5
-0+free (anchors.data); +free (cies); +free (sorted_relas); +free (out_eh.data); +free (out_relas);
scripts/min_eh_frame.c line 1801
Quoted 10 lines
scripts/min_eh_frame.c new file +10
-0+return 0 ; + +bail: +/* Leave unusual/hand-crafted .eh_frame untouched rather than failing build */ +free (anchors.data); +free (cies); +free (sorted_relas); +free (out_eh.data); +free (out_relas); +return 0 ;
This isn't a bug, but since the success path and bail: free the same buffers and both return 0, could the success path fall through to a single cleanup label, with a ret variable for the -1 case, as minify_insns() does?
process_elf64() has a third copy of the same five frees in the record-length error path, which returns -1. The FDE branch also repeats "free(rmaps); free(min_fde_insns.data); free(fde_rec.data); goto bail;" three times.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 6/30 kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY object pass
In reply to Ian RogersInvoke scripts/min_eh_frame on standard kernel C, Rust, and post-LTO composite .o objects when CONFIG_UNWINDER_DWARF_CFI_MINIFY is enabled, recording scripts/min_eh_frame as a rebuild dependency in .*.cmd files.
Across full vmlinux builds on x86-64, ARM64, and RISC-V, minification achieves 100.00% FDE coverage and reduces .eh_frame size 18%-28% below SFrame v3 (.sframe).
--- rust/Makefile | 4 +++- scripts/Makefile.build | 12 ++++++++++-- scripts/Makefile.lib | 13 +++++++++++-- scripts/Makefile.vmlinux_o | 8 +++++++- 4 files changed, 31 insertions(+), 6 deletions(-)
rust/Makefile +3 -1
@@ -668,7 +668,8 @@ quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L $(CC_FLAGS_RUST_INLINE_HELPERS) -Wno-override-module -c $(patsubst %.o,%.m.bc,$@) -o $@ \ $(cmd_ld_single)) \ $(if $(rustc_objcopy),;$(OBJCOPY) $(rustc_objcopy) $@) \ - $(cmd_objtool) + $(cmd_objtool) \ + $(cmd_min_eh_frame) rust-analyzer: $(Q)MAKEFLAGS= $(srctree)/scripts/generate_rust_analyzer.py \
@@ -721,6 +722,7 @@ endif define rule_rustc_library $(call cmd_and_fixdep,rustc_library) $(call cmd,gen_objtooldep) + $(call cmd,gen_min_eh_framedep) $(call cmd,gendwarfksyms) endef
scripts/Makefile.build +10 -2
@@ -281,6 +281,10 @@ ifdef CONFIG_OBJTOOL $(obj)/%.o: private objtool-enabled = $(if $(is-standard-object),$(if $(delay-objtool),$(is-single-obj-m),y)) endif +ifdef CONFIG_UNWINDER_DWARF_CFI_MINIFY +$(obj)/%.o: private min-eh-frame-enabled = $(if $(filter-out scripts/mod/empty.o,$@),$(is-standard-object)) +endif + ifneq ($(findstring 1, $(KBUILD_EXTRA_WARN)),) cmd_warn_shared_object = $(if $(word 2, $(modname-multi)),$(warning $(kbuild-file): $*.o is added to multiple modules: $(modname-multi))) endif
@@ -371,11 +375,13 @@ quiet_cmd_rustc_o_rs = $(RUSTC_OR_CLIPPY_QUIET) $(quiet_modtag) $@ $(CC) $(CLANG_FLAGS) $(filter-out $(CC_FLAGS_LTO),$(KBUILD_CFLAGS)) \ $(CC_FLAGS_RUST_INLINE_HELPERS) -Wno-override-module -c $(patsubst %.o,%.m.bc,$@) -o $@ \ $(cmd_ld_single)) \ - $(cmd_objtool) + $(cmd_objtool) \ + $(cmd_min_eh_frame) define rule_rustc_o_rs $(call cmd_and_fixdep,rustc_o_rs) $(call cmd,gen_objtooldep) + $(call cmd,gen_min_eh_framedep) endef $(obj)/%.o: $(obj)/%.rs FORCE
@@ -518,14 +524,16 @@ $(obj)/lib.a: $(lib-y) FORCE $(call if_changed,ar) quiet_cmd_ld_multi_m = LD [M] $@ - cmd_ld_multi_m = $(LD) $(ld_flags) -r -o $@ @$< $(cmd_objtool) + cmd_ld_multi_m = $(LD) $(ld_flags) -r -o $@ @$< $(cmd_objtool) $(cmd_min_eh_frame) define rule_ld_multi_m $(call cmd_and_savecmd,ld_multi_m) $(call cmd,gen_objtooldep) + $(call cmd,gen_min_eh_framedep) endef $(multi-obj-m): private objtool-enabled := $(delay-objtool) +$(multi-obj-m): private min-eh-frame-enabled := $(CONFIG_LTO_CLANG) $(multi-obj-m): private part-of-module := y $(multi-obj-m): %.o: %.mod FORCE $(call if_changed_rule,ld_multi_m)
scripts/Makefile.lib +11 -2
@@ -222,6 +222,12 @@ objtool-enabled := y endif # CONFIG_OBJTOOL +ifdef CONFIG_UNWINDER_DWARF_CFI_MINIFY +min_eh_frame := $(objtree)/scripts/min_eh_frame +cmd_min_eh_frame = $(if $(min-eh-frame-enabled), ; $(min_eh_frame) $@) +cmd_gen_min_eh_framedep = $(if $(min-eh-frame-enabled), { echo ; echo '$@: $$(wildcard $(min_eh_frame))' ; } >> $(dot-target).cmd) +endif + # Useful for describing the dependency of composite objects # Usage: # $(call multi_depend, multi_used_targets, suffix_to_remove, suffix_to_add)
@@ -265,7 +271,8 @@ endif quiet_cmd_cc_o_c = CC $(quiet_modtag) $@ cmd_cc_o_c = $(CC) $(c_flags) -c -o $@ $< \ $(cmd_ld_single) \ - $(cmd_objtool) + $(cmd_objtool) \ + $(cmd_min_eh_frame) define rule_cc_o_c $(call cmd_and_fixdep,cc_o_c)
@@ -273,17 +280,19 @@ define rule_cc_o_c $(call cmd,checksrc) $(call cmd,checkdoc) $(call cmd,gen_objtooldep) + $(call cmd,gen_min_eh_framedep) $(call cmd,gen_symversions_c) $(call cmd,record_mcount) $(call cmd,warn_shared_object) endef quiet_cmd_as_o_S = AS $(quiet_modtag) $@ - cmd_as_o_S = $(CC) $(a_flags) -c -o $@ $< $(cmd_objtool) + cmd_as_o_S = $(CC) $(a_flags) -c -o $@ $< $(cmd_objtool) $(cmd_min_eh_frame) define rule_as_o_S $(call cmd_and_fixdep,as_o_S) $(call cmd,gen_objtooldep) + $(call cmd,gen_min_eh_framedep) $(call cmd,gen_symversions_S) $(call cmd,warn_shared_object) endef
scripts/Makefile.vmlinux_o +7 -1
@@ -52,6 +52,10 @@ vmlinux-objtool-args-$(if $(KLP_SYMIDS),y) += --klp-symids objtool-args = $(vmlinux-objtool-args-y) --link +ifdef CONFIG_UNWINDER_DWARF_CFI_MINIFY +min-eh-frame-enabled := $(CONFIG_LTO_CLANG) +endif + # Link of vmlinux.o used for section mismatch analysis # ---------------------------------------------------------------------------
@@ -64,13 +68,15 @@ quiet_cmd_ld_vmlinux.o = LD $@ $(addprefix -T , $(initcalls-lds)) \ --whole-archive vmlinux.a --no-whole-archive \ --start-group $(KBUILD_VMLINUX_LIBS) --end-group \ - $(cmd_objtool) + $(cmd_objtool) \ + $(cmd_min_eh_frame) cmd_check_function_names = $(srctree)/scripts/check-function-names.sh $@ define rule_ld_vmlinux.o $(call cmd_and_savecmd,ld_vmlinux.o) $(call cmd,gen_objtooldep) + $(call cmd,gen_min_eh_framedep) $(call cmd,check_function_names) endef
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 06/30] kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY object pass
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] kbuild: redundant per-object min_eh_frame execution under CONFIG_LTO_CLANG --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] kbuild: redundant per-object min_eh_frame execution under CONFIG_LTO_CLANG
--
commit 101a56a36516bdc9a2795fbb054e65478eaa7f49
Author: Ian Rogers <[email protected]>
kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY object pass
This commit invokes scripts/min_eh_frame on standard kernel objects and post-LTO composite objects when CONFIG_UNWINDER_DWARF_CFI_MINIFY is enabled, and records scripts/min_eh_frame as a rebuild dependency in .*.cmd files.
scripts/Makefile.build ifdef CONFIG_OBJTOOL · line 287
Quoted 12 lines
scripts/Makefile.build +4
-0@@ -281,6 +281,10 @@ ifdef CONFIG_OBJTOOL $(obj)/%.o: private objtool-enabled = $(if $(is-standard-object),$(if $(delay-objtool),$(is-single-obj-m),y)) endif +ifdef CONFIG_UNWINDER_DWARF_CFI_MINIFY +$(obj)/%.o: private min-eh-frame-enabled = $(if $(filter-out scripts/mod/empty.o,$@),$(is-standard-object)) +endif +
[Severity: Low]
Should min-eh-frame-enabled on $(obj)/%.o restrict per-object runs under CONFIG_LTO_CLANG to $(is-single-obj-m), similar to objtool-enabled above?
With CONFIG_LTO_CLANG=y, composite targets (vmlinux.o and $(multi-obj-m)) already run scripts/min_eh_frame after linking. Enabling it unconditionally for all $(is-standard-object) targets spawns scripts/min_eh_frame on every per-TU LLVM bitcode .o file (where cmd_ld_single did not convert it to ELF) and processes non-bitcode ELF .o files such as assembly and Rust objects twice.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Ian Rogers
reviewerRFC PATCH v2 7/30 objtool/ibt: Ignore .eh_frame relocations during ENDBR validation
In reply to Ian RogersWhen vmlinux.o is built with -fasynchronous-unwind-tables and CONFIG_X86_KERNEL_IBT=y, .eh_frame FDE headers contain PC-relative relocations referencing function start addresses across .text. Because .eh_frame is read-only unwind metadata rather than executable code or indirect branch targets, skip .eh_frame* sections during objtool's IBT relocation validation alongside .orc_unwind_ip and DWARF .debug_* sections.
--- tools/objtool/check.c | 1 + 1 file changed, 1 insertion(+)
tools/objtool/check.c +1 -0
@@ -4644,6 +4644,7 @@ static int validate_ibt(struct objtool_file *file) if ((!strncmp(sec->name, ".discard", 8) && strcmp(sec->name, ".discard.ibt_endbr_noseal")) || !strncmp(sec->name, ".debug", 6) || + !strncmp(sec->name, ".eh_frame", 9) || !strcmp(sec->name, ".altinstructions") || !strcmp(sec->name, ".ibt_endbr_seal") || !strcmp(sec->name, ".kcfi_traps") ||
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 8/30 vmlinux.lds.h: Allow architectures to emit custom RO_DATA sections
In reply to Ian RogersAdd an optional ARCH_RODATA_SECTIONS hook inside RO_DATA() so architectures using runtime .eh_frame / .eh_frame_hdr kernel unwinding can place unwind tables inside write-protected RO_DATA without leaving them in unmapped rodata/data gap pages.
--- include/asm-generic/vmlinux.lds.h | 5 +++++ 1 file changed, 5 insertions(+)
include/asm-generic/vmlinux.lds.h +5 -0
@@ -472,6 +472,10 @@#endif #endif +#ifndef ARCH_RODATA_SECTIONS +#define ARCH_RODATA_SECTIONS +#endif +/* * Read only Data */
@@ -554,6 +558,7 @@RO_EXCEPTION_TABLE \ NOTES \BTF \ +ARCH_RODATA_SECTIONS \ \ . = ALIGN((align)); \ __end_rodata = .;
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 9/30 efi/libstub: Disable unwind tables in x86 and RISC-V EFI stubs
In reply to Ian RogersPass -fno-unwind-tables and -fno-asynchronous-unwind-tables when building x86 and RISC-V EFI libstub objects so enabling kernel-wide asynchronous unwind tables under CONFIG_UNWINDER_DWARF_CFI does not emit unwanted .eh_frame sections into the standalone EFI boot stub.
--- drivers/firmware/efi/libstub/Makefile | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/firmware/efi/libstub/Makefile +5 -2
@@ -19,7 +19,8 @@ cflags-$(CONFIG_X86) := $(filter-out -mcmodel=kernel \ $(PADDING_CFLAGS), $(cflags-y)) cflags-$(CONFIG_X86_32) += -march=i386 cflags-$(CONFIG_X86_64) += -mcmodel=small -cflags-$(CONFIG_X86) += -fPIC +cflags-$(CONFIG_X86) += -fPIC -fno-unwind-tables \ + -fno-asynchronous-unwind-tables # Nothing enables IBT while the stub runs, so ENDBR would only take space. cflags-$(CONFIG_X86) += $(call cc-option,-fcf-protection=none)
@@ -29,7 +30,9 @@ cflags-$(CONFIG_ARM) += -DEFI_HAVE_STRLEN -DEFI_HAVE_STRNLEN \ -DEFI_HAVE_MEMCHR -DEFI_HAVE_STRRCHR \ -DEFI_HAVE_STRCMP -fno-builtin -fpic \ $(call cc-option,-mno-single-pic-base) -cflags-$(CONFIG_RISCV) += -fpic -DNO_ALTERNATIVE -mno-relax +cflags-$(CONFIG_RISCV) += -fpic -DNO_ALTERNATIVE -mno-relax \ + -fno-unwind-tables \ + -fno-asynchronous-unwind-tables cflags-$(CONFIG_LOONGARCH) += -fpie cflags-$(CONFIG_EFI_PARAMS_FROM_FDT) += -I$(srctree)/scripts/dtc/libfdt
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 10/30 tracing: Skip internal ftrace frames under CONFIG_UNWINDER_DWARF_CFI
In reply to Ian RogersCalibrate ftrace internal stack-trace skip counts under CONFIG_UNWINDER_DWARF_CFI alongside CONFIG_UNWINDER_ORC so stack traces captured from tracepoints and function tracers omit internal ftrace wrapper frames consistently.
--- kernel/trace/trace.c | 4 ++-- kernel/trace/trace_events_trigger.c | 2 +- kernel/trace/trace_functions.c | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-)
kernel/trace/trace.c +2 -2
@@ -2156,7 +2156,7 @@ void __ftrace_trace_stack(struct trace_array *tr,* Add one, for this function and the call to save_stack_trace() * If regs is set, then these functions will not be in the way. */ -#ifndef CONFIG_UNWINDER_ORC +#if !defined(CONFIG_UNWINDER_ORC ) && !defined(CONFIG_UNWINDER_DWARF_CFI )if (!regs) skip++;#endif
@@ -2258,7 +2258,7 @@ void trace_dump_stack(int skip)if (tracing_disabled || tracing_selftest_running)return ; -#ifndef CONFIG_UNWINDER_ORC +#if !defined(CONFIG_UNWINDER_ORC ) && !defined(CONFIG_UNWINDER_DWARF_CFI )/* Skip 1 to skip this function. */ skip++;#endif
kernel/trace/trace_events_trigger.c +1 -1
@@ -1597,7 +1597,7 @@ static __init int register_trigger_snapshot_cmd(void) { return 0; }#endif /* CONFIG_TRACER_SNAPSHOT */ #ifdef CONFIG_STACKTRACE -#ifdef CONFIG_UNWINDER_ORC +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI )/* Skip 2: * event_triggers_post_call() * trace_event_raw_event_xxx()
kernel/trace/trace_functions.c +2 -2
@@ -251,7 +251,7 @@ function_args_trace_call(unsigned long ip, unsigned long parent_ip,ftrace_test_recursion_unlock (bit); } -#ifdef CONFIG_UNWINDER_ORC +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI )/* * Skip 2: *
@@ -602,7 +602,7 @@ ftrace_traceoff(unsigned long ip, unsigned long parent_ip,tracer_tracing_off (tr); } -#ifdef CONFIG_UNWINDER_ORC +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI )/* * Skip 3: *
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 11/30 x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook
In reply to Ian RogersPrepare x86-64 hand-written and inline assembly paths for runtime Minimal DWARF CFI kernel unwinding when CONFIG_UNWINDER_DWARF_CFI is enabled:
- Emit .eh_frame alongside .debug_frame in asm/dwarf2.h and preserve FRAME_BEGIN/FRAME_END frame setup for non-leaf assembly helpers in asm/frame.h.
- Annotate THUNK (arch/x86/entry/calling.h), ftrace_caller / ftrace_regs_caller / return_to_handler (arch/x86/kernel/ftrace_64.S), and arch_rethook_trampoline() (arch/x86/kernel/rethook.c) with .cfi_* directives.
--- arch/x86/entry/calling.h | 17 +++++++ arch/x86/include/asm/dwarf2.h | 6 +-- arch/x86/include/asm/frame.h | 42 ++++++++++------ arch/x86/kernel/ftrace_64.S | 44 ++++++++++++++++- arch/x86/kernel/rethook.c | 92 ++++++++++++++++++++++++++++++++++- 5 files changed, 180 insertions(+), 21 deletions(-)
arch/x86/entry/calling.h +17 -0
@@ -432,9 +432,19 @@ For 32-bit we have the following conventions - kernel is built with/* rdi: arg1 ... normal C conventions. rax is saved/restored. */ .macro THUNK name, func SYM_FUNC_START(\name) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc +#endif ANNOTATE_NOENDBR pushq %rbp +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 16 + .cfi_offset rbp, -16 +#endif movq %rsp, %rbp +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_register rbp +#endif pushq %rdi pushq %rsi
@@ -458,7 +468,14 @@ SYM_FUNC_START(\name) popq %rsi popq %rdi popq %rbp +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa rsp, 8 + .cfi_restore rbp +#endif RET +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_FUNC_END(\name) _ASM_NOKPROBE(\name) .endm
arch/x86/include/asm/dwarf2.h +3 -3
@@ -22,7 +22,7 @@#define CFI_ESCAPE .cfi_escape#define CFI_SIGNAL_FRAME .cfi_signal_frame -#ifndef BUILD_VDSO +#if !defined(BUILD_VDSO ) && !defined(CONFIG_UNWINDER_DWARF_CFI )/* * Emit CFI data in .debug_frame sections, not .eh_frame sections. * The latter we currently just discard since we don't do DWARF
@@ -33,8 +33,8 @@ .cfi_sections .debug_frame#else /* -* For the vDSO, emit both runtime unwind information and debug -* symbols for the .dbg file. +* For the vDSO or runtime Minimal DWARF unwinding, emit both +* runtime unwind information and debug symbols. */ .cfi_sections .eh_frame, .debug_frame#endif
arch/x86/include/asm/frame.h +27 -15
71 lines not on this page · raw message
arch/x86/kernel/ftrace_64.S +43 -1
160 lines not on this page · raw message
arch/x86/kernel/rethook.c +90 -2
119 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 11/30] x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook
TL;DR: - Commit message omits that ENCODE_FRAME_POINTER and FRAME_BEGIN/END are newly enabled for DWARF CFI - Nits: duplicated frame.h condition block - Nits: rethook copies kprobes…
Quoted 1 line
x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook
TL;DR:
- Commit message omits that ENCODE_FRAME_POINTER and FRAME_BEGIN/END are newly enabled for DWARF CFI
- Nits: duplicated frame.h condition block
- Nits: rethook copies kprobes SAVE_REGS_STRING, duplicating the pt_regs layout
Quoted 13 lines
x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook
Prepare x86-64 hand-written and inline assembly paths for runtime Minimal DWARF CFI kernel unwinding when
CONFIG_UNWINDER_DWARF_CFIis enabled:
- Emit .eh_frame alongside .debug_frame inasm/dwarf2.hand preserve FRAME_BEGIN/FRAME_END frame setup for non-leaf assembly helpers inasm/frame.h.
- Annotate THUNK (arch/x86/entry/calling.h),ftrace_caller/ftrace_regs_caller/return_to_handler(arch/x86/kernel/ftrace_64.S), andarch_rethook_trampoline()(arch/x86/kernel/rethook.c) with .cfi_* directives.
Quoted 1 line
Signed-off-by Ian Rogers <[email protected]>
This isn't a bug, but the commit message says FRAME_BEGIN/FRAME_END are "preserved". Without CONFIG_FRAME_POINTER they used to expand to nothing, so with CONFIG_UNWINDER_DWARF_CFI they are newly enabled.
The same hunk also enables ENCODE_FRAME_POINTER and encode_frame_pointer() for CONFIG_UNWINDER_DWARF_CFI, so entry_64.S, SAVE_REGS_STRING (kprobes/rethook), ftrace_regs_caller and copy_thread() now load an encoded pt_regs pointer into %rbp in builds without frame pointers. The message doesn't mention this.
Could the changelog say that ENCODE_FRAME_POINTER/encode_frame_pointer() are also enabled, and explain that the DWARF unwinder relies on %rbp frames and encoded pt_regs pointers for asm that has no .eh_frame?
Quoted 4 lines
arch/x86/include/asm/frame.h +0
-0
[ ... ]
Quoted 19 lines
arch/x86/include/asm/frame.h +15
-0@@ -22,6 +22,30 @@ pop %_ASM_BP .endm +#else /* !__ASSEMBLER__ */ + +#define FRAME_BEGIN \ + "push %" _ASM_BP "\n" \ + _ASM_MOV "%" _ASM_SP ", %" _ASM_BP "\n" + +#define FRAME_END "pop %" _ASM_BP "\n" + +#endif /* __ASSEMBLER__ */ + +#define FRAME_OFFSET __ASM_SEL(4, 8) + +#else /* !CONFIG_FRAME_POINTER && !CONFIG_UNWINDER_DWARF_CFI */ + +#define FRAME_BEGIN
arch/x86/include/asm/frame.h line 49
Quoted 10 lines
arch/x86/include/asm/frame.h +9
-0+#define FRAME_END +#define FRAME_OFFSET 0 + +#endif /* CONFIG_FRAME_POINTER || CONFIG_UNWINDER_DWARF_CFI */ + +#if defined(CONFIG_FRAME_POINTER ) || defined(CONFIG_UNWINDER_DWARF_CFI ) + +#ifdef __ASSEMBLER__ +#ifdef CONFIG_X86_64
This isn't a bug, but both blocks here use the identical condition "defined(CONFIG_FRAME_POINTER) || defined(CONFIG_UNWINDER_DWARF_CFI)". Could the original single block be kept, with only its "#ifdef CONFIG_FRAME_POINTER" line changed, so the diff stays small?
Quoted 17 lines
arch/x86/kernel/rethook.c +9
-0@@ -15,6 +15,87 @@ __visible void arch_rethook_trampoline_callback(struct pt_regs *regs);#define ANNOTATE_NOENDBR #endif +#if defined(CONFIG_X86_64 ) && defined(CONFIG_UNWINDER_DWARF_CFI ) +#define RETHOOK_CFI_STARTPROC " .cfi_startproc\n" +#define RETHOOK_CFI_ENDPROC " .cfi_endproc\n" +#define RETHOOK_CFI_ADJUST (off) " .cfi_adjust_cfa_offset " #off "\n" +#define RETHOOK_SAVE_REGS_STRING \ + " subq $24, %rsp\n" \ + RETHOOK_CFI_ADJUST(24) \ + " pushq %rdi\n" \ + RETHOOK_CFI_ADJUST(8) \
[ ... ]
Quoted 3 lines
arch/x86/kernel/rethook.c +3
-0+" pushq %rbp\n" \ + RETHOOK_CFI_ADJUST(8) \ +" .cfi_offset rbp, -144\n" \
[ ... ]
arch/x86/kernel/rethook.c __visible void arch_rethook_trampoline_callback(struct pt_regs *regs); · line 59
Quoted 3 lines
arch/x86/kernel/rethook.c +3
-0+#define RETHOOK_RESTORE_REGS_STRING \ + " popq %r15\n" \ + RETHOOK_CFI_ADJUST(-8) \
[ ... ]
This isn't a bug, but RETHOOK_SAVE_REGS_STRING and RETHOOK_RESTORE_REGS_STRING are an instruction-for-instruction copy of SAVE_REGS_STRING and RESTORE_REGS_STRING in arch/x86/kernel/kprobes/common.h with a CFI line added after each push and pop. The pt_regs save order is now defined in two places, and the hard-coded ".cfi_offset rbp, -144" depends on that layout.
optprobe_template_func() in kprobes/opt.c also uses the shared macros and has no .cfi_startproc, so they can't be annotated unconditionally.
Could kprobes/common.h's SAVE_REGS_STRING/RESTORE_REGS_STRING instead take an optional per-push annotation hook that is empty by default, so the register list stays in one place?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 12/30 x86/unwind: Add Minimal DWARF CFI kernel unwinder
In reply to Ian RogersAdd CONFIG_UNWINDER_DWARF_CFI as a selectable x86-64 kernel stack unwinder in arch/x86/kernel/unwind_dwarf.c, implementing the asm/unwind.h and HAVE_RELIABLE_STACKTRACE interfaces over compiler-generated .eh_frame and linker-generated --eh-frame-hdr tables:
- Build kernel C and Rust objects with asynchronous unwind tables and -fomit-frame-pointer while suppressing unwind tables in boot/startup and purgatory objects.
- Place .eh_frame_hdr and .eh_frame inside RO_DATA via ARCH_RODATA_SECTIONS, index loadable module .eh_frame sections via dwarf_cfi_mod_alloc()/dwarf_cfi_mod_free_rcu(), and enable BPF exception stack walks in arch/x86/net/bpf_jit_comp.c.
- Unwind across task, IRQ, exception, ftrace, fgraph, rethook, BPF, and call_on_stack() frames, while rejecting in-kernel pt_regs exception boundaries in arch_stack_walk_reliable().
--- arch/x86/Kconfig | 2 +- arch/x86/Kconfig.debug | 13 + arch/x86/Makefile | 7 + arch/x86/boot/startup/Makefile | 1 + arch/x86/include/asm/module.h | 5 + arch/x86/include/asm/unwind.h | 15 +- arch/x86/kernel/Makefile | 4 + arch/x86/kernel/module.c | 11 +- arch/x86/kernel/stacktrace.c | 8 +- arch/x86/kernel/unwind_dwarf.c | 674 +++++++++++++++++++++++++++++++++ arch/x86/kernel/vmlinux.lds.S | 16 + arch/x86/net/bpf_jit_comp.c | 12 +- arch/x86/purgatory/Makefile | 1 + 13 files changed, 754 insertions(+), 15 deletions(-) create mode 100644 arch/x86/kernel/unwind_dwarf.c
arch/x86/Kconfig +1 -1
@@ -287,7 +287,7 @@ config X86 select MMU_GATHER_MERGE_VMAS select HAVE_POSIX_CPU_TIMERS_TASK_WORK select HAVE_REGS_AND_STACK_ACCESS_API - select HAVE_RELIABLE_STACKTRACE if UNWINDER_ORC || STACK_VALIDATION + select HAVE_RELIABLE_STACKTRACE if UNWINDER_ORC || UNWINDER_DWARF_CFI || STACK_VALIDATION select HAVE_FUNCTION_ARG_ACCESS_API select HAVE_SETUP_PER_CPU_AREA select HAVE_SOFTIRQ_ON_OWN_STACK
arch/x86/Kconfig.debug +13 -0
@@ -246,6 +246,19 @@ config UNWINDER_ORC Enabling this option will increase the kernel's runtime memory usage by roughly 2-4MB, depending on your kernel config. +config UNWINDER_DWARF_CFI + bool "Minimal DWARF CFI unwinder" + depends on X86_64 + select UNWIND_DWARF_CFI + select UNWIND_TABLES + help + This option enables the Minimal DWARF Call Frame Information (CFI) + unwinder for kernel stack traces. It interprets a strictly bounded + subset of compiler-generated .eh_frame / .eh_frame_hdr tables + matching SFrame's stack state model (PC advances, SP/FP-based CFA + offsets, and FP/RA stack offsets) without requiring frame pointers + in C code or objtool ORC table generation. + config UNWINDER_FRAME_POINTER bool "Frame pointer unwinder" select ARCH_WANT_FRAME_POINTERS
arch/x86/Makefile +7 -0
@@ -208,7 +208,14 @@ endif # Workaround for a gcc prelease that unfortunately was shipped in a suse release KBUILD_CFLAGS += -Wno-sign-compare # +ifdef CONFIG_UNWINDER_DWARF_CFI +KBUILD_CFLAGS += -fasynchronous-unwind-tables +KBUILD_RUSTFLAGS += -Cforce-unwind-tables=y -Zuse-sync-unwind=n +KBUILD_RUSTFLAGS += $(if $(call rustc-min-version,109800),,-Zllvm_module_flag=uwtable:u32:2:max) +LDFLAGS_vmlinux += --eh-frame-hdr +else KBUILD_CFLAGS += -fno-asynchronous-unwind-tables +endif # Avoid indirect branches in kernel to deal with Spectre ifdef CONFIG_MITIGATION_RETPOLINE
arch/x86/boot/startup/Makefile +1 -0
@@ -7,6 +7,7 @@ KBUILD_CFLAGS += -D__DISABLE_EXPORTS -mcmodel=small -fPIC \ $(DISABLE_LATENT_ENTROPY_PLUGIN) \ -fno-stack-protector -D__NO_FORTIFY \ -fno-jump-tables \ + -fno-unwind-tables -fno-asynchronous-unwind-tables \ -include $(srctree)/include/linux/hidden.h # disable ftrace hooks and LTO
arch/x86/include/asm/module.h +5 -0
@@ -12,11 +12,16 @@ struct its_array {#endif }; +struct mod_dwarf_cfi_index ; +struct mod_arch_specific {#ifdef CONFIG_UNWINDER_ORC unsigned int num_orcs;int *orc_unwind_ip;struct orc_entry *orc_unwind; +#endif +#ifdef CONFIG_UNWINDER_DWARF_CFI +struct mod_dwarf_cfi_index __rcu *dwarf_cfi_index;#endif struct its_array its_pages; };
arch/x86/include/asm/unwind.h +11 -4
@@ -20,7 +20,7 @@ struct unwind_state {struct llist_node *kr_cur;#endif bool error; -#if defined(CONFIG_UNWINDER_ORC ) +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI )bool signal, full_regs;unsigned long sp, bp, ip;struct pt_regs *regs, *prev_regs;
@@ -64,7 +64,8 @@ void unwind_start(struct unwind_state *state, struct task_struct *task,__unwind_start (state, task, regs, first_frame); } -#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_FRAME_POINTER ) +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI ) || \ + defined(CONFIG_UNWINDER_FRAME_POINTER )/* * If 'partial' returns true, only the iret frame registers are valid. */
@@ -75,7 +76,7 @@ static inline struct pt_regs *unwind_get_entry_regs(struct unwind_state *state,return NULL ;if (partial) { -#ifdef CONFIG_UNWINDER_ORC +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI ) *partial = !state->full_regs;#else *partial = false;
@@ -92,7 +93,7 @@ static inline struct pt_regs *unwind_get_entry_regs(struct unwind_state *state, }#endif -#ifdef CONFIG_UNWINDER_ORC +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI )void unwind_init (void );void unwind_module_init (struct module *mod,void *orc_ip,size_t orc_ip_size,void *orc,size_t orc_size);
@@ -103,6 +104,12 @@ void unwind_module_init(struct module *mod, void *orc_ip, size_t orc_ip_size, void *orc, size_t orc_size) {}#endif +#ifdef CONFIG_UNWINDER_DWARF_CFI +void unwind_module_cleanup (struct module *mod); +#else +static inline void unwind_module_cleanup (struct module *mod) {} +#endif +static inline unsigned long unwind_recover_rethook (struct unwind_state *state,unsigned long addr,unsigned long *addr_p)
arch/x86/kernel/Makefile +4 -0
@@ -18,6 +18,7 @@ CFLAGS_REMOVE_early_printk.o = -pg CFLAGS_REMOVE_head64.o = -pg CFLAGS_REMOVE_head32.o = -pg CFLAGS_REMOVE_rethook.o = -pg +CFLAGS_REMOVE_unwind_dwarf.o = -pg endif KASAN_SANITIZE_head$(BITS).o := n
@@ -25,6 +26,7 @@ KASAN_SANITIZE_dumpstack.o := n KASAN_SANITIZE_dumpstack_$(BITS).o := n KASAN_SANITIZE_stacktrace.o := n KASAN_SANITIZE_paravirt.o := n +KASAN_SANITIZE_unwind_dwarf.o := n # With some compiler versions the generated code results in boot hangs, caused # by several compilation units. To be safe, disable all instrumentation.
@@ -41,6 +43,7 @@ KCOV_INSTRUMENT_stacktrace.o := n KCOV_INSTRUMENT_dumpstack.o := n KCOV_INSTRUMENT_dumpstack_$(BITS).o := n KCOV_INSTRUMENT_unwind_orc.o := n +KCOV_INSTRUMENT_unwind_dwarf.o := n KCOV_INSTRUMENT_unwind_frame.o := n KCOV_INSTRUMENT_unwind_guess.o := n
@@ -159,6 +162,7 @@ obj-$(CONFIG_SCHED_MC_PRIO) += itmt.o obj-$(CONFIG_X86_UMIP) += umip.o obj-$(CONFIG_UNWINDER_ORC) += unwind_orc.o +obj-$(CONFIG_UNWINDER_DWARF_CFI) += unwind_dwarf.o obj-$(CONFIG_UNWINDER_FRAME_POINTER) += unwind_frame.o obj-$(CONFIG_UNWINDER_GUESS) += unwind_guess.o
arch/x86/kernel/module.c +9 -2
@@ -228,7 +228,7 @@ int module_finalize(const Elf_Ehdr *hdr, struct module *me) {const Elf_Shdr *s, *alt =NULL , - *orc =NULL , *orc_ip =NULL , + *orc =NULL , *orc_ip =NULL , *eh_frame =NULL , *retpolines =NULL , *returns =NULL , *ibt_endbr =NULL , *calls =NULL , *cfi =NULL ;char *secstrings = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
@@ -240,6 +240,8 @@ int module_finalize(const Elf_Ehdr *hdr, orc = s;if (!strcmp (".orc_unwind_ip" , secstrings + s->sh_name)) orc_ip = s; +if (!strcmp (".eh_frame" , secstrings + s->sh_name)) + eh_frame = s;if (!strcmp (".retpoline_sites" , secstrings + s->sh_name)) retpolines = s;if (!strcmp (".return_sites" , secstrings + s->sh_name))
@@ -299,14 +301,19 @@ int module_finalize(const Elf_Ehdr *hdr,apply_seal_endbr (iseg, iseg + ibt_endbr->sh_size); } -if (orc && orc_ip) +if (IS_ENABLED (CONFIG_UNWINDER_ORC ) && orc && orc_ip)unwind_module_init (me, (void *)orc_ip->sh_addr, orc_ip->sh_size, (void *)orc->sh_addr, orc->sh_size); +if (IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ) && eh_frame && + (eh_frame->sh_flags &SHF_ALLOC ) && eh_frame->sh_addr) +unwind_module_init (me,/*orc_ip=*/ NULL ,/*orc_ip_size=*/ 0 , + (void *)eh_frame->sh_addr, eh_frame->sh_size);return 0 ; }void module_arch_cleanup (struct module *mod) { +unwind_module_cleanup (mod);its_free_mod (mod); }
arch/x86/kernel/stacktrace.c +5 -3
@@ -49,10 +49,12 @@ int arch_stack_walk_reliable(stack_trace_consume_fn consume_entry,/* * Kernel mode registers on the stack indicate an * in-kernel interrupt or exception (e.g., preemption -* or a page fault), which can make frame pointers -* unreliable. +* or a page fault), which can make frame pointers or +* compiler-generated DWARF CFI (across unannotated +* inline assembly stack adjustments) unreliable. */ -if (IS_ENABLED (CONFIG_FRAME_POINTER )) +if (IS_ENABLED (CONFIG_FRAME_POINTER ) || +IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ))return -EINVAL ; }
arch/x86/kernel/unwind_dwarf.c new file +674 -0
674 lines not on this page · raw message
arch/x86/kernel/vmlinux.lds.S +16 -0
@@ -21,6 +21,22 @@ #define EMITS_PT_NOTE #define RO_EXCEPTION_TABLE_ALIGN 16 +#ifdef CONFIG_UNWINDER_DWARF_CFI +#define ARCH_RODATA_SECTIONS \ + . = ALIGN(4); \ + .eh_frame_hdr : AT(ADDR(.eh_frame_hdr) - LOAD_OFFSET) { \ + __start_eh_frame_hdr = .; \ + *(.eh_frame_hdr) \ + __stop_eh_frame_hdr = .; \ + } \ + . = ALIGN(8); \ + .eh_frame : AT(ADDR(.eh_frame) - LOAD_OFFSET) { \ + __start_eh_frame = .; \ + *(.eh_frame) *(.eh_frame.*) \ + __stop_eh_frame = .; \ + } +#endif + #include <asm-generic/vmlinux.lds.h> #include <asm/asm-offsets.h> #include <asm/thread_info.h>
arch/x86/net/bpf_jit_comp.c +7 -5
@@ -5122,11 +5122,13 @@ void bpf_jit_free(struct bpf_prog *prog)bool bpf_jit_supports_exceptions (void ) { -/* We unwind through both kernel frames (starting from within bpf_throw -* call) and BPF frames. Therefore we require ORC unwinder to be enabled -* to walk kernel frames and reach BPF frames in the stack trace. +/* +* We unwind through both kernel frames (starting from within bpf_throw +* call) and BPF frames. Therefore we require ORC or Minimal DWARF CFI +* unwinder to be enabled to walk kernel frames and reach BPF frames. */ -return IS_ENABLED (CONFIG_UNWINDER_ORC ); +return IS_ENABLED (CONFIG_UNWINDER_ORC ) || +IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ); }bool bpf_jit_supports_private_stack (void )
@@ -5136,7 +5138,7 @@ bool bpf_jit_supports_private_stack(void)void arch_bpf_stack_walk (bool (*consume_fn)(void *cookie,u64 ip,u64 sp,u64 bp),void *cookie) { -#if defined(CONFIG_UNWINDER_ORC ) +#if defined(CONFIG_UNWINDER_ORC ) || defined(CONFIG_UNWINDER_DWARF_CFI )struct unwind_state state;unsigned long addr;
arch/x86/purgatory/Makefile +1 -0
@@ -35,6 +35,7 @@ PURGATORY_CFLAGS := -mcmodel=small -ffreestanding -fno-zero-initialized-in-bss - PURGATORY_CFLAGS += -fpic -fvisibility=hidden PURGATORY_CFLAGS += $(DISABLE_KSTACK_ERASE) -DDISABLE_BRANCH_PROFILING PURGATORY_CFLAGS += -fno-stack-protector +PURGATORY_CFLAGS += -fno-unwind-tables -fno-asynchronous-unwind-tables PURGATORY_CFLAGS += -D__DISABLE_EXPORTS -D__NO_FORTIFY # Default KBUILD_CFLAGS can have -pg option set when FTRACE is enabled. That
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 12/30] x86/unwind: Add Minimal DWARF CFI kernel unwinder
TL;DR: Nits only in the DWARF CFI unwinder: unwind_module_init() is reused with NULL/0 placeholders, where a dedicated init hook may be cleaner, and the get_scratch_reg() prev_regs fallback looks…
Quoted 1 line
x86/unwind: Add Minimal DWARF CFI kernel unwinder
TL;DR: Nits only in the DWARF CFI unwinder: unwind_module_init() is reused with NULL/0 placeholders, where a dedicated init hook may be cleaner, and the get_scratch_reg() prev_regs fallback looks unreachable.
Quoted 3 lines
arch/x86/kernel/module.c +0
-0
[ ... ]
arch/x86/kernel/module.c int module_finalize(const Elf_Ehdr *hdr, · line 307
Quoted 9 lines
arch/x86/kernel/module.c +5
-1@@ -299,14 +301,19 @@ int module_finalize(const Elf_Ehdr *hdr, -if (orc && orc_ip) +if (IS_ENABLED (CONFIG_UNWINDER_ORC ) && orc && orc_ip)unwind_module_init (me, (void *)orc_ip->sh_addr, orc_ip->sh_size, (void *)orc->sh_addr, orc->sh_size); +if (IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ) && eh_frame && + (eh_frame->sh_flags &SHF_ALLOC ) && eh_frame->sh_addr) +unwind_module_init (me,/*orc_ip=*/ NULL ,/*orc_ip_size=*/ 0 , + (void *)eh_frame->sh_addr, eh_frame->sh_size);
this isn't a bug, but the DWARF path reuses the ORC prototype of unwind_module_init(), so it passes NULL/0 placeholders for orc_ip and orc_ip_size and hands .eh_frame in through the parameters named orc and orc_size.
The two branches are already separate IS_ENABLED() tests, so the shared prototype doesn't save anything at the call site.
Could the DWARF path get its own init hook, for example one taking (mod, eh_frame, eh_frame_size), alongside the new unwind_module_cleanup()?
[ ... ]
Quoted 3 lines
arch/x86/kernel/unwind_dwarf.c new file +0
-0
[ ... ]
arch/x86/kernel/unwind_dwarf.c line 326
Quoted 4 lines
arch/x86/kernel/unwind_dwarf.c new file +4
-0+static bool get_scratch_reg (struct unwind_state *state,u8 dwarf_reg, +unsigned long *val) +{ +struct pt_regs *regs = state->full_regs ? state->regs : state->prev_regs;
this isn't a bug, but is the state->prev_regs fallback in get_scratch_reg() reachable?
Nothing in unwind_dwarf.c sets prev_regs to anything other than NULL (__unwind_start() memsets the state, and unwind_next_frame() only stores NULL into it), and full_regs is only set where state->regs is also set.
Could this use state->full_regs ? state->regs : NULL and drop the prev_regs = NULL stores in unwind_next_frame()? The kernel-doc also says the register is recovered "from full pt_regs", which doesn't match the prev_regs fallback.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 13/30 lib/Kconfig.debug: Allow LATENCYTOP and fault-injection filter with DWARF CFI
In reply to Ian RogersAllow CONFIG_LATENCYTOP and CONFIG_FAULT_INJECTION_STACKTRACE_FILTER to be enabled on architectures using CONFIG_UNWINDER_DWARF_CFI with -fomit-frame-pointer (such as arm64 and riscv).
--- lib/Kconfig.debug | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
lib/Kconfig.debug +2 -2
@@ -1893,7 +1893,7 @@ config LATENCYTOP depends on DEBUG_KERNEL depends on STACKTRACE_SUPPORT depends on PROC_FS - depends on FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86 + depends on FRAME_POINTER || UNWINDER_DWARF_CFI || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86 select KALLSYMS select KALLSYMS_ALL select STACKTRACE
@@ -2188,7 +2188,7 @@ config FAULT_INJECTION_STACKTRACE_FILTER depends on FAULT_INJECTION depends on (FAULT_INJECTION_DEBUG_FS || FAULT_INJECTION_CONFIGFS) && STACKTRACE_SUPPORT select STACKTRACE - depends on FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86 + depends on FRAME_POINTER || UNWINDER_DWARF_CFI || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86 help Provide stacktrace filter for fault-injection capabilities
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 14/30 arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding
In reply to Ian RogersWire up CONFIG_HAVE_UNWIND_USER_CFI and CONFIG_HAVE_UNWIND_USER_FP on arm64 by providing arch/arm64/include/asm/unwind_user.h and unwind_user_sigreturn():
- Populate DWARF CFI register mappings for both 64-bit AArch64 (ws=8, sp=31, fp=29, lr=30) and 32-bit AArch32 compat tasks (ws=4, sp=13, fp=11, lr=14).
- Expose the user frame pointer (x29 / compat_fp) and link register (x30 / compat_lr) via unwind_user_frame_pointer() and unwind_user_link_register(), and override unwind_user_fp_sets_sp() to return false because AArch64 frame records live at the bottom of the callee's stack frame rather than at caller_sp - 16.
- Implement unwind_user_sigreturn() in arch/arm64/kernel/signal.c to recover pc, sp, x29, and x30 directly from rt_sigframe.uc.uc_mcontext at __kernel_rt_sigreturn when state->sp_valid is true (falling back to user->next_frame via FP otherwise), preserving interrupted leaf functions and SA_ONSTACK alternate signal stacks.
- Strip user-space pointer authentication codes via ptrauth_strip_user_insn_pac() (and clear Thumb bit 0 for compat user tasks) in unwind_user_strip_pac(), and define ARCH_INIT_USER_FP_FRAME for both 64-bit AArch64 PCS frame records and 32-bit AArch32 compat_frame_tail layouts.
--- arch/arm64/Kconfig | 2 + arch/arm64/include/asm/unwind_user.h | 145 +++++++++++++++++++++++++++ arch/arm64/kernel/signal.c | 55 ++++++++++ 3 files changed, 202 insertions(+) create mode 100644 arch/arm64/include/asm/unwind_user.h
arch/arm64/Kconfig +2 -0
@@ -228,6 +228,8 @@ config ARM64 select HAVE_STACKPROTECTOR select HAVE_STATIC_CALL if CFI select HAVE_SYSCALL_TRACEPOINTS + select HAVE_UNWIND_USER_CFI + select HAVE_UNWIND_USER_FP select HAVE_KPROBES select HAVE_KRETPROBES select HOTPLUG_CORE_SYNC_DEAD if HOTPLUG_CPU
arch/arm64/include/asm/unwind_user.h new file +145 -0
145 lines not on this page · raw message
arch/arm64/kernel/signal.c +55 -0
67 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 15/30 arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN
In reply to Ian RogersAnnotate arm64 hand-written assembly helpers with .cfi_* directives under CONFIG_UNWINDER_DWARF_CFI so runtime .eh_frame unwinding traverses call_on_irq_stack(), __efi_rt_asm_wrapper(), return_to_handler() (and exports ftrace_caller_end), __hwasan_tag_mismatch(), and arch_bpf_timed_may_goto(), and allow bpf_jit_supports_exceptions() when CONFIG_UNWINDER_DWARF_CFI is enabled.
--- arch/arm64/kernel/efi-rt-wrapper.S | 22 ++++++++++++++++++ arch/arm64/kernel/entry-ftrace.S | 35 ++++++++++++++++++++++++++++- arch/arm64/kernel/entry.S | 22 ++++++++++++++++++ arch/arm64/lib/kasan_sw_tags.S | 16 +++++++++++++ arch/arm64/net/bpf_jit_comp.c | 9 ++++---- arch/arm64/net/bpf_timed_may_goto.S | 19 ++++++++++++++++ 6 files changed, 118 insertions(+), 5 deletions(-)
arch/arm64/kernel/efi-rt-wrapper.S +22 -0
@@ -7,8 +7,19 @@ #include <asm/assembler.h> SYM_FUNC_START(__efi_rt_asm_wrapper) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc +#endif stp x29, x30, [sp, #-112]! +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 112 + .cfi_offset 29, -112 + .cfi_offset 30, -104 +#endif mov x29, sp +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_register 29 +#endif /* * Register x18 is designated as the 'platform' register by the AAPCS,
@@ -48,11 +59,19 @@ SYM_FUNC_START(__efi_rt_asm_wrapper) mov x16, sp mov sp, x29 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_register 31 +#endif str xzr, [x16, #8] // clear recorded task SP value ldp x1, x2, [sp, #16] cmp x2, x18 ldp x29, x30, [sp], #112 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 0 + .cfi_restore 29 + .cfi_restore 30 +#endif b.ne 0f ret 0:
@@ -69,6 +88,9 @@ SYM_FUNC_START(__efi_rt_asm_wrapper) #endif b efi_handle_corrupted_x18 // tail call +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_FUNC_END(__efi_rt_asm_wrapper) SYM_CODE_START(__efi_rt_asm_recover)
arch/arm64/kernel/entry-ftrace.S +34 -1
@@ -167,6 +167,7 @@ SYM_INNER_LABEL(ftrace_caller_direct, SYM_L_LOCAL) */ br x17 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */ +SYM_INNER_LABEL(ftrace_caller_end, SYM_L_GLOBAL) SYM_CODE_END(ftrace_caller) #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
@@ -327,10 +328,23 @@ SYM_FUNC_END(ftrace_stub_graph) * * Run ftrace_return_to_handler() before going back to parent. * @fp is checked against the value passed by ftrace_graph_caller(). + * + * Under CONFIG_UNWINDER_DWARF_CFI, FREGS_PC is seeded with &return_to_handler + * before calling ftrace_return_to_handler(), which then overwrites FREGS_PC + * with the restored caller PC prior to invoking return callbacks. Tracking the + * return address at FREGS_PC allows kunwind_next_cfi() to unwind cleanly from + * inside ftrace_return_to_handler(), graph return callbacks, and interrupts. */ SYM_CODE_START(return_to_handler) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc + .cfi_def_cfa sp, 0 +#endif /* Make room for ftrace_regs */ sub sp, sp, #FREGS_SIZE +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset FREGS_SIZE +#endif /* Save return value regs */ stp x0, x1, [sp, #FREGS_X0]
@@ -338,12 +352,24 @@ SYM_CODE_START(return_to_handler) stp x4, x5, [sp, #FREGS_X4] stp x6, x7, [sp, #FREGS_X6] - /* Save the callsite's FP */ + /* Save the callsite's FP and clear unused LR slot in ftrace_regs */ str x29, [sp, #FREGS_FP] + str xzr, [sp, #FREGS_LR] +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_offset x29, FREGS_FP - FREGS_SIZE + adr x9, return_to_handler + add x10, sp, #FREGS_SIZE + str x10, [sp, #FREGS_SP] + str x9, [sp, #FREGS_PC] + .cfi_offset x30, FREGS_PC - FREGS_SIZE +#endif mov x0, sp bl ftrace_return_to_handler // addr = ftrace_return_to_hander(fregs); mov x30, x0 // restore the original return address +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_same_value x30 +#endif /* Restore return value regs */ ldp x0, x1, [sp, #FREGS_X0]
@@ -351,7 +377,14 @@ SYM_CODE_START(return_to_handler) ldp x4, x5, [sp, #FREGS_X4] ldp x6, x7, [sp, #FREGS_X6] add sp, sp, #FREGS_SIZE +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 0 + .cfi_restore x29 +#endif ret +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_CODE_END(return_to_handler) #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
arch/arm64/kernel/entry.S +22 -0
@@ -882,6 +882,9 @@ NOKPROBE(ret_from_fork) * Calls func(regs) using this CPU's irq stack and shadow irq stack. */ SYM_FUNC_START(call_on_irq_stack) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc +#endif save_and_disable_daif x9 #ifdef CONFIG_SHADOW_CALL_STACK get_current_task x16
@@ -891,7 +894,15 @@ SYM_FUNC_START(call_on_irq_stack) /* Create a frame record to save our LR and SP (implicit in FP) */ stp x29, x30, [sp, #-16]! +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 16 + .cfi_offset 29, -16 + .cfi_offset 30, -8 +#endif mov x29, sp +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_register 29 +#endif ldr_this_cpu x16, irq_stack_ptr, x17
@@ -906,10 +917,21 @@ SYM_FUNC_START(call_on_irq_stack) * record. */ mov sp, x29 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_register 31 +#endif ldp x29, x30, [sp], #16 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 0 + .cfi_restore 29 + .cfi_restore 30 +#endif scs_load_current restore_irq x9 ret +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_FUNC_END(call_on_irq_stack) NOKPROBE(call_on_irq_stack)
arch/arm64/lib/kasan_sw_tags.S +16 -0
@@ -38,6 +38,12 @@ * incremented by 256 prior to return). */ SYM_CODE_START(__hwasan_tag_mismatch) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc + .cfi_def_cfa_offset 256 + .cfi_offset x29, -24 + .cfi_offset x30, -16 +#endif bti c add x29, sp, #232 stp x2, x3, [sp, #8 * 2]
@@ -66,9 +72,19 @@ SYM_CODE_START(__hwasan_tag_mismatch) ldr x18, [sp, #8 * 18] #endif ldp x29, x30, [sp, #8 * 29] +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_restore x29 + .cfi_restore x30 +#endif /* remove the structure from the stack */ add sp, sp, #256 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 0 +#endif ret +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_CODE_END(__hwasan_tag_mismatch) EXPORT_SYMBOL(__hwasan_tag_mismatch)
arch/arm64/net/bpf_jit_comp.c +5 -4
@@ -3489,10 +3489,11 @@ bool bpf_jit_supports_ptr_xchg(void)bool bpf_jit_supports_exceptions (void ) { -/* We unwind through both kernel frames starting from within bpf_throw -* call and BPF frames. Therefore we require FP unwinder to be enabled -* to walk kernel frames and reach BPF frames in the stack trace. -* ARM64 kernel is always compiled with CONFIG_FRAME_POINTER=y +/* +* We unwind through both kernel frames starting from within bpf_throw +* call and BPF frames. Both UNWINDER_FRAME_POINTER and +* UNWINDER_DWARF_CFI preserve x29 across kernel frames and walk +* JITed BPF frame records. */ return true; }
arch/arm64/net/bpf_timed_may_goto.S +19 -0
@@ -4,9 +4,20 @@ #include <linux/linkage.h> SYM_FUNC_START(arch_bpf_timed_may_goto) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc +#endif /* Allocate stack space and emit frame record */ stp x29, x30, [sp, #-96]! +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 96 + .cfi_offset 29, -96 + .cfi_offset 30, -88 +#endif mov x29, sp +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_register 29 +#endif /* Save BPF registers R0 - R5 (x8, x0-x4)*/ stp x8, x0, [sp, #16]
@@ -35,6 +46,14 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) /* Restore FP and LR */ ldp x29, x30, [sp], #96 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa 31, 0 + .cfi_restore 29 + .cfi_restore 30 +#endif ret +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_FUNC_END(arch_bpf_timed_may_goto)
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 15/30] arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN
TL;DR: Commit message only: it claims bpf_jit_supports_exceptions() is changed but only a comment is, possibly premature before the unwinder commit; it also omits an unconditional xzr store in…
Quoted 1 line
arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN
TL;DR: Commit message only: it claims bpf_jit_supports_exceptions() is changed but only a comment is, possibly premature before the unwinder commit; it also omits an unconditional xzr store in return_to_handler.
Quoted 10 lines
arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN
Annotate arm64 hand-written assembly helpers with .cfi_* directives under
CONFIG_UNWINDER_DWARF_CFIso runtime .eh_frame unwinding traversescall_on_irq_stack(),__efi_rt_asm_wrapper(),return_to_handler()(and exportsftrace_caller_end),__hwasan_tag_mismatch(), andarch_bpf_timed_may_goto(), and allowbpf_jit_supports_exceptions()whenCONFIG_UNWINDER_DWARF_CFIis enabled.Signed-off-by Ian Rogers <[email protected]>
The commit message says the patch will "allow bpf_jit_supports_exceptions() when CONFIG_UNWINDER_DWARF_CFI is enabled", but the arm64 hunk only rewrites the comment:
Quoted 9 lines
arch/arm64/net/bpf_jit_comp.c +0
-2@@ -3909,10 +3909,11 @@ u64 bpf_arch_uaddress_limit(void)bool bpf_jit_supports_exceptions (void ) { -/* We unwind through both kernel frames starting from within bpf_throw -* call and BPF frames. Therefore we require FP unwinder to be enabled
arch/arm64/net/bpf_jit_comp.c u64 bpf_arch_uaddress_limit(void) · line 3919
Quoted 10 lines
arch/arm64/net/bpf_jit_comp.c +5
-2-* to walk kernel frames and reach BPF frames in the stack trace. -* ARM64 kernel is always compiled with CONFIG_FRAME_POINTER=y +/* +* We unwind through both kernel frames starting from within bpf_throw +* call and BPF frames. Both UNWINDER_FRAME_POINTER and +* UNWINDER_DWARF_CFI preserve x29 across kernel frames and walk +* JITed BPF frame records. */ return true; }
bpf_jit_supports_exceptions() returned true unconditionally before this patch and still does. The wording looks like it came from the x86 patch in this series, which added "|| IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI)".
There is also an ordering question. At this commit arm64 has neither UNWINDER_FRAME_POINTER nor UNWINDER_DWARF_CFI; both arrive in the next commit, 14d0cf0eeab5 ("arm64/unwind: Add Minimal DWARF CFI kernel unwinder"). The removed sentence "ARM64 kernel is always compiled with CONFIG_FRAME_POINTER=y" is still true here and stops being true only in that commit. Should this comment change move there?
The message also says the annotations are added "under CONFIG_UNWINDER_DWARF_CFI", but one change in return_to_handler is not under that option:
arch/arm64/net/bpf_jit_comp.c SYM_CODE_START(return_to_handler) · line 355
Quoted 6 lines
arch/arm64/net/bpf_jit_comp.c +3
-1@@ -338,12 +352,24 @@ SYM_CODE_START(return_to_handler) -/* Save the callsite's FP */ +/* Save the callsite's FP and clear unused LR slot in ftrace_regs */ str x29, [sp, #FREGS_FP] + str xzr, [sp, #FREGS_LR] +#ifdef CONFIG_UNWINDER_DWARF_CFI
The str xzr store runs in every CONFIG_FUNCTION_GRAPH_TRACER build. It looks harmless, since ftrace_partial_regs() used to copy stack garbage into regs->regs[30] for kprobe_multi return programs and now copies 0, but it is not mentioned in the changelog.
Could the changelog say that the bpf_jit_comp.c part only updates the justification ahead of the unwinder-choice commit (or move it there), and mention the unconditional FREGS_LR store?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 16/30 arm64/unwind: Add Minimal DWARF CFI kernel unwinder
In reply to Ian RogersAdd CONFIG_UNWINDER_DWARF_CFI as a kernel unwinder choice alongside CONFIG_UNWINDER_FRAME_POINTER on arm64:
- Move select ARCH_WANT_FRAME_POINTERS and select FRAME_POINTER under UNWINDER_FRAME_POINTER and pass -fomit-frame-pointer and -fasynchronous-unwind-tables under UNWINDER_DWARF_CFI, while keeping -fno-omit-frame-pointer for the user vDSO and nVHE EL2 objects.
- Emit --eh-frame-hdr and place .eh_frame_hdr and .eh_frame in vmlinux RO_DATA while preserving __pi___eh_frame_start/__pi___eh_frame_end for Dynamic Shadow Call Stack patching, and index SHF_ALLOC module .eh_frame sections with RCU-safe lifetime.
- Key function_graph and kretprobe shadow return stacks on entry SP (CFA) rather than x29, mark caller-fetched perf regs via FRAME_META_TYPE_CALLER, and implement noinstr-safe kunwind_next_cfi() in arch/arm64/kernel/stacktrace.c.
--- arch/arm64/Kconfig | 2 - arch/arm64/Kconfig.debug | 32 ++ arch/arm64/Makefile | 5 + arch/arm64/include/asm/ftrace.h | 18 +- arch/arm64/include/asm/module.h | 16 + arch/arm64/include/asm/module.lds.h | 2 +- arch/arm64/include/asm/perf_event.h | 2 + arch/arm64/include/asm/stacktrace/frame.h | 6 + arch/arm64/kernel/Makefile | 6 + arch/arm64/kernel/ftrace.c | 12 +- arch/arm64/kernel/module.c | 17 +- arch/arm64/kernel/probes/kprobes.c | 14 +- arch/arm64/kernel/stacktrace.c | 477 ++++++++++++++++++++-- arch/arm64/kernel/vdso/Makefile | 7 +- arch/arm64/kernel/vmlinux.lds.S | 21 +- arch/arm64/kvm/hyp/nvhe/Makefile | 1 + 16 files changed, 596 insertions(+), 42 deletions(-)
arch/arm64/Kconfig +0 -2
@@ -91,7 +91,6 @@ config ARM64 select ARCH_WANT_COMPAT_IPC_PARSE_VERSION if COMPAT select ARCH_WANT_DEFAULT_BPF_JIT select ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT - select ARCH_WANT_FRAME_POINTERS select ARCH_WANT_HUGE_PMD_SHARE if ARM64_4K_PAGES || (ARM64_16K_PAGES && !ARM64_VA_BITS_36) select ARCH_WANT_LD_ORPHAN_WARN select ARCH_WANTS_EXECMEM_LATE
@@ -118,7 +117,6 @@ config ARM64 select DMA_BOUNCE_UNALIGNED_KMALLOC select DMA_DIRECT_REMAP select EDAC_SUPPORT - select FRAME_POINTER select FUNCTION_ALIGNMENT_4B select FUNCTION_ALIGNMENT_8B if DYNAMIC_FTRACE_WITH_CALL_OPS select GENERIC_ALLOCATOR
arch/arm64/Kconfig.debug +32 -0
@@ -1,5 +1,37 @@ # SPDX-License-Identifier: GPL-2.0-only +choice + prompt "Choose kernel unwinder" + default UNWINDER_FRAME_POINTER + help + This determines which method will be used for unwinding kernel stack + traces for panics, oopses, bugs, warnings, perf, /proc/<pid>/stack, + livepatch, lockdep, and more. If unsure, keep the default frame + pointer unwinder. + +config UNWINDER_FRAME_POINTER + bool "Frame pointer unwinder" + select ARCH_WANT_FRAME_POINTERS + select FRAME_POINTER + help + This option enables the standard frame pointer (x29) unwinder for + unwinding kernel stack traces on arm64. Kernel code is compiled + with frame records stored on the stack at a small runtime register + and code-size cost. + +config UNWINDER_DWARF_CFI + bool "Minimal DWARF CFI unwinder" + depends on (!FUNCTION_TRACER || DYNAMIC_FTRACE_WITH_ARGS) && (!SHADOW_CALL_STACK || DYNAMIC_SCS) + select UNWIND_DWARF_CFI + select UNWIND_TABLES + help + This option enables the Minimal DWARF Call Frame Information (CFI) + unwinder for kernel stack traces. It interprets a strictly bounded + subset of compiler-generated .eh_frame / .eh_frame_hdr tables + matching SFrame's stack state model without requiring frame pointers. + +endchoice + config PID_IN_CONTEXTIDR bool "Write the current PID to the CONTEXTIDR register" help
arch/arm64/Makefile +5 -0
@@ -23,6 +23,11 @@ ifeq ($(CONFIG_ARM64_ERRATUM_843419),y) LDFLAGS_vmlinux += --fix-cortex-a53-843419 endif +ifeq ($(CONFIG_UNWINDER_DWARF_CFI),y) +KBUILD_CFLAGS += -fomit-frame-pointer +LDFLAGS_vmlinux += --eh-frame-hdr +endif + cc_has_k_constraint := $(call try-run,echo \ 'int main(void) { \ asm volatile("and w0, w0, %w0" :: "K" (4294967295)); \
arch/arm64/include/asm/ftrace.h +13 -5
@@ -56,6 +56,7 @@ unsigned long arch_ftrace_get_symaddr(unsigned long fentry_ip);#define ftrace_get_symaddr (fentry_ip) arch_ftrace_get_symaddr(fentry_ip)#ifdef CONFIG_DYNAMIC_FTRACE_WITH_ARGS +void ftrace_caller_end (void );#define HAVE_ARCH_FTRACE_REGS struct dyn_ftrace ;struct ftrace_ops ;
@@ -154,14 +155,21 @@ ftrace_partial_regs(const struct ftrace_regs *fregs, struct pt_regs *regs) regs->regs[29 ] = afregs->fp; regs->regs[30 ] = afregs->lr; regs->pstate = PSR_MODE_EL1h; + regs->stackframe.type =FRAME_META_TYPE_NONE ;return regs; } -#define arch_ftrace_fill_perf_regs (fregs, _regs) do { \ - (_regs)->pc = arch_ftrace_regs(fregs)->pc; \ - (_regs)->regs[29] = arch_ftrace_regs(fregs)->fp; \ - (_regs)->sp = arch_ftrace_regs(fregs)->sp; \ - (_regs)->pstate = PSR_MODE_EL1h; \ +#define arch_ftrace_fill_perf_regs (fregs, _regs) do { \ + const struct __arch_ftrace_regs *__afregs = \ + arch_ftrace_regs(fregs); \ + struct pt_regs *__regs = (_regs); \ + \ + __regs->pc = __afregs->pc; \ + __regs->regs[29] = __afregs->fp; \ + __regs->regs[30] = __afregs->lr; \ + __regs->sp = __afregs->sp; \ + __regs->pstate = PSR_MODE_EL1h; \ + __regs->stackframe.type = FRAME_META_TYPE_NONE; \ } while (0)int ftrace_regs_query_register_offset (const char *name);
arch/arm64/include/asm/module.h +16 -0
@@ -13,6 +13,8 @@ struct mod_plt_sec {int plt_max_entries; }; +struct mod_dwarf_cfi_index ; +struct mod_arch_specific {struct mod_plt_sec core;struct mod_plt_sec init;
@@ -20,8 +22,22 @@ struct mod_arch_specific {/* for CONFIG_DYNAMIC_FTRACE */ struct plt_entry *ftrace_trampolines;struct plt_entry *init_ftrace_trampolines; + +#ifdef CONFIG_UNWINDER_DWARF_CFI +struct mod_dwarf_cfi_index __rcu *dwarf_cfi_index; +#endif }; +#ifdef CONFIG_UNWINDER_DWARF_CFI +void arm64_unwind_module_init (struct module *mod,void *eh_frame, +size_t eh_frame_size); +void arm64_unwind_module_cleanup (struct module *mod); +#else +static inline void arm64_unwind_module_init (struct module *mod,void *eh_frame, +size_t eh_frame_size) {} +static inline void arm64_unwind_module_cleanup (struct module *mod) {} +#endif +u64 module_emit_plt_entry (struct module *mod,Elf64_Shdr *sechdrs,void *loc,const Elf64_Rela *rela,Elf64_Sym *sym);
arch/arm64/include/asm/module.lds.h +1 -1
@@ -4,7 +4,7 @@ SECTIONS { .text.ftrace_trampoline 0 : { BYTE(0) } .init.text.ftrace_trampoline 0 : { BYTE(0) } -#ifdef CONFIG_UNWIND_TABLES +#if defined(CONFIG_UNWIND_TABLES ) && !defined(CONFIG_UNWINDER_DWARF_CFI )/* * Currently, we only use unwind info at module load time, so we can * put it into the .init allocation.
arch/arm64/include/asm/perf_event.h +2 -0
@@ -16,8 +16,10 @@#define perf_arch_fetch_caller_regs (regs, __ip) { \ (regs)->pc = (__ip); \ (regs)->regs[29] = (unsigned long) __builtin_frame_address(0); \ + (regs)->regs[30] = 0; \ (regs)->sp = current_stack_pointer; \ (regs)->pstate = PSR_MODE_EL1h; \ + (regs)->stackframe.type = FRAME_META_TYPE_CALLER; \ }#endif
arch/arm64/include/asm/stacktrace/frame.h +6 -0
@@ -18,12 +18,18 @@* an arbitrary point in time. * Unwinding should consume pt_regs::pc, followed by pt_regs::lr. * +* - FRAME_META_TYPE_CALLER +* +* Synthetic caller-fetched struct pt_regs from perf_arch_fetch_caller_regs() +* (not linked into the stack frame chain). +* * Note: all other values are reserved and should result in unwinding * terminating with an error. */ #define FRAME_META_TYPE_NONE 0#define FRAME_META_TYPE_FINAL 1#define FRAME_META_TYPE_PT_REGS 2 +#define FRAME_META_TYPE_CALLER 3#ifndef __ASSEMBLER__/*
arch/arm64/kernel/Makefile +6 -0
@@ -8,6 +8,9 @@ CFLAGS_armv8_deprecated.o := -I$(src) CFLAGS_REMOVE_ftrace.o = $(CC_FLAGS_FTRACE) CFLAGS_REMOVE_insn.o = $(CC_FLAGS_FTRACE) CFLAGS_REMOVE_return_address.o = $(CC_FLAGS_FTRACE) +ifdef CONFIG_UNWINDER_DWARF_CFI +CFLAGS_REMOVE_stacktrace.o = $(CC_FLAGS_FTRACE) +endif # Remove stack protector to avoid triggering unneeded stack canary # checks due to randomize_kstack_offset.
@@ -24,6 +27,9 @@ KASAN_SANITIZE_stacktrace.o := n # inhibit KCOV instrumentation, disable it for the entire compilation unit. KCOV_INSTRUMENT_entry-common.o := n KCOV_INSTRUMENT_idle.o := n +ifdef CONFIG_UNWINDER_DWARF_CFI +KCOV_INSTRUMENT_stacktrace.o := n +endif # Softirq stack switching can run outside interrupt context. KCOV_INSTRUMENT_irq.o := n
arch/arm64/kernel/ftrace.c +9 -3
@@ -553,6 +553,14 @@ void ftrace_graph_func(unsigned long ip, unsigned long parent_ip, {unsigned long return_hooker = (unsigned long )&return_to_handler;unsigned long frame_pointer =arch_ftrace_regs (fregs)->fp; +/* +* With -fomit-frame-pointer under CONFIG_UNWINDER_DWARF_CFI, nested +* functions share x29, whereas each frame's entry SP (its DWARF CFA) +* uniquely keys its shadow stack slot for ftrace_graph_ret_addr(). +*/ +unsigned long *retp =IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ) ? + (unsigned long *)arch_ftrace_regs (fregs)->sp : + (unsigned long *)frame_pointer;unsigned long *parent = &arch_ftrace_regs (fregs)->lr;unsigned long old;
@@ -561,10 +569,8 @@ void ftrace_graph_func(unsigned long ip, unsigned long parent_ip, old = *parent; -if (!function_graph_enter_regs (old, ip, frame_pointer, - (void *)frame_pointer, fregs)) { +if (!function_graph_enter_regs (old, ip, frame_pointer, retp, fregs)) *parent = return_hooker; - } }#else /*
arch/arm64/kernel/module.c +16 -1
@@ -499,6 +499,8 @@ int module_finalize(const Elf_Ehdr *hdr,if (scs_is_dynamic ()) { s =find_section (hdr, sechdrs,".init.eh_frame" ); +if (!s) + s =find_section (hdr, sechdrs,".eh_frame" );if (s) {/* * Because we can reject modules that are malformed
@@ -515,5 +517,18 @@ int module_finalize(const Elf_Ehdr *hdr, } } -return module_init_ftrace_plt (hdr, sechdrs, me); + ret =module_init_ftrace_plt (hdr, sechdrs, me); +if (ret) +return ret; + + s =find_section (hdr, sechdrs,".eh_frame" ); +if (s && (s->sh_flags &SHF_ALLOC )) +arm64_unwind_module_init (me, (void *)s->sh_addr, s->sh_size); + +return 0 ; +} + +void module_arch_cleanup (struct module *mod) +{ +arm64_unwind_module_cleanup (mod); }
arch/arm64/kernel/probes/kprobes.c +12 -2
@@ -416,10 +416,13 @@ kprobe_ss_brk_handler(struct pt_regs *regs, unsigned long esr)int __kprobes kretprobe_brk_handler (struct pt_regs *regs,unsigned long esr) { +void *frame =IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ) ? + (void *)regs->sp : (void *)regs->regs[29 ]; +if (regs->pc != (unsigned long )__kretprobe_trampoline)return DBG_HOOK_ERROR ; - regs->pc =kretprobe_trampoline_handler (regs, (void *)regs->regs[29 ]); + regs->pc =kretprobe_trampoline_handler (regs, frame);return DBG_HOOK_HANDLED ; }
@@ -452,7 +455,14 @@ void __kprobes arch_prepare_kretprobe(struct kretprobe_instance *ri, struct pt_regs *regs) { ri->ret_addr = (kprobe_opcode_t *)regs->regs[30 ]; - ri->fp = (void *)regs->regs[29 ]; +/* +* Under CONFIG_UNWINDER_DWARF_CFI (-fomit-frame-pointer), nested C +* functions do not update x29; key the kretprobe instance on the +* probed function's entry SP (its DWARF CFA), which matches regs->sp +* upon returning to __kretprobe_trampoline. +*/ + ri->fp =IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ) ? + (void *)regs->sp : (void *)regs->regs[29 ];/* replace return addr (x30) with trampoline */ regs->regs[30 ] = (long )&__kretprobe_trampoline;
arch/arm64/kernel/stacktrace.c +452 -25
620 lines not on this page · raw message
arch/arm64/kernel/vdso/Makefile +5 -2
@@ -35,13 +35,16 @@ ccflags-y += -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO # -Wmissing-prototypes and -Wmissing-declarations are removed from # the CFLAGS to make possible to build the kernel with CONFIG_WERROR enabled. -CC_FLAGS_REMOVE_VDSO := $(CC_FLAGS_FTRACE) -Os $(CC_FLAGS_SCS) \ +CC_FLAGS_REMOVE_VDSO := $(CC_FLAGS_FTRACE) -Os -fomit-frame-pointer \ + $(CC_FLAGS_SCS) \ $(RANDSTRUCT_CFLAGS) $(KSTACK_ERASE_CFLAGS) \ $(GCC_PLUGINS_CFLAGS) \ $(CC_FLAGS_LTO) $(CC_FLAGS_CFI) \ -Wmissing-prototypes -Wmissing-declarations -CC_FLAGS_ADD_VDSO := -O2 -mcmodel=tiny -fasynchronous-unwind-tables $(CONFIG_CC_OPT_INLINE_MEMSET) +CC_FLAGS_ADD_VDSO := -O2 -mcmodel=tiny -fno-omit-frame-pointer \ + -fasynchronous-unwind-tables \ + $(CONFIG_CC_OPT_INLINE_MEMSET) CFLAGS_REMOVE_vgettimeofday.o = $(CC_FLAGS_REMOVE_VDSO) CFLAGS_REMOVE_vgetrandom.o = $(CC_FLAGS_REMOVE_VDSO)
arch/arm64/kernel/vmlinux.lds.S +20 -1
@@ -144,7 +144,23 @@ jiffies = jiffies_64; #define TRAMP_TEXT #endif -#ifdef CONFIG_UNWIND_TABLES +#ifdef CONFIG_UNWINDER_DWARF_CFI +#define UNWIND_RODATA_SECTIONS \ + .eh_frame_hdr : ALIGN(4) { \ + __start_eh_frame_hdr = .; \ + *(.eh_frame_hdr) \ + __stop_eh_frame_hdr = .; \ + } \ + .eh_frame : ALIGN(8) { \ + __start_eh_frame = .; \ + __pi___eh_frame_start = .; \ + *(.eh_frame) \ + __pi___eh_frame_end = .; \ + __stop_eh_frame = .; \ + } +#define UNWIND_DATA_SECTIONS +#elif defined(CONFIG_UNWIND_TABLES) +#define UNWIND_RODATA_SECTIONS #define UNWIND_DATA_SECTIONS \ .eh_frame : { \ __pi___eh_frame_start = .; \
@@ -152,6 +168,7 @@ jiffies = jiffies_64; __pi___eh_frame_end = .; \ } #else +#define UNWIND_RODATA_SECTIONS #define UNWIND_DATA_SECTIONS #endif
@@ -212,6 +229,8 @@ SECTIONS /* everything from this point to __init_begin will be marked RO NX */ RO_DATA(PAGE_SIZE) + UNWIND_RODATA_SECTIONS + HYPERVISOR_RODATA_SECTIONS #ifdef CONFIG_NVHE_EL2_TRACING
arch/arm64/kvm/hyp/nvhe/Makefile +1 -0
@@ -104,6 +104,7 @@ KBUILD_CFLAGS := $(filter-out $(CC_FLAGS_FTRACE) $(CC_FLAGS_SCS), $(KBUILD_CFLAG # when profile optimization is applied. gen-hyprel does not support SHT_REL and # causes a build failure. Remove profile optimization flags. KBUILD_CFLAGS := $(filter-out -fprofile-sample-use=% -fprofile-use=%, $(KBUILD_CFLAGS)) +KBUILD_CFLAGS := $(filter-out -fomit-frame-pointer, $(KBUILD_CFLAGS)) -fno-omit-frame-pointer KBUILD_CFLAGS += -fno-asynchronous-unwind-tables -fno-unwind-tables ifeq ($(CONFIG_UBSAN_KVM_EL2),y)
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 16/30] arm64/unwind: Add Minimal DWARF CFI kernel unwinder
TL;DR: The module lookup (__module_address) called from the noinstr arm64 stack walkers is unannotated, so kprobes or tracing may re-enter the walker and RCU may not be watching; no concrete crash…
Quoted 1 line
arm64/unwind: Add Minimal DWARF CFI kernel unwinder
TL;DR: The module lookup (__module_address) called from the noinstr arm64 stack walkers is unannotated, so kprobes or tracing may re-enter the walker and RCU may not be watching; no concrete crash found.
Quoted 3 lines
arch/arm64/kernel/stacktrace.c +0
-0
[ ... ]
Quoted 10 lines
arch/arm64/kernel/stacktrace.c +10
-0+/** +* arm64_dwarf_cfi_module_find() - Look up Minimal DWARF CFI in loadable modules +* @pc: Kernel instruction pointer to evaluate. +* @row: Output evaluated Minimal DWARF CFI row. +* +* Uses rcu_read_lock_sched_notrace() and rcu_dereference_raw() so lookups are +* safe inside noinstr stack walks and NMI contexts. +* +* Return: 0 on success, -ENOENT if @pc is not in a module FDE, or a negative +* errno on invalid FDE bytecode.
arch/arm64/kernel/stacktrace.c line 87
Quoted 10 lines
arch/arm64/kernel/stacktrace.c +10
-0+*/ +static __always_inline int +arm64_dwarf_cfi_module_find (unsigned long pc,struct dwarf_cfi_row *row) +{ +struct mod_dwarf_cfi_index *idx; +struct module *mod; +int ret; + +rcu_read_lock_sched_notrace (); + mod =__module_address (pc);
Is this safe inside the noinstr stack walkers?
arm64_dwarf_cfi_module_find() is __always_inline into arch_stack_walk(), arch_stack_walk_reliable() and arch_bpf_stack_walk(), which are all noinline noinstr. But __module_address() is an ordinary out-of-line function with no noinstr, notrace or NOKPROBE_SYMBOL() annotation, and it calls mod_find(), which is also unannotated.
The arm64 walker was made noinstr by commit 0fbcd8abf337 ("arm64: Prohibit instrumentation on arch_stack_walk()") because the stacktrace code can be used in kprobe context and cannot be safely probed. With CONFIG_UNWINDER_DWARF_CFI=y, any pc not covered by the vmlinux .eh_frame_hdr (module text, BPF JIT code, asm without CFI such as the el1h_64_sync vectors) goes to __module_address(). Can a kprobe, fprobe or function tracer attached to __module_address() or mod_find() now fire from inside the walker, for example via a kprobe event with a stacktrace trigger that re-hits the probe?
Separately, rcu_read_lock_sched_notrace() only skips lockdep and tracing. It does not make RCU watch, so is the RCU-sched read side section valid in a noinstr region where RCU may not be watching?
The comment claims the lookup is "safe inside noinstr stack walks and NMI contexts", and the commit message calls kunwind_next_cfi() "noinstr-safe". Either the module lookup path needs to be noinstr or kprobe-blacklisted, or the comment and commit message should drop that claim. I could not construct a concrete crash through the current kprobe re-entry handling.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 17/30 riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding
In reply to Ian RogersWire up CONFIG_HAVE_UNWIND_USER_CFI and CONFIG_HAVE_UNWIND_USER_FP on MMU-enabled RISC-V kernels by adding arch/riscv/include/asm/unwind_user.h and unwind_user_sigreturn():
- Define DWARF CFI register mappings for RV64 and RV32/compat user tasks (sp=2, fp/s0=8, ra=1).
- Provide unwind_user_link_register() reading regs->ra for leaf-frame unwinding and ARCH_INIT_USER_FP_FRAME matching the RISC-V psABI frame layout (CFA = s0, RA at s0 - ws, saved s0 at s0 - 2*ws).
- Implement unwind_user_sigreturn() (and compat_unwind_user_sigreturn()) to recover pc, ra, sp, and s0 from rt_sigframe.uc.uc_mcontext.sc_regs across __vdso_rt_sigreturn (whose vDSO FDE omits register rules so libgcc takes its instruction-matching sigcontext fallback), supporting interrupted leaf functions, -fomit-frame-pointer frames, and SA_ONSTACK alternate signal stacks.
--- arch/riscv/Kconfig | 2 + arch/riscv/include/asm/signal32.h | 9 +++ arch/riscv/include/asm/unwind_user.h | 82 ++++++++++++++++++++++++++++ arch/riscv/kernel/compat_signal.c | 45 +++++++++++++++ arch/riscv/kernel/signal.c | 57 +++++++++++++++++++ 5 files changed, 195 insertions(+) create mode 100644 arch/riscv/include/asm/unwind_user.h
arch/riscv/Kconfig +2 -0
@@ -202,6 +202,8 @@ config RISCV select HAVE_SAMPLE_FTRACE_DIRECT_MULTI select HAVE_STACKPROTECTOR select HAVE_SYSCALL_TRACEPOINTS + select HAVE_UNWIND_USER_CFI if MMU + select HAVE_UNWIND_USER_FP if MMU select HOTPLUG_PARALLEL if HOTPLUG_CPU select IRQ_DOMAIN select IRQ_FORCED_THREADING
arch/riscv/include/asm/signal32.h +9 -0
@@ -3,9 +3,12 @@#ifndef __ASM_SIGNAL32_H#define __ASM_SIGNAL32_H +struct unwind_user_state ; +#if IS_ENABLED (CONFIG_COMPAT )int compat_setup_rt_frame (struct ksignal *ksig,sigset_t *set,struct pt_regs *regs); +bool compat_unwind_user_sigreturn (struct unwind_user_state *state);#else static inline int compat_setup_rt_frame(struct ksignal *ksig, sigset_t *set,
@@ -13,6 +16,12 @@ int compat_setup_rt_frame(struct ksignal *ksig, sigset_t *set, {return -1 ; } + +static inline +bool compat_unwind_user_sigreturn (struct unwind_user_state *state) +{ +return false; +}#endif #endif
arch/riscv/include/asm/unwind_user.h new file +82 -0
82 lines not on this page · raw message
arch/riscv/kernel/compat_signal.c +45 -0
54 lines not on this page · raw message
arch/riscv/kernel/signal.c +57 -0
66 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 18/30 riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF JIT
In reply to Ian RogersPrepare RISC-V assembly, probe trampolines, and RV64 BPF JIT prologues for runtime Minimal DWARF CFI kernel unwinding:
- Export end labels for ret_from_fork_user_asm, call_on_irq_stack, and ftrace_caller save/restore boundaries, and save s0 in ftrace_caller under CONFIG_UNWINDER_DWARF_CFI.
- Annotate return_to_handler() and arch_rethook_trampoline() with .cfi_* directives and key rethook shadow stacks on entry SP (CFA) under CONFIG_UNWINDER_DWARF_CFI.
- Save RV_REG_RA unconditionally in RV64 BPF JIT prologues under CONFIG_UNWINDER_DWARF_CFI so leaf BPF programs unwind into frameless C callers.
--- arch/riscv/kernel/entry.S | 2 ++ arch/riscv/kernel/mcount-dyn.S | 6 ++-- arch/riscv/kernel/mcount.S | 34 +++++++++++++++++-- arch/riscv/kernel/probes/rethook.c | 13 +++++-- arch/riscv/kernel/probes/rethook_trampoline.S | 30 ++++++++++++++++ arch/riscv/net/bpf_jit_comp64.c | 6 ++-- 6 files changed, 81 insertions(+), 10 deletions(-)
arch/riscv/kernel/entry.S +2 -0
@@ -374,6 +374,7 @@ SYM_CODE_START(ret_from_fork_user_asm) move a0, sp /* pt_regs */ call ret_from_fork_user j ret_from_exception +SYM_INNER_LABEL(ret_from_fork_asm_end, SYM_L_GLOBAL) SYM_CODE_END(ret_from_fork_user_asm) #ifdef CONFIG_IRQ_STACKS
@@ -410,6 +411,7 @@ SYM_FUNC_START(call_on_irq_stack) addi sp, sp, STACKFRAME_SIZE_ON_STACK ret +SYM_INNER_LABEL(call_on_irq_stack_end, SYM_L_GLOBAL) SYM_FUNC_END(call_on_irq_stack) #endif /* CONFIG_IRQ_STACKS */
arch/riscv/kernel/mcount-dyn.S +4 -2
@@ -85,7 +85,7 @@ addi sp, sp, -FREGS_SIZE_ON_STACK REG_S t0, FREGS_EPC(sp) REG_S x1, FREGS_RA(sp) -#ifdef HAVE_FUNCTION_GRAPH_FP_TEST +#if defined(HAVE_FUNCTION_GRAPH_FP_TEST) || defined(CONFIG_UNWINDER_DWARF_CFI) REG_S x8, FREGS_S0(sp) #endif REG_S x6, FREGS_T1(sp)
@@ -113,7 +113,7 @@ .macro RESTORE_ABI_REGS REG_L t0, FREGS_EPC(sp) REG_L x1, FREGS_RA(sp) -#ifdef HAVE_FUNCTION_GRAPH_FP_TEST +#if defined(HAVE_FUNCTION_GRAPH_FP_TEST) || defined(CONFIG_UNWINDER_DWARF_CFI) REG_L x8, FREGS_S0(sp) #endif REG_L x6, FREGS_T1(sp)
@@ -183,6 +183,7 @@ SYM_FUNC_START(ftrace_caller) #endif #endif SAVE_ABI_REGS +SYM_INNER_LABEL(ftrace_caller_saved, SYM_L_GLOBAL) PREPARE_ARGS #ifdef CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS
@@ -193,6 +194,7 @@ SYM_INNER_LABEL(ftrace_call, SYM_L_GLOBAL) jalr ra, 0(ra) #endif RESTORE_ABI_REGS +SYM_INNER_LABEL(ftrace_caller_restore, SYM_L_GLOBAL) #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS bnez t1, ftrace_caller_direct #endif
arch/riscv/kernel/mcount.S +31 -3
@@ -27,8 +27,17 @@ */ .macro SAVE_RET_ABI_STATE addi sp, sp, -FREGS_SIZE_ON_STACK +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset FREGS_SIZE_ON_STACK +#endif REG_S ra, FREGS_RA(sp) REG_S s0, FREGS_S0(sp) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_offset s0, FREGS_S0 - FREGS_SIZE_ON_STACK + la t0, return_to_handler + REG_S t0, FREGS_EPC(sp) + .cfi_offset ra, FREGS_EPC - FREGS_SIZE_ON_STACK +#endif REG_S a0, FREGS_A0(sp) REG_S a1, FREGS_A1(sp) addi s0, sp, FREGS_SIZE_ON_STACK
@@ -41,11 +50,16 @@ .endm .macro RESTORE_RET_ABI_STATE - REG_L ra, FREGS_RA(sp) REG_L s0, FREGS_S0(sp) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_restore s0 +#endif REG_L a0, FREGS_A0(sp) REG_L a1, FREGS_A1(sp) addi sp, sp, FREGS_SIZE_ON_STACK +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 0 +#endif .endm SYM_TYPED_FUNC_START(ftrace_stub)
@@ -69,13 +83,27 @@ SYM_FUNC_START(return_to_handler) * * So alternatively we check the *old* frame pointer position, that is, the * value stored in -16(s0) on entry, and the s0 on return. + * + * Under CONFIG_UNWINDER_DWARF_CFI, FREGS_EPC(sp) is seeded with + * &return_to_handler before ftrace_return_to_handler() overwrites fregs->epc + * with the popped caller PC, allowing walk_stackframe_cfi() to unwind cleanly + * both before and after current->curr_ret_stack is decremented. */ +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc +#endif SAVE_RET_ABI_STATE mv a0, sp call ftrace_return_to_handler - mv a2, a0 + mv ra, a0 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_same_value ra +#endif RESTORE_RET_ABI_STATE - jalr a2 + ret +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_FUNC_END(return_to_handler) #endif
arch/riscv/kernel/probes/rethook.c +11 -2
@@ -10,7 +10,10 @@/* This is called from arch_rethook_trampoline() */ unsigned long __used arch_rethook_trampoline_callback (struct pt_regs *regs) { -return rethook_trampoline_handler (regs, regs->s0); +unsigned long frame =IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ) ? + regs->sp : regs->s0; + +return rethook_trampoline_handler (regs, frame); }NOKPROBE_SYMBOL (arch_rethook_trampoline_callback);
@@ -18,7 +21,13 @@ NOKPROBE_SYMBOL(arch_rethook_trampoline_callback);void arch_rethook_prepare (struct rethook_node *rhn,struct pt_regs *regs,bool mcount) { rhn->ret_addr = regs->ra; - rhn->frame = regs->s0; +/* +* With -fomit-frame-pointer under CONFIG_UNWINDER_DWARF_CFI, nested +* functions share s0; key the rethook node on the function's entry SP +* (its DWARF CFA), which matches regs->sp at arch_rethook_trampoline. +*/ + rhn->frame =IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI ) ? + regs->sp : regs->s0;/* replace return addr with trampoline */ regs->ra = (unsigned long )arch_rethook_trampoline;
arch/riscv/kernel/probes/rethook_trampoline.S +30 -0
@@ -78,9 +78,27 @@ REG_L x31, PT_T6(sp) .endm +/* + * Under CONFIG_UNWINDER_DWARF_CFI, PT_EPC(sp) is seeded with + * &arch_rethook_trampoline before rethook_trampoline_handler() overwrites + * regs->epc with the restored caller PC prior to running rethook handlers, + * enabling reliable CFI unwinding across kretprobe return hooks. + */ SYM_CODE_START(arch_rethook_trampoline) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_startproc +#endif addi sp, sp, -(PT_SIZE_ON_STACK) +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset PT_SIZE_ON_STACK +#endif save_all_base_regs +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_offset s0, PT_S0 - PT_SIZE_ON_STACK + la t0, arch_rethook_trampoline + REG_S t0, PT_EPC(sp) + .cfi_offset ra, PT_EPC - PT_SIZE_ON_STACK +#endif move a0, sp /* pt_regs */
@@ -88,9 +106,21 @@ SYM_CODE_START(arch_rethook_trampoline) /* use the result as the return-address */ move ra, a0 +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_same_value ra +#endif restore_all_base_regs +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_restore s0 +#endif addi sp, sp, PT_SIZE_ON_STACK +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_def_cfa_offset 0 +#endif ret +#ifdef CONFIG_UNWINDER_DWARF_CFI + .cfi_endproc +#endif SYM_CODE_END(arch_rethook_trampoline)
arch/riscv/net/bpf_jit_comp64.c +3 -3
@@ -201,7 +201,7 @@ static void __build_epilogue(bool is_tail_call, struct rv_jit_context *ctx) {int stack_adjust = ctx->stack_size, store_offset = stack_adjust -8 ; -if (seen_reg (RV_REG_RA , ctx)) { +if (seen_reg (RV_REG_RA , ctx) ||IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI )) {emit_ld (RV_REG_RA , store_offset,RV_REG_SP , ctx); store_offset -=8 ; }
@@ -2130,7 +2130,7 @@ void bpf_jit_build_prologue(struct rv_jit_context *ctx, bool is_subprog)if (bpf_stack_adjust)mark_fp (ctx); -if (seen_reg (RV_REG_RA , ctx)) +if (seen_reg (RV_REG_RA , ctx) ||IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI )) stack_adjust +=8 ; stack_adjust +=8 ;/* RV_REG_FP */ if (seen_reg (RV_REG_S1 , ctx))
@@ -2168,7 +2168,7 @@ void bpf_jit_build_prologue(struct rv_jit_context *ctx, bool is_subprog)emit_addi (RV_REG_SP ,RV_REG_SP , -stack_adjust, ctx); -if (seen_reg (RV_REG_RA , ctx)) { +if (seen_reg (RV_REG_RA , ctx) ||IS_ENABLED (CONFIG_UNWINDER_DWARF_CFI )) {emit_sd (RV_REG_SP , store_offset,RV_REG_RA , ctx); store_offset -=8 ; }
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 18/30] riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF JIT
TL;DR: Commit message only: it says the return_to_handler() rewrite in riscv mcount.S is under CONFIG_UNWINDER_DWARF_CFI, but part of it is unconditional. The code looks functionally correct.
Quoted 1 line
riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF JIT
TL;DR: Commit message only: it says the return_to_handler() rewrite in riscv mcount.S is under CONFIG_UNWINDER_DWARF_CFI, but part of it is unconditional. The code looks functionally correct.
Quoted 14 lines
riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF JIT
Prepare RISC-V assembly, probe trampolines, and RV64 BPF JIT prologues for runtime Minimal DWARF CFI kernel unwinding:
- Export end labels forret_from_fork_user_asm,call_on_irq_stack, andftrace_callersave/restore boundaries, and save s0 inftrace_callerunderCONFIG_UNWINDER_DWARF_CFI.
- Annotatereturn_to_handler()andarch_rethook_trampoline()with .cfi_* directives and key rethook shadow stacks on entry SP (CFA) underCONFIG_UNWINDER_DWARF_CFI.
- SaveRV_REG_RAunconditionally in RV64 BPF JIT prologues underCONFIG_UNWINDER_DWARF_CFIso leaf BPF programs unwind into frameless C callers.
Quoted 1 line
Signed-off-by Ian Rogers <[email protected]>
The commit message describes the return_to_handler() changes as being under CONFIG_UNWINDER_DWARF_CFI, but part of that rewrite is not config gated:
arch/riscv/kernel/mcount.S:
call ftrace_return_to_handler
- mv a2, a0
+ mv ra, a0
...
- jalr a2
+ ret
and RESTORE_RET_ABI_STATE no longer does:
- REG_L ra, FREGS_RA(sp)
This applies to every riscv kernel with CONFIG_FUNCTION_GRAPH_TRACER, including builds that never enable the new unwinder. On return, ra now holds the real return address instead of a value inside return_to_handler, a2 is no longer written, and ret replaces an indirect jalr.
The new sequence looks functionally correct, but should the commit message say that this part is unconditional and explain why it is needed (the .cfi_same_value ra over the final instructions), so riscv and ftrace maintainers can review it as such?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 19/30 riscv/unwind: Add Minimal DWARF CFI kernel unwinder
In reply to Ian RogersAdd CONFIG_UNWINDER_DWARF_CFI as a selectable 64-bit RISC-V kernel unwinder (selecting HAVE_RELIABLE_STACKTRACE) in arch/riscv/kernel/stacktrace.c:
- Build C and Rust kernel code with -fomit-frame-pointer and -fasynchronous-unwind-tables, link vmlinux with --eh-frame-hdr, place .eh_frame_hdr and .eh_frame in RO_DATA, and index SHF_ALLOC module .eh_frame sections via dwarf_cfi_mod_alloc()/dwarf_cfi_mod_free_rcu().
- Implement walk_stackframe_cfi() and arch_stack_walk_reliable() across task, IRQ, and overflow stacks with RVC 16-bit call-site support, SP-keyed ftrace_graph/rethook recovery, BPF frame fallback, and exception/entry root termination.
--- arch/riscv/Kconfig | 5 +- arch/riscv/Kconfig.debug | 16 + arch/riscv/Makefile | 15 +- arch/riscv/include/asm/ftrace.h | 1 + arch/riscv/include/asm/module.h | 22 + arch/riscv/include/asm/perf_event.h | 2 + arch/riscv/include/asm/stacktrace.h | 11 + arch/riscv/kernel/Makefile | 9 + arch/riscv/kernel/module.c | 9 + arch/riscv/kernel/stacktrace.c | 650 +++++++++++++++++++++++++++- arch/riscv/kernel/vmlinux.lds.S | 13 + arch/riscv/purgatory/Makefile | 3 +- 12 files changed, 749 insertions(+), 7 deletions(-)
arch/riscv/Kconfig +3 -2
@@ -83,7 +83,7 @@ config RISCV select ARCH_USES_CFI_TRAPS if CFI select ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH if MMU select ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT if MMU - select ARCH_WANT_FRAME_POINTERS + select ARCH_WANT_FRAME_POINTERS if !UNWINDER_DWARF_CFI select ARCH_WANT_GENERAL_HUGETLB if !RISCV_ISA_SVNAPOT select ARCH_WANT_HUGE_PMD_SHARE if 64BIT select ARCH_WANT_LD_ORPHAN_WARN
@@ -101,7 +101,7 @@ config RISCV select CPU_PM if CPU_IDLE || HIBERNATION || SUSPEND select DYNAMIC_FTRACE if FUNCTION_TRACER select EDAC_SUPPORT - select FRAME_POINTER if PERF_EVENTS || (FUNCTION_TRACER && !DYNAMIC_FTRACE) + select FRAME_POINTER if !UNWINDER_DWARF_CFI && (PERF_EVENTS || (FUNCTION_TRACER && !DYNAMIC_FTRACE)) select FTRACE_MCOUNT_USE_PATCHABLE_FUNCTION_ENTRY if DYNAMIC_FTRACE select FUNCTION_ALIGNMENT_8B if DYNAMIC_FTRACE_WITH_CALL_OPS select GENERIC_ARCH_TOPOLOGY
@@ -195,6 +195,7 @@ config RISCV select HAVE_PERF_USER_STACK_DUMP select HAVE_POSIX_CPU_TIMERS_TASK_WORK select HAVE_REGS_AND_STACK_ACCESS_API + select HAVE_RELIABLE_STACKTRACE if UNWINDER_DWARF_CFI select HAVE_RETHOOK select HAVE_RSEQ select HAVE_RUST if RUSTC_SUPPORTS_RISCV && CC_IS_CLANG
arch/riscv/Kconfig.debug +16 -0
@@ -1 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-only + +config UNWINDER_DWARF_CFI + bool "Minimal DWARF CFI kernel unwinder" + depends on 64BIT && MMU + depends on (!FUNCTION_TRACER || DYNAMIC_FTRACE_WITH_ARGS) && !SHADOW_CALL_STACK + select HAVE_MOD_ARCH_SPECIFIC if MODULES + select UNWIND_DWARF_CFI + select UNWIND_TABLES + help + This option enables the Minimal DWARF Call Frame Information (CFI) + unwinder for kernel stack traces on 64-bit RISC-V. It interprets a + strictly bounded subset of compiler-generated .eh_frame / + .eh_frame_hdr tables matching SFrame's stack state model without + requiring frame pointers. + source "arch/riscv/kernel/tests/Kconfig.debug"
arch/riscv/Makefile +14 -1
@@ -7,6 +7,9 @@ # LDFLAGS_vmlinux := -z norelro +ifeq ($(CONFIG_UNWINDER_DWARF_CFI),y) + LDFLAGS_vmlinux += --eh-frame-hdr +endif ifeq ($(CONFIG_RELOCATABLE),y) LDFLAGS_vmlinux += -shared -Bsymbolic -z notext KBUILD_CFLAGS += -fPIE
@@ -96,8 +99,18 @@ ifeq ($(CONFIG_CMODEL_MEDANY),y) KBUILD_CFLAGS += -mcmodel=medany endif -# Avoid generating .eh_frame sections. +# Avoid generating .eh_frame sections unless runtime unwind tables are enabled. +ifeq ($(CONFIG_UNWIND_TABLES),y) +KBUILD_CFLAGS += -fasynchronous-unwind-tables +KBUILD_AFLAGS += -fasynchronous-unwind-tables +ifeq ($(CONFIG_UNWINDER_DWARF_CFI),y) +KBUILD_CFLAGS += -fomit-frame-pointer +KBUILD_RUSTFLAGS += -Cforce-unwind-tables=y -Zuse-sync-unwind=n +KBUILD_RUSTFLAGS += $(if $(call rustc-min-version,109800),,-Zllvm_module_flag=uwtable:u32:2:max) +endif +else KBUILD_CFLAGS += -fno-asynchronous-unwind-tables -fno-unwind-tables +endif # The RISC-V attributes frequently cause compatibility issues and provide no # information, so just turn them off.
arch/riscv/include/asm/ftrace.h +1 -0
@@ -217,6 +217,7 @@ ftrace_partial_regs(const struct ftrace_regs *fregs, struct pt_regs *regs) regs->sp = afregs->sp; regs->s0 = afregs->s0; regs->t1 = afregs->t1; + regs->cause =0 ;return regs; }
arch/riscv/include/asm/module.h +22 -0
@@ -11,18 +11,40 @@ struct module;unsigned long module_emit_got_entry (struct module *mod,unsigned long val);unsigned long module_emit_plt_entry (struct module *mod,unsigned long val); +struct mod_dwarf_cfi_index ; +#ifdef CONFIG_MODULE_SECTIONS struct mod_section {Elf_Shdr *shdr;int num_entries;int max_entries; }; +#endif +#ifdef CONFIG_HAVE_MOD_ARCH_SPECIFIC struct mod_arch_specific { +#ifdef CONFIG_MODULE_SECTIONS struct mod_section got;struct mod_section plt;struct mod_section got_plt; +#endif +#if defined(CONFIG_UNWINDER_DWARF_CFI ) && defined(CONFIG_MODULES ) +struct mod_dwarf_cfi_index __rcu *dwarf_cfi_index; +#endif }; +#endif + +#if defined(CONFIG_UNWINDER_DWARF_CFI ) && defined(CONFIG_MODULES ) +void riscv_unwind_module_init (struct module *mod,void *eh_frame, +size_t eh_frame_size); +void riscv_unwind_module_cleanup (struct module *mod); +#else +static inline void riscv_unwind_module_init (struct module *mod,void *eh_frame, +size_t eh_frame_size) {} +static inline void riscv_unwind_module_cleanup (struct module *mod) {} +#endif + +#ifdef CONFIG_MODULE_SECTIONS struct got_entry { unsigned long symbol_addr; /* the real variable address */
arch/riscv/include/asm/perf_event.h +2 -0
@@ -14,9 +14,11 @@#define perf_arch_fetch_caller_regs (regs, __ip) { \ (regs)->epc = (__ip); \ + (regs)->ra = 0; \ (regs)->s0 = (unsigned long) __builtin_frame_address(0); \ (regs)->sp = current_stack_pointer; \ (regs)->status = SR_PP; \ + (regs)->cause = ~0UL; \ }#endif
arch/riscv/include/asm/stacktrace.h +11 -0
@@ -15,6 +15,17 @@ extern void notrace walk_stackframe(struct task_struct *task, struct pt_regs *re bool (*fn)(void *, unsigned long), void *arg);extern void dump_backtrace (struct pt_regs *regs,struct task_struct *task,const char *loglvl); +extern char _start[]; +asmlinkage void ret_from_fork_kernel_asm(void); +asmlinkage void ret_from_fork_user_asm(void); +extern unsigned long ret_from_fork_asm_end; +#ifdef CONFIG_IRQ_STACKS +extern unsigned long call_on_irq_stack_end; +#endif +#ifdef CONFIG_DYNAMIC_FTRACE_WITH_ARGS +void ftrace_caller_saved (void ); +void ftrace_caller_restore (void ); +#endif static inline bool on_thread_stack (void ) {
arch/riscv/kernel/Makefile +9 -0
@@ -42,6 +42,15 @@ CFLAGS_REMOVE_patch.o = $(CC_FLAGS_FTRACE) CFLAGS_REMOVE_sbi.o = $(CC_FLAGS_FTRACE) CFLAGS_REMOVE_return_address.o = $(CC_FLAGS_FTRACE) CFLAGS_REMOVE_sbi_ecall.o = $(CC_FLAGS_FTRACE) +ifdef CONFIG_UNWINDER_DWARF_CFI +CFLAGS_REMOVE_stacktrace.o = $(CC_FLAGS_FTRACE) +endif +endif + +ifdef CONFIG_UNWINDER_DWARF_CFI +CFLAGS_stacktrace.o += -fno-optimize-sibling-calls +KASAN_SANITIZE_stacktrace.o := n +KCOV_INSTRUMENT_stacktrace.o := n endif always-$(KBUILD_BUILTIN) += vmlinux.lds
arch/riscv/kernel/module.c +9 -0
@@ -902,5 +902,14 @@ int module_finalize(const Elf_Ehdr *hdr,if (s)apply_module_alternatives ((void *)s->sh_addr, s->sh_size); + s =find_section (hdr, sechdrs,".eh_frame" ); +if (s && (s->sh_flags &SHF_ALLOC )) +riscv_unwind_module_init (me, (void *)s->sh_addr, s->sh_size); +return 0 ; } + +void module_arch_cleanup (struct module *mod) +{ +riscv_unwind_module_cleanup (mod); +}
arch/riscv/kernel/stacktrace.c +647 -3
676 lines not on this page · raw message
arch/riscv/kernel/vmlinux.lds.S +13 -0
@@ -125,6 +125,19 @@ SECTIONS *(.srodata*) } +#ifdef CONFIG_UNWINDER_DWARF_CFI + .eh_frame_hdr : ALIGN(4) { + __start_eh_frame_hdr = .; + *(.eh_frame_hdr) + __stop_eh_frame_hdr = .; + } + .eh_frame : ALIGN(8) { + __start_eh_frame = .; + *(.eh_frame) + __stop_eh_frame = .; + } +#endif + . = ALIGN(SECTION_ALIGN); _data = .;
arch/riscv/purgatory/Makefile +2 -1
@@ -60,8 +60,9 @@ targets += purgatory.ro purgatory.chk # These are adjustments to the compiler flags used for objects that # make up the standalone purgatory.ro -PURGATORY_CFLAGS_REMOVE := -mcmodel=kernel +PURGATORY_CFLAGS_REMOVE := -mcmodel=kernel -fasynchronous-unwind-tables -funwind-tables PURGATORY_CFLAGS := -mcmodel=medany -ffreestanding -fno-zero-initialized-in-bss +PURGATORY_CFLAGS += -fno-asynchronous-unwind-tables -fno-unwind-tables PURGATORY_CFLAGS += $(DISABLE_KSTACK_ERASE) -DDISABLE_BRANCH_PROFILING PURGATORY_CFLAGS += -fno-stack-protector -g0
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 19/30] riscv/unwind: Add Minimal DWARF CFI kernel unwinder
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] riscv: ftrace: missing arch_ftrace_fill_perf_regs() breaks fprobe unwind --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] riscv: ftrace: missing arch_ftrace_fill_perf_regs() breaks fprobe unwind
--
commit 3d24292fed2450c8bd95936a258cfa1db43fe2ca
Author: Ian Rogers <[email protected]>
riscv/unwind: Add Minimal DWARF CFI kernel unwinder
This commit adds a Minimal DWARF CFI kernel unwinder (CONFIG_UNWINDER_DWARF_CFI) and reliable stack trace support for 64-bit RISC-V.
Quoted 12 lines
arch/riscv/include/asm/ftrace.h +1
-0@@ -217,6 +217,7 @@ ftrace_partial_regs(const struct ftrace_regs *fregs, struct pt_regs *regs) regs->sp = afregs->sp; regs->s0 = afregs->s0; regs->t1 = afregs->t1; + regs->cause =0 ;return regs; }
[ ... ]
Quoted 16 lines
arch/riscv/include/asm/perf_event.h +2
-0@@ -14,9 +14,11 @@#define perf_arch_fetch_caller_regs (regs, __ip) { \ (regs)->epc = (__ip); \ + (regs)->ra = 0; \ (regs)->s0 = (unsigned long) __builtin_frame_address(0); \ (regs)->sp = current_stack_pointer; \ (regs)->status = SR_PP; \ + (regs)->cause = ~0UL; \ }#endif
[ ... ]
Quoted 4 lines
arch/riscv/kernel/stacktrace.c +0
-0
[ ... ]
Quoted 13 lines
arch/riscv/kernel/stacktrace.c +13
-0+static __always_inline int +walk_stackframe_cfi (struct task_struct *task,struct pt_regs *regs, +bool (*fn)(void *,unsigned long ),void *arg, +bool require_reliable) +{ +unsigned long fp, sp, pc, ra =0 , min_sp =0 , caller_fp =0 , caller_pc =0 ; +bool ra_valid = false, exact_pc = false, unreliable = false; +struct llist_node *kr_cur =NULL ; +unsigned int used_stacks =0 ; +int graph_idx =0 ; +int level =0 ; + +if (!task)
arch/riscv/kernel/stacktrace.c line 298
Quoted 10 lines
arch/riscv/kernel/stacktrace.c +10
-0+ task = current; + +if (regs && regs->cause == ~0UL && !regs->ra) { +if (require_reliable || task != current) +return -EINVAL ; + min_sp = regs->sp; + caller_fp = regs->s0; + caller_pc = regs->epc; + regs =NULL ; + }
[Severity: Medium]
Should arch/riscv/include/asm/ftrace.h also define arch_ftrace_fill_perf_regs()?
fentry_perf_func() and fexit_perf_func() in kernel/trace/trace_fprobe.c allocate regs from the per-CPU __perf_regs[rctx] buffer via perf_trace_buf_alloc() and populate it with ftrace_fill_perf_regs(). Without arch_ftrace_fill_perf_regs(), ftrace_fill_perf_regs() is a no-op that only calls ftrace_partial_regs(). If an earlier tracepoint or software perf event on the same CPU ran perf_arch_fetch_caller_regs(), __perf_regs[rctx] retains regs->cause == ~0UL and regs->ra == 0 along with the earlier event's sp, s0 and epc, causing walk_stackframe_cfi() to match the sentinel and filter the fprobe callchain against stale frame bounds (or if __perf_regs[rctx] was never initialized, regs->status == 0 causes user_mode(regs) to skip kernel callchain unwinding in get_perf_callchain()).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
[email protected]
AI reviewRe: [RFC PATCH v2 19/30] riscv/unwind: Add Minimal DWARF CFI kernel unwinder
In reply to Ian RogersTL;DR: Without KEEP(), GNU ld --gc-sections (LD_DEAD_CODE_DATA_ELIMINATION) may discard the core kernel .eh_frame in vmlinux.lds.S, so the DWARF CFI unwinder would fail silently for every kernel PC…
Quoted 1 line
riscv/unwind: Add Minimal DWARF CFI kernel unwinder
TL;DR: Without KEEP(), GNU ld --gc-sections (LD_DEAD_CODE_DATA_ELIMINATION) may discard the core kernel .eh_frame in vmlinux.lds.S, so the DWARF CFI unwinder would fail silently for every kernel PC and degrade stack traces.
Quoted 3 lines
arch/riscv/kernel/vmlinux.lds.S +0
-0
[ ... ]
Quoted 6 lines
arch/riscv/kernel/vmlinux.lds.S +2
-0@@ -125,6 +125,19 @@ SECTIONS *(.srodata*) } +#ifdef CONFIG_UNWINDER_DWARF_CFI + .eh_frame_hdr : ALIGN(4) {
arch/riscv/kernel/vmlinux.lds.S SECTIONS · line 139
Quoted 10 lines
arch/riscv/kernel/vmlinux.lds.S +10
-0+ __start_eh_frame_hdr = .; + *(.eh_frame_hdr) + __stop_eh_frame_hdr = .; + } + .eh_frame : ALIGN(8) { + __start_eh_frame = .; + *(.eh_frame) + __stop_eh_frame = .; + } +#endif
Can the core kernel .eh_frame be discarded here when linking with GNU ld and CONFIG_LD_DEAD_CODE_DATA_ELIMINATION=y?
riscv selects HAVE_LD_DEAD_CODE_DATA_ELIMINATION if !LD_IS_LLD, and the top-level Makefile then adds --gc-sections to LDFLAGS_vmlinux. UNWINDER_DWARF_CFI in arch/riscv/Kconfig.debug does not exclude that option.
Nothing references the .eh_frame input sections, and the __start_eh_frame/__stop_eh_frame assignments do not keep them alive, so without KEEP() the garbage collector would be free to drop them.
If that happens, .eh_frame_hdr would have no FDE table and dwarf_cfi_unwind_eh_frame_hdr() would return -EINVAL for every core kernel PC. Oops, WARN and perf/BPF callchains would then shrink to the heuristic fallbacks, and arch_stack_walk_reliable() would always return -EINVAL, with no build or runtime warning.
The other sections in this file that nothing references use KEEP, for example .alternative and __soc_early_init_table, and the riscv vDSO script uses:
.eh_frame : { KEEP (*(.eh_frame)) }Should this be KEEP(*(.eh_frame)), or should UNWINDER_DWARF_CFI depend on !LD_DEAD_CODE_DATA_ELIMINATION?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 20/30 selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test
In reply to Ian RogersAdd a multi-architecture kselftest (unwind_user_cfi) under tools/testing/selftests/perf_events/ exercising deferred user-space callchain unwinding (PERF_RECORD_CALLCHAIN_DEFERRED) compiled with -O2 -fomit-frame-pointer -fasynchronous-unwind-tables across:
1. Standard SP-based frames with the architectural frame-pointer register (%rbp / x29 / s0) explicitly clobbered
2. Dynamic alloca() VLA FP-based frames (DW_CFA_def_cfa_register)
3. 64-byte stack-realigned frames (DRAP on x86-64)
4. Shrink-wrapped early-return functions (remember_state/restore_state)
5. Anonymous RX JIT-style frame-pointer stubs lacking .eh_frame_hdr
(including a >16-byte AArch64 frame testing state->sp_valid across
FP -> CFI transitions), exercising per-frame CFI -> FP -> CFI -> FP
-> CFI fallback and negative VMA caching in find_user_eh_frame_hdr()Skip gracefully via dl_iterate_phdr() if the test binary lacks PT_GNU_EH_FRAME (e.g. 32-bit ARM EHABI builds using .ARM.exidx).
--- .../testing/selftests/perf_events/.gitignore | 1 + tools/testing/selftests/perf_events/Makefile | 4 +- .../selftests/perf_events/unwind_user_cfi.c | 482 ++++++++++++++++++ 3 files changed, 486 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/perf_events/unwind_user_cfi.c
tools/testing/selftests/perf_events/.gitignore +1 -0
@@ -3,3 +3,4 @@ sigtrap_threads remove_on_exec watermark_signal mmap +unwind_user_cfi
tools/testing/selftests/perf_events/Makefile +3 -1
@@ -2,5 +2,7 @@ CFLAGS += -Wl,-no-as-needed -Wall $(KHDR_INCLUDES) LDFLAGS += -lpthread -TEST_GEN_PROGS := sigtrap_threads remove_on_exec watermark_signal mmap +TEST_GEN_PROGS := sigtrap_threads remove_on_exec watermark_signal mmap unwind_user_cfi include ../lib.mk + +$(OUTPUT)/unwind_user_cfi: CFLAGS += $(TOOLS_INCLUDES) -O2 -fomit-frame-pointer -fasynchronous-unwind-tables
tools/testing/selftests/perf_events/unwind_user_cfi.c new file +482 -0
482 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 20/30] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test
TL;DR: Test issues only, low severity: unwind_user_cfi.c includes a kernel-internal header and #undefs macros, and may report "not ok" instead of skip when perf_event_open returns ENOSYS.
Quoted 1 line
selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test
TL;DR: Test issues only, low severity: unwind_user_cfi.c includes a kernel-internal header and #undefs macros, and may report "not ok" instead of skip when perf_event_open returns ENOSYS.
Quoted 6 lines
tools/testing/selftests/perf_events/unwind_user_cfi.c new file +0
-0@@ -0,0 +1,482 @@
[ ... ]
tools/testing/selftests/perf_events/unwind_user_cfi.c line 39
Quoted 6 lines
tools/testing/selftests/perf_events/unwind_user_cfi.c new file +6
-0+#include "../kselftest.h" +#undef __always_inline +#undef __attribute_const__ +#undef __must_check +#undef __printf +#include "../../../../include/linux/compiler_attributes.h"
This isn't a bug, but would it be simpler to spell the few attributes this test needs directly, for example __attribute__((noinline, noclone)) and __attribute__((aligned(64))), instead of including include/linux/compiler_attributes.h and #undef'ing the clashing macros first?
From tools/testing/selftests/perf_events/ that path resolves to the kernel-internal include/linux/ header rather than a tools/include copy, and no other selftest includes a kernel-internal header this way. Also, __must_check is not defined by either earlier include, so that #undef appears to do nothing.
[ ... ]
tools/testing/selftests/perf_events/unwind_user_cfi.c line 378
Quoted 12 lines
tools/testing/selftests/perf_events/unwind_user_cfi.c new file +12
-0+ fd = (int )sys_perf_event_open (&attr,/*pid=*/ 0 ,/*cpu=*/ -1 , +/*group_fd=*/ -1 ,/*flags=*/ 0 ); +if (fd <0 ) { +if (jit_page !=MAP_FAILED ) +munmap (jit_page, page_sz); +if (errno ==EACCES || errno ==EPERM || errno ==EINVAL ) { +ksft_test_result_skip ("perf_event_open(defer_callchain) unavailable: %s\n" , +strerror (errno)); +ksft_finished (); + } +ksft_exit_fail_msg ("perf_event_open failed: %s\n" ,strerror (errno)); + }
Should ENOSYS be treated as a skip here as well?
On a kernel built without CONFIG_PERF_EVENTS, perf_event_open is a COND_SYSCALL and returns -ENOSYS, so main() reaches ksft_exit_fail_msg() and the runner records "not ok" instead of a skip. The selftests guide flags exiting nonzero other than KSFT_SKIP when a feature or config option is missing.
The other missing prerequisites in main() (unsupported architecture, no PT_GNU_EH_FRAME, defer bits unknown to an older kernel) are already reported as skips, so adding ENOSYS to the errno check would make this case consistent with them. The neighbouring perf_events tests also fail rather than skip when perf_event_open() fails, so this is low severity.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 21/30 scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer
In reply to Ian RogersAdd an optional standalone developer inspection script (scripts/eh_frame_min.py, not invoked by Kbuild) to analyze ELF32/ELF64 relocatable objects (.o, .ko), vmlinux images, user-space executables, and shared libraries across x86_64, i386, arm64, arm, and riscv.
It reports .text / .eh_frame / .eh_frame_hdr / .sframe / .orc_unwind section sizes, simulated minified .eh_frame savings, Minimal DWARF FDE coverage (and breakdown of any unsupported opcodes), kept SP/FP/RA vs. ignored GPR register rules, maximum DW_CFA_remember_state depth, and top DWARF CFA opcode counts.
Example usage:
$ ./scripts/eh_frame_min.py vmlinux $ ./scripts/eh_frame_min.py mm/vmscan.o kernel/fork.o $ ./scripts/eh_frame_min.py /bin/bash /lib/x86_64-linux-gnu/libc.so.6 $ ./scripts/eh_frame_min.py --minify /tmp/eh_frame.min mm/vmscan.o
--- scripts/eh_frame_min.py | 961 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 961 insertions(+) create mode 100755 scripts/eh_frame_min.py
scripts/eh_frame_min.py new file +961 -0
@@ -0,0 +1,961 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +""" +Offline ELF .eh_frame / Minimal DWARF CFA coverage and size analyzer. + +Note: This script is a standalone developer/benchmarking inspection tool and +is NOT invoked during Kbuild (which uses the standalone C host tool in +scripts/min_eh_frame.c when CONFIG_UNWINDER_DWARF_CFI_MINIFY=y). + +It parses ELF32/ELF64 relocatable objects (.o, .ko), vmlinux images, user +executables, and shared libraries across x86_64, i386, arm64, arm, and riscv, +reporting: + - .text, .eh_frame, .eh_frame_hdr, .sframe, and .orc_unwind section sizes + - Simulated minified .eh_frame + .eh_frame_hdr sizes and byte savings + - Minimal DWARF CFA FDE coverage (supported vs. unsupported FDEs & reasons) + - Kept FP/RA register rules vs. ignored general-purpose register spill ops + - Maximum DW_CFA_remember_state nesting depth and top DWARF CFA opcodes + +Example usage (from the kernel tree root, invoke via ./scripts/eh_frame_min*): + 1. Analyze a built vmlinux image (with or without build-time minification): + $ eh_frame_min.py vmlinux + + 2. Compare multiple kernel objects, loadable modules, or cross-arch builds: + $ eh_frame_min.py mm/vmscan.o kernel/fork.o fs/ext4/inode.o + $ eh_frame_min.py build_arm64/vmlinux build_riscv/vmlinux + + 3. Analyze existing user-space binaries and shared libraries: + $ eh_frame_min.py /bin/bash /lib/x86_64-linux-gnu/libc.so.6 + + 4. Emit a standalone minified .eh_frame section blob for differential tests: + $ eh_frame_min.py --minify /tmp/eh_frame.min mm/vmscan.o + +Example output: + === build_arm64/vmlinux (arm64) === + .text size : 18,500,228 B + Original .eh_frame : 2,294,092 B (1 CIEs, 69,765 FDEs) + Original .eh_frame_hdr : 558,132 B (combined: 2,852,224 B) + Minified .eh_frame : 2,285,920 B (1 CIEs, -0.4% vs .eh_frame) + Minified + .eh_frame_hdr: 2,844,052 B (-0.3% combined) + FDE bytecode payload : 1,108,067 B -> 953,348 B (avg 13.7 B/FDE) + .sframe section : 2,938,460 B + Minimal DWARF coverage : 69,765 / 69,765 FDEs (100.00%) + Register ops kept/skip : 125,630 kept (FP/RA), 0 ignored (other GPRs/args) + Max remember_state depth: 1 +""" + +import argparse +import os +import struct +import sys +from collections import Counter + +# DWARF register numbers per ELF e_machine (drap = transient stack-realign scratch regs) +ARCH_REGS = { + 62: {"name": "x86_64", "sp": 7, "fp": 6, "ra": 16, "drap": {1, 2, 5, 10, 13}}, # EM_X86_64 + 3: {"name": "i386", "sp": 4, "fp": 5, "ra": 8, "drap": {1, 7}}, # EM_386 (%ecx, %edi) + 40: {"name": "arm", "sp": 13, "fp": 11, "ra": 14, "drap": set()}, # EM_ARM + 183: {"name": "arm64", "sp": 31, "fp": 29, "ra": 30, "drap": set()}, # EM_AARCH64 + 243: {"name": "riscv", "sp": 2, "fp": 8, "ra": 1, "drap": set()}, # EM_RISCV +} + +DW_CFA_nop = 0x00 +DW_CFA_set_loc = 0x01 +DW_CFA_advance_loc1 = 0x02 +DW_CFA_advance_loc2 = 0x03 +DW_CFA_advance_loc4 = 0x04 +DW_CFA_offset_extended = 0x05 +DW_CFA_restore_extended = 0x06 +DW_CFA_undefined = 0x07 +DW_CFA_same_value = 0x08 +DW_CFA_register = 0x09 +DW_CFA_remember_state = 0x0a +DW_CFA_restore_state = 0x0b +DW_CFA_def_cfa = 0x0c +DW_CFA_def_cfa_register = 0x0d +DW_CFA_def_cfa_offset = 0x0e +DW_CFA_def_cfa_expression = 0x0f +DW_CFA_expression = 0x10 +DW_CFA_offset_extended_sf = 0x11 +DW_CFA_def_cfa_sf = 0x12 +DW_CFA_def_cfa_offset_sf = 0x13 +DW_CFA_val_offset = 0x14 +DW_CFA_val_offset_sf = 0x15 +DW_CFA_val_expression = 0x16 +DW_CFA_AARCH64_negate_ra_state = 0x2d +DW_CFA_GNU_args_size = 0x2e +DW_CFA_GNU_negative_offset_extended = 0x2f + +OPCODE_NAMES = { + 0x00: "DW_CFA_nop", + 0x01: "DW_CFA_set_loc", + 0x02: "DW_CFA_advance_loc1", + 0x03: "DW_CFA_advance_loc2", + 0x04: "DW_CFA_advance_loc4", + 0x05: "DW_CFA_offset_extended", + 0x06: "DW_CFA_restore_extended", + 0x07: "DW_CFA_undefined", + 0x08: "DW_CFA_same_value", + 0x09: "DW_CFA_register", + 0x0a: "DW_CFA_remember_state", + 0x0b: "DW_CFA_restore_state", + 0x0c: "DW_CFA_def_cfa", + 0x0d: "DW_CFA_def_cfa_register", + 0x0e: "DW_CFA_def_cfa_offset", + 0x0f: "DW_CFA_def_cfa_expression", + 0x10: "DW_CFA_expression", + 0x11: "DW_CFA_offset_extended_sf", + 0x12: "DW_CFA_def_cfa_sf", + 0x13: "DW_CFA_def_cfa_offset_sf", + 0x14: "DW_CFA_val_offset", + 0x15: "DW_CFA_val_offset_sf", + 0x16: "DW_CFA_val_expression", + 0x2d: "DW_CFA_negate_ra_state/window_save", + 0x2e: "DW_CFA_GNU_args_size", + 0x2f: "DW_CFA_GNU_negative_offset_extended", +} + +DW_EH_PE_omit = 0xff +DW_EH_PE_absptr = 0x00 +DW_EH_PE_uleb128 = 0x01 +DW_EH_PE_udata2 = 0x02 +DW_EH_PE_udata4 = 0x03 +DW_EH_PE_udata8 = 0x04 +DW_EH_PE_sleb128 = 0x09 +DW_EH_PE_sdata2 = 0x0a +DW_EH_PE_sdata4 = 0x0b +DW_EH_PE_sdata8 = 0x0c +DW_EH_PE_pcrel = 0x10 +DW_EH_PE_indirect = 0x80 + + +def read_uleb128(buf, pos, end): + val = 0 + shift = 0 + while pos < end: + b = buf[pos] + pos += 1 + val |= (b & 0x7f) << shift + if not (b & 0x80): + return val, pos + shift += 7 + if shift > 63: + raise ValueError("ULEB128 overflow") + raise ValueError("Truncated ULEB128") + + +def read_sleb128(buf, pos, end): + val = 0 + shift = 0 + while pos < end: + b = buf[pos] + pos += 1 + val |= (b & 0x7f) << shift + shift += 7 + if not (b & 0x80): + if b & 0x40: + val |= -(1 << shift) + return val, pos + if shift > 63: + raise ValueError("SLEB128 overflow") + raise ValueError("Truncated SLEB128") + + +def encode_uleb128(val): + if val < 0: + raise ValueError("Negative ULEB128") + out = bytearray() + while True: + b = val & 0x7f + val >>= 7 + if val: + b |= 0x80 + out.append(b) + if not val: + break + return bytes(out) + + +def encode_sleb128(val): + out = bytearray() + more = True + while more: + b = val & 0x7f + val >>= 7 + if (val == 0 and not (b & 0x40)) or (val == -1 and (b & 0x40)): + more = False + else: + b |= 0x80 + out.append(b) + return bytes(out) + + +def encoded_ptr_size(enc, addr_size): + if enc == DW_EH_PE_omit: + return 0 + fmt = enc & 0x0f + if fmt == DW_EH_PE_absptr: + return addr_size + if fmt in (DW_EH_PE_udata2, DW_EH_PE_sdata2): + return 2 + if fmt in (DW_EH_PE_udata4, DW_EH_PE_sdata4): + return 4 + if fmt in (DW_EH_PE_udata8, DW_EH_PE_sdata8): + return 8 + return None + + +def read_encoded_ptr(buf, pos, end, enc, addr_size, sec_vaddr): + if enc == DW_EH_PE_omit: + return 0, pos + orig_pos = pos + fmt = enc & 0x0f + if fmt == DW_EH_PE_absptr: + fmt_str = "<Q" if addr_size == 8 else "<I" + val = struct.unpack_from(fmt_str, buf, pos)[0] + pos += addr_size + elif fmt == DW_EH_PE_udata2: + val = struct.unpack_from("<H", buf, pos)[0] + pos += 2 + elif fmt == DW_EH_PE_sdata2: + val = struct.unpack_from("<h", buf, pos)[0] + pos += 2 + elif fmt == DW_EH_PE_udata4: + val = struct.unpack_from("<I", buf, pos)[0] + pos += 4 + elif fmt == DW_EH_PE_sdata4: + val = struct.unpack_from("<i", buf, pos)[0] + pos += 4 + elif fmt == DW_EH_PE_udata8: + val = struct.unpack_from("<Q", buf, pos)[0] + pos += 8 + elif fmt == DW_EH_PE_sdata8: + val = struct.unpack_from("<q", buf, pos)[0] + pos += 8 + elif fmt == DW_EH_PE_uleb128: + val, pos = read_uleb128(buf, pos, end) + elif fmt == DW_EH_PE_sleb128: + val, pos = read_sleb128(buf, pos, end) + else: + raise ValueError(f"Unsupported pointer format 0x{enc:02x}") + + adj = enc & 0x70 + if adj == DW_EH_PE_pcrel: + val = (sec_vaddr + orig_pos + val) & ((1 << (addr_size * 8)) - 1) + elif adj != 0x00: + raise ValueError(f"Unsupported pointer adjustment 0x{enc:02x}") + return val, pos + + +def parse_elf_sections(data): + if data[:4] != b"\x7fELF": + raise ValueError("Not an ELF file") + ei_class = data[4] + ei_data = data[5] + if ei_data != 1: + raise ValueError("Only little-endian ELF supported") + if ei_class == 2: + addr_size = 8 + _, e_machine, _, _, _, e_shoff, _, _, _, _, e_shentsize, e_shnum, e_shstrndx = ( + struct.unpack_from("<HHIQQQIHHHHHH", data, 16) + ) + sh_fmt = "<IIQQQQIIQQ" + elif ei_class == 1: + addr_size = 4 + _, e_machine, _, _, _, e_shoff, _, _, _, _, e_shentsize, e_shnum, e_shstrndx = ( + struct.unpack_from("<HHIIIIIHHHHHH", data, 16) + ) + sh_fmt = "<IIIIIIIIII" + else: + raise ValueError(f"Unknown ELF class {ei_class}") + + sections = {} + if e_shoff == 0: + raise ValueError("ELF has no section headers") + + if e_shnum == 0 or e_shstrndx == 0xffff: + sh0 = struct.unpack_from(sh_fmt, data, e_shoff) + if e_shnum == 0: + e_shnum = sh0[5] + if e_shstrndx == 0xffff: + e_shstrndx = sh0[6] + + if e_shnum == 0 or e_shstrndx >= e_shnum: + raise ValueError("ELF has invalid section header counts") + + shdrs = [] + for i in range(e_shnum): + off = e_shoff + i * e_shentsize + shdrs.append(struct.unpack_from(sh_fmt, data, off)) + + shstr_off = shdrs[e_shstrndx][4] + shstr_sz = shdrs[e_shstrndx][5] + shstrtab = data[shstr_off : shstr_off + shstr_sz] + + for sh in shdrs: + sh_name_idx = sh[0] + sh_type = sh[1] + sh_addr = sh[3] + sh_offset = sh[4] + sh_size = sh[5] + end_idx = shstrtab.find(b"\x00", sh_name_idx) + name = shstrtab[sh_name_idx:end_idx].decode("utf-8", errors="replace") + # SHT_NOBITS == 8 + sec_bytes = b"" if sh_type == 8 else data[sh_offset : sh_offset + sh_size] + if name in sections: + # Accumulate sizes for multi-section objects (e.g. .text.*) + prev_addr, prev_sz, prev_b = sections[name] + sections[name] = (prev_addr, prev_sz + sh_size, prev_b) + else: + sections[name] = (sh_addr, sh_size, sec_bytes) + + return e_machine, addr_size, sections + + +def parse_cie(buf, entry_off, body_off, entry_end, addr_size, sec_vaddr): + pos = body_off + version = buf[pos] + pos += 1 + nul = buf.find(b"\x00", pos, entry_end) + if nul < 0: + raise ValueError("Unterminated CIE augmentation string") + aug = buf[pos:nul].decode("ascii", errors="replace") + pos = nul + 1 + + if version == 4: + addr_size = buf[pos] + seg_size = buf[pos + 1] + pos += 2 + if seg_size != 0: + raise ValueError("Non-zero segment selector size") + + code_align, pos = read_uleb128(buf, pos, entry_end) + data_align, pos = read_sleb128(buf, pos, entry_end) + if version == 1: + ra_reg = buf[pos] + pos += 1 + else: + ra_reg, pos = read_uleb128(buf, pos, entry_end) + + fde_enc = DW_EH_PE_absptr + lsda_enc = DW_EH_PE_omit + has_z = False + is_signal = False + + if aug.startswith("z"): + has_z = True + aug_len, pos = read_uleb128(buf, pos, entry_end) + aug_end = pos + aug_len + ap = pos + for ch in aug[1:]: + if ch == "L": + lsda_enc = buf[ap] + ap += 1 + elif ch == "P": + p_enc = buf[ap] + ap += 1 + _, ap = read_encoded_ptr(buf, ap, aug_end, p_enc & ~DW_EH_PE_indirect, addr_size, sec_vaddr) + elif ch == "R": + fde_enc = buf[ap] + ap += 1 + elif ch == "S": + is_signal = True + elif ch == "B": + # BTI / PAC key on arm64 + pass + else: + raise ValueError(f"Unknown CIE augmentation '{ch}' in '{aug}'") + pos = aug_end + elif aug != "": + raise ValueError(f"Unsupported non-z CIE augmentation '{aug}'") + + return { + "offset": entry_off, + "version": version, + "aug": aug, + "addr_size": addr_size, + "code_align": code_align, + "data_align": data_align, + "ra_reg": ra_reg, + "fde_enc": fde_enc, + "lsda_enc": lsda_enc, + "has_z": has_z, + "is_signal": is_signal, + "has_indirect_fde": bool(fde_enc & DW_EH_PE_indirect), + "insns": bytes(buf[pos:entry_end]), + } + + +def decode_and_minify_insns(insns, cie, arch, init_row=None, is_cie=False): + """ + Decode CFI instructions, validate against Minimal DWARF subset, and emit + minified instructions keeping only PC advances and {CFA(SP|FP), SP, FP, RA}. + """ + sp_reg = arch["sp"] + fp_reg = arch["fp"] + ra_reg = cie["ra_reg"] + tracked_regs = {sp_reg, fp_reg, ra_reg} + + def reg_key(reg): + if reg == fp_reg: + return "fp" + if reg == ra_reg: + return "ra" + return "sp" + + pos = 0 + end = len(insns) + op_counts = Counter() + ignored_reg_ops = 0 + kept_reg_ops = 0 + max_state_depth = 0 + reasons = [] + + if init_row is None: + row = { + "cfa_reg": None, + "cfa_off": 0, + "sp": ("same", 0), + "fp": ("same", 0), + "ra": ("same", 0), + "ra_signed": False, + } + else: + row = dict(init_row) + + cie_base_row = dict(row) + state_stack = [] + + # Stream of abstract events: ("adv", delta_units) or ("op", raw_bytes) + events = [] + pending_adv = 0 + + def emit_op(raw_bytes): + nonlocal pending_adv + if pending_adv > 0 and not is_cie: + events.append(("adv", pending_adv)) + pending_adv = 0 + events.append(("op", raw_bytes)) + + try: + while pos < end: + op = insns[pos] + pos += 1 + hi = op & 0xc0 + lo = op & 0x3f + + if hi == 0x40: + op_counts["DW_CFA_advance_loc"] += 1 + pending_adv += lo + continue + if hi == 0x80: + op_counts["DW_CFA_offset"] += 1 + reg = lo + uoff, pos = read_uleb128(insns, pos, end) + off = uoff * cie["data_align"] + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + if row[key] != ("off", off): + row[key] = ("off", off) + emit_op(bytes([0x80 | reg]) + encode_uleb128(uoff)) + else: + ignored_reg_ops += 1 + continue + if hi == 0xc0: + op_counts["DW_CFA_restore"] += 1 + reg = lo + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + if row[key] != cie_base_row[key]: + row[key] = cie_base_row[key] + emit_op(bytes([0xc0 | reg])) + else: + ignored_reg_ops += 1 + continue + + name = OPCODE_NAMES.get(op, f"DW_CFA_unknown_0x{op:02x}") + op_counts[name] += 1 + + if op == DW_CFA_nop: + continue + elif op == DW_CFA_advance_loc1: + if pos + 1 > end: + raise ValueError("Truncated advance_loc1") + pending_adv += insns[pos] + pos += 1 + elif op == DW_CFA_advance_loc2: + pending_adv += struct.unpack_from("<H", insns, pos)[0] + pos += 2 + elif op == DW_CFA_advance_loc4: + pending_adv += struct.unpack_from("<I", insns, pos)[0] + pos += 4 + elif op == DW_CFA_def_cfa: + reg, pos = read_uleb128(insns, pos, end) + uoff, pos = read_uleb128(insns, pos, end) + if reg not in (sp_reg, fp_reg) and reg not in arch["drap"]: + reasons.append(f"def_cfa non-SP/FP reg={reg}") + if row["cfa_reg"] != reg or row["cfa_off"] != uoff: + row["cfa_reg"] = reg + row["cfa_off"] = uoff + emit_op(bytes([DW_CFA_def_cfa]) + encode_uleb128(reg) + encode_uleb128(uoff)) + elif op == DW_CFA_def_cfa_sf: + reg, pos = read_uleb128(insns, pos, end) + soff, pos = read_sleb128(insns, pos, end) + off = soff * cie["data_align"] + if reg not in (sp_reg, fp_reg) and reg not in arch["drap"]: + reasons.append(f"def_cfa_sf non-SP/FP reg={reg}") + if row["cfa_reg"] != reg or row["cfa_off"] != off: + row["cfa_reg"] = reg + row["cfa_off"] = off + emit_op(bytes([DW_CFA_def_cfa_sf]) + encode_uleb128(reg) + encode_sleb128(soff)) + elif op == DW_CFA_def_cfa_register: + reg, pos = read_uleb128(insns, pos, end) + if not isinstance(row["cfa_reg"], int): + reasons.append("def_cfa_register without reg+off CFA") + if reg not in (sp_reg, fp_reg) and reg not in arch["drap"]: + reasons.append(f"def_cfa_register non-SP/FP reg={reg}") + if row["cfa_reg"] != reg: + row["cfa_reg"] = reg + emit_op(bytes([DW_CFA_def_cfa_register]) + encode_uleb128(reg)) + elif op == DW_CFA_def_cfa_offset: + uoff, pos = read_uleb128(insns, pos, end) + if not isinstance(row["cfa_reg"], int): + reasons.append("def_cfa_offset without reg+off CFA") + if row["cfa_off"] != uoff: + row["cfa_off"] = uoff + emit_op(bytes([DW_CFA_def_cfa_offset]) + encode_uleb128(uoff)) + elif op == DW_CFA_def_cfa_offset_sf: + soff, pos = read_sleb128(insns, pos, end) + off = soff * cie["data_align"] + if not isinstance(row["cfa_reg"], int): + reasons.append("def_cfa_offset_sf without reg+off CFA") + if row["cfa_off"] != off: + row["cfa_off"] = off + emit_op(bytes([DW_CFA_def_cfa_offset_sf]) + encode_sleb128(soff)) + elif op == DW_CFA_offset_extended: + reg, pos = read_uleb128(insns, pos, end) + uoff, pos = read_uleb128(insns, pos, end) + off = uoff * cie["data_align"] + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + if row[key] != ("off", off): + row[key] = ("off", off) + raw = (bytes([0x80 | reg]) + encode_uleb128(uoff) if reg < 64 + else bytes([DW_CFA_offset_extended]) + encode_uleb128(reg) + encode_uleb128(uoff)) + emit_op(raw) + else: + ignored_reg_ops += 1 + elif op == DW_CFA_offset_extended_sf: + reg, pos = read_uleb128(insns, pos, end) + soff, pos = read_sleb128(insns, pos, end) + off = soff * cie["data_align"] + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + if row[key] != ("off", off): + row[key] = ("off", off) + emit_op(bytes([DW_CFA_offset_extended_sf]) + encode_uleb128(reg) + encode_sleb128(soff)) + else: + ignored_reg_ops += 1 + elif op == DW_CFA_GNU_negative_offset_extended: + reg, pos = read_uleb128(insns, pos, end) + uoff, pos = read_uleb128(insns, pos, end) + off = -uoff * cie["data_align"] + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + if row[key] != ("off", off): + row[key] = ("off", off) + emit_op(bytes([DW_CFA_GNU_negative_offset_extended]) + + encode_uleb128(reg) + encode_uleb128(uoff)) + else: + ignored_reg_ops += 1 + elif op == DW_CFA_restore_extended: + reg, pos = read_uleb128(insns, pos, end) + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + if row[key] != cie_base_row[key]: + row[key] = cie_base_row[key] + raw = bytes([0xc0 | reg]) if reg < 64 else bytes([DW_CFA_restore_extended]) + encode_uleb128(reg) + emit_op(raw) + else: + ignored_reg_ops += 1 + elif op == DW_CFA_undefined: + reg, pos = read_uleb128(insns, pos, end) + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + row[key] = ("undef", 0) + emit_op(bytes([DW_CFA_undefined]) + encode_uleb128(reg)) + else: + ignored_reg_ops += 1 + elif op == DW_CFA_same_value: + reg, pos = read_uleb128(insns, pos, end) + if reg in tracked_regs: + kept_reg_ops += 1 + key = reg_key(reg) + row[key] = ("same", 0) + emit_op(bytes([DW_CFA_same_value]) + encode_uleb128(reg)) + else: + ignored_reg_ops += 1 + elif op == DW_CFA_remember_state: + emit_op(bytes([DW_CFA_remember_state])) + state_stack.append((dict(row), len(events) - 1)) + max_state_depth = max(max_state_depth, len(state_stack)) + if len(state_stack) > 4: + reasons.append(f"remember_state depth={len(state_stack)} > 4") + elif op == DW_CFA_restore_state: + if not state_stack: + reasons.append("unmatched restore_state") + else: + saved_row, rem_idx = state_stack.pop() + if saved_row != row: + row = saved_row + emit_op(bytes([DW_CFA_restore_state])) + else: + # Nothing in {CFA, SP, FP, RA} changed inside remember/restore! + # If remember_state is only followed by adv, elide the pair. + elided = False + if rem_idx < len(events) and events[rem_idx] == ("op", bytes([DW_CFA_remember_state])): + if all(ev[0] == "adv" for ev in events[rem_idx + 1:]): + extra_adv = sum(ev[1] for ev in events[rem_idx + 1:]) + del events[rem_idx:] + pending_adv += extra_adv + elided = True + if not elided: + emit_op(bytes([DW_CFA_restore_state])) + elif op == DW_CFA_GNU_args_size: + _, pos = read_uleb128(insns, pos, end) + ignored_reg_ops += 1 + elif op == DW_CFA_AARCH64_negate_ra_state and arch["name"] == "arm64": + row["ra_signed"] = not row["ra_signed"] + emit_op(bytes([DW_CFA_AARCH64_negate_ra_state])) + elif op == DW_CFA_def_cfa_expression: + expr_len, pos = read_uleb128(insns, pos, end) + if pos + expr_len > end: + raise ValueError("Truncated def_cfa_expression") + expr = insns[pos : pos + expr_len] + pos += expr_len + # Fixed DRAP / sigframe pattern: DW_OP_breg(FP|SP) <sleb128>, DW_OP_deref + if (len(expr) >= 3 and expr[-1] == 0x06 and + expr[0] in (0x70 + fp_reg, 0x70 + sp_reg)): + try: + soff, epos = read_sleb128(expr, 1, len(expr) - 1) + except ValueError: + epos = -1 + if epos == len(expr) - 1: + kind = "fp_indirect" if expr[0] == (0x70 + fp_reg) else "sp_indirect" + row["cfa_reg"] = (kind,) + row["cfa_off"] = soff + emit_op(bytes([DW_CFA_def_cfa_expression]) + encode_uleb128(len(expr)) + expr) + continue + reasons.append(name) + elif op in (DW_CFA_expression, DW_CFA_val_expression): + reg, pos = read_uleb128(insns, pos, end) + expr_len, pos = read_uleb128(insns, pos, end) + if pos + expr_len > end: + raise ValueError("Truncated register expression") + expr = insns[pos : pos + expr_len] + pos += expr_len + if reg == sp_reg: + if (op == DW_CFA_expression and len(expr) >= 2 and + expr[0] == (0x70 + sp_reg) and row["cfa_reg"] == ("sp_indirect",)): + try: + soff, epos = read_sleb128(expr, 1, len(expr)) + except ValueError: + epos = -1 + if epos == len(expr) and soff == row["cfa_off"]: + ignored_reg_ops += 1 + continue + reasons.append(f"{name} r{reg}") + continue + if reg not in tracked_regs: + ignored_reg_ops += 1 + continue + # Fixed DRAP / sigframe save pattern: DW_CFA_expression(FP|RA, DW_OP_breg(FP|SP) <sleb128>) + if (op == DW_CFA_expression and len(expr) >= 2 and + expr[0] in (0x70 + fp_reg, 0x70 + sp_reg)): + try: + soff, epos = read_sleb128(expr, 1, len(expr)) + except ValueError: + epos = -1 + if epos == len(expr) and (reg == fp_reg or expr[0] == (0x70 + sp_reg)): + kept_reg_ops += 1 + rule = "fp_off" if expr[0] == (0x70 + fp_reg) else "sp_off" + row["fp" if reg == fp_reg else "ra"] = (rule, soff) + emit_op(bytes([DW_CFA_expression]) + encode_uleb128(reg) + + encode_uleb128(len(expr)) + expr) + continue + reasons.append(f"{name} r{reg}") + elif op == DW_CFA_register: + r1, pos = read_uleb128(insns, pos, end) + r2, pos = read_uleb128(insns, pos, end) + if r1 in tracked_regs: + reasons.append(f"DW_CFA_register r{r1}->r{r2}") + else: + ignored_reg_ops += 1 + elif op == DW_CFA_val_offset: + r1, pos = read_uleb128(insns, pos, end) + _, pos = read_uleb128(insns, pos, end) + if r1 in tracked_regs: + reasons.append(f"DW_CFA_val_offset r{r1}") + else: + ignored_reg_ops += 1 + elif op == DW_CFA_val_offset_sf: + r1, pos = read_uleb128(insns, pos, end) + _, pos = read_sleb128(insns, pos, end) + if r1 in tracked_regs: + reasons.append(f"DW_CFA_val_offset_sf r{r1}") + else: + ignored_reg_ops += 1 + elif op == DW_CFA_set_loc: + _, pos = read_encoded_ptr(insns, pos, end, cie["fde_enc"], cie["addr_size"], 0) + reasons.append("DW_CFA_set_loc") + else: + reasons.append(name) + break + except (ValueError, struct.error, IndexError) as exc: + reasons.append(f"malformed_bytecode({exc})") + + # Coalesce consecutive ("adv", d) events and drop trailing ("adv", d) + while events and events[-1][0] == "adv": + events.pop() + + min_bytes = bytearray() + acc_adv = 0 + for kind, payload in events: + if kind == "adv": + acc_adv += payload + else: + if acc_adv > 0: + if acc_adv <= 0x3f: + min_bytes.append(0x40 | acc_adv) + elif acc_adv <= 0xff: + min_bytes.extend([DW_CFA_advance_loc1, acc_adv]) + elif acc_adv <= 0xffff: + min_bytes.append(DW_CFA_advance_loc2) + min_bytes.extend(struct.pack("<H", acc_adv)) + else: + min_bytes.append(DW_CFA_advance_loc4) + min_bytes.extend(struct.pack("<I", acc_adv)) + acc_adv = 0 + min_bytes.extend(payload) + + return { + "row": row, + "min_insns": bytes(min_bytes), + "op_counts": op_counts, + "ignored_reg_ops": ignored_reg_ops, + "kept_reg_ops": kept_reg_ops, + "max_state_depth": max_state_depth, + "unsupported_reasons": reasons, + } + + +def build_minimal_cie_bytes(cie, min_cie_insns, align=4): + aug = b"zRS\x00" if cie["is_signal"] else b"zR\x00" + fde_enc = DW_EH_PE_pcrel | DW_EH_PE_sdata4 + body = bytearray() + body.append(1) # CIE version 1 + body.extend(aug) + body.extend(encode_uleb128(cie["code_align"])) + body.extend(encode_sleb128(cie["data_align"])) + body.append(cie["ra_reg"]) + body.append(1) # augmentation data length = 1 ('R') + body.append(fde_enc) + body.extend(min_cie_insns) + # Total record is 4 (length) + 4 (CIE_id=0) + len(body), pad to align + rem = (8 + len(body)) % align + if rem: + body.extend(b"\x00" * (align - rem)) + return struct.pack("<II", 4 + len(body), 0) + bytes(body) + + +def build_minimal_fde_bytes(min_fde_insns, cie_offset_from_here, init_loc_rel=0, pc_range=0, align=4): + body = bytearray() + body.extend(struct.pack("<iI", init_loc_rel, pc_range)) + body.append(0) # zR augmentation data length = 0 + body.extend(min_fde_insns) + rem = (8 + len(body)) % align + if rem: + body.extend(b"\x00" * (align - rem)) + return struct.pack("<II", 4 + len(body), cie_offset_from_here) + bytes(body) + + +def analyze_elf(path, out_min_path=None): + with open(path, "rb") as f: + data = f.read() + + e_machine, addr_size, sections = parse_elf_sections(data) + if e_machine not in ARCH_REGS: + raise ValueError(f"Unsupported ELF e_machine={e_machine}") + arch = ARCH_REGS[e_machine] + + if ".eh_frame" not in sections: + print(f"{path}: no .eh_frame section found") + return + + eh_vaddr, eh_size, eh_buf = sections[".eh_frame"] + eh_hdr_size = sections.get(".eh_frame_hdr", (0, 0, b""))[1] + sframe_size = sections.get(".sframe", (0, 0, b""))[1] + orc_size = (sections.get(".orc_unwind", (0, 0, b""))[1] + + sections.get(".orc_unwind_ip", (0, 0, b""))[1]) + text_size = sum(sz for name, (_, sz, _) in sections.items() if name.startswith(".text") or name in (".init.text", ".exit.text")) + + cies = {} + cie_init_rows = {} + min_eh_stream = bytearray() + min_cie_offsets = {} + + total_cies = 0 + total_fdes = 0 + supported_fdes = 0 + unsupported_fdes = 0 + unsupported_breakdown = Counter() + total_op_counts = Counter() + total_orig_insn_bytes = 0 + total_min_insn_bytes = 0 + total_ignored_ops = 0 + total_kept_ops = 0 + max_depth_seen = 0 + + pos = 0 + end = len(eh_buf) + while pos + 4 <= end: + length = struct.unpack_from("<I", eh_buf, pos)[0] + entry_off = pos + pos += 4 + if length == 0: + break + if length == 0xffffffff: + length = struct.unpack_from("<Q", eh_buf, pos)[0] + pos += 8 + entry_end = pos + length + cie_id = struct.unpack_from("<I", eh_buf, pos)[0] + + if cie_id == 0: + total_cies += 1 + cie = parse_cie(eh_buf, entry_off, pos + 4, entry_end, addr_size, eh_vaddr) + res = decode_and_minify_insns(cie["insns"], cie, arch, is_cie=True) + cie["unsupported_reasons"] = list(res["unsupported_reasons"]) + cies[entry_off] = cie + cie_init_rows[entry_off] = res["row"] + total_op_counts.update(res["op_counts"]) + + cie_key = (cie["code_align"], cie["data_align"], cie["ra_reg"], cie["is_signal"], res["min_insns"]) + if not cie["unsupported_reasons"] and not cie["has_indirect_fde"] and cie_key not in min_cie_offsets: + min_cie_offsets[cie_key] = len(min_eh_stream) + min_eh_stream.extend(build_minimal_cie_bytes(cie, res["min_insns"], align=4)) + cie["min_key"] = cie_key + else: + total_fdes += 1 + cie_off = pos - cie_id + cie = cies[cie_off] + fpos = pos + 4 + init_loc, fpos = read_encoded_ptr(eh_buf, fpos, entry_end, cie["fde_enc"], addr_size, eh_vaddr) + range_enc = (cie["fde_enc"] & 0x0f) & ~0x08 + pc_range, fpos = read_encoded_ptr(eh_buf, fpos, entry_end, range_enc, addr_size, 0) + if cie["has_z"]: + aug_len, fpos = read_uleb128(eh_buf, fpos, entry_end) + fpos += aug_len + fde_insns = eh_buf[fpos:entry_end] + total_orig_insn_bytes += len(fde_insns) + + res = decode_and_minify_insns(fde_insns, cie, arch, init_row=cie_init_rows[cie_off]) + total_op_counts.update(res["op_counts"]) + total_min_insn_bytes += len(res["min_insns"]) + total_ignored_ops += res["ignored_reg_ops"] + total_kept_ops += res["kept_reg_ops"] + max_depth_seen = max(max_depth_seen, res["max_state_depth"]) + + reasons = list(cie["unsupported_reasons"]) + list(res["unsupported_reasons"]) + if cie["has_indirect_fde"]: + reasons.append("indirect_fde_encoding") + + if not reasons: + supported_fdes += 1 + min_cie_off = min_cie_offsets[cie["min_key"]] + fde_id_pos = len(min_eh_stream) + 4 + init_rel = (init_loc - (eh_vaddr + len(min_eh_stream) + 8)) if eh_vaddr else 0 + if not (-0x80000000 <= init_rel <= 0x7fffffff): + init_rel = 0 + min_eh_stream.extend( + build_minimal_fde_bytes(res["min_insns"], fde_id_pos - min_cie_off, init_rel, pc_range, align=4) + ) + else: + unsupported_fdes += 1 + for r in set(reasons): + unsupported_breakdown[r] += 1 + + pos = entry_end + + min_eh_stream.extend(b"\x00\x00\x00\x00") # terminator + min_eh_hdr_size = 12 + supported_fdes * 8 + + if out_min_path: + with open(out_min_path, "wb") as outf: + outf.write(min_eh_stream) + + pct_cov = (100.0 * supported_fdes / total_fdes) if total_fdes else 100.0 + orig_total = eh_size + eh_hdr_size + min_total = len(min_eh_stream) + min_eh_hdr_size + eh_delta_pct = (100.0 * (len(min_eh_stream) / eh_size - 1.0)) if eh_size else 0.0 + + print(f"=== {path} ({arch['name']}) ===") + print(f" .text size : {text_size:10,d} B") + print(f" Original .eh_frame : {eh_size:10,d} B ({total_cies} CIEs, {total_fdes:,d} FDEs)") + if eh_hdr_size: + total_delta_pct = 100.0 * (min_total / orig_total - 1.0) + print(f" Original .eh_frame_hdr : {eh_hdr_size:10,d} B (combined: {orig_total:,d} B)") + print(f" Minified .eh_frame : {len(min_eh_stream):10,d} B ({len(min_cie_offsets)} CIEs, {eh_delta_pct:+.1f}% vs .eh_frame)") + print(f" Minified + .eh_frame_hdr: {min_total:10,d} B ({total_delta_pct:+.1f}% combined)") + else: + print(f" Minified .eh_frame : {len(min_eh_stream):10,d} B ({len(min_cie_offsets)} CIEs, {eh_delta_pct:+.1f}% vs .eh_frame)") + print(f" Simulated .eh_frame_hdr : {min_eh_hdr_size:10,d} B (linker-generated at final link)") + print(f" FDE bytecode payload : {total_orig_insn_bytes:10,d} B -> {total_min_insn_bytes:,d} B " + f"(avg {total_min_insn_bytes / max(supported_fdes, 1):.1f} B/FDE)") + if sframe_size: + print(f" .sframe section : {sframe_size:10,d} B") + if orc_size: + print(f" .orc_unwind + _ip : {orc_size:10,d} B") + print(f" Minimal DWARF coverage : {supported_fdes:,d} / {total_fdes:,d} FDEs ({pct_cov:.2f}%)") + print(f" Register ops kept/skip : {total_kept_ops:,d} kept (FP/RA), {total_ignored_ops:,d} ignored (other GPRs/args)") + print(f" Max remember_state depth: {max_depth_seen}") + if unsupported_breakdown: + print(" Unsupported FDE reasons :") + for r, cnt in unsupported_breakdown.most_common(): + print(f" - {r}: {cnt}") + print(" Top DWARF CFA opcodes :") + for op_name, cnt in total_op_counts.most_common(10): + print(f" - {op_name:34s}: {cnt:8,d}") + print() + + +def main(): + epilog = ( + "Examples:\n" + " %(prog)s vmlinux\n" + " %(prog)s mm/vmscan.o kernel/fork.o\n" + " %(prog)s /bin/bash /lib/x86_64-linux-gnu/libc.so.6\n" + " %(prog)s --minify /tmp/eh_frame.min mm/vmscan.o\n" + ) + ap = argparse.ArgumentParser( + description="Analyze ELF .eh_frame coverage and size for Minimal DWARF CFI", + epilog=epilog, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + ap.add_argument("files", nargs="+", help="ELF files (.o, .ko, vmlinux, DSO, executable) to analyze") + ap.add_argument("--minify", metavar="OUT", help="Write minified .eh_frame binary for the first file") + args = ap.parse_args() + + for idx, path in enumerate(args.files): + out_p = args.minify if idx == 0 else None + analyze_elf(path, out_min_path=out_p) + + +if __name__ == "__main__": + main()
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 21/30] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer
TL;DR: - eh_frame_min.py may misreport sizes for RISC-V relocatable objects (relocated advances unread), so savings and --minify output are wrong - FDE byte total counts unsupported FDEs, skewing…
Quoted 1 line
scripts: Add
eh_frame_min.py.eh_frame coverage and size analyzer
TL;DR:
- eh_frame_min.py may misreport sizes for RISC-V relocatable objects (relocated advances unread), so savings and --minify output are wrong
- FDE byte total counts unsupported FDEs, skewing the average
- Two comment nits
Quoted 3 lines
scripts/eh_frame_min.py new file +0
-0
[ ... ]
scripts/eh_frame_min.py line 307
Quoted 3 lines
scripts/eh_frame_min.py new file +3
-0+ if name in sections: + # Accumulate sizes for multi-section objects (e.g. .text.*) + prev_addr, prev_sz, prev_b = sections[name]
This isn't a bug, but this branch only runs when two section headers have the identical name. Per-function sections such as .text.foo and .text.bar have distinct names and never reach it; they are summed later in analyze_elf() by the name.startswith(".text") prefix check. Does the "(e.g. .text.*)" comment point at the right place?
[ ... ]
scripts/eh_frame_min.py line 365
Quoted 3 lines
scripts/eh_frame_min.py new file +3
-0+ elif ch == "B": + # BTI / PAC key on arm64 + pass
This isn't a bug, but 'B' in the AArch64 DWARF ABI only means that frames use the B key for return address signing. BTI has no CIE augmentation, so should "BTI" be dropped from this comment?
[ ... ]
scripts/eh_frame_min.py line 450
Quoted 4 lines
scripts/eh_frame_min.py new file +4
-0+ if hi == 0x40: + op_counts["DW_CFA_advance_loc"] += 1 + pending_adv += lo + continue
On RISC-V relocatable objects, are the DW_CFA_advance_loc and advance_loc1/2/4 bytes stored in .eh_frame the real PC deltas?
With linker relaxation, those deltas are filled in at link time from R_RISCV_SET6/SUB6 (and SET8/SUB8, SET16/SUB16, SET32/SUB32) relocation pairs, and the stored bytes are placeholders. The script never reads .rela.eh_frame.
arch/riscv/Makefile only adds -mno-relax through KBUILD_CFLAGS_MODULE and KBUILD_AFLAGS_MODULE, so objects such as the example mm/vmscan.o keep relaxation. The build-time minifier in this series handles this case in scripts/min_eh_frame.c:
* Buffered output event emitted by minify_insns(). Adjacent non-relocated
* PC-advance events are coalesced before serialization, whereas relocated
* DW_CFA_advance_loc* instructions (e.g. RISC-V R_RISCV_ADD/SUB pairs) are
* preserved verbatim ...
Here a relocated advance read as 0 leaves pending_adv at 0, so emit_op() flushes no "adv" event and the next kept rule is attached to the previous PC. For riscv .o inputs that makes the 'FDE bytecode payload ... -> N B' figure and the 'Minified .eh_frame' size understated, which overstates the savings percentage, and the --minify blob, documented as being for differential tests, is not equivalent to the input CFI.
Neither the commit message nor the docstring lists this as a limitation. Should the script read .rela.eh_frame and keep relocated advances verbatim, as min_eh_frame.c does, or refuse or flag ET_REL EM_RISCV inputs?
[ ... ]
Quoted 3 lines
scripts/eh_frame_min.py new file +3
-0+ res = decode_and_minify_insns(fde_insns, cie, arch, init_row=cie_init_rows[cie_off]) + total_op_counts.update(res["op_counts"]) + total_min_insn_bytes += len(res["min_insns"])
[ ... ]
Quoted 2 lines
scripts/eh_frame_min.py new file +2
-0+ if not reasons: + supported_fdes += 1
[ ... ]
scripts/eh_frame_min.py line 920
Quoted 2 lines
scripts/eh_frame_min.py new file +2
-0+ print(f" FDE bytecode payload : {total_orig_insn_bytes:10,d} B -> {total_min_insn_bytes:,d} B " + f"(avg {total_min_insn_bytes / max(supported_fdes, 1):.1f} B/FDE)")
Is total_min_insn_bytes computed over the same set of FDEs as supported_fdes?
total_min_insn_bytes is incremented for every FDE, before the "if not reasons:" check. Unsupported FDEs are never written to min_eh_stream, but their minified bytecode is still counted, and the average then divides by supported_fdes only.
For example, with 100 FDEs of which 50 are supported and 50 unsupported, each with 10 B of minified bytecode, total_min_insn_bytes is 1000 and supported_fdes is 50. The script prints "avg 20.0 B/FDE", while the emitted FDEs average 10 B and only 500 B of FDE bytecode is in the minified stream.
This is reachable with the listed inputs. The x86_64 .plt FDE in /bin/bash uses a DW_CFA_def_cfa_expression that ends in DW_OP_plus, not DW_OP_deref, so it is added to reasons and treated as unsupported, yet its earlier def_cfa_offset ops still add to total_min_insn_bytes.
Should total_min_insn_bytes be accumulated only inside the "if not reasons:" branch, or should the average divide by total_fdes and the line be labelled as covering all FDEs?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 22/30 tools headers: Add linux/kmsan-checks.h copy from the kernel sources
In reply to Ian RogersCopy include/linux/kmsan-checks.h to tools/include/linux/kmsan-checks.h so host tools in tools/ can compile kernel sources using kmsan_unpoison_memory() without referencing ../../include/linux directly, and register it in tools/perf/check-headers.sh.
--- tools/include/linux/kmsan-checks.h | 98 ++++++++++++++++++++++++++++++ tools/perf/check-headers.sh | 1 + 2 files changed, 99 insertions(+) create mode 100644 tools/include/linux/kmsan-checks.h
tools/include/linux/kmsan-checks.h new file +98 -0
@@ -0,0 +1,98 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* KMSAN checks to be used for one-off annotations in subsystems. +* +* Copyright (C) 2017-2022 Google LLC +* Author: Alexander Potapenko <[email protected]> +* +*/ + +#ifndef _LINUX_KMSAN_CHECKS_H +#define _LINUX_KMSAN_CHECKS_H + +#include <linux/types.h> + +#ifdef CONFIG_KMSAN + +/** +* kmsan_poison_memory() - Mark the memory range as uninitialized. +* @address: address to start with. +* @size: size of buffer to poison. +* @flags: GFP flags for allocations done by this function. +* +* Until other data is written to this range, KMSAN will treat it as +* uninitialized. Error reports for this memory will reference the call site of +* kmsan_poison_memory() as origin. +*/ +void kmsan_poison_memory (const void *address,size_t size,gfp_t flags); + +/** +* kmsan_unpoison_memory() - Mark the memory range as initialized. +* @address: address to start with. +* @size: size of buffer to unpoison. +* +* Until other data is written to this range, KMSAN will treat it as +* initialized. +*/ +void kmsan_unpoison_memory (const void *address,size_t size); + +/** +* kmsan_check_memory() - Check the memory range for being initialized. +* @address: address to start with. +* @size: size of buffer to check. +* +* If any piece of the given range is marked as uninitialized, KMSAN will report +* an error. +*/ +void kmsan_check_memory (const void *address,size_t size); + +/** +* kmsan_copy_to_user() - Notify KMSAN about a data transfer to userspace. +* @to: destination address in the userspace. +* @from: source address in the kernel. +* @to_copy: number of bytes to copy. +* @left: number of bytes not copied. +* +* If this is a real userspace data transfer, KMSAN checks the bytes that were +* actually copied to ensure there was no information leak. If @to belongs to +* the kernel space (which is possible for compat syscalls), KMSAN just copies +* the metadata. +*/ +void kmsan_copy_to_user (void __user *to,const void *from,size_t to_copy, +size_t left); + +/** +* kmsan_memmove() - Notify KMSAN about a data copy within kernel. +* @to: destination address in the kernel. +* @from: source address in the kernel. +* @size: number of bytes to copy. +* +* Invoked after non-instrumented version (e.g. implemented using assembly +* code) of memmove()/memcpy() is called, in order to copy KMSAN's metadata. +*/ +void kmsan_memmove (void *to,const void *from,size_t to_copy); + +#else + +static inline void kmsan_poison_memory (const void *address,size_t size, +gfp_t flags) +{ +} +static inline void kmsan_unpoison_memory (const void *address,size_t size) +{ +} +static inline void kmsan_check_memory (const void *address,size_t size) +{ +} +static inline void kmsan_copy_to_user (void __user *to,const void *from, +size_t to_copy,size_t left) +{ +} + +static inline void kmsan_memmove (void *to,const void *from,size_t to_copy) +{ +} + +#endif + +#endif /* _LINUX_KMSAN_CHECKS_H */
tools/perf/check-headers.sh +1 -0
@@ -28,6 +28,7 @@ declare -a FILES=( "include/vdso/unaligned.h" "include/linux/gfp_types.h" "include/linux/hash.h" + "include/linux/kmsan-checks.h" "include/linux/list-sort.h" "include/uapi/linux/hw_breakpoint.h" "arch/x86/include/asm/cpufeatures.h"
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 23/30 tools headers: Add linux/nospec.h copy from the kernel sources
In reply to Ian RogersCopy include/linux/nospec.h to tools/include/linux/nospec.h (using the standard /* ... */ header SPDX comment style), include <asm-generic/bitsperlong.h> in tools/include/linux/kernel.h for BITS_PER_LONG, and register linux/nospec.h in tools/perf/check-headers.sh.
--- tools/include/linux/kernel.h | 1 + tools/include/linux/nospec.h | 74 ++++++++++++++++++++++++++++++++++++ tools/perf/check-headers.sh | 1 + 3 files changed, 76 insertions(+) create mode 100644 tools/include/linux/nospec.h
tools/include/linux/kernel.h +1 -0
@@ -11,6 +11,7 @@#include <linux/panic.h> #include <endian.h> #include <byteswap.h> +#include <asm-generic/bitsperlong.h> #include <linux/container_of.h> #ifndef UINT_MAX
tools/include/linux/nospec.h new file +74 -0
74 lines not on this page · raw message
tools/perf/check-headers.sh +1 -0
@@ -193,6 +193,7 @@ check include/uapi/asm-generic/mman.h '-I "^#include <\(uapi/\)*asm-generic/mman check include/uapi/linux/mman.h '-I "^#include <\(uapi/\)*asm/mman.h>"' check include/linux/build_bug.h '-I "^#\(ifndef\|endif\)\( \/\/\)* static_assert$"' check include/linux/ctype.h '-I "isdigit("' +check include/linux/nospec.h '-I "^.*[S]PDX-License-Identifier:"' check lib/ctype.c '-I "^EXPORT_SYMBOL" -I "^#include <linux/export.h>" -B' # diff non-symmetric files
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 24/30 tools headers: Add linux/unwind_dwarf_cfi.h copy from the kernel sources
In reply to Ian RogersCopy include/linux/unwind_dwarf_cfi.h to tools/include/linux/unwind_dwarf_cfi.h for host unwinding verification tools under tools/, and add it to tools/perf/check-headers.sh.
--- tools/include/linux/unwind_dwarf_cfi.h | 181 +++++++++++++++++++++++++ tools/perf/check-headers.sh | 1 + 2 files changed, 182 insertions(+) create mode 100644 tools/include/linux/unwind_dwarf_cfi.h
tools/include/linux/unwind_dwarf_cfi.h new file +181 -0
@@ -0,0 +1,181 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _LINUX_UNWIND_DWARF_CFI_H +#define _LINUX_UNWIND_DWARF_CFI_H + +#include <linux/types.h> + +/* +* Minimal DWARF Call Frame Information (CFI) unwinder subset. +* +* Evaluates a strictly bounded, non-Turing-complete subset of .eh_frame and +* .eh_frame_hdr tables matching SFrame's stack-unwinding state model (plus +* fixed-pattern DRAP stack-realignment and signal-frame expressions): +* - Advances PC monotonically through a single FDE (no backward jumps) +* - Tracks CFA = (SP | FP | scratch) + cfa_off or *(FP/SP + cfa_off) +* - Tracks stack save offsets for SP, FP, and RA (ignoring callee-saved GPR +* spills) +* - Rejects general DWARF expressions, register-to-register rules on SP/FP/RA, +* and DW_EH_PE_indirect FDE/table pointer encodings (skipping CIE +* personality and LSDA fields without dereferencing). +*/ + +/* Hard safety bounds enforced on CIE/FDE lengths, offsets, and state stack */ +#define DWARF_CFI_MAX_CIE_LEN 128U +#define DWARF_CFI_MAX_FDE_LEN 4096U +#define DWARF_CFI_MAX_CIE_DELTA (64U * 1024U * 1024U) +#define DWARF_CFI_MAX_FDE_COUNT (4U * 1024U * 1024U) +#define DWARF_CFI_MAX_STATE_STACK 4U + +/** +* enum dwarf_cfi_base - Base register or addressing mode for computing the CFA +* @DWARF_CFI_BASE_UNDEFINED: CFA rule has not been established yet. +* @DWARF_CFI_BASE_SP: CFA = stack pointer + cfa_off. +* @DWARF_CFI_BASE_FP: CFA = frame pointer + cfa_off. +* @DWARF_CFI_BASE_FP_INDIRECT: DRAP stack realignment: CFA = *(FP + cfa_off). +* @DWARF_CFI_BASE_SP_INDIRECT: Signal trampoline frame: CFA = *(SP + cfa_off). +* @DWARF_CFI_BASE_REG: Transient prologue/epilogue scratch register: +* CFA = reg(cfa_reg) + cfa_off. +*/ +enum dwarf_cfi_base { +DWARF_CFI_BASE_UNDEFINED =0 , +DWARF_CFI_BASE_SP , +DWARF_CFI_BASE_FP , +DWARF_CFI_BASE_FP_INDIRECT , +DWARF_CFI_BASE_SP_INDIRECT , +DWARF_CFI_BASE_REG , +}; + +/** +* enum dwarf_cfi_rule - Recovery rule for caller's SP, FP, or return address +* @DWARF_CFI_RULE_SAME: Register retains its value from the current frame +* (or defaults to CFA for SP). +* @DWARF_CFI_RULE_OFFSET: Saved on the stack at *(CFA + off). +* @DWARF_CFI_RULE_FP_OFFSET: Saved relative to FP at *(FP + off) (DRAP frame). +* @DWARF_CFI_RULE_SP_OFFSET: Saved relative to SP at *(SP + off) (sigframe). +* @DWARF_CFI_RULE_UNDEFINED: Explicitly undefined (DW_CFA_undefined); marks +* the bottom of a stack (e.g. _start or clone). +*/ +enum dwarf_cfi_rule { +DWARF_CFI_RULE_SAME =0 , +DWARF_CFI_RULE_OFFSET , +DWARF_CFI_RULE_FP_OFFSET , +DWARF_CFI_RULE_SP_OFFSET , +DWARF_CFI_RULE_UNDEFINED , +}; + +/** +* struct dwarf_cfi_arch - Architecture DWARF register numbers and word size +* @ws: Target address/word size in bytes (4 or 8). +* @sp_reg: DWARF register number for the stack pointer. +* @fp_reg: DWARF register number for the frame pointer. +* @ra_reg: Default DWARF return-address column number. +*/ +struct dwarf_cfi_arch { +u8 ws; +u8 sp_reg; +u8 fp_reg; +u8 ra_reg; +}; + +/** +* struct dwarf_cfi_row - Evaluated Minimal DWARF unwind state at a target PC +* @cfa_off: Byte offset added to the CFA base register before or as the CFA. +* @sp_off: Byte offset used to load the saved SP when @sp_rule is an offset. +* @fp_off: Byte offset used to load the saved FP when @fp_rule is an offset. +* @ra_off: Byte offset used to load the saved RA when @ra_rule is an offset. +* @cfa_base: CFA computation mode (&enum dwarf_cfi_base). +* @cfa_reg: DWARF register number when @cfa_base is %DWARF_CFI_BASE_REG. +* @sp_rule: Recovery rule for the stack pointer (&enum dwarf_cfi_rule; +* %DWARF_CFI_RULE_SAME indicates caller SP equals CFA). +* @fp_rule: Recovery rule for the frame pointer (&enum dwarf_cfi_rule). +* @ra_rule: Recovery rule for the return address (&enum dwarf_cfi_rule). +* @signal: True if the CIE carries the 'S' signal/interrupt frame augmentation, +* indicating that the saved PC points directly to the interrupted +* instruction rather than after a call instruction. +* @ra_signed: True on AArch64 when DW_CFA_AARCH64_negate_ra_state indicates +* that the saved return address carries a PAC signature. +*/ +struct dwarf_cfi_row { +s32 cfa_off; +s32 sp_off; +s32 fp_off; +s32 ra_off; +u8 cfa_base; +u8 cfa_reg; +u8 sp_rule; +u8 fp_rule; +u8 ra_rule; +bool signal; +bool ra_signed; +}; + +/** +* struct eh_frame_hdr_entry - Binary-search index entry for an FDE +* @start_off: Signed 32-bit offset from the table base (or entry field) to the +* FDE's initial PC location. +* @fde_off: Signed 32-bit offset from the table base (or entry field) to the +* start of the FDE record in .eh_frame. +*/ +struct eh_frame_hdr_entry { +s32 start_off; +s32 fde_off; +}; + +#ifdef CONFIG_UNWIND_DWARF_CFI + +extern const u8 __start_eh_frame_hdr[]; +extern const u8 __stop_eh_frame_hdr[]; +extern const u8 __start_eh_frame[]; +extern const u8 __stop_eh_frame[]; + +int dwarf_cfi_eval_fde_kmem (const u8 *fde,const u8 *eh_start, +const u8 *eh_end,unsigned long pc, +const struct dwarf_cfi_arch *arch, +struct dwarf_cfi_row *out_row); + +int dwarf_cfi_unwind_eh_frame_hdr (const u8 *hdr,size_t hdr_size, +const u8 *eh_start,const u8 *eh_end, +unsigned long pc, +const struct dwarf_cfi_arch *arch, +struct dwarf_cfi_row *out_row); + +int dwarf_cfi_scan_eh_frame_kmem (const u8 *eh_start,size_t eh_size, +const struct dwarf_cfi_arch *arch, +unsigned long base_addr, +struct eh_frame_hdr_entry *entries, +unsigned int max_entries, +unsigned int *out_count); + +int dwarf_cfi_unwind_user_eh_frame_hdr (unsigned long hdr_uaddr, +size_t hdr_size,unsigned long pc, +const struct dwarf_cfi_arch *arch, +struct dwarf_cfi_row *out_row); + +#if defined(CONFIG_UNWINDER_DWARF_CFI ) && defined(CONFIG_MODULES ) +/** +* struct mod_dwarf_cfi_index - Sorted FDE lookup table for a loadable module +* @num_fdes: Number of sorted FDE index entries in @entries. +* @eh_frame: Pointer to the module's in-memory SHF_ALLOC .eh_frame section; +* also serves as the base address for @entries offsets. +* @eh_frame_size: Size in bytes of the module's .eh_frame section. +* @entries: Sorted binary-search table mapping PCs to module FDEs. +*/ +struct mod_dwarf_cfi_index { +unsigned int num_fdes; +const u8 *eh_frame; +size_t eh_frame_size; + struct eh_frame_hdr_entry entries[] __counted_by(num_fdes); +}; + +struct mod_dwarf_cfi_index *dwarf_cfi_mod_alloc (const void *eh_frame, +size_t eh_frame_size, +const struct dwarf_cfi_arch *arch); +void dwarf_cfi_mod_free_rcu (struct mod_dwarf_cfi_index *idx); +int dwarf_cfi_mod_eval (const struct mod_dwarf_cfi_index *idx,unsigned long ip, +const struct dwarf_cfi_arch *arch, +struct dwarf_cfi_row *out_row); +#endif + +#endif /* CONFIG_UNWIND_DWARF_CFI */ + +#endif /* _LINUX_UNWIND_DWARF_CFI_H */
tools/perf/check-headers.sh +1 -0
@@ -30,6 +30,7 @@ declare -a FILES=( "include/linux/hash.h" "include/linux/kmsan-checks.h" "include/linux/list-sort.h" + "include/linux/unwind_dwarf_cfi.h" "include/uapi/linux/hw_breakpoint.h" "arch/x86/include/asm/cpufeatures.h" "arch/x86/include/asm/inat_types.h"
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 25/30 tools include: Add linux/uaccess.h stub for userspace tools
In reply to Ian RogersAdd a minimal tools/include/linux/uaccess.h providing a no-op might_fault() stub so userspace tools under tools/ can compile shared kernel code that includes <linux/uaccess.h>.
--- tools/include/linux/uaccess.h | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 tools/include/linux/uaccess.h
tools/include/linux/uaccess.h new file +9 -0
@@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _TOOLS_INCLUDE_LINUX_UACCESS_H +#define _TOOLS_INCLUDE_LINUX_UACCESS_H + +#ifndef might_fault +#define might_fault () do { } while (0) +#endif + +#endif /* _TOOLS_INCLUDE_LINUX_UACCESS_H */
Signature · 1 line
2.56.1.831.g720f3f5937-goog
Ian Rogers
reviewerRFC PATCH v2 26/30 tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier
In reply to Ian RogersAdd an optional standalone host verification tool (tools/unwind/verify_cfi, built via make -C tools/unwind or make tools/unwind when libLLVM is detected via tools/build/Makefile.feature, and gracefully skipped otherwise) linked directly against kernel/unwind/dwarf_cfi.c.
This initial commit implements the CLI harness, host VMA and kmem buffer wrappers (dwarf_cfi_host.c), and Oracle 1 (verifyOracle1Dwarf()), which evaluates libLLVM's full reference DWARFUnwindTable (llvm::dwarf::createUnwindTable) and verifies exact agreement with both dwarf_cfi_unwind_user_eh_frame_hdr() and dwarf_cfi_unwind_eh_frame_hdr() at every FDE start, row-transition boundary (pc - 1 and pc), and end PC.
Across 207,450 vmlinux FDEs (2,575,276 transition PCs) on x86_64, arm64, and riscv64, plus user-space shared libraries (libc.so.6, libstdc++.so.6, libcrypto.so.3, /bin/bash), Oracle 1 reports 0 mismatches.
--- tools/Makefile | 13 +- tools/unwind/.gitignore | 4 + tools/unwind/Makefile | 123 ++++++ tools/unwind/dwarf_cfi_host.c | 80 ++++ tools/unwind/dwarf_cfi_host.h | 42 ++ tools/unwind/verify_cfi.cpp | 789 ++++++++++++++++++++++++++++++++++ tools/unwind/verify_cfi.hpp | 147 +++++++ 7 files changed, 1192 insertions(+), 6 deletions(-) create mode 100644 tools/unwind/.gitignore create mode 100644 tools/unwind/Makefile create mode 100644 tools/unwind/dwarf_cfi_host.c create mode 100644 tools/unwind/dwarf_cfi_host.h create mode 100644 tools/unwind/verify_cfi.cpp create mode 100644 tools/unwind/verify_cfi.hpp
tools/Makefile +7 -6
@@ -37,6 +37,7 @@ help: @echo ' thermal - thermal library' @echo ' tracing - misc tracing tools' @echo ' turbostat - Intel CPU idle stats and freq reporting tool' + @echo ' unwind - Minimal DWARF CFI static verifier' @echo ' usb - USB testing tools' @echo ' virtio - vhost test module' @echo ' mm - misc mm tools'
@@ -70,7 +71,7 @@ acpi: FORCE cpupower: FORCE $(call descend,power/$@) -counter dma firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi firmware debugging tracing: FORCE +counter dma firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi firmware debugging tracing unwind: FORCE $(call descend,$@) bpf/%: FORCE
@@ -127,7 +128,7 @@ all: acpi counter cpupower dma gpio hv firewire \ perf selftests bootconfig spi turbostat usb \ virtio mm bpf x86_energy_perf_policy \ tmon freefall iio objtool kvm_stat wmi \ - debugging tracing thermal thermometer thermal-engine ynl + debugging tracing thermal thermometer thermal-engine unwind ynl acpi_install: $(call descend,power/$(@:_install=),install)
@@ -135,7 +136,7 @@ acpi_install: cpupower_install: $(call descend,power/$(@:_install=),install) -counter_install dma_install firewire_install gpio_install hv_install iio_install perf_install bootconfig_install spi_install usb_install virtio_install mm_install bpf_install objtool_install wmi_install debugging_install tracing_install: +counter_install dma_install firewire_install gpio_install hv_install iio_install perf_install bootconfig_install spi_install usb_install virtio_install mm_install bpf_install objtool_install wmi_install debugging_install tracing_install unwind_install: $(call descend,$(@:_install=),install) selftests_install:
@@ -171,7 +172,7 @@ install: acpi_install counter_install cpupower_install dma_install gpio_install virtio_install mm_install bpf_install x86_energy_perf_policy_install \ tmon_install freefall_install objtool_install kvm_stat_install \ wmi_install debugging_install intel-speed-select_install \ - tracing_install thermometer_install thermal-engine_install ynl_install + tracing_install thermometer_install thermal-engine_install unwind_install ynl_install acpi_clean: $(call descend,power/acpi,clean)
@@ -179,7 +180,7 @@ acpi_clean: cpupower_clean: $(call descend,power/cpupower,clean) -counter_clean dma_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean firmware_clean debugging_clean tracing_clean: +counter_clean dma_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean firmware_clean debugging_clean tracing_clean unwind_clean: $(call descend,$(@:_clean=),clean) libapi_clean:
@@ -231,6 +232,6 @@ clean: acpi_clean counter_clean cpupower_clean dma_clean hv_clean firewire_clean freefall_clean build_clean libbpf_clean libsubcmd_clean \ gpio_clean objtool_clean leds_clean wmi_clean firmware_clean debugging_clean \ intel-speed-select_clean tracing_clean thermal_clean thermometer_clean thermal-engine_clean \ - sched_ext_clean ynl_clean + sched_ext_clean unwind_clean ynl_clean .PHONY: FORCE
tools/unwind/.gitignore new file +4 -0
@@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +verify_cfi +FEATURE-DUMP* +feature/
tools/unwind/Makefile new file +123 -0
123 lines not on this page · raw message
tools/unwind/dwarf_cfi_host.c new file +80 -0
80 lines not on this page · raw message
tools/unwind/dwarf_cfi_host.h new file +42 -0
42 lines not on this page · raw message
tools/unwind/verify_cfi.cpp new file +789 -0
789 lines not on this page · raw message
tools/unwind/verify_cfi.hpp new file +147 -0
147 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 26/30] tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] tools/unwind: missing host arch include path breaks build on RISC-V hosts - [Low] tools/unwind…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] tools/unwind: missing host arch include path breaks build on RISC-V hosts
- [Low] tools/unwind: uint64_t overflow in verifyFile() kmem_arena bounds check
--
commit 8799e1737c7df626cec2cf3930d6a2c81661a407
Author: Ian Rogers <[email protected]>
tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier
This commit adds a standalone host tool (tools/unwind/verify_cfi) that links against kernel/unwind/dwarf_cfi.c and compares its unwind results against libLLVM's reference DWARFUnwindTable.
Quoted 6 lines
tools/unwind/Makefile new file +0
-0@@ -0,0 +1,123 @@
[ ... ]
tools/unwind/Makefile line 77
Quoted 2 lines
tools/unwind/Makefile new file +2
-0+TOOLS_INCLUDES := -I$(srctree)/tools/include -I$(srctree)/tools/include/uapi \ + -I$(srctree)/tools/arch/x86/include
[Severity: Medium]
Does hardcoding only tools/arch/x86/include in TOOLS_INCLUDES break the build on RISC-V hosts?
dwarf_cfi_host.c includes kernel/unwind/dwarf_cfi.c, which pulls in tools/include/linux/nospec.h -> tools/include/asm/barrier.h -> tools/arch/riscv/include/asm/barrier.h -> <asm/fence.h>. Without -I$(srctree)/tools/arch/$(HOSTARCH)/include (via ../scripts/Makefile.arch), the compiler cannot find tools/arch/riscv/include/asm/fence.h when building on riscv64.
Quoted 6 lines
tools/unwind/verify_cfi.cpp new file +0
-0@@ -0,0 +1,789 @@
[ ... ]
Quoted 2 lines
tools/unwind/verify_cfi.cpp new file +2
-0+static int verifyFile(const char *path, const VerifyOptions &opts) +{
[ ... ]
Quoted 8 lines
tools/unwind/verify_cfi.cpp new file +8
-0+ uint64_t min_eh_vma = std::min(eh_hdr_vma, eh_vma); + uint64_t max_eh_end = std::max(eh_hdr_vma + eh_hdr_bytes.size(), + eh_vma + eh_bytes.size()); + std::vector<uint8_t> kmem_arena; + bool can_test_kmem = + (max_eh_end >= min_eh_vma) && + (max_eh_end - min_eh_vma) <= (64ULL * 1024 * 1024) && + isRelativeEhEncoding((uint8_t)eh_hdr_bytes[1]) &&
tools/unwind/verify_cfi.cpp line 515
Quoted 10 lines
tools/unwind/verify_cfi.cpp new file +10
-0+ isRelativeEhEncoding((uint8_t)eh_hdr_bytes[3]); + const uint8_t *kmem_hdr = nullptr; + const uint8_t *kmem_eh_start = nullptr; + const uint8_t *kmem_eh_end = nullptr; + if (can_test_kmem) { + kmem_arena.assign(max_eh_end - min_eh_vma, 0); + memcpy(kmem_arena.data() + (eh_hdr_vma - min_eh_vma), + eh_hdr_bytes.data(), eh_hdr_bytes.size()); + memcpy(kmem_arena.data() + (eh_vma - min_eh_vma), + eh_bytes.data(), eh_bytes.size());
[Severity: Low]
Can an integer overflow in the section end calculation bypass the kmem_arena bounds check and write out of bounds?
In a malformed ELF file where one section end addition wraps around 64 bits (for example eh_hdr_vma + eh_hdr_bytes.size()) while the other does not, std::max() selects the un-wrapped end address. max_eh_end >= min_eh_vma and the 64 MiB limit can then both hold, leaving kmem_arena smaller than (eh_hdr_vma - min_eh_vma) + eh_hdr_bytes.size() when memcpy() runs.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=26
[email protected]
AI reviewRe: [RFC PATCH v2 26/30] tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier
In reply to Ian RogersTL;DR: - Makefile: possibly unreliable LLVM detection; wrong LLVM 21 requirement message - C++ objects may not rebuild after dwarf_cfi_row changes, possibly causing stale-layout memory errors…
Quoted 1 line
tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier
TL;DR:
- Makefile: possibly unreliable LLVM detection; wrong LLVM 21 requirement message
- C++ objects may not rebuild after dwarf_cfi_row changes, possibly causing stale-layout memory errors
- Mismatch diagnostics omit differing fields; misleading comment (nit)
Quoted 4 lines
tools/unwind/Makefile new file +0
-0
[ ... ]
tools/unwind/Makefile line 37
Quoted 3 lines
tools/unwind/Makefile new file +3
-0+FEATURE_USER := .verify_cfi +FEATURE_TESTS := llvm +FEATURE_DISPLAY := llvm
Is feature-llvm reliable here? FEATURE_TESTS is replaced with llvm, but nothing calls $(call feature_check,llvm) before the later "ifeq ($(feature-llvm),1)".
In tools/build/Makefile.feature, when test-all.bin builds, $(foreach feat,$(FEATURE_TESTS),$(call feature_set,$(feat))) sets feature-llvm to 1 without compiling test-llvm.cpp, since test-all.c is C and cannot include the C++ LLVM test. On such a host the display can print "llvm: [ on ]" whether or not LLVM is installed, and only the later DWARFUnwindTable.h wildcard keeps the build from proceeding.
On hosts where test-all.bin fails, the slow path runs test-llvm.bin, which links "llvm-config --libs Core BPF". Can an LLVM built without the BPF target, which verify_cfi does not need, make feature-llvm 0 and skip the tool?
Would an explicit $(call feature_check,llvm), or dropping the Makefile.feature probe in favour of the header check alone, make detection consistent with the "when libLLVM is detected via tools/build/Makefile.feature" wording in the commit message?
[ ... ]
tools/unwind/Makefile line 101
Quoted 10 lines
tools/unwind/Makefile new file +10
-0+ifeq ($(HAS_LIBLLVM),1) +all: $(OUTPUT)verify_cfi +else +all: +ifeq ($(REQUIRE_LLVM),1) + $(error libLLVM 17+ development headers/libraries not found (LLVM_CONFIG=$(LLVM_CONFIG))) +else + @echo " SKIP verify_cfi (libLLVM dev files not found; set LLVM_CONFIG=...)" +endif +endif
The real gate is:
ifneq ($(wildcard $(LLVM_INCDIR)/llvm/DebugInfo/DWARF/LowLevel/DWARFUnwindTable.h),)
but that header does not exist before LLVM 21, and verify_cfi.cpp calls llvm::dwarf::createUnwindTable(). On a host with LLVM 17-20 development files installed, REQUIRE_LLVM=1 fails with "libLLVM 17+ development headers/libraries not found (LLVM_CONFIG=llvm-config-18)", and the default build prints "libLLVM dev files not found". Both messages are wrong for that case.
The same applies to LLVM_CONFIG_CANDIDATES, which lists llvm-config-20 through llvm-config-18 even though they can never pass the header check. Should the message and the candidate list state LLVM 21 as the minimum?
tools/unwind/Makefile line 107
Quoted 5 lines
+$(OUTPUT)dwarf_cfi_host.o:
dwarf_cfi_host.cdwarf_cfi_host.h$(KERNEL_CFI_DEPS)tools/unwind/Makefile new file +4
-0+ $(QUIET_CC)$(HOSTCC) $(SHIM_CFLAGS) -c $< -o $@ + +$(OUTPUT)%.o: %.cpp $(wildcard *.hpp) dwarf_cfi_host.h + $(QUIET_CXX)$(HOSTCXX) $(VERIFY_CXXFLAGS) -c $< -o $@
Is QUIET_CXX defined anywhere? tools/scripts/Makefile.include defines QUIET_CC, QUIET_LINK and QUIET_CLANG, but a grep for QUIET_CXX only finds this line. In a default build the C++ objects would echo the full $(HOSTCXX) command line with every flag from llvm-config --cxxflags, instead of a short "CXX" line.
Also, KERNEL_CFI_DEPS (including tools/include/linux/unwind_dwarf_cfi.h) is only a prerequisite of dwarf_cfi_host.o. verify_cfi.cpp allocates struct dwarf_cfi_row and uses struct dwarf_cfi_arch and passes them to dwarf_cfi_unwind_user_eh_frame_hdr() and dwarf_cfi_unwind_eh_frame_hdr().
If a developer changes struct dwarf_cfi_row and reruns make -C tools/unwind, only dwarf_cfi_host.o is rebuilt, and verify_cfi.o keeps the old layout. Can the kernel code then write a larger dwarf_cfi_row into a smaller C++ stack object, or read fields at different offsets? Should $(KERNEL_CFI_DEPS), or at least the unwind_dwarf_cfi.h copy, be a prerequisite of the C++ rule too?
Quoted 4 lines
tools/unwind/dwarf_cfi_host.h new file +0
-0
[ ... ]
Quoted 6 lines
+/*
+ * Note: In C++ files using LLVM headers, include this header AFTER <llvm/...>
+ * headers (matchingtools/perf/util/llvm-c-helpers.cpp) because
+ *tools/include/linux/compiler.hdefines macros such as 'noinline' that
+ * conflict with LLVM attribute declarations.
+ */
This isn't a bug, but is this comment accurate? This header never includes compiler.h. Its only include is:
#include <linux/unwind_dwarf_cfi.h>
which resolves to tools/include/linux/unwind_dwarf_cfi.h, and that only includes <linux/types.h>. tools/include/linux/types.h includes <stdbool.h>, <stddef.h>, <stdint.h>, <asm/types.h> and <asm/posix_types.h>, so linux/compiler.h and its 'noinline' macro are not reached from this header.
What this header does bring in is tools/include/linux/types.h, which defines __must_check, __cold, __force, __user and __bitwise as macros. Could the comment name the macros this header actually introduces, or be dropped if there is no real ordering constraint?
Quoted 4 lines
tools/unwind/verify_cfi.cpp new file +0
-0
[ ... ]
Quoted 16 lines
tools/unwind/verify_cfi.cpp new file +16
-0+ if (err_u != 0 || !rowsEqual(krow_user, *exp)) { + st.llvm_vs_kernel_mismatches++; + char buf[200]; + snprintf(buf, sizeof(buf), + "PC=0x%" PRIx64 " err_u=%d kernel(cfa=%u:%d fp=%u:%d ra=%u:%d)" + " llvm(cfa=%u:%d fp=%u:%d ra=%u:%d)", + pc, err_u, krow_user.cfa_base, + krow_user.cfa_off, krow_user.fp_rule, + krow_user.fp_off, krow_user.ra_rule, + krow_user.ra_off, exp->cfa_base, + exp->cfa_off, exp->fp_rule, + exp->fp_off, exp->ra_rule, + exp->ra_off); + recordIssue(st, opts, "llvm_vs_kernel_dwarf", + buf); + }
[ ... ]
tools/unwind/verify_cfi.cpp line 409
Quoted 4 lines
tools/unwind/verify_cfi.cpp new file +4
-0+ if (err_k != err_u || + (err_u == 0 && + !rowsEqual(krow_kmem, krow_user))) + st.kmem_vs_user_mismatches++;
Does this sample omit fields that rowsEqual() compares? rowsEqual() returns false when sp_rule, signal or ra_signed differ, when cfa_reg differs under DWARF_CFI_BASE_REG, or when sp_off differs under DWARF_CFI_RULE_OFFSET, but the sample only prints cfa_base:cfa_off, fp_rule:fp_off and ra_rule:ra_off.
For example, if the kernel and LLVM disagree about ra_signed after DW_CFA_AARCH64_negate_ra_state, the mismatch is counted and the tool exits 1, but the sample reads:
kernel(cfa=1:16 fp=1:-16 ra=1:-8) llvm(cfa=1:16 fp=1:-16 ra=1:-8)
which hides the field that actually differs. The same holds for the signal flag, sp_rule and the CFA register.
Similarly, a kmem-vs-user disagreement only increments st.kmem_vs_user_mismatches and never calls recordIssue(). verifyFile() then fails the file and prints only the count, with no PC, error codes or rows. Could the sample include sp_rule:sp_off, cfa_reg, signal and ra_signed, and could the kmem path call recordIssue() with the PC, err_k/err_u and both rows?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 27/30 tools/unwind: Add multi-arch symbolic instruction lifters for verify_cfi
In reply to Ian RogersAdd the symbolic stack/register abstract domain (verify_insn.hpp), per-architecture Tier-2 instruction lifters (stepInstructionX86(), stepInstructionArm64(), stepInstructionRiscv(), and normalizeRiscvControlFlow()), and the conservative Tier-1 MCInstrDesc / MCRegisterInfo register-def clobber fallback (clobberGenericDefs()) in verify_insn_arch.cpp.
--- tools/unwind/Makefile | 3 +- tools/unwind/verify_insn.hpp | 103 ++++ tools/unwind/verify_insn_arch.cpp | 757 ++++++++++++++++++++++++++++++ 3 files changed, 862 insertions(+), 1 deletion(-) create mode 100644 tools/unwind/verify_insn.hpp create mode 100644 tools/unwind/verify_insn_arch.cpp
tools/unwind/Makefile +2 -1
@@ -87,7 +87,8 @@ KERNEL_CFI_DEPS := $(srctree)/kernel/unwind/dwarf_cfi.c \ $(srctree)/tools/include/linux/unwind_dwarf_cfi.h VERIFY_OBJS := $(OUTPUT)dwarf_cfi_host.o \ - $(OUTPUT)verify_cfi.o + $(OUTPUT)verify_cfi.o \ + $(OUTPUT)verify_insn_arch.o ifeq ($(HAS_LIBLLVM),1) all: $(OUTPUT)verify_cfi
tools/unwind/verify_insn.hpp new file +103 -0
103 lines not on this page · raw message
tools/unwind/verify_insn_arch.cpp new file +757 -0
757 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 27/30] tools/unwind: Add multi-arch symbolic instruction lifters for verify_cfi
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] tools/unwind: prefix checks in stepInstructionX86() shadow PUSH64rmm/POP64rmm --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] tools/unwind: prefix checks in stepInstructionX86() shadow PUSH64rmm/POP64rmm
--
commit 706436be3648ce84ad4baf3ce57398690cc2b113
Author: Ian Rogers <[email protected]>
tools/unwind: Add multi-arch symbolic instruction lifters for verify_cfi
This commit adds the symbolic stack and register abstract domain along with per-architecture instruction lifters and a generic register-def clobber fallback for verify_cfi.
Quoted 5 lines
tools/unwind/verify_insn_arch.cpp new file +0
-0
[ ... ]
Quoted 4 lines
tools/unwind/verify_insn_arch.cpp new file +4
-0+static bool stepInstructionX86(AbsState &st, StringRef OpName, + const MCInstrDesc &Desc, const InsnStepCtx &ctx) +{ + const MCInst &MI = ctx.MI;
[ ... ]
Quoted 14 lines
tools/unwind/verify_insn_arch.cpp new file +14
-0+ if (OpName.starts_with("PUSH64r")) { + int src = ctx.regD(0); + st.regs[7] = addSymImm(st.regs[7], -8); + st.store(st.regs[7], ctx.getRegVal(st, src)); + return true; + } + if (OpName == "PUSHF64" || OpName.starts_with("PUSH64i") || + OpName == "PUSH64rmm" || OpName == "PUSH64rmr") { + st.regs[7] = addSymImm(st.regs[7], -8); + st.store(st.regs[7], {VK_UNKNOWN, 0}); + return true; + } + if (OpName.starts_with("POP64r")) { + int dst = ctx.regD(0);
tools/unwind/verify_insn_arch.cpp line 237
Quoted 10 lines
tools/unwind/verify_insn_arch.cpp new file +10
-0+ SymVal loaded = st.load(st.regs[7]); + st.regs[7] = addSymImm(st.regs[7], 8); + if (dst != 7) + ctx.setRegVal(st, dst, loaded); + return true; + } + if (OpName == "POPF64" || OpName == "POP64rmm") { + st.regs[7] = addSymImm(st.regs[7], 8); + return true; + }
[Severity: Medium]
Do the OpName.starts_with("PUSH64r") and OpName.starts_with("POP64r") checks shadow the PUSH64rmm, PUSH64rmr and POP64rmm branches right below them?
Because those opcodes share the "PUSH64r" and "POP64r" prefixes, they always take the register-operand branch first, where ctx.regD(0) is the memory address base register rather than a value register. As a result, PUSH64rmm (such as pushq -8(%r10) in a DRAP prologue) pushes the base register's symbolic value onto the stack instead of VK_UNKNOWN, and POP64rmm overwrites the base register with the popped stack value.
In addition, in the POP64r handler, guarding ctx.setRegVal(st, dst, loaded) with dst != 7 prevents pop %rsp from updating st.regs[7] with the value loaded from the stack.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=27
[email protected]
AI reviewRe: [RFC PATCH v2 27/30] tools/unwind: Add multi-arch symbolic instruction lifters for verify_cfi
In reply to Ian RogersTL;DR: - x86 PUSH64r/POP64r prefix tests likely catch memory forms, possibly clobbering %rbp and causing false CFI mismatches - arm64 sub/add sp, sp, xN probably matches wrong opcodes, leaving SP…
Quoted 1 line
tools/unwind: Add multi-arch symbolic instruction lifters forverify_cfi
TL;DR:
- x86 PUSH64r/POP64r prefix tests likely catch memory forms, possibly clobbering %rbp and causing false CFI mismatches
- arm64 sub/add sp, sp, xN probably matches wrong opcodes, leaving SP unknown
- RISC-V jal x0 may clobber ra; LDP W scale looks wrong
Quoted 3 lines
tools/unwind/verify_insn_arch.cpp new file +0
-0
[ ... ]
Quoted 3 lines
tools/unwind/verify_insn_arch.cpp new file +3
-0+ if (Desc.isCall()) { + for (int d = 0; d < 32; d++) { + if (AS.llvm_arch == Triple::x86_64) {
[ ... ]
tools/unwind/verify_insn_arch.cpp line 141
Quoted 5 lines
tools/unwind/verify_insn_arch.cpp new file +5
-0+ } else if (AS.llvm_arch == Triple::riscv64) { + if (d == 0 || d == 2 || d == 3 || d == 4 || + d == 8 || d == 9 || (d >= 18 && d <= 27)) + continue; + st.regs[d] = {VK_UNKNOWN, 0};
On riscv64, jal ra, sym and jalr ra, off(rs) do not set isCall in their MCInstrDesc, and stepInstructionRiscv() does not model JAL/JALR. Is this riscv64 arm of the Desc.isCall() loop reachable for a real call?
In the later patch "tools/unwind: Add CFG instruction abstract execution oracle to verify_cfi" (9528bbf0f915), verifyOracle2Instructions() sends every RISC-V call around stepInstruction() and repeats the same register list:
if (AS.llvm_arch == Triple::riscv64 && is_call) {
for (int d = 1; d < 32; d++) {
if (d == 2 || d == 3 || d == 4 ||
d == 8 || d == 9 ||
(d >= 18 && d <= 27))
continue;
next_st.regs[d] = {VK_UNKNOWN, 0};
}
} else {
stepInstruction(next_st, MI, OpName, Desc, MCRI, ...);
}So the RISC-V caller-saved set is kept in two places that have to stay in sync, and any other caller of clobberGenericDefs()/stepInstruction() leaves a0-a7 and t0-t6 live across jal ra/jalr ra, contrary to the "ABI caller-saved registers across call instructions" comment.
Could the normalized is_call be passed into stepInstruction() and clobberGenericDefs() so the oracle can drop its copy, or could this arm be removed with a note that the caller handles RISC-V calls?
[ ... ]
Quoted 14 lines
tools/unwind/verify_insn_arch.cpp new file +14
-0+ if (OpName.starts_with("PUSH64r")) { + int src = ctx.regD(0); + st.regs[7] = addSymImm(st.regs[7], -8); + st.store(st.regs[7], ctx.getRegVal(st, src)); + return true; + } + if (OpName == "PUSHF64" || OpName.starts_with("PUSH64i") || + OpName == "PUSH64rmm" || OpName == "PUSH64rmr") { + st.regs[7] = addSymImm(st.regs[7], -8); + st.store(st.regs[7], {VK_UNKNOWN, 0}); + return true; + } + if (OpName.starts_with("POP64r")) { + int dst = ctx.regD(0);
tools/unwind/verify_insn_arch.cpp line 237
Quoted 10 lines
tools/unwind/verify_insn_arch.cpp new file +10
-0+ SymVal loaded = st.load(st.regs[7]); + st.regs[7] = addSymImm(st.regs[7], 8); + if (dst != 7) + ctx.setRegVal(st, dst, loaded); + return true; + } + if (OpName == "POPF64" || OpName == "POP64rmm") { + st.regs[7] = addSymImm(st.regs[7], 8); + return true; + }
Don't starts_with("PUSH64r") and starts_with("POP64r") also match the memory forms PUSH64rmm and POP64rmm? If so, the explicit "PUSH64rmm", "PUSH64rmr" and "POP64rmm" tests below them can never be reached.
For those memory forms, MCInst operand 0 is the base register of the memory reference, so ctx.regD(0) returns the address base rather than a data register.
For pushq -8(%r10) (PUSH64rmm) this stores the symbolic value of %r10 into the new stack slot, where the intended branch would store VK_UNKNOWN. That is the DRAP sequence the function's kernel-doc says it models:
lea 8(%rsp), %r10
and $-64, %rsp
pushq -8(%r10)The same happens for any pushq disp(%rbp) or pushq disp(%rsp), such as GCC pushing stack-passed arguments for calls with more than six arguments.
For popq disp(%base) (POP64rmm), ctx.setRegVal(st, base, loaded) overwrites the base register's symbolic value with the popped value instead of storing to memory. With base == %rbp, for example pushf; popq -0x10(%rbp) from native_save_fl() with the "=rm" output constraint, %rbp becomes VK_UNKNOWN. Every following row with an rbp-based CFA would then fail in evalRowAgainstAbs() with cfa_clobbered_or_opaque or fp_recovery_mismatch for a correct function.
Would testing exact names (OpName == "PUSH64r" || OpName == "PUSH64rmr", and OpName == "POP64r" || OpName == "POP64rmr"), or moving the memory-form branches ahead of the prefix tests, give the intended behaviour? No later patch in the series (up to 0278f019673d) touches verify_insn_arch.cpp.
[ ... ]
Quoted 3 lines
tools/unwind/verify_insn_arch.cpp new file +3
-0+ if ((OpName == "ADDXrs" || OpName == "SUBXrs" || + OpName == "ADDXrx" || OpName == "SUBXrx") && + MI.getNumOperands() >= 4 && MI.getOperand(3).isImm()) {
[ ... ]
tools/unwind/verify_insn_arch.cpp line 424
Quoted 5 lines
tools/unwind/verify_insn_arch.cpp new file +5
-0+ } else if (OpName.ends_with("rx") && + ((imm_arg >> 3) == 3 || (imm_arg >> 3) == 7) && + (imm_arg & 7) == 0) { + ok_shift = true; + }
Are these the right LLVM opcode names for add/sub sp, sp, xN? In LLVM's AArch64 AddSub multiclass, ADDXrx/SUBXrx take a GPR32 Rm with the UXTB..SXTW extends. The 64-bit Rm forms that allow only UXTX/SXTX are the separate opcodes ADDXrx64/SUBXrx64, and the aliases used when Rd or Rn is SP (sub sp, sp, x12 == sub sp, sp, x12, uxtx #0) bind to those.
If so, the (imm_arg >> 3) == 3 || == 7 test can never be true for a decoded ADDXrx/SUBXrx, so this sub-branch is dead. "SUBXrx64"/"ADDXrx64" match no case, stepInstructionArm64() returns false, and clobberGenericDefs() sets operand 0 (SP, DWARF 31) to VK_UNKNOWN.
This prologue shape is common with GCC when the adjustment is not a valid add immediate but can be loaded with one mov:
mov x12, 4160 sub sp, sp, x12 .cfi_def_cfa_offset 4160
After that instruction sp is VK_UNKNOWN, and evalRowAgainstAbs() would report cfa_clobbered_or_opaque for the SP-based CFA. Even with the CFA moved to x29, the matching add sp, sp, x12 / ldp x29, x30, [sp], #N epilogue would still report a mismatch. The MOVZXi/MOVNXi/MOVKXi constant tracking added for this case then has no consumer for SP.
Should this match "ADDXrx64"/"SUBXrx64" (and adjust the ends_with("rx") test), with the current ADDXrx/SUBXrx names dropped or handled separately with W-register extend semantics? No later patch in the series fixes this.
[ ... ]
tools/unwind/verify_insn_arch.cpp line 444
Quoted 7 lines
tools/unwind/verify_insn_arch.cpp new file +7
-0+ auto scaleOf = [](StringRef N) -> int64_t { + if (N.contains("Q")) + return 16; + if (N.contains("X") || N.contains("D")) + return 8; + if (N.contains("W") || N.contains("S")) + return 4;
Doesn't N.contains("D") also match the "D" in the "LDP" mnemonic prefix? scaleOf("LDPWpost") and scaleOf("LDPWpre") would then return 8 instead of 4.
The MC operand for LDP/STP is the raw signed imm7, so the scale is used directly here:
ctx.setRegVal(st, wb, addSymImm(addr, MI.getOperand(4).getImm() * scaleOf(OpName)));
For example ldp w19, w20, [sp], #8 would advance the abstract SP by 16 and desynchronise it from the CFI, giving a spurious CFA mismatch for the rest of the path. The STP W forms come out right only because "STP" contains neither 'D' nor 'X'. Compiler-generated prologues and epilogues do not use W-pair writeback on SP, so this mainly affects hand-written assembly.
Would selecting the scale from the register-class character after "LDP"/"STP" (OpName[3]) avoid the substring ambiguity?
[ ... ]
Quoted 5 lines
tools/unwind/verify_insn_arch.cpp new file +5
-0+void normalizeRiscvControlFlow(const MCInst &MI, StringRef OpName, + const MCRegisterInfo &MCRI, + bool &is_ret_or_ind_jump, bool &is_uncond_branch, + bool &is_call) +{
[ ... ]
tools/unwind/verify_insn_arch.cpp line 737
Quoted 4 lines
tools/unwind/verify_insn_arch.cpp new file +4
-0+ if (OpName == "JAL") { + if (rd == 0) { + is_uncond_branch = true; + is_call = false;
normalizeRiscvControlFlow() clears is_call for an uncompressed j (JAL x0), but doesn't stepInstruction() still see it as a call and clobber ra?
The caller verifyOracle2Instructions() added in 9528bbf0f915 starts from is_call = Desc.isCall(), which is true for JAL since LLVM marks JAL/JALR isCall = 1. After normalisation is_call is false, so the caller takes the else branch and calls stepInstruction(). stepInstructionRiscv() has no "JAL" case and returns false, so stepInstruction() falls back to:
if (!handled) clobberGenericDefs(st, MI, Desc, MCRI, AS);
clobberGenericDefs() re-reads Desc.isCall(), which is still true for JAL, and the riscv64 arm sets ra (x1), t0-t6 and a0-a7 to VK_UNKNOWN on every plain unconditional jump. The state is then enqueued at the branch target. If the RA rule there is DWARF_CFI_RULE_SAME, evalRowAgainstAbs() reads st.regs[1] == VK_UNKNOWN and records a spurious ra_recovery_mismatch. RA is SAME throughout leaf functions, and before the prologue or after the epilogue in shrink-wrapped paths.
With RVC, c.j (C_J, not isCall) is unaffected, but an uncompressed jal x0 is still emitted when the target is outside the +/-2KB c.j range, and for every jump in code built without the C extension. The real call paths never reach this clobber because the caller handles riscv64 calls itself, so the riscv64 isCall branch in clobberGenericDefs() only fires for JAL x0, the one case that is not a call.
Could "JAL" with rd == x0 (and C_J) be modelled in stepInstructionRiscv() as a no-op returning true, or could stepInstruction() take the normalised is_call instead of using Desc.isCall()? No later patch in the series fixes this.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 28/30 tools/unwind: Add CFG instruction abstract execution oracle to verify_cfi
In reply to Ian RogersAdd verifyOracle2Instructions() in tools/unwind/verify_insn.cpp and enable -DHAVE_VERIFY_INSN in tools/unwind/Makefile, propagating symbolic register and stack state over per-function basic-block CFGs across x86_64, arm64, and riscv64 and verifying at every reachable instruction that Minimal DWARF CFI recovers the caller's exact CFA, RA (including AArch64 PAC sign state), and FP.
--- tools/unwind/Makefile | 5 +- tools/unwind/verify_insn.cpp | 360 +++++++++++++++++++++++++++++++++++ 2 files changed, 363 insertions(+), 2 deletions(-) create mode 100644 tools/unwind/verify_insn.cpp
tools/unwind/Makefile +3 -2
@@ -79,7 +79,7 @@ TOOLS_INCLUDES := -I$(srctree)/tools/include -I$(srctree)/tools/include/uapi \ SHIM_CFLAGS := -O2 -g -Wall -Wextra -Wno-unused-parameter -Wno-maybe-uninitialized \ $(TOOLS_INCLUDES) -VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) \ +VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) -DHAVE_VERIFY_INSN \ -I$(CURDIR) $(TOOLS_INCLUDES) $(CXXFLAGS) VERIFY_LDFLAGS := $(LLVM_LDFLAGS) $(LDFLAGS)
@@ -88,7 +88,8 @@ KERNEL_CFI_DEPS := $(srctree)/kernel/unwind/dwarf_cfi.c \ VERIFY_OBJS := $(OUTPUT)dwarf_cfi_host.o \ $(OUTPUT)verify_cfi.o \ - $(OUTPUT)verify_insn_arch.o + $(OUTPUT)verify_insn_arch.o \ + $(OUTPUT)verify_insn.o ifeq ($(HAS_LIBLLVM),1) all: $(OUTPUT)verify_cfi
tools/unwind/verify_insn.cpp new file +360 -0
360 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 28/30] tools/unwind: Add CFG instruction abstract execution oracle to verify_cfi
TL;DR: - verify_cfi may skip code after returning calls or syscall/svc/ecall, and silently skips past 4096 instructions, yet still counts functions clean, so --strict may miss CFI mismatches…
Quoted 1 line
tools/unwind: Add CFG instruction abstract execution oracle toverify_cfi
TL;DR:
- verify_cfi may skip code after returning calls or syscall/svc/ecall, and silently skips past 4096 instructions, yet still counts functions clean, so --strict may miss CFI mismatches
- noreturn name list may be wrong
Quoted 3 lines
tools/unwind/verify_insn.cpp new file +0
-0
[ ... ]
Quoted 6 lines
tools/unwind/verify_insn.cpp new file +6
-0+bool isKnownNoreturnName(StringRef Name) +{ + static const char *const Exact[] = { + "panic", "do_exit", "make_task_dead", "__stack_chk_fail", + "__stack_chk_fail_local", "fortify_panic", "usercopy_abort", + "__bug", "bug_at", "do_group_exit", "complete_and_exit",
[ ... ]
tools/unwind/verify_insn.cpp line 49
Quoted 7 lines
tools/unwind/verify_insn.cpp new file +7
-0+ if (Name.starts_with("__throw_") || Name.starts_with("_ZSt7__throw") || + Name.starts_with("_ZSt9__throw") || Name.contains("panicking") || + Name.starts_with("rust_begin_unwind") || Name.contains("noreturn") || + Name.starts_with("__bad_")) + return true; + return false; +}
The kernel-doc says this returns true only when calls to @Name never return. Can Name.starts_with("__bad_") match functions that do return?
__bad_area() and __bad_area_nosemaphore() in arch/x86/mm/fault.c are ordinary static void functions, and bad_area_nosemaphore() returns after calling __bad_area_nosemaphore(). Similarly, Name.contains("panicking") also matches returning Rust std helpers such as std::panicking::panic_count::is_zero_slow_path() -> bool.
verifyFile() puts the address of every such symbol into noreturn_addrs, and verifyOracle2Instructions() then does:
if (has_target && noreturn_addrs.count(CallTarget)) continue;
so the fallthrough PC is never enqueued. Instructions only reachable past such a call (e.g. the epilogue after call __bad_area_nosemaphore) are never checked, yet the function is still counted in funcs_clean. Could these two rules be narrowed to exact names (or core::panicking only)?
The kernel names in Exact[] also differ from tools/objtool/noreturns.h:complete_and_exit and bug_at do not exist in this tree, and fortify_panic is a macro (the symbol is __fortify_panic). __fortify_panic, kthread_complete_and_exit, vpanic and do_task_dead are not recognized. Could the kernel names come from tools/objtool/noreturns.h instead of a separate hand-kept list?
The prefixes _ZSt7__throw and _ZSt9__throw can only match a 7- or 9-character std:: identifier starting with __throw, so helpers like _ZSt16__throw_bad_castv or _ZSt28__throw_bad_array_new_lengthv are missed.
[ ... ]
tools/unwind/verify_insn.cpp line 230
Quoted 6 lines
tools/unwind/verify_insn.cpp new file +6
-0+ bool func_ok = true; + unsigned steps = 0; + while (!worklist.empty() && steps < 4096) { + uint64_t pc = worklist.front(); + worklist.pop(); + steps++;
Each PC enters the worklist at most once, so steps counts distinct checked instructions. When a function has more than 4096 reachable instructions, the loop exits with the worklist still non-empty. Is it intended that the function is then still counted by:
tools/unwind/verify_insn.cpp line 358
Quoted 2 lines
tools/unwind/verify_insn.cpp new file +2
-0+ if (func_ok) + st.funcs_clean++;
func_ok is only cleared by an fde_eval_error or an evalRowAgainstAbs() failure on one of the first 4096 PCs. Nothing records the truncation, so the function is listed as "Functions 100% instruction-clean", and a CFA/RA/FP mismatch after the cutoff is not counted in insns_*_mismatch, so --strict still exits 0. Large functions such as sqlite3VdbeExec exceed this easily.
The decode-failure path behaves the same way:if (DStat != MCDisassembler::Success || InsnSize == 0) continue; drops all successors of an undecodable instruction and the function can still be counted clean. This also seems to contradict the commit message's "verifying at every reachable instruction". Could a truncated or abandoned walk clear func_ok, or be recorded with recordIssue() (for example as "step_limit")?
[ ... ]
tools/unwind/verify_insn.cpp line 296
Quoted 8 lines
tools/unwind/verify_insn.cpp new file +8
-0+ if (is_ret_or_ind_jump || Desc.isTrap() || + OpName == "UD2" || OpName == "BRK" || + OpName == "EBREAK" || OpName == "C_EBREAK" || + OpName == "SVC" || OpName == "ECALL" || + OpName == "SYSCALL" || OpName == "IRET64" || + OpName == "SYSRET64" || OpName == "ERET" || + OpName == "SRET" || OpName == "MRET") + continue;
SVC, ECALL and SYSCALL return to the next instruction, but here they end the path and next_pc is never enqueued. Everything after them on that path is unchecked, and the function can still be counted in funcs_clean.
Examples are the arm64 vDSO fallbacks in arch/arm64/include/asm/vdso/gettimeofday.h (svc #0 followed by the return and the caller's epilogue), RISC-V sbi_ecall(), and user-space syscall wrappers (syscall; cmp $-4095,%rax; ...; ret). The address after a syscall instruction is also the user PC that dwarf_cfi_unwind_user_eh_frame_hdr() starts from for a task that entered the kernel through a syscall.
sigreturn trampolines are already excluded by the earlierif (fr->signal) continue;, and HVC/SMC are not in the list and fall through. Should SVC/ECALL/SYSCALL be dropped from this terminator list so the fallthrough is verified, with stepInstruction() clobbering their defs?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45561209846
Ian Rogers
reviewerRFC PATCH v2 29/30 tools/unwind: Add x86-64 ORC cross-check oracle to verify_cfi
In reply to Ian RogersAdd verifyOracle3Orc() in tools/unwind/verify_orc.cpp using <asm/orc_types.h> and enable -DHAVE_VERIFY_ORC in tools/unwind/Makefile, cross-checking objtool's ORC_TYPE_CALL entries in .orc_unwind / .orc_unwind_ip directly against Minimal DWARF CFI across every instruction covered by an FDE (matching identically on 99.9823% of 4,468,154 x86-64 vmlinux instructions, with 0 BP diffs).
--- tools/unwind/Makefile | 5 +- tools/unwind/verify_orc.cpp | 205 ++++++++++++++++++++++++++++++++++++ 2 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 tools/unwind/verify_orc.cpp
tools/unwind/Makefile +3 -2
@@ -79,7 +79,7 @@ TOOLS_INCLUDES := -I$(srctree)/tools/include -I$(srctree)/tools/include/uapi \ SHIM_CFLAGS := -O2 -g -Wall -Wextra -Wno-unused-parameter -Wno-maybe-uninitialized \ $(TOOLS_INCLUDES) -VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) -DHAVE_VERIFY_INSN \ +VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) -DHAVE_VERIFY_INSN -DHAVE_VERIFY_ORC \ -I$(CURDIR) $(TOOLS_INCLUDES) $(CXXFLAGS) VERIFY_LDFLAGS := $(LLVM_LDFLAGS) $(LDFLAGS)
@@ -89,7 +89,8 @@ KERNEL_CFI_DEPS := $(srctree)/kernel/unwind/dwarf_cfi.c \ VERIFY_OBJS := $(OUTPUT)dwarf_cfi_host.o \ $(OUTPUT)verify_cfi.o \ $(OUTPUT)verify_insn_arch.o \ - $(OUTPUT)verify_insn.o + $(OUTPUT)verify_insn.o \ + $(OUTPUT)verify_orc.o ifeq ($(HAS_LIBLLVM),1) all: $(OUTPUT)verify_cfi
tools/unwind/verify_orc.cpp new file +205 -0
205 lines not on this page · raw message
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewRe: [RFC PATCH v2 29/30] tools/unwind: Add x86-64 ORC cross-check oracle to verify_cfi
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] tools/unwind: missing ORC_TYPE_UNDEFINED tie-break in verifyOracle3Orc() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] tools/unwind: missing ORC_TYPE_UNDEFINED tie-break in verifyOracle3Orc()
--
commit 21fa29da140895241f891570070d39da3828738f
Author: Ian Rogers <[email protected]>
tools/unwind: Add x86-64 ORC cross-check oracle to verify_cfi
This commit adds verifyOracle3Orc() to tools/unwind/verify_orc.cpp to cross-check x86-64 ORC_TYPE_CALL entries against Minimal DWARF CFI across every instruction covered by an FDE.
Quoted 6 lines
tools/unwind/verify_orc.cpp new file +0
-0@@ -0,0 +1,205 @@
[ ... ]
Quoted 33 lines
tools/unwind/verify_orc.cpp new file +33
-0+void verifyOracle3Orc(const ArchSpec &AS, uint64_t eh_hdr_vma, + StringRef eh_hdr_bytes, StringRef orc_bytes, + StringRef orc_ip_bytes, uint64_t orc_ip_vma, + const std::vector<ExecSec> &exec_secs, + const std::vector<FuncSym> &func_syms, + const MCDisassembler &Disasm, const MCSubtargetInfo &STI, + MCInstPrinter &InstPrinter, const VerifyOptions &opts, + VerifyStats &st) +{ + st.has_orc = true; + constexpr size_t kOrcEntSz = 6; + size_t n_orc = orc_bytes.size() / kOrcEntSz; + size_t n_ip = orc_ip_bytes.size() / 4; + size_t n = std::min(n_orc, n_ip); + const uint8_t *orc_raw = + reinterpret_cast<const uint8_t *>(orc_bytes.data()); + const uint8_t *ip_raw = + reinterpret_cast<const uint8_t *>(orc_ip_bytes.data()); + + std::vector<std::pair<uint64_t, size_t>> sorted_orc; + sorted_orc.reserve(n); + for (size_t i = 0; i < n; i++) { + int32_t rel = (int32_t)support::endian::read32le(ip_raw + i * 4); + uint64_t epc = orc_ip_vma + i * 4 + (uint64_t)(int64_t)rel; + sorted_orc.push_back({epc, i}); + } + std::stable_sort(sorted_orc.begin(), sorted_orc.end(), + [](const auto &a, const auto &b) { + return a.first < b.first; + }); + + auto lookupOrcIdx = [&](uint64_t pc, size_t &idx_out) -> bool { + auto it = std::upper_bound(
tools/unwind/verify_orc.cpp line 89
Quoted 10 lines
tools/unwind/verify_orc.cpp new file +10
-0+ sorted_orc.begin(), sorted_orc.end(), pc, + [](uint64_t val, const std::pair<uint64_t, size_t> &e) { + return val < e.first; + }); + if (it == sorted_orc.begin()) + return false; + --it; + idx_out = it->second; + return true; + };
[Severity: Low]
Can lookupOrcIdx() return an ORC_TYPE_UNDEFINED section-terminator entry instead of the real ORC_TYPE_CALL entry at contiguous text section boundaries?
objtool appends an ORC_TYPE_UNDEFINED terminator at the end address of each non-empty text section. When an unsorted .orc_unwind table is used (such as a vmlinux built with CONFIG_UNWINDER_DWARF_CFI=y where scripts/sorttable does not sort the ORC table) and a lower-VMA text section appears after an adjacent higher-VMA text section in ELF section order, sorting only by epc leaves the terminator after the next section's first entry at the same address. Because lookupOrcIdx() picks the rightmost entry with epc <= pc, it selects the ORC_TYPE_UNDEFINED entry and verifyOracle3Orc() silently skips verifying the boundary instructions.
In arch/x86/kernel/unwind_orc.c and scripts/sorttable.c, orc_sort_cmp() breaks ties at equal addresses by ordering ORC_TYPE_UNDEFINED entries before real entries.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=29
Ian Rogers
reviewerRFC PATCH v2 30/30 MAINTAINERS: Add DWARF CFI stack unwinding entry
In reply to Ian RogersAdd a MAINTAINERS entry for Minimal DWARF CFI stack unwinding covering the core .eh_frame / .eh_frame_hdr bytecode interpreter and KUnit tests, the user-space PT_GNU_EH_FRAME VMA unwinder, the x86-64 DWARF CFI kernel unwinder, the build-time .eh_frame minifier and analyzer scripts, the standalone tools/unwind/ CFI verifier, and the deferred user-space CFI kselftest.
Also add arch/*/include/asm/unwind_user*.h to USERSPACE STACK UNWINDING so architectural unwind_user headers on x86, arm64, riscv, and future ports are routed to the user-space unwinding maintainers.
--- MAINTAINERS | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
MAINTAINERS +16 -0
@@ -9496,6 +9496,21 @@ Q: http://patchwork.linuxtv.org/project/linux-media/list/ F: drivers/media/usb/dvb-usb-v2/dvb_usb* F: drivers/media/usb/dvb-usb-v2/usb_urb.c +DWARF CFI STACK UNWINDING +M: Ian Rogers <[email protected]> +L: [email protected] +L: [email protected] +S: Maintained +F: arch/x86/kernel/unwind_dwarf.c +F: include/linux/unwind_dwarf_cfi.h +F: kernel/unwind/dwarf_cfi*.c +F: kernel/unwind/user_cfi.c +F: scripts/eh_frame_min.py +F: scripts/min_eh_frame.c +F: tools/include/linux/unwind_dwarf_cfi.h +F: tools/testing/selftests/perf_events/unwind_user_cfi.c +F: tools/unwind/ + DYNAMIC DEBUG M: Jason Baron <[email protected]> M: Jim Cromie <[email protected]>
@@ -29300,6 +29315,7 @@ USERSPACE STACK UNWINDING M: Josh Poimboeuf <[email protected]> M: Steven Rostedt <[email protected]> S: Maintained +F: arch/*/include/asm/unwind_user*.h F: include/linux/unwind*.h F: kernel/unwind/
Signature · 1 line
2.56.1.831.g720f3f5937-goog
[email protected]
AI reviewSashiko has finished reviewing this 30-patch series:
Sashiko has finished reviewing this 30-patch series:
- Patches 2-5, 7-18, 20-25, and 28: no issues found.
- Patch 1 ("unwind: Add Minimal DWARF CFI bytecode interpreter"): 1 potential issue (1 Medium)
- Patch 6 ("kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY obj..."): 1 potential issue (1 Low)
- Patch 19 ("riscv/unwind: Add Minimal DWARF CFI kernel unwinder"): 1 potential issue (1 Medium)
- Patch 26 ("tools/unwind: Add standalone libLLVM Minimal DWARF C..."):
2 potential issues (1 Medium, 1 Low)
- Patch 27 ("tools/unwind: Add multi-arch symbolic instruction li..."):
1 potential issue (1 Medium)
- Patch 29 ("tools/unwind: Add x86-64 ORC cross-check oracle to v..."):
1 potential issue (1 Low)
- Patch 30: skipped (not reviewed).
Detailed reviews have been sent as separate replies to patches 1, 6, 19, 26, 27, and 29.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]