Skip to contentSkip to conversation

unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv

RFC PATCH New Ian Rogers 3 participants 27 messages Nov 22 – Nov 23

Subsystems (20)
x86 Kbuild Kselftest BPF +16 more subsystems
lore
Share & tools
lore

Ian Rogers

author reviewer
#0 lore raw

cover unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv

Overview
========

This RFC 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.

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, 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.)

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 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 routines. For this reason, arch_stack_walk_reliable() on ARM64 and RISC-V continues to conservatively reject stacks containing in-kernel asynchronous exception pt_regs boundaries until asynchronous epilogue/.S CFI auditing is established.
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 tables vs. cold
                                                           user 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-bit

Whenever 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) from rt_sigframe. On x86-64, .cfi_signal_frame ('S' augmentation) 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 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.
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): Unwinds vmlinux and RCU module .eh_frame tables, traverses %rsp-verified ENCODE_FRAME_POINTER pt_regs frames across task/IRQ/exception stacks, recovers CFA-keyed ftrace_graph and rethook return addresses, and sets state->error on any missing or invalid FDE so arch_stack_walk_reliable() returns -EINVAL rather than guessing.
- 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 out-of-tree ARM64 SFrame proposals, 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), 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 pops

Minified .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 08

SFrame 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 FRE

Example 2: Kernel-Space Walk (eBPF + DRAP Module + kretprobe on ARM64)
----------------------------------------------------------------------
[Context: JITed eBPF raw_tracepoint("sched_switch") calls 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 = 1 }
    -> 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.00%: 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*+.sframe
  ------------------------  -------  --------  --------  -------  ------------
  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 checks: 0 errors/warnings from scripts/checkpatch.pl, scripts/kernel-doc -Werror -none, and scripts/spdxcheck.py across all 11 patches.
- 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 7/7 KUnit tests, 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 CFI->FP->CFI fallback), -m32 IA32 compat, '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:

- Tool used: Gemini (AI coding assistant), used interactively across an extended engineering session.
- 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, KUnit/kselftest suites, differential fuzzers, QEMU multi-arch test harnesses, and series documentation.

Ian Rogers (11):
unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests
unwind_user: Support Minimal DWARF CFI user-space unwinding scripts, unwind: Add build-time .eh_frame minifier objtool/ibt: Ignore .eh_frame relocations during ENDBR validation x86/unwind: Add Minimal DWARF CFI kernel unwinder
arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding arm64/unwind: Add Minimal DWARF CFI kernel unwinder
riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding 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

 arch/Kconfig                                  |   31 +
 arch/arm64/Kconfig                            |    7 +-
 arch/arm64/Kconfig.debug                      |   32 +
 arch/arm64/Makefile                           |    5 +
 arch/arm64/include/asm/ftrace.h               |   10 +-
 arch/arm64/include/asm/module.h               |   16 +
 arch/arm64/include/asm/module.lds.h           |    2 +-
 arch/arm64/include/asm/perf_event.h           |   15 +
 arch/arm64/include/asm/unwind_user.h          |  126 ++
 arch/arm64/kernel/Makefile                    |    2 +
 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                    |   54 +
 arch/arm64/kernel/stacktrace.c                |  537 ++++-
 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/module.h               |   22 +
 arch/riscv/include/asm/perf_event.h           |   15 +
 arch/riscv/include/asm/signal32.h             |    8 +
 arch/riscv/include/asm/stacktrace.h           |   11 +
 arch/riscv/include/asm/unwind_user.h          |   81 +
 arch/riscv/kernel/Makefile                    |    4 +
 arch/riscv/kernel/compat_signal.c             |   44 +
 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                    |   62 +
 arch/riscv/kernel/stacktrace.c                |  732 ++++++-
 arch/riscv/kernel/vmlinux.lds.S               |   13 +
 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/unwind_dwarf.c                |  663 ++++++
 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              |  174 ++
 include/linux/unwind_user.h                   |   78 +
 include/linux/unwind_user_types.h             |   92 +-
 kernel/unwind/Makefile                        |   14 +-
 kernel/unwind/dwarf_cfi.c                     | 1842 +++++++++++++++++
 kernel/unwind/dwarf_cfi_kunit.c               |  625 ++++++
 kernel/unwind/user.c                          |  155 +-
 kernel/unwind/user_cfi.c                      |  378 ++++
 rust/Makefile                                 |    4 +-
 scripts/Makefile                              |    1 +
 scripts/Makefile.build                        |   12 +-
 scripts/Makefile.lib                          |   13 +-
 scripts/Makefile.vmlinux_o                    |    8 +-
 scripts/eh_frame_min.py                       |  938 +++++++++
 scripts/min_eh_frame.c                        | 1719 +++++++++++++++
 tools/objtool/check.c                         |    1 +
 .../testing/selftests/perf_events/.gitignore  |    1 +
 tools/testing/selftests/perf_events/Makefile  |    4 +-
 .../selftests/perf_events/unwind_user_cfi.c   |  447 ++++
 82 files changed, 9551 insertions(+), 118 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/testing/selftests/perf_events/unwind_user_cfi.c

base-commit: 4843f6873f7c4835e62f2c73ba0fd538e57a2f22

Signature · 1 line
2.56.1.750.gf70dc682cf-goog
author reviewer
#1 lore raw

RFC PATCH 1/11 unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests

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)
- 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, DW_CFA_register rules on {SP, FP, RA}, and DW_EH_PE_indirect pointer encodings are unconditionally rejected with -EINVAL. 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, and Spectre v1 / v1.1 nospec hardening (array_index_nospec() and barrier_nospec()) across all windowed user stream, expression-buffer, and state-stack accesses.

Also provide shared RCU-safe loadable-module .eh_frame indexing helpers (dwarf_cfi_mod_alloc(), dwarf_cfi_mod_free_rcu(), dwarf_cfi_mod_eval()) and a built-in KUnit test suite (CONFIG_UNWIND_DWARF_CFI_KUNIT_TEST) covering SP/FP frames, ignored GPR spills, shrink-wrapped state stacks, DRAP and sigreturn frames, ARM64 PAC-RET and RISC-V leaf frames, security rejections, and live kernel stack walks.

---
 arch/Kconfig                     |   16 +
 arch/arm64/Kconfig               |    3 -
 include/linux/unwind_dwarf_cfi.h |  174 +++
 kernel/unwind/Makefile           |   13 +-
 kernel/unwind/dwarf_cfi.c        | 1842 ++++++++++++++++++++++++++++++
 kernel/unwind/dwarf_cfi_kunit.c  |  625 ++++++++++
 6 files changed, 2669 insertions(+), 4 deletions(-)
 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
arch/Kconfig +16 -0
index 1163736de1f9..03399120aa8f 100644
@@ -500,6 +500,22 @@ 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_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
 
arch/arm64/Kconfig +0 -3
index 9b08b2457a55..ee0f263f477d 100644
@@ -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 +174 -0

174 lines not on this page · raw message

kernel/unwind/Makefile +12 -1
index eae37bea54fd..73a1ccc2ad77 100644
@@ -1 +1,12 @@
- 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
+obj-$(CONFIG_UNWIND_DWARF_CFI_KUNIT_TEST) += dwarf_cfi_kunit.o
kernel/unwind/dwarf_cfi.c new file +1842 -0

1,842 lines not on this page · raw message

kernel/unwind/dwarf_cfi_kunit.c new file +625 -0

625 lines not on this page · raw message

Signature · 1 line
2.56.1.750.gf70dc682cf-goog
#2 lore raw

Re: [RFC PATCH v1 01/11] unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] unwind: missing CONFIG_STACKTRACE dependency for dwarf_cfi_kunit.c - [Medium] unwind: signed FDE…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] unwind: missing CONFIG_STACKTRACE dependency for dwarf_cfi_kunit.c
- [Medium] unwind: signed FDE range sign-extension in dwarf_cfi_eval_fde_streams()
- [Medium] unwind: high-order kmalloc() for FDE index table in dwarf_cfi_mod_alloc()
--

commit 31c297accf2da5579a418d80b5e8b6a08f8ba8e6
Author: Ian Rogers <[email protected]>

unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests

This commit adds a bounded DWARF Call Frame Information (.eh_frame and .eh_frame_hdr) bytecode interpreter, module FDE indexing helpers, and a KUnit test suite.

Quoted 8 lines
arch/Kconfig +0 -0
index 1163736de1f99..03399120aa8f7 100644
@@ -500,6 +500,22 @@ config HAVE_HARDLOCKUP_DETECTOR_ARCH
 	  It uses the same command line parameters, and sysctl interface,
 	  as the generic hardlockup detectors.
 

arch/Kconfig config HAVE_HARDLOCKUP_DETECTOR_ARCH · line 512

Quoted 10 lines
arch/Kconfig +10 -0
+config UNWIND_TABLES
+	bool
+
+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

[Severity: Medium]
Does UNWIND_DWARF_CFI_KUNIT_TEST fail to build when CONFIG_STACKTRACE is disabled?

unwind_test_leaf() in kernel/unwind/dwarf_cfi_kunit.c unconditionally calls stack_trace_save(), which include/linux/stacktrace.h only declares under CONFIG_STACKTRACE. In addition, test_live_kernel_stack_walk() guards stack_trace_save_tsk_reliable() only with CONFIG_HAVE_RELIABLE_STACKTRACE, so with CONFIG_STACKTRACE=n it calls the fallback stub returning -ENOSYS. Either UNWIND_DWARF_CFI_KUNIT_TEST should depend on STACKTRACE, or the live stack walk test should be guarded by IS_ENABLED(CONFIG_STACKTRACE).

Quoted 5 lines
kernel/unwind/dwarf_cfi.c new file +0 -0
new file mode 100644
index 0000000000000..3e474bce1ab5e

[ ... ]

Quoted 32 lines
kernel/unwind/dwarf_cfi.c new file +32 -0
+static 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)
+{
+	struct dwarf_cfi_cie cie;
+	struct dwarf_cfi_row cie_row, row;
+	unsigned long init_loc, pc_range, end_loc;
+	int err;
+
+	err = dwarf_cfi_parse_cie(cie_s, arch, &cie, &cie_row);
+	if (err)
+		return err;
+
+	if (likely(cie.fde_enc == (DW_EH_PE_pcrel | DW_EH_PE_sdata4) &&
+		   fde_s->pos + 8 <= fde_s->win_len)) {
+		unsigned long faddr = cfi_stream_addr(fde_s);
+		s32 rel = (s32)get_unaligned_le32(fde_s->buf + fde_s->pos);
+		u32 rng = get_unaligned_le32(fde_s->buf + fde_s->pos + 4);
+
+		fde_s->pos += 8;
+		init_loc = faddr + (long)rel;
+		if (arch->ws == 4)
+			init_loc = (u32)init_loc;
+		pc_range = rng;
+	} else {
+		err = cfi_read_encoded_ptr(fde_s, cie.fde_enc, arch->ws,
+					   /*datarel_base=*/0, &init_loc);
+		if (err)
+			return err;
+		err = cfi_read_encoded_ptr(fde_s, cie.fde_enc & DW_EH_PE_FORM,

kernel/unwind/dwarf_cfi.c line 1270

Quoted 10 lines
kernel/unwind/dwarf_cfi.c new file +10 -0
+					   arch->ws, /*datarel_base=*/0,
+					   &pc_range);
+		if (err)
+			return err;
+	}
+
+	if (!pc_range || check_add_overflow(init_loc, pc_range, &end_loc))
+		return -EINVAL;
+	if (pc < init_loc || pc >= end_loc)
+		return -ENOENT;

[Severity: Medium]
Can a negative FDE range in the slow path sign-extend into pc_range and bypass the end_loc overflow check?

cie.fde_enc & DW_EH_PE_FORM preserves the signed encoding bit (0x08), so unlike the fast path above (which reads rng as u32), cfi_read_encoded_ptr() sign-extends negative sdata2, sdata4, sdata8, or sleb128 values to s64 before casting to unsigned long. When the decoded value is negative with a magnitude greater than init_loc (for example, init_loc = 0x400000 and a range of -0x500000), init_loc + pc_range does not wrap unsigned long and sets end_loc near ULONG_MAX, causing the FDE to match any pc >= init_loc.

[ ... ]

Quoted 20 lines
kernel/unwind/dwarf_cfi.c new file +20 -0
+struct mod_dwarf_cfi_index *dwarf_cfi_mod_alloc(const void *eh_frame,
+						size_t eh_frame_size,
+						const struct dwarf_cfi_arch *arch)
+{
+	struct mod_dwarf_cfi_index *idx;
+	unsigned int num_fdes = 0;
+	unsigned long base;
+
+	if (!eh_frame || !eh_frame_size)
+		return NULL;
+
+	base = (unsigned long)eh_frame;
+	if (dwarf_cfi_scan_eh_frame_kmem(eh_frame, eh_frame_size, arch, base,
+					 /*entries=*/NULL, /*max_entries=*/0,
+					 &num_fdes) || !num_fdes)
+		return NULL;
+
+	idx = kmalloc(struct_size(idx, entries, num_fdes), GFP_KERNEL);
+	if (!idx)
+		return NULL;

kernel/unwind/dwarf_cfi.c line 1775

Quoted 10 lines
kernel/unwind/dwarf_cfi.c new file +10 -0
+
+	idx->num_fdes = num_fdes;
+	idx->eh_frame = eh_frame;
+	idx->eh_frame_size = eh_frame_size;
+
+	if (dwarf_cfi_scan_eh_frame_kmem(eh_frame, eh_frame_size, arch, base,
+					 idx->entries, num_fdes, &num_fdes)) {
+		kfree(idx);
+		return NULL;
+	}

[Severity: Medium]
Should dwarf_cfi_mod_alloc() use kvmalloc() and kvfree() instead of kmalloc() and kfree()?

Each function in a module produces an 8-byte eh_frame_hdr_entry, so any module with more than ~4,093 functions requires an allocation above PAGE_ALLOC_COSTLY_ORDER (32 KiB on 4 KiB page systems), and large modules such as amdgpu or i915 can need 64 KiB to 256+ KiB of physically contiguous memory, risking compaction stalls or allocation failure under fragmentation. dwarf_cfi_mod_free_rcu() already frees idx with kfree_rcu_mightsleep(), which handles vmalloc pointers.

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

Re: [RFC PATCH v1 01/11] unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests

In reply to Ian Rogers
TL;DR: - Disabling KMSAN for dwarf_cfi.o may cause false uninit-value reports on returned rows - Commit message and header misdescribe indirect-encoding rejection - Kernel-doc claims test use of…
Quoted 1 line

unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests

TL;DR:
- Disabling KMSAN for dwarf_cfi.o may cause false uninit-value reports on returned rows
- Commit message and header misdescribe indirect-encoding rejection
- Kernel-doc claims test use of module indexing helpers that tests never call

kernel/unwind/Makefile line 8

Quoted 12 lines
kernel/unwind/Makefile +8 -0
@@ -1 +1,12 @@
+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

Can KMSAN_SANITIZE_dwarf_cfi.o := n cause false uninit-value reports?

Every public entry point in dwarf_cfi.c returns its result by storing into a struct dwarf_cfi_row supplied by the caller:

    dwarf_cfi_eval_fde_streams():
        *out_row = row;

Without KMSAN instrumentation these stores do not update the shadow, while the callers are instrumented and keep the row on their stack, where KMSAN has poisoned it on function entry. The caller would then see row as uninitialized as soon as it branches on a field, for example in the later user unwinder:

    unwind_user_next_cfi():
        struct dwarf_cfi_row row;
        ...
        err = dwarf_cfi_unwind_user_eh_frame_hdr(hdr_uaddr, hdr_size,
                                                 lookup_ip, &arch, &row);
        ...
        if (row.ra_rule == DWARF_CFI_RULE_UNDEFINED) {

The same applies to the KUnit tests in this patch, which read row.cfa_base and other fields after dwarf_cfi_eval_fde_kmem(), and to the x86 kernel unwinder added later in the series.

Documentation/dev-tools/kmsan.rst warns that disabling instrumentation produces wrong shadow and false positives, and other code that returns data from uninstrumented code calls kmsan_unpoison_memory() on the output. dwarf_cfi.c only reads .eh_frame data and memory obtained through copy_from_user(), which unpoisons its destination, so would KMSAN_ENABLE_CHECKS_dwarf_cfi.o := n (or no KMSAN switch at all) be enough here while keeping shadow propagation for out_row?

[ ... ]

Quoted 3 lines
kernel/unwind/dwarf_cfi.c new file +0 -0

[ ... ]

kernel/unwind/dwarf_cfi.c line 1181

Quoted 7 lines
kernel/unwind/dwarf_cfi.c new file +7 -0
+			case 'P':
+				/* Personality encoding + pointer; skipped without deref */
+				err = cfi_read_u8(s, &enc);
+				if (err)
+					return err;
+				psize = cfi_encoded_ptr_size(enc & ~DW_EH_PE_indirect,
+							     arch->ws);

This isn't a bug, but the commit message says:

Quoted 2 lines

DW_EH_PE_indirect pointer encodings are unconditionally rejected with -EINVAL.

and the file header comment says "expressions and indirect pointer encodings are rejected".

dwarf_cfi_parse_cie() masks DW_EH_PE_indirect off the 'P' personality encoding and accepts it, and the 'L' LSDA encoding byte is accepted whatever its value. Only the 'R' FDE encoding and cfi_read_encoded_ptr() reject DW_EH_PE_indirect.

Skipping the personality pointer without dereferencing it looks correct, and the function's own kernel-doc describes that accurately. Could the commit message and the file header say that indirect encodings are rejected for pointers that are decoded (FDE initial_location/range and .eh_frame_hdr fields), and that personality/LSDA pointers are skipped without being dereferenced?

[ ... ]

Quoted 4 lines

+ * @out_count: Output number of valid FDEs discovered in [@eh_start, +@eh_size).
+ *
+ * Used at module load time (and in tests) to construct a binary-search FDE
+ * lookup table when the linker has not emitted a separate .eh_frame_hdr.

This isn't a bug, but the kernel-doc says dwarf_cfi_scan_eh_frame_kmem() is used "in tests". kernel/unwind/dwarf_cfi_kunit.c never references dwarf_cfi_scan_eh_frame_kmem(), dwarf_cfi_mod_alloc(), dwarf_cfi_mod_eval() or dwarf_cfi_unwind_user_eh_frame_hdr(), and the only caller of dwarf_cfi_scan_eh_frame_kmem() is dwarf_cfi_mod_alloc().

Should the comment drop "(and in tests)", or should a test be added that indexes a small .eh_frame blob through dwarf_cfi_mod_alloc() and dwarf_cfi_mod_eval()?

---
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/45087188604

author reviewer
#4 lore raw

RFC PATCH 2/11 unwind_user: Support Minimal DWARF CFI user-space unwinding

In reply to Ian Rogers

Extend 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 and enabling 64-bit and 32-bit compat user unwinding on x86.

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.
- Fence non-masked access_ok() checks in get_user_word() with barrier_nospec() so chained cfa_indirect user stack loads cannot speculatively dereference kernel addresses on architectures without branchless uaccess pointer masking.
- Provide overridable unwind_user_frame_pointer() 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 (supporting SA_ONSTACK alternate signal stacks and signal trampolines without leading NOPs).
- Support link-register leaf frames (ra_from_reg when state->ra_valid is true, clearing ra_valid after the first step so subsequent frames enforce strict cfa > sp progression), DRAP/sigframe indirect CFA rules, and clean bottom-of-stack termination on DW_CFA_undefined or zero RA.

---
 arch/Kconfig                       |   5 +
 arch/x86/Kconfig                   |   1 +
 arch/x86/include/asm/unwind_user.h |  47 ++++
 include/linux/unwind_user.h        |  78 ++++++
 include/linux/unwind_user_types.h  |  92 ++++++-
 kernel/unwind/Makefile             |   1 +
 kernel/unwind/user.c               | 155 +++++++++++-
 kernel/unwind/user_cfi.c           | 378 +++++++++++++++++++++++++++++
 8 files changed, 740 insertions(+), 17 deletions(-)
 create mode 100644 kernel/unwind/user_cfi.c
arch/Kconfig +5 -0
index 03399120aa8f..340a7ecbfc68 100644
@@ -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
arch/x86/Kconfig +1 -0
index 58dce0b66179..c8096cf66c38 100644
@@ -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

include/linux/unwind_user.h +78 -0

90 lines not on this page · raw message

include/linux/unwind_user_types.h +87 -5

128 lines not on this page · raw message

kernel/unwind/Makefile +1 -0
index 73a1ccc2ad77..954083868790 100644
@@ -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 +143 -12

260 lines not on this page · raw message

kernel/unwind/user_cfi.c new file +378 -0

378 lines not on this page · raw message

Signature · 1 line
2.56.1.750.gf70dc682cf-goog
#5 lore raw

Re: [RFC PATCH v1 02/11] unwind_user: Support Minimal DWARF CFI user-space unwinding

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] unwind_user: unguarded frame_pointer() call in unwind_user_frame_pointer() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] unwind_user: unguarded frame_pointer() call in unwind_user_frame_pointer()
--

commit ad18f29bd8a6b46031b3d36b8ae44ab35c61c7c8
Author: Ian Rogers <[email protected]>

unwind_user: Support Minimal DWARF CFI user-space unwinding

This commit extends the generic user-space unwinder with UNWIND_USER_TYPE_CFI to resolve ELF PT_GNU_EH_FRAME headers across executable VMAs and enables 64-bit and 32-bit compat user unwinding on x86.

Quoted 24 lines
include/linux/unwind_user.h +9 -0
index 64618618febde..dcd87012ab82c 100644
@@ -16,6 +16,12 @@
 #endif
 
 #ifndef unwind_user_at_function_start
+/**
+ * unwind_user_at_function_start() - Default stub for function-entry detection
+ * @regs: User-mode register state.
+ *
+ * Return: false when the architecture does not override entry detection.
+ */
 static inline bool unwind_user_at_function_start(struct pt_regs *regs)
 {
 	return false;
@@ -23,6 +29,78 @@ static inline bool unwind_user_at_function_start(struct pt_regs *regs)
 #define unwind_user_at_function_start unwind_user_at_function_start
 #endif
 
+#ifndef unwind_user_frame_pointer
+/**
+ * unwind_user_frame_pointer() - Default helper returning @regs's frame pointer

include/linux/unwind_user.h static inline bool unwind_user_at_function_start(struct pt_regs *regs) · line 44

Quoted 10 lines
include/linux/unwind_user.h +10 -0
+ * @regs: User-mode register state.
+ *
+ * Return: Architectural user frame pointer from frame_pointer(@regs).
+ */
+static inline unsigned long unwind_user_frame_pointer(struct pt_regs *regs)
+{
+	return frame_pointer(regs);
+}
+#define unwind_user_frame_pointer unwind_user_frame_pointer
+#endif

[Severity: High]
Does defining unwind_user_frame_pointer() unconditionally break the build on architectures that do not provide frame_pointer(regs)?

include/linux/unwind_deferred.h includes include/linux/unwind_user.h outside CONFIG_UNWIND_USER, and core files such as kernel/exit.c include include/linux/unwind_deferred.h on all architectures. Architectures like LoongArch and s390 do not define frame_pointer(regs) in asm/ptrace.h, and include/linux/unwind_user.h also does not include linux/ptrace.h before referencing struct pt_regs and frame_pointer().

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

Re: [RFC PATCH v1 02/11] unwind_user: Support Minimal DWARF CFI user-space unwinding

In reply to Ian Rogers
TL;DR: - Possible wrong stack pointer after 32-bit compat vdso sigreturn FDE, giving bogus user callchain IPs - Speculation fence in get_user_word() may be a no-op on all architectures - Return: doc…
Quoted 1 line

unwind_user: Support Minimal DWARF CFI user-space unwinding

TL;DR:
- Possible wrong stack pointer after 32-bit compat vdso sigreturn FDE, giving bogus user callchain IPs
- Speculation fence in get_user_word() may be a no-op on all architectures
- Return: doc mismatch (nit)

Quoted 3 lines
kernel/unwind/user.c +0 -0

[ ... ]

Quoted 9 lines
kernel/unwind/user.c +4 -0
@@ -11,14 +12,38 @@
 static inline int
 get_user_word(unsigned long *word, unsigned long base, int off, unsigned int ws)
 {
 	unsigned long __user *addr = (void __user *)base + off;
+
+	/*
+	 * On architectures whose get_user() uses a conditional access_ok()
+	 * branch rather than branchless address masking, fence bad access_ok()

kernel/unwind/user.c line 29

Quoted 10 lines
kernel/unwind/user.c +10 -0
+	 * speculation so chained cfa_indirect stack reads cannot transiently
+	 * dereference kernel addresses.
+	 */
+	if (!can_do_masked_user_access()) {
+		if (!access_ok(addr, ws)) {
+			*word = 0;
+			return -EFAULT;
+		}
+		barrier_nospec();
+	}

The commit message says this block fences non-masked access_ok() checks "so chained cfa_indirect user stack loads cannot speculatively dereference kernel addresses". Does this code provide that protection on any architecture that uses it?

x86_64 is the only architecture selecting HAVE_UNWIND_USER_CFI at this commit, and it defines masked_user_access_begin(), so can_do_masked_user_access() is true and the whole block is compiled out.

arm64 and riscv enable this later in the series. Neither defines masked_user_access_begin(), so the branch is taken, but neither defines barrier_nospec() either, so it falls back to the empty generic definition:

    # define barrier_nospec() do { } while (0)

That leaves only an access_ok() check that get_user() repeats right after.

The comment's condition also looks off for arm64, whose get_user() already masks the pointer without a branch (__uaccess_mask_ptr()), yet it still takes this branch. can_do_masked_user_access() only reports whether masked_user_access_begin() exists, not how get_user() is implemented.

Should the comment and changelog describe what the code does (defer to the arch barrier_nospec()), or should the block be dropped since get_user() already does the access_ok() check?

[ ... ]

Quoted 3 lines
kernel/unwind/user_cfi.c new file +0 -0

[ ... ]

Quoted 5 lines

+ * Return: 0 on success, -ENOENT if no PT_GNU_EH_FRAME covers @ip's VMA,
+ * -EINTR if killed while waiting for mmap_lock, -EFAULT on user copy fault, or
+ * -EINVAL if current->mm is absent or @state->ws is unsupported.
+ */
+static int find_user_eh_frame_hdr(struct unwind_user_state *state,

This isn't a bug, but does this Return: list match the code?

parse_user_elf64_eh_hdr() and parse_user_elf32_eh_hdr() also return -EINVAL for bad magic, wrong EI_CLASS, a bad e_phentsize, or e_phnum of 0 or above 64, and find_user_eh_frame_hdr() passes that through:

    if (state->ws == 8)
        err = parse_user_elf64_eh_hdr(elf_base, out_hdr_uaddr, out_hdr_size);
    ...
    if (err)
        return err;

That happens for any VM_EXEC file mapping at vm_pgoff 0 that is not an ELF image of the task's class, for example a memfd JIT region, the [uprobes] XOL page, or an x32 binary (ws == 8 but ELFCLASS32).

The errno also changes once the VMA is cached. The slot is marked valid with eh_hdr_uaddr = 0 before parsing, so the first lookup returns -EINVAL or -EFAULT, and every later lookup in the same VMA hits:

    if (!c->eh_hdr_uaddr)
        return -ENOENT;

So the documented -EFAULT/-EINVAL distinction only holds for the first lookup. The walk falls back to FP either way. Could the Return: list name the invalid-ELF -EINVAL case and say that cached negative entries report -ENOENT, or should the cache keep the original error?

[ ... ]

Quoted 11 lines
kernel/unwind/user_cfi.c new file +11 -0
+	lookup_ip = (state->topmost || state->signal) ? state->ip : state->ip - 1;
+
+	err = find_user_eh_frame_hdr(state, lookup_ip, &hdr_uaddr, &hdr_size);
+	if (!err)
+		err = dwarf_cfi_unwind_user_eh_frame_hdr(hdr_uaddr, hdr_size,
+							 lookup_ip, &arch, &row);
+	if (err == -ENOENT && lookup_ip != state->ip) {
+		/*
+		 * A signal trampoline without a leading NOP has state->ip at
+		 * the exact start of its FDE, where state->ip - 1 misses.
+		 */

kernel/unwind/user_cfi.c line 334

Quoted 10 lines
kernel/unwind/user_cfi.c new file +10 -0
+		err = find_user_eh_frame_hdr(state, state->ip, &hdr_uaddr,
+					     &hdr_size);
+		if (!err)
+			err = dwarf_cfi_unwind_user_eh_frame_hdr(hdr_uaddr,
+								 hdr_size,
+								 state->ip,
+								 &arch, &row);
+		if (!err && !row.signal)
+			err = -ENOENT;
+	}

For 32-bit compat tasks on x86_64, does this retry path accept the vdso32 sigreturn FDE and then hand back the wrong caller stack pointer?

Compat tasks that do not set SA_RESTORER return from signal handlers through the vDSO trampolines (vdso32_image.sym___kernel_rt_sigreturn). In arch/x86/entry/vdso/vdso32/sigreturn.S the FDE starts exactly at __kernel_rt_sigreturn, and the nop in front of it is outside any FDE. So the first lookup at state->ip - 1 returns -ENOENT, and this retry at state->ip finds the 'S' FDE and accepts it.

That FDE describes the interrupted registers as:

CFI_DEF_CFA esp, \sc - 4
CFI_OFFSET eip, IA32_SIGCONTEXT_ip
...
CFI_OFFSET esp, IA32_SIGCONTEXT_sp
CFI_OFFSET ebp, IA32_SIGCONTEXT_bp

The interrupted esp is the value saved at CFA + IA32_SIGCONTEXT_sp, not the CFA itself. dwarf_cfi_exec_insns() only applies DW_CFA_offset* to fp_reg and ra_reg:

    if (lo == arch->fp_reg || lo == cie->ra_reg)

so the esp rule is silently dropped. unwind_user_next_cfi() then builds a row with cfa_base SP, cfa_indirect false, cfa_off = sc - 4, and unwind_user_next_common() gets the correct RA and FP from the sigcontext but sets state->sp = cfa, which is the address of the sigcontext inside the signal frame rather than the interrupted esp.

The next step uses state->ip with this wrong SP. If the interrupted function's CFA is SP-based (default -fomit-frame-pointer i386 code, or any prologue/epilogue/leaf), the CFA becomes &sigcontext + N, the progression check passes, and the RA is read from inside the sigcontext (for example the gs/ds selector words). The result is bogus IPs in the deferred user callchain, and the walk never falls back to FP.

The commit message claims "32-bit compat user unwinding on x86" and support for "signal trampolines without leading NOPs", which is this trampoline. Should a signal row whose SP is restored from memory either be translated, for example by treating "esp at CFA+off" as an SP-indirect CFA, or be rejected so the unwind falls back to FP instead of producing wrong frames?

No later commit in the series changes dwarf_cfi.c, user_cfi.c or user.c.

---
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/45087188604

author reviewer
#7 lore raw

RFC PATCH 3/11 scripts, unwind: Add build-time .eh_frame minifier

In reply to Ian Rogers

Add a standalone C build-time ELF relocatable (.o) .eh_frame minifier (scripts/min_eh_frame.c, enabled by CONFIG_UNWINDER_DWARF_CFI_MINIFY) supporting x86-64, ARM64, and RISC-V with zero external library or scripting dependencies.

During Kbuild compilation (C, Rust, and post-LTO composite objects), 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, 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).

Across full vmlinux builds on x86-64 (69,958 FDEs), ARM64 (69,765 FDEs), and RISC-V (55,296 FDEs), minification achieves 100.00% FDE coverage and reduces .eh_frame size 18%-28% below SFrame v3 (.sframe).

---
 arch/Kconfig               |   10 +
 rust/Makefile              |    4 +-
 scripts/Makefile           |    1 +
 scripts/Makefile.build     |   12 +-
 scripts/Makefile.lib       |   13 +-
 scripts/Makefile.vmlinux_o |    8 +-
 scripts/min_eh_frame.c     | 1719 ++++++++++++++++++++++++++++++++++++
 7 files changed, 1761 insertions(+), 6 deletions(-)
 create mode 100644 scripts/min_eh_frame.c
arch/Kconfig +10 -0
index 340a7ecbfc68..6509265065e1 100644
@@ -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 UNWINDER_DWARF_CFI
+	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
rust/Makefile +3 -1
index 0165626decbe..1238b4ac661d 100644
@@ -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 +1 -0
index d7fbb7ca098b..c392610b65dd 100644
@@ -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/Makefile.build +10 -2
index 6127feb970c6..ced0f630f566 100644
@@ -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
index 19e96b30a122..b27bcd50daf7 100644
@@ -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
index 0b37bd5dc3a4..160d43fbb393 100644
@@ -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
 
scripts/min_eh_frame.c new file +1719 -0

1,719 lines not on this page · raw message

Signature · 1 line
2.56.1.750.gf70dc682cf-goog
#8 lore raw

Re: [RFC PATCH v1 03/11] scripts, unwind: Add build-time .eh_frame minifier

TL;DR: - On big-endian build hosts, min_eh_frame may silently skip minifying every object, so the size reduction is lost - Kconfig depends on UNWINDER_DWARF_CFI, which is defined only later in the…
Quoted 1 line

scripts, unwind: Add build-time .eh_frame minifier

TL;DR:
- On big-endian build hosts, min_eh_frame may silently skip minifying every object, so the size reduction is lost
- Kconfig depends on UNWINDER_DWARF_CFI, which is defined only later in the series
- min_eh_frame is missing from scripts/.gitignore

arch/Kconfig config HAVE_UNWIND_USER_CFI · line 533

Quoted 10 lines
arch/Kconfig +3 -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 UNWINDER_DWARF_CFI

A subsystem pattern flags this as potentially concerning: a depends on naming a symbol that no Kconfig file defines.

UNWINDER_DWARF_CFI is not defined anywhere at this commit, so this option evaluates to n on every architecture. That leaves the hostprogs-always entry in scripts/Makefile, the cmd_min_eh_frame hooks in Makefile.lib, Makefile.build, Makefile.vmlinux_o and rust/Makefile, and scripts/min_eh_frame.c itself unreachable here, so the results quoted in the commit message cannot be reproduced from this commit.

The symbol is defined later in the series, in 6cf5792e969e ("x86/unwind:
Add Minimal DWARF CFI kernel unwinder"), efdfa5f38673 ("arm64/unwind: Add Minimal DWARF CFI kernel unwinder") and 90a680847a32 ("riscv/unwind: Add Minimal DWARF CFI kernel unwinder"), so this looks like a forward reference rather than a misspelling, and bisection is not broken.

Would it make sense to reorder the series so the unwinder Kconfig symbol comes before its consumers?

Quoted 6 lines
arch/Kconfig +6 -0
+	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.

[ ... ]

scripts/Makefile hostprogs-always-$(CONFIG_SYSTEM_EXTRA_CERTIFICATE) += insert-sys-cert · line 15

Quoted 8 lines
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

Should /min_eh_frame be added to scripts/.gitignore?

Every other host program built here has an entry there (/kallsyms, /sorttable, /tracepoint-update, /insert-sys-cert, and so on), and git check-ignore -v scripts/min_eh_frame matches no rule. After an in-tree build with the option enabled, the binary shows up as untracked and could be picked up by git add -A. No later commit in the series adds the entry.

[ ... ]

Quoted 4 lines
scripts/min_eh_frame.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 2 lines
scripts/min_eh_frame.c new file +2 -0
+int main(int argc, char **argv)
+{

[ ... ]

scripts/min_eh_frame.c line 1711

Quoted 4 lines
scripts/min_eh_frame.c new file +4 -0
+		if (memcmp(map, ELFMAG, SELFMAG) == 0 &&
+		    map[EI_DATA] == ELFDATA2LSB &&
+		    map[EI_CLASS] == ELFCLASS64)
+			rc = process_elf64(map, (size_t)st.st_size);

main() checks that the target object is little-endian, but not the byte order of the host the tool runs on. process_elf64() then reads and writes the ELF header, section header, symbol and Elf64_Rela fields as native structs, and only the .eh_frame payload goes through get_le32()/put_le32().

On a big-endian build host cross-compiling an x86_64, arm64 or riscv64 kernel, the first check in process_elf64() sees the bytes 01 00 of e_type as 0x0100:

    if (ehdr->e_type != ET_REL)
        return 0;

Won't every object then be silently left unminified while the build still succeeds? CONFIG_UNWINDER_DWARF_CFI_MINIFY is default y and its help text says only Minimal DWARF CFA bytecodes remain in vmlinux and modules, but on such a host nothing is stripped, coalesced or dropped, and nothing reports it.

Other ELF host tools in scripts/ handle this: scripts/elf-parse.c picks rle/rbe accessors from EI_DATA, and scripts/mod/modpost.c applies TO_NATIVE() to the ELF header fields.

The resulting kernel should still work, since kernel/unwind/dwarf_cfi.c parses unminified CIEs and FDEs, but the documented size reduction would not apply.

Could this either fail the build with a message when the host is not little-endian, or read the ELF header, section, symbol and rela fields through le16/le32/le64 accessors as elf-parse.c does?

---
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/45087188604

author reviewer
#9 lore raw

RFC PATCH 4/11 objtool/ibt: Ignore .eh_frame relocations during ENDBR validation

In reply to Ian Rogers

When 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
index 931c5c412f15..e631b0da9bad 100644
@@ -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.750.gf70dc682cf-goog
author reviewer
#10 lore raw

RFC PATCH 5/11 x86/unwind: Add Minimal DWARF CFI kernel unwinder

In reply to Ian Rogers

Add 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 disabling unwind table emission in special boot, purgatory, and EFI libstub objects and enabling BPF exception stack walks in arch/x86/net/bpf_jit_comp.c.
- Place .eh_frame_hdr and .eh_frame inside RO_DATA via ARCH_RODATA_SECTIONS so mark_rodata_ro() write-protects them without freeing them as rodata/data gap pages, and index loadable module .eh_frame sections via dwarf_cfi_mod_alloc()/dwarf_cfi_mod_free_rcu().
- Annotate THUNK, ftrace_64.S, and arch_rethook_trampoline() with .cfi_* directives, preserve FRAME_BEGIN/FRAME_END for non-leaf asm, and pair with ENCODE_FRAME_POINTER (%rsp-verified against pt_regs) in entry assembly stubs and call_on_stack() IRQ stack pivots so unwind_next_frame() transitions cleanly across task, IRQ, exception, ftrace, fgraph, rethook, BPF, and NMI frames.

---
 arch/x86/Kconfig                      |   2 +-
 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/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/unwind_dwarf.c        | 663 ++++++++++++++++++++++++++
 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 |   3 +-
 include/asm-generic/vmlinux.lds.h     |   5 +
 19 files changed, 925 insertions(+), 34 deletions(-)
 create mode 100644 arch/x86/kernel/unwind_dwarf.c
arch/x86/Kconfig +1 -1
index c8096cf66c38..517c2b728752 100644
@@ -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
index c95c3aaadf97..bd894d76360c 100644
@@ -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
index b7e08519b8c1..70c3308653dd 100644
@@ -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
index 5e499cfb29b5..4e3ad26bfc04 100644
@@ -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/entry/calling.h +17 -0
index 77e2d920a640..1a133ad44b95 100644
@@ -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
index 09c9684d3ad6..0fa61360f69d 100644
@@ -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/include/asm/module.h +5 -0
index 3c2de4ce3b10..da990da59e2b 100644
@@ -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
index 7cede4dc21f0..49bf73193927 100644
@@ -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
index 31f46fd00527..117cf86617cb 100644
@@ -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/ftrace_64.S +43 -1

160 lines not on this page · raw message

arch/x86/kernel/module.c +9 -2
index 33080ad889b7..9cfd60619acc 100644
@@ -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/rethook.c +90 -2

119 lines not on this page · raw message

arch/x86/kernel/unwind_dwarf.c new file +663 -0

663 lines not on this page · raw message

arch/x86/kernel/vmlinux.lds.S +16 -0
index 2438b89a4620..20f0fa33ea9c 100644
@@ -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
index 4c3e09d98131..84217ce6a283 100644
@@ -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
index fad91ea28fe7..ef3ae80f5c06 100644
@@ -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
drivers/firmware/efi/libstub/Makefile +2 -1
index bbab12b8eb4b..d62dabfdc1c3 100644
@@ -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)
 
include/asm-generic/vmlinux.lds.h +5 -0
index 3eb732942d69..1bde7a2a19d0 100644
@@ -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.750.gf70dc682cf-goog
#11 lore raw

Re: [RFC PATCH v1 05/11] x86/unwind: Add Minimal DWARF CFI kernel unwinder

TL;DR: - Reliable stacktrace may wrongly succeed on kernel pt_regs inside inline asm, so livepatch could miss a sleeping function - Build may fail with KPROBES=n (rethook symbol) - KMSAN false…
Quoted 1 line

x86/unwind: Add Minimal DWARF CFI kernel unwinder

TL;DR:
- Reliable stacktrace may wrongly succeed on kernel pt_regs inside inline asm, so livepatch could miss a sleeping function
- Build may fail with KPROBES=n (rethook symbol)
- KMSAN false reports; ftrace skip counts drop frames

arch/x86/Kconfig config X86 · line 294

Quoted 12 lines
arch/x86/Kconfig +1 -1
@@ -288,7 +288,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

Is HAVE_RELIABLE_STACKTRACE justified for UNWINDER_DWARF_CFI?

arch_stack_walk_reliable() only refuses kernel-mode pt_regs when frame pointers are enabled:

    regs = unwind_get_entry_regs(&state, NULL);
    if (regs) {
        if (user_mode(regs))
            return 0;
        ...
        if (IS_ENABLED(CONFIG_FRAME_POINTER))
            return -EINVAL;
    }

With UNWINDER_DWARF_CFI, FRAME_POINTER is n, so the walk continues. unwind_next_frame() then reaches the pt_regs through the encoded %rbp, sets state->ip = regs->ip and state->sp = regs->sp, and evaluates the compiler-generated .eh_frame row at regs->ip.

The compiler's .eh_frame only describes stack changes the compiler made itself. It knows nothing about push/pop inside inline asm, for example native_save_fl(), which arch_local_irq_save() inlines into every spin_lock_irqsave():

    asm volatile("# __raw_save_flags\n\t"
                 "pushf ; pop %0"

The paravirt save_fl alternative, KVM's fastop() and iret_to_self() do the same. ORC handles these because objtool decodes the instructions, but no objtool stack validation runs here (STACK_VALIDATION depends on UNWINDER_FRAME_POINTER).

Consider CONFIG_PREEMPTION=y, IRQs on, preempt_count 0, and a task in __raw_spin_lock_irqsave(). An IRQ arrives after pushf and before pop, and irqentry_exit() calls preempt_schedule_irq(), so the task sleeps with regs->ip at the pop. Later:

klp_try_switch_task()
klp_check_stack()
stack_trace_save_tsk_reliable()

walks the task. At regs->ip the CFA computed from %rsp is 8 bytes too low, so the return address is read from the wrong slot.

If that slot holds a pushed flags value, the walk fails safely. If it holds a kernel text address, such as a callee-saved function pointer, the walk records a bogus frame and drops the real caller. If it then resynchronises and reaches task_pt_regs(), it returns 0, and livepatch treats a function the task is sleeping in as absent.

Documentation/livepatch/reliable-stacktrace.rst section 4.3 says:
"Architectures which cannot identify when it is reliable to unwind such cases ... must reject unwinding across exception boundaries."

Should arch_stack_walk_reliable() also return -EINVAL on kernel-mode regs for UNWINDER_DWARF_CFI, or should the unwinder otherwise prove that regs->ip is not inside an inline-asm stack adjustment?

[ ... ]

arch/x86/Kconfig.debug config UNWINDER_ORC · line 253

Quoted 12 lines
arch/x86/Kconfig.debug +5 -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

The new unwinder skips frames the same way unwind_orc.c does, and the kernel is built without frame pointers, so -fno-optimize-sibling-calls is dropped just as under ORC. But the tracing code picks its skip counts by testing CONFIG_UNWINDER_ORC alone:

kernel/trace/trace.c:__ftrace_trace_stack() {

#ifndef CONFIG_UNWINDER_ORC
    if (!regs)
        skip++;

#endif
}

trace_dump_stack() has the same extra skip++, and:

kernel/trace/trace_functions.c: STACK_SKIP is 3 instead of 2 and FTRACE_STACK_SKIP is 5 instead of 3 kernel/trace/trace_events_trigger.c: STACK_SKIP is 4 instead of 2

These values were calibrated separately for ORC and frame pointers (commit 2ee5b92a2598). With UNWINDER_DWARF_CFI=y, the func_stack_trace option, the stacktrace event trigger, the stacktrace probe command and trace_dump_stack() take the frame-pointer branch and would drop one or two real caller frames from their output.

Should these tests be CONFIG_UNWINDER_ORC || CONFIG_UNWINDER_DWARF_CFI, or be keyed on !CONFIG_FRAME_POINTER?

[ ... ]

Quoted 12 lines
arch/x86/kernel/Makefile +1 -0
@@ -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.

arch/x86/kernel/Makefile KCOV_INSTRUMENT_stacktrace.o := n · line 48

Quoted 6 lines
arch/x86/kernel/Makefile +1 -0
@@ -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

With CONFIG_KMSAN=y, will this report false "uninit-value in unwind_next_frame" on ordinary stack walks?

KASAN and KCOV are turned off for unwind_dwarf.o, but KMSAN stays on, while the interpreter it calls is built with no KMSAN instrumentation (kernel/unwind/Makefile has KMSAN_SANITIZE_dwarf_cfi.o := n).

In unwind_next_frame():

    struct dwarf_cfi_row row;
    ...
    err = dwarf_cfi_find(lookup_ip, &row);
    ...
    if (row.ra_rule == DWARF_CFI_RULE_UNDEFINED)

KMSAN poisons row on entry. dwarf_cfi_find() fills it through dwarf_cfi_unwind_eh_frame_hdr() or dwarf_cfi_mod_eval(), both out-of-line in the uninstrumented dwarf_cfi.c, so their stores never clear the shadow. The later row.ra_rule, row.cfa_base and row.fp_rule tests then read poisoned memory.

KMSAN depends only on HAVE_ARCH_KMSAN, clang and a few other options, and UNWINDER_DWARF_CFI depends only on X86_64, so nothing prevents this combination. INIT_STACK_ALL_ZERO and INIT_STACK_ALL_PATTERN depend on !KMSAN, so row is not pre-initialised.

Callers that would report include stack_trace_save() -> arch_stack_walk(), arch_stack_walk_reliable(), perf_callchain_kernel() and __get_wchan().

unwind_frame.c marks unwind_next_frame() and update_stack_state() __no_kmsan_checks for a related reason (commit 37ad4ee83642).

Would marking unwind_next_frame() __no_kmsan_checks, calling kmsan_unpoison_memory(&row, sizeof(row)) after a successful dwarf_cfi_find(), or building dwarf_cfi.o with KMSAN_ENABLE_CHECKS_dwarf_cfi.o := n instead be needed here? Adding KMSAN_SANITIZE_unwind_dwarf.o := n alone would leave the callers' struct unwind_state poisoned.

[ ... ]

Quoted 3 lines
arch/x86/kernel/unwind_dwarf.c new file +0 -0

[ ... ]

arch/x86/kernel/unwind_dwarf.c line 449

Quoted 12 lines
arch/x86/kernel/unwind_dwarf.c new file +12 -0
+	lookup_ip = state->signal ? state->ip : state->ip - 1;
+	err = dwarf_cfi_find(lookup_ip, &row);
+	if (err) {
+		/*
+		 * Handle an interrupt/unwind starting right at the entry of
+		 * arch_rethook_trampoline() before pushq $arch_rethook_trampoline.
+		 */
+		if (state->signal && is_rethook_trampoline(state->ip)) {
+			state->ip = dwarf_recover_ret_addr(state, state->ip,
+					(unsigned long *)(state->sp - sizeof(long)));
+			if (!state->ip || is_rethook_trampoline(state->ip))
+				goto err;

Can this fail to link when CONFIG_UNWINDER_DWARF_CFI=y and CONFIG_KPROBES=n?

unwind_next_frame() calls is_rethook_trampoline() unconditionally in several places, and nothing guards those calls with CONFIG_RETHOOK. is_rethook_trampoline() in include/linux/rethook.h is an unconditional static inline:

    static inline bool is_rethook_trampoline(unsigned long addr)
    {
        return addr == (unsigned long)dereference_symbol_descriptor(arch_rethook_trampoline);
    }

On x86, arch_rethook_trampoline is defined only in arch/x86/kernel/rethook.c, which is built only with obj-$(CONFIG_RETHOOK). RETHOOK is a hidden bool whose only selector is KRETPROBE_ON_RETHOOK, which depends on KRETPROBES and therefore KPROBES. UNWINDER_DWARF_CFI depends only on X86_64 and selects neither, so KPROBES=n is a valid configuration. There unwind_dwarf.o references arch_rethook_trampoline, no object defines it, and vmlinux fails with an undefined reference.

Other users are guarded: unwind_recover_rethook() in arch/x86/include/asm/unwind.h and unwind_recover_ret_addr() in arch/s390/include/asm/unwind.h use #ifdef CONFIG_RETHOOK, and this file already guards the return_to_handler checks with
#ifdef CONFIG_FUNCTION_GRAPH_TRACER, but the rethook checks next to them have no matching guard.

Should the rethook branch and comparisons be wrapped in IS_ENABLED(CONFIG_RETHOOK), or should is_rethook_trampoline() get a stub returning false when !CONFIG_RETHOOK? No later patch in the series touches unwind_dwarf.c, rethook.h or the x86 Kconfig.

[ ... ]

arch/x86/kernel/unwind_dwarf.c line 654

Quoted 4 lines
arch/x86/kernel/unwind_dwarf.c new file +4 -0
+	while (!unwind_done(state) &&
+	       (!on_stack(&state->stack_info, first_frame, sizeof(long)) ||
+		state->sp <= (unsigned long)first_frame))
+		unwind_next_frame(state);

This is the same skip loop as in unwind_orc.c, and a DWARF build has the same code generation as an ORC build: CONFIG_FRAME_POINTER is off, so the top-level Makefile does not add -fno-omit-frame-pointer -fno-optimize-sibling-calls and sibling calls stay enabled.

The ftrace stack-trace skip counts are chosen only by CONFIG_UNWINDER_ORC (kernel/trace/trace.c __ftrace_trace_stack() and trace_dump_stack(), trace_functions.c STACK_SKIP and FTRACE_STACK_SKIP, trace_events_trigger.c STACK_SKIP), so with CONFIG_UNWINDER_DWARF_CFI=y each takes the frame-pointer branch. Going by the ORC calibration, that would drop about two frames for the function tracer's stacktrace option and trace_dump_stack(), and about three for the stacktrace event trigger and func-probe command. The exact count was inferred from the ORC calibration and not measured.

This patch already updates the ORC-keyed check in arch/x86/net/bpf_jit_comp.c to
IS_ENABLED(CONFIG_UNWINDER_ORC) || IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI), but not the ones in kernel/trace, and no later commit in the series touches kernel/trace.

Should these conditionals also cover CONFIG_UNWINDER_DWARF_CFI, or be keyed on whether frame pointers are used rather than on one unwinder?

---
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/45087188604

author reviewer
#12 lore raw

RFC PATCH 6/11 arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding

In reply to Ian Rogers

Wire 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() so leaf functions with DW_CFA_same_value on LR unwind accurately before falling back to stack-saved return addresses.
- 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 (which intentionally omits .eh_frame in the arm64 vDSO), preserving interrupted leaf functions and SA_ONSTACK alternate signal stacks.
- Strip user-space pointer authentication codes via ptrauth_strip_user_insn_pac() 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 | 126 +++++++++++++++++++++++++++
 arch/arm64/kernel/signal.c           |  54 ++++++++++++
 3 files changed, 182 insertions(+)
 create mode 100644 arch/arm64/include/asm/unwind_user.h
arch/arm64/Kconfig +2 -0
index ee0f263f477d..918d7e278f7d 100644
@@ -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 +126 -0

126 lines not on this page · raw message

arch/arm64/kernel/signal.c +54 -0

66 lines not on this page · raw message

Signature · 1 line
2.56.1.750.gf70dc682cf-goog
#13 lore raw

Re: [RFC PATCH v1 06/11] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] arm64: unwind_user: shifted rt_sigframe base in unwind_user_sigreturn() - [Medium] arm64…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] arm64: unwind_user: shifted rt_sigframe base in unwind_user_sigreturn()
- [Medium] arm64: unwind_user: wrong state->sp on FP-to-CFI frame transition
- [Medium] arm64: unwind_user: Thumb bit 0 not stripped in unwind_user_strip_pac()
--

commit 6b2ce687ccf3b40dba131fb7a09e5054f9d0557a
Author: Ian Rogers <[email protected]>

arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding

This commit adds arm64 support for user-space DWARF CFI and frame pointer unwinding, including register mappings, pointer authentication stripping, and vDSO signal trampoline recovery.

Quoted 6 lines
arch/arm64/include/asm/unwind_user.h new file +0 -0
new file mode 100644
index 0000000000000..38d0641ae5549
@@ -0,0 +1,126 @@

[ ... ]

arch/arm64/include/asm/unwind_user.h line 74

Quoted 9 lines
arch/arm64/include/asm/unwind_user.h new file +9 -0
+static inline unsigned long unwind_user_strip_pac(unsigned long ip,
+						  bool ra_signed)
+{
+	if (IS_ENABLED(CONFIG_COMPAT) &&
+	    compat_user_mode(task_pt_regs(current)))
+		return ip;
+	return ptrauth_strip_user_insn_pac(ip);
+}
+#define unwind_user_strip_pac unwind_user_strip_pac

[Severity: Medium]
Should unwind_user_strip_pac() clear bit 0 (ip & ~1UL) for 32-bit compat tasks?

In AArch32 Thumb mode, BL/BLX and compat_setup_return() set bit 0 of LR to indicate Thumb state. Leaving bit 0 set records odd addresses in the callchain and causes lookup_ip = state->ip - 1 in unwind_user_next_cfi() to evaluate to return_pc rather than return_pc - 1, applying post-call CFA rule changes prematurely or missing the FDE when a call is at the end of a function.

[ ... ]

arch/arm64/include/asm/unwind_user.h line 124

Quoted 13 lines
arch/arm64/include/asm/unwind_user.h new file +13 -0
+#ifdef CONFIG_HAVE_UNWIND_USER_FP
+
+/*
+ * AArch64 PCS stores {fp, lr} at [fp, fp + 16), while 32-bit AArch32 compat
+ * APCS stores struct compat_frame_tail {fp, sp, lr} at [compat_fp - 12, compat_fp).
+ */
+#define ARCH_INIT_USER_FP_FRAME(ws)			\
+	.cfa_off	= (ws) == 8 ? 2 * (ws) : 0,	\
+	.ra_off		= -1 * (ws),			\
+	.fp_off		= (ws) == 8 ? -2 * (ws) : -3 * (ws), \
+	.use_fp		= true,
+
+#endif /* CONFIG_HAVE_UNWIND_USER_FP */

[Severity: Medium]
Does ARCH_INIT_USER_FP_FRAME() leave state->sp inaccurate when an inner frame unwound via FP transitions to an outer frame unwound via SP-based DWARF CFI?

On AArch64, a function with frame size N > 16 places its frame record at the lowest address of its frame (callee_fp = caller_sp - N). Setting cfa_off = 16 with use_fp = true updates state->sp to callee_fp + 16 = caller_sp - (N - 16) rather than caller_sp (and on AArch32, cfa_off = 0 sets state->sp to compat_fp rather than loading compat_frame_tail.sp from [compat_fp - 8]). If unwind_user_next() then resumes UNWIND_USER_TYPE_CFI on an outer caller whose FDE uses DWARF_CFI_BASE_SP, the outer CFA is computed from the wrong state->sp and reads the caller's saved registers from the wrong stack offset.

Quoted 4 lines
arch/arm64/kernel/signal.c +0 -0
index 80398ac83c3b1..41dfbfcc1d2eb 100644

[ ... ]

Quoted 13 lines
arch/arm64/kernel/signal.c +12 -0
@@ -1705,6 +1706,59 @@ void __init minsigstksz_setup(void)
+bool unwind_user_sigreturn(struct unwind_user_state *state)
+{
+	struct mm_struct *mm = current->mm;
+	struct rt_sigframe __user *sf;
+	unsigned long sigtramp;
+	u64 fp_lr[2], sp_pc[2];
+
+	if (!mm || state->ws != 8 || !mm->context.vdso)
+		return false;
+
+	sigtramp = (unsigned long)VDSO_SYMBOL(mm->context.vdso, sigtramp);
+	if (state->ip != sigtramp &&

arch/arm64/kernel/signal.c void __init minsigstksz_setup(void) · line 1727

Quoted 10 lines
arch/arm64/kernel/signal.c +10 -0
+	    !(state->topmost && state->ip == sigtramp + 4))
+		return false;
+
+	if (state->sp & 0xfUL)
+		return false;
+
+	sf = (struct rt_sigframe __user *)state->sp;
+	if (copy_from_user(fp_lr, &sf->uc.uc_mcontext.regs[29], sizeof(fp_lr)) ||
+	    copy_from_user(sp_pc, &sf->uc.uc_mcontext.sp, sizeof(sp_pc)))
+		return false;

[Severity: Medium]
Can unwind_user_sigreturn() read from a shifted struct rt_sigframe pointer when the signal handler was unwound via frame pointers?

When a signal handler with stack frame size S > 16 is unwound via UNWIND_USER_TYPE_FP, unwind_user_next_fp() sets state->ip = sigtramp and state->sp = handler_fp + 16 = (unsigned long)user->sigframe - (S - 16), which remains 16-byte aligned. On the next step, unwind_user_sigreturn() casts that shifted state->sp to struct rt_sigframe __user *; for a 32-byte handler frame, sf is user->sigframe - 16, so reading regs[29..30] and {sp, pc} actually reads regs[27..28] and regs[29..30] from the real sigcontext, passing the alignment and non-zero checks and corrupting the rest of the unwind walk.

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

RFC PATCH 7/11 arm64/unwind: Add Minimal DWARF CFI kernel unwinder

In reply to Ian Rogers

Add 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 nVHE EL2 hypervisor objects and BPF JIT frames.
- Emit --eh-frame-hdr and place .eh_frame_hdr and .eh_frame in vmlinux RO_DATA while preserving __pi___eh_frame_start and __pi___eh_frame_end so CONFIG_UNWIND_PATCH_PAC_INTO_SCS continues to work unchanged.
- Retain SHF_ALLOC module .eh_frame sections in module.lds.h and index them with RCU-safe lifetime in arch/arm64/kernel/module.c.
- Annotate call_on_irq_stack(), __efi_rt_asm_wrapper(), arch_bpf_timed_may_goto(), return_to_handler(), and __hwasan_tag_mismatch() with .cfi_* directives, key function_graph and kretprobe shadow return stacks on entry SP (CFA) rather than x29, and implement noinstr-safe kunwind_next_cfi() and arm64_unwind_perf_caller_regs() in arch/arm64/kernel/stacktrace.c with link-register leaf support, PAC stripping, cross-stack pivot transitions, ftrace_caller / ftrace_graph / kretprobe recovery, BPF JIT/trampoline frame records, and SP-verified frame_record_meta entry transitions.

---
 arch/arm64/Kconfig                  |   2 -
 arch/arm64/Kconfig.debug            |  32 ++
 arch/arm64/Makefile                 |   5 +
 arch/arm64/include/asm/ftrace.h     |  10 +-
 arch/arm64/include/asm/module.h     |  16 +
 arch/arm64/include/asm/module.lds.h |   2 +-
 arch/arm64/include/asm/perf_event.h |  15 +
 arch/arm64/kernel/Makefile          |   2 +
 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/stacktrace.c      | 537 ++++++++++++++++++++++++++--
 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 +
 20 files changed, 768 insertions(+), 41 deletions(-)
arch/arm64/Kconfig +0 -2
index 918d7e278f7d..0c0b24d1ec4a 100644
@@ -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
index 265c4461031f..4f5c99a2fa96 100644
@@ -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
index ed28f94be428..7ec8e96b2032 100644
@@ -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 +6 -4
index 1621c84f44b3..f7558cbb148b 100644
@@ -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
+extern void ftrace_caller_end(void);
 #define HAVE_ARCH_FTRACE_REGS
 struct dyn_ftrace;
 struct ftrace_ops;
@@ -158,10 +159,11 @@ ftrace_partial_regs(const struct ftrace_regs *fregs, struct pt_regs *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;		\
+		(_regs)->pc = arch_ftrace_regs(fregs)->pc;		\
+		(_regs)->regs[29] = arch_ftrace_regs(fregs)->fp;	\
+		(_regs)->regs[30] = arch_ftrace_regs(fregs)->lr;	\
+		(_regs)->sp = arch_ftrace_regs(fregs)->sp;		\
+		(_regs)->pstate = PSR_MODE_EL1h;			\
 	} while (0)
 
 int ftrace_regs_query_register_offset(const char *name);
arch/arm64/include/asm/module.h +16 -0
index fb9b88eebeb1..71f423be20c2 100644
@@ -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
index 603f92a8a73e..d754f3743487 100644
@@ -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 +15 -0
index ee45b4e77347..4a7dbb7ce41c 100644
@@ -13,11 +13,26 @@
 #define perf_arch_bpf_user_pt_regs(regs) &regs->user_regs
 #endif
 
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+void arm64_unwind_perf_caller_regs(struct pt_regs *regs, unsigned long pc,
+				   unsigned long caller_ip, unsigned long sp,
+				   unsigned long fp);
+
+#define perf_arch_fetch_caller_regs(regs, __ip) do {			\
+	unsigned long __here_pc, __here_fp;				\
+	asm volatile("1: adr %0, 1b\n\t"				\
+		     "mov %1, x29"					\
+		     : "=r" (__here_pc), "=r" (__here_fp));		\
+	arm64_unwind_perf_caller_regs((regs), __here_pc, (__ip),	\
+				      current_stack_pointer, __here_fp);\
+} while (0)
+#else
 #define perf_arch_fetch_caller_regs(regs, __ip) { \
 	(regs)->pc = (__ip);    \
 	(regs)->regs[29] = (unsigned long) __builtin_frame_address(0); \
 	(regs)->sp = current_stack_pointer; \
 	(regs)->pstate = PSR_MODE_EL1h;	\
 }
+#endif
 
 #endif
arch/arm64/kernel/Makefile +2 -0
index fc5d1a0c38b3..d727fda788a3 100644
@@ -8,6 +8,7 @@ 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)
+CFLAGS_REMOVE_stacktrace.o = $(CC_FLAGS_FTRACE)
 
 # Remove stack protector to avoid triggering unneeded stack canary
 # checks due to randomize_kstack_offset.
@@ -24,6 +25,7 @@ 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
+KCOV_INSTRUMENT_stacktrace.o := n
 
 # Softirq stack switching can run outside interrupt context.
 KCOV_INSTRUMENT_irq.o := n
arch/arm64/kernel/efi-rt-wrapper.S +22 -0
index e8ae803662cf..4ddfa5362e4f 100644
@@ -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
index 025140caafe7..d112a29fd1a7 100644
@@ -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
index 8d17f61d1b5b..15a591996307 100644
@@ -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/kernel/ftrace.c +9 -3
index e1a3c0b3a051..5f9458a6b477 100644
@@ -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
index 24adb581af0e..88d07ecf6e64 100644
@@ -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
index 4e0efad5caf2..eae1f2326efa 100644
@@ -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 +515 -22

674 lines not on this page · raw message

arch/arm64/kernel/vmlinux.lds.S +20 -1
index c95243a8b24e..3d70eb12fa11 100644
@@ -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
index 56a7e2c05f73..bb9907b8ec7f 100644
@@ -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)
arch/arm64/lib/kasan_sw_tags.S +16 -0
index 20784ce75def..7959b5f3c6b0 100644
@@ -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
index 33632fb20997..ee1436295046 100644
@@ -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
index f8732b13bb1e..6d0aa023c1f4 100644
@@ -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.750.gf70dc682cf-goog
#15 lore raw

Re: [RFC PATCH v1 07/11] arm64/unwind: Add Minimal DWARF CFI kernel unwinder

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] arm64: perf: eager CFI walk and off-by-4 PC in perf_arch_fetch_caller_regs() - [Medium] arm64: vdso…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] arm64: perf: eager CFI walk and off-by-4 PC in perf_arch_fetch_caller_regs()
- [Medium] arm64: vdso: -fomit-frame-pointer breaks vDSO unwinding with DWARF CFI
- [Low] arm64: Kconfig disables LATENCYTOP and fault-injection filter with DWARF CFI
- [Low] arm64: stacktrace: unused frame_key in kunwind_recover_return_address()
--

commit 2d8be9c8d60de13378d6fcee8e46e78f6a7a8167
Author: Ian Rogers <[email protected]>

arm64/unwind: Add Minimal DWARF CFI kernel unwinder

This commit adds CONFIG_UNWINDER_DWARF_CFI as a kernel unwinder choice alongside CONFIG_UNWINDER_FRAME_POINTER on arm64, building the kernel with -fomit-frame-pointer and unwinding kernel frames via Minimal DWARF CFI tables.

Quoted 21 lines
arch/arm64/Kconfig.debug +14 -0
index 265c4461031f4..4f5c99a2fa967 100644
@@ -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

arch/arm64/Kconfig.debug line 26

Quoted 10 lines
arch/arm64/Kconfig.debug +10 -0
+	  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

[Severity: Low]
Moving select FRAME_POINTER out of config ARM64 and under CONFIG_UNWINDER_FRAME_POINTER leaves CONFIG_FRAME_POINTER disabled when CONFIG_UNWINDER_DWARF_CFI=y. Because LATENCYTOP and FAULT_INJECTION_STACKTRACE_FILTER in lib/Kconfig.debug still depend on:

	depends on FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86

should ARM64 (or UNWINDER_DWARF_CFI) be added to those dependency lists so both features remain selectable with the DWARF CFI unwinder?

arch/arm64/Makefile ifeq ($(CONFIG_ARM64_ERRATUM_843419),y) · line 29

Quoted 12 lines
arch/arm64/Makefile +4 -0
index ed28f94be428e..7ec8e96b20329 100644
@@ -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

[Severity: Medium]
Does adding -fomit-frame-pointer globally to KBUILD_CFLAGS break user stack unwinding through the arm64 vDSO?

Unlike arch/arm64/kvm/hyp/nvhe/Makefile, arch/arm64/kernel/vdso/Makefile does not filter out -fomit-frame-pointer or pass -fno-omit-frame-pointer, and arch/arm64/kernel/vdso/vdso.lds.S discards *(.eh_frame .eh_frame_hdr). Non-leaf vDSO C functions (such as __kernel_getrandom and clock_gettime_fallback) are therefore built without frame records and linked without .eh_frame tables, breaking both arch_stack_walk_user() and user-space frame-pointer unwinders when a thread is inside the vDSO.

Quoted 11 lines
arch/arm64/include/asm/perf_event.h +3 -0
index ee45b4e773470..4a7dbb7ce41c9 100644
@@ -13,11 +13,26 @@
 #define perf_arch_bpf_user_pt_regs(regs) &regs->user_regs
 #endif
 
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+void arm64_unwind_perf_caller_regs(struct pt_regs *regs, unsigned long pc,
+				   unsigned long caller_ip, unsigned long sp,

arch/arm64/include/asm/perf_event.h line 28

Quoted 10 lines
arch/arm64/include/asm/perf_event.h +10 -0
+				   unsigned long fp);
+
+#define perf_arch_fetch_caller_regs(regs, __ip) do {			\
+	unsigned long __here_pc, __here_fp;				\
+	asm volatile("1: adr %0, 1b\n\t"				\
+		     "mov %1, x29"					\
+		     : "=r" (__here_pc), "=r" (__here_fp));		\
+	arm64_unwind_perf_caller_regs((regs), __here_pc, (__ip),	\
+				      current_stack_pointer, __here_fp);\
+} while (0)

[Severity: High]
Does perf_arch_fetch_caller_regs() need to perform a full DWARF CFI lookup and bytecode evaluation eagerly on every call, and does storing __ip in regs->pc cause kunwind_next_cfi() to look up the caller FDE at an off-by-4 address?

perf_fetch_caller_regs() runs unconditionally on every tracepoint hit in do_perf_trace_##call() and on every context switch with active software events in __perf_sw_event_sched(), even when no callchain is requested. Replacing the four inline register stores with arm64_unwind_perf_caller_regs() constructs stack_info descriptors, binary searches .eh_frame_hdr (and module FDE tables), and evaluates DWARF CFI bytecode on every event.

In addition, perf_fetch_caller_regs() passes CALLER_ADDR0 (call_insn + 4) as __ip. arm64_unwind_perf_caller_regs() steps regs->sp and regs->regs[29] to the caller frame and sets regs->pc = caller_ip, but when perf_callchain_kernel() later unwinds those regs, kunwind_init_from_regs() sets state->source = KUNWIND_SOURCE_REGS_PC. kunwind_next_cfi() then skips the - 4 adjustment:

	lookup_pc = (state->source == KUNWIND_SOURCE_REGS_PC) ?
		    state->common.pc : state->common.pc - 4;

and evaluates the caller's CFI at call_insn + 4 instead of call_insn, which can mis-unwind if call_insn sits immediately before an epilogue or FDE boundary.

Quoted 4 lines
arch/arm64/kernel/stacktrace.c +0 -0
index 3ebcf8c53fb04..9ce0e3f6cabe6 100644

[ ... ]

Quoted 15 lines
arch/arm64/kernel/stacktrace.c +8 -0
@@ -124,19 +363,35 @@ kunwind_init_from_task(struct kunwind_state *state,
 
 	state->common.fp = thread_saved_fp(task);
 	state->common.pc = thread_saved_pc(task);
+	state->sp = thread_saved_sp(task);
 	state->source = KUNWIND_SOURCE_TASK;
 }
 
+/**
+ * kunwind_recover_return_address() - Restore fgraph/kretprobe return addresses
+ * @state: Current ARM64 kernel unwind state.
+ *
+ * Replaces return_to_handler and __kretprobe_trampoline return addresses with
+ * the original caller PC from @state->task's shadow stacks in either hooking
+ * order. Under CONFIG_UNWINDER_DWARF_CFI (-fomit-frame-pointer), entries are

arch/arm64/kernel/stacktrace.c kunwind_init_from_task(struct kunwind_state *state, · line 386

Quoted 10 lines
arch/arm64/kernel/stacktrace.c +7 -0
+ * keyed on the frame's entry SP (@state->sp, equal to the callee's CFA) rather
+ * than x29.
+ *
+ * Return: 0 on success, or -EINVAL if a shadow return address cannot be found.
+ */
 static __always_inline int
 kunwind_recover_return_address(struct kunwind_state *state)
 {
+	void *frame_key = IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI) ?
+			  (void *)state->sp : (void *)state->common.fp;

[Severity: Low]
When both CONFIG_FUNCTION_GRAPH_TRACER and CONFIG_KRETPROBES are disabled, frame_key is unused in kunwind_recover_return_address(), triggering a -Wunused-variable warning. Should frame_key be marked __maybe_unused?

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

Re: [RFC PATCH v1 07/11] arm64/unwind: Add Minimal DWARF CFI kernel unwinder

In reply to Ian Rogers
TL;DR: - DWARF CFI unwinder may WARN or truncate traces when IRQ hits the ftrace_caller epilogue under function_graph - CFI lookups called from noinstr walks are kprobe-able - Build may fail without…
Quoted 1 line

arm64/unwind: Add Minimal DWARF CFI kernel unwinder

TL;DR:
- DWARF CFI unwinder may WARN or truncate traces when IRQ hits the ftrace_caller epilogue under function_graph
- CFI lookups called from noinstr walks are kprobe-able
- Build may fail without PERF_EVENTS; unconditional notrace/KCOV exclusion

Quoted 8 lines
arch/arm64/kernel/Makefile +1 -0
@@ -8,6 +8,7 @@ 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)
+CFLAGS_REMOVE_stacktrace.o = $(CC_FLAGS_FTRACE)

[ ... ]

arch/arm64/kernel/Makefile KASAN_SANITIZE_stacktrace.o := n · line 27

Quoted 4 lines
arch/arm64/kernel/Makefile +1 -0
@@ -24,6 +25,7 @@ KASAN_SANITIZE_stacktrace.o := n
 KCOV_INSTRUMENT_entry-common.o := n
 KCOV_INSTRUMENT_idle.o := n
+KCOV_INSTRUMENT_stacktrace.o := n

Both of these are unconditional, so they also apply to the default CONFIG_UNWINDER_FRAME_POINTER build, where the unwinder is unchanged.

Do dump_backtrace(), show_stack(), arch_stack_walk_user() and the other non-noinstr functions in stacktrace.c now lose function tracer, fentry/fexit BPF attachment and KCOV coverage for frame pointer kernels? The commit message does not mention this.

The noinstr walkers were already excluded, and the only new function that plausibly needs notrace is arm64_unwind_perf_caller_regs(), which exists only with CONFIG_UNWINDER_DWARF_CFI. Could these switches be made conditional on CONFIG_UNWINDER_DWARF_CFI, or could that one function be marked notrace instead?

Quoted 3 lines
arch/arm64/kernel/stacktrace.c +0 -0

[ ... ]

Quoted 2 lines

+ * Uses rcu_read_lock_sched_notrace() and rcu_dereference_raw() so lookups are
+ * safe inside noinstr stack walks and NMI contexts.

[ ... ]

Quoted 4 lines
arch/arm64/kernel/stacktrace.c +4 -0
+static __always_inline int
+arm64_dwarf_cfi_find(unsigned long pc, struct dwarf_cfi_row *row)
+{
+	size_t hdr_size = __stop_eh_frame_hdr - __start_eh_frame_hdr;

arch/arm64/kernel/stacktrace.c line 128

Quoted 10 lines
arch/arm64/kernel/stacktrace.c +10 -0
+	int err;
+
+	err = dwarf_cfi_unwind_eh_frame_hdr(__start_eh_frame_hdr, hdr_size,
+					    __start_eh_frame, __stop_eh_frame,
+					    pc, &arm64_cfi_arch, row);
+	if (!err)
+		return 0;
+
+	return arm64_dwarf_cfi_module_find(pc, row);
+}

arch_stack_walk(), arch_stack_walk_reliable() and arch_bpf_stack_walk() are noinline noinstr, with every helper __always_inline, so that the walk cannot be kprobed (see commit 0fbcd8abf337, "arm64: Prohibit instrumentation on arch_stack_walk()"). Lockdep and irq tracing reach the walk through return_address(), e.g. trace_hardirqs_off_finish() in arm64_enter_el1_dbg().

Doesn't this inlined helper make ordinary out-of-line calls into .text for every frame?

dwarf_cfi_unwind_eh_frame_hdr() (kernel/unwind/dwarf_cfi.c, no
NOKPROBE_SYMBOL)
__module_address() (kernel/module/main.c, for PCs outside
vmlinux)
dwarf_cfi_mod_eval() (dwarf_cfi.c, for module PCs)

None of these are in __noinstr_text or __kprobes_text, so the kprobe blacklist does not cover them. A probe on dwarf_cfi_unwind_eh_frame_hdr() can then be hit from inside the debug exception stack walk, which is the path the noinstr marking was meant to close. I could not show a nested KPROBE_REENTER BUG in this tree because reenter_kprobe() now recovers from KPROBE_HIT_SS reentry (23f851ac0078), but such probes would still be reentered and counted as missed.

Is the kernel-doc claim that these lookups are "safe inside noinstr stack walks and NMI contexts" accurate as written? Should the interpreter and module lookup entry points be noinstr or NOKPROBE_SYMBOL(), or the comment be corrected?

[ ... ]

arch/arm64/kernel/stacktrace.c line 144

Quoted 3 lines
arch/arm64/kernel/stacktrace.c +3 -0
+void arm64_unwind_perf_caller_regs(struct pt_regs *regs, unsigned long pc,
+				   unsigned long caller_ip, unsigned long sp,
+				   unsigned long fp)

arm64_unwind_perf_caller_regs() is a global function whose only prototype is in arch/arm64/include/asm/perf_event.h. stacktrace.c only gets that header through <linux/perf_event.h>, which includes <asm/perf_event.h> under CONFIG_PERF_EVENTS. CONFIG_PERF_EVENTS is user selectable on arm64 and UNWINDER_DWARF_CFI does not depend on it.

With CONFIG_PERF_EVENTS=n and CONFIG_UNWINDER_DWARF_CFI=y, doesn't this definition get compiled with no previous prototype, so that -Wmissing-prototypes (always enabled by scripts/Makefile.warn) fails the build under CONFIG_WERROR=y? The function and its EXPORT_SYMBOL_GPL() are also dead code in that configuration, since perf_fetch_caller_regs() has no callers without perf.

Should the definition and export be under CONFIG_PERF_EVENTS, or the prototype moved to a header that is always included?

[ ... ]

Quoted 1 line
arch/arm64/kernel/stacktrace.c +0 -0
@@ -159,6 +414,22 @@ kunwind_recover_return_address(struct kunwind_state *state)

[ ... ]

Quoted 5 lines
arch/arm64/kernel/stacktrace.c +5 -0
+#ifdef CONFIG_FUNCTION_GRAPH_TRACER
+	if (state->task->ret_stack &&
+	    (state->common.pc == (unsigned long)return_to_handler)) {
+		unsigned long orig_pc;
+

arch/arm64/kernel/stacktrace.c kunwind_recover_return_address(struct kunwind_state *state) · line 431

Quoted 10 lines
arch/arm64/kernel/stacktrace.c +10 -0
+		orig_pc = ftrace_graph_ret_addr(state->task, &state->graph_idx,
+						state->common.pc, frame_key);
+		if (state->common.pc == orig_pc) {
+			WARN_ON_ONCE(state->task == current);
+			return -EINVAL;
+		}
+		state->common.pc = orig_pc;
+		state->flags.fgraph = 1;
+	}
+#endif /* CONFIG_FUNCTION_GRAPH_TRACER */

Under CONFIG_UNWINDER_DWARF_CFI, frame_key is state->sp, which matches the retp recorded by ftrace_graph_func() only if the previous step computed a CFA. The link register fallback in kunwind_next_cfi() does not compute one:

	if (state->lr_valid && !is_bpf_text_address(lookup_pc)) {
		state->common.pc = state->lr;
		state->lr_valid = false;
		state->source = KUNWIND_SOURCE_FRAME;
		state->unreliable = true;
		return 0;
	}

state->sp is left at the interrupted SP, and kunwind_init_from_regs() and kunwind_next_regs_pc() now set lr_valid = !!regs->regs[30]. The ftrace_caller epilogue can reach this fallback:

	ldr  x29, [sp, #FREGS_FP]	// x29 = callsite FP
	ldr  x30, [sp, #FREGS_LR]	// x30 = return_to_handler if hooked
	ldr  x9,  [sp, #FREGS_PC]	// <- IRQ here
	add  sp, sp, #FREGS_SIZE + 32	// <- or here
	ret  x9

If an IRQ or pseudo-NMI lands on the ldr x9 or add sp instruction for a function F hooked by ftrace_graph_func():

- regs->pc is in ftrace_caller, so arm64_dwarf_cfi_find() fails.
- x29 is already restored, so the old_fp == state->sp + sizeof(struct __arch_ftrace_regs) check is false and the ftrace_caller special case is skipped.
- The fallback sets pc = regs->regs[30] = return_to_handler, and state->sp stays at the interrupted SP, which is below F's CFA.
- kunwind_next()->kunwind_recover_return_address() then finds no ret_stack entry whose retp equals that SP, so ftrace_graph_ret_addr() returns return_to_handler unchanged.

At that point state->common.pc == orig_pc, so WARN_ON_ONCE(state->task == current) fires and the walk returns -EINVAL, cutting the trace off. Current task walks that can reach this include perf_callchain_kernel(), show_regs()->dump_backtrace(regs), and any stack_trace_save() from IRQ context (lockdep, KASAN, kmemleak, page_owner). With function_graph tracing and perf -g sampling the two instruction window can be hit regularly, and with panic_on_warn it panics.

The frame pointer unwinder follows regs->regs[29] here and does not hit this. Can the ftrace_caller epilogue be recognised without relying on x29 (fregs->sp == state->sp + fsize is still valid until the add sp), or should the walk stop without a WARN when return_to_handler is recovered from an LR fallback whose SP was never advanced to a CFA?

[ ... ]

arch/arm64/kernel/stacktrace.c kunwind_next_frame_record(struct kunwind_state *state) · line 536

Quoted 7 lines
arch/arm64/kernel/stacktrace.c +3 -0
@@ -251,6 +531,212 @@ kunwind_next_frame_record(struct kunwind_state *state)
  * records (e.g. a cycle), determined based on the location and fp value of A
  * and the location (but not the fp value) of B.
  */
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+/**
+ * kunwind_next_cfi() - Step one ARM64 kernel frame using Minimal DWARF CFI

Doesn't inserting kunwind_next_cfi() here leave the existing block comment ("Unwind from one frame record (A) to the next frame record (B). We terminate early if ...") sitting above the new #ifdef and kernel-doc, about 200 lines away from kunwind_next(), which it was documenting?

The orphaned text describes frame record chaining, whereas kunwind_next_cfi() steps by DWARF CFI and only uses frame records as a fallback, so it is misleading for both functions. Could the CONFIG_UNWINDER_DWARF_CFI block be placed before that comment, directly after kunwind_next_frame_record()?

---
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/45087188604

author reviewer
#17 lore raw

RFC PATCH 8/11 riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding

In reply to Ian Rogers

Wire 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    |  8 +++
 arch/riscv/include/asm/unwind_user.h | 81 ++++++++++++++++++++++++++++
 arch/riscv/kernel/compat_signal.c    | 44 +++++++++++++++
 arch/riscv/kernel/signal.c           | 62 +++++++++++++++++++++
 5 files changed, 197 insertions(+)
 create mode 100644 arch/riscv/include/asm/unwind_user.h
arch/riscv/Kconfig +2 -0
index e7891a2a89da..84b61c755db3 100644
@@ -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 +8 -0
index 96dc56932e76..2c3e8eae56e5 100644
@@ -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,11 @@ 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 +81 -0

81 lines not on this page · raw message

arch/riscv/kernel/compat_signal.c +44 -0

53 lines not on this page · raw message

arch/riscv/kernel/signal.c +62 -0

71 lines not on this page · raw message

Signature · 1 line
2.56.1.750.gf70dc682cf-goog
#18 lore raw

Re: [RFC PATCH v1 08/11] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding

TL;DR: - Nits only: a comment names a nonexistent __compat_vdso_rt_sigreturn symbol - The !CONFIG_MMU branch in the sigreturn unwinder looks like dead code, since Kconfig requires MMU
Quoted 1 line

riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding

TL;DR:
- Nits only: a comment names a nonexistent __compat_vdso_rt_sigreturn symbol
- The !CONFIG_MMU branch in the sigreturn unwinder looks like dead code, since Kconfig requires MMU

Quoted 3 lines
arch/riscv/kernel/compat_signal.c +0 -0

[ ... ]

arch/riscv/kernel/compat_signal.c int compat_setup_rt_frame(struct ksignal *ksig, sigset_t *set, · line 255

Quoted 8 lines
arch/riscv/kernel/compat_signal.c +8 -0
+#ifdef CONFIG_UNWIND_USER
+/**
+ * compat_unwind_user_sigreturn() - Unwind an RV32 compat vDSO rt_sigreturn frame
+ * @state: Current user unwind state.
+ *
+ * Return: true if @state was at __compat_vdso_rt_sigreturn and advanced to the
+ * interrupted 32-bit user context, false otherwise.
+ */

This isn't a bug, but __compat_vdso_rt_sigreturn does not appear to exist anywhere in the tree.

arch/riscv/kernel/compat_vdso/rt_sigreturn.S just includes ../vdso/rt_sigreturn.S, so the compat vDSO symbol is also __vdso_rt_sigreturn, which COMPAT_VDSO_SYMBOL(mm->context.vdso, rt_sigreturn) resolves through compat__vdso_rt_sigreturn_offset.

Could the comment say "the compat vDSO __vdso_rt_sigreturn" instead?

Quoted 3 lines
arch/riscv/kernel/signal.c +0 -0

[ ... ]

Quoted 1 line

+#ifdef CONFIG_UNWIND_USER

[ ... ]

arch/riscv/kernel/signal.c bool sigaltstack_size_valid(size_t ss_size) · line 630

Quoted 8 lines
arch/riscv/kernel/signal.c +8 -0
+	frame = (struct rt_sigframe __user *)state->sp;
+#ifdef CONFIG_MMU
+	if (!mm->context.vdso)
+		return false;
+	sigret = (unsigned long)VDSO_SYMBOL(mm->context.vdso, rt_sigreturn);
+#else
+	sigret = (unsigned long)&frame->sigreturn_code;
+#endif

Can the !CONFIG_MMU branch here ever be built?

This function is inside #ifdef CONFIG_UNWIND_USER, and UNWIND_USER is only selected by HAVE_UNWIND_USER_FP and HAVE_UNWIND_USER_CFI. The Kconfig change in this patch selects both only when MMU is set:

select HAVE_UNWIND_USER_CFI if MMU
select HAVE_UNWIND_USER_FP if MMU

So CONFIG_UNWIND_USER=y on riscv implies CONFIG_MMU=y, and the &frame->sigreturn_code path can never be compiled or tested. Should the #ifdef CONFIG_MMU / #else be dropped, leaving only the vDSO lookup? A nommu variant could come together with the Kconfig change that enables it.

---
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/45087188604

author reviewer
#19 lore raw

RFC PATCH 9/11 riscv/unwind: Add Minimal DWARF CFI kernel unwinder

In reply to Ian Rogers

Add CONFIG_UNWINDER_DWARF_CFI for 64-bit MMU-enabled RISC-V kernels in arch/riscv/kernel/stacktrace.c, enabling frame-pointer-free kernel stack unwinding and HAVE_RELIABLE_STACKTRACE (arch_stack_walk_reliable()):

- Gate ARCH_WANT_FRAME_POINTERS and FRAME_POINTER on !UNWINDER_DWARF_CFI, build kernel C and Rust objects with asynchronous unwind tables and -fomit-frame-pointer, link vmlinux with --eh-frame-hdr, and suppress unwind tables in purgatory and the EFI libstub.
- Index SHF_ALLOC loadable module .eh_frame sections via dwarf_cfi_mod_alloc() and dwarf_cfi_mod_free_rcu() in arch/riscv/kernel/module.c.
- Annotate return_to_handler() and arch_rethook_trampoline() with .cfi_* directives, key rethook shadow stacks on entry SP (CFA) rather than s0, and implement walk_stackframe_cfi(), arch_stack_walk_reliable(), and bounds-checked riscv_unwind_perf_caller_regs() across task, IRQ, and overflow stacks, supporting RVC 16-bit call sites (pc - 2), ftrace_caller / return_to_handler / rethook recovery, BPF JIT and trampoline frame records, handle_exception / ret_from_fork_asm / head.S root terminations, and call_on_irq_stack() transitions.

---
 arch/riscv/Kconfig                            |   5 +-
 arch/riscv/Kconfig.debug                      |  16 +
 arch/riscv/Makefile                           |  15 +-
 arch/riscv/include/asm/module.h               |  22 +
 arch/riscv/include/asm/perf_event.h           |  15 +
 arch/riscv/include/asm/stacktrace.h           |  11 +
 arch/riscv/kernel/Makefile                    |   4 +
 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/stacktrace.c                | 732 +++++++++++++++++-
 arch/riscv/kernel/vmlinux.lds.S               |  13 +
 arch/riscv/purgatory/Makefile                 |   3 +-
 drivers/firmware/efi/libstub/Makefile         |   4 +-
 17 files changed, 919 insertions(+), 15 deletions(-)
arch/riscv/Kconfig +3 -2
index 84b61c755db3..14d64a3fa33c 100644
@@ -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
index eafe17ebf710..afc8be5ec97f 100644
@@ -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
index 44f5a439741a..ffa8842e7959 100644
@@ -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/module.h +22 -0
index 0f3baaa6a9a8..ff783889774b 100644
@@ -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
 
+#if defined(CONFIG_MODULE_SECTIONS) || defined(CONFIG_UNWINDER_DWARF_CFI)
 struct mod_arch_specific {
+#ifdef CONFIG_MODULE_SECTIONS
 	struct mod_section got;
 	struct mod_section plt;
 	struct mod_section got_plt;
+#endif
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+	struct mod_dwarf_cfi_index __rcu *dwarf_cfi_index;
+#endif
 };
+#endif
+
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+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 +15 -0
index bcc928fd3785..cfe95b9106e5 100644
@@ -12,6 +12,20 @@
 #include <linux/perf_event.h>
 #define perf_arch_bpf_user_pt_regs(regs) (struct user_regs_struct *)regs
 
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+void riscv_unwind_perf_caller_regs(struct pt_regs *regs, unsigned long pc,
+				   unsigned long caller_ip, unsigned long sp,
+				   unsigned long fp);
+
+#define perf_arch_fetch_caller_regs(regs, __ip) do {			\
+	unsigned long __here_pc, __here_fp;				\
+	asm volatile("1: auipc %0, 0\n\t"				\
+		     "mv %1, s0"					\
+		     : "=r" (__here_pc), "=r" (__here_fp));		\
+	riscv_unwind_perf_caller_regs((regs), __here_pc, (__ip),	\
+				      current_stack_pointer, __here_fp);\
+} while (0)
+#else
 #define perf_arch_fetch_caller_regs(regs, __ip) { \
 	(regs)->epc = (__ip); \
 	(regs)->s0 = (unsigned long) __builtin_frame_address(0); \
@@ -19,5 +33,6 @@
 	(regs)->status = SR_PP; \
 }
 #endif
+#endif
 
 #endif /* _ASM_RISCV_PERF_EVENT_H */
arch/riscv/include/asm/stacktrace.h +11 -0
index b1495a7e06ce..5a7b77367041 100644
@@ -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 +4 -0
index f54c336bf547..f2e1f342e3d7 100644
@@ -42,8 +42,12 @@ 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)
+CFLAGS_REMOVE_stacktrace.o = $(CC_FLAGS_FTRACE)
 endif
 
+KASAN_SANITIZE_stacktrace.o := n
+KCOV_INSTRUMENT_stacktrace.o := n
+
 always-$(KBUILD_BUILTIN) += vmlinux.lds
 
 obj-y	+= head.o
arch/riscv/kernel/entry.S +2 -0
index 61b7a7716697..0a37ac12128c 100644
@@ -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
index 082fe0b0e3c0..06c26725a830 100644
@@ -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
index da4a4000e57e..c13aa07cdb04 100644
@@ -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/module.c +9 -0
index 1961135689db..93092b17b53a 100644
@@ -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/probes/rethook.c +11 -2
index 5c27c1f50989..1ae3faf48218 100644
@@ -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
index c3aa8d8cf5af..50c68105c76b 100644
@@ -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 and fprobe 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/kernel/stacktrace.c +729 -3

758 lines not on this page · raw message

arch/riscv/kernel/vmlinux.lds.S +13 -0
index 1f4f8496941a..f2bd07e08d5e 100644
@@ -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
index b0358a78f11a..29c23c58b26c 100644
@@ -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
 
drivers/firmware/efi/libstub/Makefile +3 -1
index d62dabfdc1c3..19c2822eb302 100644
@@ -30,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.750.gf70dc682cf-goog
#20 lore raw

Re: [RFC PATCH v1 09/11] riscv/unwind: Add Minimal DWARF CFI kernel unwinder

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] riscv/unwind: off-by-one in return_address() from arch_stack_walk() tail call - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] riscv/unwind: off-by-one in return_address() from arch_stack_walk() tail call
- [Medium] riscv/unwind: broken leaf BPF frame detection in walk_stackframe_cfi()
- [Medium] riscv/unwind: riscv_stack_bounds() and handle_exception reject sp == high
--

commit fd04e120d9c16cff3a5efd054c9692101ae1abd1
Author: Ian Rogers <[email protected]>

riscv/unwind: Add Minimal DWARF CFI kernel unwinder

This commit adds CONFIG_UNWINDER_DWARF_CFI to enable frame-pointer-free kernel stack unwinding and reliable stack traces on 64-bit MMU-enabled RISC-V kernels using Minimal DWARF CFI.

Quoted 4 lines
arch/riscv/kernel/stacktrace.c +0 -0
index c7555447149bf..05f846c147877 100644

[ ... ]

Quoted 41 lines
arch/riscv/kernel/stacktrace.c +41 -0
+static __always_inline unsigned int
+riscv_stack_bounds(struct task_struct *task, unsigned long addr,
+		   size_t size, unsigned long *out_low,
+		   unsigned long *out_high)
+{
+	unsigned long low, high;
+
+	low = (unsigned long)task_stack_page(task);
+	high = low + THREAD_SIZE;
+	if (addr >= low && addr < high && addr + size >= addr &&
+	    addr + size <= high) {
+		*out_low = low;
+		*out_high = high;
+		return RISCV_STACK_TASK;
+	}
+
+	if (task == current && !preemptible()) {
+#ifdef CONFIG_IRQ_STACKS
+		low = (unsigned long)raw_cpu_read(irq_stack_ptr);
+		high = low + IRQ_STACK_SIZE;
+		if (low && addr >= low && addr < high && addr + size >= addr &&
+		    addr + size <= high) {
+			*out_low = low;
+			*out_high = high;
+			return RISCV_STACK_IRQ;
+		}
+#endif
+#ifdef CONFIG_VMAP_STACK
+		low = (unsigned long)raw_cpu_ptr(overflow_stack);
+		high = low + OVERFLOW_STACK_SIZE;
+		if (addr >= low && addr < high && addr + size >= addr &&
+		    addr + size <= high) {
+			*out_low = low;
+			*out_high = high;
+			return RISCV_STACK_OVERFLOW;
+		}
+#endif
+	}
+
+	return 0;
+}

[ ... ]

Quoted 18 lines
arch/riscv/kernel/stacktrace.c +18 -0
+		if (pc >= (unsigned long)handle_exception &&
+		    pc < (unsigned long)&ret_from_exception_end) {
+			struct pt_regs *er = (struct pt_regs *)sp;
+			unsigned long status, next_sp, next_ra;
+
+			if (sp & (sizeof(long) - 1))
+				return -EINVAL;
+			cur_stk = riscv_stack_bounds(task, sp, sizeof(*er),
+						     &cur_low, &cur_high);
+			if (!cur_stk)
+				return -EINVAL;
+			status = READ_ONCE_TASK_STACK(task, er->status);
+			if ((status & SR_PP) == 0)
+				return 0;
+			if (require_reliable)
+				return -EINVAL;
+
+			next_pc = READ_ONCE_TASK_STACK(task, er->epc);

arch/riscv/kernel/stacktrace.c line 476

Quoted 10 lines
arch/riscv/kernel/stacktrace.c +10 -0
+			next_sp = READ_ONCE_TASK_STACK(task, er->sp);
+			next_fp = READ_ONCE_TASK_STACK(task, er->s0);
+			next_ra = READ_ONCE_TASK_STACK(task, er->ra);
+			if (next_sp & (sizeof(long) - 1))
+				return -EINVAL;
+			next_stk = riscv_stack_bounds(task, next_sp,
+						      sizeof(long),
+						      &low, &high);
+			if (!next_stk)
+				return -EINVAL;

[Severity: Medium]
Does riscv_stack_bounds() reject a valid stack pointer at the top of the IRQ stack (sp == irq_stack_ptr + IRQ_STACK_SIZE)?

call_on_irq_stack() sets sp to irq_stack_ptr + IRQ_STACK_SIZE before calling handle_riscv_irq() or ___do_softirq(). At the pre-prologue entry (such as after unwinding ftrace_caller) or post-epilogue ret of that root function, sp equals high. Because riscv_stack_bounds() requires addr < high even when size == 0, and the handle_exception check passes size = sizeof(long) instead of 0 for next_sp, unwinding from or across that point aborts with -EINVAL.

[ ... ]

Quoted 27 lines
arch/riscv/kernel/stacktrace.c +27 -0
+			/*
+			 * Fallback to frame-pointer record at (fp - 16) for
+			 * JITed BPF programs and BPF trampolines.
+			 */
+			if (!require_reliable && !(sp & 0x7) &&
+			    riscv_stack_bounds(task, sp, /*size=*/0, &cur_low,
+					       &cur_high) &&
+			    !(fp & 0x7) &&
+			    fp >= sp + sizeof(struct stackframe) &&
+			    fp <= cur_high) {
+				struct stackframe *fr = (struct stackframe *)fp - 1;
+				unsigned long old_fp = fp;
+
+				next_fp = READ_ONCE_TASK_STACK(task, fr->fp);
+				next_pc = READ_ONCE_TASK_STACK(task, fr->ra);
+				if (exact_pc && ra_valid &&
+				    !(next_pc & 0x7) &&
+				    next_pc >= old_fp && next_pc <= cur_high) {
+					/* Leaf BPF prog without saved ra */
+					fp = next_pc;
+					pc = ra;
+				} else {
+					next_pc = riscv_recover_ret_addr(task,
+							&graph_idx, &kr_cur,
+							next_pc, old_fp,
+							&fr->ra);
+					if (!next_pc)

arch/riscv/kernel/stacktrace.c line 613

Quoted 10 lines
arch/riscv/kernel/stacktrace.c +10 -0
+						return 0;
+					fp = next_fp;
+					pc = next_pc;
+				}
+				sp = old_fp;
+				ra_valid = false;
+				exact_pc = false;
+				unreliable = true;
+				continue;
+			}

[Severity: Medium]
Will the leaf BPF program check fail when its C caller was built with -fomit-frame-pointer?

In bpf_jit_build_prologue(), a leaf BPF program omits saving RV_REG_RA and saves the caller's s0 at fp - 8 (fr->ra):

arch/riscv/net/bpf_jit_comp64.c:bpf_jit_build_prologue() {
    ...
	if (seen_reg(RV_REG_RA, ctx)) {
		emit_sd(RV_REG_SP, store_offset, RV_REG_RA, ctx);
		store_offset -= 8;
	}
	emit_sd(RV_REG_SP, store_offset, RV_REG_FP, ctx);
	store_offset -= 8;
    ...
}

Under CONFIG_UNWINDER_DWARF_CFI=y, the C caller uses s0 as an ordinary callee-saved register rather than a frame pointer in [old_fp, cur_high]. When an interrupt or perf sample lands inside a leaf BPF program, next_pc (the caller's s0) fails the [old_fp, cur_high] check and the else branch treats that s0 value as the return PC, truncating the stack trace above the BPF frame.

[ ... ]

arch/riscv/kernel/stacktrace.c line 752

Quoted 7 lines
arch/riscv/kernel/stacktrace.c +7 -0
+noinline void notrace walk_stackframe(struct task_struct *task,
+				      struct pt_regs *regs,
+				      bool (*fn)(void *, unsigned long),
+				      void *arg)
+{
+	walk_stackframe_cfi(task, regs, fn, arg, /*require_reliable=*/false);
+}

[Severity: Medium]
Can tail-call optimization of arch_stack_walk() -> walk_stackframe() shift return_address(level) by one frame under CONFIG_UNWINDER_DWARF_CFI=y?

return_address() sets data.level = level + 3 expecting return_address(), arch_stack_walk(), and walk_stackframe() to be separate frames:

arch/riscv/kernel/return_address.c:return_address() {
    ...
	data.level = level + 3;
	data.addr = NULL;

	arch_stack_walk(save_return_addr, &data, current, NULL);
    ...
}

Unlike CONFIG_FRAME_POINTER=y, CONFIG_UNWINDER_DWARF_CFI=y does not add -fno-optimize-sibling-calls, so arch_stack_walk() tail-calls the noinline walk_stackframe() without creating a stack frame. When walk_stackframe_cfi() skips walk_stackframe() via level = -1, the first frame reported to save_return_addr() is return_address() instead of arch_stack_walk(), causing return_address(level) and CALLER_ADDR* to return the caller at level + 1.

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

Re: [RFC PATCH v1 09/11] riscv/unwind: Add Minimal DWARF CFI kernel unwinder

In reply to Ian Rogers
TL;DR: - struct mod_arch_specific may be redefined (build error) with CONFIG_MODULES=n - Stack walk may stop at IRQ stack top, losing frames - return_address(n) may be off by one frame (unverified)…
Quoted 1 line

riscv/unwind: Add Minimal DWARF CFI kernel unwinder

TL;DR:
- struct mod_arch_specific may be redefined (build error) with CONFIG_MODULES=n
- Stack walk may stop at IRQ stack top, losing frames
- return_address(n) may be off by one frame (unverified)
- fprobe comment nit

Quoted 3 lines
arch/riscv/include/asm/module.h +0 -0

[ ... ]

arch/riscv/include/asm/module.h struct module; · line 35

Quoted 12 lines
arch/riscv/include/asm/module.h +7 -0
+#if defined(CONFIG_MODULE_SECTIONS) || defined(CONFIG_UNWINDER_DWARF_CFI)
 struct mod_arch_specific {
+#ifdef CONFIG_MODULE_SECTIONS
 	struct mod_section got;
 	struct mod_section plt;
 	struct mod_section got_plt;
+#endif
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+	struct mod_dwarf_cfi_index __rcu *dwarf_cfi_index;
+#endif
 };
+#endif

Can this define struct mod_arch_specific twice when CONFIG_MODULES=n?

UNWINDER_DWARF_CFI only does 'select HAVE_MOD_ARCH_SPECIFIC if MODULES', and MODULE_SECTIONS is selected by RELOCATABLE only 'if MODULES'. With CONFIG_MODULES=n and CONFIG_UNWINDER_DWARF_CFI=y, CONFIG_HAVE_MOD_ARCH_SPECIFIC is unset, so include/asm-generic/module.h (included first) already provides:

	#ifndef CONFIG_HAVE_MOD_ARCH_SPECIFIC
	struct mod_arch_specific
	{
	};
	#endif

include/linux/module.h includes <asm/module.h> even with CONFIG_MODULES=n, so the block above would then fail with a redefinition of struct mod_arch_specific.

Before this patch, MODULE_SECTIONS guarded the struct and also selected HAVE_MOD_ARCH_SPECIFIC, so the two always agreed.

Would guarding the struct with CONFIG_HAVE_MOD_ARCH_SPECIFIC, adding '&& defined(CONFIG_MODULES)' to the UNWINDER_DWARF_CFI half of the condition, or selecting HAVE_MOD_ARCH_SPECIFIC unconditionally from UNWINDER_DWARF_CFI be better?

Quoted 3 lines
arch/riscv/kernel/probes/rethook_trampoline.S +0 -0

[ ... ]

Quoted 7 lines

+/*
+ * 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 and fprobe return hooks.
+ */
SYM_CODE_START(arch_rethook_trampoline)

This isn't a bug, but does fprobe use rethook in this tree?

FPROBE selects FUNCTION_GRAPH_TRACER and kernel/trace/fprobe.c has no rethook references; the only rethook_hook() caller is pre_handler_kretprobe() in kernel/kprobes.c. So fprobe exits run through return_to_handler() in mcount.S rather than arch_rethook_trampoline().

Should the comment mention only kretprobes, or point fprobe readers at return_to_handler?

Quoted 3 lines
arch/riscv/kernel/stacktrace.c +0 -0

[ ... ]

arch/riscv/kernel/stacktrace.c line 635

Quoted 4 lines
arch/riscv/kernel/stacktrace.c +4 -0
+		if ((sp & (sizeof(long) - 1)) ||
+		    !riscv_stack_bounds(task, sp, /*size=*/0, &cur_low,
+					&cur_high))
+			return -EINVAL;

Can this reject a valid sp at the top of the IRQ stack?

The CFA check only rejects values above the top:

	if ((cfa & (sizeof(long) - 1)) || cfa < cur_low || cfa > cur_high)

and the call_on_irq_stack() transition accepts the top:

	sp <= irq_low + IRQ_STACK_SIZE &&

but riscv_stack_bounds(task, sp, /*size=*/0, ...) only matches when 'addr < high'.

When the walker reaches the function that call_on_irq_stack() called while it is still at its entry, sp is irq_stack_ptr + IRQ_STACK_SIZE, and the walk returns -EINVAL before it can use the entry row.

One way to reach it:

local_bh_enable()
do_softirq()

    do_softirq_own_stack()
      call_on_irq_stack(NULL, ___do_softirq)

If an ftrace callback on ___do_softirq takes a stack trace (func_stack_trace, or an fprobe event with a stacktrace trigger), the ftrace_caller branch sets sp to the IRQ stack top, and riscv_stack_bounds() then matches none of the task, IRQ or overflow stacks. The same happens for walks starting from ftrace_partial_regs() pt_regs where regs->sp is the top, for example fprobe/kprobe_multi BPF programs calling bpf_get_stackid()
-> perf_callchain_kernel() -> walk_stackframe(NULL, regs). It also happens to __do_softirq() when ___do_softirq() tail-calls it.

The trace then stops at ___do_softirq and loses call_on_irq_stack(), do_softirq_own_stack() and every frame on the task stack. There is no memory-safety impact, and the old frame-pointer unwinder could not cross the IRQ stack either, but this defeats the call_on_irq_stack() transition support the commit message describes.

Should riscv_stack_bounds() accept addr == high when size == 0, or should the IRQ stack top be special-cased here?

[ ... ]

arch/riscv/kernel/stacktrace.c line 752

Quoted 7 lines
arch/riscv/kernel/stacktrace.c +7 -0
+noinline void notrace walk_stackframe(struct task_struct *task,
+				      struct pt_regs *regs,
+				      bool (*fn)(void *, unsigned long),
+				      void *arg)
+{
+	walk_stackframe_cfi(task, regs, fn, arg, /*require_reliable=*/false);
+}

Does return_address(n) now return an address one frame too far up with CONFIG_UNWINDER_DWARF_CFI=y?

return_address() in arch/riscv/kernel/return_address.c does:

	data.level = level + 3;
	...
	arch_stack_walk(save_return_addr, &data, current, NULL);

The three skipped entries are arch_stack_walk, return_address and the caller of return_address, which assumes arch_stack_walk() has its own frame. That held because CONFIG_FRAME_POINTER builds pass -fno-optimize-sibling-calls (top-level Makefile). This patch makes FRAME_POINTER unavailable under UNWINDER_DWARF_CFI and adds -fomit-frame-pointer, so sibling-call optimisation is back on at -O2.

arch_stack_walk() is a single forwarding call:

	noinline noinstr void arch_stack_walk(stack_trace_consume_fn consume_entry,
					      void *cookie,
					      struct task_struct *task,
					      struct pt_regs *regs)
	{
		walk_stackframe(task, regs, consume_entry, cookie);
	}

which is a candidate for 'tail walk_stackframe', leaving no frame of its own. The walk would then report return_address, F, G, H instead of arch_stack_walk, return_address, F, G, so return_address(n) yields __builtin_return_address(n+1) of F.

That affects get_lock_parent_ip() (current->preempt_disable_ip, shown as "Preemption disabled at:") and the preemptirq tracepoints and the irqsoff/preemptoff tracers that use CALLER_ADDR1. s390, which also unwinds without frame pointers, adds CFLAGS_stacktrace.o += -fno-optimize-sibling-calls in arch/s390/kernel/Makefile for this reason.

I haven't verified this by compiling for RISC-V, so it is inferred from the compiler rules and the s390 precedent. Would adding -fno-optimize-sibling-calls for stacktrace.o under UNWINDER_DWARF_CFI, having arch_stack_walk() call an always-inline walker directly, or adjusting the skip count in return_address() be appropriate?

---
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/45087188604

author reviewer
#22 lore raw

RFC PATCH 10/11 selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test

In reply to Ian Rogers

Add 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, exercising per-frame CFI -> FP -> CFI -> FP -> CFI fallback and negative VMA caching in find_user_eh_frame_hdr()

---
 .../testing/selftests/perf_events/.gitignore  |   1 +
 tools/testing/selftests/perf_events/Makefile  |   4 +-
 .../selftests/perf_events/unwind_user_cfi.c   | 447 ++++++++++++++++++
 3 files changed, 451 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/perf_events/unwind_user_cfi.c
tools/testing/selftests/perf_events/.gitignore +1 -0
index 4931b3b6bbd3..4567b6563646 100644
@@ -3,3 +3,4 @@ sigtrap_threads
 remove_on_exec
 watermark_signal
 mmap
+unwind_user_cfi
tools/testing/selftests/perf_events/Makefile +3 -1
index 2e5d85770dfe..6a3a774544e8 100644
@@ -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 +447 -0

447 lines not on this page · raw message

Signature · 1 line
2.56.1.750.gf70dc682cf-goog
#23 lore raw

Re: [RFC PATCH v1 10/11] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test

TL;DR: - Selftest may report false "not ok" for 32-bit ARM builds on arm64 COMPAT kernels, since __arm__ is listed as supported (unverified) - Redundant PERF_RECORD_CALLCHAIN_DEFERRED #ifndef (nit)
Quoted 1 line

selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test

TL;DR:
- Selftest may report false "not ok" for 32-bit ARM builds on arm64 COMPAT kernels, since __arm__ is listed as supported (unverified)
- Redundant PERF_RECORD_CALLCHAIN_DEFERRED #ifndef (nit)

Quoted 4 lines
tools/testing/selftests/perf_events/unwind_user_cfi.c new file +0 -0
new file mode 100644

[ ... ]

tools/testing/selftests/perf_events/unwind_user_cfi.c line 42

Quoted 5 lines
tools/testing/selftests/perf_events/unwind_user_cfi.c new file +5 -0
+#include "../../../../include/linux/compiler_attributes.h"
+
+#ifndef PERF_RECORD_CALLCHAIN_DEFERRED
+#define PERF_RECORD_CALLCHAIN_DEFERRED 22
+#endif

this isn't a bug, but PERF_RECORD_CALLCHAIN_DEFERRED is an enumerator of enum perf_event_type, not a preprocessor macro, so the #ifndef is always true.

The defer_callchain and defer_output attr fields used later in main() come from the same uapi change as the enumerator, so any header that compiles this file already has it.

Could this #ifndef/#define fallback be dropped?

[ ... ]

tools/testing/selftests/perf_events/unwind_user_cfi.c line 302

Quoted 5 lines
tools/testing/selftests/perf_events/unwind_user_cfi.c new file +5 -0
+#if !defined(__x86_64__) && !defined(__i386__) && !defined(__aarch64__) && \
+	!defined(__arm__) && !defined(__riscv)
+	ksft_test_result_skip("Architecture lacks Minimal DWARF CFI user unwind support\n");
+	ksft_finished();
+#endif

A subsystem pattern flags this as potentially concerning: exiting with a status other than KSFT_SKIP when a feature is missing makes run_one() record "not ok".

Is __arm__ correct in this list of supported architectures?

The kernel CFI user unwinder finds unwind data only through PT_GNU_EH_FRAME. parse_user_elf32_eh_hdr() returns -ENOENT without it:

    if (!have_load0 || !have_eh || !eh_memsz)
        return -ENOENT;

As far as I know, arm-linux-gnueabi(hf) toolchains emit ARM EHABI tables (.ARM.exidx) rather than .eh_frame, so a normal AArch32 binary would have no PT_GNU_EH_FRAME. I did not have an ARM cross compiler to confirm this.

On a native arm32 kernel, arch/arm does not select HAVE_UNWIND_USER_FP or HAVE_UNWIND_USER_CFI, so no deferred record arrives and the test reaches its "No PERF_RECORD_CALLCHAIN_DEFERRED records" skip.

On an arm64 kernel with CONFIG_COMPAT, deferred records are produced since unwind_user_cfi_arch() accepts ws == 4. Each frame gets -ENOENT from unwind_user_next_cfi(), and unwind_user_next() falls back to unwind_user_next_fp(), which expects APCS frames at compat_fp (r11). A -fomit-frame-pointer build does not have those.

The record then stops after one or two entries and saw_full_chain stays false:

    ksft_test_result(saw_full_chain, "unwind_user Minimal DWARF CFI across ...\n");
    ksft_finished();

ksft_finished() exits with KSFT_FAIL, so a 32-bit ARM build run on an arm64 COMPAT kernel reports "not ok" because of an unsupported unwind format rather than a kernel regression.

Should __arm__ be dropped from the supported list so the existing skip runs, or should the test skip when the binary has no PT_GNU_EH_FRAME?

---
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/45087188604

author reviewer
#24 lore raw

RFC PATCH 11/11 scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer

In reply to Ian Rogers

Add 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 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 | 938 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 938 insertions(+)
 create mode 100755 scripts/eh_frame_min.py
scripts/eh_frame_min.py new file +938 -0
new file mode 100755
index 000000000000..6a64563a7c40
@@ -0,0 +1,938 @@
+#!/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, 2}},              # EM_386
+    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
+    has_indirect = 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]
+                if lsda_enc != DW_EH_PE_omit and (lsda_enc & DW_EH_PE_indirect):
+                    has_indirect = True
+                ap += 1
+            elif ch == "P":
+                p_enc = buf[ap]
+                ap += 1
+                if p_enc & DW_EH_PE_indirect:
+                    has_indirect = True
+                _, 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]
+                if fde_enc & DW_EH_PE_indirect:
+                    has_indirect = True
+                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), FP, RA}.
+    """
+    sp_reg = arch["sp"]
+    fp_reg = arch["fp"]
+    ra_reg = cie["ra_reg"]
+    tracked_regs = {fp_reg, ra_reg}
+
+    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,
+            "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, new_row_snapshot)
+    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))
+
+    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 = "fp" if reg == fp_reg else "ra"
+                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 = "fp" if reg == fp_reg else "ra"
+                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:
+            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 = "fp" if reg == fp_reg else "ra"
+                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 = "fp" if reg == fp_reg else "ra"
+                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 = "fp" if reg == fp_reg else "ra"
+                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 = "fp" if reg == fp_reg else "ra"
+                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 = "fp" if reg == fp_reg else "ra"
+                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 = "fp" if reg == fp_reg else "ra"
+                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, 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)
+            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)):
+                soff, epos = read_sleb128(expr, 1, len(expr) - 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)
+            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",)):
+                    soff, epos = read_sleb128(expr, 1, len(expr))
+                    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)):
+                soff, epos = read_sleb128(expr, 1, len(expr))
+                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 or r1 == sp_reg:
+                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 or r1 == sp_reg:
+                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 or r1 == sp_reg:
+                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
+
+    # 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
+            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
+    savings_pct = (100.0 * (1.0 - len(min_eh_stream) / eh_size)) if eh_size else 0.0
+    total_savings_pct = (100.0 * (1.0 - min_total / orig_total)) if orig_total 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)")
+    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, -{savings_pct:.1f}% vs .eh_frame)")
+    print(f"  Minified + .eh_frame_hdr: {min_total:10,d} B  (-{total_savings_pct:.1f}% combined)")
+    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.750.gf70dc682cf-goog
#25 lore raw

Re: [RFC PATCH v1 11/11] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer

TL;DR: - eh_frame_min.py may abort with a traceback on a valid truncated-looking CFA expression, skipping later files - i386 DRAP registers look wrong, skewing coverage - combined savings figure for…
Quoted 1 line

scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer

TL;DR:
- eh_frame_min.py may abort with a traceback on a valid truncated-looking CFA expression, skipping later files
- i386 DRAP registers look wrong, skewing coverage
- combined savings figure for .o/.ko compares unlike sizes
- dead variable and stale comment (nits)

Quoted 4 lines
scripts/eh_frame_min.py new file +0 -0
new file mode 100755

[ ... ]

scripts/eh_frame_min.py line 56

Quoted 4 lines
scripts/eh_frame_min.py new file +4 -0
+# 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, 2}},              # EM_386

In i386 DWARF numbering 1 is %ecx and 2 is %edx. GCC's i386 DRAP register is %ecx, or %edi (DWARF 7) when the function emits tail calls, needs a static chain, or uses regparm 3 as the i386 kernel does. %edx is never the DRAP register. The set {1, 2} looks like the x86_64 numbers reused without renumbering.

When a stack-realigning function uses %edi as DRAP, the script sees "DW_CFA_def_cfa: r7 ofs 0", records "def_cfa non-SP/FP reg=7" and counts the FDE as unsupported, and --minify leaves it out. The same prologue using %ecx is counted as supported.

The kernel interpreter (cfi_set_cfa_reg() in kernel/unwind/dwarf_cfi.c) and scripts/min_eh_frame.c accept either register, so the reported coverage for i386 inputs differs from what the minifier would keep. Should the i386 entry be {1, 7}?

[ ... ]

Quoted 1 line

+ has_indirect = False

This isn't a bug, but parse_cie() sets has_indirect to True in the 'L', 'P' and 'R' augmentation branches and nothing ever reads it. The returned dict derives the flag the caller uses independently:

"has_indirect_fde": bool(fde_enc & DW_EH_PE_indirect),

Could the variable and its assignments be removed? The "offset", "version", "aug" and "lsda_enc" entries of the same dict also appear to have no consumer in analyze_elf() or decode_and_minify_insns().

[ ... ]

Quoted 1 line

+ # Stream of abstract events: ("adv", delta_units) or ("op", raw_bytes, new_row_snapshot)

Is the comment accurate? emit_op() appends only 2-tuples:

    events.append(("op", raw_bytes))

and the rest of decode_and_minify_insns() relies on that form, for example the "for kind, payload in events:" loop and the restore_state elision that compares against ("op", bytes([DW_CFA_remember_state])). Row snapshots are kept in state_stack. Should the comment describe ("op", raw_bytes)?

[ ... ]

scripts/eh_frame_min.py line 640

Quoted 8 lines
scripts/eh_frame_min.py new file +8 -0
+        elif op == DW_CFA_def_cfa_expression:
+            expr_len, pos = read_uleb128(insns, pos, end)
+            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)):
+                soff, epos = read_sleb128(expr, 1, len(expr) - 1)

Can this read_sleb128() call raise an uncaught ValueError? It raises "Truncated SLEB128" when no terminating byte appears before the end. A valid expression whose SLEB128 operand ends in 0x06 with no DW_OP_deref after it hits this, for example on x86_64:

    DW_CFA_def_cfa_expression 3: DW_OP_breg7 0x80 0x06

Here expr[0] == 0x70 + sp_reg and expr[-1] == 0x06, so the guard passes and read_sleb128(expr, 1, 2) reads 0x80 with the continuation bit set and runs off the end.

Nothing catches the exception in decode_and_minify_insns(), analyze_elf() or main(), so the script aborts with a traceback, later files on the command line are not analyzed, and --minify writes no output.

The kernel parser treats the same bytes as an unsupported FDE (cfi_parse_indirect_cfa_expr() returns -EINVAL), and scripts/min_eh_frame.c does likewise. Should the analyzer append the opcode name to reasons and mark the FDE unsupported instead? The script is aimed at arbitrary user-space binaries and shared libraries, so the input is not controlled.

[ ... ]

Quoted 1 line

+ min_eh_hdr_size = 12 + supported_fdes * 8

[ ... ]

Quoted 4 lines
scripts/eh_frame_min.py new file +4 -0
+    orig_total = eh_size + eh_hdr_size
+    min_total = len(min_eh_stream) + min_eh_hdr_size
+    savings_pct = (100.0 * (1.0 - len(min_eh_stream) / eh_size)) if eh_size else 0.0
+    total_savings_pct = (100.0 * (1.0 - min_total / orig_total)) if orig_total else 0.0

[ ... ]

Quoted 1 line

+ print(f" Minified + .eh_frame_hdr: {min_total:10,d} B (-{total_savings_pct:.1f}% combined)")

Is the combined figure comparing like with like? The minified side adds a simulated .eh_frame_hdr of 12 + 8 bytes per supported FDE, while the original side uses the input's real .eh_frame_hdr. Relocatable inputs (.o and .ko, as in the commit message examples) have no .eh_frame_hdr, so eh_hdr_size is 0 and only the minified side is charged for the lookup table.

Since minification barely shrinks .eh_frame, total_savings_pct comes out around -20% for every object or module.

The sign also looks wrong, because the format string prints a literal '-' before the value, so a negative percentage renders as something like "(--24.0% combined)".

Could the original side simulate 12 + 8 * total_fdes when the input has no .eh_frame_hdr, or could the simulated header be skipped when eh_hdr_size is 0, with the sign taken from the value?

---
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/45087188604

#26 lore raw
In reply to Ian Rogers
Sashiko has finished reviewing this 11-patch series:

Sashiko has finished reviewing this 11-patch series:

- Patches 3-5, 8, 10, and 11: no issues found.
- Patch 1 ("unwind: Add Minimal DWARF CFI bytecode interpreter a..."): 3 potential issues (3 Medium)
- Patch 2 ("unwind_user: Support Minimal DWARF CFI user-space un..."): 1 potential issue (1 High)
- Patch 6 ("arm64: unwind_user: Support Minimal DWARF CFI and FP..."): 3 potential issues (3 Medium)
- Patch 7 ("arm64/unwind: Add Minimal DWARF CFI kernel unwinder"): 4 potential issues (1 High, 1 Medium, 2 Low)
- Patch 9 ("riscv/unwind: Add Minimal DWARF CFI kernel unwinder"): 3 potential issues (3 Medium)

Detailed reviews have been sent as separate replies to patches 1, 2, 6, 7, and 9.

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