Linux-ARM-Kernel Archive on lore.kernel.org
 help / color / mirror / Atom feed
* [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv
@ 2026-11-22 23:57 Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 01/11] unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests Ian Rogers
                   ` (10 more replies)
  0 siblings, 11 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	Ian Rogers

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
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 01/11] unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 02/11] unwind_user: Support Minimal DWARF CFI user-space unwinding Ian Rogers
                   ` (9 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	Ian Rogers

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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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

diff --git a/arch/Kconfig b/arch/Kconfig
index 1163736de1f9..03399120aa8f 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -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
 
diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig
index 9b08b2457a55..ee0f263f477d 100644
--- a/arch/arm64/Kconfig
+++ b/arch/arm64/Kconfig
@@ -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"
diff --git a/include/linux/unwind_dwarf_cfi.h b/include/linux/unwind_dwarf_cfi.h
new file mode 100644
index 000000000000..66abb9ee24b9
--- /dev/null
+++ b/include/linux/unwind_dwarf_cfi.h
@@ -0,0 +1,174 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_UNWIND_DWARF_CFI_H
+#define _LINUX_UNWIND_DWARF_CFI_H
+
+#include <linux/types.h>
+
+/*
+ * Minimal DWARF Call Frame Information (CFI) unwinder subset.
+ *
+ * Evaluates a strictly bounded, non-Turing-complete subset of .eh_frame and
+ * .eh_frame_hdr tables matching SFrame's stack-unwinding state model (plus
+ * fixed-pattern DRAP stack-realignment and signal-frame expressions):
+ *  - Advances PC monotonically through a single FDE (no backward jumps)
+ *  - Tracks CFA = (SP | FP | scratch) + cfa_off or *(FP/SP + cfa_off)
+ *  - Tracks stack save offsets for FP and RA (ignoring callee-saved GPR spills)
+ *  - Rejects general DWARF expressions, register-to-register rules on SP/FP/RA,
+ *    and DW_EH_PE_indirect pointer dereferences.
+ */
+
+/* Hard safety bounds enforced on CIE/FDE lengths, offsets, and state stack */
+#define DWARF_CFI_MAX_CIE_LEN		128U
+#define DWARF_CFI_MAX_FDE_LEN		4096U
+#define DWARF_CFI_MAX_CIE_DELTA		(64U * 1024U * 1024U)
+#define DWARF_CFI_MAX_FDE_COUNT		(4U * 1024U * 1024U)
+#define DWARF_CFI_MAX_STATE_STACK	4U
+
+/**
+ * enum dwarf_cfi_base - Base register or addressing mode for computing the CFA
+ * @DWARF_CFI_BASE_UNDEFINED: CFA rule has not been established yet.
+ * @DWARF_CFI_BASE_SP: CFA = stack pointer + cfa_off.
+ * @DWARF_CFI_BASE_FP: CFA = frame pointer + cfa_off.
+ * @DWARF_CFI_BASE_FP_INDIRECT: DRAP stack realignment: CFA = *(FP + cfa_off).
+ * @DWARF_CFI_BASE_SP_INDIRECT: Signal trampoline frame: CFA = *(SP + cfa_off).
+ * @DWARF_CFI_BASE_REG: Transient prologue/epilogue scratch register:
+ *                      CFA = reg(cfa_reg) + cfa_off.
+ */
+enum dwarf_cfi_base {
+	DWARF_CFI_BASE_UNDEFINED = 0,
+	DWARF_CFI_BASE_SP,
+	DWARF_CFI_BASE_FP,
+	DWARF_CFI_BASE_FP_INDIRECT,
+	DWARF_CFI_BASE_SP_INDIRECT,
+	DWARF_CFI_BASE_REG,
+};
+
+/**
+ * enum dwarf_cfi_rule - Recovery rule for the caller's FP or return address
+ * @DWARF_CFI_RULE_SAME: Register retains its value from the current frame
+ *                       (e.g. leaf function link register or unmodified FP).
+ * @DWARF_CFI_RULE_OFFSET: Saved on the stack at *(CFA + off).
+ * @DWARF_CFI_RULE_FP_OFFSET: Saved relative to FP at *(FP + off) (DRAP frame).
+ * @DWARF_CFI_RULE_SP_OFFSET: Saved relative to SP at *(SP + off) (sigframe).
+ * @DWARF_CFI_RULE_UNDEFINED: Explicitly undefined (DW_CFA_undefined); marks
+ *                            the bottom of a stack (e.g. _start or clone).
+ */
+enum dwarf_cfi_rule {
+	DWARF_CFI_RULE_SAME = 0,
+	DWARF_CFI_RULE_OFFSET,
+	DWARF_CFI_RULE_FP_OFFSET,
+	DWARF_CFI_RULE_SP_OFFSET,
+	DWARF_CFI_RULE_UNDEFINED,
+};
+
+/**
+ * struct dwarf_cfi_arch - Architecture DWARF register numbers and word size
+ * @ws: Target address/word size in bytes (4 or 8).
+ * @sp_reg: DWARF register number for the stack pointer.
+ * @fp_reg: DWARF register number for the frame pointer.
+ * @ra_reg: Default DWARF return-address column number.
+ */
+struct dwarf_cfi_arch {
+	u8 ws;
+	u8 sp_reg;
+	u8 fp_reg;
+	u8 ra_reg;
+};
+
+/**
+ * struct dwarf_cfi_row - Evaluated Minimal DWARF unwind state at a target PC
+ * @cfa_off: Byte offset added to the CFA base register before or as the CFA.
+ * @fp_off: Byte offset used to load the saved FP when @fp_rule is an offset.
+ * @ra_off: Byte offset used to load the saved RA when @ra_rule is an offset.
+ * @cfa_base: CFA computation mode (&enum dwarf_cfi_base).
+ * @cfa_reg: DWARF register number when @cfa_base is %DWARF_CFI_BASE_REG.
+ * @fp_rule: Recovery rule for the frame pointer (&enum dwarf_cfi_rule).
+ * @ra_rule: Recovery rule for the return address (&enum dwarf_cfi_rule).
+ * @signal: True if the CIE carries the 'S' signal/interrupt frame augmentation,
+ *          indicating that the saved PC points directly to the interrupted
+ *          instruction rather than after a call instruction.
+ * @ra_signed: True on AArch64 when DW_CFA_AARCH64_negate_ra_state indicates
+ *             that the saved return address carries a PAC signature.
+ */
+struct dwarf_cfi_row {
+	s32 cfa_off;
+	s32 fp_off;
+	s32 ra_off;
+	u8 cfa_base;
+	u8 cfa_reg;
+	u8 fp_rule;
+	u8 ra_rule;
+	bool signal;
+	bool ra_signed;
+};
+
+/**
+ * struct eh_frame_hdr_entry - Binary-search index entry for an FDE
+ * @start_off: Signed 32-bit offset from the table base (or entry field) to the
+ *             FDE's initial PC location.
+ * @fde_off: Signed 32-bit offset from the table base (or entry field) to the
+ *           start of the FDE record in .eh_frame.
+ */
+struct eh_frame_hdr_entry {
+	s32 start_off;
+	s32 fde_off;
+};
+
+#ifdef CONFIG_UNWIND_DWARF_CFI
+
+extern const u8 __start_eh_frame_hdr[];
+extern const u8 __stop_eh_frame_hdr[];
+extern const u8 __start_eh_frame[];
+extern const u8 __stop_eh_frame[];
+
+int dwarf_cfi_eval_fde_kmem(const u8 *fde, const u8 *eh_start,
+			    const u8 *eh_end, unsigned long pc,
+			    const struct dwarf_cfi_arch *arch,
+			    struct dwarf_cfi_row *out_row);
+
+int dwarf_cfi_unwind_eh_frame_hdr(const u8 *hdr, size_t hdr_size,
+				  const u8 *eh_start, const u8 *eh_end,
+				  unsigned long pc,
+				  const struct dwarf_cfi_arch *arch,
+				  struct dwarf_cfi_row *out_row);
+
+int dwarf_cfi_scan_eh_frame_kmem(const u8 *eh_start, size_t eh_size,
+				 const struct dwarf_cfi_arch *arch,
+				 unsigned long base_addr,
+				 struct eh_frame_hdr_entry *entries,
+				 unsigned int max_entries,
+				 unsigned int *out_count);
+
+int dwarf_cfi_unwind_user_eh_frame_hdr(unsigned long hdr_uaddr,
+				       size_t hdr_size, unsigned long pc,
+				       const struct dwarf_cfi_arch *arch,
+				       struct dwarf_cfi_row *out_row);
+
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+/**
+ * struct mod_dwarf_cfi_index - Sorted FDE lookup table for a loadable module
+ * @num_fdes: Number of sorted FDE index entries in @entries.
+ * @eh_frame: Pointer to the module's in-memory SHF_ALLOC .eh_frame section;
+ *            also serves as the base address for @entries offsets.
+ * @eh_frame_size: Size in bytes of the module's .eh_frame section.
+ * @entries: Sorted binary-search table mapping PCs to module FDEs.
+ */
+struct mod_dwarf_cfi_index {
+	unsigned int num_fdes;
+	const u8 *eh_frame;
+	size_t eh_frame_size;
+	struct eh_frame_hdr_entry entries[] __counted_by(num_fdes);
+};
+
+struct mod_dwarf_cfi_index *dwarf_cfi_mod_alloc(const void *eh_frame,
+						size_t eh_frame_size,
+						const struct dwarf_cfi_arch *arch);
+void dwarf_cfi_mod_free_rcu(struct mod_dwarf_cfi_index *idx);
+int dwarf_cfi_mod_eval(const struct mod_dwarf_cfi_index *idx, unsigned long ip,
+		       const struct dwarf_cfi_arch *arch,
+		       struct dwarf_cfi_row *out_row);
+#endif
+
+#endif /* CONFIG_UNWIND_DWARF_CFI */
+
+#endif /* _LINUX_UNWIND_DWARF_CFI_H */
diff --git a/kernel/unwind/Makefile b/kernel/unwind/Makefile
index eae37bea54fd..73a1ccc2ad77 100644
--- a/kernel/unwind/Makefile
+++ b/kernel/unwind/Makefile
@@ -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
diff --git a/kernel/unwind/dwarf_cfi.c b/kernel/unwind/dwarf_cfi.c
new file mode 100644
index 000000000000..3e474bce1ab5
--- /dev/null
+++ b/kernel/unwind/dwarf_cfi.c
@@ -0,0 +1,1842 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Minimal DWARF Call Frame Information (CFI) bytecode interpreter.
+ *
+ * Implements a strictly bounded subset of .eh_frame / .eh_frame_hdr matching
+ * SFrame's expressiveness: PC advancement, SP/FP-based CFA offsets, and FP/RA
+ * stack save offsets. Callee-saved GPR spills are decoded and ignored; DWARF
+ * expressions and indirect pointer encodings are rejected.
+ */
+
+#include <linux/errno.h>
+#include <linux/kernel.h>
+#include <linux/limits.h>
+#include <linux/nospec.h>
+#include <linux/overflow.h>
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+#include <linux/rcupdate.h>
+#include <linux/slab.h>
+#include <linux/sort.h>
+#endif
+#include <linux/string.h>
+#include <linux/uaccess.h>
+#include <linux/unaligned.h>
+#include <linux/unwind_dwarf_cfi.h>
+
+/* DWARF Call Frame Instruction opcodes */
+#define DW_CFA_nop				0x00
+#define DW_CFA_set_loc				0x01
+#define DW_CFA_advance_loc1			0x02
+#define DW_CFA_advance_loc2			0x03
+#define DW_CFA_advance_loc4			0x04
+#define DW_CFA_offset_extended			0x05
+#define DW_CFA_restore_extended			0x06
+#define DW_CFA_undefined			0x07
+#define DW_CFA_same_value			0x08
+#define DW_CFA_register				0x09
+#define DW_CFA_remember_state			0x0a
+#define DW_CFA_restore_state			0x0b
+#define DW_CFA_def_cfa				0x0c
+#define DW_CFA_def_cfa_register			0x0d
+#define DW_CFA_def_cfa_offset			0x0e
+#define DW_CFA_def_cfa_expression		0x0f
+#define DW_CFA_expression			0x10
+#define DW_CFA_offset_extended_sf		0x11
+#define DW_CFA_def_cfa_sf			0x12
+#define DW_CFA_def_cfa_offset_sf		0x13
+#define DW_CFA_val_offset			0x14
+#define DW_CFA_val_offset_sf			0x15
+#define DW_CFA_val_expression			0x16
+#define DW_CFA_AARCH64_negate_ra_state		0x2d
+#define DW_CFA_GNU_args_size			0x2e
+#define DW_CFA_GNU_negative_offset_extended	0x2f
+
+/* Fixed DWARF expression opcodes for DRAP stack-realigned frames */
+#define DW_OP_deref				0x06
+#define DW_OP_breg0				0x70
+
+/* Exception Header Pointer Encoding formats */
+#define DW_EH_PE_omit		0xff
+#define DW_EH_PE_FORM		0x0f
+#define DW_EH_PE_absptr		0x00
+#define DW_EH_PE_uleb128	0x01
+#define DW_EH_PE_udata2		0x02
+#define DW_EH_PE_udata4		0x03
+#define DW_EH_PE_udata8		0x04
+#define DW_EH_PE_sleb128	0x09
+#define DW_EH_PE_sdata2		0x0a
+#define DW_EH_PE_sdata4		0x0b
+#define DW_EH_PE_sdata8		0x0c
+
+#define DW_EH_PE_ADJUST		0x70
+#define DW_EH_PE_abs		0x00
+#define DW_EH_PE_pcrel		0x10
+#define DW_EH_PE_datarel	0x30
+#define DW_EH_PE_indirect	0x80
+
+#define DWARF_CFI_WIN_SIZE	128U
+
+/**
+ * struct dwarf_cfi_cie - Parsed Common Information Entry (CIE) attributes
+ * @code_align: Multiplier applied to DW_CFA_advance_loc* deltas.
+ * @data_align: Signed multiplier applied to factored register/CFA offsets.
+ * @ra_reg: DWARF register column holding the return address for this CIE.
+ * @fde_enc: DW_EH_PE_* pointer encoding for FDE initial_location and range.
+ * @has_z: True if the CIE augmentation string starts with 'z' (length-prefixed
+ *         augmentation data present in both CIE and FDEs).
+ * @signal: True if the CIE augmentation string includes 'S' (signal/interrupt
+ *          frame where PC is not decremented before FDE lookup).
+ */
+struct dwarf_cfi_cie {
+	u32 code_align;
+	s32 data_align;
+	u8 ra_reg;
+	u8 fde_enc;
+	bool has_z;
+	bool signal;
+};
+
+/**
+ * struct dwarf_cfi_stream - Bounded byte reader over kernel or user memory
+ * @buf: Active byte buffer (direct kernel pointer or @scratch window).
+ * @pos: Current byte offset within @buf.
+ * @win_len: Number of valid bytes currently available in @buf.
+ * @rem_after_win: Remaining bytes in user memory after the current window.
+ * @next_uaddr: Next user virtual address to copy when refilling @scratch.
+ * @cur_base_addr: Virtual address corresponding to @buf[0] (used for
+ *                 DW_EH_PE_pcrel pointer decoding).
+ * @scratch: Caller-supplied %DWARF_CFI_WIN_SIZE stack buffer for user streams.
+ * @is_user: False for zero-copy kernel memory, true for windowed user memory.
+ */
+struct dwarf_cfi_stream {
+	const u8 *buf;
+	size_t pos;
+	size_t win_len;
+	size_t rem_after_win;
+	unsigned long next_uaddr;
+	unsigned long cur_base_addr;
+	u8 *scratch;
+	bool is_user;
+};
+
+static __always_inline void cfi_stream_init_kmem(struct dwarf_cfi_stream *s,
+						 const u8 *ptr, size_t len)
+{
+	s->buf = ptr;
+	s->pos = 0;
+	s->win_len = len;
+	s->rem_after_win = 0;
+	s->next_uaddr = 0;
+	s->cur_base_addr = (unsigned long)ptr;
+	s->scratch = NULL;
+	s->is_user = false;
+}
+
+static int cfi_stream_init_user(struct dwarf_cfi_stream *s, unsigned long uaddr,
+				size_t len, u8 *scratch)
+{
+	size_t chunk = min_t(size_t, len, DWARF_CFI_WIN_SIZE);
+
+	if (chunk && copy_from_user(scratch, (const void __user *)uaddr, chunk))
+		return -EFAULT;
+
+	s->buf = scratch;
+	s->pos = 0;
+	s->win_len = chunk;
+	s->rem_after_win = len - chunk;
+	s->next_uaddr = uaddr + chunk;
+	s->cur_base_addr = uaddr;
+	s->scratch = scratch;
+	s->is_user = true;
+	return 0;
+}
+
+static __always_inline bool cfi_stream_empty(const struct dwarf_cfi_stream *s)
+{
+	return s->pos >= s->win_len && (!s->is_user || s->rem_after_win == 0);
+}
+
+static __always_inline unsigned long
+cfi_stream_addr(const struct dwarf_cfi_stream *s)
+{
+	return s->cur_base_addr + s->pos;
+}
+
+static noinline int cfi_stream_refill(struct dwarf_cfi_stream *s)
+{
+	size_t chunk;
+
+	if (!s->is_user || !s->rem_after_win || !s->scratch)
+		return -EINVAL;
+
+	chunk = min_t(size_t, s->rem_after_win, DWARF_CFI_WIN_SIZE);
+	if (copy_from_user(s->scratch, (const void __user *)s->next_uaddr, chunk))
+		return -EFAULT;
+
+	s->cur_base_addr = s->next_uaddr;
+	s->next_uaddr += chunk;
+	s->rem_after_win -= chunk;
+	s->pos = 0;
+	s->win_len = chunk;
+	return 0;
+}
+
+static __always_inline int cfi_read_u8(struct dwarf_cfi_stream *s, u8 *val)
+{
+	size_t idx;
+
+	if (unlikely(s->pos >= s->win_len)) {
+		int err;
+
+		if (!s->is_user)
+			return -EINVAL;
+		err = cfi_stream_refill(s);
+		if (err)
+			return err;
+	}
+	/*
+	 * Prevent Spectre v1 OOB reads past the 128-byte user stack window if
+	 * a preceding bounds check in cfi_skip_bytes() or here mispredicts.
+	 */
+	idx = s->is_user ? array_index_nospec(s->pos, DWARF_CFI_WIN_SIZE) :
+			   s->pos;
+	s->pos = idx + 1;
+	*val = s->buf[idx];
+	return 0;
+}
+
+static __always_inline int cfi_read_bytes(struct dwarf_cfi_stream *s,
+					  void *dst, size_t n)
+{
+	u8 *out = dst;
+
+	if (likely(n <= s->win_len && s->pos <= s->win_len - n)) {
+		size_t idx = s->is_user ?
+			array_index_nospec(s->pos, DWARF_CFI_WIN_SIZE - n + 1) :
+			s->pos;
+
+		memcpy(out, s->buf + idx, n);
+		s->pos = idx + n;
+		return 0;
+	}
+
+	if (!s->is_user)
+		return -EINVAL;
+
+	while (n--) {
+		int err = cfi_read_u8(s, out++);
+
+		if (err)
+			return err;
+	}
+	return 0;
+}
+
+static int cfi_skip_bytes(struct dwarf_cfi_stream *s, size_t n)
+{
+	size_t avail = (s->win_len - s->pos) + s->rem_after_win;
+
+	if (n > avail)
+		return -EINVAL;
+
+	while (n > 0) {
+		size_t in_win = s->win_len - s->pos;
+
+		if (n <= in_win) {
+			barrier_nospec();
+			s->pos += n;
+			return 0;
+		}
+		if (!s->is_user)
+			return -EINVAL;
+		n -= in_win;
+		s->pos = s->win_len;
+		if (n > 0) {
+			int err = cfi_stream_refill(s);
+
+			if (err)
+				return err;
+		}
+	}
+	return 0;
+}
+
+static noinline int cfi_read_uleb128_u32_slow(struct dwarf_cfi_stream *s,
+					      u32 val, u32 *out)
+{
+	unsigned int shift = 7;
+
+	for (;;) {
+		u8 b;
+		int err = cfi_read_u8(s, &b);
+
+		if (err)
+			return err;
+
+		if (shift == 28 && ((b & 0x7f) > 0x0f || (b & 0x80)))
+			return -EOVERFLOW;
+
+		val |= (u32)(b & 0x7f) << shift;
+		if (!(b & 0x80)) {
+			*out = val;
+			return 0;
+		}
+		shift += 7;
+	}
+}
+
+static __always_inline int cfi_read_uleb128_u32(struct dwarf_cfi_stream *s,
+						u32 *out)
+{
+	u8 b;
+	int err = cfi_read_u8(s, &b);
+
+	if (unlikely(err))
+		return err;
+	if (likely(!(b & 0x80))) {
+		*out = b;
+		return 0;
+	}
+	return cfi_read_uleb128_u32_slow(s, b & 0x7f, out);
+}
+
+static noinline int cfi_read_sleb128_s32_slow(struct dwarf_cfi_stream *s,
+					      u32 val, s32 *out)
+{
+	unsigned int shift = 7;
+
+	for (;;) {
+		u8 b;
+		int err = cfi_read_u8(s, &b);
+
+		if (err)
+			return err;
+
+		if (shift == 28) {
+			u8 top = b & 0x78;
+
+			if ((b & 0x80) || (top != 0x00 && top != 0x78))
+				return -EOVERFLOW;
+		}
+
+		val |= (u32)(b & 0x7f) << shift;
+		shift += 7;
+		if (!(b & 0x80)) {
+			if (shift < 32 && (b & 0x40))
+				val |= ~0U << shift;
+			*out = (s32)val;
+			return 0;
+		}
+	}
+}
+
+static __always_inline int cfi_read_sleb128_s32(struct dwarf_cfi_stream *s,
+						s32 *out)
+{
+	u8 b;
+	int err = cfi_read_u8(s, &b);
+
+	if (unlikely(err))
+		return err;
+	if (likely(!(b & 0x80))) {
+		*out = (b & 0x40) ? (s32)((u32)b | ~0x7fU) : (s32)b;
+		return 0;
+	}
+	return cfi_read_sleb128_s32_slow(s, b & 0x7f, out);
+}
+
+static int cfi_encoded_ptr_size(u8 enc, u8 ws)
+{
+	if (enc == DW_EH_PE_omit)
+		return 0;
+
+	switch (enc & DW_EH_PE_FORM) {
+	case DW_EH_PE_absptr:
+		return ws;
+	case DW_EH_PE_udata2:
+	case DW_EH_PE_sdata2:
+		return 2;
+	case DW_EH_PE_udata4:
+	case DW_EH_PE_sdata4:
+		return 4;
+	case DW_EH_PE_udata8:
+	case DW_EH_PE_sdata8:
+		return 8;
+	default:
+		return -EINVAL;
+	}
+}
+
+/**
+ * cfi_read_encoded_ptr() - Decode a DW_EH_PE_* pointer from a CFI stream
+ * @s: Input byte stream.
+ * @enc: DWARF Exception Header pointer encoding byte.
+ * @ws: Target word size in bytes (4 or 8).
+ * @datarel_base: Base address added when @enc uses DW_EH_PE_datarel.
+ * @out: Decoded virtual address (0 when @enc is DW_EH_PE_omit).
+ *
+ * Decodes fixed-width and LEB128 pointer encodings with abs, pcrel, or datarel
+ * adjustments without ever dereferencing memory: any DW_EH_PE_indirect flag is
+ * strictly rejected with -EINVAL.
+ *
+ * Return: 0 on success, -EFAULT on user copy fault, -EOVERFLOW on LEB128
+ * overflow, or -EINVAL on unsupported or indirect encodings.
+ */
+static int cfi_read_encoded_ptr(struct dwarf_cfi_stream *s, u8 enc, u8 ws,
+				unsigned long datarel_base, unsigned long *out)
+{
+	unsigned long field_addr = cfi_stream_addr(s);
+	s64 raw = 0;
+	u8 buf[8];
+	int err;
+
+	if (enc == DW_EH_PE_omit) {
+		*out = 0;
+		return 0;
+	}
+	if (enc & DW_EH_PE_indirect)
+		return -EINVAL;
+
+	switch (enc & DW_EH_PE_FORM) {
+	case DW_EH_PE_absptr:
+		err = cfi_read_bytes(s, buf, ws);
+		if (err)
+			return err;
+		raw = (ws == 8) ? (s64)get_unaligned_le64(buf) :
+				  (s64)get_unaligned_le32(buf);
+		break;
+	case DW_EH_PE_udata2:
+		err = cfi_read_bytes(s, buf, 2);
+		if (err)
+			return err;
+		raw = get_unaligned_le16(buf);
+		break;
+	case DW_EH_PE_sdata2:
+		err = cfi_read_bytes(s, buf, 2);
+		if (err)
+			return err;
+		raw = (s16)get_unaligned_le16(buf);
+		break;
+	case DW_EH_PE_udata4:
+		err = cfi_read_bytes(s, buf, 4);
+		if (err)
+			return err;
+		raw = get_unaligned_le32(buf);
+		break;
+	case DW_EH_PE_sdata4:
+		err = cfi_read_bytes(s, buf, 4);
+		if (err)
+			return err;
+		raw = (s32)get_unaligned_le32(buf);
+		break;
+	case DW_EH_PE_udata8:
+	case DW_EH_PE_sdata8:
+		err = cfi_read_bytes(s, buf, 8);
+		if (err)
+			return err;
+		raw = (s64)get_unaligned_le64(buf);
+		break;
+	case DW_EH_PE_uleb128: {
+		u32 uval;
+
+		err = cfi_read_uleb128_u32(s, &uval);
+		if (err)
+			return err;
+		raw = uval;
+		break;
+	}
+	case DW_EH_PE_sleb128: {
+		s32 sval;
+
+		err = cfi_read_sleb128_s32(s, &sval);
+		if (err)
+			return err;
+		raw = sval;
+		break;
+	}
+	default:
+		return -EINVAL;
+	}
+
+	switch (enc & DW_EH_PE_ADJUST) {
+	case DW_EH_PE_abs:
+		*out = (unsigned long)raw;
+		break;
+	case DW_EH_PE_pcrel:
+		*out = field_addr + (unsigned long)raw;
+		break;
+	case DW_EH_PE_datarel:
+		*out = datarel_base + (unsigned long)raw;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	if (ws == 4)
+		*out = (u32)*out;
+
+	return 0;
+}
+
+static __always_inline int cfi_factored_offset(s64 factor_operand,
+					       s32 data_align, s32 *out)
+{
+	s64 prod;
+
+	if (unlikely(check_mul_overflow(factor_operand, (s64)data_align, &prod)))
+		return -EOVERFLOW;
+	if (unlikely(prod < S32_MIN || prod > S32_MAX))
+		return -EOVERFLOW;
+
+	*out = (s32)prod;
+	return 0;
+}
+
+static __always_inline bool cfi_cfa_is_reg_off(const struct dwarf_cfi_row *row)
+{
+	return row->cfa_base == DWARF_CFI_BASE_SP ||
+	       row->cfa_base == DWARF_CFI_BASE_FP ||
+	       row->cfa_base == DWARF_CFI_BASE_REG;
+}
+
+static int cfi_set_cfa_reg(u32 reg, const struct dwarf_cfi_arch *arch,
+			   struct dwarf_cfi_row *row)
+{
+	if (reg > U8_MAX)
+		return -EINVAL;
+	if (reg == arch->sp_reg) {
+		row->cfa_base = DWARF_CFI_BASE_SP;
+		row->cfa_reg = (u8)reg;
+		return 0;
+	}
+	if (reg == arch->fp_reg) {
+		row->cfa_base = DWARF_CFI_BASE_FP;
+		row->cfa_reg = (u8)reg;
+		return 0;
+	}
+	/*
+	 * Allow transient prologue/epilogue DRAP scratch registers so scanning
+	 * reaches the body's FP/FP_INDIRECT state (or recovers from pt_regs).
+	 */
+	row->cfa_base = DWARF_CFI_BASE_REG;
+	row->cfa_reg = (u8)reg;
+	return 0;
+}
+
+/*
+ * Match ONLY the fixed 3-part DRAP / sigreturn CFA indirect pattern:
+ *   DW_OP_breg(fp_reg | sp_reg) <sleb128>, DW_OP_deref  =>  CFA = *(reg + off)
+ * All other DWARF expressions are rejected.
+ */
+static int cfi_parse_indirect_cfa_expr(struct dwarf_cfi_stream *s, u32 expr_len,
+				       const struct dwarf_cfi_arch *arch,
+				       struct dwarf_cfi_row *row)
+{
+	struct dwarf_cfi_stream es;
+	u8 expr_buf[8], op0, op_end;
+	enum dwarf_cfi_base base;
+	s32 off;
+	int err;
+
+	if (expr_len < 3 || expr_len > 7)
+		return -EINVAL;
+	/* Prevent Spectre v1.1 speculative stack overflow of expr_buf[8] */
+	barrier_nospec();
+
+	err = cfi_read_bytes(s, expr_buf, expr_len);
+	if (err)
+		return err;
+
+	cfi_stream_init_kmem(&es, expr_buf, expr_len - 1);
+	err = cfi_read_u8(&es, &op0);
+	if (err)
+		return err;
+
+	if (arch->fp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->fp_reg))
+		base = DWARF_CFI_BASE_FP_INDIRECT;
+	else if (arch->sp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->sp_reg))
+		base = DWARF_CFI_BASE_SP_INDIRECT;
+	else
+		return -EINVAL;
+
+	err = cfi_read_sleb128_s32(&es, &off);
+	if (err || !cfi_stream_empty(&es))
+		return -EINVAL;
+
+	op_end = expr_buf[expr_len - 1];
+	if (op_end != DW_OP_deref)
+		return -EINVAL;
+
+	row->cfa_base = base;
+	row->cfa_off = off;
+	return 0;
+}
+
+/*
+ * Match ONLY the fixed 2-part DRAP / sigreturn register save pattern:
+ *   DW_OP_breg(fp_reg | sp_reg) <sleb128>   =>   saved reg at *(FP/SP + off)
+ */
+static int cfi_parse_reg_expr(struct dwarf_cfi_stream *s, u32 reg, u32 expr_len,
+			      const struct dwarf_cfi_arch *arch, u8 ra_reg,
+			      struct dwarf_cfi_row *row)
+{
+	struct dwarf_cfi_stream es;
+	u8 expr_buf[8], op0;
+	enum dwarf_cfi_rule rule;
+	s32 off;
+	int err;
+
+	if (expr_len < 2 || expr_len > 6)
+		return -EINVAL;
+	/* Prevent Spectre v1.1 speculative stack overflow of expr_buf[8] */
+	barrier_nospec();
+
+	err = cfi_read_bytes(s, expr_buf, expr_len);
+	if (err)
+		return err;
+
+	cfi_stream_init_kmem(&es, expr_buf, expr_len);
+	err = cfi_read_u8(&es, &op0);
+	if (err)
+		return err;
+
+	if (arch->fp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->fp_reg))
+		rule = DWARF_CFI_RULE_FP_OFFSET;
+	else if (arch->sp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->sp_reg))
+		rule = DWARF_CFI_RULE_SP_OFFSET;
+	else
+		return -EINVAL;
+
+	err = cfi_read_sleb128_s32(&es, &off);
+	if (err || !cfi_stream_empty(&es))
+		return -EINVAL;
+
+	if (reg == arch->fp_reg) {
+		row->fp_rule = rule;
+		row->fp_off = off;
+		return 0;
+	}
+	if (reg == ra_reg && rule == DWARF_CFI_RULE_SP_OFFSET) {
+		row->ra_rule = rule;
+		row->ra_off = off;
+		return 0;
+	}
+	if (reg == arch->sp_reg && rule == DWARF_CFI_RULE_SP_OFFSET &&
+	    row->cfa_base == DWARF_CFI_BASE_SP_INDIRECT && off == row->cfa_off)
+		return 0;
+
+	return -EINVAL;
+}
+
+static void cfi_apply_reg_rule(u32 reg, enum dwarf_cfi_rule rule, s32 off,
+			       const struct dwarf_cfi_arch *arch, u8 ra_reg,
+			       struct dwarf_cfi_row *row)
+{
+	if (reg == arch->fp_reg) {
+		row->fp_rule = rule;
+		row->fp_off = off;
+	} else if (reg == ra_reg) {
+		row->ra_rule = rule;
+		row->ra_off = off;
+	}
+	/* All other general-purpose registers are intentionally ignored. */
+}
+
+static void cfi_restore_reg(u32 reg, const struct dwarf_cfi_arch *arch,
+			    u8 ra_reg, const struct dwarf_cfi_row *cie_row,
+			    struct dwarf_cfi_row *row)
+{
+	if (reg == arch->fp_reg) {
+		row->fp_rule = cie_row->fp_rule;
+		row->fp_off = cie_row->fp_off;
+	} else if (reg == ra_reg) {
+		row->ra_rule = cie_row->ra_rule;
+		row->ra_off = cie_row->ra_off;
+	}
+}
+
+static __always_inline int cfi_advance_pc(unsigned long *loc, u32 delta,
+					  u32 code_align)
+{
+	unsigned long step;
+
+	if (likely(code_align == 1)) {
+		if (unlikely(check_add_overflow(*loc, (unsigned long)delta, loc)))
+			return -EOVERFLOW;
+		return 0;
+	}
+
+	if (check_mul_overflow((unsigned long)delta, (unsigned long)code_align, &step) ||
+	    check_add_overflow(*loc, step, loc))
+		return -EOVERFLOW;
+	return 0;
+}
+
+/**
+ * dwarf_cfi_exec_insns() - Execute Minimal DWARF CFA instructions up to a PC
+ * @s: Stream positioned at the start of CIE or FDE CFA instructions.
+ * @cie: Parsed CIE attributes providing alignment factors and @ra_reg.
+ * @arch: Target architecture DWARF register numbers.
+ * @cie_row: Initial CIE unwind row for DW_CFA_restore* (NULL while parsing CIE).
+ * @row: In/out unwind row updated in place as instructions execute.
+ * @check_pc: True when evaluating an FDE up to @target_pc; false for CIE init.
+ * @start_pc: Initial PC of the FDE when @check_pc is true.
+ * @target_pc: Target PC at which to stop FDE execution (inclusive).
+ *
+ * Interprets the strictly bounded Minimal DWARF CFA subset in a single forward
+ * pass with a 4-entry state stack for shrink-wrapped functions. Backward PC
+ * jumps (DW_CFA_set_loc), register-to-register rules on SP/FP/RA, and general
+ * DWARF expressions are rejected.
+ *
+ * Return: 0 on success, -EFAULT on user stream fault, -EOVERFLOW on arithmetic
+ * or LEB128 overflow, or -EINVAL on unsupported or malformed opcodes.
+ */
+static int dwarf_cfi_exec_insns(struct dwarf_cfi_stream *s,
+				const struct dwarf_cfi_cie *cie,
+				const struct dwarf_cfi_arch *arch,
+				const struct dwarf_cfi_row *cie_row,
+				struct dwarf_cfi_row *row,
+				bool check_pc, unsigned long start_pc,
+				unsigned long target_pc)
+{
+	struct dwarf_cfi_row state_stack[DWARF_CFI_MAX_STATE_STACK];
+	unsigned int stack_depth = 0;
+	unsigned long loc = start_pc;
+
+	while (!cfi_stream_empty(s) && (!check_pc || loc <= target_pc)) {
+		u8 op, hi, lo;
+		u32 reg, uval;
+		s32 sval, off;
+		int err;
+
+		err = cfi_read_u8(s, &op);
+		if (err)
+			return err;
+
+		hi = op & 0xc0;
+		lo = op & 0x3f;
+
+		if (hi == 0x40) {
+			/* DW_CFA_advance_loc */
+			err = cfi_advance_pc(&loc, lo, cie->code_align);
+			if (err)
+				return err;
+			continue;
+		}
+		if (hi == 0x80) {
+			/* DW_CFA_offset */
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (lo == arch->fp_reg || lo == cie->ra_reg) {
+				err = cfi_factored_offset(uval, cie->data_align, &off);
+				if (err)
+					return err;
+				cfi_apply_reg_rule(lo, DWARF_CFI_RULE_OFFSET,
+						   off, arch, cie->ra_reg, row);
+			}
+			continue;
+		}
+		if (hi == 0xc0) {
+			/* DW_CFA_restore */
+			if (cie_row)
+				cfi_restore_reg(lo, arch, cie->ra_reg, cie_row, row);
+			continue;
+		}
+
+		switch (op) {
+		case DW_CFA_nop:
+			break;
+
+		case DW_CFA_advance_loc1: {
+			u8 d8;
+
+			err = cfi_read_u8(s, &d8);
+			if (err)
+				return err;
+			err = cfi_advance_pc(&loc, d8, cie->code_align);
+			if (err)
+				return err;
+			break;
+		}
+
+		case DW_CFA_advance_loc2: {
+			u8 b2[2];
+
+			err = cfi_read_bytes(s, b2, 2);
+			if (err)
+				return err;
+			err = cfi_advance_pc(&loc, get_unaligned_le16(b2),
+					     cie->code_align);
+			if (err)
+				return err;
+			break;
+		}
+
+		case DW_CFA_advance_loc4: {
+			u8 b4[4];
+
+			err = cfi_read_bytes(s, b4, 4);
+			if (err)
+				return err;
+			err = cfi_advance_pc(&loc, get_unaligned_le32(b4),
+					     cie->code_align);
+			if (err)
+				return err;
+			break;
+		}
+
+		case DW_CFA_def_cfa:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (uval > (u32)S32_MAX)
+				return -EOVERFLOW;
+			err = cfi_set_cfa_reg(reg, arch, row);
+			if (err)
+				return err;
+			row->cfa_off = (s32)uval;
+			break;
+
+		case DW_CFA_def_cfa_sf:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_sleb128_s32(s, &sval);
+			if (err)
+				return err;
+			err = cfi_factored_offset(sval, cie->data_align, &off);
+			if (err)
+				return err;
+			err = cfi_set_cfa_reg(reg, arch, row);
+			if (err)
+				return err;
+			row->cfa_off = off;
+			break;
+
+		case DW_CFA_def_cfa_register:
+			if (!cfi_cfa_is_reg_off(row))
+				return -EINVAL;
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_set_cfa_reg(reg, arch, row);
+			if (err)
+				return err;
+			break;
+
+		case DW_CFA_def_cfa_offset:
+			if (!cfi_cfa_is_reg_off(row))
+				return -EINVAL;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (uval > (u32)S32_MAX)
+				return -EOVERFLOW;
+			row->cfa_off = (s32)uval;
+			break;
+
+		case DW_CFA_def_cfa_offset_sf:
+			if (!cfi_cfa_is_reg_off(row))
+				return -EINVAL;
+			err = cfi_read_sleb128_s32(s, &sval);
+			if (err)
+				return err;
+			err = cfi_factored_offset(sval, cie->data_align, &off);
+			if (err)
+				return err;
+			row->cfa_off = off;
+			break;
+
+		case DW_CFA_offset_extended:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				err = cfi_factored_offset(uval, cie->data_align, &off);
+				if (err)
+					return err;
+				cfi_apply_reg_rule(reg, DWARF_CFI_RULE_OFFSET,
+						   off, arch, cie->ra_reg, row);
+			}
+			break;
+
+		case DW_CFA_offset_extended_sf:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_sleb128_s32(s, &sval);
+			if (err)
+				return err;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				err = cfi_factored_offset(sval, cie->data_align, &off);
+				if (err)
+					return err;
+				cfi_apply_reg_rule(reg, DWARF_CFI_RULE_OFFSET,
+						   off, arch, cie->ra_reg, row);
+			}
+			break;
+
+		case DW_CFA_GNU_negative_offset_extended:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				err = cfi_factored_offset(-(s64)uval,
+							  cie->data_align, &off);
+				if (err)
+					return err;
+				cfi_apply_reg_rule(reg, DWARF_CFI_RULE_OFFSET,
+						   off, arch, cie->ra_reg, row);
+			}
+			break;
+
+		case DW_CFA_restore_extended:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			if (cie_row)
+				cfi_restore_reg(reg, arch, cie->ra_reg, cie_row, row);
+			break;
+
+		case DW_CFA_undefined:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			cfi_apply_reg_rule(reg, DWARF_CFI_RULE_UNDEFINED,
+					   /*off=*/0, arch, cie->ra_reg, row);
+			break;
+
+		case DW_CFA_same_value:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			cfi_apply_reg_rule(reg, DWARF_CFI_RULE_SAME, /*off=*/0,
+					   arch, cie->ra_reg, row);
+			break;
+
+		case DW_CFA_remember_state:
+			if (stack_depth >= DWARF_CFI_MAX_STATE_STACK)
+				return -EINVAL;
+			stack_depth = array_index_nospec(stack_depth,
+							 DWARF_CFI_MAX_STATE_STACK);
+			state_stack[stack_depth++] = *row;
+			break;
+
+		case DW_CFA_restore_state: {
+			unsigned int idx;
+
+			if (!stack_depth)
+				return -EINVAL;
+			idx = array_index_nospec(stack_depth - 1,
+						 DWARF_CFI_MAX_STATE_STACK);
+			stack_depth = idx;
+			*row = state_stack[idx];
+			break;
+		}
+
+		case DW_CFA_GNU_args_size:
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			break;
+
+		case DW_CFA_AARCH64_negate_ra_state:
+			if (arch->ws != 8 || arch->ra_reg != 30)
+				return -EINVAL;
+			row->ra_signed = !row->ra_signed;
+			break;
+
+		case DW_CFA_register:
+			/* Ignorable only if targeting an untracked GPR */
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (reg == arch->sp_reg || reg == arch->fp_reg ||
+			    reg == cie->ra_reg)
+				return -EINVAL;
+			break;
+
+		case DW_CFA_val_offset:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (reg == arch->sp_reg || reg == arch->fp_reg ||
+			    reg == cie->ra_reg)
+				return -EINVAL;
+			break;
+
+		case DW_CFA_val_offset_sf:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_sleb128_s32(s, &sval);
+			if (err)
+				return err;
+			if (reg == arch->sp_reg || reg == arch->fp_reg ||
+			    reg == cie->ra_reg)
+				return -EINVAL;
+			break;
+
+		case DW_CFA_def_cfa_expression:
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			err = cfi_parse_indirect_cfa_expr(s, uval, arch, row);
+			if (err)
+				return err;
+			break;
+
+		case DW_CFA_expression:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (reg == arch->fp_reg || reg == arch->sp_reg ||
+			    reg == cie->ra_reg) {
+				err = cfi_parse_reg_expr(s, reg, uval, arch,
+							 cie->ra_reg, row);
+				if (err)
+					return err;
+				break;
+			}
+			err = cfi_skip_bytes(s, uval);
+			if (err)
+				return err;
+			break;
+
+		case DW_CFA_val_expression:
+			err = cfi_read_uleb128_u32(s, &reg);
+			if (err)
+				return err;
+			err = cfi_read_uleb128_u32(s, &uval);
+			if (err)
+				return err;
+			if (reg == arch->sp_reg || reg == arch->fp_reg ||
+			    reg == cie->ra_reg)
+				return -EINVAL;
+			err = cfi_skip_bytes(s, uval);
+			if (err)
+				return err;
+			break;
+
+		/*
+		 * Strictly rejected: backward PC jumps and unknown opcodes.
+		 */
+		case DW_CFA_set_loc:
+		default:
+			return -EINVAL;
+		}
+	}
+
+	return 0;
+}
+
+/**
+ * dwarf_cfi_parse_cie() - Parse a CIE header and its initial CFA instructions
+ * @s: Bounded stream covering the CIE body (after length and CIE ID fields).
+ * @arch: Target architecture DWARF register numbers and word size.
+ * @cie: Output parsed CIE attributes.
+ * @cie_row: Output initial unwind row established by the CIE's instructions.
+ *
+ * Supports CIE versions 1, 3, and 4 and 'z' augmentation strings containing
+ * 'R', 'L', 'P', 'S', and 'B' (skipping LSDA/personality encodings without
+ * dereferencing pointers).
+ *
+ * Return: 0 on success, -EFAULT on user copy fault, -EOVERFLOW on LEB128
+ * overflow, or -EINVAL on unsupported CIE headers or instructions.
+ */
+static int dwarf_cfi_parse_cie(struct dwarf_cfi_stream *s,
+			       const struct dwarf_cfi_arch *arch,
+			       struct dwarf_cfi_cie *cie,
+			       struct dwarf_cfi_row *cie_row)
+{
+	char aug[8];
+	unsigned int aug_idx = 0;
+	u8 version;
+	u32 ra_col;
+	int err;
+
+	memset(cie, 0, sizeof(*cie));
+	cie->fde_enc = DW_EH_PE_absptr;
+
+	err = cfi_read_u8(s, &version);
+	if (err)
+		return err;
+	if (version != 1 && version != 3 && version != 4)
+		return -EINVAL;
+
+	/* Read NUL-terminated augmentation string (bounded to 7 chars) */
+	for (;;) {
+		u8 ch;
+
+		err = cfi_read_u8(s, &ch);
+		if (err)
+			return err;
+		if (ch == '\0') {
+			aug[aug_idx] = '\0';
+			break;
+		}
+		if (aug_idx >= sizeof(aug) - 1)
+			return -EINVAL;
+		aug_idx = array_index_nospec(aug_idx, sizeof(aug) - 1);
+		aug[aug_idx++] = (char)ch;
+	}
+
+	if (version == 4) {
+		u8 addr_sz, seg_sz;
+
+		err = cfi_read_u8(s, &addr_sz);
+		if (err)
+			return err;
+		err = cfi_read_u8(s, &seg_sz);
+		if (err)
+			return err;
+		if (addr_sz != arch->ws || seg_sz != 0)
+			return -EINVAL;
+	}
+
+	err = cfi_read_uleb128_u32(s, &cie->code_align);
+	if (err)
+		return err;
+	err = cfi_read_sleb128_s32(s, &cie->data_align);
+	if (err)
+		return err;
+	if (!cie->code_align || !cie->data_align)
+		return -EINVAL;
+
+	if (version == 1) {
+		u8 ra8;
+
+		err = cfi_read_u8(s, &ra8);
+		if (err)
+			return err;
+		ra_col = ra8;
+	} else {
+		err = cfi_read_uleb128_u32(s, &ra_col);
+		if (err)
+			return err;
+	}
+	if (ra_col > U8_MAX)
+		return -EINVAL;
+	cie->ra_reg = (u8)ra_col;
+
+	if (aug[0] == 'z') {
+		u32 aug_len;
+		unsigned long aug_end;
+		unsigned int i;
+
+		cie->has_z = true;
+		err = cfi_read_uleb128_u32(s, &aug_len);
+		if (err)
+			return err;
+		if (aug_len > DWARF_CFI_MAX_CIE_LEN)
+			return -EINVAL;
+
+		aug_end = cfi_stream_addr(s) + aug_len;
+		for (i = 1; aug[i] != '\0'; i++) {
+			u8 enc;
+			int psize;
+
+			if (cfi_stream_addr(s) > aug_end)
+				return -EINVAL;
+
+			switch (aug[i]) {
+			case 'R':
+				err = cfi_read_u8(s, &cie->fde_enc);
+				if (err)
+					return err;
+				if (cie->fde_enc & DW_EH_PE_indirect)
+					return -EINVAL;
+				break;
+			case 'L':
+				/* LSDA encoding byte; never dereferenced */
+				err = cfi_read_u8(s, &enc);
+				if (err)
+					return err;
+				break;
+			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);
+				if (psize < 0)
+					return psize;
+				err = cfi_skip_bytes(s, psize);
+				if (err)
+					return err;
+				break;
+			case 'S':
+				cie->signal = true;
+				break;
+			case 'B':
+				break;
+			default:
+				return -EINVAL;
+			}
+		}
+
+		if (cfi_stream_addr(s) > aug_end)
+			return -EINVAL;
+		if (cfi_stream_addr(s) < aug_end) {
+			err = cfi_skip_bytes(s, aug_end - cfi_stream_addr(s));
+			if (err)
+				return err;
+		}
+	} else if (aug[0] != '\0') {
+		return -EINVAL;
+	}
+
+	memset(cie_row, 0, sizeof(*cie_row));
+	cie_row->signal = cie->signal;
+
+	return dwarf_cfi_exec_insns(s, cie, arch, /*cie_row=*/NULL, cie_row,
+				    /*check_pc=*/false, /*start_pc=*/0,
+				    /*target_pc=*/0);
+}
+
+/**
+ * dwarf_cfi_eval_fde_streams() - Evaluate a CIE/FDE stream pair at @pc
+ * @cie_s: Bounded stream over the CIE body.
+ * @fde_s: Bounded stream over the FDE body.
+ * @pc: Target instruction pointer to unwind.
+ * @arch: Target architecture DWARF register descriptor.
+ * @out_row: Output Minimal DWARF unwind row at @pc.
+ *
+ * Return: 0 on success, -ENOENT if @pc lies outside the FDE's address range,
+ * -EFAULT on user copy fault, -EOVERFLOW on overflow, or -EINVAL on malformed
+ * CIE/FDE contents.
+ */
+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,
+					   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;
+
+	if (cie.has_z) {
+		u32 aug_len;
+
+		err = cfi_read_uleb128_u32(fde_s, &aug_len);
+		if (err)
+			return err;
+		err = cfi_skip_bytes(fde_s, aug_len);
+		if (err)
+			return err;
+	}
+
+	row = cie_row;
+	err = dwarf_cfi_exec_insns(fde_s, &cie, arch, &cie_row, &row,
+				   /*check_pc=*/true, init_loc, pc);
+	if (err)
+		return err;
+
+	*out_row = row;
+	return 0;
+}
+
+/**
+ * dwarf_cfi_eval_fde_kmem() - Evaluate an in-kernel FDE record at @pc
+ * @fde: Pointer to the start of the FDE record within [@eh_start, @eh_end).
+ * @eh_start: Start of the containing kernel/module .eh_frame section.
+ * @eh_end: End (exclusive) of the containing kernel/module .eh_frame section.
+ * @pc: Target kernel instruction pointer.
+ * @arch: Target architecture DWARF register descriptor.
+ * @out_row: Output Minimal DWARF unwind row at @pc.
+ *
+ * Validates CIE/FDE bounds within [@eh_start, @eh_end) and executes the FDE
+ * directly in kernel memory with zero allocations, making it safe in atomic,
+ * NMI, and noinstr contexts.
+ *
+ * Return: 0 on success, -ENOENT if @pc is outside the FDE's PC range, or
+ * -EINVAL / -EOVERFLOW if the FDE or CIE is malformed or out of bounds.
+ */
+int dwarf_cfi_eval_fde_kmem(const u8 *fde, const u8 *eh_start,
+			    const u8 *eh_end, unsigned long pc,
+			    const struct dwarf_cfi_arch *arch,
+			    struct dwarf_cfi_row *out_row)
+{
+	struct dwarf_cfi_stream cie_s, fde_s;
+	u32 fde_len, cie_delta, cie_len, cie_id;
+	const u8 *cie;
+
+	if (eh_end < eh_start || fde < eh_start || fde >= eh_end ||
+	    (size_t)(eh_end - fde) < 8)
+		return -EINVAL;
+
+	fde_len = get_unaligned_le32(fde);
+	cie_delta = get_unaligned_le32(fde + 4);
+	if (fde_len <= 4 || fde_len > DWARF_CFI_MAX_FDE_LEN || cie_delta < 4)
+		return -EINVAL;
+	if ((size_t)(eh_end - fde) - 4 < (size_t)fde_len)
+		return -EINVAL;
+	if ((size_t)((fde + 4) - eh_start) < cie_delta)
+		return -EINVAL;
+
+	cie = (fde + 4) - cie_delta;
+	if (cie < eh_start || cie >= eh_end || (size_t)(eh_end - cie) < 8)
+		return -EINVAL;
+
+	cie_len = get_unaligned_le32(cie);
+	cie_id = get_unaligned_le32(cie + 4);
+	if (cie_id != 0 || cie_len <= 4 || cie_len > DWARF_CFI_MAX_CIE_LEN)
+		return -EINVAL;
+	if ((size_t)(eh_end - cie) - 4 < (size_t)cie_len)
+		return -EINVAL;
+
+	cfi_stream_init_kmem(&cie_s, cie + 8, cie_len - 4);
+	cfi_stream_init_kmem(&fde_s, fde + 8, fde_len - 4);
+
+	return dwarf_cfi_eval_fde_streams(&cie_s, &fde_s, pc, arch, out_row);
+}
+
+static inline unsigned long eh_hdr_entry_addr(unsigned long hdr_base,
+					      unsigned long entry_addr,
+					      s32 off, u8 table_enc, u8 ws)
+{
+	unsigned long addr;
+
+	if ((table_enc & DW_EH_PE_ADJUST) == DW_EH_PE_pcrel)
+		addr = entry_addr + (long)off;
+	else
+		addr = hdr_base + (long)off;
+
+	return (ws == 4) ? (u32)addr : addr;
+}
+
+/**
+ * dwarf_cfi_unwind_eh_frame_hdr() - Look up and evaluate kernel CFI via hdr
+ * @hdr: Pointer to the kernel's .eh_frame_hdr section.
+ * @hdr_size: Size in bytes of @hdr.
+ * @eh_start: Start of the kernel's .eh_frame section.
+ * @eh_end: End (exclusive) of the kernel's .eh_frame section.
+ * @pc: Target kernel instruction pointer.
+ * @arch: Target architecture DWARF register descriptor.
+ * @out_row: Output Minimal DWARF unwind row at @pc.
+ *
+ * Performs an O(log N) binary search over the sorted version-1 .eh_frame_hdr
+ * lookup table and evaluates the matching FDE in [@eh_start, @eh_end). Safe in
+ * NMI and noinstr contexts.
+ *
+ * Return: 0 on success, -ENOENT if @pc is not covered by any FDE in @hdr, or
+ * -EINVAL / -EOVERFLOW on invalid header or FDE encodings.
+ */
+int dwarf_cfi_unwind_eh_frame_hdr(const u8 *hdr, size_t hdr_size,
+				  const u8 *eh_start, const u8 *eh_end,
+				  unsigned long pc,
+				  const struct dwarf_cfi_arch *arch,
+				  struct dwarf_cfi_row *out_row)
+{
+	unsigned long hdr_base = (unsigned long)hdr;
+	unsigned long fde_cnt_ul, fde_addr;
+	const size_t ent_sz = sizeof(struct eh_frame_hdr_entry);
+	const u8 *table;
+	u32 lo, hi;
+	u8 table_enc;
+
+	if (!hdr || hdr_size < 12 || hdr[0] != 1)
+		return -EINVAL;
+
+	table_enc = hdr[3];
+	if (table_enc != (DW_EH_PE_datarel | DW_EH_PE_sdata4) &&
+	    table_enc != (DW_EH_PE_pcrel | DW_EH_PE_sdata4))
+		return -EINVAL;
+
+	if (likely(hdr[1] == (DW_EH_PE_pcrel | DW_EH_PE_sdata4) &&
+		   hdr[2] == DW_EH_PE_udata4)) {
+		fde_cnt_ul = get_unaligned_le32(hdr + 8);
+		if (!fde_cnt_ul || fde_cnt_ul > DWARF_CFI_MAX_FDE_COUNT)
+			return -EINVAL;
+		if (hdr_size - 12 < fde_cnt_ul * ent_sz)
+			return -EINVAL;
+		table = hdr + 12;
+	} else {
+		struct dwarf_cfi_stream hs;
+		unsigned long eh_ptr;
+		int err;
+
+		cfi_stream_init_kmem(&hs, hdr + 4, hdr_size - 4);
+		err = cfi_read_encoded_ptr(&hs, hdr[1], arch->ws, hdr_base,
+					   &eh_ptr);
+		if (err)
+			return err;
+		err = cfi_read_encoded_ptr(&hs, hdr[2], arch->ws, hdr_base,
+					   &fde_cnt_ul);
+		if (err)
+			return err;
+
+		if (!fde_cnt_ul || fde_cnt_ul > DWARF_CFI_MAX_FDE_COUNT)
+			return -EINVAL;
+		if ((hs.win_len - hs.pos) < fde_cnt_ul * ent_sz)
+			return -EINVAL;
+
+		table = hs.buf + hs.pos;
+	}
+
+	lo = 0;
+	hi = (u32)fde_cnt_ul;
+	if (likely(table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4))) {
+		while (lo < hi) {
+			u32 mid = lo + (hi - lo) / 2;
+			const u8 *ent = table + (size_t)mid * ent_sz;
+			s32 off = (s32)get_unaligned_le32(ent);
+
+			if (hdr_base + (long)off <= pc)
+				lo = mid + 1;
+			else
+				hi = mid;
+		}
+		if (!lo)
+			return -ENOENT;
+		fde_addr = hdr_base +
+			   (long)(s32)get_unaligned_le32(table + (size_t)(lo - 1) * ent_sz + 4);
+	} else {
+		while (lo < hi) {
+			u32 mid = lo + (hi - lo) / 2;
+			const u8 *ent = table + (size_t)mid * ent_sz;
+			unsigned long e_pc = (unsigned long)ent +
+					     (long)(s32)get_unaligned_le32(ent);
+
+			if (e_pc <= pc)
+				lo = mid + 1;
+			else
+				hi = mid;
+		}
+		if (!lo)
+			return -ENOENT;
+		{
+			const u8 *fent = table + (size_t)(lo - 1) * ent_sz + 4;
+
+			fde_addr = (unsigned long)fent +
+				   (long)(s32)get_unaligned_le32(fent);
+		}
+	}
+
+	return dwarf_cfi_eval_fde_kmem((const u8 *)fde_addr, eh_start, eh_end,
+				       pc, arch, out_row);
+}
+
+static bool cfi_s32_rel_offset(unsigned long target, unsigned long base,
+			       s32 *out)
+{
+	unsigned long diff;
+
+	if (target >= base) {
+		diff = target - base;
+		if (diff > (unsigned long)S32_MAX)
+			return false;
+		*out = (s32)diff;
+		return true;
+	}
+
+	diff = base - target;
+	if (diff > (unsigned long)S32_MAX + 1UL)
+		return false;
+	*out = (diff == (unsigned long)S32_MAX + 1UL) ? S32_MIN : -(s32)diff;
+	return true;
+}
+
+/**
+ * dwarf_cfi_scan_eh_frame_kmem() - Scan a kernel .eh_frame to index its FDEs
+ * @eh_start: Start of the in-memory .eh_frame section.
+ * @eh_size: Size in bytes of the .eh_frame section.
+ * @arch: Target architecture DWARF register descriptor.
+ * @base_addr: Reference base address from which @entries offsets are computed.
+ * @entries: Optional output array of &struct eh_frame_hdr_entry (NULL to only
+ *           count FDEs).
+ * @max_entries: Capacity of @entries when @entries is non-NULL.
+ * @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.
+ *
+ * Return: 0 on success, -ENOSPC if @entries is non-NULL and smaller than the
+ * FDE count, -EOVERFLOW if an offset exceeds s32 range from @base_addr, or
+ * -EINVAL on malformed CIE/FDE records.
+ */
+int dwarf_cfi_scan_eh_frame_kmem(const u8 *eh_start, size_t eh_size,
+				 const struct dwarf_cfi_arch *arch,
+				 unsigned long base_addr,
+				 struct eh_frame_hdr_entry *entries,
+				 unsigned int max_entries,
+				 unsigned int *out_count)
+{
+	const u8 *p = eh_start;
+	const u8 *eh_end = eh_start + eh_size;
+	unsigned int count = 0;
+
+	if (!arch || arch->ws != sizeof(unsigned long))
+		return -EINVAL;
+
+	while (p < eh_end && (size_t)(eh_end - p) >= 4) {
+		u32 len = get_unaligned_le32(p);
+		u32 cie_delta;
+		const u8 *entry_end;
+
+		if (len == 0)
+			break;
+		if (len <= 4 || len == U32_MAX ||
+		    (size_t)(eh_end - p) - 4 < (size_t)len)
+			return -EINVAL;
+
+		entry_end = p + 4 + len;
+		cie_delta = get_unaligned_le32(p + 4);
+
+		if (cie_delta != 0) {
+			/* FDE: resolve CIE to decode initial_loc */
+			const u8 *cie;
+			u32 cie_len;
+			struct dwarf_cfi_stream cie_s, fde_s;
+			struct dwarf_cfi_cie parsed_cie;
+			struct dwarf_cfi_row dummy_row;
+			unsigned long init_loc;
+			s32 rel_pc, rel_fde;
+			int err;
+
+			if (cie_delta < 4 ||
+			    (size_t)((p + 4) - eh_start) < cie_delta)
+				return -EINVAL;
+			cie = (p + 4) - cie_delta;
+			if (cie < eh_start || cie >= eh_end ||
+			    (size_t)(eh_end - cie) < 8)
+				return -EINVAL;
+			cie_len = get_unaligned_le32(cie);
+			if (cie_len <= 4 || cie_len > DWARF_CFI_MAX_CIE_LEN ||
+			    (size_t)(eh_end - cie) - 4 < (size_t)cie_len ||
+			    get_unaligned_le32(cie + 4) != 0)
+				return -EINVAL;
+
+			cfi_stream_init_kmem(&cie_s, cie + 8, cie_len - 4);
+			err = dwarf_cfi_parse_cie(&cie_s, arch, &parsed_cie, &dummy_row);
+			if (err)
+				return err;
+
+			cfi_stream_init_kmem(&fde_s, p + 8, len - 4);
+			err = cfi_read_encoded_ptr(&fde_s, parsed_cie.fde_enc,
+						   arch->ws, /*datarel_base=*/0,
+						   &init_loc);
+			if (err)
+				return err;
+
+			if (!cfi_s32_rel_offset(init_loc, base_addr, &rel_pc) ||
+			    !cfi_s32_rel_offset((unsigned long)p, base_addr,
+						&rel_fde))
+				return -EOVERFLOW;
+
+			if (entries) {
+				if (count >= max_entries)
+					return -ENOSPC;
+				entries[count].start_off = rel_pc;
+				entries[count].fde_off = rel_fde;
+			}
+			count++;
+		}
+
+		p = entry_end;
+	}
+
+	*out_count = count;
+	return 0;
+}
+
+/**
+ * dwarf_cfi_unwind_user_eh_frame_hdr() - Evaluate user-space CFI from user hdr
+ * @hdr_uaddr: User virtual address of the binary's PT_GNU_EH_FRAME segment.
+ * @hdr_size: Size in bytes of the PT_GNU_EH_FRAME segment.
+ * @pc: Target user instruction pointer.
+ * @arch: User architecture DWARF register descriptor (native or compat).
+ * @out_row: Output Minimal DWARF unwind row at @pc.
+ *
+ * Binary-searches the user .eh_frame_hdr table via copy_from_user() and
+ * streams the matching FDE and its CIE through bounded 128-byte stack windows.
+ * Must be called in sleepable task context (calls might_fault()).
+ *
+ * Return: 0 on success, -ENOENT if @pc is not covered by @hdr_uaddr, -EFAULT
+ * on unmapped user memory, or -EINVAL / -EOVERFLOW on invalid encodings.
+ */
+int dwarf_cfi_unwind_user_eh_frame_hdr(unsigned long hdr_uaddr,
+				       size_t hdr_size, unsigned long pc,
+				       const struct dwarf_cfi_arch *arch,
+				       struct dwarf_cfi_row *out_row)
+{
+	struct dwarf_cfi_stream hs, cie_s, fde_s;
+	unsigned long eh_ptr, fde_cnt_ul, table_uaddr, fde_uaddr, cie_uaddr;
+	const size_t ent_sz = sizeof(struct eh_frame_hdr_entry);
+	u8 cie_win[DWARF_CFI_WIN_SIZE], fde_win[DWARF_CFI_WIN_SIZE];
+	u8 hdr_prefix[28];
+	u8 fde_hdr[8], cie_hdr[8];
+	u32 fde_len, cie_delta, cie_len, cie_id;
+	u32 lo, hi;
+	bool have_match = false;
+	size_t prefix_len;
+	u8 table_enc;
+	int err;
+
+	might_fault();
+
+	if (!hdr_uaddr || hdr_size < 12)
+		return -EINVAL;
+
+	prefix_len = min_t(size_t, hdr_size, sizeof(hdr_prefix));
+	if (copy_from_user(hdr_prefix, (const void __user *)hdr_uaddr, prefix_len))
+		return -EFAULT;
+
+	if (hdr_prefix[0] != 1)
+		return -EINVAL;
+
+	table_enc = hdr_prefix[3];
+	if (table_enc != (DW_EH_PE_datarel | DW_EH_PE_sdata4) &&
+	    table_enc != (DW_EH_PE_pcrel | DW_EH_PE_sdata4))
+		return -EINVAL;
+
+	cfi_stream_init_kmem(&hs, hdr_prefix + 4, prefix_len - 4);
+	hs.cur_base_addr = hdr_uaddr + 4;
+
+	err = cfi_read_encoded_ptr(&hs, hdr_prefix[1], arch->ws, hdr_uaddr, &eh_ptr);
+	if (err)
+		return err;
+	err = cfi_read_encoded_ptr(&hs, hdr_prefix[2], arch->ws, hdr_uaddr, &fde_cnt_ul);
+	if (err)
+		return err;
+
+	if (!fde_cnt_ul || fde_cnt_ul > DWARF_CFI_MAX_FDE_COUNT)
+		return -EINVAL;
+
+	table_uaddr = cfi_stream_addr(&hs);
+	if (hdr_size - (table_uaddr - hdr_uaddr) < fde_cnt_ul * ent_sz)
+		return -EINVAL;
+
+	lo = 0;
+	hi = (u32)fde_cnt_ul;
+	while (lo < hi) {
+		u32 mid = lo + (hi - lo) / 2;
+		unsigned long ent_uaddr = table_uaddr + (size_t)mid * ent_sz;
+		struct eh_frame_hdr_entry ent;
+		unsigned long e_pc;
+
+		if (copy_from_user(&ent, (const void __user *)ent_uaddr, sizeof(ent)))
+			return -EFAULT;
+
+		e_pc = eh_hdr_entry_addr(hdr_uaddr, ent_uaddr,
+					 le32_to_cpu((__force __le32)ent.start_off),
+					 table_enc, arch->ws);
+		if (e_pc <= pc) {
+			unsigned long foff_uaddr =
+				ent_uaddr + offsetof(struct eh_frame_hdr_entry, fde_off);
+
+			fde_uaddr = eh_hdr_entry_addr(hdr_uaddr, foff_uaddr,
+						      le32_to_cpu((__force __le32)ent.fde_off),
+						      table_enc, arch->ws);
+			have_match = true;
+			lo = mid + 1;
+		} else {
+			hi = mid;
+		}
+	}
+
+	if (!have_match)
+		return -ENOENT;
+
+	if (copy_from_user(fde_hdr, (const void __user *)fde_uaddr, sizeof(fde_hdr)))
+		return -EFAULT;
+
+	fde_len = get_unaligned_le32(fde_hdr);
+	cie_delta = get_unaligned_le32(fde_hdr + 4);
+	if (fde_len <= 4 || fde_len > DWARF_CFI_MAX_FDE_LEN ||
+	    cie_delta < 4 || cie_delta > DWARF_CFI_MAX_CIE_DELTA)
+		return -EINVAL;
+	if (fde_uaddr + 4 < cie_delta)
+		return -EINVAL;
+
+	cie_uaddr = (fde_uaddr + 4) - cie_delta;
+	if (copy_from_user(cie_hdr, (const void __user *)cie_uaddr, sizeof(cie_hdr)))
+		return -EFAULT;
+
+	cie_len = get_unaligned_le32(cie_hdr);
+	cie_id = get_unaligned_le32(cie_hdr + 4);
+	if (cie_id != 0 || cie_len <= 4 || cie_len > DWARF_CFI_MAX_CIE_LEN)
+		return -EINVAL;
+
+	err = cfi_stream_init_user(&cie_s, cie_uaddr + 8, cie_len - 4, cie_win);
+	if (err)
+		return err;
+	err = cfi_stream_init_user(&fde_s, fde_uaddr + 8, fde_len - 4, fde_win);
+	if (err)
+		return err;
+
+	return dwarf_cfi_eval_fde_streams(&cie_s, &fde_s, pc, arch, out_row);
+}
+
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+static int cmp_eh_hdr_entry(const void *a, const void *b)
+{
+	const struct eh_frame_hdr_entry *ea = a;
+	const struct eh_frame_hdr_entry *eb = b;
+
+	return (ea->start_off > eb->start_off) - (ea->start_off < eb->start_off);
+}
+
+/**
+ * dwarf_cfi_mod_alloc() - Allocate and sort a module .eh_frame lookup index
+ * @eh_frame: Pointer to the module's SHF_ALLOC .eh_frame section.
+ * @eh_frame_size: Size in bytes of @eh_frame.
+ * @arch: Target architecture DWARF register descriptor.
+ *
+ * Performs a two-pass scan over @eh_frame to count and populate relative FDE
+ * index entries and sorts them by initial PC offset for binary search.
+ *
+ * Return: Newly allocated &struct mod_dwarf_cfi_index on success, or NULL if
+ * @eh_frame is empty, malformed, or memory allocation fails.
+ */
+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;
+
+	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;
+	}
+	idx->num_fdes = num_fdes;
+
+	sort(idx->entries, idx->num_fdes, sizeof(idx->entries[0]),
+	     cmp_eh_hdr_entry, /*swap_func=*/NULL);
+	return idx;
+}
+
+/**
+ * dwarf_cfi_mod_free_rcu() - Free a module CFI index after an RCU grace period
+ * @idx: Module CFI index previously unpublished from mod->arch (may be NULL).
+ */
+void dwarf_cfi_mod_free_rcu(struct mod_dwarf_cfi_index *idx)
+{
+	if (idx)
+		kfree_rcu_mightsleep(idx);
+}
+
+/**
+ * dwarf_cfi_mod_eval() - Look up and evaluate a module FDE at @ip
+ * @idx: RCU-protected module CFI index (may be NULL).
+ * @ip: Target module instruction pointer.
+ * @arch: Target architecture DWARF register descriptor.
+ * @out_row: Output Minimal DWARF unwind row at @ip.
+ *
+ * Caller must hold an RCU or RCU-sched read lock keeping both @idx and the
+ * module's core/init .eh_frame memory alive across the evaluation.
+ *
+ * Return: 0 on success, -ENOENT if @idx is NULL or no FDE covers @ip, or
+ * -EINVAL / -EOVERFLOW on invalid FDE bytecode.
+ */
+int dwarf_cfi_mod_eval(const struct mod_dwarf_cfi_index *idx, unsigned long ip,
+		       const struct dwarf_cfi_arch *arch,
+		       struct dwarf_cfi_row *out_row)
+{
+	unsigned long base;
+	u32 lo, hi, found = 0;
+	bool have_match = false;
+	const u8 *fde;
+
+	if (!idx || !idx->num_fdes)
+		return -ENOENT;
+
+	base = (unsigned long)idx->eh_frame;
+	lo = 0;
+	hi = idx->num_fdes;
+	while (lo < hi) {
+		u32 mid = lo + (hi - lo) / 2;
+		unsigned long e_pc = base + (long)idx->entries[mid].start_off;
+
+		if (e_pc <= ip) {
+			found = mid;
+			have_match = true;
+			lo = mid + 1;
+		} else {
+			hi = mid;
+		}
+	}
+
+	if (!have_match)
+		return -ENOENT;
+
+	fde = (const u8 *)(base + (long)idx->entries[found].fde_off);
+	return dwarf_cfi_eval_fde_kmem(fde, idx->eh_frame,
+				       idx->eh_frame + idx->eh_frame_size,
+				       ip, arch, out_row);
+}
+#endif /* CONFIG_UNWINDER_DWARF_CFI && CONFIG_MODULES */
diff --git a/kernel/unwind/dwarf_cfi_kunit.c b/kernel/unwind/dwarf_cfi_kunit.c
new file mode 100644
index 000000000000..8d63fb5535be
--- /dev/null
+++ b/kernel/unwind/dwarf_cfi_kunit.c
@@ -0,0 +1,625 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for Minimal DWARF Call Frame Information (CFI) unwinder.
+ */
+
+#include <kunit/test.h>
+#include <linux/kernel.h>
+#include <linux/stacktrace.h>
+#include <linux/unaligned.h>
+#include <linux/unwind_dwarf_cfi.h>
+
+static __always_inline unsigned long record_here_ip(void)
+{
+	unsigned long ip;
+
+#if defined(__x86_64__)
+	asm volatile("1: lea 1b(%%rip), %0" : "=r"(ip));
+#elif defined(__aarch64__)
+	asm volatile("1: adr %0, 1b" : "=r"(ip));
+#elif defined(__riscv)
+	asm volatile("1: auipc %0, 0" : "=r"(ip));
+#else
+	ip = _THIS_IP_;
+#endif
+	return ip;
+}
+
+static const struct dwarf_cfi_arch test_x86_64_arch = {
+	.ws	= 8,
+	.sp_reg	= 7,	/* rsp */
+	.fp_reg	= 6,	/* rbp */
+	.ra_reg	= 16,	/* rip */
+};
+
+static const struct dwarf_cfi_arch test_arm64_arch = {
+	.ws	= 8,
+	.sp_reg	= 31,	/* sp */
+	.fp_reg	= 29,	/* x29 */
+	.ra_reg	= 30,	/* x30 (lr) */
+};
+
+static const struct dwarf_cfi_arch test_riscv64_arch = {
+	.ws	= 8,
+	.sp_reg	= 2,	/* sp (x2) */
+	.fp_reg	= 8,	/* s0/fp (x8) */
+	.ra_reg	= 1,	/* ra (x1) */
+};
+
+/*
+ * Helper to construct a compact [CIE | FDE] .eh_frame blob in kernel memory
+ * with absptr encoding so tests can use arbitrary synthetic PCs.
+ */
+struct test_eh_blob {
+	u8 buf[256];
+	size_t fde_off;
+	size_t total_len;
+};
+
+static void build_arch_eh_blob(struct test_eh_blob *b,
+			       const struct dwarf_cfi_arch *arch,
+			       u8 code_align, u8 data_align_sleb,
+			       const char *aug, u8 fde_enc,
+			       const u8 *cie_insns, size_t cie_insns_len,
+			       unsigned long init_pc, unsigned long pc_range,
+			       const u8 *fde_insns, size_t fde_insns_len)
+{
+	u8 *p = b->buf;
+	size_t cie_start = 0, cie_len_pos, fde_start, fde_len_pos;
+
+	memset(b, 0, sizeof(*b));
+
+	/* CIE */
+	cie_len_pos = p - b->buf;
+	p += 4;
+	put_unaligned_le32(0, p);
+	p += 4;
+	*p++ = 1;
+	memcpy(p, aug, strlen(aug) + 1);
+	p += strlen(aug) + 1;
+	*p++ = code_align;
+	*p++ = data_align_sleb;
+	*p++ = arch->ra_reg;
+	if (aug[0] == 'z') {
+		*p++ = 1;
+		*p++ = fde_enc;
+	}
+	memcpy(p, cie_insns, cie_insns_len);
+	p += cie_insns_len;
+	while ((p - b->buf) & 3)
+		*p++ = 0x00;
+	put_unaligned_le32((u32)((p - b->buf) - cie_start - 4),
+			   b->buf + cie_len_pos);
+
+	/* FDE */
+	fde_start = p - b->buf;
+	b->fde_off = fde_start;
+	fde_len_pos = fde_start;
+	p += 4;
+	put_unaligned_le32((u32)((p - b->buf) - cie_start), p);
+	p += 4;
+	put_unaligned_le64(init_pc, p);
+	p += 8;
+	put_unaligned_le64(pc_range, p);
+	p += 8;
+	if (aug[0] == 'z')
+		*p++ = 0;
+	memcpy(p, fde_insns, fde_insns_len);
+	p += fde_insns_len;
+	while ((p - b->buf) & 3)
+		*p++ = 0x00;
+	put_unaligned_le32((u32)((p - b->buf) - fde_start - 4),
+			   b->buf + fde_len_pos);
+
+	b->total_len = p - b->buf;
+}
+
+static void build_test_eh_blob(struct test_eh_blob *b, const char *aug,
+			       u8 fde_enc, unsigned long init_pc,
+			       unsigned long pc_range,
+			       const u8 *fde_insns, size_t fde_insns_len)
+{
+	static const u8 x86_cie_insns[] = { 0x0c, 7, 8, 0x80 | 16, 1 };
+
+	build_arch_eh_blob(b, &test_x86_64_arch, /*code_align=*/1,
+			   /*data_align_sleb=*/0x78, aug, fde_enc,
+			   x86_cie_insns, sizeof(x86_cie_insns),
+			   init_pc, pc_range, fde_insns, fde_insns_len);
+}
+
+static void test_cfi_sp_and_ignored_gprs(struct kunit *test)
+{
+	/*
+	 * Simulate a typical -fomit-frame-pointer function at 0x1000..0x1040:
+	 *   +0..+1: push %r12 -> advance_loc 2, def_cfa_offset 16, offset r12 at cfa-16
+	 *   +2..+2: push %rbx -> advance_loc 1, def_cfa_offset 24, offset rbx at cfa-24
+	 *   +3..+6: sub $32, %rsp -> advance_loc 4, def_cfa_offset 56
+	 *   +7:     GNU_args_size 16
+	 */
+	static const u8 insns[] = {
+		0x40 | 2,		/* DW_CFA_advance_loc 2 -> 0x1002 */
+		0x0e, 16,		/* DW_CFA_def_cfa_offset 16 */
+		0x80 | 12, 2,		/* DW_CFA_offset r12, 2 (ignored) */
+		0x40 | 1,		/* DW_CFA_advance_loc 1 -> 0x1003 */
+		0x0e, 24,		/* DW_CFA_def_cfa_offset 24 */
+		0x80 | 3, 3,		/* DW_CFA_offset rbx, 3 (ignored) */
+		0x40 | 4,		/* DW_CFA_advance_loc 4 -> 0x1007 */
+		0x0e, 56,		/* DW_CFA_def_cfa_offset 56 */
+		0x2e, 16,		/* DW_CFA_GNU_args_size 16 (ignored) */
+	};
+	struct test_eh_blob blob;
+	struct dwarf_cfi_row row;
+
+	build_test_eh_blob(&blob, "zR", 0x04 /* udata8 abs */, 0x1000, 0x40,
+			   insns, sizeof(insns));
+
+	/* At entry (0x1000): CFA = rsp + 8, RA = cfa - 8, FP = same */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x1000,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_SP);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 8);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_SAME);
+	KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.ra_off, -8);
+
+	/* Mid-prologue (0x1002): CFA = rsp + 16 */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x1002,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 16);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_SAME);
+
+	/* Body (0x1020): CFA = rsp + 56, r12/rbx spills ignored */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x1020,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_SP);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 56);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_SAME);
+
+	/* Out-of-range PC (0x1040) returns -ENOENT */
+	KUNIT_EXPECT_EQ(test, -ENOENT,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x1040,
+					&test_x86_64_arch, &row));
+}
+
+static void test_cfi_fp_and_remember_restore(struct kunit *test)
+{
+	/*
+	 * Simulate an FP frame with a mid-function shrink-wrapped epilogue:
+	 *   0x2001: def_cfa_offset 16, offset rbp at cfa-16
+	 *   0x2004: def_cfa_register rbp
+	 *   0x2010: remember_state; def_cfa rsp, 8; restore rbp (early ret)
+	 *   0x2012: restore_state (cold tail still uses rbp frame)
+	 */
+	static const u8 insns[] = {
+		0x40 | 1,		/* advance 1 -> 0x2001 */
+		0x0e, 16,		/* def_cfa_offset 16 */
+		0x80 | 6, 2,		/* offset rbp(6), cfa-16 */
+		0x40 | 3,		/* advance 3 -> 0x2004 */
+		0x0d, 6,		/* def_cfa_register rbp(6) */
+		0x40 | 12,		/* advance 12 -> 0x2010 */
+		0x0a,			/* DW_CFA_remember_state */
+		0x0c, 7, 8,		/* def_cfa rsp(7), 8 */
+		0xc0 | 6,		/* restore rbp(6) */
+		0x40 | 2,		/* advance 2 -> 0x2012 */
+		0x0b,			/* DW_CFA_restore_state */
+	};
+	struct test_eh_blob blob;
+	struct dwarf_cfi_row row;
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x2000, 0x30, insns, sizeof(insns));
+
+	/* In body (0x2008): CFA = rbp + 16, FP = *(cfa - 16) */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x2008,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_FP);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 16);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.fp_off, -16);
+
+	/* At early ret (0x2011): CFA = rsp + 8, FP restored to SAME */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x2011,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_SP);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 8);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_SAME);
+
+	/* After restore_state (0x2020): back to CFA = rbp + 16, FP at cfa-16 */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x2020,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_FP);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 16);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.fp_off, -16);
+}
+
+static void test_cfi_drap_realigned_frame(struct kunit *test)
+{
+	/*
+	 * Simulate GCC x86-64 DRAP stack-realigned function (e.g. shrink_lruvec):
+	 *   0x2805: def_cfa r10, 0
+	 *   0x2810: DW_CFA_expression rbp(6), [DW_OP_breg6(0x76), 0]
+	 *   0x281a: DW_CFA_def_cfa_expression [DW_OP_breg6(0x76), -40(0x58), DW_OP_deref(0x06)]
+	 *           DW_CFA_expression r12(12), [DW_OP_breg6(0x76), -32(0x60)] (ignored)
+	 */
+	static const u8 insns[] = {
+		0x40 | 5,			/* advance 5 -> 0x2805 */
+		0x0c, 10, 0,			/* def_cfa r10(10), 0 */
+		0x40 | 11,			/* advance 11 -> 0x2810 */
+		0x10, 6, 2, 0x76, 0x00,		/* expression rbp: breg6 + 0 */
+		0x40 | 10,			/* advance 10 -> 0x281a */
+		0x0f, 3, 0x76, 0x58, 0x06,	/* def_cfa_expr: *(breg6 - 40) */
+		0x10, 12, 2, 0x76, 0x60,	/* expression r12: ignored */
+	};
+	struct test_eh_blob blob;
+	struct dwarf_cfi_row row;
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x2800, 0x40, insns, sizeof(insns));
+
+	/* Transient prologue at 0x2806: DWARF_CFI_BASE_REG (r10) */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x2806,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_REG);
+	KUNIT_EXPECT_EQ(test, row.cfa_reg, 10);
+
+	/* Function body at 0x2820: CFA = *(rbp - 40), FP = *(rbp + 0) */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x2820,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_FP_INDIRECT);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, -40);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_FP_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.fp_off, 0);
+}
+
+static void test_cfi_sigreturn_frame(struct kunit *test)
+{
+	/*
+	 * Matches glibc x86-64 __restore_rt ("zRS") FDE:
+	 *   DW_CFA_def_cfa_expression [DW_OP_breg7 + 160, DW_OP_deref]
+	 *   DW_CFA_expression r6 (rbp), [DW_OP_breg7 + 120]
+	 *   DW_CFA_expression r7 (rsp), [DW_OP_breg7 + 160]
+	 *   DW_CFA_expression r16 (rip), [DW_OP_breg7 + 168]
+	 */
+	static const u8 sig_insns[] = {
+		0x0f, 4, 0x77, 0xa0, 0x01, 0x06,
+		0x10, 6, 3, 0x77, 0xf8, 0x00,
+		0x10, 7, 3, 0x77, 0xa0, 0x01,
+		0x10, 16, 3, 0x77, 0xa8, 0x01,
+	};
+	struct test_eh_blob blob;
+	struct dwarf_cfi_row row;
+
+	build_test_eh_blob(&blob, "zRS", 0x04, 0x2c00, 0x10,
+			   sig_insns, sizeof(sig_insns));
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x2c01,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_TRUE(test, row.signal);
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_SP_INDIRECT);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 160);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_SP_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.fp_off, 120);
+	KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_SP_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.ra_off, 168);
+}
+
+static void test_cfi_arm64_pac_and_riscv_leaf(struct kunit *test)
+{
+	/*
+	 * AArch64 CIE: code_align=4, data_align=-8 (0x78), ra_reg=30,
+	 * initial: DW_CFA_def_cfa sp(31), 0 (RA starts as SAME in x30).
+	 * FDE at 0x4000..0x4020:
+	 *   +4  (0x4004): paciasp -> DW_CFA_AARCH64_negate_ra_state (0x2d)
+	 *   +8  (0x4008): stp x29,x30,[sp,#-32]! -> cfa=sp+32, x29@-32, x30@-24, x19@-16
+	 *   +24 (0x4018): ldp x29,x30,[sp],#32   -> restore x19/x29/x30, cfa=sp+0
+	 *   +28 (0x401c): autiasp -> DW_CFA_AARCH64_negate_ra_state (0x2d)
+	 */
+	static const u8 arm64_cie[] = { 0x0c, 31, 0 };
+	static const u8 arm64_fde[] = {
+		0x41, 0x2d,
+		0x41, 0x0e, 32, 0x80 | 29, 4, 0x80 | 30, 3, 0x80 | 19, 2,
+		0x44, 0xc0 | 19, 0xc0 | 29, 0xc0 | 30, 0x0e, 0,
+		0x41, 0x2d,
+	};
+	/*
+	 * RISC-V CIE: code_align=1, data_align=-4 (0x7c), ra_reg=1,
+	 * initial: DW_CFA_def_cfa sp(2), 0 (RA starts as SAME in x1/ra).
+	 * FDE at 0x5000..0x501a:
+	 *   +2 (0x5002): c.addi16sp -16 -> cfa=sp+16
+	 *   +6 (0x5006): sd s0, 0(sp); sd ra, 8(sp) -> s0(8)@-16, ra(1)@-8
+	 */
+	static const u8 rv_cie[] = { 0x0c, 2, 0 };
+	static const u8 rv_fde[] = {
+		0x42, 0x0e, 16,
+		0x44, 0x80 | 8, 4, 0x80 | 1, 2,
+	};
+	struct test_eh_blob blob;
+	struct dwarf_cfi_row row;
+
+	build_arch_eh_blob(&blob, &test_arm64_arch, /*code_align=*/4,
+			   /*data_align_sleb=*/0x78, "zR", /*fde_enc=*/0x04,
+			   arm64_cie, sizeof(arm64_cie), /*init_pc=*/0x4000,
+			   /*pc_range=*/0x20, arm64_fde, sizeof(arm64_fde));
+
+	/* Entry leaf state at 0x4000: CFA=sp+0, RA=SAME (unsigned) */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x4000,
+					&test_arm64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_SP);
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 0);
+	KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_SAME);
+	KUNIT_EXPECT_FALSE(test, row.ra_signed);
+
+	/* Body at 0x400c: CFA=sp+32, FP@cfa-32, RA@cfa-24 (PAC-signed) */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x400c,
+					&test_arm64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 32);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.fp_off, -32);
+	KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.ra_off, -24);
+	KUNIT_EXPECT_TRUE(test, row.ra_signed);
+
+	/* Epilogue after autiasp at 0x401c: CFA=sp+0, RA=SAME (unsigned) */
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x401c,
+					&test_arm64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 0);
+	KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_SAME);
+	KUNIT_EXPECT_FALSE(test, row.ra_signed);
+
+	/* DW_CFA_AARCH64_negate_ra_state (0x2d) must be rejected on x86_64 */
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x400c,
+					&test_x86_64_arch, &row));
+
+	/* RISC-V leaf + non-leaf prologue */
+	build_arch_eh_blob(&blob, &test_riscv64_arch, /*code_align=*/1,
+			   /*data_align_sleb=*/0x7c, "zR", /*fde_enc=*/0x04,
+			   rv_cie, sizeof(rv_cie), /*init_pc=*/0x5000,
+			   /*pc_range=*/0x1a, rv_fde, sizeof(rv_fde));
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x5000,
+					&test_riscv64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 0);
+	KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_SAME);
+
+	KUNIT_ASSERT_EQ(test, 0,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x5008,
+					&test_riscv64_arch, &row));
+	KUNIT_EXPECT_EQ(test, row.cfa_off, 16);
+	KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.fp_off, -16);
+	KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_OFFSET);
+	KUNIT_EXPECT_EQ(test, row.ra_off, -8);
+}
+
+static void test_cfi_security_rejections(struct kunit *test)
+{
+	/* 1. Arbitrary DW_CFA_def_cfa_expression must be rejected */
+	static const u8 expr_insns[] = { 0x0f, 0x01, 0x57 };
+	/* 2. Arbitrary DW_CFA_expression on RA (rip=16) must be rejected */
+	static const u8 ra_expr_insns[] = { 0x10, 16, 2, 0x76, 0x00 };
+	/* 3. Excessive remember_state nesting (> 4) must be rejected */
+	static const u8 deep_state_insns[] = { 0x0a, 0x0a, 0x0a, 0x0a, 0x0a };
+	/* 4. DW_CFA_set_loc must be rejected */
+	static const u8 set_loc_insns[] = { 0x01, 0, 0, 0, 0, 0, 0, 0, 0 };
+	/* 7. 5-byte SLEB128 outside s32 range (5th byte 0x08 / 0x77) must return -EOVERFLOW */
+	static const u8 sleb_pos_ovf[] = { 0x13, 0x80, 0x80, 0x80, 0x80, 0x08 };
+	static const u8 sleb_neg_ovf[] = { 0x13, 0x80, 0x80, 0x80, 0x80, 0x77 };
+	/* 8. DW_CFA_def_cfa_offset after indirect CFA expression must return -EINVAL */
+	static const u8 def_off_after_ind[] = { 0x0f, 3, 0x76, 0x58, 0x06, 0x0e, 16 };
+	struct test_eh_blob blob;
+	struct dwarf_cfi_row row;
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x3000, 0x20,
+			   expr_insns, sizeof(expr_insns));
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x3000, 0x20,
+			   ra_expr_insns, sizeof(ra_expr_insns));
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x3000, 0x20,
+			   deep_state_insns, sizeof(deep_state_insns));
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x3000, 0x20,
+			   set_loc_insns, sizeof(set_loc_insns));
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	/* 5. DW_EH_PE_indirect (0x80) in CIE 'R' encoding must be rejected */
+	build_test_eh_blob(&blob, "zR", /*fde_enc=*/0x80 | 0x04,
+			   /*init_pc=*/0x3000, /*pc_range=*/0x20,
+			   /*fde_insns=*/NULL, /*fde_insns_len=*/0);
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	/* 6. Out-of-bounds FDE pointers (fde >= eh_end or fde < eh_start) must not underflow */
+	build_test_eh_blob(&blob, "zR", /*fde_enc=*/0x04, /*init_pc=*/0x3000,
+			   /*pc_range=*/0x20, /*fde_insns=*/NULL,
+			   /*fde_insns_len=*/0);
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.total_len + 64, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.total_len, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x3000, 0x20,
+			   sleb_pos_ovf, sizeof(sleb_pos_ovf));
+	KUNIT_EXPECT_EQ(test, -EOVERFLOW,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x3000, 0x20,
+			   sleb_neg_ovf, sizeof(sleb_neg_ovf));
+	KUNIT_EXPECT_EQ(test, -EOVERFLOW,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+
+	build_test_eh_blob(&blob, "zR", 0x04, 0x3000, 0x20,
+			   def_off_after_ind, sizeof(def_off_after_ind));
+	KUNIT_EXPECT_EQ(test, -EINVAL,
+		dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+					blob.buf + blob.total_len, 0x3004,
+					&test_x86_64_arch, &row));
+}
+
+struct live_walk_ctx {
+	unsigned long *entries;
+	unsigned int size;
+	unsigned long leaf_ip;
+	unsigned long realign_ip;
+	unsigned long mid_ip;
+	unsigned long caller_ip;
+};
+
+static noinline unsigned int unwind_test_leaf(struct live_walk_ctx *ctx)
+{
+	unsigned int nr;
+
+	nr = stack_trace_save(ctx->entries, ctx->size, /*skipnr=*/0);
+	ctx->leaf_ip = record_here_ip();
+	OPTIMIZER_HIDE_VAR(nr);
+	return nr;
+}
+
+static noinline unsigned int unwind_test_realigned(struct live_walk_ctx *ctx)
+{
+	/* Force dynamic stack realignment (DRAP) on 8-byte aligned kernel stack */
+	u8 __aligned(64) aligned_buf[64];
+	unsigned int nr;
+
+	aligned_buf[0] = (u8)ctx->size;
+	asm volatile("" : "+m"(aligned_buf) :: "memory");
+	nr = unwind_test_leaf(ctx);
+	ctx->realign_ip = record_here_ip();
+	OPTIMIZER_HIDE_VAR(nr);
+	return nr;
+}
+
+static noinline unsigned int unwind_test_mid(struct live_walk_ctx *ctx,
+					     int depth)
+{
+	unsigned long local_buf[4];
+	unsigned int nr;
+
+	local_buf[0] = depth;
+	asm volatile("" : "+m"(local_buf) :: "memory");
+	if (depth > 1)
+		nr = unwind_test_mid(ctx, depth - 1);
+	else
+		nr = unwind_test_realigned(ctx);
+	ctx->mid_ip = record_here_ip();
+	OPTIMIZER_HIDE_VAR(nr);
+	return nr;
+}
+
+static inline bool ip_within(unsigned long ip, unsigned long ref_ip)
+{
+	return ip + 256 >= ref_ip && ip <= ref_ip + 256;
+}
+
+static void test_live_kernel_stack_walk(struct kunit *test)
+{
+	unsigned long entries[32];
+	struct live_walk_ctx ctx = {
+		.entries = entries,
+		.size = ARRAY_SIZE(entries),
+	};
+	unsigned int nr, i;
+	int rel_nr;
+	bool saw_leaf = false, saw_realign = false, saw_mid = false, saw_caller = false;
+
+	nr = unwind_test_mid(&ctx, /*depth=*/3);
+	ctx.caller_ip = record_here_ip();
+	KUNIT_ASSERT_GT(test, nr, 4U);
+
+	for (i = 0; i < nr; i++) {
+		unsigned long sym_ip = entries[i];
+
+		if (ip_within(sym_ip, ctx.leaf_ip))
+			saw_leaf = true;
+		if (ip_within(sym_ip, ctx.realign_ip))
+			saw_realign = true;
+		if (ip_within(sym_ip, ctx.mid_ip))
+			saw_mid = true;
+		if (ip_within(sym_ip, ctx.caller_ip))
+			saw_caller = true;
+	}
+
+	KUNIT_EXPECT_TRUE(test, saw_leaf);
+	KUNIT_EXPECT_TRUE(test, saw_realign);
+	KUNIT_EXPECT_TRUE(test, saw_mid);
+	KUNIT_EXPECT_TRUE(test, saw_caller);
+
+	if (IS_ENABLED(CONFIG_HAVE_RELIABLE_STACKTRACE)) {
+		rel_nr = stack_trace_save_tsk_reliable(current, entries,
+						       ARRAY_SIZE(entries));
+		KUNIT_EXPECT_GT(test, rel_nr, 0);
+	}
+}
+
+static struct kunit_case dwarf_cfi_test_cases[] = {
+	KUNIT_CASE(test_cfi_sp_and_ignored_gprs),
+	KUNIT_CASE(test_cfi_fp_and_remember_restore),
+	KUNIT_CASE(test_cfi_drap_realigned_frame),
+	KUNIT_CASE(test_cfi_sigreturn_frame),
+	KUNIT_CASE(test_cfi_arm64_pac_and_riscv_leaf),
+	KUNIT_CASE(test_cfi_security_rejections),
+	KUNIT_CASE(test_live_kernel_stack_walk),
+	{}
+};
+
+static struct kunit_suite dwarf_cfi_test_suite = {
+	.name = "unwind_dwarf_cfi",
+	.test_cases = dwarf_cfi_test_cases,
+};
+
+kunit_test_suites(&dwarf_cfi_test_suite);
+
+MODULE_DESCRIPTION("KUnit tests for Minimal DWARF CFI unwinder");
+MODULE_LICENSE("GPL");
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 02/11] unwind_user: Support Minimal DWARF CFI user-space unwinding
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 01/11] unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 03/11] scripts, unwind: Add build-time .eh_frame minifier Ian Rogers
                   ` (8 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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

diff --git a/arch/Kconfig b/arch/Kconfig
index 03399120aa8f..340a7ecbfc68 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -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
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 58dce0b66179..c8096cf66c38 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -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
diff --git a/arch/x86/include/asm/unwind_user.h b/arch/x86/include/asm/unwind_user.h
index 6e469044e4de..1a6be08968c3 100644
--- a/arch/x86/include/asm/unwind_user.h
+++ b/arch/x86/include/asm/unwind_user.h
@@ -4,9 +4,17 @@
 
 #ifdef CONFIG_UNWIND_USER
 
+#include <linux/unwind_dwarf_cfi.h>
 #include <asm/ptrace.h>
 #include <asm/uprobes.h>
 
+/**
+ * unwind_user_word_size() - Return the user-space word size in bytes on x86
+ * @regs: User-mode register state.
+ *
+ * Return: 8 for 64-bit user mode, 4 for 32-bit IA-32/compat mode, or 0 for
+ * VM86 mode stacks which cannot be unwound.
+ */
 static inline int unwind_user_word_size(struct pt_regs *regs)
 {
 	/* We can't unwind VM86 stacks */
@@ -15,22 +23,61 @@ static inline int unwind_user_word_size(struct pt_regs *regs)
 	return user_64bit_mode(regs) ? 8 : 4;
 }
 
+/**
+ * unwind_user_cfi_arch() - Populate x86/x86-64 DWARF register numbers
+ * @ws: User word size in bytes (8 for x86-64, 4 for i386).
+ * @arch: Output DWARF CFI architecture descriptor.
+ *
+ * Return: true if @ws is 4 or 8, false otherwise.
+ */
+static inline bool unwind_user_cfi_arch(unsigned int ws,
+					struct dwarf_cfi_arch *arch)
+{
+	if (ws == 8) {
+		*arch = (struct dwarf_cfi_arch){
+			.ws	= 8,
+			.sp_reg	= 7,	/* %rsp */
+			.fp_reg	= 6,	/* %rbp */
+			.ra_reg	= 16,	/* %rip */
+		};
+		return true;
+	}
+	if (ws == 4) {
+		*arch = (struct dwarf_cfi_arch){
+			.ws	= 4,
+			.sp_reg	= 4,	/* %esp */
+			.fp_reg	= 5,	/* %ebp */
+			.ra_reg	= 8,	/* %eip */
+		};
+		return true;
+	}
+	return false;
+}
+
 #endif /* CONFIG_UNWIND_USER */
 
 #ifdef CONFIG_HAVE_UNWIND_USER_FP
 
+/* Standard x86 frame record: {saved_bp, ret_addr} at [bp, bp + 2 * ws). */
 #define ARCH_INIT_USER_FP_FRAME(ws)			\
 	.cfa_off	=  2*(ws),			\
 	.ra_off		= -1*(ws),			\
 	.fp_off		= -2*(ws),			\
 	.use_fp		= true,
 
+/* At function entry before push %rbp: return address is at [sp, sp + ws). */
 #define ARCH_INIT_USER_FP_ENTRY_FRAME(ws)		\
 	.cfa_off	=  1*(ws),			\
 	.ra_off		= -1*(ws),			\
 	.fp_off		= 0,				\
 	.use_fp		= false,
 
+/**
+ * unwind_user_at_function_start() - Check if @regs is at a function entry point
+ * @regs: User-mode register state.
+ *
+ * Return: true if stopped on an entry uprobe before the frame prologue ran.
+ */
 static inline bool unwind_user_at_function_start(struct pt_regs *regs)
 {
 	return is_uprobe_at_func_entry(regs);
diff --git a/include/linux/unwind_user.h b/include/linux/unwind_user.h
index 64618618febd..dcd87012ab82 100644
--- a/include/linux/unwind_user.h
+++ b/include/linux/unwind_user.h
@@ -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
+ * @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
+
+#ifndef unwind_user_link_register
+/**
+ * unwind_user_link_register() - Default stub for architectures without an LR
+ * @regs: User-mode register state.
+ * @ra: Unused output link register pointer.
+ *
+ * Return: false on architectures where calls push the return address on stack.
+ */
+static inline bool unwind_user_link_register(struct pt_regs *regs,
+					     unsigned long *ra)
+{
+	return false;
+}
+#define unwind_user_link_register unwind_user_link_register
+#endif
+
+#ifndef unwind_user_strip_pac
+/**
+ * unwind_user_strip_pac() - Default no-op PAC stripping helper
+ * @ip: Recovered user instruction pointer.
+ * @ra_signed: Whether CFI marked the return address as PAC-signed.
+ *
+ * Return: @ip unchanged on architectures without pointer authentication.
+ */
+static inline unsigned long unwind_user_strip_pac(unsigned long ip,
+						  bool ra_signed)
+{
+	return ip;
+}
+#define unwind_user_strip_pac unwind_user_strip_pac
+#endif
+
+#ifndef unwind_user_sigreturn
+/**
+ * unwind_user_sigreturn() - Default stub for arch signal-trampoline unwinding
+ * @state: Current user unwind state.
+ *
+ * Return: false on architectures whose signal trampolines unwind via CFI/FP.
+ */
+static inline bool unwind_user_sigreturn(struct unwind_user_state *state)
+{
+	return false;
+}
+#define unwind_user_sigreturn unwind_user_sigreturn
+#endif
+
+#ifdef CONFIG_HAVE_UNWIND_USER_CFI
+int unwind_user_next_cfi(struct unwind_user_state *state,
+			 struct unwind_user_frame *out_frame, bool *out_signal);
+#else
+static inline int unwind_user_next_cfi(struct unwind_user_state *state,
+				       struct unwind_user_frame *out_frame,
+				       bool *out_signal)
+{
+	return -EINVAL;
+}
+#endif
+
 int unwind_user(struct unwind_stacktrace *trace, unsigned int max_entries);
 
 #endif /* _LINUX_UNWIND_USER_H */
diff --git a/include/linux/unwind_user_types.h b/include/linux/unwind_user_types.h
index 412729a269bc..9d00315dbbb9 100644
--- a/include/linux/unwind_user_types.h
+++ b/include/linux/unwind_user_types.h
@@ -4,41 +4,123 @@
 
 #include <linux/types.h>
 
-/*
- * Unwind types, listed in priority order: lower numbers are attempted first if
- * available.
+/**
+ * enum unwind_user_type_bits - Priority bit indices for user-space unwinders
+ * @UNWIND_USER_TYPE_CFI_BIT: Bit index for Minimal DWARF CFI (.eh_frame_hdr).
+ * @UNWIND_USER_TYPE_FP_BIT: Bit index for architectural frame-pointer chains.
+ * @NR_UNWIND_USER_TYPE_BITS: Total number of user-space unwind method bits.
+ *
+ * Listed in priority order: lower bit indices are attempted first on each
+ * frame when enabled in &unwind_user_state.available_types.
  */
 enum unwind_user_type_bits {
-	UNWIND_USER_TYPE_FP_BIT =		0,
+	UNWIND_USER_TYPE_CFI_BIT =		0,
+	UNWIND_USER_TYPE_FP_BIT =		1,
 
 	NR_UNWIND_USER_TYPE_BITS,
 };
 
+/**
+ * enum unwind_user_type - Bitmask values identifying a user-space unwind method
+ * @UNWIND_USER_TYPE_NONE: No active unwind method (initial or terminal state).
+ * @UNWIND_USER_TYPE_CFI: Unwind using Minimal DWARF CFI via PT_GNU_EH_FRAME.
+ * @UNWIND_USER_TYPE_FP: Unwind using architectural frame-pointer records.
+ */
 enum unwind_user_type {
-	/* Type "none" for the start of stack walk iteration. */
 	UNWIND_USER_TYPE_NONE =			0,
+	UNWIND_USER_TYPE_CFI =			BIT(UNWIND_USER_TYPE_CFI_BIT),
 	UNWIND_USER_TYPE_FP =			BIT(UNWIND_USER_TYPE_FP_BIT),
 };
 
+/**
+ * struct unwind_stacktrace - Captured user-space callchain buffer
+ * @nr: Number of instruction pointers stored in @entries.
+ * @entries: Caller-allocated array of user instruction pointers.
+ */
 struct unwind_stacktrace {
 	unsigned int	nr;
 	unsigned long	*entries;
 };
 
+/**
+ * struct unwind_user_frame - Evaluated unwind rule for stepping one user frame
+ * @cfa_off: Byte offset added to FP (when @use_fp is true) or SP to form CFA.
+ * @ra_off: Byte offset from CFA (or SP when @ra_from_sp is true) to saved RA.
+ * @fp_off: Byte offset from CFA, FP, or SP to saved caller FP (0 if unchanged,
+ *          unless @fp_from_fp or @fp_from_sp is set).
+ * @use_fp: True if the CFA base register is FP rather than SP.
+ * @cfa_indirect: True if the computed CFA address must be dereferenced once in
+ *                user memory (DRAP or signal trampoline frame).
+ * @fp_from_fp: True if saved FP is located at *(state->fp + @fp_off).
+ * @fp_from_sp: True if saved FP is located at *(old_sp + @fp_off).
+ * @ra_from_sp: True if saved RA is located at *(old_sp + @ra_off).
+ * @ra_from_reg: True if RA is still in @state->ra rather than on the stack.
+ * @ra_signed: True if the recovered RA carries an AArch64 PAC signature.
+ */
 struct unwind_user_frame {
 	s32 cfa_off;
 	s32 ra_off;
 	s32 fp_off;
 	bool use_fp;
+	bool cfa_indirect;
+	bool fp_from_fp;
+	bool fp_from_sp;
+	bool ra_from_sp;
+	bool ra_from_reg;
+	bool ra_signed;
+};
+
+/**
+ * struct unwind_user_cfi_cache - Per-walk cache entry mapping a VMA to EH_FRAME
+ * @vma_start: Start virtual address of the cached executable VMA.
+ * @vma_end: End virtual address (exclusive) of the cached executable VMA.
+ * @eh_hdr_uaddr: User virtual address of PT_GNU_EH_FRAME (0 for negative cache
+ *                entries when an executable VMA has no PT_GNU_EH_FRAME).
+ * @eh_hdr_size: Size in bytes of the PT_GNU_EH_FRAME segment.
+ * @valid: True if this cache slot holds a populated entry.
+ */
+struct unwind_user_cfi_cache {
+	unsigned long	vma_start;
+	unsigned long	vma_end;
+	unsigned long	eh_hdr_uaddr;
+	size_t		eh_hdr_size;
+	bool		valid;
 };
 
+#define UNWIND_USER_MAX_SIGNALS	4U
+
+/**
+ * struct unwind_user_state - Iteration state for a user-space stack walk
+ * @ip: Current frame's user instruction pointer.
+ * @sp: Current frame's user stack pointer.
+ * @fp: Current frame's user frame pointer.
+ * @ra: Link register value for leaf/topmost frames when @ra_valid is true.
+ * @ws: User word size in bytes (4 for compat 32-bit tasks, 8 for 64-bit tasks).
+ * @current_type: Unwind method used for the current step.
+ * @available_types: Bitmask of &enum unwind_user_type methods available.
+ * @cfi_cache_next: Round-robin replacement cursor into @cfi_cache.
+ * @cfi_cache: Small per-walk cache of executable VMA PT_GNU_EH_FRAME lookups.
+ * @nr_signals: Number of signal frames unwound so far during this walk.
+ * @ra_valid: True if @ra holds a live link register value for this frame.
+ * @signal: True if the current frame was entered from a signal trampoline, so
+ *          @ip points directly at the interrupted instruction rather than
+ *          immediately after a call instruction.
+ * @topmost: True when unwinding the innermost interrupted user frame.
+ * @done: True once the stack walk has reached the bottom or terminated.
+ */
 struct unwind_user_state {
 	unsigned long				ip;
 	unsigned long				sp;
 	unsigned long				fp;
+	unsigned long				ra;
 	unsigned int				ws;
 	enum unwind_user_type			current_type;
 	unsigned int				available_types;
+	unsigned int				cfi_cache_next;
+	struct unwind_user_cfi_cache		cfi_cache[4];
+	unsigned int				nr_signals;
+	bool					ra_valid;
+	bool					signal;
 	bool					topmost;
 	bool					done;
 };
diff --git a/kernel/unwind/Makefile b/kernel/unwind/Makefile
index 73a1ccc2ad77..954083868790 100644
--- a/kernel/unwind/Makefile
+++ b/kernel/unwind/Makefile
@@ -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
diff --git a/kernel/unwind/user.c b/kernel/unwind/user.c
index 90ab3c1a205e..1f1cb6c83cf0 100644
--- a/kernel/unwind/user.c
+++ b/kernel/unwind/user.c
@@ -1,8 +1,9 @@
 // SPDX-License-Identifier: GPL-2.0
 /*
-* Generic interfaces for unwinding user space
-*/
+ * Generic interfaces for unwinding user space.
+ */
 #include <linux/kernel.h>
+#include <linux/nospec.h>
 #include <linux/sched.h>
 #include <linux/sched/task_stack.h>
 #include <linux/unwind_user.h>
@@ -11,14 +12,38 @@
 #define for_each_user_frame(state) \
 	for (unwind_user_start(state); !(state)->done; unwind_user_next(state))
 
+/**
+ * get_user_word() - Read a native or compat-sized word from the user stack
+ * @word: Output zero-extended word value.
+ * @base: Base user virtual address.
+ * @off: Signed byte offset from @base.
+ * @ws: Word size in bytes (4 for compat 32-bit tasks, sizeof(long) otherwise).
+ *
+ * Return: 0 on success, or -EFAULT if the user memory access faults.
+ */
 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()
+	 * 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();
+	}
 #ifdef CONFIG_COMPAT
 	if (ws == sizeof(int)) {
 		unsigned int data;
 		int ret = get_user(data, (unsigned int __user *)addr);
+
 		*word = data;
 		return ret;
 	}
@@ -26,45 +51,97 @@ get_user_word(unsigned long *word, unsigned long base, int off, unsigned int ws)
 	return get_user(*word, addr);
 }
 
+/**
+ * unwind_user_next_common() - Apply an evaluated &struct unwind_user_frame rule
+ * @state: Current user unwind state to advance to the caller frame.
+ * @frame: Frame CFA, RA, and FP recovery rule.
+ * @signal: True if @frame unwinds a signal trampoline (allowing bounded stack
+ *          switching across alternate signal stacks).
+ *
+ * Computes the caller's CFA, validates alignment and monotonic stack progress,
+ * reads and strips PAC bits from the return address, optionally recovers the
+ * saved frame pointer, and updates @state.
+ *
+ * Return: 0 on success, -ENOENT if the recovered return address is 0 (marking
+ * @state->done), or -EINVAL on invalid alignment, stack regression, or fault.
+ */
 static int unwind_user_next_common(struct unwind_user_state *state,
-				   const struct unwind_user_frame *frame)
+				   const struct unwind_user_frame *frame,
+				   bool signal)
 {
+	unsigned long old_sp = state->sp;
 	unsigned long cfa, fp, ra;
 
+	if (signal && state->nr_signals >= UNWIND_USER_MAX_SIGNALS)
+		return -EINVAL;
+
 	/* Get the Canonical Frame Address (CFA) */
 	if (frame->use_fp) {
-		if (state->fp < state->sp)
+		if (!signal && state->fp < state->sp)
 			return -EINVAL;
 		cfa = state->fp;
 	} else {
 		cfa = state->sp;
 	}
 	cfa += frame->cfa_off;
+	if (frame->cfa_indirect && get_user_word(&cfa, cfa, /*off=*/0, state->ws))
+		return -EINVAL;
 
 	/* Make sure that stack is not going in wrong direction */
-	if (cfa <= state->sp)
+	if (frame->ra_from_reg) {
+		if (!state->ra_valid || (!signal && cfa < state->sp))
+			return -EINVAL;
+	} else if (!signal && cfa <= state->sp) {
 		return -EINVAL;
+	}
 
 	/* Make sure that the address is word aligned */
 	if (cfa & (state->ws - 1))
 		return -EINVAL;
 
 	/* Get the Return Address (RA) */
-	if (get_user_word(&ra, cfa, frame->ra_off, state->ws))
+	if (frame->ra_from_reg) {
+		ra = state->ra;
+	} else if (get_user_word(&ra, frame->ra_from_sp ? old_sp : cfa,
+				 frame->ra_off, state->ws)) {
 		return -EINVAL;
+	}
+	ra = unwind_user_strip_pac(ra, frame->ra_signed);
+	if (!ra) {
+		state->done = true;
+		return -ENOENT;
+	}
 
 	/* Get the Frame Pointer (FP) */
-	if (frame->fp_off && get_user_word(&fp, cfa, frame->fp_off, state->ws))
-		return -EINVAL;
+	if (frame->fp_from_fp) {
+		if (get_user_word(&fp, state->fp, frame->fp_off, state->ws))
+			return -EINVAL;
+	} else if (frame->fp_from_sp) {
+		if (get_user_word(&fp, old_sp, frame->fp_off, state->ws))
+			return -EINVAL;
+	} else if (frame->fp_off) {
+		if (get_user_word(&fp, cfa, frame->fp_off, state->ws))
+			return -EINVAL;
+	}
 
 	state->ip = ra;
 	state->sp = cfa;
-	if (frame->fp_off)
+	if (frame->fp_from_fp || frame->fp_from_sp || frame->fp_off)
 		state->fp = fp;
+	if (signal)
+		state->nr_signals++;
+	state->signal = signal;
+	state->ra_valid = false;
 	state->topmost = false;
 	return 0;
 }
 
+/**
+ * unwind_user_next_fp() - Step one user frame using architectural frame records
+ * @state: Current user unwind state.
+ *
+ * Return: 0 on success, or a negative errno from unwind_user_next_common().
+ */
 static int unwind_user_next_fp(struct unwind_user_state *state)
 {
 	struct pt_regs *regs = task_pt_regs(current);
@@ -73,15 +150,28 @@ static int unwind_user_next_fp(struct unwind_user_state *state)
 		const struct unwind_user_frame fp_entry_frame = {
 			ARCH_INIT_USER_FP_ENTRY_FRAME(state->ws)
 		};
-		return unwind_user_next_common(state, &fp_entry_frame);
+		return unwind_user_next_common(state, &fp_entry_frame,
+					       /*signal=*/false);
 	}
 
 	const struct unwind_user_frame fp_frame = {
 		ARCH_INIT_USER_FP_FRAME(state->ws)
 	};
-	return unwind_user_next_common(state, &fp_frame);
+	return unwind_user_next_common(state, &fp_frame, /*signal=*/false);
 }
 
+/**
+ * unwind_user_next() - Advance @state to the next outer user-space stack frame
+ * @state: Current user unwind state.
+ *
+ * Checks architectural signal-trampoline unwinding first, then attempts each
+ * enabled method in @state->available_types in priority order (Minimal DWARF
+ * CFI first, falling back per frame to frame pointers when an executable
+ * mapping such as JIT code lacks .eh_frame_hdr).
+ *
+ * Return: 0 on success, or -EINVAL when no unwind method succeeds or the walk
+ * has reached the bottom of the stack (setting @state->done).
+ */
 static int unwind_user_next(struct unwind_user_state *state)
 {
 	unsigned long iter_mask = state->available_types;
@@ -90,11 +180,28 @@ static int unwind_user_next(struct unwind_user_state *state)
 	if (state->done)
 		return -EINVAL;
 
+	if (state->nr_signals < UNWIND_USER_MAX_SIGNALS &&
+	    unwind_user_sigreturn(state)) {
+		state->nr_signals++;
+		return 0;
+	}
+
 	for_each_set_bit(bit, &iter_mask, NR_UNWIND_USER_TYPE_BITS) {
 		enum unwind_user_type type = BIT(bit);
 
 		state->current_type = type;
 		switch (type) {
+		case UNWIND_USER_TYPE_CFI: {
+			struct unwind_user_frame frame;
+			bool signal = false;
+
+			if (!unwind_user_next_cfi(state, &frame, &signal) &&
+			    !unwind_user_next_common(state, &frame, signal))
+				return 0;
+			if (state->done)
+				break;
+			continue;
+		}
 		case UNWIND_USER_TYPE_FP:
 			if (!unwind_user_next_fp(state))
 				return 0;
@@ -112,6 +219,16 @@ static int unwind_user_next(struct unwind_user_state *state)
 	return -EINVAL;
 }
 
+/**
+ * unwind_user_start() - Initialize user-space stack unwinding from current task
+ * @state: Unwind state structure to initialize.
+ *
+ * Populates @state from task_pt_regs(current) if the current task is a user
+ * task with valid user-mode registers.
+ *
+ * Return: 0 on success, or -EINVAL if current is a kernel thread, not in user
+ * mode, or running in an unsupported execution mode (e.g. x86 VM86).
+ */
 static int unwind_user_start(struct unwind_user_state *state)
 {
 	struct pt_regs *regs = task_pt_regs(current);
@@ -123,12 +240,15 @@ static int unwind_user_start(struct unwind_user_state *state)
 		return -EINVAL;
 	}
 
+	if (IS_ENABLED(CONFIG_HAVE_UNWIND_USER_CFI))
+		state->available_types |= UNWIND_USER_TYPE_CFI;
 	if (IS_ENABLED(CONFIG_HAVE_UNWIND_USER_FP))
 		state->available_types |= UNWIND_USER_TYPE_FP;
 
 	state->ip = instruction_pointer(regs);
 	state->sp = user_stack_pointer(regs);
-	state->fp = frame_pointer(regs);
+	state->fp = unwind_user_frame_pointer(regs);
+	state->ra_valid = unwind_user_link_register(regs, &state->ra);
 	state->ws = unwind_user_word_size(regs);
 	if (!state->ws) {
 		state->done = true;
@@ -139,6 +259,17 @@ static int unwind_user_start(struct unwind_user_state *state)
 	return 0;
 }
 
+/**
+ * unwind_user() - Capture a user-space stack trace for the current task
+ * @trace: Output stack trace descriptor with caller-allocated @trace->entries.
+ * @max_entries: Maximum number of instruction pointers to store in @trace.
+ *
+ * Must be called in sleepable task context (e.g. syscall return / task_work
+ * deferred unwinding) because user stack and ELF .eh_frame_hdr reads may fault.
+ *
+ * Return: 0 on success (including 0 entries for kernel threads), or -EINVAL if
+ * @max_entries is 0.
+ */
 int unwind_user(struct unwind_stacktrace *trace, unsigned int max_entries)
 {
 	struct unwind_user_state state;
diff --git a/kernel/unwind/user_cfi.c b/kernel/unwind/user_cfi.c
new file mode 100644
index 000000000000..f3abd58eacd3
--- /dev/null
+++ b/kernel/unwind/user_cfi.c
@@ -0,0 +1,378 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * User-space Minimal DWARF CFI unwinding via ELF PT_GNU_EH_FRAME.
+ */
+
+#include <linux/elf.h>
+#include <linux/errno.h>
+#include <linux/kernel.h>
+#include <linux/mm.h>
+#include <linux/mmap_lock.h>
+#include <linux/sched.h>
+#include <linux/uaccess.h>
+#include <linux/unwind_dwarf_cfi.h>
+#include <linux/unwind_user.h>
+
+#define USER_CFI_MAX_PHDRS	64U
+#define USER_CFI_MAX_VMA_STEPS	8U
+
+/**
+ * parse_user_elf64_eh_hdr() - Locate PT_GNU_EH_FRAME in a 64-bit user ELF image
+ * @elf_base: User virtual address of the mapped ELF64 header (file offset 0).
+ * @hdr_uaddr: Output user virtual address of the PT_GNU_EH_FRAME segment.
+ * @hdr_size: Output size in bytes of the PT_GNU_EH_FRAME segment.
+ *
+ * Reads the 64-bit ELF header and up to %USER_CFI_MAX_PHDRS program headers
+ * from user memory, computes the mapping load bias from the file-offset-0
+ * PT_LOAD segment, and resolves the runtime address of PT_GNU_EH_FRAME.
+ * Must be called without holding mmap_lock because copy_from_user() may fault.
+ *
+ * Return: 0 on success, -ENOENT if no non-empty PT_GNU_EH_FRAME or base
+ * PT_LOAD segment exists, -EINVAL if the ELF header is invalid, or -EFAULT on
+ * an unmapped user read.
+ */
+static int parse_user_elf64_eh_hdr(unsigned long elf_base,
+				   unsigned long *hdr_uaddr, size_t *hdr_size)
+{
+	Elf64_Ehdr ehdr;
+	unsigned long load_bias = 0;
+	bool have_load0 = false, have_eh = false;
+	Elf64_Addr eh_vaddr = 0;
+	Elf64_Xword eh_memsz = 0;
+	unsigned int i;
+
+	if (copy_from_user(&ehdr, (const void __user *)elf_base, sizeof(ehdr)))
+		return -EFAULT;
+
+	if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0 ||
+	    ehdr.e_ident[EI_CLASS] != ELFCLASS64 ||
+	    ehdr.e_phentsize != sizeof(Elf64_Phdr) ||
+	    !ehdr.e_phnum || ehdr.e_phnum > USER_CFI_MAX_PHDRS)
+		return -EINVAL;
+
+	for (i = 0; i < ehdr.e_phnum; i++) {
+		Elf64_Phdr phdr;
+		unsigned long p_addr = elf_base + ehdr.e_phoff +
+				       (size_t)i * sizeof(phdr);
+
+		if (copy_from_user(&phdr, (const void __user *)p_addr, sizeof(phdr)))
+			return -EFAULT;
+
+		if (phdr.p_type == PT_LOAD && !have_load0 && phdr.p_offset == 0) {
+			load_bias = elf_base - ALIGN_DOWN(phdr.p_vaddr, PAGE_SIZE);
+			have_load0 = true;
+		} else if (phdr.p_type == PT_GNU_EH_FRAME) {
+			eh_vaddr = phdr.p_vaddr;
+			eh_memsz = phdr.p_memsz;
+			have_eh = true;
+		}
+	}
+
+	if (!have_load0 || !have_eh || !eh_memsz)
+		return -ENOENT;
+
+	*hdr_uaddr = load_bias + eh_vaddr;
+	*hdr_size = (size_t)eh_memsz;
+	return 0;
+}
+
+/**
+ * parse_user_elf32_eh_hdr() - Locate PT_GNU_EH_FRAME in a 32-bit user ELF image
+ * @elf_base: User virtual address of the mapped ELF32 header (file offset 0).
+ * @hdr_uaddr: Output user virtual address of the PT_GNU_EH_FRAME segment.
+ * @hdr_size: Output size in bytes of the PT_GNU_EH_FRAME segment.
+ *
+ * 32-bit compat counterpart to parse_user_elf64_eh_hdr(). Must be called
+ * without holding mmap_lock.
+ *
+ * Return: 0 on success, -ENOENT if no non-empty PT_GNU_EH_FRAME or base
+ * PT_LOAD segment exists, -EINVAL if the ELF header is invalid, or -EFAULT on
+ * an unmapped user read.
+ */
+static int parse_user_elf32_eh_hdr(unsigned long elf_base,
+				   unsigned long *hdr_uaddr, size_t *hdr_size)
+{
+	Elf32_Ehdr ehdr;
+	unsigned long load_bias = 0;
+	bool have_load0 = false, have_eh = false;
+	Elf32_Addr eh_vaddr = 0;
+	Elf32_Word eh_memsz = 0;
+	unsigned int i;
+
+	if (copy_from_user(&ehdr, (const void __user *)elf_base, sizeof(ehdr)))
+		return -EFAULT;
+
+	if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0 ||
+	    ehdr.e_ident[EI_CLASS] != ELFCLASS32 ||
+	    ehdr.e_phentsize != sizeof(Elf32_Phdr) ||
+	    !ehdr.e_phnum || ehdr.e_phnum > USER_CFI_MAX_PHDRS)
+		return -EINVAL;
+
+	for (i = 0; i < ehdr.e_phnum; i++) {
+		Elf32_Phdr phdr;
+		unsigned long p_addr = elf_base + ehdr.e_phoff +
+				       (size_t)i * sizeof(phdr);
+
+		if (copy_from_user(&phdr, (const void __user *)p_addr, sizeof(phdr)))
+			return -EFAULT;
+
+		if (phdr.p_type == PT_LOAD && !have_load0 && phdr.p_offset == 0) {
+			load_bias = elf_base - ALIGN_DOWN((unsigned long)phdr.p_vaddr,
+							  PAGE_SIZE);
+			have_load0 = true;
+		} else if (phdr.p_type == PT_GNU_EH_FRAME) {
+			eh_vaddr = phdr.p_vaddr;
+			eh_memsz = phdr.p_memsz;
+			have_eh = true;
+		}
+	}
+
+	if (!have_load0 || !have_eh || !eh_memsz)
+		return -ENOENT;
+
+	*hdr_uaddr = load_bias + eh_vaddr;
+	*hdr_size = (size_t)eh_memsz;
+	return 0;
+}
+
+/**
+ * lookup_vma_elf_base_locked() - Find the ELF base mapping for an executable IP
+ * @mm: Address space of the current user task (mmap_lock held for read).
+ * @ip: User instruction pointer to resolve.
+ * @vma_start: Output start address of the executable VMA containing @ip.
+ * @vma_end: Output end address of the executable VMA containing @ip (left
+ *           unchanged if @ip does not lie in an executable VMA).
+ * @elf_base: Output start address of the file-offset-0 ELF header mapping.
+ *
+ * Modern linkers (-z separate-code) often place the ELF header in a preceding
+ * read-only VMA at vm_pgoff == 0 while mapping .text into a separate VM_EXEC
+ * VMA with vm_pgoff > 0. Walk up to %USER_CFI_MAX_VMA_STEPS preceding VMAs
+ * backed by the same file to locate the vm_pgoff == 0 mapping, while also
+ * supporting single-VMA binaries and special mappings such as [vdso].
+ *
+ * Return: true if an ELF base mapping was found and stored in *@elf_base,
+ * false otherwise.
+ */
+static bool lookup_vma_elf_base_locked(struct mm_struct *mm, unsigned long ip,
+				       unsigned long *vma_start,
+				       unsigned long *vma_end,
+				       unsigned long *elf_base)
+{
+	struct vm_area_struct *vma = vma_lookup(mm, ip);
+	struct vm_area_struct *prev;
+	struct file *target_file;
+	unsigned int steps = 0;
+
+	if (!vma || !(vma->vm_flags & VM_EXEC))
+		return false;
+
+	*vma_start = vma->vm_start;
+	*vma_end = vma->vm_end;
+
+	if (vma_is_anonymous(vma) || !vma->vm_file) {
+		if (vma->vm_pgoff == 0) {
+			/* Special mappings such as [vdso] */
+			*elf_base = vma->vm_start;
+			return true;
+		}
+		return false;
+	}
+
+	if (vma->vm_pgoff == 0) {
+		*elf_base = vma->vm_start;
+		return true;
+	}
+
+	target_file = vma->vm_file;
+	{
+		VMA_ITERATOR(vmi, mm, vma->vm_start);
+
+		while (steps++ < USER_CFI_MAX_VMA_STEPS &&
+		       (prev = vma_prev(&vmi)) != NULL) {
+			if (vma_is_anonymous(prev) || prev->vm_file != target_file)
+				break;
+			if (prev->vm_pgoff == 0) {
+				*elf_base = prev->vm_start;
+				return true;
+			}
+		}
+	}
+
+	return false;
+}
+
+/**
+ * find_user_eh_frame_hdr() - Resolve PT_GNU_EH_FRAME for a user IP with caching
+ * @state: User unwind walk state holding the per-walk VMA cache.
+ * @ip: Lookup instruction pointer in current->mm.
+ * @out_hdr_uaddr: Output user virtual address of .eh_frame_hdr.
+ * @out_hdr_size: Output size in bytes of .eh_frame_hdr.
+ *
+ * Consults @state->cfi_cache before taking mmap_read_lock_killable(). Negative
+ * lookups for executable VMAs lacking ELF headers or PT_GNU_EH_FRAME (such as
+ * JIT regions) are also cached with eh_hdr_uaddr == 0 to avoid repeated lock
+ * acquisitions during a stack walk.
+ *
+ * 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,
+				  unsigned long ip,
+				  unsigned long *out_hdr_uaddr,
+				  size_t *out_hdr_size)
+{
+	struct mm_struct *mm = current->mm;
+	unsigned long vma_start = 0, vma_end = 0, elf_base = 0;
+	bool found_base;
+	unsigned int i, slot;
+	int err;
+
+	if (!mm)
+		return -EINVAL;
+
+	/* Check per-walk VMA cache first */
+	for (i = 0; i < ARRAY_SIZE(state->cfi_cache); i++) {
+		const struct unwind_user_cfi_cache *c = &state->cfi_cache[i];
+
+		if (c->valid && ip >= c->vma_start && ip < c->vma_end) {
+			if (!c->eh_hdr_uaddr)
+				return -ENOENT;
+			*out_hdr_uaddr = c->eh_hdr_uaddr;
+			*out_hdr_size = c->eh_hdr_size;
+			return 0;
+		}
+	}
+
+	/*
+	 * Resolve the executable VMA and its base ELF mapping (pgoff == 0)
+	 * under mmap_read_lock, then drop mmap_read_lock BEFORE any faultable
+	 * copy_from_user() calls.
+	 */
+	if (mmap_read_lock_killable(mm))
+		return -EINTR;
+
+	found_base = lookup_vma_elf_base_locked(mm, ip, &vma_start, &vma_end,
+						&elf_base);
+	mmap_read_unlock(mm);
+
+	if (!vma_end)
+		return -ENOENT;
+
+	slot = state->cfi_cache_next++ % ARRAY_SIZE(state->cfi_cache);
+	state->cfi_cache[slot].vma_start = vma_start;
+	state->cfi_cache[slot].vma_end = vma_end;
+	state->cfi_cache[slot].eh_hdr_uaddr = 0;
+	state->cfi_cache[slot].eh_hdr_size = 0;
+	state->cfi_cache[slot].valid = true;
+
+	if (!found_base)
+		return -ENOENT;
+
+	if (state->ws == 8)
+		err = parse_user_elf64_eh_hdr(elf_base, out_hdr_uaddr, out_hdr_size);
+	else if (state->ws == 4)
+		err = parse_user_elf32_eh_hdr(elf_base, out_hdr_uaddr, out_hdr_size);
+	else
+		return -EINVAL;
+
+	if (err)
+		return err;
+
+	state->cfi_cache[slot].eh_hdr_uaddr = *out_hdr_uaddr;
+	state->cfi_cache[slot].eh_hdr_size = *out_hdr_size;
+	return 0;
+}
+
+/**
+ * unwind_user_next_cfi() - Compute the Minimal DWARF CFI frame rule for @state
+ * @state: Current user-space unwind state (may set @state->done on bottom).
+ * @out_frame: Output frame recovery rule for unwind_user_next_common().
+ * @out_signal: Set to true if the evaluated FDE represents a signal frame.
+ *
+ * Looks up the user binary's PT_GNU_EH_FRAME table, evaluates the Minimal
+ * DWARF CFI bytecode at @state->ip (or @state->ip - 1 for normal call return
+ * addresses), and translates the resulting &struct dwarf_cfi_row into a
+ * &struct unwind_user_frame.
+ *
+ * Return: 0 on success, -ENOENT if no FDE covers @state->ip or if
+ * DW_CFA_undefined marks the bottom of the stack (setting @state->done), or a
+ * negative errno (-EINVAL, -EFAULT, -EOVERFLOW, -EINTR) on failure.
+ */
+int unwind_user_next_cfi(struct unwind_user_state *state,
+			 struct unwind_user_frame *out_frame, bool *out_signal)
+{
+	struct dwarf_cfi_arch arch;
+	struct dwarf_cfi_row row;
+	unsigned long lookup_ip, hdr_uaddr;
+	size_t hdr_size;
+	int err;
+
+	if (!unwind_user_cfi_arch(state->ws, &arch))
+		return -EINVAL;
+
+	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.
+		 */
+		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;
+	}
+	if (err)
+		return err;
+
+	/* Explicit DW_CFA_undefined on RA marks bottom of stack (_start/clone) */
+	if (row.ra_rule == DWARF_CFI_RULE_UNDEFINED) {
+		state->done = true;
+		return -ENOENT;
+	}
+
+	if (row.cfa_base != DWARF_CFI_BASE_SP &&
+	    row.cfa_base != DWARF_CFI_BASE_FP &&
+	    row.cfa_base != DWARF_CFI_BASE_FP_INDIRECT &&
+	    row.cfa_base != DWARF_CFI_BASE_SP_INDIRECT)
+		return -EINVAL;
+	if (row.ra_rule == DWARF_CFI_RULE_SAME) {
+		if (!state->ra_valid)
+			return -EINVAL;
+	} else if (row.ra_rule != DWARF_CFI_RULE_OFFSET &&
+		   row.ra_rule != DWARF_CFI_RULE_SP_OFFSET) {
+		return -EINVAL;
+	}
+
+	memset(out_frame, 0, sizeof(*out_frame));
+	out_frame->use_fp = (row.cfa_base == DWARF_CFI_BASE_FP ||
+			     row.cfa_base == DWARF_CFI_BASE_FP_INDIRECT);
+	out_frame->cfa_indirect = (row.cfa_base == DWARF_CFI_BASE_FP_INDIRECT ||
+				   row.cfa_base == DWARF_CFI_BASE_SP_INDIRECT);
+	out_frame->cfa_off = row.cfa_off;
+	out_frame->ra_from_reg = (row.ra_rule == DWARF_CFI_RULE_SAME);
+	out_frame->ra_from_sp = (row.ra_rule == DWARF_CFI_RULE_SP_OFFSET);
+	out_frame->ra_signed = row.ra_signed;
+	out_frame->ra_off = row.ra_off;
+	if (row.fp_rule == DWARF_CFI_RULE_OFFSET) {
+		out_frame->fp_off = row.fp_off;
+	} else if (row.fp_rule == DWARF_CFI_RULE_FP_OFFSET) {
+		out_frame->fp_from_fp = true;
+		out_frame->fp_off = row.fp_off;
+	} else if (row.fp_rule == DWARF_CFI_RULE_SP_OFFSET) {
+		out_frame->fp_from_sp = true;
+		out_frame->fp_off = row.fp_off;
+	}
+	*out_signal = row.signal;
+	return 0;
+}
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 03/11] scripts, unwind: Add build-time .eh_frame minifier
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 01/11] unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 02/11] unwind_user: Support Minimal DWARF CFI user-space unwinding Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 04/11] objtool/ibt: Ignore .eh_frame relocations during ENDBR validation Ian Rogers
                   ` (7 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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).

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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

diff --git a/arch/Kconfig b/arch/Kconfig
index 340a7ecbfc68..6509265065e1 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -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
diff --git a/rust/Makefile b/rust/Makefile
index 0165626decbe..1238b4ac661d 100644
--- a/rust/Makefile
+++ b/rust/Makefile
@@ -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
 
diff --git a/scripts/Makefile b/scripts/Makefile
index d7fbb7ca098b..c392610b65dd 100644
--- a/scripts/Makefile
+++ b/scripts/Makefile
@@ -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
diff --git a/scripts/Makefile.build b/scripts/Makefile.build
index 6127feb970c6..ced0f630f566 100644
--- a/scripts/Makefile.build
+++ b/scripts/Makefile.build
@@ -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)
diff --git a/scripts/Makefile.lib b/scripts/Makefile.lib
index 19e96b30a122..b27bcd50daf7 100644
--- a/scripts/Makefile.lib
+++ b/scripts/Makefile.lib
@@ -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
diff --git a/scripts/Makefile.vmlinux_o b/scripts/Makefile.vmlinux_o
index 0b37bd5dc3a4..160d43fbb393 100644
--- a/scripts/Makefile.vmlinux_o
+++ b/scripts/Makefile.vmlinux_o
@@ -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
 
diff --git a/scripts/min_eh_frame.c b/scripts/min_eh_frame.c
new file mode 100644
index 000000000000..4138a2f69dcd
--- /dev/null
+++ b/scripts/min_eh_frame.c
@@ -0,0 +1,1719 @@
+// SPDX-License-Identifier: GPL-2.0-only OR MIT
+/*
+ * min_eh_frame.c - Build-time .eh_frame minifier for Minimal DWARF CFI.
+ *
+ * Rewrites ET_REL (.o) .eh_frame and .rela.eh_frame sections in place so only
+ * Minimal DWARF CFA bytecodes remain:
+ *  - Strips general-purpose register spills/restores (keeping only SP, FP, RA)
+ *  - Strips DW_CFA_GNU_args_size and redundant remember_state/restore_state
+ *  - Coalesces adjacent DW_CFA_advance_loc* instructions and drops trailing
+ *    PC-advance instructions after the last state transition
+ *  - Drops FDEs (and their relocations) that use unsupported DWARF expressions
+ */
+
+#include <elf.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define DW_CFA_nop				0x00
+#define DW_CFA_set_loc				0x01
+#define DW_CFA_advance_loc1			0x02
+#define DW_CFA_advance_loc2			0x03
+#define DW_CFA_advance_loc4			0x04
+#define DW_CFA_offset_extended			0x05
+#define DW_CFA_restore_extended			0x06
+#define DW_CFA_undefined			0x07
+#define DW_CFA_same_value			0x08
+#define DW_CFA_register				0x09
+#define DW_CFA_remember_state			0x0a
+#define DW_CFA_restore_state			0x0b
+#define DW_CFA_def_cfa				0x0c
+#define DW_CFA_def_cfa_register			0x0d
+#define DW_CFA_def_cfa_offset			0x0e
+#define DW_CFA_def_cfa_expression		0x0f
+#define DW_CFA_expression			0x10
+#define DW_CFA_offset_extended_sf		0x11
+#define DW_CFA_def_cfa_sf			0x12
+#define DW_CFA_def_cfa_offset_sf		0x13
+#define DW_CFA_val_offset			0x14
+#define DW_CFA_val_offset_sf			0x15
+#define DW_CFA_val_expression			0x16
+#define DW_CFA_AARCH64_negate_ra_state		0x2d
+#define DW_CFA_GNU_args_size			0x2e
+#define DW_CFA_GNU_negative_offset_extended	0x2f
+
+#ifndef EM_RISCV
+#define EM_RISCV				243
+#endif
+
+#ifndef SHT_X86_64_UNWIND
+#define SHT_X86_64_UNWIND			0x70000001U
+#endif
+
+#define DW_OP_deref				0x06
+#define DW_OP_breg0				0x70
+
+#define DW_EH_PE_omit				0xff
+#define DW_EH_PE_FORM				0x0f
+#define DW_EH_PE_absptr				0x00
+#define DW_EH_PE_udata2				0x02
+#define DW_EH_PE_udata4				0x03
+#define DW_EH_PE_udata8				0x04
+#define DW_EH_PE_sdata2				0x0a
+#define DW_EH_PE_sdata4				0x0b
+#define DW_EH_PE_sdata8				0x0c
+#define DW_EH_PE_indirect			0x80
+
+/* Target architecture DWARF register numbers for SP, FP, and RA. */
+struct arch_cfg {
+	uint8_t addr_size;
+	uint8_t sp_reg;
+	uint8_t fp_reg;
+	uint8_t ra_reg;
+};
+
+/* Abstract Minimal DWARF unwind row tracked while filtering CFA opcodes. */
+struct min_row {
+	int32_t cfa_off;
+	int32_t fp_off;
+	int32_t ra_off;
+	uint8_t cfa_kind; /* 0=undef, 1=reg, 2=fp_indirect, 3=sp_indirect */
+	uint8_t cfa_reg;
+	uint8_t fp_rule;  /* 0=same, 1=cfa_off, 2=fp_off, 3=undef, 4=sp_off */
+	uint8_t ra_rule;  /* 0=same, 1=cfa_off, 3=undef, 4=sp_off */
+	bool ra_signed;
+};
+
+/* Parsed CIE metadata and its rewritten offset in the minified .eh_frame. */
+struct cie_info {
+	size_t old_off;
+	size_t new_off;
+	uint32_t code_align;
+	int32_t data_align;
+	uint8_t ra_reg;
+	uint8_t fde_enc;
+	bool has_z;
+	bool is_signal;
+	struct min_row init_row;
+};
+
+/*
+ * Buffered output event emitted by minify_insns(). Adjacent non-relocated
+ * PC-advance events are coalesced before serialization, whereas relocated
+ * DW_CFA_advance_loc* instructions (e.g. RISC-V R_RISCV_ADD/SUB pairs) are
+ * preserved verbatim with their original byte offsets recorded for relocation
+ * remapping.
+ */
+struct out_event {
+	bool is_adv;
+	bool has_reloc;
+	uint32_t adv;
+	size_t orig_off;
+	size_t new_off;
+	uint8_t bytes[16];
+	size_t len;
+};
+
+/* Mapping from an input relocated CFA instruction span to its new offset. */
+struct reloc_map {
+	size_t orig_off;
+	size_t len;
+	size_t new_off;
+};
+
+/* Wrapper preserving original .rela.eh_frame order across r_offset sorting. */
+struct indexed_rela {
+	Elf64_Rela rela;
+	size_t orig_idx;
+};
+
+/* Monotonic mapping anchor from an input .eh_frame span to output .eh_frame. */
+struct eh_anchor {
+	size_t old_off;
+	size_t len;
+	size_t new_off;
+};
+
+/* Sorted list of .eh_frame anchors for updating section-local symbols/relocs. */
+struct anchor_list {
+	struct eh_anchor *data;
+	size_t len;
+	size_t cap;
+};
+
+/* Growable output byte buffer. */
+struct byte_buf {
+	uint8_t *data;
+	size_t len;
+	size_t cap;
+};
+
+static void buf_append(struct byte_buf *b, const void *src, size_t n)
+{
+	if (!n)
+		return;
+	if (b->len + n > b->cap) {
+		size_t ncap = b->cap ? b->cap * 2 : 4096;
+
+		while (ncap < b->len + n)
+			ncap *= 2;
+		b->data = realloc(b->data, ncap);
+		if (!b->data) {
+			perror("realloc");
+			exit(1);
+		}
+		b->cap = ncap;
+	}
+	memcpy(b->data + b->len, src, n);
+	b->len += n;
+}
+
+static void buf_append_u8(struct byte_buf *b, uint8_t v)
+{
+	buf_append(b, &v, 1);
+}
+
+static uint16_t get_le16(const uint8_t *p)
+{
+	return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
+}
+
+static uint32_t get_le32(const uint8_t *p)
+{
+	return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
+	       ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
+}
+
+static void put_le16(uint8_t *p, uint16_t v)
+{
+	p[0] = (uint8_t)v;
+	p[1] = (uint8_t)(v >> 8);
+}
+
+static void put_le32(uint8_t *p, uint32_t v)
+{
+	p[0] = (uint8_t)v;
+	p[1] = (uint8_t)(v >> 8);
+	p[2] = (uint8_t)(v >> 16);
+	p[3] = (uint8_t)(v >> 24);
+}
+
+static int read_uleb128(const uint8_t *buf, size_t *pos, size_t end, uint32_t *out)
+{
+	uint32_t val = 0;
+	unsigned int shift = 0;
+
+	while (*pos < end) {
+		uint8_t b = buf[(*pos)++];
+
+		if (shift == 28 && ((b & 0x7f) > 0x0f || (b & 0x80)))
+			return -1;
+		val |= (uint32_t)(b & 0x7f) << shift;
+		if (!(b & 0x80)) {
+			*out = val;
+			return 0;
+		}
+		shift += 7;
+	}
+	return -1;
+}
+
+static int read_sleb128(const uint8_t *buf, size_t *pos, size_t end, int32_t *out)
+{
+	uint32_t val = 0;
+	unsigned int shift = 0;
+
+	while (*pos < end) {
+		uint8_t b = buf[(*pos)++];
+
+		if (shift == 28) {
+			uint8_t top = b & 0x78;
+
+			if ((b & 0x80) || (top != 0x00 && top != 0x78))
+				return -1;
+		}
+		val |= (uint32_t)(b & 0x7f) << shift;
+		shift += 7;
+		if (!(b & 0x80)) {
+			if (shift < 32 && (b & 0x40))
+				val |= ~0U << shift;
+			*out = (int32_t)val;
+			return 0;
+		}
+	}
+	return -1;
+}
+
+static size_t encode_uleb128(uint32_t val, uint8_t *out)
+{
+	size_t n = 0;
+
+	do {
+		uint8_t b = val & 0x7f;
+
+		val >>= 7;
+		if (val)
+			b |= 0x80;
+		out[n++] = b;
+	} while (val);
+	return n;
+}
+
+static size_t encode_sleb128(int32_t val, uint8_t *out)
+{
+	size_t n = 0;
+	bool more = true;
+
+	while (more) {
+		uint8_t b = val & 0x7f;
+
+		val >>= 7;
+		if ((val == 0 && !(b & 0x40)) || (val == -1 && (b & 0x40)))
+			more = false;
+		else
+			b |= 0x80;
+		out[n++] = b;
+	}
+	return n;
+}
+
+static int ptr_enc_size(uint8_t enc, uint8_t addr_size)
+{
+	if (enc == DW_EH_PE_omit)
+		return 0;
+	switch (enc & DW_EH_PE_FORM) {
+	case DW_EH_PE_absptr:
+		return addr_size;
+	case DW_EH_PE_udata2:
+	case DW_EH_PE_sdata2:
+		return 2;
+	case DW_EH_PE_udata4:
+	case DW_EH_PE_sdata4:
+		return 4;
+	case DW_EH_PE_udata8:
+	case DW_EH_PE_sdata8:
+		return 8;
+	default:
+		return -1;
+	}
+}
+
+static bool rows_equal(const struct min_row *a, const struct min_row *b)
+{
+	if (a->cfa_kind != b->cfa_kind || a->cfa_off != b->cfa_off ||
+	    a->fp_rule != b->fp_rule || a->ra_rule != b->ra_rule ||
+	    a->ra_signed != b->ra_signed)
+		return false;
+	if (a->cfa_kind == 1 && a->cfa_reg != b->cfa_reg)
+		return false;
+	if ((a->fp_rule == 1 || a->fp_rule == 2 || a->fp_rule == 4) &&
+	    a->fp_off != b->fp_off)
+		return false;
+	if ((a->ra_rule == 1 || a->ra_rule == 4) &&
+	    a->ra_off != b->ra_off)
+		return false;
+	return true;
+}
+
+static int mul_s32(int64_t a, int64_t b, int32_t *out)
+{
+	int64_t prod = a * b;
+
+	if (prod < INT32_MIN || prod > INT32_MAX)
+		return -1;
+	*out = (int32_t)prod;
+	return 0;
+}
+
+static int add_adv_u32(uint32_t *acc, uint32_t delta)
+{
+	if (UINT32_MAX - *acc < delta)
+		return -1;
+	*acc += delta;
+	return 0;
+}
+
+static bool has_reloc_in_range(const Elf64_Rela *relas, size_t nrelas,
+			       size_t lo, size_t hi)
+{
+	for (size_t i = 0; i < nrelas; i++) {
+		if (relas[i].r_offset >= lo && relas[i].r_offset < hi)
+			return true;
+	}
+	return false;
+}
+
+static void flush_adv_bytes(struct byte_buf *out_bytes, uint32_t *acc)
+{
+	uint8_t abuf[5];
+	uint32_t v = *acc;
+
+	if (!v)
+		return;
+	if (v <= 0x3f) {
+		abuf[0] = 0x40 | (uint8_t)v;
+		buf_append(out_bytes, abuf, 1);
+	} else if (v <= 0xff) {
+		abuf[0] = DW_CFA_advance_loc1;
+		abuf[1] = (uint8_t)v;
+		buf_append(out_bytes, abuf, 2);
+	} else if (v <= 0xffff) {
+		abuf[0] = DW_CFA_advance_loc2;
+		put_le16(abuf + 1, (uint16_t)v);
+		buf_append(out_bytes, abuf, 3);
+	} else {
+		abuf[0] = DW_CFA_advance_loc4;
+		put_le32(abuf + 1, v);
+		buf_append(out_bytes, abuf, 5);
+	}
+	*acc = 0;
+}
+
+/*
+ * Filter a CIE or FDE instruction stream down to Minimal DWARF CFA opcodes:
+ *  - Drop untracked GPR spills/restores, DW_CFA_nop, and DW_CFA_GNU_args_size
+ *  - Elide redundant state transitions and empty remember_state/restore_state
+ *  - Coalesce non-relocated DW_CFA_advance_loc* ops into minimal encodings and
+ *    drop trailing PC advances after the final state change
+ *  - Return -1 if an FDE uses opcodes or DWARF expressions outside the Minimal
+ *    DWARF subset so the caller can drop that FDE cleanly.
+ */
+static int minify_insns(const uint8_t *insns, size_t end, size_t insns_eh_off,
+			const Elf64_Rela *insn_relas, size_t n_insn_relas,
+			const struct cie_info *cie, const struct arch_cfg *arch,
+			bool is_cie, struct min_row *io_row,
+			struct byte_buf *out_bytes,
+			struct reloc_map **out_rmaps, size_t *out_nrmaps)
+{
+	size_t cap = end + 16;
+	struct out_event *evs = calloc(cap, sizeof(*evs));
+	size_t nev = 0;
+	uint32_t pending_adv = 0;
+	struct min_row row = *io_row;
+	struct min_row cie_base = *io_row;
+	struct {
+		struct min_row saved;
+		size_t ev_idx;
+	} stack[4];
+	unsigned int sp = 0;
+	size_t pos = 0;
+	int ret = -1;
+
+	if (!evs)
+		return -1;
+
+#define EMIT_OP(raw_ptr, raw_len) do {					\
+	if (pending_adv > 0 && !is_cie) {				\
+		evs[nev].is_adv = true;					\
+		evs[nev].adv = pending_adv;				\
+		nev++;							\
+		pending_adv = 0;					\
+	}								\
+	evs[nev].is_adv = false;					\
+	evs[nev].len = (raw_len);					\
+	memcpy(evs[nev].bytes, (raw_ptr), (raw_len));			\
+	nev++;								\
+} while (0)
+
+#define EMIT_REL_ADV(op_pos, op_len) do {				\
+	if (pending_adv > 0 && !is_cie) {				\
+		evs[nev].is_adv = true;					\
+		evs[nev].adv = pending_adv;				\
+		nev++;							\
+		pending_adv = 0;					\
+	}								\
+	evs[nev].is_adv = true;						\
+	evs[nev].has_reloc = true;					\
+	evs[nev].orig_off = insns_eh_off + (op_pos);			\
+	evs[nev].len = (op_len);					\
+	memcpy(evs[nev].bytes, insns + (op_pos), (op_len));		\
+	nev++;								\
+} while (0)
+
+	while (pos < end) {
+		size_t op_start = pos;
+		uint8_t op = insns[pos++];
+		uint8_t hi = op & 0xc0;
+		uint8_t lo = op & 0x3f;
+		uint8_t tmp[16];
+		size_t tn;
+		uint32_t reg, uval;
+		int32_t sval;
+
+		if (nev + 2 >= cap) {
+			struct out_event *nevs;
+
+			cap *= 2;
+			nevs = realloc(evs, cap * sizeof(*evs));
+			if (!nevs)
+				goto out;
+			evs = nevs;
+		}
+
+		if (hi == 0x40) {
+			if (!is_cie && n_insn_relas &&
+			    has_reloc_in_range(insn_relas, n_insn_relas,
+					       insns_eh_off + op_start,
+					       insns_eh_off + pos)) {
+				EMIT_REL_ADV(op_start, 1);
+				continue;
+			}
+			if (add_adv_u32(&pending_adv, lo))
+				goto out;
+			continue;
+		}
+		if (hi == 0x80) {
+			if (read_uleb128(insns, &pos, end, &uval))
+				goto out;
+			if (lo == arch->fp_reg || lo == cie->ra_reg) {
+				int32_t off;
+
+				if (mul_s32(uval, cie->data_align, &off))
+					goto out;
+
+				if (lo == arch->fp_reg &&
+				    (row.fp_rule != 1 || row.fp_off != off)) {
+					row.fp_rule = 1;
+					row.fp_off = off;
+					tmp[0] = 0x80 | lo;
+					tn = 1 + encode_uleb128(uval, tmp + 1);
+					EMIT_OP(tmp, tn);
+				} else if (lo == cie->ra_reg &&
+					   (row.ra_rule != 1 || row.ra_off != off)) {
+					row.ra_rule = 1;
+					row.ra_off = off;
+					tmp[0] = 0x80 | lo;
+					tn = 1 + encode_uleb128(uval, tmp + 1);
+					EMIT_OP(tmp, tn);
+				}
+			}
+			continue;
+		}
+		if (hi == 0xc0) {
+			if (lo == arch->fp_reg &&
+			    (row.fp_rule != cie_base.fp_rule ||
+			     ((cie_base.fp_rule == 1 || cie_base.fp_rule == 2 ||
+			       cie_base.fp_rule == 4) &&
+			      row.fp_off != cie_base.fp_off))) {
+				row.fp_rule = cie_base.fp_rule;
+				row.fp_off = cie_base.fp_off;
+				tmp[0] = 0xc0 | lo;
+				EMIT_OP(tmp, 1);
+			} else if (lo == cie->ra_reg &&
+				   (row.ra_rule != cie_base.ra_rule ||
+				    ((cie_base.ra_rule == 1 ||
+				      cie_base.ra_rule == 4) &&
+				     row.ra_off != cie_base.ra_off))) {
+				row.ra_rule = cie_base.ra_rule;
+				row.ra_off = cie_base.ra_off;
+				tmp[0] = 0xc0 | lo;
+				EMIT_OP(tmp, 1);
+			}
+			continue;
+		}
+
+		switch (op) {
+		case DW_CFA_nop:
+			break;
+		case DW_CFA_advance_loc1:
+			if (pos + 1 > end)
+				goto out;
+			pos += 1;
+			if (!is_cie && n_insn_relas &&
+			    has_reloc_in_range(insn_relas, n_insn_relas,
+					       insns_eh_off + op_start,
+					       insns_eh_off + pos)) {
+				EMIT_REL_ADV(op_start, 2);
+				break;
+			}
+			if (add_adv_u32(&pending_adv, insns[op_start + 1]))
+				goto out;
+			break;
+		case DW_CFA_advance_loc2:
+			if (pos + 2 > end)
+				goto out;
+			pos += 2;
+			if (!is_cie && n_insn_relas &&
+			    has_reloc_in_range(insn_relas, n_insn_relas,
+					       insns_eh_off + op_start,
+					       insns_eh_off + pos)) {
+				EMIT_REL_ADV(op_start, 3);
+				break;
+			}
+			if (add_adv_u32(&pending_adv, get_le16(insns + op_start + 1)))
+				goto out;
+			break;
+		case DW_CFA_advance_loc4:
+			if (pos + 4 > end)
+				goto out;
+			pos += 4;
+			if (!is_cie && n_insn_relas &&
+			    has_reloc_in_range(insn_relas, n_insn_relas,
+					       insns_eh_off + op_start,
+					       insns_eh_off + pos)) {
+				EMIT_REL_ADV(op_start, 5);
+				break;
+			}
+			if (add_adv_u32(&pending_adv, get_le32(insns + op_start + 1)))
+				goto out;
+			break;
+		case DW_CFA_def_cfa:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_uleb128(insns, &pos, end, &uval) ||
+			    reg > 255 || uval > INT32_MAX)
+				goto out;
+			if (row.cfa_kind != 1 || row.cfa_reg != reg ||
+			    row.cfa_off != (int32_t)uval) {
+				row.cfa_kind = 1;
+				row.cfa_reg = (uint8_t)reg;
+				row.cfa_off = (int32_t)uval;
+				tmp[0] = DW_CFA_def_cfa;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				tn += encode_uleb128(uval, tmp + tn);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_def_cfa_sf:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_sleb128(insns, &pos, end, &sval) || reg > 255 ||
+			    mul_s32(sval, cie->data_align, &row.cfa_off))
+				goto out;
+			row.cfa_kind = 1;
+			row.cfa_reg = (uint8_t)reg;
+			tmp[0] = DW_CFA_def_cfa_sf;
+			tn = 1 + encode_uleb128(reg, tmp + 1);
+			tn += encode_sleb128(sval, tmp + tn);
+			EMIT_OP(tmp, tn);
+			break;
+		case DW_CFA_def_cfa_register:
+			if (row.cfa_kind != 1 ||
+			    read_uleb128(insns, &pos, end, &reg) || reg > 255)
+				goto out;
+			if (row.cfa_reg != reg) {
+				row.cfa_reg = (uint8_t)reg;
+				tmp[0] = DW_CFA_def_cfa_register;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_def_cfa_offset:
+			if (row.cfa_kind != 1 ||
+			    read_uleb128(insns, &pos, end, &uval) ||
+			    uval > INT32_MAX)
+				goto out;
+			if (row.cfa_off != (int32_t)uval) {
+				row.cfa_off = (int32_t)uval;
+				tmp[0] = DW_CFA_def_cfa_offset;
+				tn = 1 + encode_uleb128(uval, tmp + 1);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_def_cfa_offset_sf:
+			if (row.cfa_kind != 1 ||
+			    read_sleb128(insns, &pos, end, &sval) ||
+			    mul_s32(sval, cie->data_align, &row.cfa_off))
+				goto out;
+			tmp[0] = DW_CFA_def_cfa_offset_sf;
+			tn = 1 + encode_sleb128(sval, tmp + 1);
+			EMIT_OP(tmp, tn);
+			break;
+		case DW_CFA_offset_extended:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_uleb128(insns, &pos, end, &uval))
+				goto out;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				int32_t off;
+
+				if (mul_s32(uval, cie->data_align, &off))
+					goto out;
+
+				if (reg == arch->fp_reg) {
+					row.fp_rule = 1;
+					row.fp_off = off;
+				} else {
+					row.ra_rule = 1;
+					row.ra_off = off;
+				}
+				tmp[0] = DW_CFA_offset_extended;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				tn += encode_uleb128(uval, tmp + tn);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_offset_extended_sf:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_sleb128(insns, &pos, end, &sval))
+				goto out;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				int32_t off;
+
+				if (mul_s32(sval, cie->data_align, &off))
+					goto out;
+
+				if (reg == arch->fp_reg) {
+					row.fp_rule = 1;
+					row.fp_off = off;
+				} else {
+					row.ra_rule = 1;
+					row.ra_off = off;
+				}
+				tmp[0] = DW_CFA_offset_extended_sf;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				tn += encode_sleb128(sval, tmp + tn);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_GNU_negative_offset_extended:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_uleb128(insns, &pos, end, &uval))
+				goto out;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				int32_t off;
+
+				if (mul_s32(-(int64_t)uval, cie->data_align, &off))
+					goto out;
+
+				if (reg == arch->fp_reg) {
+					row.fp_rule = 1;
+					row.fp_off = off;
+				} else {
+					row.ra_rule = 1;
+					row.ra_off = off;
+				}
+				tmp[0] = DW_CFA_GNU_negative_offset_extended;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				tn += encode_uleb128(uval, tmp + tn);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_restore_extended:
+			if (read_uleb128(insns, &pos, end, &reg))
+				goto out;
+			if (reg == arch->fp_reg) {
+				row.fp_rule = cie_base.fp_rule;
+				row.fp_off = cie_base.fp_off;
+				tmp[0] = DW_CFA_restore_extended;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				EMIT_OP(tmp, tn);
+			} else if (reg == cie->ra_reg) {
+				row.ra_rule = cie_base.ra_rule;
+				row.ra_off = cie_base.ra_off;
+				tmp[0] = DW_CFA_restore_extended;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_undefined:
+			if (read_uleb128(insns, &pos, end, &reg))
+				goto out;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				if (reg == arch->fp_reg) {
+					row.fp_rule = 3;
+					row.fp_off = 0;
+				} else {
+					row.ra_rule = 3;
+					row.ra_off = 0;
+				}
+				tmp[0] = DW_CFA_undefined;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_same_value:
+			if (read_uleb128(insns, &pos, end, &reg))
+				goto out;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				if (reg == arch->fp_reg) {
+					row.fp_rule = 0;
+					row.fp_off = 0;
+				} else {
+					row.ra_rule = 0;
+					row.ra_off = 0;
+				}
+				tmp[0] = DW_CFA_same_value;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				EMIT_OP(tmp, tn);
+			}
+			break;
+		case DW_CFA_remember_state:
+			if (sp >= 4)
+				goto out;
+			tmp[0] = DW_CFA_remember_state;
+			EMIT_OP(tmp, 1);
+			stack[sp].saved = row;
+			stack[sp].ev_idx = nev - 1;
+			sp++;
+			break;
+		case DW_CFA_restore_state:
+			if (!sp)
+				goto out;
+			sp--;
+			if (!rows_equal(&stack[sp].saved, &row)) {
+				row = stack[sp].saved;
+				tmp[0] = DW_CFA_restore_state;
+				EMIT_OP(tmp, 1);
+			} else {
+				/*
+				 * Elide dead remember_state..restore_state if
+				 * no minimal ops occurred inside.
+				 */
+				size_t ridx = stack[sp].ev_idx;
+				bool only_adv = true;
+				uint32_t extra = 0;
+
+				for (size_t k = ridx + 1; k < nev; k++) {
+					if (!evs[k].is_adv || evs[k].has_reloc) {
+						only_adv = false;
+						break;
+					}
+					if (add_adv_u32(&extra, evs[k].adv))
+						goto out;
+				}
+				if (only_adv) {
+					if (add_adv_u32(&pending_adv, extra))
+						goto out;
+					nev = ridx;
+				} else {
+					tmp[0] = DW_CFA_restore_state;
+					EMIT_OP(tmp, 1);
+				}
+			}
+			break;
+		case DW_CFA_AARCH64_negate_ra_state:
+			if (arch->ra_reg != 30)
+				goto out;
+			row.ra_signed = !row.ra_signed;
+			tmp[0] = DW_CFA_AARCH64_negate_ra_state;
+			EMIT_OP(tmp, 1);
+			break;
+		case DW_CFA_GNU_args_size:
+			if (read_uleb128(insns, &pos, end, &uval))
+				goto out;
+			break;
+		case DW_CFA_register:
+		case DW_CFA_val_offset:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_uleb128(insns, &pos, end, &uval))
+				goto out;
+			if (reg == arch->sp_reg || reg == arch->fp_reg ||
+			    reg == cie->ra_reg)
+				goto out;
+			break;
+		case DW_CFA_val_offset_sf:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_sleb128(insns, &pos, end, &sval))
+				goto out;
+			if (reg == arch->sp_reg || reg == arch->fp_reg ||
+			    reg == cie->ra_reg)
+				goto out;
+			break;
+		case DW_CFA_def_cfa_expression: {
+			size_t epos = 1;
+
+			if (read_uleb128(insns, &pos, end, &uval) ||
+			    uval > end - pos || uval < 3 || uval > 7)
+				goto out;
+			if ((insns[pos] != (uint8_t)(DW_OP_breg0 + arch->fp_reg) &&
+			     insns[pos] != (uint8_t)(DW_OP_breg0 + arch->sp_reg)) ||
+			    insns[pos + uval - 1] != DW_OP_deref ||
+			    read_sleb128(insns + pos, &epos, uval - 1, &sval) ||
+			    epos != uval - 1)
+				goto out;
+			row.cfa_kind = (insns[pos] == (uint8_t)(DW_OP_breg0 + arch->fp_reg)) ?
+				       2 : 3;
+			row.cfa_reg = 0;
+			row.cfa_off = sval;
+			tmp[0] = DW_CFA_def_cfa_expression;
+			tn = 1 + encode_uleb128(uval, tmp + 1);
+			memcpy(tmp + tn, insns + pos, uval);
+			tn += uval;
+			pos += uval;
+			EMIT_OP(tmp, tn);
+			break;
+		}
+		case DW_CFA_expression: {
+			size_t epos = 1;
+
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_uleb128(insns, &pos, end, &uval) ||
+			    uval > end - pos)
+				goto out;
+			if (reg == arch->fp_reg || reg == cie->ra_reg) {
+				uint8_t fp_op = DW_OP_breg0 + arch->fp_reg;
+				uint8_t sp_op = DW_OP_breg0 + arch->sp_reg;
+				uint8_t b0 = insns[pos];
+
+				if (uval < 2 || uval > 6 ||
+				    (b0 != fp_op && b0 != sp_op) ||
+				    (reg == cie->ra_reg && b0 != sp_op) ||
+				    read_sleb128(insns + pos, &epos, uval, &sval) ||
+				    epos != uval)
+					goto out;
+				if (reg == arch->fp_reg) {
+					row.fp_rule = (b0 == fp_op) ? 2 : 4;
+					row.fp_off = sval;
+				} else {
+					row.ra_rule = 4;
+					row.ra_off = sval;
+				}
+				tmp[0] = DW_CFA_expression;
+				tn = 1 + encode_uleb128(reg, tmp + 1);
+				tn += encode_uleb128(uval, tmp + tn);
+				memcpy(tmp + tn, insns + pos, uval);
+				tn += uval;
+				pos += uval;
+				EMIT_OP(tmp, tn);
+			} else if (reg == arch->sp_reg) {
+				if (uval < 2 || uval > 6 || row.cfa_kind != 3 ||
+				    insns[pos] != (uint8_t)(DW_OP_breg0 + arch->sp_reg) ||
+				    read_sleb128(insns + pos, &epos, uval, &sval) ||
+				    epos != uval || sval != row.cfa_off)
+					goto out;
+				pos += uval;
+			} else {
+				pos += uval;
+			}
+			break;
+		}
+		case DW_CFA_val_expression:
+			if (read_uleb128(insns, &pos, end, &reg) ||
+			    read_uleb128(insns, &pos, end, &uval) ||
+			    pos + uval > end)
+				goto out;
+			if (reg == arch->sp_reg || reg == arch->fp_reg ||
+			    reg == cie->ra_reg)
+				goto out;
+			pos += uval;
+			break;
+		default:
+			goto out;
+		}
+	}
+
+	/* Drop trailing advance_loc instructions */
+	while (nev > 0 && evs[nev - 1].is_adv)
+		nev--;
+
+	{
+		uint32_t acc = 0;
+		size_t nrm = 0;
+
+		for (size_t i = 0; i < nev; i++) {
+			if (evs[i].is_adv && !evs[i].has_reloc) {
+				if (add_adv_u32(&acc, evs[i].adv))
+					goto out;
+			} else {
+				flush_adv_bytes(out_bytes, &acc);
+				evs[i].new_off = out_bytes->len;
+				if (evs[i].has_reloc)
+					nrm++;
+				buf_append(out_bytes, evs[i].bytes, evs[i].len);
+			}
+		}
+
+		if (nrm && out_rmaps && out_nrmaps) {
+			struct reloc_map *rm = calloc(nrm, sizeof(*rm));
+			size_t idx = 0;
+
+			if (!rm)
+				goto out;
+			for (size_t i = 0; i < nev; i++) {
+				if (!evs[i].has_reloc)
+					continue;
+				rm[idx].orig_off = evs[i].orig_off;
+				rm[idx].len = evs[i].len;
+				rm[idx].new_off = evs[i].new_off;
+				idx++;
+			}
+			*out_rmaps = rm;
+			*out_nrmaps = nrm;
+		}
+	}
+
+	*io_row = row;
+	ret = 0;
+out:
+#undef EMIT_REL_ADV
+#undef EMIT_OP
+	free(evs);
+	return ret;
+}
+
+static int anchor_add(struct anchor_list *al, size_t old_off, size_t len,
+		      size_t new_off)
+{
+	if (al->len == al->cap) {
+		size_t ncap = al->cap ? al->cap * 2 : 128;
+		struct eh_anchor *nd = realloc(al->data, ncap * sizeof(*nd));
+
+		if (!nd)
+			return -1;
+		al->data = nd;
+		al->cap = ncap;
+	}
+	al->data[al->len++] = (struct eh_anchor){ old_off, len, new_off };
+	return 0;
+}
+
+static int anchor_find_exact(const struct anchor_list *al, size_t old_off,
+			     size_t *out_new_off)
+{
+	size_t lo = 0, hi = al->len;
+
+	while (lo < hi) {
+		size_t mid = lo + (hi - lo) / 2;
+
+		if (al->data[mid].old_off <= old_off)
+			lo = mid + 1;
+		else
+			hi = mid;
+	}
+	if (!lo)
+		return -1;
+	lo--;
+	if (old_off == al->data[lo].old_off ||
+	    old_off - al->data[lo].old_off < al->data[lo].len) {
+		*out_new_off = al->data[lo].new_off +
+			       (old_off - al->data[lo].old_off);
+		return 0;
+	}
+	return -1;
+}
+
+static size_t anchor_clamp_map(const struct anchor_list *al, size_t old_off,
+			       size_t max_new)
+{
+	size_t mapped = 0;
+
+	if (anchor_find_exact(al, old_off, &mapped) == 0)
+		return mapped <= max_new ? mapped : max_new;
+
+	for (size_t i = al->len; i-- > 0;) {
+		if (al->data[i].old_off <= old_off) {
+			size_t end_new = al->data[i].new_off + al->data[i].len;
+
+			return end_new <= max_new ? end_new : max_new;
+		}
+	}
+	return 0;
+}
+
+static bool sym_is_in_eh_frame(const Elf64_Sym *sym, size_t sym_i,
+			       uint32_t eh_idx, const uint32_t *shndx_tab,
+			       size_t nshndx)
+{
+	if (sym->st_shndx == SHN_XINDEX)
+		return shndx_tab && sym_i < nshndx && shndx_tab[sym_i] == eh_idx;
+	if (sym->st_shndx >= SHN_LORESERVE)
+		return false;
+	return sym->st_shndx == eh_idx;
+}
+
+static int cmp_rela_off(const void *a, const void *b)
+{
+	const struct indexed_rela *ra = a;
+	const struct indexed_rela *rb = b;
+
+	if (ra->rela.r_offset != rb->rela.r_offset)
+		return (ra->rela.r_offset > rb->rela.r_offset) -
+		       (ra->rela.r_offset < rb->rela.r_offset);
+	return (ra->orig_idx > rb->orig_idx) - (ra->orig_idx < rb->orig_idx);
+}
+
+static size_t lower_bound_rela(const Elf64_Rela *relas, size_t nrelas, size_t off)
+{
+	size_t lo = 0, hi = nrelas;
+
+	while (lo < hi) {
+		size_t mid = lo + (hi - lo) / 2;
+
+		if (relas[mid].r_offset < off)
+			lo = mid + 1;
+		else
+			hi = mid;
+	}
+	return lo;
+}
+
+static int remap_fde_relocs(const Elf64_Rela *loc_relas, size_t n_loc_relas,
+			    size_t max_out_relas, size_t loc_off,
+			    size_t new_fde_off,
+			    const Elf64_Rela *insn_relas, size_t n_insn_relas,
+			    const struct reloc_map *rmaps, size_t nrmaps,
+			    size_t new_insns_base,
+			    Elf64_Rela *out_relas, size_t *out_nrelas)
+{
+	for (size_t r = 0; r < n_loc_relas; r++) {
+		if (*out_nrelas >= max_out_relas)
+			return -1;
+		out_relas[*out_nrelas] = loc_relas[r];
+		out_relas[(*out_nrelas)++].r_offset =
+			new_fde_off + 8 + (loc_relas[r].r_offset - loc_off);
+	}
+
+	for (size_t m = 0; m < nrmaps; m++) {
+		size_t lo = rmaps[m].orig_off;
+		size_t hi = lo + rmaps[m].len;
+
+		for (size_t r = 0; r < n_insn_relas; r++) {
+			if (insn_relas[r].r_offset < lo ||
+			    insn_relas[r].r_offset >= hi)
+				continue;
+			if (*out_nrelas >= max_out_relas)
+				return -1;
+			out_relas[*out_nrelas] = insn_relas[r];
+			out_relas[(*out_nrelas)++].r_offset =
+				new_insns_base + rmaps[m].new_off +
+				(insn_relas[r].r_offset - lo);
+		}
+	}
+	return 0;
+}
+
+static int parse_cie_record(const uint8_t *eh_in, size_t p, size_t rec_end,
+			    const struct arch_cfg *arch, struct cie_info *cie,
+			    size_t *out_insns_off)
+{
+	uint8_t ver;
+	const char *aug;
+	size_t aug_len_str;
+	uint32_t ra_col;
+
+	if (p >= rec_end)
+		return -1;
+	ver = eh_in[p++];
+	aug = (const char *)(eh_in + p);
+	aug_len_str = strnlen(aug, rec_end - p);
+	if (p + aug_len_str >= rec_end)
+		return -1;
+	p += aug_len_str + 1;
+	if (ver == 4) {
+		if (p + 2 > rec_end)
+			return -1;
+		p += 2;
+	}
+	if (read_uleb128(eh_in, &p, rec_end, &cie->code_align) ||
+	    read_sleb128(eh_in, &p, rec_end, &cie->data_align))
+		return -1;
+	if (ver == 1) {
+		if (p >= rec_end)
+			return -1;
+		ra_col = eh_in[p++];
+	} else if (read_uleb128(eh_in, &p, rec_end, &ra_col)) {
+		return -1;
+	}
+	cie->ra_reg = (uint8_t)ra_col;
+	cie->fde_enc = DW_EH_PE_absptr;
+
+	if (aug[0] == 'z') {
+		uint32_t alen;
+		size_t aend;
+
+		cie->has_z = true;
+		if (read_uleb128(eh_in, &p, rec_end, &alen) ||
+		    alen > rec_end - p)
+			return -1;
+		aend = p + alen;
+		for (size_t k = 1; aug[k]; k++) {
+			uint8_t penc;
+			int psz;
+
+			if (aug[k] == 'R') {
+				if (p >= aend)
+					return -1;
+				cie->fde_enc = eh_in[p++];
+				if (cie->fde_enc & DW_EH_PE_indirect)
+					return -1;
+			} else if (aug[k] == 'L') {
+				if (p >= aend)
+					return -1;
+				p++;
+			} else if (aug[k] == 'P') {
+				if (p >= aend)
+					return -1;
+				penc = eh_in[p++];
+				psz = ptr_enc_size(penc & ~DW_EH_PE_indirect,
+						   arch->addr_size);
+				if (psz < 0 || (size_t)psz > aend - p)
+					return -1;
+				p += (size_t)psz;
+			} else if (aug[k] == 'S') {
+				cie->is_signal = true;
+			} else if (aug[k] != 'B') {
+				return -1;
+			}
+		}
+		p = aend;
+	} else if (aug[0] != '\0') {
+		return -1;
+	}
+
+	*out_insns_off = p;
+	return 0;
+}
+
+/*
+ * Rewrite a 64-bit little-endian ET_REL object's .eh_frame and .rela.eh_frame
+ * sections in place. Objects with unexpected formats or external relocations
+ * into .eh_frame are left untouched (returning 0) so the build never breaks on
+ * unusual hand-crafted assembly objects.
+ */
+static int process_elf64(uint8_t *map, size_t file_size)
+{
+	Elf64_Ehdr *ehdr = (Elf64_Ehdr *)map;
+	Elf64_Shdr *shdrs;
+	uint32_t shnum, shstrndx;
+	const char *shstrtab;
+	Elf64_Shdr *eh_shdr = NULL, *rela_shdr = NULL, *sym_shdr = NULL;
+	uint32_t eh_idx = 0, sym_idx = 0;
+	Elf64_Sym *syms = NULL;
+	size_t nsyms = 0, nshndx = 0;
+	const uint32_t *shndx_tab = NULL;
+	struct arch_cfg arch;
+	const uint8_t *eh_in;
+	size_t eh_in_len;
+	Elf64_Rela *sorted_relas = NULL;
+	size_t nrelas = 0, out_nrelas = 0;
+	Elf64_Rela *out_relas = NULL;
+	struct cie_info *cies = NULL;
+	size_t ncies = 0, cies_cap = 0;
+	struct anchor_list anchors = {};
+	struct byte_buf out_eh = {};
+	size_t last_len_pos = 0;
+	bool have_last_rec = false;
+	size_t pos = 0;
+
+	if (ehdr->e_type != ET_REL)
+		return 0;
+
+	if (ehdr->e_machine == EM_X86_64)
+		arch = (struct arch_cfg){ 8, 7, 6, 16 };
+	else if (ehdr->e_machine == EM_AARCH64)
+		arch = (struct arch_cfg){ 8, 31, 29, 30 };
+	else if (ehdr->e_machine == EM_RISCV)
+		arch = (struct arch_cfg){ 8, 2, 8, 1 };
+	else
+		return 0;
+
+	if (!ehdr->e_shoff || (ehdr->e_shoff & 7) ||
+	    ehdr->e_shoff > file_size ||
+	    file_size - ehdr->e_shoff < sizeof(Elf64_Shdr))
+		return 0;
+	if (ehdr->e_shentsize != sizeof(Elf64_Shdr))
+		return -1;
+
+	shdrs = (Elf64_Shdr *)(map + ehdr->e_shoff);
+	shnum = ehdr->e_shnum ? ehdr->e_shnum : (uint32_t)shdrs[0].sh_size;
+	if (!shnum ||
+	    (size_t)shnum > (file_size - ehdr->e_shoff) / sizeof(Elf64_Shdr))
+		return -1;
+	shstrndx = (ehdr->e_shstrndx != SHN_XINDEX) ?
+		   ehdr->e_shstrndx : shdrs[0].sh_link;
+
+	if (!shstrndx || shstrndx >= shnum ||
+	    shdrs[shstrndx].sh_offset > file_size ||
+	    shdrs[shstrndx].sh_size == 0 ||
+	    shdrs[shstrndx].sh_size > file_size - shdrs[shstrndx].sh_offset)
+		return -1;
+	shstrtab = (const char *)(map + shdrs[shstrndx].sh_offset);
+
+	for (uint32_t i = 1; i < shnum; i++) {
+		size_t shstr_size = shdrs[shstrndx].sh_size;
+		uint32_t nm_off = shdrs[i].sh_name;
+
+		if ((shdrs[i].sh_type == SHT_PROGBITS ||
+		     shdrs[i].sh_type == SHT_X86_64_UNWIND) &&
+		    nm_off < shstr_size &&
+		    shstr_size - nm_off >= sizeof(".eh_frame") &&
+		    memcmp(shstrtab + nm_off, ".eh_frame",
+			   sizeof(".eh_frame")) == 0) {
+			eh_shdr = &shdrs[i];
+			eh_idx = i;
+			break;
+		}
+	}
+
+	if (!eh_shdr || eh_shdr->sh_size == 0)
+		return 0;
+	if (eh_shdr->sh_offset > file_size ||
+	    eh_shdr->sh_size > file_size - eh_shdr->sh_offset ||
+	    eh_shdr->sh_addralign > 16 ||
+	    (eh_shdr->sh_addralign & (eh_shdr->sh_addralign - 1)) != 0)
+		return -1;
+
+	for (uint32_t i = 1; i < shnum; i++) {
+		if (shdrs[i].sh_type == SHT_RELA && shdrs[i].sh_info == eh_idx) {
+			rela_shdr = &shdrs[i];
+			break;
+		}
+	}
+
+	if (rela_shdr && rela_shdr->sh_link > 0 && rela_shdr->sh_link < shnum &&
+	    shdrs[rela_shdr->sh_link].sh_type == SHT_SYMTAB) {
+		sym_idx = rela_shdr->sh_link;
+		sym_shdr = &shdrs[sym_idx];
+	} else {
+		for (uint32_t i = 1; i < shnum; i++) {
+			if (shdrs[i].sh_type == SHT_SYMTAB) {
+				sym_idx = i;
+				sym_shdr = &shdrs[i];
+				break;
+			}
+		}
+	}
+
+	if (sym_shdr && sym_shdr->sh_size > 0) {
+		if ((sym_shdr->sh_offset & 7) ||
+		    sym_shdr->sh_offset > file_size ||
+		    sym_shdr->sh_size > file_size - sym_shdr->sh_offset ||
+		    sym_shdr->sh_entsize != sizeof(Elf64_Sym) ||
+		    (sym_shdr->sh_size % sizeof(Elf64_Sym)) != 0)
+			return -1;
+		syms = (Elf64_Sym *)(map + sym_shdr->sh_offset);
+		nsyms = sym_shdr->sh_size / sizeof(Elf64_Sym);
+
+		for (uint32_t i = 1; i < shnum; i++) {
+			if (shdrs[i].sh_type == SHT_SYMTAB_SHNDX &&
+			    shdrs[i].sh_link == sym_idx) {
+				if ((shdrs[i].sh_offset & 3) ||
+				    shdrs[i].sh_offset > file_size ||
+				    shdrs[i].sh_size > file_size - shdrs[i].sh_offset ||
+				    shdrs[i].sh_entsize != sizeof(uint32_t) ||
+				    shdrs[i].sh_size != nsyms * sizeof(uint32_t))
+					return -1;
+				shndx_tab = (const uint32_t *)(map + shdrs[i].sh_offset);
+				nshndx = nsyms;
+				break;
+			}
+		}
+
+		/*
+		 * Bail out cleanly if any other relocation section references
+		 * symbols inside .eh_frame.
+		 */
+		for (uint32_t i = 1; i < shnum; i++) {
+			const Elf64_Rela *other;
+			size_t nother;
+
+			if (&shdrs[i] == rela_shdr || shdrs[i].sh_type != SHT_RELA ||
+			    shdrs[i].sh_link != sym_idx || shdrs[i].sh_size == 0)
+				continue;
+			if ((shdrs[i].sh_offset & 7) ||
+			    shdrs[i].sh_offset > file_size ||
+			    shdrs[i].sh_size > file_size - shdrs[i].sh_offset ||
+			    shdrs[i].sh_entsize != sizeof(Elf64_Rela) ||
+			    (shdrs[i].sh_size % sizeof(Elf64_Rela)) != 0)
+				return -1;
+			other = (const Elf64_Rela *)(map + shdrs[i].sh_offset);
+			nother = shdrs[i].sh_size / sizeof(Elf64_Rela);
+			for (size_t r = 0; r < nother; r++) {
+				uint32_t si = ELF64_R_SYM(other[r].r_info);
+
+				if (si < nsyms &&
+				    sym_is_in_eh_frame(&syms[si], si, eh_idx,
+						       shndx_tab, nshndx))
+					return 0;
+			}
+		}
+	}
+
+	eh_in = map + eh_shdr->sh_offset;
+	eh_in_len = eh_shdr->sh_size;
+	if (rela_shdr && rela_shdr->sh_size > 0) {
+		struct indexed_rela *idx_relas;
+		const Elf64_Rela *raw_relas;
+
+		if ((rela_shdr->sh_offset & 7) ||
+		    rela_shdr->sh_offset > file_size ||
+		    rela_shdr->sh_size > file_size - rela_shdr->sh_offset ||
+		    rela_shdr->sh_entsize != sizeof(Elf64_Rela) ||
+		    (rela_shdr->sh_size % sizeof(Elf64_Rela)) != 0)
+			return -1;
+		nrelas = rela_shdr->sh_size / sizeof(Elf64_Rela);
+		idx_relas = malloc(nrelas * sizeof(*idx_relas));
+		sorted_relas = malloc(nrelas * sizeof(Elf64_Rela));
+		out_relas = calloc(nrelas, sizeof(Elf64_Rela));
+		if (!idx_relas || !sorted_relas || !out_relas) {
+			free(idx_relas);
+			free(sorted_relas);
+			free(out_relas);
+			return -1;
+		}
+		raw_relas = (const Elf64_Rela *)(map + rela_shdr->sh_offset);
+		for (size_t i = 0; i < nrelas; i++) {
+			idx_relas[i].rela = raw_relas[i];
+			idx_relas[i].orig_idx = i;
+		}
+		qsort(idx_relas, nrelas, sizeof(*idx_relas), cmp_rela_off);
+		for (size_t i = 0; i < nrelas; i++)
+			sorted_relas[i] = idx_relas[i].rela;
+		free(idx_relas);
+	}
+
+	if (anchor_add(&anchors, /*old_off=*/0, /*len=*/0, /*new_off=*/0))
+		goto bail;
+
+	while (pos + 4 <= eh_in_len) {
+		uint32_t len = get_le32(eh_in + pos);
+		size_t rec_start = pos;
+		size_t rec_end, p;
+		uint32_t cie_id;
+
+		if (len == 0)
+			break;
+		if (len <= 4 || len == 0xffffffffU ||
+		    len > eh_in_len - pos - 4) {
+			free(anchors.data);
+			free(cies);
+			free(sorted_relas);
+			free(out_eh.data);
+			free(out_relas);
+			return -1;
+		}
+		rec_end = pos + 4 + len;
+		cie_id = get_le32(eh_in + pos + 4);
+		p = pos + 8;
+
+		if (cie_id == 0) {
+			struct cie_info cie = {};
+			struct byte_buf min_cie_insns = {};
+			struct byte_buf cie_rec = {};
+			const char *out_aug;
+			uint8_t tmp[16];
+			size_t tn;
+
+			if (parse_cie_record(eh_in, p, rec_end, &arch, &cie, &p))
+				goto bail;
+			if (ncies >= cies_cap) {
+				size_t ncap = cies_cap ? cies_cap * 2 : 64;
+				struct cie_info *ncies_arr;
+
+				ncies_arr = realloc(cies, ncap * sizeof(*cies));
+				if (!ncies_arr)
+					goto bail;
+				cies = ncies_arr;
+				cies_cap = ncap;
+			}
+
+			cie.old_off = rec_start;
+			cie.new_off = out_eh.len;
+			if (minify_insns(eh_in + p, rec_end - p, p,
+					 /*insn_relas=*/NULL,
+					 /*n_insn_relas=*/0, &cie, &arch,
+					 /*is_cie=*/true, &cie.init_row,
+					 &min_cie_insns, /*out_rmaps=*/NULL,
+					 /*out_nrmaps=*/NULL)) {
+				free(min_cie_insns.data);
+				goto bail;
+			}
+
+			/* Emit normalized compact CIE (version 1, "zR" or "zRS") */
+			out_aug = cie.is_signal ? "zRS" : "zR";
+			if (cie.fde_enc == DW_EH_PE_absptr && !cie.has_z)
+				out_aug = "";
+
+			put_le32(tmp, 0);
+			put_le32(tmp + 4, 0);
+			buf_append(&cie_rec, tmp, 8);
+			buf_append_u8(&cie_rec, 1);
+			buf_append(&cie_rec, out_aug, strlen(out_aug) + 1);
+			tn = encode_uleb128(cie.code_align, tmp);
+			buf_append(&cie_rec, tmp, tn);
+			tn = encode_sleb128(cie.data_align, tmp);
+			buf_append(&cie_rec, tmp, tn);
+			buf_append_u8(&cie_rec, cie.ra_reg);
+			if (out_aug[0] == 'z') {
+				buf_append_u8(&cie_rec, 1);
+				buf_append_u8(&cie_rec, cie.fde_enc);
+			}
+			buf_append(&cie_rec, min_cie_insns.data, min_cie_insns.len);
+			while (cie_rec.len & 3)
+				buf_append_u8(&cie_rec, DW_CFA_nop);
+			put_le32(cie_rec.data, (uint32_t)(cie_rec.len - 4));
+
+			last_len_pos = out_eh.len;
+			have_last_rec = true;
+			if (anchor_add(&anchors, rec_start, /*len=*/8,
+				       cie.new_off)) {
+				free(min_cie_insns.data);
+				free(cie_rec.data);
+				goto bail;
+			}
+			buf_append(&out_eh, cie_rec.data, cie_rec.len);
+
+			cies[ncies++] = cie;
+			free(min_cie_insns.data);
+			free(cie_rec.data);
+		} else {
+			size_t old_cie_off;
+			const struct cie_info *cie = NULL;
+			int ptr_sz;
+			size_t loc_off, fde_insns_off;
+			struct min_row fde_row;
+			struct byte_buf min_fde_insns = {};
+			struct byte_buf fde_rec = {};
+			size_t new_fde_off;
+			uint8_t hdr8[8];
+			struct reloc_map *rmaps = NULL;
+			size_t nrmaps = 0;
+			const Elf64_Rela *loc_relas = NULL, *insn_relas = NULL;
+			size_t n_loc_relas = 0, n_insn_relas = 0;
+
+			if (cie_id > rec_start + 4)
+				goto bail;
+			old_cie_off = (rec_start + 4) - cie_id;
+			for (size_t k = ncies; k-- > 0;) {
+				if (cies[k].old_off == old_cie_off) {
+					cie = &cies[k];
+					break;
+				}
+			}
+			if (!cie)
+				goto bail;
+
+			ptr_sz = ptr_enc_size(cie->fde_enc, arch.addr_size);
+			if (ptr_sz <= 0 || p + 2 * (size_t)ptr_sz > rec_end)
+				goto bail;
+			loc_off = p;
+			p += 2 * (size_t)ptr_sz;
+
+			if (cie->has_z) {
+				uint32_t alen;
+
+				if (read_uleb128(eh_in, &p, rec_end, &alen) ||
+				    p + alen > rec_end)
+					goto bail;
+				p += alen;
+			}
+			fde_insns_off = p;
+			fde_row = cie->init_row;
+
+			if (nrelas) {
+				size_t l_lo = lower_bound_rela(sorted_relas,
+							       nrelas, loc_off);
+				size_t l_hi = lower_bound_rela(sorted_relas,
+							       nrelas,
+							       loc_off + 2 * (size_t)ptr_sz);
+				size_t i_lo = lower_bound_rela(sorted_relas,
+							       nrelas,
+							       fde_insns_off);
+				size_t i_hi = lower_bound_rela(sorted_relas,
+							       nrelas, rec_end);
+
+				loc_relas = sorted_relas + l_lo;
+				n_loc_relas = l_hi - l_lo;
+				insn_relas = sorted_relas + i_lo;
+				n_insn_relas = i_hi - i_lo;
+			}
+
+			if (minify_insns(eh_in + fde_insns_off,
+					 rec_end - fde_insns_off,
+					 fde_insns_off, insn_relas,
+					 n_insn_relas, cie, &arch,
+					 /*is_cie=*/false, &fde_row,
+					 &min_fde_insns, &rmaps,
+					 &nrmaps) == 0) {
+				size_t new_insns_base;
+
+				new_fde_off = out_eh.len;
+				put_le32(hdr8, 0);
+				put_le32(hdr8 + 4,
+					 (uint32_t)((new_fde_off + 4) - cie->new_off));
+				buf_append(&fde_rec, hdr8, 8);
+				buf_append(&fde_rec, eh_in + loc_off,
+					   2 * (size_t)ptr_sz);
+				if (cie->has_z || cie->is_signal ||
+				    cie->fde_enc != DW_EH_PE_absptr)
+					buf_append_u8(&fde_rec, 0);
+				new_insns_base = new_fde_off + fde_rec.len;
+				buf_append(&fde_rec, min_fde_insns.data,
+					   min_fde_insns.len);
+				while (fde_rec.len & 3)
+					buf_append_u8(&fde_rec, DW_CFA_nop);
+				put_le32(fde_rec.data,
+					 (uint32_t)(fde_rec.len - 4));
+
+				if (remap_fde_relocs(loc_relas, n_loc_relas,
+						     nrelas, loc_off,
+						     new_fde_off, insn_relas,
+						     n_insn_relas, rmaps,
+						     nrmaps, new_insns_base,
+						     out_relas, &out_nrelas)) {
+					free(rmaps);
+					free(min_fde_insns.data);
+					free(fde_rec.data);
+					goto bail;
+				}
+
+				if (anchor_add(&anchors, rec_start,
+					       8 + 2 * (size_t)ptr_sz,
+					       new_fde_off) ||
+				    anchor_add(&anchors, fde_insns_off,
+					       /*len=*/0, new_insns_base)) {
+					free(rmaps);
+					free(min_fde_insns.data);
+					free(fde_rec.data);
+					goto bail;
+				}
+				for (size_t m = 0; m < nrmaps; m++) {
+					if (anchor_add(&anchors,
+						       rmaps[m].orig_off,
+						       rmaps[m].len,
+						       new_insns_base + rmaps[m].new_off)) {
+						free(rmaps);
+						free(min_fde_insns.data);
+						free(fde_rec.data);
+						goto bail;
+					}
+				}
+
+				last_len_pos = out_eh.len;
+				have_last_rec = true;
+				buf_append(&out_eh, fde_rec.data, fde_rec.len);
+			}
+			free(rmaps);
+			/* Unsupported FDEs are cleanly dropped along with their relocs */
+			free(min_fde_insns.data);
+			free(fde_rec.data);
+		}
+
+		pos = rec_end;
+	}
+
+	/* Pad final record with DW_CFA_nop to section alignment (8 bytes) */
+	if (have_last_rec && eh_shdr->sh_addralign > 4) {
+		size_t align = eh_shdr->sh_addralign;
+
+		while (out_eh.len & (align - 1))
+			buf_append_u8(&out_eh, DW_CFA_nop);
+		put_le32(out_eh.data + last_len_pos,
+			 (uint32_t)(out_eh.len - last_len_pos - 4));
+	}
+
+	if (anchor_add(&anchors, pos, /*len=*/0, out_eh.len) ||
+	    anchor_add(&anchors, eh_in_len, /*len=*/0, out_eh.len))
+		goto bail;
+
+	/*
+	 * Update any .rela.eh_frame relocations whose target symbol resides in
+	 * .eh_frame (e.g. R_RISCV_SUB32 subtracting FDE initial_location).
+	 */
+	for (size_t r = 0; r < out_nrelas; r++) {
+		uint32_t si = ELF64_R_SYM(out_relas[r].r_info);
+		int64_t old_target;
+		size_t new_target, new_sym_val;
+
+		if (!si)
+			continue;
+		if (!syms || si >= nsyms)
+			goto bail;
+		if (!sym_is_in_eh_frame(&syms[si], si, eh_idx, shndx_tab, nshndx))
+			continue;
+
+		old_target = (int64_t)syms[si].st_value + out_relas[r].r_addend;
+		if (old_target <= 0 || (uint64_t)old_target > eh_in_len ||
+		    anchor_find_exact(&anchors, (size_t)old_target, &new_target))
+			goto bail;
+
+		if (ELF64_ST_TYPE(syms[si].st_info) == STT_SECTION) {
+			out_relas[r].r_addend = (int64_t)new_target -
+						(int64_t)syms[si].st_value;
+		} else {
+			if (syms[si].st_value > eh_in_len ||
+			    anchor_find_exact(&anchors, (size_t)syms[si].st_value,
+					      &new_sym_val))
+				goto bail;
+			out_relas[r].r_addend = (int64_t)new_target -
+						(int64_t)new_sym_val;
+		}
+	}
+
+	if (have_last_rec && out_eh.data && out_eh.len <= eh_in_len) {
+		if (syms) {
+			for (size_t s = 1; s < nsyms; s++) {
+				if (!sym_is_in_eh_frame(&syms[s], s, eh_idx,
+							shndx_tab, nshndx) ||
+				    ELF64_ST_TYPE(syms[s].st_info) == STT_SECTION)
+					continue;
+				syms[s].st_value = anchor_clamp_map(&anchors,
+						(size_t)syms[s].st_value,
+						out_eh.len);
+			}
+		}
+		memcpy(map + eh_shdr->sh_offset, out_eh.data, out_eh.len);
+		eh_shdr->sh_size = out_eh.len;
+		if (rela_shdr && out_relas) {
+			memcpy(map + rela_shdr->sh_offset, out_relas,
+			       out_nrelas * sizeof(Elf64_Rela));
+			rela_shdr->sh_size = out_nrelas * sizeof(Elf64_Rela);
+		}
+	}
+
+	free(anchors.data);
+	free(cies);
+	free(sorted_relas);
+	free(out_eh.data);
+	free(out_relas);
+	return 0;
+
+bail:
+	/* Leave unusual/hand-crafted .eh_frame untouched rather than failing build */
+	free(anchors.data);
+	free(cies);
+	free(sorted_relas);
+	free(out_eh.data);
+	free(out_relas);
+	return 0;
+}
+
+int main(int argc, char **argv)
+{
+	for (int i = 1; i < argc; i++) {
+		const char *path = argv[i];
+		struct stat st;
+		uint8_t *map;
+		int fd, rc = 0;
+
+		fd = open(path, O_RDWR);
+		if (fd < 0) {
+			perror(path);
+			return 1;
+		}
+		if (fstat(fd, &st) < 0) {
+			perror("fstat");
+			close(fd);
+			return 1;
+		}
+		if ((size_t)st.st_size < sizeof(Elf64_Ehdr)) {
+			close(fd);
+			continue;
+		}
+		map = mmap(/*addr=*/NULL, (size_t)st.st_size,
+			   PROT_READ | PROT_WRITE, MAP_SHARED, fd,
+			   /*offset=*/0);
+		if (map == MAP_FAILED) {
+			perror("mmap");
+			close(fd);
+			return 1;
+		}
+		if (memcmp(map, ELFMAG, SELFMAG) == 0 &&
+		    map[EI_DATA] == ELFDATA2LSB &&
+		    map[EI_CLASS] == ELFCLASS64)
+			rc = process_elf64(map, (size_t)st.st_size);
+
+		munmap(map, (size_t)st.st_size);
+		close(fd);
+		if (rc)
+			return 1;
+	}
+	return 0;
+}
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 04/11] objtool/ibt: Ignore .eh_frame relocations during ENDBR validation
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (2 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 03/11] scripts, unwind: Add build-time .eh_frame minifier Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 05/11] x86/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
                   ` (6 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/objtool/check.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/tools/objtool/check.c b/tools/objtool/check.c
index 931c5c412f15..e631b0da9bad 100644
--- a/tools/objtool/check.c
+++ b/tools/objtool/check.c
@@ -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")			||
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 05/11] x86/unwind: Add Minimal DWARF CFI kernel unwinder
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (3 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 04/11] objtool/ibt: Ignore .eh_frame relocations during ENDBR validation Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 06/11] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
                   ` (5 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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

diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index c8096cf66c38..517c2b728752 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -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
diff --git a/arch/x86/Kconfig.debug b/arch/x86/Kconfig.debug
index c95c3aaadf97..bd894d76360c 100644
--- a/arch/x86/Kconfig.debug
+++ b/arch/x86/Kconfig.debug
@@ -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
diff --git a/arch/x86/Makefile b/arch/x86/Makefile
index b7e08519b8c1..70c3308653dd 100644
--- a/arch/x86/Makefile
+++ b/arch/x86/Makefile
@@ -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
diff --git a/arch/x86/boot/startup/Makefile b/arch/x86/boot/startup/Makefile
index 5e499cfb29b5..4e3ad26bfc04 100644
--- a/arch/x86/boot/startup/Makefile
+++ b/arch/x86/boot/startup/Makefile
@@ -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
diff --git a/arch/x86/entry/calling.h b/arch/x86/entry/calling.h
index 77e2d920a640..1a133ad44b95 100644
--- a/arch/x86/entry/calling.h
+++ b/arch/x86/entry/calling.h
@@ -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
diff --git a/arch/x86/include/asm/dwarf2.h b/arch/x86/include/asm/dwarf2.h
index 09c9684d3ad6..0fa61360f69d 100644
--- a/arch/x86/include/asm/dwarf2.h
+++ b/arch/x86/include/asm/dwarf2.h
@@ -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
diff --git a/arch/x86/include/asm/frame.h b/arch/x86/include/asm/frame.h
index 0ab65073c1cc..62939fbb6668 100644
--- a/arch/x86/include/asm/frame.h
+++ b/arch/x86/include/asm/frame.h
@@ -9,7 +9,7 @@
  * callable non-leaf asm function to make kernel stack traces more reliable.
  */
 
-#ifdef CONFIG_FRAME_POINTER
+#if defined(CONFIG_FRAME_POINTER) || defined(CONFIG_UNWINDER_DWARF_CFI)
 
 #ifdef __ASSEMBLER__
 
@@ -22,6 +22,30 @@
 	pop %_ASM_BP
 .endm
 
+#else /* !__ASSEMBLER__ */
+
+#define FRAME_BEGIN				\
+	"push %" _ASM_BP "\n"			\
+	_ASM_MOV "%" _ASM_SP ", %" _ASM_BP "\n"
+
+#define FRAME_END "pop %" _ASM_BP "\n"
+
+#endif /* __ASSEMBLER__ */
+
+#define FRAME_OFFSET __ASM_SEL(4, 8)
+
+#else /* !CONFIG_FRAME_POINTER && !CONFIG_UNWINDER_DWARF_CFI */
+
+#define FRAME_BEGIN
+#define FRAME_END
+#define FRAME_OFFSET 0
+
+#endif /* CONFIG_FRAME_POINTER || CONFIG_UNWINDER_DWARF_CFI */
+
+#if defined(CONFIG_FRAME_POINTER) || defined(CONFIG_UNWINDER_DWARF_CFI)
+
+#ifdef __ASSEMBLER__
+
 #ifdef CONFIG_X86_64
 /*
  * This is a sneaky trick to help the unwinder find pt_regs on the stack.  The
@@ -53,12 +77,6 @@
 
 #else /* !__ASSEMBLER__ */
 
-#define FRAME_BEGIN				\
-	"push %" _ASM_BP "\n"			\
-	_ASM_MOV "%" _ASM_SP ", %" _ASM_BP "\n"
-
-#define FRAME_END "pop %" _ASM_BP "\n"
-
 #ifdef CONFIG_X86_64
 
 #define ENCODE_FRAME_POINTER			\
@@ -84,9 +102,7 @@ static inline unsigned long encode_frame_pointer(struct pt_regs *regs)
 
 #endif /* __ASSEMBLER__ */
 
-#define FRAME_OFFSET __ASM_SEL(4, 8)
-
-#else /* !CONFIG_FRAME_POINTER */
+#else /* !CONFIG_FRAME_POINTER && !CONFIG_UNWINDER_DWARF_CFI */
 
 #ifdef __ASSEMBLER__
 
@@ -104,10 +120,6 @@ static inline unsigned long encode_frame_pointer(struct pt_regs *regs)
 
 #endif
 
-#define FRAME_BEGIN
-#define FRAME_END
-#define FRAME_OFFSET 0
-
-#endif /* CONFIG_FRAME_POINTER */
+#endif /* CONFIG_FRAME_POINTER || CONFIG_UNWINDER_DWARF_CFI */
 
 #endif /* _ASM_X86_FRAME_H */
diff --git a/arch/x86/include/asm/module.h b/arch/x86/include/asm/module.h
index 3c2de4ce3b10..da990da59e2b 100644
--- a/arch/x86/include/asm/module.h
+++ b/arch/x86/include/asm/module.h
@@ -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;
 };
diff --git a/arch/x86/include/asm/unwind.h b/arch/x86/include/asm/unwind.h
index 7cede4dc21f0..49bf73193927 100644
--- a/arch/x86/include/asm/unwind.h
+++ b/arch/x86/include/asm/unwind.h
@@ -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)
diff --git a/arch/x86/kernel/Makefile b/arch/x86/kernel/Makefile
index 31f46fd00527..117cf86617cb 100644
--- a/arch/x86/kernel/Makefile
+++ b/arch/x86/kernel/Makefile
@@ -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
 
diff --git a/arch/x86/kernel/ftrace_64.S b/arch/x86/kernel/ftrace_64.S
index 4b20673a3395..a7afcded8d09 100644
--- a/arch/x86/kernel/ftrace_64.S
+++ b/arch/x86/kernel/ftrace_64.S
@@ -27,6 +27,24 @@
 /* Size of stack used to save mcount regs in save_mcount_regs */
 #define MCOUNT_REG_SIZE		(FRAME_SIZE + MCOUNT_FRAME_SIZE)
 
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+# define FTRACE_CFI_STARTPROC		.cfi_startproc
+# define FTRACE_CFI_ENDPROC		.cfi_endproc
+# define FTRACE_CFI_ADJUST_CFA(off)	.cfi_adjust_cfa_offset (off)
+# define FTRACE_CFI_OFFSET(reg, off)	.cfi_offset reg, (off)
+# define FTRACE_CFI_RESTORE(reg)	.cfi_restore reg
+# define FTRACE_CFI_REMEMBER		.cfi_remember_state
+# define FTRACE_CFI_RESTORE_STATE	.cfi_restore_state
+#else
+# define FTRACE_CFI_STARTPROC
+# define FTRACE_CFI_ENDPROC
+# define FTRACE_CFI_ADJUST_CFA(off)
+# define FTRACE_CFI_OFFSET(reg, off)
+# define FTRACE_CFI_RESTORE(reg)
+# define FTRACE_CFI_REMEMBER
+# define FTRACE_CFI_RESTORE_STATE
+#endif
+
 /*
  * gcc -pg option adds a call to 'mcount' in most functions.
  * When -mfentry is used, the call is to 'fentry' and not 'mcount'
@@ -80,6 +98,7 @@
 	 * We add enough stack to save all regs.
 	 */
 	subq $(FRAME_SIZE), %rsp
+	FTRACE_CFI_ADJUST_CFA(FRAME_SIZE)
 	movq %rax, RAX(%rsp)
 	movq %rcx, RCX(%rsp)
 	movq %rdx, RDX(%rsp)
@@ -98,6 +117,7 @@
 	movq %rbp, %rdx
 #endif
 	movq %rdx, RBP(%rsp)
+	FTRACE_CFI_OFFSET(rbp, RBP - MCOUNT_REG_SIZE - 8 - \added)
 
 	/* Copy the parent address into %rsi (second parameter) */
 	movq MCOUNT_REG_SIZE+8+\added(%rsp), %rsi
@@ -118,6 +138,7 @@
 
 	/* ftrace_regs_caller or frame pointers require this */
 	movq RBP(%rsp), %rbp
+	FTRACE_CFI_RESTORE(rbp)
 
 	movq R9(%rsp), %r9
 	movq R8(%rsp), %r8
@@ -128,6 +149,7 @@
 	movq RAX(%rsp), %rax
 
 	addq $MCOUNT_REG_SIZE-\save, %rsp
+	FTRACE_CFI_ADJUST_CFA(-(MCOUNT_REG_SIZE - \save))
 
 	.endm
 
@@ -153,6 +175,7 @@ SYM_FUNC_END(__fentry__)
 EXPORT_SYMBOL(__fentry__)
 
 SYM_FUNC_START(ftrace_caller)
+	FTRACE_CFI_STARTPROC
 	ANNOTATE_NOENDBR
 	/* save_mcount_regs fills in first two parameters */
 	save_mcount_regs
@@ -195,13 +218,16 @@ SYM_INNER_LABEL(ftrace_call, SYM_L_GLOBAL)
 SYM_INNER_LABEL(ftrace_caller_end, SYM_L_GLOBAL)
 	ANNOTATE_NOENDBR
 	RET
+	FTRACE_CFI_ENDPROC
 SYM_FUNC_END(ftrace_caller);
 STACK_FRAME_NON_STANDARD_FP(ftrace_caller)
 
 SYM_FUNC_START(ftrace_regs_caller)
+	FTRACE_CFI_STARTPROC
 	ANNOTATE_NOENDBR
 	/* Save the current flags before any operations that can change them */
 	pushfq
+	FTRACE_CFI_ADJUST_CFA(8)
 
 	/* added 8 bytes to save flags */
 	save_mcount_regs 8
@@ -274,9 +300,11 @@ SYM_INNER_LABEL(ftrace_regs_caller_jmp, SYM_L_GLOBAL)
 	ANNOTATE_NOENDBR
 	jnz	1f
 
+	FTRACE_CFI_REMEMBER
 	restore_mcount_regs
 	/* Restore flags */
 	popfq
+	FTRACE_CFI_ADJUST_CFA(-8)
 
 	/*
 	 * The trampoline will add the return.
@@ -286,23 +314,28 @@ SYM_INNER_LABEL(ftrace_regs_caller_end, SYM_L_GLOBAL)
 	RET
 
 1:
+	FTRACE_CFI_RESTORE_STATE
 	/* See ftrace_jmp_set(), jmp to the trampoline */
 	btsq	$63, %rax
 	jc	2f
+	FTRACE_CFI_REMEMBER
 	movq %rax, MCOUNT_REG_SIZE+8(%rsp)
 	restore_mcount_regs
 	/* Restore flags */
 	popfq
+	FTRACE_CFI_ADJUST_CFA(-8)
 	RET
 
 	/* Swap the flags with orig_rax */
-2:	movq MCOUNT_REG_SIZE(%rsp), %rdi
+2:	FTRACE_CFI_RESTORE_STATE
+	movq MCOUNT_REG_SIZE(%rsp), %rdi
 	movq %rdi, MCOUNT_REG_SIZE-8(%rsp)
 	movq %rax, MCOUNT_REG_SIZE(%rsp)
 
 	restore_mcount_regs 8
 	/* Restore flags */
 	popfq
+	FTRACE_CFI_ADJUST_CFA(-8)
 	UNWIND_HINT_FUNC
 
 	/*
@@ -314,11 +347,14 @@ SYM_INNER_LABEL(ftrace_regs_caller_end, SYM_L_GLOBAL)
 	CALL .Ldo_rebalance
 	int3
 .Ldo_rebalance:
+	FTRACE_CFI_ADJUST_CFA(8)
 	add $8, %rsp
+	FTRACE_CFI_ADJUST_CFA(-8)
 	ALTERNATIVE __stringify(RET), \
 		    __stringify(ANNOTATE_UNRET_SAFE; ret; int3), \
 		    X86_FEATURE_CALL_DEPTH
 
+	FTRACE_CFI_ENDPROC
 SYM_FUNC_END(ftrace_regs_caller)
 STACK_FRAME_NON_STANDARD_FP(ftrace_regs_caller)
 
@@ -370,17 +406,21 @@ SYM_CODE_START(return_to_handler)
 	/* Restore return_to_handler value that got eaten by previous ret instruction. */
 	subq $8, %rsp
 	UNWIND_HINT_FUNC
+	FTRACE_CFI_STARTPROC
 
 	/* Save ftrace_regs for function exit context  */
 	subq $(FRAME_SIZE), %rsp
+	FTRACE_CFI_ADJUST_CFA(FRAME_SIZE)
 
 	movq %rax, RAX(%rsp)
 	movq %rdx, RDX(%rsp)
 	movq %rbp, RBP(%rsp)
+	FTRACE_CFI_OFFSET(rbp, RBP - FRAME_SIZE - 8)
 	movq %rdi, RSP(%rsp)
 	movq %rsp, %rdi
 
 	call ftrace_return_to_handler
+	FTRACE_CFI_ENDPROC
 
 	movq %rax, %rdi
 	movq RDX(%rsp), %rdx
@@ -398,8 +438,10 @@ SYM_CODE_START(return_to_handler)
 	int3
 .Ldo_rop:
 	mov %rdi, (%rsp)
+	FTRACE_CFI_STARTPROC
 	ALTERNATIVE __stringify(RET), \
 		    __stringify(ANNOTATE_UNRET_SAFE; ret; int3), \
 		    X86_FEATURE_CALL_DEPTH
+	FTRACE_CFI_ENDPROC
 SYM_CODE_END(return_to_handler)
 #endif
diff --git a/arch/x86/kernel/module.c b/arch/x86/kernel/module.c
index 33080ad889b7..9cfd60619acc 100644
--- a/arch/x86/kernel/module.c
+++ b/arch/x86/kernel/module.c
@@ -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);
 }
diff --git a/arch/x86/kernel/rethook.c b/arch/x86/kernel/rethook.c
index 85e2f2d16a90..2bff76758024 100644
--- a/arch/x86/kernel/rethook.c
+++ b/arch/x86/kernel/rethook.c
@@ -15,6 +15,87 @@ __visible void arch_rethook_trampoline_callback(struct pt_regs *regs);
 #define ANNOTATE_NOENDBR
 #endif
 
+#if defined(CONFIG_X86_64) && defined(CONFIG_UNWINDER_DWARF_CFI)
+#define RETHOOK_CFI_STARTPROC		"	.cfi_startproc\n"
+#define RETHOOK_CFI_ENDPROC		"	.cfi_endproc\n"
+#define RETHOOK_CFI_ADJUST(off)		"	.cfi_adjust_cfa_offset " #off "\n"
+#define RETHOOK_SAVE_REGS_STRING	\
+	"	subq $24, %rsp\n"	\
+	RETHOOK_CFI_ADJUST(24)		\
+	"	pushq %rdi\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %rsi\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %rdx\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %rcx\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %rax\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %r8\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %r9\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %r10\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %r11\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %rbx\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %rbp\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	.cfi_offset rbp, -144\n"\
+	"	pushq %r12\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %r13\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %r14\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	"	pushq %r15\n"		\
+	RETHOOK_CFI_ADJUST(8)		\
+	ENCODE_FRAME_POINTER
+#define RETHOOK_RESTORE_REGS_STRING	\
+	"	popq %r15\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %r14\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %r13\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %r12\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %rbp\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	.cfi_restore rbp\n"	\
+	"	popq %rbx\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %r11\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %r10\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %r9\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %r8\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %rax\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %rcx\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %rdx\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %rsi\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	popq %rdi\n"		\
+	RETHOOK_CFI_ADJUST(-8)		\
+	"	addq $24, %rsp\n"	\
+	RETHOOK_CFI_ADJUST(-24)
+#else
+#define RETHOOK_CFI_STARTPROC
+#define RETHOOK_CFI_ENDPROC
+#define RETHOOK_CFI_ADJUST(off)
+#define RETHOOK_SAVE_REGS_STRING	SAVE_REGS_STRING
+#define RETHOOK_RESTORE_REGS_STRING	RESTORE_REGS_STRING
+#endif
+
 /*
  * When a target function returns, this code saves registers and calls
  * arch_rethook_trampoline_callback(), which calls the rethook handler.
@@ -29,17 +110,23 @@ asm(
 	/* Push a fake return address to tell the unwinder it's a rethook. */
 	"	pushq $arch_rethook_trampoline\n"
 	UNWIND_HINT_FUNC
+	RETHOOK_CFI_STARTPROC
 	"       pushq $" __stringify(__KERNEL_DS) "\n"
+	RETHOOK_CFI_ADJUST(8)
 	/* Save the 'sp - 16', this will be fixed later. */
 	"	pushq %rsp\n"
+	RETHOOK_CFI_ADJUST(8)
 	"	pushfq\n"
-	SAVE_REGS_STRING
+	RETHOOK_CFI_ADJUST(8)
+	RETHOOK_SAVE_REGS_STRING
 	"	movq %rsp, %rdi\n"
 	"	call arch_rethook_trampoline_callback\n"
-	RESTORE_REGS_STRING
+	RETHOOK_RESTORE_REGS_STRING
 	/* In the callback function, 'regs->flags' is copied to 'regs->ss'. */
 	"	addq $16, %rsp\n"
+	RETHOOK_CFI_ADJUST(-16)
 	"	popfq\n"
+	RETHOOK_CFI_ADJUST(-8)
 #else
 	/* Push a fake return address to tell the unwinder it's a rethook. */
 	"	pushl $arch_rethook_trampoline\n"
@@ -57,6 +144,7 @@ asm(
 	"	popfl\n"
 #endif
 	ASM_RET
+	RETHOOK_CFI_ENDPROC
 	".size arch_rethook_trampoline, .-arch_rethook_trampoline\n"
 );
 NOKPROBE_SYMBOL(arch_rethook_trampoline);
diff --git a/arch/x86/kernel/unwind_dwarf.c b/arch/x86/kernel/unwind_dwarf.c
new file mode 100644
index 000000000000..e591321ed391
--- /dev/null
+++ b/arch/x86/kernel/unwind_dwarf.c
@@ -0,0 +1,663 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Minimal DWARF CFI kernel stack unwinder for x86-64.
+ *
+ * Unwinds kernel stacks using the link-time .eh_frame_hdr / .eh_frame tables
+ * and the strictly bounded Minimal DWARF CFA subset (matching SFrame's state
+ * model), with ENCODE_FRAME_POINTER handling entry/exception pt_regs frames.
+ */
+
+#define pr_fmt(fmt) "unwind_dwarf: " fmt
+
+#include <linux/bpf.h>
+#include <linux/export.h>
+#include <linux/ftrace.h>
+#include <linux/module.h>
+#include <linux/rcupdate.h>
+#include <linux/sched.h>
+#include <linux/sched/task_stack.h>
+#include <linux/unwind_dwarf_cfi.h>
+#include <asm/ptrace.h>
+#include <asm/sections.h>
+#include <asm/stacktrace.h>
+#include <asm/unwind.h>
+
+static bool dwarf_cfi_ready __ro_after_init;
+
+static const struct dwarf_cfi_arch x86_64_cfi_arch = {
+	.ws	= 8,
+	.sp_reg	= 7,	/* %rsp */
+	.fp_reg	= 6,	/* %rbp */
+	.ra_reg	= 16,	/* %rip */
+};
+
+/* Frame-pointer fallback row for BPF JIT frames */
+static const struct dwarf_cfi_row bpf_fp_row = {
+	.cfa_base	= DWARF_CFI_BASE_FP,
+	.cfa_off	= 16,
+	.fp_rule	= DWARF_CFI_RULE_OFFSET,
+	.fp_off		= -16,
+	.ra_rule	= DWARF_CFI_RULE_OFFSET,
+	.ra_off		= -8,
+};
+
+/* Hardcoded row for IP == 0 (NULL function pointer call crash) */
+static const struct dwarf_cfi_row null_call_row = {
+	.cfa_base	= DWARF_CFI_BASE_SP,
+	.cfa_off	= sizeof(long),
+	.fp_rule	= DWARF_CFI_RULE_SAME,
+	.ra_rule	= DWARF_CFI_RULE_OFFSET,
+	.ra_off		= -(s32)sizeof(long),
+};
+
+#ifdef CONFIG_MODULES
+/**
+ * unwind_module_init() - Build Minimal DWARF CFI index for a loadable module
+ * @mod: Module being loaded.
+ * @orc_ip: Unused under CONFIG_UNWINDER_DWARF_CFI (shared prototype with ORC).
+ * @orc_ip_size: Unused under CONFIG_UNWINDER_DWARF_CFI.
+ * @eh_frame: Pointer to the module's SHF_ALLOC .eh_frame section.
+ * @eh_frame_size: Size in bytes of @eh_frame.
+ *
+ * Scans and sorts the module's FDEs and publishes the resulting index to
+ * @mod->arch.dwarf_cfi_index for RCU-protected lockless lookups.
+ */
+void unwind_module_init(struct module *mod, void *orc_ip, size_t orc_ip_size,
+			void *eh_frame, size_t eh_frame_size)
+{
+	struct mod_dwarf_cfi_index *idx;
+
+	idx = dwarf_cfi_mod_alloc(eh_frame, eh_frame_size, &x86_64_cfi_arch);
+	if (idx)
+		rcu_assign_pointer(mod->arch.dwarf_cfi_index, idx);
+}
+
+/**
+ * unwind_module_cleanup() - Unpublish and RCU-free a module's DWARF CFI index
+ * @mod: Module being unloaded or torn down on load failure.
+ */
+void unwind_module_cleanup(struct module *mod)
+{
+	struct mod_dwarf_cfi_index *idx;
+
+	idx = rcu_replace_pointer(mod->arch.dwarf_cfi_index, /*ptr=*/NULL,
+				  /*c=*/true);
+	dwarf_cfi_mod_free_rcu(idx);
+}
+
+/**
+ * dwarf_cfi_module_find() - Evaluate Minimal DWARF CFI for a module text IP
+ * @ip: Kernel instruction pointer to look up (caller holds RCU read lock).
+ * @row: Output evaluated Minimal DWARF CFI row.
+ *
+ * Return: 0 on success, -ENOENT if @ip is not in a module with an FDE, or a
+ * negative errno on invalid FDE bytecode.
+ */
+static int dwarf_cfi_module_find(unsigned long ip, struct dwarf_cfi_row *row)
+{
+	struct mod_dwarf_cfi_index *idx;
+	struct module *mod;
+
+	mod = __module_address(ip);
+	if (!mod)
+		return -ENOENT;
+
+	idx = rcu_dereference_raw(mod->arch.dwarf_cfi_index);
+	return dwarf_cfi_mod_eval(idx, ip, &x86_64_cfi_arch, row);
+}
+#else
+static int dwarf_cfi_module_find(unsigned long ip, struct dwarf_cfi_row *row)
+{
+	return -ENOENT;
+}
+#endif /* CONFIG_MODULES */
+
+static int dwarf_cfi_find(unsigned long ip, struct dwarf_cfi_row *row);
+
+#ifdef CONFIG_DYNAMIC_FTRACE
+/**
+ * dwarf_cfi_ftrace_find() - Map dynamic ftrace trampolines to template CFI
+ * @ip: Instruction pointer potentially inside a dynamic ftrace ops trampoline.
+ * @row: Output evaluated Minimal DWARF CFI row.
+ *
+ * Dynamic ftrace trampolines are copied from ftrace_caller or
+ * ftrace_regs_caller templates at runtime and therefore have no static FDEs of
+ * their own; translate @ip to the corresponding offset in the template stub.
+ *
+ * Return: 0 on success, or -ENOENT if @ip is not in a dynamic trampoline.
+ */
+static int dwarf_cfi_ftrace_find(unsigned long ip, struct dwarf_cfi_row *row)
+{
+	struct ftrace_ops *ops;
+	unsigned long tramp_addr;
+
+	ops = ftrace_ops_trampoline(ip);
+	if (!ops)
+		return -ENOENT;
+
+	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS)
+		tramp_addr = (unsigned long)ftrace_regs_caller;
+	else
+		tramp_addr = (unsigned long)ftrace_caller;
+
+	tramp_addr += ip - ops->trampoline;
+	if (ip == tramp_addr)
+		return -ENOENT;
+
+	return dwarf_cfi_find(tramp_addr, row);
+}
+#else
+static int dwarf_cfi_ftrace_find(unsigned long ip, struct dwarf_cfi_row *row)
+{
+	return -ENOENT;
+}
+#endif
+
+/**
+ * dwarf_cfi_find() - Locate and evaluate the Minimal DWARF CFI row for @ip
+ * @ip: Kernel instruction pointer (caller holds RCU read lock).
+ * @row: Output evaluated Minimal DWARF CFI row.
+ *
+ * Checks NULL-call faults (ip == 0), core vmlinux .eh_frame_hdr, loadable
+ * modules, JITed BPF programs/trampolines with frame pointers, and dynamic
+ * ftrace trampolines.
+ *
+ * Return: 0 on success, -ENOENT if no unwind entry covers @ip, or a negative
+ * errno on malformed CFI data.
+ */
+static int dwarf_cfi_find(unsigned long ip, struct dwarf_cfi_row *row)
+{
+	size_t hdr_size = __stop_eh_frame_hdr - __start_eh_frame_hdr;
+	int err;
+
+	if (ip == 0) {
+		*row = null_call_row;
+		return 0;
+	}
+
+	err = dwarf_cfi_unwind_eh_frame_hdr(__start_eh_frame_hdr, hdr_size,
+					    __start_eh_frame, __stop_eh_frame,
+					    ip, &x86_64_cfi_arch, row);
+	if (!err)
+		return 0;
+
+	err = dwarf_cfi_module_find(ip, row);
+	if (!err)
+		return 0;
+
+#ifdef CONFIG_BPF_JIT
+	if (bpf_has_frame_pointer(ip)) {
+		*row = bpf_fp_row;
+		return 0;
+	}
+#endif
+
+	return dwarf_cfi_ftrace_find(ip, row);
+}
+
+/**
+ * unwind_init() - Validate vmlinux .eh_frame_hdr and enable the CFI unwinder
+ *
+ * Verifies that the linker-generated .eh_frame_hdr version-1 table and
+ * .eh_frame section are present before marking the unwinder ready during early
+ * boot.
+ */
+void __init unwind_init(void)
+{
+	size_t hdr_size = __stop_eh_frame_hdr - __start_eh_frame_hdr;
+	size_t eh_size = __stop_eh_frame - __start_eh_frame;
+
+	if (hdr_size < 12 || !eh_size || __start_eh_frame_hdr[0] != 1) {
+		pr_warn("Bad or missing .eh_frame_hdr table; disabling Minimal DWARF unwinder.\n");
+		return;
+	}
+
+	dwarf_cfi_ready = true;
+}
+
+/**
+ * unwind_get_return_address() - Return the current frame's kernel text IP
+ * @state: Current x86 unwind state.
+ *
+ * Return: Kernel text instruction pointer for @state, or 0 if unwinding is
+ * complete or @state->ip is outside kernel/module/BPF/ftrace text.
+ */
+unsigned long unwind_get_return_address(struct unwind_state *state)
+{
+	if (unwind_done(state))
+		return 0;
+
+	return __kernel_text_address(state->ip) ? state->ip : 0;
+}
+EXPORT_SYMBOL_GPL(unwind_get_return_address);
+
+/**
+ * unwind_get_return_address_ptr() - Return stack slot address holding @state's IP
+ * @state: Current x86 unwind state.
+ *
+ * Return: Pointer to the saved IP in @state->regs or at @state->sp - 8, or
+ * NULL if unwinding is complete.
+ */
+unsigned long *unwind_get_return_address_ptr(struct unwind_state *state)
+{
+	if (unwind_done(state))
+		return NULL;
+
+	if (state->regs)
+		return &state->regs->ip;
+
+	if (state->sp)
+		return (unsigned long *)state->sp - 1;
+
+	return NULL;
+}
+
+static bool stack_access_ok(struct unwind_state *state, unsigned long _addr,
+			    size_t len)
+{
+	struct stack_info *info = &state->stack_info;
+	void *addr = (void *)_addr;
+
+	if (on_stack(info, addr, len))
+		return true;
+
+	return !get_stack_info(addr, state->task, info, &state->stack_mask) &&
+	       on_stack(info, addr, len);
+}
+
+static bool deref_stack_reg(struct unwind_state *state, unsigned long addr,
+			    unsigned long *val)
+{
+	if (!stack_access_ok(state, addr, sizeof(long)))
+		return false;
+
+	*val = READ_ONCE_NOCHECK(*(unsigned long *)addr);
+	return true;
+}
+
+static bool deref_stack_regs(struct unwind_state *state, unsigned long addr,
+			     unsigned long *ip, unsigned long *sp,
+			     unsigned long *bp)
+{
+	struct pt_regs *regs = (struct pt_regs *)addr;
+
+	if (!stack_access_ok(state, addr, sizeof(struct pt_regs)))
+		return false;
+
+	*ip = READ_ONCE_NOCHECK(regs->ip);
+	*sp = READ_ONCE_NOCHECK(regs->sp);
+	*bp = READ_ONCE_NOCHECK(regs->bp);
+
+	if (!user_mode(regs) &&
+	    !on_stack(&state->stack_info, (void *)*sp, sizeof(long))) {
+		struct stack_info next_info;
+
+		if (!get_stack_info((unsigned long *)*sp, state->task,
+				    &next_info, &state->stack_mask))
+			state->stack_info = next_info;
+	}
+	return true;
+}
+
+static struct pt_regs *decode_frame_pointer(unsigned long bp)
+{
+	if (!(bp & 0x1))
+		return NULL;
+
+	return (struct pt_regs *)(bp & ~0x1UL);
+}
+
+/**
+ * get_scratch_reg() - Read a transient DRAP CFA register from @state's pt_regs
+ * @state: Current x86 unwind state.
+ * @dwarf_reg: x86-64 DWARF register number used by DW_CFA_def_cfa_register.
+ * @val: Output register value.
+ *
+ * Compilers realignment prologues/epilogues (DRAP) briefly define the CFA in a
+ * caller-saved scratch register (%r10, %rcx, etc.) for 1-2 instructions. When
+ * unwinding directly from an interrupt/exception with full pt_regs, recover
+ * that register so asynchronous unwinding succeeds at every instruction.
+ *
+ * Return: true if @dwarf_reg was recovered from full pt_regs, false otherwise.
+ */
+static bool get_scratch_reg(struct unwind_state *state, u8 dwarf_reg,
+			    unsigned long *val)
+{
+	struct pt_regs *regs = state->full_regs ? state->regs : state->prev_regs;
+
+	if (!regs)
+		return false;
+
+	switch (dwarf_reg) {
+	case 0: /* %rax */
+		*val = READ_ONCE_NOCHECK(regs->ax);
+		return true;
+	case 1: /* %rdx */
+		*val = READ_ONCE_NOCHECK(regs->dx);
+		return true;
+	case 2: /* %rcx */
+		*val = READ_ONCE_NOCHECK(regs->cx);
+		return true;
+	case 5: /* %rdi */
+		*val = READ_ONCE_NOCHECK(regs->di);
+		return true;
+	case 10: /* %r10 */
+		*val = READ_ONCE_NOCHECK(regs->r10);
+		return true;
+	case 13: /* %r13 */
+		*val = READ_ONCE_NOCHECK(regs->r13);
+		return true;
+	default:
+		return false;
+	}
+}
+
+static bool in_entry_text(unsigned long ip)
+{
+	char *addr = (char *)ip;
+
+	return (addr >= __entry_text_start && addr < __entry_text_end) ||
+	       (void *)ip == ret_from_fork_asm;
+}
+
+/**
+ * dwarf_recover_ret_addr() - Recover ftrace_graph and rethook return addresses
+ * @state: Current x86 unwind state.
+ * @addr: Raw return address read from the stack or pt_regs.
+ * @addr_p: Stack slot address where @addr was stored.
+ *
+ * Handles both single hooks and stacked hooks in either installation order
+ * (fgraph->rethook via unwind_recover_ret_addr(), or rethook->fgraph via a
+ * follow-up ftrace_graph_ret_addr() pass).
+ *
+ * Return: Original caller instruction pointer (or 0 if rethook lookup failed).
+ */
+static unsigned long dwarf_recover_ret_addr(struct unwind_state *state,
+					    unsigned long addr,
+					    unsigned long *addr_p)
+{
+	unsigned long ret;
+
+	ret = unwind_recover_ret_addr(state, addr, addr_p);
+	return ftrace_graph_ret_addr(state->task, &state->graph_idx,
+				     ret, addr_p);
+}
+
+/**
+ * unwind_next_frame() - Advance @state to the next outer x86-64 kernel frame
+ * @state: Current x86 unwind state.
+ *
+ * Evaluates Minimal DWARF CFI for @state->ip, handles top-of-stack task
+ * pt_regs, arch_rethook_trampoline entry, %rsp-verified ENCODE_FRAME_POINTER
+ * entry/exception pt_regs transitions, and call_on_stack() IRQ stack pivots.
+ *
+ * Return: true if a valid outer frame was unwound, or false when the bottom of
+ * the stack is reached or an error terminates the walk.
+ */
+bool unwind_next_frame(struct unwind_state *state)
+{
+	enum stack_type prev_type = state->stack_info.type;
+	unsigned long prev_sp = state->sp;
+	struct dwarf_cfi_row row;
+	unsigned long lookup_ip, cfa, ip_p;
+	struct pt_regs *regs;
+	int err;
+
+	if (unwind_done(state))
+		return false;
+
+	/* Keep module .eh_frame tables alive across lookup and evaluation */
+	guard(rcu)();
+
+	if (state->regs && user_mode(state->regs))
+		goto the_end;
+
+	/*
+	 * Check if we have reached the top-of-task-stack pt_regs boundary
+	 * (syscall entry, newly forked thread, kthread, or idle thread).
+	 */
+	regs = task_pt_regs(state->task);
+	if ((void *)state->ip == ret_from_fork_asm ||
+	    state->sp == (unsigned long)regs) {
+		if (!user_mode(regs))
+			goto the_end;
+
+		if (!deref_stack_regs(state, (unsigned long)regs,
+				      &state->ip, &state->sp, &state->bp))
+			goto err;
+		state->regs = regs;
+		state->prev_regs = NULL;
+		state->full_regs = true;
+		state->signal = true;
+		return true;
+	}
+
+	if (!state->ip && !state->signal)
+		goto err;
+
+	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;
+#ifdef CONFIG_FUNCTION_GRAPH_TRACER
+			if (state->ip == (unsigned long)return_to_handler)
+				goto err;
+#endif
+			state->regs = NULL;
+			state->prev_regs = NULL;
+			state->full_regs = false;
+			state->signal = true;
+			return true;
+		}
+
+		/*
+		 * Entry / interrupt / exception .S stubs without .eh_frame
+		 * encode a pointer to struct pt_regs in %rbp via
+		 * ENCODE_FRAME_POINTER (setting bit 0).  Verify that %rsp has
+		 * actually reached that pt_regs frame (or the 8-byte return
+		 * slot immediately below it in error_entry / paranoid_entry)
+		 * so a stale outer encoded %rbp never skips intermediate frames.
+		 */
+		regs = decode_frame_pointer(state->bp);
+		if (regs &&
+		    (state->sp == (unsigned long)regs ||
+		     (in_entry_text(state->ip) &&
+		      state->sp == (unsigned long)regs - sizeof(long)))) {
+			unsigned long orig_ip;
+
+			if (!deref_stack_regs(state, (unsigned long)regs,
+					      &orig_ip, &state->sp, &state->bp))
+				goto err;
+			state->ip = dwarf_recover_ret_addr(state, orig_ip,
+					(unsigned long *)(state->sp - sizeof(long)));
+			if (is_rethook_trampoline(orig_ip) &&
+			    (!state->ip || is_rethook_trampoline(state->ip)))
+				goto err;
+#ifdef CONFIG_FUNCTION_GRAPH_TRACER
+			if (is_rethook_trampoline(orig_ip) &&
+			    state->ip == (unsigned long)return_to_handler)
+				goto err;
+#endif
+			state->regs = regs;
+			state->prev_regs = NULL;
+			state->full_regs = true;
+			state->signal = true;
+			goto check_progress;
+		}
+
+		/*
+		 * Unencoded entry assembly (pre-ENCODE_FRAME_POINTER or
+		 * post-POP_REGS) or an unaligned/encoded %rbp cannot be
+		 * unwound via a frame-pointer guess.
+		 */
+		if (in_entry_text(state->ip) || (state->bp & (sizeof(long) - 1)))
+			goto err;
+
+		/* Fallback to frame-pointer guess and mark unreliable */
+		row = bpf_fp_row;
+		state->error = true;
+	}
+
+	if (row.ra_rule == DWARF_CFI_RULE_UNDEFINED)
+		goto the_end;
+
+	if (row.ra_rule != DWARF_CFI_RULE_OFFSET)
+		goto err;
+
+	switch (row.cfa_base) {
+	case DWARF_CFI_BASE_SP: {
+		unsigned long sp_base = state->sp;
+
+		/*
+		 * call_on_stack() stores the pre-switch task-stack %rsp at the
+		 * top slot of the per-CPU IRQ stack (info.end - 1) and pivots
+		 * %rsp there before invoking the IRQ/softirq handler.
+		 */
+		if (state->stack_info.type == STACK_TYPE_IRQ &&
+		    state->sp == (unsigned long)(state->stack_info.end - 1)) {
+			if (!deref_stack_reg(state, state->sp, &sp_base))
+				goto err;
+		}
+		cfa = sp_base + row.cfa_off;
+		break;
+	}
+	case DWARF_CFI_BASE_FP:
+		cfa = state->bp + row.cfa_off;
+		break;
+	case DWARF_CFI_BASE_FP_INDIRECT:
+		if (!deref_stack_reg(state, state->bp + row.cfa_off, &cfa))
+			goto err;
+		break;
+	case DWARF_CFI_BASE_REG:
+		if (!get_scratch_reg(state, row.cfa_reg, &cfa))
+			goto err;
+		cfa += row.cfa_off;
+		break;
+	default:
+		goto err;
+	}
+
+	ip_p = cfa + row.ra_off;
+	if (!deref_stack_reg(state, ip_p, &state->ip))
+		goto err;
+
+	state->ip = dwarf_recover_ret_addr(state, state->ip,
+					   (unsigned long *)ip_p);
+	if (!state->ip || is_rethook_trampoline(state->ip))
+		goto err;
+#ifdef CONFIG_FUNCTION_GRAPH_TRACER
+	if (state->ip == (unsigned long)return_to_handler)
+		goto err;
+#endif
+
+	if (row.fp_rule == DWARF_CFI_RULE_OFFSET) {
+		if (!deref_stack_reg(state, cfa + row.fp_off, &state->bp))
+			goto err;
+	} else if (row.fp_rule == DWARF_CFI_RULE_FP_OFFSET) {
+		if (!deref_stack_reg(state, state->bp + row.fp_off, &state->bp))
+			goto err;
+	}
+
+	state->sp = cfa;
+	state->regs = NULL;
+	state->prev_regs = NULL;
+	state->full_regs = false;
+	state->signal = row.signal;
+
+check_progress:
+	if (state->stack_info.type == prev_type &&
+	    on_stack(&state->stack_info, (void *)state->sp, sizeof(long)) &&
+	    state->sp <= prev_sp)
+		goto err;
+
+	return true;
+
+err:
+	state->error = true;
+the_end:
+	state->stack_info.type = STACK_TYPE_UNKNOWN;
+	return false;
+}
+EXPORT_SYMBOL_GPL(unwind_next_frame);
+
+/**
+ * __unwind_start() - Initialize an x86-64 Minimal DWARF CFI kernel stack walk
+ * @state: Unwind state structure to initialize.
+ * @task: Task whose kernel stack is being unwound.
+ * @regs: Optional starting register state (e.g. from an interrupt/exception).
+ * @first_frame: Stack pointer threshold to skip frames below the caller.
+ */
+void __unwind_start(struct unwind_state *state, struct task_struct *task,
+		    struct pt_regs *regs, unsigned long *first_frame)
+{
+	memset(state, 0, sizeof(*state));
+	state->task = task;
+
+	if (!dwarf_cfi_ready)
+		goto err;
+
+	if (task_on_another_cpu(task))
+		goto err;
+
+	if (regs) {
+		if (user_mode(regs))
+			goto the_end;
+
+		state->ip = regs->ip;
+		state->sp = regs->sp;
+		state->bp = regs->bp;
+		state->regs = regs;
+		state->full_regs = true;
+		state->signal = true;
+	} else if (task == current) {
+		asm volatile("lea (%%rip), %0\n\t"
+			     "mov %%rsp, %1\n\t"
+			     "mov %%rbp, %2\n\t"
+			     : "=r" (state->ip), "=r" (state->sp),
+			       "=r" (state->bp));
+		state->signal = true;
+	} else {
+		struct inactive_task_frame *frame = (void *)task->thread.sp;
+
+		state->sp = task->thread.sp + sizeof(*frame);
+		state->bp = READ_ONCE_NOCHECK(frame->bp);
+		state->ip = READ_ONCE_NOCHECK(frame->ret_addr);
+		state->signal = (void *)state->ip == ret_from_fork_asm;
+	}
+
+	if (get_stack_info((unsigned long *)state->sp, state->task,
+			   &state->stack_info, &state->stack_mask)) {
+		void *next_page = (void *)PAGE_ALIGN((unsigned long)state->sp);
+
+		state->error = true;
+		if (get_stack_info(next_page, state->task, &state->stack_info,
+				   &state->stack_mask))
+			return;
+	}
+
+	if (regs) {
+		unwind_next_frame(state);
+		return;
+	}
+
+	while (!unwind_done(state) &&
+	       (!on_stack(&state->stack_info, first_frame, sizeof(long)) ||
+		state->sp <= (unsigned long)first_frame))
+		unwind_next_frame(state);
+
+	return;
+
+err:
+	state->error = true;
+the_end:
+	state->stack_info.type = STACK_TYPE_UNKNOWN;
+}
+EXPORT_SYMBOL_GPL(__unwind_start);
diff --git a/arch/x86/kernel/vmlinux.lds.S b/arch/x86/kernel/vmlinux.lds.S
index 2438b89a4620..20f0fa33ea9c 100644
--- a/arch/x86/kernel/vmlinux.lds.S
+++ b/arch/x86/kernel/vmlinux.lds.S
@@ -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>
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 4c3e09d98131..84217ce6a283 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -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;
 
diff --git a/arch/x86/purgatory/Makefile b/arch/x86/purgatory/Makefile
index fad91ea28fe7..ef3ae80f5c06 100644
--- a/arch/x86/purgatory/Makefile
+++ b/arch/x86/purgatory/Makefile
@@ -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
diff --git a/drivers/firmware/efi/libstub/Makefile b/drivers/firmware/efi/libstub/Makefile
index bbab12b8eb4b..d62dabfdc1c3 100644
--- a/drivers/firmware/efi/libstub/Makefile
+++ b/drivers/firmware/efi/libstub/Makefile
@@ -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)
 
diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h
index 3eb732942d69..1bde7a2a19d0 100644
--- a/include/asm-generic/vmlinux.lds.h
+++ b/include/asm-generic/vmlinux.lds.h
@@ -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 = .;
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 06/11] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (4 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 05/11] x86/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 07/11] arm64/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
                   ` (4 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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

diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig
index ee0f263f477d..918d7e278f7d 100644
--- a/arch/arm64/Kconfig
+++ b/arch/arm64/Kconfig
@@ -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
diff --git a/arch/arm64/include/asm/unwind_user.h b/arch/arm64/include/asm/unwind_user.h
new file mode 100644
index 000000000000..38d0641ae554
--- /dev/null
+++ b/arch/arm64/include/asm/unwind_user.h
@@ -0,0 +1,126 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef __ASM_ARM64_UNWIND_USER_H
+#define __ASM_ARM64_UNWIND_USER_H
+
+#ifdef CONFIG_UNWIND_USER
+
+#include <linux/sched.h>
+#include <linux/sched/task_stack.h>
+#include <linux/unwind_dwarf_cfi.h>
+#include <linux/unwind_user_types.h>
+#include <asm/compiler.h>
+#include <asm/ptrace.h>
+
+/**
+ * unwind_user_word_size() - Return the user-space word size in bytes on arm64
+ * @regs: User-mode register state.
+ *
+ * Return: 4 for AArch32 compat user mode, or 8 for AArch64 user mode.
+ */
+static inline int unwind_user_word_size(struct pt_regs *regs)
+{
+	return compat_user_mode(regs) ? 4 : 8;
+}
+
+/**
+ * unwind_user_frame_pointer() - Fetch the user frame pointer from @regs
+ * @regs: User-mode register state.
+ *
+ * Return: r11 (compat_fp) for AArch32 compat tasks, or x29 for AArch64 tasks.
+ */
+static inline unsigned long unwind_user_frame_pointer(struct pt_regs *regs)
+{
+	return compat_user_mode(regs) ? regs->compat_fp : frame_pointer(regs);
+}
+#define unwind_user_frame_pointer unwind_user_frame_pointer
+
+/**
+ * unwind_user_link_register() - Fetch the user link register from @regs
+ * @regs: User-mode register state.
+ * @ra: Output link register value (r14 for AArch32 compat, x30 for AArch64).
+ *
+ * Return: Always true on arm64 because a link register is architecturally
+ * present in both AArch64 and AArch32 execution states.
+ */
+static inline bool unwind_user_link_register(struct pt_regs *regs,
+					     unsigned long *ra)
+{
+	if (compat_user_mode(regs))
+		*ra = regs->compat_lr;
+	else
+		*ra = procedure_link_pointer(regs);
+	return true;
+}
+#define unwind_user_link_register unwind_user_link_register
+
+/**
+ * unwind_user_strip_pac() - Strip user pointer authentication bits on arm64
+ * @ip: Recovered user return address.
+ * @ra_signed: Whether CFI marked the return address as PAC-signed (unused;
+ *             arm64 strips user instruction PAC bits unconditionally via the
+ *             task's configured pointer authentication mask).
+ *
+ * Return: @ip unchanged for AArch32 compat tasks, or @ip with user instruction
+ * PAC bits stripped for AArch64 tasks.
+ */
+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
+
+/**
+ * unwind_user_cfi_arch() - Populate AArch64/AArch32 DWARF register numbers
+ * @ws: User word size in bytes (8 for AArch64, 4 for AArch32 compat).
+ * @arch: Output DWARF CFI architecture descriptor.
+ *
+ * Return: true if @ws is 4 or 8, false otherwise.
+ */
+static inline bool unwind_user_cfi_arch(unsigned int ws,
+					struct dwarf_cfi_arch *arch)
+{
+	if (ws == 8) {
+		*arch = (struct dwarf_cfi_arch){
+			.ws	= 8,
+			.sp_reg	= 31,	/* sp */
+			.fp_reg	= 29,	/* x29 */
+			.ra_reg	= 30,	/* x30 (lr) */
+		};
+		return true;
+	}
+	if (ws == 4) {
+		*arch = (struct dwarf_cfi_arch){
+			.ws	= 4,
+			.sp_reg	= 13,	/* r13 (sp) */
+			.fp_reg	= 11,	/* r11 (fp) */
+			.ra_reg	= 14,	/* r14 (lr) */
+		};
+		return true;
+	}
+	return false;
+}
+
+bool unwind_user_sigreturn(struct unwind_user_state *state);
+#define unwind_user_sigreturn unwind_user_sigreturn
+
+#endif /* CONFIG_UNWIND_USER */
+
+#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 */
+
+#endif /* __ASM_ARM64_UNWIND_USER_H */
diff --git a/arch/arm64/kernel/signal.c b/arch/arm64/kernel/signal.c
index 80398ac83c3b..41dfbfcc1d2e 100644
--- a/arch/arm64/kernel/signal.c
+++ b/arch/arm64/kernel/signal.c
@@ -21,6 +21,7 @@
 #include <linux/rseq.h>
 #include <linux/syscalls.h>
 #include <linux/pkeys.h>
+#include <linux/unwind_user.h>
 
 #include <asm/daifflags.h>
 #include <asm/debug-monitors.h>
@@ -1705,6 +1706,59 @@ void __init minsigstksz_setup(void)
 		16; /* max alignment padding */
 }
 
+#ifdef CONFIG_UNWIND_USER
+/**
+ * unwind_user_sigreturn() - Unwind an AArch64 vDSO rt_sigreturn signal frame
+ * @state: Current user unwind state.
+ *
+ * __kernel_rt_sigreturn intentionally omits .eh_frame directives in the arm64
+ * vDSO so libgcc uses its sigcontext fallback path, and the synthetic
+ * user->next_frame FP record skips the interrupted PC. Recover the interrupted
+ * PC, SP, x29, and x30 directly from &rt_sigframe.uc.uc_mcontext so leaf
+ * functions, -fomit-frame-pointer code, and alternate signal stacks unwind
+ * accurately.
+ *
+ * Return: true if @state was at __kernel_rt_sigreturn and advanced to the
+ * interrupted user context, false otherwise.
+ */
+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 &&
+	    !(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;
+
+	sp_pc[1] = ptrauth_strip_user_insn_pac(sp_pc[1]);
+	if ((sp_pc[0] & 7ULL) || !sp_pc[1])
+		return false;
+
+	state->fp = fp_lr[0];
+	state->ra = ptrauth_strip_user_insn_pac(fp_lr[1]);
+	state->sp = sp_pc[0];
+	state->ip = sp_pc[1];
+	state->ra_valid = true;
+	state->signal = true;
+	state->topmost = false;
+	return true;
+}
+#endif
+
 /*
  * Compile-time assertions for siginfo_t offsets. Check NSIG* as well, as
  * changes likely come with new fields that should be added below.
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 07/11] arm64/unwind: Add Minimal DWARF CFI kernel unwinder
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (5 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 06/11] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 08/11] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
                   ` (3 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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(-)

diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig
index 918d7e278f7d..0c0b24d1ec4a 100644
--- a/arch/arm64/Kconfig
+++ b/arch/arm64/Kconfig
@@ -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
diff --git a/arch/arm64/Kconfig.debug b/arch/arm64/Kconfig.debug
index 265c4461031f..4f5c99a2fa96 100644
--- a/arch/arm64/Kconfig.debug
+++ b/arch/arm64/Kconfig.debug
@@ -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
diff --git a/arch/arm64/Makefile b/arch/arm64/Makefile
index ed28f94be428..7ec8e96b2032 100644
--- a/arch/arm64/Makefile
+++ b/arch/arm64/Makefile
@@ -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));	\
diff --git a/arch/arm64/include/asm/ftrace.h b/arch/arm64/include/asm/ftrace.h
index 1621c84f44b3..f7558cbb148b 100644
--- a/arch/arm64/include/asm/ftrace.h
+++ b/arch/arm64/include/asm/ftrace.h
@@ -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);
diff --git a/arch/arm64/include/asm/module.h b/arch/arm64/include/asm/module.h
index fb9b88eebeb1..71f423be20c2 100644
--- a/arch/arm64/include/asm/module.h
+++ b/arch/arm64/include/asm/module.h
@@ -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);
diff --git a/arch/arm64/include/asm/module.lds.h b/arch/arm64/include/asm/module.lds.h
index 603f92a8a73e..d754f3743487 100644
--- a/arch/arm64/include/asm/module.lds.h
+++ b/arch/arm64/include/asm/module.lds.h
@@ -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.
diff --git a/arch/arm64/include/asm/perf_event.h b/arch/arm64/include/asm/perf_event.h
index ee45b4e77347..4a7dbb7ce41c 100644
--- a/arch/arm64/include/asm/perf_event.h
+++ b/arch/arm64/include/asm/perf_event.h
@@ -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
diff --git a/arch/arm64/kernel/Makefile b/arch/arm64/kernel/Makefile
index fc5d1a0c38b3..d727fda788a3 100644
--- a/arch/arm64/kernel/Makefile
+++ b/arch/arm64/kernel/Makefile
@@ -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
diff --git a/arch/arm64/kernel/efi-rt-wrapper.S b/arch/arm64/kernel/efi-rt-wrapper.S
index e8ae803662cf..4ddfa5362e4f 100644
--- a/arch/arm64/kernel/efi-rt-wrapper.S
+++ b/arch/arm64/kernel/efi-rt-wrapper.S
@@ -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)
diff --git a/arch/arm64/kernel/entry-ftrace.S b/arch/arm64/kernel/entry-ftrace.S
index 025140caafe7..d112a29fd1a7 100644
--- a/arch/arm64/kernel/entry-ftrace.S
+++ b/arch/arm64/kernel/entry-ftrace.S
@@ -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 */
diff --git a/arch/arm64/kernel/entry.S b/arch/arm64/kernel/entry.S
index 8d17f61d1b5b..15a591996307 100644
--- a/arch/arm64/kernel/entry.S
+++ b/arch/arm64/kernel/entry.S
@@ -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)
 
diff --git a/arch/arm64/kernel/ftrace.c b/arch/arm64/kernel/ftrace.c
index e1a3c0b3a051..5f9458a6b477 100644
--- a/arch/arm64/kernel/ftrace.c
+++ b/arch/arm64/kernel/ftrace.c
@@ -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
 /*
diff --git a/arch/arm64/kernel/module.c b/arch/arm64/kernel/module.c
index 24adb581af0e..88d07ecf6e64 100644
--- a/arch/arm64/kernel/module.c
+++ b/arch/arm64/kernel/module.c
@@ -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);
 }
diff --git a/arch/arm64/kernel/probes/kprobes.c b/arch/arm64/kernel/probes/kprobes.c
index 4e0efad5caf2..eae1f2326efa 100644
--- a/arch/arm64/kernel/probes/kprobes.c
+++ b/arch/arm64/kernel/probes/kprobes.c
@@ -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;
diff --git a/arch/arm64/kernel/stacktrace.c b/arch/arm64/kernel/stacktrace.c
index 3ebcf8c53fb0..9ce0e3f6cabe 100644
--- a/arch/arm64/kernel/stacktrace.c
+++ b/arch/arm64/kernel/stacktrace.c
@@ -10,16 +10,221 @@
 #include <linux/filter.h>
 #include <linux/ftrace.h>
 #include <linux/kprobes.h>
+#include <linux/module.h>
+#include <linux/perf_event.h>
+#include <linux/rcupdate.h>
 #include <linux/sched.h>
 #include <linux/sched/debug.h>
 #include <linux/sched/task_stack.h>
 #include <linux/stacktrace.h>
+#include <linux/unwind_dwarf_cfi.h>
 
 #include <asm/efi.h>
 #include <asm/irq.h>
+#include <asm/module.h>
+#include <asm/sections.h>
 #include <asm/stack_pointer.h>
 #include <asm/stacktrace.h>
 
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+static const struct dwarf_cfi_arch arm64_cfi_arch = {
+	.ws	= 8,
+	.sp_reg	= 31,	/* sp */
+	.fp_reg	= 29,	/* x29 */
+	.ra_reg	= 30,	/* x30 (lr) */
+};
+
+#ifdef CONFIG_MODULES
+/**
+ * arm64_unwind_module_init() - Build Minimal DWARF CFI index for a module
+ * @mod: Module being loaded.
+ * @eh_frame: Pointer to the module's SHF_ALLOC .eh_frame section.
+ * @eh_frame_size: Size in bytes of @eh_frame.
+ *
+ * Scans and sorts the module's FDEs and publishes the index to
+ * @mod->arch.dwarf_cfi_index for RCU-protected lockless unwinding.
+ */
+void arm64_unwind_module_init(struct module *mod, void *eh_frame,
+			      size_t eh_frame_size)
+{
+	struct mod_dwarf_cfi_index *idx;
+
+	idx = dwarf_cfi_mod_alloc(eh_frame, eh_frame_size, &arm64_cfi_arch);
+	if (idx)
+		rcu_assign_pointer(mod->arch.dwarf_cfi_index, idx);
+}
+
+/**
+ * arm64_unwind_module_cleanup() - Unpublish and RCU-free module DWARF CFI index
+ * @mod: Module being unloaded or cleaned up after a failed load.
+ */
+void arm64_unwind_module_cleanup(struct module *mod)
+{
+	struct mod_dwarf_cfi_index *idx;
+
+	idx = rcu_replace_pointer(mod->arch.dwarf_cfi_index, /*ptr=*/NULL,
+				  /*c=*/true);
+	dwarf_cfi_mod_free_rcu(idx);
+}
+
+/**
+ * arm64_dwarf_cfi_module_find() - Look up Minimal DWARF CFI in loadable modules
+ * @pc: Kernel instruction pointer to evaluate.
+ * @row: Output evaluated Minimal DWARF CFI row.
+ *
+ * Uses rcu_read_lock_sched_notrace() and rcu_dereference_raw() so lookups are
+ * safe inside noinstr stack walks and NMI contexts.
+ *
+ * Return: 0 on success, -ENOENT if @pc is not in a module FDE, or a negative
+ * errno on invalid FDE bytecode.
+ */
+static __always_inline int
+arm64_dwarf_cfi_module_find(unsigned long pc, struct dwarf_cfi_row *row)
+{
+	struct mod_dwarf_cfi_index *idx;
+	struct module *mod;
+	int ret;
+
+	rcu_read_lock_sched_notrace();
+	mod = __module_address(pc);
+	if (!mod) {
+		rcu_read_unlock_sched_notrace();
+		return -ENOENT;
+	}
+	idx = rcu_dereference_raw(mod->arch.dwarf_cfi_index);
+	ret = dwarf_cfi_mod_eval(idx, pc, &arm64_cfi_arch, row);
+	rcu_read_unlock_sched_notrace();
+	return ret;
+}
+#else
+static __always_inline int
+arm64_dwarf_cfi_module_find(unsigned long pc, struct dwarf_cfi_row *row)
+{
+	return -ENOENT;
+}
+#endif /* CONFIG_MODULES */
+
+/**
+ * arm64_dwarf_cfi_find() - Evaluate Minimal DWARF CFI for core or module @pc
+ * @pc: Kernel instruction pointer to look up.
+ * @row: Output evaluated Minimal DWARF CFI row.
+ *
+ * Return: 0 on success, -ENOENT if no FDE covers @pc, or a negative errno on
+ * malformed CFI data.
+ */
+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;
+	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);
+}
+
+/**
+ * arm64_unwind_perf_caller_regs() - Populate caller pt_regs for perf events
+ * @regs: Output pt_regs initialized for the caller frame.
+ * @pc: Current instruction pointer inside the function invoking perf_fetch_caller_regs.
+ * @caller_ip: Target caller instruction pointer to record in @regs->pc.
+ * @sp: Current stack pointer corresponding to @pc.
+ * @fp: Current x29 value corresponding to @pc.
+ *
+ * Under -fomit-frame-pointer, __builtin_frame_address(0) does not yield a
+ * valid frame chain; step one frame via Minimal DWARF CFI at @pc so @regs->sp
+ * and @regs->regs[29] match the caller's stack state for subsequent unwinding.
+ */
+void arm64_unwind_perf_caller_regs(struct pt_regs *regs, unsigned long pc,
+				   unsigned long caller_ip, unsigned long sp,
+				   unsigned long fp)
+{
+	struct stack_info stacks[] = {
+		stackinfo_get_task(current),
+		!preemptible() ? stackinfo_get_irq() : stackinfo_get_unknown(),
+		!preemptible() ? stackinfo_get_overflow() : stackinfo_get_unknown(),
+#if defined(CONFIG_ARM_SDE_INTERFACE)
+		in_nmi() ? stackinfo_get_sdei_normal() : stackinfo_get_unknown(),
+		in_nmi() ? stackinfo_get_sdei_critical() : stackinfo_get_unknown(),
+#endif
+#ifdef CONFIG_EFI
+		current_in_efi() ? stackinfo_get_efi() : stackinfo_get_unknown(),
+#endif
+	};
+	struct unwind_state common = {
+		.stacks = stacks,
+		.nr_stacks = ARRAY_SIZE(stacks),
+	};
+	struct dwarf_cfi_row row;
+
+	unwind_init_common(&common);
+
+	regs->pc = caller_ip;
+	regs->regs[29] = fp;
+	regs->regs[30] = 0;
+	regs->sp = sp;
+	regs->pstate = PSR_MODE_EL1h;
+
+	if (arm64_dwarf_cfi_find(pc, &row))
+		return;
+
+	switch (row.cfa_base) {
+	case DWARF_CFI_BASE_SP:
+		sp += row.cfa_off;
+		break;
+	case DWARF_CFI_BASE_FP:
+		sp = fp + row.cfa_off;
+		break;
+	case DWARF_CFI_BASE_FP_INDIRECT: {
+		unsigned long cfa_addr = fp + row.cfa_off;
+
+		if ((cfa_addr & 0x7) ||
+		    !unwind_find_stack(&common, cfa_addr, sizeof(long)))
+			return;
+		sp = READ_ONCE(*(unsigned long *)cfa_addr);
+		break;
+	}
+	default:
+		return;
+	}
+
+	if ((sp & 0x7) || !unwind_find_stack(&common, sp, /*size=*/0))
+		return;
+
+	if (row.fp_rule == DWARF_CFI_RULE_OFFSET) {
+		unsigned long fp_addr = sp + row.fp_off;
+
+		if ((fp_addr & 0x7) ||
+		    !unwind_find_stack(&common, fp_addr, sizeof(long)))
+			return;
+		fp = READ_ONCE(*(unsigned long *)fp_addr);
+	} else if (row.fp_rule == DWARF_CFI_RULE_FP_OFFSET) {
+		unsigned long fp_addr = fp + row.fp_off;
+
+		if ((fp_addr & 0x7) ||
+		    !unwind_find_stack(&common, fp_addr, sizeof(long)))
+			return;
+		fp = READ_ONCE(*(unsigned long *)fp_addr);
+	}
+
+	regs->sp = sp;
+	regs->regs[29] = fp;
+}
+EXPORT_SYMBOL_GPL(arm64_unwind_perf_caller_regs);
+#endif /* CONFIG_UNWINDER_DWARF_CFI */
+
+/**
+ * enum kunwind_source - Origin of the current frame's PC during kernel unwind
+ * @KUNWIND_SOURCE_UNKNOWN: Uninitialized or invalid unwind state.
+ * @KUNWIND_SOURCE_FRAME: Unwound from a callee stack frame or return address.
+ * @KUNWIND_SOURCE_CALLER: Initialized from the immediate caller of the walker.
+ * @KUNWIND_SOURCE_TASK: Initialized from a blocked task's saved thread_struct.
+ * @KUNWIND_SOURCE_REGS_PC: Exact PC from an exception/interrupt &struct pt_regs.
+ */
 enum kunwind_source {
 	KUNWIND_SOURCE_UNKNOWN,
 	KUNWIND_SOURCE_FRAME,
@@ -36,37 +241,49 @@ union unwind_flags {
 	};
 };
 
-/*
- * Kernel unwind state
- *
- * @common:      Common unwind state.
- * @task:        The task being unwound.
- * @graph_idx:   Used by ftrace_graph_ret_addr() for optimized stack unwinding.
- * @kr_cur:      When KRETPROBES is selected, holds the kretprobe instance
- *               associated with the most recently encountered replacement lr
- *               value.
+/**
+ * struct kunwind_state - ARM64 kernel stack unwind iteration state
+ * @common: Common stack-bounds, PC, and FP unwind state.
+ * @task: The task being unwound.
+ * @sp: Current frame's stack pointer (equal to the callee's CFA after stepping).
+ * @lr: Saved link register (x30) when @lr_valid is true.
+ * @graph_idx: Shadow-stack cursor for ftrace_graph_ret_addr().
+ * @kr_cur: Cursor into @task->kretprobe_instances for kretprobe_find_ret_addr().
+ * @source: How @common.pc was obtained (&enum kunwind_source).
+ * @flags: Return-address recovery annotations (fgraph / kretprobe) for printing.
+ * @lr_valid: True if @lr holds a live return address for leaf/entry frames.
+ * @unreliable: True if an unannotated fallback (LR guess or non-CFI frame
+ *              record) was used, disqualifying reliable stacktraces.
  */
 struct kunwind_state {
 	struct unwind_state common;
 	struct task_struct *task;
+	unsigned long sp;
+	unsigned long lr;
 	int graph_idx;
 #ifdef CONFIG_KRETPROBES
 	struct llist_node *kr_cur;
 #endif
 	enum kunwind_source source;
 	union unwind_flags flags;
-	struct pt_regs *regs;
+	bool lr_valid;
+	bool unreliable;
 };
 
+static __always_inline int kunwind_next(struct kunwind_state *state);
+
 static __always_inline void
 kunwind_init(struct kunwind_state *state,
 	     struct task_struct *task)
 {
 	unwind_init_common(&state->common);
 	state->task = task;
+	state->sp = 0;
+	state->lr = 0;
+	state->lr_valid = false;
+	state->unreliable = false;
 	state->source = KUNWIND_SOURCE_UNKNOWN;
 	state->flags.all = 0;
-	state->regs = NULL;
 }
 
 /*
@@ -82,9 +299,11 @@ kunwind_init_from_regs(struct kunwind_state *state,
 {
 	kunwind_init(state, current);
 
-	state->regs = regs;
 	state->common.fp = regs->regs[29];
 	state->common.pc = regs->pc;
+	state->sp = regs->sp;
+	state->lr = regs->regs[30];
+	state->lr_valid = !!state->lr;
 	state->source = KUNWIND_SOURCE_REGS_PC;
 }
 
@@ -101,9 +320,29 @@ kunwind_init_from_caller(struct kunwind_state *state)
 {
 	kunwind_init(state, current);
 
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+	{
+		unsigned long pc, fp;
+
+		asm volatile("1: adr %0, 1b\n\t"
+			     "mov %1, x29"
+			     : "=r"(pc), "=r"(fp));
+		state->common.pc = pc;
+		state->common.fp = fp;
+		state->sp = current_stack_pointer;
+		state->lr = (unsigned long)__builtin_return_address(0);
+		state->lr_valid = true;
+		state->source = KUNWIND_SOURCE_REGS_PC;
+		if (!kunwind_next(state))
+			state->source = KUNWIND_SOURCE_CALLER;
+		else
+			state->source = KUNWIND_SOURCE_UNKNOWN;
+	}
+#else
 	state->common.fp = (unsigned long)__builtin_frame_address(1);
 	state->common.pc = (unsigned long)__builtin_return_address(0);
 	state->source = KUNWIND_SOURCE_CALLER;
+#endif
 }
 
 /*
@@ -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
+ * 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;
+
 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
 	if (state->task->ret_stack &&
 	    (state->common.pc == (unsigned long)return_to_handler)) {
 		unsigned long orig_pc;
+
 		orig_pc = ftrace_graph_ret_addr(state->task, &state->graph_idx,
-						state->common.pc,
-						(void *)state->common.fp);
+						state->common.pc, frame_key);
 		if (state->common.pc == orig_pc) {
 			WARN_ON_ONCE(state->task == current);
 			return -EINVAL;
@@ -149,8 +404,8 @@ kunwind_recover_return_address(struct kunwind_state *state)
 #ifdef CONFIG_KRETPROBES
 	if (is_kretprobe_trampoline(state->common.pc)) {
 		unsigned long orig_pc;
-		orig_pc = kretprobe_find_ret_addr(state->task,
-						  (void *)state->common.fp,
+
+		orig_pc = kretprobe_find_ret_addr(state->task, frame_key,
 						  &state->kr_cur);
 		if (!orig_pc)
 			return -EINVAL;
@@ -159,6 +414,22 @@ kunwind_recover_return_address(struct kunwind_state *state)
 	}
 #endif /* CONFIG_KRETPROBES */
 
+#ifdef CONFIG_FUNCTION_GRAPH_TRACER
+	if (state->task->ret_stack &&
+	    (state->common.pc == (unsigned long)return_to_handler)) {
+		unsigned long orig_pc;
+
+		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 */
+
 	return 0;
 }
 
@@ -178,10 +449,11 @@ int kunwind_next_regs_pc(struct kunwind_state *state)
 	unwind_consume_stack(&state->common, info, (unsigned long)regs,
 			     sizeof(*regs));
 
-	state->regs = regs;
 	state->common.pc = regs->pc;
 	state->common.fp = regs->regs[29];
-	state->regs = NULL;
+	state->sp = regs->sp;
+	state->lr = regs->regs[30];
+	state->lr_valid = !!state->lr;
 	state->source = KUNWIND_SOURCE_REGS_PC;
 	return 0;
 }
@@ -201,11 +473,19 @@ kunwind_next_frame_record_meta(struct kunwind_state *state)
 	meta = (struct frame_record_meta *)fp;
 	switch (READ_ONCE(meta->type)) {
 	case FRAME_META_TYPE_FINAL:
-		if (meta == &task_pt_regs(tsk)->stackframe)
+		if (meta == &task_pt_regs(tsk)->stackframe) {
+			if (IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI) &&
+			    state->sp != (unsigned long)task_pt_regs(tsk))
+				return -EINVAL;
 			return -ENOENT;
+		}
 		WARN_ON_ONCE(tsk == current);
 		return -EINVAL;
 	case FRAME_META_TYPE_PT_REGS:
+		if (IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI) &&
+		    state->sp != (unsigned long)container_of(meta, struct pt_regs,
+							     stackframe))
+			return -EINVAL;
 		return kunwind_next_regs_pc(state);
 	default:
 		WARN_ON_ONCE(tsk == current);
@@ -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
+ * @state: Current ARM64 kernel unwind state.
+ *
+ * Evaluates the Minimal DWARF CFI table at @state->common.pc (or pc - 4 for
+ * call return addresses), validates stack bounds and monotonic stack
+ * consumption across task/IRQ/overflow/SDEI/EFI stacks, and handles ftrace
+ * trampolines, SP-verified exception frame_record_meta boundaries, and
+ * frame-pointer fallbacks for JITed BPF code.
+ *
+ * Return: 0 on success, -ENOENT at the final user/kthread boundary or an
+ * explicit DW_CFA_undefined root frame, or -EINVAL on invalid unwind state.
+ */
+static __always_inline int kunwind_next_cfi(struct kunwind_state *state)
+{
+	unsigned long lookup_pc, cfa, ra_addr = 0, new_pc, new_fp = state->common.fp;
+	struct stack_info *info, *ra_info = NULL;
+	struct dwarf_cfi_row row;
+	int err;
+
+	lookup_pc = (state->source == KUNWIND_SOURCE_REGS_PC) ?
+		    state->common.pc : state->common.pc - 4;
+
+	err = arm64_dwarf_cfi_find(lookup_pc, &row);
+	if (err) {
+		unsigned long old_fp = state->common.fp;
+
+#ifdef CONFIG_DYNAMIC_FTRACE_WITH_ARGS
+		if (lookup_pc >= (unsigned long)ftrace_caller &&
+		    lookup_pc < (unsigned long)ftrace_caller_end &&
+		    old_fp == state->sp + sizeof(struct __arch_ftrace_regs)) {
+			struct __arch_ftrace_regs *fregs = (void *)state->sp;
+			size_t fsize = sizeof(*fregs) + 32;
+
+			info = unwind_find_stack(&state->common, state->sp, fsize);
+			if (!info || READ_ONCE(fregs->sp) != state->sp + fsize)
+				return -EINVAL;
+			unwind_consume_stack(&state->common, info, state->sp, fsize);
+			state->common.pc = READ_ONCE(fregs->pc);
+			state->common.fp = READ_ONCE(fregs->fp);
+			state->lr = ptrauth_strip_kernel_insn_pac(READ_ONCE(fregs->lr));
+			state->lr_valid = true;
+			state->sp += fsize;
+			state->source = KUNWIND_SOURCE_FRAME;
+			return 0;
+		}
+#endif
+		if (!(old_fp & 0x7) &&
+		    unwind_find_stack(&state->common, old_fp,
+				      sizeof(struct frame_record_meta))) {
+			struct frame_record_meta *m = (void *)old_fp;
+
+			if (state->sp == (unsigned long)container_of(m,
+					struct pt_regs, stackframe) &&
+			    !READ_ONCE(m->record.fp) &&
+			    !READ_ONCE(m->record.lr))
+				return kunwind_next_frame_record_meta(state);
+		}
+
+		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;
+		}
+
+		info = !(old_fp & 0x7) ?
+		       unwind_find_stack(&state->common, old_fp,
+					 sizeof(struct frame_record)) : NULL;
+		if (!info ||
+		    (stackinfo_on_stack(info, state->sp, /*size=*/0) &&
+		     old_fp < state->sp)) {
+			if (state->lr_valid) {
+				state->common.pc = state->lr;
+				state->lr_valid = false;
+				state->source = KUNWIND_SOURCE_FRAME;
+				state->unreliable = true;
+				return 0;
+			}
+			return -EINVAL;
+		}
+
+		err = kunwind_next_frame_record(state);
+		if (!err && state->source == KUNWIND_SOURCE_FRAME) {
+			state->sp = old_fp + sizeof(struct frame_record);
+			state->lr_valid = false;
+			state->unreliable = true;
+		} else if (err && state->lr_valid) {
+			state->common.pc = state->lr;
+			state->lr_valid = false;
+			state->source = KUNWIND_SOURCE_FRAME;
+			state->unreliable = true;
+			return 0;
+		}
+		return err;
+	}
+
+	if (row.ra_rule == DWARF_CFI_RULE_UNDEFINED)
+		return -ENOENT;
+
+	switch (row.cfa_base) {
+	case DWARF_CFI_BASE_SP:
+		cfa = state->sp + row.cfa_off;
+		break;
+	case DWARF_CFI_BASE_FP:
+		cfa = state->common.fp + row.cfa_off;
+		break;
+	case DWARF_CFI_BASE_FP_INDIRECT:
+		info = unwind_find_stack(&state->common,
+					 state->common.fp + row.cfa_off,
+					 sizeof(long));
+		if (!info)
+			return -EINVAL;
+		cfa = READ_ONCE(*(unsigned long *)(state->common.fp + row.cfa_off));
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	if (cfa & 0x7)
+		return -EINVAL;
+
+	if (row.ra_rule == DWARF_CFI_RULE_SAME) {
+		if (!state->lr_valid) {
+			/*
+			 * Non-struct_ops BPF trampolines push a synthetic
+			 * parent frame record above the inner traced-function
+			 * frame record; consume it at the pre-prologue entry.
+			 */
+			if (state->unreliable &&
+			    row.cfa_base == DWARF_CFI_BASE_SP &&
+			    row.cfa_off == 0 &&
+			    state->common.fp == state->sp) {
+				unsigned long old_fp = state->common.fp;
+
+				err = kunwind_next_frame_record(state);
+				if (!err && state->source == KUNWIND_SOURCE_FRAME)
+					state->sp = old_fp + sizeof(struct frame_record);
+				return err;
+			}
+			return -EINVAL;
+		}
+		if (cfa < state->sp)
+			return -EINVAL;
+		new_pc = state->lr;
+	} else if (row.ra_rule == DWARF_CFI_RULE_OFFSET) {
+		ra_addr = cfa + row.ra_off;
+
+		ra_info = unwind_find_stack(&state->common, ra_addr, sizeof(long));
+		if (!ra_info || !stackinfo_on_stack(ra_info, cfa, /*size=*/0))
+			return -EINVAL;
+		new_pc = READ_ONCE(*(unsigned long *)ra_addr);
+	} else {
+		return -EINVAL;
+	}
+
+	if (row.fp_rule == DWARF_CFI_RULE_OFFSET) {
+		unsigned long fp_addr = cfa + row.fp_off;
+
+		info = unwind_find_stack(&state->common, fp_addr, sizeof(long));
+		if (!info)
+			return -EINVAL;
+		new_fp = READ_ONCE(*(unsigned long *)fp_addr);
+	} else if (row.fp_rule == DWARF_CFI_RULE_FP_OFFSET) {
+		unsigned long fp_addr = state->common.fp + row.fp_off;
+
+		info = unwind_find_stack(&state->common, fp_addr, sizeof(long));
+		if (!info)
+			return -EINVAL;
+		new_fp = READ_ONCE(*(unsigned long *)fp_addr);
+	}
+
+	if (row.ra_rule == DWARF_CFI_RULE_OFFSET) {
+		if (stackinfo_on_stack(ra_info, state->sp, /*size=*/0)) {
+			if (cfa <= state->sp ||
+			    !stackinfo_on_stack(ra_info, state->sp,
+						cfa - state->sp))
+				return -EINVAL;
+			unwind_consume_stack(&state->common, ra_info, state->sp,
+					     cfa - state->sp);
+		} else {
+			if (row.cfa_base == DWARF_CFI_BASE_SP || cfa <= ra_addr)
+				return -EINVAL;
+			unwind_consume_stack(&state->common, ra_info, ra_addr,
+					     cfa - ra_addr);
+		}
+	} else if (cfa > state->sp) {
+		info = unwind_find_stack(&state->common, state->sp,
+					 cfa - state->sp);
+		if (!info)
+			return -EINVAL;
+		unwind_consume_stack(&state->common, info, state->sp,
+				     cfa - state->sp);
+	}
+
+	state->sp = cfa;
+	state->common.fp = new_fp;
+	state->common.pc = new_pc;
+	state->lr_valid = false;
+	state->source = KUNWIND_SOURCE_FRAME;
+	return 0;
+}
+#endif /* CONFIG_UNWINDER_DWARF_CFI */
+
 static __always_inline int
 kunwind_next(struct kunwind_state *state)
 {
@@ -263,7 +749,11 @@ kunwind_next(struct kunwind_state *state)
 	case KUNWIND_SOURCE_CALLER:
 	case KUNWIND_SOURCE_TASK:
 	case KUNWIND_SOURCE_REGS_PC:
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+		err = kunwind_next_cfi(state);
+#else
 		err = kunwind_next_frame_record(state);
+#endif
 		break;
 	default:
 		err = -EINVAL;
@@ -285,6 +775,9 @@ do_kunwind(struct kunwind_state *state, kunwind_consume_fn consume_state,
 {
 	int ret;
 
+	if (state->source == KUNWIND_SOURCE_UNKNOWN)
+		return -EINVAL;
+
 	ret = kunwind_recover_return_address(state);
 	if (ret)
 		return ret;
@@ -401,7 +894,7 @@ arch_reliable_kunwind_consume_entry(const struct kunwind_state *state, void *coo
 	 * All that matters is whether the *entire* unwind is reliable, so give
 	 * up as soon as we hit an exception boundary.
 	 */
-	if (state->source == KUNWIND_SOURCE_REGS_PC)
+	if (state->source == KUNWIND_SOURCE_REGS_PC || state->unreliable)
 		return false;
 
 	return arch_kunwind_consume_entry(state, cookie);
@@ -474,8 +967,8 @@ static bool dump_backtrace_entry(const struct kunwind_state *state, void *arg)
 	return true;
 }
 
-void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk,
-		    const char *loglvl)
+noinline void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk,
+			     const char *loglvl)
 {
 	pr_debug("%s(regs = %p tsk = %p)\n", __func__, regs, tsk);
 
diff --git a/arch/arm64/kernel/vmlinux.lds.S b/arch/arm64/kernel/vmlinux.lds.S
index c95243a8b24e..3d70eb12fa11 100644
--- a/arch/arm64/kernel/vmlinux.lds.S
+++ b/arch/arm64/kernel/vmlinux.lds.S
@@ -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
diff --git a/arch/arm64/kvm/hyp/nvhe/Makefile b/arch/arm64/kvm/hyp/nvhe/Makefile
index 56a7e2c05f73..bb9907b8ec7f 100644
--- a/arch/arm64/kvm/hyp/nvhe/Makefile
+++ b/arch/arm64/kvm/hyp/nvhe/Makefile
@@ -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)
diff --git a/arch/arm64/lib/kasan_sw_tags.S b/arch/arm64/lib/kasan_sw_tags.S
index 20784ce75def..7959b5f3c6b0 100644
--- a/arch/arm64/lib/kasan_sw_tags.S
+++ b/arch/arm64/lib/kasan_sw_tags.S
@@ -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)
diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 33632fb20997..ee1436295046 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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;
 }
diff --git a/arch/arm64/net/bpf_timed_may_goto.S b/arch/arm64/net/bpf_timed_may_goto.S
index f8732b13bb1e..6d0aa023c1f4 100644
--- a/arch/arm64/net/bpf_timed_may_goto.S
+++ b/arch/arm64/net/bpf_timed_may_goto.S
@@ -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)
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 08/11] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (6 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 07/11] arm64/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 09/11] riscv/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
                   ` (2 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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

diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig
index e7891a2a89da..84b61c755db3 100644
--- a/arch/riscv/Kconfig
+++ b/arch/riscv/Kconfig
@@ -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
diff --git a/arch/riscv/include/asm/signal32.h b/arch/riscv/include/asm/signal32.h
index 96dc56932e76..2c3e8eae56e5 100644
--- a/arch/riscv/include/asm/signal32.h
+++ b/arch/riscv/include/asm/signal32.h
@@ -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
diff --git a/arch/riscv/include/asm/unwind_user.h b/arch/riscv/include/asm/unwind_user.h
new file mode 100644
index 000000000000..a2c2068df4ad
--- /dev/null
+++ b/arch/riscv/include/asm/unwind_user.h
@@ -0,0 +1,81 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _ASM_RISCV_UNWIND_USER_H
+#define _ASM_RISCV_UNWIND_USER_H
+
+#ifdef CONFIG_UNWIND_USER
+
+#include <linux/compat.h>
+#include <linux/unwind_dwarf_cfi.h>
+#include <linux/unwind_user_types.h>
+#include <asm/ptrace.h>
+
+/**
+ * unwind_user_word_size() - Return the user-space word size in bytes on RISC-V
+ * @regs: User-mode register state.
+ *
+ * Return: 4 for RV32 compat user tasks, or sizeof(unsigned long) otherwise.
+ */
+static inline int unwind_user_word_size(struct pt_regs *regs)
+{
+	if (IS_ENABLED(CONFIG_COMPAT) && is_compat_task())
+		return 4;
+	return sizeof(unsigned long);
+}
+
+/**
+ * unwind_user_link_register() - Fetch the user link register (ra/x1) from @regs
+ * @regs: User-mode register state.
+ * @ra: Output link register value.
+ *
+ * Return: Always true on RISC-V.
+ */
+static inline bool unwind_user_link_register(struct pt_regs *regs,
+					     unsigned long *ra)
+{
+	*ra = regs->ra;
+	return true;
+}
+#define unwind_user_link_register unwind_user_link_register
+
+/**
+ * unwind_user_cfi_arch() - Populate RISC-V DWARF register numbers
+ * @ws: User word size in bytes (4 for RV32, 8 for RV64).
+ * @arch: Output DWARF CFI architecture descriptor.
+ *
+ * Return: true if @ws is 4 or 8, false otherwise.
+ */
+static inline bool unwind_user_cfi_arch(unsigned int ws,
+					struct dwarf_cfi_arch *arch)
+{
+	if (ws == 8 || ws == 4) {
+		*arch = (struct dwarf_cfi_arch){
+			.ws	= (u8)ws,
+			.sp_reg	= 2,	/* sp (x2) */
+			.fp_reg	= 8,	/* s0/fp (x8) */
+			.ra_reg	= 1,	/* ra (x1) */
+		};
+		return true;
+	}
+	return false;
+}
+
+bool unwind_user_sigreturn(struct unwind_user_state *state);
+#define unwind_user_sigreturn unwind_user_sigreturn
+
+#endif /* CONFIG_UNWIND_USER */
+
+#ifdef CONFIG_HAVE_UNWIND_USER_FP
+
+/*
+ * Standard RISC-V psABI frame record stores {saved_s0, saved_ra} at
+ * [s0 - 2 * ws, s0), with s0 pointing to the caller's stack pointer (CFA).
+ */
+#define ARCH_INIT_USER_FP_FRAME(ws)			\
+	.cfa_off	=  0,				\
+	.ra_off		= -1 * (ws),			\
+	.fp_off		= -2 * (ws),			\
+	.use_fp		= true,
+
+#endif /* CONFIG_HAVE_UNWIND_USER_FP */
+
+#endif /* _ASM_RISCV_UNWIND_USER_H */
diff --git a/arch/riscv/kernel/compat_signal.c b/arch/riscv/kernel/compat_signal.c
index cf3eb33a11e4..d549c3f46ae8 100644
--- a/arch/riscv/kernel/compat_signal.c
+++ b/arch/riscv/kernel/compat_signal.c
@@ -5,6 +5,7 @@
 #include <linux/uaccess.h>
 #include <linux/syscalls.h>
 #include <linux/linkage.h>
+#include <linux/unwind_user.h>
 
 #include <asm/csr.h>
 #include <asm/signal32.h>
@@ -243,3 +244,46 @@ int compat_setup_rt_frame(struct ksignal *ksig, sigset_t *set,
 
 	return 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.
+ */
+bool compat_unwind_user_sigreturn(struct unwind_user_state *state)
+{
+	struct mm_struct *mm = current->mm;
+	struct compat_rt_sigframe __user *frame;
+	struct compat_user_regs_struct cregs;
+	unsigned long sigret;
+
+	if (!mm || !mm->context.vdso || (state->sp & 3UL))
+		return false;
+
+	sigret = (unsigned long)COMPAT_VDSO_SYMBOL(mm->context.vdso,
+						   rt_sigreturn);
+	if (state->ip != sigret &&
+	    !(state->topmost && state->ip == sigret + 4))
+		return false;
+
+	frame = (struct compat_rt_sigframe __user *)state->sp;
+	if (copy_from_user(&cregs, &frame->uc.uc_mcontext.sc_regs,
+			   offsetofend(struct compat_user_regs_struct, s0)))
+		return false;
+
+	if ((cregs.sp & 3U) || !cregs.pc)
+		return false;
+
+	state->ip = cregs.pc;
+	state->ra = cregs.ra;
+	state->sp = cregs.sp;
+	state->fp = cregs.s0;
+	state->ra_valid = true;
+	state->signal = true;
+	state->topmost = false;
+	return true;
+}
+#endif
diff --git a/arch/riscv/kernel/signal.c b/arch/riscv/kernel/signal.c
index 59784dc117e4..6472c645914d 100644
--- a/arch/riscv/kernel/signal.c
+++ b/arch/riscv/kernel/signal.c
@@ -13,6 +13,7 @@
 #include <linux/resume_user_mode.h>
 #include <linux/linkage.h>
 #include <linux/entry-common.h>
+#include <linux/unwind_user.h>
 
 #include <asm/ucontext.h>
 #include <asm/vdso.h>
@@ -587,3 +588,64 @@ bool sigaltstack_size_valid(size_t ss_size)
 	return ss_size > get_rt_frame_size(false);
 }
 #endif /* CONFIG_DYNAMIC_SIGFRAME */
+
+#ifdef CONFIG_UNWIND_USER
+/**
+ * unwind_user_sigreturn() - Unwind a RISC-V rt_sigreturn user signal frame
+ * @state: Current user unwind state.
+ *
+ * __vdso_rt_sigreturn carries an empty .cfi_signal_frame FDE without register
+ * rules so user-space unwinders such as libgcc take their instruction-matching
+ * sigcontext fallback. Recover pc, ra, sp, and s0 directly from
+ * &rt_sigframe.uc.uc_mcontext.sc_regs so interrupted leaf functions,
+ * -fomit-frame-pointer code, and alternate signal stacks unwind cleanly.
+ *
+ * Return: true if @state was at the rt_sigreturn trampoline and advanced to
+ * the interrupted user context, false otherwise.
+ */
+bool unwind_user_sigreturn(struct unwind_user_state *state)
+{
+	struct mm_struct *mm = current->mm;
+	struct rt_sigframe __user *frame;
+	struct user_regs_struct sc_regs;
+	unsigned long sigret;
+
+	if (!mm)
+		return false;
+
+	if (IS_ENABLED(CONFIG_COMPAT) && state->ws == 4)
+		return compat_unwind_user_sigreturn(state);
+
+	if (state->ws != sizeof(unsigned long) ||
+	    (state->sp & (sizeof(unsigned long) - 1)))
+		return false;
+
+	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
+	if (state->ip != sigret &&
+	    !(state->topmost && state->ip == sigret + 4))
+		return false;
+
+	if (copy_from_user(&sc_regs, &frame->uc.uc_mcontext.sc_regs,
+			   offsetofend(struct user_regs_struct, s0)))
+		return false;
+
+	if ((sc_regs.sp & (sizeof(unsigned long) - 1)) || !sc_regs.pc)
+		return false;
+
+	state->ip = sc_regs.pc;
+	state->ra = sc_regs.ra;
+	state->sp = sc_regs.sp;
+	state->fp = sc_regs.s0;
+	state->ra_valid = true;
+	state->signal = true;
+	state->topmost = false;
+	return true;
+}
+#endif
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 09/11] riscv/unwind: Add Minimal DWARF CFI kernel unwinder
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (7 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 08/11] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 10/11] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 11/11] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer Ian Rogers
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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.

Signed-off-by: Ian Rogers <irogers@google.com>
---
 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(-)

diff --git a/arch/riscv/Kconfig b/arch/riscv/Kconfig
index 84b61c755db3..14d64a3fa33c 100644
--- a/arch/riscv/Kconfig
+++ b/arch/riscv/Kconfig
@@ -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
diff --git a/arch/riscv/Kconfig.debug b/arch/riscv/Kconfig.debug
index eafe17ebf710..afc8be5ec97f 100644
--- a/arch/riscv/Kconfig.debug
+++ b/arch/riscv/Kconfig.debug
@@ -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"
diff --git a/arch/riscv/Makefile b/arch/riscv/Makefile
index 44f5a439741a..ffa8842e7959 100644
--- a/arch/riscv/Makefile
+++ b/arch/riscv/Makefile
@@ -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.
diff --git a/arch/riscv/include/asm/module.h b/arch/riscv/include/asm/module.h
index 0f3baaa6a9a8..ff783889774b 100644
--- a/arch/riscv/include/asm/module.h
+++ b/arch/riscv/include/asm/module.h
@@ -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 */
diff --git a/arch/riscv/include/asm/perf_event.h b/arch/riscv/include/asm/perf_event.h
index bcc928fd3785..cfe95b9106e5 100644
--- a/arch/riscv/include/asm/perf_event.h
+++ b/arch/riscv/include/asm/perf_event.h
@@ -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 */
diff --git a/arch/riscv/include/asm/stacktrace.h b/arch/riscv/include/asm/stacktrace.h
index b1495a7e06ce..5a7b77367041 100644
--- a/arch/riscv/include/asm/stacktrace.h
+++ b/arch/riscv/include/asm/stacktrace.h
@@ -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)
 {
diff --git a/arch/riscv/kernel/Makefile b/arch/riscv/kernel/Makefile
index f54c336bf547..f2e1f342e3d7 100644
--- a/arch/riscv/kernel/Makefile
+++ b/arch/riscv/kernel/Makefile
@@ -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
diff --git a/arch/riscv/kernel/entry.S b/arch/riscv/kernel/entry.S
index 61b7a7716697..0a37ac12128c 100644
--- a/arch/riscv/kernel/entry.S
+++ b/arch/riscv/kernel/entry.S
@@ -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 */
 
diff --git a/arch/riscv/kernel/mcount-dyn.S b/arch/riscv/kernel/mcount-dyn.S
index 082fe0b0e3c0..06c26725a830 100644
--- a/arch/riscv/kernel/mcount-dyn.S
+++ b/arch/riscv/kernel/mcount-dyn.S
@@ -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
diff --git a/arch/riscv/kernel/mcount.S b/arch/riscv/kernel/mcount.S
index da4a4000e57e..c13aa07cdb04 100644
--- a/arch/riscv/kernel/mcount.S
+++ b/arch/riscv/kernel/mcount.S
@@ -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
 
diff --git a/arch/riscv/kernel/module.c b/arch/riscv/kernel/module.c
index 1961135689db..93092b17b53a 100644
--- a/arch/riscv/kernel/module.c
+++ b/arch/riscv/kernel/module.c
@@ -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);
+}
diff --git a/arch/riscv/kernel/probes/rethook.c b/arch/riscv/kernel/probes/rethook.c
index 5c27c1f50989..1ae3faf48218 100644
--- a/arch/riscv/kernel/probes/rethook.c
+++ b/arch/riscv/kernel/probes/rethook.c
@@ -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;
diff --git a/arch/riscv/kernel/probes/rethook_trampoline.S b/arch/riscv/kernel/probes/rethook_trampoline.S
index c3aa8d8cf5af..50c68105c76b 100644
--- a/arch/riscv/kernel/probes/rethook_trampoline.S
+++ b/arch/riscv/kernel/probes/rethook_trampoline.S
@@ -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)
diff --git a/arch/riscv/kernel/stacktrace.c b/arch/riscv/kernel/stacktrace.c
index c7555447149b..05f846c14787 100644
--- a/arch/riscv/kernel/stacktrace.c
+++ b/arch/riscv/kernel/stacktrace.c
@@ -6,16 +6,22 @@
 
 #include <linux/export.h>
 #include <linux/kallsyms.h>
+#include <linux/module.h>
+#include <linux/perf_event.h>
+#include <linux/rcupdate.h>
+#include <linux/rethook.h>
 #include <linux/sched.h>
 #include <linux/sched/debug.h>
 #include <linux/sched/task_stack.h>
 #include <linux/stacktrace.h>
 #include <linux/ftrace.h>
+#include <linux/unwind_dwarf_cfi.h>
 
+#include <asm/irq_stack.h>
+#include <asm/module.h>
+#include <asm/sections.h>
 #include <asm/stacktrace.h>
 
-#ifdef CONFIG_FRAME_POINTER
-
 /*
  * This disables KASAN checking when reading a value from another task's stack,
  * since the other task could be running on another CPU and could have poisoned
@@ -35,6 +41,726 @@
 extern asmlinkage void handle_exception(void);
 extern unsigned long ret_from_exception_end;
 
+#ifdef CONFIG_UNWINDER_DWARF_CFI
+
+static const struct dwarf_cfi_arch riscv_cfi_arch = {
+	.ws	= sizeof(unsigned long),
+	.sp_reg	= 2,	/* sp (x2) */
+	.fp_reg	= 8,	/* s0/fp (x8) */
+	.ra_reg	= 1,	/* ra (x1) */
+};
+
+#ifdef CONFIG_MODULES
+/**
+ * riscv_unwind_module_init() - Build Minimal DWARF CFI index for a module
+ * @mod: Module being loaded.
+ * @eh_frame: Pointer to the module's SHF_ALLOC .eh_frame section.
+ * @eh_frame_size: Size in bytes of @eh_frame.
+ *
+ * Scans and sorts the module's FDEs and publishes the index to
+ * @mod->arch.dwarf_cfi_index for RCU-protected lockless unwinding.
+ */
+void riscv_unwind_module_init(struct module *mod, void *eh_frame,
+			      size_t eh_frame_size)
+{
+	struct mod_dwarf_cfi_index *idx;
+
+	idx = dwarf_cfi_mod_alloc(eh_frame, eh_frame_size, &riscv_cfi_arch);
+	if (idx)
+		rcu_assign_pointer(mod->arch.dwarf_cfi_index, idx);
+}
+
+/**
+ * riscv_unwind_module_cleanup() - Unpublish and RCU-free module DWARF CFI index
+ * @mod: Module being unloaded or cleaned up after a failed load.
+ */
+void riscv_unwind_module_cleanup(struct module *mod)
+{
+	struct mod_dwarf_cfi_index *idx;
+
+	idx = rcu_replace_pointer(mod->arch.dwarf_cfi_index, /*ptr=*/NULL,
+				  /*c=*/true);
+	dwarf_cfi_mod_free_rcu(idx);
+}
+
+/**
+ * riscv_dwarf_cfi_module_find() - Look up Minimal DWARF CFI in loadable modules
+ * @pc: Kernel instruction pointer to evaluate.
+ * @row: Output evaluated Minimal DWARF CFI row.
+ *
+ * Uses rcu_read_lock_sched_notrace() and rcu_dereference_raw() so lookups are
+ * safe inside noinstr stack walks and NMI contexts.
+ *
+ * Return: 0 on success, -ENOENT if @pc is not in a module FDE, or a negative
+ * errno on invalid FDE bytecode.
+ */
+static __always_inline int
+riscv_dwarf_cfi_module_find(unsigned long pc, struct dwarf_cfi_row *row)
+{
+	struct mod_dwarf_cfi_index *idx;
+	struct module *mod;
+	int ret;
+
+	rcu_read_lock_sched_notrace();
+	mod = __module_address(pc);
+	if (!mod) {
+		rcu_read_unlock_sched_notrace();
+		return -ENOENT;
+	}
+	idx = rcu_dereference_raw(mod->arch.dwarf_cfi_index);
+	ret = dwarf_cfi_mod_eval(idx, pc, &riscv_cfi_arch, row);
+	rcu_read_unlock_sched_notrace();
+	return ret;
+}
+#else
+static __always_inline int
+riscv_dwarf_cfi_module_find(unsigned long pc, struct dwarf_cfi_row *row)
+{
+	return -ENOENT;
+}
+#endif /* CONFIG_MODULES */
+
+/**
+ * riscv_dwarf_cfi_find() - Evaluate Minimal DWARF CFI for core or module @pc
+ * @pc: Kernel instruction pointer to look up.
+ * @row: Output evaluated Minimal DWARF CFI row.
+ *
+ * Return: 0 on success, -ENOENT if no FDE covers @pc, or a negative errno on
+ * malformed CFI data.
+ */
+static __always_inline int
+riscv_dwarf_cfi_find(unsigned long pc, struct dwarf_cfi_row *row)
+{
+	size_t hdr_size = __stop_eh_frame_hdr - __start_eh_frame_hdr;
+	int err;
+
+	err = dwarf_cfi_unwind_eh_frame_hdr(__start_eh_frame_hdr, hdr_size,
+					    __start_eh_frame, __stop_eh_frame,
+					    pc, &riscv_cfi_arch, row);
+	if (!err)
+		return 0;
+
+	return riscv_dwarf_cfi_module_find(pc, row);
+}
+
+/**
+ * riscv_fgraph_recover() - Recover original return address from ftrace_graph
+ * @task: Task being unwound.
+ * @graph_idx: Shadow-stack index cursor for ftrace_graph_ret_addr().
+ * @pc: Candidate return address (potentially &return_to_handler).
+ * @cfa: Callee frame's Canonical Frame Address (entry SP).
+ * @ra_slot: Stack slot where @pc was saved (overridden when DYNAMIC_FTRACE_WITH_ARGS).
+ *
+ * Return: Restored caller PC if @pc matched &return_to_handler, or @pc.
+ */
+static __always_inline unsigned long
+riscv_fgraph_recover(struct task_struct *task, int *graph_idx,
+		     unsigned long pc, unsigned long cfa,
+		     unsigned long *ra_slot)
+{
+#if defined(CONFIG_FUNCTION_GRAPH_TRACER) && defined(CONFIG_DYNAMIC_FTRACE_WITH_ARGS)
+	unsigned long fregs_addr = cfa - ALIGN(sizeof(struct __arch_ftrace_regs),
+					       STACK_ALIGN);
+
+	ra_slot = &((struct __arch_ftrace_regs *)fregs_addr)->ra;
+#endif
+	return ftrace_graph_ret_addr(task, graph_idx, pc, ra_slot);
+}
+
+/**
+ * riscv_recover_ret_addr() - Recover ftrace_graph and rethook return addresses
+ * @task: Task being unwound.
+ * @graph_idx: Shadow-stack cursor for ftrace_graph_ret_addr().
+ * @kr_cur: Shadow-list cursor for rethook_find_ret_addr().
+ * @pc: Candidate return address to recover.
+ * @cfa: Callee frame's Canonical Frame Address (entry SP).
+ * @ra_slot: Stack slot where @pc was saved (or NULL if still in ra).
+ *
+ * Recovers original caller PCs across both ftrace_graph and rethook shadow
+ * stacks in either hooking order, keying rethook lookups on @cfa (matching
+ * arch_rethook_prepare() under CONFIG_UNWINDER_DWARF_CFI).
+ *
+ * Return: Restored caller PC, or 0 if recovery failed.
+ */
+static __always_inline unsigned long
+riscv_recover_ret_addr(struct task_struct *task, int *graph_idx,
+		       struct llist_node **kr_cur, unsigned long pc,
+		       unsigned long cfa, unsigned long *ra_slot)
+{
+	pc = riscv_fgraph_recover(task, graph_idx, pc, cfa, ra_slot);
+#ifdef CONFIG_RETHOOK
+	if (is_rethook_trampoline(pc)) {
+		pc = rethook_find_ret_addr(task, cfa, kr_cur);
+		if (!pc || is_rethook_trampoline(pc))
+			return 0;
+	}
+#endif
+	pc = riscv_fgraph_recover(task, graph_idx, pc, cfa, ra_slot);
+#ifdef CONFIG_FUNCTION_GRAPH_TRACER
+	if (pc == (unsigned long)return_to_handler)
+		return 0;
+#endif
+	return pc;
+}
+
+#define RISCV_STACK_TASK	BIT(0)
+#define RISCV_STACK_IRQ		BIT(1)
+#define RISCV_STACK_OVERFLOW	BIT(2)
+
+/**
+ * riscv_stack_bounds() - Validate that [@addr, @addr + @size) lies on a stack
+ * @task: Task whose stacks are checked.
+ * @addr: Start virtual address of the stack access.
+ * @size: Access size in bytes.
+ * @out_low: Output lower bound of the matched stack.
+ * @out_high: Output upper bound of the matched stack.
+ *
+ * Checks @task's task stack, and when unwinding @current in non-preemptible
+ * context, also checks the per-CPU IRQ and vmap overflow stacks.
+ *
+ * Return: RISCV_STACK_* bit for the matched stack, or 0 if out of bounds.
+ */
+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;
+}
+
+#ifdef CONFIG_PERF_EVENTS
+/**
+ * riscv_unwind_perf_caller_regs() - Populate caller pt_regs for perf events
+ * @regs: Output pt_regs initialized for the caller frame.
+ * @pc: Current instruction pointer inside the function invoking perf_fetch_caller_regs.
+ * @caller_ip: Target caller instruction pointer to record in @regs->epc.
+ * @sp: Current stack pointer corresponding to @pc.
+ * @fp: Current s0 value corresponding to @pc.
+ *
+ * Steps one frame via Minimal DWARF CFI at @pc so @regs->sp, @regs->s0, and
+ * @regs->epc reflect the caller's stack state under -fomit-frame-pointer.
+ */
+void riscv_unwind_perf_caller_regs(struct pt_regs *regs, unsigned long pc,
+				   unsigned long caller_ip, unsigned long sp,
+				   unsigned long fp)
+{
+	unsigned long cur_low = 0, cur_high = 0, low = 0, high = 0;
+	struct llist_node *kr_cur = NULL;
+	struct dwarf_cfi_row row;
+	int graph_idx = 0;
+
+	regs->epc = caller_ip;
+	regs->ra = 0;
+	regs->s0 = fp;
+	regs->sp = sp;
+	regs->status = SR_PP;
+
+	if ((sp & (sizeof(long) - 1)) ||
+	    !riscv_stack_bounds(current, sp, /*size=*/0, &cur_low, &cur_high))
+		return;
+
+	if (riscv_dwarf_cfi_find(pc, &row))
+		return;
+
+	switch (row.cfa_base) {
+	case DWARF_CFI_BASE_SP:
+		sp += row.cfa_off;
+		break;
+	case DWARF_CFI_BASE_FP:
+		sp = fp + row.cfa_off;
+		break;
+	case DWARF_CFI_BASE_FP_INDIRECT: {
+		unsigned long cfa_addr = fp + row.cfa_off;
+
+		if ((cfa_addr & (sizeof(long) - 1)) ||
+		    !riscv_stack_bounds(current, cfa_addr, sizeof(long),
+					&low, &high) ||
+		    low != cur_low)
+			return;
+		sp = READ_ONCE(*(unsigned long *)cfa_addr);
+		break;
+	}
+	default:
+		return;
+	}
+
+	if ((sp & (sizeof(long) - 1)) || sp < cur_low || sp > cur_high)
+		return;
+
+	if (row.fp_rule == DWARF_CFI_RULE_OFFSET) {
+		unsigned long fp_addr = sp + row.fp_off;
+
+		if ((fp_addr & (sizeof(long) - 1)) ||
+		    !riscv_stack_bounds(current, fp_addr, sizeof(long),
+					&low, &high) ||
+		    low != cur_low)
+			return;
+		fp = READ_ONCE(*(unsigned long *)fp_addr);
+	} else if (row.fp_rule == DWARF_CFI_RULE_FP_OFFSET) {
+		unsigned long fp_addr = fp + row.fp_off;
+
+		if ((fp_addr & (sizeof(long) - 1)) ||
+		    !riscv_stack_bounds(current, fp_addr, sizeof(long),
+					&low, &high) ||
+		    low != cur_low)
+			return;
+		fp = READ_ONCE(*(unsigned long *)fp_addr);
+	}
+
+	caller_ip = riscv_recover_ret_addr(current, &graph_idx, &kr_cur,
+					   caller_ip, sp, /*ra_slot=*/NULL);
+	if (caller_ip)
+		regs->epc = caller_ip;
+	regs->sp = sp;
+	regs->s0 = fp;
+}
+EXPORT_SYMBOL_GPL(riscv_unwind_perf_caller_regs);
+#endif /* CONFIG_PERF_EVENTS */
+
+/**
+ * walk_stackframe_cfi() - Unwind a RISC-V kernel stack via Minimal DWARF CFI
+ * @task: Target task to unwind (NULL defaults to current).
+ * @regs: Optional starting register state (rejected when @require_reliable).
+ * @fn: Callback invoked for each unwound PC; returning false stops the walk.
+ * @arg: Opaque cookie passed to @fn.
+ * @require_reliable: When true, reject exception boundaries, unannotated leaf
+ *                    fallbacks, and non-CFI frame-pointer guesses.
+ *
+ * Return: 0 on clean stack termination (or early callback stop when
+ * !@require_reliable), or -EINVAL when a reliable walk cannot be guaranteed.
+ */
+static __always_inline int
+walk_stackframe_cfi(struct task_struct *task, struct pt_regs *regs,
+		    bool (*fn)(void *, unsigned long), void *arg,
+		    bool require_reliable)
+{
+	unsigned long fp, sp, pc, ra = 0;
+	bool ra_valid = false, exact_pc = false, unreliable = false;
+	struct llist_node *kr_cur = NULL;
+	unsigned int used_stacks = 0;
+	int graph_idx = 0;
+	int level = 0;
+
+	if (!task)
+		task = current;
+
+	if (regs) {
+		if (require_reliable)
+			return -EINVAL;
+		fp = frame_pointer(regs);
+		sp = kernel_stack_pointer(regs);
+		pc = instruction_pointer(regs);
+		ra = regs->ra;
+		ra_valid = !!ra;
+		exact_pc = true;
+	} else if (task == current) {
+		asm volatile("1: auipc %0, 0\n\t"
+			     "mv %1, s0"
+			     : "=r"(pc), "=r"(fp));
+		sp = current_stack_pointer;
+		ra = (unsigned long)__builtin_return_address(0);
+		ra_valid = true;
+		exact_pc = true;
+		level = -1;
+	} else {
+		fp = task->thread.s[0];
+		sp = task->thread.sp;
+		pc = task->thread.ra;
+	}
+
+	for (;;) {
+		unsigned long lookup_pc, cfa, next_pc, next_fp = fp;
+		unsigned long cur_low = 0, cur_high = 0, low = 0, high = 0;
+		unsigned long tsk_low = (unsigned long)task_stack_page(task);
+		unsigned int cur_stk, next_stk;
+		struct dwarf_cfi_row row;
+		int err;
+
+		if (!pc) {
+			if (exact_pc && ra_valid && !require_reliable) {
+				pc = ra;
+				ra_valid = false;
+				exact_pc = false;
+				unreliable = true;
+				continue;
+			}
+			return require_reliable ? -EINVAL : 0;
+		}
+
+		/*
+		 * Boot and secondary CPU idle tasks enter C code from
+		 * .head.text ([_start, _stext)), which precedes _stext.
+		 */
+		if (is_idle_task(task) &&
+		    sp >= (unsigned long)task_pt_regs(task) &&
+		    sp <= tsk_low + THREAD_SIZE &&
+		    pc >= (unsigned long)_start &&
+		    pc < (unsigned long)_stext)
+			return 0;
+
+		if (!__kernel_text_address(pc))
+			return require_reliable ? -EINVAL : 0;
+
+		if (sp == (unsigned long)task_pt_regs(task) &&
+		    pc >= (unsigned long)ret_from_fork_kernel_asm &&
+		    pc < (unsigned long)&ret_from_fork_asm_end) {
+			if (level++ >= 0 && !fn(arg, pc))
+				return require_reliable ? -EINVAL : 0;
+			return 0;
+		}
+
+		if (level++ >= 0 && !fn(arg, pc))
+			return require_reliable ? -EINVAL : 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);
+			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;
+			if (low == cur_low) {
+				if (next_sp <= sp)
+					return -EINVAL;
+			} else {
+				if (used_stacks & next_stk)
+					return -EINVAL;
+				used_stacks |= cur_stk;
+			}
+			pc = next_pc;
+			sp = next_sp;
+			fp = next_fp;
+			ra = next_ra;
+			ra_valid = true;
+			exact_pc = true;
+			unreliable = true;
+			continue;
+		}
+
+		lookup_pc = exact_pc ? pc : pc - 2;
+		err = riscv_dwarf_cfi_find(lookup_pc, &row);
+		if (err) {
+#ifdef CONFIG_DYNAMIC_FTRACE_WITH_ARGS
+			if (lookup_pc >= (unsigned long)ftrace_caller_saved &&
+			    lookup_pc < (unsigned long)ftrace_caller_restore &&
+			    (!exact_pc || !require_reliable)) {
+				size_t fsize = ALIGN(sizeof(struct __arch_ftrace_regs),
+						     STACK_ALIGN);
+				struct __arch_ftrace_regs *fregs = (void *)sp;
+
+				if ((sp & (sizeof(long) - 1)) ||
+				    !riscv_stack_bounds(task, sp, fsize,
+							&cur_low, &cur_high) ||
+				    READ_ONCE_TASK_STACK(task, fregs->sp) != sp + fsize)
+					return -EINVAL;
+				pc = READ_ONCE_TASK_STACK(task, fregs->epc);
+				fp = READ_ONCE_TASK_STACK(task, fregs->s0);
+				ra = READ_ONCE_TASK_STACK(task, fregs->ra);
+				sp += fsize;
+				ra_valid = true;
+				exact_pc = true;
+				if (!pc)
+					return -EINVAL;
+				continue;
+			}
+#endif
+#ifdef CONFIG_IRQ_STACKS
+			/*
+			 * call_on_irq_stack() saves {fp, ra} below s0 on the
+			 * task stack before switching sp to irq_stack_ptr.
+			 */
+			if (!require_reliable &&
+			    task == current && !preemptible() &&
+			    !(used_stacks & RISCV_STACK_TASK) &&
+			    pc >= (unsigned long)call_on_irq_stack &&
+			    pc < (unsigned long)&call_on_irq_stack_end) {
+				unsigned long irq_low =
+					(unsigned long)raw_cpu_read(irq_stack_ptr);
+
+				if (irq_low && sp > irq_low &&
+				    sp <= irq_low + IRQ_STACK_SIZE &&
+				    fp && !(fp & 0x7) &&
+				    fp >= tsk_low + sizeof(struct stackframe) &&
+				    fp <= tsk_low + THREAD_SIZE) {
+					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);
+					next_pc = riscv_recover_ret_addr(task,
+							&graph_idx, &kr_cur,
+							next_pc, old_fp,
+							&fr->ra);
+					if (!next_pc)
+						return 0;
+					used_stacks |= RISCV_STACK_IRQ;
+					fp = next_fp;
+					pc = next_pc;
+					sp = old_fp;
+					ra_valid = false;
+					exact_pc = false;
+					unreliable = true;
+					continue;
+				}
+			}
+#endif
+			if (exact_pc && ra_valid && !require_reliable &&
+			    pc >= (unsigned long)_stext &&
+			    pc < (unsigned long)_etext) {
+				pc = riscv_recover_ret_addr(task, &graph_idx,
+							    &kr_cur, ra, sp,
+							    /*ra_slot=*/NULL);
+				if (!pc)
+					return 0;
+				ra_valid = false;
+				exact_pc = false;
+				unreliable = true;
+				continue;
+			}
+
+			/*
+			 * 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)
+						return 0;
+					fp = next_fp;
+					pc = next_pc;
+				}
+				sp = old_fp;
+				ra_valid = false;
+				exact_pc = false;
+				unreliable = true;
+				continue;
+			}
+
+			if (exact_pc && ra_valid && !require_reliable) {
+				pc = riscv_recover_ret_addr(task, &graph_idx,
+							    &kr_cur, ra, sp,
+							    /*ra_slot=*/NULL);
+				if (!pc)
+					return 0;
+				ra_valid = false;
+				exact_pc = false;
+				unreliable = true;
+				continue;
+			}
+			return -EINVAL;
+		}
+
+		if (row.ra_rule == DWARF_CFI_RULE_UNDEFINED)
+			return require_reliable ? -EINVAL : 0;
+
+		if ((sp & (sizeof(long) - 1)) ||
+		    !riscv_stack_bounds(task, sp, /*size=*/0, &cur_low,
+					&cur_high))
+			return -EINVAL;
+
+		switch (row.cfa_base) {
+		case DWARF_CFI_BASE_SP:
+			cfa = sp + row.cfa_off;
+			break;
+		case DWARF_CFI_BASE_FP:
+			cfa = fp + row.cfa_off;
+			break;
+		case DWARF_CFI_BASE_FP_INDIRECT:
+			if (((fp + row.cfa_off) & (sizeof(long) - 1)) ||
+			    !riscv_stack_bounds(task, fp + row.cfa_off,
+						sizeof(long), &low, &high) ||
+			    low != cur_low)
+				return -EINVAL;
+			cfa = READ_ONCE_TASK_STACK(task,
+				*(unsigned long *)(fp + row.cfa_off));
+			break;
+		default:
+			return -EINVAL;
+		}
+
+		if ((cfa & (sizeof(long) - 1)) || cfa < cur_low || cfa > cur_high)
+			return -EINVAL;
+
+		if (row.fp_rule == DWARF_CFI_RULE_OFFSET) {
+			unsigned long fp_addr = cfa + row.fp_off;
+
+			if ((fp_addr & (sizeof(long) - 1)) ||
+			    !riscv_stack_bounds(task, fp_addr, sizeof(long),
+						&low, &high) ||
+			    low != cur_low)
+				return -EINVAL;
+			next_fp = READ_ONCE_TASK_STACK(task, *(unsigned long *)fp_addr);
+		} else if (row.fp_rule == DWARF_CFI_RULE_FP_OFFSET) {
+			unsigned long fp_addr = fp + row.fp_off;
+
+			if ((fp_addr & (sizeof(long) - 1)) ||
+			    !riscv_stack_bounds(task, fp_addr, sizeof(long),
+						&low, &high) ||
+			    low != cur_low)
+				return -EINVAL;
+			next_fp = READ_ONCE_TASK_STACK(task, *(unsigned long *)fp_addr);
+		}
+
+		if (row.ra_rule == DWARF_CFI_RULE_SAME) {
+			if (!ra_valid) {
+				/*
+				 * Non-struct_ops BPF trampolines push a
+				 * synthetic parent frame record above the
+				 * inner traced-function frame record.
+				 */
+				if (!require_reliable && unreliable &&
+				    row.cfa_base == DWARF_CFI_BASE_SP &&
+				    row.cfa_off == 0 &&
+				    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);
+					next_pc = riscv_recover_ret_addr(task,
+							&graph_idx, &kr_cur,
+							next_pc, old_fp,
+							&fr->ra);
+					if (!next_pc)
+						return 0;
+					sp = old_fp;
+					fp = next_fp;
+					pc = next_pc;
+					ra_valid = false;
+					exact_pc = false;
+					continue;
+				}
+				return -EINVAL;
+			}
+			if (cfa < sp)
+				return -EINVAL;
+			next_pc = riscv_recover_ret_addr(task, &graph_idx,
+							 &kr_cur, ra, cfa,
+							 /*ra_slot=*/NULL);
+		} else if (row.ra_rule == DWARF_CFI_RULE_OFFSET) {
+			unsigned long *ra_p = (unsigned long *)(cfa + row.ra_off);
+
+			if (cfa <= sp ||
+			    ((unsigned long)ra_p & (sizeof(long) - 1)) ||
+			    !riscv_stack_bounds(task, (unsigned long)ra_p,
+						sizeof(long), &low, &high) ||
+			    low != cur_low)
+				return -EINVAL;
+			next_pc = READ_ONCE_TASK_STACK(task, *ra_p);
+			next_pc = riscv_recover_ret_addr(task, &graph_idx,
+							 &kr_cur, next_pc, cfa,
+							 ra_p);
+		} else {
+			return -EINVAL;
+		}
+
+		if (!next_pc)
+			return require_reliable ? -EINVAL : 0;
+
+		sp = cfa;
+		fp = next_fp;
+		pc = next_pc;
+		ra_valid = false;
+		exact_pc = row.signal;
+	}
+}
+
+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);
+}
+
+noinline noinstr int arch_stack_walk_reliable(stack_trace_consume_fn consume_entry,
+					      void *cookie,
+					      struct task_struct *task)
+{
+	return walk_stackframe_cfi(task, /*regs=*/NULL, consume_entry, cookie,
+				   /*require_reliable=*/true);
+}
+
+#elif defined(CONFIG_FRAME_POINTER)
+
 static inline int fp_is_valid(unsigned long fp, unsigned long sp)
 {
 	unsigned long low, high;
@@ -102,7 +828,7 @@ void notrace walk_stackframe(struct task_struct *task, struct pt_regs *regs,
 	}
 }
 
-#else /* !CONFIG_FRAME_POINTER */
+#else /* !CONFIG_FRAME_POINTER && !CONFIG_UNWINDER_DWARF_CFI */
 
 void notrace walk_stackframe(struct task_struct *task,
 	struct pt_regs *regs, bool (*fn)(void *, unsigned long), void *arg)
diff --git a/arch/riscv/kernel/vmlinux.lds.S b/arch/riscv/kernel/vmlinux.lds.S
index 1f4f8496941a..f2bd07e08d5e 100644
--- a/arch/riscv/kernel/vmlinux.lds.S
+++ b/arch/riscv/kernel/vmlinux.lds.S
@@ -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 = .;
 
diff --git a/arch/riscv/purgatory/Makefile b/arch/riscv/purgatory/Makefile
index b0358a78f11a..29c23c58b26c 100644
--- a/arch/riscv/purgatory/Makefile
+++ b/arch/riscv/purgatory/Makefile
@@ -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
 
diff --git a/drivers/firmware/efi/libstub/Makefile b/drivers/firmware/efi/libstub/Makefile
index d62dabfdc1c3..19c2822eb302 100644
--- a/drivers/firmware/efi/libstub/Makefile
+++ b/drivers/firmware/efi/libstub/Makefile
@@ -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
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 10/11] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (8 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 09/11] riscv/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  2026-11-22 23:57 ` [RFC PATCH v1 11/11] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer Ian Rogers
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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()

Signed-off-by: Ian Rogers <irogers@google.com>
---
 .../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

diff --git a/tools/testing/selftests/perf_events/.gitignore b/tools/testing/selftests/perf_events/.gitignore
index 4931b3b6bbd3..4567b6563646 100644
--- a/tools/testing/selftests/perf_events/.gitignore
+++ b/tools/testing/selftests/perf_events/.gitignore
@@ -3,3 +3,4 @@ sigtrap_threads
 remove_on_exec
 watermark_signal
 mmap
+unwind_user_cfi
diff --git a/tools/testing/selftests/perf_events/Makefile b/tools/testing/selftests/perf_events/Makefile
index 2e5d85770dfe..6a3a774544e8 100644
--- a/tools/testing/selftests/perf_events/Makefile
+++ b/tools/testing/selftests/perf_events/Makefile
@@ -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
diff --git a/tools/testing/selftests/perf_events/unwind_user_cfi.c b/tools/testing/selftests/perf_events/unwind_user_cfi.c
new file mode 100644
index 000000000000..3f9fb8500824
--- /dev/null
+++ b/tools/testing/selftests/perf_events/unwind_user_cfi.c
@@ -0,0 +1,447 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * unwind_user_cfi.c - Multi-arch selftest for Minimal DWARF CFI user unwinding.
+ *
+ * Verifies that deferred user-space stack unwinding (PERF_RECORD_CALLCHAIN_DEFERRED)
+ * accurately walks user callchains compiled with -fomit-frame-pointer across:
+ *   1. Standard SP-based frames with the frame-pointer register (%rbp / x29 / s0)
+ *      explicitly clobbered to defeat FP unwinding
+ *   2. Dynamic alloca()/VLA FP-based frames (DW_CFA_def_cfa_register)
+ *   3. 64-byte aligned stack-realigned frames (DRAP on x86-64)
+ *   4. Multi-return shrink-wrapped epilogue functions (remember/restore_state)
+ *   5. Anonymous RX JIT-style frame-pointer stubs lacking .eh_frame_hdr,
+ *      verifying per-frame CFI -> FP -> CFI -> FP -> CFI hybrid fallback and
+ *      negative VMA caching in find_user_eh_frame_hdr()
+ */
+
+#define _GNU_SOURCE
+#include <alloca.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <linux/perf_event.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/syscall.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "../kselftest.h"
+#undef __always_inline
+#undef __attribute_const__
+#undef __must_check
+#undef __printf
+#include "../../../../include/linux/compiler_attributes.h"
+
+#ifndef PERF_RECORD_CALLCHAIN_DEFERRED
+#define PERF_RECORD_CALLCHAIN_DEFERRED 22
+#endif
+
+struct perf_record_deferred {
+	struct perf_event_header header;
+	uint64_t cookie;
+	uint64_t nr;
+	uint64_t ips[];
+};
+
+/*
+ * Tiny architecture-specific machine-code stubs for:
+ *   int jit_stub(int (*fn)(int), int arg);
+ *
+ * Mapped into an anonymous PROT_READ | PROT_EXEC VMA without an ELF header or
+ * PT_GNU_EH_FRAME segment. Each stub establishes a standard architectural
+ * frame-pointer record before calling fn(arg), forcing unwind_user_next() to
+ * fall back from UNWIND_USER_TYPE_CFI to UNWIND_USER_TYPE_FP on the JIT frames
+ * and resume UNWIND_USER_TYPE_CFI on the surrounding -fomit-frame-pointer C
+ * frames.
+ */
+#if defined(__x86_64__)
+#define HAVE_JIT_FP_STUB 1
+static const uint8_t jit_stub_code[] = {
+	0xf3, 0x0f, 0x1e, 0xfa,		/* endbr64 */
+	0x55,				/* push   %rbp */
+	0x48, 0x89, 0xe5,		/* mov    %rsp, %rbp */
+	0x48, 0x89, 0xf8,		/* mov    %rdi, %rax */
+	0x89, 0xf7,			/* mov    %esi, %edi */
+	0xff, 0xd0,			/* call   *%rax */
+	0x5d,				/* pop    %rbp */
+	0xc3,				/* ret */
+};
+#elif defined(__i386__)
+#define HAVE_JIT_FP_STUB 1
+static const uint8_t jit_stub_code[] = {
+	0xf3, 0x0f, 0x1e, 0xfb,		/* endbr32 */
+	0x55,				/* push   %ebp */
+	0x89, 0xe5,			/* mov    %esp, %ebp */
+	0x83, 0xec, 0x04,		/* sub    $4, %esp */
+	0xff, 0x75, 0x0c,		/* pushl  12(%ebp) */
+	0xff, 0x55, 0x08,		/* call   *8(%ebp) */
+	0x83, 0xc4, 0x08,		/* add    $8, %esp */
+	0x5d,				/* pop    %ebp */
+	0xc3,				/* ret */
+};
+#elif defined(__aarch64__)
+#define HAVE_JIT_FP_STUB 1
+static const uint32_t jit_stub_code[] = {
+	0xd503245fU,			/* bti    c */
+	0xa9bf7bfdU,			/* stp    x29, x30, [sp, #-16]! */
+	0x910003fdU,			/* mov    x29, sp */
+	0xaa0003e9U,			/* mov    x9, x0 */
+	0x2a0103e0U,			/* mov    w0, w1 */
+	0xd63f0120U,			/* blr    x9 */
+	0xa8c17bfdU,			/* ldp    x29, x30, [sp], #16 */
+	0xd65f03c0U,			/* ret */
+};
+#elif defined(__riscv) && __riscv_xlen == 64
+#define HAVE_JIT_FP_STUB 1
+static const uint32_t jit_stub_code[] = {
+	0xff010113U,			/* addi   sp, sp, -16 */
+	0x00813023U,			/* sd     s0, 0(sp) */
+	0x00113423U,			/* sd     ra, 8(sp) */
+	0x01010413U,			/* addi   s0, sp, 16 */
+	0x00050313U,			/* mv     t1, a0 */
+	0x00058513U,			/* mv     a0, a1 */
+	0x000300e7U,			/* jalr   ra, 0(t1) */
+	0x00813083U,			/* ld     ra, 8(sp) */
+	0x00013403U,			/* ld     s0, 0(sp) */
+	0x01010113U,			/* addi   sp, sp, 16 */
+	0x00008067U,			/* ret */
+};
+#else
+#define HAVE_JIT_FP_STUB 0
+#endif
+
+static int (*g_jit_fn)(int (*fn)(int), int arg);
+
+static uintptr_t expect_ip_leaf;
+static uintptr_t expect_ip_shrink;
+static uintptr_t expect_ip_jit;
+static uintptr_t expect_ip_bridge;
+static uintptr_t expect_ip_drap;
+static uintptr_t expect_ip_vla;
+static uintptr_t expect_ip_clobber;
+static uintptr_t expect_ip_main;
+
+static __always_inline uintptr_t caller_return_ip(void)
+{
+	return (uintptr_t)__builtin_extract_return_addr(__builtin_return_address(0));
+}
+
+static long sys_perf_event_open(struct perf_event_attr *attr, pid_t pid,
+				int cpu, int group_fd, unsigned long flags)
+{
+	return syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags);
+}
+
+noinline __noclone
+static void cfi_do_nanosleep(const struct timespec *ts)
+{
+	expect_ip_leaf = caller_return_ip();
+	asm volatile("" ::: "memory");
+	nanosleep(ts, /*rem=*/NULL);
+	asm volatile("" ::: "memory");
+}
+
+noinline __noclone
+static void cfi_leaf_sleep(void)
+{
+	struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000 * 1000 };
+
+	expect_ip_shrink = caller_return_ip();
+	asm volatile("" ::: "memory");
+	cfi_do_nanosleep(&ts);
+	asm volatile("" ::: "memory");
+}
+
+/* 4. Shrink-wrapped early-return epilogue before main call */
+noinline __noclone
+static int cfi_shrink_wrap(int mode)
+{
+	expect_ip_jit = caller_return_ip();
+	if (mode < 0)
+		return -1;
+
+	{
+		char pad[32];
+
+		memset(pad, mode, sizeof(pad));
+		asm volatile("" : "+m"(pad) :: "memory");
+		cfi_leaf_sleep();
+		return pad[0];
+	}
+}
+
+/*
+ * 5. Hybrid CFI -> FP -> CFI -> FP -> CFI bridge:
+ *    cfi_pre_jit -> jit_stub #1 -> cfi_jit_bridge -> cfi_mid_jit ->
+ *    jit_stub #2 -> cfi_shrink_wrap
+ *
+ * Invoking the anonymous RX JIT stub twice with -fomit-frame-pointer C frames
+ * in between exercises both per-frame CFI<->FP transitions and negative VMA
+ * cache insertion + hit in find_user_eh_frame_hdr().
+ */
+noinline __noclone
+static int cfi_mid_jit(int x)
+{
+	char pad[32];
+	int res;
+
+	expect_ip_bridge = caller_return_ip();
+	memset(pad, x + 5, sizeof(pad));
+	asm volatile("" : "+m"(pad) :: "memory");
+	res = g_jit_fn ? g_jit_fn(cfi_shrink_wrap, x) : cfi_shrink_wrap(x);
+	asm volatile("" : "+m"(pad) :: "memory");
+	return res + pad[0];
+}
+
+noinline __noclone
+static int cfi_jit_bridge(int x)
+{
+	char pad[32];
+	int res;
+
+	memset(pad, x + 7, sizeof(pad));
+	asm volatile("" : "+m"(pad) :: "memory");
+	res = cfi_mid_jit(x);
+	asm volatile("" : "+m"(pad) :: "memory");
+	return res + pad[0];
+}
+
+noinline __noclone
+static int cfi_pre_jit(int x)
+{
+	char pad[32];
+	int res;
+
+	expect_ip_drap = caller_return_ip();
+	memset(pad, x + 9, sizeof(pad));
+	asm volatile("" : "+m"(pad) :: "memory");
+	res = g_jit_fn ? g_jit_fn(cfi_jit_bridge, x) : cfi_jit_bridge(x);
+	asm volatile("" : "+m"(pad) :: "memory");
+	return res + pad[0];
+}
+
+/* 3. 64-byte aligned local buffer forcing stack realignment (DRAP on x86-64) */
+noinline __noclone
+static int cfi_drap_realigned(int x)
+{
+	uint8_t __aligned(64) aligned_buf[128];
+
+	expect_ip_vla = caller_return_ip();
+	memset(aligned_buf, x + 3, sizeof(aligned_buf));
+	asm volatile("" : "+m"(aligned_buf) :: "memory");
+	return cfi_pre_jit(x) + aligned_buf[0];
+}
+
+/* 2. Dynamic VLA / alloca() forcing FP-based CFA (DW_CFA_def_cfa_register) */
+noinline __noclone
+static int cfi_vla_fp_frame(int n)
+{
+	size_t sz;
+	char *dyn;
+
+	expect_ip_clobber = caller_return_ip();
+	asm volatile("" : "+r"(n));
+	sz = (size_t)((n & 0x3f) + 32);
+	dyn = alloca(sz);
+
+	memset(dyn, n, sz);
+	asm volatile("" : "+m"(*(char (*)[32])dyn) :: "memory");
+	return cfi_drap_realigned(n + dyn[0]);
+}
+
+/* 1. SP-based frame with FP (%rbp / x29 / s0) clobbered to defeat FP unwinding */
+noinline __noclone
+static int cfi_clobber_fp(int x)
+{
+#if defined(__x86_64__)
+	register long bad_fp asm("rbp") = 0x13579bdfL + x;
+#elif defined(__aarch64__)
+	register long bad_fp asm("x29") = 0x13579bdfL + x;
+#elif defined(__riscv)
+	register long bad_fp asm("s0") = 0x13579bdfL + x;
+#else
+	long bad_fp = 0x13579bdfL + x;
+#endif
+	char pad[48];
+
+	expect_ip_main = caller_return_ip();
+	asm volatile("" : "+r"(x));
+	memset(pad, x, sizeof(pad));
+	asm volatile("" : "+r"(bad_fp), "+m"(pad) :: "memory");
+	return cfi_vla_fp_frame(x + 1) ^ (int)bad_fp ^ pad[1];
+}
+
+int main(void)
+{
+	struct perf_event_attr attr;
+	struct perf_event_mmap_page *mpage;
+	size_t page_sz = (size_t)sysconf(_SC_PAGESIZE);
+	size_t mmap_len = (1 + 16) * page_sz;
+	void *jit_page = MAP_FAILED;
+	uint8_t *ring;
+	uint64_t head, tail;
+	bool got_deferred = false;
+	bool saw_leaf = false, saw_shrink = false, saw_jit = false;
+	bool saw_bridge = false, saw_drap = false, saw_vla = false;
+	bool saw_clobber = false, saw_main = false;
+	bool saw_full_chain = false;
+	int fd, arg = 1;
+
+	ksft_print_header();
+	ksft_set_plan(1);
+
+#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
+
+#if HAVE_JIT_FP_STUB
+	jit_page = mmap(/*addr=*/NULL, page_sz, PROT_READ | PROT_WRITE,
+			MAP_PRIVATE | MAP_ANONYMOUS, /*fd=*/-1, /*offset=*/0);
+	if (jit_page != MAP_FAILED) {
+		memcpy(jit_page, jit_stub_code, sizeof(jit_stub_code));
+		if (mprotect(jit_page, page_sz, PROT_READ | PROT_EXEC) == 0) {
+			__builtin___clear_cache((char *)jit_page,
+						(char *)jit_page + sizeof(jit_stub_code));
+			g_jit_fn = (int (*)(int (*)(int), int))jit_page;
+		} else {
+			ksft_print_msg("W^X JIT mprotect unavailable (%s); skipping JIT stub\n",
+				       strerror(errno));
+			munmap(jit_page, page_sz);
+			jit_page = MAP_FAILED;
+		}
+	}
+#endif
+
+	memset(&attr, 0, sizeof(attr));
+	attr.type = PERF_TYPE_SOFTWARE;
+	attr.size = sizeof(attr);
+	attr.config = PERF_COUNT_SW_CONTEXT_SWITCHES;
+	attr.sample_period = 1;
+	attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_CALLCHAIN;
+	attr.disabled = 1;
+	attr.defer_callchain = 1;
+	attr.defer_output = 1;
+
+	fd = (int)sys_perf_event_open(&attr, /*pid=*/0, /*cpu=*/-1,
+				      /*group_fd=*/-1, /*flags=*/0);
+	if (fd < 0) {
+		if (jit_page != MAP_FAILED)
+			munmap(jit_page, page_sz);
+		if (errno == EACCES || errno == EPERM || errno == EINVAL) {
+			ksft_test_result_skip("perf_event_open(defer_callchain) unavailable: %s\n",
+					      strerror(errno));
+			ksft_finished();
+		}
+		ksft_exit_fail_msg("perf_event_open failed: %s\n", strerror(errno));
+	}
+
+	mpage = mmap(/*addr=*/NULL, mmap_len, PROT_READ | PROT_WRITE,
+		     MAP_SHARED, fd, /*offset=*/0);
+	if (mpage == MAP_FAILED) {
+		if (jit_page != MAP_FAILED)
+			munmap(jit_page, page_sz);
+		close(fd);
+		ksft_exit_fail_msg("mmap failed: %s\n", strerror(errno));
+	}
+
+	ioctl(fd, PERF_EVENT_IOC_RESET, 0);
+	ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
+
+	asm volatile("" : "+r"(arg));
+	cfi_clobber_fp(arg);
+
+	ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
+
+	ring = (uint8_t *)mpage + page_sz;
+	head = __atomic_load_n(&mpage->data_head, __ATOMIC_ACQUIRE);
+	tail = mpage->data_tail;
+
+	while (tail < head) {
+		size_t mask = 16 * page_sz - 1;
+		struct perf_event_header *hdr =
+			(struct perf_event_header *)(ring + (tail & mask));
+
+		if (hdr->type == PERF_RECORD_CALLCHAIN_DEFERRED) {
+			struct perf_record_deferred *rec = (void *)hdr;
+			bool c_leaf = false, c_shrink = false, c_bridge = false;
+			bool c_drap = false, c_vla = false, c_clobber = false;
+			bool c_main = false, c_jit_ok = false;
+			unsigned int c_jit_hits = 0;
+
+			got_deferred = true;
+			for (uint64_t i = 0; i < rec->nr; i++) {
+				uintptr_t ip = (uintptr_t)rec->ips[i];
+
+				if (ip == expect_ip_leaf)
+					c_leaf = true;
+				else if (ip == expect_ip_shrink)
+					c_shrink = true;
+				else if (ip == expect_ip_jit)
+					c_jit_hits++;
+				else if (ip == expect_ip_bridge)
+					c_bridge = true;
+				else if (ip == expect_ip_drap)
+					c_drap = true;
+				else if (ip == expect_ip_vla)
+					c_vla = true;
+				else if (ip == expect_ip_clobber)
+					c_clobber = true;
+				else if (ip == expect_ip_main)
+					c_main = true;
+			}
+
+#if HAVE_JIT_FP_STUB
+			if (g_jit_fn) {
+				uintptr_t jb = (uintptr_t)jit_page;
+
+				c_jit_ok = expect_ip_jit >= jb &&
+					   expect_ip_jit < jb + sizeof(jit_stub_code) &&
+					   c_jit_hits >= 2;
+			} else {
+				c_jit_ok = c_jit_hits >= 1;
+			}
+#else
+			c_jit_ok = c_jit_hits >= 1;
+#endif
+			saw_leaf |= c_leaf;
+			saw_shrink |= c_shrink;
+			saw_jit |= c_jit_ok;
+			saw_bridge |= c_bridge;
+			saw_drap |= c_drap;
+			saw_vla |= c_vla;
+			saw_clobber |= c_clobber;
+			saw_main |= c_main;
+
+			if (c_leaf && c_shrink && c_jit_ok && c_bridge &&
+			    c_drap && c_vla && c_clobber && c_main)
+				saw_full_chain = true;
+		}
+		tail += hdr->size;
+	}
+
+	munmap(mpage, mmap_len);
+	if (jit_page != MAP_FAILED)
+		munmap(jit_page, page_sz);
+	close(fd);
+
+	if (!got_deferred) {
+		ksft_test_result_skip("No PERF_RECORD_CALLCHAIN_DEFERRED records\n");
+		ksft_finished();
+	}
+
+	ksft_print_msg("def=%d ok=%d leaf=%d shr=%d jit=%d br=%d drap=%d vla=%d fp=%d entry=%d\n",
+		       got_deferred, saw_full_chain, saw_leaf, saw_shrink,
+		       saw_jit, saw_bridge, saw_drap, saw_vla, saw_clobber,
+		       saw_main);
+
+	ksft_test_result(saw_full_chain,
+			 "unwind_user Minimal DWARF CFI across SP, VLA, DRAP, shrink-wrap, and hybrid JIT FP frames\n");
+	ksft_finished();
+}
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [RFC PATCH v1 11/11] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer
  2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
                   ` (9 preceding siblings ...)
  2026-11-22 23:57 ` [RFC PATCH v1 10/11] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test Ian Rogers
@ 2026-11-22 23:57 ` Ian Rogers
  10 siblings, 0 replies; 12+ messages in thread
From: Ian Rogers @ 2026-11-22 23:57 UTC (permalink / raw)
  To: linux-kernel, linux-trace-kernel, linux-arch
  Cc: jpoimboe, rostedt, peterz, mingo, tglx, bp, dave.hansen, x86,
	catalin.marinas, will, mark.rutland, linux-arm-kernel, pjw,
	palmer, aou, alex, linux-riscv, acme, namhyung, linux-perf-users,
	mhiramat, ast, daniel, andrii, bpf, nathan, nsc, linux-kbuild,
	ojeda, rust-for-linux, ardb, linux-efi, maz, oupton, kvmarm,
	shuah, linux-kselftest, indu.bhagat, jremus, wnliu, dylanbhatch,
	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

Signed-off-by: Ian Rogers <irogers@google.com>
---
 scripts/eh_frame_min.py | 938 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 938 insertions(+)
 create mode 100755 scripts/eh_frame_min.py

diff --git a/scripts/eh_frame_min.py b/scripts/eh_frame_min.py
new file mode 100755
index 000000000000..6a64563a7c40
--- /dev/null
+++ b/scripts/eh_frame_min.py
@@ -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()
-- 
2.56.1.750.gf70dc682cf-goog



^ permalink raw reply related	[flat|nested] 12+ messages in thread

end of thread, other threads:[~2026-11-23  0:01 UTC | newest]

Thread overview: 12+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-22 23:57 [RFC PATCH v1 00/11] unwind: Minimal DWARF CFI stack unwinding for x86, arm64, and riscv Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 01/11] unwind: Add Minimal DWARF CFI bytecode interpreter and KUnit tests Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 02/11] unwind_user: Support Minimal DWARF CFI user-space unwinding Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 03/11] scripts, unwind: Add build-time .eh_frame minifier Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 04/11] objtool/ibt: Ignore .eh_frame relocations during ENDBR validation Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 05/11] x86/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 06/11] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 07/11] arm64/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 08/11] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 09/11] riscv/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 10/11] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test Ian Rogers
2026-11-22 23:57 ` [RFC PATCH v1 11/11] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer Ian Rogers

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox