* [RFC PATCH v2 01/30] unwind: Add Minimal DWARF CFI bytecode interpreter
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
@ 2026-11-25 6:14 ` Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 02/30] unwind: Add KUnit tests for Minimal DWARF CFI interpreter Ian Rogers
` (28 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:14 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, llvm, 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)
- Stack pointer save rule (SAME or *(CFA + off)) for signal frames that
save SP in sigcontext (such as 32-bit x86 vdso32 __kernel_rt_sigreturn)
- Frame pointer save rule (SAME, *(CFA + off), *(FP + off), *(SP + off))
- Return address save rule (SAME in link register, *(CFA + off),
*(SP + off), or UNDEFINED for bottom-of-stack termination), plus
AArch64 PAC-RET signing state (DW_CFA_AARCH64_negate_ra_state)
Callee-saved general-purpose register spill/restore opcodes are decoded
and ignored in O(1) space. General DW_OP_* expressions, DW_CFA_set_loc
backward PC jumps, and DW_CFA_register rules on {SP, FP, RA} are
rejected with -EINVAL; DW_EH_PE_indirect encodings are rejected whenever
an encoded address is evaluated (while unused 'P'/'L' CIE augmentation
fields are skipped by encoded width without dereferencing). CIEs
(<= 128 B), FDEs (<= 4096 B), LEB128 operands (<= 5 B), and
DW_CFA_remember_state nesting (<= 4 entries) execute in a single forward
pass with zero dynamic memory allocations, zero locks, KMSAN output
unpoisoning, noinstr kernel-memory entry points, and Spectre v1 / v1.1
nospec hardening (array_index_nospec() and barrier_nospec()).
Also provide shared RCU-safe loadable-module .eh_frame indexing helpers
using kvmalloc()/kvfree_rcu_mightsleep() (dwarf_cfi_mod_alloc(),
dwarf_cfi_mod_free_rcu(), dwarf_cfi_mod_eval()).
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/Kconfig | 6 +
arch/arm64/Kconfig | 3 -
include/linux/unwind_dwarf_cfi.h | 181 +++
kernel/unwind/Makefile | 12 +-
kernel/unwind/dwarf_cfi.c | 1923 ++++++++++++++++++++++++++++++
5 files changed, 2121 insertions(+), 4 deletions(-)
create mode 100644 include/linux/unwind_dwarf_cfi.h
create mode 100644 kernel/unwind/dwarf_cfi.c
diff --git a/arch/Kconfig b/arch/Kconfig
index 1163736de1f9..5ed64e6cc72e 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -500,6 +500,12 @@ config HAVE_HARDLOCKUP_DETECTOR_ARCH
It uses the same command line parameters, and sysctl interface,
as the generic hardlockup detectors.
+config UNWIND_TABLES
+ bool
+
+config UNWIND_DWARF_CFI
+ bool
+
config UNWIND_USER
bool
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..3530794c8543
--- /dev/null
+++ b/include/linux/unwind_dwarf_cfi.h
@@ -0,0 +1,181 @@
+/* SPDX-License-Identifier: GPL-2.0-only OR MIT */
+#ifndef _LINUX_UNWIND_DWARF_CFI_H
+#define _LINUX_UNWIND_DWARF_CFI_H
+
+#include <linux/types.h>
+
+/*
+ * Minimal DWARF Call Frame Information (CFI) unwinder subset.
+ *
+ * Evaluates a strictly bounded, non-Turing-complete subset of .eh_frame and
+ * .eh_frame_hdr tables matching SFrame's stack-unwinding state model (plus
+ * fixed-pattern DRAP stack-realignment and signal-frame expressions):
+ * - Advances PC monotonically through a single FDE (no backward jumps)
+ * - Tracks CFA = (SP | FP | scratch) + cfa_off or *(FP/SP + cfa_off)
+ * - Tracks stack save offsets for SP, FP, and RA (ignoring callee-saved GPR
+ * spills)
+ * - Rejects general DWARF expressions, register-to-register rules on SP/FP/RA,
+ * and DW_EH_PE_indirect FDE/table pointer encodings (skipping CIE
+ * personality and LSDA fields without dereferencing).
+ */
+
+/* Hard safety bounds enforced on CIE/FDE lengths, offsets, and state stack */
+#define DWARF_CFI_MAX_CIE_LEN 128U
+#define DWARF_CFI_MAX_FDE_LEN 4096U
+#define DWARF_CFI_MAX_CIE_DELTA (64U * 1024U * 1024U)
+#define DWARF_CFI_MAX_FDE_COUNT (4U * 1024U * 1024U)
+#define DWARF_CFI_MAX_STATE_STACK 4U
+
+/**
+ * enum dwarf_cfi_base - Base register or addressing mode for computing the CFA
+ * @DWARF_CFI_BASE_UNDEFINED: CFA rule has not been established yet.
+ * @DWARF_CFI_BASE_SP: CFA = stack pointer + cfa_off.
+ * @DWARF_CFI_BASE_FP: CFA = frame pointer + cfa_off.
+ * @DWARF_CFI_BASE_FP_INDIRECT: DRAP stack realignment: CFA = *(FP + cfa_off).
+ * @DWARF_CFI_BASE_SP_INDIRECT: Signal trampoline frame: CFA = *(SP + cfa_off).
+ * @DWARF_CFI_BASE_REG: Transient prologue/epilogue scratch register:
+ * CFA = reg(cfa_reg) + cfa_off.
+ */
+enum dwarf_cfi_base {
+ DWARF_CFI_BASE_UNDEFINED = 0,
+ DWARF_CFI_BASE_SP,
+ DWARF_CFI_BASE_FP,
+ DWARF_CFI_BASE_FP_INDIRECT,
+ DWARF_CFI_BASE_SP_INDIRECT,
+ DWARF_CFI_BASE_REG,
+};
+
+/**
+ * enum dwarf_cfi_rule - Recovery rule for caller's SP, FP, or return address
+ * @DWARF_CFI_RULE_SAME: Register retains its value from the current frame
+ * (or defaults to CFA for SP).
+ * @DWARF_CFI_RULE_OFFSET: Saved on the stack at *(CFA + off).
+ * @DWARF_CFI_RULE_FP_OFFSET: Saved relative to FP at *(FP + off) (DRAP frame).
+ * @DWARF_CFI_RULE_SP_OFFSET: Saved relative to SP at *(SP + off) (sigframe).
+ * @DWARF_CFI_RULE_UNDEFINED: Explicitly undefined (DW_CFA_undefined); marks
+ * the bottom of a stack (e.g. _start or clone).
+ */
+enum dwarf_cfi_rule {
+ DWARF_CFI_RULE_SAME = 0,
+ DWARF_CFI_RULE_OFFSET,
+ DWARF_CFI_RULE_FP_OFFSET,
+ DWARF_CFI_RULE_SP_OFFSET,
+ DWARF_CFI_RULE_UNDEFINED,
+};
+
+/**
+ * struct dwarf_cfi_arch - Architecture DWARF register numbers and word size
+ * @ws: Target address/word size in bytes (4 or 8).
+ * @sp_reg: DWARF register number for the stack pointer.
+ * @fp_reg: DWARF register number for the frame pointer.
+ * @ra_reg: Default DWARF return-address column number.
+ */
+struct dwarf_cfi_arch {
+ u8 ws;
+ u8 sp_reg;
+ u8 fp_reg;
+ u8 ra_reg;
+};
+
+/**
+ * struct dwarf_cfi_row - Evaluated Minimal DWARF unwind state at a target PC
+ * @cfa_off: Byte offset added to the CFA base register before or as the CFA.
+ * @sp_off: Byte offset used to load the saved SP when @sp_rule is an offset.
+ * @fp_off: Byte offset used to load the saved FP when @fp_rule is an offset.
+ * @ra_off: Byte offset used to load the saved RA when @ra_rule is an offset.
+ * @cfa_base: CFA computation mode (&enum dwarf_cfi_base).
+ * @cfa_reg: DWARF register number when @cfa_base is %DWARF_CFI_BASE_REG.
+ * @sp_rule: Recovery rule for the stack pointer (&enum dwarf_cfi_rule;
+ * %DWARF_CFI_RULE_SAME indicates caller SP equals CFA).
+ * @fp_rule: Recovery rule for the frame pointer (&enum dwarf_cfi_rule).
+ * @ra_rule: Recovery rule for the return address (&enum dwarf_cfi_rule).
+ * @signal: True if the CIE carries the 'S' signal/interrupt frame augmentation,
+ * indicating that the saved PC points directly to the interrupted
+ * instruction rather than after a call instruction.
+ * @ra_signed: True on AArch64 when DW_CFA_AARCH64_negate_ra_state indicates
+ * that the saved return address carries a PAC signature.
+ */
+struct dwarf_cfi_row {
+ s32 cfa_off;
+ s32 sp_off;
+ s32 fp_off;
+ s32 ra_off;
+ u8 cfa_base;
+ u8 cfa_reg;
+ u8 sp_rule;
+ u8 fp_rule;
+ u8 ra_rule;
+ bool signal;
+ bool ra_signed;
+};
+
+/**
+ * struct eh_frame_hdr_entry - Binary-search index entry for an FDE
+ * @start_off: Signed 32-bit offset from the table base (or entry field) to the
+ * FDE's initial PC location.
+ * @fde_off: Signed 32-bit offset from the table base (or entry field) to the
+ * start of the FDE record in .eh_frame.
+ */
+struct eh_frame_hdr_entry {
+ s32 start_off;
+ s32 fde_off;
+};
+
+#ifdef CONFIG_UNWIND_DWARF_CFI
+
+extern const u8 __start_eh_frame_hdr[];
+extern const u8 __stop_eh_frame_hdr[];
+extern const u8 __start_eh_frame[];
+extern const u8 __stop_eh_frame[];
+
+int dwarf_cfi_eval_fde_kmem(const u8 *fde, const u8 *eh_start,
+ const u8 *eh_end, unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+
+int dwarf_cfi_unwind_eh_frame_hdr(const u8 *hdr, size_t hdr_size,
+ const u8 *eh_start, const u8 *eh_end,
+ unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+
+int dwarf_cfi_scan_eh_frame_kmem(const u8 *eh_start, size_t eh_size,
+ const struct dwarf_cfi_arch *arch,
+ unsigned long base_addr,
+ struct eh_frame_hdr_entry *entries,
+ unsigned int max_entries,
+ unsigned int *out_count);
+
+int dwarf_cfi_unwind_user_eh_frame_hdr(unsigned long hdr_uaddr,
+ size_t hdr_size, unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+/**
+ * struct mod_dwarf_cfi_index - Sorted FDE lookup table for a loadable module
+ * @num_fdes: Number of sorted FDE index entries in @entries.
+ * @eh_frame: Pointer to the module's in-memory SHF_ALLOC .eh_frame section;
+ * also serves as the base address for @entries offsets.
+ * @eh_frame_size: Size in bytes of the module's .eh_frame section.
+ * @entries: Sorted binary-search table mapping PCs to module FDEs.
+ */
+struct mod_dwarf_cfi_index {
+ unsigned int num_fdes;
+ const u8 *eh_frame;
+ size_t eh_frame_size;
+ struct eh_frame_hdr_entry entries[] __counted_by(num_fdes);
+};
+
+struct mod_dwarf_cfi_index *dwarf_cfi_mod_alloc(const void *eh_frame,
+ size_t eh_frame_size,
+ const struct dwarf_cfi_arch *arch);
+void dwarf_cfi_mod_free_rcu(struct mod_dwarf_cfi_index *idx);
+int dwarf_cfi_mod_eval(const struct mod_dwarf_cfi_index *idx, unsigned long ip,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+#endif
+
+#endif /* CONFIG_UNWIND_DWARF_CFI */
+
+#endif /* _LINUX_UNWIND_DWARF_CFI_H */
diff --git a/kernel/unwind/Makefile b/kernel/unwind/Makefile
index eae37bea54fd..f772fc607985 100644
--- a/kernel/unwind/Makefile
+++ b/kernel/unwind/Makefile
@@ -1 +1,11 @@
- obj-$(CONFIG_UNWIND_USER) += user.o deferred.o
+ifdef CONFIG_FUNCTION_TRACER
+CFLAGS_REMOVE_dwarf_cfi.o = $(CC_FLAGS_FTRACE)
+endif
+KASAN_SANITIZE_dwarf_cfi.o := n
+KCSAN_SANITIZE_dwarf_cfi.o := n
+UBSAN_SANITIZE_dwarf_cfi.o := n
+KMSAN_SANITIZE_dwarf_cfi.o := n
+KCOV_INSTRUMENT_dwarf_cfi.o := n
+
+obj-$(CONFIG_UNWIND_DWARF_CFI) += dwarf_cfi.o
+obj-$(CONFIG_UNWIND_USER) += user.o deferred.o
diff --git a/kernel/unwind/dwarf_cfi.c b/kernel/unwind/dwarf_cfi.c
new file mode 100644
index 000000000000..8b8004b1b8d1
--- /dev/null
+++ b/kernel/unwind/dwarf_cfi.c
@@ -0,0 +1,1923 @@
+// SPDX-License-Identifier: GPL-2.0-only OR MIT
+/*
+ * 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
+ * SP/FP/RA stack save offsets. Callee-saved GPR spills are decoded and ignored;
+ * general DWARF expressions and DW_EH_PE_indirect FDE/table pointer encodings
+ * are rejected (skipping CIE personality and LSDA fields without dereferencing).
+ */
+
+#include <linux/errno.h>
+#include <linux/kernel.h>
+#include <linux/kmsan-checks.h>
+#include <linux/limits.h>
+#include <linux/nospec.h>
+#include <linux/overflow.h>
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+#include <linux/mm.h>
+#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_SIGNED 0x08
+#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.
+ */
+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;
+};
+
+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;
+}
+
+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;
+ return 0;
+}
+
+static __always_inline bool cfi_stream_empty(const struct dwarf_cfi_stream *s,
+ bool is_user)
+{
+ return s->pos >= s->win_len && (!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->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,
+ bool is_user)
+{
+ size_t idx;
+
+ if (unlikely(s->pos >= s->win_len)) {
+ int err;
+
+ if (!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 = 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, bool is_user)
+{
+ u8 *out = dst;
+ size_t i;
+
+ if (likely(n <= s->win_len && s->pos <= s->win_len - n)) {
+ size_t idx = is_user ?
+ array_index_nospec(s->pos, DWARF_CFI_WIN_SIZE - n + 1) :
+ s->pos;
+
+ for (i = 0; i < n; i++)
+ out[i] = s->buf[idx + i];
+ s->pos = idx + n;
+ return 0;
+ }
+
+ if (!is_user)
+ return -EINVAL;
+
+ while (n--) {
+ int err = cfi_read_u8(s, out++, /*is_user=*/true);
+
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
+static __always_inline int cfi_skip_bytes(struct dwarf_cfi_stream *s, size_t n,
+ bool is_user)
+{
+ size_t avail;
+
+ if (!is_user) {
+ if (n > s->win_len - s->pos)
+ return -EINVAL;
+ s->pos += n;
+ return 0;
+ }
+
+ 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;
+ }
+ n -= in_win;
+ s->pos = s->win_len;
+ if (n > 0) {
+ int err = cfi_stream_refill(s);
+
+ if (err)
+ return err;
+ }
+ }
+ return 0;
+}
+
+static __always_inline int cfi_read_uleb128_u32_tail(struct dwarf_cfi_stream *s,
+ u32 val, u32 *out,
+ bool is_user)
+{
+ unsigned int shift = 7;
+
+ for (;;) {
+ u8 b;
+ int err = cfi_read_u8(s, &b, is_user);
+
+ 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 noinline noinstr int
+cfi_read_uleb128_u32_slow_kmem(struct dwarf_cfi_stream *s, u32 val, u32 *out)
+{
+ return cfi_read_uleb128_u32_tail(s, val, out, /*is_user=*/false);
+}
+
+static noinline int
+cfi_read_uleb128_u32_slow_user(struct dwarf_cfi_stream *s, u32 val, u32 *out)
+{
+ return cfi_read_uleb128_u32_tail(s, val, out, /*is_user=*/true);
+}
+
+static __always_inline int cfi_read_uleb128_u32(struct dwarf_cfi_stream *s,
+ u32 *out, bool is_user)
+{
+ u8 b;
+ int err = cfi_read_u8(s, &b, is_user);
+
+ if (unlikely(err))
+ return err;
+ if (likely(!(b & 0x80))) {
+ *out = b;
+ return 0;
+ }
+ return is_user ? cfi_read_uleb128_u32_slow_user(s, b & 0x7f, out) :
+ cfi_read_uleb128_u32_slow_kmem(s, b & 0x7f, out);
+}
+
+static __always_inline int cfi_read_sleb128_s32_tail(struct dwarf_cfi_stream *s,
+ u32 val, s32 *out,
+ bool is_user)
+{
+ unsigned int shift = 7;
+
+ for (;;) {
+ u8 b;
+ int err = cfi_read_u8(s, &b, is_user);
+
+ 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 noinline noinstr int
+cfi_read_sleb128_s32_slow_kmem(struct dwarf_cfi_stream *s, u32 val, s32 *out)
+{
+ return cfi_read_sleb128_s32_tail(s, val, out, /*is_user=*/false);
+}
+
+static noinline int
+cfi_read_sleb128_s32_slow_user(struct dwarf_cfi_stream *s, u32 val, s32 *out)
+{
+ return cfi_read_sleb128_s32_tail(s, val, out, /*is_user=*/true);
+}
+
+static __always_inline int cfi_read_sleb128_s32(struct dwarf_cfi_stream *s,
+ s32 *out, bool is_user)
+{
+ u8 b;
+ int err = cfi_read_u8(s, &b, is_user);
+
+ if (unlikely(err))
+ return err;
+ if (likely(!(b & 0x80))) {
+ *out = (b & 0x40) ? (s32)((u32)b | ~0x7fU) : (s32)b;
+ return 0;
+ }
+ return is_user ? cfi_read_sleb128_s32_slow_user(s, b & 0x7f, out) :
+ cfi_read_sleb128_s32_slow_kmem(s, b & 0x7f, out);
+}
+
+static __always_inline 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).
+ * @is_user: True when reading from a windowed user-space stream.
+ *
+ * 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 __always_inline int cfi_read_encoded_ptr(struct dwarf_cfi_stream *s,
+ u8 enc, u8 ws,
+ unsigned long datarel_base,
+ unsigned long *out,
+ bool is_user)
+{
+ 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, is_user);
+ 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, is_user);
+ if (err)
+ return err;
+ raw = get_unaligned_le16(buf);
+ break;
+ case DW_EH_PE_sdata2:
+ err = cfi_read_bytes(s, buf, 2, is_user);
+ if (err)
+ return err;
+ raw = (s16)get_unaligned_le16(buf);
+ break;
+ case DW_EH_PE_udata4:
+ err = cfi_read_bytes(s, buf, 4, is_user);
+ if (err)
+ return err;
+ raw = get_unaligned_le32(buf);
+ break;
+ case DW_EH_PE_sdata4:
+ err = cfi_read_bytes(s, buf, 4, is_user);
+ 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, is_user);
+ 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, is_user);
+ if (err)
+ return err;
+ raw = uval;
+ break;
+ }
+ case DW_EH_PE_sleb128: {
+ s32 sval;
+
+ err = cfi_read_sleb128_s32(s, &sval, is_user);
+ 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 __always_inline 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 __always_inline int
+cfi_parse_indirect_cfa_expr(struct dwarf_cfi_stream *s, u32 expr_len,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *row, bool is_user)
+{
+ struct dwarf_cfi_stream es;
+ u8 expr_buf[8], op0, op_end;
+ enum dwarf_cfi_base base;
+ s32 off;
+ int err;
+
+ if (expr_len < 3 || expr_len > 7)
+ return -EINVAL;
+ /* Prevent Spectre v1.1 speculative stack overflow of expr_buf[8] */
+ barrier_nospec();
+
+ err = cfi_read_bytes(s, expr_buf, expr_len, is_user);
+ if (err)
+ return err;
+
+ cfi_stream_init_kmem(&es, expr_buf, expr_len - 1);
+ err = cfi_read_u8(&es, &op0, /*is_user=*/false);
+ if (err)
+ return err;
+
+ if (arch->fp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->fp_reg))
+ base = DWARF_CFI_BASE_FP_INDIRECT;
+ else if (arch->sp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->sp_reg))
+ base = DWARF_CFI_BASE_SP_INDIRECT;
+ else
+ return -EINVAL;
+
+ err = cfi_read_sleb128_s32(&es, &off, /*is_user=*/false);
+ if (err || !cfi_stream_empty(&es, /*is_user=*/false))
+ return -EINVAL;
+
+ 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 __always_inline int
+cfi_parse_reg_expr(struct dwarf_cfi_stream *s, u32 reg, u32 expr_len,
+ const struct dwarf_cfi_arch *arch, u8 ra_reg,
+ struct dwarf_cfi_row *row, bool is_user)
+{
+ struct dwarf_cfi_stream es;
+ u8 expr_buf[8], op0;
+ enum dwarf_cfi_rule rule;
+ s32 off;
+ int err;
+
+ if (expr_len < 2 || expr_len > 6)
+ return -EINVAL;
+ /* Prevent Spectre v1.1 speculative stack overflow of expr_buf[8] */
+ barrier_nospec();
+
+ err = cfi_read_bytes(s, expr_buf, expr_len, is_user);
+ if (err)
+ return err;
+
+ cfi_stream_init_kmem(&es, expr_buf, expr_len);
+ err = cfi_read_u8(&es, &op0, /*is_user=*/false);
+ if (err)
+ return err;
+
+ if (arch->fp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->fp_reg))
+ rule = DWARF_CFI_RULE_FP_OFFSET;
+ else if (arch->sp_reg <= 31 && op0 == (u8)(DW_OP_breg0 + arch->sp_reg))
+ rule = DWARF_CFI_RULE_SP_OFFSET;
+ else
+ return -EINVAL;
+
+ err = cfi_read_sleb128_s32(&es, &off, /*is_user=*/false);
+ if (err || !cfi_stream_empty(&es, /*is_user=*/false))
+ 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 __always_inline 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;
+ } else if (reg == arch->sp_reg) {
+ row->sp_rule = rule;
+ row->sp_off = off;
+ }
+ /* All other general-purpose registers are intentionally ignored. */
+}
+
+static __always_inline 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;
+ } else if (reg == arch->sp_reg) {
+ row->sp_rule = cie_row->sp_rule;
+ row->sp_off = cie_row->sp_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).
+ * @is_user: True when reading from a windowed user-space stream.
+ *
+ * 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 __always_inline 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, bool is_user)
+{
+ 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, is_user) && (!check_pc || loc <= target_pc)) {
+ u8 op, hi, lo;
+ u32 reg, uval;
+ s32 sval, off;
+ int err;
+
+ err = cfi_read_u8(s, &op, is_user);
+ 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, is_user);
+ if (err)
+ return err;
+ if (lo == arch->fp_reg || lo == cie->ra_reg ||
+ lo == arch->sp_reg) {
+ err = cfi_factored_offset(uval, cie->data_align, &off);
+ if (err)
+ return err;
+ cfi_apply_reg_rule(lo, DWARF_CFI_RULE_OFFSET,
+ off, arch, cie->ra_reg, row);
+ }
+ continue;
+ }
+ 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, is_user);
+ 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, is_user);
+ 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, is_user);
+ 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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_uleb128_u32(s, &uval, is_user);
+ 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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_sleb128_s32(s, &sval, is_user);
+ 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, ®, is_user);
+ 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, is_user);
+ 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, is_user);
+ 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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_uleb128_u32(s, &uval, is_user);
+ if (err)
+ return err;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_sleb128_s32(s, &sval, is_user);
+ if (err)
+ return err;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_uleb128_u32(s, &uval, is_user);
+ if (err)
+ return err;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_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, ®, is_user);
+ 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, ®, is_user);
+ 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, ®, is_user);
+ 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, is_user);
+ 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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_uleb128_u32(s, &uval, is_user);
+ 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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_uleb128_u32(s, &uval, is_user);
+ 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, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_sleb128_s32(s, &sval, is_user);
+ 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, is_user);
+ if (err)
+ return err;
+ err = cfi_parse_indirect_cfa_expr(s, uval, arch, row,
+ is_user);
+ if (err)
+ return err;
+ break;
+
+ case DW_CFA_expression:
+ err = cfi_read_uleb128_u32(s, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_uleb128_u32(s, &uval, is_user);
+ 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,
+ is_user);
+ if (err)
+ return err;
+ break;
+ }
+ err = cfi_skip_bytes(s, uval, is_user);
+ if (err)
+ return err;
+ break;
+
+ case DW_CFA_val_expression:
+ err = cfi_read_uleb128_u32(s, ®, is_user);
+ if (err)
+ return err;
+ err = cfi_read_uleb128_u32(s, &uval, is_user);
+ 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, is_user);
+ 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.
+ * @is_user: True when reading from a windowed user-space stream.
+ *
+ * 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 __always_inline 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,
+ bool is_user)
+{
+ 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, is_user);
+ 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, is_user);
+ 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, is_user);
+ if (err)
+ return err;
+ err = cfi_read_u8(s, &seg_sz, is_user);
+ if (err)
+ return err;
+ if (addr_sz != arch->ws || seg_sz != 0)
+ return -EINVAL;
+ }
+
+ err = cfi_read_uleb128_u32(s, &cie->code_align, is_user);
+ if (err)
+ return err;
+ err = cfi_read_sleb128_s32(s, &cie->data_align, is_user);
+ if (err)
+ return err;
+ if (!cie->code_align || !cie->data_align)
+ return -EINVAL;
+
+ if (version == 1) {
+ u8 ra8;
+
+ err = cfi_read_u8(s, &ra8, is_user);
+ if (err)
+ return err;
+ ra_col = ra8;
+ } else {
+ err = cfi_read_uleb128_u32(s, &ra_col, is_user);
+ 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, is_user);
+ 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, is_user);
+ 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, is_user);
+ if (err)
+ return err;
+ break;
+ case 'P':
+ /* Personality encoding + pointer; skipped without deref */
+ err = cfi_read_u8(s, &enc, is_user);
+ 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, is_user);
+ 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),
+ is_user);
+ 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, is_user);
+}
+
+/**
+ * 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.
+ * @is_user: True when reading from windowed user-space streams.
+ *
+ * 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 __always_inline int
+dwarf_cfi_eval_fde_streams(struct dwarf_cfi_stream *cie_s,
+ struct dwarf_cfi_stream *fde_s,
+ unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row,
+ bool is_user)
+{
+ 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, is_user);
+ 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 {
+ u8 range_enc = (cie.fde_enc & DW_EH_PE_FORM) & ~DW_EH_PE_SIGNED;
+
+ err = cfi_read_encoded_ptr(fde_s, cie.fde_enc, arch->ws,
+ /*datarel_base=*/0, &init_loc,
+ is_user);
+ if (err)
+ return err;
+ err = cfi_read_encoded_ptr(fde_s, range_enc, arch->ws,
+ /*datarel_base=*/0, &pc_range,
+ is_user);
+ 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, is_user);
+ if (err)
+ return err;
+ err = cfi_skip_bytes(fde_s, aug_len, is_user);
+ 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, is_user);
+ if (err)
+ return err;
+
+ *out_row = row;
+ kmsan_unpoison_memory(out_row, sizeof(*out_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.
+ */
+noinstr int dwarf_cfi_eval_fde_kmem(const u8 *fde, const u8 *eh_start,
+ const u8 *eh_end, unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row)
+{
+ 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,
+ /*is_user=*/false);
+}
+
+static __always_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.
+ */
+noinstr 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, /*is_user=*/false);
+ if (err)
+ return err;
+ err = cfi_read_encoded_ptr(&hs, hdr[2], arch->ws, hdr_base,
+ &fde_cnt_ul, /*is_user=*/false);
+ 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 to construct a binary-search FDE lookup table for in-memory .eh_frame
+ * sections (such as loadable kernel modules) that lack a linker-generated
+ * .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, /*is_user=*/false);
+ 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, /*is_user=*/false);
+ 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;
+ }
+
+ if (entries && count)
+ kmsan_unpoison_memory(entries, count * sizeof(*entries));
+ *out_count = count;
+ kmsan_unpoison_memory(out_count, sizeof(*out_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, /*is_user=*/false);
+ if (err)
+ return err;
+ err = cfi_read_encoded_ptr(&hs, hdr_prefix[2], arch->ws, hdr_uaddr,
+ &fde_cnt_ul, /*is_user=*/false);
+ 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,
+ /*is_user=*/true);
+}
+
+#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 = kvmalloc(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)) {
+ kvfree(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)
+ kvfree_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.
+ */
+noinstr 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 */
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 02/30] unwind: Add KUnit tests for Minimal DWARF CFI interpreter
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 01/30] unwind: Add Minimal DWARF CFI bytecode interpreter Ian Rogers
@ 2026-11-25 6:14 ` Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 03/30] unwind_user: Support Minimal DWARF CFI user-space unwinding Ian Rogers
` (27 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:14 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, llvm, 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 built-in KUnit test suite (CONFIG_UNWIND_DWARF_CFI_KUNIT_TEST) in
kernel/unwind/dwarf_cfi_kunit.c exercising the Minimal DWARF CFI
interpreter across:
- SP-based and FP-based stack frames and ignored callee-saved GPR spills
- Shrink-wrapped DW_CFA_remember_state / DW_CFA_restore_state stacks
- DRAP stack realignment and 64-bit / 32-bit vdso32 sigreturn frames
- ARM64 PAC-RET (DW_CFA_AARCH64_negate_ra_state) and RISC-V leaf frames
- Malformed bytecode, negative sdata4 range, and overflow rejections
- Linear .eh_frame scanning (dwarf_cfi_scan_eh_frame_kmem()) and live
CALLER_ADDR0/1 and kernel stack walks
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/Kconfig | 10 +
kernel/unwind/Makefile | 1 +
kernel/unwind/dwarf_cfi_kunit.c | 767 ++++++++++++++++++++++++++++++++
3 files changed, 778 insertions(+)
create mode 100644 kernel/unwind/dwarf_cfi_kunit.c
diff --git a/arch/Kconfig b/arch/Kconfig
index 5ed64e6cc72e..03399120aa8f 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -506,6 +506,16 @@ config UNWIND_TABLES
config UNWIND_DWARF_CFI
bool
+config UNWIND_DWARF_CFI_KUNIT_TEST
+ bool "KUnit tests for Minimal DWARF CFI unwinder" if !KUNIT_ALL_TESTS
+ depends on KUNIT=y && UNWIND_DWARF_CFI
+ default KUNIT_ALL_TESTS
+ help
+ Builds KUnit tests for the Minimal DWARF Call Frame Information (CFI)
+ bytecode interpreter and stack unwinder. Covers SP/FP-based frames,
+ callee-saved GPR opcode skipping, shrink-wrapped state stacks, DRAP
+ stack realignment, malformed bytecode rejections, and live walks.
+
config UNWIND_USER
bool
diff --git a/kernel/unwind/Makefile b/kernel/unwind/Makefile
index f772fc607985..73a1ccc2ad77 100644
--- a/kernel/unwind/Makefile
+++ b/kernel/unwind/Makefile
@@ -9,3 +9,4 @@ KCOV_INSTRUMENT_dwarf_cfi.o := n
obj-$(CONFIG_UNWIND_DWARF_CFI) += dwarf_cfi.o
obj-$(CONFIG_UNWIND_USER) += user.o deferred.o
+obj-$(CONFIG_UNWIND_DWARF_CFI_KUNIT_TEST) += dwarf_cfi_kunit.o
diff --git a/kernel/unwind/dwarf_cfi_kunit.c b/kernel/unwind/dwarf_cfi_kunit.c
new file mode 100644
index 000000000000..5e8e0ff2ec36
--- /dev/null
+++ b/kernel/unwind/dwarf_cfi_kunit.c
@@ -0,0 +1,767 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * KUnit tests for Minimal DWARF Call Frame Information (CFI) unwinder.
+ */
+
+#include <kunit/test.h>
+#include <linux/ftrace.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_i386_arch = {
+ .ws = 4,
+ .sp_reg = 4, /* esp */
+ .fp_reg = 5, /* ebp */
+ .ra_reg = 8, /* eip */
+};
+
+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;
+ }
+ if (cie_insns_len) {
+ 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;
+ if ((fde_enc & 0x07) == 0x03 || (arch->ws == 4 && (fde_enc & 0x0f) == 0)) {
+ put_unaligned_le32((u32)init_pc, p);
+ p += 4;
+ put_unaligned_le32((u32)pc_range, p);
+ p += 4;
+ } else {
+ put_unaligned_le64(init_pc, p);
+ p += 8;
+ put_unaligned_le64(pc_range, p);
+ p += 8;
+ }
+ if (aug[0] == 'z')
+ *p++ = 0;
+ if (fde_insns_len) {
+ 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,
+ };
+ /*
+ * Matches 32-bit x86 vdso32 __kernel_rt_sigreturn ("zRS", data_align=-4):
+ * DW_CFA_def_cfa esp(4), 160 (&sigcontext)
+ * DW_CFA_offset_extended_sf eip(8), -14 (+56)
+ * DW_CFA_offset_extended_sf esp(4), -7 (+28)
+ * DW_CFA_offset_extended_sf ebp(5), -6 (+24)
+ */
+ static const u8 vdso32_cie[] = { 0x0c, 4, 4 };
+ static const u8 vdso32_sig_insns[] = {
+ 0x0c, 4, 0xa0, 0x01,
+ 0x11, 8, 0x72,
+ 0x11, 4, 0x79,
+ 0x11, 5, 0x7a,
+ };
+ 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);
+
+ build_arch_eh_blob(&blob, &test_i386_arch, /*code_align=*/1,
+ /*data_align_sleb=*/0x7c, "zRS", /*fde_enc=*/0x03,
+ vdso32_cie, sizeof(vdso32_cie), /*init_pc=*/0x2d00,
+ /*pc_range=*/0x08, vdso32_sig_insns,
+ sizeof(vdso32_sig_insns));
+ KUNIT_ASSERT_EQ(test, 0,
+ dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+ blob.buf + blob.total_len, 0x2d00,
+ &test_i386_arch, &row));
+ KUNIT_EXPECT_TRUE(test, row.signal);
+ KUNIT_EXPECT_EQ(test, row.cfa_base, DWARF_CFI_BASE_SP);
+ KUNIT_EXPECT_EQ(test, row.cfa_off, 160);
+ KUNIT_EXPECT_EQ(test, row.sp_rule, DWARF_CFI_RULE_OFFSET);
+ KUNIT_EXPECT_EQ(test, row.sp_off, 28);
+ KUNIT_EXPECT_EQ(test, row.fp_rule, DWARF_CFI_RULE_OFFSET);
+ KUNIT_EXPECT_EQ(test, row.fp_off, 24);
+ KUNIT_EXPECT_EQ(test, row.ra_rule, DWARF_CFI_RULE_OFFSET);
+ KUNIT_EXPECT_EQ(test, row.ra_off, 56);
+}
+
+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));
+
+ /*
+ * 9. Slow-path DW_EH_PE_sdata4 (0x0b) FDE pc_range with bit 31 set
+ * (0xffffffe0) must be decoded unsigned rather than sign-extending to
+ * 0xffffffffffffffe0 on 64-bit platforms.
+ */
+#ifdef CONFIG_64BIT
+ build_test_eh_blob(&blob, "zR", /*fde_enc=*/0x0b,
+ /*init_pc=*/0x10, /*pc_range=*/0xffffffe0UL,
+ /*fde_insns=*/NULL, /*fde_insns_len=*/0);
+ KUNIT_EXPECT_EQ(test, -ENOENT,
+ dwarf_cfi_eval_fde_kmem(blob.buf + blob.fde_off, blob.buf,
+ blob.buf + blob.total_len,
+ 0x100000000UL, &test_x86_64_arch,
+ &row));
+#endif
+}
+
+static void test_cfi_scan_eh_frame(struct kunit *test)
+{
+ const struct dwarf_cfi_arch native_arch = {
+ .ws = sizeof(unsigned long),
+ .sp_reg = 7,
+ .fp_reg = 6,
+ .ra_reg = 16,
+ };
+ static const u8 cie_insns[] = { 0x0c, 7, sizeof(unsigned long) };
+ struct test_eh_blob b1, b2;
+ struct eh_frame_hdr_entry entries[2];
+ u8 combined[512];
+ unsigned long base;
+ unsigned int count = 0;
+ size_t fde2_len;
+
+ base = (unsigned long)combined;
+ build_arch_eh_blob(&b1, &native_arch, /*code_align=*/1,
+ /*data_align_sleb=*/0x78, "zR", /*fde_enc=*/0x00,
+ cie_insns, sizeof(cie_insns), base + 0x100, 0x20,
+ /*fde_insns=*/NULL, /*fde_insns_len=*/0);
+ build_arch_eh_blob(&b2, &native_arch, /*code_align=*/1,
+ /*data_align_sleb=*/0x78, "zR", /*fde_enc=*/0x00,
+ cie_insns, sizeof(cie_insns), base + 0x200, 0x30,
+ /*fde_insns=*/NULL, /*fde_insns_len=*/0);
+
+ memset(combined, 0, sizeof(combined));
+ memcpy(combined, b1.buf, b1.total_len);
+ fde2_len = b2.total_len - b2.fde_off;
+ memcpy(combined + b1.total_len, b2.buf + b2.fde_off, fde2_len);
+ /* Point second FDE's CIE_pointer back to the shared CIE at offset 0 */
+ put_unaligned_le32((u32)(b1.total_len + 4), combined + b1.total_len + 4);
+
+ KUNIT_ASSERT_EQ(test, 0,
+ dwarf_cfi_scan_eh_frame_kmem(combined,
+ b1.total_len + fde2_len + 4,
+ &native_arch, base,
+ /*entries=*/NULL,
+ /*max_entries=*/0, &count));
+ KUNIT_EXPECT_EQ(test, count, 2U);
+
+ KUNIT_EXPECT_EQ(test, -ENOSPC,
+ dwarf_cfi_scan_eh_frame_kmem(combined,
+ b1.total_len + fde2_len + 4,
+ &native_arch, base, entries,
+ /*max_entries=*/1, &count));
+
+ KUNIT_ASSERT_EQ(test, 0,
+ dwarf_cfi_scan_eh_frame_kmem(combined,
+ b1.total_len + fde2_len + 4,
+ &native_arch, base, entries,
+ ARRAY_SIZE(entries), &count));
+ KUNIT_EXPECT_EQ(test, count, 2U);
+ KUNIT_EXPECT_EQ(test, entries[0].start_off, 0x100);
+ KUNIT_EXPECT_EQ(test, entries[0].fde_off, (s32)b1.fde_off);
+ KUNIT_EXPECT_EQ(test, entries[1].start_off, 0x200);
+ KUNIT_EXPECT_EQ(test, entries[1].fde_off, (s32)b1.total_len);
+}
+
+#ifdef CONFIG_STACKTRACE
+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;
+ unsigned long caller_addr0;
+ unsigned long caller_addr1;
+};
+
+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->caller_addr0 = CALLER_ADDR0;
+ ctx->caller_addr1 = CALLER_ADDR1;
+ 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);
+ KUNIT_EXPECT_TRUE(test, ip_within(ctx.caller_addr0, ctx.realign_ip));
+ if (ctx.caller_addr1)
+ KUNIT_EXPECT_TRUE(test, ip_within(ctx.caller_addr1, ctx.mid_ip));
+
+ 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);
+ }
+}
+#else
+static void test_live_kernel_stack_walk(struct kunit *test)
+{
+ kunit_skip(test, "CONFIG_STACKTRACE disabled");
+}
+#endif /* CONFIG_STACKTRACE */
+
+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_cfi_scan_eh_frame),
+ 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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 03/30] unwind_user: Support Minimal DWARF CFI user-space unwinding
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 01/30] unwind: Add Minimal DWARF CFI bytecode interpreter Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 02/30] unwind: Add KUnit tests for Minimal DWARF CFI interpreter Ian Rogers
@ 2026-11-25 6:14 ` Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 04/30] x86: unwind_user: Support Minimal DWARF CFI user unwinding Ian Rogers
` (26 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:14 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, llvm, 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.
Key design details:
- Find the executable VMA and its base ELF mapping (vm_pgoff == 0)
under mmap_read_lock_killable(), then drop mmap_read_lock() before
issuing any faultable copy_from_user() reads.
- Cache VMA -> PT_GNU_EH_FRAME lookups (including negative lookups for
anonymous/JIT VMAs so unwind_user_next() falls back per frame to FP)
in a 4-slot per-walk cache on struct unwind_user_state.
- Track stack-pointer validity (state->sp_valid and
unwind_user_fp_sets_sp()) across mixed CFI -> FP -> CFI walks so
architectures whose FP step does not recover exact caller SP reject
SP-based rules until an outer FP-based FDE or sigreturn restores SP,
and support signal-frame SP recovery from *(CFA + sp_off).
- Provide overridable unwind_user_frame_pointer() (guarded by
CONFIG_HAVE_UNWIND_USER_FP), unwind_user_fp_sets_sp(), and
unwind_user_sigreturn() hooks alongside unwind_user_link_register()
and unwind_user_strip_pac(), and allow up to UNWIND_USER_MAX_SIGNALS
signal frames per walk to switch stacks (SA_ONSTACK).
- Support link-register leaf frames, DRAP/sigframe indirect CFA rules,
and clean bottom-of-stack termination on DW_CFA_undefined or zero RA.
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/Kconfig | 5 +
include/linux/unwind_user.h | 104 ++++++++
include/linux/unwind_user_types.h | 101 +++++++-
kernel/unwind/Makefile | 1 +
kernel/unwind/user.c | 169 +++++++++++--
kernel/unwind/user_cfi.c | 392 ++++++++++++++++++++++++++++++
6 files changed, 753 insertions(+), 19 deletions(-)
create mode 100644 kernel/unwind/user_cfi.c
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/include/linux/unwind_user.h b/include/linux/unwind_user.h
index 64618618febd..5a05182825a5 100644
--- a/include/linux/unwind_user.h
+++ b/include/linux/unwind_user.h
@@ -2,6 +2,7 @@
#ifndef _LINUX_UNWIND_USER_H
#define _LINUX_UNWIND_USER_H
+#include <linux/ptrace.h>
#include <linux/unwind_user_types.h>
#include <asm/unwind_user.h>
@@ -16,6 +17,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 +30,103 @@ 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) when
+ * CONFIG_HAVE_UNWIND_USER_FP is enabled, or 0 otherwise.
+ */
+static inline unsigned long unwind_user_frame_pointer(struct pt_regs *regs)
+{
+#ifdef CONFIG_HAVE_UNWIND_USER_FP
+ return frame_pointer(regs);
+#else
+ return 0;
+#endif
+}
+
+#define unwind_user_frame_pointer unwind_user_frame_pointer
+#endif
+
+#ifndef unwind_user_fp_sets_sp
+/**
+ * unwind_user_fp_sets_sp() - Whether FP unwinding recovers exact caller SP
+ *
+ * Return: true on architectures where the frame record resides at a fixed
+ * offset from the caller's stack pointer (e.g. x86 and RISC-V), or false when
+ * it resides at the bottom of the callee's frame (e.g. ARM64).
+ */
+static inline bool unwind_user_fp_sets_sp(void)
+{
+ return true;
+}
+
+#define unwind_user_fp_sets_sp unwind_user_fp_sets_sp
+#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..b78b86f8d423 100644
--- a/include/linux/unwind_user_types.h
+++ b/include/linux/unwind_user_types.h
@@ -4,41 +4,132 @@
#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.
+ * @sp_off: Byte offset from CFA to saved caller SP when @sp_from_cfa is true.
+ * @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).
+ * @sp_from_cfa: True if saved SP is located at *(cfa + @sp_off) (e.g. vdso32
+ * sigreturn frame where CFA points at sigcontext).
+ * @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 sp_off;
s32 ra_off;
s32 fp_off;
bool use_fp;
+ bool cfa_indirect;
+ bool sp_from_cfa;
+ 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.
+ * @sp_valid: True if @sp holds the exact stack pointer of the current frame;
+ * false after an architectural FP step that only establishes a lower
+ * bound on the caller's SP.
+ * @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 sp_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..4a3db15970f2 100644
--- a/kernel/unwind/user.c
+++ b/kernel/unwind/user.c
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: GPL-2.0
/*
-* Generic interfaces for unwinding user space
-*/
+ * Generic interfaces for unwinding user space.
+ */
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/sched/task_stack.h>
@@ -11,14 +11,25 @@
#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;
+
#ifdef CONFIG_COMPAT
if (ws == sizeof(int)) {
unsigned int data;
int ret = get_user(data, (unsigned int __user *)addr);
+
*word = data;
return ret;
}
@@ -26,62 +37,147 @@ 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, SP, 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 stack 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 cfa, fp, ra;
+ unsigned long old_sp = state->sp;
+ unsigned long cfa, new_sp, 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 {
+ if (!state->sp_valid)
+ return -EINVAL;
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;
+ }
+
+ if (frame->sp_from_cfa) {
+ if (get_user_word(&new_sp, cfa, frame->sp_off, state->ws))
+ return -EINVAL;
+ if (!signal && new_sp <= state->sp)
+ return -EINVAL;
+ } else {
+ new_sp = cfa;
+ }
state->ip = ra;
- state->sp = cfa;
- if (frame->fp_off)
+ state->sp = new_sp;
+ 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);
+ int ret;
if (state->topmost && unwind_user_at_function_start(regs)) {
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);
+
+ ret = unwind_user_next_common(state, &fp_entry_frame,
+ /*signal=*/false);
+ if (!ret)
+ state->sp_valid = true;
+ return ret;
}
const struct unwind_user_frame fp_frame = {
ARCH_INIT_USER_FP_FRAME(state->ws)
};
- return unwind_user_next_common(state, &fp_frame);
+
+ ret = unwind_user_next_common(state, &fp_frame, /*signal=*/false);
+ if (!ret)
+ state->sp_valid = unwind_user_fp_sets_sp();
+ return ret;
}
+/**
+ * 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 +186,31 @@ 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->sp_valid = true;
+ 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)) {
+ state->sp_valid = true;
+ return 0;
+ }
+ if (state->done)
+ break;
+ continue;
+ }
case UNWIND_USER_TYPE_FP:
if (!unwind_user_next_fp(state))
return 0;
@@ -112,6 +228,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,22 +249,37 @@ 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;
return -EINVAL;
}
+ state->sp_valid = true;
state->topmost = true;
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..e1727b07ce72
--- /dev/null
+++ b/kernel/unwind/user_cfi.c
@@ -0,0 +1,392 @@
+// 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)
+{
+ struct elf64_hdr ehdr;
+ unsigned long load_bias = 0;
+ bool have_load0 = false, have_eh = false;
+ u64 eh_vaddr = 0;
+ u64 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(struct elf64_phdr) ||
+ !ehdr.e_phnum || ehdr.e_phnum > USER_CFI_MAX_PHDRS)
+ return -EINVAL;
+
+ for (i = 0; i < ehdr.e_phnum; i++) {
+ struct 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)
+{
+ struct elf32_hdr ehdr;
+ unsigned long load_bias = 0;
+ bool have_load0 = false, have_eh = false;
+ u32 eh_vaddr = 0;
+ u32 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(struct elf32_phdr) ||
+ !ehdr.e_phnum || ehdr.e_phnum > USER_CFI_MAX_PHDRS)
+ return -EINVAL;
+
+ for (i = 0; i < ehdr.e_phnum; i++) {
+ struct 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
+ * (including cached negative entries for non-ELF/JIT VMAs), -EINTR if killed
+ * while waiting for mmap_lock, -EFAULT on user copy fault, or -EINVAL if
+ * current->mm is absent, @state->ws is unsupported, or the mapped ELF header
+ * is malformed.
+ */
+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 (!state->sp_valid &&
+ (row.cfa_base == DWARF_CFI_BASE_SP ||
+ row.cfa_base == DWARF_CFI_BASE_SP_INDIRECT ||
+ row.ra_rule == DWARF_CFI_RULE_SP_OFFSET ||
+ row.fp_rule == DWARF_CFI_RULE_SP_OFFSET))
+ 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));
+ if (row.sp_rule == DWARF_CFI_RULE_OFFSET) {
+ out_frame->sp_from_cfa = true;
+ out_frame->sp_off = row.sp_off;
+ } else if (row.sp_rule != DWARF_CFI_RULE_SAME) {
+ return -EINVAL;
+ }
+ 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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 04/30] x86: unwind_user: Support Minimal DWARF CFI user unwinding
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (2 preceding siblings ...)
2026-11-25 6:14 ` [RFC PATCH v2 03/30] unwind_user: Support Minimal DWARF CFI user-space unwinding Ian Rogers
@ 2026-11-25 6:14 ` Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 05/30] scripts: Add min_eh_frame build-time .eh_frame minifier Ian Rogers
` (25 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:14 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Provide unwind_user_cfi_arch() in arch/x86/include/asm/unwind_user.h for
both 64-bit x86-64 (%rsp=7, %rbp=6, %rip=16) and 32-bit IA-32 compat
(%esp=4, %ebp=5, %eip=8) user tasks, and select HAVE_UNWIND_USER_CFI on
X86_64.
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/x86/Kconfig | 1 +
arch/x86/include/asm/unwind_user.h | 47 ++++++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
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);
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 05/30] scripts: Add min_eh_frame build-time .eh_frame minifier
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (3 preceding siblings ...)
2026-11-25 6:14 ` [RFC PATCH v2 04/30] x86: unwind_user: Support Minimal DWARF CFI user unwinding Ian Rogers
@ 2026-11-25 6:14 ` Ian Rogers
2026-11-25 6:14 ` [RFC PATCH v2 06/30] kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY object pass Ian Rogers
` (24 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:14 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, llvm, 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, built under CONFIG_UNWINDER_DWARF_CFI_MINIFY)
supporting x86-64, ARM64, and RISC-V with explicit little-endian ELF
field accessors for big-endian cross-build hosts and zero external
library dependencies.
scripts/min_eh_frame rewrites .eh_frame (both SHT_PROGBITS and
SHT_X86_64_UNWIND) in place to:
- Strip callee-saved GPR spill/restore opcodes (%rbx/%r12-%r15 on
x86-64, x19-x28 on ARM64, s1-s11 on RISC-V) and DW_CFA_GNU_args_size
while preserving CFA, SP, FP, RA, shrink-wrap state-stack, DRAP, and
ARM64 DW_CFA_AARCH64_negate_ra_state (0x2d) transitions.
- Normalize CIEs and coalesce consecutive unrelocated PC-advance
instructions while remapping sorted .rela.eh_frame relocations
(including RISC-V R_RISCV_SET6/SUB6 and ADD32/SUB32 relaxation pairs).
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/Kconfig | 10 +
scripts/.gitignore | 1 +
scripts/Makefile | 1 +
scripts/min_eh_frame.c | 1845 ++++++++++++++++++++++++++++++++++++++++
4 files changed, 1857 insertions(+)
create mode 100644 scripts/min_eh_frame.c
diff --git a/arch/Kconfig b/arch/Kconfig
index 340a7ecbfc68..baeba9b307fe 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 UNWIND_TABLES && UNWIND_DWARF_CFI && !FRAME_POINTER
+ default y
+ help
+ Strip unneeded callee-saved register opcodes and coalesce PC-advance
+ bytecodes in .eh_frame sections at build time, reducing kernel unwind
+ table memory usage while ensuring only Minimal DWARF CFA bytecodes
+ remain in vmlinux and modules.
+
config HAVE_PERF_REGS
bool
help
diff --git a/scripts/.gitignore b/scripts/.gitignore
index 700456543910..cf4d1c60ce65 100644
--- a/scripts/.gitignore
+++ b/scripts/.gitignore
@@ -5,6 +5,7 @@
/generate_rust_target
/insert-sys-cert
/kallsyms
+/min_eh_frame
/module.lds
/recordmcount
/rustdoc_test_builder
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/min_eh_frame.c b/scripts/min_eh_frame.c
new file mode 100644
index 000000000000..55b07b11c635
--- /dev/null
+++ b/scripts/min_eh_frame.c
@@ -0,0 +1,1845 @@
+// 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 sp_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 sp_rule; /* 0=same, 1=cfa_off, 3=undef */
+ 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 uint64_t get_le64(const void *vp)
+{
+ const uint8_t *p = vp;
+
+ return (uint64_t)get_le32(p) | ((uint64_t)get_le32(p + 4) << 32);
+}
+
+static void put_le16(void *vp, uint16_t v)
+{
+ uint8_t *p = vp;
+
+ p[0] = (uint8_t)v;
+ p[1] = (uint8_t)(v >> 8);
+}
+
+static void put_le32(void *vp, uint32_t v)
+{
+ uint8_t *p = vp;
+
+ p[0] = (uint8_t)v;
+ p[1] = (uint8_t)(v >> 8);
+ p[2] = (uint8_t)(v >> 16);
+ p[3] = (uint8_t)(v >> 24);
+}
+
+static void put_le64(void *vp, uint64_t v)
+{
+ uint8_t *p = vp;
+
+ put_le32(p, (uint32_t)v);
+ put_le32(p + 4, (uint32_t)(v >> 32));
+}
+
+static uint16_t r16(const uint16_t *p)
+{
+ return get_le16((const uint8_t *)p);
+}
+
+static uint32_t r32(const uint32_t *p)
+{
+ return get_le32((const uint8_t *)p);
+}
+
+static uint64_t r64(const uint64_t *p)
+{
+ return get_le64(p);
+}
+
+static void w64(uint64_t *p, uint64_t v)
+{
+ put_le64(p, v);
+}
+
+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->sp_rule != b->sp_rule || 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->sp_rule == 1 && a->sp_off != b->sp_off)
+ 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 { \
+ size_t _raw_len = (raw_len); \
+ \
+ 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 { \
+ size_t _op_pos = (op_pos); \
+ size_t _op_len = (op_len); \
+ \
+ 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 ||
+ lo == arch->sp_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);
+ } else if (lo == arch->sp_reg &&
+ (row.sp_rule != 1 || row.sp_off != off)) {
+ row.sp_rule = 1;
+ row.sp_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);
+ } else if (lo == arch->sp_reg &&
+ (row.sp_rule != cie_base.sp_rule ||
+ (cie_base.sp_rule == 1 &&
+ row.sp_off != cie_base.sp_off))) {
+ row.sp_rule = cie_base.sp_rule;
+ row.sp_off = cie_base.sp_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, ®) ||
+ 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, ®) ||
+ 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 > 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, ®) ||
+ read_uleb128(insns, &pos, end, &uval))
+ goto out;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_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 if (reg == cie->ra_reg) {
+ row.ra_rule = 1;
+ row.ra_off = off;
+ } else {
+ row.sp_rule = 1;
+ row.sp_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, ®) ||
+ read_sleb128(insns, &pos, end, &sval))
+ goto out;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_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 if (reg == cie->ra_reg) {
+ row.ra_rule = 1;
+ row.ra_off = off;
+ } else {
+ row.sp_rule = 1;
+ row.sp_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, ®) ||
+ read_uleb128(insns, &pos, end, &uval))
+ goto out;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_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 if (reg == cie->ra_reg) {
+ row.ra_rule = 1;
+ row.ra_off = off;
+ } else {
+ row.sp_rule = 1;
+ row.sp_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, ®))
+ 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);
+ } else if (reg == arch->sp_reg) {
+ row.sp_rule = cie_base.sp_rule;
+ row.sp_off = cie_base.sp_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, ®))
+ goto out;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_reg) {
+ if (reg == arch->fp_reg) {
+ row.fp_rule = 3;
+ row.fp_off = 0;
+ } else if (reg == cie->ra_reg) {
+ row.ra_rule = 3;
+ row.ra_off = 0;
+ } else {
+ row.sp_rule = 3;
+ row.sp_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, ®))
+ goto out;
+ if (reg == arch->fp_reg || reg == cie->ra_reg ||
+ reg == arch->sp_reg) {
+ if (reg == arch->fp_reg) {
+ row.fp_rule = 0;
+ row.fp_off = 0;
+ } else if (reg == cie->ra_reg) {
+ row.ra_rule = 0;
+ row.ra_off = 0;
+ } else {
+ row.sp_rule = 0;
+ row.sp_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, ®) ||
+ 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, ®) ||
+ 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, ®) ||
+ 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, ®) ||
+ 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)
+{
+ uint16_t shndx = r16(&sym->st_shndx);
+
+ if (shndx == SHN_XINDEX)
+ return shndx_tab && sym_i < nshndx &&
+ r32(&shndx_tab[sym_i]) == eh_idx;
+ if (shndx >= SHN_LORESERVE)
+ return false;
+ return 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;
+ uint64_t shoff, shstr_off, shstr_size, eh_shoff, eh_align;
+ uint16_t e_machine;
+ 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 (r16(&ehdr->e_type) != ET_REL)
+ return 0;
+
+ e_machine = r16(&ehdr->e_machine);
+ if (e_machine == EM_X86_64)
+ arch = (struct arch_cfg){ 8, 7, 6, 16 };
+ else if (e_machine == EM_AARCH64)
+ arch = (struct arch_cfg){ 8, 31, 29, 30 };
+ else if (e_machine == EM_RISCV)
+ arch = (struct arch_cfg){ 8, 2, 8, 1 };
+ else
+ return 0;
+
+ shoff = r64(&ehdr->e_shoff);
+ if (!shoff || (shoff & 7) || shoff > file_size ||
+ file_size - shoff < sizeof(Elf64_Shdr))
+ return 0;
+ if (r16(&ehdr->e_shentsize) != sizeof(Elf64_Shdr))
+ return -1;
+
+ shdrs = (Elf64_Shdr *)(map + shoff);
+ shnum = r16(&ehdr->e_shnum) ? r16(&ehdr->e_shnum) :
+ (uint32_t)r64(&shdrs[0].sh_size);
+ if (!shnum ||
+ (size_t)shnum > (file_size - shoff) / sizeof(Elf64_Shdr))
+ return -1;
+ shstrndx = (r16(&ehdr->e_shstrndx) != SHN_XINDEX) ?
+ r16(&ehdr->e_shstrndx) : r32(&shdrs[0].sh_link);
+
+ if (!shstrndx || shstrndx >= shnum)
+ return -1;
+ shstr_off = r64(&shdrs[shstrndx].sh_offset);
+ shstr_size = r64(&shdrs[shstrndx].sh_size);
+ if (shstr_off > file_size || shstr_size == 0 ||
+ shstr_size > file_size - shstr_off)
+ return -1;
+ shstrtab = (const char *)(map + shstr_off);
+
+ for (uint32_t i = 1; i < shnum; i++) {
+ uint32_t sh_type = r32(&shdrs[i].sh_type);
+ uint32_t nm_off = r32(&shdrs[i].sh_name);
+
+ if ((sh_type == SHT_PROGBITS ||
+ 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 || r64(&eh_shdr->sh_size) == 0)
+ return 0;
+ eh_shoff = r64(&eh_shdr->sh_offset);
+ eh_in_len = (size_t)r64(&eh_shdr->sh_size);
+ eh_align = r64(&eh_shdr->sh_addralign);
+ if (eh_shoff > file_size || eh_in_len > file_size - eh_shoff ||
+ eh_align > 16 || (eh_align & (eh_align - 1)) != 0)
+ return -1;
+
+ for (uint32_t i = 1; i < shnum; i++) {
+ if (r32(&shdrs[i].sh_type) == SHT_RELA &&
+ r32(&shdrs[i].sh_info) == eh_idx) {
+ rela_shdr = &shdrs[i];
+ break;
+ }
+ }
+
+ if (rela_shdr && r32(&rela_shdr->sh_link) > 0 &&
+ r32(&rela_shdr->sh_link) < shnum &&
+ r32(&shdrs[r32(&rela_shdr->sh_link)].sh_type) == SHT_SYMTAB) {
+ sym_idx = r32(&rela_shdr->sh_link);
+ sym_shdr = &shdrs[sym_idx];
+ } else {
+ for (uint32_t i = 1; i < shnum; i++) {
+ if (r32(&shdrs[i].sh_type) == SHT_SYMTAB) {
+ sym_idx = i;
+ sym_shdr = &shdrs[i];
+ break;
+ }
+ }
+ }
+
+ if (sym_shdr && r64(&sym_shdr->sh_size) > 0) {
+ uint64_t sym_off = r64(&sym_shdr->sh_offset);
+ uint64_t sym_sz = r64(&sym_shdr->sh_size);
+
+ if ((sym_off & 7) || sym_off > file_size ||
+ sym_sz > file_size - sym_off ||
+ r64(&sym_shdr->sh_entsize) != sizeof(Elf64_Sym) ||
+ (sym_sz % sizeof(Elf64_Sym)) != 0)
+ return -1;
+ syms = (Elf64_Sym *)(map + sym_off);
+ nsyms = (size_t)(sym_sz / sizeof(Elf64_Sym));
+
+ for (uint32_t i = 1; i < shnum; i++) {
+ if (r32(&shdrs[i].sh_type) == SHT_SYMTAB_SHNDX &&
+ r32(&shdrs[i].sh_link) == sym_idx) {
+ uint64_t xoff = r64(&shdrs[i].sh_offset);
+ uint64_t xsz = r64(&shdrs[i].sh_size);
+
+ if ((xoff & 3) || xoff > file_size ||
+ xsz > file_size - xoff ||
+ r64(&shdrs[i].sh_entsize) != sizeof(uint32_t) ||
+ xsz != nsyms * sizeof(uint32_t))
+ return -1;
+ shndx_tab = (const uint32_t *)(map + xoff);
+ 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;
+ uint64_t o_off, o_sz;
+
+ if (&shdrs[i] == rela_shdr ||
+ r32(&shdrs[i].sh_type) != SHT_RELA ||
+ r32(&shdrs[i].sh_link) != sym_idx ||
+ r64(&shdrs[i].sh_size) == 0)
+ continue;
+ o_off = r64(&shdrs[i].sh_offset);
+ o_sz = r64(&shdrs[i].sh_size);
+ if ((o_off & 7) || o_off > file_size ||
+ o_sz > file_size - o_off ||
+ r64(&shdrs[i].sh_entsize) != sizeof(Elf64_Rela) ||
+ (o_sz % sizeof(Elf64_Rela)) != 0)
+ return -1;
+ other = (const Elf64_Rela *)(map + o_off);
+ nother = (size_t)(o_sz / sizeof(Elf64_Rela));
+ for (size_t r = 0; r < nother; r++) {
+ uint32_t si = ELF64_R_SYM(r64(&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_shoff;
+ if (rela_shdr && r64(&rela_shdr->sh_size) > 0) {
+ struct indexed_rela *idx_relas;
+ const Elf64_Rela *raw_relas;
+ uint64_t r_off = r64(&rela_shdr->sh_offset);
+ uint64_t r_sz = r64(&rela_shdr->sh_size);
+
+ if ((r_off & 7) || r_off > file_size ||
+ r_sz > file_size - r_off ||
+ r64(&rela_shdr->sh_entsize) != sizeof(Elf64_Rela) ||
+ (r_sz % sizeof(Elf64_Rela)) != 0)
+ return -1;
+ nrelas = (size_t)(r_sz / 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 + r_off);
+ for (size_t i = 0; i < nrelas; i++) {
+ idx_relas[i].rela.r_offset = r64(&raw_relas[i].r_offset);
+ idx_relas[i].rela.r_info = r64(&raw_relas[i].r_info);
+ idx_relas[i].rela.r_addend =
+ (int64_t)r64((const uint64_t *)&raw_relas[i].r_addend);
+ 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_align > 4) {
+ size_t align = (size_t)eh_align;
+
+ 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);
+ uint64_t sym_val;
+ 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;
+
+ sym_val = r64(&syms[si].st_value);
+ old_target = (int64_t)sym_val + 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)sym_val;
+ } else {
+ if (sym_val > eh_in_len ||
+ anchor_find_exact(&anchors, (size_t)sym_val,
+ &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++) {
+ uint64_t sv;
+
+ if (!sym_is_in_eh_frame(&syms[s], s, eh_idx,
+ shndx_tab, nshndx) ||
+ ELF64_ST_TYPE(syms[s].st_info) == STT_SECTION)
+ continue;
+ sv = r64(&syms[s].st_value);
+ w64(&syms[s].st_value,
+ anchor_clamp_map(&anchors, (size_t)sv,
+ out_eh.len));
+ }
+ }
+ memcpy(map + eh_shoff, out_eh.data, out_eh.len);
+ w64(&eh_shdr->sh_size, out_eh.len);
+ if (rela_shdr && out_relas) {
+ Elf64_Rela *dst =
+ (Elf64_Rela *)(map + r64(&rela_shdr->sh_offset));
+
+ for (size_t r = 0; r < out_nrelas; r++) {
+ w64(&dst[r].r_offset, out_relas[r].r_offset);
+ w64(&dst[r].r_info, out_relas[r].r_info);
+ w64((uint64_t *)&dst[r].r_addend,
+ (uint64_t)out_relas[r].r_addend);
+ }
+ w64(&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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 06/30] kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY object pass
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (4 preceding siblings ...)
2026-11-25 6:14 ` [RFC PATCH v2 05/30] scripts: Add min_eh_frame build-time .eh_frame minifier Ian Rogers
@ 2026-11-25 6:14 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 07/30] objtool/ibt: Ignore .eh_frame relocations during ENDBR validation Ian Rogers
` (23 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:14 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Invoke scripts/min_eh_frame on standard kernel C, Rust, and post-LTO
composite .o objects when CONFIG_UNWINDER_DWARF_CFI_MINIFY is enabled,
recording scripts/min_eh_frame as a rebuild dependency in .*.cmd files.
Across full vmlinux builds on x86-64, ARM64, and RISC-V, minification
achieves 100.00% FDE coverage and reduces .eh_frame size 18%-28% below
SFrame v3 (.sframe).
Signed-off-by: Ian Rogers <irogers@google.com>
---
rust/Makefile | 4 +++-
scripts/Makefile.build | 12 ++++++++++--
scripts/Makefile.lib | 13 +++++++++++--
scripts/Makefile.vmlinux_o | 8 +++++++-
4 files changed, 31 insertions(+), 6 deletions(-)
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.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
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 07/30] objtool/ibt: Ignore .eh_frame relocations during ENDBR validation
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (5 preceding siblings ...)
2026-11-25 6:14 ` [RFC PATCH v2 06/30] kbuild: Wire up CONFIG_UNWINDER_DWARF_CFI_MINIFY object pass Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 08/30] vmlinux.lds.h: Allow architectures to emit custom RO_DATA sections Ian Rogers
` (22 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 08/30] vmlinux.lds.h: Allow architectures to emit custom RO_DATA sections
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (6 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 07/30] objtool/ibt: Ignore .eh_frame relocations during ENDBR validation Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 09/30] efi/libstub: Disable unwind tables in x86 and RISC-V EFI stubs Ian Rogers
` (21 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 ARCH_RODATA_SECTIONS hook inside RO_DATA() so
architectures using runtime .eh_frame / .eh_frame_hdr kernel unwinding
can place unwind tables inside write-protected RO_DATA without leaving
them in unmapped rodata/data gap pages.
Signed-off-by: Ian Rogers <irogers@google.com>
---
include/asm-generic/vmlinux.lds.h | 5 +++++
1 file changed, 5 insertions(+)
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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 09/30] efi/libstub: Disable unwind tables in x86 and RISC-V EFI stubs
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (7 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 08/30] vmlinux.lds.h: Allow architectures to emit custom RO_DATA sections Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 10/30] tracing: Skip internal ftrace frames under CONFIG_UNWINDER_DWARF_CFI Ian Rogers
` (20 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Pass -fno-unwind-tables and -fno-asynchronous-unwind-tables when
building x86 and RISC-V EFI libstub objects so enabling kernel-wide
asynchronous unwind tables under CONFIG_UNWINDER_DWARF_CFI does not emit
unwanted .eh_frame sections into the standalone EFI boot stub.
Signed-off-by: Ian Rogers <irogers@google.com>
---
drivers/firmware/efi/libstub/Makefile | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/drivers/firmware/efi/libstub/Makefile b/drivers/firmware/efi/libstub/Makefile
index bbab12b8eb4b..19c2822eb302 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)
@@ -29,7 +30,9 @@ cflags-$(CONFIG_ARM) += -DEFI_HAVE_STRLEN -DEFI_HAVE_STRNLEN \
-DEFI_HAVE_MEMCHR -DEFI_HAVE_STRRCHR \
-DEFI_HAVE_STRCMP -fno-builtin -fpic \
$(call cc-option,-mno-single-pic-base)
-cflags-$(CONFIG_RISCV) += -fpic -DNO_ALTERNATIVE -mno-relax
+cflags-$(CONFIG_RISCV) += -fpic -DNO_ALTERNATIVE -mno-relax \
+ -fno-unwind-tables \
+ -fno-asynchronous-unwind-tables
cflags-$(CONFIG_LOONGARCH) += -fpie
cflags-$(CONFIG_EFI_PARAMS_FROM_FDT) += -I$(srctree)/scripts/dtc/libfdt
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 10/30] tracing: Skip internal ftrace frames under CONFIG_UNWINDER_DWARF_CFI
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (8 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 09/30] efi/libstub: Disable unwind tables in x86 and RISC-V EFI stubs Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 11/30] x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook Ian Rogers
` (19 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Calibrate ftrace internal stack-trace skip counts under
CONFIG_UNWINDER_DWARF_CFI alongside CONFIG_UNWINDER_ORC so stack traces
captured from tracepoints and function tracers omit internal ftrace
wrapper frames consistently.
Signed-off-by: Ian Rogers <irogers@google.com>
---
kernel/trace/trace.c | 4 ++--
kernel/trace/trace_events_trigger.c | 2 +-
kernel/trace/trace_functions.c | 4 ++--
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index 65b9d67647e5..6d36c790c2b0 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -2156,7 +2156,7 @@ void __ftrace_trace_stack(struct trace_array *tr,
* Add one, for this function and the call to save_stack_trace()
* If regs is set, then these functions will not be in the way.
*/
-#ifndef CONFIG_UNWINDER_ORC
+#if !defined(CONFIG_UNWINDER_ORC) && !defined(CONFIG_UNWINDER_DWARF_CFI)
if (!regs)
skip++;
#endif
@@ -2258,7 +2258,7 @@ void trace_dump_stack(int skip)
if (tracing_disabled || tracing_selftest_running)
return;
-#ifndef CONFIG_UNWINDER_ORC
+#if !defined(CONFIG_UNWINDER_ORC) && !defined(CONFIG_UNWINDER_DWARF_CFI)
/* Skip 1 to skip this function. */
skip++;
#endif
diff --git a/kernel/trace/trace_events_trigger.c b/kernel/trace/trace_events_trigger.c
index a2487ad7fef8..c79df5b526e5 100644
--- a/kernel/trace/trace_events_trigger.c
+++ b/kernel/trace/trace_events_trigger.c
@@ -1597,7 +1597,7 @@ static __init int register_trigger_snapshot_cmd(void) { return 0; }
#endif /* CONFIG_TRACER_SNAPSHOT */
#ifdef CONFIG_STACKTRACE
-#ifdef CONFIG_UNWINDER_ORC
+#if defined(CONFIG_UNWINDER_ORC) || defined(CONFIG_UNWINDER_DWARF_CFI)
/* Skip 2:
* event_triggers_post_call()
* trace_event_raw_event_xxx()
diff --git a/kernel/trace/trace_functions.c b/kernel/trace/trace_functions.c
index acaba990aaaa..d601fdedceaa 100644
--- a/kernel/trace/trace_functions.c
+++ b/kernel/trace/trace_functions.c
@@ -251,7 +251,7 @@ function_args_trace_call(unsigned long ip, unsigned long parent_ip,
ftrace_test_recursion_unlock(bit);
}
-#ifdef CONFIG_UNWINDER_ORC
+#if defined(CONFIG_UNWINDER_ORC) || defined(CONFIG_UNWINDER_DWARF_CFI)
/*
* Skip 2:
*
@@ -602,7 +602,7 @@ ftrace_traceoff(unsigned long ip, unsigned long parent_ip,
tracer_tracing_off(tr);
}
-#ifdef CONFIG_UNWINDER_ORC
+#if defined(CONFIG_UNWINDER_ORC) || defined(CONFIG_UNWINDER_DWARF_CFI)
/*
* Skip 3:
*
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 11/30] x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (9 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 10/30] tracing: Skip internal ftrace frames under CONFIG_UNWINDER_DWARF_CFI Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 12/30] x86/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
` (18 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Prepare x86-64 hand-written and inline assembly paths for runtime
Minimal DWARF CFI kernel unwinding when CONFIG_UNWINDER_DWARF_CFI is
enabled:
- Emit .eh_frame alongside .debug_frame in asm/dwarf2.h and preserve
FRAME_BEGIN/FRAME_END frame setup for non-leaf assembly helpers in
asm/frame.h.
- Annotate THUNK (arch/x86/entry/calling.h), ftrace_caller /
ftrace_regs_caller / return_to_handler (arch/x86/kernel/ftrace_64.S),
and arch_rethook_trampoline() (arch/x86/kernel/rethook.c) with .cfi_*
directives.
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/x86/entry/calling.h | 17 +++++++
arch/x86/include/asm/dwarf2.h | 6 +--
arch/x86/include/asm/frame.h | 42 ++++++++++------
arch/x86/kernel/ftrace_64.S | 44 ++++++++++++++++-
arch/x86/kernel/rethook.c | 92 ++++++++++++++++++++++++++++++++++-
5 files changed, 180 insertions(+), 21 deletions(-)
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/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/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);
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 12/30] x86/unwind: Add Minimal DWARF CFI kernel unwinder
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (10 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 11/30] x86: Add DWARF CFI annotations to entry, ftrace, frame, and rethook Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 13/30] lib/Kconfig.debug: Allow LATENCYTOP and fault-injection filter with DWARF CFI Ian Rogers
` (17 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 suppressing unwind tables in boot/startup
and purgatory objects.
- Place .eh_frame_hdr and .eh_frame inside RO_DATA via
ARCH_RODATA_SECTIONS, index loadable module .eh_frame sections via
dwarf_cfi_mod_alloc()/dwarf_cfi_mod_free_rcu(), and enable BPF
exception stack walks in arch/x86/net/bpf_jit_comp.c.
- Unwind across task, IRQ, exception, ftrace, fgraph, rethook, BPF, and
call_on_stack() frames, while rejecting in-kernel pt_regs exception
boundaries in arch_stack_walk_reliable().
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/include/asm/module.h | 5 +
arch/x86/include/asm/unwind.h | 15 +-
arch/x86/kernel/Makefile | 4 +
arch/x86/kernel/module.c | 11 +-
arch/x86/kernel/stacktrace.c | 8 +-
arch/x86/kernel/unwind_dwarf.c | 674 +++++++++++++++++++++++++++++++++
arch/x86/kernel/vmlinux.lds.S | 16 +
arch/x86/net/bpf_jit_comp.c | 12 +-
arch/x86/purgatory/Makefile | 1 +
13 files changed, 754 insertions(+), 15 deletions(-)
create mode 100644 arch/x86/kernel/unwind_dwarf.c
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/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/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/stacktrace.c b/arch/x86/kernel/stacktrace.c
index 9412ac4ddf46..995810b61999 100644
--- a/arch/x86/kernel/stacktrace.c
+++ b/arch/x86/kernel/stacktrace.c
@@ -49,10 +49,12 @@ int arch_stack_walk_reliable(stack_trace_consume_fn consume_entry,
/*
* Kernel mode registers on the stack indicate an
* in-kernel interrupt or exception (e.g., preemption
- * or a page fault), which can make frame pointers
- * unreliable.
+ * or a page fault), which can make frame pointers or
+ * compiler-generated DWARF CFI (across unannotated
+ * inline assembly stack adjustments) unreliable.
*/
- if (IS_ENABLED(CONFIG_FRAME_POINTER))
+ if (IS_ENABLED(CONFIG_FRAME_POINTER) ||
+ IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI))
return -EINVAL;
}
diff --git a/arch/x86/kernel/unwind_dwarf.c b/arch/x86/kernel/unwind_dwarf.c
new file mode 100644
index 000000000000..135e1cd8b1a0
--- /dev/null
+++ b/arch/x86/kernel/unwind_dwarf.c
@@ -0,0 +1,674 @@
+// 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;
+}
+
+static bool dwarf_is_rethook_trampoline(unsigned long addr)
+{
+#ifdef CONFIG_RETHOOK
+ return is_rethook_trampoline(addr);
+#else
+ return false;
+#endif
+}
+
+/**
+ * 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 && dwarf_is_rethook_trampoline(state->ip)) {
+ state->ip =
+ dwarf_recover_ret_addr(state, state->ip,
+ (unsigned long *)(state->sp - sizeof(long)));
+ if (!state->ip || dwarf_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 (dwarf_is_rethook_trampoline(orig_ip) &&
+ (!state->ip || dwarf_is_rethook_trampoline(state->ip)))
+ goto err;
+#ifdef CONFIG_FUNCTION_GRAPH_TRACER
+ if (dwarf_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 || dwarf_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
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 13/30] lib/Kconfig.debug: Allow LATENCYTOP and fault-injection filter with DWARF CFI
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (11 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 12/30] x86/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 14/30] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
` (16 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Allow CONFIG_LATENCYTOP and CONFIG_FAULT_INJECTION_STACKTRACE_FILTER to
be enabled on architectures using CONFIG_UNWINDER_DWARF_CFI with
-fomit-frame-pointer (such as arm64 and riscv).
Signed-off-by: Ian Rogers <irogers@google.com>
---
lib/Kconfig.debug | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 2d22638ec13a..650ed105860d 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -1893,7 +1893,7 @@ config LATENCYTOP
depends on DEBUG_KERNEL
depends on STACKTRACE_SUPPORT
depends on PROC_FS
- depends on FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86
+ depends on FRAME_POINTER || UNWINDER_DWARF_CFI || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86
select KALLSYMS
select KALLSYMS_ALL
select STACKTRACE
@@ -2188,7 +2188,7 @@ config FAULT_INJECTION_STACKTRACE_FILTER
depends on FAULT_INJECTION
depends on (FAULT_INJECTION_DEBUG_FS || FAULT_INJECTION_CONFIGFS) && STACKTRACE_SUPPORT
select STACKTRACE
- depends on FRAME_POINTER || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86
+ depends on FRAME_POINTER || UNWINDER_DWARF_CFI || MIPS || PPC || S390 || MICROBLAZE || ARM || ARC || X86
help
Provide stacktrace filter for fault-injection capabilities
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 14/30] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (12 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 13/30] lib/Kconfig.debug: Allow LATENCYTOP and fault-injection filter with DWARF CFI Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 15/30] arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN Ian Rogers
` (15 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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(), and override unwind_user_fp_sets_sp() to
return false because AArch64 frame records live at the bottom of the
callee's stack frame rather than at caller_sp - 16.
- Implement unwind_user_sigreturn() in arch/arm64/kernel/signal.c to
recover pc, sp, x29, and x30 directly from rt_sigframe.uc.uc_mcontext
at __kernel_rt_sigreturn when state->sp_valid is true (falling back
to user->next_frame via FP otherwise), preserving interrupted leaf
functions and SA_ONSTACK alternate signal stacks.
- Strip user-space pointer authentication codes via
ptrauth_strip_user_insn_pac() (and clear Thumb bit 0 for compat user
tasks) in unwind_user_strip_pac(), and define ARCH_INIT_USER_FP_FRAME
for both 64-bit AArch64 PCS frame records and 32-bit AArch32
compat_frame_tail layouts.
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/arm64/Kconfig | 2 +
arch/arm64/include/asm/unwind_user.h | 145 +++++++++++++++++++++++++++
arch/arm64/kernel/signal.c | 55 ++++++++++
3 files changed, 202 insertions(+)
create mode 100644 arch/arm64/include/asm/unwind_user.h
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..919fbc406747
--- /dev/null
+++ b/arch/arm64/include/asm/unwind_user.h
@@ -0,0 +1,145 @@
+/* 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_fp_sets_sp() - Indicate ARM64 FP records do not recover caller SP
+ *
+ * AArch64 PCS places {x29, x30} at the bottom of the callee's frame rather than
+ * adjacent to the caller's stack pointer, so FP unwinding only yields a lower
+ * bound on the caller's SP.
+ *
+ * Return: Always false on arm64.
+ */
+static inline bool unwind_user_fp_sets_sp(void)
+{
+ return false;
+}
+
+#define unwind_user_fp_sets_sp unwind_user_fp_sets_sp
+
+/**
+ * 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() - Normalize user return address 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 with Thumb bit 0 cleared 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 & ~1UL;
+ 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..1cc4f3992e1a 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,60 @@ 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 || !state->sp_valid || !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->sp_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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 15/30] arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (13 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 14/30] arm64: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 16/30] arm64/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
` (14 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Annotate arm64 hand-written assembly helpers with .cfi_* directives
under CONFIG_UNWINDER_DWARF_CFI so runtime .eh_frame unwinding traverses
call_on_irq_stack(), __efi_rt_asm_wrapper(), return_to_handler() (and
exports ftrace_caller_end), __hwasan_tag_mismatch(), and
arch_bpf_timed_may_goto(), and allow bpf_jit_supports_exceptions() when
CONFIG_UNWINDER_DWARF_CFI is enabled.
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/arm64/kernel/efi-rt-wrapper.S | 22 ++++++++++++++++++
arch/arm64/kernel/entry-ftrace.S | 35 ++++++++++++++++++++++++++++-
arch/arm64/kernel/entry.S | 22 ++++++++++++++++++
arch/arm64/lib/kasan_sw_tags.S | 16 +++++++++++++
arch/arm64/net/bpf_jit_comp.c | 9 ++++----
arch/arm64/net/bpf_timed_may_goto.S | 19 ++++++++++++++++
6 files changed, 118 insertions(+), 5 deletions(-)
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/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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 16/30] arm64/unwind: Add Minimal DWARF CFI kernel unwinder
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (14 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 15/30] arm64: Add DWARF CFI annotations to entry, ftrace, EFI, BPF, and KASAN Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 17/30] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
` (13 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 the user vDSO and nVHE EL2 objects.
- Emit --eh-frame-hdr and place .eh_frame_hdr and .eh_frame in vmlinux
RO_DATA while preserving __pi___eh_frame_start/__pi___eh_frame_end
for Dynamic Shadow Call Stack patching, and index SHF_ALLOC module
.eh_frame sections with RCU-safe lifetime.
- Key function_graph and kretprobe shadow return stacks on entry SP
(CFA) rather than x29, mark caller-fetched perf regs via
FRAME_META_TYPE_CALLER, and implement noinstr-safe kunwind_next_cfi()
in arch/arm64/kernel/stacktrace.c.
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 | 18 +-
arch/arm64/include/asm/module.h | 16 +
arch/arm64/include/asm/module.lds.h | 2 +-
arch/arm64/include/asm/perf_event.h | 2 +
arch/arm64/include/asm/stacktrace/frame.h | 6 +
arch/arm64/kernel/Makefile | 6 +
arch/arm64/kernel/ftrace.c | 12 +-
arch/arm64/kernel/module.c | 17 +-
arch/arm64/kernel/probes/kprobes.c | 14 +-
arch/arm64/kernel/stacktrace.c | 477 ++++++++++++++++++++--
arch/arm64/kernel/vdso/Makefile | 7 +-
arch/arm64/kernel/vmlinux.lds.S | 21 +-
arch/arm64/kvm/hyp/nvhe/Makefile | 1 +
16 files changed, 596 insertions(+), 42 deletions(-)
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..57f19103c526 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
+void ftrace_caller_end(void);
#define HAVE_ARCH_FTRACE_REGS
struct dyn_ftrace;
struct ftrace_ops;
@@ -154,14 +155,21 @@ ftrace_partial_regs(const struct ftrace_regs *fregs, struct pt_regs *regs)
regs->regs[29] = afregs->fp;
regs->regs[30] = afregs->lr;
regs->pstate = PSR_MODE_EL1h;
+ regs->stackframe.type = FRAME_META_TYPE_NONE;
return regs;
}
-#define arch_ftrace_fill_perf_regs(fregs, _regs) do { \
- (_regs)->pc = arch_ftrace_regs(fregs)->pc; \
- (_regs)->regs[29] = arch_ftrace_regs(fregs)->fp; \
- (_regs)->sp = arch_ftrace_regs(fregs)->sp; \
- (_regs)->pstate = PSR_MODE_EL1h; \
+#define arch_ftrace_fill_perf_regs(fregs, _regs) do { \
+ const struct __arch_ftrace_regs *__afregs = \
+ arch_ftrace_regs(fregs); \
+ struct pt_regs *__regs = (_regs); \
+ \
+ __regs->pc = __afregs->pc; \
+ __regs->regs[29] = __afregs->fp; \
+ __regs->regs[30] = __afregs->lr; \
+ __regs->sp = __afregs->sp; \
+ __regs->pstate = PSR_MODE_EL1h; \
+ __regs->stackframe.type = FRAME_META_TYPE_NONE; \
} while (0)
int ftrace_regs_query_register_offset(const char *name);
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..3ee32cb68c5c 100644
--- a/arch/arm64/include/asm/perf_event.h
+++ b/arch/arm64/include/asm/perf_event.h
@@ -16,8 +16,10 @@
#define perf_arch_fetch_caller_regs(regs, __ip) { \
(regs)->pc = (__ip); \
(regs)->regs[29] = (unsigned long) __builtin_frame_address(0); \
+ (regs)->regs[30] = 0; \
(regs)->sp = current_stack_pointer; \
(regs)->pstate = PSR_MODE_EL1h; \
+ (regs)->stackframe.type = FRAME_META_TYPE_CALLER; \
}
#endif
diff --git a/arch/arm64/include/asm/stacktrace/frame.h b/arch/arm64/include/asm/stacktrace/frame.h
index 796797b8db7e..b6138367d50f 100644
--- a/arch/arm64/include/asm/stacktrace/frame.h
+++ b/arch/arm64/include/asm/stacktrace/frame.h
@@ -18,12 +18,18 @@
* an arbitrary point in time.
* Unwinding should consume pt_regs::pc, followed by pt_regs::lr.
*
+ * - FRAME_META_TYPE_CALLER
+ *
+ * Synthetic caller-fetched struct pt_regs from perf_arch_fetch_caller_regs()
+ * (not linked into the stack frame chain).
+ *
* Note: all other values are reserved and should result in unwinding
* terminating with an error.
*/
#define FRAME_META_TYPE_NONE 0
#define FRAME_META_TYPE_FINAL 1
#define FRAME_META_TYPE_PT_REGS 2
+#define FRAME_META_TYPE_CALLER 3
#ifndef __ASSEMBLER__
/*
diff --git a/arch/arm64/kernel/Makefile b/arch/arm64/kernel/Makefile
index fc5d1a0c38b3..a2507a4f7531 100644
--- a/arch/arm64/kernel/Makefile
+++ b/arch/arm64/kernel/Makefile
@@ -8,6 +8,9 @@ CFLAGS_armv8_deprecated.o := -I$(src)
CFLAGS_REMOVE_ftrace.o = $(CC_FLAGS_FTRACE)
CFLAGS_REMOVE_insn.o = $(CC_FLAGS_FTRACE)
CFLAGS_REMOVE_return_address.o = $(CC_FLAGS_FTRACE)
+ifdef CONFIG_UNWINDER_DWARF_CFI
+CFLAGS_REMOVE_stacktrace.o = $(CC_FLAGS_FTRACE)
+endif
# Remove stack protector to avoid triggering unneeded stack canary
# checks due to randomize_kstack_offset.
@@ -24,6 +27,9 @@ KASAN_SANITIZE_stacktrace.o := n
# inhibit KCOV instrumentation, disable it for the entire compilation unit.
KCOV_INSTRUMENT_entry-common.o := n
KCOV_INSTRUMENT_idle.o := n
+ifdef CONFIG_UNWINDER_DWARF_CFI
+KCOV_INSTRUMENT_stacktrace.o := n
+endif
# Softirq stack switching can run outside interrupt context.
KCOV_INSTRUMENT_irq.o := n
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..d19dbd6982ac 100644
--- a/arch/arm64/kernel/stacktrace.c
+++ b/arch/arm64/kernel/stacktrace.c
@@ -10,16 +10,130 @@
#include <linux/filter.h>
#include <linux/ftrace.h>
#include <linux/kprobes.h>
+#include <linux/module.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/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);
+}
+#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 +150,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 +208,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 +229,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,21 +272,39 @@ 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 __maybe_unused = 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)) {
+ 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);
+ WARN_ON_ONCE(state->task == current &&
+ !state->unreliable);
return -EINVAL;
}
state->common.pc = orig_pc;
@@ -149,8 +315,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 +325,23 @@ 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 &&
+ !state->unreliable);
+ return -EINVAL;
+ }
+ state->common.pc = orig_pc;
+ state->flags.fgraph = 1;
+ }
+#endif /* CONFIG_FUNCTION_GRAPH_TRACER */
+
return 0;
}
@@ -178,10 +361,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 +385,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);
@@ -244,6 +436,215 @@ kunwind_next_frame_record(struct kunwind_state *state)
return 0;
}
+#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 &&
+ !(state->sp & 0x7)) {
+ 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) {
+ unwind_consume_stack(&state->common, info,
+ state->sp, fsize);
+ state->common.pc = READ_ONCE(fregs->pc);
+ if (old_fp == state->sp + sizeof(*fregs))
+ 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 */
+
/*
* Unwind from one frame record (A) to the next frame record (B).
*
@@ -263,7 +664,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 +690,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;
@@ -356,7 +764,26 @@ kunwind_stack_walk(kunwind_consume_fn consume_state,
if (regs) {
if (task != current)
return -EINVAL;
- kunwind_init_from_regs(&state, regs);
+ if (IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI) &&
+ regs->stackframe.type == FRAME_META_TYPE_CALLER &&
+ !regs->regs[30]) {
+ unsigned long target_pc =
+ ptrauth_strip_kernel_insn_pac(regs->pc);
+
+ kunwind_init_from_caller(&state);
+ while (state.source != KUNWIND_SOURCE_UNKNOWN &&
+ (state.sp < regs->sp ||
+ (state.sp == regs->sp &&
+ state.sp <= regs->regs[29] &&
+ state.common.pc != target_pc))) {
+ if (kunwind_next(&state)) {
+ state.source = KUNWIND_SOURCE_UNKNOWN;
+ break;
+ }
+ }
+ } else {
+ kunwind_init_from_regs(&state, regs);
+ }
} else if (task == current) {
kunwind_init_from_caller(&state);
} else {
@@ -401,7 +828,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 +901,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/vdso/Makefile b/arch/arm64/kernel/vdso/Makefile
index f6619e1cb2ce..94f1ad06c6ab 100644
--- a/arch/arm64/kernel/vdso/Makefile
+++ b/arch/arm64/kernel/vdso/Makefile
@@ -35,13 +35,16 @@ ccflags-y += -DDISABLE_BRANCH_PROFILING -DBUILD_VDSO
# -Wmissing-prototypes and -Wmissing-declarations are removed from
# the CFLAGS to make possible to build the kernel with CONFIG_WERROR enabled.
-CC_FLAGS_REMOVE_VDSO := $(CC_FLAGS_FTRACE) -Os $(CC_FLAGS_SCS) \
+CC_FLAGS_REMOVE_VDSO := $(CC_FLAGS_FTRACE) -Os -fomit-frame-pointer \
+ $(CC_FLAGS_SCS) \
$(RANDSTRUCT_CFLAGS) $(KSTACK_ERASE_CFLAGS) \
$(GCC_PLUGINS_CFLAGS) \
$(CC_FLAGS_LTO) $(CC_FLAGS_CFI) \
-Wmissing-prototypes -Wmissing-declarations
-CC_FLAGS_ADD_VDSO := -O2 -mcmodel=tiny -fasynchronous-unwind-tables $(CONFIG_CC_OPT_INLINE_MEMSET)
+CC_FLAGS_ADD_VDSO := -O2 -mcmodel=tiny -fno-omit-frame-pointer \
+ -fasynchronous-unwind-tables \
+ $(CONFIG_CC_OPT_INLINE_MEMSET)
CFLAGS_REMOVE_vgettimeofday.o = $(CC_FLAGS_REMOVE_VDSO)
CFLAGS_REMOVE_vgetrandom.o = $(CC_FLAGS_REMOVE_VDSO)
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)
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 17/30] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (15 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 16/30] arm64/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 18/30] riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF JIT Ian Rogers
` (12 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 | 9 +++
arch/riscv/include/asm/unwind_user.h | 82 ++++++++++++++++++++++++++++
arch/riscv/kernel/compat_signal.c | 45 +++++++++++++++
arch/riscv/kernel/signal.c | 57 +++++++++++++++++++
5 files changed, 195 insertions(+)
create mode 100644 arch/riscv/include/asm/unwind_user.h
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..c1cbcb681aa7 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,12 @@ int compat_setup_rt_frame(struct ksignal *ksig, sigset_t *set,
{
return -1;
}
+
+static inline
+bool compat_unwind_user_sigreturn(struct unwind_user_state *state)
+{
+ return false;
+}
#endif
#endif
diff --git a/arch/riscv/include/asm/unwind_user.h b/arch/riscv/include/asm/unwind_user.h
new file mode 100644
index 000000000000..d3c12a183ac9
--- /dev/null
+++ b/arch/riscv/include/asm/unwind_user.h
@@ -0,0 +1,82 @@
+/* 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..53b5be62e393 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,47 @@ 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 the compat vDSO __vdso_rt_sigreturn trampoline
+ * 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->sp_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..c0d70220e4a4 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,59 @@ 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) || !mm->context.vdso ||
+ (state->sp & (sizeof(unsigned long) - 1)))
+ return false;
+
+ frame = (struct rt_sigframe __user *)state->sp;
+ sigret = (unsigned long)VDSO_SYMBOL(mm->context.vdso, rt_sigreturn);
+ 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->sp_valid = true;
+ state->signal = true;
+ state->topmost = false;
+ return true;
+}
+#endif
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 18/30] riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF JIT
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (16 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 17/30] riscv: unwind_user: Support Minimal DWARF CFI and FP user unwinding Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 19/30] riscv/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
` (11 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Prepare RISC-V assembly, probe trampolines, and RV64 BPF JIT prologues
for runtime Minimal DWARF CFI kernel unwinding:
- Export end labels for ret_from_fork_user_asm, call_on_irq_stack, and
ftrace_caller save/restore boundaries, and save s0 in ftrace_caller
under CONFIG_UNWINDER_DWARF_CFI.
- Annotate return_to_handler() and arch_rethook_trampoline() with
.cfi_* directives and key rethook shadow stacks on entry SP (CFA)
under CONFIG_UNWINDER_DWARF_CFI.
- Save RV_REG_RA unconditionally in RV64 BPF JIT prologues under
CONFIG_UNWINDER_DWARF_CFI so leaf BPF programs unwind into frameless C
callers.
Signed-off-by: Ian Rogers <irogers@google.com>
---
arch/riscv/kernel/entry.S | 2 ++
arch/riscv/kernel/mcount-dyn.S | 6 ++--
arch/riscv/kernel/mcount.S | 34 +++++++++++++++++--
arch/riscv/kernel/probes/rethook.c | 13 +++++--
arch/riscv/kernel/probes/rethook_trampoline.S | 30 ++++++++++++++++
arch/riscv/net/bpf_jit_comp64.c | 6 ++--
6 files changed, 81 insertions(+), 10 deletions(-)
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/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..f632630846de 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 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/net/bpf_jit_comp64.c b/arch/riscv/net/bpf_jit_comp64.c
index 788fcc21fd5b..fb8cc74cff11 100644
--- a/arch/riscv/net/bpf_jit_comp64.c
+++ b/arch/riscv/net/bpf_jit_comp64.c
@@ -201,7 +201,7 @@ static void __build_epilogue(bool is_tail_call, struct rv_jit_context *ctx)
{
int stack_adjust = ctx->stack_size, store_offset = stack_adjust - 8;
- if (seen_reg(RV_REG_RA, ctx)) {
+ if (seen_reg(RV_REG_RA, ctx) || IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI)) {
emit_ld(RV_REG_RA, store_offset, RV_REG_SP, ctx);
store_offset -= 8;
}
@@ -2130,7 +2130,7 @@ void bpf_jit_build_prologue(struct rv_jit_context *ctx, bool is_subprog)
if (bpf_stack_adjust)
mark_fp(ctx);
- if (seen_reg(RV_REG_RA, ctx))
+ if (seen_reg(RV_REG_RA, ctx) || IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI))
stack_adjust += 8;
stack_adjust += 8; /* RV_REG_FP */
if (seen_reg(RV_REG_S1, ctx))
@@ -2168,7 +2168,7 @@ void bpf_jit_build_prologue(struct rv_jit_context *ctx, bool is_subprog)
emit_addi(RV_REG_SP, RV_REG_SP, -stack_adjust, ctx);
- if (seen_reg(RV_REG_RA, ctx)) {
+ if (seen_reg(RV_REG_RA, ctx) || IS_ENABLED(CONFIG_UNWINDER_DWARF_CFI)) {
emit_sd(RV_REG_SP, store_offset, RV_REG_RA, ctx);
store_offset -= 8;
}
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 19/30] riscv/unwind: Add Minimal DWARF CFI kernel unwinder
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (17 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 18/30] riscv: Add DWARF CFI annotations to entry, ftrace, rethook, and BPF JIT Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 20/30] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test Ian Rogers
` (10 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 64-bit RISC-V kernel
unwinder (selecting HAVE_RELIABLE_STACKTRACE) in
arch/riscv/kernel/stacktrace.c:
- Build C and Rust kernel code with -fomit-frame-pointer and
-fasynchronous-unwind-tables, link vmlinux with --eh-frame-hdr, place
.eh_frame_hdr and .eh_frame in RO_DATA, and index SHF_ALLOC module
.eh_frame sections via dwarf_cfi_mod_alloc()/dwarf_cfi_mod_free_rcu().
- Implement walk_stackframe_cfi() and arch_stack_walk_reliable() across
task, IRQ, and overflow stacks with RVC 16-bit call-site support,
SP-keyed ftrace_graph/rethook recovery, BPF frame fallback, and
exception/entry root termination.
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/ftrace.h | 1 +
arch/riscv/include/asm/module.h | 22 +
arch/riscv/include/asm/perf_event.h | 2 +
arch/riscv/include/asm/stacktrace.h | 11 +
arch/riscv/kernel/Makefile | 9 +
arch/riscv/kernel/module.c | 9 +
arch/riscv/kernel/stacktrace.c | 650 +++++++++++++++++++++++++++-
arch/riscv/kernel/vmlinux.lds.S | 13 +
arch/riscv/purgatory/Makefile | 3 +-
12 files changed, 749 insertions(+), 7 deletions(-)
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/ftrace.h b/arch/riscv/include/asm/ftrace.h
index e5026cd8f022..663831d950e5 100644
--- a/arch/riscv/include/asm/ftrace.h
+++ b/arch/riscv/include/asm/ftrace.h
@@ -217,6 +217,7 @@ ftrace_partial_regs(const struct ftrace_regs *fregs, struct pt_regs *regs)
regs->sp = afregs->sp;
regs->s0 = afregs->s0;
regs->t1 = afregs->t1;
+ regs->cause = 0;
return regs;
}
diff --git a/arch/riscv/include/asm/module.h b/arch/riscv/include/asm/module.h
index 0f3baaa6a9a8..2a8dd969c1f8 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
+#ifdef CONFIG_HAVE_MOD_ARCH_SPECIFIC
struct mod_arch_specific {
+#ifdef CONFIG_MODULE_SECTIONS
struct mod_section got;
struct mod_section plt;
struct mod_section got_plt;
+#endif
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+ struct mod_dwarf_cfi_index __rcu *dwarf_cfi_index;
+#endif
};
+#endif
+
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+void riscv_unwind_module_init(struct module *mod, void *eh_frame,
+ size_t eh_frame_size);
+void riscv_unwind_module_cleanup(struct module *mod);
+#else
+static inline void riscv_unwind_module_init(struct module *mod, void *eh_frame,
+ size_t eh_frame_size) {}
+static inline void riscv_unwind_module_cleanup(struct module *mod) {}
+#endif
+
+#ifdef CONFIG_MODULE_SECTIONS
struct got_entry {
unsigned long symbol_addr; /* the real variable address */
diff --git a/arch/riscv/include/asm/perf_event.h b/arch/riscv/include/asm/perf_event.h
index bcc928fd3785..30d0c6b37e91 100644
--- a/arch/riscv/include/asm/perf_event.h
+++ b/arch/riscv/include/asm/perf_event.h
@@ -14,9 +14,11 @@
#define perf_arch_fetch_caller_regs(regs, __ip) { \
(regs)->epc = (__ip); \
+ (regs)->ra = 0; \
(regs)->s0 = (unsigned long) __builtin_frame_address(0); \
(regs)->sp = current_stack_pointer; \
(regs)->status = SR_PP; \
+ (regs)->cause = ~0UL; \
}
#endif
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..7ad74377dd4c 100644
--- a/arch/riscv/kernel/Makefile
+++ b/arch/riscv/kernel/Makefile
@@ -42,6 +42,15 @@ CFLAGS_REMOVE_patch.o = $(CC_FLAGS_FTRACE)
CFLAGS_REMOVE_sbi.o = $(CC_FLAGS_FTRACE)
CFLAGS_REMOVE_return_address.o = $(CC_FLAGS_FTRACE)
CFLAGS_REMOVE_sbi_ecall.o = $(CC_FLAGS_FTRACE)
+ifdef CONFIG_UNWINDER_DWARF_CFI
+CFLAGS_REMOVE_stacktrace.o = $(CC_FLAGS_FTRACE)
+endif
+endif
+
+ifdef CONFIG_UNWINDER_DWARF_CFI
+CFLAGS_stacktrace.o += -fno-optimize-sibling-calls
+KASAN_SANITIZE_stacktrace.o := n
+KCOV_INSTRUMENT_stacktrace.o := n
endif
always-$(KBUILD_BUILTIN) += vmlinux.lds
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/stacktrace.c b/arch/riscv/kernel/stacktrace.c
index c7555447149b..45d81aa11a8e 100644
--- a/arch/riscv/kernel/stacktrace.c
+++ b/arch/riscv/kernel/stacktrace.c
@@ -6,16 +6,20 @@
#include <linux/export.h>
#include <linux/kallsyms.h>
+#include <linux/module.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/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 +39,646 @@
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 || (!size && 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 || (!size && 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 || (!size && addr == high)) &&
+ addr + size >= addr && addr + size <= high) {
+ *out_low = low;
+ *out_high = high;
+ return RISCV_STACK_OVERFLOW;
+ }
+#endif
+ }
+
+ return 0;
+}
+
+/**
+ * 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, min_sp = 0, caller_fp = 0, caller_pc = 0;
+ bool ra_valid = false, exact_pc = false, unreliable = false;
+ struct llist_node *kr_cur = NULL;
+ unsigned int used_stacks = 0;
+ int graph_idx = 0;
+ int level = 0;
+
+ if (!task)
+ task = current;
+
+ if (regs && regs->cause == ~0UL && !regs->ra) {
+ if (require_reliable || task != current)
+ return -EINVAL;
+ min_sp = regs->sp;
+ caller_fp = regs->s0;
+ caller_pc = regs->epc;
+ regs = NULL;
+ }
+
+ 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;
+ bool skip_emit;
+ 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;
+
+ skip_emit = (level++ < 0) ||
+ (min_sp && (sp < min_sp ||
+ (sp == min_sp && sp < caller_fp &&
+ pc != caller_pc)));
+
+ 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 (!skip_emit && !fn(arg, pc))
+ return require_reliable ? -EINVAL : 0;
+ return 0;
+ }
+
+ if (!skip_emit && !fn(arg, pc))
+ return require_reliable ? -EINVAL : 0;
+ if (!skip_emit)
+ min_sp = 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,
+ /*size=*/0,
+ &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);
+ 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 +746,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
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 20/30] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (18 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 19/30] riscv/unwind: Add Minimal DWARF CFI kernel unwinder Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 21/30] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer Ian Rogers
` (9 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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
(including a >16-byte AArch64 frame testing state->sp_valid across
FP -> CFI transitions), exercising per-frame CFI -> FP -> CFI -> FP
-> CFI fallback and negative VMA caching in find_user_eh_frame_hdr()
Skip gracefully via dl_iterate_phdr() if the test binary lacks
PT_GNU_EH_FRAME (e.g. 32-bit ARM EHABI builds using .ARM.exidx).
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 | 482 ++++++++++++++++++
3 files changed, 486 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..a36e9f4d39e2
--- /dev/null
+++ b/tools/testing/selftests/perf_events/unwind_user_cfi.c
@@ -0,0 +1,482 @@
+// 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 <link.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"
+
+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
+/*
+ * Allocate a 32-byte frame (> 16 bytes) with {x29, x30} at [sp, #0] per
+ * AArch64 PCS so fp + 16 != caller_sp, exercising state->sp_valid tracking.
+ */
+static const uint32_t jit_stub_code[] = {
+ 0xd503245fU, /* bti c */
+ 0xa9be7bfdU, /* stp x29, x30, [sp, #-32]! */
+ 0x910003fdU, /* mov x29, sp */
+ 0xaa0003e9U, /* mov x9, x0 */
+ 0x2a0103e0U, /* mov w0, w1 */
+ 0xd63f0120U, /* blr x9 */
+ 0xa8c27bfdU, /* ldp x29, x30, [sp], #32 */
+ 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)
+{
+ size_t sz;
+ char *pad;
+ int res;
+
+ expect_ip_bridge = caller_return_ip();
+ asm volatile("" : "+r"(x));
+ sz = (size_t)((x & 0xf) + 32);
+ pad = alloca(sz);
+ memset(pad, x + 5, sz);
+ asm volatile("" : "+m"(*(char (*)[32])pad) :: "memory");
+ res = g_jit_fn ? g_jit_fn(cfi_shrink_wrap, x) : cfi_shrink_wrap(x);
+ asm volatile("" : "+m"(*(char (*)[32])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)
+{
+ size_t sz;
+ char *pad;
+ int res;
+
+ expect_ip_drap = caller_return_ip();
+ asm volatile("" : "+r"(x));
+ sz = (size_t)((x & 0xf) + 32);
+ pad = alloca(sz);
+ memset(pad, x + 9, sz);
+ asm volatile("" : "+m"(*(char (*)[32])pad) :: "memory");
+ res = g_jit_fn ? g_jit_fn(cfi_jit_bridge, x) : cfi_jit_bridge(x);
+ asm volatile("" : "+m"(*(char (*)[32])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];
+}
+
+static int check_main_eh_frame_cb(struct dl_phdr_info *info, size_t size,
+ void *data)
+{
+ bool *has_eh_frame = data;
+
+ (void)size;
+ if (!info->dlpi_name || info->dlpi_name[0] != '\0')
+ return 0;
+
+ for (int i = 0; i < info->dlpi_phnum; i++) {
+ if (info->dlpi_phdr[i].p_type == PT_GNU_EH_FRAME &&
+ info->dlpi_phdr[i].p_memsz > 0) {
+ *has_eh_frame = true;
+ return 1;
+ }
+ }
+ return 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;
+ bool has_eh_frame = 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
+
+ dl_iterate_phdr(check_main_eh_frame_cb, &has_eh_frame);
+ if (!has_eh_frame) {
+ ksft_test_result_skip("Test binary lacks PT_GNU_EH_FRAME\n");
+ ksft_finished();
+ }
+
+#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.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 21/30] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (19 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 20/30] selftests/perf_events: Add Minimal DWARF CFI deferred user unwind test Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 22/30] tools headers: Add linux/kmsan-checks.h copy from the kernel sources Ian Rogers
` (8 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 SP/FP/RA vs.
ignored GPR register rules, maximum DW_CFA_remember_state depth, and top
DWARF CFA opcode counts.
Example usage:
$ ./scripts/eh_frame_min.py vmlinux
$ ./scripts/eh_frame_min.py mm/vmscan.o kernel/fork.o
$ ./scripts/eh_frame_min.py /bin/bash /lib/x86_64-linux-gnu/libc.so.6
$ ./scripts/eh_frame_min.py --minify /tmp/eh_frame.min mm/vmscan.o
Signed-off-by: Ian Rogers <irogers@google.com>
---
scripts/eh_frame_min.py | 961 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 961 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..9b6fa3822ae6
--- /dev/null
+++ b/scripts/eh_frame_min.py
@@ -0,0 +1,961 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+"""
+Offline ELF .eh_frame / Minimal DWARF CFA coverage and size analyzer.
+
+Note: This script is a standalone developer/benchmarking inspection tool and
+is NOT invoked during Kbuild (which uses the standalone C host tool in
+scripts/min_eh_frame.c when CONFIG_UNWINDER_DWARF_CFI_MINIFY=y).
+
+It parses ELF32/ELF64 relocatable objects (.o, .ko), vmlinux images, user
+executables, and shared libraries across x86_64, i386, arm64, arm, and riscv,
+reporting:
+ - .text, .eh_frame, .eh_frame_hdr, .sframe, and .orc_unwind section sizes
+ - Simulated minified .eh_frame + .eh_frame_hdr sizes and byte savings
+ - Minimal DWARF CFA FDE coverage (supported vs. unsupported FDEs & reasons)
+ - Kept FP/RA register rules vs. ignored general-purpose register spill ops
+ - Maximum DW_CFA_remember_state nesting depth and top DWARF CFA opcodes
+
+Example usage (from the kernel tree root, invoke via ./scripts/eh_frame_min*):
+ 1. Analyze a built vmlinux image (with or without build-time minification):
+ $ eh_frame_min.py vmlinux
+
+ 2. Compare multiple kernel objects, loadable modules, or cross-arch builds:
+ $ eh_frame_min.py mm/vmscan.o kernel/fork.o fs/ext4/inode.o
+ $ eh_frame_min.py build_arm64/vmlinux build_riscv/vmlinux
+
+ 3. Analyze existing user-space binaries and shared libraries:
+ $ eh_frame_min.py /bin/bash /lib/x86_64-linux-gnu/libc.so.6
+
+ 4. Emit a standalone minified .eh_frame section blob for differential tests:
+ $ eh_frame_min.py --minify /tmp/eh_frame.min mm/vmscan.o
+
+Example output:
+ === build_arm64/vmlinux (arm64) ===
+ .text size : 18,500,228 B
+ Original .eh_frame : 2,294,092 B (1 CIEs, 69,765 FDEs)
+ Original .eh_frame_hdr : 558,132 B (combined: 2,852,224 B)
+ Minified .eh_frame : 2,285,920 B (1 CIEs, -0.4% vs .eh_frame)
+ Minified + .eh_frame_hdr: 2,844,052 B (-0.3% combined)
+ FDE bytecode payload : 1,108,067 B -> 953,348 B (avg 13.7 B/FDE)
+ .sframe section : 2,938,460 B
+ Minimal DWARF coverage : 69,765 / 69,765 FDEs (100.00%)
+ Register ops kept/skip : 125,630 kept (FP/RA), 0 ignored (other GPRs/args)
+ Max remember_state depth: 1
+"""
+
+import argparse
+import os
+import struct
+import sys
+from collections import Counter
+
+# DWARF register numbers per ELF e_machine (drap = transient stack-realign scratch regs)
+ARCH_REGS = {
+ 62: {"name": "x86_64", "sp": 7, "fp": 6, "ra": 16, "drap": {1, 2, 5, 10, 13}}, # EM_X86_64
+ 3: {"name": "i386", "sp": 4, "fp": 5, "ra": 8, "drap": {1, 7}}, # EM_386 (%ecx, %edi)
+ 40: {"name": "arm", "sp": 13, "fp": 11, "ra": 14, "drap": set()}, # EM_ARM
+ 183: {"name": "arm64", "sp": 31, "fp": 29, "ra": 30, "drap": set()}, # EM_AARCH64
+ 243: {"name": "riscv", "sp": 2, "fp": 8, "ra": 1, "drap": set()}, # EM_RISCV
+}
+
+DW_CFA_nop = 0x00
+DW_CFA_set_loc = 0x01
+DW_CFA_advance_loc1 = 0x02
+DW_CFA_advance_loc2 = 0x03
+DW_CFA_advance_loc4 = 0x04
+DW_CFA_offset_extended = 0x05
+DW_CFA_restore_extended = 0x06
+DW_CFA_undefined = 0x07
+DW_CFA_same_value = 0x08
+DW_CFA_register = 0x09
+DW_CFA_remember_state = 0x0a
+DW_CFA_restore_state = 0x0b
+DW_CFA_def_cfa = 0x0c
+DW_CFA_def_cfa_register = 0x0d
+DW_CFA_def_cfa_offset = 0x0e
+DW_CFA_def_cfa_expression = 0x0f
+DW_CFA_expression = 0x10
+DW_CFA_offset_extended_sf = 0x11
+DW_CFA_def_cfa_sf = 0x12
+DW_CFA_def_cfa_offset_sf = 0x13
+DW_CFA_val_offset = 0x14
+DW_CFA_val_offset_sf = 0x15
+DW_CFA_val_expression = 0x16
+DW_CFA_AARCH64_negate_ra_state = 0x2d
+DW_CFA_GNU_args_size = 0x2e
+DW_CFA_GNU_negative_offset_extended = 0x2f
+
+OPCODE_NAMES = {
+ 0x00: "DW_CFA_nop",
+ 0x01: "DW_CFA_set_loc",
+ 0x02: "DW_CFA_advance_loc1",
+ 0x03: "DW_CFA_advance_loc2",
+ 0x04: "DW_CFA_advance_loc4",
+ 0x05: "DW_CFA_offset_extended",
+ 0x06: "DW_CFA_restore_extended",
+ 0x07: "DW_CFA_undefined",
+ 0x08: "DW_CFA_same_value",
+ 0x09: "DW_CFA_register",
+ 0x0a: "DW_CFA_remember_state",
+ 0x0b: "DW_CFA_restore_state",
+ 0x0c: "DW_CFA_def_cfa",
+ 0x0d: "DW_CFA_def_cfa_register",
+ 0x0e: "DW_CFA_def_cfa_offset",
+ 0x0f: "DW_CFA_def_cfa_expression",
+ 0x10: "DW_CFA_expression",
+ 0x11: "DW_CFA_offset_extended_sf",
+ 0x12: "DW_CFA_def_cfa_sf",
+ 0x13: "DW_CFA_def_cfa_offset_sf",
+ 0x14: "DW_CFA_val_offset",
+ 0x15: "DW_CFA_val_offset_sf",
+ 0x16: "DW_CFA_val_expression",
+ 0x2d: "DW_CFA_negate_ra_state/window_save",
+ 0x2e: "DW_CFA_GNU_args_size",
+ 0x2f: "DW_CFA_GNU_negative_offset_extended",
+}
+
+DW_EH_PE_omit = 0xff
+DW_EH_PE_absptr = 0x00
+DW_EH_PE_uleb128 = 0x01
+DW_EH_PE_udata2 = 0x02
+DW_EH_PE_udata4 = 0x03
+DW_EH_PE_udata8 = 0x04
+DW_EH_PE_sleb128 = 0x09
+DW_EH_PE_sdata2 = 0x0a
+DW_EH_PE_sdata4 = 0x0b
+DW_EH_PE_sdata8 = 0x0c
+DW_EH_PE_pcrel = 0x10
+DW_EH_PE_indirect = 0x80
+
+
+def read_uleb128(buf, pos, end):
+ val = 0
+ shift = 0
+ while pos < end:
+ b = buf[pos]
+ pos += 1
+ val |= (b & 0x7f) << shift
+ if not (b & 0x80):
+ return val, pos
+ shift += 7
+ if shift > 63:
+ raise ValueError("ULEB128 overflow")
+ raise ValueError("Truncated ULEB128")
+
+
+def read_sleb128(buf, pos, end):
+ val = 0
+ shift = 0
+ while pos < end:
+ b = buf[pos]
+ pos += 1
+ val |= (b & 0x7f) << shift
+ shift += 7
+ if not (b & 0x80):
+ if b & 0x40:
+ val |= -(1 << shift)
+ return val, pos
+ if shift > 63:
+ raise ValueError("SLEB128 overflow")
+ raise ValueError("Truncated SLEB128")
+
+
+def encode_uleb128(val):
+ if val < 0:
+ raise ValueError("Negative ULEB128")
+ out = bytearray()
+ while True:
+ b = val & 0x7f
+ val >>= 7
+ if val:
+ b |= 0x80
+ out.append(b)
+ if not val:
+ break
+ return bytes(out)
+
+
+def encode_sleb128(val):
+ out = bytearray()
+ more = True
+ while more:
+ b = val & 0x7f
+ val >>= 7
+ if (val == 0 and not (b & 0x40)) or (val == -1 and (b & 0x40)):
+ more = False
+ else:
+ b |= 0x80
+ out.append(b)
+ return bytes(out)
+
+
+def encoded_ptr_size(enc, addr_size):
+ if enc == DW_EH_PE_omit:
+ return 0
+ fmt = enc & 0x0f
+ if fmt == DW_EH_PE_absptr:
+ return addr_size
+ if fmt in (DW_EH_PE_udata2, DW_EH_PE_sdata2):
+ return 2
+ if fmt in (DW_EH_PE_udata4, DW_EH_PE_sdata4):
+ return 4
+ if fmt in (DW_EH_PE_udata8, DW_EH_PE_sdata8):
+ return 8
+ return None
+
+
+def read_encoded_ptr(buf, pos, end, enc, addr_size, sec_vaddr):
+ if enc == DW_EH_PE_omit:
+ return 0, pos
+ orig_pos = pos
+ fmt = enc & 0x0f
+ if fmt == DW_EH_PE_absptr:
+ fmt_str = "<Q" if addr_size == 8 else "<I"
+ val = struct.unpack_from(fmt_str, buf, pos)[0]
+ pos += addr_size
+ elif fmt == DW_EH_PE_udata2:
+ val = struct.unpack_from("<H", buf, pos)[0]
+ pos += 2
+ elif fmt == DW_EH_PE_sdata2:
+ val = struct.unpack_from("<h", buf, pos)[0]
+ pos += 2
+ elif fmt == DW_EH_PE_udata4:
+ val = struct.unpack_from("<I", buf, pos)[0]
+ pos += 4
+ elif fmt == DW_EH_PE_sdata4:
+ val = struct.unpack_from("<i", buf, pos)[0]
+ pos += 4
+ elif fmt == DW_EH_PE_udata8:
+ val = struct.unpack_from("<Q", buf, pos)[0]
+ pos += 8
+ elif fmt == DW_EH_PE_sdata8:
+ val = struct.unpack_from("<q", buf, pos)[0]
+ pos += 8
+ elif fmt == DW_EH_PE_uleb128:
+ val, pos = read_uleb128(buf, pos, end)
+ elif fmt == DW_EH_PE_sleb128:
+ val, pos = read_sleb128(buf, pos, end)
+ else:
+ raise ValueError(f"Unsupported pointer format 0x{enc:02x}")
+
+ adj = enc & 0x70
+ if adj == DW_EH_PE_pcrel:
+ val = (sec_vaddr + orig_pos + val) & ((1 << (addr_size * 8)) - 1)
+ elif adj != 0x00:
+ raise ValueError(f"Unsupported pointer adjustment 0x{enc:02x}")
+ return val, pos
+
+
+def parse_elf_sections(data):
+ if data[:4] != b"\x7fELF":
+ raise ValueError("Not an ELF file")
+ ei_class = data[4]
+ ei_data = data[5]
+ if ei_data != 1:
+ raise ValueError("Only little-endian ELF supported")
+ if ei_class == 2:
+ addr_size = 8
+ _, e_machine, _, _, _, e_shoff, _, _, _, _, e_shentsize, e_shnum, e_shstrndx = (
+ struct.unpack_from("<HHIQQQIHHHHHH", data, 16)
+ )
+ sh_fmt = "<IIQQQQIIQQ"
+ elif ei_class == 1:
+ addr_size = 4
+ _, e_machine, _, _, _, e_shoff, _, _, _, _, e_shentsize, e_shnum, e_shstrndx = (
+ struct.unpack_from("<HHIIIIIHHHHHH", data, 16)
+ )
+ sh_fmt = "<IIIIIIIIII"
+ else:
+ raise ValueError(f"Unknown ELF class {ei_class}")
+
+ sections = {}
+ if e_shoff == 0:
+ raise ValueError("ELF has no section headers")
+
+ if e_shnum == 0 or e_shstrndx == 0xffff:
+ sh0 = struct.unpack_from(sh_fmt, data, e_shoff)
+ if e_shnum == 0:
+ e_shnum = sh0[5]
+ if e_shstrndx == 0xffff:
+ e_shstrndx = sh0[6]
+
+ if e_shnum == 0 or e_shstrndx >= e_shnum:
+ raise ValueError("ELF has invalid section header counts")
+
+ shdrs = []
+ for i in range(e_shnum):
+ off = e_shoff + i * e_shentsize
+ shdrs.append(struct.unpack_from(sh_fmt, data, off))
+
+ shstr_off = shdrs[e_shstrndx][4]
+ shstr_sz = shdrs[e_shstrndx][5]
+ shstrtab = data[shstr_off : shstr_off + shstr_sz]
+
+ for sh in shdrs:
+ sh_name_idx = sh[0]
+ sh_type = sh[1]
+ sh_addr = sh[3]
+ sh_offset = sh[4]
+ sh_size = sh[5]
+ end_idx = shstrtab.find(b"\x00", sh_name_idx)
+ name = shstrtab[sh_name_idx:end_idx].decode("utf-8", errors="replace")
+ # SHT_NOBITS == 8
+ sec_bytes = b"" if sh_type == 8 else data[sh_offset : sh_offset + sh_size]
+ if name in sections:
+ # Accumulate sizes for multi-section objects (e.g. .text.*)
+ prev_addr, prev_sz, prev_b = sections[name]
+ sections[name] = (prev_addr, prev_sz + sh_size, prev_b)
+ else:
+ sections[name] = (sh_addr, sh_size, sec_bytes)
+
+ return e_machine, addr_size, sections
+
+
+def parse_cie(buf, entry_off, body_off, entry_end, addr_size, sec_vaddr):
+ pos = body_off
+ version = buf[pos]
+ pos += 1
+ nul = buf.find(b"\x00", pos, entry_end)
+ if nul < 0:
+ raise ValueError("Unterminated CIE augmentation string")
+ aug = buf[pos:nul].decode("ascii", errors="replace")
+ pos = nul + 1
+
+ if version == 4:
+ addr_size = buf[pos]
+ seg_size = buf[pos + 1]
+ pos += 2
+ if seg_size != 0:
+ raise ValueError("Non-zero segment selector size")
+
+ code_align, pos = read_uleb128(buf, pos, entry_end)
+ data_align, pos = read_sleb128(buf, pos, entry_end)
+ if version == 1:
+ ra_reg = buf[pos]
+ pos += 1
+ else:
+ ra_reg, pos = read_uleb128(buf, pos, entry_end)
+
+ fde_enc = DW_EH_PE_absptr
+ lsda_enc = DW_EH_PE_omit
+ has_z = False
+ is_signal = False
+
+ if aug.startswith("z"):
+ has_z = True
+ aug_len, pos = read_uleb128(buf, pos, entry_end)
+ aug_end = pos + aug_len
+ ap = pos
+ for ch in aug[1:]:
+ if ch == "L":
+ lsda_enc = buf[ap]
+ ap += 1
+ elif ch == "P":
+ p_enc = buf[ap]
+ ap += 1
+ _, ap = read_encoded_ptr(buf, ap, aug_end, p_enc & ~DW_EH_PE_indirect, addr_size, sec_vaddr)
+ elif ch == "R":
+ fde_enc = buf[ap]
+ ap += 1
+ elif ch == "S":
+ is_signal = True
+ elif ch == "B":
+ # BTI / PAC key on arm64
+ pass
+ else:
+ raise ValueError(f"Unknown CIE augmentation '{ch}' in '{aug}'")
+ pos = aug_end
+ elif aug != "":
+ raise ValueError(f"Unsupported non-z CIE augmentation '{aug}'")
+
+ return {
+ "offset": entry_off,
+ "version": version,
+ "aug": aug,
+ "addr_size": addr_size,
+ "code_align": code_align,
+ "data_align": data_align,
+ "ra_reg": ra_reg,
+ "fde_enc": fde_enc,
+ "lsda_enc": lsda_enc,
+ "has_z": has_z,
+ "is_signal": is_signal,
+ "has_indirect_fde": bool(fde_enc & DW_EH_PE_indirect),
+ "insns": bytes(buf[pos:entry_end]),
+ }
+
+
+def decode_and_minify_insns(insns, cie, arch, init_row=None, is_cie=False):
+ """
+ Decode CFI instructions, validate against Minimal DWARF subset, and emit
+ minified instructions keeping only PC advances and {CFA(SP|FP), SP, FP, RA}.
+ """
+ sp_reg = arch["sp"]
+ fp_reg = arch["fp"]
+ ra_reg = cie["ra_reg"]
+ tracked_regs = {sp_reg, fp_reg, ra_reg}
+
+ def reg_key(reg):
+ if reg == fp_reg:
+ return "fp"
+ if reg == ra_reg:
+ return "ra"
+ return "sp"
+
+ pos = 0
+ end = len(insns)
+ op_counts = Counter()
+ ignored_reg_ops = 0
+ kept_reg_ops = 0
+ max_state_depth = 0
+ reasons = []
+
+ if init_row is None:
+ row = {
+ "cfa_reg": None,
+ "cfa_off": 0,
+ "sp": ("same", 0),
+ "fp": ("same", 0),
+ "ra": ("same", 0),
+ "ra_signed": False,
+ }
+ else:
+ row = dict(init_row)
+
+ cie_base_row = dict(row)
+ state_stack = []
+
+ # Stream of abstract events: ("adv", delta_units) or ("op", raw_bytes)
+ events = []
+ pending_adv = 0
+
+ def emit_op(raw_bytes):
+ nonlocal pending_adv
+ if pending_adv > 0 and not is_cie:
+ events.append(("adv", pending_adv))
+ pending_adv = 0
+ events.append(("op", raw_bytes))
+
+ try:
+ while pos < end:
+ op = insns[pos]
+ pos += 1
+ hi = op & 0xc0
+ lo = op & 0x3f
+
+ if hi == 0x40:
+ op_counts["DW_CFA_advance_loc"] += 1
+ pending_adv += lo
+ continue
+ if hi == 0x80:
+ op_counts["DW_CFA_offset"] += 1
+ reg = lo
+ uoff, pos = read_uleb128(insns, pos, end)
+ off = uoff * cie["data_align"]
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ if row[key] != ("off", off):
+ row[key] = ("off", off)
+ emit_op(bytes([0x80 | reg]) + encode_uleb128(uoff))
+ else:
+ ignored_reg_ops += 1
+ continue
+ if hi == 0xc0:
+ op_counts["DW_CFA_restore"] += 1
+ reg = lo
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ if row[key] != cie_base_row[key]:
+ row[key] = cie_base_row[key]
+ emit_op(bytes([0xc0 | reg]))
+ else:
+ ignored_reg_ops += 1
+ continue
+
+ name = OPCODE_NAMES.get(op, f"DW_CFA_unknown_0x{op:02x}")
+ op_counts[name] += 1
+
+ if op == DW_CFA_nop:
+ continue
+ elif op == DW_CFA_advance_loc1:
+ if pos + 1 > end:
+ raise ValueError("Truncated advance_loc1")
+ pending_adv += insns[pos]
+ pos += 1
+ elif op == DW_CFA_advance_loc2:
+ pending_adv += struct.unpack_from("<H", insns, pos)[0]
+ pos += 2
+ elif op == DW_CFA_advance_loc4:
+ pending_adv += struct.unpack_from("<I", insns, pos)[0]
+ pos += 4
+ elif op == DW_CFA_def_cfa:
+ reg, pos = read_uleb128(insns, pos, end)
+ uoff, pos = read_uleb128(insns, pos, end)
+ if reg not in (sp_reg, fp_reg) and reg not in arch["drap"]:
+ reasons.append(f"def_cfa non-SP/FP reg={reg}")
+ if row["cfa_reg"] != reg or row["cfa_off"] != uoff:
+ row["cfa_reg"] = reg
+ row["cfa_off"] = uoff
+ emit_op(bytes([DW_CFA_def_cfa]) + encode_uleb128(reg) + encode_uleb128(uoff))
+ elif op == DW_CFA_def_cfa_sf:
+ reg, pos = read_uleb128(insns, pos, end)
+ soff, pos = read_sleb128(insns, pos, end)
+ off = soff * cie["data_align"]
+ if reg not in (sp_reg, fp_reg) and reg not in arch["drap"]:
+ reasons.append(f"def_cfa_sf non-SP/FP reg={reg}")
+ if row["cfa_reg"] != reg or row["cfa_off"] != off:
+ row["cfa_reg"] = reg
+ row["cfa_off"] = off
+ emit_op(bytes([DW_CFA_def_cfa_sf]) + encode_uleb128(reg) + encode_sleb128(soff))
+ elif op == DW_CFA_def_cfa_register:
+ reg, pos = read_uleb128(insns, pos, end)
+ if not isinstance(row["cfa_reg"], int):
+ reasons.append("def_cfa_register without reg+off CFA")
+ if reg not in (sp_reg, fp_reg) and reg not in arch["drap"]:
+ reasons.append(f"def_cfa_register non-SP/FP reg={reg}")
+ if row["cfa_reg"] != reg:
+ row["cfa_reg"] = reg
+ emit_op(bytes([DW_CFA_def_cfa_register]) + encode_uleb128(reg))
+ elif op == DW_CFA_def_cfa_offset:
+ uoff, pos = read_uleb128(insns, pos, end)
+ if not isinstance(row["cfa_reg"], int):
+ reasons.append("def_cfa_offset without reg+off CFA")
+ if row["cfa_off"] != uoff:
+ row["cfa_off"] = uoff
+ emit_op(bytes([DW_CFA_def_cfa_offset]) + encode_uleb128(uoff))
+ elif op == DW_CFA_def_cfa_offset_sf:
+ soff, pos = read_sleb128(insns, pos, end)
+ off = soff * cie["data_align"]
+ if not isinstance(row["cfa_reg"], int):
+ reasons.append("def_cfa_offset_sf without reg+off CFA")
+ if row["cfa_off"] != off:
+ row["cfa_off"] = off
+ emit_op(bytes([DW_CFA_def_cfa_offset_sf]) + encode_sleb128(soff))
+ elif op == DW_CFA_offset_extended:
+ reg, pos = read_uleb128(insns, pos, end)
+ uoff, pos = read_uleb128(insns, pos, end)
+ off = uoff * cie["data_align"]
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ if row[key] != ("off", off):
+ row[key] = ("off", off)
+ raw = (bytes([0x80 | reg]) + encode_uleb128(uoff) if reg < 64
+ else bytes([DW_CFA_offset_extended]) + encode_uleb128(reg) + encode_uleb128(uoff))
+ emit_op(raw)
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_offset_extended_sf:
+ reg, pos = read_uleb128(insns, pos, end)
+ soff, pos = read_sleb128(insns, pos, end)
+ off = soff * cie["data_align"]
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ if row[key] != ("off", off):
+ row[key] = ("off", off)
+ emit_op(bytes([DW_CFA_offset_extended_sf]) + encode_uleb128(reg) + encode_sleb128(soff))
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_GNU_negative_offset_extended:
+ reg, pos = read_uleb128(insns, pos, end)
+ uoff, pos = read_uleb128(insns, pos, end)
+ off = -uoff * cie["data_align"]
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ if row[key] != ("off", off):
+ row[key] = ("off", off)
+ emit_op(bytes([DW_CFA_GNU_negative_offset_extended]) +
+ encode_uleb128(reg) + encode_uleb128(uoff))
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_restore_extended:
+ reg, pos = read_uleb128(insns, pos, end)
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ if row[key] != cie_base_row[key]:
+ row[key] = cie_base_row[key]
+ raw = bytes([0xc0 | reg]) if reg < 64 else bytes([DW_CFA_restore_extended]) + encode_uleb128(reg)
+ emit_op(raw)
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_undefined:
+ reg, pos = read_uleb128(insns, pos, end)
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ row[key] = ("undef", 0)
+ emit_op(bytes([DW_CFA_undefined]) + encode_uleb128(reg))
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_same_value:
+ reg, pos = read_uleb128(insns, pos, end)
+ if reg in tracked_regs:
+ kept_reg_ops += 1
+ key = reg_key(reg)
+ row[key] = ("same", 0)
+ emit_op(bytes([DW_CFA_same_value]) + encode_uleb128(reg))
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_remember_state:
+ emit_op(bytes([DW_CFA_remember_state]))
+ state_stack.append((dict(row), len(events) - 1))
+ max_state_depth = max(max_state_depth, len(state_stack))
+ if len(state_stack) > 4:
+ reasons.append(f"remember_state depth={len(state_stack)} > 4")
+ elif op == DW_CFA_restore_state:
+ if not state_stack:
+ reasons.append("unmatched restore_state")
+ else:
+ saved_row, rem_idx = state_stack.pop()
+ if saved_row != row:
+ row = saved_row
+ emit_op(bytes([DW_CFA_restore_state]))
+ else:
+ # Nothing in {CFA, SP, FP, RA} changed inside remember/restore!
+ # If remember_state is only followed by adv, elide the pair.
+ elided = False
+ if rem_idx < len(events) and events[rem_idx] == ("op", bytes([DW_CFA_remember_state])):
+ if all(ev[0] == "adv" for ev in events[rem_idx + 1:]):
+ extra_adv = sum(ev[1] for ev in events[rem_idx + 1:])
+ del events[rem_idx:]
+ pending_adv += extra_adv
+ elided = True
+ if not elided:
+ emit_op(bytes([DW_CFA_restore_state]))
+ elif op == DW_CFA_GNU_args_size:
+ _, pos = read_uleb128(insns, pos, end)
+ ignored_reg_ops += 1
+ elif op == DW_CFA_AARCH64_negate_ra_state and arch["name"] == "arm64":
+ row["ra_signed"] = not row["ra_signed"]
+ emit_op(bytes([DW_CFA_AARCH64_negate_ra_state]))
+ elif op == DW_CFA_def_cfa_expression:
+ expr_len, pos = read_uleb128(insns, pos, end)
+ if pos + expr_len > end:
+ raise ValueError("Truncated def_cfa_expression")
+ expr = insns[pos : pos + expr_len]
+ pos += expr_len
+ # Fixed DRAP / sigframe pattern: DW_OP_breg(FP|SP) <sleb128>, DW_OP_deref
+ if (len(expr) >= 3 and expr[-1] == 0x06 and
+ expr[0] in (0x70 + fp_reg, 0x70 + sp_reg)):
+ try:
+ soff, epos = read_sleb128(expr, 1, len(expr) - 1)
+ except ValueError:
+ epos = -1
+ if epos == len(expr) - 1:
+ kind = "fp_indirect" if expr[0] == (0x70 + fp_reg) else "sp_indirect"
+ row["cfa_reg"] = (kind,)
+ row["cfa_off"] = soff
+ emit_op(bytes([DW_CFA_def_cfa_expression]) + encode_uleb128(len(expr)) + expr)
+ continue
+ reasons.append(name)
+ elif op in (DW_CFA_expression, DW_CFA_val_expression):
+ reg, pos = read_uleb128(insns, pos, end)
+ expr_len, pos = read_uleb128(insns, pos, end)
+ if pos + expr_len > end:
+ raise ValueError("Truncated register expression")
+ expr = insns[pos : pos + expr_len]
+ pos += expr_len
+ if reg == sp_reg:
+ if (op == DW_CFA_expression and len(expr) >= 2 and
+ expr[0] == (0x70 + sp_reg) and row["cfa_reg"] == ("sp_indirect",)):
+ try:
+ soff, epos = read_sleb128(expr, 1, len(expr))
+ except ValueError:
+ epos = -1
+ if epos == len(expr) and soff == row["cfa_off"]:
+ ignored_reg_ops += 1
+ continue
+ reasons.append(f"{name} r{reg}")
+ continue
+ if reg not in tracked_regs:
+ ignored_reg_ops += 1
+ continue
+ # Fixed DRAP / sigframe save pattern: DW_CFA_expression(FP|RA, DW_OP_breg(FP|SP) <sleb128>)
+ if (op == DW_CFA_expression and len(expr) >= 2 and
+ expr[0] in (0x70 + fp_reg, 0x70 + sp_reg)):
+ try:
+ soff, epos = read_sleb128(expr, 1, len(expr))
+ except ValueError:
+ epos = -1
+ if epos == len(expr) and (reg == fp_reg or expr[0] == (0x70 + sp_reg)):
+ kept_reg_ops += 1
+ rule = "fp_off" if expr[0] == (0x70 + fp_reg) else "sp_off"
+ row["fp" if reg == fp_reg else "ra"] = (rule, soff)
+ emit_op(bytes([DW_CFA_expression]) + encode_uleb128(reg) +
+ encode_uleb128(len(expr)) + expr)
+ continue
+ reasons.append(f"{name} r{reg}")
+ elif op == DW_CFA_register:
+ r1, pos = read_uleb128(insns, pos, end)
+ r2, pos = read_uleb128(insns, pos, end)
+ if r1 in tracked_regs:
+ reasons.append(f"DW_CFA_register r{r1}->r{r2}")
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_val_offset:
+ r1, pos = read_uleb128(insns, pos, end)
+ _, pos = read_uleb128(insns, pos, end)
+ if r1 in tracked_regs:
+ reasons.append(f"DW_CFA_val_offset r{r1}")
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_val_offset_sf:
+ r1, pos = read_uleb128(insns, pos, end)
+ _, pos = read_sleb128(insns, pos, end)
+ if r1 in tracked_regs:
+ reasons.append(f"DW_CFA_val_offset_sf r{r1}")
+ else:
+ ignored_reg_ops += 1
+ elif op == DW_CFA_set_loc:
+ _, pos = read_encoded_ptr(insns, pos, end, cie["fde_enc"], cie["addr_size"], 0)
+ reasons.append("DW_CFA_set_loc")
+ else:
+ reasons.append(name)
+ break
+ except (ValueError, struct.error, IndexError) as exc:
+ reasons.append(f"malformed_bytecode({exc})")
+
+ # Coalesce consecutive ("adv", d) events and drop trailing ("adv", d)
+ while events and events[-1][0] == "adv":
+ events.pop()
+
+ min_bytes = bytearray()
+ acc_adv = 0
+ for kind, payload in events:
+ if kind == "adv":
+ acc_adv += payload
+ else:
+ if acc_adv > 0:
+ if acc_adv <= 0x3f:
+ min_bytes.append(0x40 | acc_adv)
+ elif acc_adv <= 0xff:
+ min_bytes.extend([DW_CFA_advance_loc1, acc_adv])
+ elif acc_adv <= 0xffff:
+ min_bytes.append(DW_CFA_advance_loc2)
+ min_bytes.extend(struct.pack("<H", acc_adv))
+ else:
+ min_bytes.append(DW_CFA_advance_loc4)
+ min_bytes.extend(struct.pack("<I", acc_adv))
+ acc_adv = 0
+ min_bytes.extend(payload)
+
+ return {
+ "row": row,
+ "min_insns": bytes(min_bytes),
+ "op_counts": op_counts,
+ "ignored_reg_ops": ignored_reg_ops,
+ "kept_reg_ops": kept_reg_ops,
+ "max_state_depth": max_state_depth,
+ "unsupported_reasons": reasons,
+ }
+
+
+def build_minimal_cie_bytes(cie, min_cie_insns, align=4):
+ aug = b"zRS\x00" if cie["is_signal"] else b"zR\x00"
+ fde_enc = DW_EH_PE_pcrel | DW_EH_PE_sdata4
+ body = bytearray()
+ body.append(1) # CIE version 1
+ body.extend(aug)
+ body.extend(encode_uleb128(cie["code_align"]))
+ body.extend(encode_sleb128(cie["data_align"]))
+ body.append(cie["ra_reg"])
+ body.append(1) # augmentation data length = 1 ('R')
+ body.append(fde_enc)
+ body.extend(min_cie_insns)
+ # Total record is 4 (length) + 4 (CIE_id=0) + len(body), pad to align
+ rem = (8 + len(body)) % align
+ if rem:
+ body.extend(b"\x00" * (align - rem))
+ return struct.pack("<II", 4 + len(body), 0) + bytes(body)
+
+
+def build_minimal_fde_bytes(min_fde_insns, cie_offset_from_here, init_loc_rel=0, pc_range=0, align=4):
+ body = bytearray()
+ body.extend(struct.pack("<iI", init_loc_rel, pc_range))
+ body.append(0) # zR augmentation data length = 0
+ body.extend(min_fde_insns)
+ rem = (8 + len(body)) % align
+ if rem:
+ body.extend(b"\x00" * (align - rem))
+ return struct.pack("<II", 4 + len(body), cie_offset_from_here) + bytes(body)
+
+
+def analyze_elf(path, out_min_path=None):
+ with open(path, "rb") as f:
+ data = f.read()
+
+ e_machine, addr_size, sections = parse_elf_sections(data)
+ if e_machine not in ARCH_REGS:
+ raise ValueError(f"Unsupported ELF e_machine={e_machine}")
+ arch = ARCH_REGS[e_machine]
+
+ if ".eh_frame" not in sections:
+ print(f"{path}: no .eh_frame section found")
+ return
+
+ eh_vaddr, eh_size, eh_buf = sections[".eh_frame"]
+ eh_hdr_size = sections.get(".eh_frame_hdr", (0, 0, b""))[1]
+ sframe_size = sections.get(".sframe", (0, 0, b""))[1]
+ orc_size = (sections.get(".orc_unwind", (0, 0, b""))[1] +
+ sections.get(".orc_unwind_ip", (0, 0, b""))[1])
+ text_size = sum(sz for name, (_, sz, _) in sections.items() if name.startswith(".text") or name in (".init.text", ".exit.text"))
+
+ cies = {}
+ cie_init_rows = {}
+ min_eh_stream = bytearray()
+ min_cie_offsets = {}
+
+ total_cies = 0
+ total_fdes = 0
+ supported_fdes = 0
+ unsupported_fdes = 0
+ unsupported_breakdown = Counter()
+ total_op_counts = Counter()
+ total_orig_insn_bytes = 0
+ total_min_insn_bytes = 0
+ total_ignored_ops = 0
+ total_kept_ops = 0
+ max_depth_seen = 0
+
+ pos = 0
+ end = len(eh_buf)
+ while pos + 4 <= end:
+ length = struct.unpack_from("<I", eh_buf, pos)[0]
+ entry_off = pos
+ pos += 4
+ if length == 0:
+ break
+ if length == 0xffffffff:
+ length = struct.unpack_from("<Q", eh_buf, pos)[0]
+ pos += 8
+ entry_end = pos + length
+ cie_id = struct.unpack_from("<I", eh_buf, pos)[0]
+
+ if cie_id == 0:
+ total_cies += 1
+ cie = parse_cie(eh_buf, entry_off, pos + 4, entry_end, addr_size, eh_vaddr)
+ res = decode_and_minify_insns(cie["insns"], cie, arch, is_cie=True)
+ cie["unsupported_reasons"] = list(res["unsupported_reasons"])
+ cies[entry_off] = cie
+ cie_init_rows[entry_off] = res["row"]
+ total_op_counts.update(res["op_counts"])
+
+ cie_key = (cie["code_align"], cie["data_align"], cie["ra_reg"], cie["is_signal"], res["min_insns"])
+ if not cie["unsupported_reasons"] and not cie["has_indirect_fde"] and cie_key not in min_cie_offsets:
+ min_cie_offsets[cie_key] = len(min_eh_stream)
+ min_eh_stream.extend(build_minimal_cie_bytes(cie, res["min_insns"], align=4))
+ cie["min_key"] = cie_key
+ else:
+ total_fdes += 1
+ cie_off = pos - cie_id
+ cie = cies[cie_off]
+ fpos = pos + 4
+ init_loc, fpos = read_encoded_ptr(eh_buf, fpos, entry_end, cie["fde_enc"], addr_size, eh_vaddr)
+ range_enc = (cie["fde_enc"] & 0x0f) & ~0x08
+ pc_range, fpos = read_encoded_ptr(eh_buf, fpos, entry_end, range_enc, addr_size, 0)
+ if cie["has_z"]:
+ aug_len, fpos = read_uleb128(eh_buf, fpos, entry_end)
+ fpos += aug_len
+ fde_insns = eh_buf[fpos:entry_end]
+ total_orig_insn_bytes += len(fde_insns)
+
+ res = decode_and_minify_insns(fde_insns, cie, arch, init_row=cie_init_rows[cie_off])
+ total_op_counts.update(res["op_counts"])
+ total_min_insn_bytes += len(res["min_insns"])
+ total_ignored_ops += res["ignored_reg_ops"]
+ total_kept_ops += res["kept_reg_ops"]
+ max_depth_seen = max(max_depth_seen, res["max_state_depth"])
+
+ reasons = list(cie["unsupported_reasons"]) + list(res["unsupported_reasons"])
+ if cie["has_indirect_fde"]:
+ reasons.append("indirect_fde_encoding")
+
+ if not reasons:
+ supported_fdes += 1
+ min_cie_off = min_cie_offsets[cie["min_key"]]
+ fde_id_pos = len(min_eh_stream) + 4
+ init_rel = (init_loc - (eh_vaddr + len(min_eh_stream) + 8)) if eh_vaddr else 0
+ if not (-0x80000000 <= init_rel <= 0x7fffffff):
+ init_rel = 0
+ min_eh_stream.extend(
+ build_minimal_fde_bytes(res["min_insns"], fde_id_pos - min_cie_off, init_rel, pc_range, align=4)
+ )
+ else:
+ unsupported_fdes += 1
+ for r in set(reasons):
+ unsupported_breakdown[r] += 1
+
+ pos = entry_end
+
+ min_eh_stream.extend(b"\x00\x00\x00\x00") # terminator
+ min_eh_hdr_size = 12 + supported_fdes * 8
+
+ if out_min_path:
+ with open(out_min_path, "wb") as outf:
+ outf.write(min_eh_stream)
+
+ pct_cov = (100.0 * supported_fdes / total_fdes) if total_fdes else 100.0
+ orig_total = eh_size + eh_hdr_size
+ min_total = len(min_eh_stream) + min_eh_hdr_size
+ eh_delta_pct = (100.0 * (len(min_eh_stream) / eh_size - 1.0)) if eh_size else 0.0
+
+ print(f"=== {path} ({arch['name']}) ===")
+ print(f" .text size : {text_size:10,d} B")
+ print(f" Original .eh_frame : {eh_size:10,d} B ({total_cies} CIEs, {total_fdes:,d} FDEs)")
+ if eh_hdr_size:
+ total_delta_pct = 100.0 * (min_total / orig_total - 1.0)
+ print(f" Original .eh_frame_hdr : {eh_hdr_size:10,d} B (combined: {orig_total:,d} B)")
+ print(f" Minified .eh_frame : {len(min_eh_stream):10,d} B ({len(min_cie_offsets)} CIEs, {eh_delta_pct:+.1f}% vs .eh_frame)")
+ print(f" Minified + .eh_frame_hdr: {min_total:10,d} B ({total_delta_pct:+.1f}% combined)")
+ else:
+ print(f" Minified .eh_frame : {len(min_eh_stream):10,d} B ({len(min_cie_offsets)} CIEs, {eh_delta_pct:+.1f}% vs .eh_frame)")
+ print(f" Simulated .eh_frame_hdr : {min_eh_hdr_size:10,d} B (linker-generated at final link)")
+ print(f" FDE bytecode payload : {total_orig_insn_bytes:10,d} B -> {total_min_insn_bytes:,d} B "
+ f"(avg {total_min_insn_bytes / max(supported_fdes, 1):.1f} B/FDE)")
+ if sframe_size:
+ print(f" .sframe section : {sframe_size:10,d} B")
+ if orc_size:
+ print(f" .orc_unwind + _ip : {orc_size:10,d} B")
+ print(f" Minimal DWARF coverage : {supported_fdes:,d} / {total_fdes:,d} FDEs ({pct_cov:.2f}%)")
+ print(f" Register ops kept/skip : {total_kept_ops:,d} kept (FP/RA), {total_ignored_ops:,d} ignored (other GPRs/args)")
+ print(f" Max remember_state depth: {max_depth_seen}")
+ if unsupported_breakdown:
+ print(" Unsupported FDE reasons :")
+ for r, cnt in unsupported_breakdown.most_common():
+ print(f" - {r}: {cnt}")
+ print(" Top DWARF CFA opcodes :")
+ for op_name, cnt in total_op_counts.most_common(10):
+ print(f" - {op_name:34s}: {cnt:8,d}")
+ print()
+
+
+def main():
+ epilog = (
+ "Examples:\n"
+ " %(prog)s vmlinux\n"
+ " %(prog)s mm/vmscan.o kernel/fork.o\n"
+ " %(prog)s /bin/bash /lib/x86_64-linux-gnu/libc.so.6\n"
+ " %(prog)s --minify /tmp/eh_frame.min mm/vmscan.o\n"
+ )
+ ap = argparse.ArgumentParser(
+ description="Analyze ELF .eh_frame coverage and size for Minimal DWARF CFI",
+ epilog=epilog,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ ap.add_argument("files", nargs="+", help="ELF files (.o, .ko, vmlinux, DSO, executable) to analyze")
+ ap.add_argument("--minify", metavar="OUT", help="Write minified .eh_frame binary for the first file")
+ args = ap.parse_args()
+
+ for idx, path in enumerate(args.files):
+ out_p = args.minify if idx == 0 else None
+ analyze_elf(path, out_min_path=out_p)
+
+
+if __name__ == "__main__":
+ main()
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 22/30] tools headers: Add linux/kmsan-checks.h copy from the kernel sources
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (20 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 21/30] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 23/30] tools headers: Add linux/nospec.h " Ian Rogers
` (7 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Copy include/linux/kmsan-checks.h to tools/include/linux/kmsan-checks.h
so host tools in tools/ can compile kernel sources using
kmsan_unpoison_memory() without referencing ../../include/linux
directly, and register it in tools/perf/check-headers.sh.
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/include/linux/kmsan-checks.h | 98 ++++++++++++++++++++++++++++++
| 1 +
2 files changed, 99 insertions(+)
create mode 100644 tools/include/linux/kmsan-checks.h
diff --git a/tools/include/linux/kmsan-checks.h b/tools/include/linux/kmsan-checks.h
new file mode 100644
index 000000000000..e1082dc40abc
--- /dev/null
+++ b/tools/include/linux/kmsan-checks.h
@@ -0,0 +1,98 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * KMSAN checks to be used for one-off annotations in subsystems.
+ *
+ * Copyright (C) 2017-2022 Google LLC
+ * Author: Alexander Potapenko <glider@google.com>
+ *
+ */
+
+#ifndef _LINUX_KMSAN_CHECKS_H
+#define _LINUX_KMSAN_CHECKS_H
+
+#include <linux/types.h>
+
+#ifdef CONFIG_KMSAN
+
+/**
+ * kmsan_poison_memory() - Mark the memory range as uninitialized.
+ * @address: address to start with.
+ * @size: size of buffer to poison.
+ * @flags: GFP flags for allocations done by this function.
+ *
+ * Until other data is written to this range, KMSAN will treat it as
+ * uninitialized. Error reports for this memory will reference the call site of
+ * kmsan_poison_memory() as origin.
+ */
+void kmsan_poison_memory(const void *address, size_t size, gfp_t flags);
+
+/**
+ * kmsan_unpoison_memory() - Mark the memory range as initialized.
+ * @address: address to start with.
+ * @size: size of buffer to unpoison.
+ *
+ * Until other data is written to this range, KMSAN will treat it as
+ * initialized.
+ */
+void kmsan_unpoison_memory(const void *address, size_t size);
+
+/**
+ * kmsan_check_memory() - Check the memory range for being initialized.
+ * @address: address to start with.
+ * @size: size of buffer to check.
+ *
+ * If any piece of the given range is marked as uninitialized, KMSAN will report
+ * an error.
+ */
+void kmsan_check_memory(const void *address, size_t size);
+
+/**
+ * kmsan_copy_to_user() - Notify KMSAN about a data transfer to userspace.
+ * @to: destination address in the userspace.
+ * @from: source address in the kernel.
+ * @to_copy: number of bytes to copy.
+ * @left: number of bytes not copied.
+ *
+ * If this is a real userspace data transfer, KMSAN checks the bytes that were
+ * actually copied to ensure there was no information leak. If @to belongs to
+ * the kernel space (which is possible for compat syscalls), KMSAN just copies
+ * the metadata.
+ */
+void kmsan_copy_to_user(void __user *to, const void *from, size_t to_copy,
+ size_t left);
+
+/**
+ * kmsan_memmove() - Notify KMSAN about a data copy within kernel.
+ * @to: destination address in the kernel.
+ * @from: source address in the kernel.
+ * @size: number of bytes to copy.
+ *
+ * Invoked after non-instrumented version (e.g. implemented using assembly
+ * code) of memmove()/memcpy() is called, in order to copy KMSAN's metadata.
+ */
+void kmsan_memmove(void *to, const void *from, size_t to_copy);
+
+#else
+
+static inline void kmsan_poison_memory(const void *address, size_t size,
+ gfp_t flags)
+{
+}
+static inline void kmsan_unpoison_memory(const void *address, size_t size)
+{
+}
+static inline void kmsan_check_memory(const void *address, size_t size)
+{
+}
+static inline void kmsan_copy_to_user(void __user *to, const void *from,
+ size_t to_copy, size_t left)
+{
+}
+
+static inline void kmsan_memmove(void *to, const void *from, size_t to_copy)
+{
+}
+
+#endif
+
+#endif /* _LINUX_KMSAN_CHECKS_H */
--git a/tools/perf/check-headers.sh b/tools/perf/check-headers.sh
index 531c0e0e84df..76fc6e20096c 100755
--- a/tools/perf/check-headers.sh
+++ b/tools/perf/check-headers.sh
@@ -28,6 +28,7 @@ declare -a FILES=(
"include/vdso/unaligned.h"
"include/linux/gfp_types.h"
"include/linux/hash.h"
+ "include/linux/kmsan-checks.h"
"include/linux/list-sort.h"
"include/uapi/linux/hw_breakpoint.h"
"arch/x86/include/asm/cpufeatures.h"
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 23/30] tools headers: Add linux/nospec.h copy from the kernel sources
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (21 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 22/30] tools headers: Add linux/kmsan-checks.h copy from the kernel sources Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 24/30] tools headers: Add linux/unwind_dwarf_cfi.h " Ian Rogers
` (6 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Copy include/linux/nospec.h to tools/include/linux/nospec.h (using the
standard /* ... */ header SPDX comment style), include
<asm-generic/bitsperlong.h> in tools/include/linux/kernel.h for
BITS_PER_LONG, and register linux/nospec.h in
tools/perf/check-headers.sh.
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/include/linux/kernel.h | 1 +
tools/include/linux/nospec.h | 74 ++++++++++++++++++++++++++++++++++++
| 1 +
3 files changed, 76 insertions(+)
create mode 100644 tools/include/linux/nospec.h
diff --git a/tools/include/linux/kernel.h b/tools/include/linux/kernel.h
index c8c18d3908a9..e0108edc2251 100644
--- a/tools/include/linux/kernel.h
+++ b/tools/include/linux/kernel.h
@@ -11,6 +11,7 @@
#include <linux/panic.h>
#include <endian.h>
#include <byteswap.h>
+#include <asm-generic/bitsperlong.h>
#include <linux/container_of.h>
#ifndef UINT_MAX
diff --git a/tools/include/linux/nospec.h b/tools/include/linux/nospec.h
new file mode 100644
index 000000000000..464a9a9e16ba
--- /dev/null
+++ b/tools/include/linux/nospec.h
@@ -0,0 +1,74 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+// Copyright(c) 2018 Linus Torvalds. All rights reserved.
+// Copyright(c) 2018 Alexei Starovoitov. All rights reserved.
+// Copyright(c) 2018 Intel Corporation. All rights reserved.
+
+#ifndef _LINUX_NOSPEC_H
+#define _LINUX_NOSPEC_H
+
+#include <linux/compiler.h>
+#include <asm/barrier.h>
+
+struct task_struct;
+
+#ifndef barrier_nospec
+# define barrier_nospec() do { } while (0)
+#endif
+
+/**
+ * array_index_mask_nospec() - generate a ~0 mask when index < size, 0 otherwise
+ * @index: array element index
+ * @size: number of elements in array
+ *
+ * When @index is out of bounds (@index >= @size), the sign bit will be
+ * set. Extend the sign bit to all bits and invert, giving a result of
+ * zero for an out of bounds index, or ~0 if within bounds [0, @size).
+ */
+#ifndef array_index_mask_nospec
+static inline unsigned long array_index_mask_nospec(unsigned long index,
+ unsigned long size)
+{
+ /*
+ * Always calculate and emit the mask even if the compiler
+ * thinks the mask is not needed. The compiler does not take
+ * into account the value of @index under speculation.
+ */
+ OPTIMIZER_HIDE_VAR(index);
+ return ~(long)(index | (size - 1UL - index)) >> (BITS_PER_LONG - 1);
+}
+#endif
+
+/*
+ * array_index_nospec - sanitize an array index after a bounds check
+ *
+ * For a code sequence like:
+ *
+ * if (index < size) {
+ * index = array_index_nospec(index, size);
+ * val = array[index];
+ * }
+ *
+ * ...if the CPU speculates past the bounds check then
+ * array_index_nospec() will clamp the index within the range of [0,
+ * size).
+ */
+#define array_index_nospec(index, size) \
+({ \
+ typeof(index) _i = (index); \
+ typeof(size) _s = (size); \
+ unsigned long _mask = array_index_mask_nospec(_i, _s); \
+ \
+ BUILD_BUG_ON(sizeof(_i) > sizeof(long)); \
+ BUILD_BUG_ON(sizeof(_s) > sizeof(long)); \
+ \
+ (typeof(_i)) (_i & _mask); \
+})
+
+/* Speculation control prctl */
+int arch_prctl_spec_ctrl_get(struct task_struct *task, unsigned long which);
+int arch_prctl_spec_ctrl_set(struct task_struct *task, unsigned long which,
+ unsigned long ctrl);
+/* Speculation control for seccomp enforced mitigation */
+void arch_seccomp_spec_mitigate(struct task_struct *task);
+
+#endif /* _LINUX_NOSPEC_H */
--git a/tools/perf/check-headers.sh b/tools/perf/check-headers.sh
index 76fc6e20096c..3e684c851a86 100755
--- a/tools/perf/check-headers.sh
+++ b/tools/perf/check-headers.sh
@@ -193,6 +193,7 @@ check include/uapi/asm-generic/mman.h '-I "^#include <\(uapi/\)*asm-generic/mman
check include/uapi/linux/mman.h '-I "^#include <\(uapi/\)*asm/mman.h>"'
check include/linux/build_bug.h '-I "^#\(ifndef\|endif\)\( \/\/\)* static_assert$"'
check include/linux/ctype.h '-I "isdigit("'
+check include/linux/nospec.h '-I "^.*[S]PDX-License-Identifier:"'
check lib/ctype.c '-I "^EXPORT_SYMBOL" -I "^#include <linux/export.h>" -B'
# diff non-symmetric files
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 24/30] tools headers: Add linux/unwind_dwarf_cfi.h copy from the kernel sources
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (22 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 23/30] tools headers: Add linux/nospec.h " Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 25/30] tools include: Add linux/uaccess.h stub for userspace tools Ian Rogers
` (5 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Copy include/linux/unwind_dwarf_cfi.h to
tools/include/linux/unwind_dwarf_cfi.h for host unwinding verification
tools under tools/, and add it to tools/perf/check-headers.sh.
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/include/linux/unwind_dwarf_cfi.h | 181 +++++++++++++++++++++++++
| 1 +
2 files changed, 182 insertions(+)
create mode 100644 tools/include/linux/unwind_dwarf_cfi.h
diff --git a/tools/include/linux/unwind_dwarf_cfi.h b/tools/include/linux/unwind_dwarf_cfi.h
new file mode 100644
index 000000000000..3530794c8543
--- /dev/null
+++ b/tools/include/linux/unwind_dwarf_cfi.h
@@ -0,0 +1,181 @@
+/* SPDX-License-Identifier: GPL-2.0-only OR MIT */
+#ifndef _LINUX_UNWIND_DWARF_CFI_H
+#define _LINUX_UNWIND_DWARF_CFI_H
+
+#include <linux/types.h>
+
+/*
+ * Minimal DWARF Call Frame Information (CFI) unwinder subset.
+ *
+ * Evaluates a strictly bounded, non-Turing-complete subset of .eh_frame and
+ * .eh_frame_hdr tables matching SFrame's stack-unwinding state model (plus
+ * fixed-pattern DRAP stack-realignment and signal-frame expressions):
+ * - Advances PC monotonically through a single FDE (no backward jumps)
+ * - Tracks CFA = (SP | FP | scratch) + cfa_off or *(FP/SP + cfa_off)
+ * - Tracks stack save offsets for SP, FP, and RA (ignoring callee-saved GPR
+ * spills)
+ * - Rejects general DWARF expressions, register-to-register rules on SP/FP/RA,
+ * and DW_EH_PE_indirect FDE/table pointer encodings (skipping CIE
+ * personality and LSDA fields without dereferencing).
+ */
+
+/* Hard safety bounds enforced on CIE/FDE lengths, offsets, and state stack */
+#define DWARF_CFI_MAX_CIE_LEN 128U
+#define DWARF_CFI_MAX_FDE_LEN 4096U
+#define DWARF_CFI_MAX_CIE_DELTA (64U * 1024U * 1024U)
+#define DWARF_CFI_MAX_FDE_COUNT (4U * 1024U * 1024U)
+#define DWARF_CFI_MAX_STATE_STACK 4U
+
+/**
+ * enum dwarf_cfi_base - Base register or addressing mode for computing the CFA
+ * @DWARF_CFI_BASE_UNDEFINED: CFA rule has not been established yet.
+ * @DWARF_CFI_BASE_SP: CFA = stack pointer + cfa_off.
+ * @DWARF_CFI_BASE_FP: CFA = frame pointer + cfa_off.
+ * @DWARF_CFI_BASE_FP_INDIRECT: DRAP stack realignment: CFA = *(FP + cfa_off).
+ * @DWARF_CFI_BASE_SP_INDIRECT: Signal trampoline frame: CFA = *(SP + cfa_off).
+ * @DWARF_CFI_BASE_REG: Transient prologue/epilogue scratch register:
+ * CFA = reg(cfa_reg) + cfa_off.
+ */
+enum dwarf_cfi_base {
+ DWARF_CFI_BASE_UNDEFINED = 0,
+ DWARF_CFI_BASE_SP,
+ DWARF_CFI_BASE_FP,
+ DWARF_CFI_BASE_FP_INDIRECT,
+ DWARF_CFI_BASE_SP_INDIRECT,
+ DWARF_CFI_BASE_REG,
+};
+
+/**
+ * enum dwarf_cfi_rule - Recovery rule for caller's SP, FP, or return address
+ * @DWARF_CFI_RULE_SAME: Register retains its value from the current frame
+ * (or defaults to CFA for SP).
+ * @DWARF_CFI_RULE_OFFSET: Saved on the stack at *(CFA + off).
+ * @DWARF_CFI_RULE_FP_OFFSET: Saved relative to FP at *(FP + off) (DRAP frame).
+ * @DWARF_CFI_RULE_SP_OFFSET: Saved relative to SP at *(SP + off) (sigframe).
+ * @DWARF_CFI_RULE_UNDEFINED: Explicitly undefined (DW_CFA_undefined); marks
+ * the bottom of a stack (e.g. _start or clone).
+ */
+enum dwarf_cfi_rule {
+ DWARF_CFI_RULE_SAME = 0,
+ DWARF_CFI_RULE_OFFSET,
+ DWARF_CFI_RULE_FP_OFFSET,
+ DWARF_CFI_RULE_SP_OFFSET,
+ DWARF_CFI_RULE_UNDEFINED,
+};
+
+/**
+ * struct dwarf_cfi_arch - Architecture DWARF register numbers and word size
+ * @ws: Target address/word size in bytes (4 or 8).
+ * @sp_reg: DWARF register number for the stack pointer.
+ * @fp_reg: DWARF register number for the frame pointer.
+ * @ra_reg: Default DWARF return-address column number.
+ */
+struct dwarf_cfi_arch {
+ u8 ws;
+ u8 sp_reg;
+ u8 fp_reg;
+ u8 ra_reg;
+};
+
+/**
+ * struct dwarf_cfi_row - Evaluated Minimal DWARF unwind state at a target PC
+ * @cfa_off: Byte offset added to the CFA base register before or as the CFA.
+ * @sp_off: Byte offset used to load the saved SP when @sp_rule is an offset.
+ * @fp_off: Byte offset used to load the saved FP when @fp_rule is an offset.
+ * @ra_off: Byte offset used to load the saved RA when @ra_rule is an offset.
+ * @cfa_base: CFA computation mode (&enum dwarf_cfi_base).
+ * @cfa_reg: DWARF register number when @cfa_base is %DWARF_CFI_BASE_REG.
+ * @sp_rule: Recovery rule for the stack pointer (&enum dwarf_cfi_rule;
+ * %DWARF_CFI_RULE_SAME indicates caller SP equals CFA).
+ * @fp_rule: Recovery rule for the frame pointer (&enum dwarf_cfi_rule).
+ * @ra_rule: Recovery rule for the return address (&enum dwarf_cfi_rule).
+ * @signal: True if the CIE carries the 'S' signal/interrupt frame augmentation,
+ * indicating that the saved PC points directly to the interrupted
+ * instruction rather than after a call instruction.
+ * @ra_signed: True on AArch64 when DW_CFA_AARCH64_negate_ra_state indicates
+ * that the saved return address carries a PAC signature.
+ */
+struct dwarf_cfi_row {
+ s32 cfa_off;
+ s32 sp_off;
+ s32 fp_off;
+ s32 ra_off;
+ u8 cfa_base;
+ u8 cfa_reg;
+ u8 sp_rule;
+ u8 fp_rule;
+ u8 ra_rule;
+ bool signal;
+ bool ra_signed;
+};
+
+/**
+ * struct eh_frame_hdr_entry - Binary-search index entry for an FDE
+ * @start_off: Signed 32-bit offset from the table base (or entry field) to the
+ * FDE's initial PC location.
+ * @fde_off: Signed 32-bit offset from the table base (or entry field) to the
+ * start of the FDE record in .eh_frame.
+ */
+struct eh_frame_hdr_entry {
+ s32 start_off;
+ s32 fde_off;
+};
+
+#ifdef CONFIG_UNWIND_DWARF_CFI
+
+extern const u8 __start_eh_frame_hdr[];
+extern const u8 __stop_eh_frame_hdr[];
+extern const u8 __start_eh_frame[];
+extern const u8 __stop_eh_frame[];
+
+int dwarf_cfi_eval_fde_kmem(const u8 *fde, const u8 *eh_start,
+ const u8 *eh_end, unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+
+int dwarf_cfi_unwind_eh_frame_hdr(const u8 *hdr, size_t hdr_size,
+ const u8 *eh_start, const u8 *eh_end,
+ unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+
+int dwarf_cfi_scan_eh_frame_kmem(const u8 *eh_start, size_t eh_size,
+ const struct dwarf_cfi_arch *arch,
+ unsigned long base_addr,
+ struct eh_frame_hdr_entry *entries,
+ unsigned int max_entries,
+ unsigned int *out_count);
+
+int dwarf_cfi_unwind_user_eh_frame_hdr(unsigned long hdr_uaddr,
+ size_t hdr_size, unsigned long pc,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+
+#if defined(CONFIG_UNWINDER_DWARF_CFI) && defined(CONFIG_MODULES)
+/**
+ * struct mod_dwarf_cfi_index - Sorted FDE lookup table for a loadable module
+ * @num_fdes: Number of sorted FDE index entries in @entries.
+ * @eh_frame: Pointer to the module's in-memory SHF_ALLOC .eh_frame section;
+ * also serves as the base address for @entries offsets.
+ * @eh_frame_size: Size in bytes of the module's .eh_frame section.
+ * @entries: Sorted binary-search table mapping PCs to module FDEs.
+ */
+struct mod_dwarf_cfi_index {
+ unsigned int num_fdes;
+ const u8 *eh_frame;
+ size_t eh_frame_size;
+ struct eh_frame_hdr_entry entries[] __counted_by(num_fdes);
+};
+
+struct mod_dwarf_cfi_index *dwarf_cfi_mod_alloc(const void *eh_frame,
+ size_t eh_frame_size,
+ const struct dwarf_cfi_arch *arch);
+void dwarf_cfi_mod_free_rcu(struct mod_dwarf_cfi_index *idx);
+int dwarf_cfi_mod_eval(const struct mod_dwarf_cfi_index *idx, unsigned long ip,
+ const struct dwarf_cfi_arch *arch,
+ struct dwarf_cfi_row *out_row);
+#endif
+
+#endif /* CONFIG_UNWIND_DWARF_CFI */
+
+#endif /* _LINUX_UNWIND_DWARF_CFI_H */
--git a/tools/perf/check-headers.sh b/tools/perf/check-headers.sh
index 3e684c851a86..1b1bd04a6690 100755
--- a/tools/perf/check-headers.sh
+++ b/tools/perf/check-headers.sh
@@ -30,6 +30,7 @@ declare -a FILES=(
"include/linux/hash.h"
"include/linux/kmsan-checks.h"
"include/linux/list-sort.h"
+ "include/linux/unwind_dwarf_cfi.h"
"include/uapi/linux/hw_breakpoint.h"
"arch/x86/include/asm/cpufeatures.h"
"arch/x86/include/asm/inat_types.h"
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 25/30] tools include: Add linux/uaccess.h stub for userspace tools
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (23 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 24/30] tools headers: Add linux/unwind_dwarf_cfi.h " Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 26/30] tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier Ian Rogers
` (4 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 minimal tools/include/linux/uaccess.h providing a no-op
might_fault() stub so userspace tools under tools/ can compile shared
kernel code that includes <linux/uaccess.h>.
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/include/linux/uaccess.h | 9 +++++++++
1 file changed, 9 insertions(+)
create mode 100644 tools/include/linux/uaccess.h
diff --git a/tools/include/linux/uaccess.h b/tools/include/linux/uaccess.h
new file mode 100644
index 000000000000..5a9e6bf4cfb5
--- /dev/null
+++ b/tools/include/linux/uaccess.h
@@ -0,0 +1,9 @@
+/* SPDX-License-Identifier: GPL-2.0-only OR MIT */
+#ifndef _TOOLS_INCLUDE_LINUX_UACCESS_H
+#define _TOOLS_INCLUDE_LINUX_UACCESS_H
+
+#ifndef might_fault
+#define might_fault() do { } while (0)
+#endif
+
+#endif /* _TOOLS_INCLUDE_LINUX_UACCESS_H */
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 26/30] tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (24 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 25/30] tools include: Add linux/uaccess.h stub for userspace tools Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 27/30] tools/unwind: Add multi-arch symbolic instruction lifters for verify_cfi Ian Rogers
` (3 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 host verification tool (tools/unwind/verify_cfi,
built via `make -C tools/unwind` or `make tools/unwind` when libLLVM is
detected via tools/build/Makefile.feature, and gracefully skipped
otherwise) linked directly against kernel/unwind/dwarf_cfi.c.
This initial commit implements the CLI harness, host VMA and kmem buffer
wrappers (dwarf_cfi_host.c), and Oracle 1 (verifyOracle1Dwarf()), which
evaluates libLLVM's full reference DWARFUnwindTable
(llvm::dwarf::createUnwindTable) and verifies exact agreement with both
dwarf_cfi_unwind_user_eh_frame_hdr() and dwarf_cfi_unwind_eh_frame_hdr()
at every FDE start, row-transition boundary (pc - 1 and pc), and end PC.
Across 207,450 vmlinux FDEs (2,575,276 transition PCs) on x86_64, arm64,
and riscv64, plus user-space shared libraries (libc.so.6, libstdc++.so.6,
libcrypto.so.3, /bin/bash), Oracle 1 reports 0 mismatches.
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/Makefile | 13 +-
tools/unwind/.gitignore | 4 +
tools/unwind/Makefile | 123 ++++++
tools/unwind/dwarf_cfi_host.c | 80 ++++
tools/unwind/dwarf_cfi_host.h | 42 ++
tools/unwind/verify_cfi.cpp | 789 ++++++++++++++++++++++++++++++++++
tools/unwind/verify_cfi.hpp | 147 +++++++
7 files changed, 1192 insertions(+), 6 deletions(-)
create mode 100644 tools/unwind/.gitignore
create mode 100644 tools/unwind/Makefile
create mode 100644 tools/unwind/dwarf_cfi_host.c
create mode 100644 tools/unwind/dwarf_cfi_host.h
create mode 100644 tools/unwind/verify_cfi.cpp
create mode 100644 tools/unwind/verify_cfi.hpp
diff --git a/tools/Makefile b/tools/Makefile
index cb40961a740f..0890921e56b2 100644
--- a/tools/Makefile
+++ b/tools/Makefile
@@ -37,6 +37,7 @@ help:
@echo ' thermal - thermal library'
@echo ' tracing - misc tracing tools'
@echo ' turbostat - Intel CPU idle stats and freq reporting tool'
+ @echo ' unwind - Minimal DWARF CFI static verifier'
@echo ' usb - USB testing tools'
@echo ' virtio - vhost test module'
@echo ' mm - misc mm tools'
@@ -70,7 +71,7 @@ acpi: FORCE
cpupower: FORCE
$(call descend,power/$@)
-counter dma firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi firmware debugging tracing: FORCE
+counter dma firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi firmware debugging tracing unwind: FORCE
$(call descend,$@)
bpf/%: FORCE
@@ -127,7 +128,7 @@ all: acpi counter cpupower dma gpio hv firewire \
perf selftests bootconfig spi turbostat usb \
virtio mm bpf x86_energy_perf_policy \
tmon freefall iio objtool kvm_stat wmi \
- debugging tracing thermal thermometer thermal-engine ynl
+ debugging tracing thermal thermometer thermal-engine unwind ynl
acpi_install:
$(call descend,power/$(@:_install=),install)
@@ -135,7 +136,7 @@ acpi_install:
cpupower_install:
$(call descend,power/$(@:_install=),install)
-counter_install dma_install firewire_install gpio_install hv_install iio_install perf_install bootconfig_install spi_install usb_install virtio_install mm_install bpf_install objtool_install wmi_install debugging_install tracing_install:
+counter_install dma_install firewire_install gpio_install hv_install iio_install perf_install bootconfig_install spi_install usb_install virtio_install mm_install bpf_install objtool_install wmi_install debugging_install tracing_install unwind_install:
$(call descend,$(@:_install=),install)
selftests_install:
@@ -171,7 +172,7 @@ install: acpi_install counter_install cpupower_install dma_install gpio_install
virtio_install mm_install bpf_install x86_energy_perf_policy_install \
tmon_install freefall_install objtool_install kvm_stat_install \
wmi_install debugging_install intel-speed-select_install \
- tracing_install thermometer_install thermal-engine_install ynl_install
+ tracing_install thermometer_install thermal-engine_install unwind_install ynl_install
acpi_clean:
$(call descend,power/acpi,clean)
@@ -179,7 +180,7 @@ acpi_clean:
cpupower_clean:
$(call descend,power/cpupower,clean)
-counter_clean dma_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean firmware_clean debugging_clean tracing_clean:
+counter_clean dma_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean firmware_clean debugging_clean tracing_clean unwind_clean:
$(call descend,$(@:_clean=),clean)
libapi_clean:
@@ -231,6 +232,6 @@ clean: acpi_clean counter_clean cpupower_clean dma_clean hv_clean firewire_clean
freefall_clean build_clean libbpf_clean libsubcmd_clean \
gpio_clean objtool_clean leds_clean wmi_clean firmware_clean debugging_clean \
intel-speed-select_clean tracing_clean thermal_clean thermometer_clean thermal-engine_clean \
- sched_ext_clean ynl_clean
+ sched_ext_clean unwind_clean ynl_clean
.PHONY: FORCE
diff --git a/tools/unwind/.gitignore b/tools/unwind/.gitignore
new file mode 100644
index 000000000000..1fa1fbaca9b0
--- /dev/null
+++ b/tools/unwind/.gitignore
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+verify_cfi
+FEATURE-DUMP*
+feature/
diff --git a/tools/unwind/Makefile b/tools/unwind/Makefile
new file mode 100644
index 000000000000..ca6b84dbd31a
--- /dev/null
+++ b/tools/unwind/Makefile
@@ -0,0 +1,123 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+include ../scripts/Makefile.include
+
+bindir ?= /usr/bin
+
+ifeq ($(srctree),)
+srctree := $(patsubst %/,%,$(dir $(CURDIR)))
+srctree := $(patsubst %/,%,$(dir $(srctree)))
+endif
+
+ifneq ($(LLVM),)
+ $(call allow-override,HOSTCXX,$(LLVM_PREFIX)clang++$(LLVM_SUFFIX))
+else
+ $(call allow-override,HOSTCXX,g++)
+endif
+
+# verify_cfi is a host analysis tool; ensure feature checks probe the host
+# compiler even when CROSS_COMPILE is set in the environment.
+CC := $(HOSTCC)
+CXX := $(HOSTCXX)
+
+# Auto-discover versioned llvm-config (e.g. Debian/Ubuntu llvm-config-21) when
+# the default unversioned binary is absent, and export it for Makefile.feature.
+ifeq ($(shell command -v $(firstword $(LLVM_CONFIG)) >/dev/null 2>&1 && echo y),)
+ LLVM_CONFIG_CANDIDATES := llvm-config-22 llvm-config-21 llvm-config-20 \
+ llvm-config-19 llvm-config-18
+ FOUND_LLVM_CONFIG := $(firstword $(foreach c,$(LLVM_CONFIG_CANDIDATES), \
+ $(if $(shell command -v $(c) >/dev/null 2>&1 && echo y),$(c))))
+ ifneq ($(FOUND_LLVM_CONFIG),)
+ LLVM_CONFIG := $(FOUND_LLVM_CONFIG)
+ endif
+endif
+export LLVM_CONFIG
+
+FEATURE_USER := .verify_cfi
+FEATURE_TESTS := llvm
+FEATURE_DISPLAY := llvm
+
+check_feat := 1
+NON_CHECK_FEAT_TARGETS := clean
+ifdef MAKECMDGOALS
+ifeq ($(filter-out $(NON_CHECK_FEAT_TARGETS),$(MAKECMDGOALS)),)
+ check_feat := 0
+endif
+endif
+ifeq ($(SKIP_LLVM),1)
+ check_feat := 0
+endif
+
+ifeq ($(check_feat),1)
+ifeq ($(FEATURES_DUMP),)
+include $(srctree)/tools/build/Makefile.feature
+else
+include $(FEATURES_DUMP)
+endif
+endif
+
+LLVM_COMPONENTS := debuginfodwarf object mc mcdisassembler all-targets support
+
+ifeq ($(feature-llvm),1)
+ifneq ($(SKIP_LLVM),1)
+ LLVM_INCDIR := $(shell $(LLVM_CONFIG) --includedir 2>/dev/null)
+ ifneq ($(wildcard $(LLVM_INCDIR)/llvm/DebugInfo/DWARF/LowLevel/DWARFUnwindTable.h),)
+ HAS_LIBLLVM := 1
+ LLVM_CXXFLAGS := $(filter-out -D_GNU_SOURCE -std=%,$(shell $(LLVM_CONFIG) --cxxflags 2>/dev/null))
+ LLVM_LDFLAGS := $(shell $(LLVM_CONFIG) --ldflags 2>/dev/null)
+ LLVM_LIBS := $(shell $(LLVM_CONFIG) --link-shared --libs $(LLVM_COMPONENTS) 2>/dev/null)
+ ifeq ($(LLVM_LIBS),)
+ LLVM_LIBS := $(shell $(LLVM_CONFIG) --libs $(LLVM_COMPONENTS) 2>/dev/null) \
+ $(shell $(LLVM_CONFIG) --system-libs $(LLVM_COMPONENTS) 2>/dev/null)
+ endif
+ endif
+endif
+endif
+
+TOOLS_INCLUDES := -I$(srctree)/tools/include -I$(srctree)/tools/include/uapi \
+ -I$(srctree)/tools/arch/x86/include
+
+SHIM_CFLAGS := -O2 -g -Wall -Wextra -Wno-unused-parameter -Wno-maybe-uninitialized \
+ $(TOOLS_INCLUDES)
+
+VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) \
+ -I$(CURDIR) $(TOOLS_INCLUDES) $(CXXFLAGS)
+VERIFY_LDFLAGS := $(LLVM_LDFLAGS) $(LDFLAGS)
+
+KERNEL_CFI_DEPS := $(srctree)/kernel/unwind/dwarf_cfi.c \
+ $(srctree)/tools/include/linux/unwind_dwarf_cfi.h
+
+VERIFY_OBJS := $(OUTPUT)dwarf_cfi_host.o \
+ $(OUTPUT)verify_cfi.o
+
+ifeq ($(HAS_LIBLLVM),1)
+all: $(OUTPUT)verify_cfi
+else
+all:
+ifeq ($(REQUIRE_LLVM),1)
+ $(error libLLVM 17+ development headers/libraries not found (LLVM_CONFIG=$(LLVM_CONFIG)))
+else
+ @echo " SKIP verify_cfi (libLLVM dev files not found; set LLVM_CONFIG=...)"
+endif
+endif
+
+$(OUTPUT)dwarf_cfi_host.o: dwarf_cfi_host.c dwarf_cfi_host.h $(KERNEL_CFI_DEPS)
+ $(QUIET_CC)$(HOSTCC) $(SHIM_CFLAGS) -c $< -o $@
+
+$(OUTPUT)%.o: %.cpp $(wildcard *.hpp) dwarf_cfi_host.h
+ $(QUIET_CXX)$(HOSTCXX) $(VERIFY_CXXFLAGS) -c $< -o $@
+
+$(OUTPUT)verify_cfi: $(VERIFY_OBJS)
+ $(QUIET_LINK)$(HOSTCXX) $(VERIFY_CXXFLAGS) $(VERIFY_OBJS) \
+ -o $@ $(VERIFY_LDFLAGS) $(LLVM_LIBS)
+
+install: all
+ @if [ -x "$(OUTPUT)verify_cfi" ]; then \
+ install -d -m 755 $(DESTDIR)$(bindir); \
+ install $(OUTPUT)verify_cfi $(DESTDIR)$(bindir); \
+ fi
+
+clean:
+ $(RM) -r $(OUTPUT)*.o $(OUTPUT)verify_cfi \
+ $(OUTPUT)feature $(OUTPUT)FEATURE-DUMP*
+
+.PHONY: all install clean
diff --git a/tools/unwind/dwarf_cfi_host.c b/tools/unwind/dwarf_cfi_host.c
new file mode 100644
index 000000000000..307b18fc6fe1
--- /dev/null
+++ b/tools/unwind/dwarf_cfi_host.c
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: GPL-2.0-only OR MIT
+/*
+ * Host userspace wrapper compiling kernel/unwind/dwarf_cfi.c verbatim against
+ * tools/include/ headers so verify_cfi exercises the exact kernel Minimal DWARF
+ * CFI interpreter on both the 128-byte windowed user stream path and the direct
+ * kmem noinstr path.
+ */
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+#include "dwarf_cfi_host.h"
+
+static const struct host_vma_seg *g_segs;
+static size_t g_nsegs;
+
+void host_set_vma_segs(const struct host_vma_seg *segs, size_t nsegs)
+{
+ g_segs = segs;
+ g_nsegs = nsegs;
+}
+
+static unsigned long host_copy_from_vma(void *to, const void *from_ptr,
+ unsigned long n)
+{
+ unsigned long addr = (unsigned long)from_ptr;
+ unsigned char *dst = to;
+
+ while (n > 0) {
+ bool found = false;
+ size_t i;
+
+ for (i = 0; i < g_nsegs; i++) {
+ unsigned long start = g_segs[i].vma;
+
+ if (addr >= start && (addr - start) < g_segs[i].size) {
+ unsigned long off = addr - start;
+ unsigned long avail = g_segs[i].size - off;
+ unsigned long chunk = n < avail ? n : avail;
+
+ memcpy(dst, g_segs[i].data + off, chunk);
+ dst += chunk;
+ addr += chunk;
+ n -= chunk;
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ return n;
+ }
+ return 0;
+}
+
+/*
+ * In userspace, <linux/limits.h> resolves to the UAPI header rather than
+ * kernel-internal include/linux/limits.h, and tools/include/linux/kernel.h
+ * avoids defining fixed-width integer bounds globally because other tools/
+ * targets define their own U8_MAX/U32_MAX macros.
+ */
+#ifndef U8_MAX
+#define U8_MAX ((u8)~0U)
+#endif
+#ifndef U32_MAX
+#define U32_MAX ((u32)~0U)
+#endif
+#ifndef S32_MAX
+#define S32_MAX ((s32)(U32_MAX >> 1))
+#endif
+#ifndef S32_MIN
+#define S32_MIN ((s32)(-S32_MAX - 1))
+#endif
+#ifndef noinstr
+#define noinstr
+#endif
+#define copy_from_user(to, from, n) host_copy_from_vma(to, from, n)
+
+#include "../../kernel/unwind/dwarf_cfi.c"
diff --git a/tools/unwind/dwarf_cfi_host.h b/tools/unwind/dwarf_cfi_host.h
new file mode 100644
index 000000000000..c797f9992bf1
--- /dev/null
+++ b/tools/unwind/dwarf_cfi_host.h
@@ -0,0 +1,42 @@
+/* SPDX-License-Identifier: GPL-2.0-only OR MIT */
+#ifndef _TOOLS_UNWIND_DWARF_CFI_HOST_H
+#define _TOOLS_UNWIND_DWARF_CFI_HOST_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+/*
+ * Note: In C++ files using LLVM headers, include this header AFTER <llvm/...>
+ * headers (matching tools/perf/util/llvm-c-helpers.cpp) because
+ * tools/include/linux/compiler.h defines macros such as 'noinline' that
+ * conflict with LLVM attribute declarations.
+ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef CONFIG_UNWIND_DWARF_CFI
+#define CONFIG_UNWIND_DWARF_CFI 1
+#endif
+#include <linux/unwind_dwarf_cfi.h>
+
+/**
+ * struct host_vma_seg - Simulated user VMA backing range for host CFI testing
+ * @vma: Starting virtual address of the ELF section/segment.
+ * @size: Length in bytes of the backing buffer @data.
+ * @data: Pointer to in-memory ELF section contents on the host.
+ */
+struct host_vma_seg {
+ unsigned long vma;
+ size_t size;
+ const uint8_t *data;
+};
+
+void host_set_vma_segs(const struct host_vma_seg *segs, size_t nsegs);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TOOLS_UNWIND_DWARF_CFI_HOST_H */
diff --git a/tools/unwind/verify_cfi.cpp b/tools/unwind/verify_cfi.cpp
new file mode 100644
index 000000000000..15d99ba57ce3
--- /dev/null
+++ b/tools/unwind/verify_cfi.cpp
@@ -0,0 +1,789 @@
+// SPDX-License-Identifier: GPL-2.0-only OR MIT
+/*
+ * Standalone Multi-Architecture Minimal DWARF CFI Verifier using libLLVM.
+ *
+ * Entry point and Oracle 1 (libLLVM reference DWARFUnwindTable vs. kernel
+ * Minimal DWARF interpreter across both user-stream and kmem paths), with
+ * optional compile-time hooks for Oracle 2 (HAVE_VERIFY_INSN) and Oracle 3
+ * (HAVE_VERIFY_ORC).
+ */
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/BinaryFormat/Dwarf.h"
+#include "llvm/BinaryFormat/ELF.h"
+#include "llvm/DebugInfo/DWARF/DWARFContext.h"
+#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
+#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
+#include "llvm/DebugInfo/DWARF/LowLevel/DWARFUnwindTable.h"
+#include "llvm/MC/MCAsmInfo.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCObjectFileInfo.h"
+#include "llvm/MC/MCTargetOptions.h"
+#include "llvm/MC/TargetRegistry.h"
+#include "llvm/Object/ELFObjectFile.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/raw_ostream.h"
+#pragma GCC diagnostic pop
+
+#include "verify_cfi.hpp"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+
+using namespace llvm;
+using namespace llvm::object;
+
+/**
+ * getArchSpec() - Populate target architecture metadata from an ELF ObjectFile
+ * @Obj: Parsed LLVM ObjectFile under inspection.
+ * @Out: Output &struct ArchSpec populated on success.
+ *
+ * Return: true if @Obj targets a supported architecture (x86_64, aarch64, or
+ * riscv64); false otherwise.
+ */
+static bool getArchSpec(const ObjectFile &Obj, ArchSpec &Out)
+{
+ auto A = Obj.getArch();
+ if (A == Triple::x86_64) {
+ Out = {Triple::x86_64, "x86_64-unknown-linux-gnu", "",
+ {8, 7, 6, 16}, 8, true};
+ return true;
+ }
+ if (A == Triple::aarch64) {
+ Out = {Triple::aarch64, "aarch64-unknown-linux-gnu",
+ "+v8.5a,+pauth,+bti", {8, 31, 29, 30}, 0, false};
+ return true;
+ }
+ if (A == Triple::riscv64) {
+ Out = {Triple::riscv64, "riscv64-unknown-linux-gnu",
+ "+m,+a,+f,+d,+c,+zicsr,+zifencei",
+ {8, 2, 8, 1}, 0, false};
+ return true;
+ }
+ return false;
+}
+
+/**
+ * rowsEqual() - Compare two evaluated Minimal DWARF unwind rows for equality
+ */
+bool rowsEqual(const dwarf_cfi_row &a, const dwarf_cfi_row &b)
+{
+ if (a.cfa_base != b.cfa_base || a.cfa_off != b.cfa_off ||
+ a.sp_rule != b.sp_rule || a.fp_rule != b.fp_rule ||
+ a.ra_rule != b.ra_rule || a.signal != b.signal ||
+ a.ra_signed != b.ra_signed)
+ return false;
+ if (a.cfa_base == DWARF_CFI_BASE_REG && a.cfa_reg != b.cfa_reg)
+ return false;
+ if (a.sp_rule == DWARF_CFI_RULE_OFFSET && a.sp_off != b.sp_off)
+ return false;
+ if ((a.fp_rule == DWARF_CFI_RULE_OFFSET ||
+ a.fp_rule == DWARF_CFI_RULE_FP_OFFSET ||
+ a.fp_rule == DWARF_CFI_RULE_SP_OFFSET) &&
+ a.fp_off != b.fp_off)
+ return false;
+ if ((a.ra_rule == DWARF_CFI_RULE_OFFSET ||
+ a.ra_rule == DWARF_CFI_RULE_SP_OFFSET) &&
+ a.ra_off != b.ra_off)
+ return false;
+ return true;
+}
+
+void recordIssue(VerifyStats &st, const VerifyOptions &opts,
+ const std::string &reason, const std::string &detail)
+{
+ uint64_t cnt = ++st.mismatch_reasons[reason];
+ if (cnt <= opts.max_samples &&
+ st.sample_issues.size() < opts.max_samples * 8)
+ st.sample_issues.push_back("[" + reason + "] " + detail);
+}
+
+ArrayRef<uint8_t> findExecBytes(const std::vector<ExecSec> &exec_secs,
+ uint64_t addr, uint64_t len)
+{
+ for (const auto &es : exec_secs) {
+ if (addr >= es.vma && len <= es.bytes.size() &&
+ (addr - es.vma) <= es.bytes.size() - len) {
+ const uint8_t *p =
+ reinterpret_cast<const uint8_t *>(es.bytes.data()) +
+ (addr - es.vma);
+ return ArrayRef<uint8_t>(p, len);
+ }
+ }
+ return {};
+}
+
+/**
+ * llvmRowToMinimal() - Convert an LLVM reference UnwindRow to Minimal DWARF
+ */
+static bool llvmRowToMinimal(const dwarf::UnwindRow &UR, const dwarf::CIE *Cie,
+ const dwarf_cfi_arch &arch, dwarf_cfi_row &out)
+{
+ memset(&out, 0, sizeof(out));
+ out.signal = Cie && Cie->getAugmentationString().contains('S');
+
+ if (arch.ra_reg == 30) {
+ if (auto Loc = UR.getRegisterLocations().getRegisterLocation(34)) {
+ if (Loc->getLocation() == dwarf::UnwindLocation::Constant)
+ out.ra_signed = (Loc->getConstant() != 0);
+ }
+ }
+
+ const auto &CFA = UR.getCFAValue();
+ if (CFA.getLocation() == dwarf::UnwindLocation::RegPlusOffset &&
+ !CFA.getDereference()) {
+ uint32_t r = CFA.getRegister();
+ if (r > 255)
+ return false;
+ if (r == arch.sp_reg)
+ out.cfa_base = DWARF_CFI_BASE_SP;
+ else if (r == arch.fp_reg)
+ out.cfa_base = DWARF_CFI_BASE_FP;
+ else
+ out.cfa_base = DWARF_CFI_BASE_REG;
+ out.cfa_reg = (uint8_t)r;
+ out.cfa_off = CFA.getOffset();
+ } else if (CFA.getLocation() == dwarf::UnwindLocation::DWARFExpr) {
+ auto ExprOpt = CFA.getDWARFExpressionBytes();
+ if (!ExprOpt)
+ return false;
+ SmallVector<DWARFExpression::Operation, 4> Ops;
+ for (auto &Op : *ExprOpt) {
+ if (Op.isError())
+ return false;
+ Ops.push_back(Op);
+ }
+ uint8_t breg_fp = dwarf::DW_OP_breg0 + arch.fp_reg;
+ uint8_t breg_sp = dwarf::DW_OP_breg0 + arch.sp_reg;
+ if (CFA.getDereference() && Ops.size() == 1 &&
+ (Ops[0].getCode() == breg_fp ||
+ Ops[0].getCode() == breg_sp)) {
+ out.cfa_base = (Ops[0].getCode() == breg_fp)
+ ? DWARF_CFI_BASE_FP_INDIRECT
+ : DWARF_CFI_BASE_SP_INDIRECT;
+ out.cfa_off = (int32_t)(int64_t)Ops[0].getRawOperand(0);
+ } else if (!CFA.getDereference() && Ops.size() == 2 &&
+ (Ops[0].getCode() == breg_fp ||
+ Ops[0].getCode() == breg_sp) &&
+ Ops[1].getCode() == dwarf::DW_OP_deref) {
+ out.cfa_base = (Ops[0].getCode() == breg_fp)
+ ? DWARF_CFI_BASE_FP_INDIRECT
+ : DWARF_CFI_BASE_SP_INDIRECT;
+ out.cfa_off = (int32_t)(int64_t)Ops[0].getRawOperand(0);
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ auto mapRegRule = [&](uint32_t reg, uint8_t &rule, int32_t &off,
+ bool is_sp, bool is_ra) -> bool {
+ auto LocOpt = UR.getRegisterLocations().getRegisterLocation(reg);
+ if (!LocOpt) {
+ rule = DWARF_CFI_RULE_SAME;
+ off = 0;
+ return true;
+ }
+ const auto &L = *LocOpt;
+ switch (L.getLocation()) {
+ case dwarf::UnwindLocation::Unspecified:
+ case dwarf::UnwindLocation::Same:
+ rule = DWARF_CFI_RULE_SAME;
+ off = 0;
+ return true;
+ case dwarf::UnwindLocation::Undefined:
+ rule = DWARF_CFI_RULE_UNDEFINED;
+ off = 0;
+ return true;
+ case dwarf::UnwindLocation::CFAPlusOffset:
+ if (!L.getDereference())
+ return false;
+ rule = DWARF_CFI_RULE_OFFSET;
+ off = L.getOffset();
+ return true;
+ case dwarf::UnwindLocation::DWARFExpr: {
+ if (!L.getDereference())
+ return false;
+ auto ExprOpt = L.getDWARFExpressionBytes();
+ if (!ExprOpt)
+ return false;
+ SmallVector<DWARFExpression::Operation, 4> Ops;
+ for (auto &Op : *ExprOpt) {
+ if (Op.isError())
+ return false;
+ Ops.push_back(Op);
+ }
+ uint8_t breg_fp = dwarf::DW_OP_breg0 + arch.fp_reg;
+ uint8_t breg_sp = dwarf::DW_OP_breg0 + arch.sp_reg;
+ if (Ops.size() == 1 &&
+ (Ops[0].getCode() == breg_fp ||
+ Ops[0].getCode() == breg_sp)) {
+ int32_t o =
+ (int32_t)(int64_t)Ops[0].getRawOperand(0);
+ if (is_sp) {
+ if (Ops[0].getCode() == breg_sp &&
+ out.cfa_base ==
+ DWARF_CFI_BASE_SP_INDIRECT &&
+ o == out.cfa_off) {
+ rule = DWARF_CFI_RULE_SAME;
+ off = 0;
+ return true;
+ }
+ return false;
+ }
+ if (is_ra && Ops[0].getCode() != breg_sp)
+ return false;
+ rule = (Ops[0].getCode() == breg_fp)
+ ? DWARF_CFI_RULE_FP_OFFSET
+ : DWARF_CFI_RULE_SP_OFFSET;
+ off = o;
+ return true;
+ }
+ return false;
+ }
+ default:
+ return false;
+ }
+ };
+
+ uint32_t ra_col = Cie ? (uint32_t)Cie->getReturnAddressRegister()
+ : arch.ra_reg;
+ if (!mapRegRule(arch.fp_reg, out.fp_rule, out.fp_off, false, false))
+ return false;
+ if (!mapRegRule(ra_col, out.ra_rule, out.ra_off, false, true))
+ return false;
+ if (!mapRegRule(arch.sp_reg, out.sp_rule, out.sp_off, true, false))
+ return false;
+
+ return true;
+}
+
+static bool isRelativeEhEncoding(uint8_t enc)
+{
+ if (enc == dwarf::DW_EH_PE_omit)
+ return true;
+ uint8_t adj = enc & 0x70;
+ return adj == dwarf::DW_EH_PE_pcrel || adj == dwarf::DW_EH_PE_datarel;
+}
+
+/**
+ * verifyOracle1Dwarf() - Cross-check libLLVM DWARFUnwindTable vs. dwarf_cfi.c
+ */
+static int verifyOracle1Dwarf(const ObjectFile &Obj, const ArchSpec &AS,
+ uint64_t eh_hdr_vma, StringRef eh_hdr_bytes,
+ uint64_t min_eh_vma, bool can_test_kmem,
+ const std::vector<uint8_t> &kmem_arena,
+ const uint8_t *kmem_hdr,
+ const uint8_t *kmem_eh_start,
+ const uint8_t *kmem_eh_end,
+ const VerifyOptions &opts, VerifyStats &st,
+ std::vector<FDERange> &fde_ranges)
+{
+ std::unique_ptr<DWARFContext> DCtx = DWARFContext::create(Obj);
+ auto EHOrErr = DCtx->getEHFrame();
+ if (!EHOrErr) {
+ consumeError(EHOrErr.takeError());
+ return 1;
+ }
+ const DWARFDebugFrame *EH = *EHOrErr;
+
+ for (const dwarf::FrameEntry &FE : EH->entries()) {
+ const auto *Fde = dyn_cast<dwarf::FDE>(&FE);
+ if (!Fde || Fde->getAddressRange() == 0)
+ continue;
+ st.fdes_total++;
+
+ uint64_t fstart = Fde->getInitialLocation();
+ uint64_t fend = fstart + Fde->getAddressRange();
+
+ auto UTOrErr = dwarf::createUnwindTable(Fde);
+ if (!UTOrErr) {
+ consumeError(UTOrErr.takeError());
+ st.fdes_outside_minimal++;
+ fde_ranges.push_back({fstart, fend, false, false});
+ continue;
+ }
+ const dwarf::UnwindTable &UT = *UTOrErr;
+ if (UT.size() == 0) {
+ st.fdes_outside_minimal++;
+ fde_ranges.push_back({fstart, fend, false, false});
+ continue;
+ }
+
+ bool all_rows_minimal = true;
+ std::vector<std::pair<uint64_t, dwarf_cfi_row>> exp_rows;
+ exp_rows.reserve(UT.size());
+ for (size_t i = 0; i < UT.size(); i++) {
+ dwarf_cfi_row mr;
+ if (!llvmRowToMinimal(UT[i], Fde->getLinkedCIE(),
+ AS.karch, mr)) {
+ all_rows_minimal = false;
+ break;
+ }
+ exp_rows.push_back({UT[i].getAddress(), mr});
+ }
+
+ if (!all_rows_minimal) {
+ st.fdes_outside_minimal++;
+ fde_ranges.push_back({fstart, fend, false, false});
+ continue;
+ }
+ st.fdes_minimal_supported++;
+ const dwarf::CIE *Cie = Fde->getLinkedCIE();
+ bool is_sig = Cie && Cie->getAugmentationString().contains('S');
+ bool fde_rel = Cie &&
+ isRelativeEhEncoding(Cie->getFDEPointerEncoding());
+ fde_ranges.push_back({fstart, fend, true, is_sig});
+
+ SmallVector<uint64_t, 16> check_pcs;
+ check_pcs.push_back(fstart);
+ for (auto &pr : exp_rows) {
+ if (pr.first >= fstart && pr.first < fend) {
+ if (pr.first > fstart)
+ check_pcs.push_back(pr.first - 1);
+ check_pcs.push_back(pr.first);
+ }
+ }
+ check_pcs.push_back(fend - 1);
+ std::sort(check_pcs.begin(), check_pcs.end());
+ check_pcs.erase(std::unique(check_pcs.begin(), check_pcs.end()),
+ check_pcs.end());
+
+ for (uint64_t pc : check_pcs) {
+ const dwarf_cfi_row *exp = &exp_rows[0].second;
+ for (auto &pr : exp_rows) {
+ if (pr.first <= pc)
+ exp = &pr.second;
+ else
+ break;
+ }
+
+ dwarf_cfi_row krow_user{};
+ int err_u = dwarf_cfi_unwind_user_eh_frame_hdr(
+ (unsigned long)eh_hdr_vma, eh_hdr_bytes.size(),
+ (unsigned long)pc, &AS.karch, &krow_user);
+ st.fde_pc_checks++;
+
+ if (err_u != 0 || !rowsEqual(krow_user, *exp)) {
+ st.llvm_vs_kernel_mismatches++;
+ char buf[200];
+ snprintf(buf, sizeof(buf),
+ "PC=0x%" PRIx64 " err_u=%d kernel(cfa=%u:%d fp=%u:%d ra=%u:%d)"
+ " llvm(cfa=%u:%d fp=%u:%d ra=%u:%d)",
+ pc, err_u, krow_user.cfa_base,
+ krow_user.cfa_off, krow_user.fp_rule,
+ krow_user.fp_off, krow_user.ra_rule,
+ krow_user.ra_off, exp->cfa_base,
+ exp->cfa_off, exp->fp_rule,
+ exp->fp_off, exp->ra_rule,
+ exp->ra_off);
+ recordIssue(st, opts, "llvm_vs_kernel_dwarf",
+ buf);
+ }
+
+ if (can_test_kmem && fde_rel) {
+ dwarf_cfi_row krow_kmem{};
+ uintptr_t base_u =
+ reinterpret_cast<uintptr_t>(kmem_arena.data());
+ unsigned long kpc = (unsigned long)(
+ base_u +
+ static_cast<uintptr_t>(pc - min_eh_vma));
+ int err_k = dwarf_cfi_unwind_eh_frame_hdr(
+ kmem_hdr, eh_hdr_bytes.size(),
+ kmem_eh_start, kmem_eh_end, kpc,
+ &AS.karch, &krow_kmem);
+ st.kmem_pc_checks++;
+ if (err_k != err_u ||
+ (err_u == 0 &&
+ !rowsEqual(krow_kmem, krow_user)))
+ st.kmem_vs_user_mismatches++;
+ }
+ }
+ }
+
+ std::sort(fde_ranges.begin(), fde_ranges.end(),
+ [](const FDERange &a, const FDERange &b) {
+ return a.start < b.start;
+ });
+ return 0;
+}
+
+static int verifyFile(const char *path, const VerifyOptions &opts)
+{
+ auto BufOrErr = MemoryBuffer::getFile(path);
+ if (!BufOrErr) {
+ errs() << "Failed to open " << path << "\n";
+ return 1;
+ }
+ auto ObjOrErr =
+ ObjectFile::createObjectFile(BufOrErr.get()->getMemBufferRef());
+ if (!ObjOrErr) {
+ consumeError(ObjOrErr.takeError());
+ errs() << "Not an object file: " << path << "\n";
+ return 1;
+ }
+ ObjectFile &Obj = *ObjOrErr.get();
+
+ if (Obj.is64Bit() && sizeof(unsigned long) < 8) {
+ errs() << path
+ << ": 64-bit ELF verification requires a 64-bit host build\n";
+ return 1;
+ }
+
+ ArchSpec AS;
+ if (!getArchSpec(Obj, AS)) {
+ errs() << "Unsupported architecture in " << path << "\n";
+ return 1;
+ }
+
+ StringRef eh_bytes, eh_hdr_bytes, orc_bytes, orc_ip_bytes;
+ uint64_t eh_vma = 0, eh_hdr_vma = 0, orc_ip_vma = 0;
+ std::vector<ExecSec> exec_secs;
+
+ for (const SectionRef &Sec : Obj.sections()) {
+ Expected<StringRef> NameOrErr = Sec.getName();
+ if (!NameOrErr) {
+ consumeError(NameOrErr.takeError());
+ continue;
+ }
+ StringRef Name = *NameOrErr;
+ Expected<StringRef> DataOrErr = Sec.getContents();
+ if (!DataOrErr) {
+ consumeError(DataOrErr.takeError());
+ continue;
+ }
+ StringRef Data = *DataOrErr;
+ uint64_t Addr = Sec.getAddress();
+
+ if (Name == ".eh_frame") {
+ eh_bytes = Data;
+ eh_vma = Addr;
+ } else if (Name == ".eh_frame_hdr") {
+ eh_hdr_bytes = Data;
+ eh_hdr_vma = Addr;
+ } else if (Name == ".orc_unwind") {
+ orc_bytes = Data;
+ } else if (Name == ".orc_unwind_ip") {
+ orc_ip_bytes = Data;
+ orc_ip_vma = Addr;
+ }
+ if (Sec.isText() && !Data.empty())
+ exec_secs.push_back({Name.str(), Addr, Data});
+ }
+
+ if (eh_bytes.empty() || eh_hdr_bytes.empty() ||
+ eh_hdr_bytes.size() < 12) {
+ errs() << path << ": missing .eh_frame or .eh_frame_hdr\n";
+ return 1;
+ }
+
+ host_vma_seg segs[2] = {
+ {(unsigned long)eh_hdr_vma, eh_hdr_bytes.size(),
+ reinterpret_cast<const uint8_t *>(eh_hdr_bytes.data())},
+ {(unsigned long)eh_vma, eh_bytes.size(),
+ reinterpret_cast<const uint8_t *>(eh_bytes.data())},
+ };
+ host_set_vma_segs(segs, 2);
+
+ uint64_t min_eh_vma = std::min(eh_hdr_vma, eh_vma);
+ uint64_t max_eh_end = std::max(eh_hdr_vma + eh_hdr_bytes.size(),
+ eh_vma + eh_bytes.size());
+ std::vector<uint8_t> kmem_arena;
+ bool can_test_kmem =
+ (max_eh_end >= min_eh_vma) &&
+ (max_eh_end - min_eh_vma) <= (64ULL * 1024 * 1024) &&
+ isRelativeEhEncoding((uint8_t)eh_hdr_bytes[1]) &&
+ isRelativeEhEncoding((uint8_t)eh_hdr_bytes[3]);
+ const uint8_t *kmem_hdr = nullptr;
+ const uint8_t *kmem_eh_start = nullptr;
+ const uint8_t *kmem_eh_end = nullptr;
+ if (can_test_kmem) {
+ kmem_arena.assign(max_eh_end - min_eh_vma, 0);
+ memcpy(kmem_arena.data() + (eh_hdr_vma - min_eh_vma),
+ eh_hdr_bytes.data(), eh_hdr_bytes.size());
+ memcpy(kmem_arena.data() + (eh_vma - min_eh_vma),
+ eh_bytes.data(), eh_bytes.size());
+ kmem_hdr = kmem_arena.data() + (eh_hdr_vma - min_eh_vma);
+ kmem_eh_start = kmem_arena.data() + (eh_vma - min_eh_vma);
+ kmem_eh_end = kmem_eh_start + eh_bytes.size();
+ uintptr_t h_addr = reinterpret_cast<uintptr_t>(kmem_hdr);
+ if (h_addr < 0x80000000ULL ||
+ h_addr > UINTPTR_MAX - 0x80000000ULL)
+ can_test_kmem = false;
+ }
+
+ VerifyStats st;
+ std::vector<FDERange> fde_ranges;
+ if (verifyOracle1Dwarf(Obj, AS, eh_hdr_vma, eh_hdr_bytes, min_eh_vma,
+ can_test_kmem, kmem_arena, kmem_hdr,
+ kmem_eh_start, kmem_eh_end, opts, st,
+ fde_ranges) != 0) {
+ errs() << path << ": LLVM getEHFrame() failed\n";
+ return 1;
+ }
+
+#if defined(HAVE_VERIFY_INSN) || defined(HAVE_VERIFY_ORC)
+ std::string TargetErr;
+ const Target *TheTarget =
+ TargetRegistry::lookupTarget(AS.triple_str, TargetErr);
+ if (!TheTarget) {
+ errs() << "lookupTarget failed: " << TargetErr << "\n";
+ return 1;
+ }
+
+ MCTargetOptions MCOpts;
+ std::unique_ptr<MCRegisterInfo> MCRI(
+ TheTarget->createMCRegInfo(AS.triple_str));
+ std::unique_ptr<MCAsmInfo> MAI(
+ TheTarget->createMCAsmInfo(*MCRI, AS.triple_str, MCOpts));
+ std::unique_ptr<MCSubtargetInfo> STI(
+ TheTarget->createMCSubtargetInfo(AS.triple_str, "",
+ AS.features));
+ std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
+ std::unique_ptr<MCInstrAnalysis> MIA(
+ TheTarget->createMCInstrAnalysis(MCII.get()));
+ MCContext Ctx(Triple(AS.triple_str), MAI.get(), MCRI.get(), STI.get());
+ std::unique_ptr<MCObjectFileInfo> MOFI(
+ TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));
+ Ctx.setObjectFileInfo(MOFI.get());
+ std::unique_ptr<MCDisassembler> Disasm(
+ TheTarget->createMCDisassembler(*STI, Ctx));
+ std::unique_ptr<MCInstPrinter> InstPrinter(
+ TheTarget->createMCInstPrinter(Triple(AS.triple_str), 0, *MAI,
+ *MCII, *MCRI));
+
+ std::vector<FuncSym> func_syms;
+ std::unordered_set<uint64_t> noreturn_addrs;
+
+ auto collectSyms = [&](symbol_iterator begin, symbol_iterator end) {
+ for (auto it = begin; it != end; ++it) {
+ SymbolRef Sym = *it;
+ auto TypeOrErr = Sym.getType();
+ auto AddrOrErr = Sym.getAddress();
+ auto NameOrErr = Sym.getName();
+ if (!TypeOrErr || !AddrOrErr || !NameOrErr) {
+ if (!TypeOrErr)
+ consumeError(TypeOrErr.takeError());
+ if (!AddrOrErr)
+ consumeError(AddrOrErr.takeError());
+ if (!NameOrErr)
+ consumeError(NameOrErr.takeError());
+ continue;
+ }
+ uint64_t addr = *AddrOrErr;
+ StringRef name = *NameOrErr;
+ if ((AS.llvm_arch == Triple::aarch64 ||
+ AS.llvm_arch == Triple::riscv64) &&
+ (name.starts_with("$x") || name.starts_with("$d")))
+ continue;
+#ifdef HAVE_VERIFY_INSN
+ if (!name.empty() && isKnownNoreturnName(name))
+ noreturn_addrs.insert(addr);
+#endif
+ if (*TypeOrErr == SymbolRef::ST_Function) {
+ uint64_t sz = ELFSymbolRef(Sym).getSize();
+ func_syms.push_back({addr, sz, name.str()});
+ }
+ }
+ };
+ collectSyms(Obj.symbol_begin(), Obj.symbol_end());
+ if (const auto *EObj = dyn_cast<ELFObjectFileBase>(&Obj)) {
+ auto DynSyms = EObj->getDynamicSymbolIterators();
+ collectSyms(DynSyms.begin(), DynSyms.end());
+ }
+
+ std::sort(func_syms.begin(), func_syms.end(),
+ [](const FuncSym &a, const FuncSym &b) {
+ return a.addr != b.addr ? a.addr < b.addr
+ : a.size > b.size;
+ });
+ func_syms.erase(std::unique(func_syms.begin(), func_syms.end(),
+ [](const FuncSym &a, const FuncSym &b) {
+ return a.addr == b.addr;
+ }),
+ func_syms.end());
+
+#ifdef HAVE_VERIFY_INSN
+ verifyOracle2Instructions(AS, eh_hdr_vma, eh_hdr_bytes, exec_secs,
+ func_syms, noreturn_addrs, fde_ranges,
+ *Disasm, *MCII, *MCRI, MIA.get(), opts, st);
+#endif
+
+#ifdef HAVE_VERIFY_ORC
+ if (AS.llvm_arch == Triple::x86_64 && !orc_bytes.empty() &&
+ !orc_ip_bytes.empty()) {
+ verifyOracle3Orc(AS, eh_hdr_vma, eh_hdr_bytes, orc_bytes,
+ orc_ip_bytes, orc_ip_vma, exec_secs, func_syms,
+ *Disasm, *STI, *InstPrinter, opts, st);
+ }
+#else
+ (void)orc_bytes;
+ (void)orc_ip_bytes;
+ (void)orc_ip_vma;
+#endif
+#else
+ (void)orc_bytes;
+ (void)orc_ip_bytes;
+ (void)orc_ip_vma;
+ (void)exec_secs;
+#endif
+
+ bool oracle1_fail = (st.llvm_vs_kernel_mismatches > 0 ||
+ st.kmem_vs_user_mismatches > 0);
+ bool strict_fail = opts.strict &&
+ (st.insns_cfa_mismatch > 0 ||
+ st.insns_ra_mismatch > 0 ||
+ st.insns_fp_mismatch > 0 ||
+ st.orc_cfa_mismatch > 0 ||
+ st.orc_bp_mismatch > 0);
+
+ if (opts.quiet && !oracle1_fail && !strict_fail) {
+ if (st.has_insn_oracle) {
+ printf("%s: OK (FDEs: %" PRIu64 "/%" PRIu64
+ ", funcs clean: %" PRIu64 "/%" PRIu64 ")\n",
+ path, st.fdes_minimal_supported, st.fdes_total,
+ st.funcs_clean, st.funcs_verified);
+ } else {
+ printf("%s: OK (FDEs: %" PRIu64 "/%" PRIu64 ")\n",
+ path, st.fdes_minimal_supported, st.fdes_total);
+ }
+ fflush(stdout);
+ return 0;
+ }
+
+ printf("=== %s (%s) ===\n", path, AS.triple_str);
+ printf(" [Oracle 1: LLVM Reference DWARF vs Kernel Minimal DWARF]\n");
+ printf(" FDEs total / Minimal-supported : %" PRIu64 " / %" PRIu64
+ " (%.2f%%)\n",
+ st.fdes_total, st.fdes_minimal_supported,
+ st.fdes_total ? 100.0 * st.fdes_minimal_supported / st.fdes_total
+ : 0.0);
+ printf(" Transition PCs evaluated : %" PRIu64 "\n",
+ st.fde_pc_checks);
+ printf(" LLVM vs Kernel mismatches : %" PRIu64 "\n",
+ st.llvm_vs_kernel_mismatches);
+ if (st.kmem_pc_checks > 0)
+ printf(" kmem vs user stream mismatches : %" PRIu64
+ " (%" PRIu64 " PCs)\n",
+ st.kmem_vs_user_mismatches, st.kmem_pc_checks);
+
+ if (st.has_insn_oracle) {
+ printf(" [Oracle 2: Machine-Instruction Abstract Execution & Clobber Check]\n");
+ printf(" STT_FUNC total / verified : %" PRIu64
+ " / %" PRIu64 " (no-FDE: %" PRIu64
+ ", split/custom-entry: %" PRIu64 ")\n",
+ st.funcs_total, st.funcs_verified, st.funcs_no_fde,
+ st.funcs_mid_frame_split);
+ printf(" Functions 100%% instruction-clean: %" PRIu64
+ " / %" PRIu64 " (%.2f%%)\n",
+ st.funcs_clean, st.funcs_verified,
+ st.funcs_verified
+ ? 100.0 * st.funcs_clean / st.funcs_verified
+ : 0.0);
+ printf(" Reachable instructions checked : %" PRIu64
+ " (CFA diff: %" PRIu64 ", RA diff: %" PRIu64
+ ", FP diff: %" PRIu64 ")\n",
+ st.insns_verified, st.insns_cfa_mismatch,
+ st.insns_ra_mismatch, st.insns_fp_mismatch);
+ }
+ for (const auto &kv : st.mismatch_reasons)
+ printf(" - %-28s : %" PRIu64 "\n", kv.first.c_str(),
+ kv.second);
+ for (const auto &s : st.sample_issues)
+ printf(" sample: %s\n", s.c_str());
+
+ if (st.has_orc) {
+ uint64_t denom = st.orc_call_insns - st.orc_no_fde;
+ printf(" [Oracle 3: Direct x86-64 ORC (.orc_unwind) vs Kernel Minimal DWARF]\n");
+ printf(" ORC_TYPE_CALL insns (with FDE) : %" PRIu64
+ " (no-FDE asm: %" PRIu64 ")\n",
+ denom, st.orc_no_fde);
+ printf(" Exact ORC == CFI matches : %" PRIu64
+ " / %" PRIu64 " (%.4f%%)\n",
+ st.orc_matched, denom,
+ denom ? 100.0 * st.orc_matched / denom : 0.0);
+ printf(" ORC diffs (CFA / BP) : %" PRIu64
+ " / %" PRIu64 "\n",
+ st.orc_cfa_mismatch, st.orc_bp_mismatch);
+ for (const auto &s : st.sample_orc_diffs)
+ printf(" orc_diff: %s\n", s.c_str());
+ }
+ printf("\n");
+ fflush(stdout);
+ return (oracle1_fail || strict_fail) ? 1 : 0;
+}
+
+static void printUsage(const char *prog)
+{
+ printf("Usage: %s [options] <elf_file> [elf_file...]\n"
+ "\n"
+ "Options:\n"
+ " --strict Fail (exit 1) on any instruction or ORC diff\n"
+ " (Oracle 1 DWARF interpreter mismatches always fail)\n"
+ " --max-samples <N> Maximum sample diagnostics per category (default: 6)\n"
+ " -q, --quiet Print single-line summary when verification succeeds\n"
+ " -h, --help Show this help message\n",
+ prog);
+}
+
+int main(int argc, char **argv)
+{
+ InitLLVM X(argc, argv);
+ InitializeAllTargetInfos();
+ InitializeAllTargetMCs();
+ InitializeAllDisassemblers();
+
+ VerifyOptions opts;
+ std::vector<const char *> files;
+
+ for (int i = 1; i < argc; i++) {
+ StringRef arg(argv[i]);
+ if (arg == "-h" || arg == "--help") {
+ printUsage(argv[0]);
+ return 0;
+ } else if (arg == "--strict") {
+ opts.strict = true;
+ } else if (arg == "-q" || arg == "--quiet") {
+ opts.quiet = true;
+ } else if (arg == "--max-samples") {
+ if (i + 1 >= argc) {
+ errs() << "--max-samples requires an integer argument\n";
+ return 1;
+ }
+ char *endp = nullptr;
+ unsigned long v = strtoul(argv[++i], &endp, 10);
+ if (!endp || *endp != '\0') {
+ errs() << "Invalid --max-samples value: "
+ << argv[i] << "\n";
+ return 1;
+ }
+ opts.max_samples = (size_t)v;
+ } else if (arg.starts_with("-")) {
+ errs() << "Unknown option: " << arg << "\n";
+ printUsage(argv[0]);
+ return 1;
+ } else {
+ files.push_back(argv[i]);
+ }
+ }
+
+ if (files.empty()) {
+ printUsage(argv[0]);
+ return 1;
+ }
+
+ int rc = 0;
+ for (const char *f : files)
+ rc |= verifyFile(f, opts);
+ return rc;
+}
diff --git a/tools/unwind/verify_cfi.hpp b/tools/unwind/verify_cfi.hpp
new file mode 100644
index 000000000000..10bb77302e38
--- /dev/null
+++ b/tools/unwind/verify_cfi.hpp
@@ -0,0 +1,147 @@
+/* SPDX-License-Identifier: GPL-2.0-only OR MIT */
+#ifndef _TOOLS_UNWIND_VERIFY_CFI_H
+#define _TOOLS_UNWIND_VERIFY_CFI_H
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/MC/MCDisassembler/MCDisassembler.h"
+#include "llvm/MC/MCInstPrinter.h"
+#include "llvm/MC/MCInstrAnalysis.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCRegisterInfo.h"
+#include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/TargetParser/Triple.h"
+#pragma GCC diagnostic pop
+
+#include <cstddef>
+#include <cstdint>
+#include <map>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+#include "dwarf_cfi_host.h"
+
+/**
+ * struct VerifyOptions - Command-line configuration for verify_cfi
+ * @strict: Return exit status 1 if Oracle 2 or Oracle 3 finds any instruction
+ * or ORC discrepancy (Oracle 1 mismatches always return exit status 1).
+ * @quiet: Emit a single-line summary per verified file when no failure occurs.
+ * @max_samples: Maximum number of diagnostic mismatch samples printed per kind.
+ */
+struct VerifyOptions {
+ bool strict = false;
+ bool quiet = false;
+ size_t max_samples = 6;
+};
+
+/**
+ * struct ArchSpec - Target architecture parameters for LLVM MC and kernel CFI
+ * @llvm_arch: LLVM Triple::ArchType identifier.
+ * @triple_str: Target triple passed to LLVM TargetRegistry / MCDisassembler.
+ * @features: Subtarget feature string enabling ISA extensions in disassembly
+ * (e.g. PAC/BTI on AArch64, compressed RVC on RISC-V).
+ * @karch: Kernel DWARF register mapping passed to kernel/unwind/dwarf_cfi.c.
+ * @entry_cfa_off: Byte offset from entry SP to caller's SP (8 on x86_64 where
+ * CALL pushes the 8-byte return address; 0 on arm64/riscv64).
+ * @ra_on_entry_stack: True if the return address starts at *(entry_SP + 0)
+ * rather than in @karch.ra_reg.
+ */
+struct ArchSpec {
+ llvm::Triple::ArchType llvm_arch;
+ const char *triple_str;
+ const char *features;
+ dwarf_cfi_arch karch;
+ int32_t entry_cfa_off;
+ bool ra_on_entry_stack;
+};
+
+/**
+ * struct VerifyStats - Aggregated verification counters and diagnostic samples
+ */
+struct VerifyStats {
+ // Oracle 1: LLVM Reference DWARF vs Kernel Minimal DWARF
+ uint64_t fdes_total = 0;
+ uint64_t fdes_minimal_supported = 0;
+ uint64_t fdes_outside_minimal = 0;
+ uint64_t fde_pc_checks = 0;
+ uint64_t kmem_pc_checks = 0;
+ uint64_t kmem_vs_user_mismatches = 0;
+ uint64_t llvm_vs_kernel_mismatches = 0;
+
+ // Oracle 2: Instruction Abstract Execution & Clobber Check
+ bool has_insn_oracle = false;
+ uint64_t funcs_total = 0;
+ uint64_t funcs_no_fde = 0;
+ uint64_t funcs_mid_frame_split = 0;
+ uint64_t funcs_verified = 0;
+ uint64_t funcs_clean = 0;
+ uint64_t insns_verified = 0;
+ uint64_t insns_cfa_mismatch = 0;
+ uint64_t insns_ra_mismatch = 0;
+ uint64_t insns_fp_mismatch = 0;
+ std::map<std::string, uint64_t> mismatch_reasons;
+ std::vector<std::string> sample_issues;
+
+ // Oracle 3: ORC vs Kernel Minimal DWARF
+ bool has_orc = false;
+ uint64_t orc_call_insns = 0;
+ uint64_t orc_matched = 0;
+ uint64_t orc_no_fde = 0;
+ uint64_t orc_cfa_mismatch = 0;
+ uint64_t orc_bp_mismatch = 0;
+ std::vector<std::string> sample_orc_diffs;
+};
+
+struct FDERange {
+ uint64_t start;
+ uint64_t end;
+ bool supported;
+ bool signal;
+};
+
+struct ExecSec {
+ std::string name;
+ uint64_t vma;
+ llvm::StringRef bytes;
+};
+
+struct FuncSym {
+ uint64_t addr;
+ uint64_t size;
+ std::string name;
+};
+
+bool rowsEqual(const dwarf_cfi_row &a, const dwarf_cfi_row &b);
+
+void recordIssue(VerifyStats &st, const VerifyOptions &opts,
+ const std::string &reason, const std::string &detail);
+
+llvm::ArrayRef<uint8_t> findExecBytes(const std::vector<ExecSec> &exec_secs,
+ uint64_t addr, uint64_t len);
+
+bool isKnownNoreturnName(llvm::StringRef Name);
+
+void verifyOracle2Instructions(
+ const ArchSpec &AS, uint64_t eh_hdr_vma, llvm::StringRef eh_hdr_bytes,
+ const std::vector<ExecSec> &exec_secs,
+ const std::vector<FuncSym> &func_syms,
+ const std::unordered_set<uint64_t> &noreturn_addrs,
+ const std::vector<FDERange> &fde_ranges,
+ const llvm::MCDisassembler &Disasm, const llvm::MCInstrInfo &MCII,
+ const llvm::MCRegisterInfo &MCRI, const llvm::MCInstrAnalysis *MIA,
+ const VerifyOptions &opts, VerifyStats &st);
+
+void verifyOracle3Orc(const ArchSpec &AS, uint64_t eh_hdr_vma,
+ llvm::StringRef eh_hdr_bytes, llvm::StringRef orc_bytes,
+ llvm::StringRef orc_ip_bytes, uint64_t orc_ip_vma,
+ const std::vector<ExecSec> &exec_secs,
+ const std::vector<FuncSym> &func_syms,
+ const llvm::MCDisassembler &Disasm,
+ const llvm::MCSubtargetInfo &STI,
+ llvm::MCInstPrinter &InstPrinter,
+ const VerifyOptions &opts, VerifyStats &st);
+
+#endif /* _TOOLS_UNWIND_VERIFY_CFI_H */
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 27/30] tools/unwind: Add multi-arch symbolic instruction lifters for verify_cfi
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (25 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 26/30] tools/unwind: Add standalone libLLVM Minimal DWARF CFI verifier Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 28/30] tools/unwind: Add CFG instruction abstract execution oracle to verify_cfi Ian Rogers
` (2 subsequent siblings)
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Add the symbolic stack/register abstract domain (verify_insn.hpp),
per-architecture Tier-2 instruction lifters (stepInstructionX86(),
stepInstructionArm64(), stepInstructionRiscv(), and
normalizeRiscvControlFlow()), and the conservative Tier-1 MCInstrDesc /
MCRegisterInfo register-def clobber fallback (clobberGenericDefs()) in
verify_insn_arch.cpp.
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/unwind/Makefile | 3 +-
tools/unwind/verify_insn.hpp | 103 ++++
tools/unwind/verify_insn_arch.cpp | 757 ++++++++++++++++++++++++++++++
3 files changed, 862 insertions(+), 1 deletion(-)
create mode 100644 tools/unwind/verify_insn.hpp
create mode 100644 tools/unwind/verify_insn_arch.cpp
diff --git a/tools/unwind/Makefile b/tools/unwind/Makefile
index ca6b84dbd31a..90c4b47ae851 100644
--- a/tools/unwind/Makefile
+++ b/tools/unwind/Makefile
@@ -87,7 +87,8 @@ KERNEL_CFI_DEPS := $(srctree)/kernel/unwind/dwarf_cfi.c \
$(srctree)/tools/include/linux/unwind_dwarf_cfi.h
VERIFY_OBJS := $(OUTPUT)dwarf_cfi_host.o \
- $(OUTPUT)verify_cfi.o
+ $(OUTPUT)verify_cfi.o \
+ $(OUTPUT)verify_insn_arch.o
ifeq ($(HAS_LIBLLVM),1)
all: $(OUTPUT)verify_cfi
diff --git a/tools/unwind/verify_insn.hpp b/tools/unwind/verify_insn.hpp
new file mode 100644
index 000000000000..c0d2711b716e
--- /dev/null
+++ b/tools/unwind/verify_insn.hpp
@@ -0,0 +1,103 @@
+/* SPDX-License-Identifier: GPL-2.0-only OR MIT */
+#ifndef _TOOLS_UNWIND_VERIFY_INSN_H
+#define _TOOLS_UNWIND_VERIFY_INSN_H
+
+#include "verify_cfi.hpp"
+
+/**
+ * enum ValKind - Symbolic lattice value kinds tracked in registers and stack
+ * @VK_UNKNOWN: Clobbered, runtime-dependent, or unmodeled value.
+ * @VK_ENTRY_SP: Value equal to function-entry SP + @off.
+ * @VK_ALIGNED_SP: Post-realignment SP + @off (after `and $-align, sp` DRAP).
+ * @VK_CALLER_FP: Preserved caller frame pointer value at function entry.
+ * @VK_CALLER_RA: Preserved caller return address (@off == 1 when PAC-signed).
+ * @VK_CONST: Known 64-bit integer constant (e.g. >4KB frame size setup).
+ */
+enum ValKind : uint8_t {
+ VK_UNKNOWN = 0,
+ VK_ENTRY_SP,
+ VK_ALIGNED_SP,
+ VK_CALLER_FP,
+ VK_CALLER_RA,
+ VK_CONST,
+};
+
+struct SymVal {
+ ValKind kind = VK_UNKNOWN;
+ int64_t off = 0;
+
+ bool operator==(const SymVal &o) const
+ {
+ return kind == o.kind && (kind == VK_UNKNOWN || off == o.off);
+ }
+ bool operator!=(const SymVal &o) const { return !(*this == o); }
+};
+
+struct StackKey {
+ uint8_t base; // VK_ENTRY_SP or VK_ALIGNED_SP
+ int64_t off;
+ bool operator<(const StackKey &o) const
+ {
+ return base != o.base ? base < o.base : off < o.off;
+ }
+ bool operator==(const StackKey &o) const
+ {
+ return base == o.base && off == o.off;
+ }
+};
+
+/**
+ * struct AbsState - Per-PC abstract machine state during CFG symbolic execution
+ * @regs: Symbolic values of DWARF registers 0..31.
+ * @stack: Sparse symbolic stack slots keyed by (ENTRY_SP | ALIGNED_SP) + offset.
+ */
+struct AbsState {
+ SymVal regs[32];
+ std::map<StackKey, SymVal> stack;
+
+ SymVal load(const SymVal &addr) const
+ {
+ if (addr.kind != VK_ENTRY_SP && addr.kind != VK_ALIGNED_SP)
+ return {VK_UNKNOWN, 0};
+ auto it = stack.find({(uint8_t)addr.kind, addr.off});
+ if (it == stack.end())
+ return {VK_UNKNOWN, 0};
+ return it->second;
+ }
+
+ void store(const SymVal &addr, const SymVal &val)
+ {
+ if (addr.kind != VK_ENTRY_SP && addr.kind != VK_ALIGNED_SP)
+ return;
+ StackKey k{(uint8_t)addr.kind, addr.off};
+ if (val.kind == VK_UNKNOWN)
+ stack.erase(k);
+ else
+ stack[k] = val;
+ }
+};
+
+int mcRegToDwarf32(const llvm::MCRegisterInfo &MCRI, llvm::MCRegister Reg,
+ llvm::Triple::ArchType Arch);
+
+SymVal addSymImm(SymVal base, int64_t delta);
+SymVal addSymVals(SymVal a, SymVal b);
+SymVal subSymVals(SymVal a, SymVal b);
+
+void clobberGenericDefs(AbsState &st, const llvm::MCInst &MI,
+ const llvm::MCInstrDesc &Desc,
+ const llvm::MCRegisterInfo &MCRI,
+ const ArchSpec &AS);
+
+bool stepInstruction(AbsState &st, const llvm::MCInst &MI,
+ llvm::StringRef OpName, const llvm::MCInstrDesc &Desc,
+ const llvm::MCRegisterInfo &MCRI, const ArchSpec &AS,
+ uint64_t NextPC, const llvm::MCInstrAnalysis *MIA,
+ uint64_t CurPC, uint64_t InsnSize);
+
+void normalizeRiscvControlFlow(const llvm::MCInst &MI, llvm::StringRef OpName,
+ const llvm::MCRegisterInfo &MCRI,
+ bool &is_ret_or_ind_jump, bool &is_uncond_branch,
+ bool &is_call);
+
+#endif /* _TOOLS_UNWIND_VERIFY_INSN_H */
diff --git a/tools/unwind/verify_insn_arch.cpp b/tools/unwind/verify_insn_arch.cpp
new file mode 100644
index 000000000000..3005c8a9d9bd
--- /dev/null
+++ b/tools/unwind/verify_insn_arch.cpp
@@ -0,0 +1,757 @@
+// SPDX-License-Identifier: GPL-2.0-only OR MIT
+/*
+ * Per-architecture Tier-2 symbolic instruction lifters (x86_64, arm64, riscv64)
+ * and Tier-1 generic MCInstrDesc register-def clobber fallback for verify_cfi.
+ */
+
+#include "verify_insn.hpp"
+
+using namespace llvm;
+
+/**
+ * mcRegToDwarf32() - Map an LLVM physical MCRegister to DWARF reg 0..31
+ * @MCRI: Target MCRegisterInfo table.
+ * @Reg: Physical register operand from an MCInst.
+ * @Arch: Target architecture type.
+ *
+ * Resolves both full-width registers and sub-registers (e.g. %eax -> %rax on
+ * x86_64, w29 -> x29 on AArch64) via super-register traversal. On AArch64,
+ * LLVM's getDwarfRegNum() maps both XZR/WZR (zero sink) and SP/WSP to DWARF
+ * number 31 because they share architectural 5-bit encoding 31 in different
+ * instruction classes; XZR and WZR are explicitly filtered out so flag-setting
+ * compares (`cmp` -> `SUBS XZR, ...`) never clobber the stack pointer.
+ *
+ * Return: DWARF register number in [0, 31], or -1 if unmapped / zero sink.
+ */
+int mcRegToDwarf32(const MCRegisterInfo &MCRI, MCRegister Reg,
+ Triple::ArchType Arch)
+{
+ if (!Reg.isValid() || Reg.id() == 0)
+ return -1;
+ if (Arch == Triple::aarch64) {
+ StringRef N = MCRI.getName(Reg);
+ if (N == "XZR" || N == "WZR")
+ return -1;
+ }
+ int64_t d = MCRI.getDwarfRegNum(Reg, /*isEH=*/true);
+ if (d >= 0 && d < 32)
+ return (int)d;
+ for (MCPhysReg Super : MCRI.superregs(Reg)) {
+ if (Arch == Triple::aarch64) {
+ StringRef SN = MCRI.getName(Super);
+ if (SN == "XZR" || SN == "WZR")
+ continue;
+ }
+ int64_t sd = MCRI.getDwarfRegNum(Super, /*isEH=*/true);
+ if (sd >= 0 && sd < 32)
+ return (int)sd;
+ }
+ return -1;
+}
+
+SymVal addSymImm(SymVal base, int64_t delta)
+{
+ if (base.kind == VK_ENTRY_SP || base.kind == VK_ALIGNED_SP ||
+ base.kind == VK_CONST)
+ return {base.kind, (int64_t)((uint64_t)base.off + (uint64_t)delta)};
+ return {VK_UNKNOWN, 0};
+}
+
+SymVal addSymVals(SymVal a, SymVal b)
+{
+ if (a.kind == VK_CONST && b.kind == VK_CONST)
+ return {VK_CONST, (int64_t)((uint64_t)a.off + (uint64_t)b.off)};
+ if ((a.kind == VK_ENTRY_SP || a.kind == VK_ALIGNED_SP) &&
+ b.kind == VK_CONST)
+ return {a.kind, (int64_t)((uint64_t)a.off + (uint64_t)b.off)};
+ if (a.kind == VK_CONST &&
+ (b.kind == VK_ENTRY_SP || b.kind == VK_ALIGNED_SP))
+ return {b.kind, (int64_t)((uint64_t)b.off + (uint64_t)a.off)};
+ return {VK_UNKNOWN, 0};
+}
+
+SymVal subSymVals(SymVal a, SymVal b)
+{
+ if (b.kind == VK_CONST)
+ return addSymVals(a, {VK_CONST, (int64_t)(-(uint64_t)b.off)});
+ return {VK_UNKNOWN, 0};
+}
+
+/**
+ * clobberGenericDefs() - Tier-1 conservative register-def clobber fallback
+ * @st: Abstract state updated in place.
+ * @MI: Decoded LLVM MCInst.
+ * @Desc: Instruction descriptor providing explicit/implicit register defs.
+ * @MCRI: Target register alias hierarchy.
+ * @AS: Target architecture specification.
+ *
+ * Marks every architectural DWARF register (0..31) modified by @MI (explicit
+ * def operands, implicit defs, and sub-/super-register aliases) as VK_UNKNOWN,
+ * and clobbers ABI caller-saved registers across call instructions.
+ */
+void clobberGenericDefs(AbsState &st, const MCInst &MI, const MCInstrDesc &Desc,
+ const MCRegisterInfo &MCRI, const ArchSpec &AS)
+{
+ auto clobberPhys = [&](MCRegister R) {
+ if (!R.isValid() || R.id() == 0)
+ return;
+ if (AS.llvm_arch == Triple::aarch64) {
+ StringRef RN = MCRI.getName(R);
+ if (RN == "XZR" || RN == "WZR")
+ return;
+ }
+ for (MCPhysReg Alias : MCRI.sub_and_superregs_inclusive(R)) {
+ if (AS.llvm_arch == Triple::aarch64) {
+ StringRef AN = MCRI.getName(Alias);
+ if (AN == "XZR" || AN == "WZR")
+ continue;
+ }
+ int64_t d = MCRI.getDwarfRegNum(Alias, /*isEH=*/true);
+ if (d >= 0 && d < 32) {
+ if (AS.llvm_arch == Triple::riscv64 && d == 0)
+ continue;
+ st.regs[d] = {VK_UNKNOWN, 0};
+ }
+ }
+ };
+
+ unsigned numDefs = Desc.getNumDefs();
+ for (unsigned i = 0; i < numDefs && i < MI.getNumOperands(); i++) {
+ if (MI.getOperand(i).isReg())
+ clobberPhys(MI.getOperand(i).getReg());
+ }
+ for (MCPhysReg Imp : Desc.implicit_defs())
+ clobberPhys(Imp);
+
+ if (Desc.isCall()) {
+ for (int d = 0; d < 32; d++) {
+ if (AS.llvm_arch == Triple::x86_64) {
+ if (d == 3 || d == 6 || d == 7 ||
+ (d >= 12 && d <= 15))
+ continue;
+ st.regs[d] = {VK_UNKNOWN, 0};
+ } else if (AS.llvm_arch == Triple::aarch64) {
+ if ((d >= 19 && d <= 29) || d == 31)
+ continue;
+ st.regs[d] = {VK_UNKNOWN, 0};
+ } else if (AS.llvm_arch == Triple::riscv64) {
+ if (d == 0 || d == 2 || d == 3 || d == 4 ||
+ d == 8 || d == 9 || (d >= 18 && d <= 27))
+ continue;
+ st.regs[d] = {VK_UNKNOWN, 0};
+ }
+ }
+ }
+}
+
+struct InsnStepCtx {
+ const MCInst &MI;
+ const MCRegisterInfo &MCRI;
+ const ArchSpec &AS;
+ const MCInstrAnalysis *MIA;
+ uint64_t CurPC;
+ uint64_t NextPC;
+ uint64_t InsnSize;
+
+ int regD(unsigned idx) const
+ {
+ if (idx >= MI.getNumOperands() || !MI.getOperand(idx).isReg())
+ return -1;
+ return mcRegToDwarf32(MCRI, MI.getOperand(idx).getReg(),
+ AS.llvm_arch);
+ }
+
+ SymVal getRegVal(const AbsState &st, int d) const
+ {
+ if (d < 0 || d >= 32)
+ return {VK_UNKNOWN, 0};
+ if (AS.llvm_arch == Triple::riscv64 && d == 0)
+ return {VK_CONST, 0};
+ return st.regs[d];
+ }
+
+ void setRegVal(AbsState &st, int d, SymVal v) const
+ {
+ if (d < 0 || d >= 32)
+ return;
+ if (AS.llvm_arch == Triple::riscv64 && d == 0)
+ return;
+ st.regs[d] = v;
+ }
+};
+
+/**
+ * stepInstructionX86() - Tier-2 symbolic lifter for x86-64 frame instructions
+ * @st: Abstract register/stack state updated in place.
+ * @OpName: LLVM MC opcode name (e.g. "PUSH64r", "SUB64ri8", "LEA64r").
+ * @Desc: Instruction descriptor.
+ * @ctx: Disassembled instruction context.
+ *
+ * Models x86-64 prologue, epilogue, DRAP (`lea 8(%rsp), %r10; and $-64, %rsp;
+ * pushq -8(%r10)`), frame-pointer (`push %rbp; mov %rsp, %rbp; leave`), and
+ * PIC `call next_pc` stack effects.
+ *
+ * Return: true if @OpName was modeled; false to trigger generic clobbering.
+ */
+static bool stepInstructionX86(AbsState &st, StringRef OpName,
+ const MCInstrDesc &Desc, const InsnStepCtx &ctx)
+{
+ const MCInst &MI = ctx.MI;
+
+ if (Desc.isCall()) {
+ uint64_t Target = 0;
+ if (ctx.MIA &&
+ ctx.MIA->evaluateBranch(MI, ctx.CurPC, ctx.InsnSize,
+ Target) &&
+ Target == ctx.NextPC) {
+ st.regs[7] = addSymImm(st.regs[7], -8);
+ st.store(st.regs[7], {VK_UNKNOWN, 0});
+ return true;
+ }
+ clobberGenericDefs(st, MI, Desc, ctx.MCRI, ctx.AS);
+ return true;
+ }
+ if (OpName.starts_with("PUSH64r")) {
+ int src = ctx.regD(0);
+ st.regs[7] = addSymImm(st.regs[7], -8);
+ st.store(st.regs[7], ctx.getRegVal(st, src));
+ return true;
+ }
+ if (OpName == "PUSHF64" || OpName.starts_with("PUSH64i") ||
+ OpName == "PUSH64rmm" || OpName == "PUSH64rmr") {
+ st.regs[7] = addSymImm(st.regs[7], -8);
+ st.store(st.regs[7], {VK_UNKNOWN, 0});
+ return true;
+ }
+ if (OpName.starts_with("POP64r")) {
+ int dst = ctx.regD(0);
+ SymVal loaded = st.load(st.regs[7]);
+ st.regs[7] = addSymImm(st.regs[7], 8);
+ if (dst != 7)
+ ctx.setRegVal(st, dst, loaded);
+ return true;
+ }
+ if (OpName == "POPF64" || OpName == "POP64rmm") {
+ st.regs[7] = addSymImm(st.regs[7], 8);
+ return true;
+ }
+ if (OpName == "LEAVE64") {
+ st.regs[7] = st.regs[6];
+ st.regs[6] = st.load(st.regs[7]);
+ st.regs[7] = addSymImm(st.regs[7], 8);
+ return true;
+ }
+ if (OpName == "MOV64rr" || OpName == "MOV64rr_REV") {
+ ctx.setRegVal(st, ctx.regD(0), ctx.getRegVal(st, ctx.regD(1)));
+ return true;
+ }
+ if (OpName == "MOV32ri" || OpName == "MOV64ri" ||
+ OpName == "MOV64ri32") {
+ int dst = ctx.regD(0);
+ if (MI.getNumOperands() >= 2 && MI.getOperand(1).isImm()) {
+ int64_t imm = MI.getOperand(1).getImm();
+ if (OpName == "MOV32ri")
+ imm = (uint32_t)imm;
+ ctx.setRegVal(st, dst, {VK_CONST, imm});
+ return true;
+ }
+ }
+ if (OpName == "XOR32rr" || OpName == "XOR64rr") {
+ int dst = ctx.regD(0), s1 = ctx.regD(1), s2 = ctx.regD(2);
+ if (s1 >= 0 && s1 == s2) {
+ ctx.setRegVal(st, dst, {VK_CONST, 0});
+ return true;
+ }
+ }
+ if ((OpName == "ADD64ri8" || OpName == "ADD64ri32" ||
+ OpName == "SUB64ri8" || OpName == "SUB64ri32") &&
+ MI.getNumOperands() >= 3 && MI.getOperand(2).isImm()) {
+ int dst = ctx.regD(0), src = ctx.regD(1);
+ int64_t imm = MI.getOperand(2).getImm();
+ if (OpName.starts_with("SUB"))
+ imm = (int64_t)(-(uint64_t)imm);
+ ctx.setRegVal(st, dst, addSymImm(ctx.getRegVal(st, src), imm));
+ return true;
+ }
+ if (OpName == "ADD64rr" || OpName == "SUB64rr") {
+ int dst = ctx.regD(0), s1 = ctx.regD(1), s2 = ctx.regD(2);
+ ctx.setRegVal(st, dst,
+ OpName == "ADD64rr"
+ ? addSymVals(ctx.getRegVal(st, s1),
+ ctx.getRegVal(st, s2))
+ : subSymVals(ctx.getRegVal(st, s1),
+ ctx.getRegVal(st, s2)));
+ return true;
+ }
+ if ((OpName == "AND64ri8" || OpName == "AND64ri32") &&
+ MI.getNumOperands() >= 3 && MI.getOperand(2).isImm()) {
+ int dst = ctx.regD(0), src = ctx.regD(1);
+ int64_t mask = MI.getOperand(2).getImm();
+ if (dst == 7 && src == 7 && mask < 0 && (mask & 0x7) == 0) {
+ st.regs[7] = {VK_ALIGNED_SP, 0};
+ return true;
+ }
+ }
+ if (OpName == "LEA64r" && MI.getNumOperands() >= 6) {
+ int dst = ctx.regD(0), base = ctx.regD(1), idx = ctx.regD(3);
+ if (base >= 0 && MI.getOperand(2).isImm() &&
+ MI.getOperand(2).getImm() == 1 && idx < 0 &&
+ MI.getOperand(4).isImm()) {
+ ctx.setRegVal(st, dst,
+ addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(4).getImm()));
+ return true;
+ }
+ }
+ if (OpName == "MOV64mr" && MI.getNumOperands() >= 6) {
+ int base = ctx.regD(0), idx = ctx.regD(2), src = ctx.regD(5);
+ if (base >= 0 && MI.getOperand(1).isImm() &&
+ MI.getOperand(1).getImm() == 1 && idx < 0 &&
+ MI.getOperand(3).isImm()) {
+ st.store(addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(3).getImm()),
+ ctx.getRegVal(st, src));
+ return true;
+ }
+ }
+ if (OpName == "MOV64rm" && MI.getNumOperands() >= 6) {
+ int dst = ctx.regD(0), base = ctx.regD(1), idx = ctx.regD(3);
+ if (base >= 0 && MI.getOperand(2).isImm() &&
+ MI.getOperand(2).getImm() == 1 && idx < 0 &&
+ MI.getOperand(4).isImm()) {
+ ctx.setRegVal(st, dst,
+ st.load(addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(4).getImm())));
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * stepInstructionArm64() - Tier-2 symbolic lifter for AArch64 instructions
+ * @st: Abstract register/stack state updated in place.
+ * @OpName: LLVM MC opcode name (e.g. "STPXpre", "LDPXi", "PACIASP").
+ * @ctx: Disassembled instruction context.
+ *
+ * Models AAPCS64 frame setup and teardown including Pointer Authentication
+ * (`paciasp`/`autiasp`), >4KB stack-frame constant materialization, and paired
+ * or single stack spills/reloads.
+ *
+ * Return: true if @OpName was modeled; false to trigger generic clobbering.
+ */
+static bool stepInstructionArm64(AbsState &st, StringRef OpName,
+ const InsnStepCtx &ctx)
+{
+ const MCInst &MI = ctx.MI;
+
+ if (OpName == "PACIASP" || OpName == "PACIBSP" ||
+ OpName == "AUTIASP" || OpName == "AUTIBSP") {
+ if (st.regs[30].kind == VK_CALLER_RA)
+ st.regs[30].off ^= 1;
+ return true;
+ }
+ if (OpName == "HINT" && MI.getNumOperands() >= 1 &&
+ MI.getOperand(0).isImm()) {
+ int64_t h = MI.getOperand(0).getImm();
+ if (h == 25 || h == 27 || h == 29 || h == 31) {
+ if (st.regs[30].kind == VK_CALLER_RA)
+ st.regs[30].off ^= 1;
+ return true;
+ }
+ }
+ if ((OpName == "ADDXri" || OpName == "SUBXri") &&
+ MI.getNumOperands() >= 4 && MI.getOperand(2).isImm() &&
+ MI.getOperand(3).isImm()) {
+ int dst = ctx.regD(0), src = ctx.regD(1);
+ unsigned sh = (unsigned)MI.getOperand(3).getImm() & 0x3f;
+ int64_t imm = (int64_t)((uint64_t)MI.getOperand(2).getImm() << sh);
+ if (OpName == "SUBXri")
+ imm = (int64_t)(-(uint64_t)imm);
+ ctx.setRegVal(st, dst, addSymImm(ctx.getRegVal(st, src), imm));
+ return true;
+ }
+ if (OpName == "ORRXrs" && MI.getNumOperands() >= 4 &&
+ MI.getOperand(3).isImm() && MI.getOperand(3).getImm() == 0) {
+ if (MI.getOperand(1).isReg() &&
+ StringRef(ctx.MCRI.getName(MI.getOperand(1).getReg())) == "XZR") {
+ ctx.setRegVal(st, ctx.regD(0),
+ ctx.getRegVal(st, ctx.regD(2)));
+ return true;
+ }
+ }
+ if (OpName == "MOVZXi" && MI.getNumOperands() >= 3 &&
+ MI.getOperand(1).isImm() && MI.getOperand(2).isImm()) {
+ unsigned sh = (unsigned)MI.getOperand(2).getImm() & 0x3f;
+ uint64_t v = ((uint64_t)MI.getOperand(1).getImm()) << sh;
+ ctx.setRegVal(st, ctx.regD(0), {VK_CONST, (int64_t)v});
+ return true;
+ }
+ if (OpName == "MOVNXi" && MI.getNumOperands() >= 3 &&
+ MI.getOperand(1).isImm() && MI.getOperand(2).isImm()) {
+ unsigned sh = (unsigned)MI.getOperand(2).getImm() & 0x3f;
+ uint64_t v = ~(((uint64_t)MI.getOperand(1).getImm()) << sh);
+ ctx.setRegVal(st, ctx.regD(0), {VK_CONST, (int64_t)v});
+ return true;
+ }
+ if (OpName == "MOVKXi" && MI.getNumOperands() >= 4 &&
+ MI.getOperand(2).isImm() && MI.getOperand(3).isImm()) {
+ SymVal cur = ctx.getRegVal(st, ctx.regD(1));
+ if (cur.kind == VK_CONST) {
+ unsigned sh = (unsigned)MI.getOperand(3).getImm() & 0x3f;
+ uint64_t u = ((uint64_t)cur.off & ~(0xffffULL << sh)) |
+ (((uint64_t)MI.getOperand(2).getImm() &
+ 0xffffULL) << sh);
+ ctx.setRegVal(st, ctx.regD(0), {VK_CONST, (int64_t)u});
+ return true;
+ }
+ }
+ if ((OpName == "ADDXrs" || OpName == "SUBXrs" ||
+ OpName == "ADDXrx" || OpName == "SUBXrx") &&
+ MI.getNumOperands() >= 4 && MI.getOperand(3).isImm()) {
+ int dst = ctx.regD(0), s1 = ctx.regD(1), s2 = ctx.regD(2);
+ SymVal v2 = ctx.getRegVal(st, s2);
+ int64_t imm_arg = MI.getOperand(3).getImm();
+ bool ok_shift = false;
+ if (OpName.ends_with("rs") && (imm_arg & ~0x3f) == 0) {
+ if (v2.kind == VK_CONST)
+ v2.off = (int64_t)((uint64_t)v2.off << imm_arg);
+ ok_shift = (imm_arg == 0 || v2.kind == VK_CONST);
+ } else if (OpName.ends_with("rx") &&
+ ((imm_arg >> 3) == 3 || (imm_arg >> 3) == 7) &&
+ (imm_arg & 7) == 0) {
+ ok_shift = true;
+ }
+ if (ok_shift) {
+ ctx.setRegVal(st, dst,
+ OpName.starts_with("ADD")
+ ? addSymVals(ctx.getRegVal(st, s1), v2)
+ : subSymVals(ctx.getRegVal(st, s1), v2));
+ return true;
+ }
+ }
+ if (OpName == "ANDXri" && ctx.regD(0) == 31) {
+ st.regs[31] = {VK_ALIGNED_SP, 0};
+ return true;
+ }
+
+ auto scaleOf = [](StringRef N) -> int64_t {
+ if (N.contains("Q"))
+ return 16;
+ if (N.contains("X") || N.contains("D"))
+ return 8;
+ if (N.contains("W") || N.contains("S"))
+ return 4;
+ if (N.contains("H"))
+ return 2;
+ return 1;
+ };
+
+ if ((OpName == "STPXpre" || OpName == "STPWpre" ||
+ OpName == "STPDpre" || OpName == "STPQpre") &&
+ MI.getNumOperands() >= 5 && MI.getOperand(4).isImm()) {
+ int wb = ctx.regD(0), r1 = ctx.regD(1), r2 = ctx.regD(2);
+ int base = ctx.regD(3);
+ SymVal addr = addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(4).getImm() * scaleOf(OpName));
+ ctx.setRegVal(st, wb, addr);
+ if (OpName == "STPXpre") {
+ st.store(addr, ctx.getRegVal(st, r1));
+ st.store(addSymImm(addr, 8), ctx.getRegVal(st, r2));
+ }
+ return true;
+ }
+ if ((OpName == "STPXpost" || OpName == "STPWpost" ||
+ OpName == "STPDpost" || OpName == "STPQpost") &&
+ MI.getNumOperands() >= 5 && MI.getOperand(4).isImm()) {
+ int wb = ctx.regD(0), r1 = ctx.regD(1), r2 = ctx.regD(2);
+ int base = ctx.regD(3);
+ SymVal addr = ctx.getRegVal(st, base);
+ if (OpName == "STPXpost") {
+ st.store(addr, ctx.getRegVal(st, r1));
+ st.store(addSymImm(addr, 8), ctx.getRegVal(st, r2));
+ }
+ ctx.setRegVal(st, wb,
+ addSymImm(addr,
+ MI.getOperand(4).getImm() * scaleOf(OpName)));
+ return true;
+ }
+ if (OpName == "STPXi" && MI.getNumOperands() >= 4 &&
+ MI.getOperand(3).isImm()) {
+ int r1 = ctx.regD(0), r2 = ctx.regD(1), base = ctx.regD(2);
+ SymVal addr = addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(3).getImm() * 8);
+ st.store(addr, ctx.getRegVal(st, r1));
+ st.store(addSymImm(addr, 8), ctx.getRegVal(st, r2));
+ return true;
+ }
+ if ((OpName == "LDPXpost" || OpName == "LDPWpost" ||
+ OpName == "LDPDpost" || OpName == "LDPQpost") &&
+ MI.getNumOperands() >= 5 && MI.getOperand(4).isImm()) {
+ int wb = ctx.regD(0), r1 = ctx.regD(1), r2 = ctx.regD(2);
+ int base = ctx.regD(3);
+ SymVal addr = ctx.getRegVal(st, base);
+ SymVal v1 = st.load(addr), v2 = st.load(addSymImm(addr, 8));
+ ctx.setRegVal(st, wb,
+ addSymImm(addr,
+ MI.getOperand(4).getImm() * scaleOf(OpName)));
+ if (OpName == "LDPXpost") {
+ ctx.setRegVal(st, r1, v1);
+ ctx.setRegVal(st, r2, v2);
+ } else {
+ if (r1 >= 0)
+ ctx.setRegVal(st, r1, {VK_UNKNOWN, 0});
+ if (r2 >= 0)
+ ctx.setRegVal(st, r2, {VK_UNKNOWN, 0});
+ }
+ return true;
+ }
+ if ((OpName == "LDPXpre" || OpName == "LDPWpre" ||
+ OpName == "LDPDpre" || OpName == "LDPQpre") &&
+ MI.getNumOperands() >= 5 && MI.getOperand(4).isImm()) {
+ int wb = ctx.regD(0), r1 = ctx.regD(1), r2 = ctx.regD(2);
+ int base = ctx.regD(3);
+ SymVal addr = addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(4).getImm() * scaleOf(OpName));
+ ctx.setRegVal(st, wb, addr);
+ if (OpName == "LDPXpre") {
+ ctx.setRegVal(st, r1, st.load(addr));
+ ctx.setRegVal(st, r2, st.load(addSymImm(addr, 8)));
+ } else {
+ if (r1 >= 0)
+ ctx.setRegVal(st, r1, {VK_UNKNOWN, 0});
+ if (r2 >= 0)
+ ctx.setRegVal(st, r2, {VK_UNKNOWN, 0});
+ }
+ return true;
+ }
+ if (OpName == "LDPXi" && MI.getNumOperands() >= 4 &&
+ MI.getOperand(3).isImm()) {
+ int r1 = ctx.regD(0), r2 = ctx.regD(1), base = ctx.regD(2);
+ SymVal addr = addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(3).getImm() * 8);
+ SymVal v1 = st.load(addr), v2 = st.load(addSymImm(addr, 8));
+ ctx.setRegVal(st, r1, v1);
+ ctx.setRegVal(st, r2, v2);
+ return true;
+ }
+ if ((OpName == "STRXpre" || OpName == "STRWpre" ||
+ OpName == "STRQpre" || OpName == "STRDpre" ||
+ OpName == "STRBpre" || OpName == "STRHpre") &&
+ MI.getNumOperands() >= 4 && MI.getOperand(3).isImm()) {
+ int wb = ctx.regD(0), rt = ctx.regD(1), base = ctx.regD(2);
+ SymVal addr = addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(3).getImm());
+ ctx.setRegVal(st, wb, addr);
+ if (OpName == "STRXpre")
+ st.store(addr, ctx.getRegVal(st, rt));
+ return true;
+ }
+ if ((OpName == "STRXpost" || OpName == "STRWpost" ||
+ OpName == "STRQpost" || OpName == "STRDpost" ||
+ OpName == "STRBpost" || OpName == "STRHpost") &&
+ MI.getNumOperands() >= 4 && MI.getOperand(3).isImm()) {
+ int wb = ctx.regD(0), rt = ctx.regD(1), base = ctx.regD(2);
+ SymVal addr = ctx.getRegVal(st, base);
+ if (OpName == "STRXpost")
+ st.store(addr, ctx.getRegVal(st, rt));
+ ctx.setRegVal(st, wb,
+ addSymImm(addr, MI.getOperand(3).getImm()));
+ return true;
+ }
+ if ((OpName == "LDRXpost" || OpName == "LDRWpost" ||
+ OpName == "LDRQpost" || OpName == "LDRDpost" ||
+ OpName == "LDRBpost" || OpName == "LDRHpost") &&
+ MI.getNumOperands() >= 4 && MI.getOperand(3).isImm()) {
+ int wb = ctx.regD(0), rt = ctx.regD(1), base = ctx.regD(2);
+ SymVal addr = ctx.getRegVal(st, base);
+ SymVal v = (OpName == "LDRXpost") ? st.load(addr)
+ : SymVal{VK_UNKNOWN, 0};
+ ctx.setRegVal(st, wb,
+ addSymImm(addr, MI.getOperand(3).getImm()));
+ if (rt >= 0)
+ ctx.setRegVal(st, rt, v);
+ return true;
+ }
+ if ((OpName == "LDRXpre" || OpName == "LDRWpre" ||
+ OpName == "LDRQpre" || OpName == "LDRDpre") &&
+ MI.getNumOperands() >= 4 && MI.getOperand(3).isImm()) {
+ int wb = ctx.regD(0), rt = ctx.regD(1), base = ctx.regD(2);
+ SymVal addr = addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(3).getImm());
+ ctx.setRegVal(st, wb, addr);
+ if (rt >= 0)
+ ctx.setRegVal(st, rt,
+ OpName == "LDRXpre"
+ ? st.load(addr)
+ : SymVal{VK_UNKNOWN, 0});
+ return true;
+ }
+ if (OpName == "STRXui" && MI.getNumOperands() >= 3 &&
+ MI.getOperand(2).isImm()) {
+ st.store(addSymImm(ctx.getRegVal(st, ctx.regD(1)),
+ MI.getOperand(2).getImm() * 8),
+ ctx.getRegVal(st, ctx.regD(0)));
+ return true;
+ }
+ if (OpName == "STURXi" && MI.getNumOperands() >= 3 &&
+ MI.getOperand(2).isImm()) {
+ st.store(addSymImm(ctx.getRegVal(st, ctx.regD(1)),
+ MI.getOperand(2).getImm()),
+ ctx.getRegVal(st, ctx.regD(0)));
+ return true;
+ }
+ if (OpName == "LDRXui" && MI.getNumOperands() >= 3 &&
+ MI.getOperand(2).isImm()) {
+ ctx.setRegVal(st, ctx.regD(0),
+ st.load(addSymImm(ctx.getRegVal(st, ctx.regD(1)),
+ MI.getOperand(2).getImm() * 8)));
+ return true;
+ }
+ if (OpName == "LDURXi" && MI.getNumOperands() >= 3 &&
+ MI.getOperand(2).isImm()) {
+ ctx.setRegVal(st, ctx.regD(0),
+ st.load(addSymImm(ctx.getRegVal(st, ctx.regD(1)),
+ MI.getOperand(2).getImm())));
+ return true;
+ }
+ return false;
+}
+
+/**
+ * stepInstructionRiscv() - Tier-2 symbolic lifter for RISC-V (RV64GC)
+ * @st: Abstract register/stack state updated in place.
+ * @OpName: LLVM MC opcode name (e.g. "C_ADDI16SP", "C_SDSP", "LUI").
+ * @ctx: Disassembled instruction context.
+ *
+ * Models standard and RVC compressed RISC-V prologue/epilogue sequences.
+ *
+ * Return: true if @OpName was modeled; false to trigger generic clobbering.
+ */
+static bool stepInstructionRiscv(AbsState &st, StringRef OpName,
+ const InsnStepCtx &ctx)
+{
+ const MCInst &MI = ctx.MI;
+
+ if ((OpName == "ADDI" || OpName == "C_ADDI" || OpName == "C_ADDI16SP" ||
+ OpName == "C_ADDI4SPN" || OpName == "ADDIW" ||
+ OpName == "C_ADDIW") &&
+ MI.getNumOperands() >= 3 && MI.getOperand(2).isImm()) {
+ int dst = ctx.regD(0), src = ctx.regD(1);
+ SymVal v = addSymImm(ctx.getRegVal(st, src),
+ MI.getOperand(2).getImm());
+ if ((OpName == "ADDIW" || OpName == "C_ADDIW") &&
+ v.kind == VK_CONST)
+ v.off = (int32_t)v.off;
+ ctx.setRegVal(st, dst, v);
+ return true;
+ }
+ if ((OpName == "LUI" || OpName == "C_LUI") &&
+ MI.getNumOperands() >= 2 && MI.getOperand(1).isImm()) {
+ int dst = ctx.regD(0);
+ int32_t s32 = (int32_t)((uint32_t)MI.getOperand(1).getImm() << 12);
+ ctx.setRegVal(st, dst, {VK_CONST, (int64_t)s32});
+ return true;
+ }
+ if (OpName == "C_LI" && MI.getNumOperands() >= 2 &&
+ MI.getOperand(1).isImm()) {
+ ctx.setRegVal(st, ctx.regD(0),
+ {VK_CONST, MI.getOperand(1).getImm()});
+ return true;
+ }
+ if (OpName == "C_MV" && MI.getNumOperands() >= 2) {
+ ctx.setRegVal(st, ctx.regD(0), ctx.getRegVal(st, ctx.regD(1)));
+ return true;
+ }
+ if ((OpName == "ADD" || OpName == "C_ADD" || OpName == "SUB" ||
+ OpName == "C_SUB") &&
+ MI.getNumOperands() >= 3) {
+ int dst = ctx.regD(0), s1 = ctx.regD(1), s2 = ctx.regD(2);
+ ctx.setRegVal(st, dst,
+ OpName.contains("ADD")
+ ? addSymVals(ctx.getRegVal(st, s1),
+ ctx.getRegVal(st, s2))
+ : subSymVals(ctx.getRegVal(st, s1),
+ ctx.getRegVal(st, s2)));
+ return true;
+ }
+ if (OpName == "ANDI" && ctx.regD(0) == 2 && ctx.regD(1) == 2) {
+ st.regs[2] = {VK_ALIGNED_SP, 0};
+ return true;
+ }
+ if ((OpName == "SD" || OpName == "C_SDSP") &&
+ MI.getNumOperands() >= 3 && MI.getOperand(2).isImm()) {
+ int src = ctx.regD(0), base = ctx.regD(1);
+ st.store(addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(2).getImm()),
+ ctx.getRegVal(st, src));
+ return true;
+ }
+ if ((OpName == "LD" || OpName == "C_LDSP") &&
+ MI.getNumOperands() >= 3 && MI.getOperand(2).isImm()) {
+ int dst = ctx.regD(0), base = ctx.regD(1);
+ ctx.setRegVal(st, dst,
+ st.load(addSymImm(ctx.getRegVal(st, base),
+ MI.getOperand(2).getImm())));
+ return true;
+ }
+ return false;
+}
+
+bool stepInstruction(AbsState &st, const MCInst &MI, StringRef OpName,
+ const MCInstrDesc &Desc, const MCRegisterInfo &MCRI,
+ const ArchSpec &AS, uint64_t NextPC,
+ const MCInstrAnalysis *MIA, uint64_t CurPC,
+ uint64_t InsnSize)
+{
+ InsnStepCtx ctx{MI, MCRI, AS, MIA, CurPC, NextPC, InsnSize};
+ bool handled = false;
+
+ if (AS.llvm_arch == Triple::x86_64)
+ handled = stepInstructionX86(st, OpName, Desc, ctx);
+ else if (AS.llvm_arch == Triple::aarch64)
+ handled = stepInstructionArm64(st, OpName, ctx);
+ else if (AS.llvm_arch == Triple::riscv64)
+ handled = stepInstructionRiscv(st, OpName, ctx);
+
+ if (!handled)
+ clobberGenericDefs(st, MI, Desc, MCRI, AS);
+ return handled;
+}
+
+/**
+ * normalizeRiscvControlFlow() - Classify RISC-V JAL/JALR control-flow roles
+ */
+void normalizeRiscvControlFlow(const MCInst &MI, StringRef OpName,
+ const MCRegisterInfo &MCRI,
+ bool &is_ret_or_ind_jump, bool &is_uncond_branch,
+ bool &is_call)
+{
+ int rd = (MI.getNumOperands() >= 1 && MI.getOperand(0).isReg())
+ ? mcRegToDwarf32(MCRI, MI.getOperand(0).getReg(),
+ Triple::riscv64)
+ : -1;
+ if (OpName == "JAL") {
+ if (rd == 0) {
+ is_uncond_branch = true;
+ is_call = false;
+ } else {
+ is_call = true;
+ }
+ } else if (OpName == "C_J") {
+ is_uncond_branch = true;
+ is_call = false;
+ } else if (OpName == "JALR") {
+ if (rd == 0) {
+ is_ret_or_ind_jump = true;
+ is_call = false;
+ } else {
+ is_call = true;
+ }
+ } else if (OpName == "C_JR") {
+ is_ret_or_ind_jump = true;
+ is_call = false;
+ } else if (OpName == "C_JALR") {
+ is_call = true;
+ }
+}
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 28/30] tools/unwind: Add CFG instruction abstract execution oracle to verify_cfi
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (26 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 27/30] tools/unwind: Add multi-arch symbolic instruction lifters for verify_cfi Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 29/30] tools/unwind: Add x86-64 ORC cross-check " Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 30/30] MAINTAINERS: Add DWARF CFI stack unwinding entry Ian Rogers
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Add verifyOracle2Instructions() in tools/unwind/verify_insn.cpp and
enable -DHAVE_VERIFY_INSN in tools/unwind/Makefile, propagating symbolic
register and stack state over per-function basic-block CFGs across
x86_64, arm64, and riscv64 and verifying at every reachable instruction
that Minimal DWARF CFI recovers the caller's exact CFA, RA (including
AArch64 PAC sign state), and FP.
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/unwind/Makefile | 5 +-
tools/unwind/verify_insn.cpp | 360 +++++++++++++++++++++++++++++++++++
2 files changed, 363 insertions(+), 2 deletions(-)
create mode 100644 tools/unwind/verify_insn.cpp
diff --git a/tools/unwind/Makefile b/tools/unwind/Makefile
index 90c4b47ae851..c0a8d477dc13 100644
--- a/tools/unwind/Makefile
+++ b/tools/unwind/Makefile
@@ -79,7 +79,7 @@ TOOLS_INCLUDES := -I$(srctree)/tools/include -I$(srctree)/tools/include/uapi \
SHIM_CFLAGS := -O2 -g -Wall -Wextra -Wno-unused-parameter -Wno-maybe-uninitialized \
$(TOOLS_INCLUDES)
-VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) \
+VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) -DHAVE_VERIFY_INSN \
-I$(CURDIR) $(TOOLS_INCLUDES) $(CXXFLAGS)
VERIFY_LDFLAGS := $(LLVM_LDFLAGS) $(LDFLAGS)
@@ -88,7 +88,8 @@ KERNEL_CFI_DEPS := $(srctree)/kernel/unwind/dwarf_cfi.c \
VERIFY_OBJS := $(OUTPUT)dwarf_cfi_host.o \
$(OUTPUT)verify_cfi.o \
- $(OUTPUT)verify_insn_arch.o
+ $(OUTPUT)verify_insn_arch.o \
+ $(OUTPUT)verify_insn.o
ifeq ($(HAS_LIBLLVM),1)
all: $(OUTPUT)verify_cfi
diff --git a/tools/unwind/verify_insn.cpp b/tools/unwind/verify_insn.cpp
new file mode 100644
index 000000000000..45dbd9a94764
--- /dev/null
+++ b/tools/unwind/verify_insn.cpp
@@ -0,0 +1,360 @@
+// SPDX-License-Identifier: GPL-2.0-only OR MIT
+/*
+ * Oracle 2: Multi-architecture basic-block CFG abstract execution & soundness
+ * verification against kernel/unwind/dwarf_cfi.c.
+ */
+
+#include "verify_insn.hpp"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstdio>
+#include <queue>
+#include <unordered_map>
+
+using namespace llvm;
+
+/**
+ * isKnownNoreturnName() - Check if a symbol name is a non-returning callee
+ * @Name: ELF symbol name of a direct call target.
+ *
+ * Return: true if calls to @Name never return to the fallthrough instruction.
+ */
+bool isKnownNoreturnName(StringRef Name)
+{
+ static const char *const Exact[] = {
+ "panic", "do_exit", "make_task_dead", "__stack_chk_fail",
+ "__stack_chk_fail_local", "fortify_panic", "usercopy_abort",
+ "__bug", "bug_at", "do_group_exit", "complete_and_exit",
+ "kthread_exit", "cpu_bringup_and_idle", "cpu_startup_entry",
+ "abort", "_exit", "_Exit", "exit", "__assert_fail",
+ "__assert_perror_fail", "__cxa_throw", "__cxa_rethrow",
+ "__cxa_bad_cast", "__cxa_bad_typeid", "_Unwind_Resume",
+ "_ZSt9terminatev", "_ZSt20__throw_length_errorPKc",
+ "_ZSt17__throw_bad_allocv", "_ZSt20__throw_out_of_rangePKc",
+ "_ZSt24__throw_out_of_range_fmtPKcz", "_ZSt19__throw_logic_errorPKc",
+ "__libc_fatal", "__chk_fail", "pthread_exit", "__longjmp_chk",
+ "longjmp", "_longjmp", "siglongjmp", "verr", "verrx", "err", "errx",
+ };
+ for (const char *s : Exact) {
+ if (Name == s)
+ return true;
+ }
+ if (Name.starts_with("__throw_") || Name.starts_with("_ZSt7__throw") ||
+ Name.starts_with("_ZSt9__throw") || Name.contains("panicking") ||
+ Name.starts_with("rust_begin_unwind") || Name.contains("noreturn") ||
+ Name.starts_with("__bad_"))
+ return true;
+ return false;
+}
+
+/**
+ * evalRowAgainstAbs() - Check Minimal DWARF unwind row against abstract state
+ * @st: Symbolic register/stack state reaching the current instruction PC.
+ * @row: Unwind row returned by kernel/unwind/dwarf_cfi.c at the same PC.
+ * @AS: Target architecture parameters.
+ * @err_kind: Populated with a short category tag on mismatch.
+ * @err_detail: Populated with diagnostic state details on mismatch.
+ *
+ * Return: true if CFA, RA (including AArch64 PAC sign state), and FP all
+ * recover the exact caller entry state; false on any discrepancy.
+ */
+static bool evalRowAgainstAbs(const AbsState &st, const dwarf_cfi_row &row,
+ const ArchSpec &AS, std::string &err_kind,
+ std::string &err_detail)
+{
+ SymVal cfa{VK_UNKNOWN, 0};
+ if (row.cfa_base == DWARF_CFI_BASE_SP)
+ cfa = addSymImm(st.regs[AS.karch.sp_reg], row.cfa_off);
+ else if (row.cfa_base == DWARF_CFI_BASE_FP)
+ cfa = addSymImm(st.regs[AS.karch.fp_reg], row.cfa_off);
+ else if (row.cfa_base == DWARF_CFI_BASE_REG && row.cfa_reg < 32)
+ cfa = addSymImm(st.regs[row.cfa_reg], row.cfa_off);
+ else if (row.cfa_base == DWARF_CFI_BASE_FP_INDIRECT)
+ cfa = st.load(addSymImm(st.regs[AS.karch.fp_reg], row.cfa_off));
+ else if (row.cfa_base == DWARF_CFI_BASE_SP_INDIRECT)
+ cfa = st.load(addSymImm(st.regs[AS.karch.sp_reg], row.cfa_off));
+
+ SymVal expected_cfa{VK_ENTRY_SP, AS.entry_cfa_off};
+ if (cfa != expected_cfa) {
+ err_kind = (cfa.kind == VK_UNKNOWN) ? "cfa_clobbered_or_opaque"
+ : "cfa_offset_mismatch";
+ char buf[160];
+ snprintf(buf, sizeof(buf),
+ "CFI cfa_base=%u off=%d evaluated to kind=%u off=%" PRId64
+ ", expected ENTRY_SP+%d",
+ row.cfa_base, row.cfa_off, cfa.kind, cfa.off,
+ AS.entry_cfa_off);
+ err_detail = buf;
+ return false;
+ }
+
+ if (row.ra_rule != DWARF_CFI_RULE_UNDEFINED) {
+ SymVal ra{VK_UNKNOWN, 0};
+ if (row.ra_rule == DWARF_CFI_RULE_SAME) {
+ if (AS.karch.ra_reg < 32)
+ ra = st.regs[AS.karch.ra_reg];
+ } else if (row.ra_rule == DWARF_CFI_RULE_OFFSET) {
+ ra = st.load(addSymImm(cfa, row.ra_off));
+ } else if (row.ra_rule == DWARF_CFI_RULE_SP_OFFSET) {
+ ra = st.load(addSymImm(st.regs[AS.karch.sp_reg],
+ row.ra_off));
+ }
+ int64_t exp_signed =
+ (AS.llvm_arch == Triple::aarch64 && row.ra_signed) ? 1 : 0;
+ if (ra.kind != VK_CALLER_RA ||
+ (AS.llvm_arch == Triple::aarch64 && ra.off != exp_signed)) {
+ err_kind = "ra_recovery_mismatch";
+ char buf[160];
+ snprintf(buf, sizeof(buf),
+ "CFI ra_rule=%u off=%d signed=%d evaluated to kind=%u off=%" PRId64,
+ row.ra_rule, row.ra_off, (int)row.ra_signed,
+ ra.kind, ra.off);
+ err_detail = buf;
+ return false;
+ }
+ }
+
+ if (row.fp_rule != DWARF_CFI_RULE_UNDEFINED) {
+ SymVal fp{VK_UNKNOWN, 0};
+ if (row.fp_rule == DWARF_CFI_RULE_SAME)
+ fp = st.regs[AS.karch.fp_reg];
+ else if (row.fp_rule == DWARF_CFI_RULE_OFFSET)
+ fp = st.load(addSymImm(cfa, row.fp_off));
+ else if (row.fp_rule == DWARF_CFI_RULE_FP_OFFSET)
+ fp = st.load(addSymImm(st.regs[AS.karch.fp_reg],
+ row.fp_off));
+ else if (row.fp_rule == DWARF_CFI_RULE_SP_OFFSET)
+ fp = st.load(addSymImm(st.regs[AS.karch.sp_reg],
+ row.fp_off));
+ if (fp.kind != VK_CALLER_FP) {
+ err_kind = "fp_recovery_mismatch";
+ char buf[160];
+ snprintf(buf, sizeof(buf),
+ "CFI fp_rule=%u off=%d evaluated to kind=%u off=%" PRId64,
+ row.fp_rule, row.fp_off, fp.kind, fp.off);
+ err_detail = buf;
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * verifyOracle2Instructions() - Verify CFI rows via CFG symbolic execution
+ */
+void verifyOracle2Instructions(
+ const ArchSpec &AS, uint64_t eh_hdr_vma, StringRef eh_hdr_bytes,
+ const std::vector<ExecSec> &exec_secs,
+ const std::vector<FuncSym> &func_syms,
+ const std::unordered_set<uint64_t> &noreturn_addrs,
+ const std::vector<FDERange> &fde_ranges, const MCDisassembler &Disasm,
+ const MCInstrInfo &MCII, const MCRegisterInfo &MCRI,
+ const MCInstrAnalysis *MIA, const VerifyOptions &opts, VerifyStats &st)
+{
+ st.has_insn_oracle = true;
+
+ auto findFDE = [&](uint64_t pc) -> const FDERange * {
+ auto it = std::upper_bound(
+ fde_ranges.begin(), fde_ranges.end(), pc,
+ [](uint64_t val, const FDERange &r) {
+ return val < r.start;
+ });
+ if (it == fde_ranges.begin())
+ return nullptr;
+ --it;
+ if (pc >= it->start && pc < it->end)
+ return &*it;
+ return nullptr;
+ };
+
+ for (const FuncSym &fn : func_syms) {
+ st.funcs_total++;
+ const FDERange *fr = findFDE(fn.addr);
+ if (!fr || !fr->supported) {
+ st.funcs_no_fde++;
+ continue;
+ }
+ if (fr->signal)
+ continue;
+
+ dwarf_cfi_row entry_row{};
+ if (dwarf_cfi_unwind_user_eh_frame_hdr(
+ (unsigned long)eh_hdr_vma, eh_hdr_bytes.size(),
+ (unsigned long)fn.addr, &AS.karch, &entry_row) != 0) {
+ st.funcs_no_fde++;
+ continue;
+ }
+ if (fn.addr != fr->start ||
+ entry_row.cfa_base != DWARF_CFI_BASE_SP ||
+ entry_row.cfa_off != AS.entry_cfa_off ||
+ entry_row.fp_rule != DWARF_CFI_RULE_SAME ||
+ (AS.ra_on_entry_stack
+ ? (entry_row.ra_rule != DWARF_CFI_RULE_OFFSET ||
+ entry_row.ra_off != -8)
+ : (entry_row.ra_rule != DWARF_CFI_RULE_SAME))) {
+ st.funcs_mid_frame_split++;
+ continue;
+ }
+
+ uint64_t range_end =
+ fn.size ? std::min(fr->end, fn.addr + fn.size) : fr->end;
+ if (range_end <= fn.addr)
+ continue;
+ ArrayRef<uint8_t> code =
+ findExecBytes(exec_secs, fn.addr, range_end - fn.addr);
+ if (code.empty())
+ continue;
+
+ st.funcs_verified++;
+
+ AbsState init_st;
+ init_st.regs[AS.karch.sp_reg] = {VK_ENTRY_SP, 0};
+ init_st.regs[AS.karch.fp_reg] = {VK_CALLER_FP, 0};
+ if (AS.ra_on_entry_stack)
+ init_st.store({VK_ENTRY_SP, 0}, {VK_CALLER_RA, 0});
+ else
+ init_st.regs[AS.karch.ra_reg] = {VK_CALLER_RA, 0};
+
+ std::unordered_map<uint64_t, AbsState> visited;
+ std::queue<uint64_t> worklist;
+ visited[fn.addr] = init_st;
+ worklist.push(fn.addr);
+
+ bool func_ok = true;
+ unsigned steps = 0;
+ while (!worklist.empty() && steps < 4096) {
+ uint64_t pc = worklist.front();
+ worklist.pop();
+ steps++;
+
+ if (pc < fn.addr || pc >= range_end)
+ continue;
+
+ const AbsState cur = visited[pc];
+
+ dwarf_cfi_row row{};
+ int kerr = dwarf_cfi_unwind_user_eh_frame_hdr(
+ (unsigned long)eh_hdr_vma, eh_hdr_bytes.size(),
+ (unsigned long)pc, &AS.karch, &row);
+ if (kerr != 0) {
+ func_ok = false;
+ recordIssue(st, opts, "fde_eval_error", fn.name);
+ break;
+ }
+
+ st.insns_verified++;
+ std::string ekind, edetail;
+ if (!evalRowAgainstAbs(cur, row, AS, ekind, edetail)) {
+ func_ok = false;
+ if (ekind.starts_with("cfa"))
+ st.insns_cfa_mismatch++;
+ else if (ekind.starts_with("ra"))
+ st.insns_ra_mismatch++;
+ else
+ st.insns_fp_mismatch++;
+
+ char loc_buf[128];
+ snprintf(loc_buf, sizeof(loc_buf),
+ "%s+0x%" PRIx64 " (0x%" PRIx64 "): ",
+ fn.name.c_str(), pc - fn.addr, pc);
+ recordIssue(st, opts, ekind,
+ std::string(loc_buf) + edetail);
+ break;
+ }
+
+ MCInst MI;
+ uint64_t InsnSize = 0;
+ ArrayRef<uint8_t> slice = code.slice(pc - fn.addr);
+ auto DStat = Disasm.getInstruction(MI, InsnSize, slice,
+ pc, nulls());
+ if (DStat != MCDisassembler::Success || InsnSize == 0)
+ continue;
+
+ const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
+ StringRef OpName = MCII.getName(MI.getOpcode());
+
+ bool is_ret_or_ind_jump =
+ Desc.isReturn() || Desc.isIndirectBranch();
+ bool is_uncond_branch = Desc.isUnconditionalBranch();
+ bool is_cond_branch = Desc.isConditionalBranch();
+ bool is_call = Desc.isCall();
+ if (AS.llvm_arch == Triple::riscv64)
+ normalizeRiscvControlFlow(MI, OpName, MCRI,
+ is_ret_or_ind_jump,
+ is_uncond_branch,
+ is_call);
+
+ if (is_ret_or_ind_jump || Desc.isTrap() ||
+ OpName == "UD2" || OpName == "BRK" ||
+ OpName == "EBREAK" || OpName == "C_EBREAK" ||
+ OpName == "SVC" || OpName == "ECALL" ||
+ OpName == "SYSCALL" || OpName == "IRET64" ||
+ OpName == "SYSRET64" || OpName == "ERET" ||
+ OpName == "SRET" || OpName == "MRET")
+ continue;
+
+ uint64_t next_pc = pc + InsnSize;
+
+ if (is_call) {
+ uint64_t CallTarget = 0;
+ bool has_target = MIA &&
+ MIA->evaluateBranch(MI, pc,
+ InsnSize,
+ CallTarget);
+ if (has_target &&
+ noreturn_addrs.count(CallTarget))
+ continue;
+ if (next_pc < range_end &&
+ (!has_target || CallTarget != next_pc)) {
+ dwarf_cfi_row next_row{};
+ if (dwarf_cfi_unwind_user_eh_frame_hdr(
+ (unsigned long)eh_hdr_vma,
+ eh_hdr_bytes.size(),
+ (unsigned long)next_pc,
+ &AS.karch, &next_row) == 0 &&
+ !rowsEqual(row, next_row))
+ continue;
+ }
+ }
+
+ AbsState next_st = cur;
+ if (AS.llvm_arch == Triple::riscv64 && is_call) {
+ for (int d = 1; d < 32; d++) {
+ if (d == 2 || d == 3 || d == 4 ||
+ d == 8 || d == 9 ||
+ (d >= 18 && d <= 27))
+ continue;
+ next_st.regs[d] = {VK_UNKNOWN, 0};
+ }
+ } else {
+ stepInstruction(next_st, MI, OpName, Desc, MCRI,
+ AS, next_pc, MIA, pc, InsnSize);
+ }
+
+ auto enqueue = [&](uint64_t target) {
+ if (target < fn.addr || target >= range_end)
+ return;
+ if (!visited.count(target)) {
+ visited[target] = next_st;
+ worklist.push(target);
+ }
+ };
+
+ if (is_uncond_branch || is_cond_branch) {
+ uint64_t BranchTarget = 0;
+ if (MIA && MIA->evaluateBranch(MI, pc, InsnSize,
+ BranchTarget))
+ enqueue(BranchTarget);
+ if (is_cond_branch)
+ enqueue(next_pc);
+ } else if (!Desc.isBarrier()) {
+ enqueue(next_pc);
+ }
+ }
+
+ if (func_ok)
+ st.funcs_clean++;
+ }
+}
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 29/30] tools/unwind: Add x86-64 ORC cross-check oracle to verify_cfi
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (27 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 28/30] tools/unwind: Add CFG instruction abstract execution oracle to verify_cfi Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
2026-11-25 6:15 ` [RFC PATCH v2 30/30] MAINTAINERS: Add DWARF CFI stack unwinding entry Ian Rogers
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, nsc,
linux-kbuild, ojeda, rust-for-linux, ardb, linux-efi, maz, oupton,
kvmarm, shuah, linux-kselftest, indu.bhagat, jremus, wnliu,
dylanbhatch, Ian Rogers
Add verifyOracle3Orc() in tools/unwind/verify_orc.cpp using
<asm/orc_types.h> and enable -DHAVE_VERIFY_ORC in tools/unwind/Makefile,
cross-checking objtool's ORC_TYPE_CALL entries in .orc_unwind /
.orc_unwind_ip directly against Minimal DWARF CFI across every
instruction covered by an FDE (matching identically on 99.9823% of
4,468,154 x86-64 vmlinux instructions, with 0 BP diffs).
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/unwind/Makefile | 5 +-
tools/unwind/verify_orc.cpp | 205 ++++++++++++++++++++++++++++++++++++
2 files changed, 208 insertions(+), 2 deletions(-)
create mode 100644 tools/unwind/verify_orc.cpp
diff --git a/tools/unwind/Makefile b/tools/unwind/Makefile
index c0a8d477dc13..d368b9ed90ee 100644
--- a/tools/unwind/Makefile
+++ b/tools/unwind/Makefile
@@ -79,7 +79,7 @@ TOOLS_INCLUDES := -I$(srctree)/tools/include -I$(srctree)/tools/include/uapi \
SHIM_CFLAGS := -O2 -g -Wall -Wextra -Wno-unused-parameter -Wno-maybe-uninitialized \
$(TOOLS_INCLUDES)
-VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) -DHAVE_VERIFY_INSN \
+VERIFY_CXXFLAGS := -O2 -g -Wall -Wextra -std=gnu++20 $(LLVM_CXXFLAGS) -DHAVE_VERIFY_INSN -DHAVE_VERIFY_ORC \
-I$(CURDIR) $(TOOLS_INCLUDES) $(CXXFLAGS)
VERIFY_LDFLAGS := $(LLVM_LDFLAGS) $(LDFLAGS)
@@ -89,7 +89,8 @@ KERNEL_CFI_DEPS := $(srctree)/kernel/unwind/dwarf_cfi.c \
VERIFY_OBJS := $(OUTPUT)dwarf_cfi_host.o \
$(OUTPUT)verify_cfi.o \
$(OUTPUT)verify_insn_arch.o \
- $(OUTPUT)verify_insn.o
+ $(OUTPUT)verify_insn.o \
+ $(OUTPUT)verify_orc.o
ifeq ($(HAS_LIBLLVM),1)
all: $(OUTPUT)verify_cfi
diff --git a/tools/unwind/verify_orc.cpp b/tools/unwind/verify_orc.cpp
new file mode 100644
index 000000000000..629849f3187e
--- /dev/null
+++ b/tools/unwind/verify_orc.cpp
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: GPL-2.0-only OR MIT
+/*
+ * Oracle 3: Direct x86-64 .orc_unwind / .orc_unwind_ip comparison against
+ * kernel/unwind/dwarf_cfi.c.
+ */
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wunused-parameter"
+#include "llvm/MC/MCInst.h"
+#include "llvm/Support/Endian.h"
+#include "llvm/Support/raw_ostream.h"
+#pragma GCC diagnostic pop
+
+#include "verify_cfi.hpp"
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstdio>
+
+extern "C" {
+#include <asm/orc_types.h>
+}
+
+using namespace llvm;
+
+/**
+ * verifyOracle3Orc() - Cross-check x86-64 .orc_unwind against Minimal DWARF CFI
+ * @AS: Target architecture specification (x86_64).
+ * @eh_hdr_vma: Virtual address of .eh_frame_hdr.
+ * @eh_hdr_bytes: Raw contents of .eh_frame_hdr.
+ * @orc_bytes: Raw contents of .orc_unwind (6-byte &struct orc_entry records).
+ * @orc_ip_bytes: Raw contents of .orc_unwind_ip (PC-relative s32 offsets).
+ * @orc_ip_vma: Virtual address of .orc_unwind_ip.
+ * @exec_secs: Executable ELF sections.
+ * @func_syms: Deduplicated STT_FUNC symbol list.
+ * @Disasm: x86-64 LLVM MCDisassembler.
+ * @STI: Target subtarget info for instruction printing.
+ * @InstPrinter: Disassembly formatter for mismatch diagnostics.
+ * @opts: CLI verification options.
+ * @st: Aggregated verification counters and diagnostic samples.
+ *
+ * Evaluates every instruction inside STT_FUNC symbols whose active ORC record
+ * has type %ORC_TYPE_CALL and a defined SP base register, mapping `<asm/
+ * orc_types.h>` `ORC_REG_*` encodings directly to `DWARF_CFI_BASE_*` and
+ * `DWARF_CFI_RULE_*` fields.
+ */
+void verifyOracle3Orc(const ArchSpec &AS, uint64_t eh_hdr_vma,
+ StringRef eh_hdr_bytes, StringRef orc_bytes,
+ StringRef orc_ip_bytes, uint64_t orc_ip_vma,
+ const std::vector<ExecSec> &exec_secs,
+ const std::vector<FuncSym> &func_syms,
+ const MCDisassembler &Disasm, const MCSubtargetInfo &STI,
+ MCInstPrinter &InstPrinter, const VerifyOptions &opts,
+ VerifyStats &st)
+{
+ st.has_orc = true;
+ constexpr size_t kOrcEntSz = 6;
+ size_t n_orc = orc_bytes.size() / kOrcEntSz;
+ size_t n_ip = orc_ip_bytes.size() / 4;
+ size_t n = std::min(n_orc, n_ip);
+ const uint8_t *orc_raw =
+ reinterpret_cast<const uint8_t *>(orc_bytes.data());
+ const uint8_t *ip_raw =
+ reinterpret_cast<const uint8_t *>(orc_ip_bytes.data());
+
+ std::vector<std::pair<uint64_t, size_t>> sorted_orc;
+ sorted_orc.reserve(n);
+ for (size_t i = 0; i < n; i++) {
+ int32_t rel = (int32_t)support::endian::read32le(ip_raw + i * 4);
+ uint64_t epc = orc_ip_vma + i * 4 + (uint64_t)(int64_t)rel;
+ sorted_orc.push_back({epc, i});
+ }
+ std::stable_sort(sorted_orc.begin(), sorted_orc.end(),
+ [](const auto &a, const auto &b) {
+ return a.first < b.first;
+ });
+
+ auto lookupOrcIdx = [&](uint64_t pc, size_t &idx_out) -> bool {
+ auto it = std::upper_bound(
+ sorted_orc.begin(), sorted_orc.end(), pc,
+ [](uint64_t val, const std::pair<uint64_t, size_t> &e) {
+ return val < e.first;
+ });
+ if (it == sorted_orc.begin())
+ return false;
+ --it;
+ idx_out = it->second;
+ return true;
+ };
+
+ for (const FuncSym &fn : func_syms) {
+ if (!fn.size)
+ continue;
+ ArrayRef<uint8_t> code =
+ findExecBytes(exec_secs, fn.addr, fn.size);
+ if (code.empty())
+ continue;
+
+ uint64_t off = 0;
+ while (off < code.size()) {
+ uint64_t pc = fn.addr + off;
+ MCInst MI;
+ uint64_t InsnSize = 0;
+ auto DStat = Disasm.getInstruction(
+ MI, InsnSize, code.slice(off), pc, nulls());
+ if (DStat != MCDisassembler::Success || InsnSize == 0) {
+ off++;
+ continue;
+ }
+ off += InsnSize;
+
+ size_t oidx = 0;
+ if (!lookupOrcIdx(pc, oidx))
+ continue;
+ const uint8_t *ep = orc_raw + oidx * kOrcEntSz;
+ int16_t sp_offset =
+ (int16_t)support::endian::read16le(ep + 0);
+ int16_t bp_offset =
+ (int16_t)support::endian::read16le(ep + 2);
+ uint16_t flags = support::endian::read16le(ep + 4);
+
+ unsigned o_sp_reg = flags & 0xf;
+ unsigned o_bp_reg = (flags >> 4) & 0xf;
+ unsigned o_type = (flags >> 8) & 0x7;
+ if (o_type != ORC_TYPE_CALL ||
+ o_sp_reg == ORC_REG_UNDEFINED)
+ continue;
+
+ st.orc_call_insns++;
+ dwarf_cfi_row row{};
+ if (dwarf_cfi_unwind_user_eh_frame_hdr(
+ (unsigned long)eh_hdr_vma,
+ eh_hdr_bytes.size(), (unsigned long)pc,
+ &AS.karch, &row) != 0) {
+ st.orc_no_fde++;
+ continue;
+ }
+
+ bool cfa_ok = false;
+ if (o_sp_reg == ORC_REG_SP) {
+ cfa_ok = (row.cfa_base == DWARF_CFI_BASE_SP &&
+ row.cfa_off == sp_offset);
+ } else if (o_sp_reg == ORC_REG_BP) {
+ cfa_ok = (row.cfa_base == DWARF_CFI_BASE_FP &&
+ row.cfa_off == sp_offset);
+ } else if (o_sp_reg == ORC_REG_BP_INDIRECT) {
+ cfa_ok = (row.cfa_base ==
+ DWARF_CFI_BASE_FP_INDIRECT &&
+ row.cfa_off == sp_offset);
+ } else if (o_sp_reg == ORC_REG_SP_INDIRECT) {
+ cfa_ok = (row.cfa_base ==
+ DWARF_CFI_BASE_SP_INDIRECT &&
+ row.cfa_off == sp_offset);
+ } else if (row.cfa_base == DWARF_CFI_BASE_REG) {
+ int exp_dreg = (o_sp_reg == ORC_REG_AX) ? 0 :
+ (o_sp_reg == ORC_REG_DX) ? 1 :
+ (o_sp_reg == ORC_REG_DI) ? 5 :
+ (o_sp_reg == ORC_REG_R10) ? 10 :
+ (o_sp_reg == ORC_REG_R13) ? 13 :
+ -1;
+ cfa_ok = (row.cfa_reg == exp_dreg &&
+ row.cfa_off == sp_offset);
+ }
+
+ bool bp_ok = false;
+ if (o_bp_reg == ORC_REG_UNDEFINED) {
+ bp_ok = (row.fp_rule == DWARF_CFI_RULE_SAME);
+ } else if (o_bp_reg == ORC_REG_PREV_SP) {
+ bp_ok = (row.fp_rule == DWARF_CFI_RULE_OFFSET &&
+ row.fp_off == bp_offset);
+ } else if (o_bp_reg == ORC_REG_BP) {
+ bp_ok = (row.fp_rule ==
+ DWARF_CFI_RULE_FP_OFFSET &&
+ row.fp_off == bp_offset);
+ }
+
+ if (cfa_ok && bp_ok) {
+ st.orc_matched++;
+ } else {
+ if (!cfa_ok)
+ st.orc_cfa_mismatch++;
+ if (!bp_ok)
+ st.orc_bp_mismatch++;
+ if (st.sample_orc_diffs.size() <
+ opts.max_samples * 3) {
+ std::string dis_str;
+ raw_string_ostream rso(dis_str);
+ InstPrinter.printInst(&MI, pc, "", STI,
+ rso);
+ char b[256];
+ snprintf(b, sizeof(b),
+ "%s+0x%" PRIx64 " (0x%" PRIx64
+ ")%s | ORC(sp=%u:%+d bp=%u:%+d)"
+ " vs CFI(cfa=%u:%+d fp=%u:%+d)",
+ fn.name.c_str(), pc - fn.addr,
+ pc, rso.str().c_str(), o_sp_reg,
+ sp_offset, o_bp_reg, bp_offset,
+ row.cfa_base, row.cfa_off,
+ row.fp_rule, row.fp_off);
+ st.sample_orc_diffs.push_back(b);
+ }
+ }
+ }
+ }
+}
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread* [RFC PATCH v2 30/30] MAINTAINERS: Add DWARF CFI stack unwinding entry
2026-11-25 6:14 [RFC PATCH v2 00/30] unwind: Minimal DWARF CFI unwinding for user and kernel space Ian Rogers
` (28 preceding siblings ...)
2026-11-25 6:15 ` [RFC PATCH v2 29/30] tools/unwind: Add x86-64 ORC cross-check " Ian Rogers
@ 2026-11-25 6:15 ` Ian Rogers
29 siblings, 0 replies; 31+ messages in thread
From: Ian Rogers @ 2026-11-25 6:15 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, llvm, 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 MAINTAINERS entry for Minimal DWARF CFI stack unwinding covering
the core .eh_frame / .eh_frame_hdr bytecode interpreter and KUnit tests,
the user-space PT_GNU_EH_FRAME VMA unwinder, the x86-64 DWARF CFI kernel
unwinder, the build-time .eh_frame minifier and analyzer scripts, the
standalone tools/unwind/ CFI verifier, and the deferred user-space CFI
kselftest.
Also add arch/*/include/asm/unwind_user*.h to USERSPACE STACK UNWINDING
so architectural unwind_user headers on x86, arm64, riscv, and future
ports are routed to the user-space unwinding maintainers.
Signed-off-by: Ian Rogers <irogers@google.com>
---
MAINTAINERS | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/MAINTAINERS b/MAINTAINERS
index 44540a1eb2b8..0584279d745e 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -9496,6 +9496,21 @@ Q: http://patchwork.linuxtv.org/project/linux-media/list/
F: drivers/media/usb/dvb-usb-v2/dvb_usb*
F: drivers/media/usb/dvb-usb-v2/usb_urb.c
+DWARF CFI STACK UNWINDING
+M: Ian Rogers <irogers@google.com>
+L: linux-trace-kernel@vger.kernel.org
+L: linux-kernel@vger.kernel.org
+S: Maintained
+F: arch/x86/kernel/unwind_dwarf.c
+F: include/linux/unwind_dwarf_cfi.h
+F: kernel/unwind/dwarf_cfi*.c
+F: kernel/unwind/user_cfi.c
+F: scripts/eh_frame_min.py
+F: scripts/min_eh_frame.c
+F: tools/include/linux/unwind_dwarf_cfi.h
+F: tools/testing/selftests/perf_events/unwind_user_cfi.c
+F: tools/unwind/
+
DYNAMIC DEBUG
M: Jason Baron <jbaron@akamai.com>
M: Jim Cromie <jim.cromie@gmail.com>
@@ -29300,6 +29315,7 @@ USERSPACE STACK UNWINDING
M: Josh Poimboeuf <jpoimboe@kernel.org>
M: Steven Rostedt <rostedt@goodmis.org>
S: Maintained
+F: arch/*/include/asm/unwind_user*.h
F: include/linux/unwind*.h
F: kernel/unwind/
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply related [flat|nested] 31+ messages in thread