| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/10/17 07:54 | flow | patch-triage |
3mArgs:null Results: {
"EnableConfigs": [
"BPF_SYSCALL",
"BPF_JIT",
"UNWINDER_ORC"
],
"FocusSymbols": [
"bpf_unwind",
"arch_bpf_stack_walk_ra",
"bpf_exc_check_info",
"bpf_exc_check_prog",
"bpf_exc_patch_unwind_calls",
"bpf_exc_fill_native_ranges",
"bpf_exc_pad_for_ip",
"bpf_jit_supports_cleanup_pads"
],
"KMSANReasoning": "The patch series introduces support for BPF exception cleanup landing pads, adding the `bpf_unwind()` and `bpf_unwind_resume()` kfuncs, stack frame return-address rewriting via `arch_bpf_stack_walk_ra()`, BPF verifier tracking for cleanup pads and unwinding edges, and ELF/loader support for `.bpf_cleanup`.\n\nFrom a memory sanitizer perspective, a dedicated KMSAN fuzzing session is not warranted:\n1. No Kernel-to-User Information Leaks: The patch adds input fields to `union bpf_attr` for `BPF_PROG_LOAD` and copies records from user memory to the kernel, but does not add or modify any data copied back to userspace (no `bpf_prog_info` extensions, `copy_to_user()`, or netlink attributes).\n2. Proper Memory Initialization: All newly introduced kernel heap objects (`struct bpf_exception_info`, `struct bpf_cleanup_range`, `struct bpf_cleanup_info`) are allocated using `kzalloc_obj()` or `kvcalloc()`, and stack variables (`struct bpf_unwind_ctx`, `struct bpf_unwind_ra_consume_entry_data`, instruction patch arrays) are zero-initialized with designated initializers or fully written before use.\n3. KASAN/LOCKDEP Applicability: The primary risks associated with this patch involve control-flow graph exploration, insn patch offsets, return address rewriting on the call stack, and lock/reference tracking across unwinds. These issues manifest as out-of-bounds memory accesses, illegal instruction dereferences, or locking mismatches, which are detected by KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN.\n\nTherefore, running a dedicated KMSAN session would provide no additional benefit over standard KASAN/LOCKDEP testing.",
"NeedsKMSAN": false,
"Reasoning": "The patch introduces BPF exception cleanup landing pads and unwinding support (via bpf_unwind and bpf_unwind_resume kfuncs). It adds kernel verification logic for exception cleanup tables, CFG analysis for landing pad edges, backtracking adjustments, instruction patching, x86 JIT epilogue handling, and stack return address rewriting via arch_bpf_stack_walk_ra() and the ORC unwinder. This touches core BPF verification and runtime execution paths reachable via the bpf() syscall on amd64, warranting fuzzing.",
"WorthFuzzing": true
} |
| 1/1 | 2026/10/17 07:54 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 48a3914cefd04f21bef6cd3ea63cd8ad35d7b0c8\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Sat Oct 17 07:54:16 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/arch/arm64/kernel/stacktrace.c b/arch/arm64/kernel/stacktrace.c\nindex 3ebcf8c53fb04..6ff485280da53 100644\n--- a/arch/arm64/kernel/stacktrace.c\n+++ b/arch/arm64/kernel/stacktrace.c\n@@ -445,6 +445,83 @@ noinline noinstr void arch_bpf_stack_walk(bool (*consume_entry)(void *cookie, u6\n \tkunwind_stack_walk(arch_bpf_unwind_consume_entry, \u0026data, current, NULL);\n }\n \n+struct bpf_unwind_ra_consume_entry_data {\n+\tbool (*consume_entry)(void *cookie, u64 ip, u64 sp, u64 fp, u64 *ra);\n+\tvoid *cookie;\n+\tunsigned long record;\n+\tbool seen_first;\n+};\n+\n+/* PACIA1716 (hint #8): sign x17 with the modifier in x16, under key IA. */\n+static u64 bpf_unwind_sign_ra(u64 ra, u64 modifier)\n+{\n+\tregister u64 x17 asm(\"x17\") = ra;\n+\tregister u64 x16 asm(\"x16\") = modifier;\n+\n+\tasm volatile(ARM64_ASM_PREAMBLE\n+\t\t \"\thint\t#8\\n\"\n+\t\t : \"+r\" (x17) : \"r\" (x16));\n+\treturn x17;\n+}\n+\n+/* PACIASP's modifier is the entry sp, record + 16 for a BPF prologue. */\n+static void bpf_unwind_store_ra(unsigned long record, u64 ra)\n+{\n+\tstruct frame_record *rec = (struct frame_record *)record;\n+\n+\t/*\n+\t * Whether the slot holds a signed address is a property of the build,\n+\t * not one to be read off the value: a PAC can come out equal to the\n+\t * bits stripping puts back, and a signed address would then be taken\n+\t * for an unsigned one. What signs is CONFIG_ARM64_PTR_AUTH_KERNEL --\n+\t * the prologue here, and -mbranch-protection for everything the\n+\t * compiler emits.\n+\t */\n+\tif (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL) \u0026\u0026\n+\t system_supports_address_auth())\n+\t\tra = bpf_unwind_sign_ra(ra, record + sizeof(struct frame_record));\n+\tWRITE_ONCE(rec-\u003elr, ra);\n+}\n+\n+static bool\n+arch_bpf_unwind_ra_consume_entry(const struct kunwind_state *state, void *cookie)\n+{\n+\tstruct bpf_unwind_ra_consume_entry_data *data = cookie;\n+\tunsigned long record = data-\u003erecord;\n+\tbool seen_first = data-\u003eseen_first;\n+\tu64 ra = state-\u003ecommon.pc;\n+\tbool cont;\n+\n+\t/* The record this frame's return address will have come out of. */\n+\tdata-\u003erecord = state-\u003ecommon.fp;\n+\tdata-\u003eseen_first = true;\n+\n+\t/*\n+\t * The first pc returns into bpf_unwind(), from this walk's own frame\n+\t * record: not a BPF frame, and not one to redirect.\n+\t */\n+\tif (!seen_first)\n+\t\treturn true;\n+\t/* A consumer that stops still gets to redirect the frame it stopped on. */\n+\tcont = data-\u003econsume_entry(data-\u003ecookie, state-\u003ecommon.pc, 0,\n+\t\t\t\t state-\u003ecommon.fp, \u0026ra);\n+\tif (ra != state-\u003ecommon.pc)\n+\t\tbpf_unwind_store_ra(record, ra);\n+\treturn cont;\n+}\n+\n+noinline noinstr void arch_bpf_stack_walk_ra(bool (*consume_entry)(void *cookie, u64 ip, u64 sp,\n+\t\t\t\t\t\t\t\t u64 fp, u64 *ra),\n+\t\t\t\t\t void *cookie)\n+{\n+\tstruct bpf_unwind_ra_consume_entry_data data = {\n+\t\t.consume_entry = consume_entry,\n+\t\t.cookie = cookie,\n+\t};\n+\n+\tkunwind_stack_walk(arch_bpf_unwind_ra_consume_entry, \u0026data, current, NULL);\n+}\n+\n static const char *state_source_string(const struct kunwind_state *state)\n {\n \tswitch (state-\u003esource) {\ndiff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c\nindex 506c4201fec85..c8c0328b3219c 100644\n--- a/arch/arm64/net/bpf_jit_comp.c\n+++ b/arch/arm64/net/bpf_jit_comp.c\n@@ -2422,6 +2422,17 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr\n \t\t * reasons, expects to point to the next instruction)\n \t\t */\n \t\tbpf_prog_update_insn_ptrs(prog, ctx.offset, ctx.ro_image);\n+\n+\t\t/*\n+\t\t * Same byte offsets, consumed by the bpf_unwind() walk:\n+\t\t * turn the cleanup records into native address ranges now that\n+\t\t * the image is final.\n+\t\t */\n+\t\tbpf_exc_fill_native_ranges(prog, ctx.offset, ctx.ro_image);\n+\n+\t\t/* Where an unwind sends a frame with no pad. */\n+\t\tprog-\u003eaux-\u003eepilogue_ip = (u64)ctx.ro_image +\n+\t\t\t\t\t ctx.epilogue_offset * AARCH64_INSN_SIZE;\n out_off:\n \t\tif (!ro_header \u0026\u0026 priv_stack_ptr) {\n \t\t\tfree_percpu(priv_stack_ptr);\n@@ -3415,6 +3426,11 @@ bool bpf_jit_supports_exceptions(void)\n \treturn true;\n }\n \n+bool bpf_jit_supports_cleanup_pads(void)\n+{\n+\treturn true;\n+}\n+\n bool bpf_jit_supports_arena(void)\n {\n \treturn true;\ndiff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c\nindex 11a4e4f87aac7..e0e39661bce83 100644\n--- a/arch/x86/net/bpf_jit_comp.c\n+++ b/arch/x86/net/bpf_jit_comp.c\n@@ -15,6 +15,7 @@\n #include \u003clinux/memory.h\u003e\n #include \u003clinux/sort.h\u003e\n #include \u003clinux/execmem.h\u003e\n+#include \u003clinux/kprobes.h\u003e\n #include \u003casm/extable.h\u003e\n #include \u003casm/ftrace.h\u003e\n #include \u003casm/set_memory.h\u003e\n@@ -3779,6 +3780,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *\n \t\t\tseen_exit = true;\n \t\t\t/* Update cleanup_addr */\n \t\t\tctx-\u003ecleanup_addr = proglen;\n+\t\t\t/* Where an unwind sends a frame with no pad. */\n+\t\t\tbpf_prog-\u003eaux-\u003eepilogue_ip = (u64)image + proglen;\n \t\t\tif (bpf_prog_was_classic(bpf_prog) \u0026\u0026\n \t\t\t !ns_capable_noaudit(\u0026init_user_ns, CAP_SYS_ADMIN)) {\n \t\t\t\tif (emit_spectre_bhb_barrier(\u0026prog, ip, bpf_prog))\n@@ -4976,6 +4979,13 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr\n \t\t */\n \t\tbpf_prog_update_insn_ptrs(prog, addrs, image);\n \n+\t\t/*\n+\t\t * Same mapping, consumed by the bpf_unwind() walk:\n+\t\t * turn the cleanup records into native address ranges now\n+\t\t * that the image is final.\n+\t\t */\n+\t\tbpf_exc_fill_native_ranges(prog, addrs, image);\n+\n \t\t/*\n \t\t * ctx.prog_offset is used when CFI preambles put code *before*\n \t\t * the function. See emit_cfi(). For FineIBT specifically this code\n@@ -5114,6 +5124,11 @@ bool bpf_jit_supports_exceptions(void)\n \treturn IS_ENABLED(CONFIG_UNWINDER_ORC);\n }\n \n+bool bpf_jit_supports_cleanup_pads(void)\n+{\n+\treturn IS_ENABLED(CONFIG_UNWINDER_ORC);\n+}\n+\n bool bpf_jit_supports_private_stack(void)\n {\n \treturn true;\n@@ -5135,6 +5150,27 @@ void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp\n #endif\n }\n \n+notrace void arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp,\n+\t\t\t\t\t\t\tu64 *ra),\n+\t\t\t\t void *cookie)\n+{\n+#if defined(CONFIG_UNWINDER_ORC)\n+\tstruct unwind_state state;\n+\tunsigned long addr, *ra;\n+\n+\tfor (unwind_start(\u0026state, current, NULL, NULL); !unwind_done(\u0026state);\n+\t unwind_next_frame(\u0026state)) {\n+\t\taddr = state.ip;\n+\t\tra = unwind_get_return_address_ptr(\u0026state);\n+\t\tif (!ra)\n+\t\t\tbreak;\n+\t\tif (!consume_fn(cookie, (u64)addr, (u64)state.sp, (u64)state.bp, (u64 *)ra))\n+\t\t\tbreak;\n+\t}\n+#endif\n+}\n+NOKPROBE_SYMBOL(arch_bpf_stack_walk_ra);\n+\n void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,\n \t\t\t struct bpf_prog *new, struct bpf_prog *old)\n {\ndiff --git a/include/linux/bpf.h b/include/linux/bpf.h\nindex 54144372281cb..1b3b6ee05c092 100644\n--- a/include/linux/bpf.h\n+++ b/include/linux/bpf.h\n@@ -1841,6 +1841,34 @@ enum bpf_sig_keyring {\n \tBPF_SIG_KEYRING_BPF,\n };\n \n+/* One cleanup region of a JITed (sub)program. */\n+struct bpf_cleanup_range {\n+\tu64 begin;\n+\tu64 end;\n+\tu64 pad;\n+};\n+\n+struct bpf_exception_info {\n+\tstruct bpf_cleanup_info *info;\n+\tstruct bpf_cleanup_range *ranges;\n+\tu32 nr_info;\n+\tu32 nr_ranges;\n+};\n+\n+#ifdef CONFIG_BPF_SYSCALL\n+void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image);\n+void bpf_exc_free_info(struct bpf_prog_aux *aux);\n+#else\n+\n+static inline void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image)\n+{\n+}\n+\n+static inline void bpf_exc_free_info(struct bpf_prog_aux *aux)\n+{\n+}\n+#endif\n+\n struct bpf_prog_aux {\n \tatomic64_t refcnt;\n \tu32 used_map_cnt;\n@@ -1882,6 +1910,7 @@ struct bpf_prog_aux {\n \tbool priv_stack_requested;\n \tbool changes_pkt_data;\n \tbool might_sleep;\n+\tbool might_unwind;\n \tbool kprobe_write_ctx;\n \tstruct {\n \t\ts32 keyring_serial;\n@@ -1922,6 +1951,8 @@ struct bpf_prog_aux {\n \tu64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64);\n \tu16 stack_arg_sp_adjust;\n \tu16 freplace_link_cnt; /* counts freplace links extending this prog */\n+\tstruct bpf_exception_info *exc;\n+\tu64 epilogue_ip; /* native address of this (sub)program's epilogue */\n #ifdef CONFIG_SECURITY\n \tvoid *security;\n #endif\ndiff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h\nindex 112ca1511da4d..1c33b2cf29cfe 100644\n--- a/include/linux/bpf_verifier.h\n+++ b/include/linux/bpf_verifier.h\n@@ -379,6 +379,7 @@ struct bpf_func_state {\n \tbool in_async_callback_fn;\n \tbool in_exception_callback_fn;\n \tbool no_stack_arg_load;\n+\tbool in_pad;\n \t/* For callback calling functions that limit number of possible\n \t * callback executions (e.g. bpf_loop) keeps track of current\n \t * simulated iteration number.\n@@ -429,6 +430,8 @@ enum {\n \tINSN_F_SRC_REG_STACK = BIT(2), /* src_reg is PTR_TO_STACK */\n \n \tINSN_F_STACK_ARG_ACCESS = BIT(3),\n+\n+\tINSN_F_UNWIND = BIT(4),\n };\n \n /* Registers linked to one jump condition that a history entry can record */\n@@ -437,10 +440,10 @@ enum {\n struct bpf_jmp_history_entry {\n \t/* insn idx can't be bigger than 1 million */\n \tu32 idx : 20;\n-\tu32 frame : 4;\t/* stack access frame number */\n+\tu32 frame : 4;\t/* stack access frame number, or the frame an unwind ran in */\n \t/* special INSN_F_xxx flags */\n-\tu32 flags : 4;\n-\tu32 : 4;\n+\tu32 flags : 5;\n+\tu32 : 3;\n \tu32 prev_idx : 20;\n \tu32 spi : 12;\t/* stack slot index */\n \t/*\n@@ -527,6 +530,8 @@ struct bpf_verifier_state {\n \n \tbool speculative;\n \tbool in_sleepable;\n+\t/* the path ends with an unwind returning from frame 0 */\n+\tbool unwind_exit;\n \n \t/*\n \t * First and last insn idx of this verifier state.\n@@ -806,6 +811,11 @@ struct bpf_insn_aux_data {\n \tu64 jump_target:1;\n \n \tunsigned int orig_idx; /* original instruction index, initialized once */\n+\t/*\n+\t * 1 + the instruction index of the exception cleanup landing pad\n+\t * this call site unwinds to, or 0 for none.\n+\t */\n+\tu32 cleanup_pad;\n \t/*\n \t * CFG strongly connected component this instruction belongs to,\n \t * zero if it is a singleton SCC.\n@@ -944,6 +954,7 @@ struct bpf_subprog_info {\n \ts16 fastcall_stack_off;\n \tbool has_tail_call: 1;\n \tbool might_throw: 1;\n+\tbool might_unwind: 1;\n \tbool tail_call_reachable: 1;\n \tbool has_ld_abs: 1;\n \tbool is_cb: 1;\n@@ -1135,6 +1146,8 @@ struct bpf_verifier_env {\n \tstruct spill_snapshot **callsite_at_stack;\n \tu32 pass_cnt; /* number of times do_check() was called */\n \tu32 subprog_cnt;\n+\tstruct bpf_cleanup_info *cleanup_info;\n+\tu32 cleanup_info_cnt;\n \t/* number of instructions analyzed by the verifier */\n \tu32 prev_insn_processed, insn_processed;\n \t/* number of jmps, calls, exits analyzed so far */\n@@ -1990,6 +2003,7 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union\n int bpf_convert_ctx_accesses(struct bpf_verifier_env *env);\n int bpf_jit_subprogs(struct bpf_verifier_env *env);\n int bpf_fixup_call_args(struct bpf_verifier_env *env);\n+int bpf_exc_patch_unwind_calls(struct bpf_verifier_env *env);\n int bpf_do_misc_fixups(struct bpf_verifier_env *env);\n int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);\n \ndiff --git a/include/linux/filter.h b/include/linux/filter.h\nindex 9339c6131f8ff..a61a78675d11e 100644\n--- a/include/linux/filter.h\n+++ b/include/linux/filter.h\n@@ -1248,6 +1248,7 @@ bool bpf_jit_supports_stack_args(void);\n bool bpf_jit_supports_arena_args(void);\n bool bpf_jit_supports_far_kfunc_call(void);\n bool bpf_jit_supports_exceptions(void);\n+bool bpf_jit_supports_cleanup_pads(void);\n bool bpf_jit_supports_ptr_xchg(void);\n bool bpf_jit_supports_arena(void);\n bool bpf_jit_supports_arena_scalar(void);\n@@ -1290,6 +1291,8 @@ u32 bpf_jit_plan_arg_moves(const struct bpf_jit_arg_abi *abi,\n \t\t\t struct bpf_jit_arg_move *moves);\n u64 bpf_arch_uaddress_limit(void);\n void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie);\n+void arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp, u64 *ra),\n+\t\t\t void *cookie);\n u64 arch_bpf_timed_may_goto(void);\n u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *);\n bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id);\ndiff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h\nindex 6f70db7515dd4..9d7439c96e52e 100644\n--- a/include/uapi/linux/bpf.h\n+++ b/include/uapi/linux/bpf.h\n@@ -1708,6 +1708,9 @@ union bpf_attr {\n \t\t * verification.\n \t\t */\n \t\t__s32\t\tkeyring_id;\n+\t\t__aligned_u64\tcleanup_info;\t/* exception cleanup table */\n+\t\t__u32\t\tcleanup_info_rec_size; /* userspace bpf_cleanup_info size */\n+\t\t__u32\t\tcleanup_info_cnt; /* number of bpf_cleanup_info records */\n \t};\n \n \tstruct { /* anonymous struct used by BPF_OBJ_* commands */\n@@ -7669,6 +7672,17 @@ struct bpf_line_info {\n \t__u32\tline_col;\n };\n \n+/*\n+ * One record of an exception cleanup table: calls in [begin_off, end_off)\n+ * that unwind resume at landing_pad_off. All three are instruction offsets\n+ * in the program as loaded.\n+ */\n+struct bpf_cleanup_info {\n+\t__u32\tbegin_off;\n+\t__u32\tend_off;\n+\t__u32\tlanding_pad_off;\n+};\n+\n struct bpf_spin_lock {\n \t__u32\tval;\n };\ndiff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile\nindex 269810b128c46..df71ec19d0a04 100644\n--- a/kernel/bpf/Makefile\n+++ b/kernel/bpf/Makefile\n@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_\n obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o\n obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o\n obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o\n-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o\n+obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o exception.o\n obj-${CONFIG_BPF_LSM}\t += bpf_inode_storage.o\n obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o\n obj-$(CONFIG_BPF_JIT) += trampoline.o\ndiff --git a/kernel/bpf/backtrack.c b/kernel/bpf/backtrack.c\nindex 43d5740034c0f..16f6ef59ddf75 100644\n--- a/kernel/bpf/backtrack.c\n+++ b/kernel/bpf/backtrack.c\n@@ -4,6 +4,7 @@\n #include \u003clinux/bpf_verifier.h\u003e\n #include \u003clinux/filter.h\u003e\n #include \u003clinux/bitmap.h\u003e\n+#include \"exception.h\"\n \n #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)\n \n@@ -424,7 +425,31 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,\n \t\tif (class == BPF_STX)\n \t\t\tbt_set_reg(bt, sreg);\n \t} else if (class == BPF_JMP || class == BPF_JMP32) {\n-\t\tif (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {\n+\t\tif (hist \u0026\u0026 (hist-\u003eflags \u0026 INSN_F_UNWIND)) {\n+\t\t\t/*\n+\t\t\t * A bpf_unwind(), a resume or an unwinding global call\n+\t\t\t * left frame hist-\u003eframe here, for a landing pad in\n+\t\t\t * this one, or for the main frame's exit, which is\n+\t\t\t * this frame itself when it is the main one. The walk\n+\t\t\t * crosses back into that frame, past any frames\n+\t\t\t * between, which were entered and never returned\n+\t\t\t * from. The pad found r0 unknown and r1-r5 clobbered;\n+\t\t\t * r6-r9 and the stack are this frame's own and stay\n+\t\t\t * marked in its masks until the walk comes back out.\n+\t\t\t */\n+\t\t\tbt_clear_reg(bt, BPF_REG_0);\n+\t\t\tif (bt_reg_mask(bt) \u0026 BPF_REGMASK_ARGS) {\n+\t\t\t\tverifier_bug(env, \"backtracking unwind unexpected regs %x\",\n+\t\t\t\t\t bt_reg_mask(bt));\n+\t\t\t\treturn -EFAULT;\n+\t\t\t}\n+\t\t\tif (verifier_bug_if(hist-\u003eframe \u003c bt-\u003eframe, env,\n+\t\t\t\t\t \"unwind from frame %d to frame %d\",\n+\t\t\t\t\t hist-\u003eframe, bt-\u003eframe))\n+\t\t\t\treturn -EFAULT;\n+\t\t\tbt-\u003eframe = hist-\u003eframe;\n+\t\t\treturn 0;\n+\t\t} else if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {\n \t\t\tint subprog_insn_idx, subprog = -1;\n \n \t\t\tif (bpf_pseudo_call(insn)) {\n@@ -440,10 +465,17 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,\n \t\t\t\t * extra instructions from subprog; the next\n \t\t\t\t * instruction after call to global subprog\n \t\t\t\t * should be literally next instruction in\n-\t\t\t\t * caller program\n+\t\t\t\t * caller program, or the call's landing pad,\n+\t\t\t\t * branched to from the state the call returns\n+\t\t\t\t * in when the callee can unwind. A pad may be\n+\t\t\t\t * the next instruction too, so the two edges\n+\t\t\t\t * cannot be told apart, and need not be: the\n+\t\t\t\t * pad finds r0 unknown and r1-r5 cleared, so\n+\t\t\t\t * both clear the same registers below.\n \t\t\t\t */\n-\t\t\t\tverifier_bug_if(idx + 1 != subseq_idx, env,\n-\t\t\t\t\t\t\"extra insn from subprog\");\n+\t\t\t\tverifier_bug_if(idx + 1 != subseq_idx \u0026\u0026\n+\t\t\t\t\t\tbpf_exc_pad_of_call(env, idx) != subseq_idx,\n+\t\t\t\t\t\tenv, \"extra insn from subprog\");\n \t\t\t\t/* global subprog always sets R0 */\n \t\t\t\tbt_clear_reg(bt, BPF_REG_0);\n \t\t\t\t/* and if it does not set R2, main pass would catch it */\ndiff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c\nindex bce7b5abcfda3..9608293bdc069 100644\n--- a/kernel/bpf/cfg.c\n+++ b/kernel/bpf/cfg.c\n@@ -6,6 +6,7 @@\n #include \u003clinux/sort.h\u003e\n \n #include \"diagnostics.h\"\n+#include \"exception.h\"\n \n #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)\n \n@@ -75,6 +76,14 @@ static void mark_subprog_might_throw(struct bpf_verifier_env *env, int off)\n \tsubprog-\u003emight_throw = true;\n }\n \n+static void mark_subprog_might_unwind(struct bpf_verifier_env *env, int off)\n+{\n+\tstruct bpf_subprog_info *subprog;\n+\n+\tsubprog = bpf_find_containing_subprog(env, off);\n+\tsubprog-\u003emight_unwind = true;\n+}\n+\n /* 't' is an index of a call-site.\n * 'w' is a callee entry point.\n * Eventually this function would be called when env-\u003ecfg.insn_state[w] == EXPLORED.\n@@ -90,6 +99,7 @@ static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)\n \tcaller-\u003echanges_pkt_data |= callee-\u003echanges_pkt_data;\n \tcaller-\u003emight_sleep |= callee-\u003emight_sleep;\n \tcaller-\u003emight_throw |= callee-\u003emight_throw;\n+\tcaller-\u003emight_unwind |= callee-\u003emight_unwind;\n }\n \n enum {\n@@ -160,6 +170,38 @@ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)\n \treturn DONE_EXPLORING;\n }\n \n+static int visit_cleanup_pad_edge(int t, struct bpf_verifier_env *env)\n+{\n+\tint *insn_stack = env-\u003ecfg.insn_stack;\n+\tint *insn_state = env-\u003ecfg.insn_state;\n+\tint w;\n+\n+\tif (!env-\u003ecleanup_info_cnt)\n+\t\treturn DONE_EXPLORING;\n+\tw = bpf_exc_pad_of_call(env, t);\n+\tif (w \u003c 0)\n+\t\treturn DONE_EXPLORING;\n+\n+\t/*\n+\t * @t is a call that may branch here, and @w is the target of that\n+\t * branch, so both are prune points. @w especially: every covered call\n+\t * site in a region unwinds to the same pad, and without a prune point\n+\t * at its head the verifier walks the pad again for each of them.\n+\t */\n+\tmark_prune_point(env, t);\n+\tmark_prune_point(env, w);\n+\tmark_jmp_point(env, w);\n+\tmark_jump_target(env, w);\n+\n+\tif (insn_state[w])\n+\t\treturn DONE_EXPLORING;\n+\tif (env-\u003ecfg.cur_stack \u003e= env-\u003eprog-\u003elen)\n+\t\treturn -E2BIG;\n+\tinsn_stack[env-\u003ecfg.cur_stack++] = w;\n+\tinsn_state[w] |= DISCOVERED;\n+\treturn KEEP_EXPLORING;\n+}\n+\n static int visit_func_call_insn(int t, struct bpf_insn *insns,\n \t\t\t\tstruct bpf_verifier_env *env,\n \t\t\t\tbool visit_callee)\n@@ -167,6 +209,11 @@ static int visit_func_call_insn(int t, struct bpf_insn *insns,\n \tint ret, insn_sz;\n \tint w;\n \n+\t/* One push per visit: @t is revisited once the pad is explored. */\n+\tret = visit_cleanup_pad_edge(t, env);\n+\tif (ret != DONE_EXPLORING)\n+\t\treturn ret;\n+\n \tinsn_sz = bpf_is_ldimm64(\u0026insns[t]) ? 2 : 1;\n \tret = push_insn(t, t + insn_sz, FALLTHROUGH, env);\n \tif (ret)\n@@ -630,6 +677,8 @@ static int visit_insn(int t, struct bpf_verifier_env *env)\n \t\t\t\tmark_subprog_changes_pkt_data(env, t);\n \t\t\tif (ret == 0 \u0026\u0026 bpf_is_throw_kfunc(insn))\n \t\t\t\tmark_subprog_might_throw(env, t);\n+\t\t\tif (ret == 0 \u0026\u0026 bpf_is_unwind_kfunc(insn))\n+\t\t\t\tmark_subprog_might_unwind(env, t);\n \t\t}\n \t\treturn visit_func_call_insn(t, insns, env, insn-\u003esrc_reg == BPF_PSEUDO_CALL);\n \n@@ -667,6 +716,82 @@ static int visit_insn(int t, struct bpf_verifier_env *env)\n \t}\n }\n \n+static bool addr_taken_subprog_might_unwind(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n+\tstruct bpf_subprog_info *callee;\n+\tstruct bpf_func_ptr *ptrs;\n+\tu32 cnt, j;\n+\tint i;\n+\n+\tfor (i = 0; i \u003c env-\u003eprog-\u003elen; i++) {\n+\t\tif (bpf_pseudo_func(\u0026insns[i])) {\n+\t\t\tcallee = bpf_find_containing_subprog(env, i + insns[i].imm + 1);\n+\t\t\tif (callee-\u003emight_unwind)\n+\t\t\t\treturn true;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tptrs = insn_func_ptrs(env, i, \u0026cnt);\n+\t\tfor (j = 0; j \u003c cnt; j++) {\n+\t\t\tcallee = bpf_find_containing_subprog(env, ptrs[j].xlated_off);\n+\t\t\tif (callee-\u003emight_unwind)\n+\t\t\t\treturn true;\n+\t\t}\n+\t}\n+\treturn false;\n+}\n+\n+/*\n+ * merge_callee_effects() does not carry might_unwind to a subprog that calls\n+ * through a pointer it was handed. So if any subprog a callx can reach may\n+ * unwind, mark every subprog with a callx, and its callers.\n+ *\n+ * This is conservative: a subprog with a callx is marked even when nothing it\n+ * calls unwinds. The main walk knows each callx's target and could tell those\n+ * apart.\n+ */\n+static void mark_callx_might_unwind(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n+\tstruct bpf_subprog_info *caller, *callee;\n+\tint i, j, len = env-\u003eprog-\u003elen;\n+\tstruct bpf_func_ptr *ptrs;\n+\tbool changed;\n+\tu32 cnt;\n+\n+\tif (!addr_taken_subprog_might_unwind(env))\n+\t\treturn;\n+\n+\tfor (i = 0; i \u003c len; i++)\n+\t\tif (bpf_is_callx(\u0026insns[i]))\n+\t\t\tbpf_find_containing_subprog(env, i)-\u003emight_unwind = true;\n+\n+\tdo {\n+\t\tchanged = false;\n+\t\tfor (i = 0; i \u003c len; i++) {\n+\t\t\tcaller = bpf_find_containing_subprog(env, i);\n+\t\t\tif (caller-\u003emight_unwind)\n+\t\t\t\tcontinue;\n+\t\t\tif (bpf_pseudo_call(\u0026insns[i]) || bpf_pseudo_func(\u0026insns[i])) {\n+\t\t\t\tcallee = bpf_find_containing_subprog(env, i + insns[i].imm + 1);\n+\t\t\t\tif (!callee-\u003emight_unwind)\n+\t\t\t\t\tcontinue;\n+\t\t\t\tcaller-\u003emight_unwind = true;\n+\t\t\t\tchanged = true;\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tptrs = insn_func_ptrs(env, i, \u0026cnt);\n+\t\t\tfor (j = 0; j \u003c cnt; j++) {\n+\t\t\t\tcallee = bpf_find_containing_subprog(env, ptrs[j].xlated_off);\n+\t\t\t\tif (!callee-\u003emight_unwind)\n+\t\t\t\t\tcontinue;\n+\t\t\t\tcaller-\u003emight_unwind = true;\n+\t\t\t\tchanged = true;\n+\t\t\t}\n+\t\t}\n+\t} while (changed);\n+}\n+\n /* non-recursive depth-first-search to detect loops in BPF program\n * loop == back-edge in directed graph\n */\n@@ -757,6 +882,7 @@ int bpf_check_cfg(struct bpf_verifier_env *env)\n \t\t}\n \t}\n \tret = 0; /* cfg looks good */\n+\tmark_callx_might_unwind(env);\n \tenv-\u003eprog-\u003eaux-\u003echanges_pkt_data = env-\u003esubprog_info[0].changes_pkt_data;\n \tenv-\u003eprog-\u003eaux-\u003emight_sleep = env-\u003esubprog_info[0].might_sleep;\n \ndiff --git a/kernel/bpf/core.c b/kernel/bpf/core.c\nindex 642f0ab8eb2d8..3af8e82726917 100644\n--- a/kernel/bpf/core.c\n+++ b/kernel/bpf/core.c\n@@ -292,6 +292,7 @@ void __bpf_prog_free(struct bpf_prog *fp)\n \t\tmutex_destroy(\u0026fp-\u003eaux-\u003edst_mutex);\n \t\tmutex_destroy(\u0026fp-\u003eaux-\u003est_ops_assoc_mutex);\n \t\tkfree(fp-\u003eaux-\u003epoke_tab);\n+\t\tbpf_exc_free_info(fp-\u003eaux);\n \t\tkfree(fp-\u003eaux);\n \t}\n \tfree_percpu(fp-\u003estats);\n@@ -3524,6 +3525,17 @@ void __weak arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp,\n {\n }\n \n+void __weak arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp,\n+\t\t\t\t\t\t u64 *ra),\n+\t\t\t\t void *cookie)\n+{\n+}\n+\n+bool __weak bpf_jit_supports_cleanup_pads(void)\n+{\n+\treturn false;\n+}\n+\n bool __weak bpf_jit_supports_timed_may_goto(void)\n {\n \treturn false;\ndiff --git a/kernel/bpf/exception.c b/kernel/bpf/exception.c\nnew file mode 100644\nindex 0000000000000..e06f2606b41e7\n--- /dev/null\n+++ b/kernel/bpf/exception.c\n@@ -0,0 +1,379 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#include \u003clinux/bpf.h\u003e\n+#include \u003clinux/bpf_verifier.h\u003e\n+#include \u003clinux/btf_ids.h\u003e\n+#include \u003clinux/filter.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \"exception.h\"\n+\n+#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)\n+\n+#define MIN_BPF_CLEANUP_INFO_SIZE\t12\n+#define MAX_CLEANUP_INFO_REC_SIZE\t252\t/* as MAX_FUNCINFO_REC_SIZE */\n+\n+int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,\n+\t\t bpfptr_t uattr)\n+{\n+\tu32 krec_size = sizeof(struct bpf_cleanup_info);\n+\tu32 i, nrec, urec_size, min_size, prev_end = 0;\n+\tstruct bpf_cleanup_info *krecord;\n+\tbpfptr_t urecord;\n+\tint ret = -EINVAL;\n+\n+\tnrec = attr-\u003ecleanup_info_cnt;\n+\tif (!nrec)\n+\t\treturn 0;\n+\tif (nrec \u003e env-\u003eprog-\u003elen) {\n+\t\tverbose(env, \"cleanup info has %u records for %u instructions\\n\",\n+\t\t\tnrec, env-\u003eprog-\u003elen);\n+\t\treturn -EINVAL;\n+\t}\n+\n+\turec_size = attr-\u003ecleanup_info_rec_size;\n+\tif (urec_size \u003c MIN_BPF_CLEANUP_INFO_SIZE ||\n+\t urec_size \u003e MAX_CLEANUP_INFO_REC_SIZE ||\n+\t urec_size % sizeof(u32)) {\n+\t\tverbose(env, \"invalid cleanup info rec size %u\\n\", urec_size);\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tkrecord = kvcalloc(nrec, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);\n+\tif (!krecord)\n+\t\treturn -ENOMEM;\n+\n+\tmin_size = min_t(u32, krec_size, urec_size);\n+\turecord = make_bpfptr(attr-\u003ecleanup_info, uattr.is_kernel);\n+\tfor (i = 0; i \u003c nrec; i++) {\n+\t\tstruct bpf_subprog_info *sb, *se, *sl;\n+\t\tstruct bpf_cleanup_info *rec = \u0026krecord[i];\n+\n+\t\t/*\n+\t\t * A record longer than the kernel's is taken only if the rest\n+\t\t * is zero. Unlike func_info, no size is handed back for the\n+\t\t * loader to zero the rest and retry: a field this kernel does\n+\t\t * not know could change what a pad does.\n+\t\t */\n+\t\tret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);\n+\t\tif (ret) {\n+\t\t\tif (ret == -E2BIG)\n+\t\t\t\tverbose(env, \"nonzero tailing record in cleanup info\\n\");\n+\t\t\tgoto err_free;\n+\t\t}\n+\n+\t\tif (copy_from_bpfptr(rec, urecord, min_size)) {\n+\t\t\tret = -EFAULT;\n+\t\t\tgoto err_free;\n+\t\t}\n+\t\tbpfptr_add(\u0026urecord, urec_size);\n+\n+\t\tret = -EINVAL;\n+\t\tif (rec-\u003ebegin_off \u003e= rec-\u003eend_off) {\n+\t\t\tverbose(env, \"cleanup_info[%u]: begin %u \u003e= end %u\\n\",\n+\t\t\t\ti, rec-\u003ebegin_off, rec-\u003eend_off);\n+\t\t\tgoto err_free;\n+\t\t}\n+\t\tif (rec-\u003ebegin_off \u003c prev_end) {\n+\t\t\tverbose(env,\n+\t\t\t\t\"cleanup_info[%u]: range [%u,%u) is unsorted or overlaps the previous record\\n\",\n+\t\t\t\ti, rec-\u003ebegin_off, rec-\u003eend_off);\n+\t\t\tgoto err_free;\n+\t\t}\n+\t\tprev_end = rec-\u003eend_off;\n+\n+\t\tsb = bpf_find_containing_subprog(env, rec-\u003ebegin_off);\n+\t\tse = bpf_find_containing_subprog(env, rec-\u003eend_off - 1);\n+\t\tsl = bpf_find_containing_subprog(env, rec-\u003elanding_pad_off);\n+\t\tif (!sb || !se || !sl) {\n+\t\t\tverbose(env, \"cleanup_info[%u]: offset out of range\\n\", i);\n+\t\t\tgoto err_free;\n+\t\t}\n+\t\tif (sb != se || sb != sl) {\n+\t\t\tverbose(env,\n+\t\t\t\t\"cleanup_info[%u]: range/landing pad span multiple subprogs\\n\",\n+\t\t\t\ti);\n+\t\t\tgoto err_free;\n+\t\t}\n+\t\t/*\n+\t\t * A zero opcode is the second half of a 16-byte insn, not an\n+\t\t * insn. end_off is exclusive, so it may be one past the last.\n+\t\t */\n+\t\tif (!env-\u003eprog-\u003einsnsi[rec-\u003ebegin_off].code ||\n+\t\t !env-\u003eprog-\u003einsnsi[rec-\u003elanding_pad_off].code ||\n+\t\t (rec-\u003eend_off \u003c env-\u003eprog-\u003elen \u0026\u0026\n+\t\t !env-\u003eprog-\u003einsnsi[rec-\u003eend_off].code)) {\n+\t\t\tverbose(env, \"cleanup_info[%u]: points at invalid insn\\n\", i);\n+\t\t\tgoto err_free;\n+\t\t}\n+\t}\n+\n+\t/* Reject a landing pad inside any call-site range, its own included. */\n+\tret = -EINVAL;\n+\tfor (i = 0; i \u003c nrec; i++) {\n+\t\tu32 pad = krecord[i].landing_pad_off;\n+\t\tu32 l = 0, r = nrec;\n+\n+\t\twhile (l \u003c r) {\n+\t\t\tu32 m = l + (r - l) / 2;\n+\n+\t\t\tif (pad \u003c krecord[m].begin_off) {\n+\t\t\t\tr = m;\n+\t\t\t} else if (pad \u003e= krecord[m].end_off) {\n+\t\t\t\tl = m + 1;\n+\t\t\t} else {\n+\t\t\t\tverbose(env,\n+\t\t\t\t\t\"cleanup_info[%u]: landing pad %u is inside the call-site range of cleanup_info[%u]\\n\",\n+\t\t\t\t\ti, pad, m);\n+\t\t\t\tgoto err_free;\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tenv-\u003ecleanup_info = krecord;\n+\tenv-\u003ecleanup_info_cnt = nrec;\n+\treturn 0;\n+\n+err_free:\n+\tkvfree(krecord);\n+\treturn ret;\n+}\n+\n+BTF_ID_LIST_SINGLE(bpf_unwind_id, func, bpf_unwind)\n+BTF_ID_LIST_SINGLE(bpf_unwind_resume_id, func, bpf_unwind_resume)\n+\n+int bpf_exc_check_callback(struct bpf_verifier_env *env, int subprog)\n+{\n+\tif (!env-\u003esubprog_info[subprog].might_unwind)\n+\t\treturn 0;\n+\n+\tverbose(env, \"subprog %d may unwind and is used as a callback\\n\", subprog);\n+\treturn -EINVAL;\n+}\n+\n+static int reject_throw(struct bpf_verifier_env *env)\n+{\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c env-\u003eprog-\u003elen; i++) {\n+\t\tif (!bpf_is_throw_kfunc(\u0026env-\u003eprog-\u003einsnsi[i]))\n+\t\t\tcontinue;\n+\t\tverbose(env,\n+\t\t\t\"exception cleanup cannot be combined with bpf_throw at insn %u\\n\",\n+\t\t\ti);\n+\t\treturn -EINVAL;\n+\t}\n+\treturn 0;\n+}\n+\n+void bpf_exc_mark_call_sites(struct bpf_verifier_env *env)\n+{\n+\tu32 i, j;\n+\n+\tfor (i = 0; i \u003c env-\u003ecleanup_info_cnt; i++) {\n+\t\tstruct bpf_cleanup_info *rec = \u0026env-\u003ecleanup_info[i];\n+\n+\t\tfor (j = rec-\u003ebegin_off; j \u003c rec-\u003eend_off; j++) {\n+\t\t\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[j];\n+\n+\t\t\tif (!bpf_pseudo_call(insn) \u0026\u0026 !bpf_is_callx(insn) \u0026\u0026\n+\t\t\t !bpf_is_unwind_kfunc(insn))\n+\t\t\t\tcontinue;\n+\t\t\tenv-\u003einsn_aux_data[j].cleanup_pad = rec-\u003elanding_pad_off + 1;\n+\t\t}\n+\t}\n+}\n+\n+bool bpf_prog_may_unwind(const struct bpf_verifier_env *env)\n+{\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++)\n+\t\tif (env-\u003esubprog_info[i].might_unwind)\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+int bpf_exc_check_prog(struct bpf_verifier_env *env)\n+{\n+\tint err;\n+\n+\tif (bpf_prog_is_offloaded(env-\u003eprog-\u003eaux)) {\n+\t\tverbose(env,\n+\t\t\t\"exception cleanup is not supported for offloaded programs\\n\");\n+\t\treturn -EINVAL;\n+\t}\n+\tif (!bpf_jit_supports_cleanup_pads() || !env-\u003eprog-\u003ejit_requested) {\n+\t\tverbose(env,\n+\t\t\t\"exception cleanup needs a JIT that can dispatch landing pads\\n\");\n+\t\treturn -EOPNOTSUPP;\n+\t}\n+\tif (env-\u003eops-\u003egen_epilogue) {\n+\t\tverbose(env,\n+\t\t\t\"exception cleanup is not supported for a program with an epilogue\\n\");\n+\t\treturn -EOPNOTSUPP;\n+\t}\n+\tif (env-\u003eexception_callback_subprog) {\n+\t\tverbose(env,\n+\t\t\t\"exception cleanup cannot be combined with an exception callback\\n\");\n+\t\treturn -EINVAL;\n+\t}\n+\terr = reject_throw(env);\n+\tif (err)\n+\t\treturn err;\n+\tenv-\u003eprog-\u003ejit_required = 1;\n+\treturn 0;\n+}\n+\n+bool bpf_is_unwind_kfunc(const struct bpf_insn *insn)\n+{\n+\treturn bpf_pseudo_kfunc_call(insn) \u0026\u0026 insn-\u003eoff == 0 \u0026\u0026\n+\t insn-\u003eimm == bpf_unwind_id[0];\n+}\n+\n+bool bpf_is_unwind_resume_kfunc(const struct bpf_insn *insn)\n+{\n+\treturn bpf_pseudo_kfunc_call(insn) \u0026\u0026 insn-\u003eoff == 0 \u0026\u0026\n+\t insn-\u003eimm == bpf_unwind_resume_id[0];\n+}\n+\n+static bool unwinding(const struct bpf_verifier_state *state)\n+{\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c= state-\u003ecurframe; i++)\n+\t\tif (state-\u003eframe[i]-\u003ein_pad)\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+int bpf_exc_check_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)\n+{\n+\tbool in_pad = cur_func(env)-\u003ein_pad;\n+\tu32 i = env-\u003einsn_idx;\n+\tconst char *why = NULL;\n+\n+\tif (unwinding(env-\u003ecur_state)) {\n+\t\tif (bpf_is_unwind_kfunc(insn)) {\n+\t\t\tverbose(env, \"insn %u starts a second unwind while one is in flight\\n\", i);\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\tif (bpf_pseudo_call(insn)) {\n+\t\t\tint subprog = bpf_find_subprog(env, i + insn-\u003eimm + 1);\n+\n+\t\t\tif (bpf_subprog_is_global(env, subprog) \u0026\u0026\n+\t\t\t env-\u003esubprog_info[subprog].might_unwind) {\n+\t\t\t\tverbose(env,\n+\t\t\t\t\t\"insn %u calls global subprog %d, which can unwind while an unwind is in flight\\n\",\n+\t\t\t\t\ti, subprog);\n+\t\t\t\treturn -EINVAL;\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tif (!in_pad)\n+\t\treturn 0;\n+\n+\tif (insn-\u003ecode == (BPF_JMP | BPF_EXIT)) {\n+\t\tverbose(env,\n+\t\t\t\"exit at insn %u ends a landing pad: a catch pad is not supported yet, only cleanup pads that resume\\n\",\n+\t\t\ti);\n+\t\treturn -EINVAL;\n+\t}\n+\tif (bpf_helper_call(insn) \u0026\u0026 insn-\u003eimm == BPF_FUNC_tail_call)\n+\t\twhy = \"is a tail call, which replaces the frame\";\n+\telse if (BPF_CLASS(insn-\u003ecode) == BPF_LD \u0026\u0026\n+\t\t (BPF_MODE(insn-\u003ecode) == BPF_ABS || BPF_MODE(insn-\u003ecode) == BPF_IND))\n+\t\twhy = \"is a BPF_LD_[ABS|IND], which can leave through the epilogue\";\n+\telse if (insn_is_gotox(insn))\n+\t\twhy = \"is an indirect jump, which nothing a compiler frontend emits in a pad needs\";\n+\n+\tif (!why)\n+\t\treturn 0;\n+\n+\tverbose(env, \"insn %u %s, and is in a landing pad\\n\", i, why);\n+\treturn -EINVAL;\n+}\n+\n+int bpf_exc_pad_of_call(struct bpf_verifier_env *env, u32 idx)\n+{\n+\tu32 pad = env-\u003einsn_aux_data[idx].cleanup_pad;\n+\n+\treturn pad ? (int)pad - 1 : -1;\n+}\n+\n+/*\n+ * The record covering @ip, which is a return address: the call it belongs to\n+ * is the instruction before it, so a range matches on begin \u003c ip \u003c= end.\n+ */\n+const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip)\n+{\n+\tconst struct bpf_exception_info *exc = prog-\u003eaux-\u003eexc;\n+\tu32 l = 0, r = exc ? exc-\u003enr_ranges : 0;\n+\n+\twhile (l \u003c r) {\n+\t\tu32 m = l + (r - l) / 2;\n+\t\tconst struct bpf_cleanup_range *rec = \u0026exc-\u003eranges[m];\n+\n+\t\tif (ip \u003c= rec-\u003ebegin)\n+\t\t\tr = m;\n+\t\telse if (ip \u003e rec-\u003eend)\n+\t\t\tl = m + 1;\n+\t\telse\n+\t\t\treturn rec;\n+\t}\n+\treturn NULL;\n+}\n+\n+int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt)\n+{\n+\tstruct bpf_cleanup_range *ranges;\n+\tstruct bpf_exception_info *exc;\n+\n+\texc = kzalloc_obj(struct bpf_exception_info, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);\n+\tranges = kvcalloc(cnt, sizeof(*ranges), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);\n+\tif (!exc || !ranges) {\n+\t\tkfree(exc);\n+\t\tkvfree(ranges);\n+\t\tkvfree(recs);\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\texc-\u003einfo = recs;\n+\texc-\u003enr_info = cnt;\n+\texc-\u003eranges = ranges;\n+\t/* Withheld until the JIT has filled the table in. */\n+\texc-\u003enr_ranges = 0;\n+\taux-\u003eexc = exc;\n+\treturn 0;\n+}\n+\n+void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image)\n+{\n+\tstruct bpf_exception_info *exc = prog-\u003eaux-\u003eexc;\n+\tu32 i, n;\n+\n+\tif (!exc)\n+\t\treturn;\n+\n+\tn = exc-\u003enr_info;\n+\tfor (i = 0; i \u003c n; i++) {\n+\t\tconst struct bpf_cleanup_info *rec = \u0026exc-\u003einfo[i];\n+\n+\t\texc-\u003eranges[i].begin = (u64)(long)image + addrs[rec-\u003ebegin_off];\n+\t\texc-\u003eranges[i].end = (u64)(long)image + addrs[rec-\u003eend_off];\n+\t\texc-\u003eranges[i].pad = (u64)(long)image + addrs[rec-\u003elanding_pad_off];\n+\t}\n+\texc-\u003enr_ranges = n;\n+}\n+\n+void bpf_exc_free_info(struct bpf_prog_aux *aux)\n+{\n+\tstruct bpf_exception_info *exc = aux-\u003eexc;\n+\n+\tif (!exc)\n+\t\treturn;\n+\tkvfree(exc-\u003eranges);\n+\tkvfree(exc-\u003einfo);\n+\tkfree(exc);\n+\taux-\u003eexc = NULL;\n+}\ndiff --git a/kernel/bpf/exception.h b/kernel/bpf/exception.h\nnew file mode 100644\nindex 0000000000000..09bbcd0a09de3\n--- /dev/null\n+++ b/kernel/bpf/exception.h\n@@ -0,0 +1,30 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#ifndef __BPF_EXCEPTION_H\n+#define __BPF_EXCEPTION_H\n+\n+#include \u003clinux/bpfptr.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+union bpf_attr;\n+struct bpf_verifier_env;\n+struct bpf_insn;\n+struct bpf_cleanup_info;\n+struct bpf_cleanup_range;\n+struct bpf_prog;\n+struct bpf_prog_aux;\n+\n+int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,\n+\t\t bpfptr_t uattr);\n+void bpf_exc_mark_call_sites(struct bpf_verifier_env *env);\n+int bpf_exc_check_prog(struct bpf_verifier_env *env);\n+bool bpf_prog_may_unwind(const struct bpf_verifier_env *env);\n+int bpf_exc_pad_of_call(struct bpf_verifier_env *env, u32 idx);\n+bool bpf_is_unwind_kfunc(const struct bpf_insn *insn);\n+bool bpf_is_unwind_resume_kfunc(const struct bpf_insn *insn);\n+int bpf_exc_check_callback(struct bpf_verifier_env *env, int subprog);\n+int bpf_exc_check_insn(struct bpf_verifier_env *env, struct bpf_insn *insn);\n+int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt);\n+const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip);\n+\n+#endif /* __BPF_EXCEPTION_H */\ndiff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c\nindex 608621d7f225c..dd29ead32cf33 100644\n--- a/kernel/bpf/fixups.c\n+++ b/kernel/bpf/fixups.c\n@@ -9,6 +9,7 @@\n #include \u003clinux/sched/signal.h\u003e\n #include \u003cnet/xdp.h\u003e\n #include \"disasm.h\"\n+#include \"exception.h\"\n \n #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)\n \n@@ -244,11 +245,20 @@ static void adjust_insn_aux_data(struct bpf_verifier_env *env,\n \t\t\tdata[i].non_stack_access =\n \t\t\t\tdata[off + cnt - 1].non_stack_access;\n \t\t\tdata[off + cnt - 1].non_stack_access = false;\n+\t\t\tdata[i].cleanup_pad = data[off + cnt - 1].cleanup_pad;\n+\t\t\tdata[off + cnt - 1].cleanup_pad = 0;\n+\t\t\tdata[i].arg_prog = data[off + cnt - 1].arg_prog;\n+\t\t\tdata[off + cnt - 1].arg_prog = 0;\n \t\t} else if (bpf_is_mem_insn(insn + i)) {\n \t\t\tdata[i].non_stack_access = true;\n \t\t}\n \t}\n \n+\tif (env-\u003ecleanup_info_cnt)\n+\t\tfor (i = 0; i \u003c prog_len; i++)\n+\t\t\tif (data[i].cleanup_pad \u003e off + 1)\n+\t\t\t\tdata[i].cleanup_pad += cnt - 1;\n+\n \t/*\n \t * Last slot instruction could be a newly generated\n \t * BPF_ST/BPF_LDX/BPF_STX, systematically mark it for non-stack access\n@@ -604,6 +614,7 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)\n \tstruct bpf_insn_aux_data *aux_data = env-\u003einsn_aux_data;\n \tunsigned int orig_prog_len = env-\u003eprog-\u003elen;\n \tint err;\n+\tu32 i;\n \n \tif (bpf_rewrite_must_abort())\n \t\treturn -EINTR;\n@@ -634,6 +645,17 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)\n \t\tsizeof(*aux_data) * (orig_prog_len - off - cnt));\n \tenv-\u003einsn_aux_data_len -= cnt;\n \n+\tif (env-\u003ecleanup_info_cnt) {\n+\t\tfor (i = 0; i \u003c env-\u003einsn_aux_data_len; i++) {\n+\t\t\tu32 pad = aux_data[i].cleanup_pad;\n+\n+\t\t\tif (pad \u003e off + cnt)\n+\t\t\t\taux_data[i].cleanup_pad = pad - cnt;\n+\t\t\telse if (pad \u003e off)\n+\t\t\t\taux_data[i].cleanup_pad = 0;\n+\t\t}\n+\t}\n+\n \treturn 0;\n }\n \n@@ -707,13 +729,63 @@ static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env)\n \t}\n }\n \n+/*\n+ * The walk sends a frame that a callee unwinds through to its epilogue, which\n+ * the x86 JIT emits at the first exit, so keep one. A frame that only unwinds\n+ * may have none: put one after its last insn.\n+ */\n+static int keep_subprog_exits(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn patch[2] = { {}, BPF_EXIT_INSN() };\n+\tstruct bpf_prog *new_prog;\n+\tu32 i, j;\n+\n+\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++) {\n+\t\tu32 start, end;\n+\t\tbool found = false;\n+\n+\t\tif (!env-\u003esubprog_info[i].might_unwind)\n+\t\t\tcontinue;\n+\t\tstart = env-\u003esubprog_info[i].start;\n+\t\tif (!env-\u003einsn_aux_data[start].seen)\n+\t\t\tcontinue;\n+\n+\t\tend = env-\u003esubprog_info[i + 1].start;\n+\t\tfor (j = end; j-- \u003e start; ) {\n+\t\t\tif (env-\u003eprog-\u003einsnsi[j].code == (BPF_JMP | BPF_EXIT)) {\n+\t\t\t\tfound = true;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tif (!found) {\n+\t\t\tstruct bpf_insn_aux_data aux = env-\u003einsn_aux_data[end - 1];\n+\n+\t\t\tpatch[0] = env-\u003eprog-\u003einsnsi[end - 1];\n+\t\t\tnew_prog = bpf_patch_insn_data(env, end - 1, patch, 2);\n+\t\t\tif (!new_prog)\n+\t\t\t\treturn -ENOMEM;\n+\t\t\tenv-\u003eprog = new_prog;\n+\t\t\tenv-\u003einsn_aux_data[end - 1] = aux;\n+\t\t\tmemset(\u0026env-\u003einsn_aux_data[end], 0, sizeof(aux));\n+\t\t\tj = end;\n+\t\t}\n+\t\tenv-\u003einsn_aux_data[j].seen = env-\u003epass_cnt;\n+\t}\n+\treturn 0;\n+}\n+\n int bpf_opt_remove_dead_code(struct bpf_verifier_env *env)\n {\n-\tstruct bpf_insn_aux_data *aux_data = env-\u003einsn_aux_data;\n-\tint insn_cnt = env-\u003eprog-\u003elen;\n-\tint i, err;\n+\tstruct bpf_insn_aux_data *aux_data;\n+\tint i, insn_cnt, err;\n \n \tkeep_funcs_with_addr_taken(env);\n+\terr = keep_subprog_exits(env);\n+\tif (err)\n+\t\treturn err;\n+\n+\taux_data = env-\u003einsn_aux_data;\n+\tinsn_cnt = env-\u003eprog-\u003elen;\n \n \tfor (i = 0; i \u003c insn_cnt; i++) {\n \t\tint j;\n@@ -739,7 +811,7 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env)\n \tstruct bpf_insn *insn = env-\u003eprog-\u003einsnsi;\n \tint insn_cnt = env-\u003eprog-\u003elen;\n \tbool is_may_goto_0, is_ja;\n-\tint i, err;\n+\tint i, j, err;\n \n \tfor (i = 0; i \u003c insn_cnt; i++) {\n \t\tis_may_goto_0 = !memcmp(\u0026insn[i], \u0026MAY_GOTO_0, sizeof(MAY_GOTO_0));\n@@ -750,6 +822,11 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env)\n \t\tif (aux[i].indirect_target)\n \t\t\tcontinue;\n \n+\t\tif (env-\u003ecleanup_info_cnt)\n+\t\t\tfor (j = 0; j \u003c insn_cnt; j++)\n+\t\t\t\tif (aux[j].cleanup_pad == i + 1)\n+\t\t\t\t\taux[j].cleanup_pad = i + 2;\n+\n \t\terr = verifier_remove_insns(env, i, 1);\n \t\tif (err)\n \t\t\treturn err;\n@@ -1249,6 +1326,40 @@ static int resolve_func_ptrs(struct bpf_verifier_env *env, struct bpf_prog *prog\n \treturn 0;\n }\n \n+static int exc_info_for_subprog(struct bpf_verifier_env *env, struct bpf_prog *sub,\n+\t\t\t\tu32 start, u32 end)\n+{\n+\tstruct bpf_cleanup_info *recs;\n+\tu32 i, cnt = 0;\n+\n+\tif (!env-\u003ecleanup_info_cnt)\n+\t\treturn 0;\n+\n+\tfor (i = start; i \u003c end; i++) {\n+\t\tif (env-\u003einsn_aux_data[i].cleanup_pad)\n+\t\t\tcnt++;\n+\t}\n+\tif (!cnt)\n+\t\treturn 0;\n+\n+\trecs = kvmalloc_array(cnt, sizeof(*recs), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);\n+\tif (!recs)\n+\t\treturn -ENOMEM;\n+\n+\tfor (i = start, cnt = 0; i \u003c end; i++) {\n+\t\tu32 pad = env-\u003einsn_aux_data[i].cleanup_pad;\n+\n+\t\tif (!pad)\n+\t\t\tcontinue;\n+\t\tpad--;\n+\t\trecs[cnt].begin_off = i - start;\n+\t\trecs[cnt].end_off = i - start + 1;\n+\t\trecs[cnt].landing_pad_off = pad - start;\n+\t\tcnt++;\n+\t}\n+\treturn bpf_exc_attach_info(sub-\u003eaux, recs, cnt);\n+}\n+\n static int jit_subprogs(struct bpf_verifier_env *env)\n {\n \tstruct bpf_prog *prog = env-\u003eprog, **func, *tmp;\n@@ -1256,7 +1367,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)\n \tstruct bpf_map *map_ptr;\n \tstruct bpf_insn *insn;\n \tvoid *old_bpf_func;\n-\tint err, num_exentries;\n+\tint err, exc_err, num_exentries;\n \n \tfor (i = 0, insn = prog-\u003einsnsi; i \u003c prog-\u003elen; i++, insn++) {\n \t\tif (!bpf_pseudo_func(insn) \u0026\u0026 !bpf_pseudo_call(insn))\n@@ -1383,9 +1494,15 @@ static int jit_subprogs(struct bpf_verifier_env *env)\n \t\tfunc[i]-\u003eaux-\u003eexception_cb = env-\u003esubprog_info[i].is_exception_cb;\n \t\tfunc[i]-\u003eaux-\u003echanges_pkt_data = env-\u003esubprog_info[i].changes_pkt_data;\n \t\tfunc[i]-\u003eaux-\u003emight_sleep = env-\u003esubprog_info[i].might_sleep;\n+\t\tfunc[i]-\u003eaux-\u003emight_unwind = env-\u003esubprog_info[i].might_unwind;\n \t\tfunc[i]-\u003eaux-\u003etoken = prog-\u003eaux-\u003etoken;\n \t\tif (!i)\n \t\t\tfunc[i]-\u003eaux-\u003eexception_boundary = env-\u003eseen_exception;\n+\t\texc_err = exc_info_for_subprog(env, func[i], subprog_start, subprog_end);\n+\t\tif (exc_err) {\n+\t\t\terr = exc_err;\n+\t\t\tgoto out_free;\n+\t\t}\n \t\tfunc[i] = bpf_int_jit_compile(env, func[i]);\n \t\tif (!func[i]-\u003ejited) {\n \t\t\terr = -ENOTSUPP;\n@@ -1495,6 +1612,9 @@ static int jit_subprogs(struct bpf_verifier_env *env)\n \tprog-\u003eaux-\u003ebpf_exception_cb = (void *)func[env-\u003eexception_callback_subprog]-\u003ebpf_func;\n \tprog-\u003eaux-\u003eexception_boundary = func[0]-\u003eaux-\u003eexception_boundary;\n \tprog-\u003eaux-\u003estack_arg_sp_adjust = func[0]-\u003eaux-\u003estack_arg_sp_adjust;\n+\tprog-\u003eaux-\u003eexc = func[0]-\u003eaux-\u003eexc;\n+\tfunc[0]-\u003eaux-\u003eexc = NULL;\n+\tprog-\u003eaux-\u003eepilogue_ip = func[0]-\u003eaux-\u003eepilogue_ip;\n \tbpf_prog_jit_attempt_done(prog);\n \treturn 0;\n out_free:\n@@ -1720,6 +1840,48 @@ static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off,\n \treturn cnt + tail_cnt;\n }\n \n+/*\n+ * Follow each bpf_unwind() call with 'r0 = 0; exit', or with\n+ * 'r0 = 0; goto pad' where a record covers the call.\n+ */\n+int bpf_exc_patch_unwind_calls(struct bpf_verifier_env *env)\n+{\n+\tint insn_cnt = env-\u003eprog-\u003elen;\n+\tstruct bpf_insn insn_buf[3];\n+\tstruct bpf_prog *new_prog;\n+\tint i, off, delta = 0;\n+\n+\tif (!bpf_prog_may_unwind(env))\n+\t\treturn 0;\n+\n+\tfor (i = 0; i \u003c insn_cnt; i++) {\n+\t\tint call = i + delta, pad;\n+\t\tstruct bpf_insn *insn = env-\u003eprog-\u003einsnsi + call;\n+\n+\t\tif (!bpf_is_unwind_kfunc(insn))\n+\t\t\tcontinue;\n+\n+\t\tinsn_buf[0] = *insn;\n+\t\tinsn_buf[1] = BPF_MOV64_IMM(BPF_REG_0, 0);\n+\t\tinsn_buf[2] = BPF_EXIT_INSN();\n+\t\tpad = bpf_exc_pad_of_call(env, call);\n+\t\tif (pad \u003e= 0) {\n+\t\t\t/* The goto is at call + 2; a pad after the call moves down by 2. */\n+\t\t\tif (pad \u003e call)\n+\t\t\t\tpad += 2;\n+\t\t\toff = pad - (call + 3);\n+\t\t\tinsn_buf[2] = off == (s16)off ? BPF_JMP_A(off) : BPF_JMP32_A(off);\n+\t\t}\n+\n+\t\tnew_prog = bpf_patch_insn_data(env, call, insn_buf, 3);\n+\t\tif (!new_prog)\n+\t\t\treturn -ENOMEM;\n+\t\tdelta += 2;\n+\t\tenv-\u003eprog = new_prog;\n+\t}\n+\treturn 0;\n+}\n+\n /* Do various post-verification rewrites in a single program pass.\n * These rewrites simplify JIT and interpreter implementations.\n */\n@@ -2112,6 +2274,25 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)\n \t\t\tgoto next_insn;\n \t\tif (insn-\u003esrc_reg == BPF_PSEUDO_CALL)\n \t\t\tgoto next_insn;\n+\t\tif (bpf_is_unwind_resume_kfunc(insn)) {\n+\t\t\t/*\n+\t\t\t * A pad's resume is just the frame returning, to\n+\t\t\t * where bpf_unwind() pointed its return address: its\n+\t\t\t * caller's pad or epilogue, or the kernel from the main\n+\t\t\t * program. The verifier checked this exit with r0 a\n+\t\t\t * known zero, so return zero.\n+\t\t\t */\n+\t\t\tinsn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, 0);\n+\t\t\tinsn_buf[1] = BPF_EXIT_INSN();\n+\t\t\tcnt = 2;\n+\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\n+\t\t\tif (!new_prog)\n+\t\t\t\treturn -ENOMEM;\n+\t\t\tdelta += cnt - 1;\n+\t\t\tenv-\u003eprog = prog = new_prog;\n+\t\t\tinsn = new_prog-\u003einsnsi + i + delta;\n+\t\t\tgoto next_insn;\n+\t\t}\n \t\tif (insn-\u003esrc_reg == BPF_PSEUDO_KFUNC_CALL) {\n \t\t\tret = bpf_fixup_kfunc_call(env, insn, insn_buf, i + delta, \u0026cnt);\n \t\t\tif (ret)\ndiff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c\nindex 439370d73cc5f..1cf7b712854b8 100644\n--- a/kernel/bpf/helpers.c\n+++ b/kernel/bpf/helpers.c\n@@ -29,8 +29,10 @@\n #include \u003clinux/task_work.h\u003e\n #include \u003clinux/irq_work.h\u003e\n #include \u003clinux/buildid.h\u003e\n+#include \u003clinux/kprobes.h\u003e\n \n #include \"../../lib/kstrtox.h\"\n+#include \"exception.h\"\n \n /* If kernel subsystem is allowing eBPF programs to call this function,\n * inside its own verifier_ops-\u003eget_func_proto() callback it should return\n@@ -3424,6 +3426,71 @@ static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)\n \treturn false;\n }\n \n+struct bpf_unwind_ctx {\n+\tconst struct bpf_prog_aux *aux;\n+\tu32 cnt;\n+};\n+\n+static bool bpf_unwind_ip_in(const struct bpf_prog *prog, u64 ip)\n+{\n+\tu64 start = (u64)(long)prog-\u003ebpf_func;\n+\n+\treturn ip \u003e start \u0026\u0026 ip \u003c= start + prog-\u003ejited_len;\n+}\n+\n+/*\n+ * The function of the calling program that @ip returns into, looked up in the\n+ * program itself: its kallsyms entries can go while an instance still runs.\n+ * The main function is the outer program, which holds its table and epilogue.\n+ */\n+static struct bpf_prog *bpf_unwind_find_prog(const struct bpf_prog_aux *aux, u64 ip)\n+{\n+\tu32 i;\n+\n+\tfor (i = 1; i \u003c aux-\u003efunc_cnt; i++)\n+\t\tif (bpf_unwind_ip_in(aux-\u003efunc[i], ip))\n+\t\t\treturn aux-\u003efunc[i];\n+\treturn bpf_unwind_ip_in(aux-\u003eprog, ip) ? aux-\u003eprog : NULL;\n+}\n+\n+static bool bpf_unwind_rewrite(void *cookie, u64 ip, u64 sp, u64 bp, u64 *ra)\n+{\n+\tconst struct bpf_cleanup_range *rec;\n+\tstruct bpf_unwind_ctx *ctx = cookie;\n+\tstruct bpf_prog *prog;\n+\n+\tprog = bpf_unwind_find_prog(ctx-\u003eaux, ip);\n+\tif (!prog)\n+\t\treturn !ctx-\u003ecnt;\n+\tctx-\u003ecnt++;\n+\n+\t/*\n+\t * The frame that called bpf_unwind(): bpf_exc_patch_unwind_calls()\n+\t * put 'r0 = 0' and a jump to its pad, or an exit, after the call,\n+\t * so leave its return address alone and let it go on there. The pad\n+\t * then starts with r0 at a known zero.\n+\t */\n+\tif (ctx-\u003ecnt == 1)\n+\t\treturn bpf_is_subprog(prog);\n+\n+\trec = bpf_exc_pad_for_ip(prog, ip);\n+\t*ra = rec ? rec-\u003epad : prog-\u003eaux-\u003eepilogue_ip;\n+\n+\treturn bpf_is_subprog(prog);\n+}\n+\n+/*\n+ * @aux is the calling program's, supplied by the verifier (KF_IMPLICIT_ARGS):\n+ * programs call bpf_unwind() with no arguments.\n+ */\n+__bpf_kfunc notrace void bpf_unwind(struct bpf_prog_aux *aux)\n+{\n+\tstruct bpf_unwind_ctx ctx = { .aux = aux };\n+\n+\tarch_bpf_stack_walk_ra(bpf_unwind_rewrite, \u0026ctx);\n+}\n+NOKPROBE_SYMBOL(bpf_unwind);\n+\n __bpf_kfunc void bpf_throw(u64 cookie)\n {\n \tstruct bpf_throw_ctx ctx = {};\n@@ -3445,6 +3512,15 @@ __bpf_kfunc void bpf_throw(u64 cookie)\n \tWARN(1, \"A call to BPF exception callback should never return\\n\");\n }\n \n+__bpf_kfunc void bpf_unwind_resume(void *ptr__ign)\n+{\n+\t/*\n+\t * Not meant to run: every call of this kfunc is to be lowered to\n+\t * 'r0 = 0; exit' by the verifier.\n+\t */\n+\tWARN_ONCE(1, \"exception cleanup resume was not lowered to a return\\n\");\n+}\n+\n __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags)\n {\n \tstruct bpf_async_kern *async = (struct bpf_async_kern *)wq;\n@@ -5115,6 +5191,8 @@ BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)\n BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)\n BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL)\n BTF_ID_FLAGS(func, bpf_throw)\n+BTF_ID_FLAGS(func, bpf_unwind, KF_IMPLICIT_ARGS)\n+BTF_ID_FLAGS(func, bpf_unwind_resume)\n #ifdef CONFIG_BPF_EVENTS\n BTF_ID_FLAGS(func, bpf_send_signal_task)\n #endif\ndiff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c\nindex e657e6d95408f..8b7ee551ff6f5 100644\n--- a/kernel/bpf/liveness.c\n+++ b/kernel/bpf/liveness.c\n@@ -8,6 +8,8 @@\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/sort.h\u003e\n \n+#include \"exception.h\"\n+\n #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)\n \n /*\n@@ -404,6 +406,18 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)\n \t\t\tsucc-\u003eitems[succ-\u003ecnt++] = exit_idx;\n \t}\n \n+\t/*\n+\t * A covered call can also leave through its landing pad. Only a call to\n+\t * a subprog or to bpf_unwind() is covered, so the two entries of\n+\t * env-\u003esucc are enough.\n+\t */\n+\tif (unlikely(env-\u003ecleanup_info_cnt)) {\n+\t\tint pad = bpf_exc_pad_of_call(env, idx);\n+\n+\t\tif (pad \u003e= 0)\n+\t\t\tsucc-\u003eitems[succ-\u003ecnt++] = pad;\n+\t}\n+\n \treturn succ;\n }\n \n@@ -530,7 +544,8 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp\n \t * Slot is alive if it is read before q-\u003einsn_idx in current func instance,\n \t * or if for some outer func instance:\n \t * - alive before callsite if callsite calls callback or is callx, otherwise\n-\t * - alive after callsite\n+\t * - alive after callsite,\n+\t * - or alive at the landing pad a cleanup record gives the callsite\n \t */\n \tstruct live_stack_query *q = \u0026env-\u003eliveness-\u003elive_stack_query;\n \tstruct func_instance *instance, *curframe_instance;\n@@ -565,6 +580,13 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp\n \t\talive = callee_stack_access_at_callsite(env, callsite)\n \t\t\t? is_live_before(instance, callsite, rel, half_spi)\n \t\t\t: is_live_before(instance, callsite + 1, rel, half_spi);\n+\n+\t\tif (!alive \u0026\u0026 unlikely(env-\u003ecleanup_info_cnt)) {\n+\t\t\tint pad = bpf_exc_pad_of_call(env, callsite);\n+\n+\t\t\tif (pad \u003e= 0)\n+\t\t\t\talive = is_live_before(instance, pad, rel, half_spi);\n+\t\t}\n \t\tif (alive)\n \t\t\treturn true;\n \t}\ndiff --git a/kernel/bpf/states.c b/kernel/bpf/states.c\nindex 953700822fa73..93b5cc3a2f02d 100644\n--- a/kernel/bpf/states.c\n+++ b/kernel/bpf/states.c\n@@ -201,9 +201,13 @@ static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_stat\n \t\t * c. A checkpoint is reached and matched. Checkpoints are created by\n \t\t * is_state_visited(), which calls maybe_enter_scc(), which allocates\n \t\t * bpf_scc_visit instances for checkpoints within SCCs.\n-\t\t * (c) is the only case that can reach this point.\n+\t\t * d. An unwind returns from frame 0, ending the path at a call or at\n+\t\t * the unwinding insn, which may be in an SCC as a top-level\n+\t\t * BPF_EXIT is not. Like (b), it leaves nothing to exit.\n+\t\t * (c) and (d), and a speculative path, are the only ways to reach\n+\t\t * this point.\n \t\t */\n-\t\tif (!st-\u003especulative) {\n+\t\tif (!st-\u003especulative \u0026\u0026 !st-\u003eunwind_exit) {\n \t\t\tverifier_bug(env, \"scc exit: no visit info for call chain %s\",\n \t\t\t\t format_callchain(env, callchain));\n \t\t\treturn -EFAULT;\n@@ -995,6 +999,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat\n \tif (!old-\u003eno_stack_arg_load \u0026\u0026 cur-\u003eno_stack_arg_load)\n \t\treturn false;\n \n+\tif (old-\u003ein_pad != cur-\u003ein_pad)\n+\t\treturn false;\n+\n \tfor (i = 0; i \u003c MAX_BPF_REG; i++)\n \t\tif (((1 \u003c\u003c i) \u0026 live_regs) \u0026\u0026\n \t\t !regsafe(env, \u0026old-\u003eregs[i], \u0026cur-\u003eregs[i],\ndiff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c\nindex 654f896af265b..10e0a693a06d5 100644\n--- a/kernel/bpf/syscall.c\n+++ b/kernel/bpf/syscall.c\n@@ -2948,7 +2948,7 @@ int __init __used bpf_multi_func(void) { return 0; }\n BTF_ID_LIST_GLOBAL_SINGLE(bpf_multi_func_btf_id, func, bpf_multi_func)\n \n /* last field in 'union bpf_attr' used by this command */\n-#define BPF_PROG_LOAD_LAST_FIELD keyring_id\n+#define BPF_PROG_LOAD_LAST_FIELD cleanup_info_cnt\n \n static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)\n {\ndiff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c\nindex ddfa0c6d2755f..505ecb8de2211 100644\n--- a/kernel/bpf/verifier.c\n+++ b/kernel/bpf/verifier.c\n@@ -39,6 +39,7 @@\n \n #include \"diagnostics.h\"\n #include \"disasm.h\"\n+#include \"exception.h\"\n \n static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {\n #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \\\n@@ -1750,6 +1751,7 @@ int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,\n \t\treturn err;\n \tdst_state-\u003especulative = src-\u003especulative;\n \tdst_state-\u003ein_sleepable = src-\u003ein_sleepable;\n+\tdst_state-\u003eunwind_exit = src-\u003eunwind_exit;\n \tdst_state-\u003ecurframe = src-\u003ecurframe;\n \tdst_state-\u003ebranches = src-\u003ebranches;\n \tdst_state-\u003eparent = src-\u003eparent;\n@@ -3315,6 +3317,54 @@ static void find_subprog_properties(struct bpf_verifier_env *env)\n \t}\n }\n \n+static int subprog_falls_through(struct bpf_verifier_env *env, int subprog, int idx)\n+{\n+\tverbose(env, \"last insn is not an exit or jmp\\n\");\n+\tbpf_diag_program_structure(\n+\t\tenv, idx, \"subprogram can fall through\",\n+\t\t\"End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.\",\n+\t\t\"Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.\",\n+\t\tsubprog, idx);\n+\treturn -EINVAL;\n+}\n+\n+/*\n+ * Put an exit after a call that ends a subprog, so that nothing from the CFG\n+ * walk on has to know a subprog can end that way. check_subprogs() only lets\n+ * such a call be to a callee that never returns, so do_check() never reaches\n+ * the exit.\n+ */\n+static int add_exits_after_final_calls(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn patch[2] = { {}, BPF_EXIT_INSN() };\n+\tstruct bpf_prog *new_prog;\n+\tint i, j;\n+\n+\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++) {\n+\t\tint last = env-\u003esubprog_info[i + 1].start - 1;\n+\t\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[last];\n+\n+\t\tif (!bpf_pseudo_call(insn) \u0026\u0026 !bpf_pseudo_kfunc_call(insn))\n+\t\t\tcontinue;\n+\t\tpatch[0] = *insn;\n+\t\tnew_prog = bpf_patch_insn_data(env, last, patch, 2);\n+\t\tif (!new_prog)\n+\t\t\treturn -ENOMEM;\n+\t\tenv-\u003eprog = new_prog;\n+\t\t/* The patch moved the call's aux data, orig_idx included, to the exit. */\n+\t\tenv-\u003einsn_aux_data[last].orig_idx = env-\u003einsn_aux_data[last + 1].orig_idx;\n+\t\t/* The patch does not adjust the call itself for a callee after it. */\n+\t\tinsn = \u0026new_prog-\u003einsnsi[last];\n+\t\tif (bpf_pseudo_call(insn) \u0026\u0026 insn-\u003eimm \u003e= 0)\n+\t\t\tinsn-\u003eimm++;\n+\t\t/* Nor does it move the exits check_subprogs() found after it. */\n+\t\tfor (j = i + 1; j \u003c env-\u003esubprog_cnt; j++)\n+\t\t\tif (env-\u003esubprog_info[j].exit_idx != U32_MAX)\n+\t\t\t\tenv-\u003esubprog_info[j].exit_idx++;\n+\t}\n+\treturn 0;\n+}\n+\n static int check_subprogs(struct bpf_verifier_env *env)\n {\n \tint i, subprog_start, subprog_end, off, cur_subprog = 0;\n@@ -3354,26 +3404,44 @@ static int check_subprogs(struct bpf_verifier_env *env)\n \t\t\t/*\n \t\t\t * To avoid fall-through from one subprog into another,\n \t\t\t * the last insn of the subprog should be either exit\n-\t\t\t * or unconditional jump back or bpf_throw call.\n+\t\t\t * or unconditional jump back or a call that does not\n+\t\t\t * return, checked below.\n \t\t\t */\n \t\t\tif (code != (BPF_JMP | BPF_EXIT) \u0026\u0026\n \t\t\t code != (BPF_JMP32 | BPF_JA) \u0026\u0026\n \t\t\t code != (BPF_JMP | BPF_JA) \u0026\u0026\n-\t\t\t !insn_is_gotox(\u0026insn[i])) {\n-\t\t\t\tverbose(env, \"last insn is not an exit or jmp\\n\");\n-\t\t\t\tbpf_diag_program_structure(\n-\t\t\t\t\tenv, i, \"subprogram can fall through\",\n-\t\t\t\t\t\"End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.\",\n-\t\t\t\t\t\"Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.\",\n-\t\t\t\t\tcur_subprog, i);\n-\t\t\t\treturn -EINVAL;\n-\t\t\t}\n+\t\t\t !insn_is_gotox(\u0026insn[i]) \u0026\u0026\n+\t\t\t !bpf_pseudo_call(\u0026insn[i]) \u0026\u0026\n+\t\t\t !bpf_pseudo_kfunc_call(\u0026insn[i]))\n+\t\t\t\treturn subprog_falls_through(env, cur_subprog, i);\n \t\t\tsubprog_start = subprog_end;\n \t\t\tcur_subprog++;\n \t\t\tif (cur_subprog \u003c env-\u003esubprog_cnt)\n \t\t\t\tsubprog_end = subprog[cur_subprog + 1].start;\n \t\t}\n \t}\n+\n+\t/*\n+\t * A compiler ends a subprog with a call only if the callee never\n+\t * returns. Refuse any other final call.\n+\t */\n+\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++) {\n+\t\tint last = subprog[i + 1].start - 1, callee;\n+\n+\t\tif (bpf_pseudo_kfunc_call(\u0026insn[last])) {\n+\t\t\tif (!bpf_is_unwind_kfunc(\u0026insn[last]) \u0026\u0026\n+\t\t\t !bpf_is_unwind_resume_kfunc(\u0026insn[last]))\n+\t\t\t\treturn subprog_falls_through(env, i, last);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (!bpf_pseudo_call(\u0026insn[last]))\n+\t\t\tcontinue;\n+\t\tcallee = bpf_find_subprog(env, last + insn[last].imm + 1);\n+\t\tif (bpf_subprog_is_global(env, callee) ||\n+\t\t subprog[callee].exit_idx != U32_MAX ||\n+\t\t subprog[callee].has_tail_call || subprog[callee].has_ld_abs)\n+\t\t\treturn subprog_falls_through(env, i, last);\n+\t}\n \treturn 0;\n }\n \n@@ -5954,6 +6022,17 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)\n \t\t}\n \t}\n \n+\t/*\n+\t * A private stack keeps its frame pointer in %r9 on x86-64, restored\n+\t * by a pop after the call that an unwind skips. A frame resumed at a\n+\t * pad then addresses its stack through a stale pointer, and a frame\n+\t * sent to its epilogue instead pops its callee-saved registers one\n+\t * slot off. Do not use a private stack for any program that can\n+\t * unwind, on every arch for now.\n+\t */\n+\tif (env-\u003ecleanup_info_cnt || bpf_prog_may_unwind(env))\n+\t\tpriv_stack_mode = NO_PRIV_STACK;\n+\n \tif (priv_stack_mode == PRIV_STACK_UNKNOWN)\n \t\tpriv_stack_mode = bpf_enable_priv_stack(env-\u003eprog);\n \n@@ -11189,6 +11268,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins\n \t * callbacks\n \t */\n \tenv-\u003esubprog_info[subprog].is_cb = true;\n+\terr = bpf_exc_check_callback(env, subprog);\n+\tif (err)\n+\t\treturn err;\n+\n \tif (bpf_pseudo_kfunc_call(insn) \u0026\u0026\n \t !is_callback_calling_kfunc(insn-\u003eimm)) {\n \t\tverifier_bug(env, \"kfunc %s#%d not marked as callback-calling\",\n@@ -11251,6 +11334,8 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins\n \n static int process_bpf_exit_full(struct bpf_verifier_env *env,\n \t\t\t\t bool *do_print_state, bool exception_exit);\n+static int process_bpf_unwind(struct bpf_verifier_env *env, int *insn_idx);\n+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state);\n \n /*\n * Call of a static subprog. The callee is verified in the context of\n@@ -15563,6 +15648,16 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n \tif (bpf_is_throw_kfunc(insn))\n \t\treturn process_bpf_exit_full(env, NULL, true);\n \n+\tif (bpf_is_unwind_kfunc(insn))\n+\t\treturn process_bpf_unwind(env, insn_idx_p);\n+\tif (bpf_is_unwind_resume_kfunc(insn)) {\n+\t\tif (!cur_func(env)-\u003ein_pad) {\n+\t\t\tverbose(env, \"resume at insn %d is not in a landing pad\\n\", insn_idx);\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\treturn unwind_frames(env, NULL);\n+\t}\n+\n \treturn 0;\n }\n \n@@ -19673,6 +19768,136 @@ enum {\n \tINSN_IDX_UPDATED = 2,\n };\n \n+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state)\n+{\n+\tstruct bpf_verifier_state *state = env-\u003ecur_state;\n+\tu32 frameno = state-\u003ecurframe;\n+\tstruct bpf_func_state *callee, *caller;\n+\tint err, pad;\n+\n+\twhile (state-\u003ecurframe) {\n+\t\tcallee = cur_func(env);\n+\t\tcaller = state-\u003eframe[state-\u003ecurframe - 1];\n+\t\tpad = bpf_exc_pad_of_call(env, callee-\u003ecallsite);\n+\t\t/* The caller is at its call now, not at this frame's insn. */\n+\t\tstate-\u003einsn_idx = callee-\u003ecallsite;\n+\t\t/* As on a return: the frame's dynptrs, and their slices, go with it. */\n+\t\terr = destroy_dynptrs_in_stack_slots(env, callee, 0,\n+\t\t\t\t\t\t callee-\u003eallocated_stack / BPF_REG_SIZE - 1);\n+\t\tif (err)\n+\t\t\treturn err;\n+\n+\t\taccount_processed_insns(env, callee, caller);\n+\t\tfree_func_state(callee);\n+\t\tstate-\u003eframe[state-\u003ecurframe--] = NULL;\n+\t\tinvalidate_outgoing_stack_args(env, caller);\n+\t\tif (pad \u003c 0)\n+\t\t\tcontinue;\n+\n+\t\t/*\n+\t\t * Mark the unwinding insn with the frame it ran in: backtracking\n+\t\t * from the pad comes back to that insn and goes on in that frame.\n+\t\t */\n+\t\terr = bpf_push_jmp_history(env, state, INSN_F_UNWIND, 0, frameno, NULL, 0);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t\tclear_caller_saved_regs(env, caller-\u003eregs);\n+\t\tmark_reg_unknown(env, caller-\u003eregs, BPF_REG_0);\n+\t\tcaller-\u003ein_pad = true;\n+\t\tenv-\u003einsn_idx = pad;\n+\t\tif (do_print_state)\n+\t\t\t*do_print_state = true;\n+\t\treturn INSN_IDX_UPDATED;\n+\t}\n+\n+\t/* A resource still held leaks; report it at the unwinding insn. */\n+\terr = check_resource_leak(env, false, true, \"bpf_unwind\");\n+\tif (err)\n+\t\treturn err;\n+\t/*\n+\t * No pad: the program ends at frame 0's call into the popped frames, or\n+\t * at the unwinding insn itself if none was popped. Mark the unwinding\n+\t * insn as above; an unwinding global call needs that when backtracking\n+\t * from the end reaches it.\n+\t */\n+\terr = bpf_push_jmp_history(env, state, INSN_F_UNWIND, 0, frameno, NULL, 0);\n+\tif (err)\n+\t\treturn err;\n+\t/*\n+\t * Then, in an entry of its own, a jump from the unwinding insn to the\n+\t * end, so backtracking from the end goes back to the unwinding insn.\n+\t */\n+\tenv-\u003ecur_hist_ent = NULL;\n+\tenv-\u003eprev_insn_idx = env-\u003einsn_idx;\n+\tenv-\u003einsn_idx = state-\u003einsn_idx;\n+\terr = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0);\n+\tif (err)\n+\t\treturn err;\n+\t/*\n+\t * The end may be in a loop: unlike a plain exit, the path can stop\n+\t * inside an SCC with no checkpoint there.\n+\t */\n+\tstate-\u003eunwind_exit = true;\n+\n+\t/* The call clobbered r1-r5, and r0 holds the zero the fixups put there. */\n+\tclear_caller_saved_regs(env, cur_regs(env));\n+\t__mark_reg_const_zero(env, \u0026cur_regs(env)[BPF_REG_0]);\n+\t/*\n+\t * A global subprog verified on its own returns here too. One that\n+\t * returns in R0:R2 has R2 checked as well, though its caller never\n+\t * reads either: it resumes at a pad or an epilogue.\n+\t */\n+\tif (cur_func(env)-\u003esubprogno \u0026\u0026\n+\t bpf_ret_reg_pair(env, cur_func(env)-\u003esubprogno))\n+\t\tmark_reg_unknown(env, cur_regs(env), BPF_REG_2);\n+\n+\treturn process_bpf_exit_full(env, do_print_state, false);\n+}\n+\n+static int process_global_call_unwind(struct bpf_verifier_env *env,\n+\t\t\t\t int call_idx, bool *do_print_state)\n+{\n+\tconst struct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[call_idx];\n+\tint subprog = bpf_find_subprog(env, call_idx + insn-\u003eimm + 1);\n+\tstruct bpf_verifier_state *branch;\n+\tstruct bpf_func_state *frame;\n+\tint pad;\n+\n+\tif (!bpf_subprog_is_global(env, subprog) ||\n+\t !env-\u003esubprog_info[subprog].might_unwind)\n+\t\treturn 0;\n+\n+\t/* The call returning normally is walked later. */\n+\tbranch = push_stack(env, call_idx + 1, call_idx, false);\n+\tif (IS_ERR(branch))\n+\t\treturn PTR_ERR(branch);\n+\n+\tpad = bpf_exc_pad_of_call(env, call_idx);\n+\tif (pad \u003c 0)\n+\t\treturn unwind_frames(env, do_print_state);\n+\tframe = cur_func(env);\n+\tclear_caller_saved_regs(env, frame-\u003eregs);\n+\tmark_reg_unknown(env, frame-\u003eregs, BPF_REG_0);\n+\tframe-\u003ein_pad = true;\n+\tenv-\u003einsn_idx = pad;\n+\t*do_print_state = true;\n+\treturn INSN_IDX_UPDATED;\n+}\n+\n+static int process_bpf_unwind(struct bpf_verifier_env *env, int *insn_idx)\n+{\n+\tstruct bpf_func_state *frame = cur_func(env);\n+\tint pad = bpf_exc_pad_of_call(env, *insn_idx);\n+\n+\tif (pad \u003c 0)\n+\t\treturn unwind_frames(env, NULL);\n+\tclear_caller_saved_regs(env, frame-\u003eregs);\n+\tmark_reg_unknown(env, frame-\u003eregs, BPF_REG_0);\n+\tframe-\u003ein_pad = true;\n+\t*insn_idx = pad;\n+\treturn INSN_IDX_UPDATED;\n+}\n+\n static int process_bpf_exit_full(struct bpf_verifier_env *env,\n \t\t\t\t bool *do_print_state,\n \t\t\t\t bool exception_exit)\n@@ -19864,6 +20089,12 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)\n \tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[env-\u003einsn_idx];\n \tu8 class = BPF_CLASS(insn-\u003ecode);\n \n+\tif (unlikely(env-\u003ecleanup_info_cnt)) {\n+\t\terr = bpf_exc_check_insn(env, insn);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\n \tswitch (class) {\n \tcase BPF_ALU:\n \tcase BPF_ALU64:\n@@ -19934,8 +20165,14 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)\n \t\t\t\tcur_func(env)-\u003eno_stack_arg_load = true;\n \t\t\tif (bpf_is_callx(insn))\n \t\t\t\treturn check_func_callx(env, insn, \u0026env-\u003einsn_idx);\n-\t\t\tif (insn-\u003esrc_reg == BPF_PSEUDO_CALL)\n-\t\t\t\treturn check_func_call(env, insn, \u0026env-\u003einsn_idx);\n+\t\t\tif (insn-\u003esrc_reg == BPF_PSEUDO_CALL) {\n+\t\t\t\tint call_idx = env-\u003einsn_idx;\n+\n+\t\t\t\terr = check_func_call(env, insn, \u0026env-\u003einsn_idx);\n+\t\t\t\tif (err)\n+\t\t\t\t\treturn err;\n+\t\t\t\treturn process_global_call_unwind(env, call_idx, do_print_state);\n+\t\t\t}\n \t\t\tif (insn-\u003esrc_reg == BPF_PSEUDO_KFUNC_CALL)\n \t\t\t\treturn check_kfunc_call(env, insn, \u0026env-\u003einsn_idx);\n \t\t\treturn check_helper_call(env, insn, \u0026env-\u003einsn_idx);\n@@ -22134,6 +22371,23 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,\n \t\t\t\tprog_extension ? \"Extension\" : \"Tracing\");\n \t\t\treturn -EINVAL;\n \t\t}\n+\t\t/*\n+\t\t * A trampoline that calls its target stays as a frame between a\n+\t\t * subprog and its caller, and bpf_unwind() cannot walk past it:\n+\t\t * the frames above it would carry on after their calls rather\n+\t\t * than at their landing pads or epilogues. fentry leaves no\n+\t\t * frame, and the main program's caller is above where the walk\n+\t\t * stops.\n+\t\t */\n+\t\tif (aux-\u003efunc \u0026\u0026 subprog \u0026\u0026 aux-\u003efunc[subprog]-\u003eaux-\u003emight_unwind \u0026\u0026\n+\t\t (prog-\u003eexpected_attach_type == BPF_TRACE_FEXIT ||\n+\t\t prog-\u003eexpected_attach_type == BPF_MODIFY_RETURN ||\n+\t\t prog-\u003eexpected_attach_type == BPF_TRACE_FSESSION)) {\n+\t\t\tbpf_log(log,\n+\t\t\t\t\"Cannot attach fexit, fmod_ret or fsession to %s, which can unwind\\n\",\n+\t\t\t\ttname);\n+\t\t\treturn -EINVAL;\n+\t\t}\n \t\tconservative = aux-\u003efunc_info_aux[subprog].unreliable;\n \t\tif (prog_extension) {\n \t\t\tif (conservative) {\n@@ -23431,15 +23685,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tenv-\u003etest_reg_invariants = attr-\u003eprog_flags \u0026 BPF_F_TEST_REG_INVARIANTS;\n \tenv-\u003earena_scalar = attr-\u003eprog_flags \u0026 BPF_F_ARENA_SCALAR;\n \n-\tenv-\u003eexplored_states = kvzalloc_objs(struct list_head,\n-\t\t\t\t\t state_htab_size(env),\n-\t\t\t\t\t GFP_KERNEL_ACCOUNT);\n-\tret = -ENOMEM;\n-\tif (!env-\u003eexplored_states)\n-\t\tgoto skip_full_check;\n-\n-\tfor (i = 0; i \u003c state_htab_size(env); i++)\n-\t\tINIT_LIST_HEAD(\u0026env-\u003eexplored_states[i]);\n \tINIT_LIST_HEAD(\u0026env-\u003efree_list);\n \n \t/* Prepare BTF and func_info needed to discover all subprograms. */\n@@ -23468,6 +23713,13 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tif (ret \u003c 0)\n \t\tgoto skip_full_check;\n \n+\tret = bpf_exc_check_info(env, attr, uattr);\n+\tif (ret \u003c 0)\n+\t\tgoto skip_full_check;\n+\n+\t/* The CFG needs an edge from a call in a cleanup range to its pad. */\n+\tbpf_exc_mark_call_sites(env);\n+\n \t/* Validate instructions and resolve the program's referenced resources. */\n \tret = check_and_resolve_insns(env);\n \tif (ret \u003c 0)\n@@ -23483,6 +23735,24 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tif (ret \u003c 0)\n \t\tgoto skip_full_check;\n \n+\t/*\n+\t * After everything above has recorded insn offsets, so the patch\n+\t * adjusts them, and before an offloaded program's per-insn state.\n+\t */\n+\tret = add_exits_after_final_calls(env);\n+\tif (ret \u003c 0)\n+\t\tgoto skip_full_check;\n+\n+\tenv-\u003eexplored_states = kvzalloc_objs(struct list_head,\n+\t\t\t\t\t state_htab_size(env),\n+\t\t\t\t\t GFP_KERNEL_ACCOUNT);\n+\tret = -ENOMEM;\n+\tif (!env-\u003eexplored_states)\n+\t\tgoto skip_full_check;\n+\n+\tfor (i = 0; i \u003c state_htab_size(env); i++)\n+\t\tINIT_LIST_HEAD(\u0026env-\u003eexplored_states[i]);\n+\n \tif (bpf_prog_is_offloaded(env-\u003eprog-\u003eaux)) {\n \t\tret = bpf_prog_offload_verifier_prep(env-\u003eprog);\n \t\tif (ret)\n@@ -23505,6 +23775,12 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tif (ret)\n \t\tgoto skip_full_check;\n \n+\tif (env-\u003ecleanup_info_cnt || bpf_prog_may_unwind(env)) {\n+\t\tret = bpf_exc_check_prog(env);\n+\t\tif (ret)\n+\t\t\tgoto skip_full_check;\n+\t}\n+\n \tret = bpf_compute_const_regs(env);\n \tif (ret \u003c 0)\n \t\tgoto skip_full_check;\n@@ -23599,6 +23875,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \t\t/* program is valid, convert *(u32*)(ctx + off) accesses */\n \t\tret = bpf_convert_ctx_accesses(env);\n \n+\tif (ret == 0)\n+\t\tret = bpf_exc_patch_unwind_calls(env);\n+\n \tif (ret == 0)\n \t\tret = bpf_do_misc_fixups(env);\n \n@@ -23713,6 +23992,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tkvfree(env-\u003efunc_ptrs);\n \tbpf_diag_free(env);\n \tkvfree(env-\u003eidoms);\n+\tkvfree(env-\u003ecleanup_info);\n \tkvfree(env);\n \treturn ret;\n }\ndiff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h\nindex 6f70db7515dd4..9d7439c96e52e 100644\n--- a/tools/include/uapi/linux/bpf.h\n+++ b/tools/include/uapi/linux/bpf.h\n@@ -1708,6 +1708,9 @@ union bpf_attr {\n \t\t * verification.\n \t\t */\n \t\t__s32\t\tkeyring_id;\n+\t\t__aligned_u64\tcleanup_info;\t/* exception cleanup table */\n+\t\t__u32\t\tcleanup_info_rec_size; /* userspace bpf_cleanup_info size */\n+\t\t__u32\t\tcleanup_info_cnt; /* number of bpf_cleanup_info records */\n \t};\n \n \tstruct { /* anonymous struct used by BPF_OBJ_* commands */\n@@ -7669,6 +7672,17 @@ struct bpf_line_info {\n \t__u32\tline_col;\n };\n \n+/*\n+ * One record of an exception cleanup table: calls in [begin_off, end_off)\n+ * that unwind resume at landing_pad_off. All three are instruction offsets\n+ * in the program as loaded.\n+ */\n+struct bpf_cleanup_info {\n+\t__u32\tbegin_off;\n+\t__u32\tend_off;\n+\t__u32\tlanding_pad_off;\n+};\n+\n struct bpf_spin_lock {\n \t__u32\tval;\n };\ndiff --git a/tools/lib/bpf/bpf.c b/tools/lib/bpf/bpf.c\nindex b49822d212aed..b4031f62bdee5 100644\n--- a/tools/lib/bpf/bpf.c\n+++ b/tools/lib/bpf/bpf.c\n@@ -295,7 +295,7 @@ int bpf_prog_load(enum bpf_prog_type prog_type,\n \t\t const struct bpf_insn *insns, size_t insn_cnt,\n \t\t struct bpf_prog_load_opts *opts)\n {\n-\tconst size_t attr_sz = offsetofend(union bpf_attr, keyring_id);\n+\tconst size_t attr_sz = offsetofend(union bpf_attr, cleanup_info_cnt);\n \tvoid *finfo = NULL, *linfo = NULL;\n \tconst char *func_info, *line_info;\n \t__u32 log_size, log_level, attach_prog_fd, attach_btf_obj_fd;\n@@ -370,6 +370,10 @@ int bpf_prog_load(enum bpf_prog_type prog_type,\n \tattr.fd_array = ptr_to_u64(OPTS_GET(opts, fd_array, NULL));\n \tattr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0);\n \n+\tattr.cleanup_info = ptr_to_u64(OPTS_GET(opts, cleanup_info, NULL));\n+\tattr.cleanup_info_rec_size = OPTS_GET(opts, cleanup_info_rec_size, 0);\n+\tattr.cleanup_info_cnt = OPTS_GET(opts, cleanup_info_cnt, 0);\n+\n \tif (log_level) {\n \t\tattr.log_buf = ptr_to_u64(log_buf);\n \t\tattr.log_size = log_size;\ndiff --git a/tools/lib/bpf/bpf.h b/tools/lib/bpf/bpf.h\nindex 826d9cc9ab65d..64699e0e4e1a8 100644\n--- a/tools/lib/bpf/bpf.h\n+++ b/tools/lib/bpf/bpf.h\n@@ -128,9 +128,17 @@ struct bpf_prog_load_opts {\n \n \t/* if set, provides the length of fd_array */\n \t__u32 fd_array_cnt;\n+\n+\t/* exception cleanup table: cleanup_info_cnt records of\n+\t * cleanup_info_rec_size bytes each (struct bpf_cleanup_info),\n+\t * holding instruction indices into insns\n+\t */\n+\t__u32 cleanup_info_cnt;\n+\tconst void *cleanup_info;\n+\t__u32 cleanup_info_rec_size;\n \tsize_t :0;\n };\n-#define bpf_prog_load_opts__last_field fd_array_cnt\n+#define bpf_prog_load_opts__last_field cleanup_info_rec_size\n \n LIBBPF_API int bpf_prog_load(enum bpf_prog_type prog_type,\n \t\t\t const char *prog_name, const char *license,\ndiff --git a/tools/lib/bpf/gen_loader.c b/tools/lib/bpf/gen_loader.c\nindex 251392aa8b41f..f07727c5b5fb8 100644\n--- a/tools/lib/bpf/gen_loader.c\n+++ b/tools/lib/bpf/gen_loader.c\n@@ -994,13 +994,15 @@ static void cleanup_relos(struct bpf_gen *gen, int insns)\n \tcleanup_core_relo(gen);\n }\n \n-/* Convert func, line, and core relo info blobs to target endianness */\n+/* Convert func, line, core relo and cleanup info blobs to target endianness */\n static void info_blob_bswap(struct bpf_gen *gen, int func_info, int line_info,\n-\t\t\t int core_relos, struct bpf_prog_load_opts *load_attr)\n+\t\t\t int core_relos, int cleanup_info,\n+\t\t\t struct bpf_prog_load_opts *load_attr)\n {\n \tstruct bpf_func_info *fi = gen-\u003edata_start + func_info;\n \tstruct bpf_line_info *li = gen-\u003edata_start + line_info;\n \tstruct bpf_core_relo *cr = gen-\u003edata_start + core_relos;\n+\tstruct bpf_cleanup_info *ci = gen-\u003edata_start + cleanup_info;\n \tint i;\n \n \tfor (i = 0; i \u003c load_attr-\u003efunc_info_cnt; i++)\n@@ -1011,6 +1013,9 @@ static void info_blob_bswap(struct bpf_gen *gen, int func_info, int line_info,\n \n \tfor (i = 0; i \u003c gen-\u003ecore_relo_cnt; i++)\n \t\tbpf_core_relo_bswap(cr++);\n+\n+\tfor (i = 0; i \u003c load_attr-\u003ecleanup_info_cnt; i++)\n+\t\tbpf_cleanup_info_bswap(ci++);\n }\n \n void bpf_gen__prog_load(struct bpf_gen *gen,\n@@ -1024,10 +1029,15 @@ void bpf_gen__prog_load(struct bpf_gen *gen,\n \t\t\t load_attr-\u003eline_info_rec_size;\n \tint core_relo_tot_sz = gen-\u003ecore_relo_cnt *\n \t\t\t sizeof(struct bpf_core_relo);\n+\tint cleanup_info_tot_sz = load_attr-\u003ecleanup_info_cnt *\n+\t\t\t\t load_attr-\u003ecleanup_info_rec_size;\n \tint prog_load_attr, license_off, insns_off, func_info, line_info, core_relos;\n \tint attr_size = offsetofend(union bpf_attr, core_relo_rec_size);\n+\tint cleanup_info;\n \tunion bpf_attr attr;\n \n+\tif (load_attr-\u003ecleanup_info_cnt)\n+\t\tattr_size = offsetofend(union bpf_attr, cleanup_info_cnt);\n \tmemset(\u0026attr, 0, attr_size);\n \t/* add license string to blob of bytes */\n \tlicense_off = add_data(gen, license, strlen(license) + 1);\n@@ -1074,9 +1084,17 @@ void bpf_gen__prog_load(struct bpf_gen *gen,\n \t\t core_relos, gen-\u003ecore_relo_cnt,\n \t\t sizeof(struct bpf_core_relo));\n \n+\tattr.cleanup_info_rec_size = tgt_endian(load_attr-\u003ecleanup_info_rec_size);\n+\tattr.cleanup_info_cnt = tgt_endian(load_attr-\u003ecleanup_info_cnt);\n+\tcleanup_info = add_data(gen, load_attr-\u003ecleanup_info, cleanup_info_tot_sz);\n+\tpr_debug(\"gen: prog_load: cleanup_info: off %d cnt %u rec size %u\\n\",\n+\t\t cleanup_info, load_attr-\u003ecleanup_info_cnt,\n+\t\t load_attr-\u003ecleanup_info_rec_size);\n+\n \t/* convert all info blobs to target endianness */\n \tif (gen-\u003eswapped_endian \u0026\u0026 !gen-\u003eerror)\n-\t\tinfo_blob_bswap(gen, func_info, line_info, core_relos, load_attr);\n+\t\tinfo_blob_bswap(gen, func_info, line_info, core_relos, cleanup_info,\n+\t\t\t\tload_attr);\n \n \tlibbpf_strlcpy(attr.prog_name, prog_name, sizeof(attr.prog_name));\n \tprog_load_attr = add_data(gen, \u0026attr, attr_size);\n@@ -1098,6 +1116,11 @@ void bpf_gen__prog_load(struct bpf_gen *gen,\n \t/* populate union bpf_attr with a pointer to core_relos */\n \temit_rel_store(gen, attr_field(prog_load_attr, core_relos), core_relos);\n \n+\t/* with no records, attr ends before cleanup_info: nothing to store */\n+\tif (load_attr-\u003ecleanup_info_cnt)\n+\t\temit_rel_store(gen, attr_field(prog_load_attr, cleanup_info),\n+\t\t\t cleanup_info);\n+\n \t/* populate union bpf_attr fd_array with a pointer to data where map_fds are saved */\n \temit_rel_store(gen, attr_field(prog_load_attr, fd_array), gen-\u003efd_array);\n \ndiff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c\nindex cb09ded907732..d227dcc7ef0bb 100644\n--- a/tools/lib/bpf/libbpf.c\n+++ b/tools/lib/bpf/libbpf.c\n@@ -516,6 +516,11 @@ struct bpf_program {\n \tvoid *line_info;\n \t__u32 line_info_rec_size;\n \t__u32 line_info_cnt;\n+\n+\tstruct bpf_cleanup_info *cleanup_info;\n+\t__u32 cleanup_info_rec_size;\n+\t__u32 cleanup_info_cnt;\n+\n \t__u32 prog_flags;\n \t__u8 hash[SHA256_DIGEST_LENGTH];\n \n@@ -572,6 +577,7 @@ struct bpf_struct_ops {\n * are loaded with BPF_F_ARENA_SCALAR.\n */\n #define ARENA_DATA_SEC \".arena.data\"\n+#define CLEANUP_SEC \".bpf_cleanup\"\n \n enum libbpf_map_type {\n \tLIBBPF_MAP_UNSPEC,\n@@ -710,6 +716,25 @@ struct elf_sec_desc {\n \tElf_Data *data;\n };\n \n+#define CLEANUP_REC_FIELDS\t(sizeof(struct bpf_cleanup_info) / sizeof(__u32))\n+\n+/* Index of each field of struct bpf_cleanup_info, read as an array of __u32. */\n+enum {\n+\tCLEANUP_REC_BEGIN,\n+\tCLEANUP_REC_END,\n+\tCLEANUP_REC_PAD,\n+};\n+\n+/*\n+ * One (begin, end, landing_pad) triple from .bpf_cleanup, each field resolved\n+ * from its relocation to a section and an instruction index within it. Final\n+ * indices wait for subprogram placement, which differs per main program.\n+ */\n+struct cleanup_raw_rec {\n+\tint sec_idx[CLEANUP_REC_FIELDS];\n+\tsize_t insn_idx[CLEANUP_REC_FIELDS];\n+};\n+\n struct elf_state {\n \tint fd;\n \tconst void *obj_buf;\n@@ -729,6 +754,8 @@ struct elf_state {\n \tbool has_st_ops;\n \tint arena_data_shndx;\n \tint jumptables_data_shndx;\n+\tElf_Data *cleanup_data;\n+\tint cleanup_shndx;\n };\n \n struct usdt_manager;\n@@ -817,6 +844,9 @@ struct bpf_object {\n \tvoid *jumptables_data;\n \tsize_t jumptables_data_sz;\n \n+\tstruct cleanup_raw_rec *cleanup_recs;\n+\tsize_t cleanup_rec_cnt;\n+\n \tstruct {\n \t\tstruct bpf_program *prog;\n \t\tunsigned int sym_off;\n@@ -874,6 +904,7 @@ void bpf_program__unload(struct bpf_program *prog)\n \tzfree(\u0026prog-\u003efunc_info);\n \tzfree(\u0026prog-\u003eline_info);\n \tzfree(\u0026prog-\u003esubprogs);\n+\tzfree(\u0026prog-\u003ecleanup_info);\n }\n \n static void bpf_program__exit(struct bpf_program *prog)\n@@ -1639,6 +1670,7 @@ static struct bpf_object *bpf_object__new(const char *path,\n \tobj-\u003eefile.obj_buf_sz = obj_buf_sz;\n \tobj-\u003eefile.btf_maps_shndx = -1;\n \tobj-\u003eefile.arena_data_shndx = -1;\n+\tobj-\u003eefile.cleanup_shndx = -1;\n \tobj-\u003ekconfig_map_idx = -1;\n \tobj-\u003earena_map_idx = -1;\n \n@@ -1658,6 +1690,7 @@ static void bpf_object__elf_finish(struct bpf_object *obj)\n \tobj-\u003eefile.ehdr = NULL;\n \tobj-\u003eefile.symbols = NULL;\n \tobj-\u003eefile.arena_data = NULL;\n+\tobj-\u003eefile.cleanup_data = NULL;\n \n \tzfree(\u0026obj-\u003eefile.secs);\n \tobj-\u003eefile.sec_cnt = 0;\n@@ -4275,6 +4308,9 @@ static int bpf_object__elf_collect(struct bpf_object *obj)\n \t\t\t\tsec_desc-\u003eshdr = sh;\n \t\t\t\tsec_desc-\u003edata = data;\n \t\t\t\tobj-\u003eefile.has_st_ops = true;\n+\t\t\t} else if (strcmp(name, CLEANUP_SEC) == 0) {\n+\t\t\t\tobj-\u003eefile.cleanup_data = data;\n+\t\t\t\tobj-\u003eefile.cleanup_shndx = idx;\n \t\t\t} else if (strcmp(name, ARENA_SEC) == 0) {\n \t\t\t\tobj-\u003eefile.arena_data = data;\n \t\t\t\tobj-\u003eefile.arena_data_shndx = idx;\n@@ -4300,8 +4336,9 @@ static int bpf_object__elf_collect(struct bpf_object *obj)\n \n \t\t\t/*\n \t\t\t * Only do relo for section with exec instructions,\n-\t\t\t * struct_ops, maps, and read-only data that might\n-\t\t\t * have pointers to functions.\n+\t\t\t * struct_ops, maps, read-only data that might have\n+\t\t\t * pointers to functions, and the exception cleanup\n+\t\t\t * table.\n \t\t\t */\n \t\t\tif (!section_have_execinstr(obj, targ_sec_idx) \u0026\u0026\n \t\t\t !(obj-\u003edata_in_arena \u0026\u0026\n@@ -4315,6 +4352,7 @@ static int bpf_object__elf_collect(struct bpf_object *obj)\n \t\t\t strcmp(name, \".rel\" STRUCT_OPS_LINK_SEC) \u0026\u0026\n \t\t\t strcmp(name, \".rel?\" STRUCT_OPS_SEC) \u0026\u0026\n \t\t\t strcmp(name, \".rel?\" STRUCT_OPS_LINK_SEC) \u0026\u0026\n+\t\t\t strcmp(name, \".rel\" CLEANUP_SEC) \u0026\u0026\n \t\t\t strcmp(name, \".rel\" MAPS_ELF_SEC)) {\n \t\t\t\tpr_info(\"elf: skipping relo section(%d) %s for section(%d) %s\\n\",\n \t\t\t\t\tidx, name, targ_sec_idx,\n@@ -5099,6 +5137,219 @@ static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,\n \treturn NULL;\n }\n \n+static int bpf_object_init_cleanup_info(struct bpf_object *obj)\n+{\n+\tElf_Data *data = obj-\u003eefile.cleanup_data;\n+\tsize_t i, nrels, nslots, nrecs;\n+\tstruct cleanup_raw_rec *recs;\n+\tElf_Data *relo = NULL;\n+\tconst char *vals;\n+\tint ret = 0;\n+\tbool native;\n+\n+\tif (!data || obj-\u003eefile.cleanup_shndx \u003c 0 || !data-\u003ed_size)\n+\t\treturn 0;\n+\n+\tnative = is_native_endianness(obj);\n+\n+\tfor (i = 0; i \u003c obj-\u003eefile.sec_cnt; i++) {\n+\t\tstruct elf_sec_desc *sd = \u0026obj-\u003eefile.secs[i];\n+\n+\t\tif (sd-\u003esec_type == SEC_RELO \u0026\u0026 sd-\u003eshdr \u0026\u0026\n+\t\t sd-\u003eshdr-\u003esh_info == (Elf64_Word)obj-\u003eefile.cleanup_shndx) {\n+\t\t\trelo = sd-\u003edata;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tif (!relo) {\n+\t\tpr_warn(\"%s present without relocations\\n\", CLEANUP_SEC);\n+\t\treturn -LIBBPF_ERRNO__FORMAT;\n+\t}\n+\tif (data-\u003ed_size % sizeof(struct bpf_cleanup_info)) {\n+\t\tpr_warn(\"%s size %zu is not a multiple of the record size %zu\\n\",\n+\t\t\tCLEANUP_SEC, data-\u003ed_size, sizeof(struct bpf_cleanup_info));\n+\t\treturn -LIBBPF_ERRNO__FORMAT;\n+\t}\n+\n+\tvals = data-\u003ed_buf;\n+\tnslots = data-\u003ed_size / sizeof(__u32);\n+\tnrecs = data-\u003ed_size / sizeof(struct bpf_cleanup_info);\n+\n+\trecs = calloc(nrecs, sizeof(*recs));\n+\tif (!recs)\n+\t\treturn -ENOMEM;\n+\tfor (i = 0; i \u003c nslots; i++)\n+\t\trecs[i / CLEANUP_REC_FIELDS].sec_idx[i % CLEANUP_REC_FIELDS] = -1;\n+\n+\t/* One relocation per 4-byte field, naming the section it points into. */\n+\tnrels = relo-\u003ed_size / sizeof(Elf64_Rel);\n+\tfor (i = 0; i \u003c nrels; i++) {\n+\t\tElf64_Rel *rel = elf_rel_by_idx(relo, i);\n+\t\tElf64_Sym *sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel-\u003er_info));\n+\t\tsize_t type = ELF64_R_TYPE(rel-\u003er_info);\n+\t\tsize_t slot = rel-\u003er_offset / sizeof(__u32);\n+\t\tstruct cleanup_raw_rec *rec;\n+\t\tsize_t off;\n+\t\t__u32 val;\n+\n+\t\tif (type != R_BPF_64_NODYLD32 \u0026\u0026 type != R_BPF_64_ABS32) {\n+\t\t\tpr_warn(\"%s: relocation %zu has unexpected type %zu\\n\",\n+\t\t\t\tCLEANUP_SEC, i, type);\n+\t\t\tret = -LIBBPF_ERRNO__FORMAT;\n+\t\t\tgoto out;\n+\t\t}\n+\t\tif (!sym || slot \u003e= nslots || rel-\u003er_offset % sizeof(__u32)) {\n+\t\t\tpr_warn(\"%s: bad relocation %zu\\n\", CLEANUP_SEC, i);\n+\t\t\tret = -LIBBPF_ERRNO__FORMAT;\n+\t\t\tgoto out;\n+\t\t}\n+\t\t/*\n+\t\t * The addend lives in the section data, which libelf leaves in\n+\t\t * the object's byte order; a non-section symbol additionally\n+\t\t * contributes its own value. The section is only byte aligned.\n+\t\t */\n+\t\tmemcpy(\u0026val, vals + slot * sizeof(val), sizeof(val));\n+\t\toff = (native ? val : bswap_32(val)) + sym-\u003est_value;\n+\t\tif (off % BPF_INSN_SZ) {\n+\t\t\tpr_warn(\"%s: field %zu offset %zu is not instruction aligned\\n\",\n+\t\t\t\tCLEANUP_SEC, slot, off);\n+\t\t\tret = -LIBBPF_ERRNO__FORMAT;\n+\t\t\tgoto out;\n+\t\t}\n+\t\trec = \u0026recs[slot / CLEANUP_REC_FIELDS];\n+\t\tif (rec-\u003esec_idx[slot % CLEANUP_REC_FIELDS] \u003e= 0) {\n+\t\t\tpr_warn(\"%s: field %zu has more than one relocation\\n\",\n+\t\t\t\tCLEANUP_SEC, slot);\n+\t\t\tret = -LIBBPF_ERRNO__FORMAT;\n+\t\t\tgoto out;\n+\t\t}\n+\t\trec-\u003esec_idx[slot % CLEANUP_REC_FIELDS] = sym-\u003est_shndx;\n+\t\trec-\u003einsn_idx[slot % CLEANUP_REC_FIELDS] = off / BPF_INSN_SZ;\n+\t}\n+\n+\tfor (i = 0; i \u003c nslots; i++) {\n+\t\tif (recs[i / CLEANUP_REC_FIELDS].sec_idx[i % CLEANUP_REC_FIELDS] \u003c 0) {\n+\t\t\tpr_warn(\"%s: field %zu has no relocation\\n\", CLEANUP_SEC, i);\n+\t\t\tret = -LIBBPF_ERRNO__FORMAT;\n+\t\t\tgoto out;\n+\t\t}\n+\t}\n+\n+\tobj-\u003ecleanup_recs = recs;\n+\tobj-\u003ecleanup_rec_cnt = nrecs;\n+\treturn 0;\n+out:\n+\tfree(recs);\n+\treturn ret;\n+}\n+\n+static int cmp_cleanup_info(const void *a, const void *b)\n+{\n+\tconst struct bpf_cleanup_info *x = a, *y = b;\n+\n+\tif (x-\u003ebegin_off == y-\u003ebegin_off)\n+\t\treturn 0;\n+\treturn x-\u003ebegin_off \u003c y-\u003ebegin_off ? -1 : 1;\n+}\n+\n+static int bpf_prog_collect_cleanup_info(struct bpf_object *obj,\n+\t\t\t\t\t struct bpf_program *prog)\n+{\n+\tsize_t i;\n+\tint j;\n+\n+\tfor (i = 0; i \u003c obj-\u003ecleanup_rec_cnt; i++) {\n+\t\tstruct cleanup_raw_rec *raw = \u0026obj-\u003ecleanup_recs[i];\n+\t\tstruct bpf_program *owner = NULL;\n+\t\tstruct bpf_cleanup_info ci = {};\n+\t\t__u32 fields[CLEANUP_REC_FIELDS];\n+\t\tvoid *tmp;\n+\n+\t\tfor (j = 0; j \u003c CLEANUP_REC_FIELDS; j++) {\n+\t\t\tsize_t idx = raw-\u003einsn_idx[j], final;\n+\t\t\tstruct bpf_program *p;\n+\n+\t\t\t/*\n+\t\t\t * An exclusive end may name the instruction past the\n+\t\t\t * last of a function, so ask about the last one the\n+\t\t\t * range covers, the way the kernel does.\n+\t\t\t */\n+\t\t\tif (j == CLEANUP_REC_END) {\n+\t\t\t\tif (!idx) {\n+\t\t\t\t\tpr_warn(\"%s: record %zu ends at instruction 0\\n\",\n+\t\t\t\t\t\tCLEANUP_SEC, i);\n+\t\t\t\t\treturn -LIBBPF_ERRNO__FORMAT;\n+\t\t\t\t}\n+\t\t\t\tidx--;\n+\t\t\t}\n+\n+\t\t\tp = find_prog_by_sec_insn(obj, raw-\u003esec_idx[j], idx);\n+\t\t\tif (!p \u0026\u0026 j == CLEANUP_REC_BEGIN) {\n+\t\t\t\t/*\n+\t\t\t\t * Code no function claims is an overridden weak\n+\t\t\t\t * function the linker kept: skip its records,\n+\t\t\t\t * as its relocations are.\n+\t\t\t\t */\n+\t\t\t\tpr_debug(\"%s: record %zu is in no function, probably an overridden weak function, skipping\\n\",\n+\t\t\t\t\t CLEANUP_SEC, i);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tif (!p) {\n+\t\t\t\tpr_warn(\"%s: record %zu field %d is not inside a function\\n\",\n+\t\t\t\t\tCLEANUP_SEC, i, j);\n+\t\t\t\treturn -LIBBPF_ERRNO__FORMAT;\n+\t\t\t}\n+\t\t\tif (!owner) {\n+\t\t\t\towner = p;\n+\t\t\t} else if (owner != p) {\n+\t\t\t\tpr_warn(\"%s: record %zu spans functions '%s' and '%s'\\n\",\n+\t\t\t\t\tCLEANUP_SEC, i, owner-\u003ename, p-\u003ename);\n+\t\t\t\treturn -LIBBPF_ERRNO__FORMAT;\n+\t\t\t}\n+\n+\t\t\tif (owner == prog) {\n+\t\t\t\tfinal = raw-\u003einsn_idx[j] - prog-\u003esec_insn_off;\n+\t\t\t} else if (prog_is_subprog(obj, owner) \u0026\u0026 owner-\u003esub_insn_off) {\n+\t\t\t\t/*\n+\t\t\t\t * sub_insn_off is where this subprogram was\n+\t\t\t\t * appended to the main program being relocated;\n+\t\t\t\t * zero means it is not part of it.\n+\t\t\t\t */\n+\t\t\t\tfinal = owner-\u003esub_insn_off +\n+\t\t\t\t\traw-\u003einsn_idx[j] - owner-\u003esec_insn_off;\n+\t\t\t} else {\n+\t\t\t\towner = NULL;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tfields[j] = final;\n+\t\t}\n+\t\tif (!owner)\n+\t\t\tcontinue;\n+\n+\t\tci.begin_off = fields[CLEANUP_REC_BEGIN];\n+\t\tci.end_off = fields[CLEANUP_REC_END];\n+\t\tci.landing_pad_off = fields[CLEANUP_REC_PAD];\n+\n+\t\ttmp = libbpf_reallocarray(prog-\u003ecleanup_info, prog-\u003ecleanup_info_cnt + 1,\n+\t\t\t\t\t sizeof(*prog-\u003ecleanup_info));\n+\t\tif (!tmp)\n+\t\t\treturn -ENOMEM;\n+\t\tprog-\u003ecleanup_info = tmp;\n+\t\tprog-\u003ecleanup_info_rec_size = sizeof(struct bpf_cleanup_info);\n+\t\tprog-\u003ecleanup_info[prog-\u003ecleanup_info_cnt++] = ci;\n+\n+\t\tpr_debug(\"prog '%s': cleanup region [%u,%u) -\u003e landing pad %u\\n\",\n+\t\t\t prog-\u003ename, ci.begin_off, ci.end_off, ci.landing_pad_off);\n+\t}\n+\n+\tif (!prog-\u003ecleanup_info_cnt)\n+\t\treturn 0;\n+\n+\tqsort(prog-\u003ecleanup_info, prog-\u003ecleanup_info_cnt,\n+\t sizeof(*prog-\u003ecleanup_info), cmp_cleanup_info);\n+\treturn 0;\n+}\n+\n static int\n bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)\n {\n@@ -8197,6 +8448,13 @@ static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_pat\n \t\t\t\t\treturn err;\n \t\t\t}\n \t\t}\n+\n+\t\terr = bpf_prog_collect_cleanup_info(obj, prog);\n+\t\tif (err) {\n+\t\t\tpr_warn(\"prog '%s': failed to collect cleanup info: %s\\n\",\n+\t\t\t\tprog-\u003ename, errstr(err));\n+\t\t\treturn err;\n+\t\t}\n \t}\n \tfor (i = 0; i \u003c obj-\u003enr_programs; i++) {\n \t\tprog = \u0026obj-\u003eprograms[i];\n@@ -8561,6 +8819,9 @@ static int bpf_object__collect_relos(struct bpf_object *obj)\n \t\t\treturn -LIBBPF_ERRNO__INTERNAL;\n \t\t}\n \n+\t\tif (idx == obj-\u003eefile.cleanup_shndx)\n+\t\t\tcontinue;\n+\n \t\tif (obj-\u003eefile.secs[idx].sec_type == SEC_RODATA)\n \t\t\terr = bpf_object__collect_rodata_relos(obj, shdr, data);\n \t\telse if (obj-\u003eefile.secs[idx].sec_type == SEC_DATA)\n@@ -8856,6 +9117,11 @@ static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog\n \t\tload_attr.line_info_rec_size = prog-\u003eline_info_rec_size;\n \t\tload_attr.line_info_cnt = prog-\u003eline_info_cnt;\n \t}\n+\tif (prog-\u003ecleanup_info_cnt) {\n+\t\tload_attr.cleanup_info = prog-\u003ecleanup_info;\n+\t\tload_attr.cleanup_info_cnt = prog-\u003ecleanup_info_cnt;\n+\t\tload_attr.cleanup_info_rec_size = prog-\u003ecleanup_info_rec_size;\n+\t}\n \tload_attr.log_level = log_level;\n \tload_attr.prog_flags = prog-\u003eprog_flags;\n \t/* the program accesses its data in arena through plain numbers */\n@@ -9187,6 +9453,23 @@ static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_s\n \t}\n }\n \n+/*\n+ * LLVM terminates a cleanup landing pad with a call to _Unwind_Resume, the\n+ * base unwind ABI's entry point for carrying an unwind on once a frame's\n+ * cleanups have run. The kernel knows it as bpf_unwind_resume. Any other\n+ * extern, and a variable of that name, is looked up by @name unchanged.\n+ */\n+static const char *kern_extern_name(const struct bpf_object *obj,\n+\t\t\t\t const struct extern_desc *ext, const char *name)\n+{\n+\tconst char *essent = ext-\u003eessent_name ?: ext-\u003ename;\n+\n+\tif (!btf_is_func(btf__type_by_id(obj-\u003ebtf, ext-\u003ebtf_id)) ||\n+\t strcmp(essent, \"_Unwind_Resume\"))\n+\t\treturn name;\n+\treturn \"bpf_unwind_resume\";\n+}\n+\n static int bpf_program_record_relos(struct bpf_program *prog)\n {\n \tstruct bpf_object *obj = prog-\u003eobj;\n@@ -9195,6 +9478,7 @@ static int bpf_program_record_relos(struct bpf_program *prog)\n \tfor (i = 0; i \u003c prog-\u003enr_reloc; i++) {\n \t\tstruct reloc_desc *relo = \u0026prog-\u003ereloc_desc[i];\n \t\tstruct extern_desc *ext = \u0026obj-\u003eexterns[relo-\u003eext_idx];\n+\t\tconst char *name;\n \t\tint kind;\n \n \t\tswitch (relo-\u003etype) {\n@@ -9203,14 +9487,14 @@ static int bpf_program_record_relos(struct bpf_program *prog)\n \t\t\t\tcontinue;\n \t\t\tkind = btf_is_var(btf__type_by_id(obj-\u003ebtf, ext-\u003ebtf_id)) ?\n \t\t\t\tBTF_KIND_VAR : BTF_KIND_FUNC;\n-\t\t\tbpf_gen__record_extern(obj-\u003egen_loader, ext-\u003ename,\n-\t\t\t\t\t ext-\u003eis_weak, !ext-\u003eksym.type_id,\n-\t\t\t\t\t true, kind, relo-\u003einsn_idx);\n+\t\t\tname = kern_extern_name(obj, ext, ext-\u003ename);\n+\t\t\tbpf_gen__record_extern(obj-\u003egen_loader, name, ext-\u003eis_weak,\n+\t\t\t\t\t !ext-\u003eksym.type_id, true, kind, relo-\u003einsn_idx);\n \t\t\tbreak;\n \t\tcase RELO_EXTERN_CALL:\n-\t\t\tbpf_gen__record_extern(obj-\u003egen_loader, ext-\u003ename,\n-\t\t\t\t\t ext-\u003eis_weak, false, false, BTF_KIND_FUNC,\n-\t\t\t\t\t relo-\u003einsn_idx);\n+\t\t\tname = kern_extern_name(obj, ext, ext-\u003ename);\n+\t\t\tbpf_gen__record_extern(obj-\u003egen_loader, name, ext-\u003eis_weak, false,\n+\t\t\t\t\t false, BTF_KIND_FUNC, relo-\u003einsn_idx);\n \t\t\tbreak;\n \t\tcase RELO_CORE: {\n \t\t\tstruct bpf_core_relo cr = {\n@@ -9442,6 +9726,7 @@ static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf,\n \terr = err ? : bpf_object__init_maps(obj, opts);\n \terr = err ? : bpf_object_init_progs(obj, opts);\n \terr = err ? : bpf_object__collect_relos(obj);\n+\terr = err ? : bpf_object_init_cleanup_info(obj);\n \tif (err)\n \t\tgoto out;\n \n@@ -9684,17 +9969,24 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,\n \tstruct module_btf *mod_btf = NULL;\n \tconst struct btf_type *kern_func;\n \tstruct btf *kern_btf = NULL;\n+\tconst char *local_name, *kern_name;\n \tint ret;\n \n \tlocal_func_proto_id = ext-\u003eksym.type_id;\n \n-\tkfunc_id = find_ksym_btf_id(obj, ext-\u003eessent_name ?: ext-\u003ename, BTF_KIND_FUNC, \u0026kern_btf,\n-\t\t\t\t \u0026mod_btf);\n+\tlocal_name = ext-\u003eessent_name ?: ext-\u003ename;\n+\tkern_name = kern_extern_name(obj, ext, local_name);\n+\n+\tkfunc_id = find_ksym_btf_id(obj, kern_name, BTF_KIND_FUNC, \u0026kern_btf, \u0026mod_btf);\n \tif (kfunc_id \u003c 0) {\n \t\tif (kfunc_id == -ESRCH \u0026\u0026 ext-\u003eis_weak)\n \t\t\treturn 0;\n-\t\tpr_warn(\"extern (func ksym) '%s': not found in kernel or module BTFs\\n\",\n-\t\t\text-\u003ename);\n+\t\tif (kern_name != local_name)\n+\t\t\tpr_warn(\"extern (func ksym) '%s' ('%s' in the kernel): not found in kernel or module BTFs\\n\",\n+\t\t\t\text-\u003ename, kern_name);\n+\t\telse\n+\t\t\tpr_warn(\"extern (func ksym) '%s': not found in kernel or module BTFs\\n\",\n+\t\t\t\text-\u003ename);\n \t\treturn kfunc_id;\n \t}\n \n@@ -9707,9 +9999,14 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,\n \t\tif (ext-\u003eis_weak)\n \t\t\treturn 0;\n \n-\t\tpr_warn(\"extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\\n\",\n-\t\t\text-\u003ename, local_func_proto_id,\n-\t\t\tmod_btf ? mod_btf-\u003ename : \"vmlinux\", kfunc_proto_id);\n+\t\tif (kern_name != local_name)\n+\t\t\tpr_warn(\"extern (func ksym) '%s': func_proto [%d] incompatible with '%s' in %s [%d]\\n\",\n+\t\t\t\text-\u003ename, local_func_proto_id, kern_name,\n+\t\t\t\tmod_btf ? mod_btf-\u003ename : \"vmlinux\", kfunc_proto_id);\n+\t\telse\n+\t\t\tpr_warn(\"extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\\n\",\n+\t\t\t\text-\u003ename, local_func_proto_id,\n+\t\t\t\tmod_btf ? mod_btf-\u003ename : \"vmlinux\", kfunc_proto_id);\n \t\treturn -EINVAL;\n \t}\n \n@@ -10572,6 +10869,9 @@ void bpf_object__close(struct bpf_object *obj)\n \tzfree(\u0026obj-\u003ejumptables_data);\n \tobj-\u003ejumptables_data_sz = 0;\n \n+\tzfree(\u0026obj-\u003ecleanup_recs);\n+\tobj-\u003ecleanup_rec_cnt = 0;\n+\n \tfor (i = 0; i \u003c obj-\u003ejumptable_map_cnt; i++)\n \t\tclose(obj-\u003ejumptable_maps[i].fd);\n \tzfree(\u0026obj-\u003ejumptable_maps);\n@@ -10981,6 +11281,19 @@ int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts\n \t\tattr.line_info_rec_size = info ? info_rec_size : prog-\u003eline_info_rec_size;\n \t}\n \n+\t/* exception cleanup table */\n+\tinfo = OPTS_GET(opts, cleanup_info, NULL);\n+\tinfo_cnt = OPTS_GET(opts, cleanup_info_cnt, 0);\n+\tinfo_rec_size = OPTS_GET(opts, cleanup_info_rec_size, 0);\n+\tif (!!info != !!info_cnt || !!info != !!info_rec_size) {\n+\t\tpr_warn(\"prog '%s': cleanup_info, cleanup_info_cnt, and cleanup_info_rec_size must all be specified or all omitted\\n\",\n+\t\t\tprog-\u003ename);\n+\t\treturn libbpf_err(-EINVAL);\n+\t}\n+\tattr.cleanup_info = info ?: prog-\u003ecleanup_info;\n+\tattr.cleanup_info_cnt = info ? info_cnt : prog-\u003ecleanup_info_cnt;\n+\tattr.cleanup_info_rec_size = info ? info_rec_size : prog-\u003ecleanup_info_rec_size;\n+\n \t/* Logging is caller-controlled; no fallback to prog/obj log settings */\n \tattr.log_buf = OPTS_GET(opts, log_buf, NULL);\n \tattr.log_size = OPTS_GET(opts, log_size, 0);\ndiff --git a/tools/lib/bpf/libbpf_internal.h b/tools/lib/bpf/libbpf_internal.h\nindex 4e45dfacb548a..e17fc8f601995 100644\n--- a/tools/lib/bpf/libbpf_internal.h\n+++ b/tools/lib/bpf/libbpf_internal.h\n@@ -56,6 +56,9 @@\n #ifndef R_BPF_64_ABS32\n #define R_BPF_64_ABS32 3\n #endif\n+#ifndef R_BPF_64_NODYLD32\n+#define R_BPF_64_NODYLD32 4\n+#endif\n #ifndef R_BPF_64_32\n #define R_BPF_64_32 10\n #endif\n@@ -570,6 +573,13 @@ static inline void bpf_core_relo_bswap(struct bpf_core_relo *i)\n \ti-\u003ekind = bswap_32(i-\u003ekind);\n }\n \n+static inline void bpf_cleanup_info_bswap(struct bpf_cleanup_info *i)\n+{\n+\ti-\u003ebegin_off = bswap_32(i-\u003ebegin_off);\n+\ti-\u003eend_off = bswap_32(i-\u003eend_off);\n+\ti-\u003elanding_pad_off = bswap_32(i-\u003elanding_pad_off);\n+}\n+\n enum btf_field_iter_kind {\n \tBTF_FIELD_ITER_IDS,\n \tBTF_FIELD_ITER_STRS,\ndiff --git a/tools/lib/bpf/linker.c b/tools/lib/bpf/linker.c\nindex f3f71c452f007..911a649219a98 100644\n--- a/tools/lib/bpf/linker.c\n+++ b/tools/lib/bpf/linker.c\n@@ -1036,7 +1036,8 @@ static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *se\n \t\tsize_t sym_type = ELF64_R_TYPE(relo-\u003er_info);\n \n \t\tif (sym_type != R_BPF_64_64 \u0026\u0026 sym_type != R_BPF_64_32 \u0026\u0026\n-\t\t sym_type != R_BPF_64_ABS64 \u0026\u0026 sym_type != R_BPF_64_ABS32) {\n+\t\t sym_type != R_BPF_64_ABS64 \u0026\u0026 sym_type != R_BPF_64_ABS32 \u0026\u0026\n+\t\t sym_type != R_BPF_64_NODYLD32) {\n \t\t\tpr_warn(\"ELF relo #%d in section #%zu has unexpected type %zu in %s\\n\",\n \t\t\t\ti, sec-\u003esec_idx, sym_type, obj-\u003efilename);\n \t\t\treturn -EINVAL;\n@@ -2263,6 +2264,7 @@ static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *ob\n \t\t\tif (ELF64_ST_TYPE(src_sym-\u003est_info) == STT_SECTION) {\n \t\t\t\tstruct src_sec *sec = \u0026obj-\u003esecs[src_sym-\u003est_shndx];\n \t\t\t\tstruct bpf_insn *insn;\n+\t\t\t\t__u32 *val;\n \n \t\t\t\tif (src_linked_sec-\u003eshdr-\u003esh_flags \u0026 SHF_EXECINSTR) {\n \t\t\t\t\t/* calls to the very first static function inside\n@@ -2297,6 +2299,41 @@ static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *ob\n \t\t\t\t\tif (linker-\u003eswapped_endian)\n \t\t\t\t\t\toff = bswap_64(off);\n \t\t\t\t\tmemcpy(ptr, \u0026off, sizeof(off));\n+\t\t\t\t} else if ((sym_type == R_BPF_64_NODYLD32 ||\n+\t\t\t\t\t sym_type == R_BPF_64_ABS32) \u0026\u0026\n+\t\t\t\t\t (sec-\u003eshdr-\u003esh_flags \u0026 SHF_EXECINSTR)) {\n+\t\t\t\t\t/*\n+\t\t\t\t\t * A byte offset into a code section,\n+\t\t\t\t\t * stored in place. LLVM spells this\n+\t\t\t\t\t * relocation NODYLD32 and GNU as\n+\t\t\t\t\t * spells it ABS32; being bytes, the\n+\t\t\t\t\t * section's new start goes in as it\n+\t\t\t\t\t * is, not scaled the way a call's\n+\t\t\t\t\t * instruction index is above.\n+\t\t\t\t\t *\n+\t\t\t\t\t * The sanity check only checks the\n+\t\t\t\t\t * alignment of r_offset, and only for\n+\t\t\t\t\t * an executable section, and SHT_NOBITS\n+\t\t\t\t\t * has no raw_data, so check both here,\n+\t\t\t\t\t * bounding by subtraction so it cannot\n+\t\t\t\t\t * wrap.\n+\t\t\t\t\t */\n+\t\t\t\t\tif (!dst_linked_sec-\u003eraw_data ||\n+\t\t\t\t\t dst_linked_sec-\u003esec_sz \u003c (int)sizeof(*val) ||\n+\t\t\t\t\t dst_rel-\u003er_offset % sizeof(*val) ||\n+\t\t\t\t\t dst_rel-\u003er_offset \u003e\n+\t\t\t\t\t (size_t)dst_linked_sec-\u003esec_sz - sizeof(*val)) {\n+\t\t\t\t\t\tpr_warn(\"ELF relo #%d in section #%zu points outside the data of section '%s' in %s\\n\",\n+\t\t\t\t\t\t\tj, src_sec-\u003esec_idx,\n+\t\t\t\t\t\t\tdst_linked_sec-\u003esec_name,\n+\t\t\t\t\t\t\tobj-\u003efilename);\n+\t\t\t\t\t\treturn -EINVAL;\n+\t\t\t\t\t}\n+\t\t\t\t\tval = dst_linked_sec-\u003eraw_data + dst_rel-\u003er_offset;\n+\t\t\t\t\tif (linker-\u003eswapped_endian)\n+\t\t\t\t\t\t*val = bswap_32(bswap_32(*val) + sec-\u003edst_off);\n+\t\t\t\t\telse\n+\t\t\t\t\t\t*val += sec-\u003edst_off;\n \t\t\t\t} else {\n \t\t\t\t\tpr_warn(\"relocation against STT_SECTION in non-exec section is not supported!\\n\");\n \t\t\t\t\treturn -EINVAL;\ndiff --git a/tools/testing/selftests/bpf/Makefile.skel b/tools/testing/selftests/bpf/Makefile.skel\nindex 06e297a17156c..d9cbe8ac85b76 100644\n--- a/tools/testing/selftests/bpf/Makefile.skel\n+++ b/tools/testing/selftests/bpf/Makefile.skel\n@@ -40,7 +40,7 @@ LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c\n \n # Generate both light skeleton and libbpf skeleton for these\n LSKELS_EXTRA := test_ksyms_module.c test_ksyms_weak.c kfunc_call_test.c \\\n-\tkfunc_call_test_subprog.c test_global_percpu_data.c\n+\tkfunc_call_test_subprog.c test_global_percpu_data.c exceptions_cleanup.c\n SKEL_BLACKLIST += $(LSKELS) $(LSKELS_SIGNED)\n \n test_static_linked.skel.h-deps := test_static_linked1.bpf.o test_static_linked2.bpf.o\ndiff --git a/tools/testing/selftests/bpf/exceptions_cleanup.h b/tools/testing/selftests/bpf/exceptions_cleanup.h\nnew file mode 100644\nindex 0000000000000..84f21ecc630ab\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/exceptions_cleanup.h\n@@ -0,0 +1,48 @@\n+/* SPDX-License-Identifier: GPL-2.0 */\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#ifndef __EXCEPTIONS_CLEANUP_H__\n+#define __EXCEPTIONS_CLEANUP_H__\n+\n+/* progs/exceptions_cleanup.c: one bit per function that reports it ran. */\n+#define RAN_FOO3_PREEMPT\t0x1\n+#define RAN_FOO2_RCU\t\t0x2\n+#define RAN_FOO1V_PREEMPT\t0x4\n+#define RAN_FOO2_DROP\t\t0x8\n+#define RAN_BUMP\t\t0x10\n+\n+/* progs/exceptions_cleanup_shapes.c: one bit per landing pad. */\n+#define RAN_REGS\t\t0x1\n+#define RAN_WIDE_REC\t\t0x2\n+#define RAN_RESUME_ALIAS\t0x4\n+#define RAN_NOP_PAD\t\t0x8\n+#define RAN_VAR_STACK\t\t0x10\n+#define RAN_GAP_INNER\t\t0x20\n+#define RAN_GAP_OUTER\t\t0x40\n+#define RAN_PREC_RESUME\t\t0x80\n+#define RAN_NO_EXIT_JA\t\t0x100\n+#define RAN_CALLX\t\t0x200\n+#define RAN_CALLEE_WRITE\t0x400\n+#define RAN_CALLEE_OFFSET\t0x800\n+#define RAN_GLOBAL_WRITE\t0x1000\n+#define RAN_THROUGH_GLOBAL\t0x2000\n+#define RAN_PAIR_GLOBAL\t\t0x4000\n+#define RAN_MOVE\t\t0x8000\n+#define RAN_NO_EXIT_LOOP\t0x10000\n+#define RAN_LAST_CALL\t\t0x20000\n+#define RAN_NO_TAIL\t\t0x40000\n+\n+#define CLEANUP_REC(begin, end, landing_pad)\t\t\t\\\n+\t\".pushsection .bpf_cleanup,\\\"a\\\",@progbits;\"\t\t\\\n+\t\".long \" begin \";\"\t\t\t\t\t\\\n+\t\".long \" end \";\"\t\t\t\t\t\\\n+\t\".long \" landing_pad \";\"\t\t\t\t\\\n+\t\".popsection;\"\n+\n+/* Set a bit in @pads_ran. */\n+#define PAD_RAN(bit)\t\t\t\t\t\t\\\n+\t\"r1 = %[pads_ran] ll;\"\t\t\t\t\t\\\n+\t\"r2 = *(u64 *)(r1 + 0);\"\t\t\t\t\\\n+\t\"r2 |= \" bit \";\"\t\t\t\t\t\\\n+\t\"*(u64 *)(r1 + 0) = r2;\"\n+\n+#endif /* __EXCEPTIONS_CLEANUP_H__ */\ndiff --git a/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c b/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c\nnew file mode 100644\nindex 0000000000000..b8581716bbd40\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c\n@@ -0,0 +1,173 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#include \u003ctest_progs.h\u003e\n+#include \"exceptions_cleanup.h\"\n+#include \"exceptions_cleanup.skel.h\"\n+#include \"exceptions_cleanup_fail.skel.h\"\n+#include \"exceptions_cleanup_shapes.skel.h\"\n+#include \"exceptions_cleanup_tracing.skel.h\"\n+#include \"exceptions_cleanup.lskel.h\"\n+\n+/* foo3 unwound: every frame that has a pad ran it. */\n+#define PADS_FOO3_UNWOUND \\\n+\t(RAN_FOO3_PREEMPT | RAN_FOO2_RCU | RAN_FOO1V_PREEMPT | RAN_FOO2_DROP)\n+\n+/* foo2 unwound after foo3 returned normally: foo3's pad must not run. */\n+#define PADS_FOO2_UNWOUND \\\n+\t(RAN_FOO2_RCU | RAN_FOO1V_PREEMPT | RAN_FOO2_DROP)\n+\n+static void run(struct exceptions_cleanup *skel, __u64 input, __u32 retval,\n+\t\t__u64 pads)\n+{\n+\t__u64 ctx = 0;\n+\tint err;\n+\n+\tLIBBPF_OPTS(bpf_test_run_opts, topts,\n+\t\t .ctx_in = \u0026ctx,\n+\t\t .ctx_size_in = sizeof(ctx),\n+\t);\n+\n+\tskel-\u003ebss-\u003einput = input;\n+\tskel-\u003ebss-\u003epads_ran = 0;\n+\tskel-\u003ebss-\u003eresult = 0;\n+\n+\terr = bpf_prog_test_run_opts(bpf_program__fd(skel-\u003eprogs.entry), \u0026topts);\n+\tif (!ASSERT_OK(err, \"run\"))\n+\t\treturn;\n+\tASSERT_EQ(topts.retval, retval, \"retval\");\n+\t/* bump() is not a landing pad; it sets its bit on every run. */\n+\tASSERT_EQ(skel-\u003ebss-\u003epads_ran, pads | RAN_BUMP, \"pads_ran\");\n+}\n+\n+/*\n+ * Tracing programs against foo1(), which an unwind passes through. fexit\n+ * keeps a trampoline frame between foo1() and its caller that the unwind\n+ * cannot walk past, so it is refused; fentry leaves none, so foo3 can still\n+ * unwind through foo1() with it attached.\n+ */\n+static void test_tracing(struct exceptions_cleanup *tgt)\n+{\n+\tstruct exceptions_cleanup_tracing *skel;\n+\tint tgt_fd = bpf_program__fd(tgt-\u003eprogs.entry);\n+\tchar log[8192] = {};\n+\tint err;\n+\n+\tLIBBPF_OPTS(bpf_object_open_opts, opts,\n+\t\t .kernel_log_buf = log,\n+\t\t .kernel_log_size = sizeof(log));\n+\n+\tskel = exceptions_cleanup_tracing__open_opts(\u0026opts);\n+\tif (!ASSERT_OK_PTR(skel, \"tracer open\"))\n+\t\treturn;\n+\tbpf_program__set_autoload(skel-\u003eprogs.fentry_unwinding_subprog, true);\n+\terr = bpf_program__set_attach_target(skel-\u003eprogs.fentry_unwinding_subprog,\n+\t\t\t\t\t tgt_fd, \"foo1\");\n+\tif (!ASSERT_OK(err, \"fentry target\"))\n+\t\tgoto out;\n+\terr = exceptions_cleanup_tracing__load(skel);\n+\tif (!ASSERT_OK(err, \"fentry load\"))\n+\t\tgoto out;\n+\terr = exceptions_cleanup_tracing__attach(skel);\n+\tif (!ASSERT_OK(err, \"fentry attach\"))\n+\t\tgoto out;\n+\trun(tgt, 101, 0, PADS_FOO3_UNWOUND);\n+\tASSERT_EQ(skel-\u003ebss-\u003efentry_hits, 1, \"fentry_hits\");\n+\texceptions_cleanup_tracing__destroy(skel);\n+\n+\tskel = exceptions_cleanup_tracing__open_opts(\u0026opts);\n+\tif (!ASSERT_OK_PTR(skel, \"tracer open\"))\n+\t\treturn;\n+\tbpf_program__set_autoload(skel-\u003eprogs.fexit_unwinding_subprog, true);\n+\terr = bpf_program__set_attach_target(skel-\u003eprogs.fexit_unwinding_subprog,\n+\t\t\t\t\t tgt_fd, \"foo1\");\n+\tif (!ASSERT_OK(err, \"fexit target\"))\n+\t\tgoto out;\n+\terr = exceptions_cleanup_tracing__load(skel);\n+\tASSERT_EQ(err, -EINVAL, \"fexit load\");\n+\tASSERT_HAS_SUBSTR(log, \"Cannot attach fexit, fmod_ret or fsession to foo1\",\n+\t\t\t \"fexit log\");\n+out:\n+\texceptions_cleanup_tracing__destroy(skel);\n+}\n+\n+static void test_light_skeleton(void)\n+{\n+\tstruct exceptions_cleanup_lskel *skel;\n+\t__u64 ctx = 0;\n+\tint err;\n+\n+\tLIBBPF_OPTS(bpf_test_run_opts, topts,\n+\t\t .ctx_in = \u0026ctx,\n+\t\t .ctx_size_in = sizeof(ctx),\n+\t);\n+\n+\tskel = exceptions_cleanup_lskel__open_and_load();\n+\tif (!ASSERT_OK_PTR(skel, \"light open_and_load\"))\n+\t\treturn;\n+\n+\t/* foo3 unwinds, so every pad runs: the whole table has to arrive. */\n+\tskel-\u003ebss-\u003einput = 101;\n+\terr = bpf_prog_test_run_opts(skel-\u003eprogs.entry.prog_fd, \u0026topts);\n+\tif (!ASSERT_OK(err, \"run\"))\n+\t\tgoto out;\n+\tASSERT_EQ(topts.retval, 0, \"retval\");\n+\tASSERT_EQ(skel-\u003ebss-\u003epads_ran, PADS_FOO3_UNWOUND | RAN_BUMP,\n+\t\t \"pads_ran\");\n+out:\n+\texceptions_cleanup_lskel__destroy(skel);\n+}\n+\n+void test_exceptions_cleanup(void)\n+{\n+\tchar log[8192] = {};\n+\n+\tLIBBPF_OPTS(bpf_object_open_opts, opts,\n+\t\t .kernel_log_buf = log,\n+\t\t .kernel_log_size = sizeof(log));\n+\tstruct exceptions_cleanup *skel;\n+\tint err;\n+\n+\tskel = exceptions_cleanup__open_opts(\u0026opts);\n+\tif (!ASSERT_OK_PTR(skel, \"open\"))\n+\t\treturn;\n+\n+\terr = exceptions_cleanup__load(skel);\n+\tif (err) {\n+\t\tif (err == -EOPNOTSUPP \u0026\u0026\n+\t\t strstr(log, \"exception cleanup needs a JIT that can dispatch landing pads\")) {\n+\t\t\tprintf(\"%s:SKIP:JIT cannot dispatch exception cleanup landing pads\\n\",\n+\t\t\t __func__);\n+\t\t\ttest__skip();\n+\t\t} else if (!ASSERT_OK(err, \"load\")) {\n+\t\t\tfprintf(stderr, \"%s\", log);\n+\t\t}\n+\t\texceptions_cleanup__destroy(skel);\n+\t\treturn;\n+\t}\n+\n+\t/* No unwind: foo3 returns 1 ^ 1 == 0, foo2 adds one, no pad runs. */\n+\tif (test__start_subtest(\"no_unwind\"))\n+\t\trun(skel, 1, 1, 0);\n+\n+\t/* foo3 unwinds; every pad runs and entry returns zero. */\n+\tif (test__start_subtest(\"unwind_from_foo3\"))\n+\t\trun(skel, 101, 0, PADS_FOO3_UNWOUND);\n+\n+\t/*\n+\t * foo3 returns 2 ^ 1 == 3, so foo2 unwinds from its own second region;\n+\t * foo3's frame is long gone, so its pad must not run.\n+\t */\n+\tif (test__start_subtest(\"unwind_from_foo2\"))\n+\t\trun(skel, 2, 0, PADS_FOO2_UNWOUND);\n+\n+\tif (test__start_subtest(\"tracing_unwinding_subprog\"))\n+\t\ttest_tracing(skel);\n+\n+\texceptions_cleanup__destroy(skel);\n+\n+\tif (test__start_subtest(\"light_skeleton\"))\n+\t\ttest_light_skeleton();\n+\n+\tRUN_TESTS(exceptions_cleanup_fail);\n+\tRUN_TESTS(exceptions_cleanup_shapes);\n+}\ndiff --git a/tools/testing/selftests/bpf/progs/bpf_misc.h b/tools/testing/selftests/bpf/progs/bpf_misc.h\nindex d7f706c3bc4af..f5baeb979cc22 100644\n--- a/tools/testing/selftests/bpf/progs/bpf_misc.h\n+++ b/tools/testing/selftests/bpf/progs/bpf_misc.h\n@@ -107,6 +107,16 @@\n * - POINTER_VALUE\n * - TEST_DATA_LEN\n * __retval_unpriv Same, but load program in unprivileged mode.\n+ * __set_global Set a global variable of the program to a value before\n+ * executing it. The variable has to be an int or an enum,\n+ * live in .bss or .data and be four or eight bytes wide,\n+ * and the value is a number or several joined by '|',\n+ * without parentheses.\n+ * __ret_global Execute the program and check that a global variable\n+ * holds the given value afterwards, under the same rules.\n+ * __set_global and __ret_global both make the loader run\n+ * the program and check its return value; without\n+ * __retval, the program must return 0.\n *\n * __description Text to be used for display and as an additional filter\n * alias, while the original program name stays matchable.\n@@ -167,6 +177,8 @@\n #define __flag(flag)\t\t__test_tag(\"test_prog_flags=\" #flag)\n #define __retval(val)\t\t__test_tag(\"test_retval=\" XSTR(val))\n #define __retval_unpriv(val)\t__test_tag(\"test_retval_unpriv=\" XSTR(val))\n+#define __set_global(var, val)\t__test_tag(\"test_global_set=\" #var \":\" XSTR(val))\n+#define __ret_global(var, val)\t__test_tag(\"test_global_ret=\" #var \":\" XSTR(val))\n #define __auxiliary\t\t__test_tag(\"test_auxiliary\")\n #define __auxiliary_unpriv\t__test_tag(\"test_auxiliary_unpriv\")\n #define __btf_path(path)\t__test_tag(\"test_btf_path=\" path)\ndiff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup.c\nnew file mode 100644\nindex 0000000000000..24523ee05acf8\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup.c\n@@ -0,0 +1,157 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#include \u003cvmlinux.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_misc.h\"\n+#include \"exceptions_cleanup.h\"\n+\n+static __used __noinline void __kfunc_btf_anchor(void)\n+{\n+\tbpf_unwind();\n+\tbpf_rcu_read_lock();\n+\tbpf_rcu_read_unlock();\n+\tbpf_preempt_disable();\n+\tbpf_preempt_enable();\n+\tbpf_unwind_resume(NULL);\n+}\n+\n+__u64 input = 0;\n+__u64 pads_ran = 0;\n+__u64 result = 0;\n+__u64 never = 0;\n+\n+static __used __noinline __u64 foo3(__u64 x)\n+{\n+\tbpf_preempt_disable();\n+\tif (x \u003e 100)\n+\t\tasm volatile (\n+\t\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\t\"2:\"\n+\t\t\"goto 3f;\"\n+\t\"4:\"\t\t\t\t\t/* landing pad */\n+\t\t/*\n+\t\t * r0 at pad entry is the zero the fixups put after the\n+\t\t * bpf_unwind() call. It is kept in a callee-saved\n+\t\t * register and handed to the resume, the way a\n+\t\t * compiler-emitted pad passes the exception pointer to\n+\t\t * _Unwind_Resume. The kfunc takes it and ignores it, and\n+\t\t * the two pads below do without the shuffle.\n+\t\t */\n+\t\t\"r7 = r0;\"\n+\t\t\"call bpf_preempt_enable;\"\n+\t\tPAD_RAN(\"%[ran]\")\n+\t\t\"r1 = r7;\"\n+\t\t\"call bpf_unwind_resume;\"\n+\t\"3:\"\n+\t\tCLEANUP_REC(\"1b\", \"2b\", \"4b\")\n+\t\t:\n+\t\t: [ran]\"i\"(RAN_FOO3_PREEMPT),\n+\t\t __imm_addr(pads_ran)\n+\t\t: __clobber_all);\n+\tbpf_preempt_enable();\n+\treturn x ^ 1;\n+}\n+\n+static __used __naked __noinline void drop_glue(void)\n+{\n+\tasm volatile (\n+\tPAD_RAN(\"%[ran]\")\n+\t\"exit;\"\n+\t:\n+\t: [ran]\"i\"(RAN_FOO2_DROP), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 foo2(void)\n+{\n+\tasm volatile (\n+\t\"r6 = r1;\"\n+\t\"call bpf_rcu_read_lock;\"\n+\t\"r1 = r6;\"\n+\"1:\"\t\"call foo3;\"\t\t\t/* cleanup region #1 */\n+\"2:\"\n+\t\"r6 = r0;\"\n+\t\"if r6 == 0 goto 5f;\"\n+\"3:\"\t\"call bpf_unwind;\"\t\t/* cleanup region #2 */\n+\"4:\"\t\"goto 4b;\"\n+\"5:\"\n+\t\"call bpf_rcu_read_unlock;\"\n+\t\"r0 = r6;\"\n+\t\"r0 += 1;\"\n+\t\"exit;\"\n+\"6:\"\t\t\t\t\t/* landing pad, shared by both regions */\n+\t\"call drop_glue;\"\n+\t\"call bpf_rcu_read_unlock;\"\n+\tPAD_RAN(\"%[ran_rcu]\")\n+\t\"call bpf_unwind_resume;\"\n+\t\"exit;\"\t\t\t\t/* never reached, kept for coverage */\n+\tCLEANUP_REC(\"1b\", \"2b\", \"6b\")\n+\tCLEANUP_REC(\"3b\", \"4b\", \"6b\")\n+\t:\n+\t: [ran_rcu]\"i\"(RAN_FOO2_RCU),\n+\t __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked __noinline void foo1v(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\"1:\"\t\"call foo2;\"\t\t\t/* cleanup region */\n+\"2:\"\n+\t\"r6 = r0;\"\n+\t\"call bpf_preempt_enable;\"\n+\t\"r1 = %[result] ll;\"\n+\t\"*(u64 *)(r1 + 0) = r6;\"\n+\t\"goto 7f;\"\n+\"8:\"\t\t\t\t\t/* landing pad */\n+\t\"call bpf_preempt_enable;\"\n+\tPAD_RAN(\"%[ran]\")\n+\t\"goto 9f;\"\n+\"7:\"\t\t\t\t\t/* the frame's own exit block */\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"9:\"\t\t\t\t\t/* resume block, after the frame's exit */\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"8b\")\n+\t:\n+\t: [ran]\"i\"(RAN_FOO1V_PREEMPT), __imm_addr(input),\n+\t __imm_addr(result), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * A frame with no cleanup record: an unwind leaving it runs no pad. The\n+ * unwind never fires -- @never is global -- and the bit marks the return path.\n+ */\n+static __used __naked __noinline void bump(void)\n+{\n+\tasm volatile (\n+\tPAD_RAN(\"%[ran]\")\n+\t\"r1 = %[never] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\t\"if r1 == 0 goto 1f;\"\n+\t\"call bpf_unwind;\"\n+\"1:\"\n+\t\"exit;\"\t\t\t\t/* r0 deliberately left alone */\n+\t:\n+\t: [ran]\"i\"(RAN_BUMP), __imm_addr(never), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+__noinline __u64 foo1(void)\n+{\n+\tbump();\n+\tfoo1v();\n+\treturn result;\n+}\n+\n+SEC(\"syscall\")\n+int entry(void *ctx)\n+{\n+\treturn foo1();\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c\nnew file mode 100644\nindex 0000000000000..18d45395425fc\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c\n@@ -0,0 +1,792 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#include \u003cvmlinux.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_experimental.h\"\n+#include \"bpf_misc.h\"\n+#include \"exceptions_cleanup.h\"\n+\n+__u64 input = 0;\n+\n+static __used __noinline void __kfunc_btf_anchor(void)\n+{\n+\tbpf_throw(0);\n+\tbpf_unwind();\n+\tbpf_preempt_disable();\n+\tbpf_preempt_enable();\n+\tbpf_rcu_read_lock();\n+\tbpf_rcu_read_unlock();\n+\tbpf_unwind_resume(NULL);\n+}\n+\n+/* An unwind raised in a callee, which is how a cleanup region gets one. */\n+static __used __naked __noinline __u64 inner_unwind(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_unwind;\"\n+\t::: __clobber_all);\n+}\n+\n+static int unwinding_cb(__u32 idx, void *ctx)\n+{\n+\tbpf_unwind();\n+\treturn 0;\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"may unwind and is used as a callback\")\n+int callback_may_unwind(void *ctx)\n+{\n+\tbpf_loop(1, unwinding_cb, NULL, 0);\n+\treturn 0;\n+}\n+\n+__noinline int unused_exc_cb(u64 cookie)\n+{\n+\treturn 0;\n+}\n+\n+/* A frame with a table and a pad, for tests whose refusal lies elsewhere. */\n+static __used __naked __noinline __u64 table_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\t\t\t\t/* never reached, kept for coverage */\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"call bpf_preempt_enable;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__exception_cb(unused_exc_cb)\n+__failure __msg(\"cannot be combined with an exception callback\")\n+int table_with_exception_cb(void *ctx)\n+{\n+\treturn table_frame();\n+}\n+\n+/*\n+ * A throw and a table, with no callback tagged: the default callback is\n+ * appended too late to stand in for the throw, so the program is scanned\n+ * for one instead.\n+ */\n+static __used __naked __noinline __u64 throw_and_table_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"call bpf_preempt_enable;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"call bpf_preempt_enable;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"cannot be combined with bpf_throw\")\n+int table_with_throw(void *ctx)\n+{\n+\tif (input)\n+\t\tbpf_throw(0);\n+\treturn throw_and_table_frame();\n+}\n+\n+__u64 never;\n+\n+/*\n+ * A pad calling a global subprogram that can unwind. The subprogram is\n+ * verified on its own, so the pad rule is what refuses it.\n+ */\n+__noinline void pad_callee_that_unwinds(void)\n+{\n+\tif (never)\n+\t\tbpf_unwind();\n+}\n+\n+static __used __naked __noinline __u64 pad_calls_unwinder_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"call pad_callee_that_unwinds;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"which can unwind while an unwind is in flight\")\n+int pad_calls_unwinder(void *ctx)\n+{\n+\treturn pad_calls_unwinder_frame();\n+}\n+\n+static __used __naked __noinline __u64 catch_pad_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\t\"goto 2b;\"\n+\"3:\"\t\t\t\t\t/* catch pad: no resume, it stops here */\n+\t\"call bpf_preempt_enable;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"ends a landing pad: a catch pad is not supported yet\")\n+int catch_landing_pad(void *ctx)\n+{\n+\treturn catch_pad_frame();\n+}\n+\n+/* A bpf_unwind_resume() outside any landing pad. */\n+SEC(\"?syscall\")\n+__failure __msg(\"is not in a landing pad\")\n+int resume_outside_pad(void *ctx)\n+{\n+\t/* Never taken, but reachable, which is all the verifier needs. */\n+\tif (never)\n+\t\tbpf_unwind_resume(NULL);\n+\treturn table_frame();\n+}\n+\n+/* A bpf_unwind_resume() in a subprogram a landing pad calls. */\n+static __used __naked __noinline void resume_in_callee(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_unwind_resume;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 pad_calls_resumer_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\t\"goto 2b;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"call bpf_preempt_enable;\"\n+\t\"call resume_in_callee;\"\t/* ...which resumes: refused */\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"is not in a landing pad\")\n+int resume_in_pad_callee(void *ctx)\n+{\n+\treturn pad_calls_resumer_frame();\n+}\n+\n+static __used __naked __noinline __u64 nested_pad_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call inner_unwind;\"\t\t/* first cleanup region */\n+\"2:\"\n+\t\"call bpf_preempt_enable;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* first pad, second region's call */\n+\t\"call bpf_preempt_enable;\"\n+\"4:\"\n+\t\"call bpf_unwind_resume;\"\n+\"5:\"\t\t\t\t\t/* second pad */\n+\t\"call bpf_preempt_enable;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\tCLEANUP_REC(\"3b\", \"4b\", \"5b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"is inside the call-site range of\")\n+int nested_landing_pad(void *ctx)\n+{\n+\treturn nested_pad_frame();\n+}\n+\n+/* A tail call in a landing pad: the frame would never reach its resume. */\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_PROG_ARRAY);\n+\t__uint(max_entries, 1);\n+\t__uint(key_size, sizeof(__u32));\n+\t__uint(value_size, sizeof(__u32));\n+} tc_map SEC(\".maps\");\n+\n+static __used __naked __noinline __u64 tail_call_pad_frame(void)\n+{\n+\tasm volatile (\n+\t\"r6 = r1;\"\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r1 = r6;\"\n+\t\"r2 = %[tc_map] ll;\"\n+\t\"r3 = 0;\"\n+\t\"call %[bpf_tail_call];\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: __imm(bpf_tail_call), __imm_addr(tc_map)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"is a tail call, which replaces the frame, and is in a landing pad\")\n+int tail_call_in_pad(void *ctx)\n+{\n+\treturn tail_call_pad_frame();\n+}\n+\n+#if defined(__BPF_FEATURE_STACK_ARGUMENT)\n+\n+/*\n+ * A pad reading an incoming stack argument after its own bpf_unwind(): the\n+ * call clobbered the register the JIT keeps it in. Every parameter is used,\n+ * so the caller passes them all, and summed before the call, so the pad's is\n+ * the only stack argument load after it.\n+ */\n+static __used __noinline __u64 stack_arg_pad_frame(__u64 a, __u64 b, __u64 c,\n+\t\t\t\t\t\t __u64 d, __u64 e, __u64 f)\n+{\n+\t__u64 sum = a + b + c + d + e + f;\n+\n+\tasm volatile (\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"goto 4f;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r0 = *(u64 *)(r11 + 8);\"\n+\t\"call bpf_unwind_resume;\"\n+\"4:\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t: \"+r\"(sum) :: __clobber_common);\n+\treturn sum;\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"r11 load must be before any r11 store or call insn\")\n+int stack_arg_load_in_pad(void *ctx)\n+{\n+\treturn stack_arg_pad_frame(1, 2, 3, 4, 5, 6);\n+}\n+\n+#endif /* __BPF_FEATURE_STACK_ARGUMENT */\n+\n+/*\n+ * A landing pad entered by ordinary control flow, with no unwind in flight:\n+ * that path reaches the pad's resume outside a pad. Only the in_pad\n+ * comparison in func_states_equal() keeps it from being pruned against the\n+ * pad's own visit of that instruction.\n+ */\n+static __used __naked __noinline __u64 jump_into_pad_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r6 = *(u64 *)(r1 + 0);\"\n+\t\"if r6 \u003e 7 goto 4f;\"\t\t/* an ordinary branch into the pad */\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r7 = r0;\"\n+\"4:\"\t\t\t\t\t/* ... and its second instruction */\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: __imm_addr(input)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"is not in a landing pad\")\n+__flag(BPF_F_TEST_STATE_FREQ)\n+int jump_into_pad(void *ctx)\n+{\n+\treturn jump_into_pad_frame();\n+}\n+\n+#if defined(__clang__) \u0026\u0026 \\\n+\t(defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))\n+\n+/*\n+ * An indirect jump in a landing pad. A jump table entry is an offset from\n+ * the program's section symbol, which has to be spelled in quotes here.\n+ */\n+SEC(\"?syscall\")\n+__failure __msg(\"is an indirect jump\")\n+__naked void gotox_in_pad(void)\n+{\n+\tasm volatile (\n+\t\".pushsection .jumptables,\\\"\\\",@progbits;\"\n+\"jt0_%=:\"\n+\t\".quad l0_%= - \\\"?syscall\\\";\"\n+\t\".quad l1_%= - \\\"?syscall\\\";\"\n+\t\".size jt0_%=, 16;\"\n+\t\".global jt0_%=;\"\n+\t\".popsection;\"\n+\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r1 = jt0_%= ll;\"\n+\t\"r1 += 8;\"\n+\t\"r2 = *(u64 *)(r1 + 0);\"\n+\t/*\n+\t * gotox r2, as raw bytes: the mnemonic only reached the LLVM\n+\t * assembler in llvm 22, and BPF_RAW_INSN() needs \u003clinux/bpf.h\u003e, which\n+\t * vmlinux.h rules out.\n+\t */\n+\t\".byte 0x0d, 0x02, 0, 0, 0, 0, 0, 0;\"\n+\"l0_%=:\"\n+\t\"call bpf_unwind_resume;\"\n+\"l1_%=:\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+#endif /* __clang__ \u0026\u0026 (x86 || arm64) */\n+\n+/* A BPF_LD_[ABS|IND] in a pad: a failed load leaves without resuming. */\n+static __used __naked __noinline __u64 ld_abs_pad_frame(void)\n+{\n+\tasm volatile (\n+\t\"r6 = r1;\"\t\t\t/* the skb BPF_LD_ABS reads */\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r0 = *(u32 *)skb[0];\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?tc\")\n+__failure __msg(\"is a BPF_LD_[ABS|IND], which can leave through the epilogue\")\n+__naked void ld_abs_in_pad(void)\n+{\n+\tasm volatile (\n+\t\"call ld_abs_pad_frame;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+/*\n+ * A subprogram a landing pad calls, which unwinds on its own. The second\n+ * unwind would rewrite return addresses the first has already redirected.\n+ */\n+static __used __naked __noinline __u64 own_pad_callee(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"call bpf_preempt_enable;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* its landing pad */\n+\t\"call bpf_preempt_enable;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 pad_calls_own_pad_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad, which calls the above */\n+\t\"call own_pad_callee;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"starts a second unwind while one is in flight\")\n+int unwind_in_pad_callee(void *ctx)\n+{\n+\treturn pad_calls_own_pad_frame();\n+}\n+\n+/* A record whose range holds no call that can unwind. */\n+static __used __naked __noinline __u64 nounwind_rec_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call bpf_preempt_enable;\"\t/* cleanup region: nounwind */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad, reached by nothing */\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"unreachable insn\")\n+int nounwind_region(void *ctx)\n+{\n+\treturn nounwind_rec_frame();\n+}\n+\n+/*\n+ * An unwind with no landing pad in the main program returns from it, so what\n+ * it holds is checked there, as at a plain exit.\n+ */\n+SEC(\"?syscall\")\n+__failure __msg(\"bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region\")\n+int unwind_no_pad_rcu(void *ctx)\n+{\n+\tbpf_rcu_read_lock();\n+\tbpf_unwind();\n+\tbpf_rcu_read_unlock();\n+\treturn 0;\n+}\n+\n+/*\n+ * Lock and reference state is the program's, not a frame's: an unwind carries\n+ * it through every pad it runs, and what is still held when the main program\n+ * returns is refused there. A pad that drops what its caller holds is fine;\n+ * the caller's own pad dropping it again is not.\n+ */\n+static __used __naked __noinline __u64 pad_drops_caller_lock_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\t\"goto 2b;\"\n+\"3:\"\t\t\t\t\t/* pad: drops a lock it never took */\n+\t\"call bpf_rcu_read_unlock;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 caller_holds_lock_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_rcu_read_lock;\"\n+\"1:\"\t\"call pad_drops_caller_lock_frame;\"\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* pad */\n+\t\"call bpf_rcu_read_unlock;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"unmatched rcu read unlock\")\n+int pad_drops_caller_lock(void *ctx)\n+{\n+\treturn caller_holds_lock_frame();\n+}\n+\n+/* The other way round: a pad that does not drop what its own frame took. */\n+static __used __naked __noinline __u64 pad_keeps_own_lock_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_rcu_read_lock;\"\n+\"1:\"\t\"call inner_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"call bpf_rcu_read_unlock;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* pad: forgets the unlock */\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region\")\n+int pad_keeps_own_lock(void *ctx)\n+{\n+\treturn pad_keeps_own_lock_frame();\n+}\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_RINGBUF);\n+\t__uint(max_entries, 4096);\n+} unwind_ringbuf SEC(\".maps\");\n+\n+/*\n+ * Always unwinds, so its caller is never returned to on the modelled path,\n+ * and the caller's post-call code, which never releases the record, is not\n+ * walked. Its pad discards the record the caller reserved.\n+ */\n+static __used __naked __noinline __u64 pad_drops_caller_ref_frame(void)\n+{\n+\tasm volatile (\n+\t\"r6 = r1;\"\t\t\t/* the caller's reserved record */\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\t\"goto 2b;\"\n+\"3:\"\t\t\t\t\t/* pad: drops what it never acquired */\n+\t\"r1 = r6;\"\n+\t\"r2 = 0;\"\n+\t\"call %[bpf_ringbuf_discard];\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: __imm(bpf_ringbuf_discard)\n+\t: __clobber_all);\n+}\n+\n+/* And this frame's own pad drops it a second time. */\n+static __used __naked __noinline __u64 caller_holds_ref_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[unwind_ringbuf] ll;\"\n+\t\"r2 = 8;\"\n+\t\"r3 = 0;\"\n+\t\"call %[bpf_ringbuf_reserve];\"\n+\t\"if r0 == 0 goto 9f;\"\n+\t\"r6 = r0;\"\n+\t\"r1 = r6;\"\n+\"1:\"\t\"call pad_drops_caller_ref_frame;\"\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* pad */\n+\t\"r1 = r6;\"\n+\t\"r2 = 0;\"\n+\t\"call %[bpf_ringbuf_discard];\"\n+\t\"call bpf_unwind_resume;\"\n+\"9:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard),\n+\t __imm_addr(unwind_ringbuf)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"R1 type=scalar expected=ringbuf_mem\")\n+int pad_drops_caller_ref(void *ctx)\n+{\n+\treturn caller_holds_ref_frame();\n+}\n+\n+/*\n+ * A frame an unwind returns through without a pad is abandoned where it made\n+ * the call: the JIT sends it to its epilogue, so nothing of it runs again and\n+ * whatever it acquired is never released -- which the main program's exit\n+ * then finds still held.\n+ */\n+static __used __naked __noinline __u64 pad_resumes_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\t\"goto 2b;\"\n+\"3:\"\t\t\t\t\t/* pad */\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 uncovered_holds_lock_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_rcu_read_lock;\"\n+\t\"call pad_resumes_frame;\"\t/* no record covers this call */\n+\t\"call bpf_rcu_read_unlock;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region\")\n+int unwind_through_call_keeps_lock(void *ctx)\n+{\n+\treturn uncovered_holds_lock_frame();\n+}\n+\n+static __used __naked __noinline __u64 uncovered_holds_ref_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[unwind_ringbuf] ll;\"\n+\t\"r2 = 8;\"\n+\t\"r3 = 0;\"\n+\t\"call %[bpf_ringbuf_reserve];\"\n+\t\"if r0 == 0 goto 9f;\"\n+\t\"r6 = r0;\"\n+\t\"call pad_resumes_frame;\"\t/* no record covers this call */\n+\t\"r1 = r6;\"\n+\t\"r2 = 0;\"\n+\t\"call %[bpf_ringbuf_discard];\"\n+\"9:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard),\n+\t __imm_addr(unwind_ringbuf)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"Unreleased reference id=\")\n+int unwind_through_call_keeps_ref(void *ctx)\n+{\n+\treturn uncovered_holds_ref_frame();\n+}\n+\n+/*\n+ * A callee writes its caller's stack through a pointer argument, then\n+ * unwinds. The caller's pad runs after that write, so it cannot keep trusting\n+ * the slot to hold the zero it held at the call.\n+ */\n+static __used __naked __noinline __u64 stack_writer(void)\n+{\n+\tasm volatile (\n+\t\"r2 = 0x10000000;\"\n+\t\"*(u64 *)(r1 + 0) = r2;\"\t/* r1 is the caller's fp-8 */\n+\t\"call bpf_unwind;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 stale_stack_frame(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0;\"\n+\t\"*(u64 *)(r10 - 8) = r6;\"\n+\t\"*(u64 *)(r10 - 64) = r6;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\"1:\"\t\"call stack_writer;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* pad: fp-8 as an offset into fp-64 */\n+\t\"r1 = *(u64 *)(r10 - 8);\"\n+\t\"r2 = r10;\"\n+\t\"r2 += -64;\"\n+\t\"r2 += r1;\"\n+\t\"r0 = *(u8 *)(r2 + 0);\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"invalid read from stack R2 off=268435392 size=1\")\n+int stale_stack_pad(void *ctx)\n+{\n+\treturn stale_stack_frame();\n+}\n+\n+/* The same through a global subprog, which is not walked from its caller. */\n+__noinline int global_stack_writer(__u64 *p)\n+{\n+\tif (!p)\n+\t\treturn 0;\n+\t*p = 0x10000000;\n+\tbpf_unwind();\n+\treturn 0;\n+}\n+\n+static __used __naked __noinline __u64 global_stale_stack_frame(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0;\"\n+\t\"*(u64 *)(r10 - 8) = r6;\"\n+\t\"*(u64 *)(r10 - 64) = r6;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\"1:\"\t\"call global_stack_writer;\"\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* pad: fp-8 as an offset into fp-64 */\n+\t\"r1 = *(u64 *)(r10 - 8);\"\n+\t\"r2 = r10;\"\n+\t\"r2 += -64;\"\n+\t\"r2 += r1;\"\n+\t\"r0 = *(u8 *)(r2 + 0);\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"math between fp pointer and register with unbounded min value\")\n+int global_stale_stack_pad(void *ctx)\n+{\n+\treturn global_stale_stack_frame();\n+}\n+\n+/* gcc has no indirect calls, and only these JITs emit them */\n+#if defined(__clang__) \u0026\u0026 \\\n+\t(defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))\n+\n+/*\n+ * A callback calling an unwinding subprog through a pointer it read from its\n+ * caller's stack: it neither calls nor takes the address of inner_unwind, so\n+ * only the marking of every subprog with a callx makes it might_unwind.\n+ */\n+static __used __naked __noinline int callx_cb(void)\n+{\n+\tasm volatile (\n+\t\"r1 = *(u64 *)(r2 + 0);\"\n+\t\"callx r1;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__failure __msg(\"may unwind and is used as a callback\")\n+__naked int callback_callx_may_unwind(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[inner_unwind] ll;\"\n+\t\"*(u64 *)(r10 - 8) = r1;\"\n+\t\"r1 = 1;\"\n+\t\"r2 = %[callx_cb] ll;\"\n+\t\"r3 = r10;\"\n+\t\"r3 += -8;\"\n+\t\"r4 = 0;\"\n+\t\"call %[bpf_loop];\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(inner_unwind), __imm_addr(callx_cb), __imm(bpf_loop)\n+\t: __clobber_all);\n+}\n+\n+#endif /* __clang__ \u0026\u0026 (x86 || arm64) */\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c\nnew file mode 100644\nindex 0000000000000..af92ee6cb9711\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c\n@@ -0,0 +1,1134 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#include \u003cvmlinux.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_misc.h\"\n+#include \"exceptions_cleanup.h\"\n+\n+static __used __noinline void __kfunc_btf_anchor(void)\n+{\n+\tbpf_unwind();\n+\tbpf_rcu_read_lock();\n+\tbpf_rcu_read_unlock();\n+\tbpf_preempt_disable();\n+\tbpf_preempt_enable();\n+\tbpf_unwind_resume(NULL);\n+}\n+\n+__u64 input = 0;\n+__u64 magic = 0x5eed;\n+__u64 pads_ran = 0;\n+\n+/* Load r6-r9 with values derived from @magic. */\n+#define LOAD_MAGIC_REGS\t\t\t\t\t\t\\\n+\t\"r1 = %[magic] ll;\"\t\t\t\t\t\\\n+\t\"r6 = *(u64 *)(r1 + 0);\"\t\t\t\t\\\n+\t\"r7 = r6;\"\t\t\t\t\t\t\\\n+\t\"r7 += 1;\"\t\t\t\t\t\t\\\n+\t\"r8 = r6;\"\t\t\t\t\t\t\\\n+\t\"r8 += 2;\"\t\t\t\t\t\t\\\n+\t\"r9 = r6;\"\t\t\t\t\t\t\\\n+\t\"r9 += 3;\"\n+\n+/* Set @bit only if r6-r9 still hold what LOAD_MAGIC_REGS put there. */\n+#define CHECK_MAGIC_REGS(bit)\t\t\t\t\t\\\n+\t\"r1 = %[magic] ll;\"\t\t\t\t\t\\\n+\t\"r2 = *(u64 *)(r1 + 0);\"\t\t\t\t\\\n+\t\"if r6 != r2 goto 9f;\"\t\t\t\t\t\\\n+\t\"r2 += 1;\"\t\t\t\t\t\t\\\n+\t\"if r7 != r2 goto 9f;\"\t\t\t\t\t\\\n+\t\"r2 += 1;\"\t\t\t\t\t\t\\\n+\t\"if r8 != r2 goto 9f;\"\t\t\t\t\t\\\n+\t\"r2 += 1;\"\t\t\t\t\t\t\\\n+\t\"if r9 != r2 goto 9f;\"\t\t\t\t\t\\\n+\tPAD_RAN(bit)\t\t\t\t\t\t\\\n+\t\"9:\"\n+\n+/* A callee that unwinds when its argument is over 100. */\n+static __used __noinline __u64 pc_unwinder(__u64 x)\n+{\n+\tif (x \u003e 100)\n+\t\tbpf_unwind();\n+\treturn x + 1;\n+}\n+\n+static __used __naked __noinline __u64 regs_unwinder(void)\n+{\n+\tasm volatile (\n+\t/* Clobber the caller's r6-r9; the unwind must restore them. */\n+\t\"r6 = 0xdead;\"\n+\t\"r7 = 0xbeef;\"\n+\t\"r8 = 0xcafe;\"\n+\t\"r9 = 0xf00d;\"\n+\t\"call bpf_unwind;\"\n+\t::: __clobber_all);\n+}\n+\n+/* A pad that reads r6-r9, which the callee overwrote before it unwound. */\n+static __used __naked __noinline __u64 regs_frame(void)\n+{\n+\tasm volatile (\n+\tLOAD_MAGIC_REGS\n+\t\"call bpf_preempt_disable;\"\n+\"1:\"\t\"call regs_unwinder;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"call bpf_preempt_enable;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"call bpf_preempt_enable;\"\n+\tCHECK_MAGIC_REGS(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_REGS),\n+\t __imm_addr(magic), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__ret_global(pads_ran, RAN_REGS)\n+int entry_regs(void *ctx)\n+{\n+\treturn regs_frame();\n+}\n+\n+/* A region ending on a 16-byte insn, so end - 1 names its second half. */\n+static __used __naked __noinline __u64 wide_rec_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r6 = *(u64 *)(r1 + 0);\"\n+\t\"call bpf_rcu_read_lock;\"\n+\t\"r1 = r6;\"\n+\"1:\"\t\"call pc_unwinder;\"\t\t/* cleanup region begins */\n+\t\"r1 = %[magic] ll;\"\t\t/* ... and ends on this pair */\n+\"2:\"\n+\t\"r6 = r0;\"\n+\t\"call bpf_rcu_read_unlock;\"\n+\t\"r0 = r6;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r7 = r0;\"\n+\t\"call bpf_rcu_read_unlock;\"\n+\tPAD_RAN(\"%[ran]\")\n+\t\"r1 = r7;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_WIDE_REC), __imm_addr(input), __imm_addr(magic),\n+\t __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_WIDE_REC)\n+int entry_wide_rec(void *ctx)\n+{\n+\treturn wide_rec_frame();\n+}\n+\n+/* LLVM's name for the resume; libbpf resolves it to bpf_unwind_resume(). */\n+extern void _Unwind_Resume(void *ptr) __ksym;\n+\n+static __used __noinline void __resume_alias_btf_anchor(void)\n+{\n+\t_Unwind_Resume(NULL);\n+}\n+\n+static __used __naked __noinline __u64 resume_alias_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call regs_unwinder;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call _Unwind_Resume;\"\t\t/* the frontend's name for it */\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_RESUME_ALIAS), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__ret_global(pads_ran, RAN_RESUME_ALIAS)\n+int entry_resume_alias(void *ctx)\n+{\n+\treturn resume_alias_frame();\n+}\n+\n+/* A pad starting on a nop, which bpf_opt_remove_nops() drops after the walk. */\n+static __used __naked __noinline __u64 nop_pad_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r6 = *(u64 *)(r1 + 0);\"\n+\t\"if r6 \u003c 101 goto 6f;\"\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\n+\"6:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad: a nop, then its body */\n+\t\"goto +0;\"\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_NOP_PAD),\n+\t __imm_addr(input), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_NOP_PAD)\n+int entry_nop_pad(void *ctx)\n+{\n+\treturn nop_pad_frame();\n+}\n+\n+/* Put @magic in both of the slots a variable offset could name. */\n+#define FILL_MAGIC_SLOTS\t\t\t\t\t\\\n+\t\"r1 = %[magic] ll;\"\t\t\t\t\t\\\n+\t\"r1 = *(u64 *)(r1 + 0);\"\t\t\t\t\\\n+\t\"*(u64 *)(r10 - 8) = r1;\"\t\t\t\t\\\n+\t\"*(u64 *)(r10 - 16) = r1;\"\n+\n+/* Set @bit if the slot @idx names, read at a variable offset, holds it. */\n+#define CHECK_VAR_SLOT(idx, bit)\t\t\t\t\\\n+\t\"r1 = r10;\"\t\t\t\t\t\t\\\n+\t\"r1 += \" idx \";\"\t\t\t\t\t\\\n+\t\"r2 = *(u64 *)(r1 - 16);\"\t\t\t\t\\\n+\t\"r3 = %[magic] ll;\"\t\t\t\t\t\\\n+\t\"r3 = *(u64 *)(r3 + 0);\"\t\t\t\t\\\n+\t\"if r2 != r3 goto 9f;\"\t\t\t\t\t\\\n+\tPAD_RAN(bit)\t\t\t\t\t\t\\\n+\t\"9:\"\n+\n+/* A callee that unwinds when r1 is at least 101, and touches none of r6-r9. */\n+static __used __naked __noinline __u64 var_unwinder(void)\n+{\n+\tasm volatile (\n+\t\"if r1 \u003c 101 goto 1f;\"\n+\t\"call bpf_unwind;\"\n+\"1:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 var_stack_frame(void)\n+{\n+\tasm volatile (\n+\tFILL_MAGIC_SLOTS\n+\t\"r1 = %[input] ll;\"\n+\t\"r6 = *(u64 *)(r1 + 0);\"\n+\t\"r6 \u0026= 1;\"\t\t\t/* an unknown slot number... */\n+\t\"r6 \u003c\u003c= 3;\"\t\t\t/* ...as an aligned byte offset */\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\"1:\"\t\"call var_unwinder;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r7 = r0;\"\n+\tCHECK_VAR_SLOT(\"r6\", \"%[ran]\")\n+\t\"r1 = r7;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_VAR_STACK), __imm_addr(input), __imm_addr(magic),\n+\t __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_VAR_STACK)\n+int entry_var_stack(void *ctx)\n+{\n+\treturn var_stack_frame();\n+}\n+\n+/* Two pads with an uncovered frame between them. */\n+static __used __naked __noinline __u64 gap_inner_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\"1:\"\t\"call pc_unwinder;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r6 = r0;\"\n+\tPAD_RAN(\"%[ran]\")\n+\t\"r1 = r6;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_GAP_INNER), __imm_addr(input), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+/* The frame in between, with no record of its own. */\n+static __used __noinline __u64 gap_mid(void)\n+{\n+\treturn gap_inner_frame() + 1;\n+}\n+\n+static __used __naked __noinline __u64 gap_outer_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call gap_mid;\"\t\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r6 = r0;\"\n+\tPAD_RAN(\"%[ran]\")\n+\t\"r1 = r6;\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_GAP_OUTER), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+/* And one more uncovered frame between the outer pad and the main program. */\n+static __used __noinline __u64 gap_top(void)\n+{\n+\treturn gap_outer_frame() + 1;\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_GAP_INNER | RAN_GAP_OUTER)\n+int entry_two_pads(void *ctx)\n+{\n+\treturn gap_top();\n+}\n+\n+/*\n+ * A precision chain crossing a resume: the outer frame's pad uses r6 as a\n+ * variable stack offset, and the only way into that pad is the resume that\n+ * ends the inner frame's pad, so backtracking goes from the pad through the\n+ * inner frame and back to where r6 was bounded.\n+ */\n+static __used __naked __noinline __u64 prec_inner_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call bpf_unwind;\"\t\t/* cleanup region */\n+\"2:\"\t\"goto 2b;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 prec_outer_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r6 = *(u64 *)(r1 + 0);\"\n+\t\"r6 \u0026= 0x7;\"\n+\t\"r0 = 0;\"\n+\t\"*(u64 *)(r10 - 8) = r0;\"\n+\t\"*(u64 *)(r10 - 16) = r0;\"\n+\"1:\"\t\"call prec_inner_frame;\"\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* pad: r6 as a variable stack offset */\n+\t\"r2 = r10;\"\n+\t\"r2 += -16;\"\n+\t\"r2 += r6;\"\n+\t\"*(u8 *)(r2 + 0) = 1;\"\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_PREC_RESUME), __imm_addr(input), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_PREC_RESUME)\n+__log_level(2)\n+__msg(\"frame1: regs=r6 stack= before {{[0-9]+}}: (85) call bpf_unwind_resume\")\n+__msg(\"frame2: regs= stack= before {{[0-9]+}}: (85) call bpf_unwind#\")\n+__msg(\"frame1: regs=r6 stack= before {{[0-9]+}}: (57) r6 \u0026= 7\")\n+int entry_prec_across_resume(void *ctx)\n+{\n+\treturn prec_outer_frame();\n+}\n+\n+/* Unwinds every time, and no record covers it, so the path simply ends. */\n+static __used __naked __noinline __u64 always_unwind(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_unwind;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+/*\n+ * A frame with no record of its own above one that always unwinds: nothing\n+ * after the call is reachable, so dead code removal would leave it no exit\n+ * and no epilogue for the unwind to send it to. One is kept, and since this\n+ * frame ends in a jump rather than an exit, it is not the last instruction.\n+ */\n+static __used __naked __noinline __u64 no_exit_ja_mid(void)\n+{\n+\tasm volatile (\n+\t\"goto 2f;\"\n+\"1:\"\t\"r0 = 1;\"\n+\t\"exit;\"\n+\"2:\"\t\"call always_unwind;\"\n+\t\"goto 1b;\"\t\t\t/* the last insn, and not an exit */\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 no_exit_ja_outer_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call no_exit_ja_mid;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_NO_EXIT_JA), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__ret_global(pads_ran, RAN_NO_EXIT_JA)\n+int entry_no_exit_ja(void *ctx)\n+{\n+\treturn no_exit_ja_outer_frame();\n+}\n+\n+/*\n+ * Frames that only unwind, the way a compiler leaves functions that return\n+ * `!`: after the call comes the loop that stands for what cannot happen, and\n+ * no exit. The unwinder leaves through the exit put after its bpf_unwind();\n+ * the frame above it, which has no record, is sent to an epilogue, so the\n+ * verifier gives it an exit.\n+ */\n+static __used __naked __noinline __u64 no_exit_loop_unwinder(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_unwind;\"\n+\"1:\"\t\"goto 1b;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 no_exit_loop_mid(void)\n+{\n+\tasm volatile (\n+\t\"call no_exit_loop_unwinder;\"\n+\"1:\"\t\"goto 1b;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 no_exit_loop_outer_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call no_exit_loop_mid;\"\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_NO_EXIT_LOOP), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__ret_global(pads_ran, RAN_NO_EXIT_LOOP)\n+int entry_no_exit_loop(void *ctx)\n+{\n+\treturn no_exit_loop_outer_frame();\n+}\n+\n+/*\n+ * A frame with no exit whose last insn is a covered call to a subprog placed\n+ * after it: the frame jumps over its pad to get there. The exit the verifier\n+ * puts after that call moves the callee down by one, and the record has to\n+ * stay on the call, or the unwind finds no pad for the frame.\n+ */\n+static __used __naked __noinline __u64 last_call_frame(void)\n+{\n+\tasm volatile (\n+\t\"goto 1f;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\"1:\"\t\"call last_call_unwinder;\"\t/* cleanup region, and the last insn */\n+\"2:\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_LAST_CALL), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+/* After last_call_frame(), and without an exit, so it may be called last. */\n+static __used __naked __noinline void last_call_unwinder(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_unwind;\"\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__ret_global(pads_ran, RAN_LAST_CALL)\n+int entry_last_call(void *ctx)\n+{\n+\treturn last_call_frame();\n+}\n+\n+/*\n+ * Nothing after a call that does not return, the way a compiler emits it:\n+ * no_tail_fail() is a call to bpf_unwind() and nothing else, no_tail_check()\n+ * returns its argument or ends with the call to no_tail_fail(), and the pad\n+ * of no_tail_frame() ends with its resume.\n+ */\n+static __used __naked __noinline void no_tail_fail(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_unwind;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 no_tail_check(void)\n+{\n+\tasm volatile (\n+\t\"if r1 \u003e 7 goto 1f;\"\n+\t\"r0 = r1;\"\n+\t\"exit;\"\n+\"1:\"\t\"call no_tail_fail;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 no_tail_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\"1:\"\t\"call no_tail_check;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_NO_TAIL), __imm_addr(input), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_NO_TAIL)\n+int entry_no_tail_unwind(void *ctx)\n+{\n+\treturn no_tail_frame();\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 3) __retval(3)\n+__ret_global(pads_ran, 0)\n+int entry_no_tail_return(void *ctx)\n+{\n+\treturn no_tail_frame();\n+}\n+\n+/* gcc has no indirect calls, and only these JITs emit them */\n+#if defined(__clang__) \u0026\u0026 \\\n+\t(defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))\n+\n+/*\n+ * A region covering an indirect call: a record names a call by its return\n+ * address, which a callx leaves like any other call.\n+ */\n+static __used __naked __noinline __u64 callx_region_frame(void)\n+{\n+\tasm volatile (\n+\t\"call bpf_preempt_disable;\"\n+\t\"r2 = %[always_unwind] ll;\"\n+\"1:\"\t\"callx r2;\"\t\t\t/* cleanup region */\n+\"2:\"\n+\t\"call bpf_preempt_enable;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"call bpf_preempt_enable;\"\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_CALLX), __imm_addr(always_unwind),\n+\t __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__ret_global(pads_ran, RAN_CALLX)\n+int entry_callx_region(void *ctx)\n+{\n+\treturn callx_region_frame();\n+}\n+\n+/*\n+ * A subprog calling an unwinding one through a pointer it was handed: nothing\n+ * after the call runs, but a callx cannot end a subprog, so code follows it.\n+ */\n+static __used __naked __noinline __u64 callx_arg_frame(void)\n+{\n+\tasm volatile (\n+\t\"callx r1;\"\t\t\t/* r1 is always_unwind */\n+\t\"r0 = 1;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__naked int entry_callx_arg(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[always_unwind] ll;\"\n+\t\"call callx_arg_frame;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(always_unwind)\n+\t: __clobber_all);\n+}\n+\n+#endif /* __clang__ \u0026\u0026 (x86 || arm64) */\n+\n+/* Add one to the @w-bit global at @addr. */\n+#define BUMP_GLOBAL(w, addr)\t\t\t\t\t\\\n+\t\"r1 = \" addr \" ll;\"\t\t\t\t\t\\\n+\t\"r2 = *(u\" w \" *)(r1 + 0);\"\t\t\t\t\\\n+\t\"r2 += 1;\"\t\t\t\t\t\t\\\n+\t\"*(u\" w \" *)(r1 + 0) = r2;\"\n+\n+/*\n+ * A pad that touches a global of each width and sign a test tag can name,\n+ * so that __set_global() and __ret_global() are exercised on all four.\n+ */\n+int tag_i = 0;\n+unsigned int tag_ui = 0;\n+long tag_l = 0;\n+unsigned long tag_ul = 0;\n+\n+static __used __naked __noinline __u64 tag_types_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\"1:\"\t\"call pc_unwinder;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tBUMP_GLOBAL(\"32\", \"%[tag_i]\")\n+\tBUMP_GLOBAL(\"32\", \"%[tag_ui]\")\n+\tBUMP_GLOBAL(\"64\", \"%[tag_l]\")\n+\tBUMP_GLOBAL(\"64\", \"%[tag_ul]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: __imm_addr(input), __imm_addr(tag_i), __imm_addr(tag_ui),\n+\t __imm_addr(tag_l), __imm_addr(tag_ul)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__set_global(input, 101)\n+__set_global(tag_i, -23) __set_global(tag_ui, 0xfffffffe)\n+__set_global(tag_l, -23) __set_global(tag_ul, 0xfffffffffffffffe)\n+__ret_global(tag_i, -22) __ret_global(tag_ui, 0xffffffff)\n+__ret_global(tag_l, -22) __ret_global(tag_ul, 0xffffffffffffffff)\n+int entry_tag_types(void *ctx)\n+{\n+\treturn tag_types_frame();\n+}\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_RINGBUF);\n+\t__uint(max_entries, 4096);\n+} shape_ringbuf SEC(\".maps\");\n+\n+/*\n+ * A pad reading a slot its frame's callee wrote before it unwound. The write\n+ * is there when the pad runs, and the pad has to be verified that way, or\n+ * the check below is taken as always failing and the bit is never set.\n+ */\n+static __used __naked __noinline __u64 slot_writer(void)\n+{\n+\tasm volatile (\n+\t\"r2 = 42;\"\n+\t\"*(u64 *)(r1 + 0) = r2;\"\t/* r1 is the caller's fp-8 */\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\t\"if r1 \u003c 101 goto 1f;\"\n+\t\"call bpf_unwind;\"\n+\"1:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(input)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 callee_write_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 0;\"\n+\t\"*(u64 *)(r10 - 8) = r1;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\"1:\"\t\"call slot_writer;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r1 = *(u64 *)(r10 - 8);\"\n+\t\"if r1 != 42 goto 9f;\"\n+\tPAD_RAN(\"%[ran]\")\n+\"9:\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_CALLEE_WRITE), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_CALLEE_WRITE)\n+int entry_callee_write(void *ctx)\n+{\n+\treturn callee_write_frame();\n+}\n+\n+/*\n+ * A precision chain across an unwind: the pad uses a slot the callee wrote as\n+ * a variable stack offset, so backtracking follows the slot from the pad back\n+ * into the frame the unwind left.\n+ */\n+static __used __naked __noinline __u64 offset_writer(void)\n+{\n+\tasm volatile (\n+\t\"r2 = %[input] ll;\"\n+\t\"r3 = *(u64 *)(r2 + 0);\"\n+\t\"r3 \u0026= 8;\"\n+\t\"*(u64 *)(r1 + 0) = r3;\"\t/* r1 is the caller's fp-24 */\n+\t\"call bpf_unwind;\"\n+\t:\n+\t: __imm_addr(input)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 callee_offset_frame(void)\n+{\n+\tasm volatile (\n+\tFILL_MAGIC_SLOTS\n+\t\"r1 = 0;\"\n+\t\"*(u64 *)(r10 - 24) = r1;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -24;\"\n+\"1:\"\t\"call offset_writer;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r6 = *(u64 *)(r10 - 24);\"\n+\tCHECK_VAR_SLOT(\"r6\", \"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_CALLEE_OFFSET), __imm_addr(magic), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_CALLEE_OFFSET)\n+__log_level(2)\n+__msg(\"frame1: regs= stack=-24 before {{[0-9]+}}: (85) call bpf_unwind#\")\n+__msg(\"frame2: regs= stack= before {{[0-9]+}}: (7b) *(u64 *)(r1 +0) = r3\")\n+__msg(\"frame2: regs=r3 stack= before {{[0-9]+}}: (57) r3 \u0026= 8\")\n+int entry_callee_offset(void *ctx)\n+{\n+\treturn callee_offset_frame();\n+}\n+\n+/* The same through a global subprog. */\n+__noinline int global_slot_writer(__u64 *p)\n+{\n+\tif (!p)\n+\t\treturn 0;\n+\t*p = 42;\n+\tif (input \u003e 100)\n+\t\tbpf_unwind();\n+\treturn 0;\n+}\n+\n+static __used __naked __noinline __u64 global_write_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 0;\"\n+\t\"*(u64 *)(r10 - 8) = r1;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\"1:\"\t\"call global_slot_writer;\"\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\t\"r1 = *(u64 *)(r10 - 8);\"\n+\t\"if r1 != 42 goto 9f;\"\n+\tPAD_RAN(\"%[ran]\")\n+\"9:\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_GLOBAL_WRITE), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_GLOBAL_WRITE)\n+int entry_global_write(void *ctx)\n+{\n+\treturn global_write_frame();\n+}\n+\n+/*\n+ * An unwind raised in a global subprog, called with no record over the call\n+ * from a frame whose own caller has a pad. The global subprog is verified on\n+ * its own, so the unwind is taken from the state its call returns in, and it\n+ * has to go on to that pad.\n+ */\n+__noinline int global_unwinder(int x)\n+{\n+\tif (x \u003e 100)\n+\t\tbpf_unwind();\n+\treturn 0;\n+}\n+\n+static __used __naked __noinline __u64 through_global_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\t\"call global_unwinder;\"\t\t/* no record */\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(input)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 over_global_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call through_global_frame;\"\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_THROUGH_GLOBAL), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_THROUGH_GLOBAL)\n+int entry_through_global(void *ctx)\n+{\n+\treturn over_global_frame();\n+}\n+\n+#if defined(__clang_major__) \u0026\u0026 __clang_major__ \u003e= 23\n+\n+/*\n+ * The same, with the global subprog returning in R0:R2: its unwind leaves\n+ * R2 checked as a return value too, though its caller never reads either.\n+ */\n+struct u64_pair {\n+\t__u64 a;\n+\t__u64 b;\n+};\n+\n+__noinline struct u64_pair global_pair_unwinder(int x)\n+{\n+\tstruct u64_pair p = { x, x + 1 };\n+\n+\tif (x \u003e 100)\n+\t\tbpf_unwind();\n+\treturn p;\n+}\n+\n+static __used __naked __noinline __u64 through_pair_global_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\t\"call global_pair_unwinder;\"\t/* no record */\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(input)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 over_pair_global_frame(void)\n+{\n+\tasm volatile (\n+\"1:\"\t\"call through_pair_global_frame;\"\t/* cleanup region */\n+\"2:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_PAIR_GLOBAL), __imm_addr(pads_ran)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_PAIR_GLOBAL)\n+int entry_pair_global_unwind(void *ctx)\n+{\n+\treturn over_pair_global_frame();\n+}\n+\n+#endif /* __clang_major__ \u003e= 23 */\n+\n+/*\n+ * A reference moved into a callee: the caller reserves a record and hands it\n+ * over with a plain call, as rustc emits for 'consume(rec)' -- it has nothing\n+ * left to drop -- and the callee drops it on return and, from its pad, on an\n+ * unwind.\n+ */\n+static __used __naked __noinline __u64 consume_frame(void)\n+{\n+\tasm volatile (\n+\t\"r6 = r1;\"\t\t\t/* the record, now owned here */\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\"1:\"\t\"call global_unwinder;\"\t\t/* cleanup region */\n+\"2:\"\n+\t\"r1 = r6;\"\n+\t\"r2 = 0;\"\n+\t\"call %[bpf_ringbuf_discard];\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\"3:\"\t\t\t\t\t/* landing pad: drop glue */\n+\tPAD_RAN(\"%[ran]\")\n+\t\"r1 = r6;\"\n+\t\"r2 = 0;\"\n+\t\"call %[bpf_ringbuf_discard];\"\n+\t\"call bpf_unwind_resume;\"\n+\tCLEANUP_REC(\"1b\", \"2b\", \"3b\")\n+\t:\n+\t: [ran]\"i\"(RAN_MOVE), __imm_addr(pads_ran), __imm_addr(input),\n+\t __imm(bpf_ringbuf_discard)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked __noinline __u64 move_frame(void)\n+{\n+\tasm volatile (\n+\t\"r1 = %[shape_ringbuf] ll;\"\n+\t\"r2 = 8;\"\n+\t\"r3 = 0;\"\n+\t\"call %[bpf_ringbuf_reserve];\"\n+\t\"if r0 == 0 goto 1f;\"\n+\t\"r1 = r0;\"\n+\t\"call consume_frame;\"\t\t/* the record moves: no record here */\n+\"1:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(shape_ringbuf), __imm(bpf_ringbuf_reserve)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 101) __retval(0)\n+__ret_global(pads_ran, RAN_MOVE)\n+int entry_move_into_callee(void *ctx)\n+{\n+\treturn move_frame();\n+}\n+\n+/*\n+ * A bpf_unwind() inside a loop, with no pad between it and the main program.\n+ * The main program's frame returns from where the unwind left it, not from\n+ * the loop in the subprog.\n+ */\n+static __used __naked __noinline __u64 loop_unwinder(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0;\"\n+\"1:\"\n+\t\"r1 = %[input] ll;\"\n+\t\"r1 = *(u64 *)(r1 + 0);\"\n+\t\"if r1 != r6 goto 2f;\"\n+\t\"call bpf_unwind;\"\n+\"2:\"\n+\t\"r6 += 1;\"\n+\t\"if r6 \u003c 4 goto 1b;\"\n+\t\"r0 = 1;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(input)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 2) __retval(0)\n+int entry_unwind_in_loop(void *ctx)\n+{\n+\treturn loop_unwinder();\n+}\n+\n+/*\n+ * The loop in the main program itself, around a call that unwinds on one\n+ * trip. The unwind returns from the main frame at that call, inside the loop,\n+ * where no checkpoint need have been made yet.\n+ */\n+static __used __naked __noinline __u64 unwind_on_match(void)\n+{\n+\tasm volatile (\n+\t\"r2 = %[input] ll;\"\n+\t\"r2 = *(u64 *)(r2 + 0);\"\n+\t\"if r1 != r2 goto 1f;\"\n+\t\"call bpf_unwind;\"\n+\"1:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_addr(input)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"?syscall\")\n+__success __set_global(input, 2) __retval(0)\n+__naked int entry_unwind_out_of_main_loop(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0;\"\n+\"1:\"\n+\t\"r1 = r6;\"\n+\t\"call unwind_on_match;\"\n+\t\"r6 += 1;\"\n+\t\"if r6 \u003c 4 goto 1b;\"\n+\t\"r0 = 1;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+/*\n+ * An unwind reaching main's exit in a program type that checks r0: its\n+ * precision is backtracked past an earlier call to the insn that unwound.\n+ */\n+static __used __naked __noinline __u64 plain_frame(void)\n+{\n+\tasm volatile (\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+SEC(\"?cgroup/skb\")\n+__success\n+__naked int entry_unwind_to_checked_exit(void)\n+{\n+\tasm volatile (\n+\t\"call plain_frame;\"\n+\t\"call always_unwind;\"\n+\t\"r0 = 1;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+/*\n+ * The same two calls, never taken. Neither subprog is entered, so both go\n+ * whole. Keeping an exit of always_unwind would leave one dead run over\n+ * plain_frame and the head of always_unwind, and the subprog starts worked\n+ * out after removing it would hand main's exit to always_unwind.\n+ */\n+SEC(\"?syscall\")\n+__success __retval(0)\n+__naked int entry_unwinder_never_entered(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 0;\"\n+\t\"if r1 == 0 goto 1f;\"\n+\t\"call plain_frame;\"\n+\t\"call always_unwind;\"\n+\"1:\"\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+/*\n+ * Like entry_unwind_to_checked_exit(), out of a global call, which r6 = 0\n+ * keeps from being the state's first insn, where backtracking would stop.\n+ * The verifier_bug_if() this guards against only logs, so the level 2 log\n+ * is checked.\n+ */\n+__noinline int global_always_unwind(void)\n+{\n+\tbpf_unwind();\n+\treturn 0;\n+}\n+\n+SEC(\"?cgroup/skb\")\n+__success __log_level(2) __not_msg(\"verifier bug\")\n+__naked int entry_global_unwind_to_checked_exit(void)\n+{\n+\tasm volatile (\n+\t\"r6 = 0;\"\n+\t\"call global_always_unwind;\"\n+\t\"r0 = 1;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c\nnew file mode 100644\nindex 0000000000000..9fbc06d0bec4f\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c\n@@ -0,0 +1,26 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+#include \u003cvmlinux.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \u003cbpf/bpf_tracing.h\u003e\n+\n+/*\n+ * Tracing programs aimed at foo1() of progs/exceptions_cleanup.c, a subprog\n+ * an unwind passes through. The attach target is set at load time.\n+ */\n+SEC(\"?fexit\")\n+int BPF_PROG(fexit_unwinding_subprog)\n+{\n+\treturn 0;\n+}\n+\n+int fentry_hits;\n+\n+SEC(\"?fentry\")\n+int BPF_PROG(fentry_unwinding_subprog)\n+{\n+\tfentry_hits++;\n+\treturn 0;\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/test_loader.c b/tools/testing/selftests/bpf/test_loader.c\nindex 18d47e9254007..06a01a967b33e 100644\n--- a/tools/testing/selftests/bpf/test_loader.c\n+++ b/tools/testing/selftests/bpf/test_loader.c\n@@ -50,6 +50,13 @@ enum stack_mode {\n \tSMALL_STACK\t= 1 \u003c\u003c 1,\n };\n \n+#define MAX_GLOBAL_VARS 8\n+\n+struct global_var {\n+\tchar *name;\n+\t__u64 val;\n+};\n+\n struct test_subspec {\n \tchar *name;\n \tchar *description;\n@@ -62,6 +69,10 @@ struct test_subspec {\n \tint retval;\n \tbool execute;\n \t__u64 caps;\n+\tstruct global_var set_globals[MAX_GLOBAL_VARS];\n+\tint set_global_cnt;\n+\tstruct global_var ret_globals[MAX_GLOBAL_VARS];\n+\tint ret_global_cnt;\n };\n \n struct test_spec {\n@@ -115,6 +126,34 @@ void free_msgs(struct expected_msgs *msgs)\n \tmsgs-\u003ecnt = 0;\n }\n \n+static void free_global_vars(struct global_var *vars, int *cnt)\n+{\n+\tint i;\n+\n+\tfor (i = 0; i \u003c *cnt; i++) {\n+\t\tfree(vars[i].name);\n+\t\tvars[i].name = NULL;\n+\t}\n+\t*cnt = 0;\n+}\n+\n+static int clone_global_vars(struct global_var *dst, int *dst_cnt,\n+\t\t\t const struct global_var *src, int src_cnt)\n+{\n+\tint i;\n+\n+\tfor (i = 0; i \u003c src_cnt; i++) {\n+\t\tdst[i].name = strdup(src[i].name);\n+\t\tif (!dst[i].name) {\n+\t\t\tfree_global_vars(dst, dst_cnt);\n+\t\t\treturn -ENOMEM;\n+\t\t}\n+\t\tdst[i].val = src[i].val;\n+\t\t(*dst_cnt)++;\n+\t}\n+\treturn 0;\n+}\n+\n static void free_test_spec(struct test_spec *spec)\n {\n \t/* Deallocate expect_msgs arrays. */\n@@ -129,6 +168,11 @@ static void free_test_spec(struct test_spec *spec)\n \tfree_msgs(\u0026spec-\u003eunpriv.stdout);\n \tfree_msgs(\u0026spec-\u003epriv.stdout);\n \n+\tfree_global_vars(spec-\u003epriv.set_globals, \u0026spec-\u003epriv.set_global_cnt);\n+\tfree_global_vars(spec-\u003epriv.ret_globals, \u0026spec-\u003epriv.ret_global_cnt);\n+\tfree_global_vars(spec-\u003eunpriv.set_globals, \u0026spec-\u003eunpriv.set_global_cnt);\n+\tfree_global_vars(spec-\u003eunpriv.ret_globals, \u0026spec-\u003eunpriv.ret_global_cnt);\n+\n \tfree(spec-\u003epriv.name);\n \tfree(spec-\u003epriv.description);\n \tfree(spec-\u003eunpriv.name);\n@@ -311,6 +355,236 @@ static int parse_caps(const char *str, __u64 *val, const char *name)\n \treturn 0;\n }\n \n+static int parse_global_var(const char *str, struct global_var *vars, int *cnt,\n+\t\t\t const char *name)\n+{\n+\tconst char *colon = strrchr(str, ':');\n+\tstruct global_var *var;\n+\tchar *end;\n+\t__u64 *val;\n+\n+\tif (!colon || colon == str) {\n+\t\tPRINT_FAIL(\"expecting '\u003cvariable\u003e:\u003cvalue\u003e' for %s, got '%s'\\n\", name, str);\n+\t\treturn -EINVAL;\n+\t}\n+\tif (*cnt \u003e= MAX_GLOBAL_VARS) {\n+\t\tPRINT_FAIL(\"too many %s tags, at most %d are supported\\n\",\n+\t\t\t name, MAX_GLOBAL_VARS);\n+\t\treturn -E2BIG;\n+\t}\n+\n+\tvar = \u0026vars[*cnt];\n+\tval = \u0026var-\u003eval;\n+\t*val = 0;\n+\tfor (const char *term = colon + 1;;) {\n+\t\t__u64 v;\n+\n+\t\terrno = 0;\n+\t\tv = strtoull(term, \u0026end, 0);\n+\t\tif (errno || end == term) {\n+\t\t\tPRINT_FAIL(\"failed to parse %s value '%s'\\n\", name, colon + 1);\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\t*val |= v;\n+\t\twhile (*end == ' ')\n+\t\t\tend++;\n+\t\tif (!*end)\n+\t\t\tbreak;\n+\t\tif (*end != '|') {\n+\t\t\tPRINT_FAIL(\"failed to parse %s value '%s'\\n\", name, colon + 1);\n+\t\t\treturn -EINVAL;\n+\t\t}\n+\t\tterm = end + 1;\n+\t}\n+\n+\tvar-\u003ename = strndup(str, colon - str);\n+\tif (!var-\u003ename) {\n+\t\tPRINT_FAIL(\"failed to allocate %s variable name\\n\", name);\n+\t\treturn -ENOMEM;\n+\t}\n+\t(*cnt)++;\n+\n+\treturn 0;\n+}\n+\n+/* As veristat's is_signed_type(): anything not plainly unsigned is signed. */\n+static bool global_var_is_signed(const struct btf_type *t)\n+{\n+\tif (btf_is_int(t))\n+\t\treturn btf_int_encoding(t) \u0026 BTF_INT_SIGNED;\n+\tif (btf_is_any_enum(t))\n+\t\treturn btf_kflag(t);\n+\treturn true;\n+}\n+\n+static int find_global_var(struct bpf_object *obj, const char *name,\n+\t\t\t struct bpf_map **map, __u32 *off, __u32 *sz,\n+\t\t\t bool *is_signed)\n+{\n+\tstatic const char * const secs[] = { \".bss\", \".data\" };\n+\tstruct btf *btf = bpf_object__btf(obj);\n+\tint i, s;\n+\n+\tif (!btf) {\n+\t\tPRINT_FAIL(\"no BTF for object\\n\");\n+\t\treturn -ENOENT;\n+\t}\n+\n+\tfor (s = 0; s \u003c ARRAY_SIZE(secs); s++) {\n+\t\tconst struct btf_type *sec, *vt;\n+\t\tconst struct btf_var_secinfo *vsi;\n+\t\tstruct bpf_map *m = bpf_object__find_map_by_name(obj, secs[s]);\n+\t\tint id;\n+\n+\t\tid = btf__find_by_name_kind(btf, secs[s], BTF_KIND_DATASEC);\n+\t\tif (!m || id \u003c 0)\n+\t\t\tcontinue;\n+\n+\t\tsec = btf__type_by_id(btf, id);\n+\t\tvsi = btf_var_secinfos(sec);\n+\t\tfor (i = 0; i \u003c btf_vlen(sec); i++, vsi++) {\n+\t\t\tconst struct btf_type *var = btf__type_by_id(btf, vsi-\u003etype);\n+\n+\t\t\tif (strcmp(btf__name_by_offset(btf, var-\u003ename_off), name))\n+\t\t\t\tcontinue;\n+\t\t\tif (vsi-\u003esize != 4 \u0026\u0026 vsi-\u003esize != 8) {\n+\t\t\t\tPRINT_FAIL(\"'%s' is %u bytes, only 4 and 8 are supported\\n\",\n+\t\t\t\t\t name, vsi-\u003esize);\n+\t\t\t\treturn -EINVAL;\n+\t\t\t}\n+\t\t\tvt = btf__type_by_id(btf, btf__resolve_type(btf, var-\u003etype));\n+\t\t\tif (!vt || !(btf_is_int(vt) || btf_is_any_enum(vt))) {\n+\t\t\t\tPRINT_FAIL(\"'%s' is not an int or an enum\\n\", name);\n+\t\t\t\treturn -EINVAL;\n+\t\t\t}\n+\t\t\t*is_signed = global_var_is_signed(vt);\n+\t\t\t*map = m;\n+\t\t\t*off = vsi-\u003eoffset;\n+\t\t\t*sz = vsi-\u003esize;\n+\t\t\treturn 0;\n+\t\t}\n+\t}\n+\n+\tPRINT_FAIL(\"no global variable '%s'\\n\", name);\n+\treturn -ENOENT;\n+}\n+\n+/*\n+ * A tag's value is parsed as 64 bits, but the variable may be narrower and\n+ * may be signed. Hold it to the range the variable can represent, the way\n+ * veristat's set_global_var() does, and narrow it to what is stored.\n+ */\n+static int fit_global_var(const char *name, __u32 sz, bool is_signed, __u64 *val)\n+{\n+\tlong long v = (long long)*val;\n+\tlong long max_val;\n+\t__u32 bits;\n+\n+\tif (sz \u003e= sizeof(*val))\n+\t\treturn 0;\n+\tbits = sz * 8 - (is_signed ? 1 : 0);\n+\tmax_val = 1ll \u003c\u003c bits;\n+\tif (v \u003e= max_val || v \u003c (is_signed ? -max_val : 0)) {\n+\t\tPRINT_FAIL(\"value %lld for '%s' is out of range [%lld; %lld]\\n\",\n+\t\t\t v, name, is_signed ? -max_val : 0, max_val - 1);\n+\t\treturn -EINVAL;\n+\t}\n+\t*val = (__u32)*val;\n+\treturn 0;\n+}\n+\n+/* The value of @map's single element, which the caller frees. */\n+static void *global_data(struct bpf_map *map, const char *name, size_t *vsz)\n+{\n+\t__u32 zero = 0;\n+\tvoid *buf;\n+\tint err;\n+\n+\t*vsz = bpf_map__value_size(map);\n+\tbuf = calloc(1, *vsz);\n+\tif (!buf) {\n+\t\tPRINT_FAIL(\"failed to allocate %zu bytes for '%s'\\n\", *vsz, name);\n+\t\treturn NULL;\n+\t}\n+\terr = bpf_map__lookup_elem(map, \u0026zero, sizeof(zero), buf, *vsz, 0);\n+\tif (err) {\n+\t\tPRINT_FAIL(\"failed to read '%s': %d\\n\", name, err);\n+\t\tfree(buf);\n+\t\treturn NULL;\n+\t}\n+\treturn buf;\n+}\n+\n+static int read_global_var(struct bpf_map *map, const char *name, __u32 off,\n+\t\t\t __u32 sz, __u64 *val)\n+{\n+\tsize_t vsz;\n+\tvoid *buf;\n+\n+\tbuf = global_data(map, name, \u0026vsz);\n+\tif (!buf)\n+\t\treturn -EINVAL;\n+\t*val = sz == 4 ? *(__u32 *)(buf + off) : *(__u64 *)(buf + off);\n+\tfree(buf);\n+\treturn 0;\n+}\n+\n+static int write_global_var(struct bpf_map *map, const char *name, __u32 off,\n+\t\t\t __u32 sz, __u64 val)\n+{\n+\t__u32 zero = 0;\n+\tsize_t vsz;\n+\tvoid *buf;\n+\tint err;\n+\n+\tbuf = global_data(map, name, \u0026vsz);\n+\tif (!buf)\n+\t\treturn -EINVAL;\n+\tif (sz == 4)\n+\t\t*(__u32 *)(buf + off) = val;\n+\telse\n+\t\t*(__u64 *)(buf + off) = val;\n+\terr = bpf_map__update_elem(map, \u0026zero, sizeof(zero), buf, vsz, 0);\n+\tif (err)\n+\t\tPRINT_FAIL(\"failed to write '%s': %d\\n\", name, err);\n+\tfree(buf);\n+\treturn err;\n+}\n+\n+/* Write a __set_global() value into the program's global variable. */\n+static int set_global_var(struct bpf_object *obj, const struct global_var *var)\n+{\n+\t__u64 val = var-\u003eval;\n+\tstruct bpf_map *map;\n+\t__u32 off, sz;\n+\tbool is_signed;\n+\n+\tif (find_global_var(obj, var-\u003ename, \u0026map, \u0026off, \u0026sz, \u0026is_signed) ||\n+\t fit_global_var(var-\u003ename, sz, is_signed, \u0026val))\n+\t\treturn -EINVAL;\n+\treturn write_global_var(map, var-\u003ename, off, sz, val);\n+}\n+\n+/* Check the program's global variable against a __ret_global() value. */\n+static int check_global_var(struct bpf_object *obj, const struct global_var *var)\n+{\n+\t__u64 want = var-\u003eval, val;\n+\tstruct bpf_map *map;\n+\t__u32 off, sz;\n+\tbool is_signed;\n+\n+\tif (find_global_var(obj, var-\u003ename, \u0026map, \u0026off, \u0026sz, \u0026is_signed) ||\n+\t fit_global_var(var-\u003ename, sz, is_signed, \u0026want) ||\n+\t read_global_var(map, var-\u003ename, off, sz, \u0026val))\n+\t\treturn -EINVAL;\n+\tif (val != want) {\n+\t\tPRINT_FAIL(\"Unexpected %s: 0x%llx != 0x%llx\\n\", var-\u003ename,\n+\t\t\t (unsigned long long)val, (unsigned long long)want);\n+\t\treturn -EINVAL;\n+\t}\n+\treturn 0;\n+}\n+\n static int parse_retval(const char *str, int *val, const char *name)\n {\n \t/*\n@@ -567,6 +841,22 @@ static int parse_test_spec(struct test_loader *tester,\n \t\t\tspec-\u003emode_mask |= UNPRIV;\n \t\t\tspec-\u003eunpriv.execute = true;\n \t\t\thas_unpriv_retval = true;\n+\t\t} else if ((val = str_has_pfx(s, \"test_global_set=\"))) {\n+\t\t\terr = parse_global_var(val, spec-\u003epriv.set_globals,\n+\t\t\t\t\t \u0026spec-\u003epriv.set_global_cnt,\n+\t\t\t\t\t \"__set_global\");\n+\t\t\tif (err)\n+\t\t\t\tgoto cleanup;\n+\t\t\tspec-\u003epriv.execute = true;\n+\t\t\tspec-\u003emode_mask |= PRIV;\n+\t\t} else if ((val = str_has_pfx(s, \"test_global_ret=\"))) {\n+\t\t\terr = parse_global_var(val, spec-\u003epriv.ret_globals,\n+\t\t\t\t\t \u0026spec-\u003epriv.ret_global_cnt,\n+\t\t\t\t\t \"__ret_global\");\n+\t\t\tif (err)\n+\t\t\t\tgoto cleanup;\n+\t\t\tspec-\u003epriv.execute = true;\n+\t\t\tspec-\u003emode_mask |= PRIV;\n \t\t} else if ((val = str_has_pfx(s, \"test_log_level=\"))) {\n \t\t\terr = parse_int(val, \u0026spec-\u003elog_level, \"test log level\");\n \t\t\tif (err)\n@@ -754,6 +1044,23 @@ static int parse_test_spec(struct test_loader *tester,\n \t\t\tspec-\u003eunpriv.execute = spec-\u003epriv.execute;\n \t\t}\n \n+\t\tif (spec-\u003epriv.set_global_cnt \u0026\u0026 !spec-\u003eunpriv.set_global_cnt) {\n+\t\t\terr = clone_global_vars(spec-\u003eunpriv.set_globals,\n+\t\t\t\t\t\t\u0026spec-\u003eunpriv.set_global_cnt,\n+\t\t\t\t\t\tspec-\u003epriv.set_globals,\n+\t\t\t\t\t\tspec-\u003epriv.set_global_cnt);\n+\t\t\tif (err)\n+\t\t\t\tgoto cleanup;\n+\t\t}\n+\t\tif (spec-\u003epriv.ret_global_cnt \u0026\u0026 !spec-\u003eunpriv.ret_global_cnt) {\n+\t\t\terr = clone_global_vars(spec-\u003eunpriv.ret_globals,\n+\t\t\t\t\t\t\u0026spec-\u003eunpriv.ret_global_cnt,\n+\t\t\t\t\t\tspec-\u003epriv.ret_globals,\n+\t\t\t\t\t\tspec-\u003epriv.ret_global_cnt);\n+\t\t\tif (err)\n+\t\t\t\tgoto cleanup;\n+\t\t}\n+\n \t\tif (spec-\u003eunpriv.expect_msgs.cnt == 0)\n \t\t\tclone_msgs(\u0026spec-\u003epriv.expect_msgs, \u0026spec-\u003eunpriv.expect_msgs);\n \t\tif (spec-\u003eunpriv.expect_xlated.cnt == 0)\n@@ -1369,7 +1676,7 @@ void run_subtest(struct test_loader *tester,\n \tstruct cap_state caps = {};\n \tstruct bpf_object *tobj;\n \tstruct bpf_map *map;\n-\tint retval, err, i;\n+\tint retval, err, i, j;\n \tint links_cnt = 0;\n \tbool should_load;\n \n@@ -1545,6 +1852,11 @@ void run_subtest(struct test_loader *tester,\n \t\t\t}\n \t\t}\n \n+\t\tfor (j = 0; j \u003c subspec-\u003eset_global_cnt; j++) {\n+\t\t\tif (set_global_var(tobj, \u0026subspec-\u003eset_globals[j]))\n+\t\t\t\tgoto tobj_cleanup;\n+\t\t}\n+\n \t\terr = do_prog_test_run(bpf_program__fd(tprog), \u0026retval,\n \t\t\t\t bpf_program__type(tprog) == BPF_PROG_TYPE_SYSCALL ? true : false,\n \t\t\t\t spec-\u003elinear_sz);\n@@ -1553,6 +1865,11 @@ void run_subtest(struct test_loader *tester,\n \t\t\tgoto tobj_cleanup;\n \t\t}\n \n+\t\tfor (j = 0; !err \u0026\u0026 j \u003c subspec-\u003eret_global_cnt; j++) {\n+\t\t\tif (check_global_var(tobj, \u0026subspec-\u003eret_globals[j]))\n+\t\t\t\tgoto tobj_cleanup;\n+\t\t}\n+\n \t\tverify_stderr(bpf_program__fd(tprog), \u0026subspec-\u003estderr);\n \n \t\tif (subspec-\u003estdout.cnt) {\n"
} |
| 2/1 | 2026/10/17 07:54 | agent | patch-evaluator |
0mModel:core Args: null Results: {
"EnableConfigs": [
"BPF_SYSCALL",
"BPF_JIT",
"UNWINDER_ORC"
],
"FocusSymbols": [
"bpf_unwind",
"arch_bpf_stack_walk_ra",
"bpf_exc_check_info",
"bpf_exc_check_prog",
"bpf_exc_patch_unwind_calls",
"bpf_exc_fill_native_ranges",
"bpf_exc_pad_for_ip",
"bpf_jit_supports_cleanup_pads"
],
"Reasoning": "The patch introduces BPF exception cleanup landing pads and unwinding support (via bpf_unwind and bpf_unwind_resume kfuncs). It adds kernel verification logic for exception cleanup tables, CFG analysis for landing pad edges, backtracking adjustments, instruction patching, x86 JIT epilogue handling, and stack return address rewriting via arch_bpf_stack_walk_ra() and the ORC unwinder. This touches core BPF verification and runtime execution paths reachable via the bpf() syscall on amd64, warranting fuzzing.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 48a3914cefd04f21bef6cd3ea63cd8ad35d7b0c8
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Oct 17 07:54:16 2026 +0000
syz-cluster: applied patch under review
diff --git a/arch/arm64/kernel/stacktrace.c b/arch/arm64/kernel/stacktrace.c
index 3ebcf8c53fb04..6ff485280da53 100644
--- a/arch/arm64/kernel/stacktrace.c
+++ b/arch/arm64/kernel/stacktrace.c
@@ -445,6 +445,83 @@ noinline noinstr void arch_bpf_stack_walk(bool (*consume_entry)(void *cookie, u6
kunwind_stack_walk(arch_bpf_unwind_consume_entry, &data, current, NULL);
}
+struct bpf_unwind_ra_consume_entry_data {
+ bool (*consume_entry)(void *cookie, u64 ip, u64 sp, u64 fp, u64 *ra);
+ void *cookie;
+ unsigned long record;
+ bool seen_first;
+};
+
+/* PACIA1716 (hint #8): sign x17 with the modifier in x16, under key IA. */
+static u64 bpf_unwind_sign_ra(u64 ra, u64 modifier)
+{
+ register u64 x17 asm("x17") = ra;
+ register u64 x16 asm("x16") = modifier;
+
+ asm volatile(ARM64_ASM_PREAMBLE
+ " hint #8\n"
+ : "+r" (x17) : "r" (x16));
+ return x17;
+}
+
+/* PACIASP's modifier is the entry sp, record + 16 for a BPF prologue. */
+static void bpf_unwind_store_ra(unsigned long record, u64 ra)
+{
+ struct frame_record *rec = (struct frame_record *)record;
+
+ /*
+ * Whether the slot holds a signed address is a property of the build,
+ * not one to be read off the value: a PAC can come out equal to the
+ * bits stripping puts back, and a signed address would then be taken
+ * for an unsigned one. What signs is CONFIG_ARM64_PTR_AUTH_KERNEL --
+ * the prologue here, and -mbranch-protection for everything the
+ * compiler emits.
+ */
+ if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL) &&
+ system_supports_address_auth())
+ ra = bpf_unwind_sign_ra(ra, record + sizeof(struct frame_record));
+ WRITE_ONCE(rec->lr, ra);
+}
+
+static bool
+arch_bpf_unwind_ra_consume_entry(const struct kunwind_state *state, void *cookie)
+{
+ struct bpf_unwind_ra_consume_entry_data *data = cookie;
+ unsigned long record = data->record;
+ bool seen_first = data->seen_first;
+ u64 ra = state->common.pc;
+ bool cont;
+
+ /* The record this frame's return address will have come out of. */
+ data->record = state->common.fp;
+ data->seen_first = true;
+
+ /*
+ * The first pc returns into bpf_unwind(), from this walk's own frame
+ * record: not a BPF frame, and not one to redirect.
+ */
+ if (!seen_first)
+ return true;
+ /* A consumer that stops still gets to redirect the frame it stopped on. */
+ cont = data->consume_entry(data->cookie, state->common.pc, 0,
+ state->common.fp, &ra);
+ if (ra != state->common.pc)
+ bpf_unwind_store_ra(record, ra);
+ return cont;
+}
+
+noinline noinstr void arch_bpf_stack_walk_ra(bool (*consume_entry)(void *cookie, u64 ip, u64 sp,
+ u64 fp, u64 *ra),
+ void *cookie)
+{
+ struct bpf_unwind_ra_consume_entry_data data = {
+ .consume_entry = consume_entry,
+ .cookie = cookie,
+ };
+
+ kunwind_stack_walk(arch_bpf_unwind_ra_consume_entry, &data, current, NULL);
+}
+
static const char *state_source_string(const struct kunwind_state *state)
{
switch (state->source) {
diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 506c4201fec85..c8c0328b3219c 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -2422,6 +2422,17 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
* reasons, expects to point to the next instruction)
*/
bpf_prog_update_insn_ptrs(prog, ctx.offset, ctx.ro_image);
+
+ /*
+ * Same byte offsets, consumed by the bpf_unwind() walk:
+ * turn the cleanup records into native address ranges now that
+ * the image is final.
+ */
+ bpf_exc_fill_native_ranges(prog, ctx.offset, ctx.ro_image);
+
+ /* Where an unwind sends a frame with no pad. */
+ prog->aux->epilogue_ip = (u64)ctx.ro_image +
+ ctx.epilogue_offset * AARCH64_INSN_SIZE;
out_off:
if (!ro_header && priv_stack_ptr) {
free_percpu(priv_stack_ptr);
@@ -3415,6 +3426,11 @@ bool bpf_jit_supports_exceptions(void)
return true;
}
+bool bpf_jit_supports_cleanup_pads(void)
+{
+ return true;
+}
+
bool bpf_jit_supports_arena(void)
{
return true;
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 11a4e4f87aac7..e0e39661bce83 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -15,6 +15,7 @@
#include <linux/memory.h>
#include <linux/sort.h>
#include <linux/execmem.h>
+#include <linux/kprobes.h>
#include <asm/extable.h>
#include <asm/ftrace.h>
#include <asm/set_memory.h>
@@ -3779,6 +3780,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
seen_exit = true;
/* Update cleanup_addr */
ctx->cleanup_addr = proglen;
+ /* Where an unwind sends a frame with no pad. */
+ bpf_prog->aux->epilogue_ip = (u64)image + proglen;
if (bpf_prog_was_classic(bpf_prog) &&
!ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN)) {
if (emit_spectre_bhb_barrier(&prog, ip, bpf_prog))
@@ -4976,6 +4979,13 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
*/
bpf_prog_update_insn_ptrs(prog, addrs, image);
+ /*
+ * Same mapping, consumed by the bpf_unwind() walk:
+ * turn the cleanup records into native address ranges now
+ * that the image is final.
+ */
+ bpf_exc_fill_native_ranges(prog, addrs, image);
+
/*
* ctx.prog_offset is used when CFI preambles put code *before*
* the function. See emit_cfi(). For FineIBT specifically this code
@@ -5114,6 +5124,11 @@ bool bpf_jit_supports_exceptions(void)
return IS_ENABLED(CONFIG_UNWINDER_ORC);
}
+bool bpf_jit_supports_cleanup_pads(void)
+{
+ return IS_ENABLED(CONFIG_UNWINDER_ORC);
+}
+
bool bpf_jit_supports_private_stack(void)
{
return true;
@@ -5135,6 +5150,27 @@ void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp
#endif
}
+notrace void arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp,
+ u64 *ra),
+ void *cookie)
+{
+#if defined(CONFIG_UNWINDER_ORC)
+ struct unwind_state state;
+ unsigned long addr, *ra;
+
+ for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
+ unwind_next_frame(&state)) {
+ addr = state.ip;
+ ra = unwind_get_return_address_ptr(&state);
+ if (!ra)
+ break;
+ if (!consume_fn(cookie, (u64)addr, (u64)state.sp, (u64)state.bp, (u64 *)ra))
+ break;
+ }
+#endif
+}
+NOKPROBE_SYMBOL(arch_bpf_stack_walk_ra);
+
void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
struct bpf_prog *new, struct bpf_prog *old)
{
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 54144372281cb..1b3b6ee05c092 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -1841,6 +1841,34 @@ enum bpf_sig_keyring {
BPF_SIG_KEYRING_BPF,
};
+/* One cleanup region of a JITed (sub)program. */
+struct bpf_cleanup_range {
+ u64 begin;
+ u64 end;
+ u64 pad;
+};
+
+struct bpf_exception_info {
+ struct bpf_cleanup_info *info;
+ struct bpf_cleanup_range *ranges;
+ u32 nr_info;
+ u32 nr_ranges;
+};
+
+#ifdef CONFIG_BPF_SYSCALL
+void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image);
+void bpf_exc_free_info(struct bpf_prog_aux *aux);
+#else
+
+static inline void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image)
+{
+}
+
+static inline void bpf_exc_free_info(struct bpf_prog_aux *aux)
+{
+}
+#endif
+
struct bpf_prog_aux {
atomic64_t refcnt;
u32 used_map_cnt;
@@ -1882,6 +1910,7 @@ struct bpf_prog_aux {
bool priv_stack_requested;
bool changes_pkt_data;
bool might_sleep;
+ bool might_unwind;
bool kprobe_write_ctx;
struct {
s32 keyring_serial;
@@ -1922,6 +1951,8 @@ struct bpf_prog_aux {
u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64);
u16 stack_arg_sp_adjust;
u16 freplace_link_cnt; /* counts freplace links extending this prog */
+ struct bpf_exception_info *exc;
+ u64 epilogue_ip; /* native address of this (sub)program's epilogue */
#ifdef CONFIG_SECURITY
void *security;
#endif
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 112ca1511da4d..1c33b2cf29cfe 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -379,6 +379,7 @@ struct bpf_func_state {
bool in_async_callback_fn;
bool in_exception_callback_fn;
bool no_stack_arg_load;
+ bool in_pad;
/* For callback calling functions that limit number of possible
* callback executions (e.g. bpf_loop) keeps track of current
* simulated iteration number.
@@ -429,6 +430,8 @@ enum {
INSN_F_SRC_REG_STACK = BIT(2), /* src_reg is PTR_TO_STACK */
INSN_F_STACK_ARG_ACCESS = BIT(3),
+
+ INSN_F_UNWIND = BIT(4),
};
/* Registers linked to one jump condition that a history entry can record */
@@ -437,10 +440,10 @@ enum {
struct bpf_jmp_history_entry {
/* insn idx can't be bigger than 1 million */
u32 idx : 20;
- u32 frame : 4; /* stack access frame number */
+ u32 frame : 4; /* stack access frame number, or the frame an unwind ran in */
/* special INSN_F_xxx flags */
- u32 flags : 4;
- u32 : 4;
+ u32 flags : 5;
+ u32 : 3;
u32 prev_idx : 20;
u32 spi : 12; /* stack slot index */
/*
@@ -527,6 +530,8 @@ struct bpf_verifier_state {
bool speculative;
bool in_sleepable;
+ /* the path ends with an unwind returning from frame 0 */
+ bool unwind_exit;
/*
* First and last insn idx of this verifier state.
@@ -806,6 +811,11 @@ struct bpf_insn_aux_data {
u64 jump_target:1;
unsigned int orig_idx; /* original instruction index, initialized once */
+ /*
+ * 1 + the instruction index of the exception cleanup landing pad
+ * this call site unwinds to, or 0 for none.
+ */
+ u32 cleanup_pad;
/*
* CFG strongly connected component this instruction belongs to,
* zero if it is a singleton SCC.
@@ -944,6 +954,7 @@ struct bpf_subprog_info {
s16 fastcall_stack_off;
bool has_tail_call: 1;
bool might_throw: 1;
+ bool might_unwind: 1;
bool tail_call_reachable: 1;
bool has_ld_abs: 1;
bool is_cb: 1;
@@ -1135,6 +1146,8 @@ struct bpf_verifier_env {
struct spill_snapshot **callsite_at_stack;
u32 pass_cnt; /* number of times do_check() was called */
u32 subprog_cnt;
+ struct bpf_cleanup_info *cleanup_info;
+ u32 cleanup_info_cnt;
/* number of instructions analyzed by the verifier */
u32 prev_insn_processed, insn_processed;
/* number of jmps, calls, exits analyzed so far */
@@ -1990,6 +2003,7 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union
int bpf_convert_ctx_accesses(struct bpf_verifier_env *env);
int bpf_jit_subprogs(struct bpf_verifier_env *env);
int bpf_fixup_call_args(struct bpf_verifier_env *env);
+int bpf_exc_patch_unwind_calls(struct bpf_verifier_env *env);
int bpf_do_misc_fixups(struct bpf_verifier_env *env);
int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 9339c6131f8ff..a61a78675d11e 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -1248,6 +1248,7 @@ bool bpf_jit_supports_stack_args(void);
bool bpf_jit_supports_arena_args(void);
bool bpf_jit_supports_far_kfunc_call(void);
bool bpf_jit_supports_exceptions(void);
+bool bpf_jit_supports_cleanup_pads(void);
bool bpf_jit_supports_ptr_xchg(void);
bool bpf_jit_supports_arena(void);
bool bpf_jit_supports_arena_scalar(void);
@@ -1290,6 +1291,8 @@ u32 bpf_jit_plan_arg_moves(const struct bpf_jit_arg_abi *abi,
struct bpf_jit_arg_move *moves);
u64 bpf_arch_uaddress_limit(void);
void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie);
+void arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp, u64 *ra),
+ void *cookie);
u64 arch_bpf_timed_may_goto(void);
u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *);
bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id);
diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h
index 6f70db7515dd4..9d7439c96e52e 100644
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -1708,6 +1708,9 @@ union bpf_attr {
* verification.
*/
__s32 keyring_id;
+ __aligned_u64 cleanup_info; /* exception cleanup table */
+ __u32 cleanup_info_rec_size; /* userspace bpf_cleanup_info size */
+ __u32 cleanup_info_cnt; /* number of bpf_cleanup_info records */
};
struct { /* anonymous struct used by BPF_OBJ_* commands */
@@ -7669,6 +7672,17 @@ struct bpf_line_info {
__u32 line_col;
};
+/*
+ * One record of an exception cleanup table: calls in [begin_off, end_off)
+ * that unwind resume at landing_pad_off. All three are instruction offsets
+ * in the program as loaded.
+ */
+struct bpf_cleanup_info {
+ __u32 begin_off;
+ __u32 end_off;
+ __u32 landing_pad_off;
+};
+
struct bpf_spin_lock {
__u32 val;
};
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index 269810b128c46..df71ec19d0a04 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_
obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o
+obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o exception.o
obj-${CONFIG_BPF_LSM} += bpf_inode_storage.o
obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
obj-$(CONFIG_BPF_JIT) += trampoline.o
diff --git a/kernel/bpf/backtrack.c b/kernel/bpf/backtrack.c
index 43d5740034c0f..16f6ef59ddf75 100644
--- a/kernel/bpf/backtrack.c
+++ b/kernel/bpf/backtrack.c
@@ -4,6 +4,7 @@
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <linux/bitmap.h>
+#include "exception.h"
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
@@ -424,7 +425,31 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
if (class == BPF_STX)
bt_set_reg(bt, sreg);
} else if (class == BPF_JMP || class == BPF_JMP32) {
- if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {
+ if (hist && (hist->flags & INSN_F_UNWIND)) {
+ /*
+ * A bpf_unwind(), a resume or an unwinding global call
+ * left frame hist->frame here, for a landing pad in
+ * this one, or for the main frame's exit, which is
+ * this frame itself when it is the main one. The walk
+ * crosses back into that frame, past any frames
+ * between, which were entered and never returned
+ * from. The pad found r0 unknown and r1-r5 clobbered;
+ * r6-r9 and the stack are this frame's own and stay
+ * marked in its masks until the walk comes back out.
+ */
+ bt_clear_reg(bt, BPF_REG_0);
+ if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
+ verifier_bug(env, "backtracking unwind unexpected regs %x",
+ bt_reg_mask(bt));
+ return -EFAULT;
+ }
+ if (verifier_bug_if(hist->frame < bt->frame, env,
+ "unwind from frame %d to frame %d",
+ hist->frame, bt->frame))
+ return -EFAULT;
+ bt->frame = hist->frame;
+ return 0;
+ } else if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {
int subprog_insn_idx, subprog = -1;
if (bpf_pseudo_call(insn)) {
@@ -440,10 +465,17 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
* extra instructions from subprog; the next
* instruction after call to global subprog
* should be literally next instruction in
- * caller program
+ * caller program, or the call's landing pad,
+ * branched to from the state the call returns
+ * in when the callee can unwind. A pad may be
+ * the next instruction too, so the two edges
+ * cannot be told apart, and need not be: the
+ * pad finds r0 unknown and r1-r5 cleared, so
+ * both clear the same registers below.
*/
- verifier_bug_if(idx + 1 != subseq_idx, env,
- "extra insn from subprog");
+ verifier_bug_if(idx + 1 != subseq_idx &&
+ bpf_exc_pad_of_call(env, idx) != subseq_idx,
+ env, "extra insn from subprog");
/* global subprog always sets R0 */
bt_clear_reg(bt, BPF_REG_0);
/* and if it does not set R2, main pass would catch it */
diff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c
index bce7b5abcfda3..9608293bdc069 100644
--- a/kernel/bpf/cfg.c
+++ b/kernel/bpf/cfg.c
@@ -6,6 +6,7 @@
#include <linux/sort.h>
#include "diagnostics.h"
+#include "exception.h"
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
@@ -75,6 +76,14 @@ static void mark_subprog_might_throw(struct bpf_verifier_env *env, int off)
subprog->might_throw = true;
}
+static void mark_subprog_might_unwind(struct bpf_verifier_env *env, int off)
+{
+ struct bpf_subprog_info *subprog;
+
+ subprog = bpf_find_containing_subprog(env, off);
+ subprog->might_unwind = true;
+}
+
/* 't' is an index of a call-site.
* 'w' is a callee entry point.
* Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
@@ -90,6 +99,7 @@ static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
caller->changes_pkt_data |= callee->changes_pkt_data;
caller->might_sleep |= callee->might_sleep;
caller->might_throw |= callee->might_throw;
+ caller->might_unwind |= callee->might_unwind;
}
enum {
@@ -160,6 +170,38 @@ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
return DONE_EXPLORING;
}
+static int visit_cleanup_pad_edge(int t, struct bpf_verifier_env *env)
+{
+ int *insn_stack = env->cfg.insn_stack;
+ int *insn_state = env->cfg.insn_state;
+ int w;
+
+ if (!env->cleanup_info_cnt)
+ return DONE_EXPLORING;
+ w = bpf_exc_pad_of_call(env, t);
+ if (w < 0)
+ return DONE_EXPLORING;
+
+ /*
+ * @t is a call that may branch here, and @w is the target of that
+ * branch, so both are prune points. @w especially: every covered call
+ * site in a region unwinds to the same pad, and without a prune point
+ * at its head the verifier walks the pad again for each of them.
+ */
+ mark_prune_point(env, t);
+ mark_prune_point(env, w);
+ mark_jmp_point(env, w);
+ mark_jump_target(env, w);
+
+ if (insn_state[w])
+ return DONE_EXPLORING;
+ if (env->cfg.cur_stack >= env->prog->len)
+ return -E2BIG;
+ insn_stack[env->cfg.cur_stack++] = w;
+ insn_state[w] |= DISCOVERED;
+ return KEEP_EXPLORING;
+}
+
static int visit_func_call_insn(int t, struct bpf_insn *insns,
struct bpf_verifier_env *env,
bool visit_callee)
@@ -167,6 +209,11 @@ static int visit_func_call_insn(int t, struct bpf_insn *insns,
int ret, insn_sz;
int w;
+ /* One push per visit: @t is revisited once the pad is explored. */
+ ret = visit_cleanup_pad_edge(t, env);
+ if (ret != DONE_EXPLORING)
+ return ret;
+
insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
if (ret)
@@ -630,6 +677,8 @@ static int visit_insn(int t, struct bpf_verifier_env *env)
mark_subprog_changes_pkt_data(env, t);
if (ret == 0 && bpf_is_throw_kfunc(insn))
mark_subprog_might_throw(env, t);
+ if (ret == 0 && bpf_is_unwind_kfunc(insn))
+ mark_subprog_might_unwind(env, t);
}
return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
@@ -667,6 +716,82 @@ static int visit_insn(int t, struct bpf_verifier_env *env)
}
}
+static bool addr_taken_subprog_might_unwind(struct bpf_verifier_env *env)
+{
+ struct bpf_insn *insns = env->prog->insnsi;
+ struct bpf_subprog_info *callee;
+ struct bpf_func_ptr *ptrs;
+ u32 cnt, j;
+ int i;
+
+ for (i = 0; i < env->prog->len; i++) {
+ if (bpf_pseudo_func(&insns[i])) {
+ callee = bpf_find_containing_subprog(env, i + insns[i].imm + 1);
+ if (callee->might_unwind)
+ return true;
+ continue;
+ }
+ ptrs = insn_func_ptrs(env, i, &cnt);
+ for (j = 0; j < cnt; j++) {
+ callee = bpf_find_containing_subprog(env, ptrs[j].xlated_off);
+ if (callee->might_unwind)
+ return true;
+ }
+ }
+ return false;
+}
+
+/*
+ * merge_callee_effects() does not carry might_unwind to a subprog that calls
+ * through a pointer it was handed. So if any subprog a callx can reach may
+ * unwind, mark every subprog with a callx, and its callers.
+ *
+ * This is conservative: a subprog with a callx is marked even when nothing it
+ * calls unwinds. The main walk knows each callx's target and could tell those
+ * apart.
+ */
+static void mark_callx_might_unwind(struct bpf_verifier_env *env)
+{
+ struct bpf_insn *insns = env->prog->insnsi;
+ struct bpf_subprog_info *caller, *callee;
+ int i, j, len = env->prog->len;
+ struct bpf_func_ptr *ptrs;
+ bool changed;
+ u32 cnt;
+
+ if (!addr_taken_subprog_might_unwind(env))
+ return;
+
+ for (i = 0; i < len; i++)
+ if (bpf_is_callx(&insns[i]))
+ bpf_find_containing_subprog(env, i)->might_unwind = true;
+
+ do {
+ changed = false;
+ for (i = 0; i < len; i++) {
+ caller = bpf_find_containing_subprog(env, i);
+ if (caller->might_unwind)
+ continue;
+ if (bpf_pseudo_call(&insns[i]) || bpf_pseudo_func(&insns[i])) {
+ callee = bpf_find_containing_subprog(env, i + insns[i].imm + 1);
+ if (!callee->might_unwind)
+ continue;
+ caller->might_unwind = true;
+ changed = true;
+ continue;
+ }
+ ptrs = insn_func_ptrs(env, i, &cnt);
+ for (j = 0; j < cnt; j++) {
+ callee = bpf_find_containing_subprog(env, ptrs[j].xlated_off);
+ if (!callee->might_unwind)
+ continue;
+ caller->might_unwind = true;
+ changed = true;
+ }
+ }
+ } while (changed);
+}
+
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
@@ -757,6 +882,7 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
}
}
ret = 0; /* cfg looks good */
+ mark_callx_might_unwind(env);
env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 642f0ab8eb2d8..3af8e82726917 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -292,6 +292,7 @@ void __bpf_prog_free(struct bpf_prog *fp)
mutex_destroy(&fp->aux->dst_mutex);
mutex_destroy(&fp->aux->st_ops_assoc_mutex);
kfree(fp->aux->poke_tab);
+ bpf_exc_free_info(fp->aux);
kfree(fp->aux);
}
free_percpu(fp->stats);
@@ -3524,6 +3525,17 @@ void __weak arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp,
{
}
+void __weak arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp,
+ u64 *ra),
+ void *cookie)
+{
+}
+
+bool __weak bpf_jit_supports_cleanup_pads(void)
+{
+ return false;
+}
+
bool __weak bpf_jit_supports_timed_may_goto(void)
{
return false;
diff --git a/kernel/bpf/exception.c b/kernel/bpf/exception.c
new file mode 100644
index 0000000000000..e06f2606b41e7
--- /dev/null
+++ b/kernel/bpf/exception.c
@@ -0,0 +1,379 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf_ids.h>
+#include <linux/filter.h>
+#include <linux/slab.h>
+#include "exception.h"
+
+#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
+
+#define MIN_BPF_CLEANUP_INFO_SIZE 12
+#define MAX_CLEANUP_INFO_REC_SIZE 252 /* as MAX_FUNCINFO_REC_SIZE */
+
+int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
+ bpfptr_t uattr)
+{
+ u32 krec_size = sizeof(struct bpf_cleanup_info);
+ u32 i, nrec, urec_size, min_size, prev_end = 0;
+ struct bpf_cleanup_info *krecord;
+ bpfptr_t urecord;
+ int ret = -EINVAL;
+
+ nrec = attr->cleanup_info_cnt;
+ if (!nrec)
+ return 0;
+ if (nrec > env->prog->len) {
+ verbose(env, "cleanup info has %u records for %u instructions\n",
+ nrec, env->prog->len);
+ return -EINVAL;
+ }
+
+ urec_size = attr->cleanup_info_rec_size;
+ if (urec_size < MIN_BPF_CLEANUP_INFO_SIZE ||
+ urec_size > MAX_CLEANUP_INFO_REC_SIZE ||
+ urec_size % sizeof(u32)) {
+ verbose(env, "invalid cleanup info rec size %u\n", urec_size);
+ return -EINVAL;
+ }
+
+ krecord = kvcalloc(nrec, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ if (!krecord)
+ return -ENOMEM;
+
+ min_size = min_t(u32, krec_size, urec_size);
+ urecord = make_bpfptr(attr->cleanup_info, uattr.is_kernel);
+ for (i = 0; i < nrec; i++) {
+ struct bpf_subprog_info *sb, *se, *sl;
+ struct bpf_cleanup_info *rec = &krecord[i];
+
+ /*
+ * A record longer than the kernel's is taken only if the rest
+ * is zero. Unlike func_info, no size is handed back for the
+ * loader to zero the rest and retry: a field this kernel does
+ * not know could change what a pad does.
+ */
+ ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
+ if (ret) {
+ if (ret == -E2BIG)
+ verbose(env, "nonzero tailing record in cleanup info\n");
+ goto err_free;
+ }
+
+ if (copy_from_bpfptr(rec, urecord, min_size)) {
+ ret = -EFAULT;
+ goto err_free;
+ }
+ bpfptr_add(&urecord, urec_size);
+
+ ret = -EINVAL;
+ if (rec->begin_off >= rec->end_off) {
+ verbose(env, "cleanup_info[%u]: begin %u >= end %u\n",
+ i, rec->begin_off, rec->end_off);
+ goto err_free;
+ }
+ if (rec->begin_off < prev_end) {
+ verbose(env,
+ "cleanup_info[%u]: range [%u,%u) is unsorted or overlaps the previous record\n",
+ i, rec->begin_off, rec->end_off);
+ goto err_free;
+ }
+ prev_end = rec->end_off;
+
+ sb = bpf_find_containing_subprog(env, rec->begin_off);
+ se = bpf_find_containing_subprog(env, rec->end_off - 1);
+ sl = bpf_find_containing_subprog(env, rec->landing_pad_off);
+ if (!sb || !se || !sl) {
+ verbose(env, "cleanup_info[%u]: offset out of range\n", i);
+ goto err_free;
+ }
+ if (sb != se || sb != sl) {
+ verbose(env,
+ "cleanup_info[%u]: range/landing pad span multiple subprogs\n",
+ i);
+ goto err_free;
+ }
+ /*
+ * A zero opcode is the second half of a 16-byte insn, not an
+ * insn. end_off is exclusive, so it may be one past the last.
+ */
+ if (!env->prog->insnsi[rec->begin_off].code ||
+ !env->prog->insnsi[rec->landing_pad_off].code ||
+ (rec->end_off < env->prog->len &&
+ !env->prog->insnsi[rec->end_off].code)) {
+ verbose(env, "cleanup_info[%u]: points at invalid insn\n", i);
+ goto err_free;
+ }
+ }
+
+ /* Reject a landing pad inside any call-site range, its own included. */
+ ret = -EINVAL;
+ for (i = 0; i < nrec; i++) {
+ u32 pad = krecord[i].landing_pad_off;
+ u32 l = 0, r = nrec;
+
+ while (l < r) {
+ u32 m = l + (r - l) / 2;
+
+ if (pad < krecord[m].begin_off) {
+ r = m;
+ } else if (pad >= krecord[m].end_off) {
+ l = m + 1;
+ } else {
+ verbose(env,
+ "cleanup_info[%u]: landing pad %u is inside the call-site range of cleanup_info[%u]\n",
+ i, pad, m);
+ goto err_free;
+ }
+ }
+ }
+
+ env->cleanup_info = krecord;
+ env->cleanup_info_cnt = nrec;
+ return 0;
+
+err_free:
+ kvfree(krecord);
+ return ret;
+}
+
+BTF_ID_LIST_SINGLE(bpf_unwind_id, func, bpf_unwind)
+BTF_ID_LIST_SINGLE(bpf_unwind_resume_id, func, bpf_unwind_resume)
+
+int bpf_exc_check_callback(struct bpf_verifier_env *env, int subprog)
+{
+ if (!env->subprog_info[subprog].might_unwind)
+ return 0;
+
+ verbose(env, "subprog %d may unwind and is used as a callback\n", subprog);
+ return -EINVAL;
+}
+
+static int reject_throw(struct bpf_verifier_env *env)
+{
+ u32 i;
+
+ for (i = 0; i < env->prog->len; i++) {
+ if (!bpf_is_throw_kfunc(&env->prog->insnsi[i]))
+ continue;
+ verbose(env,
+ "exception cleanup cannot be combined with bpf_throw at insn %u\n",
+ i);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+void bpf_exc_mark_call_sites(struct bpf_verifier_env *env)
+{
+ u32 i, j;
+
+ for (i = 0; i < env->cleanup_info_cnt; i++) {
+ struct bpf_cleanup_info *rec = &env->cleanup_info[i];
+
+ for (j = rec->begin_off; j < rec->end_off; j++) {
+ struct bpf_insn *insn = &env->prog->insnsi[j];
+
+ if (!bpf_pseudo_call(insn) && !bpf_is_callx(insn) &&
+ !bpf_is_unwind_kfunc(insn))
+ continue;
+ env->insn_aux_data[j].cleanup_pad = rec->landing_pad_off + 1;
+ }
+ }
+}
+
+bool bpf_prog_may_unwind(const struct bpf_verifier_env *env)
+{
+ u32 i;
+
+ for (i = 0; i < env->subprog_cnt; i++)
+ if (env->subprog_info[i].might_unwind)
+ return true;
+ return false;
+}
+
+int bpf_exc_check_prog(struct bpf_verifier_env *env)
+{
+ int err;
+
+ if (bpf_prog_is_offloaded(env->prog->aux)) {
+ verbose(env,
+ "exception cleanup is not supported for offloaded programs\n");
+ return -EINVAL;
+ }
+ if (!bpf_jit_supports_cleanup_pads() || !env->prog->jit_requested) {
+ verbose(env,
+ "exception cleanup needs a JIT that can dispatch landing pads\n");
+ return -EOPNOTSUPP;
+ }
+ if (env->ops->gen_epilogue) {
+ verbose(env,
+ "exception cleanup is not supported for a program with an epilogue\n");
+ return -EOPNOTSUPP;
+ }
+ if (env->exception_callback_subprog) {
+ verbose(env,
+ "exception cleanup cannot be combined with an exception callback\n");
+ return -EINVAL;
+ }
+ err = reject_throw(env);
+ if (err)
+ return err;
+ env->prog->jit_required = 1;
+ return 0;
+}
+
+bool bpf_is_unwind_kfunc(const struct bpf_insn *insn)
+{
+ return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+ insn->imm == bpf_unwind_id[0];
+}
+
+bool bpf_is_unwind_resume_kfunc(const struct bpf_insn *insn)
+{
+ return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+ insn->imm == bpf_unwind_resume_id[0];
+}
+
+static bool unwinding(const struct bpf_verifier_state *state)
+{
+ u32 i;
+
+ for (i = 0; i <= state->curframe; i++)
+ if (state->frame[i]->in_pad)
+ return true;
+ return false;
+}
+
+int bpf_exc_check_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
+{
+ bool in_pad = cur_func(env)->in_pad;
+ u32 i = env->insn_idx;
+ const char *why = NULL;
+
+ if (unwinding(env->cur_state)) {
+ if (bpf_is_unwind_kfunc(insn)) {
+ verbose(env, "insn %u starts a second unwind while one is in flight\n", i);
+ return -EINVAL;
+ }
+ if (bpf_pseudo_call(insn)) {
+ int subprog = bpf_find_subprog(env, i + insn->imm + 1);
+
+ if (bpf_subprog_is_global(env, subprog) &&
+ env->subprog_info[subprog].might_unwind) {
+ verbose(env,
+ "insn %u calls global subprog %d, which can unwind while an unwind is in flight\n",
+ i, subprog);
+ return -EINVAL;
+ }
+ }
+ }
+
+ if (!in_pad)
+ return 0;
+
+ if (insn->code == (BPF_JMP | BPF_EXIT)) {
+ verbose(env,
+ "exit at insn %u ends a landing pad: a catch pad is not supported yet, only cleanup pads that resume\n",
+ i);
+ return -EINVAL;
+ }
+ if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call)
+ why = "is a tail call, which replaces the frame";
+ else if (BPF_CLASS(insn->code) == BPF_LD &&
+ (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND))
+ why = "is a BPF_LD_[ABS|IND], which can leave through the epilogue";
+ else if (insn_is_gotox(insn))
+ why = "is an indirect jump, which nothing a compiler frontend emits in a pad needs";
+
+ if (!why)
+ return 0;
+
+ verbose(env, "insn %u %s, and is in a landing pad\n", i, why);
+ return -EINVAL;
+}
+
+int bpf_exc_pad_of_call(struct bpf_verifier_env *env, u32 idx)
+{
+ u32 pad = env->insn_aux_data[idx].cleanup_pad;
+
+ return pad ? (int)pad - 1 : -1;
+}
+
+/*
+ * The record covering @ip, which is a return address: the call it belongs to
+ * is the instruction before it, so a range matches on begin < ip <= end.
+ */
+const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip)
+{
+ const struct bpf_exception_info *exc = prog->aux->exc;
+ u32 l = 0, r = exc ? exc->nr_ranges : 0;
+
+ while (l < r) {
+ u32 m = l + (r - l) / 2;
+ const struct bpf_cleanup_range *rec = &exc->ranges[m];
+
+ if (ip <= rec->begin)
+ r = m;
+ else if (ip > rec->end)
+ l = m + 1;
+ else
+ return rec;
+ }
+ return NULL;
+}
+
+int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt)
+{
+ struct bpf_cleanup_range *ranges;
+ struct bpf_exception_info *exc;
+
+ exc = kzalloc_obj(struct bpf_exception_info, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ ranges = kvcalloc(cnt, sizeof(*ranges), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ if (!exc || !ranges) {
+ kfree(exc);
+ kvfree(ranges);
+ kvfree(recs);
+ return -ENOMEM;
+ }
+
+ exc->info = recs;
+ exc->nr_info = cnt;
+ exc->ranges = ranges;
+ /* Withheld until the JIT has filled the table in. */
+ exc->nr_ranges = 0;
+ aux->exc = exc;
+ return 0;
+}
+
+void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image)
+{
+ struct bpf_exception_info *exc = prog->aux->exc;
+ u32 i, n;
+
+ if (!exc)
+ return;
+
+ n = exc->nr_info;
+ for (i = 0; i < n; i++) {
+ const struct bpf_cleanup_info *rec = &exc->info[i];
+
+ exc->ranges[i].begin = (u64)(long)image + addrs[rec->begin_off];
+ exc->ranges[i].end = (u64)(long)image + addrs[rec->end_off];
+ exc->ranges[i].pad = (u64)(long)image + addrs[rec->landing_pad_off];
+ }
+ exc->nr_ranges = n;
+}
+
+void bpf_exc_free_info(struct bpf_prog_aux *aux)
+{
+ struct bpf_exception_info *exc = aux->exc;
+
+ if (!exc)
+ return;
+ kvfree(exc->ranges);
+ kvfree(exc->info);
+ kfree(exc);
+ aux->exc = NULL;
+}
diff --git a/kernel/bpf/exception.h b/kernel/bpf/exception.h
new file mode 100644
index 0000000000000..09bbcd0a09de3
--- /dev/null
+++ b/kernel/bpf/exception.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#ifndef __BPF_EXCEPTION_H
+#define __BPF_EXCEPTION_H
+
+#include <linux/bpfptr.h>
+#include <linux/types.h>
+
+union bpf_attr;
+struct bpf_verifier_env;
+struct bpf_insn;
+struct bpf_cleanup_info;
+struct bpf_cleanup_range;
+struct bpf_prog;
+struct bpf_prog_aux;
+
+int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
+ bpfptr_t uattr);
+void bpf_exc_mark_call_sites(struct bpf_verifier_env *env);
+int bpf_exc_check_prog(struct bpf_verifier_env *env);
+bool bpf_prog_may_unwind(const struct bpf_verifier_env *env);
+int bpf_exc_pad_of_call(struct bpf_verifier_env *env, u32 idx);
+bool bpf_is_unwind_kfunc(const struct bpf_insn *insn);
+bool bpf_is_unwind_resume_kfunc(const struct bpf_insn *insn);
+int bpf_exc_check_callback(struct bpf_verifier_env *env, int subprog);
+int bpf_exc_check_insn(struct bpf_verifier_env *env, struct bpf_insn *insn);
+int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt);
+const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip);
+
+#endif /* __BPF_EXCEPTION_H */
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 608621d7f225c..dd29ead32cf33 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -9,6 +9,7 @@
#include <linux/sched/signal.h>
#include <net/xdp.h>
#include "disasm.h"
+#include "exception.h"
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
@@ -244,11 +245,20 @@ static void adjust_insn_aux_data(struct bpf_verifier_env *env,
data[i].non_stack_access =
data[off + cnt - 1].non_stack_access;
data[off + cnt - 1].non_stack_access = false;
+ data[i].cleanup_pad = data[off + cnt - 1].cleanup_pad;
+ data[off + cnt - 1].cleanup_pad = 0;
+ data[i].arg_prog = data[off + cnt - 1].arg_prog;
+ data[off + cnt - 1].arg_prog = 0;
} else if (bpf_is_mem_insn(insn + i)) {
data[i].non_stack_access = true;
}
}
+ if (env->cleanup_info_cnt)
+ for (i = 0; i < prog_len; i++)
+ if (data[i].cleanup_pad > off + 1)
+ data[i].cleanup_pad += cnt - 1;
+
/*
* Last slot instruction could be a newly generated
* BPF_ST/BPF_LDX/BPF_STX, systematically mark it for non-stack access
@@ -604,6 +614,7 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
unsigned int orig_prog_len = env->prog->len;
int err;
+ u32 i;
if (bpf_rewrite_must_abort())
return -EINTR;
@@ -634,6 +645,17 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
sizeof(*aux_data) * (orig_prog_len - off - cnt));
env->insn_aux_data_len -= cnt;
+ if (env->cleanup_info_cnt) {
+ for (i = 0; i < env->insn_aux_data_len; i++) {
+ u32 pad = aux_data[i].cleanup_pad;
+
+ if (pad > off + cnt)
+ aux_data[i].cleanup_pad = pad - cnt;
+ else if (pad > off)
+ aux_data[i].cleanup_pad = 0;
+ }
+ }
+
return 0;
}
@@ -707,13 +729,63 @@ static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env)
}
}
+/*
+ * The walk sends a frame that a callee unwinds through to its epilogue, which
+ * the x86 JIT emits at the first exit, so keep one. A frame that only unwinds
+ * may have none: put one after its last insn.
+ */
+static int keep_subprog_exits(struct bpf_verifier_env *env)
+{
+ struct bpf_insn patch[2] = { {}, BPF_EXIT_INSN() };
+ struct bpf_prog *new_prog;
+ u32 i, j;
+
+ for (i = 0; i < env->subprog_cnt; i++) {
+ u32 start, end;
+ bool found = false;
+
+ if (!env->subprog_info[i].might_unwind)
+ continue;
+ start = env->subprog_info[i].start;
+ if (!env->insn_aux_data[start].seen)
+ continue;
+
+ end = env->subprog_info[i + 1].start;
+ for (j = end; j-- > start; ) {
+ if (env->prog->insnsi[j].code == (BPF_JMP | BPF_EXIT)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ struct bpf_insn_aux_data aux = env->insn_aux_data[end - 1];
+
+ patch[0] = env->prog->insnsi[end - 1];
+ new_prog = bpf_patch_insn_data(env, end - 1, patch, 2);
+ if (!new_prog)
+ return -ENOMEM;
+ env->prog = new_prog;
+ env->insn_aux_data[end - 1] = aux;
+ memset(&env->insn_aux_data[end], 0, sizeof(aux));
+ j = end;
+ }
+ env->insn_aux_data[j].seen = env->pass_cnt;
+ }
+ return 0;
+}
+
int bpf_opt_remove_dead_code(struct bpf_verifier_env *env)
{
- struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
- int insn_cnt = env->prog->len;
- int i, err;
+ struct bpf_insn_aux_data *aux_data;
+ int i, insn_cnt, err;
keep_funcs_with_addr_taken(env);
+ err = keep_subprog_exits(env);
+ if (err)
+ return err;
+
+ aux_data = env->insn_aux_data;
+ insn_cnt = env->prog->len;
for (i = 0; i < insn_cnt; i++) {
int j;
@@ -739,7 +811,7 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env)
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
bool is_may_goto_0, is_ja;
- int i, err;
+ int i, j, err;
for (i = 0; i < insn_cnt; i++) {
is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
@@ -750,6 +822,11 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env)
if (aux[i].indirect_target)
continue;
+ if (env->cleanup_info_cnt)
+ for (j = 0; j < insn_cnt; j++)
+ if (aux[j].cleanup_pad == i + 1)
+ aux[j].cleanup_pad = i + 2;
+
err = verifier_remove_insns(env, i, 1);
if (err)
return err;
@@ -1249,6 +1326,40 @@ static int resolve_func_ptrs(struct bpf_verifier_env *env, struct bpf_prog *prog
return 0;
}
+static int exc_info_for_subprog(struct bpf_verifier_env *env, struct bpf_prog *sub,
+ u32 start, u32 end)
+{
+ struct bpf_cleanup_info *recs;
+ u32 i, cnt = 0;
+
+ if (!env->cleanup_info_cnt)
+ return 0;
+
+ for (i = start; i < end; i++) {
+ if (env->insn_aux_data[i].cleanup_pad)
+ cnt++;
+ }
+ if (!cnt)
+ return 0;
+
+ recs = kvmalloc_array(cnt, sizeof(*recs), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ if (!recs)
+ return -ENOMEM;
+
+ for (i = start, cnt = 0; i < end; i++) {
+ u32 pad = env->insn_aux_data[i].cleanup_pad;
+
+ if (!pad)
+ continue;
+ pad--;
+ recs[cnt].begin_off = i - start;
+ recs[cnt].end_off = i - start + 1;
+ recs[cnt].landing_pad_off = pad - start;
+ cnt++;
+ }
+ return bpf_exc_attach_info(sub->aux, recs, cnt);
+}
+
static int jit_subprogs(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog, **func, *tmp;
@@ -1256,7 +1367,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
struct bpf_map *map_ptr;
struct bpf_insn *insn;
void *old_bpf_func;
- int err, num_exentries;
+ int err, exc_err, num_exentries;
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
@@ -1383,9 +1494,15 @@ static int jit_subprogs(struct bpf_verifier_env *env)
func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
+ func[i]->aux->might_unwind = env->subprog_info[i].might_unwind;
func[i]->aux->token = prog->aux->token;
if (!i)
func[i]->aux->exception_boundary = env->seen_exception;
+ exc_err = exc_info_for_subprog(env, func[i], subprog_start, subprog_end);
+ if (exc_err) {
+ err = exc_err;
+ goto out_free;
+ }
func[i] = bpf_int_jit_compile(env, func[i]);
if (!func[i]->jited) {
err = -ENOTSUPP;
@@ -1495,6 +1612,9 @@ static int jit_subprogs(struct bpf_verifier_env *env)
prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
prog->aux->exception_boundary = func[0]->aux->exception_boundary;
prog->aux->stack_arg_sp_adjust = func[0]->aux->stack_arg_sp_adjust;
+ prog->aux->exc = func[0]->aux->exc;
+ func[0]->aux->exc = NULL;
+ prog->aux->epilogue_ip = func[0]->aux->epilogue_ip;
bpf_prog_jit_attempt_done(prog);
return 0;
out_free:
@@ -1720,6 +1840,48 @@ static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off,
return cnt + tail_cnt;
}
+/*
+ * Follow each bpf_unwind() call with 'r0 = 0; exit', or with
+ * 'r0 = 0; goto pad' where a record covers the call.
+ */
+int bpf_exc_patch_unwind_calls(struct bpf_verifier_env *env)
+{
+ int insn_cnt = env->prog->len;
+ struct bpf_insn insn_buf[3];
+ struct bpf_prog *new_prog;
+ int i, off, delta = 0;
+
+ if (!bpf_prog_may_unwind(env))
+ return 0;
+
+ for (i = 0; i < insn_cnt; i++) {
+ int call = i + delta, pad;
+ struct bpf_insn *insn = env->prog->insnsi + call;
+
+ if (!bpf_is_unwind_kfunc(insn))
+ continue;
+
+ insn_buf[0] = *insn;
+ insn_buf[1] = BPF_MOV64_IMM(BPF_REG_0, 0);
+ insn_buf[2] = BPF_EXIT_INSN();
+ pad = bpf_exc_pad_of_call(env, call);
+ if (pad >= 0) {
+ /* The goto is at call + 2; a pad after the call moves down by 2. */
+ if (pad > call)
+ pad += 2;
+ off = pad - (call + 3);
+ insn_buf[2] = off == (s16)off ? BPF_JMP_A(off) : BPF_JMP32_A(off);
+ }
+
+ new_prog = bpf_patch_insn_data(env, call, insn_buf, 3);
+ if (!new_prog)
+ return -ENOMEM;
+ delta += 2;
+ env->prog = new_prog;
+ }
+ return 0;
+}
+
/* Do various post-verification rewrites in a single program pass.
* These rewrites simplify JIT and interpreter implementations.
*/
@@ -2112,6 +2274,25 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
goto next_insn;
if (insn->src_reg == BPF_PSEUDO_CALL)
goto next_insn;
+ if (bpf_is_unwind_resume_kfunc(insn)) {
+ /*
+ * A pad's resume is just the frame returning, to
+ * where bpf_unwind() pointed its return address: its
+ * caller's pad or epilogue, or the kernel from the main
+ * program. The verifier checked this exit with r0 a
+ * known zero, so return zero.
+ */
+ insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, 0);
+ insn_buf[1] = BPF_EXIT_INSN();
+ cnt = 2;
+ new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
+ if (!new_prog)
+ return -ENOMEM;
+ delta += cnt - 1;
+ env->prog = prog = new_prog;
+ insn = new_prog->insnsi + i + delta;
+ goto next_insn;
+ }
if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
ret = bpf_fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
if (ret)
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 439370d73cc5f..1cf7b712854b8 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -29,8 +29,10 @@
#include <linux/task_work.h>
#include <linux/irq_work.h>
#include <linux/buildid.h>
+#include <linux/kprobes.h>
#include "../../lib/kstrtox.h"
+#include "exception.h"
/* If kernel subsystem is allowing eBPF programs to call this function,
* inside its own verifier_ops->get_func_proto() callback it should return
@@ -3424,6 +3426,71 @@ static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
return false;
}
+struct bpf_unwind_ctx {
+ const struct bpf_prog_aux *aux;
+ u32 cnt;
+};
+
+static bool bpf_unwind_ip_in(const struct bpf_prog *prog, u64 ip)
+{
+ u64 start = (u64)(long)prog->bpf_func;
+
+ return ip > start && ip <= start + prog->jited_len;
+}
+
+/*
+ * The function of the calling program that @ip returns into, looked up in the
+ * program itself: its kallsyms entries can go while an instance still runs.
+ * The main function is the outer program, which holds its table and epilogue.
+ */
+static struct bpf_prog *bpf_unwind_find_prog(const struct bpf_prog_aux *aux, u64 ip)
+{
+ u32 i;
+
+ for (i = 1; i < aux->func_cnt; i++)
+ if (bpf_unwind_ip_in(aux->func[i], ip))
+ return aux->func[i];
+ return bpf_unwind_ip_in(aux->prog, ip) ? aux->prog : NULL;
+}
+
+static bool bpf_unwind_rewrite(void *cookie, u64 ip, u64 sp, u64 bp, u64 *ra)
+{
+ const struct bpf_cleanup_range *rec;
+ struct bpf_unwind_ctx *ctx = cookie;
+ struct bpf_prog *prog;
+
+ prog = bpf_unwind_find_prog(ctx->aux, ip);
+ if (!prog)
+ return !ctx->cnt;
+ ctx->cnt++;
+
+ /*
+ * The frame that called bpf_unwind(): bpf_exc_patch_unwind_calls()
+ * put 'r0 = 0' and a jump to its pad, or an exit, after the call,
+ * so leave its return address alone and let it go on there. The pad
+ * then starts with r0 at a known zero.
+ */
+ if (ctx->cnt == 1)
+ return bpf_is_subprog(prog);
+
+ rec = bpf_exc_pad_for_ip(prog, ip);
+ *ra = rec ? rec->pad : prog->aux->epilogue_ip;
+
+ return bpf_is_subprog(prog);
+}
+
+/*
+ * @aux is the calling program's, supplied by the verifier (KF_IMPLICIT_ARGS):
+ * programs call bpf_unwind() with no arguments.
+ */
+__bpf_kfunc notrace void bpf_unwind(struct bpf_prog_aux *aux)
+{
+ struct bpf_unwind_ctx ctx = { .aux = aux };
+
+ arch_bpf_stack_walk_ra(bpf_unwind_rewrite, &ctx);
+}
+NOKPROBE_SYMBOL(bpf_unwind);
+
__bpf_kfunc void bpf_throw(u64 cookie)
{
struct bpf_throw_ctx ctx = {};
@@ -3445,6 +3512,15 @@ __bpf_kfunc void bpf_throw(u64 cookie)
WARN(1, "A call to BPF exception callback should never return\n");
}
+__bpf_kfunc void bpf_unwind_resume(void *ptr__ign)
+{
+ /*
+ * Not meant to run: every call of this kfunc is to be lowered to
+ * 'r0 = 0; exit' by the verifier.
+ */
+ WARN_ONCE(1, "exception cleanup resume was not lowered to a return\n");
+}
+
__bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags)
{
struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
@@ -5115,6 +5191,8 @@ BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_throw)
+BTF_ID_FLAGS(func, bpf_unwind, KF_IMPLICIT_ARGS)
+BTF_ID_FLAGS(func, bpf_unwind_resume)
#ifdef CONFIG_BPF_EVENTS
BTF_ID_FLAGS(func, bpf_send_signal_task)
#endif
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index e657e6d95408f..8b7ee551ff6f5 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -8,6 +8,8 @@
#include <linux/slab.h>
#include <linux/sort.h>
+#include "exception.h"
+
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
/*
@@ -404,6 +406,18 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
succ->items[succ->cnt++] = exit_idx;
}
+ /*
+ * A covered call can also leave through its landing pad. Only a call to
+ * a subprog or to bpf_unwind() is covered, so the two entries of
+ * env->succ are enough.
+ */
+ if (unlikely(env->cleanup_info_cnt)) {
+ int pad = bpf_exc_pad_of_call(env, idx);
+
+ if (pad >= 0)
+ succ->items[succ->cnt++] = pad;
+ }
+
return succ;
}
@@ -530,7 +544,8 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp
* Slot is alive if it is read before q->insn_idx in current func instance,
* or if for some outer func instance:
* - alive before callsite if callsite calls callback or is callx, otherwise
- * - alive after callsite
+ * - alive after callsite,
+ * - or alive at the landing pad a cleanup record gives the callsite
*/
struct live_stack_query *q = &env->liveness->live_stack_query;
struct func_instance *instance, *curframe_instance;
@@ -565,6 +580,13 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp
alive = callee_stack_access_at_callsite(env, callsite)
? is_live_before(instance, callsite, rel, half_spi)
: is_live_before(instance, callsite + 1, rel, half_spi);
+
+ if (!alive && unlikely(env->cleanup_info_cnt)) {
+ int pad = bpf_exc_pad_of_call(env, callsite);
+
+ if (pad >= 0)
+ alive = is_live_before(instance, pad, rel, half_spi);
+ }
if (alive)
return true;
}
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index 953700822fa73..93b5cc3a2f02d 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -201,9 +201,13 @@ static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_stat
* c. A checkpoint is reached and matched. Checkpoints are created by
* is_state_visited(), which calls maybe_enter_scc(), which allocates
* bpf_scc_visit instances for checkpoints within SCCs.
- * (c) is the only case that can reach this point.
+ * d. An unwind returns from frame 0, ending the path at a call or at
+ * the unwinding insn, which may be in an SCC as a top-level
+ * BPF_EXIT is not. Like (b), it leaves nothing to exit.
+ * (c) and (d), and a speculative path, are the only ways to reach
+ * this point.
*/
- if (!st->speculative) {
+ if (!st->speculative && !st->unwind_exit) {
verifier_bug(env, "scc exit: no visit info for call chain %s",
format_callchain(env, callchain));
return -EFAULT;
@@ -995,6 +999,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat
if (!old->no_stack_arg_load && cur->no_stack_arg_load)
return false;
+ if (old->in_pad != cur->in_pad)
+ return false;
+
for (i = 0; i < MAX_BPF_REG; i++)
if (((1 << i) & live_regs) &&
!regsafe(env, &old->regs[i], &cur->regs[i],
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 654f896af265b..10e0a693a06d5 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -2948,7 +2948,7 @@ int __init __used bpf_multi_func(void) { return 0; }
BTF_ID_LIST_GLOBAL_SINGLE(bpf_multi_func_btf_id, func, bpf_multi_func)
/* last field in 'union bpf_attr' used by this command */
-#define BPF_PROG_LOAD_LAST_FIELD keyring_id
+#define BPF_PROG_LOAD_LAST_FIELD cleanup_info_cnt
static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
{
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index ddfa0c6d2755f..505ecb8de2211 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -39,6 +39,7 @@
#include "diagnostics.h"
#include "disasm.h"
+#include "exception.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
@@ -1750,6 +1751,7 @@ int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
return err;
dst_state->speculative = src->speculative;
dst_state->in_sleepable = src->in_sleepable;
+ dst_state->unwind_exit = src->unwind_exit;
dst_state->curframe = src->curframe;
dst_state->branches = src->branches;
dst_state->parent = src->parent;
@@ -3315,6 +3317,54 @@ static void find_subprog_properties(struct bpf_verifier_env *env)
}
}
+static int subprog_falls_through(struct bpf_verifier_env *env, int subprog, int idx)
+{
+ verbose(env, "last insn is not an exit or jmp\n");
+ bpf_diag_program_structure(
+ env, idx, "subprogram can fall through",
+ "End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
+ "Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
+ subprog, idx);
+ return -EINVAL;
+}
+
+/*
+ * Put an exit after a call that ends a subprog, so that nothing from the CFG
+ * walk on has to know a subprog can end that way. check_subprogs() only lets
+ * such a call be to a callee that never returns, so do_check() never reaches
+ * the exit.
+ */
+static int add_exits_after_final_calls(struct bpf_verifier_env *env)
+{
+ struct bpf_insn patch[2] = { {}, BPF_EXIT_INSN() };
+ struct bpf_prog *new_prog;
+ int i, j;
+
+ for (i = 0; i < env->subprog_cnt; i++) {
+ int last = env->subprog_info[i + 1].start - 1;
+ struct bpf_insn *insn = &env->prog->insnsi[last];
+
+ if (!bpf_pseudo_call(insn) && !bpf_pseudo_kfunc_call(insn))
+ continue;
+ patch[0] = *insn;
+ new_prog = bpf_patch_insn_data(env, last, patch, 2);
+ if (!new_prog)
+ return -ENOMEM;
+ env->prog = new_prog;
+ /* The patch moved the call's aux data, orig_idx included, to the exit. */
+ env->insn_aux_data[last].orig_idx = env->insn_aux_data[last + 1].orig_idx;
+ /* The patch does not adjust the call itself for a callee after it. */
+ insn = &new_prog->insnsi[last];
+ if (bpf_pseudo_call(insn) && insn->imm >= 0)
+ insn->imm++;
+ /* Nor does it move the exits check_subprogs() found after it. */
+ for (j = i + 1; j < env->subprog_cnt; j++)
+ if (env->subprog_info[j].exit_idx != U32_MAX)
+ env->subprog_info[j].exit_idx++;
+ }
+ return 0;
+}
+
static int check_subprogs(struct bpf_verifier_env *env)
{
int i, subprog_start, subprog_end, off, cur_subprog = 0;
@@ -3354,26 +3404,44 @@ static int check_subprogs(struct bpf_verifier_env *env)
/*
* To avoid fall-through from one subprog into another,
* the last insn of the subprog should be either exit
- * or unconditional jump back or bpf_throw call.
+ * or unconditional jump back or a call that does not
+ * return, checked below.
*/
if (code != (BPF_JMP | BPF_EXIT) &&
code != (BPF_JMP32 | BPF_JA) &&
code != (BPF_JMP | BPF_JA) &&
- !insn_is_gotox(&insn[i])) {
- verbose(env, "last insn is not an exit or jmp\n");
- bpf_diag_program_structure(
- env, i, "subprogram can fall through",
- "End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
- "Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
- cur_subprog, i);
- return -EINVAL;
- }
+ !insn_is_gotox(&insn[i]) &&
+ !bpf_pseudo_call(&insn[i]) &&
+ !bpf_pseudo_kfunc_call(&insn[i]))
+ return subprog_falls_through(env, cur_subprog, i);
subprog_start = subprog_end;
cur_subprog++;
if (cur_subprog < env->subprog_cnt)
subprog_end = subprog[cur_subprog + 1].start;
}
}
+
+ /*
+ * A compiler ends a subprog with a call only if the callee never
+ * returns. Refuse any other final call.
+ */
+ for (i = 0; i < env->subprog_cnt; i++) {
+ int last = subprog[i + 1].start - 1, callee;
+
+ if (bpf_pseudo_kfunc_call(&insn[last])) {
+ if (!bpf_is_unwind_kfunc(&insn[last]) &&
+ !bpf_is_unwind_resume_kfunc(&insn[last]))
+ return subprog_falls_through(env, i, last);
+ continue;
+ }
+ if (!bpf_pseudo_call(&insn[last]))
+ continue;
+ callee = bpf_find_subprog(env, last + insn[last].imm + 1);
+ if (bpf_subprog_is_global(env, callee) ||
+ subprog[callee].exit_idx != U32_MAX ||
+ subprog[callee].has_tail_call || subprog[callee].has_ld_abs)
+ return subprog_falls_through(env, i, last);
+ }
return 0;
}
@@ -5954,6 +6022,17 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
}
}
+ /*
+ * A private stack keeps its frame pointer in %r9 on x86-64, restored
+ * by a pop after the call that an unwind skips. A frame resumed at a
+ * pad then addresses its stack through a stale pointer, and a frame
+ * sent to its epilogue instead pops its callee-saved registers one
+ * slot off. Do not use a private stack for any program that can
+ * unwind, on every arch for now.
+ */
+ if (env->cleanup_info_cnt || bpf_prog_may_unwind(env))
+ priv_stack_mode = NO_PRIV_STACK;
+
if (priv_stack_mode == PRIV_STACK_UNKNOWN)
priv_stack_mode = bpf_enable_priv_stack(env->prog);
@@ -11189,6 +11268,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
* callbacks
*/
env->subprog_info[subprog].is_cb = true;
+ err = bpf_exc_check_callback(env, subprog);
+ if (err)
+ return err;
+
if (bpf_pseudo_kfunc_call(insn) &&
!is_callback_calling_kfunc(insn->imm)) {
verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
@@ -11251,6 +11334,8 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
static int process_bpf_exit_full(struct bpf_verifier_env *env,
bool *do_print_state, bool exception_exit);
+static int process_bpf_unwind(struct bpf_verifier_env *env, int *insn_idx);
+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state);
/*
* Call of a static subprog. The callee is verified in the context of
@@ -15563,6 +15648,16 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
if (bpf_is_throw_kfunc(insn))
return process_bpf_exit_full(env, NULL, true);
+ if (bpf_is_unwind_kfunc(insn))
+ return process_bpf_unwind(env, insn_idx_p);
+ if (bpf_is_unwind_resume_kfunc(insn)) {
+ if (!cur_func(env)->in_pad) {
+ verbose(env, "resume at insn %d is not in a landing pad\n", insn_idx);
+ return -EINVAL;
+ }
+ return unwind_frames(env, NULL);
+ }
+
return 0;
}
@@ -19673,6 +19768,136 @@ enum {
INSN_IDX_UPDATED = 2,
};
+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state)
+{
+ struct bpf_verifier_state *state = env->cur_state;
+ u32 frameno = state->curframe;
+ struct bpf_func_state *callee, *caller;
+ int err, pad;
+
+ while (state->curframe) {
+ callee = cur_func(env);
+ caller = state->frame[state->curframe - 1];
+ pad = bpf_exc_pad_of_call(env, callee->callsite);
+ /* The caller is at its call now, not at this frame's insn. */
+ state->insn_idx = callee->callsite;
+ /* As on a return: the frame's dynptrs, and their slices, go with it. */
+ err = destroy_dynptrs_in_stack_slots(env, callee, 0,
+ callee->allocated_stack / BPF_REG_SIZE - 1);
+ if (err)
+ return err;
+
+ account_processed_insns(env, callee, caller);
+ free_func_state(callee);
+ state->frame[state->curframe--] = NULL;
+ invalidate_outgoing_stack_args(env, caller);
+ if (pad < 0)
+ continue;
+
+ /*
+ * Mark the unwinding insn with the frame it ran in: backtracking
+ * from the pad comes back to that insn and goes on in that frame.
+ */
+ err = bpf_push_jmp_history(env, state, INSN_F_UNWIND, 0, frameno, NULL, 0);
+ if (err)
+ return err;
+ clear_caller_saved_regs(env, caller->regs);
+ mark_reg_unknown(env, caller->regs, BPF_REG_0);
+ caller->in_pad = true;
+ env->insn_idx = pad;
+ if (do_print_state)
+ *do_print_state = true;
+ return INSN_IDX_UPDATED;
+ }
+
+ /* A resource still held leaks; report it at the unwinding insn. */
+ err = check_resource_leak(env, false, true, "bpf_unwind");
+ if (err)
+ return err;
+ /*
+ * No pad: the program ends at frame 0's call into the popped frames, or
+ * at the unwinding insn itself if none was popped. Mark the unwinding
+ * insn as above; an unwinding global call needs that when backtracking
+ * from the end reaches it.
+ */
+ err = bpf_push_jmp_history(env, state, INSN_F_UNWIND, 0, frameno, NULL, 0);
+ if (err)
+ return err;
+ /*
+ * Then, in an entry of its own, a jump from the unwinding insn to the
+ * end, so backtracking from the end goes back to the unwinding insn.
+ */
+ env->cur_hist_ent = NULL;
+ env->prev_insn_idx = env->insn_idx;
+ env->insn_idx = state->insn_idx;
+ err = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0);
+ if (err)
+ return err;
+ /*
+ * The end may be in a loop: unlike a plain exit, the path can stop
+ * inside an SCC with no checkpoint there.
+ */
+ state->unwind_exit = true;
+
+ /* The call clobbered r1-r5, and r0 holds the zero the fixups put there. */
+ clear_caller_saved_regs(env, cur_regs(env));
+ __mark_reg_const_zero(env, &cur_regs(env)[BPF_REG_0]);
+ /*
+ * A global subprog verified on its own returns here too. One that
+ * returns in R0:R2 has R2 checked as well, though its caller never
+ * reads either: it resumes at a pad or an epilogue.
+ */
+ if (cur_func(env)->subprogno &&
+ bpf_ret_reg_pair(env, cur_func(env)->subprogno))
+ mark_reg_unknown(env, cur_regs(env), BPF_REG_2);
+
+ return process_bpf_exit_full(env, do_print_state, false);
+}
+
+static int process_global_call_unwind(struct bpf_verifier_env *env,
+ int call_idx, bool *do_print_state)
+{
+ const struct bpf_insn *insn = &env->prog->insnsi[call_idx];
+ int subprog = bpf_find_subprog(env, call_idx + insn->imm + 1);
+ struct bpf_verifier_state *branch;
+ struct bpf_func_state *frame;
+ int pad;
+
+ if (!bpf_subprog_is_global(env, subprog) ||
+ !env->subprog_info[subprog].might_unwind)
+ return 0;
+
+ /* The call returning normally is walked later. */
+ branch = push_stack(env, call_idx + 1, call_idx, false);
+ if (IS_ERR(branch))
+ return PTR_ERR(branch);
+
+ pad = bpf_exc_pad_of_call(env, call_idx);
+ if (pad < 0)
+ return unwind_frames(env, do_print_state);
+ frame = cur_func(env);
+ clear_caller_saved_regs(env, frame->regs);
+ mark_reg_unknown(env, frame->regs, BPF_REG_0);
+ frame->in_pad = true;
+ env->insn_idx = pad;
+ *do_print_state = true;
+ return INSN_IDX_UPDATED;
+}
+
+static int process_bpf_unwind(struct bpf_verifier_env *env, int *insn_idx)
+{
+ struct bpf_func_state *frame = cur_func(env);
+ int pad = bpf_exc_pad_of_call(env, *insn_idx);
+
+ if (pad < 0)
+ return unwind_frames(env, NULL);
+ clear_caller_saved_regs(env, frame->regs);
+ mark_reg_unknown(env, frame->regs, BPF_REG_0);
+ frame->in_pad = true;
+ *insn_idx = pad;
+ return INSN_IDX_UPDATED;
+}
+
static int process_bpf_exit_full(struct bpf_verifier_env *env,
bool *do_print_state,
bool exception_exit)
@@ -19864,6 +20089,12 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
u8 class = BPF_CLASS(insn->code);
+ if (unlikely(env->cleanup_info_cnt)) {
+ err = bpf_exc_check_insn(env, insn);
+ if (err)
+ return err;
+ }
+
switch (class) {
case BPF_ALU:
case BPF_ALU64:
@@ -19934,8 +20165,14 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
cur_func(env)->no_stack_arg_load = true;
if (bpf_is_callx(insn))
return check_func_callx(env, insn, &env->insn_idx);
- if (insn->src_reg == BPF_PSEUDO_CALL)
- return check_func_call(env, insn, &env->insn_idx);
+ if (insn->src_reg == BPF_PSEUDO_CALL) {
+ int call_idx = env->insn_idx;
+
+ err = check_func_call(env, insn, &env->insn_idx);
+ if (err)
+ return err;
+ return process_global_call_unwind(env, call_idx, do_print_state);
+ }
if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
return check_kfunc_call(env, insn, &env->insn_idx);
return check_helper_call(env, insn, &env->insn_idx);
@@ -22134,6 +22371,23 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
prog_extension ? "Extension" : "Tracing");
return -EINVAL;
}
+ /*
+ * A trampoline that calls its target stays as a frame between a
+ * subprog and its caller, and bpf_unwind() cannot walk past it:
+ * the frames above it would carry on after their calls rather
+ * than at their landing pads or epilogues. fentry leaves no
+ * frame, and the main program's caller is above where the walk
+ * stops.
+ */
+ if (aux->func && subprog && aux->func[subprog]->aux->might_unwind &&
+ (prog->expected_attach_type == BPF_TRACE_FEXIT ||
+ prog->expected_attach_type == BPF_MODIFY_RETURN ||
+ prog->expected_attach_type == BPF_TRACE_FSESSION)) {
+ bpf_log(log,
+ "Cannot attach fexit, fmod_ret or fsession to %s, which can unwind\n",
+ tname);
+ return -EINVAL;
+ }
conservative = aux->func_info_aux[subprog].unreliable;
if (prog_extension) {
if (conservative) {
@@ -23431,15 +23685,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
env->arena_scalar = attr->prog_flags & BPF_F_ARENA_SCALAR;
- env->explored_states = kvzalloc_objs(struct list_head,
- state_htab_size(env),
- GFP_KERNEL_ACCOUNT);
- ret = -ENOMEM;
- if (!env->explored_states)
- goto skip_full_check;
-
- for (i = 0; i < state_htab_size(env); i++)
- INIT_LIST_HEAD(&env->explored_states[i]);
INIT_LIST_HEAD(&env->free_list);
/* Prepare BTF and func_info needed to discover all subprograms. */
@@ -23468,6 +23713,13 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
+ ret = bpf_exc_check_info(env, attr, uattr);
+ if (ret < 0)
+ goto skip_full_check;
+
+ /* The CFG needs an edge from a call in a cleanup range to its pad. */
+ bpf_exc_mark_call_sites(env);
+
/* Validate instructions and resolve the program's referenced resources. */
ret = check_and_resolve_insns(env);
if (ret < 0)
@@ -23483,6 +23735,24 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
+ /*
+ * After everything above has recorded insn offsets, so the patch
+ * adjusts them, and before an offloaded program's per-insn state.
+ */
+ ret = add_exits_after_final_calls(env);
+ if (ret < 0)
+ goto skip_full_check;
+
+ env->explored_states = kvzalloc_objs(struct list_head,
+ state_htab_size(env),
+ GFP_KERNEL_ACCOUNT);
+ ret = -ENOMEM;
+ if (!env->explored_states)
+ goto skip_full_check;
+
+ for (i = 0; i < state_htab_size(env); i++)
+ INIT_LIST_HEAD(&env->explored_states[i]);
+
if (bpf_prog_is_offloaded(env->prog->aux)) {
ret = bpf_prog_offload_verifier_prep(env->prog);
if (ret)
@@ -23505,6 +23775,12 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret)
goto skip_full_check;
+ if (env->cleanup_info_cnt || bpf_prog_may_unwind(env)) {
+ ret = bpf_exc_check_prog(env);
+ if (ret)
+ goto skip_full_check;
+ }
+
ret = bpf_compute_const_regs(env);
if (ret < 0)
goto skip_full_check;
@@ -23599,6 +23875,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = bpf_convert_ctx_accesses(env);
+ if (ret == 0)
+ ret = bpf_exc_patch_unwind_calls(env);
+
if (ret == 0)
ret = bpf_do_misc_fixups(env);
@@ -23713,6 +23992,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
kvfree(env->func_ptrs);
bpf_diag_free(env);
kvfree(env->idoms);
+ kvfree(env->cleanup_info);
kvfree(env);
return ret;
}
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index 6f70db7515dd4..9d7439c96e52e 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -1708,6 +1708,9 @@ union bpf_attr {
* verification.
*/
__s32 keyring_id;
+ __aligned_u64 cleanup_info; /* exception cleanup table */
+ __u32 cleanup_info_rec_size; /* userspace bpf_cleanup_info size */
+ __u32 cleanup_info_cnt; /* number of bpf_cleanup_info records */
};
struct { /* anonymous struct used by BPF_OBJ_* commands */
@@ -7669,6 +7672,17 @@ struct bpf_line_info {
__u32 line_col;
};
+/*
+ * One record of an exception cleanup table: calls in [begin_off, end_off)
+ * that unwind resume at landing_pad_off. All three are instruction offsets
+ * in the program as loaded.
+ */
+struct bpf_cleanup_info {
+ __u32 begin_off;
+ __u32 end_off;
+ __u32 landing_pad_off;
+};
+
struct bpf_spin_lock {
__u32 val;
};
diff --git a/tools/lib/bpf/bpf.c b/tools/lib/bpf/bpf.c
index b49822d212aed..b4031f62bdee5 100644
--- a/tools/lib/bpf/bpf.c
+++ b/tools/lib/bpf/bpf.c
@@ -295,7 +295,7 @@ int bpf_prog_load(enum bpf_prog_type prog_type,
const struct bpf_insn *insns, size_t insn_cnt,
struct bpf_prog_load_opts *opts)
{
- const size_t attr_sz = offsetofend(union bpf_attr, keyring_id);
+ const size_t attr_sz = offsetofend(union bpf_attr, cleanup_info_cnt);
void *finfo = NULL, *linfo = NULL;
const char *func_info, *line_info;
__u32 log_size, log_level, attach_prog_fd, attach_btf_obj_fd;
@@ -370,6 +370,10 @@ int bpf_prog_load(enum bpf_prog_type prog_type,
attr.fd_array = ptr_to_u64(OPTS_GET(opts, fd_array, NULL));
attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0);
+ attr.cleanup_info = ptr_to_u64(OPTS_GET(opts, cleanup_info, NULL));
+ attr.cleanup_info_rec_size = OPTS_GET(opts, cleanup_info_rec_size, 0);
+ attr.cleanup_info_cnt = OPTS_GET(opts, cleanup_info_cnt, 0);
+
if (log_level) {
attr.log_buf = ptr_to_u64(log_buf);
attr.log_size = log_size;
diff --git a/tools/lib/bpf/bpf.h b/tools/lib/bpf/bpf.h
index 826d9cc9ab65d..64699e0e4e1a8 100644
--- a/tools/lib/bpf/bpf.h
+++ b/tools/lib/bpf/bpf.h
@@ -128,9 +128,17 @@ struct bpf_prog_load_opts {
/* if set, provides the length of fd_array */
__u32 fd_array_cnt;
+
+ /* exception cleanup table: cleanup_info_cnt records of
+ * cleanup_info_rec_size bytes each (struct bpf_cleanup_info),
+ * holding instruction indices into insns
+ */
+ __u32 cleanup_info_cnt;
+ const void *cleanup_info;
+ __u32 cleanup_info_rec_size;
size_t :0;
};
-#define bpf_prog_load_opts__last_field fd_array_cnt
+#define bpf_prog_load_opts__last_field cleanup_info_rec_size
LIBBPF_API int bpf_prog_load(enum bpf_prog_type prog_type,
const char *prog_name, const char *license,
diff --git a/tools/lib/bpf/gen_loader.c b/tools/lib/bpf/gen_loader.c
index 251392aa8b41f..f07727c5b5fb8 100644
--- a/tools/lib/bpf/gen_loader.c
+++ b/tools/lib/bpf/gen_loader.c
@@ -994,13 +994,15 @@ static void cleanup_relos(struct bpf_gen *gen, int insns)
cleanup_core_relo(gen);
}
-/* Convert func, line, and core relo info blobs to target endianness */
+/* Convert func, line, core relo and cleanup info blobs to target endianness */
static void info_blob_bswap(struct bpf_gen *gen, int func_info, int line_info,
- int core_relos, struct bpf_prog_load_opts *load_attr)
+ int core_relos, int cleanup_info,
+ struct bpf_prog_load_opts *load_attr)
{
struct bpf_func_info *fi = gen->data_start + func_info;
struct bpf_line_info *li = gen->data_start + line_info;
struct bpf_core_relo *cr = gen->data_start + core_relos;
+ struct bpf_cleanup_info *ci = gen->data_start + cleanup_info;
int i;
for (i = 0; i < load_attr->func_info_cnt; i++)
@@ -1011,6 +1013,9 @@ static void info_blob_bswap(struct bpf_gen *gen, int func_info, int line_info,
for (i = 0; i < gen->core_relo_cnt; i++)
bpf_core_relo_bswap(cr++);
+
+ for (i = 0; i < load_attr->cleanup_info_cnt; i++)
+ bpf_cleanup_info_bswap(ci++);
}
void bpf_gen__prog_load(struct bpf_gen *gen,
@@ -1024,10 +1029,15 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
load_attr->line_info_rec_size;
int core_relo_tot_sz = gen->core_relo_cnt *
sizeof(struct bpf_core_relo);
+ int cleanup_info_tot_sz = load_attr->cleanup_info_cnt *
+ load_attr->cleanup_info_rec_size;
int prog_load_attr, license_off, insns_off, func_info, line_info, core_relos;
int attr_size = offsetofend(union bpf_attr, core_relo_rec_size);
+ int cleanup_info;
union bpf_attr attr;
+ if (load_attr->cleanup_info_cnt)
+ attr_size = offsetofend(union bpf_attr, cleanup_info_cnt);
memset(&attr, 0, attr_size);
/* add license string to blob of bytes */
license_off = add_data(gen, license, strlen(license) + 1);
@@ -1074,9 +1084,17 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
core_relos, gen->core_relo_cnt,
sizeof(struct bpf_core_relo));
+ attr.cleanup_info_rec_size = tgt_endian(load_attr->cleanup_info_rec_size);
+ attr.cleanup_info_cnt = tgt_endian(load_attr->cleanup_info_cnt);
+ cleanup_info = add_data(gen, load_attr->cleanup_info, cleanup_info_tot_sz);
+ pr_debug("gen: prog_load: cleanup_info: off %d cnt %u rec size %u\n",
+ cleanup_info, load_attr->cleanup_info_cnt,
+ load_attr->cleanup_info_rec_size);
+
/* convert all info blobs to target endianness */
if (gen->swapped_endian && !gen->error)
- info_blob_bswap(gen, func_info, line_info, core_relos, load_attr);
+ info_blob_bswap(gen, func_info, line_info, core_relos, cleanup_info,
+ load_attr);
libbpf_strlcpy(attr.prog_name, prog_name, sizeof(attr.prog_name));
prog_load_attr = add_data(gen, &attr, attr_size);
@@ -1098,6 +1116,11 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
/* populate union bpf_attr with a pointer to core_relos */
emit_rel_store(gen, attr_field(prog_load_attr, core_relos), core_relos);
+ /* with no records, attr ends before cleanup_info: nothing to store */
+ if (load_attr->cleanup_info_cnt)
+ emit_rel_store(gen, attr_field(prog_load_attr, cleanup_info),
+ cleanup_info);
+
/* populate union bpf_attr fd_array with a pointer to data where map_fds are saved */
emit_rel_store(gen, attr_field(prog_load_attr, fd_array), gen->fd_array);
diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index cb09ded907732..d227dcc7ef0bb 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -516,6 +516,11 @@ struct bpf_program {
void *line_info;
__u32 line_info_rec_size;
__u32 line_info_cnt;
+
+ struct bpf_cleanup_info *cleanup_info;
+ __u32 cleanup_info_rec_size;
+ __u32 cleanup_info_cnt;
+
__u32 prog_flags;
__u8 hash[SHA256_DIGEST_LENGTH];
@@ -572,6 +577,7 @@ struct bpf_struct_ops {
* are loaded with BPF_F_ARENA_SCALAR.
*/
#define ARENA_DATA_SEC ".arena.data"
+#define CLEANUP_SEC ".bpf_cleanup"
enum libbpf_map_type {
LIBBPF_MAP_UNSPEC,
@@ -710,6 +716,25 @@ struct elf_sec_desc {
Elf_Data *data;
};
+#define CLEANUP_REC_FIELDS (sizeof(struct bpf_cleanup_info) / sizeof(__u32))
+
+/* Index of each field of struct bpf_cleanup_info, read as an array of __u32. */
+enum {
+ CLEANUP_REC_BEGIN,
+ CLEANUP_REC_END,
+ CLEANUP_REC_PAD,
+};
+
+/*
+ * One (begin, end, landing_pad) triple from .bpf_cleanup, each field resolved
+ * from its relocation to a section and an instruction index within it. Final
+ * indices wait for subprogram placement, which differs per main program.
+ */
+struct cleanup_raw_rec {
+ int sec_idx[CLEANUP_REC_FIELDS];
+ size_t insn_idx[CLEANUP_REC_FIELDS];
+};
+
struct elf_state {
int fd;
const void *obj_buf;
@@ -729,6 +754,8 @@ struct elf_state {
bool has_st_ops;
int arena_data_shndx;
int jumptables_data_shndx;
+ Elf_Data *cleanup_data;
+ int cleanup_shndx;
};
struct usdt_manager;
@@ -817,6 +844,9 @@ struct bpf_object {
void *jumptables_data;
size_t jumptables_data_sz;
+ struct cleanup_raw_rec *cleanup_recs;
+ size_t cleanup_rec_cnt;
+
struct {
struct bpf_program *prog;
unsigned int sym_off;
@@ -874,6 +904,7 @@ void bpf_program__unload(struct bpf_program *prog)
zfree(&prog->func_info);
zfree(&prog->line_info);
zfree(&prog->subprogs);
+ zfree(&prog->cleanup_info);
}
static void bpf_program__exit(struct bpf_program *prog)
@@ -1639,6 +1670,7 @@ static struct bpf_object *bpf_object__new(const char *path,
obj->efile.obj_buf_sz = obj_buf_sz;
obj->efile.btf_maps_shndx = -1;
obj->efile.arena_data_shndx = -1;
+ obj->efile.cleanup_shndx = -1;
obj->kconfig_map_idx = -1;
obj->arena_map_idx = -1;
@@ -1658,6 +1690,7 @@ static void bpf_object__elf_finish(struct bpf_object *obj)
obj->efile.ehdr = NULL;
obj->efile.symbols = NULL;
obj->efile.arena_data = NULL;
+ obj->efile.cleanup_data = NULL;
zfree(&obj->efile.secs);
obj->efile.sec_cnt = 0;
@@ -4275,6 +4308,9 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
sec_desc->shdr = sh;
sec_desc->data = data;
obj->efile.has_st_ops = true;
+ } else if (strcmp(name, CLEANUP_SEC) == 0) {
+ obj->efile.cleanup_data = data;
+ obj->efile.cleanup_shndx = idx;
} else if (strcmp(name, ARENA_SEC) == 0) {
obj->efile.arena_data = data;
obj->efile.arena_data_shndx = idx;
@@ -4300,8 +4336,9 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
/*
* Only do relo for section with exec instructions,
- * struct_ops, maps, and read-only data that might
- * have pointers to functions.
+ * struct_ops, maps, read-only data that might have
+ * pointers to functions, and the exception cleanup
+ * table.
*/
if (!section_have_execinstr(obj, targ_sec_idx) &&
!(obj->data_in_arena &&
@@ -4315,6 +4352,7 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
+ strcmp(name, ".rel" CLEANUP_SEC) &&
strcmp(name, ".rel" MAPS_ELF_SEC)) {
pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
idx, name, targ_sec_idx,
@@ -5099,6 +5137,219 @@ static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
return NULL;
}
+static int bpf_object_init_cleanup_info(struct bpf_object *obj)
+{
+ Elf_Data *data = obj->efile.cleanup_data;
+ size_t i, nrels, nslots, nrecs;
+ struct cleanup_raw_rec *recs;
+ Elf_Data *relo = NULL;
+ const char *vals;
+ int ret = 0;
+ bool native;
+
+ if (!data || obj->efile.cleanup_shndx < 0 || !data->d_size)
+ return 0;
+
+ native = is_native_endianness(obj);
+
+ for (i = 0; i < obj->efile.sec_cnt; i++) {
+ struct elf_sec_desc *sd = &obj->efile.secs[i];
+
+ if (sd->sec_type == SEC_RELO && sd->shdr &&
+ sd->shdr->sh_info == (Elf64_Word)obj->efile.cleanup_shndx) {
+ relo = sd->data;
+ break;
+ }
+ }
+ if (!relo) {
+ pr_warn("%s present without relocations\n", CLEANUP_SEC);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+ if (data->d_size % sizeof(struct bpf_cleanup_info)) {
+ pr_warn("%s size %zu is not a multiple of the record size %zu\n",
+ CLEANUP_SEC, data->d_size, sizeof(struct bpf_cleanup_info));
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+
+ vals = data->d_buf;
+ nslots = data->d_size / sizeof(__u32);
+ nrecs = data->d_size / sizeof(struct bpf_cleanup_info);
+
+ recs = calloc(nrecs, sizeof(*recs));
+ if (!recs)
+ return -ENOMEM;
+ for (i = 0; i < nslots; i++)
+ recs[i / CLEANUP_REC_FIELDS].sec_idx[i % CLEANUP_REC_FIELDS] = -1;
+
+ /* One relocation per 4-byte field, naming the section it points into. */
+ nrels = relo->d_size / sizeof(Elf64_Rel);
+ for (i = 0; i < nrels; i++) {
+ Elf64_Rel *rel = elf_rel_by_idx(relo, i);
+ Elf64_Sym *sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
+ size_t type = ELF64_R_TYPE(rel->r_info);
+ size_t slot = rel->r_offset / sizeof(__u32);
+ struct cleanup_raw_rec *rec;
+ size_t off;
+ __u32 val;
+
+ if (type != R_BPF_64_NODYLD32 && type != R_BPF_64_ABS32) {
+ pr_warn("%s: relocation %zu has unexpected type %zu\n",
+ CLEANUP_SEC, i, type);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ if (!sym || slot >= nslots || rel->r_offset % sizeof(__u32)) {
+ pr_warn("%s: bad relocation %zu\n", CLEANUP_SEC, i);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ /*
+ * The addend lives in the section data, which libelf leaves in
+ * the object's byte order; a non-section symbol additionally
+ * contributes its own value. The section is only byte aligned.
+ */
+ memcpy(&val, vals + slot * sizeof(val), sizeof(val));
+ off = (native ? val : bswap_32(val)) + sym->st_value;
+ if (off % BPF_INSN_SZ) {
+ pr_warn("%s: field %zu offset %zu is not instruction aligned\n",
+ CLEANUP_SEC, slot, off);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ rec = &recs[slot / CLEANUP_REC_FIELDS];
+ if (rec->sec_idx[slot % CLEANUP_REC_FIELDS] >= 0) {
+ pr_warn("%s: field %zu has more than one relocation\n",
+ CLEANUP_SEC, slot);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ rec->sec_idx[slot % CLEANUP_REC_FIELDS] = sym->st_shndx;
+ rec->insn_idx[slot % CLEANUP_REC_FIELDS] = off / BPF_INSN_SZ;
+ }
+
+ for (i = 0; i < nslots; i++) {
+ if (recs[i / CLEANUP_REC_FIELDS].sec_idx[i % CLEANUP_REC_FIELDS] < 0) {
+ pr_warn("%s: field %zu has no relocation\n", CLEANUP_SEC, i);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ }
+
+ obj->cleanup_recs = recs;
+ obj->cleanup_rec_cnt = nrecs;
+ return 0;
+out:
+ free(recs);
+ return ret;
+}
+
+static int cmp_cleanup_info(const void *a, const void *b)
+{
+ const struct bpf_cleanup_info *x = a, *y = b;
+
+ if (x->begin_off == y->begin_off)
+ return 0;
+ return x->begin_off < y->begin_off ? -1 : 1;
+}
+
+static int bpf_prog_collect_cleanup_info(struct bpf_object *obj,
+ struct bpf_program *prog)
+{
+ size_t i;
+ int j;
+
+ for (i = 0; i < obj->cleanup_rec_cnt; i++) {
+ struct cleanup_raw_rec *raw = &obj->cleanup_recs[i];
+ struct bpf_program *owner = NULL;
+ struct bpf_cleanup_info ci = {};
+ __u32 fields[CLEANUP_REC_FIELDS];
+ void *tmp;
+
+ for (j = 0; j < CLEANUP_REC_FIELDS; j++) {
+ size_t idx = raw->insn_idx[j], final;
+ struct bpf_program *p;
+
+ /*
+ * An exclusive end may name the instruction past the
+ * last of a function, so ask about the last one the
+ * range covers, the way the kernel does.
+ */
+ if (j == CLEANUP_REC_END) {
+ if (!idx) {
+ pr_warn("%s: record %zu ends at instruction 0\n",
+ CLEANUP_SEC, i);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+ idx--;
+ }
+
+ p = find_prog_by_sec_insn(obj, raw->sec_idx[j], idx);
+ if (!p && j == CLEANUP_REC_BEGIN) {
+ /*
+ * Code no function claims is an overridden weak
+ * function the linker kept: skip its records,
+ * as its relocations are.
+ */
+ pr_debug("%s: record %zu is in no function, probably an overridden weak function, skipping\n",
+ CLEANUP_SEC, i);
+ break;
+ }
+ if (!p) {
+ pr_warn("%s: record %zu field %d is not inside a function\n",
+ CLEANUP_SEC, i, j);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+ if (!owner) {
+ owner = p;
+ } else if (owner != p) {
+ pr_warn("%s: record %zu spans functions '%s' and '%s'\n",
+ CLEANUP_SEC, i, owner->name, p->name);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+
+ if (owner == prog) {
+ final = raw->insn_idx[j] - prog->sec_insn_off;
+ } else if (prog_is_subprog(obj, owner) && owner->sub_insn_off) {
+ /*
+ * sub_insn_off is where this subprogram was
+ * appended to the main program being relocated;
+ * zero means it is not part of it.
+ */
+ final = owner->sub_insn_off +
+ raw->insn_idx[j] - owner->sec_insn_off;
+ } else {
+ owner = NULL;
+ break;
+ }
+ fields[j] = final;
+ }
+ if (!owner)
+ continue;
+
+ ci.begin_off = fields[CLEANUP_REC_BEGIN];
+ ci.end_off = fields[CLEANUP_REC_END];
+ ci.landing_pad_off = fields[CLEANUP_REC_PAD];
+
+ tmp = libbpf_reallocarray(prog->cleanup_info, prog->cleanup_info_cnt + 1,
+ sizeof(*prog->cleanup_info));
+ if (!tmp)
+ return -ENOMEM;
+ prog->cleanup_info = tmp;
+ prog->cleanup_info_rec_size = sizeof(struct bpf_cleanup_info);
+ prog->cleanup_info[prog->cleanup_info_cnt++] = ci;
+
+ pr_debug("prog '%s': cleanup region [%u,%u) -> landing pad %u\n",
+ prog->name, ci.begin_off, ci.end_off, ci.landing_pad_off);
+ }
+
+ if (!prog->cleanup_info_cnt)
+ return 0;
+
+ qsort(prog->cleanup_info, prog->cleanup_info_cnt,
+ sizeof(*prog->cleanup_info), cmp_cleanup_info);
+ return 0;
+}
+
static int
bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
{
@@ -8197,6 +8448,13 @@ static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_pat
return err;
}
}
+
+ err = bpf_prog_collect_cleanup_info(obj, prog);
+ if (err) {
+ pr_warn("prog '%s': failed to collect cleanup info: %s\n",
+ prog->name, errstr(err));
+ return err;
+ }
}
for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i];
@@ -8561,6 +8819,9 @@ static int bpf_object__collect_relos(struct bpf_object *obj)
return -LIBBPF_ERRNO__INTERNAL;
}
+ if (idx == obj->efile.cleanup_shndx)
+ continue;
+
if (obj->efile.secs[idx].sec_type == SEC_RODATA)
err = bpf_object__collect_rodata_relos(obj, shdr, data);
else if (obj->efile.secs[idx].sec_type == SEC_DATA)
@@ -8856,6 +9117,11 @@ static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog
load_attr.line_info_rec_size = prog->line_info_rec_size;
load_attr.line_info_cnt = prog->line_info_cnt;
}
+ if (prog->cleanup_info_cnt) {
+ load_attr.cleanup_info = prog->cleanup_info;
+ load_attr.cleanup_info_cnt = prog->cleanup_info_cnt;
+ load_attr.cleanup_info_rec_size = prog->cleanup_info_rec_size;
+ }
load_attr.log_level = log_level;
load_attr.prog_flags = prog->prog_flags;
/* the program accesses its data in arena through plain numbers */
@@ -9187,6 +9453,23 @@ static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_s
}
}
+/*
+ * LLVM terminates a cleanup landing pad with a call to _Unwind_Resume, the
+ * base unwind ABI's entry point for carrying an unwind on once a frame's
+ * cleanups have run. The kernel knows it as bpf_unwind_resume. Any other
+ * extern, and a variable of that name, is looked up by @name unchanged.
+ */
+static const char *kern_extern_name(const struct bpf_object *obj,
+ const struct extern_desc *ext, const char *name)
+{
+ const char *essent = ext->essent_name ?: ext->name;
+
+ if (!btf_is_func(btf__type_by_id(obj->btf, ext->btf_id)) ||
+ strcmp(essent, "_Unwind_Resume"))
+ return name;
+ return "bpf_unwind_resume";
+}
+
static int bpf_program_record_relos(struct bpf_program *prog)
{
struct bpf_object *obj = prog->obj;
@@ -9195,6 +9478,7 @@ static int bpf_program_record_relos(struct bpf_program *prog)
for (i = 0; i < prog->nr_reloc; i++) {
struct reloc_desc *relo = &prog->reloc_desc[i];
struct extern_desc *ext = &obj->externs[relo->ext_idx];
+ const char *name;
int kind;
switch (relo->type) {
@@ -9203,14 +9487,14 @@ static int bpf_program_record_relos(struct bpf_program *prog)
continue;
kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
BTF_KIND_VAR : BTF_KIND_FUNC;
- bpf_gen__record_extern(obj->gen_loader, ext->name,
- ext->is_weak, !ext->ksym.type_id,
- true, kind, relo->insn_idx);
+ name = kern_extern_name(obj, ext, ext->name);
+ bpf_gen__record_extern(obj->gen_loader, name, ext->is_weak,
+ !ext->ksym.type_id, true, kind, relo->insn_idx);
break;
case RELO_EXTERN_CALL:
- bpf_gen__record_extern(obj->gen_loader, ext->name,
- ext->is_weak, false, false, BTF_KIND_FUNC,
- relo->insn_idx);
+ name = kern_extern_name(obj, ext, ext->name);
+ bpf_gen__record_extern(obj->gen_loader, name, ext->is_weak, false,
+ false, BTF_KIND_FUNC, relo->insn_idx);
break;
case RELO_CORE: {
struct bpf_core_relo cr = {
@@ -9442,6 +9726,7 @@ static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf,
err = err ? : bpf_object__init_maps(obj, opts);
err = err ? : bpf_object_init_progs(obj, opts);
err = err ? : bpf_object__collect_relos(obj);
+ err = err ? : bpf_object_init_cleanup_info(obj);
if (err)
goto out;
@@ -9684,17 +9969,24 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
struct module_btf *mod_btf = NULL;
const struct btf_type *kern_func;
struct btf *kern_btf = NULL;
+ const char *local_name, *kern_name;
int ret;
local_func_proto_id = ext->ksym.type_id;
- kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
- &mod_btf);
+ local_name = ext->essent_name ?: ext->name;
+ kern_name = kern_extern_name(obj, ext, local_name);
+
+ kfunc_id = find_ksym_btf_id(obj, kern_name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
if (kfunc_id < 0) {
if (kfunc_id == -ESRCH && ext->is_weak)
return 0;
- pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
- ext->name);
+ if (kern_name != local_name)
+ pr_warn("extern (func ksym) '%s' ('%s' in the kernel): not found in kernel or module BTFs\n",
+ ext->name, kern_name);
+ else
+ pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
+ ext->name);
return kfunc_id;
}
@@ -9707,9 +9999,14 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
if (ext->is_weak)
return 0;
- pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
- ext->name, local_func_proto_id,
- mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
+ if (kern_name != local_name)
+ pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with '%s' in %s [%d]\n",
+ ext->name, local_func_proto_id, kern_name,
+ mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
+ else
+ pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
+ ext->name, local_func_proto_id,
+ mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
return -EINVAL;
}
@@ -10572,6 +10869,9 @@ void bpf_object__close(struct bpf_object *obj)
zfree(&obj->jumptables_data);
obj->jumptables_data_sz = 0;
+ zfree(&obj->cleanup_recs);
+ obj->cleanup_rec_cnt = 0;
+
for (i = 0; i < obj->jumptable_map_cnt; i++)
close(obj->jumptable_maps[i].fd);
zfree(&obj->jumptable_maps);
@@ -10981,6 +11281,19 @@ int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts
attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
}
+ /* exception cleanup table */
+ info = OPTS_GET(opts, cleanup_info, NULL);
+ info_cnt = OPTS_GET(opts, cleanup_info_cnt, 0);
+ info_rec_size = OPTS_GET(opts, cleanup_info_rec_size, 0);
+ if (!!info != !!info_cnt || !!info != !!info_rec_size) {
+ pr_warn("prog '%s': cleanup_info, cleanup_info_cnt, and cleanup_info_rec_size must all be specified or all omitted\n",
+ prog->name);
+ return libbpf_err(-EINVAL);
+ }
+ attr.cleanup_info = info ?: prog->cleanup_info;
+ attr.cleanup_info_cnt = info ? info_cnt : prog->cleanup_info_cnt;
+ attr.cleanup_info_rec_size = info ? info_rec_size : prog->cleanup_info_rec_size;
+
/* Logging is caller-controlled; no fallback to prog/obj log settings */
attr.log_buf = OPTS_GET(opts, log_buf, NULL);
attr.log_size = OPTS_GET(opts, log_size, 0);
diff --git a/tools/lib/bpf/libbpf_internal.h b/tools/lib/bpf/libbpf_internal.h
index 4e45dfacb548a..e17fc8f601995 100644
--- a/tools/lib/bpf/libbpf_internal.h
+++ b/tools/lib/bpf/libbpf_internal.h
@@ -56,6 +56,9 @@
#ifndef R_BPF_64_ABS32
#define R_BPF_64_ABS32 3
#endif
+#ifndef R_BPF_64_NODYLD32
+#define R_BPF_64_NODYLD32 4
+#endif
#ifndef R_BPF_64_32
#define R_BPF_64_32 10
#endif
@@ -570,6 +573,13 @@ static inline void bpf_core_relo_bswap(struct bpf_core_relo *i)
i->kind = bswap_32(i->kind);
}
+static inline void bpf_cleanup_info_bswap(struct bpf_cleanup_info *i)
+{
+ i->begin_off = bswap_32(i->begin_off);
+ i->end_off = bswap_32(i->end_off);
+ i->landing_pad_off = bswap_32(i->landing_pad_off);
+}
+
enum btf_field_iter_kind {
BTF_FIELD_ITER_IDS,
BTF_FIELD_ITER_STRS,
diff --git a/tools/lib/bpf/linker.c b/tools/lib/bpf/linker.c
index f3f71c452f007..911a649219a98 100644
--- a/tools/lib/bpf/linker.c
+++ b/tools/lib/bpf/linker.c
@@ -1036,7 +1036,8 @@ static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *se
size_t sym_type = ELF64_R_TYPE(relo->r_info);
if (sym_type != R_BPF_64_64 && sym_type != R_BPF_64_32 &&
- sym_type != R_BPF_64_ABS64 && sym_type != R_BPF_64_ABS32) {
+ sym_type != R_BPF_64_ABS64 && sym_type != R_BPF_64_ABS32 &&
+ sym_type != R_BPF_64_NODYLD32) {
pr_warn("ELF relo #%d in section #%zu has unexpected type %zu in %s\n",
i, sec->sec_idx, sym_type, obj->filename);
return -EINVAL;
@@ -2263,6 +2264,7 @@ static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *ob
if (ELF64_ST_TYPE(src_sym->st_info) == STT_SECTION) {
struct src_sec *sec = &obj->secs[src_sym->st_shndx];
struct bpf_insn *insn;
+ __u32 *val;
if (src_linked_sec->shdr->sh_flags & SHF_EXECINSTR) {
/* calls to the very first static function inside
@@ -2297,6 +2299,41 @@ static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *ob
if (linker->swapped_endian)
off = bswap_64(off);
memcpy(ptr, &off, sizeof(off));
+ } else if ((sym_type == R_BPF_64_NODYLD32 ||
+ sym_type == R_BPF_64_ABS32) &&
+ (sec->shdr->sh_flags & SHF_EXECINSTR)) {
+ /*
+ * A byte offset into a code section,
+ * stored in place. LLVM spells this
+ * relocation NODYLD32 and GNU as
+ * spells it ABS32; being bytes, the
+ * section's new start goes in as it
+ * is, not scaled the way a call's
+ * instruction index is above.
+ *
+ * The sanity check only checks the
+ * alignment of r_offset, and only for
+ * an executable section, and SHT_NOBITS
+ * has no raw_data, so check both here,
+ * bounding by subtraction so it cannot
+ * wrap.
+ */
+ if (!dst_linked_sec->raw_data ||
+ dst_linked_sec->sec_sz < (int)sizeof(*val) ||
+ dst_rel->r_offset % sizeof(*val) ||
+ dst_rel->r_offset >
+ (size_t)dst_linked_sec->sec_sz - sizeof(*val)) {
+ pr_warn("ELF relo #%d in section #%zu points outside the data of section '%s' in %s\n",
+ j, src_sec->sec_idx,
+ dst_linked_sec->sec_name,
+ obj->filename);
+ return -EINVAL;
+ }
+ val = dst_linked_sec->raw_data + dst_rel->r_offset;
+ if (linker->swapped_endian)
+ *val = bswap_32(bswap_32(*val) + sec->dst_off);
+ else
+ *val += sec->dst_off;
} else {
pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
return -EINVAL;
diff --git a/tools/testing/selftests/bpf/Makefile.skel b/tools/testing/selftests/bpf/Makefile.skel
index 06e297a17156c..d9cbe8ac85b76 100644
--- a/tools/testing/selftests/bpf/Makefile.skel
+++ b/tools/testing/selftests/bpf/Makefile.skel
@@ -40,7 +40,7 @@ LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c
# Generate both light skeleton and libbpf skeleton for these
LSKELS_EXTRA := test_ksyms_module.c test_ksyms_weak.c kfunc_call_test.c \
- kfunc_call_test_subprog.c test_global_percpu_data.c
+ kfunc_call_test_subprog.c test_global_percpu_data.c exceptions_cleanup.c
SKEL_BLACKLIST += $(LSKELS) $(LSKELS_SIGNED)
test_static_linked.skel.h-deps := test_static_linked1.bpf.o test_static_linked2.bpf.o
diff --git a/tools/testing/selftests/bpf/exceptions_cleanup.h b/tools/testing/selftests/bpf/exceptions_cleanup.h
new file mode 100644
index 0000000000000..84f21ecc630ab
--- /dev/null
+++ b/tools/testing/selftests/bpf/exceptions_cleanup.h
@@ -0,0 +1,48 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#ifndef __EXCEPTIONS_CLEANUP_H__
+#define __EXCEPTIONS_CLEANUP_H__
+
+/* progs/exceptions_cleanup.c: one bit per function that reports it ran. */
+#define RAN_FOO3_PREEMPT 0x1
+#define RAN_FOO2_RCU 0x2
+#define RAN_FOO1V_PREEMPT 0x4
+#define RAN_FOO2_DROP 0x8
+#define RAN_BUMP 0x10
+
+/* progs/exceptions_cleanup_shapes.c: one bit per landing pad. */
+#define RAN_REGS 0x1
+#define RAN_WIDE_REC 0x2
+#define RAN_RESUME_ALIAS 0x4
+#define RAN_NOP_PAD 0x8
+#define RAN_VAR_STACK 0x10
+#define RAN_GAP_INNER 0x20
+#define RAN_GAP_OUTER 0x40
+#define RAN_PREC_RESUME 0x80
+#define RAN_NO_EXIT_JA 0x100
+#define RAN_CALLX 0x200
+#define RAN_CALLEE_WRITE 0x400
+#define RAN_CALLEE_OFFSET 0x800
+#define RAN_GLOBAL_WRITE 0x1000
+#define RAN_THROUGH_GLOBAL 0x2000
+#define RAN_PAIR_GLOBAL 0x4000
+#define RAN_MOVE 0x8000
+#define RAN_NO_EXIT_LOOP 0x10000
+#define RAN_LAST_CALL 0x20000
+#define RAN_NO_TAIL 0x40000
+
+#define CLEANUP_REC(begin, end, landing_pad) \
+ ".pushsection .bpf_cleanup,\"a\",@progbits;" \
+ ".long " begin ";" \
+ ".long " end ";" \
+ ".long " landing_pad ";" \
+ ".popsection;"
+
+/* Set a bit in @pads_ran. */
+#define PAD_RAN(bit) \
+ "r1 = %[pads_ran] ll;" \
+ "r2 = *(u64 *)(r1 + 0);" \
+ "r2 |= " bit ";" \
+ "*(u64 *)(r1 + 0) = r2;"
+
+#endif /* __EXCEPTIONS_CLEANUP_H__ */
diff --git a/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c b/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c
new file mode 100644
index 0000000000000..b8581716bbd40
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <test_progs.h>
+#include "exceptions_cleanup.h"
+#include "exceptions_cleanup.skel.h"
+#include "exceptions_cleanup_fail.skel.h"
+#include "exceptions_cleanup_shapes.skel.h"
+#include "exceptions_cleanup_tracing.skel.h"
+#include "exceptions_cleanup.lskel.h"
+
+/* foo3 unwound: every frame that has a pad ran it. */
+#define PADS_FOO3_UNWOUND \
+ (RAN_FOO3_PREEMPT | RAN_FOO2_RCU | RAN_FOO1V_PREEMPT | RAN_FOO2_DROP)
+
+/* foo2 unwound after foo3 returned normally: foo3's pad must not run. */
+#define PADS_FOO2_UNWOUND \
+ (RAN_FOO2_RCU | RAN_FOO1V_PREEMPT | RAN_FOO2_DROP)
+
+static void run(struct exceptions_cleanup *skel, __u64 input, __u32 retval,
+ __u64 pads)
+{
+ __u64 ctx = 0;
+ int err;
+
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &ctx,
+ .ctx_size_in = sizeof(ctx),
+ );
+
+ skel->bss->input = input;
+ skel->bss->pads_ran = 0;
+ skel->bss->result = 0;
+
+ err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.entry), &topts);
+ if (!ASSERT_OK(err, "run"))
+ return;
+ ASSERT_EQ(topts.retval, retval, "retval");
+ /* bump() is not a landing pad; it sets its bit on every run. */
+ ASSERT_EQ(skel->bss->pads_ran, pads | RAN_BUMP, "pads_ran");
+}
+
+/*
+ * Tracing programs against foo1(), which an unwind passes through. fexit
+ * keeps a trampoline frame between foo1() and its caller that the unwind
+ * cannot walk past, so it is refused; fentry leaves none, so foo3 can still
+ * unwind through foo1() with it attached.
+ */
+static void test_tracing(struct exceptions_cleanup *tgt)
+{
+ struct exceptions_cleanup_tracing *skel;
+ int tgt_fd = bpf_program__fd(tgt->progs.entry);
+ char log[8192] = {};
+ int err;
+
+ LIBBPF_OPTS(bpf_object_open_opts, opts,
+ .kernel_log_buf = log,
+ .kernel_log_size = sizeof(log));
+
+ skel = exceptions_cleanup_tracing__open_opts(&opts);
+ if (!ASSERT_OK_PTR(skel, "tracer open"))
+ return;
+ bpf_program__set_autoload(skel->progs.fentry_unwinding_subprog, true);
+ err = bpf_program__set_attach_target(skel->progs.fentry_unwinding_subprog,
+ tgt_fd, "foo1");
+ if (!ASSERT_OK(err, "fentry target"))
+ goto out;
+ err = exceptions_cleanup_tracing__load(skel);
+ if (!ASSERT_OK(err, "fentry load"))
+ goto out;
+ err = exceptions_cleanup_tracing__attach(skel);
+ if (!ASSERT_OK(err, "fentry attach"))
+ goto out;
+ run(tgt, 101, 0, PADS_FOO3_UNWOUND);
+ ASSERT_EQ(skel->bss->fentry_hits, 1, "fentry_hits");
+ exceptions_cleanup_tracing__destroy(skel);
+
+ skel = exceptions_cleanup_tracing__open_opts(&opts);
+ if (!ASSERT_OK_PTR(skel, "tracer open"))
+ return;
+ bpf_program__set_autoload(skel->progs.fexit_unwinding_subprog, true);
+ err = bpf_program__set_attach_target(skel->progs.fexit_unwinding_subprog,
+ tgt_fd, "foo1");
+ if (!ASSERT_OK(err, "fexit target"))
+ goto out;
+ err = exceptions_cleanup_tracing__load(skel);
+ ASSERT_EQ(err, -EINVAL, "fexit load");
+ ASSERT_HAS_SUBSTR(log, "Cannot attach fexit, fmod_ret or fsession to foo1",
+ "fexit log");
+out:
+ exceptions_cleanup_tracing__destroy(skel);
+}
+
+static void test_light_skeleton(void)
+{
+ struct exceptions_cleanup_lskel *skel;
+ __u64 ctx = 0;
+ int err;
+
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &ctx,
+ .ctx_size_in = sizeof(ctx),
+ );
+
+ skel = exceptions_cleanup_lskel__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "light open_and_load"))
+ return;
+
+ /* foo3 unwinds, so every pad runs: the whole table has to arrive. */
+ skel->bss->input = 101;
+ err = bpf_prog_test_run_opts(skel->progs.entry.prog_fd, &topts);
+ if (!ASSERT_OK(err, "run"))
+ goto out;
+ ASSERT_EQ(topts.retval, 0, "retval");
+ ASSERT_EQ(skel->bss->pads_ran, PADS_FOO3_UNWOUND | RAN_BUMP,
+ "pads_ran");
+out:
+ exceptions_cleanup_lskel__destroy(skel);
+}
+
+void test_exceptions_cleanup(void)
+{
+ char log[8192] = {};
+
+ LIBBPF_OPTS(bpf_object_open_opts, opts,
+ .kernel_log_buf = log,
+ .kernel_log_size = sizeof(log));
+ struct exceptions_cleanup *skel;
+ int err;
+
+ skel = exceptions_cleanup__open_opts(&opts);
+ if (!ASSERT_OK_PTR(skel, "open"))
+ return;
+
+ err = exceptions_cleanup__load(skel);
+ if (err) {
+ if (err == -EOPNOTSUPP &&
+ strstr(log, "exception cleanup needs a JIT that can dispatch landing pads")) {
+ printf("%s:SKIP:JIT cannot dispatch exception cleanup landing pads\n",
+ __func__);
+ test__skip();
+ } else if (!ASSERT_OK(err, "load")) {
+ fprintf(stderr, "%s", log);
+ }
+ exceptions_cleanup__destroy(skel);
+ return;
+ }
+
+ /* No unwind: foo3 returns 1 ^ 1 == 0, foo2 adds one, no pad runs. */
+ if (test__start_subtest("no_unwind"))
+ run(skel, 1, 1, 0);
+
+ /* foo3 unwinds; every pad runs and entry returns zero. */
+ if (test__start_subtest("unwind_from_foo3"))
+ run(skel, 101, 0, PADS_FOO3_UNWOUND);
+
+ /*
+ * foo3 returns 2 ^ 1 == 3, so foo2 unwinds from its own second region;
+ * foo3's frame is long gone, so its pad must not run.
+ */
+ if (test__start_subtest("unwind_from_foo2"))
+ run(skel, 2, 0, PADS_FOO2_UNWOUND);
+
+ if (test__start_subtest("tracing_unwinding_subprog"))
+ test_tracing(skel);
+
+ exceptions_cleanup__destroy(skel);
+
+ if (test__start_subtest("light_skeleton"))
+ test_light_skeleton();
+
+ RUN_TESTS(exceptions_cleanup_fail);
+ RUN_TESTS(exceptions_cleanup_shapes);
+}
diff --git a/tools/testing/selftests/bpf/progs/bpf_misc.h b/tools/testing/selftests/bpf/progs/bpf_misc.h
index d7f706c3bc4af..f5baeb979cc22 100644
--- a/tools/testing/selftests/bpf/progs/bpf_misc.h
+++ b/tools/testing/selftests/bpf/progs/bpf_misc.h
@@ -107,6 +107,16 @@
* - POINTER_VALUE
* - TEST_DATA_LEN
* __retval_unpriv Same, but load program in unprivileged mode.
+ * __set_global Set a global variable of the program to a value before
+ * executing it. The variable has to be an int or an enum,
+ * live in .bss or .data and be four or eight bytes wide,
+ * and the value is a number or several joined by '|',
+ * without parentheses.
+ * __ret_global Execute the program and check that a global variable
+ * holds the given value afterwards, under the same rules.
+ * __set_global and __ret_global both make the loader run
+ * the program and check its return value; without
+ * __retval, the program must return 0.
*
* __description Text to be used for display and as an additional filter
* alias, while the original program name stays matchable.
@@ -167,6 +177,8 @@
#define __flag(flag) __test_tag("test_prog_flags=" #flag)
#define __retval(val) __test_tag("test_retval=" XSTR(val))
#define __retval_unpriv(val) __test_tag("test_retval_unpriv=" XSTR(val))
+#define __set_global(var, val) __test_tag("test_global_set=" #var ":" XSTR(val))
+#define __ret_global(var, val) __test_tag("test_global_ret=" #var ":" XSTR(val))
#define __auxiliary __test_tag("test_auxiliary")
#define __auxiliary_unpriv __test_tag("test_auxiliary_unpriv")
#define __btf_path(path) __test_tag("test_btf_path=" path)
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup.c
new file mode 100644
index 0000000000000..24523ee05acf8
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup.c
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "exceptions_cleanup.h"
+
+static __used __noinline void __kfunc_btf_anchor(void)
+{
+ bpf_unwind();
+ bpf_rcu_read_lock();
+ bpf_rcu_read_unlock();
+ bpf_preempt_disable();
+ bpf_preempt_enable();
+ bpf_unwind_resume(NULL);
+}
+
+__u64 input = 0;
+__u64 pads_ran = 0;
+__u64 result = 0;
+__u64 never = 0;
+
+static __used __noinline __u64 foo3(__u64 x)
+{
+ bpf_preempt_disable();
+ if (x > 100)
+ asm volatile (
+ "1:" "call bpf_unwind;" /* cleanup region */
+ "2:"
+ "goto 3f;"
+ "4:" /* landing pad */
+ /*
+ * r0 at pad entry is the zero the fixups put after the
+ * bpf_unwind() call. It is kept in a callee-saved
+ * register and handed to the resume, the way a
+ * compiler-emitted pad passes the exception pointer to
+ * _Unwind_Resume. The kfunc takes it and ignores it, and
+ * the two pads below do without the shuffle.
+ */
+ "r7 = r0;"
+ "call bpf_preempt_enable;"
+ PAD_RAN("%[ran]")
+ "r1 = r7;"
+ "call bpf_unwind_resume;"
+ "3:"
+ CLEANUP_REC("1b", "2b", "4b")
+ :
+ : [ran]"i"(RAN_FOO3_PREEMPT),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+ bpf_preempt_enable();
+ return x ^ 1;
+}
+
+static __used __naked __noinline void drop_glue(void)
+{
+ asm volatile (
+ PAD_RAN("%[ran]")
+ "exit;"
+ :
+ : [ran]"i"(RAN_FOO2_DROP), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 foo2(void)
+{
+ asm volatile (
+ "r6 = r1;"
+ "call bpf_rcu_read_lock;"
+ "r1 = r6;"
+"1:" "call foo3;" /* cleanup region #1 */
+"2:"
+ "r6 = r0;"
+ "if r6 == 0 goto 5f;"
+"3:" "call bpf_unwind;" /* cleanup region #2 */
+"4:" "goto 4b;"
+"5:"
+ "call bpf_rcu_read_unlock;"
+ "r0 = r6;"
+ "r0 += 1;"
+ "exit;"
+"6:" /* landing pad, shared by both regions */
+ "call drop_glue;"
+ "call bpf_rcu_read_unlock;"
+ PAD_RAN("%[ran_rcu]")
+ "call bpf_unwind_resume;"
+ "exit;" /* never reached, kept for coverage */
+ CLEANUP_REC("1b", "2b", "6b")
+ CLEANUP_REC("3b", "4b", "6b")
+ :
+ : [ran_rcu]"i"(RAN_FOO2_RCU),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+static __used __naked __noinline void foo1v(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call foo2;" /* cleanup region */
+"2:"
+ "r6 = r0;"
+ "call bpf_preempt_enable;"
+ "r1 = %[result] ll;"
+ "*(u64 *)(r1 + 0) = r6;"
+ "goto 7f;"
+"8:" /* landing pad */
+ "call bpf_preempt_enable;"
+ PAD_RAN("%[ran]")
+ "goto 9f;"
+"7:" /* the frame's own exit block */
+ "r0 = 0;"
+ "exit;"
+"9:" /* resume block, after the frame's exit */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "8b")
+ :
+ : [ran]"i"(RAN_FOO1V_PREEMPT), __imm_addr(input),
+ __imm_addr(result), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/*
+ * A frame with no cleanup record: an unwind leaving it runs no pad. The
+ * unwind never fires -- @never is global -- and the bit marks the return path.
+ */
+static __used __naked __noinline void bump(void)
+{
+ asm volatile (
+ PAD_RAN("%[ran]")
+ "r1 = %[never] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "if r1 == 0 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "exit;" /* r0 deliberately left alone */
+ :
+ : [ran]"i"(RAN_BUMP), __imm_addr(never), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+__noinline __u64 foo1(void)
+{
+ bump();
+ foo1v();
+ return result;
+}
+
+SEC("syscall")
+int entry(void *ctx)
+{
+ return foo1();
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c
new file mode 100644
index 0000000000000..18d45395425fc
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c
@@ -0,0 +1,792 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_experimental.h"
+#include "bpf_misc.h"
+#include "exceptions_cleanup.h"
+
+__u64 input = 0;
+
+static __used __noinline void __kfunc_btf_anchor(void)
+{
+ bpf_throw(0);
+ bpf_unwind();
+ bpf_preempt_disable();
+ bpf_preempt_enable();
+ bpf_rcu_read_lock();
+ bpf_rcu_read_unlock();
+ bpf_unwind_resume(NULL);
+}
+
+/* An unwind raised in a callee, which is how a cleanup region gets one. */
+static __used __naked __noinline __u64 inner_unwind(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+static int unwinding_cb(__u32 idx, void *ctx)
+{
+ bpf_unwind();
+ return 0;
+}
+
+SEC("?syscall")
+__failure __msg("may unwind and is used as a callback")
+int callback_may_unwind(void *ctx)
+{
+ bpf_loop(1, unwinding_cb, NULL, 0);
+ return 0;
+}
+
+__noinline int unused_exc_cb(u64 cookie)
+{
+ return 0;
+}
+
+/* A frame with a table and a pad, for tests whose refusal lies elsewhere. */
+static __used __naked __noinline __u64 table_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;" /* never reached, kept for coverage */
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__exception_cb(unused_exc_cb)
+__failure __msg("cannot be combined with an exception callback")
+int table_with_exception_cb(void *ctx)
+{
+ return table_frame();
+}
+
+/*
+ * A throw and a table, with no callback tagged: the default callback is
+ * appended too late to stand in for the throw, so the program is scanned
+ * for one instead.
+ */
+static __used __naked __noinline __u64 throw_and_table_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("cannot be combined with bpf_throw")
+int table_with_throw(void *ctx)
+{
+ if (input)
+ bpf_throw(0);
+ return throw_and_table_frame();
+}
+
+__u64 never;
+
+/*
+ * A pad calling a global subprogram that can unwind. The subprogram is
+ * verified on its own, so the pad rule is what refuses it.
+ */
+__noinline void pad_callee_that_unwinds(void)
+{
+ if (never)
+ bpf_unwind();
+}
+
+static __used __naked __noinline __u64 pad_calls_unwinder_frame(void)
+{
+ asm volatile (
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call pad_callee_that_unwinds;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("which can unwind while an unwind is in flight")
+int pad_calls_unwinder(void *ctx)
+{
+ return pad_calls_unwinder_frame();
+}
+
+static __used __naked __noinline __u64 catch_pad_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* catch pad: no resume, it stops here */
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("ends a landing pad: a catch pad is not supported yet")
+int catch_landing_pad(void *ctx)
+{
+ return catch_pad_frame();
+}
+
+/* A bpf_unwind_resume() outside any landing pad. */
+SEC("?syscall")
+__failure __msg("is not in a landing pad")
+int resume_outside_pad(void *ctx)
+{
+ /* Never taken, but reachable, which is all the verifier needs. */
+ if (never)
+ bpf_unwind_resume(NULL);
+ return table_frame();
+}
+
+/* A bpf_unwind_resume() in a subprogram a landing pad calls. */
+static __used __naked __noinline void resume_in_callee(void)
+{
+ asm volatile (
+ "call bpf_unwind_resume;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 pad_calls_resumer_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ "call resume_in_callee;" /* ...which resumes: refused */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is not in a landing pad")
+int resume_in_pad_callee(void *ctx)
+{
+ return pad_calls_resumer_frame();
+}
+
+static __used __naked __noinline __u64 nested_pad_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call inner_unwind;" /* first cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* first pad, second region's call */
+ "call bpf_preempt_enable;"
+"4:"
+ "call bpf_unwind_resume;"
+"5:" /* second pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ CLEANUP_REC("3b", "4b", "5b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is inside the call-site range of")
+int nested_landing_pad(void *ctx)
+{
+ return nested_pad_frame();
+}
+
+/* A tail call in a landing pad: the frame would never reach its resume. */
+struct {
+ __uint(type, BPF_MAP_TYPE_PROG_ARRAY);
+ __uint(max_entries, 1);
+ __uint(key_size, sizeof(__u32));
+ __uint(value_size, sizeof(__u32));
+} tc_map SEC(".maps");
+
+static __used __naked __noinline __u64 tail_call_pad_frame(void)
+{
+ asm volatile (
+ "r6 = r1;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = r6;"
+ "r2 = %[tc_map] ll;"
+ "r3 = 0;"
+ "call %[bpf_tail_call];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm(bpf_tail_call), __imm_addr(tc_map)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is a tail call, which replaces the frame, and is in a landing pad")
+int tail_call_in_pad(void *ctx)
+{
+ return tail_call_pad_frame();
+}
+
+#if defined(__BPF_FEATURE_STACK_ARGUMENT)
+
+/*
+ * A pad reading an incoming stack argument after its own bpf_unwind(): the
+ * call clobbered the register the JIT keeps it in. Every parameter is used,
+ * so the caller passes them all, and summed before the call, so the pad's is
+ * the only stack argument load after it.
+ */
+static __used __noinline __u64 stack_arg_pad_frame(__u64 a, __u64 b, __u64 c,
+ __u64 d, __u64 e, __u64 f)
+{
+ __u64 sum = a + b + c + d + e + f;
+
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:"
+ "goto 4f;"
+"3:" /* landing pad */
+ "r0 = *(u64 *)(r11 + 8);"
+ "call bpf_unwind_resume;"
+"4:"
+ CLEANUP_REC("1b", "2b", "3b")
+ : "+r"(sum) :: __clobber_common);
+ return sum;
+}
+
+SEC("?syscall")
+__failure __msg("r11 load must be before any r11 store or call insn")
+int stack_arg_load_in_pad(void *ctx)
+{
+ return stack_arg_pad_frame(1, 2, 3, 4, 5, 6);
+}
+
+#endif /* __BPF_FEATURE_STACK_ARGUMENT */
+
+/*
+ * A landing pad entered by ordinary control flow, with no unwind in flight:
+ * that path reaches the pad's resume outside a pad. Only the in_pad
+ * comparison in func_states_equal() keeps it from being pruned against the
+ * pad's own visit of that instruction.
+ */
+static __used __naked __noinline __u64 jump_into_pad_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "if r6 > 7 goto 4f;" /* an ordinary branch into the pad */
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r7 = r0;"
+"4:" /* ... and its second instruction */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is not in a landing pad")
+__flag(BPF_F_TEST_STATE_FREQ)
+int jump_into_pad(void *ctx)
+{
+ return jump_into_pad_frame();
+}
+
+#if defined(__clang__) && \
+ (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))
+
+/*
+ * An indirect jump in a landing pad. A jump table entry is an offset from
+ * the program's section symbol, which has to be spelled in quotes here.
+ */
+SEC("?syscall")
+__failure __msg("is an indirect jump")
+__naked void gotox_in_pad(void)
+{
+ asm volatile (
+ ".pushsection .jumptables,\"\",@progbits;"
+"jt0_%=:"
+ ".quad l0_%= - \"?syscall\";"
+ ".quad l1_%= - \"?syscall\";"
+ ".size jt0_%=, 16;"
+ ".global jt0_%=;"
+ ".popsection;"
+
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = jt0_%= ll;"
+ "r1 += 8;"
+ "r2 = *(u64 *)(r1 + 0);"
+ /*
+ * gotox r2, as raw bytes: the mnemonic only reached the LLVM
+ * assembler in llvm 22, and BPF_RAW_INSN() needs <linux/bpf.h>, which
+ * vmlinux.h rules out.
+ */
+ ".byte 0x0d, 0x02, 0, 0, 0, 0, 0, 0;"
+"l0_%=:"
+ "call bpf_unwind_resume;"
+"l1_%=:"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+#endif /* __clang__ && (x86 || arm64) */
+
+/* A BPF_LD_[ABS|IND] in a pad: a failed load leaves without resuming. */
+static __used __naked __noinline __u64 ld_abs_pad_frame(void)
+{
+ asm volatile (
+ "r6 = r1;" /* the skb BPF_LD_ABS reads */
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r0 = *(u32 *)skb[0];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?tc")
+__failure __msg("is a BPF_LD_[ABS|IND], which can leave through the epilogue")
+__naked void ld_abs_in_pad(void)
+{
+ asm volatile (
+ "call ld_abs_pad_frame;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * A subprogram a landing pad calls, which unwinds on its own. The second
+ * unwind would rewrite return addresses the first has already redirected.
+ */
+static __used __naked __noinline __u64 own_pad_callee(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* its landing pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 pad_calls_own_pad_frame(void)
+{
+ asm volatile (
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad, which calls the above */
+ "call own_pad_callee;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("starts a second unwind while one is in flight")
+int unwind_in_pad_callee(void *ctx)
+{
+ return pad_calls_own_pad_frame();
+}
+
+/* A record whose range holds no call that can unwind. */
+static __used __naked __noinline __u64 nounwind_rec_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_preempt_enable;" /* cleanup region: nounwind */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad, reached by nothing */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("unreachable insn")
+int nounwind_region(void *ctx)
+{
+ return nounwind_rec_frame();
+}
+
+/*
+ * An unwind with no landing pad in the main program returns from it, so what
+ * it holds is checked there, as at a plain exit.
+ */
+SEC("?syscall")
+__failure __msg("bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region")
+int unwind_no_pad_rcu(void *ctx)
+{
+ bpf_rcu_read_lock();
+ bpf_unwind();
+ bpf_rcu_read_unlock();
+ return 0;
+}
+
+/*
+ * Lock and reference state is the program's, not a frame's: an unwind carries
+ * it through every pad it runs, and what is still held when the main program
+ * returns is refused there. A pad that drops what its caller holds is fine;
+ * the caller's own pad dropping it again is not.
+ */
+static __used __naked __noinline __u64 pad_drops_caller_lock_frame(void)
+{
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* pad: drops a lock it never took */
+ "call bpf_rcu_read_unlock;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 caller_holds_lock_frame(void)
+{
+ asm volatile (
+ "call bpf_rcu_read_lock;"
+"1:" "call pad_drops_caller_lock_frame;"
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad */
+ "call bpf_rcu_read_unlock;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("unmatched rcu read unlock")
+int pad_drops_caller_lock(void *ctx)
+{
+ return caller_holds_lock_frame();
+}
+
+/* The other way round: a pad that does not drop what its own frame took. */
+static __used __naked __noinline __u64 pad_keeps_own_lock_frame(void)
+{
+ asm volatile (
+ "call bpf_rcu_read_lock;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "call bpf_rcu_read_unlock;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: forgets the unlock */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region")
+int pad_keeps_own_lock(void *ctx)
+{
+ return pad_keeps_own_lock_frame();
+}
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(max_entries, 4096);
+} unwind_ringbuf SEC(".maps");
+
+/*
+ * Always unwinds, so its caller is never returned to on the modelled path,
+ * and the caller's post-call code, which never releases the record, is not
+ * walked. Its pad discards the record the caller reserved.
+ */
+static __used __naked __noinline __u64 pad_drops_caller_ref_frame(void)
+{
+ asm volatile (
+ "r6 = r1;" /* the caller's reserved record */
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* pad: drops what it never acquired */
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm(bpf_ringbuf_discard)
+ : __clobber_all);
+}
+
+/* And this frame's own pad drops it a second time. */
+static __used __naked __noinline __u64 caller_holds_ref_frame(void)
+{
+ asm volatile (
+ "r1 = %[unwind_ringbuf] ll;"
+ "r2 = 8;"
+ "r3 = 0;"
+ "call %[bpf_ringbuf_reserve];"
+ "if r0 == 0 goto 9f;"
+ "r6 = r0;"
+ "r1 = r6;"
+"1:" "call pad_drops_caller_ref_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad */
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "call bpf_unwind_resume;"
+"9:"
+ "r0 = 0;"
+ "exit;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard),
+ __imm_addr(unwind_ringbuf)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("R1 type=scalar expected=ringbuf_mem")
+int pad_drops_caller_ref(void *ctx)
+{
+ return caller_holds_ref_frame();
+}
+
+/*
+ * A frame an unwind returns through without a pad is abandoned where it made
+ * the call: the JIT sends it to its epilogue, so nothing of it runs again and
+ * whatever it acquired is never released -- which the main program's exit
+ * then finds still held.
+ */
+static __used __naked __noinline __u64 pad_resumes_frame(void)
+{
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* pad */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 uncovered_holds_lock_frame(void)
+{
+ asm volatile (
+ "call bpf_rcu_read_lock;"
+ "call pad_resumes_frame;" /* no record covers this call */
+ "call bpf_rcu_read_unlock;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region")
+int unwind_through_call_keeps_lock(void *ctx)
+{
+ return uncovered_holds_lock_frame();
+}
+
+static __used __naked __noinline __u64 uncovered_holds_ref_frame(void)
+{
+ asm volatile (
+ "r1 = %[unwind_ringbuf] ll;"
+ "r2 = 8;"
+ "r3 = 0;"
+ "call %[bpf_ringbuf_reserve];"
+ "if r0 == 0 goto 9f;"
+ "r6 = r0;"
+ "call pad_resumes_frame;" /* no record covers this call */
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+"9:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard),
+ __imm_addr(unwind_ringbuf)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("Unreleased reference id=")
+int unwind_through_call_keeps_ref(void *ctx)
+{
+ return uncovered_holds_ref_frame();
+}
+
+/*
+ * A callee writes its caller's stack through a pointer argument, then
+ * unwinds. The caller's pad runs after that write, so it cannot keep trusting
+ * the slot to hold the zero it held at the call.
+ */
+static __used __naked __noinline __u64 stack_writer(void)
+{
+ asm volatile (
+ "r2 = 0x10000000;"
+ "*(u64 *)(r1 + 0) = r2;" /* r1 is the caller's fp-8 */
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 stale_stack_frame(void)
+{
+ asm volatile (
+ "r6 = 0;"
+ "*(u64 *)(r10 - 8) = r6;"
+ "*(u64 *)(r10 - 64) = r6;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call stack_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: fp-8 as an offset into fp-64 */
+ "r1 = *(u64 *)(r10 - 8);"
+ "r2 = r10;"
+ "r2 += -64;"
+ "r2 += r1;"
+ "r0 = *(u8 *)(r2 + 0);"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("invalid read from stack R2 off=268435392 size=1")
+int stale_stack_pad(void *ctx)
+{
+ return stale_stack_frame();
+}
+
+/* The same through a global subprog, which is not walked from its caller. */
+__noinline int global_stack_writer(__u64 *p)
+{
+ if (!p)
+ return 0;
+ *p = 0x10000000;
+ bpf_unwind();
+ return 0;
+}
+
+static __used __naked __noinline __u64 global_stale_stack_frame(void)
+{
+ asm volatile (
+ "r6 = 0;"
+ "*(u64 *)(r10 - 8) = r6;"
+ "*(u64 *)(r10 - 64) = r6;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call global_stack_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: fp-8 as an offset into fp-64 */
+ "r1 = *(u64 *)(r10 - 8);"
+ "r2 = r10;"
+ "r2 += -64;"
+ "r2 += r1;"
+ "r0 = *(u8 *)(r2 + 0);"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("math between fp pointer and register with unbounded min value")
+int global_stale_stack_pad(void *ctx)
+{
+ return global_stale_stack_frame();
+}
+
+/* gcc has no indirect calls, and only these JITs emit them */
+#if defined(__clang__) && \
+ (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))
+
+/*
+ * A callback calling an unwinding subprog through a pointer it read from its
+ * caller's stack: it neither calls nor takes the address of inner_unwind, so
+ * only the marking of every subprog with a callx makes it might_unwind.
+ */
+static __used __naked __noinline int callx_cb(void)
+{
+ asm volatile (
+ "r1 = *(u64 *)(r2 + 0);"
+ "callx r1;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("may unwind and is used as a callback")
+__naked int callback_callx_may_unwind(void)
+{
+ asm volatile (
+ "r1 = %[inner_unwind] ll;"
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = 1;"
+ "r2 = %[callx_cb] ll;"
+ "r3 = r10;"
+ "r3 += -8;"
+ "r4 = 0;"
+ "call %[bpf_loop];"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(inner_unwind), __imm_addr(callx_cb), __imm(bpf_loop)
+ : __clobber_all);
+}
+
+#endif /* __clang__ && (x86 || arm64) */
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c
new file mode 100644
index 0000000000000..af92ee6cb9711
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c
@@ -0,0 +1,1134 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "exceptions_cleanup.h"
+
+static __used __noinline void __kfunc_btf_anchor(void)
+{
+ bpf_unwind();
+ bpf_rcu_read_lock();
+ bpf_rcu_read_unlock();
+ bpf_preempt_disable();
+ bpf_preempt_enable();
+ bpf_unwind_resume(NULL);
+}
+
+__u64 input = 0;
+__u64 magic = 0x5eed;
+__u64 pads_ran = 0;
+
+/* Load r6-r9 with values derived from @magic. */
+#define LOAD_MAGIC_REGS \
+ "r1 = %[magic] ll;" \
+ "r6 = *(u64 *)(r1 + 0);" \
+ "r7 = r6;" \
+ "r7 += 1;" \
+ "r8 = r6;" \
+ "r8 += 2;" \
+ "r9 = r6;" \
+ "r9 += 3;"
+
+/* Set @bit only if r6-r9 still hold what LOAD_MAGIC_REGS put there. */
+#define CHECK_MAGIC_REGS(bit) \
+ "r1 = %[magic] ll;" \
+ "r2 = *(u64 *)(r1 + 0);" \
+ "if r6 != r2 goto 9f;" \
+ "r2 += 1;" \
+ "if r7 != r2 goto 9f;" \
+ "r2 += 1;" \
+ "if r8 != r2 goto 9f;" \
+ "r2 += 1;" \
+ "if r9 != r2 goto 9f;" \
+ PAD_RAN(bit) \
+ "9:"
+
+/* A callee that unwinds when its argument is over 100. */
+static __used __noinline __u64 pc_unwinder(__u64 x)
+{
+ if (x > 100)
+ bpf_unwind();
+ return x + 1;
+}
+
+static __used __naked __noinline __u64 regs_unwinder(void)
+{
+ asm volatile (
+ /* Clobber the caller's r6-r9; the unwind must restore them. */
+ "r6 = 0xdead;"
+ "r7 = 0xbeef;"
+ "r8 = 0xcafe;"
+ "r9 = 0xf00d;"
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+/* A pad that reads r6-r9, which the callee overwrote before it unwound. */
+static __used __naked __noinline __u64 regs_frame(void)
+{
+ asm volatile (
+ LOAD_MAGIC_REGS
+ "call bpf_preempt_disable;"
+"1:" "call regs_unwinder;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ CHECK_MAGIC_REGS("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_REGS),
+ __imm_addr(magic), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_REGS)
+int entry_regs(void *ctx)
+{
+ return regs_frame();
+}
+
+/* A region ending on a 16-byte insn, so end - 1 names its second half. */
+static __used __naked __noinline __u64 wide_rec_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "call bpf_rcu_read_lock;"
+ "r1 = r6;"
+"1:" "call pc_unwinder;" /* cleanup region begins */
+ "r1 = %[magic] ll;" /* ... and ends on this pair */
+"2:"
+ "r6 = r0;"
+ "call bpf_rcu_read_unlock;"
+ "r0 = r6;"
+ "exit;"
+"3:" /* landing pad */
+ "r7 = r0;"
+ "call bpf_rcu_read_unlock;"
+ PAD_RAN("%[ran]")
+ "r1 = r7;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_WIDE_REC), __imm_addr(input), __imm_addr(magic),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_WIDE_REC)
+int entry_wide_rec(void *ctx)
+{
+ return wide_rec_frame();
+}
+
+/* LLVM's name for the resume; libbpf resolves it to bpf_unwind_resume(). */
+extern void _Unwind_Resume(void *ptr) __ksym;
+
+static __used __noinline void __resume_alias_btf_anchor(void)
+{
+ _Unwind_Resume(NULL);
+}
+
+static __used __naked __noinline __u64 resume_alias_frame(void)
+{
+ asm volatile (
+"1:" "call regs_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call _Unwind_Resume;" /* the frontend's name for it */
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_RESUME_ALIAS), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_RESUME_ALIAS)
+int entry_resume_alias(void *ctx)
+{
+ return resume_alias_frame();
+}
+
+/* A pad starting on a nop, which bpf_opt_remove_nops() drops after the walk. */
+static __used __naked __noinline __u64 nop_pad_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "if r6 < 101 goto 6f;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:"
+"6:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad: a nop, then its body */
+ "goto +0;"
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NOP_PAD),
+ __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_NOP_PAD)
+int entry_nop_pad(void *ctx)
+{
+ return nop_pad_frame();
+}
+
+/* Put @magic in both of the slots a variable offset could name. */
+#define FILL_MAGIC_SLOTS \
+ "r1 = %[magic] ll;" \
+ "r1 = *(u64 *)(r1 + 0);" \
+ "*(u64 *)(r10 - 8) = r1;" \
+ "*(u64 *)(r10 - 16) = r1;"
+
+/* Set @bit if the slot @idx names, read at a variable offset, holds it. */
+#define CHECK_VAR_SLOT(idx, bit) \
+ "r1 = r10;" \
+ "r1 += " idx ";" \
+ "r2 = *(u64 *)(r1 - 16);" \
+ "r3 = %[magic] ll;" \
+ "r3 = *(u64 *)(r3 + 0);" \
+ "if r2 != r3 goto 9f;" \
+ PAD_RAN(bit) \
+ "9:"
+
+/* A callee that unwinds when r1 is at least 101, and touches none of r6-r9. */
+static __used __naked __noinline __u64 var_unwinder(void)
+{
+ asm volatile (
+ "if r1 < 101 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 var_stack_frame(void)
+{
+ asm volatile (
+ FILL_MAGIC_SLOTS
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "r6 &= 1;" /* an unknown slot number... */
+ "r6 <<= 3;" /* ...as an aligned byte offset */
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call var_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r7 = r0;"
+ CHECK_VAR_SLOT("r6", "%[ran]")
+ "r1 = r7;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_VAR_STACK), __imm_addr(input), __imm_addr(magic),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_VAR_STACK)
+int entry_var_stack(void *ctx)
+{
+ return var_stack_frame();
+}
+
+/* Two pads with an uncovered frame between them. */
+static __used __naked __noinline __u64 gap_inner_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call pc_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r6 = r0;"
+ PAD_RAN("%[ran]")
+ "r1 = r6;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_GAP_INNER), __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/* The frame in between, with no record of its own. */
+static __used __noinline __u64 gap_mid(void)
+{
+ return gap_inner_frame() + 1;
+}
+
+static __used __naked __noinline __u64 gap_outer_frame(void)
+{
+ asm volatile (
+"1:" "call gap_mid;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r6 = r0;"
+ PAD_RAN("%[ran]")
+ "r1 = r6;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_GAP_OUTER), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/* And one more uncovered frame between the outer pad and the main program. */
+static __used __noinline __u64 gap_top(void)
+{
+ return gap_outer_frame() + 1;
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_GAP_INNER | RAN_GAP_OUTER)
+int entry_two_pads(void *ctx)
+{
+ return gap_top();
+}
+
+/*
+ * A precision chain crossing a resume: the outer frame's pad uses r6 as a
+ * variable stack offset, and the only way into that pad is the resume that
+ * ends the inner frame's pad, so backtracking goes from the pad through the
+ * inner frame and back to where r6 was bounded.
+ */
+static __used __naked __noinline __u64 prec_inner_frame(void)
+{
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* landing pad */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 prec_outer_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "r6 &= 0x7;"
+ "r0 = 0;"
+ "*(u64 *)(r10 - 8) = r0;"
+ "*(u64 *)(r10 - 16) = r0;"
+"1:" "call prec_inner_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: r6 as a variable stack offset */
+ "r2 = r10;"
+ "r2 += -16;"
+ "r2 += r6;"
+ "*(u8 *)(r2 + 0) = 1;"
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_PREC_RESUME), __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_PREC_RESUME)
+__log_level(2)
+__msg("frame1: regs=r6 stack= before {{[0-9]+}}: (85) call bpf_unwind_resume")
+__msg("frame2: regs= stack= before {{[0-9]+}}: (85) call bpf_unwind#")
+__msg("frame1: regs=r6 stack= before {{[0-9]+}}: (57) r6 &= 7")
+int entry_prec_across_resume(void *ctx)
+{
+ return prec_outer_frame();
+}
+
+/* Unwinds every time, and no record covers it, so the path simply ends. */
+static __used __naked __noinline __u64 always_unwind(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * A frame with no record of its own above one that always unwinds: nothing
+ * after the call is reachable, so dead code removal would leave it no exit
+ * and no epilogue for the unwind to send it to. One is kept, and since this
+ * frame ends in a jump rather than an exit, it is not the last instruction.
+ */
+static __used __naked __noinline __u64 no_exit_ja_mid(void)
+{
+ asm volatile (
+ "goto 2f;"
+"1:" "r0 = 1;"
+ "exit;"
+"2:" "call always_unwind;"
+ "goto 1b;" /* the last insn, and not an exit */
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_exit_ja_outer_frame(void)
+{
+ asm volatile (
+"1:" "call no_exit_ja_mid;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NO_EXIT_JA), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_NO_EXIT_JA)
+int entry_no_exit_ja(void *ctx)
+{
+ return no_exit_ja_outer_frame();
+}
+
+/*
+ * Frames that only unwind, the way a compiler leaves functions that return
+ * `!`: after the call comes the loop that stands for what cannot happen, and
+ * no exit. The unwinder leaves through the exit put after its bpf_unwind();
+ * the frame above it, which has no record, is sent to an epilogue, so the
+ * verifier gives it an exit.
+ */
+static __used __naked __noinline __u64 no_exit_loop_unwinder(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+"1:" "goto 1b;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_exit_loop_mid(void)
+{
+ asm volatile (
+ "call no_exit_loop_unwinder;"
+"1:" "goto 1b;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_exit_loop_outer_frame(void)
+{
+ asm volatile (
+"1:" "call no_exit_loop_mid;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NO_EXIT_LOOP), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_NO_EXIT_LOOP)
+int entry_no_exit_loop(void *ctx)
+{
+ return no_exit_loop_outer_frame();
+}
+
+/*
+ * A frame with no exit whose last insn is a covered call to a subprog placed
+ * after it: the frame jumps over its pad to get there. The exit the verifier
+ * puts after that call moves the callee down by one, and the record has to
+ * stay on the call, or the unwind finds no pad for the frame.
+ */
+static __used __naked __noinline __u64 last_call_frame(void)
+{
+ asm volatile (
+ "goto 1f;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+"1:" "call last_call_unwinder;" /* cleanup region, and the last insn */
+"2:"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_LAST_CALL), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/* After last_call_frame(), and without an exit, so it may be called last. */
+static __used __naked __noinline void last_call_unwinder(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_LAST_CALL)
+int entry_last_call(void *ctx)
+{
+ return last_call_frame();
+}
+
+/*
+ * Nothing after a call that does not return, the way a compiler emits it:
+ * no_tail_fail() is a call to bpf_unwind() and nothing else, no_tail_check()
+ * returns its argument or ends with the call to no_tail_fail(), and the pad
+ * of no_tail_frame() ends with its resume.
+ */
+static __used __naked __noinline void no_tail_fail(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_tail_check(void)
+{
+ asm volatile (
+ "if r1 > 7 goto 1f;"
+ "r0 = r1;"
+ "exit;"
+"1:" "call no_tail_fail;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_tail_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call no_tail_check;" /* cleanup region */
+"2:"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NO_TAIL), __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_NO_TAIL)
+int entry_no_tail_unwind(void *ctx)
+{
+ return no_tail_frame();
+}
+
+SEC("?syscall")
+__success __set_global(input, 3) __retval(3)
+__ret_global(pads_ran, 0)
+int entry_no_tail_return(void *ctx)
+{
+ return no_tail_frame();
+}
+
+/* gcc has no indirect calls, and only these JITs emit them */
+#if defined(__clang__) && \
+ (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))
+
+/*
+ * A region covering an indirect call: a record names a call by its return
+ * address, which a callx leaves like any other call.
+ */
+static __used __naked __noinline __u64 callx_region_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+ "r2 = %[always_unwind] ll;"
+"1:" "callx r2;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_CALLX), __imm_addr(always_unwind),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_CALLX)
+int entry_callx_region(void *ctx)
+{
+ return callx_region_frame();
+}
+
+/*
+ * A subprog calling an unwinding one through a pointer it was handed: nothing
+ * after the call runs, but a callx cannot end a subprog, so code follows it.
+ */
+static __used __naked __noinline __u64 callx_arg_frame(void)
+{
+ asm volatile (
+ "callx r1;" /* r1 is always_unwind */
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__naked int entry_callx_arg(void)
+{
+ asm volatile (
+ "r1 = %[always_unwind] ll;"
+ "call callx_arg_frame;"
+ "exit;"
+ :
+ : __imm_addr(always_unwind)
+ : __clobber_all);
+}
+
+#endif /* __clang__ && (x86 || arm64) */
+
+/* Add one to the @w-bit global at @addr. */
+#define BUMP_GLOBAL(w, addr) \
+ "r1 = " addr " ll;" \
+ "r2 = *(u" w " *)(r1 + 0);" \
+ "r2 += 1;" \
+ "*(u" w " *)(r1 + 0) = r2;"
+
+/*
+ * A pad that touches a global of each width and sign a test tag can name,
+ * so that __set_global() and __ret_global() are exercised on all four.
+ */
+int tag_i = 0;
+unsigned int tag_ui = 0;
+long tag_l = 0;
+unsigned long tag_ul = 0;
+
+static __used __naked __noinline __u64 tag_types_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call pc_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ BUMP_GLOBAL("32", "%[tag_i]")
+ BUMP_GLOBAL("32", "%[tag_ui]")
+ BUMP_GLOBAL("64", "%[tag_l]")
+ BUMP_GLOBAL("64", "%[tag_ul]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm_addr(input), __imm_addr(tag_i), __imm_addr(tag_ui),
+ __imm_addr(tag_l), __imm_addr(tag_ul)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__set_global(input, 101)
+__set_global(tag_i, -23) __set_global(tag_ui, 0xfffffffe)
+__set_global(tag_l, -23) __set_global(tag_ul, 0xfffffffffffffffe)
+__ret_global(tag_i, -22) __ret_global(tag_ui, 0xffffffff)
+__ret_global(tag_l, -22) __ret_global(tag_ul, 0xffffffffffffffff)
+int entry_tag_types(void *ctx)
+{
+ return tag_types_frame();
+}
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(max_entries, 4096);
+} shape_ringbuf SEC(".maps");
+
+/*
+ * A pad reading a slot its frame's callee wrote before it unwound. The write
+ * is there when the pad runs, and the pad has to be verified that way, or
+ * the check below is taken as always failing and the bit is never set.
+ */
+static __used __naked __noinline __u64 slot_writer(void)
+{
+ asm volatile (
+ "r2 = 42;"
+ "*(u64 *)(r1 + 0) = r2;" /* r1 is the caller's fp-8 */
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "if r1 < 101 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 callee_write_frame(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call slot_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = *(u64 *)(r10 - 8);"
+ "if r1 != 42 goto 9f;"
+ PAD_RAN("%[ran]")
+"9:"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_CALLEE_WRITE), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_CALLEE_WRITE)
+int entry_callee_write(void *ctx)
+{
+ return callee_write_frame();
+}
+
+/*
+ * A precision chain across an unwind: the pad uses a slot the callee wrote as
+ * a variable stack offset, so backtracking follows the slot from the pad back
+ * into the frame the unwind left.
+ */
+static __used __naked __noinline __u64 offset_writer(void)
+{
+ asm volatile (
+ "r2 = %[input] ll;"
+ "r3 = *(u64 *)(r2 + 0);"
+ "r3 &= 8;"
+ "*(u64 *)(r1 + 0) = r3;" /* r1 is the caller's fp-24 */
+ "call bpf_unwind;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 callee_offset_frame(void)
+{
+ asm volatile (
+ FILL_MAGIC_SLOTS
+ "r1 = 0;"
+ "*(u64 *)(r10 - 24) = r1;"
+ "r1 = r10;"
+ "r1 += -24;"
+"1:" "call offset_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r6 = *(u64 *)(r10 - 24);"
+ CHECK_VAR_SLOT("r6", "%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_CALLEE_OFFSET), __imm_addr(magic), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_CALLEE_OFFSET)
+__log_level(2)
+__msg("frame1: regs= stack=-24 before {{[0-9]+}}: (85) call bpf_unwind#")
+__msg("frame2: regs= stack= before {{[0-9]+}}: (7b) *(u64 *)(r1 +0) = r3")
+__msg("frame2: regs=r3 stack= before {{[0-9]+}}: (57) r3 &= 8")
+int entry_callee_offset(void *ctx)
+{
+ return callee_offset_frame();
+}
+
+/* The same through a global subprog. */
+__noinline int global_slot_writer(__u64 *p)
+{
+ if (!p)
+ return 0;
+ *p = 42;
+ if (input > 100)
+ bpf_unwind();
+ return 0;
+}
+
+static __used __naked __noinline __u64 global_write_frame(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call global_slot_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = *(u64 *)(r10 - 8);"
+ "if r1 != 42 goto 9f;"
+ PAD_RAN("%[ran]")
+"9:"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_GLOBAL_WRITE), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_GLOBAL_WRITE)
+int entry_global_write(void *ctx)
+{
+ return global_write_frame();
+}
+
+/*
+ * An unwind raised in a global subprog, called with no record over the call
+ * from a frame whose own caller has a pad. The global subprog is verified on
+ * its own, so the unwind is taken from the state its call returns in, and it
+ * has to go on to that pad.
+ */
+__noinline int global_unwinder(int x)
+{
+ if (x > 100)
+ bpf_unwind();
+ return 0;
+}
+
+static __used __naked __noinline __u64 through_global_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "call global_unwinder;" /* no record */
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 over_global_frame(void)
+{
+ asm volatile (
+"1:" "call through_global_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_THROUGH_GLOBAL), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_THROUGH_GLOBAL)
+int entry_through_global(void *ctx)
+{
+ return over_global_frame();
+}
+
+#if defined(__clang_major__) && __clang_major__ >= 23
+
+/*
+ * The same, with the global subprog returning in R0:R2: its unwind leaves
+ * R2 checked as a return value too, though its caller never reads either.
+ */
+struct u64_pair {
+ __u64 a;
+ __u64 b;
+};
+
+__noinline struct u64_pair global_pair_unwinder(int x)
+{
+ struct u64_pair p = { x, x + 1 };
+
+ if (x > 100)
+ bpf_unwind();
+ return p;
+}
+
+static __used __naked __noinline __u64 through_pair_global_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "call global_pair_unwinder;" /* no record */
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 over_pair_global_frame(void)
+{
+ asm volatile (
+"1:" "call through_pair_global_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_PAIR_GLOBAL), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_PAIR_GLOBAL)
+int entry_pair_global_unwind(void *ctx)
+{
+ return over_pair_global_frame();
+}
+
+#endif /* __clang_major__ >= 23 */
+
+/*
+ * A reference moved into a callee: the caller reserves a record and hands it
+ * over with a plain call, as rustc emits for 'consume(rec)' -- it has nothing
+ * left to drop -- and the callee drops it on return and, from its pad, on an
+ * unwind.
+ */
+static __used __naked __noinline __u64 consume_frame(void)
+{
+ asm volatile (
+ "r6 = r1;" /* the record, now owned here */
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call global_unwinder;" /* cleanup region */
+"2:"
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad: drop glue */
+ PAD_RAN("%[ran]")
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_MOVE), __imm_addr(pads_ran), __imm_addr(input),
+ __imm(bpf_ringbuf_discard)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 move_frame(void)
+{
+ asm volatile (
+ "r1 = %[shape_ringbuf] ll;"
+ "r2 = 8;"
+ "r3 = 0;"
+ "call %[bpf_ringbuf_reserve];"
+ "if r0 == 0 goto 1f;"
+ "r1 = r0;"
+ "call consume_frame;" /* the record moves: no record here */
+"1:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(shape_ringbuf), __imm(bpf_ringbuf_reserve)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_MOVE)
+int entry_move_into_callee(void *ctx)
+{
+ return move_frame();
+}
+
+/*
+ * A bpf_unwind() inside a loop, with no pad between it and the main program.
+ * The main program's frame returns from where the unwind left it, not from
+ * the loop in the subprog.
+ */
+static __used __naked __noinline __u64 loop_unwinder(void)
+{
+ asm volatile (
+ "r6 = 0;"
+"1:"
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "if r1 != r6 goto 2f;"
+ "call bpf_unwind;"
+"2:"
+ "r6 += 1;"
+ "if r6 < 4 goto 1b;"
+ "r0 = 1;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 2) __retval(0)
+int entry_unwind_in_loop(void *ctx)
+{
+ return loop_unwinder();
+}
+
+/*
+ * The loop in the main program itself, around a call that unwinds on one
+ * trip. The unwind returns from the main frame at that call, inside the loop,
+ * where no checkpoint need have been made yet.
+ */
+static __used __naked __noinline __u64 unwind_on_match(void)
+{
+ asm volatile (
+ "r2 = %[input] ll;"
+ "r2 = *(u64 *)(r2 + 0);"
+ "if r1 != r2 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 2) __retval(0)
+__naked int entry_unwind_out_of_main_loop(void)
+{
+ asm volatile (
+ "r6 = 0;"
+"1:"
+ "r1 = r6;"
+ "call unwind_on_match;"
+ "r6 += 1;"
+ "if r6 < 4 goto 1b;"
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * An unwind reaching main's exit in a program type that checks r0: its
+ * precision is backtracked past an earlier call to the insn that unwound.
+ */
+static __used __naked __noinline __u64 plain_frame(void)
+{
+ asm volatile (
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?cgroup/skb")
+__success
+__naked int entry_unwind_to_checked_exit(void)
+{
+ asm volatile (
+ "call plain_frame;"
+ "call always_unwind;"
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * The same two calls, never taken. Neither subprog is entered, so both go
+ * whole. Keeping an exit of always_unwind would leave one dead run over
+ * plain_frame and the head of always_unwind, and the subprog starts worked
+ * out after removing it would hand main's exit to always_unwind.
+ */
+SEC("?syscall")
+__success __retval(0)
+__naked int entry_unwinder_never_entered(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "if r1 == 0 goto 1f;"
+ "call plain_frame;"
+ "call always_unwind;"
+"1:" "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * Like entry_unwind_to_checked_exit(), out of a global call, which r6 = 0
+ * keeps from being the state's first insn, where backtracking would stop.
+ * The verifier_bug_if() this guards against only logs, so the level 2 log
+ * is checked.
+ */
+__noinline int global_always_unwind(void)
+{
+ bpf_unwind();
+ return 0;
+}
+
+SEC("?cgroup/skb")
+__success __log_level(2) __not_msg("verifier bug")
+__naked int entry_global_unwind_to_checked_exit(void)
+{
+ asm volatile (
+ "r6 = 0;"
+ "call global_always_unwind;"
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c
new file mode 100644
index 0000000000000..9fbc06d0bec4f
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * Tracing programs aimed at foo1() of progs/exceptions_cleanup.c, a subprog
+ * an unwind passes through. The attach target is set at load time.
+ */
+SEC("?fexit")
+int BPF_PROG(fexit_unwinding_subprog)
+{
+ return 0;
+}
+
+int fentry_hits;
+
+SEC("?fentry")
+int BPF_PROG(fentry_unwinding_subprog)
+{
+ fentry_hits++;
+ return 0;
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/test_loader.c b/tools/testing/selftests/bpf/test_loader.c
index 18d47e9254007..06a01a967b33e 100644
--- a/tools/testing/selftests/bpf/test_loader.c
+++ b/tools/testing/selftests/bpf/test_loader.c
@@ -50,6 +50,13 @@ enum stack_mode {
SMALL_STACK = 1 << 1,
};
+#define MAX_GLOBAL_VARS 8
+
+struct global_var {
+ char *name;
+ __u64 val;
+};
+
struct test_subspec {
char *name;
char *description;
@@ -62,6 +69,10 @@ struct test_subspec {
int retval;
bool execute;
__u64 caps;
+ struct global_var set_globals[MAX_GLOBAL_VARS];
+ int set_global_cnt;
+ struct global_var ret_globals[MAX_GLOBAL_VARS];
+ int ret_global_cnt;
};
struct test_spec {
@@ -115,6 +126,34 @@ void free_msgs(struct expected_msgs *msgs)
msgs->cnt = 0;
}
+static void free_global_vars(struct global_var *vars, int *cnt)
+{
+ int i;
+
+ for (i = 0; i < *cnt; i++) {
+ free(vars[i].name);
+ vars[i].name = NULL;
+ }
+ *cnt = 0;
+}
+
+static int clone_global_vars(struct global_var *dst, int *dst_cnt,
+ const struct global_var *src, int src_cnt)
+{
+ int i;
+
+ for (i = 0; i < src_cnt; i++) {
+ dst[i].name = strdup(src[i].name);
+ if (!dst[i].name) {
+ free_global_vars(dst, dst_cnt);
+ return -ENOMEM;
+ }
+ dst[i].val = src[i].val;
+ (*dst_cnt)++;
+ }
+ return 0;
+}
+
static void free_test_spec(struct test_spec *spec)
{
/* Deallocate expect_msgs arrays. */
@@ -129,6 +168,11 @@ static void free_test_spec(struct test_spec *spec)
free_msgs(&spec->unpriv.stdout);
free_msgs(&spec->priv.stdout);
+ free_global_vars(spec->priv.set_globals, &spec->priv.set_global_cnt);
+ free_global_vars(spec->priv.ret_globals, &spec->priv.ret_global_cnt);
+ free_global_vars(spec->unpriv.set_globals, &spec->unpriv.set_global_cnt);
+ free_global_vars(spec->unpriv.ret_globals, &spec->unpriv.ret_global_cnt);
+
free(spec->priv.name);
free(spec->priv.description);
free(spec->unpriv.name);
@@ -311,6 +355,236 @@ static int parse_caps(const char *str, __u64 *val, const char *name)
return 0;
}
+static int parse_global_var(const char *str, struct global_var *vars, int *cnt,
+ const char *name)
+{
+ const char *colon = strrchr(str, ':');
+ struct global_var *var;
+ char *end;
+ __u64 *val;
+
+ if (!colon || colon == str) {
+ PRINT_FAIL("expecting '<variable>:<value>' for %s, got '%s'\n", name, str);
+ return -EINVAL;
+ }
+ if (*cnt >= MAX_GLOBAL_VARS) {
+ PRINT_FAIL("too many %s tags, at most %d are supported\n",
+ name, MAX_GLOBAL_VARS);
+ return -E2BIG;
+ }
+
+ var = &vars[*cnt];
+ val = &var->val;
+ *val = 0;
+ for (const char *term = colon + 1;;) {
+ __u64 v;
+
+ errno = 0;
+ v = strtoull(term, &end, 0);
+ if (errno || end == term) {
+ PRINT_FAIL("failed to parse %s value '%s'\n", name, colon + 1);
+ return -EINVAL;
+ }
+ *val |= v;
+ while (*end == ' ')
+ end++;
+ if (!*end)
+ break;
+ if (*end != '|') {
+ PRINT_FAIL("failed to parse %s value '%s'\n", name, colon + 1);
+ return -EINVAL;
+ }
+ term = end + 1;
+ }
+
+ var->name = strndup(str, colon - str);
+ if (!var->name) {
+ PRINT_FAIL("failed to allocate %s variable name\n", name);
+ return -ENOMEM;
+ }
+ (*cnt)++;
+
+ return 0;
+}
+
+/* As veristat's is_signed_type(): anything not plainly unsigned is signed. */
+static bool global_var_is_signed(const struct btf_type *t)
+{
+ if (btf_is_int(t))
+ return btf_int_encoding(t) & BTF_INT_SIGNED;
+ if (btf_is_any_enum(t))
+ return btf_kflag(t);
+ return true;
+}
+
+static int find_global_var(struct bpf_object *obj, const char *name,
+ struct bpf_map **map, __u32 *off, __u32 *sz,
+ bool *is_signed)
+{
+ static const char * const secs[] = { ".bss", ".data" };
+ struct btf *btf = bpf_object__btf(obj);
+ int i, s;
+
+ if (!btf) {
+ PRINT_FAIL("no BTF for object\n");
+ return -ENOENT;
+ }
+
+ for (s = 0; s < ARRAY_SIZE(secs); s++) {
+ const struct btf_type *sec, *vt;
+ const struct btf_var_secinfo *vsi;
+ struct bpf_map *m = bpf_object__find_map_by_name(obj, secs[s]);
+ int id;
+
+ id = btf__find_by_name_kind(btf, secs[s], BTF_KIND_DATASEC);
+ if (!m || id < 0)
+ continue;
+
+ sec = btf__type_by_id(btf, id);
+ vsi = btf_var_secinfos(sec);
+ for (i = 0; i < btf_vlen(sec); i++, vsi++) {
+ const struct btf_type *var = btf__type_by_id(btf, vsi->type);
+
+ if (strcmp(btf__name_by_offset(btf, var->name_off), name))
+ continue;
+ if (vsi->size != 4 && vsi->size != 8) {
+ PRINT_FAIL("'%s' is %u bytes, only 4 and 8 are supported\n",
+ name, vsi->size);
+ return -EINVAL;
+ }
+ vt = btf__type_by_id(btf, btf__resolve_type(btf, var->type));
+ if (!vt || !(btf_is_int(vt) || btf_is_any_enum(vt))) {
+ PRINT_FAIL("'%s' is not an int or an enum\n", name);
+ return -EINVAL;
+ }
+ *is_signed = global_var_is_signed(vt);
+ *map = m;
+ *off = vsi->offset;
+ *sz = vsi->size;
+ return 0;
+ }
+ }
+
+ PRINT_FAIL("no global variable '%s'\n", name);
+ return -ENOENT;
+}
+
+/*
+ * A tag's value is parsed as 64 bits, but the variable may be narrower and
+ * may be signed. Hold it to the range the variable can represent, the way
+ * veristat's set_global_var() does, and narrow it to what is stored.
+ */
+static int fit_global_var(const char *name, __u32 sz, bool is_signed, __u64 *val)
+{
+ long long v = (long long)*val;
+ long long max_val;
+ __u32 bits;
+
+ if (sz >= sizeof(*val))
+ return 0;
+ bits = sz * 8 - (is_signed ? 1 : 0);
+ max_val = 1ll << bits;
+ if (v >= max_val || v < (is_signed ? -max_val : 0)) {
+ PRINT_FAIL("value %lld for '%s' is out of range [%lld; %lld]\n",
+ v, name, is_signed ? -max_val : 0, max_val - 1);
+ return -EINVAL;
+ }
+ *val = (__u32)*val;
+ return 0;
+}
+
+/* The value of @map's single element, which the caller frees. */
+static void *global_data(struct bpf_map *map, const char *name, size_t *vsz)
+{
+ __u32 zero = 0;
+ void *buf;
+ int err;
+
+ *vsz = bpf_map__value_size(map);
+ buf = calloc(1, *vsz);
+ if (!buf) {
+ PRINT_FAIL("failed to allocate %zu bytes for '%s'\n", *vsz, name);
+ return NULL;
+ }
+ err = bpf_map__lookup_elem(map, &zero, sizeof(zero), buf, *vsz, 0);
+ if (err) {
+ PRINT_FAIL("failed to read '%s': %d\n", name, err);
+ free(buf);
+ return NULL;
+ }
+ return buf;
+}
+
+static int read_global_var(struct bpf_map *map, const char *name, __u32 off,
+ __u32 sz, __u64 *val)
+{
+ size_t vsz;
+ void *buf;
+
+ buf = global_data(map, name, &vsz);
+ if (!buf)
+ return -EINVAL;
+ *val = sz == 4 ? *(__u32 *)(buf + off) : *(__u64 *)(buf + off);
+ free(buf);
+ return 0;
+}
+
+static int write_global_var(struct bpf_map *map, const char *name, __u32 off,
+ __u32 sz, __u64 val)
+{
+ __u32 zero = 0;
+ size_t vsz;
+ void *buf;
+ int err;
+
+ buf = global_data(map, name, &vsz);
+ if (!buf)
+ return -EINVAL;
+ if (sz == 4)
+ *(__u32 *)(buf + off) = val;
+ else
+ *(__u64 *)(buf + off) = val;
+ err = bpf_map__update_elem(map, &zero, sizeof(zero), buf, vsz, 0);
+ if (err)
+ PRINT_FAIL("failed to write '%s': %d\n", name, err);
+ free(buf);
+ return err;
+}
+
+/* Write a __set_global() value into the program's global variable. */
+static int set_global_var(struct bpf_object *obj, const struct global_var *var)
+{
+ __u64 val = var->val;
+ struct bpf_map *map;
+ __u32 off, sz;
+ bool is_signed;
+
+ if (find_global_var(obj, var->name, &map, &off, &sz, &is_signed) ||
+ fit_global_var(var->name, sz, is_signed, &val))
+ return -EINVAL;
+ return write_global_var(map, var->name, off, sz, val);
+}
+
+/* Check the program's global variable against a __ret_global() value. */
+static int check_global_var(struct bpf_object *obj, const struct global_var *var)
+{
+ __u64 want = var->val, val;
+ struct bpf_map *map;
+ __u32 off, sz;
+ bool is_signed;
+
+ if (find_global_var(obj, var->name, &map, &off, &sz, &is_signed) ||
+ fit_global_var(var->name, sz, is_signed, &want) ||
+ read_global_var(map, var->name, off, sz, &val))
+ return -EINVAL;
+ if (val != want) {
+ PRINT_FAIL("Unexpected %s: 0x%llx != 0x%llx\n", var->name,
+ (unsigned long long)val, (unsigned long long)want);
+ return -EINVAL;
+ }
+ return 0;
+}
+
static int parse_retval(const char *str, int *val, const char *name)
{
/*
@@ -567,6 +841,22 @@ static int parse_test_spec(struct test_loader *tester,
spec->mode_mask |= UNPRIV;
spec->unpriv.execute = true;
has_unpriv_retval = true;
+ } else if ((val = str_has_pfx(s, "test_global_set="))) {
+ err = parse_global_var(val, spec->priv.set_globals,
+ &spec->priv.set_global_cnt,
+ "__set_global");
+ if (err)
+ goto cleanup;
+ spec->priv.execute = true;
+ spec->mode_mask |= PRIV;
+ } else if ((val = str_has_pfx(s, "test_global_ret="))) {
+ err = parse_global_var(val, spec->priv.ret_globals,
+ &spec->priv.ret_global_cnt,
+ "__ret_global");
+ if (err)
+ goto cleanup;
+ spec->priv.execute = true;
+ spec->mode_mask |= PRIV;
} else if ((val = str_has_pfx(s, "test_log_level="))) {
err = parse_int(val, &spec->log_level, "test log level");
if (err)
@@ -754,6 +1044,23 @@ static int parse_test_spec(struct test_loader *tester,
spec->unpriv.execute = spec->priv.execute;
}
+ if (spec->priv.set_global_cnt && !spec->unpriv.set_global_cnt) {
+ err = clone_global_vars(spec->unpriv.set_globals,
+ &spec->unpriv.set_global_cnt,
+ spec->priv.set_globals,
+ spec->priv.set_global_cnt);
+ if (err)
+ goto cleanup;
+ }
+ if (spec->priv.ret_global_cnt && !spec->unpriv.ret_global_cnt) {
+ err = clone_global_vars(spec->unpriv.ret_globals,
+ &spec->unpriv.ret_global_cnt,
+ spec->priv.ret_globals,
+ spec->priv.ret_global_cnt);
+ if (err)
+ goto cleanup;
+ }
+
if (spec->unpriv.expect_msgs.cnt == 0)
clone_msgs(&spec->priv.expect_msgs, &spec->unpriv.expect_msgs);
if (spec->unpriv.expect_xlated.cnt == 0)
@@ -1369,7 +1676,7 @@ void run_subtest(struct test_loader *tester,
struct cap_state caps = {};
struct bpf_object *tobj;
struct bpf_map *map;
- int retval, err, i;
+ int retval, err, i, j;
int links_cnt = 0;
bool should_load;
@@ -1545,6 +1852,11 @@ void run_subtest(struct test_loader *tester,
}
}
+ for (j = 0; j < subspec->set_global_cnt; j++) {
+ if (set_global_var(tobj, &subspec->set_globals[j]))
+ goto tobj_cleanup;
+ }
+
err = do_prog_test_run(bpf_program__fd(tprog), &retval,
bpf_program__type(tprog) == BPF_PROG_TYPE_SYSCALL ? true : false,
spec->linear_sz);
@@ -1553,6 +1865,11 @@ void run_subtest(struct test_loader *tester,
goto tobj_cleanup;
}
+ for (j = 0; !err && j < subspec->ret_global_cnt; j++) {
+ if (check_global_var(tobj, &subspec->ret_globals[j]))
+ goto tobj_cleanup;
+ }
+
verify_stderr(bpf_program__fd(tprog), &subspec->stderr);
if (subspec->stdout.cnt) {
|
| 3/2 | 2026/10/17 07:54 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 74140 output: 60 thoughts: 1219 Thoughts: **Evaluation of BPF Exception Cleanup Patch Series for Syzkaller Fuzzing** Okay, let's break this down. The task is to determine if this patch series warrants fuzzing with syzkaller. First, let's understand the scope. The initial assessment indicates a focus on amd64 (x86_64), which is promising for QEMU-based fuzzing. The changes are extensive and clearly centered around BPF, specifically implementing exception cleanup tables and landing pads. Key files have been modified or added. I see arch-specific code for arm64 but the x86 changes are where it is happening, with JIT compilation and unwinding modifications in `arch/x86/net/bpf_jit_comp.c`. The changes also include: * Extensive modifications to the BPF verifier. This is critical as the verifier is a key attack surface. * Runtime changes involving stack unwinding. * Syscall handling (`BPF_PROG_LOAD`), meaning the functionality is exposed to userspace. * New BPF core files, focusing on exception handling, backtracking, and liveness analysis. * A number of changes in `include/linux/bpf.h` and `include/uapi/linux/bpf.h` This is a major new feature. Based on the triage philosophy, "REACHABILITY IS THE PRIMARY GATE," this is an instant "yes." BPF is inherently reachable via the `bpf()` syscall and can execute in standard QEMU. The changes touch core subsystems like the verifier, runtime, and syscall handling. Therefore, the answer is WorthFuzzing = TRUE. Now, let's determine the prerequisites for actually building and running this. I need to identify the Kconfig options required to enable this functionality. The next step is to examine the kernel configuration and source files, using something like `grepper` or `read-file`, to determine what options are needed. Then I can determine what tests, if any, are available, and get to work on setting up a fuzzing target. |
| 4/2 | 2026/10/17 07:54 | tool | grepper |
0mArgs:{
"Expression": "CONFIG_BPF_SYSCALL|CONFIG_BPF_JIT|CONFIG_UNWINDER_ORC",
"PathPrefixes": [
"kernel/bpf/",
"arch/x86/"
]
}Results: {
"Output": "\nFull output is too long, showing 200 out of 303 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (19 files in total):\narch/x86/Makefile:1\narch/x86/include/asm/extable.h:1\narch/x86/include/asm/module.h:1\narch/x86/include/asm/nospec-branch.h:1\narch/x86/include/asm/unwind.h:4\narch/x86/kernel/Makefile:1\narch/x86/kernel/callthunks.c:1\narch/x86/kernel/cpu/bugs.c:3\narch/x86/kernel/unwind_orc.c:1\narch/x86/net/Makefile:2\narch/x86/net/bpf_jit_comp.c:7\nkernel/bpf/Kconfig:1\nkernel/bpf/Makefile:29\nkernel/bpf/btf.c:1\nkernel/bpf/core.c:15\nkernel/bpf/fixups.c:3\nkernel/bpf/syscall.c:1\nkernel/bpf/trampoline.c:2\nkernel/bpf/verifier.c:1\n\narch/x86/Makefile=332=endif\narch/x86/Makefile-333-\narch/x86/Makefile:334:ifdef CONFIG_UNWINDER_ORC\narch/x86/Makefile-335-orc_hash_h := arch/$(SRCARCH)/include/generated/asm/orc_hash.h\n--\narch/x86/include/asm/extable.h=46=static inline void __noreturn ex_handler_msr_mce(struct pt_regs *regs, bool wrmsr)\n--\narch/x86/include/asm/extable.h-52-\narch/x86/include/asm/extable.h:53:#if defined(CONFIG_BPF_JIT) \u0026\u0026 defined(CONFIG_X86_64)\narch/x86/include/asm/extable.h-54-bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs);\n--\narch/x86/include/asm/module.h=15=struct mod_arch_specific {\narch/x86/include/asm/module.h:16:#ifdef CONFIG_UNWINDER_ORC\narch/x86/include/asm/module.h-17-\tunsigned int num_orcs;\n--\narch/x86/include/asm/nospec-branch.h=443=extern void write_ibpb(void);\narch/x86/include/asm/nospec-branch.h-444-\narch/x86/include/asm/nospec-branch.h:445:#ifdef CONFIG_BPF_JIT\narch/x86/include/asm/nospec-branch.h-446-extern void bpf_arch_ibpb(void);\n--\narch/x86/include/asm/unwind.h=14=struct unwind_state {\n--\narch/x86/include/asm/unwind.h-22-\tbool error;\narch/x86/include/asm/unwind.h:23:#if defined(CONFIG_UNWINDER_ORC)\narch/x86/include/asm/unwind.h-24-\tbool signal, full_regs;\n--\narch/x86/include/asm/unwind.h=59=void unwind_start(struct unwind_state *state, struct task_struct *task,\n--\narch/x86/include/asm/unwind.h-66-\narch/x86/include/asm/unwind.h:67:#if defined(CONFIG_UNWINDER_ORC) || defined(CONFIG_UNWINDER_FRAME_POINTER)\narch/x86/include/asm/unwind.h-68-/*\n--\narch/x86/include/asm/unwind.h=71=static inline struct pt_regs *unwind_get_entry_regs(struct unwind_state *state,\n--\narch/x86/include/asm/unwind.h-77-\tif (partial) {\narch/x86/include/asm/unwind.h:78:#ifdef CONFIG_UNWINDER_ORC\narch/x86/include/asm/unwind.h-79-\t\t*partial = !state-\u003efull_regs;\n--\narch/x86/include/asm/unwind.h=88=static inline struct pt_regs *unwind_get_entry_regs(struct unwind_state *state,\n--\narch/x86/include/asm/unwind.h-94-\narch/x86/include/asm/unwind.h:95:#ifdef CONFIG_UNWINDER_ORC\narch/x86/include/asm/unwind.h-96-void unwind_init(void);\n--\narch/x86/kernel/Makefile=159=obj-$(CONFIG_X86_UMIP)\t\t\t+= umip.o\narch/x86/kernel/Makefile-160-\narch/x86/kernel/Makefile:161:obj-$(CONFIG_UNWINDER_ORC)\t\t+= unwind_orc.o\narch/x86/kernel/Makefile-162-obj-$(CONFIG_UNWINDER_FRAME_POINTER)\t+= unwind_frame.o\n--\narch/x86/kernel/callthunks.c=265=void *callthunks_translate_call_dest(void *dest)\n--\narch/x86/kernel/callthunks.c-280-\narch/x86/kernel/callthunks.c:281:#ifdef CONFIG_BPF_JIT\narch/x86/kernel/callthunks.c-282-static bool is_callthunk(void *addr)\n--\narch/x86/kernel/cpu/bugs.c=1669=static inline bool retpoline_seq_enabled(void) { return false; }\n--\narch/x86/kernel/cpu/bugs.c-1676-\narch/x86/kernel/cpu/bugs.c:1677:#ifdef CONFIG_BPF_SYSCALL\narch/x86/kernel/cpu/bugs.c-1678-void unpriv_ebpf_notify(int new_state)\n--\narch/x86/kernel/cpu/bugs.c=2236=static void __init spectre_v2_update_mitigation(void)\n--\narch/x86/kernel/cpu/bugs.c-2253-\narch/x86/kernel/cpu/bugs.c:2254:#ifdef CONFIG_BPF_JIT\narch/x86/kernel/cpu/bugs.c-2255-static void __bpf_arch_ibpb(void *unused)\n--\narch/x86/kernel/cpu/bugs.c=2275=static void __init spectre_v2_apply_mitigation(void)\n--\narch/x86/kernel/cpu/bugs.c-2351-\narch/x86/kernel/cpu/bugs.c:2352:#ifdef CONFIG_BPF_JIT\narch/x86/kernel/cpu/bugs.c-2353-\tif (cpu_wants_ibpb_bpf()) {\n--\narch/x86/kernel/unwind_orc.c=185=static struct orc_entry *orc_bpf_find(unsigned long ip)\narch/x86/kernel/unwind_orc.c-186-{\narch/x86/kernel/unwind_orc.c:187:#ifdef CONFIG_BPF_JIT\narch/x86/kernel/unwind_orc.c-188-\tif (bpf_has_frame_pointer(ip))\n--\narch/x86/net/Makefile=6=ifeq ($(CONFIG_X86_32),y)\narch/x86/net/Makefile:7: obj-$(CONFIG_BPF_JIT) += bpf_jit_comp32.o\narch/x86/net/Makefile-8-else\narch/x86/net/Makefile:9: obj-$(CONFIG_BPF_JIT) += bpf_jit_comp.o bpf_timed_may_goto.o\narch/x86/net/Makefile-10-endif\n--\narch/x86/net/bpf_jit_comp.c-26-\narch/x86/net/bpf_jit_comp.c:27:#if IS_ENABLED(CONFIG_BPF_JIT_KASAN)\narch/x86/net/bpf_jit_comp.c-28-void __asan_load1(void *p);\n--\narch/x86/net/bpf_jit_comp.c=1301=static int emit_kasan_check(struct bpf_verifier_env *env, u8 **pprog,\n--\narch/x86/net/bpf_jit_comp.c-1304-{\narch/x86/net/bpf_jit_comp.c:1305:#ifdef CONFIG_BPF_JIT_KASAN\narch/x86/net/bpf_jit_comp.c-1306-\tu8 *prog = *pprog;\n--\narch/x86/net/bpf_jit_comp.c-1376-\t*pprog = prog;\narch/x86/net/bpf_jit_comp.c:1377:#endif /* CONFIG_BPF_JIT_KASAN */\narch/x86/net/bpf_jit_comp.c-1378-\treturn 0;\n--\narch/x86/net/bpf_jit_comp.c=5118=bool bpf_jit_supports_exceptions(void)\n--\narch/x86/net/bpf_jit_comp.c-5123-\t */\narch/x86/net/bpf_jit_comp.c:5124:\treturn IS_ENABLED(CONFIG_UNWINDER_ORC);\narch/x86/net/bpf_jit_comp.c-5125-}\n--\narch/x86/net/bpf_jit_comp.c=5127=bool bpf_jit_supports_cleanup_pads(void)\narch/x86/net/bpf_jit_comp.c-5128-{\narch/x86/net/bpf_jit_comp.c:5129:\treturn IS_ENABLED(CONFIG_UNWINDER_ORC);\narch/x86/net/bpf_jit_comp.c-5130-}\n--\narch/x86/net/bpf_jit_comp.c=5137=void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)\narch/x86/net/bpf_jit_comp.c-5138-{\narch/x86/net/bpf_jit_comp.c:5139:#if defined(CONFIG_UNWINDER_ORC)\narch/x86/net/bpf_jit_comp.c-5140-\tstruct unwind_state state;\n--\narch/x86/net/bpf_jit_comp.c=5153=notrace void arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp,\n--\narch/x86/net/bpf_jit_comp.c-5156-{\narch/x86/net/bpf_jit_comp.c:5157:#if defined(CONFIG_UNWINDER_ORC)\narch/x86/net/bpf_jit_comp.c-5158-\tstruct unwind_state state;\n--\nkernel/bpf/Kconfig=62=config BPF_JIT_ALWAYS_ON\n--\nkernel/bpf/Kconfig-68-\nkernel/bpf/Kconfig:69:\t When CONFIG_BPF_JIT_ALWAYS_ON is enabled, /proc/sys/net/core/bpf_jit_enable\nkernel/bpf/Kconfig-70-\t is permanently set to 1 and setting any other value than that will\n--\nkernel/bpf/Makefile=2=obj-y := core.o\nkernel/bpf/Makefile:3:ifneq ($(CONFIG_BPF_JIT_ALWAYS_ON),y)\nkernel/bpf/Makefile-4-# ___bpf_prog_run() needs GCSE disabled on x86; see 3193c0836f203 for details\n--\nkernel/bpf/Makefile=7=CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)\nkernel/bpf/Makefile-8-\nkernel/bpf/Makefile:9:obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o loops.o scev.o\nkernel/bpf/Makefile:10:obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o\nkernel/bpf/Makefile:11:obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o\nkernel/bpf/Makefile:12:obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o\nkernel/bpf/Makefile:13:obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o\nkernel/bpf/Makefile:14:obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o exception.o\nkernel/bpf/Makefile-15-obj-${CONFIG_BPF_LSM}\t += bpf_inode_storage.o\nkernel/bpf/Makefile:16:obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o\nkernel/bpf/Makefile:17:obj-$(CONFIG_BPF_JIT) += trampoline.o\nkernel/bpf/Makefile:18:obj-$(CONFIG_BPF_SYSCALL) += btf.o memalloc.o rqspinlock.o stream.o\nkernel/bpf/Makefile-19-ifeq ($(CONFIG_MMU)$(CONFIG_64BIT),yy)\nkernel/bpf/Makefile:20:obj-$(CONFIG_BPF_SYSCALL) += arena.o range_tree.o\nkernel/bpf/Makefile-21-endif\nkernel/bpf/Makefile:22:obj-$(CONFIG_BPF_JIT) += dispatcher.o\nkernel/bpf/Makefile-23-ifeq ($(CONFIG_NET),y)\nkernel/bpf/Makefile:24:obj-$(CONFIG_BPF_SYSCALL) += devmap.o\nkernel/bpf/Makefile:25:obj-$(CONFIG_BPF_SYSCALL) += cpumap.o\nkernel/bpf/Makefile:26:obj-$(CONFIG_BPF_SYSCALL) += offload.o\nkernel/bpf/Makefile:27:obj-$(CONFIG_BPF_SYSCALL) += net_namespace.o\nkernel/bpf/Makefile:28:obj-$(CONFIG_BPF_SYSCALL) += tcx.o\nkernel/bpf/Makefile-29-endif\nkernel/bpf/Makefile=30=ifeq ($(CONFIG_KEYS),y)\nkernel/bpf/Makefile:31:obj-$(CONFIG_BPF_SYSCALL) += keys.o\nkernel/bpf/Makefile-32-endif\nkernel/bpf/Makefile=33=ifeq ($(CONFIG_PERF_EVENTS),y)\nkernel/bpf/Makefile:34:obj-$(CONFIG_BPF_SYSCALL) += stackmap.o\nkernel/bpf/Makefile-35-endif\nkernel/bpf/Makefile=36=ifeq ($(CONFIG_CGROUPS),y)\nkernel/bpf/Makefile:37:obj-$(CONFIG_BPF_SYSCALL) += cgroup_iter.o bpf_cgrp_storage.o\nkernel/bpf/Makefile-38-endif\n--\nkernel/bpf/Makefile=40=ifeq ($(CONFIG_INET),y)\nkernel/bpf/Makefile:41:obj-$(CONFIG_BPF_SYSCALL) += reuseport_array.o\nkernel/bpf/Makefile-42-endif\n--\nkernel/bpf/Makefile=46=endif\nkernel/bpf/Makefile:47:ifeq ($(CONFIG_BPF_JIT),y)\nkernel/bpf/Makefile:48:obj-$(CONFIG_BPF_SYSCALL) += bpf_struct_ops.o\nkernel/bpf/Makefile:49:obj-$(CONFIG_BPF_SYSCALL) += cpumask.o\nkernel/bpf/Makefile-50-# bpf_lsm_proto.o must precede bpf_lsm.o. The current pahole logic\n--\nkernel/bpf/Makefile=63=obj-$(CONFIG_BPF_PRELOAD) += preload/\nkernel/bpf/Makefile-64-\nkernel/bpf/Makefile:65:obj-$(CONFIG_BPF_SYSCALL) += relo_core.o\nkernel/bpf/Makefile:66:obj-$(CONFIG_BPF_SYSCALL) += btf_iter.o\nkernel/bpf/Makefile:67:obj-$(CONFIG_BPF_SYSCALL) += btf_relocate.o\nkernel/bpf/Makefile:68:obj-$(CONFIG_BPF_SYSCALL) += kmem_cache_iter.o\nkernel/bpf/Makefile-69-ifeq ($(CONFIG_DMA_SHARED_BUFFER),y)\nkernel/bpf/Makefile:70:obj-$(CONFIG_BPF_SYSCALL) += dmabuf_iter.o\nkernel/bpf/Makefile-71-endif\n--\nkernel/bpf/btf.c=10712=bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,\n--\nkernel/bpf/btf.c-10766-\nkernel/bpf/btf.c:10767:#ifdef CONFIG_BPF_JIT\nkernel/bpf/btf.c-10768-static int\n--\nkernel/bpf/core.c=102=struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)\n--\nkernel/bpf/core.c-130-\tfp-\u003ejit_requested = ebpf_jit_enabled();\nkernel/bpf/core.c:131:\tfp-\u003ejit_required = IS_ENABLED(CONFIG_BPF_JIT_ALWAYS_ON);\nkernel/bpf/core.c-132-\tfp-\u003eblinding_requested = bpf_jit_blinding_enabled(fp);\n--\nkernel/bpf/core.c=285=void __bpf_prog_free(struct bpf_prog *fp)\n--\nkernel/bpf/core.c-287-\tif (fp-\u003eaux) {\nkernel/bpf/core.c:288:#ifdef CONFIG_BPF_SYSCALL\nkernel/bpf/core.c-289-\t\tbpf_prog_stream_free(fp);\n\n"
} |
| 5/2 | 2026/10/17 07:54 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 80805 output: 34 thoughts: 493 Thoughts: **My Analysis of BPF Exception Handling Requirements** Okay, let's break down this `bpf_exc_check_prog` function. My initial thought is to understand the dependencies and requirements for exception cleanup in BPF programs. I need to be sure that exception handling is supported, so let's check. First, I see that the function immediately returns an error if the program is offloaded. That's straightforward: we're not supporting it in that context. Then, it checks `bpf_jit_supports_cleanup_pads()`, and I need to understand that. It returns `-EOPNOTSUPP` if the JIT lacks the ability to dispatch landing pads for exception handling. This means a compatible JIT is essential. Peeking at the x86 implementation, `bpf_jit_supports_cleanup_pads()` simply returns `IS_ENABLED(CONFIG_UNWINDER_ORC)`. This is interesting; it means that to support exception handling, we absolutely need the ORC unwinder enabled. Now, let's confirm this by looking at `arch/x86/net/Makefile`. Right here, if `CONFIG_BPF_JIT=y`, `bpf_jit_comp.c` is compiled. On x86_64, which is relevant, that includes the JIT. So, `CONFIG_BPF_JIT` is needed. I'm starting to see the pieces. If `CONFIG_BPF_JIT` is enabled, then we can use the JIT, but `CONFIG_UNWINDER_ORC` must be also set to true. Digging further, I see `CONFIG_UNWINDER_ORC` is also used in `arch_bpf_stack_walk_ra()` via `#if defined(CONFIG_UNWINDER_ORC)`. So it seems pretty critical! Finally, checking `kernel/bpf/Makefile`, I see that `exception.o` is built if `CONFIG_BPF_SYSCALL=y`. So we need that too! So, to summarize my findings and conclusions, to support BPF exception handling, I must have: * `CONFIG_BPF_SYSCALL=y` * `CONFIG_BPF_JIT=y` * `CONFIG_UNWINDER_ORC=y` Now, let me go ahead and confirm these requirements by checking x86's Kconfig file for `UNWINDER_ORC` to see if there are other dependencies I missed. |
| 6/2 | 2026/10/17 07:54 | tool | grepper |
0mArgs:{
"Expression": "config UNWINDER_ORC",
"PathPrefixes": [
"arch/x86/"
]
}Results: {
"Output": "arch/x86/Kconfig.debug=224=choice\n--\narch/x86/Kconfig.debug-232-\narch/x86/Kconfig.debug:233:config UNWINDER_ORC\narch/x86/Kconfig.debug-234-\tbool \"ORC unwinder\"\n"
} |
| 7/2 | 2026/10/17 07:54 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 81976 output: 38 thoughts: 36 Thoughts: Here's a summary of my thought process, as requested: **Investigating the Dependencies of UNWINDER_ORC** Okay, I need to understand the dependencies of `UNWINDER_ORC` within the x86 architecture's kernel configuration. My instinct says I should go straight to the source. Specifically, I should open up `arch/x86/Kconfig.debug` and zero in around line 230. That's usually where these sorts of debugging-related options are defined, and the Kconfig files are the definitive source of truth for kernel configuration logic. Let's see what conditions must be met for `UNWINDER_ORC` to be available. |
| 8/2 | 2026/10/17 07:54 | tool | read-file |
0mArgs:{
"File": "arch/x86/Kconfig.debug",
"FirstLine": 220,
"LineCount": 40
}Results: {
"Contents": " 220:\t\t each device is exposed as part of the debugfs interface.\n 221:\t\t The current power state can be read from\n 222:\t\t /sys/kernel/debug/punit_atom/dev_power_state\n 223:\t\n 224:\tchoice\n 225:\t\tprompt \"Choose kernel unwinder\"\n 226:\t\tdefault UNWINDER_ORC if X86_64\n 227:\t\tdefault UNWINDER_FRAME_POINTER if X86_32\n 228:\t\thelp\n 229:\t\t This determines which method will be used for unwinding kernel stack\n 230:\t\t traces for panics, oopses, bugs, warnings, perf, /proc/\u003cpid\u003e/stack,\n 231:\t\t livepatch, lockdep, and more.\n 232:\t\n 233:\tconfig UNWINDER_ORC\n 234:\t\tbool \"ORC unwinder\"\n 235:\t\tdepends on X86_64\n 236:\t\tselect OBJTOOL\n 237:\t\thelp\n 238:\t\t This option enables the ORC (Oops Rewind Capability) unwinder for\n 239:\t\t unwinding kernel stack traces. It uses a custom data format which is\n 240:\t\t a simplified version of the DWARF Call Frame Information standard.\n 241:\t\n 242:\t\t This unwinder is more accurate across interrupt entry frames than the\n 243:\t\t frame pointer unwinder. It also enables a 5-10% performance\n 244:\t\t improvement across the entire kernel compared to frame pointers.\n 245:\t\n 246:\t\t Enabling this option will increase the kernel's runtime memory usage\n 247:\t\t by roughly 2-4MB, depending on your kernel config.\n 248:\t\n 249:\tconfig UNWINDER_FRAME_POINTER\n 250:\t\tbool \"Frame pointer unwinder\"\n 251:\t\tselect ARCH_WANT_FRAME_POINTERS\n 252:\t\tselect FRAME_POINTER\n 253:\t\thelp\n 254:\t\t This option enables the frame pointer unwinder for unwinding kernel\n 255:\t\t stack traces.\n 256:\t\n 257:\t\t The unwinder itself is fast and it uses less RAM than the ORC\n 258:\t\t unwinder, but the kernel text size will grow by ~3% and the kernel's\n 259:\t\t overall performance will degrade by roughly 5-10%.\n"
} |
| 9/2 | 2026/10/17 07:54 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 82858 output: 38 thoughts: 71 Thoughts: Here's my summary, as I see it: **Digging into UNWINDER_ORC Dependencies** Okay, so `UNWINDER_ORC` is clearly built on the x86_64 architecture and leans on `OBJTOOL` – no surprises there, that's expected. But what's really catching my attention are `BPF_SYSCALL` and `BPF_JIT`. Those indicate some level of BPF integration, which is significant. Now I need to know *exactly* what this dependency means in the grand scheme of things. Are there any other config options tied to it that I'm missing? Time to dive into the kernel configuration files. I'll start with a scan for `BPF_SYSCALL` in the typical places: `init/Kconfig` and `kernel/bpf/Kconfig`. Let's see what's what. |
| 10/2 | 2026/10/17 07:54 | tool | grepper |
0mArgs:{
"Expression": "config BPF_SYSCALL",
"PathPrefixes": [
"init/",
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/Kconfig=29=menu \"BPF subsystem\"\nkernel/bpf/Kconfig-30-\nkernel/bpf/Kconfig:31:config BPF_SYSCALL\nkernel/bpf/Kconfig-32-\tbool \"Enable bpf() system call\"\n"
} |
| 11/2 | 2026/10/17 07:54 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 83243 output: 34 thoughts: 23 Thoughts: Okay, here's the summary, expressed as though I'm the one thinking it: **Examining BPF Kernel Configuration** Alright, let's get down to brass tacks. I need to understand the dependencies and configuration options related to the BPF (Berkeley Packet Filter) subsystem within the kernel. My immediate plan is to zero in on the `kernel/bpf/Kconfig` file, specifically around line 31. That's usually a good spot to start digging into the core dependencies and the high-level configuration options that drive the inclusion or exclusion of BPF features. By examining that section, I can quickly get a handle on what other kernel components are required or influenced by BPF. From there, I can branch out as needed, but this is a solid jumping-off point for this investigation. |
| 12/2 | 2026/10/17 07:54 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/Kconfig",
"FirstLine": 30,
"LineCount": 40
}Results: {
"Contents": " 30:\t\n 31:\tconfig BPF_SYSCALL\n 32:\t\tbool \"Enable bpf() system call\"\n 33:\t\tselect BPF\n 34:\t\tselect IRQ_WORK\n 35:\t\tselect NEED_TASKS_RCU\n 36:\t\tselect TASKS_TRACE_RCU\n 37:\t\tselect BINARY_PRINTF\n 38:\t\tselect NET_SOCK_MSG if NET\n 39:\t\tselect NET_XGRESS if NET\n 40:\t\tselect PAGE_POOL if NET\n 41:\t\tdefault n\n 42:\t\thelp\n 43:\t\t Enable the bpf() system call that allows to manipulate BPF programs\n 44:\t\t and maps via file descriptors.\n 45:\t\n 46:\tconfig BPF_JIT\n 47:\t\tbool \"Enable BPF Just In Time compiler\"\n 48:\t\tdepends on BPF\n 49:\t\tdepends on HAVE_CBPF_JIT || HAVE_EBPF_JIT\n 50:\t\tselect EXECMEM\n 51:\t\thelp\n 52:\t\t BPF programs are normally handled by a BPF interpreter. This option\n 53:\t\t allows the kernel to generate native code when a program is loaded\n 54:\t\t into the kernel. This will significantly speed-up processing of BPF\n 55:\t\t programs.\n 56:\t\n 57:\t\t Note, an admin should enable this feature changing:\n 58:\t\t /proc/sys/net/core/bpf_jit_enable\n 59:\t\t /proc/sys/net/core/bpf_jit_harden (optional)\n 60:\t\t /proc/sys/net/core/bpf_jit_kallsyms (optional)\n 61:\t\n 62:\tconfig BPF_JIT_ALWAYS_ON\n 63:\t\tbool \"Permanently enable BPF JIT and remove BPF interpreter\"\n 64:\t\tdepends on BPF_SYSCALL \u0026\u0026 HAVE_EBPF_JIT \u0026\u0026 BPF_JIT\n 65:\t\thelp\n 66:\t\t Enables BPF JIT and removes BPF interpreter to avoid speculative\n 67:\t\t execution of BPF instructions by the interpreter.\n 68:\t\n 69:\t\t When CONFIG_BPF_JIT_ALWAYS_ON is enabled, /proc/sys/net/core/bpf_jit_enable\n"
} |
| 13/2 | 2026/10/17 07:54 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 84081 output: 266 thoughts: 2909 Thoughts: **Analysis of BPF Exception Cleanup and Unwinding for Fuzzing** Okay, let's break this down. My goal here is to identify key components for focused fuzzing of this BPF exception cleanup and stack unwinding mechanism. First, I need to ensure the JIT is enabled and that we're dealing with a configuration where exception cleanup, and by extension stack unwinding, is actually relevant. That means confirming `BPF_SYSCALL`, `BPF_JIT`, and `UNWINDER_ORC` are all active. The `bpf_jit_enable` or `BPF_JIT_ALWAYS_ON` flags must also be set. Now, the core of this assessment lies in identifying *specific* functions to target. I'm avoiding ubiquitous functions like memory allocators and deallocators. The key here is to target features-specific logic. So, I need a list of the *modified* and *new* functions introduced in this patch. My investigation has narrowed them down to these modules and functions: * **`kernel/bpf/exception.c`**: Functions related to checking exception information, marking call sites, and checking if a program may unwind. These are crucial: `bpf_exc_check_info`, `bpf_exc_check_callback`, `bpf_exc_mark_call_sites`, `bpf_prog_may_unwind`, `bpf_exc_check_prog`, `bpf_is_unwind_kfunc`, `bpf_is_unwind_resume_kfunc`, `bpf_exc_check_insn`, `bpf_exc_pad_of_call`, `bpf_exc_pad_for_ip`, `bpf_exc_attach_info`, `bpf_exc_fill_native_ranges`, `bpf_exc_free_info`. * **`kernel/bpf/helpers.c`**: Critically, the `bpf_unwind` and `bpf_unwind_resume` kfuncs, and the supporting helpers: `bpf_unwind_rewrite` and `bpf_unwind_find_prog`. `bpf_unwind` is an *entrypoint* for this mechanism. * **`arch/x86/net/bpf_jit_comp.c`**: These are key: `arch_bpf_stack_walk_ra`, and `bpf_jit_supports_cleanup_pads`, and modifications to `do_jit`. * **`kernel/bpf/fixups.c`**: Functions for patching unwind calls and dealing with subprograms. Includes: `bpf_exc_patch_unwind_calls`, and modified functions: `verifier_remove_insns`, `adjust_insn_aux_data`, `bpf_opt_remove_dead_code`, `bpf_opt_remove_nops`. These functions, particularly the ones beginning with `bpf_exc_` and `bpf_unwind`, represent the *specific* logic I want to focus on. Their non-static nature means they are exposed to the verifier, or used directly by the JIT. Now, I understand that `bpf_unwind` is where the stack manipulation happens using the ORC unwinder. `arch_bpf_stack_walk_ra` performs the walk, and most importantly, `bpf_unwind_rewrite` *modifies* the return addresses on the stack. This is high-risk, sensitive code, and any error here can easily lead to memory corruption or control-flow hijacking. I am especially concerned with the interaction of the JIT, stack unwinding, verifier states, and backtracking, etc. It all gets quite complex. I've carefully considered the "FocusSymbol" criteria, and none of my selected functions are ubiquitous. They are *directly* related to the new exception handling, stack unwinding, and JIT support added in this patch. Therefore, I'm confident that the following are my focus symbols: * `bpf_unwind` * `arch_bpf_stack_walk_ra` * `bpf_exc_check_info` * `bpf_exc_check_prog` * `bpf_exc_patch_unwind_calls` * `bpf_exc_fill_native_ranges` * `bpf_exc_pad_for_ip` * `bpf_jit_supports_cleanup_pads` The `EnableConfigs` are: `BPF_SYSCALL`, `BPF_JIT`, and `UNWINDER_ORC`. |
| 14/2 | 2026/10/17 07:55 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"BPF_SYSCALL",
"BPF_JIT",
"UNWINDER_ORC"
],
"FocusSymbols": [
"bpf_unwind",
"arch_bpf_stack_walk_ra",
"bpf_exc_check_info",
"bpf_exc_check_prog",
"bpf_exc_patch_unwind_calls",
"bpf_exc_fill_native_ranges",
"bpf_exc_pad_for_ip",
"bpf_jit_supports_cleanup_pads"
],
"Reasoning": "The patch introduces BPF exception cleanup landing pads and unwinding support (via bpf_unwind and bpf_unwind_resume kfuncs). It adds kernel verification logic for exception cleanup tables, CFG analysis for landing pad edges, backtracking adjustments, instruction patching, x86 JIT epilogue handling, and stack return address rewriting via arch_bpf_stack_walk_ra() and the ORC unwinder. This touches core BPF verification and runtime execution paths reachable via the bpf() syscall on amd64, warranting fuzzing.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"BPF_SYSCALL",
"BPF_JIT",
"UNWINDER_ORC"
],
"FocusSymbols": [
"bpf_unwind",
"arch_bpf_stack_walk_ra",
"bpf_exc_check_info",
"bpf_exc_check_prog",
"bpf_exc_patch_unwind_calls",
"bpf_exc_fill_native_ranges",
"bpf_exc_pad_for_ip",
"bpf_jit_supports_cleanup_pads"
],
"Reasoning": "The patch introduces BPF exception cleanup landing pads and unwinding support (via bpf_unwind and bpf_unwind_resume kfuncs). It adds kernel verification logic for exception cleanup tables, CFG analysis for landing pad edges, backtracking adjustments, instruction patching, x86 JIT epilogue handling, and stack return address rewriting via arch_bpf_stack_walk_ra() and the ORC unwinder. This touches core BPF verification and runtime execution paths reachable via the bpf() syscall on amd64, warranting fuzzing.",
"WorthFuzzing": true
} |
| 15/1 | 2026/10/17 07:55 | action | If |
2mArgs:{
"WorthFuzzing": true
}Results: null |
| 16/2 | 2026/10/17 07:55 | agent | kmsan-evaluator |
2mModel:core Args: null Results: {
"KMSANReasoning": "The patch series introduces support for BPF exception cleanup landing pads, adding the `bpf_unwind()` and `bpf_unwind_resume()` kfuncs, stack frame return-address rewriting via `arch_bpf_stack_walk_ra()`, BPF verifier tracking for cleanup pads and unwinding edges, and ELF/loader support for `.bpf_cleanup`.\n\nFrom a memory sanitizer perspective, a dedicated KMSAN fuzzing session is not warranted:\n1. No Kernel-to-User Information Leaks: The patch adds input fields to `union bpf_attr` for `BPF_PROG_LOAD` and copies records from user memory to the kernel, but does not add or modify any data copied back to userspace (no `bpf_prog_info` extensions, `copy_to_user()`, or netlink attributes).\n2. Proper Memory Initialization: All newly introduced kernel heap objects (`struct bpf_exception_info`, `struct bpf_cleanup_range`, `struct bpf_cleanup_info`) are allocated using `kzalloc_obj()` or `kvcalloc()`, and stack variables (`struct bpf_unwind_ctx`, `struct bpf_unwind_ra_consume_entry_data`, instruction patch arrays) are zero-initialized with designated initializers or fully written before use.\n3. KASAN/LOCKDEP Applicability: The primary risks associated with this patch involve control-flow graph exploration, insn patch offsets, return address rewriting on the call stack, and lock/reference tracking across unwinds. These issues manifest as out-of-bounds memory accesses, illegal instruction dereferences, or locking mismatches, which are detected by KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN.\n\nTherefore, running a dedicated KMSAN session would provide no additional benefit over standard KASAN/LOCKDEP testing.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 48a3914cefd04f21bef6cd3ea63cd8ad35d7b0c8
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Oct 17 07:54:16 2026 +0000
syz-cluster: applied patch under review
diff --git a/arch/arm64/kernel/stacktrace.c b/arch/arm64/kernel/stacktrace.c
index 3ebcf8c53fb04..6ff485280da53 100644
--- a/arch/arm64/kernel/stacktrace.c
+++ b/arch/arm64/kernel/stacktrace.c
@@ -445,6 +445,83 @@ noinline noinstr void arch_bpf_stack_walk(bool (*consume_entry)(void *cookie, u6
kunwind_stack_walk(arch_bpf_unwind_consume_entry, &data, current, NULL);
}
+struct bpf_unwind_ra_consume_entry_data {
+ bool (*consume_entry)(void *cookie, u64 ip, u64 sp, u64 fp, u64 *ra);
+ void *cookie;
+ unsigned long record;
+ bool seen_first;
+};
+
+/* PACIA1716 (hint #8): sign x17 with the modifier in x16, under key IA. */
+static u64 bpf_unwind_sign_ra(u64 ra, u64 modifier)
+{
+ register u64 x17 asm("x17") = ra;
+ register u64 x16 asm("x16") = modifier;
+
+ asm volatile(ARM64_ASM_PREAMBLE
+ " hint #8\n"
+ : "+r" (x17) : "r" (x16));
+ return x17;
+}
+
+/* PACIASP's modifier is the entry sp, record + 16 for a BPF prologue. */
+static void bpf_unwind_store_ra(unsigned long record, u64 ra)
+{
+ struct frame_record *rec = (struct frame_record *)record;
+
+ /*
+ * Whether the slot holds a signed address is a property of the build,
+ * not one to be read off the value: a PAC can come out equal to the
+ * bits stripping puts back, and a signed address would then be taken
+ * for an unsigned one. What signs is CONFIG_ARM64_PTR_AUTH_KERNEL --
+ * the prologue here, and -mbranch-protection for everything the
+ * compiler emits.
+ */
+ if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL) &&
+ system_supports_address_auth())
+ ra = bpf_unwind_sign_ra(ra, record + sizeof(struct frame_record));
+ WRITE_ONCE(rec->lr, ra);
+}
+
+static bool
+arch_bpf_unwind_ra_consume_entry(const struct kunwind_state *state, void *cookie)
+{
+ struct bpf_unwind_ra_consume_entry_data *data = cookie;
+ unsigned long record = data->record;
+ bool seen_first = data->seen_first;
+ u64 ra = state->common.pc;
+ bool cont;
+
+ /* The record this frame's return address will have come out of. */
+ data->record = state->common.fp;
+ data->seen_first = true;
+
+ /*
+ * The first pc returns into bpf_unwind(), from this walk's own frame
+ * record: not a BPF frame, and not one to redirect.
+ */
+ if (!seen_first)
+ return true;
+ /* A consumer that stops still gets to redirect the frame it stopped on. */
+ cont = data->consume_entry(data->cookie, state->common.pc, 0,
+ state->common.fp, &ra);
+ if (ra != state->common.pc)
+ bpf_unwind_store_ra(record, ra);
+ return cont;
+}
+
+noinline noinstr void arch_bpf_stack_walk_ra(bool (*consume_entry)(void *cookie, u64 ip, u64 sp,
+ u64 fp, u64 *ra),
+ void *cookie)
+{
+ struct bpf_unwind_ra_consume_entry_data data = {
+ .consume_entry = consume_entry,
+ .cookie = cookie,
+ };
+
+ kunwind_stack_walk(arch_bpf_unwind_ra_consume_entry, &data, current, NULL);
+}
+
static const char *state_source_string(const struct kunwind_state *state)
{
switch (state->source) {
diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 506c4201fec85..c8c0328b3219c 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -2422,6 +2422,17 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
* reasons, expects to point to the next instruction)
*/
bpf_prog_update_insn_ptrs(prog, ctx.offset, ctx.ro_image);
+
+ /*
+ * Same byte offsets, consumed by the bpf_unwind() walk:
+ * turn the cleanup records into native address ranges now that
+ * the image is final.
+ */
+ bpf_exc_fill_native_ranges(prog, ctx.offset, ctx.ro_image);
+
+ /* Where an unwind sends a frame with no pad. */
+ prog->aux->epilogue_ip = (u64)ctx.ro_image +
+ ctx.epilogue_offset * AARCH64_INSN_SIZE;
out_off:
if (!ro_header && priv_stack_ptr) {
free_percpu(priv_stack_ptr);
@@ -3415,6 +3426,11 @@ bool bpf_jit_supports_exceptions(void)
return true;
}
+bool bpf_jit_supports_cleanup_pads(void)
+{
+ return true;
+}
+
bool bpf_jit_supports_arena(void)
{
return true;
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 11a4e4f87aac7..e0e39661bce83 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -15,6 +15,7 @@
#include <linux/memory.h>
#include <linux/sort.h>
#include <linux/execmem.h>
+#include <linux/kprobes.h>
#include <asm/extable.h>
#include <asm/ftrace.h>
#include <asm/set_memory.h>
@@ -3779,6 +3780,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
seen_exit = true;
/* Update cleanup_addr */
ctx->cleanup_addr = proglen;
+ /* Where an unwind sends a frame with no pad. */
+ bpf_prog->aux->epilogue_ip = (u64)image + proglen;
if (bpf_prog_was_classic(bpf_prog) &&
!ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN)) {
if (emit_spectre_bhb_barrier(&prog, ip, bpf_prog))
@@ -4976,6 +4979,13 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
*/
bpf_prog_update_insn_ptrs(prog, addrs, image);
+ /*
+ * Same mapping, consumed by the bpf_unwind() walk:
+ * turn the cleanup records into native address ranges now
+ * that the image is final.
+ */
+ bpf_exc_fill_native_ranges(prog, addrs, image);
+
/*
* ctx.prog_offset is used when CFI preambles put code *before*
* the function. See emit_cfi(). For FineIBT specifically this code
@@ -5114,6 +5124,11 @@ bool bpf_jit_supports_exceptions(void)
return IS_ENABLED(CONFIG_UNWINDER_ORC);
}
+bool bpf_jit_supports_cleanup_pads(void)
+{
+ return IS_ENABLED(CONFIG_UNWINDER_ORC);
+}
+
bool bpf_jit_supports_private_stack(void)
{
return true;
@@ -5135,6 +5150,27 @@ void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp
#endif
}
+notrace void arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp,
+ u64 *ra),
+ void *cookie)
+{
+#if defined(CONFIG_UNWINDER_ORC)
+ struct unwind_state state;
+ unsigned long addr, *ra;
+
+ for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
+ unwind_next_frame(&state)) {
+ addr = state.ip;
+ ra = unwind_get_return_address_ptr(&state);
+ if (!ra)
+ break;
+ if (!consume_fn(cookie, (u64)addr, (u64)state.sp, (u64)state.bp, (u64 *)ra))
+ break;
+ }
+#endif
+}
+NOKPROBE_SYMBOL(arch_bpf_stack_walk_ra);
+
void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
struct bpf_prog *new, struct bpf_prog *old)
{
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 54144372281cb..1b3b6ee05c092 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -1841,6 +1841,34 @@ enum bpf_sig_keyring {
BPF_SIG_KEYRING_BPF,
};
+/* One cleanup region of a JITed (sub)program. */
+struct bpf_cleanup_range {
+ u64 begin;
+ u64 end;
+ u64 pad;
+};
+
+struct bpf_exception_info {
+ struct bpf_cleanup_info *info;
+ struct bpf_cleanup_range *ranges;
+ u32 nr_info;
+ u32 nr_ranges;
+};
+
+#ifdef CONFIG_BPF_SYSCALL
+void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image);
+void bpf_exc_free_info(struct bpf_prog_aux *aux);
+#else
+
+static inline void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image)
+{
+}
+
+static inline void bpf_exc_free_info(struct bpf_prog_aux *aux)
+{
+}
+#endif
+
struct bpf_prog_aux {
atomic64_t refcnt;
u32 used_map_cnt;
@@ -1882,6 +1910,7 @@ struct bpf_prog_aux {
bool priv_stack_requested;
bool changes_pkt_data;
bool might_sleep;
+ bool might_unwind;
bool kprobe_write_ctx;
struct {
s32 keyring_serial;
@@ -1922,6 +1951,8 @@ struct bpf_prog_aux {
u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64);
u16 stack_arg_sp_adjust;
u16 freplace_link_cnt; /* counts freplace links extending this prog */
+ struct bpf_exception_info *exc;
+ u64 epilogue_ip; /* native address of this (sub)program's epilogue */
#ifdef CONFIG_SECURITY
void *security;
#endif
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 112ca1511da4d..1c33b2cf29cfe 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -379,6 +379,7 @@ struct bpf_func_state {
bool in_async_callback_fn;
bool in_exception_callback_fn;
bool no_stack_arg_load;
+ bool in_pad;
/* For callback calling functions that limit number of possible
* callback executions (e.g. bpf_loop) keeps track of current
* simulated iteration number.
@@ -429,6 +430,8 @@ enum {
INSN_F_SRC_REG_STACK = BIT(2), /* src_reg is PTR_TO_STACK */
INSN_F_STACK_ARG_ACCESS = BIT(3),
+
+ INSN_F_UNWIND = BIT(4),
};
/* Registers linked to one jump condition that a history entry can record */
@@ -437,10 +440,10 @@ enum {
struct bpf_jmp_history_entry {
/* insn idx can't be bigger than 1 million */
u32 idx : 20;
- u32 frame : 4; /* stack access frame number */
+ u32 frame : 4; /* stack access frame number, or the frame an unwind ran in */
/* special INSN_F_xxx flags */
- u32 flags : 4;
- u32 : 4;
+ u32 flags : 5;
+ u32 : 3;
u32 prev_idx : 20;
u32 spi : 12; /* stack slot index */
/*
@@ -527,6 +530,8 @@ struct bpf_verifier_state {
bool speculative;
bool in_sleepable;
+ /* the path ends with an unwind returning from frame 0 */
+ bool unwind_exit;
/*
* First and last insn idx of this verifier state.
@@ -806,6 +811,11 @@ struct bpf_insn_aux_data {
u64 jump_target:1;
unsigned int orig_idx; /* original instruction index, initialized once */
+ /*
+ * 1 + the instruction index of the exception cleanup landing pad
+ * this call site unwinds to, or 0 for none.
+ */
+ u32 cleanup_pad;
/*
* CFG strongly connected component this instruction belongs to,
* zero if it is a singleton SCC.
@@ -944,6 +954,7 @@ struct bpf_subprog_info {
s16 fastcall_stack_off;
bool has_tail_call: 1;
bool might_throw: 1;
+ bool might_unwind: 1;
bool tail_call_reachable: 1;
bool has_ld_abs: 1;
bool is_cb: 1;
@@ -1135,6 +1146,8 @@ struct bpf_verifier_env {
struct spill_snapshot **callsite_at_stack;
u32 pass_cnt; /* number of times do_check() was called */
u32 subprog_cnt;
+ struct bpf_cleanup_info *cleanup_info;
+ u32 cleanup_info_cnt;
/* number of instructions analyzed by the verifier */
u32 prev_insn_processed, insn_processed;
/* number of jmps, calls, exits analyzed so far */
@@ -1990,6 +2003,7 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union
int bpf_convert_ctx_accesses(struct bpf_verifier_env *env);
int bpf_jit_subprogs(struct bpf_verifier_env *env);
int bpf_fixup_call_args(struct bpf_verifier_env *env);
+int bpf_exc_patch_unwind_calls(struct bpf_verifier_env *env);
int bpf_do_misc_fixups(struct bpf_verifier_env *env);
int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 9339c6131f8ff..a61a78675d11e 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -1248,6 +1248,7 @@ bool bpf_jit_supports_stack_args(void);
bool bpf_jit_supports_arena_args(void);
bool bpf_jit_supports_far_kfunc_call(void);
bool bpf_jit_supports_exceptions(void);
+bool bpf_jit_supports_cleanup_pads(void);
bool bpf_jit_supports_ptr_xchg(void);
bool bpf_jit_supports_arena(void);
bool bpf_jit_supports_arena_scalar(void);
@@ -1290,6 +1291,8 @@ u32 bpf_jit_plan_arg_moves(const struct bpf_jit_arg_abi *abi,
struct bpf_jit_arg_move *moves);
u64 bpf_arch_uaddress_limit(void);
void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie);
+void arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp, u64 *ra),
+ void *cookie);
u64 arch_bpf_timed_may_goto(void);
u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *);
bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id);
diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h
index 6f70db7515dd4..9d7439c96e52e 100644
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -1708,6 +1708,9 @@ union bpf_attr {
* verification.
*/
__s32 keyring_id;
+ __aligned_u64 cleanup_info; /* exception cleanup table */
+ __u32 cleanup_info_rec_size; /* userspace bpf_cleanup_info size */
+ __u32 cleanup_info_cnt; /* number of bpf_cleanup_info records */
};
struct { /* anonymous struct used by BPF_OBJ_* commands */
@@ -7669,6 +7672,17 @@ struct bpf_line_info {
__u32 line_col;
};
+/*
+ * One record of an exception cleanup table: calls in [begin_off, end_off)
+ * that unwind resume at landing_pad_off. All three are instruction offsets
+ * in the program as loaded.
+ */
+struct bpf_cleanup_info {
+ __u32 begin_off;
+ __u32 end_off;
+ __u32 landing_pad_off;
+};
+
struct bpf_spin_lock {
__u32 val;
};
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index 269810b128c46..df71ec19d0a04 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_
obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o
+obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o exception.o
obj-${CONFIG_BPF_LSM} += bpf_inode_storage.o
obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
obj-$(CONFIG_BPF_JIT) += trampoline.o
diff --git a/kernel/bpf/backtrack.c b/kernel/bpf/backtrack.c
index 43d5740034c0f..16f6ef59ddf75 100644
--- a/kernel/bpf/backtrack.c
+++ b/kernel/bpf/backtrack.c
@@ -4,6 +4,7 @@
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <linux/bitmap.h>
+#include "exception.h"
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
@@ -424,7 +425,31 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
if (class == BPF_STX)
bt_set_reg(bt, sreg);
} else if (class == BPF_JMP || class == BPF_JMP32) {
- if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {
+ if (hist && (hist->flags & INSN_F_UNWIND)) {
+ /*
+ * A bpf_unwind(), a resume or an unwinding global call
+ * left frame hist->frame here, for a landing pad in
+ * this one, or for the main frame's exit, which is
+ * this frame itself when it is the main one. The walk
+ * crosses back into that frame, past any frames
+ * between, which were entered and never returned
+ * from. The pad found r0 unknown and r1-r5 clobbered;
+ * r6-r9 and the stack are this frame's own and stay
+ * marked in its masks until the walk comes back out.
+ */
+ bt_clear_reg(bt, BPF_REG_0);
+ if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
+ verifier_bug(env, "backtracking unwind unexpected regs %x",
+ bt_reg_mask(bt));
+ return -EFAULT;
+ }
+ if (verifier_bug_if(hist->frame < bt->frame, env,
+ "unwind from frame %d to frame %d",
+ hist->frame, bt->frame))
+ return -EFAULT;
+ bt->frame = hist->frame;
+ return 0;
+ } else if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {
int subprog_insn_idx, subprog = -1;
if (bpf_pseudo_call(insn)) {
@@ -440,10 +465,17 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
* extra instructions from subprog; the next
* instruction after call to global subprog
* should be literally next instruction in
- * caller program
+ * caller program, or the call's landing pad,
+ * branched to from the state the call returns
+ * in when the callee can unwind. A pad may be
+ * the next instruction too, so the two edges
+ * cannot be told apart, and need not be: the
+ * pad finds r0 unknown and r1-r5 cleared, so
+ * both clear the same registers below.
*/
- verifier_bug_if(idx + 1 != subseq_idx, env,
- "extra insn from subprog");
+ verifier_bug_if(idx + 1 != subseq_idx &&
+ bpf_exc_pad_of_call(env, idx) != subseq_idx,
+ env, "extra insn from subprog");
/* global subprog always sets R0 */
bt_clear_reg(bt, BPF_REG_0);
/* and if it does not set R2, main pass would catch it */
diff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c
index bce7b5abcfda3..9608293bdc069 100644
--- a/kernel/bpf/cfg.c
+++ b/kernel/bpf/cfg.c
@@ -6,6 +6,7 @@
#include <linux/sort.h>
#include "diagnostics.h"
+#include "exception.h"
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
@@ -75,6 +76,14 @@ static void mark_subprog_might_throw(struct bpf_verifier_env *env, int off)
subprog->might_throw = true;
}
+static void mark_subprog_might_unwind(struct bpf_verifier_env *env, int off)
+{
+ struct bpf_subprog_info *subprog;
+
+ subprog = bpf_find_containing_subprog(env, off);
+ subprog->might_unwind = true;
+}
+
/* 't' is an index of a call-site.
* 'w' is a callee entry point.
* Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
@@ -90,6 +99,7 @@ static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
caller->changes_pkt_data |= callee->changes_pkt_data;
caller->might_sleep |= callee->might_sleep;
caller->might_throw |= callee->might_throw;
+ caller->might_unwind |= callee->might_unwind;
}
enum {
@@ -160,6 +170,38 @@ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
return DONE_EXPLORING;
}
+static int visit_cleanup_pad_edge(int t, struct bpf_verifier_env *env)
+{
+ int *insn_stack = env->cfg.insn_stack;
+ int *insn_state = env->cfg.insn_state;
+ int w;
+
+ if (!env->cleanup_info_cnt)
+ return DONE_EXPLORING;
+ w = bpf_exc_pad_of_call(env, t);
+ if (w < 0)
+ return DONE_EXPLORING;
+
+ /*
+ * @t is a call that may branch here, and @w is the target of that
+ * branch, so both are prune points. @w especially: every covered call
+ * site in a region unwinds to the same pad, and without a prune point
+ * at its head the verifier walks the pad again for each of them.
+ */
+ mark_prune_point(env, t);
+ mark_prune_point(env, w);
+ mark_jmp_point(env, w);
+ mark_jump_target(env, w);
+
+ if (insn_state[w])
+ return DONE_EXPLORING;
+ if (env->cfg.cur_stack >= env->prog->len)
+ return -E2BIG;
+ insn_stack[env->cfg.cur_stack++] = w;
+ insn_state[w] |= DISCOVERED;
+ return KEEP_EXPLORING;
+}
+
static int visit_func_call_insn(int t, struct bpf_insn *insns,
struct bpf_verifier_env *env,
bool visit_callee)
@@ -167,6 +209,11 @@ static int visit_func_call_insn(int t, struct bpf_insn *insns,
int ret, insn_sz;
int w;
+ /* One push per visit: @t is revisited once the pad is explored. */
+ ret = visit_cleanup_pad_edge(t, env);
+ if (ret != DONE_EXPLORING)
+ return ret;
+
insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
if (ret)
@@ -630,6 +677,8 @@ static int visit_insn(int t, struct bpf_verifier_env *env)
mark_subprog_changes_pkt_data(env, t);
if (ret == 0 && bpf_is_throw_kfunc(insn))
mark_subprog_might_throw(env, t);
+ if (ret == 0 && bpf_is_unwind_kfunc(insn))
+ mark_subprog_might_unwind(env, t);
}
return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
@@ -667,6 +716,82 @@ static int visit_insn(int t, struct bpf_verifier_env *env)
}
}
+static bool addr_taken_subprog_might_unwind(struct bpf_verifier_env *env)
+{
+ struct bpf_insn *insns = env->prog->insnsi;
+ struct bpf_subprog_info *callee;
+ struct bpf_func_ptr *ptrs;
+ u32 cnt, j;
+ int i;
+
+ for (i = 0; i < env->prog->len; i++) {
+ if (bpf_pseudo_func(&insns[i])) {
+ callee = bpf_find_containing_subprog(env, i + insns[i].imm + 1);
+ if (callee->might_unwind)
+ return true;
+ continue;
+ }
+ ptrs = insn_func_ptrs(env, i, &cnt);
+ for (j = 0; j < cnt; j++) {
+ callee = bpf_find_containing_subprog(env, ptrs[j].xlated_off);
+ if (callee->might_unwind)
+ return true;
+ }
+ }
+ return false;
+}
+
+/*
+ * merge_callee_effects() does not carry might_unwind to a subprog that calls
+ * through a pointer it was handed. So if any subprog a callx can reach may
+ * unwind, mark every subprog with a callx, and its callers.
+ *
+ * This is conservative: a subprog with a callx is marked even when nothing it
+ * calls unwinds. The main walk knows each callx's target and could tell those
+ * apart.
+ */
+static void mark_callx_might_unwind(struct bpf_verifier_env *env)
+{
+ struct bpf_insn *insns = env->prog->insnsi;
+ struct bpf_subprog_info *caller, *callee;
+ int i, j, len = env->prog->len;
+ struct bpf_func_ptr *ptrs;
+ bool changed;
+ u32 cnt;
+
+ if (!addr_taken_subprog_might_unwind(env))
+ return;
+
+ for (i = 0; i < len; i++)
+ if (bpf_is_callx(&insns[i]))
+ bpf_find_containing_subprog(env, i)->might_unwind = true;
+
+ do {
+ changed = false;
+ for (i = 0; i < len; i++) {
+ caller = bpf_find_containing_subprog(env, i);
+ if (caller->might_unwind)
+ continue;
+ if (bpf_pseudo_call(&insns[i]) || bpf_pseudo_func(&insns[i])) {
+ callee = bpf_find_containing_subprog(env, i + insns[i].imm + 1);
+ if (!callee->might_unwind)
+ continue;
+ caller->might_unwind = true;
+ changed = true;
+ continue;
+ }
+ ptrs = insn_func_ptrs(env, i, &cnt);
+ for (j = 0; j < cnt; j++) {
+ callee = bpf_find_containing_subprog(env, ptrs[j].xlated_off);
+ if (!callee->might_unwind)
+ continue;
+ caller->might_unwind = true;
+ changed = true;
+ }
+ }
+ } while (changed);
+}
+
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
@@ -757,6 +882,7 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
}
}
ret = 0; /* cfg looks good */
+ mark_callx_might_unwind(env);
env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 642f0ab8eb2d8..3af8e82726917 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -292,6 +292,7 @@ void __bpf_prog_free(struct bpf_prog *fp)
mutex_destroy(&fp->aux->dst_mutex);
mutex_destroy(&fp->aux->st_ops_assoc_mutex);
kfree(fp->aux->poke_tab);
+ bpf_exc_free_info(fp->aux);
kfree(fp->aux);
}
free_percpu(fp->stats);
@@ -3524,6 +3525,17 @@ void __weak arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp,
{
}
+void __weak arch_bpf_stack_walk_ra(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp,
+ u64 *ra),
+ void *cookie)
+{
+}
+
+bool __weak bpf_jit_supports_cleanup_pads(void)
+{
+ return false;
+}
+
bool __weak bpf_jit_supports_timed_may_goto(void)
{
return false;
diff --git a/kernel/bpf/exception.c b/kernel/bpf/exception.c
new file mode 100644
index 0000000000000..e06f2606b41e7
--- /dev/null
+++ b/kernel/bpf/exception.c
@@ -0,0 +1,379 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf_ids.h>
+#include <linux/filter.h>
+#include <linux/slab.h>
+#include "exception.h"
+
+#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
+
+#define MIN_BPF_CLEANUP_INFO_SIZE 12
+#define MAX_CLEANUP_INFO_REC_SIZE 252 /* as MAX_FUNCINFO_REC_SIZE */
+
+int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
+ bpfptr_t uattr)
+{
+ u32 krec_size = sizeof(struct bpf_cleanup_info);
+ u32 i, nrec, urec_size, min_size, prev_end = 0;
+ struct bpf_cleanup_info *krecord;
+ bpfptr_t urecord;
+ int ret = -EINVAL;
+
+ nrec = attr->cleanup_info_cnt;
+ if (!nrec)
+ return 0;
+ if (nrec > env->prog->len) {
+ verbose(env, "cleanup info has %u records for %u instructions\n",
+ nrec, env->prog->len);
+ return -EINVAL;
+ }
+
+ urec_size = attr->cleanup_info_rec_size;
+ if (urec_size < MIN_BPF_CLEANUP_INFO_SIZE ||
+ urec_size > MAX_CLEANUP_INFO_REC_SIZE ||
+ urec_size % sizeof(u32)) {
+ verbose(env, "invalid cleanup info rec size %u\n", urec_size);
+ return -EINVAL;
+ }
+
+ krecord = kvcalloc(nrec, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ if (!krecord)
+ return -ENOMEM;
+
+ min_size = min_t(u32, krec_size, urec_size);
+ urecord = make_bpfptr(attr->cleanup_info, uattr.is_kernel);
+ for (i = 0; i < nrec; i++) {
+ struct bpf_subprog_info *sb, *se, *sl;
+ struct bpf_cleanup_info *rec = &krecord[i];
+
+ /*
+ * A record longer than the kernel's is taken only if the rest
+ * is zero. Unlike func_info, no size is handed back for the
+ * loader to zero the rest and retry: a field this kernel does
+ * not know could change what a pad does.
+ */
+ ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
+ if (ret) {
+ if (ret == -E2BIG)
+ verbose(env, "nonzero tailing record in cleanup info\n");
+ goto err_free;
+ }
+
+ if (copy_from_bpfptr(rec, urecord, min_size)) {
+ ret = -EFAULT;
+ goto err_free;
+ }
+ bpfptr_add(&urecord, urec_size);
+
+ ret = -EINVAL;
+ if (rec->begin_off >= rec->end_off) {
+ verbose(env, "cleanup_info[%u]: begin %u >= end %u\n",
+ i, rec->begin_off, rec->end_off);
+ goto err_free;
+ }
+ if (rec->begin_off < prev_end) {
+ verbose(env,
+ "cleanup_info[%u]: range [%u,%u) is unsorted or overlaps the previous record\n",
+ i, rec->begin_off, rec->end_off);
+ goto err_free;
+ }
+ prev_end = rec->end_off;
+
+ sb = bpf_find_containing_subprog(env, rec->begin_off);
+ se = bpf_find_containing_subprog(env, rec->end_off - 1);
+ sl = bpf_find_containing_subprog(env, rec->landing_pad_off);
+ if (!sb || !se || !sl) {
+ verbose(env, "cleanup_info[%u]: offset out of range\n", i);
+ goto err_free;
+ }
+ if (sb != se || sb != sl) {
+ verbose(env,
+ "cleanup_info[%u]: range/landing pad span multiple subprogs\n",
+ i);
+ goto err_free;
+ }
+ /*
+ * A zero opcode is the second half of a 16-byte insn, not an
+ * insn. end_off is exclusive, so it may be one past the last.
+ */
+ if (!env->prog->insnsi[rec->begin_off].code ||
+ !env->prog->insnsi[rec->landing_pad_off].code ||
+ (rec->end_off < env->prog->len &&
+ !env->prog->insnsi[rec->end_off].code)) {
+ verbose(env, "cleanup_info[%u]: points at invalid insn\n", i);
+ goto err_free;
+ }
+ }
+
+ /* Reject a landing pad inside any call-site range, its own included. */
+ ret = -EINVAL;
+ for (i = 0; i < nrec; i++) {
+ u32 pad = krecord[i].landing_pad_off;
+ u32 l = 0, r = nrec;
+
+ while (l < r) {
+ u32 m = l + (r - l) / 2;
+
+ if (pad < krecord[m].begin_off) {
+ r = m;
+ } else if (pad >= krecord[m].end_off) {
+ l = m + 1;
+ } else {
+ verbose(env,
+ "cleanup_info[%u]: landing pad %u is inside the call-site range of cleanup_info[%u]\n",
+ i, pad, m);
+ goto err_free;
+ }
+ }
+ }
+
+ env->cleanup_info = krecord;
+ env->cleanup_info_cnt = nrec;
+ return 0;
+
+err_free:
+ kvfree(krecord);
+ return ret;
+}
+
+BTF_ID_LIST_SINGLE(bpf_unwind_id, func, bpf_unwind)
+BTF_ID_LIST_SINGLE(bpf_unwind_resume_id, func, bpf_unwind_resume)
+
+int bpf_exc_check_callback(struct bpf_verifier_env *env, int subprog)
+{
+ if (!env->subprog_info[subprog].might_unwind)
+ return 0;
+
+ verbose(env, "subprog %d may unwind and is used as a callback\n", subprog);
+ return -EINVAL;
+}
+
+static int reject_throw(struct bpf_verifier_env *env)
+{
+ u32 i;
+
+ for (i = 0; i < env->prog->len; i++) {
+ if (!bpf_is_throw_kfunc(&env->prog->insnsi[i]))
+ continue;
+ verbose(env,
+ "exception cleanup cannot be combined with bpf_throw at insn %u\n",
+ i);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+void bpf_exc_mark_call_sites(struct bpf_verifier_env *env)
+{
+ u32 i, j;
+
+ for (i = 0; i < env->cleanup_info_cnt; i++) {
+ struct bpf_cleanup_info *rec = &env->cleanup_info[i];
+
+ for (j = rec->begin_off; j < rec->end_off; j++) {
+ struct bpf_insn *insn = &env->prog->insnsi[j];
+
+ if (!bpf_pseudo_call(insn) && !bpf_is_callx(insn) &&
+ !bpf_is_unwind_kfunc(insn))
+ continue;
+ env->insn_aux_data[j].cleanup_pad = rec->landing_pad_off + 1;
+ }
+ }
+}
+
+bool bpf_prog_may_unwind(const struct bpf_verifier_env *env)
+{
+ u32 i;
+
+ for (i = 0; i < env->subprog_cnt; i++)
+ if (env->subprog_info[i].might_unwind)
+ return true;
+ return false;
+}
+
+int bpf_exc_check_prog(struct bpf_verifier_env *env)
+{
+ int err;
+
+ if (bpf_prog_is_offloaded(env->prog->aux)) {
+ verbose(env,
+ "exception cleanup is not supported for offloaded programs\n");
+ return -EINVAL;
+ }
+ if (!bpf_jit_supports_cleanup_pads() || !env->prog->jit_requested) {
+ verbose(env,
+ "exception cleanup needs a JIT that can dispatch landing pads\n");
+ return -EOPNOTSUPP;
+ }
+ if (env->ops->gen_epilogue) {
+ verbose(env,
+ "exception cleanup is not supported for a program with an epilogue\n");
+ return -EOPNOTSUPP;
+ }
+ if (env->exception_callback_subprog) {
+ verbose(env,
+ "exception cleanup cannot be combined with an exception callback\n");
+ return -EINVAL;
+ }
+ err = reject_throw(env);
+ if (err)
+ return err;
+ env->prog->jit_required = 1;
+ return 0;
+}
+
+bool bpf_is_unwind_kfunc(const struct bpf_insn *insn)
+{
+ return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+ insn->imm == bpf_unwind_id[0];
+}
+
+bool bpf_is_unwind_resume_kfunc(const struct bpf_insn *insn)
+{
+ return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+ insn->imm == bpf_unwind_resume_id[0];
+}
+
+static bool unwinding(const struct bpf_verifier_state *state)
+{
+ u32 i;
+
+ for (i = 0; i <= state->curframe; i++)
+ if (state->frame[i]->in_pad)
+ return true;
+ return false;
+}
+
+int bpf_exc_check_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
+{
+ bool in_pad = cur_func(env)->in_pad;
+ u32 i = env->insn_idx;
+ const char *why = NULL;
+
+ if (unwinding(env->cur_state)) {
+ if (bpf_is_unwind_kfunc(insn)) {
+ verbose(env, "insn %u starts a second unwind while one is in flight\n", i);
+ return -EINVAL;
+ }
+ if (bpf_pseudo_call(insn)) {
+ int subprog = bpf_find_subprog(env, i + insn->imm + 1);
+
+ if (bpf_subprog_is_global(env, subprog) &&
+ env->subprog_info[subprog].might_unwind) {
+ verbose(env,
+ "insn %u calls global subprog %d, which can unwind while an unwind is in flight\n",
+ i, subprog);
+ return -EINVAL;
+ }
+ }
+ }
+
+ if (!in_pad)
+ return 0;
+
+ if (insn->code == (BPF_JMP | BPF_EXIT)) {
+ verbose(env,
+ "exit at insn %u ends a landing pad: a catch pad is not supported yet, only cleanup pads that resume\n",
+ i);
+ return -EINVAL;
+ }
+ if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call)
+ why = "is a tail call, which replaces the frame";
+ else if (BPF_CLASS(insn->code) == BPF_LD &&
+ (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND))
+ why = "is a BPF_LD_[ABS|IND], which can leave through the epilogue";
+ else if (insn_is_gotox(insn))
+ why = "is an indirect jump, which nothing a compiler frontend emits in a pad needs";
+
+ if (!why)
+ return 0;
+
+ verbose(env, "insn %u %s, and is in a landing pad\n", i, why);
+ return -EINVAL;
+}
+
+int bpf_exc_pad_of_call(struct bpf_verifier_env *env, u32 idx)
+{
+ u32 pad = env->insn_aux_data[idx].cleanup_pad;
+
+ return pad ? (int)pad - 1 : -1;
+}
+
+/*
+ * The record covering @ip, which is a return address: the call it belongs to
+ * is the instruction before it, so a range matches on begin < ip <= end.
+ */
+const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip)
+{
+ const struct bpf_exception_info *exc = prog->aux->exc;
+ u32 l = 0, r = exc ? exc->nr_ranges : 0;
+
+ while (l < r) {
+ u32 m = l + (r - l) / 2;
+ const struct bpf_cleanup_range *rec = &exc->ranges[m];
+
+ if (ip <= rec->begin)
+ r = m;
+ else if (ip > rec->end)
+ l = m + 1;
+ else
+ return rec;
+ }
+ return NULL;
+}
+
+int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt)
+{
+ struct bpf_cleanup_range *ranges;
+ struct bpf_exception_info *exc;
+
+ exc = kzalloc_obj(struct bpf_exception_info, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ ranges = kvcalloc(cnt, sizeof(*ranges), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ if (!exc || !ranges) {
+ kfree(exc);
+ kvfree(ranges);
+ kvfree(recs);
+ return -ENOMEM;
+ }
+
+ exc->info = recs;
+ exc->nr_info = cnt;
+ exc->ranges = ranges;
+ /* Withheld until the JIT has filled the table in. */
+ exc->nr_ranges = 0;
+ aux->exc = exc;
+ return 0;
+}
+
+void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image)
+{
+ struct bpf_exception_info *exc = prog->aux->exc;
+ u32 i, n;
+
+ if (!exc)
+ return;
+
+ n = exc->nr_info;
+ for (i = 0; i < n; i++) {
+ const struct bpf_cleanup_info *rec = &exc->info[i];
+
+ exc->ranges[i].begin = (u64)(long)image + addrs[rec->begin_off];
+ exc->ranges[i].end = (u64)(long)image + addrs[rec->end_off];
+ exc->ranges[i].pad = (u64)(long)image + addrs[rec->landing_pad_off];
+ }
+ exc->nr_ranges = n;
+}
+
+void bpf_exc_free_info(struct bpf_prog_aux *aux)
+{
+ struct bpf_exception_info *exc = aux->exc;
+
+ if (!exc)
+ return;
+ kvfree(exc->ranges);
+ kvfree(exc->info);
+ kfree(exc);
+ aux->exc = NULL;
+}
diff --git a/kernel/bpf/exception.h b/kernel/bpf/exception.h
new file mode 100644
index 0000000000000..09bbcd0a09de3
--- /dev/null
+++ b/kernel/bpf/exception.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#ifndef __BPF_EXCEPTION_H
+#define __BPF_EXCEPTION_H
+
+#include <linux/bpfptr.h>
+#include <linux/types.h>
+
+union bpf_attr;
+struct bpf_verifier_env;
+struct bpf_insn;
+struct bpf_cleanup_info;
+struct bpf_cleanup_range;
+struct bpf_prog;
+struct bpf_prog_aux;
+
+int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
+ bpfptr_t uattr);
+void bpf_exc_mark_call_sites(struct bpf_verifier_env *env);
+int bpf_exc_check_prog(struct bpf_verifier_env *env);
+bool bpf_prog_may_unwind(const struct bpf_verifier_env *env);
+int bpf_exc_pad_of_call(struct bpf_verifier_env *env, u32 idx);
+bool bpf_is_unwind_kfunc(const struct bpf_insn *insn);
+bool bpf_is_unwind_resume_kfunc(const struct bpf_insn *insn);
+int bpf_exc_check_callback(struct bpf_verifier_env *env, int subprog);
+int bpf_exc_check_insn(struct bpf_verifier_env *env, struct bpf_insn *insn);
+int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt);
+const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip);
+
+#endif /* __BPF_EXCEPTION_H */
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 608621d7f225c..dd29ead32cf33 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -9,6 +9,7 @@
#include <linux/sched/signal.h>
#include <net/xdp.h>
#include "disasm.h"
+#include "exception.h"
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
@@ -244,11 +245,20 @@ static void adjust_insn_aux_data(struct bpf_verifier_env *env,
data[i].non_stack_access =
data[off + cnt - 1].non_stack_access;
data[off + cnt - 1].non_stack_access = false;
+ data[i].cleanup_pad = data[off + cnt - 1].cleanup_pad;
+ data[off + cnt - 1].cleanup_pad = 0;
+ data[i].arg_prog = data[off + cnt - 1].arg_prog;
+ data[off + cnt - 1].arg_prog = 0;
} else if (bpf_is_mem_insn(insn + i)) {
data[i].non_stack_access = true;
}
}
+ if (env->cleanup_info_cnt)
+ for (i = 0; i < prog_len; i++)
+ if (data[i].cleanup_pad > off + 1)
+ data[i].cleanup_pad += cnt - 1;
+
/*
* Last slot instruction could be a newly generated
* BPF_ST/BPF_LDX/BPF_STX, systematically mark it for non-stack access
@@ -604,6 +614,7 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
unsigned int orig_prog_len = env->prog->len;
int err;
+ u32 i;
if (bpf_rewrite_must_abort())
return -EINTR;
@@ -634,6 +645,17 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
sizeof(*aux_data) * (orig_prog_len - off - cnt));
env->insn_aux_data_len -= cnt;
+ if (env->cleanup_info_cnt) {
+ for (i = 0; i < env->insn_aux_data_len; i++) {
+ u32 pad = aux_data[i].cleanup_pad;
+
+ if (pad > off + cnt)
+ aux_data[i].cleanup_pad = pad - cnt;
+ else if (pad > off)
+ aux_data[i].cleanup_pad = 0;
+ }
+ }
+
return 0;
}
@@ -707,13 +729,63 @@ static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env)
}
}
+/*
+ * The walk sends a frame that a callee unwinds through to its epilogue, which
+ * the x86 JIT emits at the first exit, so keep one. A frame that only unwinds
+ * may have none: put one after its last insn.
+ */
+static int keep_subprog_exits(struct bpf_verifier_env *env)
+{
+ struct bpf_insn patch[2] = { {}, BPF_EXIT_INSN() };
+ struct bpf_prog *new_prog;
+ u32 i, j;
+
+ for (i = 0; i < env->subprog_cnt; i++) {
+ u32 start, end;
+ bool found = false;
+
+ if (!env->subprog_info[i].might_unwind)
+ continue;
+ start = env->subprog_info[i].start;
+ if (!env->insn_aux_data[start].seen)
+ continue;
+
+ end = env->subprog_info[i + 1].start;
+ for (j = end; j-- > start; ) {
+ if (env->prog->insnsi[j].code == (BPF_JMP | BPF_EXIT)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ struct bpf_insn_aux_data aux = env->insn_aux_data[end - 1];
+
+ patch[0] = env->prog->insnsi[end - 1];
+ new_prog = bpf_patch_insn_data(env, end - 1, patch, 2);
+ if (!new_prog)
+ return -ENOMEM;
+ env->prog = new_prog;
+ env->insn_aux_data[end - 1] = aux;
+ memset(&env->insn_aux_data[end], 0, sizeof(aux));
+ j = end;
+ }
+ env->insn_aux_data[j].seen = env->pass_cnt;
+ }
+ return 0;
+}
+
int bpf_opt_remove_dead_code(struct bpf_verifier_env *env)
{
- struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
- int insn_cnt = env->prog->len;
- int i, err;
+ struct bpf_insn_aux_data *aux_data;
+ int i, insn_cnt, err;
keep_funcs_with_addr_taken(env);
+ err = keep_subprog_exits(env);
+ if (err)
+ return err;
+
+ aux_data = env->insn_aux_data;
+ insn_cnt = env->prog->len;
for (i = 0; i < insn_cnt; i++) {
int j;
@@ -739,7 +811,7 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env)
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
bool is_may_goto_0, is_ja;
- int i, err;
+ int i, j, err;
for (i = 0; i < insn_cnt; i++) {
is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
@@ -750,6 +822,11 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env)
if (aux[i].indirect_target)
continue;
+ if (env->cleanup_info_cnt)
+ for (j = 0; j < insn_cnt; j++)
+ if (aux[j].cleanup_pad == i + 1)
+ aux[j].cleanup_pad = i + 2;
+
err = verifier_remove_insns(env, i, 1);
if (err)
return err;
@@ -1249,6 +1326,40 @@ static int resolve_func_ptrs(struct bpf_verifier_env *env, struct bpf_prog *prog
return 0;
}
+static int exc_info_for_subprog(struct bpf_verifier_env *env, struct bpf_prog *sub,
+ u32 start, u32 end)
+{
+ struct bpf_cleanup_info *recs;
+ u32 i, cnt = 0;
+
+ if (!env->cleanup_info_cnt)
+ return 0;
+
+ for (i = start; i < end; i++) {
+ if (env->insn_aux_data[i].cleanup_pad)
+ cnt++;
+ }
+ if (!cnt)
+ return 0;
+
+ recs = kvmalloc_array(cnt, sizeof(*recs), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ if (!recs)
+ return -ENOMEM;
+
+ for (i = start, cnt = 0; i < end; i++) {
+ u32 pad = env->insn_aux_data[i].cleanup_pad;
+
+ if (!pad)
+ continue;
+ pad--;
+ recs[cnt].begin_off = i - start;
+ recs[cnt].end_off = i - start + 1;
+ recs[cnt].landing_pad_off = pad - start;
+ cnt++;
+ }
+ return bpf_exc_attach_info(sub->aux, recs, cnt);
+}
+
static int jit_subprogs(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog, **func, *tmp;
@@ -1256,7 +1367,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
struct bpf_map *map_ptr;
struct bpf_insn *insn;
void *old_bpf_func;
- int err, num_exentries;
+ int err, exc_err, num_exentries;
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
@@ -1383,9 +1494,15 @@ static int jit_subprogs(struct bpf_verifier_env *env)
func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
+ func[i]->aux->might_unwind = env->subprog_info[i].might_unwind;
func[i]->aux->token = prog->aux->token;
if (!i)
func[i]->aux->exception_boundary = env->seen_exception;
+ exc_err = exc_info_for_subprog(env, func[i], subprog_start, subprog_end);
+ if (exc_err) {
+ err = exc_err;
+ goto out_free;
+ }
func[i] = bpf_int_jit_compile(env, func[i]);
if (!func[i]->jited) {
err = -ENOTSUPP;
@@ -1495,6 +1612,9 @@ static int jit_subprogs(struct bpf_verifier_env *env)
prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
prog->aux->exception_boundary = func[0]->aux->exception_boundary;
prog->aux->stack_arg_sp_adjust = func[0]->aux->stack_arg_sp_adjust;
+ prog->aux->exc = func[0]->aux->exc;
+ func[0]->aux->exc = NULL;
+ prog->aux->epilogue_ip = func[0]->aux->epilogue_ip;
bpf_prog_jit_attempt_done(prog);
return 0;
out_free:
@@ -1720,6 +1840,48 @@ static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off,
return cnt + tail_cnt;
}
+/*
+ * Follow each bpf_unwind() call with 'r0 = 0; exit', or with
+ * 'r0 = 0; goto pad' where a record covers the call.
+ */
+int bpf_exc_patch_unwind_calls(struct bpf_verifier_env *env)
+{
+ int insn_cnt = env->prog->len;
+ struct bpf_insn insn_buf[3];
+ struct bpf_prog *new_prog;
+ int i, off, delta = 0;
+
+ if (!bpf_prog_may_unwind(env))
+ return 0;
+
+ for (i = 0; i < insn_cnt; i++) {
+ int call = i + delta, pad;
+ struct bpf_insn *insn = env->prog->insnsi + call;
+
+ if (!bpf_is_unwind_kfunc(insn))
+ continue;
+
+ insn_buf[0] = *insn;
+ insn_buf[1] = BPF_MOV64_IMM(BPF_REG_0, 0);
+ insn_buf[2] = BPF_EXIT_INSN();
+ pad = bpf_exc_pad_of_call(env, call);
+ if (pad >= 0) {
+ /* The goto is at call + 2; a pad after the call moves down by 2. */
+ if (pad > call)
+ pad += 2;
+ off = pad - (call + 3);
+ insn_buf[2] = off == (s16)off ? BPF_JMP_A(off) : BPF_JMP32_A(off);
+ }
+
+ new_prog = bpf_patch_insn_data(env, call, insn_buf, 3);
+ if (!new_prog)
+ return -ENOMEM;
+ delta += 2;
+ env->prog = new_prog;
+ }
+ return 0;
+}
+
/* Do various post-verification rewrites in a single program pass.
* These rewrites simplify JIT and interpreter implementations.
*/
@@ -2112,6 +2274,25 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
goto next_insn;
if (insn->src_reg == BPF_PSEUDO_CALL)
goto next_insn;
+ if (bpf_is_unwind_resume_kfunc(insn)) {
+ /*
+ * A pad's resume is just the frame returning, to
+ * where bpf_unwind() pointed its return address: its
+ * caller's pad or epilogue, or the kernel from the main
+ * program. The verifier checked this exit with r0 a
+ * known zero, so return zero.
+ */
+ insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, 0);
+ insn_buf[1] = BPF_EXIT_INSN();
+ cnt = 2;
+ new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
+ if (!new_prog)
+ return -ENOMEM;
+ delta += cnt - 1;
+ env->prog = prog = new_prog;
+ insn = new_prog->insnsi + i + delta;
+ goto next_insn;
+ }
if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
ret = bpf_fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
if (ret)
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 439370d73cc5f..1cf7b712854b8 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -29,8 +29,10 @@
#include <linux/task_work.h>
#include <linux/irq_work.h>
#include <linux/buildid.h>
+#include <linux/kprobes.h>
#include "../../lib/kstrtox.h"
+#include "exception.h"
/* If kernel subsystem is allowing eBPF programs to call this function,
* inside its own verifier_ops->get_func_proto() callback it should return
@@ -3424,6 +3426,71 @@ static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
return false;
}
+struct bpf_unwind_ctx {
+ const struct bpf_prog_aux *aux;
+ u32 cnt;
+};
+
+static bool bpf_unwind_ip_in(const struct bpf_prog *prog, u64 ip)
+{
+ u64 start = (u64)(long)prog->bpf_func;
+
+ return ip > start && ip <= start + prog->jited_len;
+}
+
+/*
+ * The function of the calling program that @ip returns into, looked up in the
+ * program itself: its kallsyms entries can go while an instance still runs.
+ * The main function is the outer program, which holds its table and epilogue.
+ */
+static struct bpf_prog *bpf_unwind_find_prog(const struct bpf_prog_aux *aux, u64 ip)
+{
+ u32 i;
+
+ for (i = 1; i < aux->func_cnt; i++)
+ if (bpf_unwind_ip_in(aux->func[i], ip))
+ return aux->func[i];
+ return bpf_unwind_ip_in(aux->prog, ip) ? aux->prog : NULL;
+}
+
+static bool bpf_unwind_rewrite(void *cookie, u64 ip, u64 sp, u64 bp, u64 *ra)
+{
+ const struct bpf_cleanup_range *rec;
+ struct bpf_unwind_ctx *ctx = cookie;
+ struct bpf_prog *prog;
+
+ prog = bpf_unwind_find_prog(ctx->aux, ip);
+ if (!prog)
+ return !ctx->cnt;
+ ctx->cnt++;
+
+ /*
+ * The frame that called bpf_unwind(): bpf_exc_patch_unwind_calls()
+ * put 'r0 = 0' and a jump to its pad, or an exit, after the call,
+ * so leave its return address alone and let it go on there. The pad
+ * then starts with r0 at a known zero.
+ */
+ if (ctx->cnt == 1)
+ return bpf_is_subprog(prog);
+
+ rec = bpf_exc_pad_for_ip(prog, ip);
+ *ra = rec ? rec->pad : prog->aux->epilogue_ip;
+
+ return bpf_is_subprog(prog);
+}
+
+/*
+ * @aux is the calling program's, supplied by the verifier (KF_IMPLICIT_ARGS):
+ * programs call bpf_unwind() with no arguments.
+ */
+__bpf_kfunc notrace void bpf_unwind(struct bpf_prog_aux *aux)
+{
+ struct bpf_unwind_ctx ctx = { .aux = aux };
+
+ arch_bpf_stack_walk_ra(bpf_unwind_rewrite, &ctx);
+}
+NOKPROBE_SYMBOL(bpf_unwind);
+
__bpf_kfunc void bpf_throw(u64 cookie)
{
struct bpf_throw_ctx ctx = {};
@@ -3445,6 +3512,15 @@ __bpf_kfunc void bpf_throw(u64 cookie)
WARN(1, "A call to BPF exception callback should never return\n");
}
+__bpf_kfunc void bpf_unwind_resume(void *ptr__ign)
+{
+ /*
+ * Not meant to run: every call of this kfunc is to be lowered to
+ * 'r0 = 0; exit' by the verifier.
+ */
+ WARN_ONCE(1, "exception cleanup resume was not lowered to a return\n");
+}
+
__bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags)
{
struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
@@ -5115,6 +5191,8 @@ BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_throw)
+BTF_ID_FLAGS(func, bpf_unwind, KF_IMPLICIT_ARGS)
+BTF_ID_FLAGS(func, bpf_unwind_resume)
#ifdef CONFIG_BPF_EVENTS
BTF_ID_FLAGS(func, bpf_send_signal_task)
#endif
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index e657e6d95408f..8b7ee551ff6f5 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -8,6 +8,8 @@
#include <linux/slab.h>
#include <linux/sort.h>
+#include "exception.h"
+
#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
/*
@@ -404,6 +406,18 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
succ->items[succ->cnt++] = exit_idx;
}
+ /*
+ * A covered call can also leave through its landing pad. Only a call to
+ * a subprog or to bpf_unwind() is covered, so the two entries of
+ * env->succ are enough.
+ */
+ if (unlikely(env->cleanup_info_cnt)) {
+ int pad = bpf_exc_pad_of_call(env, idx);
+
+ if (pad >= 0)
+ succ->items[succ->cnt++] = pad;
+ }
+
return succ;
}
@@ -530,7 +544,8 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp
* Slot is alive if it is read before q->insn_idx in current func instance,
* or if for some outer func instance:
* - alive before callsite if callsite calls callback or is callx, otherwise
- * - alive after callsite
+ * - alive after callsite,
+ * - or alive at the landing pad a cleanup record gives the callsite
*/
struct live_stack_query *q = &env->liveness->live_stack_query;
struct func_instance *instance, *curframe_instance;
@@ -565,6 +580,13 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp
alive = callee_stack_access_at_callsite(env, callsite)
? is_live_before(instance, callsite, rel, half_spi)
: is_live_before(instance, callsite + 1, rel, half_spi);
+
+ if (!alive && unlikely(env->cleanup_info_cnt)) {
+ int pad = bpf_exc_pad_of_call(env, callsite);
+
+ if (pad >= 0)
+ alive = is_live_before(instance, pad, rel, half_spi);
+ }
if (alive)
return true;
}
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index 953700822fa73..93b5cc3a2f02d 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -201,9 +201,13 @@ static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_stat
* c. A checkpoint is reached and matched. Checkpoints are created by
* is_state_visited(), which calls maybe_enter_scc(), which allocates
* bpf_scc_visit instances for checkpoints within SCCs.
- * (c) is the only case that can reach this point.
+ * d. An unwind returns from frame 0, ending the path at a call or at
+ * the unwinding insn, which may be in an SCC as a top-level
+ * BPF_EXIT is not. Like (b), it leaves nothing to exit.
+ * (c) and (d), and a speculative path, are the only ways to reach
+ * this point.
*/
- if (!st->speculative) {
+ if (!st->speculative && !st->unwind_exit) {
verifier_bug(env, "scc exit: no visit info for call chain %s",
format_callchain(env, callchain));
return -EFAULT;
@@ -995,6 +999,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat
if (!old->no_stack_arg_load && cur->no_stack_arg_load)
return false;
+ if (old->in_pad != cur->in_pad)
+ return false;
+
for (i = 0; i < MAX_BPF_REG; i++)
if (((1 << i) & live_regs) &&
!regsafe(env, &old->regs[i], &cur->regs[i],
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 654f896af265b..10e0a693a06d5 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -2948,7 +2948,7 @@ int __init __used bpf_multi_func(void) { return 0; }
BTF_ID_LIST_GLOBAL_SINGLE(bpf_multi_func_btf_id, func, bpf_multi_func)
/* last field in 'union bpf_attr' used by this command */
-#define BPF_PROG_LOAD_LAST_FIELD keyring_id
+#define BPF_PROG_LOAD_LAST_FIELD cleanup_info_cnt
static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
{
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index ddfa0c6d2755f..505ecb8de2211 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -39,6 +39,7 @@
#include "diagnostics.h"
#include "disasm.h"
+#include "exception.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
@@ -1750,6 +1751,7 @@ int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
return err;
dst_state->speculative = src->speculative;
dst_state->in_sleepable = src->in_sleepable;
+ dst_state->unwind_exit = src->unwind_exit;
dst_state->curframe = src->curframe;
dst_state->branches = src->branches;
dst_state->parent = src->parent;
@@ -3315,6 +3317,54 @@ static void find_subprog_properties(struct bpf_verifier_env *env)
}
}
+static int subprog_falls_through(struct bpf_verifier_env *env, int subprog, int idx)
+{
+ verbose(env, "last insn is not an exit or jmp\n");
+ bpf_diag_program_structure(
+ env, idx, "subprogram can fall through",
+ "End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
+ "Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
+ subprog, idx);
+ return -EINVAL;
+}
+
+/*
+ * Put an exit after a call that ends a subprog, so that nothing from the CFG
+ * walk on has to know a subprog can end that way. check_subprogs() only lets
+ * such a call be to a callee that never returns, so do_check() never reaches
+ * the exit.
+ */
+static int add_exits_after_final_calls(struct bpf_verifier_env *env)
+{
+ struct bpf_insn patch[2] = { {}, BPF_EXIT_INSN() };
+ struct bpf_prog *new_prog;
+ int i, j;
+
+ for (i = 0; i < env->subprog_cnt; i++) {
+ int last = env->subprog_info[i + 1].start - 1;
+ struct bpf_insn *insn = &env->prog->insnsi[last];
+
+ if (!bpf_pseudo_call(insn) && !bpf_pseudo_kfunc_call(insn))
+ continue;
+ patch[0] = *insn;
+ new_prog = bpf_patch_insn_data(env, last, patch, 2);
+ if (!new_prog)
+ return -ENOMEM;
+ env->prog = new_prog;
+ /* The patch moved the call's aux data, orig_idx included, to the exit. */
+ env->insn_aux_data[last].orig_idx = env->insn_aux_data[last + 1].orig_idx;
+ /* The patch does not adjust the call itself for a callee after it. */
+ insn = &new_prog->insnsi[last];
+ if (bpf_pseudo_call(insn) && insn->imm >= 0)
+ insn->imm++;
+ /* Nor does it move the exits check_subprogs() found after it. */
+ for (j = i + 1; j < env->subprog_cnt; j++)
+ if (env->subprog_info[j].exit_idx != U32_MAX)
+ env->subprog_info[j].exit_idx++;
+ }
+ return 0;
+}
+
static int check_subprogs(struct bpf_verifier_env *env)
{
int i, subprog_start, subprog_end, off, cur_subprog = 0;
@@ -3354,26 +3404,44 @@ static int check_subprogs(struct bpf_verifier_env *env)
/*
* To avoid fall-through from one subprog into another,
* the last insn of the subprog should be either exit
- * or unconditional jump back or bpf_throw call.
+ * or unconditional jump back or a call that does not
+ * return, checked below.
*/
if (code != (BPF_JMP | BPF_EXIT) &&
code != (BPF_JMP32 | BPF_JA) &&
code != (BPF_JMP | BPF_JA) &&
- !insn_is_gotox(&insn[i])) {
- verbose(env, "last insn is not an exit or jmp\n");
- bpf_diag_program_structure(
- env, i, "subprogram can fall through",
- "End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
- "Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
- cur_subprog, i);
- return -EINVAL;
- }
+ !insn_is_gotox(&insn[i]) &&
+ !bpf_pseudo_call(&insn[i]) &&
+ !bpf_pseudo_kfunc_call(&insn[i]))
+ return subprog_falls_through(env, cur_subprog, i);
subprog_start = subprog_end;
cur_subprog++;
if (cur_subprog < env->subprog_cnt)
subprog_end = subprog[cur_subprog + 1].start;
}
}
+
+ /*
+ * A compiler ends a subprog with a call only if the callee never
+ * returns. Refuse any other final call.
+ */
+ for (i = 0; i < env->subprog_cnt; i++) {
+ int last = subprog[i + 1].start - 1, callee;
+
+ if (bpf_pseudo_kfunc_call(&insn[last])) {
+ if (!bpf_is_unwind_kfunc(&insn[last]) &&
+ !bpf_is_unwind_resume_kfunc(&insn[last]))
+ return subprog_falls_through(env, i, last);
+ continue;
+ }
+ if (!bpf_pseudo_call(&insn[last]))
+ continue;
+ callee = bpf_find_subprog(env, last + insn[last].imm + 1);
+ if (bpf_subprog_is_global(env, callee) ||
+ subprog[callee].exit_idx != U32_MAX ||
+ subprog[callee].has_tail_call || subprog[callee].has_ld_abs)
+ return subprog_falls_through(env, i, last);
+ }
return 0;
}
@@ -5954,6 +6022,17 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
}
}
+ /*
+ * A private stack keeps its frame pointer in %r9 on x86-64, restored
+ * by a pop after the call that an unwind skips. A frame resumed at a
+ * pad then addresses its stack through a stale pointer, and a frame
+ * sent to its epilogue instead pops its callee-saved registers one
+ * slot off. Do not use a private stack for any program that can
+ * unwind, on every arch for now.
+ */
+ if (env->cleanup_info_cnt || bpf_prog_may_unwind(env))
+ priv_stack_mode = NO_PRIV_STACK;
+
if (priv_stack_mode == PRIV_STACK_UNKNOWN)
priv_stack_mode = bpf_enable_priv_stack(env->prog);
@@ -11189,6 +11268,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
* callbacks
*/
env->subprog_info[subprog].is_cb = true;
+ err = bpf_exc_check_callback(env, subprog);
+ if (err)
+ return err;
+
if (bpf_pseudo_kfunc_call(insn) &&
!is_callback_calling_kfunc(insn->imm)) {
verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
@@ -11251,6 +11334,8 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
static int process_bpf_exit_full(struct bpf_verifier_env *env,
bool *do_print_state, bool exception_exit);
+static int process_bpf_unwind(struct bpf_verifier_env *env, int *insn_idx);
+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state);
/*
* Call of a static subprog. The callee is verified in the context of
@@ -15563,6 +15648,16 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
if (bpf_is_throw_kfunc(insn))
return process_bpf_exit_full(env, NULL, true);
+ if (bpf_is_unwind_kfunc(insn))
+ return process_bpf_unwind(env, insn_idx_p);
+ if (bpf_is_unwind_resume_kfunc(insn)) {
+ if (!cur_func(env)->in_pad) {
+ verbose(env, "resume at insn %d is not in a landing pad\n", insn_idx);
+ return -EINVAL;
+ }
+ return unwind_frames(env, NULL);
+ }
+
return 0;
}
@@ -19673,6 +19768,136 @@ enum {
INSN_IDX_UPDATED = 2,
};
+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state)
+{
+ struct bpf_verifier_state *state = env->cur_state;
+ u32 frameno = state->curframe;
+ struct bpf_func_state *callee, *caller;
+ int err, pad;
+
+ while (state->curframe) {
+ callee = cur_func(env);
+ caller = state->frame[state->curframe - 1];
+ pad = bpf_exc_pad_of_call(env, callee->callsite);
+ /* The caller is at its call now, not at this frame's insn. */
+ state->insn_idx = callee->callsite;
+ /* As on a return: the frame's dynptrs, and their slices, go with it. */
+ err = destroy_dynptrs_in_stack_slots(env, callee, 0,
+ callee->allocated_stack / BPF_REG_SIZE - 1);
+ if (err)
+ return err;
+
+ account_processed_insns(env, callee, caller);
+ free_func_state(callee);
+ state->frame[state->curframe--] = NULL;
+ invalidate_outgoing_stack_args(env, caller);
+ if (pad < 0)
+ continue;
+
+ /*
+ * Mark the unwinding insn with the frame it ran in: backtracking
+ * from the pad comes back to that insn and goes on in that frame.
+ */
+ err = bpf_push_jmp_history(env, state, INSN_F_UNWIND, 0, frameno, NULL, 0);
+ if (err)
+ return err;
+ clear_caller_saved_regs(env, caller->regs);
+ mark_reg_unknown(env, caller->regs, BPF_REG_0);
+ caller->in_pad = true;
+ env->insn_idx = pad;
+ if (do_print_state)
+ *do_print_state = true;
+ return INSN_IDX_UPDATED;
+ }
+
+ /* A resource still held leaks; report it at the unwinding insn. */
+ err = check_resource_leak(env, false, true, "bpf_unwind");
+ if (err)
+ return err;
+ /*
+ * No pad: the program ends at frame 0's call into the popped frames, or
+ * at the unwinding insn itself if none was popped. Mark the unwinding
+ * insn as above; an unwinding global call needs that when backtracking
+ * from the end reaches it.
+ */
+ err = bpf_push_jmp_history(env, state, INSN_F_UNWIND, 0, frameno, NULL, 0);
+ if (err)
+ return err;
+ /*
+ * Then, in an entry of its own, a jump from the unwinding insn to the
+ * end, so backtracking from the end goes back to the unwinding insn.
+ */
+ env->cur_hist_ent = NULL;
+ env->prev_insn_idx = env->insn_idx;
+ env->insn_idx = state->insn_idx;
+ err = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0);
+ if (err)
+ return err;
+ /*
+ * The end may be in a loop: unlike a plain exit, the path can stop
+ * inside an SCC with no checkpoint there.
+ */
+ state->unwind_exit = true;
+
+ /* The call clobbered r1-r5, and r0 holds the zero the fixups put there. */
+ clear_caller_saved_regs(env, cur_regs(env));
+ __mark_reg_const_zero(env, &cur_regs(env)[BPF_REG_0]);
+ /*
+ * A global subprog verified on its own returns here too. One that
+ * returns in R0:R2 has R2 checked as well, though its caller never
+ * reads either: it resumes at a pad or an epilogue.
+ */
+ if (cur_func(env)->subprogno &&
+ bpf_ret_reg_pair(env, cur_func(env)->subprogno))
+ mark_reg_unknown(env, cur_regs(env), BPF_REG_2);
+
+ return process_bpf_exit_full(env, do_print_state, false);
+}
+
+static int process_global_call_unwind(struct bpf_verifier_env *env,
+ int call_idx, bool *do_print_state)
+{
+ const struct bpf_insn *insn = &env->prog->insnsi[call_idx];
+ int subprog = bpf_find_subprog(env, call_idx + insn->imm + 1);
+ struct bpf_verifier_state *branch;
+ struct bpf_func_state *frame;
+ int pad;
+
+ if (!bpf_subprog_is_global(env, subprog) ||
+ !env->subprog_info[subprog].might_unwind)
+ return 0;
+
+ /* The call returning normally is walked later. */
+ branch = push_stack(env, call_idx + 1, call_idx, false);
+ if (IS_ERR(branch))
+ return PTR_ERR(branch);
+
+ pad = bpf_exc_pad_of_call(env, call_idx);
+ if (pad < 0)
+ return unwind_frames(env, do_print_state);
+ frame = cur_func(env);
+ clear_caller_saved_regs(env, frame->regs);
+ mark_reg_unknown(env, frame->regs, BPF_REG_0);
+ frame->in_pad = true;
+ env->insn_idx = pad;
+ *do_print_state = true;
+ return INSN_IDX_UPDATED;
+}
+
+static int process_bpf_unwind(struct bpf_verifier_env *env, int *insn_idx)
+{
+ struct bpf_func_state *frame = cur_func(env);
+ int pad = bpf_exc_pad_of_call(env, *insn_idx);
+
+ if (pad < 0)
+ return unwind_frames(env, NULL);
+ clear_caller_saved_regs(env, frame->regs);
+ mark_reg_unknown(env, frame->regs, BPF_REG_0);
+ frame->in_pad = true;
+ *insn_idx = pad;
+ return INSN_IDX_UPDATED;
+}
+
static int process_bpf_exit_full(struct bpf_verifier_env *env,
bool *do_print_state,
bool exception_exit)
@@ -19864,6 +20089,12 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
u8 class = BPF_CLASS(insn->code);
+ if (unlikely(env->cleanup_info_cnt)) {
+ err = bpf_exc_check_insn(env, insn);
+ if (err)
+ return err;
+ }
+
switch (class) {
case BPF_ALU:
case BPF_ALU64:
@@ -19934,8 +20165,14 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
cur_func(env)->no_stack_arg_load = true;
if (bpf_is_callx(insn))
return check_func_callx(env, insn, &env->insn_idx);
- if (insn->src_reg == BPF_PSEUDO_CALL)
- return check_func_call(env, insn, &env->insn_idx);
+ if (insn->src_reg == BPF_PSEUDO_CALL) {
+ int call_idx = env->insn_idx;
+
+ err = check_func_call(env, insn, &env->insn_idx);
+ if (err)
+ return err;
+ return process_global_call_unwind(env, call_idx, do_print_state);
+ }
if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
return check_kfunc_call(env, insn, &env->insn_idx);
return check_helper_call(env, insn, &env->insn_idx);
@@ -22134,6 +22371,23 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
prog_extension ? "Extension" : "Tracing");
return -EINVAL;
}
+ /*
+ * A trampoline that calls its target stays as a frame between a
+ * subprog and its caller, and bpf_unwind() cannot walk past it:
+ * the frames above it would carry on after their calls rather
+ * than at their landing pads or epilogues. fentry leaves no
+ * frame, and the main program's caller is above where the walk
+ * stops.
+ */
+ if (aux->func && subprog && aux->func[subprog]->aux->might_unwind &&
+ (prog->expected_attach_type == BPF_TRACE_FEXIT ||
+ prog->expected_attach_type == BPF_MODIFY_RETURN ||
+ prog->expected_attach_type == BPF_TRACE_FSESSION)) {
+ bpf_log(log,
+ "Cannot attach fexit, fmod_ret or fsession to %s, which can unwind\n",
+ tname);
+ return -EINVAL;
+ }
conservative = aux->func_info_aux[subprog].unreliable;
if (prog_extension) {
if (conservative) {
@@ -23431,15 +23685,6 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
env->arena_scalar = attr->prog_flags & BPF_F_ARENA_SCALAR;
- env->explored_states = kvzalloc_objs(struct list_head,
- state_htab_size(env),
- GFP_KERNEL_ACCOUNT);
- ret = -ENOMEM;
- if (!env->explored_states)
- goto skip_full_check;
-
- for (i = 0; i < state_htab_size(env); i++)
- INIT_LIST_HEAD(&env->explored_states[i]);
INIT_LIST_HEAD(&env->free_list);
/* Prepare BTF and func_info needed to discover all subprograms. */
@@ -23468,6 +23713,13 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
+ ret = bpf_exc_check_info(env, attr, uattr);
+ if (ret < 0)
+ goto skip_full_check;
+
+ /* The CFG needs an edge from a call in a cleanup range to its pad. */
+ bpf_exc_mark_call_sites(env);
+
/* Validate instructions and resolve the program's referenced resources. */
ret = check_and_resolve_insns(env);
if (ret < 0)
@@ -23483,6 +23735,24 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
+ /*
+ * After everything above has recorded insn offsets, so the patch
+ * adjusts them, and before an offloaded program's per-insn state.
+ */
+ ret = add_exits_after_final_calls(env);
+ if (ret < 0)
+ goto skip_full_check;
+
+ env->explored_states = kvzalloc_objs(struct list_head,
+ state_htab_size(env),
+ GFP_KERNEL_ACCOUNT);
+ ret = -ENOMEM;
+ if (!env->explored_states)
+ goto skip_full_check;
+
+ for (i = 0; i < state_htab_size(env); i++)
+ INIT_LIST_HEAD(&env->explored_states[i]);
+
if (bpf_prog_is_offloaded(env->prog->aux)) {
ret = bpf_prog_offload_verifier_prep(env->prog);
if (ret)
@@ -23505,6 +23775,12 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret)
goto skip_full_check;
+ if (env->cleanup_info_cnt || bpf_prog_may_unwind(env)) {
+ ret = bpf_exc_check_prog(env);
+ if (ret)
+ goto skip_full_check;
+ }
+
ret = bpf_compute_const_regs(env);
if (ret < 0)
goto skip_full_check;
@@ -23599,6 +23875,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = bpf_convert_ctx_accesses(env);
+ if (ret == 0)
+ ret = bpf_exc_patch_unwind_calls(env);
+
if (ret == 0)
ret = bpf_do_misc_fixups(env);
@@ -23713,6 +23992,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
kvfree(env->func_ptrs);
bpf_diag_free(env);
kvfree(env->idoms);
+ kvfree(env->cleanup_info);
kvfree(env);
return ret;
}
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index 6f70db7515dd4..9d7439c96e52e 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -1708,6 +1708,9 @@ union bpf_attr {
* verification.
*/
__s32 keyring_id;
+ __aligned_u64 cleanup_info; /* exception cleanup table */
+ __u32 cleanup_info_rec_size; /* userspace bpf_cleanup_info size */
+ __u32 cleanup_info_cnt; /* number of bpf_cleanup_info records */
};
struct { /* anonymous struct used by BPF_OBJ_* commands */
@@ -7669,6 +7672,17 @@ struct bpf_line_info {
__u32 line_col;
};
+/*
+ * One record of an exception cleanup table: calls in [begin_off, end_off)
+ * that unwind resume at landing_pad_off. All three are instruction offsets
+ * in the program as loaded.
+ */
+struct bpf_cleanup_info {
+ __u32 begin_off;
+ __u32 end_off;
+ __u32 landing_pad_off;
+};
+
struct bpf_spin_lock {
__u32 val;
};
diff --git a/tools/lib/bpf/bpf.c b/tools/lib/bpf/bpf.c
index b49822d212aed..b4031f62bdee5 100644
--- a/tools/lib/bpf/bpf.c
+++ b/tools/lib/bpf/bpf.c
@@ -295,7 +295,7 @@ int bpf_prog_load(enum bpf_prog_type prog_type,
const struct bpf_insn *insns, size_t insn_cnt,
struct bpf_prog_load_opts *opts)
{
- const size_t attr_sz = offsetofend(union bpf_attr, keyring_id);
+ const size_t attr_sz = offsetofend(union bpf_attr, cleanup_info_cnt);
void *finfo = NULL, *linfo = NULL;
const char *func_info, *line_info;
__u32 log_size, log_level, attach_prog_fd, attach_btf_obj_fd;
@@ -370,6 +370,10 @@ int bpf_prog_load(enum bpf_prog_type prog_type,
attr.fd_array = ptr_to_u64(OPTS_GET(opts, fd_array, NULL));
attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0);
+ attr.cleanup_info = ptr_to_u64(OPTS_GET(opts, cleanup_info, NULL));
+ attr.cleanup_info_rec_size = OPTS_GET(opts, cleanup_info_rec_size, 0);
+ attr.cleanup_info_cnt = OPTS_GET(opts, cleanup_info_cnt, 0);
+
if (log_level) {
attr.log_buf = ptr_to_u64(log_buf);
attr.log_size = log_size;
diff --git a/tools/lib/bpf/bpf.h b/tools/lib/bpf/bpf.h
index 826d9cc9ab65d..64699e0e4e1a8 100644
--- a/tools/lib/bpf/bpf.h
+++ b/tools/lib/bpf/bpf.h
@@ -128,9 +128,17 @@ struct bpf_prog_load_opts {
/* if set, provides the length of fd_array */
__u32 fd_array_cnt;
+
+ /* exception cleanup table: cleanup_info_cnt records of
+ * cleanup_info_rec_size bytes each (struct bpf_cleanup_info),
+ * holding instruction indices into insns
+ */
+ __u32 cleanup_info_cnt;
+ const void *cleanup_info;
+ __u32 cleanup_info_rec_size;
size_t :0;
};
-#define bpf_prog_load_opts__last_field fd_array_cnt
+#define bpf_prog_load_opts__last_field cleanup_info_rec_size
LIBBPF_API int bpf_prog_load(enum bpf_prog_type prog_type,
const char *prog_name, const char *license,
diff --git a/tools/lib/bpf/gen_loader.c b/tools/lib/bpf/gen_loader.c
index 251392aa8b41f..f07727c5b5fb8 100644
--- a/tools/lib/bpf/gen_loader.c
+++ b/tools/lib/bpf/gen_loader.c
@@ -994,13 +994,15 @@ static void cleanup_relos(struct bpf_gen *gen, int insns)
cleanup_core_relo(gen);
}
-/* Convert func, line, and core relo info blobs to target endianness */
+/* Convert func, line, core relo and cleanup info blobs to target endianness */
static void info_blob_bswap(struct bpf_gen *gen, int func_info, int line_info,
- int core_relos, struct bpf_prog_load_opts *load_attr)
+ int core_relos, int cleanup_info,
+ struct bpf_prog_load_opts *load_attr)
{
struct bpf_func_info *fi = gen->data_start + func_info;
struct bpf_line_info *li = gen->data_start + line_info;
struct bpf_core_relo *cr = gen->data_start + core_relos;
+ struct bpf_cleanup_info *ci = gen->data_start + cleanup_info;
int i;
for (i = 0; i < load_attr->func_info_cnt; i++)
@@ -1011,6 +1013,9 @@ static void info_blob_bswap(struct bpf_gen *gen, int func_info, int line_info,
for (i = 0; i < gen->core_relo_cnt; i++)
bpf_core_relo_bswap(cr++);
+
+ for (i = 0; i < load_attr->cleanup_info_cnt; i++)
+ bpf_cleanup_info_bswap(ci++);
}
void bpf_gen__prog_load(struct bpf_gen *gen,
@@ -1024,10 +1029,15 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
load_attr->line_info_rec_size;
int core_relo_tot_sz = gen->core_relo_cnt *
sizeof(struct bpf_core_relo);
+ int cleanup_info_tot_sz = load_attr->cleanup_info_cnt *
+ load_attr->cleanup_info_rec_size;
int prog_load_attr, license_off, insns_off, func_info, line_info, core_relos;
int attr_size = offsetofend(union bpf_attr, core_relo_rec_size);
+ int cleanup_info;
union bpf_attr attr;
+ if (load_attr->cleanup_info_cnt)
+ attr_size = offsetofend(union bpf_attr, cleanup_info_cnt);
memset(&attr, 0, attr_size);
/* add license string to blob of bytes */
license_off = add_data(gen, license, strlen(license) + 1);
@@ -1074,9 +1084,17 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
core_relos, gen->core_relo_cnt,
sizeof(struct bpf_core_relo));
+ attr.cleanup_info_rec_size = tgt_endian(load_attr->cleanup_info_rec_size);
+ attr.cleanup_info_cnt = tgt_endian(load_attr->cleanup_info_cnt);
+ cleanup_info = add_data(gen, load_attr->cleanup_info, cleanup_info_tot_sz);
+ pr_debug("gen: prog_load: cleanup_info: off %d cnt %u rec size %u\n",
+ cleanup_info, load_attr->cleanup_info_cnt,
+ load_attr->cleanup_info_rec_size);
+
/* convert all info blobs to target endianness */
if (gen->swapped_endian && !gen->error)
- info_blob_bswap(gen, func_info, line_info, core_relos, load_attr);
+ info_blob_bswap(gen, func_info, line_info, core_relos, cleanup_info,
+ load_attr);
libbpf_strlcpy(attr.prog_name, prog_name, sizeof(attr.prog_name));
prog_load_attr = add_data(gen, &attr, attr_size);
@@ -1098,6 +1116,11 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
/* populate union bpf_attr with a pointer to core_relos */
emit_rel_store(gen, attr_field(prog_load_attr, core_relos), core_relos);
+ /* with no records, attr ends before cleanup_info: nothing to store */
+ if (load_attr->cleanup_info_cnt)
+ emit_rel_store(gen, attr_field(prog_load_attr, cleanup_info),
+ cleanup_info);
+
/* populate union bpf_attr fd_array with a pointer to data where map_fds are saved */
emit_rel_store(gen, attr_field(prog_load_attr, fd_array), gen->fd_array);
diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index cb09ded907732..d227dcc7ef0bb 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -516,6 +516,11 @@ struct bpf_program {
void *line_info;
__u32 line_info_rec_size;
__u32 line_info_cnt;
+
+ struct bpf_cleanup_info *cleanup_info;
+ __u32 cleanup_info_rec_size;
+ __u32 cleanup_info_cnt;
+
__u32 prog_flags;
__u8 hash[SHA256_DIGEST_LENGTH];
@@ -572,6 +577,7 @@ struct bpf_struct_ops {
* are loaded with BPF_F_ARENA_SCALAR.
*/
#define ARENA_DATA_SEC ".arena.data"
+#define CLEANUP_SEC ".bpf_cleanup"
enum libbpf_map_type {
LIBBPF_MAP_UNSPEC,
@@ -710,6 +716,25 @@ struct elf_sec_desc {
Elf_Data *data;
};
+#define CLEANUP_REC_FIELDS (sizeof(struct bpf_cleanup_info) / sizeof(__u32))
+
+/* Index of each field of struct bpf_cleanup_info, read as an array of __u32. */
+enum {
+ CLEANUP_REC_BEGIN,
+ CLEANUP_REC_END,
+ CLEANUP_REC_PAD,
+};
+
+/*
+ * One (begin, end, landing_pad) triple from .bpf_cleanup, each field resolved
+ * from its relocation to a section and an instruction index within it. Final
+ * indices wait for subprogram placement, which differs per main program.
+ */
+struct cleanup_raw_rec {
+ int sec_idx[CLEANUP_REC_FIELDS];
+ size_t insn_idx[CLEANUP_REC_FIELDS];
+};
+
struct elf_state {
int fd;
const void *obj_buf;
@@ -729,6 +754,8 @@ struct elf_state {
bool has_st_ops;
int arena_data_shndx;
int jumptables_data_shndx;
+ Elf_Data *cleanup_data;
+ int cleanup_shndx;
};
struct usdt_manager;
@@ -817,6 +844,9 @@ struct bpf_object {
void *jumptables_data;
size_t jumptables_data_sz;
+ struct cleanup_raw_rec *cleanup_recs;
+ size_t cleanup_rec_cnt;
+
struct {
struct bpf_program *prog;
unsigned int sym_off;
@@ -874,6 +904,7 @@ void bpf_program__unload(struct bpf_program *prog)
zfree(&prog->func_info);
zfree(&prog->line_info);
zfree(&prog->subprogs);
+ zfree(&prog->cleanup_info);
}
static void bpf_program__exit(struct bpf_program *prog)
@@ -1639,6 +1670,7 @@ static struct bpf_object *bpf_object__new(const char *path,
obj->efile.obj_buf_sz = obj_buf_sz;
obj->efile.btf_maps_shndx = -1;
obj->efile.arena_data_shndx = -1;
+ obj->efile.cleanup_shndx = -1;
obj->kconfig_map_idx = -1;
obj->arena_map_idx = -1;
@@ -1658,6 +1690,7 @@ static void bpf_object__elf_finish(struct bpf_object *obj)
obj->efile.ehdr = NULL;
obj->efile.symbols = NULL;
obj->efile.arena_data = NULL;
+ obj->efile.cleanup_data = NULL;
zfree(&obj->efile.secs);
obj->efile.sec_cnt = 0;
@@ -4275,6 +4308,9 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
sec_desc->shdr = sh;
sec_desc->data = data;
obj->efile.has_st_ops = true;
+ } else if (strcmp(name, CLEANUP_SEC) == 0) {
+ obj->efile.cleanup_data = data;
+ obj->efile.cleanup_shndx = idx;
} else if (strcmp(name, ARENA_SEC) == 0) {
obj->efile.arena_data = data;
obj->efile.arena_data_shndx = idx;
@@ -4300,8 +4336,9 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
/*
* Only do relo for section with exec instructions,
- * struct_ops, maps, and read-only data that might
- * have pointers to functions.
+ * struct_ops, maps, read-only data that might have
+ * pointers to functions, and the exception cleanup
+ * table.
*/
if (!section_have_execinstr(obj, targ_sec_idx) &&
!(obj->data_in_arena &&
@@ -4315,6 +4352,7 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
+ strcmp(name, ".rel" CLEANUP_SEC) &&
strcmp(name, ".rel" MAPS_ELF_SEC)) {
pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
idx, name, targ_sec_idx,
@@ -5099,6 +5137,219 @@ static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
return NULL;
}
+static int bpf_object_init_cleanup_info(struct bpf_object *obj)
+{
+ Elf_Data *data = obj->efile.cleanup_data;
+ size_t i, nrels, nslots, nrecs;
+ struct cleanup_raw_rec *recs;
+ Elf_Data *relo = NULL;
+ const char *vals;
+ int ret = 0;
+ bool native;
+
+ if (!data || obj->efile.cleanup_shndx < 0 || !data->d_size)
+ return 0;
+
+ native = is_native_endianness(obj);
+
+ for (i = 0; i < obj->efile.sec_cnt; i++) {
+ struct elf_sec_desc *sd = &obj->efile.secs[i];
+
+ if (sd->sec_type == SEC_RELO && sd->shdr &&
+ sd->shdr->sh_info == (Elf64_Word)obj->efile.cleanup_shndx) {
+ relo = sd->data;
+ break;
+ }
+ }
+ if (!relo) {
+ pr_warn("%s present without relocations\n", CLEANUP_SEC);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+ if (data->d_size % sizeof(struct bpf_cleanup_info)) {
+ pr_warn("%s size %zu is not a multiple of the record size %zu\n",
+ CLEANUP_SEC, data->d_size, sizeof(struct bpf_cleanup_info));
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+
+ vals = data->d_buf;
+ nslots = data->d_size / sizeof(__u32);
+ nrecs = data->d_size / sizeof(struct bpf_cleanup_info);
+
+ recs = calloc(nrecs, sizeof(*recs));
+ if (!recs)
+ return -ENOMEM;
+ for (i = 0; i < nslots; i++)
+ recs[i / CLEANUP_REC_FIELDS].sec_idx[i % CLEANUP_REC_FIELDS] = -1;
+
+ /* One relocation per 4-byte field, naming the section it points into. */
+ nrels = relo->d_size / sizeof(Elf64_Rel);
+ for (i = 0; i < nrels; i++) {
+ Elf64_Rel *rel = elf_rel_by_idx(relo, i);
+ Elf64_Sym *sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
+ size_t type = ELF64_R_TYPE(rel->r_info);
+ size_t slot = rel->r_offset / sizeof(__u32);
+ struct cleanup_raw_rec *rec;
+ size_t off;
+ __u32 val;
+
+ if (type != R_BPF_64_NODYLD32 && type != R_BPF_64_ABS32) {
+ pr_warn("%s: relocation %zu has unexpected type %zu\n",
+ CLEANUP_SEC, i, type);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ if (!sym || slot >= nslots || rel->r_offset % sizeof(__u32)) {
+ pr_warn("%s: bad relocation %zu\n", CLEANUP_SEC, i);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ /*
+ * The addend lives in the section data, which libelf leaves in
+ * the object's byte order; a non-section symbol additionally
+ * contributes its own value. The section is only byte aligned.
+ */
+ memcpy(&val, vals + slot * sizeof(val), sizeof(val));
+ off = (native ? val : bswap_32(val)) + sym->st_value;
+ if (off % BPF_INSN_SZ) {
+ pr_warn("%s: field %zu offset %zu is not instruction aligned\n",
+ CLEANUP_SEC, slot, off);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ rec = &recs[slot / CLEANUP_REC_FIELDS];
+ if (rec->sec_idx[slot % CLEANUP_REC_FIELDS] >= 0) {
+ pr_warn("%s: field %zu has more than one relocation\n",
+ CLEANUP_SEC, slot);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ rec->sec_idx[slot % CLEANUP_REC_FIELDS] = sym->st_shndx;
+ rec->insn_idx[slot % CLEANUP_REC_FIELDS] = off / BPF_INSN_SZ;
+ }
+
+ for (i = 0; i < nslots; i++) {
+ if (recs[i / CLEANUP_REC_FIELDS].sec_idx[i % CLEANUP_REC_FIELDS] < 0) {
+ pr_warn("%s: field %zu has no relocation\n", CLEANUP_SEC, i);
+ ret = -LIBBPF_ERRNO__FORMAT;
+ goto out;
+ }
+ }
+
+ obj->cleanup_recs = recs;
+ obj->cleanup_rec_cnt = nrecs;
+ return 0;
+out:
+ free(recs);
+ return ret;
+}
+
+static int cmp_cleanup_info(const void *a, const void *b)
+{
+ const struct bpf_cleanup_info *x = a, *y = b;
+
+ if (x->begin_off == y->begin_off)
+ return 0;
+ return x->begin_off < y->begin_off ? -1 : 1;
+}
+
+static int bpf_prog_collect_cleanup_info(struct bpf_object *obj,
+ struct bpf_program *prog)
+{
+ size_t i;
+ int j;
+
+ for (i = 0; i < obj->cleanup_rec_cnt; i++) {
+ struct cleanup_raw_rec *raw = &obj->cleanup_recs[i];
+ struct bpf_program *owner = NULL;
+ struct bpf_cleanup_info ci = {};
+ __u32 fields[CLEANUP_REC_FIELDS];
+ void *tmp;
+
+ for (j = 0; j < CLEANUP_REC_FIELDS; j++) {
+ size_t idx = raw->insn_idx[j], final;
+ struct bpf_program *p;
+
+ /*
+ * An exclusive end may name the instruction past the
+ * last of a function, so ask about the last one the
+ * range covers, the way the kernel does.
+ */
+ if (j == CLEANUP_REC_END) {
+ if (!idx) {
+ pr_warn("%s: record %zu ends at instruction 0\n",
+ CLEANUP_SEC, i);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+ idx--;
+ }
+
+ p = find_prog_by_sec_insn(obj, raw->sec_idx[j], idx);
+ if (!p && j == CLEANUP_REC_BEGIN) {
+ /*
+ * Code no function claims is an overridden weak
+ * function the linker kept: skip its records,
+ * as its relocations are.
+ */
+ pr_debug("%s: record %zu is in no function, probably an overridden weak function, skipping\n",
+ CLEANUP_SEC, i);
+ break;
+ }
+ if (!p) {
+ pr_warn("%s: record %zu field %d is not inside a function\n",
+ CLEANUP_SEC, i, j);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+ if (!owner) {
+ owner = p;
+ } else if (owner != p) {
+ pr_warn("%s: record %zu spans functions '%s' and '%s'\n",
+ CLEANUP_SEC, i, owner->name, p->name);
+ return -LIBBPF_ERRNO__FORMAT;
+ }
+
+ if (owner == prog) {
+ final = raw->insn_idx[j] - prog->sec_insn_off;
+ } else if (prog_is_subprog(obj, owner) && owner->sub_insn_off) {
+ /*
+ * sub_insn_off is where this subprogram was
+ * appended to the main program being relocated;
+ * zero means it is not part of it.
+ */
+ final = owner->sub_insn_off +
+ raw->insn_idx[j] - owner->sec_insn_off;
+ } else {
+ owner = NULL;
+ break;
+ }
+ fields[j] = final;
+ }
+ if (!owner)
+ continue;
+
+ ci.begin_off = fields[CLEANUP_REC_BEGIN];
+ ci.end_off = fields[CLEANUP_REC_END];
+ ci.landing_pad_off = fields[CLEANUP_REC_PAD];
+
+ tmp = libbpf_reallocarray(prog->cleanup_info, prog->cleanup_info_cnt + 1,
+ sizeof(*prog->cleanup_info));
+ if (!tmp)
+ return -ENOMEM;
+ prog->cleanup_info = tmp;
+ prog->cleanup_info_rec_size = sizeof(struct bpf_cleanup_info);
+ prog->cleanup_info[prog->cleanup_info_cnt++] = ci;
+
+ pr_debug("prog '%s': cleanup region [%u,%u) -> landing pad %u\n",
+ prog->name, ci.begin_off, ci.end_off, ci.landing_pad_off);
+ }
+
+ if (!prog->cleanup_info_cnt)
+ return 0;
+
+ qsort(prog->cleanup_info, prog->cleanup_info_cnt,
+ sizeof(*prog->cleanup_info), cmp_cleanup_info);
+ return 0;
+}
+
static int
bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
{
@@ -8197,6 +8448,13 @@ static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_pat
return err;
}
}
+
+ err = bpf_prog_collect_cleanup_info(obj, prog);
+ if (err) {
+ pr_warn("prog '%s': failed to collect cleanup info: %s\n",
+ prog->name, errstr(err));
+ return err;
+ }
}
for (i = 0; i < obj->nr_programs; i++) {
prog = &obj->programs[i];
@@ -8561,6 +8819,9 @@ static int bpf_object__collect_relos(struct bpf_object *obj)
return -LIBBPF_ERRNO__INTERNAL;
}
+ if (idx == obj->efile.cleanup_shndx)
+ continue;
+
if (obj->efile.secs[idx].sec_type == SEC_RODATA)
err = bpf_object__collect_rodata_relos(obj, shdr, data);
else if (obj->efile.secs[idx].sec_type == SEC_DATA)
@@ -8856,6 +9117,11 @@ static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog
load_attr.line_info_rec_size = prog->line_info_rec_size;
load_attr.line_info_cnt = prog->line_info_cnt;
}
+ if (prog->cleanup_info_cnt) {
+ load_attr.cleanup_info = prog->cleanup_info;
+ load_attr.cleanup_info_cnt = prog->cleanup_info_cnt;
+ load_attr.cleanup_info_rec_size = prog->cleanup_info_rec_size;
+ }
load_attr.log_level = log_level;
load_attr.prog_flags = prog->prog_flags;
/* the program accesses its data in arena through plain numbers */
@@ -9187,6 +9453,23 @@ static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_s
}
}
+/*
+ * LLVM terminates a cleanup landing pad with a call to _Unwind_Resume, the
+ * base unwind ABI's entry point for carrying an unwind on once a frame's
+ * cleanups have run. The kernel knows it as bpf_unwind_resume. Any other
+ * extern, and a variable of that name, is looked up by @name unchanged.
+ */
+static const char *kern_extern_name(const struct bpf_object *obj,
+ const struct extern_desc *ext, const char *name)
+{
+ const char *essent = ext->essent_name ?: ext->name;
+
+ if (!btf_is_func(btf__type_by_id(obj->btf, ext->btf_id)) ||
+ strcmp(essent, "_Unwind_Resume"))
+ return name;
+ return "bpf_unwind_resume";
+}
+
static int bpf_program_record_relos(struct bpf_program *prog)
{
struct bpf_object *obj = prog->obj;
@@ -9195,6 +9478,7 @@ static int bpf_program_record_relos(struct bpf_program *prog)
for (i = 0; i < prog->nr_reloc; i++) {
struct reloc_desc *relo = &prog->reloc_desc[i];
struct extern_desc *ext = &obj->externs[relo->ext_idx];
+ const char *name;
int kind;
switch (relo->type) {
@@ -9203,14 +9487,14 @@ static int bpf_program_record_relos(struct bpf_program *prog)
continue;
kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
BTF_KIND_VAR : BTF_KIND_FUNC;
- bpf_gen__record_extern(obj->gen_loader, ext->name,
- ext->is_weak, !ext->ksym.type_id,
- true, kind, relo->insn_idx);
+ name = kern_extern_name(obj, ext, ext->name);
+ bpf_gen__record_extern(obj->gen_loader, name, ext->is_weak,
+ !ext->ksym.type_id, true, kind, relo->insn_idx);
break;
case RELO_EXTERN_CALL:
- bpf_gen__record_extern(obj->gen_loader, ext->name,
- ext->is_weak, false, false, BTF_KIND_FUNC,
- relo->insn_idx);
+ name = kern_extern_name(obj, ext, ext->name);
+ bpf_gen__record_extern(obj->gen_loader, name, ext->is_weak, false,
+ false, BTF_KIND_FUNC, relo->insn_idx);
break;
case RELO_CORE: {
struct bpf_core_relo cr = {
@@ -9442,6 +9726,7 @@ static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf,
err = err ? : bpf_object__init_maps(obj, opts);
err = err ? : bpf_object_init_progs(obj, opts);
err = err ? : bpf_object__collect_relos(obj);
+ err = err ? : bpf_object_init_cleanup_info(obj);
if (err)
goto out;
@@ -9684,17 +9969,24 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
struct module_btf *mod_btf = NULL;
const struct btf_type *kern_func;
struct btf *kern_btf = NULL;
+ const char *local_name, *kern_name;
int ret;
local_func_proto_id = ext->ksym.type_id;
- kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
- &mod_btf);
+ local_name = ext->essent_name ?: ext->name;
+ kern_name = kern_extern_name(obj, ext, local_name);
+
+ kfunc_id = find_ksym_btf_id(obj, kern_name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
if (kfunc_id < 0) {
if (kfunc_id == -ESRCH && ext->is_weak)
return 0;
- pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
- ext->name);
+ if (kern_name != local_name)
+ pr_warn("extern (func ksym) '%s' ('%s' in the kernel): not found in kernel or module BTFs\n",
+ ext->name, kern_name);
+ else
+ pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
+ ext->name);
return kfunc_id;
}
@@ -9707,9 +9999,14 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
if (ext->is_weak)
return 0;
- pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
- ext->name, local_func_proto_id,
- mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
+ if (kern_name != local_name)
+ pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with '%s' in %s [%d]\n",
+ ext->name, local_func_proto_id, kern_name,
+ mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
+ else
+ pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
+ ext->name, local_func_proto_id,
+ mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
return -EINVAL;
}
@@ -10572,6 +10869,9 @@ void bpf_object__close(struct bpf_object *obj)
zfree(&obj->jumptables_data);
obj->jumptables_data_sz = 0;
+ zfree(&obj->cleanup_recs);
+ obj->cleanup_rec_cnt = 0;
+
for (i = 0; i < obj->jumptable_map_cnt; i++)
close(obj->jumptable_maps[i].fd);
zfree(&obj->jumptable_maps);
@@ -10981,6 +11281,19 @@ int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts
attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
}
+ /* exception cleanup table */
+ info = OPTS_GET(opts, cleanup_info, NULL);
+ info_cnt = OPTS_GET(opts, cleanup_info_cnt, 0);
+ info_rec_size = OPTS_GET(opts, cleanup_info_rec_size, 0);
+ if (!!info != !!info_cnt || !!info != !!info_rec_size) {
+ pr_warn("prog '%s': cleanup_info, cleanup_info_cnt, and cleanup_info_rec_size must all be specified or all omitted\n",
+ prog->name);
+ return libbpf_err(-EINVAL);
+ }
+ attr.cleanup_info = info ?: prog->cleanup_info;
+ attr.cleanup_info_cnt = info ? info_cnt : prog->cleanup_info_cnt;
+ attr.cleanup_info_rec_size = info ? info_rec_size : prog->cleanup_info_rec_size;
+
/* Logging is caller-controlled; no fallback to prog/obj log settings */
attr.log_buf = OPTS_GET(opts, log_buf, NULL);
attr.log_size = OPTS_GET(opts, log_size, 0);
diff --git a/tools/lib/bpf/libbpf_internal.h b/tools/lib/bpf/libbpf_internal.h
index 4e45dfacb548a..e17fc8f601995 100644
--- a/tools/lib/bpf/libbpf_internal.h
+++ b/tools/lib/bpf/libbpf_internal.h
@@ -56,6 +56,9 @@
#ifndef R_BPF_64_ABS32
#define R_BPF_64_ABS32 3
#endif
+#ifndef R_BPF_64_NODYLD32
+#define R_BPF_64_NODYLD32 4
+#endif
#ifndef R_BPF_64_32
#define R_BPF_64_32 10
#endif
@@ -570,6 +573,13 @@ static inline void bpf_core_relo_bswap(struct bpf_core_relo *i)
i->kind = bswap_32(i->kind);
}
+static inline void bpf_cleanup_info_bswap(struct bpf_cleanup_info *i)
+{
+ i->begin_off = bswap_32(i->begin_off);
+ i->end_off = bswap_32(i->end_off);
+ i->landing_pad_off = bswap_32(i->landing_pad_off);
+}
+
enum btf_field_iter_kind {
BTF_FIELD_ITER_IDS,
BTF_FIELD_ITER_STRS,
diff --git a/tools/lib/bpf/linker.c b/tools/lib/bpf/linker.c
index f3f71c452f007..911a649219a98 100644
--- a/tools/lib/bpf/linker.c
+++ b/tools/lib/bpf/linker.c
@@ -1036,7 +1036,8 @@ static int linker_sanity_check_elf_relos(struct src_obj *obj, struct src_sec *se
size_t sym_type = ELF64_R_TYPE(relo->r_info);
if (sym_type != R_BPF_64_64 && sym_type != R_BPF_64_32 &&
- sym_type != R_BPF_64_ABS64 && sym_type != R_BPF_64_ABS32) {
+ sym_type != R_BPF_64_ABS64 && sym_type != R_BPF_64_ABS32 &&
+ sym_type != R_BPF_64_NODYLD32) {
pr_warn("ELF relo #%d in section #%zu has unexpected type %zu in %s\n",
i, sec->sec_idx, sym_type, obj->filename);
return -EINVAL;
@@ -2263,6 +2264,7 @@ static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *ob
if (ELF64_ST_TYPE(src_sym->st_info) == STT_SECTION) {
struct src_sec *sec = &obj->secs[src_sym->st_shndx];
struct bpf_insn *insn;
+ __u32 *val;
if (src_linked_sec->shdr->sh_flags & SHF_EXECINSTR) {
/* calls to the very first static function inside
@@ -2297,6 +2299,41 @@ static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *ob
if (linker->swapped_endian)
off = bswap_64(off);
memcpy(ptr, &off, sizeof(off));
+ } else if ((sym_type == R_BPF_64_NODYLD32 ||
+ sym_type == R_BPF_64_ABS32) &&
+ (sec->shdr->sh_flags & SHF_EXECINSTR)) {
+ /*
+ * A byte offset into a code section,
+ * stored in place. LLVM spells this
+ * relocation NODYLD32 and GNU as
+ * spells it ABS32; being bytes, the
+ * section's new start goes in as it
+ * is, not scaled the way a call's
+ * instruction index is above.
+ *
+ * The sanity check only checks the
+ * alignment of r_offset, and only for
+ * an executable section, and SHT_NOBITS
+ * has no raw_data, so check both here,
+ * bounding by subtraction so it cannot
+ * wrap.
+ */
+ if (!dst_linked_sec->raw_data ||
+ dst_linked_sec->sec_sz < (int)sizeof(*val) ||
+ dst_rel->r_offset % sizeof(*val) ||
+ dst_rel->r_offset >
+ (size_t)dst_linked_sec->sec_sz - sizeof(*val)) {
+ pr_warn("ELF relo #%d in section #%zu points outside the data of section '%s' in %s\n",
+ j, src_sec->sec_idx,
+ dst_linked_sec->sec_name,
+ obj->filename);
+ return -EINVAL;
+ }
+ val = dst_linked_sec->raw_data + dst_rel->r_offset;
+ if (linker->swapped_endian)
+ *val = bswap_32(bswap_32(*val) + sec->dst_off);
+ else
+ *val += sec->dst_off;
} else {
pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
return -EINVAL;
diff --git a/tools/testing/selftests/bpf/Makefile.skel b/tools/testing/selftests/bpf/Makefile.skel
index 06e297a17156c..d9cbe8ac85b76 100644
--- a/tools/testing/selftests/bpf/Makefile.skel
+++ b/tools/testing/selftests/bpf/Makefile.skel
@@ -40,7 +40,7 @@ LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c
# Generate both light skeleton and libbpf skeleton for these
LSKELS_EXTRA := test_ksyms_module.c test_ksyms_weak.c kfunc_call_test.c \
- kfunc_call_test_subprog.c test_global_percpu_data.c
+ kfunc_call_test_subprog.c test_global_percpu_data.c exceptions_cleanup.c
SKEL_BLACKLIST += $(LSKELS) $(LSKELS_SIGNED)
test_static_linked.skel.h-deps := test_static_linked1.bpf.o test_static_linked2.bpf.o
diff --git a/tools/testing/selftests/bpf/exceptions_cleanup.h b/tools/testing/selftests/bpf/exceptions_cleanup.h
new file mode 100644
index 0000000000000..84f21ecc630ab
--- /dev/null
+++ b/tools/testing/selftests/bpf/exceptions_cleanup.h
@@ -0,0 +1,48 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#ifndef __EXCEPTIONS_CLEANUP_H__
+#define __EXCEPTIONS_CLEANUP_H__
+
+/* progs/exceptions_cleanup.c: one bit per function that reports it ran. */
+#define RAN_FOO3_PREEMPT 0x1
+#define RAN_FOO2_RCU 0x2
+#define RAN_FOO1V_PREEMPT 0x4
+#define RAN_FOO2_DROP 0x8
+#define RAN_BUMP 0x10
+
+/* progs/exceptions_cleanup_shapes.c: one bit per landing pad. */
+#define RAN_REGS 0x1
+#define RAN_WIDE_REC 0x2
+#define RAN_RESUME_ALIAS 0x4
+#define RAN_NOP_PAD 0x8
+#define RAN_VAR_STACK 0x10
+#define RAN_GAP_INNER 0x20
+#define RAN_GAP_OUTER 0x40
+#define RAN_PREC_RESUME 0x80
+#define RAN_NO_EXIT_JA 0x100
+#define RAN_CALLX 0x200
+#define RAN_CALLEE_WRITE 0x400
+#define RAN_CALLEE_OFFSET 0x800
+#define RAN_GLOBAL_WRITE 0x1000
+#define RAN_THROUGH_GLOBAL 0x2000
+#define RAN_PAIR_GLOBAL 0x4000
+#define RAN_MOVE 0x8000
+#define RAN_NO_EXIT_LOOP 0x10000
+#define RAN_LAST_CALL 0x20000
+#define RAN_NO_TAIL 0x40000
+
+#define CLEANUP_REC(begin, end, landing_pad) \
+ ".pushsection .bpf_cleanup,\"a\",@progbits;" \
+ ".long " begin ";" \
+ ".long " end ";" \
+ ".long " landing_pad ";" \
+ ".popsection;"
+
+/* Set a bit in @pads_ran. */
+#define PAD_RAN(bit) \
+ "r1 = %[pads_ran] ll;" \
+ "r2 = *(u64 *)(r1 + 0);" \
+ "r2 |= " bit ";" \
+ "*(u64 *)(r1 + 0) = r2;"
+
+#endif /* __EXCEPTIONS_CLEANUP_H__ */
diff --git a/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c b/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c
new file mode 100644
index 0000000000000..b8581716bbd40
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <test_progs.h>
+#include "exceptions_cleanup.h"
+#include "exceptions_cleanup.skel.h"
+#include "exceptions_cleanup_fail.skel.h"
+#include "exceptions_cleanup_shapes.skel.h"
+#include "exceptions_cleanup_tracing.skel.h"
+#include "exceptions_cleanup.lskel.h"
+
+/* foo3 unwound: every frame that has a pad ran it. */
+#define PADS_FOO3_UNWOUND \
+ (RAN_FOO3_PREEMPT | RAN_FOO2_RCU | RAN_FOO1V_PREEMPT | RAN_FOO2_DROP)
+
+/* foo2 unwound after foo3 returned normally: foo3's pad must not run. */
+#define PADS_FOO2_UNWOUND \
+ (RAN_FOO2_RCU | RAN_FOO1V_PREEMPT | RAN_FOO2_DROP)
+
+static void run(struct exceptions_cleanup *skel, __u64 input, __u32 retval,
+ __u64 pads)
+{
+ __u64 ctx = 0;
+ int err;
+
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &ctx,
+ .ctx_size_in = sizeof(ctx),
+ );
+
+ skel->bss->input = input;
+ skel->bss->pads_ran = 0;
+ skel->bss->result = 0;
+
+ err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.entry), &topts);
+ if (!ASSERT_OK(err, "run"))
+ return;
+ ASSERT_EQ(topts.retval, retval, "retval");
+ /* bump() is not a landing pad; it sets its bit on every run. */
+ ASSERT_EQ(skel->bss->pads_ran, pads | RAN_BUMP, "pads_ran");
+}
+
+/*
+ * Tracing programs against foo1(), which an unwind passes through. fexit
+ * keeps a trampoline frame between foo1() and its caller that the unwind
+ * cannot walk past, so it is refused; fentry leaves none, so foo3 can still
+ * unwind through foo1() with it attached.
+ */
+static void test_tracing(struct exceptions_cleanup *tgt)
+{
+ struct exceptions_cleanup_tracing *skel;
+ int tgt_fd = bpf_program__fd(tgt->progs.entry);
+ char log[8192] = {};
+ int err;
+
+ LIBBPF_OPTS(bpf_object_open_opts, opts,
+ .kernel_log_buf = log,
+ .kernel_log_size = sizeof(log));
+
+ skel = exceptions_cleanup_tracing__open_opts(&opts);
+ if (!ASSERT_OK_PTR(skel, "tracer open"))
+ return;
+ bpf_program__set_autoload(skel->progs.fentry_unwinding_subprog, true);
+ err = bpf_program__set_attach_target(skel->progs.fentry_unwinding_subprog,
+ tgt_fd, "foo1");
+ if (!ASSERT_OK(err, "fentry target"))
+ goto out;
+ err = exceptions_cleanup_tracing__load(skel);
+ if (!ASSERT_OK(err, "fentry load"))
+ goto out;
+ err = exceptions_cleanup_tracing__attach(skel);
+ if (!ASSERT_OK(err, "fentry attach"))
+ goto out;
+ run(tgt, 101, 0, PADS_FOO3_UNWOUND);
+ ASSERT_EQ(skel->bss->fentry_hits, 1, "fentry_hits");
+ exceptions_cleanup_tracing__destroy(skel);
+
+ skel = exceptions_cleanup_tracing__open_opts(&opts);
+ if (!ASSERT_OK_PTR(skel, "tracer open"))
+ return;
+ bpf_program__set_autoload(skel->progs.fexit_unwinding_subprog, true);
+ err = bpf_program__set_attach_target(skel->progs.fexit_unwinding_subprog,
+ tgt_fd, "foo1");
+ if (!ASSERT_OK(err, "fexit target"))
+ goto out;
+ err = exceptions_cleanup_tracing__load(skel);
+ ASSERT_EQ(err, -EINVAL, "fexit load");
+ ASSERT_HAS_SUBSTR(log, "Cannot attach fexit, fmod_ret or fsession to foo1",
+ "fexit log");
+out:
+ exceptions_cleanup_tracing__destroy(skel);
+}
+
+static void test_light_skeleton(void)
+{
+ struct exceptions_cleanup_lskel *skel;
+ __u64 ctx = 0;
+ int err;
+
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &ctx,
+ .ctx_size_in = sizeof(ctx),
+ );
+
+ skel = exceptions_cleanup_lskel__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "light open_and_load"))
+ return;
+
+ /* foo3 unwinds, so every pad runs: the whole table has to arrive. */
+ skel->bss->input = 101;
+ err = bpf_prog_test_run_opts(skel->progs.entry.prog_fd, &topts);
+ if (!ASSERT_OK(err, "run"))
+ goto out;
+ ASSERT_EQ(topts.retval, 0, "retval");
+ ASSERT_EQ(skel->bss->pads_ran, PADS_FOO3_UNWOUND | RAN_BUMP,
+ "pads_ran");
+out:
+ exceptions_cleanup_lskel__destroy(skel);
+}
+
+void test_exceptions_cleanup(void)
+{
+ char log[8192] = {};
+
+ LIBBPF_OPTS(bpf_object_open_opts, opts,
+ .kernel_log_buf = log,
+ .kernel_log_size = sizeof(log));
+ struct exceptions_cleanup *skel;
+ int err;
+
+ skel = exceptions_cleanup__open_opts(&opts);
+ if (!ASSERT_OK_PTR(skel, "open"))
+ return;
+
+ err = exceptions_cleanup__load(skel);
+ if (err) {
+ if (err == -EOPNOTSUPP &&
+ strstr(log, "exception cleanup needs a JIT that can dispatch landing pads")) {
+ printf("%s:SKIP:JIT cannot dispatch exception cleanup landing pads\n",
+ __func__);
+ test__skip();
+ } else if (!ASSERT_OK(err, "load")) {
+ fprintf(stderr, "%s", log);
+ }
+ exceptions_cleanup__destroy(skel);
+ return;
+ }
+
+ /* No unwind: foo3 returns 1 ^ 1 == 0, foo2 adds one, no pad runs. */
+ if (test__start_subtest("no_unwind"))
+ run(skel, 1, 1, 0);
+
+ /* foo3 unwinds; every pad runs and entry returns zero. */
+ if (test__start_subtest("unwind_from_foo3"))
+ run(skel, 101, 0, PADS_FOO3_UNWOUND);
+
+ /*
+ * foo3 returns 2 ^ 1 == 3, so foo2 unwinds from its own second region;
+ * foo3's frame is long gone, so its pad must not run.
+ */
+ if (test__start_subtest("unwind_from_foo2"))
+ run(skel, 2, 0, PADS_FOO2_UNWOUND);
+
+ if (test__start_subtest("tracing_unwinding_subprog"))
+ test_tracing(skel);
+
+ exceptions_cleanup__destroy(skel);
+
+ if (test__start_subtest("light_skeleton"))
+ test_light_skeleton();
+
+ RUN_TESTS(exceptions_cleanup_fail);
+ RUN_TESTS(exceptions_cleanup_shapes);
+}
diff --git a/tools/testing/selftests/bpf/progs/bpf_misc.h b/tools/testing/selftests/bpf/progs/bpf_misc.h
index d7f706c3bc4af..f5baeb979cc22 100644
--- a/tools/testing/selftests/bpf/progs/bpf_misc.h
+++ b/tools/testing/selftests/bpf/progs/bpf_misc.h
@@ -107,6 +107,16 @@
* - POINTER_VALUE
* - TEST_DATA_LEN
* __retval_unpriv Same, but load program in unprivileged mode.
+ * __set_global Set a global variable of the program to a value before
+ * executing it. The variable has to be an int or an enum,
+ * live in .bss or .data and be four or eight bytes wide,
+ * and the value is a number or several joined by '|',
+ * without parentheses.
+ * __ret_global Execute the program and check that a global variable
+ * holds the given value afterwards, under the same rules.
+ * __set_global and __ret_global both make the loader run
+ * the program and check its return value; without
+ * __retval, the program must return 0.
*
* __description Text to be used for display and as an additional filter
* alias, while the original program name stays matchable.
@@ -167,6 +177,8 @@
#define __flag(flag) __test_tag("test_prog_flags=" #flag)
#define __retval(val) __test_tag("test_retval=" XSTR(val))
#define __retval_unpriv(val) __test_tag("test_retval_unpriv=" XSTR(val))
+#define __set_global(var, val) __test_tag("test_global_set=" #var ":" XSTR(val))
+#define __ret_global(var, val) __test_tag("test_global_ret=" #var ":" XSTR(val))
#define __auxiliary __test_tag("test_auxiliary")
#define __auxiliary_unpriv __test_tag("test_auxiliary_unpriv")
#define __btf_path(path) __test_tag("test_btf_path=" path)
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup.c
new file mode 100644
index 0000000000000..24523ee05acf8
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup.c
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "exceptions_cleanup.h"
+
+static __used __noinline void __kfunc_btf_anchor(void)
+{
+ bpf_unwind();
+ bpf_rcu_read_lock();
+ bpf_rcu_read_unlock();
+ bpf_preempt_disable();
+ bpf_preempt_enable();
+ bpf_unwind_resume(NULL);
+}
+
+__u64 input = 0;
+__u64 pads_ran = 0;
+__u64 result = 0;
+__u64 never = 0;
+
+static __used __noinline __u64 foo3(__u64 x)
+{
+ bpf_preempt_disable();
+ if (x > 100)
+ asm volatile (
+ "1:" "call bpf_unwind;" /* cleanup region */
+ "2:"
+ "goto 3f;"
+ "4:" /* landing pad */
+ /*
+ * r0 at pad entry is the zero the fixups put after the
+ * bpf_unwind() call. It is kept in a callee-saved
+ * register and handed to the resume, the way a
+ * compiler-emitted pad passes the exception pointer to
+ * _Unwind_Resume. The kfunc takes it and ignores it, and
+ * the two pads below do without the shuffle.
+ */
+ "r7 = r0;"
+ "call bpf_preempt_enable;"
+ PAD_RAN("%[ran]")
+ "r1 = r7;"
+ "call bpf_unwind_resume;"
+ "3:"
+ CLEANUP_REC("1b", "2b", "4b")
+ :
+ : [ran]"i"(RAN_FOO3_PREEMPT),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+ bpf_preempt_enable();
+ return x ^ 1;
+}
+
+static __used __naked __noinline void drop_glue(void)
+{
+ asm volatile (
+ PAD_RAN("%[ran]")
+ "exit;"
+ :
+ : [ran]"i"(RAN_FOO2_DROP), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 foo2(void)
+{
+ asm volatile (
+ "r6 = r1;"
+ "call bpf_rcu_read_lock;"
+ "r1 = r6;"
+"1:" "call foo3;" /* cleanup region #1 */
+"2:"
+ "r6 = r0;"
+ "if r6 == 0 goto 5f;"
+"3:" "call bpf_unwind;" /* cleanup region #2 */
+"4:" "goto 4b;"
+"5:"
+ "call bpf_rcu_read_unlock;"
+ "r0 = r6;"
+ "r0 += 1;"
+ "exit;"
+"6:" /* landing pad, shared by both regions */
+ "call drop_glue;"
+ "call bpf_rcu_read_unlock;"
+ PAD_RAN("%[ran_rcu]")
+ "call bpf_unwind_resume;"
+ "exit;" /* never reached, kept for coverage */
+ CLEANUP_REC("1b", "2b", "6b")
+ CLEANUP_REC("3b", "4b", "6b")
+ :
+ : [ran_rcu]"i"(RAN_FOO2_RCU),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+static __used __naked __noinline void foo1v(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call foo2;" /* cleanup region */
+"2:"
+ "r6 = r0;"
+ "call bpf_preempt_enable;"
+ "r1 = %[result] ll;"
+ "*(u64 *)(r1 + 0) = r6;"
+ "goto 7f;"
+"8:" /* landing pad */
+ "call bpf_preempt_enable;"
+ PAD_RAN("%[ran]")
+ "goto 9f;"
+"7:" /* the frame's own exit block */
+ "r0 = 0;"
+ "exit;"
+"9:" /* resume block, after the frame's exit */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "8b")
+ :
+ : [ran]"i"(RAN_FOO1V_PREEMPT), __imm_addr(input),
+ __imm_addr(result), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/*
+ * A frame with no cleanup record: an unwind leaving it runs no pad. The
+ * unwind never fires -- @never is global -- and the bit marks the return path.
+ */
+static __used __naked __noinline void bump(void)
+{
+ asm volatile (
+ PAD_RAN("%[ran]")
+ "r1 = %[never] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "if r1 == 0 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "exit;" /* r0 deliberately left alone */
+ :
+ : [ran]"i"(RAN_BUMP), __imm_addr(never), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+__noinline __u64 foo1(void)
+{
+ bump();
+ foo1v();
+ return result;
+}
+
+SEC("syscall")
+int entry(void *ctx)
+{
+ return foo1();
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c
new file mode 100644
index 0000000000000..18d45395425fc
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c
@@ -0,0 +1,792 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_experimental.h"
+#include "bpf_misc.h"
+#include "exceptions_cleanup.h"
+
+__u64 input = 0;
+
+static __used __noinline void __kfunc_btf_anchor(void)
+{
+ bpf_throw(0);
+ bpf_unwind();
+ bpf_preempt_disable();
+ bpf_preempt_enable();
+ bpf_rcu_read_lock();
+ bpf_rcu_read_unlock();
+ bpf_unwind_resume(NULL);
+}
+
+/* An unwind raised in a callee, which is how a cleanup region gets one. */
+static __used __naked __noinline __u64 inner_unwind(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+static int unwinding_cb(__u32 idx, void *ctx)
+{
+ bpf_unwind();
+ return 0;
+}
+
+SEC("?syscall")
+__failure __msg("may unwind and is used as a callback")
+int callback_may_unwind(void *ctx)
+{
+ bpf_loop(1, unwinding_cb, NULL, 0);
+ return 0;
+}
+
+__noinline int unused_exc_cb(u64 cookie)
+{
+ return 0;
+}
+
+/* A frame with a table and a pad, for tests whose refusal lies elsewhere. */
+static __used __naked __noinline __u64 table_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;" /* never reached, kept for coverage */
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__exception_cb(unused_exc_cb)
+__failure __msg("cannot be combined with an exception callback")
+int table_with_exception_cb(void *ctx)
+{
+ return table_frame();
+}
+
+/*
+ * A throw and a table, with no callback tagged: the default callback is
+ * appended too late to stand in for the throw, so the program is scanned
+ * for one instead.
+ */
+static __used __naked __noinline __u64 throw_and_table_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("cannot be combined with bpf_throw")
+int table_with_throw(void *ctx)
+{
+ if (input)
+ bpf_throw(0);
+ return throw_and_table_frame();
+}
+
+__u64 never;
+
+/*
+ * A pad calling a global subprogram that can unwind. The subprogram is
+ * verified on its own, so the pad rule is what refuses it.
+ */
+__noinline void pad_callee_that_unwinds(void)
+{
+ if (never)
+ bpf_unwind();
+}
+
+static __used __naked __noinline __u64 pad_calls_unwinder_frame(void)
+{
+ asm volatile (
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call pad_callee_that_unwinds;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("which can unwind while an unwind is in flight")
+int pad_calls_unwinder(void *ctx)
+{
+ return pad_calls_unwinder_frame();
+}
+
+static __used __naked __noinline __u64 catch_pad_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* catch pad: no resume, it stops here */
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("ends a landing pad: a catch pad is not supported yet")
+int catch_landing_pad(void *ctx)
+{
+ return catch_pad_frame();
+}
+
+/* A bpf_unwind_resume() outside any landing pad. */
+SEC("?syscall")
+__failure __msg("is not in a landing pad")
+int resume_outside_pad(void *ctx)
+{
+ /* Never taken, but reachable, which is all the verifier needs. */
+ if (never)
+ bpf_unwind_resume(NULL);
+ return table_frame();
+}
+
+/* A bpf_unwind_resume() in a subprogram a landing pad calls. */
+static __used __naked __noinline void resume_in_callee(void)
+{
+ asm volatile (
+ "call bpf_unwind_resume;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 pad_calls_resumer_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ "call resume_in_callee;" /* ...which resumes: refused */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is not in a landing pad")
+int resume_in_pad_callee(void *ctx)
+{
+ return pad_calls_resumer_frame();
+}
+
+static __used __naked __noinline __u64 nested_pad_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call inner_unwind;" /* first cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* first pad, second region's call */
+ "call bpf_preempt_enable;"
+"4:"
+ "call bpf_unwind_resume;"
+"5:" /* second pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ CLEANUP_REC("3b", "4b", "5b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is inside the call-site range of")
+int nested_landing_pad(void *ctx)
+{
+ return nested_pad_frame();
+}
+
+/* A tail call in a landing pad: the frame would never reach its resume. */
+struct {
+ __uint(type, BPF_MAP_TYPE_PROG_ARRAY);
+ __uint(max_entries, 1);
+ __uint(key_size, sizeof(__u32));
+ __uint(value_size, sizeof(__u32));
+} tc_map SEC(".maps");
+
+static __used __naked __noinline __u64 tail_call_pad_frame(void)
+{
+ asm volatile (
+ "r6 = r1;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = r6;"
+ "r2 = %[tc_map] ll;"
+ "r3 = 0;"
+ "call %[bpf_tail_call];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm(bpf_tail_call), __imm_addr(tc_map)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is a tail call, which replaces the frame, and is in a landing pad")
+int tail_call_in_pad(void *ctx)
+{
+ return tail_call_pad_frame();
+}
+
+#if defined(__BPF_FEATURE_STACK_ARGUMENT)
+
+/*
+ * A pad reading an incoming stack argument after its own bpf_unwind(): the
+ * call clobbered the register the JIT keeps it in. Every parameter is used,
+ * so the caller passes them all, and summed before the call, so the pad's is
+ * the only stack argument load after it.
+ */
+static __used __noinline __u64 stack_arg_pad_frame(__u64 a, __u64 b, __u64 c,
+ __u64 d, __u64 e, __u64 f)
+{
+ __u64 sum = a + b + c + d + e + f;
+
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:"
+ "goto 4f;"
+"3:" /* landing pad */
+ "r0 = *(u64 *)(r11 + 8);"
+ "call bpf_unwind_resume;"
+"4:"
+ CLEANUP_REC("1b", "2b", "3b")
+ : "+r"(sum) :: __clobber_common);
+ return sum;
+}
+
+SEC("?syscall")
+__failure __msg("r11 load must be before any r11 store or call insn")
+int stack_arg_load_in_pad(void *ctx)
+{
+ return stack_arg_pad_frame(1, 2, 3, 4, 5, 6);
+}
+
+#endif /* __BPF_FEATURE_STACK_ARGUMENT */
+
+/*
+ * A landing pad entered by ordinary control flow, with no unwind in flight:
+ * that path reaches the pad's resume outside a pad. Only the in_pad
+ * comparison in func_states_equal() keeps it from being pruned against the
+ * pad's own visit of that instruction.
+ */
+static __used __naked __noinline __u64 jump_into_pad_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "if r6 > 7 goto 4f;" /* an ordinary branch into the pad */
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r7 = r0;"
+"4:" /* ... and its second instruction */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("is not in a landing pad")
+__flag(BPF_F_TEST_STATE_FREQ)
+int jump_into_pad(void *ctx)
+{
+ return jump_into_pad_frame();
+}
+
+#if defined(__clang__) && \
+ (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))
+
+/*
+ * An indirect jump in a landing pad. A jump table entry is an offset from
+ * the program's section symbol, which has to be spelled in quotes here.
+ */
+SEC("?syscall")
+__failure __msg("is an indirect jump")
+__naked void gotox_in_pad(void)
+{
+ asm volatile (
+ ".pushsection .jumptables,\"\",@progbits;"
+"jt0_%=:"
+ ".quad l0_%= - \"?syscall\";"
+ ".quad l1_%= - \"?syscall\";"
+ ".size jt0_%=, 16;"
+ ".global jt0_%=;"
+ ".popsection;"
+
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = jt0_%= ll;"
+ "r1 += 8;"
+ "r2 = *(u64 *)(r1 + 0);"
+ /*
+ * gotox r2, as raw bytes: the mnemonic only reached the LLVM
+ * assembler in llvm 22, and BPF_RAW_INSN() needs <linux/bpf.h>, which
+ * vmlinux.h rules out.
+ */
+ ".byte 0x0d, 0x02, 0, 0, 0, 0, 0, 0;"
+"l0_%=:"
+ "call bpf_unwind_resume;"
+"l1_%=:"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+#endif /* __clang__ && (x86 || arm64) */
+
+/* A BPF_LD_[ABS|IND] in a pad: a failed load leaves without resuming. */
+static __used __naked __noinline __u64 ld_abs_pad_frame(void)
+{
+ asm volatile (
+ "r6 = r1;" /* the skb BPF_LD_ABS reads */
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r0 = *(u32 *)skb[0];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?tc")
+__failure __msg("is a BPF_LD_[ABS|IND], which can leave through the epilogue")
+__naked void ld_abs_in_pad(void)
+{
+ asm volatile (
+ "call ld_abs_pad_frame;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * A subprogram a landing pad calls, which unwinds on its own. The second
+ * unwind would rewrite return addresses the first has already redirected.
+ */
+static __used __naked __noinline __u64 own_pad_callee(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* its landing pad */
+ "call bpf_preempt_enable;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 pad_calls_own_pad_frame(void)
+{
+ asm volatile (
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad, which calls the above */
+ "call own_pad_callee;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("starts a second unwind while one is in flight")
+int unwind_in_pad_callee(void *ctx)
+{
+ return pad_calls_own_pad_frame();
+}
+
+/* A record whose range holds no call that can unwind. */
+static __used __naked __noinline __u64 nounwind_rec_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+"1:" "call bpf_preempt_enable;" /* cleanup region: nounwind */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad, reached by nothing */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("unreachable insn")
+int nounwind_region(void *ctx)
+{
+ return nounwind_rec_frame();
+}
+
+/*
+ * An unwind with no landing pad in the main program returns from it, so what
+ * it holds is checked there, as at a plain exit.
+ */
+SEC("?syscall")
+__failure __msg("bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region")
+int unwind_no_pad_rcu(void *ctx)
+{
+ bpf_rcu_read_lock();
+ bpf_unwind();
+ bpf_rcu_read_unlock();
+ return 0;
+}
+
+/*
+ * Lock and reference state is the program's, not a frame's: an unwind carries
+ * it through every pad it runs, and what is still held when the main program
+ * returns is refused there. A pad that drops what its caller holds is fine;
+ * the caller's own pad dropping it again is not.
+ */
+static __used __naked __noinline __u64 pad_drops_caller_lock_frame(void)
+{
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* pad: drops a lock it never took */
+ "call bpf_rcu_read_unlock;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 caller_holds_lock_frame(void)
+{
+ asm volatile (
+ "call bpf_rcu_read_lock;"
+"1:" "call pad_drops_caller_lock_frame;"
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad */
+ "call bpf_rcu_read_unlock;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("unmatched rcu read unlock")
+int pad_drops_caller_lock(void *ctx)
+{
+ return caller_holds_lock_frame();
+}
+
+/* The other way round: a pad that does not drop what its own frame took. */
+static __used __naked __noinline __u64 pad_keeps_own_lock_frame(void)
+{
+ asm volatile (
+ "call bpf_rcu_read_lock;"
+"1:" "call inner_unwind;" /* cleanup region */
+"2:"
+ "call bpf_rcu_read_unlock;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: forgets the unlock */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region")
+int pad_keeps_own_lock(void *ctx)
+{
+ return pad_keeps_own_lock_frame();
+}
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(max_entries, 4096);
+} unwind_ringbuf SEC(".maps");
+
+/*
+ * Always unwinds, so its caller is never returned to on the modelled path,
+ * and the caller's post-call code, which never releases the record, is not
+ * walked. Its pad discards the record the caller reserved.
+ */
+static __used __naked __noinline __u64 pad_drops_caller_ref_frame(void)
+{
+ asm volatile (
+ "r6 = r1;" /* the caller's reserved record */
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* pad: drops what it never acquired */
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm(bpf_ringbuf_discard)
+ : __clobber_all);
+}
+
+/* And this frame's own pad drops it a second time. */
+static __used __naked __noinline __u64 caller_holds_ref_frame(void)
+{
+ asm volatile (
+ "r1 = %[unwind_ringbuf] ll;"
+ "r2 = 8;"
+ "r3 = 0;"
+ "call %[bpf_ringbuf_reserve];"
+ "if r0 == 0 goto 9f;"
+ "r6 = r0;"
+ "r1 = r6;"
+"1:" "call pad_drops_caller_ref_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad */
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "call bpf_unwind_resume;"
+"9:"
+ "r0 = 0;"
+ "exit;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard),
+ __imm_addr(unwind_ringbuf)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("R1 type=scalar expected=ringbuf_mem")
+int pad_drops_caller_ref(void *ctx)
+{
+ return caller_holds_ref_frame();
+}
+
+/*
+ * A frame an unwind returns through without a pad is abandoned where it made
+ * the call: the JIT sends it to its epilogue, so nothing of it runs again and
+ * whatever it acquired is never released -- which the main program's exit
+ * then finds still held.
+ */
+static __used __naked __noinline __u64 pad_resumes_frame(void)
+{
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* pad */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 uncovered_holds_lock_frame(void)
+{
+ asm volatile (
+ "call bpf_rcu_read_lock;"
+ "call pad_resumes_frame;" /* no record covers this call */
+ "call bpf_rcu_read_unlock;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("bpf_unwind cannot be used inside bpf_rcu_read_lock-ed region")
+int unwind_through_call_keeps_lock(void *ctx)
+{
+ return uncovered_holds_lock_frame();
+}
+
+static __used __naked __noinline __u64 uncovered_holds_ref_frame(void)
+{
+ asm volatile (
+ "r1 = %[unwind_ringbuf] ll;"
+ "r2 = 8;"
+ "r3 = 0;"
+ "call %[bpf_ringbuf_reserve];"
+ "if r0 == 0 goto 9f;"
+ "r6 = r0;"
+ "call pad_resumes_frame;" /* no record covers this call */
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+"9:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard),
+ __imm_addr(unwind_ringbuf)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("Unreleased reference id=")
+int unwind_through_call_keeps_ref(void *ctx)
+{
+ return uncovered_holds_ref_frame();
+}
+
+/*
+ * A callee writes its caller's stack through a pointer argument, then
+ * unwinds. The caller's pad runs after that write, so it cannot keep trusting
+ * the slot to hold the zero it held at the call.
+ */
+static __used __naked __noinline __u64 stack_writer(void)
+{
+ asm volatile (
+ "r2 = 0x10000000;"
+ "*(u64 *)(r1 + 0) = r2;" /* r1 is the caller's fp-8 */
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 stale_stack_frame(void)
+{
+ asm volatile (
+ "r6 = 0;"
+ "*(u64 *)(r10 - 8) = r6;"
+ "*(u64 *)(r10 - 64) = r6;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call stack_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: fp-8 as an offset into fp-64 */
+ "r1 = *(u64 *)(r10 - 8);"
+ "r2 = r10;"
+ "r2 += -64;"
+ "r2 += r1;"
+ "r0 = *(u8 *)(r2 + 0);"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("invalid read from stack R2 off=268435392 size=1")
+int stale_stack_pad(void *ctx)
+{
+ return stale_stack_frame();
+}
+
+/* The same through a global subprog, which is not walked from its caller. */
+__noinline int global_stack_writer(__u64 *p)
+{
+ if (!p)
+ return 0;
+ *p = 0x10000000;
+ bpf_unwind();
+ return 0;
+}
+
+static __used __naked __noinline __u64 global_stale_stack_frame(void)
+{
+ asm volatile (
+ "r6 = 0;"
+ "*(u64 *)(r10 - 8) = r6;"
+ "*(u64 *)(r10 - 64) = r6;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call global_stack_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: fp-8 as an offset into fp-64 */
+ "r1 = *(u64 *)(r10 - 8);"
+ "r2 = r10;"
+ "r2 += -64;"
+ "r2 += r1;"
+ "r0 = *(u8 *)(r2 + 0);"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("math between fp pointer and register with unbounded min value")
+int global_stale_stack_pad(void *ctx)
+{
+ return global_stale_stack_frame();
+}
+
+/* gcc has no indirect calls, and only these JITs emit them */
+#if defined(__clang__) && \
+ (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))
+
+/*
+ * A callback calling an unwinding subprog through a pointer it read from its
+ * caller's stack: it neither calls nor takes the address of inner_unwind, so
+ * only the marking of every subprog with a callx makes it might_unwind.
+ */
+static __used __naked __noinline int callx_cb(void)
+{
+ asm volatile (
+ "r1 = *(u64 *)(r2 + 0);"
+ "callx r1;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__failure __msg("may unwind and is used as a callback")
+__naked int callback_callx_may_unwind(void)
+{
+ asm volatile (
+ "r1 = %[inner_unwind] ll;"
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = 1;"
+ "r2 = %[callx_cb] ll;"
+ "r3 = r10;"
+ "r3 += -8;"
+ "r4 = 0;"
+ "call %[bpf_loop];"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(inner_unwind), __imm_addr(callx_cb), __imm(bpf_loop)
+ : __clobber_all);
+}
+
+#endif /* __clang__ && (x86 || arm64) */
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c
new file mode 100644
index 0000000000000..af92ee6cb9711
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c
@@ -0,0 +1,1134 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "exceptions_cleanup.h"
+
+static __used __noinline void __kfunc_btf_anchor(void)
+{
+ bpf_unwind();
+ bpf_rcu_read_lock();
+ bpf_rcu_read_unlock();
+ bpf_preempt_disable();
+ bpf_preempt_enable();
+ bpf_unwind_resume(NULL);
+}
+
+__u64 input = 0;
+__u64 magic = 0x5eed;
+__u64 pads_ran = 0;
+
+/* Load r6-r9 with values derived from @magic. */
+#define LOAD_MAGIC_REGS \
+ "r1 = %[magic] ll;" \
+ "r6 = *(u64 *)(r1 + 0);" \
+ "r7 = r6;" \
+ "r7 += 1;" \
+ "r8 = r6;" \
+ "r8 += 2;" \
+ "r9 = r6;" \
+ "r9 += 3;"
+
+/* Set @bit only if r6-r9 still hold what LOAD_MAGIC_REGS put there. */
+#define CHECK_MAGIC_REGS(bit) \
+ "r1 = %[magic] ll;" \
+ "r2 = *(u64 *)(r1 + 0);" \
+ "if r6 != r2 goto 9f;" \
+ "r2 += 1;" \
+ "if r7 != r2 goto 9f;" \
+ "r2 += 1;" \
+ "if r8 != r2 goto 9f;" \
+ "r2 += 1;" \
+ "if r9 != r2 goto 9f;" \
+ PAD_RAN(bit) \
+ "9:"
+
+/* A callee that unwinds when its argument is over 100. */
+static __used __noinline __u64 pc_unwinder(__u64 x)
+{
+ if (x > 100)
+ bpf_unwind();
+ return x + 1;
+}
+
+static __used __naked __noinline __u64 regs_unwinder(void)
+{
+ asm volatile (
+ /* Clobber the caller's r6-r9; the unwind must restore them. */
+ "r6 = 0xdead;"
+ "r7 = 0xbeef;"
+ "r8 = 0xcafe;"
+ "r9 = 0xf00d;"
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+/* A pad that reads r6-r9, which the callee overwrote before it unwound. */
+static __used __naked __noinline __u64 regs_frame(void)
+{
+ asm volatile (
+ LOAD_MAGIC_REGS
+ "call bpf_preempt_disable;"
+"1:" "call regs_unwinder;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ CHECK_MAGIC_REGS("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_REGS),
+ __imm_addr(magic), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_REGS)
+int entry_regs(void *ctx)
+{
+ return regs_frame();
+}
+
+/* A region ending on a 16-byte insn, so end - 1 names its second half. */
+static __used __naked __noinline __u64 wide_rec_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "call bpf_rcu_read_lock;"
+ "r1 = r6;"
+"1:" "call pc_unwinder;" /* cleanup region begins */
+ "r1 = %[magic] ll;" /* ... and ends on this pair */
+"2:"
+ "r6 = r0;"
+ "call bpf_rcu_read_unlock;"
+ "r0 = r6;"
+ "exit;"
+"3:" /* landing pad */
+ "r7 = r0;"
+ "call bpf_rcu_read_unlock;"
+ PAD_RAN("%[ran]")
+ "r1 = r7;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_WIDE_REC), __imm_addr(input), __imm_addr(magic),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_WIDE_REC)
+int entry_wide_rec(void *ctx)
+{
+ return wide_rec_frame();
+}
+
+/* LLVM's name for the resume; libbpf resolves it to bpf_unwind_resume(). */
+extern void _Unwind_Resume(void *ptr) __ksym;
+
+static __used __noinline void __resume_alias_btf_anchor(void)
+{
+ _Unwind_Resume(NULL);
+}
+
+static __used __naked __noinline __u64 resume_alias_frame(void)
+{
+ asm volatile (
+"1:" "call regs_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call _Unwind_Resume;" /* the frontend's name for it */
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_RESUME_ALIAS), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_RESUME_ALIAS)
+int entry_resume_alias(void *ctx)
+{
+ return resume_alias_frame();
+}
+
+/* A pad starting on a nop, which bpf_opt_remove_nops() drops after the walk. */
+static __used __naked __noinline __u64 nop_pad_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "if r6 < 101 goto 6f;"
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:"
+"6:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad: a nop, then its body */
+ "goto +0;"
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NOP_PAD),
+ __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_NOP_PAD)
+int entry_nop_pad(void *ctx)
+{
+ return nop_pad_frame();
+}
+
+/* Put @magic in both of the slots a variable offset could name. */
+#define FILL_MAGIC_SLOTS \
+ "r1 = %[magic] ll;" \
+ "r1 = *(u64 *)(r1 + 0);" \
+ "*(u64 *)(r10 - 8) = r1;" \
+ "*(u64 *)(r10 - 16) = r1;"
+
+/* Set @bit if the slot @idx names, read at a variable offset, holds it. */
+#define CHECK_VAR_SLOT(idx, bit) \
+ "r1 = r10;" \
+ "r1 += " idx ";" \
+ "r2 = *(u64 *)(r1 - 16);" \
+ "r3 = %[magic] ll;" \
+ "r3 = *(u64 *)(r3 + 0);" \
+ "if r2 != r3 goto 9f;" \
+ PAD_RAN(bit) \
+ "9:"
+
+/* A callee that unwinds when r1 is at least 101, and touches none of r6-r9. */
+static __used __naked __noinline __u64 var_unwinder(void)
+{
+ asm volatile (
+ "if r1 < 101 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 var_stack_frame(void)
+{
+ asm volatile (
+ FILL_MAGIC_SLOTS
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "r6 &= 1;" /* an unknown slot number... */
+ "r6 <<= 3;" /* ...as an aligned byte offset */
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call var_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r7 = r0;"
+ CHECK_VAR_SLOT("r6", "%[ran]")
+ "r1 = r7;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_VAR_STACK), __imm_addr(input), __imm_addr(magic),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_VAR_STACK)
+int entry_var_stack(void *ctx)
+{
+ return var_stack_frame();
+}
+
+/* Two pads with an uncovered frame between them. */
+static __used __naked __noinline __u64 gap_inner_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call pc_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r6 = r0;"
+ PAD_RAN("%[ran]")
+ "r1 = r6;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_GAP_INNER), __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/* The frame in between, with no record of its own. */
+static __used __noinline __u64 gap_mid(void)
+{
+ return gap_inner_frame() + 1;
+}
+
+static __used __naked __noinline __u64 gap_outer_frame(void)
+{
+ asm volatile (
+"1:" "call gap_mid;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r6 = r0;"
+ PAD_RAN("%[ran]")
+ "r1 = r6;"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_GAP_OUTER), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/* And one more uncovered frame between the outer pad and the main program. */
+static __used __noinline __u64 gap_top(void)
+{
+ return gap_outer_frame() + 1;
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_GAP_INNER | RAN_GAP_OUTER)
+int entry_two_pads(void *ctx)
+{
+ return gap_top();
+}
+
+/*
+ * A precision chain crossing a resume: the outer frame's pad uses r6 as a
+ * variable stack offset, and the only way into that pad is the resume that
+ * ends the inner frame's pad, so backtracking goes from the pad through the
+ * inner frame and back to where r6 was bounded.
+ */
+static __used __naked __noinline __u64 prec_inner_frame(void)
+{
+ asm volatile (
+"1:" "call bpf_unwind;" /* cleanup region */
+"2:" "goto 2b;"
+"3:" /* landing pad */
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 prec_outer_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r6 = *(u64 *)(r1 + 0);"
+ "r6 &= 0x7;"
+ "r0 = 0;"
+ "*(u64 *)(r10 - 8) = r0;"
+ "*(u64 *)(r10 - 16) = r0;"
+"1:" "call prec_inner_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* pad: r6 as a variable stack offset */
+ "r2 = r10;"
+ "r2 += -16;"
+ "r2 += r6;"
+ "*(u8 *)(r2 + 0) = 1;"
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_PREC_RESUME), __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_PREC_RESUME)
+__log_level(2)
+__msg("frame1: regs=r6 stack= before {{[0-9]+}}: (85) call bpf_unwind_resume")
+__msg("frame2: regs= stack= before {{[0-9]+}}: (85) call bpf_unwind#")
+__msg("frame1: regs=r6 stack= before {{[0-9]+}}: (57) r6 &= 7")
+int entry_prec_across_resume(void *ctx)
+{
+ return prec_outer_frame();
+}
+
+/* Unwinds every time, and no record covers it, so the path simply ends. */
+static __used __naked __noinline __u64 always_unwind(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * A frame with no record of its own above one that always unwinds: nothing
+ * after the call is reachable, so dead code removal would leave it no exit
+ * and no epilogue for the unwind to send it to. One is kept, and since this
+ * frame ends in a jump rather than an exit, it is not the last instruction.
+ */
+static __used __naked __noinline __u64 no_exit_ja_mid(void)
+{
+ asm volatile (
+ "goto 2f;"
+"1:" "r0 = 1;"
+ "exit;"
+"2:" "call always_unwind;"
+ "goto 1b;" /* the last insn, and not an exit */
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_exit_ja_outer_frame(void)
+{
+ asm volatile (
+"1:" "call no_exit_ja_mid;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NO_EXIT_JA), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_NO_EXIT_JA)
+int entry_no_exit_ja(void *ctx)
+{
+ return no_exit_ja_outer_frame();
+}
+
+/*
+ * Frames that only unwind, the way a compiler leaves functions that return
+ * `!`: after the call comes the loop that stands for what cannot happen, and
+ * no exit. The unwinder leaves through the exit put after its bpf_unwind();
+ * the frame above it, which has no record, is sent to an epilogue, so the
+ * verifier gives it an exit.
+ */
+static __used __naked __noinline __u64 no_exit_loop_unwinder(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+"1:" "goto 1b;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_exit_loop_mid(void)
+{
+ asm volatile (
+ "call no_exit_loop_unwinder;"
+"1:" "goto 1b;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_exit_loop_outer_frame(void)
+{
+ asm volatile (
+"1:" "call no_exit_loop_mid;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NO_EXIT_LOOP), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_NO_EXIT_LOOP)
+int entry_no_exit_loop(void *ctx)
+{
+ return no_exit_loop_outer_frame();
+}
+
+/*
+ * A frame with no exit whose last insn is a covered call to a subprog placed
+ * after it: the frame jumps over its pad to get there. The exit the verifier
+ * puts after that call moves the callee down by one, and the record has to
+ * stay on the call, or the unwind finds no pad for the frame.
+ */
+static __used __naked __noinline __u64 last_call_frame(void)
+{
+ asm volatile (
+ "goto 1f;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+"1:" "call last_call_unwinder;" /* cleanup region, and the last insn */
+"2:"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_LAST_CALL), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+/* After last_call_frame(), and without an exit, so it may be called last. */
+static __used __naked __noinline void last_call_unwinder(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_LAST_CALL)
+int entry_last_call(void *ctx)
+{
+ return last_call_frame();
+}
+
+/*
+ * Nothing after a call that does not return, the way a compiler emits it:
+ * no_tail_fail() is a call to bpf_unwind() and nothing else, no_tail_check()
+ * returns its argument or ends with the call to no_tail_fail(), and the pad
+ * of no_tail_frame() ends with its resume.
+ */
+static __used __naked __noinline void no_tail_fail(void)
+{
+ asm volatile (
+ "call bpf_unwind;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_tail_check(void)
+{
+ asm volatile (
+ "if r1 > 7 goto 1f;"
+ "r0 = r1;"
+ "exit;"
+"1:" "call no_tail_fail;"
+ ::: __clobber_all);
+}
+
+static __used __naked __noinline __u64 no_tail_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call no_tail_check;" /* cleanup region */
+"2:"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_NO_TAIL), __imm_addr(input), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_NO_TAIL)
+int entry_no_tail_unwind(void *ctx)
+{
+ return no_tail_frame();
+}
+
+SEC("?syscall")
+__success __set_global(input, 3) __retval(3)
+__ret_global(pads_ran, 0)
+int entry_no_tail_return(void *ctx)
+{
+ return no_tail_frame();
+}
+
+/* gcc has no indirect calls, and only these JITs emit them */
+#if defined(__clang__) && \
+ (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64))
+
+/*
+ * A region covering an indirect call: a record names a call by its return
+ * address, which a callx leaves like any other call.
+ */
+static __used __naked __noinline __u64 callx_region_frame(void)
+{
+ asm volatile (
+ "call bpf_preempt_disable;"
+ "r2 = %[always_unwind] ll;"
+"1:" "callx r2;" /* cleanup region */
+"2:"
+ "call bpf_preempt_enable;"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "call bpf_preempt_enable;"
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_CALLX), __imm_addr(always_unwind),
+ __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__ret_global(pads_ran, RAN_CALLX)
+int entry_callx_region(void *ctx)
+{
+ return callx_region_frame();
+}
+
+/*
+ * A subprog calling an unwinding one through a pointer it was handed: nothing
+ * after the call runs, but a callx cannot end a subprog, so code follows it.
+ */
+static __used __naked __noinline __u64 callx_arg_frame(void)
+{
+ asm volatile (
+ "callx r1;" /* r1 is always_unwind */
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__naked int entry_callx_arg(void)
+{
+ asm volatile (
+ "r1 = %[always_unwind] ll;"
+ "call callx_arg_frame;"
+ "exit;"
+ :
+ : __imm_addr(always_unwind)
+ : __clobber_all);
+}
+
+#endif /* __clang__ && (x86 || arm64) */
+
+/* Add one to the @w-bit global at @addr. */
+#define BUMP_GLOBAL(w, addr) \
+ "r1 = " addr " ll;" \
+ "r2 = *(u" w " *)(r1 + 0);" \
+ "r2 += 1;" \
+ "*(u" w " *)(r1 + 0) = r2;"
+
+/*
+ * A pad that touches a global of each width and sign a test tag can name,
+ * so that __set_global() and __ret_global() are exercised on all four.
+ */
+int tag_i = 0;
+unsigned int tag_ui = 0;
+long tag_l = 0;
+unsigned long tag_ul = 0;
+
+static __used __naked __noinline __u64 tag_types_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call pc_unwinder;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ BUMP_GLOBAL("32", "%[tag_i]")
+ BUMP_GLOBAL("32", "%[tag_ui]")
+ BUMP_GLOBAL("64", "%[tag_l]")
+ BUMP_GLOBAL("64", "%[tag_ul]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : __imm_addr(input), __imm_addr(tag_i), __imm_addr(tag_ui),
+ __imm_addr(tag_l), __imm_addr(tag_ul)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __retval(0)
+__set_global(input, 101)
+__set_global(tag_i, -23) __set_global(tag_ui, 0xfffffffe)
+__set_global(tag_l, -23) __set_global(tag_ul, 0xfffffffffffffffe)
+__ret_global(tag_i, -22) __ret_global(tag_ui, 0xffffffff)
+__ret_global(tag_l, -22) __ret_global(tag_ul, 0xffffffffffffffff)
+int entry_tag_types(void *ctx)
+{
+ return tag_types_frame();
+}
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(max_entries, 4096);
+} shape_ringbuf SEC(".maps");
+
+/*
+ * A pad reading a slot its frame's callee wrote before it unwound. The write
+ * is there when the pad runs, and the pad has to be verified that way, or
+ * the check below is taken as always failing and the bit is never set.
+ */
+static __used __naked __noinline __u64 slot_writer(void)
+{
+ asm volatile (
+ "r2 = 42;"
+ "*(u64 *)(r1 + 0) = r2;" /* r1 is the caller's fp-8 */
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "if r1 < 101 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 callee_write_frame(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call slot_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = *(u64 *)(r10 - 8);"
+ "if r1 != 42 goto 9f;"
+ PAD_RAN("%[ran]")
+"9:"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_CALLEE_WRITE), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_CALLEE_WRITE)
+int entry_callee_write(void *ctx)
+{
+ return callee_write_frame();
+}
+
+/*
+ * A precision chain across an unwind: the pad uses a slot the callee wrote as
+ * a variable stack offset, so backtracking follows the slot from the pad back
+ * into the frame the unwind left.
+ */
+static __used __naked __noinline __u64 offset_writer(void)
+{
+ asm volatile (
+ "r2 = %[input] ll;"
+ "r3 = *(u64 *)(r2 + 0);"
+ "r3 &= 8;"
+ "*(u64 *)(r1 + 0) = r3;" /* r1 is the caller's fp-24 */
+ "call bpf_unwind;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 callee_offset_frame(void)
+{
+ asm volatile (
+ FILL_MAGIC_SLOTS
+ "r1 = 0;"
+ "*(u64 *)(r10 - 24) = r1;"
+ "r1 = r10;"
+ "r1 += -24;"
+"1:" "call offset_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r6 = *(u64 *)(r10 - 24);"
+ CHECK_VAR_SLOT("r6", "%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_CALLEE_OFFSET), __imm_addr(magic), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_CALLEE_OFFSET)
+__log_level(2)
+__msg("frame1: regs= stack=-24 before {{[0-9]+}}: (85) call bpf_unwind#")
+__msg("frame2: regs= stack= before {{[0-9]+}}: (7b) *(u64 *)(r1 +0) = r3")
+__msg("frame2: regs=r3 stack= before {{[0-9]+}}: (57) r3 &= 8")
+int entry_callee_offset(void *ctx)
+{
+ return callee_offset_frame();
+}
+
+/* The same through a global subprog. */
+__noinline int global_slot_writer(__u64 *p)
+{
+ if (!p)
+ return 0;
+ *p = 42;
+ if (input > 100)
+ bpf_unwind();
+ return 0;
+}
+
+static __used __naked __noinline __u64 global_write_frame(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = r10;"
+ "r1 += -8;"
+"1:" "call global_slot_writer;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ "r1 = *(u64 *)(r10 - 8);"
+ "if r1 != 42 goto 9f;"
+ PAD_RAN("%[ran]")
+"9:"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_GLOBAL_WRITE), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_GLOBAL_WRITE)
+int entry_global_write(void *ctx)
+{
+ return global_write_frame();
+}
+
+/*
+ * An unwind raised in a global subprog, called with no record over the call
+ * from a frame whose own caller has a pad. The global subprog is verified on
+ * its own, so the unwind is taken from the state its call returns in, and it
+ * has to go on to that pad.
+ */
+__noinline int global_unwinder(int x)
+{
+ if (x > 100)
+ bpf_unwind();
+ return 0;
+}
+
+static __used __naked __noinline __u64 through_global_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "call global_unwinder;" /* no record */
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 over_global_frame(void)
+{
+ asm volatile (
+"1:" "call through_global_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_THROUGH_GLOBAL), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_THROUGH_GLOBAL)
+int entry_through_global(void *ctx)
+{
+ return over_global_frame();
+}
+
+#if defined(__clang_major__) && __clang_major__ >= 23
+
+/*
+ * The same, with the global subprog returning in R0:R2: its unwind leaves
+ * R2 checked as a return value too, though its caller never reads either.
+ */
+struct u64_pair {
+ __u64 a;
+ __u64 b;
+};
+
+__noinline struct u64_pair global_pair_unwinder(int x)
+{
+ struct u64_pair p = { x, x + 1 };
+
+ if (x > 100)
+ bpf_unwind();
+ return p;
+}
+
+static __used __naked __noinline __u64 through_pair_global_frame(void)
+{
+ asm volatile (
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "call global_pair_unwinder;" /* no record */
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 over_pair_global_frame(void)
+{
+ asm volatile (
+"1:" "call through_pair_global_frame;" /* cleanup region */
+"2:"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad */
+ PAD_RAN("%[ran]")
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_PAIR_GLOBAL), __imm_addr(pads_ran)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_PAIR_GLOBAL)
+int entry_pair_global_unwind(void *ctx)
+{
+ return over_pair_global_frame();
+}
+
+#endif /* __clang_major__ >= 23 */
+
+/*
+ * A reference moved into a callee: the caller reserves a record and hands it
+ * over with a plain call, as rustc emits for 'consume(rec)' -- it has nothing
+ * left to drop -- and the callee drops it on return and, from its pad, on an
+ * unwind.
+ */
+static __used __naked __noinline __u64 consume_frame(void)
+{
+ asm volatile (
+ "r6 = r1;" /* the record, now owned here */
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+"1:" "call global_unwinder;" /* cleanup region */
+"2:"
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "r0 = 0;"
+ "exit;"
+"3:" /* landing pad: drop glue */
+ PAD_RAN("%[ran]")
+ "r1 = r6;"
+ "r2 = 0;"
+ "call %[bpf_ringbuf_discard];"
+ "call bpf_unwind_resume;"
+ CLEANUP_REC("1b", "2b", "3b")
+ :
+ : [ran]"i"(RAN_MOVE), __imm_addr(pads_ran), __imm_addr(input),
+ __imm(bpf_ringbuf_discard)
+ : __clobber_all);
+}
+
+static __used __naked __noinline __u64 move_frame(void)
+{
+ asm volatile (
+ "r1 = %[shape_ringbuf] ll;"
+ "r2 = 8;"
+ "r3 = 0;"
+ "call %[bpf_ringbuf_reserve];"
+ "if r0 == 0 goto 1f;"
+ "r1 = r0;"
+ "call consume_frame;" /* the record moves: no record here */
+"1:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(shape_ringbuf), __imm(bpf_ringbuf_reserve)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 101) __retval(0)
+__ret_global(pads_ran, RAN_MOVE)
+int entry_move_into_callee(void *ctx)
+{
+ return move_frame();
+}
+
+/*
+ * A bpf_unwind() inside a loop, with no pad between it and the main program.
+ * The main program's frame returns from where the unwind left it, not from
+ * the loop in the subprog.
+ */
+static __used __naked __noinline __u64 loop_unwinder(void)
+{
+ asm volatile (
+ "r6 = 0;"
+"1:"
+ "r1 = %[input] ll;"
+ "r1 = *(u64 *)(r1 + 0);"
+ "if r1 != r6 goto 2f;"
+ "call bpf_unwind;"
+"2:"
+ "r6 += 1;"
+ "if r6 < 4 goto 1b;"
+ "r0 = 1;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 2) __retval(0)
+int entry_unwind_in_loop(void *ctx)
+{
+ return loop_unwinder();
+}
+
+/*
+ * The loop in the main program itself, around a call that unwinds on one
+ * trip. The unwind returns from the main frame at that call, inside the loop,
+ * where no checkpoint need have been made yet.
+ */
+static __used __naked __noinline __u64 unwind_on_match(void)
+{
+ asm volatile (
+ "r2 = %[input] ll;"
+ "r2 = *(u64 *)(r2 + 0);"
+ "if r1 != r2 goto 1f;"
+ "call bpf_unwind;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ :
+ : __imm_addr(input)
+ : __clobber_all);
+}
+
+SEC("?syscall")
+__success __set_global(input, 2) __retval(0)
+__naked int entry_unwind_out_of_main_loop(void)
+{
+ asm volatile (
+ "r6 = 0;"
+"1:"
+ "r1 = r6;"
+ "call unwind_on_match;"
+ "r6 += 1;"
+ "if r6 < 4 goto 1b;"
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * An unwind reaching main's exit in a program type that checks r0: its
+ * precision is backtracked past an earlier call to the insn that unwound.
+ */
+static __used __naked __noinline __u64 plain_frame(void)
+{
+ asm volatile (
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+SEC("?cgroup/skb")
+__success
+__naked int entry_unwind_to_checked_exit(void)
+{
+ asm volatile (
+ "call plain_frame;"
+ "call always_unwind;"
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * The same two calls, never taken. Neither subprog is entered, so both go
+ * whole. Keeping an exit of always_unwind would leave one dead run over
+ * plain_frame and the head of always_unwind, and the subprog starts worked
+ * out after removing it would hand main's exit to always_unwind.
+ */
+SEC("?syscall")
+__success __retval(0)
+__naked int entry_unwinder_never_entered(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "if r1 == 0 goto 1f;"
+ "call plain_frame;"
+ "call always_unwind;"
+"1:" "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+/*
+ * Like entry_unwind_to_checked_exit(), out of a global call, which r6 = 0
+ * keeps from being the state's first insn, where backtracking would stop.
+ * The verifier_bug_if() this guards against only logs, so the level 2 log
+ * is checked.
+ */
+__noinline int global_always_unwind(void)
+{
+ bpf_unwind();
+ return 0;
+}
+
+SEC("?cgroup/skb")
+__success __log_level(2) __not_msg("verifier bug")
+__naked int entry_global_unwind_to_checked_exit(void)
+{
+ asm volatile (
+ "r6 = 0;"
+ "call global_always_unwind;"
+ "r0 = 1;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c b/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c
new file mode 100644
index 0000000000000..9fbc06d0bec4f
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * Tracing programs aimed at foo1() of progs/exceptions_cleanup.c, a subprog
+ * an unwind passes through. The attach target is set at load time.
+ */
+SEC("?fexit")
+int BPF_PROG(fexit_unwinding_subprog)
+{
+ return 0;
+}
+
+int fentry_hits;
+
+SEC("?fentry")
+int BPF_PROG(fentry_unwinding_subprog)
+{
+ fentry_hits++;
+ return 0;
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/test_loader.c b/tools/testing/selftests/bpf/test_loader.c
index 18d47e9254007..06a01a967b33e 100644
--- a/tools/testing/selftests/bpf/test_loader.c
+++ b/tools/testing/selftests/bpf/test_loader.c
@@ -50,6 +50,13 @@ enum stack_mode {
SMALL_STACK = 1 << 1,
};
+#define MAX_GLOBAL_VARS 8
+
+struct global_var {
+ char *name;
+ __u64 val;
+};
+
struct test_subspec {
char *name;
char *description;
@@ -62,6 +69,10 @@ struct test_subspec {
int retval;
bool execute;
__u64 caps;
+ struct global_var set_globals[MAX_GLOBAL_VARS];
+ int set_global_cnt;
+ struct global_var ret_globals[MAX_GLOBAL_VARS];
+ int ret_global_cnt;
};
struct test_spec {
@@ -115,6 +126,34 @@ void free_msgs(struct expected_msgs *msgs)
msgs->cnt = 0;
}
+static void free_global_vars(struct global_var *vars, int *cnt)
+{
+ int i;
+
+ for (i = 0; i < *cnt; i++) {
+ free(vars[i].name);
+ vars[i].name = NULL;
+ }
+ *cnt = 0;
+}
+
+static int clone_global_vars(struct global_var *dst, int *dst_cnt,
+ const struct global_var *src, int src_cnt)
+{
+ int i;
+
+ for (i = 0; i < src_cnt; i++) {
+ dst[i].name = strdup(src[i].name);
+ if (!dst[i].name) {
+ free_global_vars(dst, dst_cnt);
+ return -ENOMEM;
+ }
+ dst[i].val = src[i].val;
+ (*dst_cnt)++;
+ }
+ return 0;
+}
+
static void free_test_spec(struct test_spec *spec)
{
/* Deallocate expect_msgs arrays. */
@@ -129,6 +168,11 @@ static void free_test_spec(struct test_spec *spec)
free_msgs(&spec->unpriv.stdout);
free_msgs(&spec->priv.stdout);
+ free_global_vars(spec->priv.set_globals, &spec->priv.set_global_cnt);
+ free_global_vars(spec->priv.ret_globals, &spec->priv.ret_global_cnt);
+ free_global_vars(spec->unpriv.set_globals, &spec->unpriv.set_global_cnt);
+ free_global_vars(spec->unpriv.ret_globals, &spec->unpriv.ret_global_cnt);
+
free(spec->priv.name);
free(spec->priv.description);
free(spec->unpriv.name);
@@ -311,6 +355,236 @@ static int parse_caps(const char *str, __u64 *val, const char *name)
return 0;
}
+static int parse_global_var(const char *str, struct global_var *vars, int *cnt,
+ const char *name)
+{
+ const char *colon = strrchr(str, ':');
+ struct global_var *var;
+ char *end;
+ __u64 *val;
+
+ if (!colon || colon == str) {
+ PRINT_FAIL("expecting '<variable>:<value>' for %s, got '%s'\n", name, str);
+ return -EINVAL;
+ }
+ if (*cnt >= MAX_GLOBAL_VARS) {
+ PRINT_FAIL("too many %s tags, at most %d are supported\n",
+ name, MAX_GLOBAL_VARS);
+ return -E2BIG;
+ }
+
+ var = &vars[*cnt];
+ val = &var->val;
+ *val = 0;
+ for (const char *term = colon + 1;;) {
+ __u64 v;
+
+ errno = 0;
+ v = strtoull(term, &end, 0);
+ if (errno || end == term) {
+ PRINT_FAIL("failed to parse %s value '%s'\n", name, colon + 1);
+ return -EINVAL;
+ }
+ *val |= v;
+ while (*end == ' ')
+ end++;
+ if (!*end)
+ break;
+ if (*end != '|') {
+ PRINT_FAIL("failed to parse %s value '%s'\n", name, colon + 1);
+ return -EINVAL;
+ }
+ term = end + 1;
+ }
+
+ var->name = strndup(str, colon - str);
+ if (!var->name) {
+ PRINT_FAIL("failed to allocate %s variable name\n", name);
+ return -ENOMEM;
+ }
+ (*cnt)++;
+
+ return 0;
+}
+
+/* As veristat's is_signed_type(): anything not plainly unsigned is signed. */
+static bool global_var_is_signed(const struct btf_type *t)
+{
+ if (btf_is_int(t))
+ return btf_int_encoding(t) & BTF_INT_SIGNED;
+ if (btf_is_any_enum(t))
+ return btf_kflag(t);
+ return true;
+}
+
+static int find_global_var(struct bpf_object *obj, const char *name,
+ struct bpf_map **map, __u32 *off, __u32 *sz,
+ bool *is_signed)
+{
+ static const char * const secs[] = { ".bss", ".data" };
+ struct btf *btf = bpf_object__btf(obj);
+ int i, s;
+
+ if (!btf) {
+ PRINT_FAIL("no BTF for object\n");
+ return -ENOENT;
+ }
+
+ for (s = 0; s < ARRAY_SIZE(secs); s++) {
+ const struct btf_type *sec, *vt;
+ const struct btf_var_secinfo *vsi;
+ struct bpf_map *m = bpf_object__find_map_by_name(obj, secs[s]);
+ int id;
+
+ id = btf__find_by_name_kind(btf, secs[s], BTF_KIND_DATASEC);
+ if (!m || id < 0)
+ continue;
+
+ sec = btf__type_by_id(btf, id);
+ vsi = btf_var_secinfos(sec);
+ for (i = 0; i < btf_vlen(sec); i++, vsi++) {
+ const struct btf_type *var = btf__type_by_id(btf, vsi->type);
+
+ if (strcmp(btf__name_by_offset(btf, var->name_off), name))
+ continue;
+ if (vsi->size != 4 && vsi->size != 8) {
+ PRINT_FAIL("'%s' is %u bytes, only 4 and 8 are supported\n",
+ name, vsi->size);
+ return -EINVAL;
+ }
+ vt = btf__type_by_id(btf, btf__resolve_type(btf, var->type));
+ if (!vt || !(btf_is_int(vt) || btf_is_any_enum(vt))) {
+ PRINT_FAIL("'%s' is not an int or an enum\n", name);
+ return -EINVAL;
+ }
+ *is_signed = global_var_is_signed(vt);
+ *map = m;
+ *off = vsi->offset;
+ *sz = vsi->size;
+ return 0;
+ }
+ }
+
+ PRINT_FAIL("no global variable '%s'\n", name);
+ return -ENOENT;
+}
+
+/*
+ * A tag's value is parsed as 64 bits, but the variable may be narrower and
+ * may be signed. Hold it to the range the variable can represent, the way
+ * veristat's set_global_var() does, and narrow it to what is stored.
+ */
+static int fit_global_var(const char *name, __u32 sz, bool is_signed, __u64 *val)
+{
+ long long v = (long long)*val;
+ long long max_val;
+ __u32 bits;
+
+ if (sz >= sizeof(*val))
+ return 0;
+ bits = sz * 8 - (is_signed ? 1 : 0);
+ max_val = 1ll << bits;
+ if (v >= max_val || v < (is_signed ? -max_val : 0)) {
+ PRINT_FAIL("value %lld for '%s' is out of range [%lld; %lld]\n",
+ v, name, is_signed ? -max_val : 0, max_val - 1);
+ return -EINVAL;
+ }
+ *val = (__u32)*val;
+ return 0;
+}
+
+/* The value of @map's single element, which the caller frees. */
+static void *global_data(struct bpf_map *map, const char *name, size_t *vsz)
+{
+ __u32 zero = 0;
+ void *buf;
+ int err;
+
+ *vsz = bpf_map__value_size(map);
+ buf = calloc(1, *vsz);
+ if (!buf) {
+ PRINT_FAIL("failed to allocate %zu bytes for '%s'\n", *vsz, name);
+ return NULL;
+ }
+ err = bpf_map__lookup_elem(map, &zero, sizeof(zero), buf, *vsz, 0);
+ if (err) {
+ PRINT_FAIL("failed to read '%s': %d\n", name, err);
+ free(buf);
+ return NULL;
+ }
+ return buf;
+}
+
+static int read_global_var(struct bpf_map *map, const char *name, __u32 off,
+ __u32 sz, __u64 *val)
+{
+ size_t vsz;
+ void *buf;
+
+ buf = global_data(map, name, &vsz);
+ if (!buf)
+ return -EINVAL;
+ *val = sz == 4 ? *(__u32 *)(buf + off) : *(__u64 *)(buf + off);
+ free(buf);
+ return 0;
+}
+
+static int write_global_var(struct bpf_map *map, const char *name, __u32 off,
+ __u32 sz, __u64 val)
+{
+ __u32 zero = 0;
+ size_t vsz;
+ void *buf;
+ int err;
+
+ buf = global_data(map, name, &vsz);
+ if (!buf)
+ return -EINVAL;
+ if (sz == 4)
+ *(__u32 *)(buf + off) = val;
+ else
+ *(__u64 *)(buf + off) = val;
+ err = bpf_map__update_elem(map, &zero, sizeof(zero), buf, vsz, 0);
+ if (err)
+ PRINT_FAIL("failed to write '%s': %d\n", name, err);
+ free(buf);
+ return err;
+}
+
+/* Write a __set_global() value into the program's global variable. */
+static int set_global_var(struct bpf_object *obj, const struct global_var *var)
+{
+ __u64 val = var->val;
+ struct bpf_map *map;
+ __u32 off, sz;
+ bool is_signed;
+
+ if (find_global_var(obj, var->name, &map, &off, &sz, &is_signed) ||
+ fit_global_var(var->name, sz, is_signed, &val))
+ return -EINVAL;
+ return write_global_var(map, var->name, off, sz, val);
+}
+
+/* Check the program's global variable against a __ret_global() value. */
+static int check_global_var(struct bpf_object *obj, const struct global_var *var)
+{
+ __u64 want = var->val, val;
+ struct bpf_map *map;
+ __u32 off, sz;
+ bool is_signed;
+
+ if (find_global_var(obj, var->name, &map, &off, &sz, &is_signed) ||
+ fit_global_var(var->name, sz, is_signed, &want) ||
+ read_global_var(map, var->name, off, sz, &val))
+ return -EINVAL;
+ if (val != want) {
+ PRINT_FAIL("Unexpected %s: 0x%llx != 0x%llx\n", var->name,
+ (unsigned long long)val, (unsigned long long)want);
+ return -EINVAL;
+ }
+ return 0;
+}
+
static int parse_retval(const char *str, int *val, const char *name)
{
/*
@@ -567,6 +841,22 @@ static int parse_test_spec(struct test_loader *tester,
spec->mode_mask |= UNPRIV;
spec->unpriv.execute = true;
has_unpriv_retval = true;
+ } else if ((val = str_has_pfx(s, "test_global_set="))) {
+ err = parse_global_var(val, spec->priv.set_globals,
+ &spec->priv.set_global_cnt,
+ "__set_global");
+ if (err)
+ goto cleanup;
+ spec->priv.execute = true;
+ spec->mode_mask |= PRIV;
+ } else if ((val = str_has_pfx(s, "test_global_ret="))) {
+ err = parse_global_var(val, spec->priv.ret_globals,
+ &spec->priv.ret_global_cnt,
+ "__ret_global");
+ if (err)
+ goto cleanup;
+ spec->priv.execute = true;
+ spec->mode_mask |= PRIV;
} else if ((val = str_has_pfx(s, "test_log_level="))) {
err = parse_int(val, &spec->log_level, "test log level");
if (err)
@@ -754,6 +1044,23 @@ static int parse_test_spec(struct test_loader *tester,
spec->unpriv.execute = spec->priv.execute;
}
+ if (spec->priv.set_global_cnt && !spec->unpriv.set_global_cnt) {
+ err = clone_global_vars(spec->unpriv.set_globals,
+ &spec->unpriv.set_global_cnt,
+ spec->priv.set_globals,
+ spec->priv.set_global_cnt);
+ if (err)
+ goto cleanup;
+ }
+ if (spec->priv.ret_global_cnt && !spec->unpriv.ret_global_cnt) {
+ err = clone_global_vars(spec->unpriv.ret_globals,
+ &spec->unpriv.ret_global_cnt,
+ spec->priv.ret_globals,
+ spec->priv.ret_global_cnt);
+ if (err)
+ goto cleanup;
+ }
+
if (spec->unpriv.expect_msgs.cnt == 0)
clone_msgs(&spec->priv.expect_msgs, &spec->unpriv.expect_msgs);
if (spec->unpriv.expect_xlated.cnt == 0)
@@ -1369,7 +1676,7 @@ void run_subtest(struct test_loader *tester,
struct cap_state caps = {};
struct bpf_object *tobj;
struct bpf_map *map;
- int retval, err, i;
+ int retval, err, i, j;
int links_cnt = 0;
bool should_load;
@@ -1545,6 +1852,11 @@ void run_subtest(struct test_loader *tester,
}
}
+ for (j = 0; j < subspec->set_global_cnt; j++) {
+ if (set_global_var(tobj, &subspec->set_globals[j]))
+ goto tobj_cleanup;
+ }
+
err = do_prog_test_run(bpf_program__fd(tprog), &retval,
bpf_program__type(tprog) == BPF_PROG_TYPE_SYSCALL ? true : false,
spec->linear_sz);
@@ -1553,6 +1865,11 @@ void run_subtest(struct test_loader *tester,
goto tobj_cleanup;
}
+ for (j = 0; !err && j < subspec->ret_global_cnt; j++) {
+ if (check_global_var(tobj, &subspec->ret_globals[j]))
+ goto tobj_cleanup;
+ }
+
verify_stderr(bpf_program__fd(tprog), &subspec->stderr);
if (subspec->stdout.cnt) {
|
| 17/3 | 2026/10/17 07:55 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 73352 output: 29 thoughts: 1006 Thoughts: **KMSAN Fuzzing Session Justification: BPF Exception Cleanup Patch** Okay, let's determine if this patch necessitates a KMSAN fuzzing session. It looks like we're dealing with BPF exception cleanup landing pads for amd64, which is interesting. We're looking at functions like `bpf_unwind()`, `bpf_unwind_resume()`, and related structures like `struct bpf_cleanup_info`. The affected files are extensive, touching everything from architecture-specific code (arm64, x86) to the core BPF infrastructure (`kernel/bpf/*`). Now, the crucial distinction between KASAN and KMSAN is what matters here. We already run KASAN, LOCKDEP, and UBSAN in our standard builds. KMSAN is specifically about catching reads of *uninitialized* memory, both within the kernel and especially any kernel-to-user info leaks. The rule is clear: If a bug is likely to be caught by KASAN or other standard detectors, KMSAN is overkill. We need KMSAN if the patch introduces or modifies: kernel structures sent to user space (where uninitialized fields could be read by userspace), conditional logic based on potentially uninitialized variables, allocation of complex structures with possible uninitialized fields, or potentially uninitialized bytes of existing buffers. Now, let's dig into the specifics. I see in `kernel/bpf/syscall.c` that the `BPF_PROG_LOAD_LAST_FIELD` was changed to `cleanup_info_cnt`. More importantly, the `union bpf_attr` is being copied *from* user space. This is a potential area of concern. Specifically, the following members are now present: `cleanup_info`, `cleanup_info_rec_size`, and `cleanup_info_cnt`. The question is: does any BPF syscall return `cleanup_info` or related structures (e.g. via `bpf_prog_get_info_by_fd`) to user space? If data is copied *from* the kernel *to* user space, uninitialized memory could be leaked. That's a classic KMSAN scenario. I'll need to grep for `cleanup_info` in the kernel to confirm if anything is copied out. If we are copying the contents of `union bpf_attr` to user space without full initialization, then we have a clear KMSAN concern. Otherwise, if the stack/heap structures touched or introduced by the patch are fully zeroed or initialized, then the patch is likely not a concern for KMSAN. |
| 18/3 | 2026/10/17 07:55 | tool | grepper |
0mArgs:{
"Expression": "cleanup_info",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/cfg.c=173=static int visit_cleanup_pad_edge(int t, struct bpf_verifier_env *env)\n--\nkernel/bpf/cfg.c-178-\nkernel/bpf/cfg.c:179:\tif (!env-\u003ecleanup_info_cnt)\nkernel/bpf/cfg.c-180-\t\treturn DONE_EXPLORING;\n--\nkernel/bpf/exception.c=15=int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,\n--\nkernel/bpf/exception.c-17-{\nkernel/bpf/exception.c:18:\tu32 krec_size = sizeof(struct bpf_cleanup_info);\nkernel/bpf/exception.c-19-\tu32 i, nrec, urec_size, min_size, prev_end = 0;\nkernel/bpf/exception.c:20:\tstruct bpf_cleanup_info *krecord;\nkernel/bpf/exception.c-21-\tbpfptr_t urecord;\n--\nkernel/bpf/exception.c-23-\nkernel/bpf/exception.c:24:\tnrec = attr-\u003ecleanup_info_cnt;\nkernel/bpf/exception.c-25-\tif (!nrec)\n--\nkernel/bpf/exception.c-32-\nkernel/bpf/exception.c:33:\turec_size = attr-\u003ecleanup_info_rec_size;\nkernel/bpf/exception.c-34-\tif (urec_size \u003c MIN_BPF_CLEANUP_INFO_SIZE ||\n--\nkernel/bpf/exception.c-45-\tmin_size = min_t(u32, krec_size, urec_size);\nkernel/bpf/exception.c:46:\turecord = make_bpfptr(attr-\u003ecleanup_info, uattr.is_kernel);\nkernel/bpf/exception.c-47-\tfor (i = 0; i \u003c nrec; i++) {\nkernel/bpf/exception.c-48-\t\tstruct bpf_subprog_info *sb, *se, *sl;\nkernel/bpf/exception.c:49:\t\tstruct bpf_cleanup_info *rec = \u0026krecord[i];\nkernel/bpf/exception.c-50-\n--\nkernel/bpf/exception.c-71-\t\tif (rec-\u003ebegin_off \u003e= rec-\u003eend_off) {\nkernel/bpf/exception.c:72:\t\t\tverbose(env, \"cleanup_info[%u]: begin %u \u003e= end %u\\n\",\nkernel/bpf/exception.c-73-\t\t\t\ti, rec-\u003ebegin_off, rec-\u003eend_off);\n--\nkernel/bpf/exception.c-77-\t\t\tverbose(env,\nkernel/bpf/exception.c:78:\t\t\t\t\"cleanup_info[%u]: range [%u,%u) is unsorted or overlaps the previous record\\n\",\nkernel/bpf/exception.c-79-\t\t\t\ti, rec-\u003ebegin_off, rec-\u003eend_off);\n--\nkernel/bpf/exception.c-87-\t\tif (!sb || !se || !sl) {\nkernel/bpf/exception.c:88:\t\t\tverbose(env, \"cleanup_info[%u]: offset out of range\\n\", i);\nkernel/bpf/exception.c-89-\t\t\tgoto err_free;\n--\nkernel/bpf/exception.c-92-\t\t\tverbose(env,\nkernel/bpf/exception.c:93:\t\t\t\t\"cleanup_info[%u]: range/landing pad span multiple subprogs\\n\",\nkernel/bpf/exception.c-94-\t\t\t\ti);\n--\nkernel/bpf/exception.c-104-\t\t !env-\u003eprog-\u003einsnsi[rec-\u003eend_off].code)) {\nkernel/bpf/exception.c:105:\t\t\tverbose(env, \"cleanup_info[%u]: points at invalid insn\\n\", i);\nkernel/bpf/exception.c-106-\t\t\tgoto err_free;\n--\nkernel/bpf/exception.c-124-\t\t\t\tverbose(env,\nkernel/bpf/exception.c:125:\t\t\t\t\t\"cleanup_info[%u]: landing pad %u is inside the call-site range of cleanup_info[%u]\\n\",\nkernel/bpf/exception.c-126-\t\t\t\t\ti, pad, m);\n--\nkernel/bpf/exception.c-131-\nkernel/bpf/exception.c:132:\tenv-\u003ecleanup_info = krecord;\nkernel/bpf/exception.c:133:\tenv-\u003ecleanup_info_cnt = nrec;\nkernel/bpf/exception.c-134-\treturn 0;\n--\nkernel/bpf/exception.c=168=void bpf_exc_mark_call_sites(struct bpf_verifier_env *env)\n--\nkernel/bpf/exception.c-171-\nkernel/bpf/exception.c:172:\tfor (i = 0; i \u003c env-\u003ecleanup_info_cnt; i++) {\nkernel/bpf/exception.c:173:\t\tstruct bpf_cleanup_info *rec = \u0026env-\u003ecleanup_info[i];\nkernel/bpf/exception.c-174-\n--\nkernel/bpf/exception.c=308=const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip)\n--\nkernel/bpf/exception.c-326-\nkernel/bpf/exception.c:327:int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt)\nkernel/bpf/exception.c-328-{\n--\nkernel/bpf/exception.c=350=void bpf_exc_fill_native_ranges(struct bpf_prog *prog, u32 *addrs, void *image)\n--\nkernel/bpf/exception.c-359-\tfor (i = 0; i \u003c n; i++) {\nkernel/bpf/exception.c:360:\t\tconst struct bpf_cleanup_info *rec = \u0026exc-\u003einfo[i];\nkernel/bpf/exception.c-361-\n--\nkernel/bpf/exception.h=11=struct bpf_insn;\nkernel/bpf/exception.h:12:struct bpf_cleanup_info;\nkernel/bpf/exception.h-13-struct bpf_cleanup_range;\n--\nkernel/bpf/exception.h=26=int bpf_exc_check_insn(struct bpf_verifier_env *env, struct bpf_insn *insn);\nkernel/bpf/exception.h:27:int bpf_exc_attach_info(struct bpf_prog_aux *aux, struct bpf_cleanup_info *recs, u32 cnt);\nkernel/bpf/exception.h-28-const struct bpf_cleanup_range *bpf_exc_pad_for_ip(const struct bpf_prog *prog, u64 ip);\n--\nkernel/bpf/fixups.c=203=static void adjust_insn_aux_data(struct bpf_verifier_env *env,\n--\nkernel/bpf/fixups.c-256-\nkernel/bpf/fixups.c:257:\tif (env-\u003ecleanup_info_cnt)\nkernel/bpf/fixups.c-258-\t\tfor (i = 0; i \u003c prog_len; i++)\n--\nkernel/bpf/fixups.c=612=static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)\n--\nkernel/bpf/fixups.c-647-\nkernel/bpf/fixups.c:648:\tif (env-\u003ecleanup_info_cnt) {\nkernel/bpf/fixups.c-649-\t\tfor (i = 0; i \u003c env-\u003einsn_aux_data_len; i++) {\n--\nkernel/bpf/fixups.c=808=int bpf_opt_remove_nops(struct bpf_verifier_env *env)\n--\nkernel/bpf/fixups.c-824-\nkernel/bpf/fixups.c:825:\t\tif (env-\u003ecleanup_info_cnt)\nkernel/bpf/fixups.c-826-\t\t\tfor (j = 0; j \u003c insn_cnt; j++)\n--\nkernel/bpf/fixups.c=1329=static int exc_info_for_subprog(struct bpf_verifier_env *env, struct bpf_prog *sub,\n--\nkernel/bpf/fixups.c-1331-{\nkernel/bpf/fixups.c:1332:\tstruct bpf_cleanup_info *recs;\nkernel/bpf/fixups.c-1333-\tu32 i, cnt = 0;\nkernel/bpf/fixups.c-1334-\nkernel/bpf/fixups.c:1335:\tif (!env-\u003ecleanup_info_cnt)\nkernel/bpf/fixups.c-1336-\t\treturn 0;\n--\nkernel/bpf/liveness.c=342=bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)\n--\nkernel/bpf/liveness.c-413-\t */\nkernel/bpf/liveness.c:414:\tif (unlikely(env-\u003ecleanup_info_cnt)) {\nkernel/bpf/liveness.c-415-\t\tint pad = bpf_exc_pad_of_call(env, idx);\n--\nkernel/bpf/liveness.c=541=bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_spi)\n--\nkernel/bpf/liveness.c-583-\nkernel/bpf/liveness.c:584:\t\tif (!alive \u0026\u0026 unlikely(env-\u003ecleanup_info_cnt)) {\nkernel/bpf/liveness.c-585-\t\t\tint pad = bpf_exc_pad_of_call(env, callsite);\n--\nkernel/bpf/syscall.c=2948=BTF_ID_LIST_GLOBAL_SINGLE(bpf_multi_func_btf_id, func, bpf_multi_func)\n--\nkernel/bpf/syscall.c-2950-/* last field in 'union bpf_attr' used by this command */\nkernel/bpf/syscall.c:2951:#define BPF_PROG_LOAD_LAST_FIELD cleanup_info_cnt\nkernel/bpf/syscall.c-2952-\n--\nkernel/bpf/verifier.c=6006=static int check_max_stack_depth(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-6032-\t */\nkernel/bpf/verifier.c:6033:\tif (env-\u003ecleanup_info_cnt || bpf_prog_may_unwind(env))\nkernel/bpf/verifier.c-6034-\t\tpriv_stack_mode = NO_PRIV_STACK;\n--\nkernel/bpf/verifier.c=20086=static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)\n--\nkernel/bpf/verifier.c-20091-\nkernel/bpf/verifier.c:20092:\tif (unlikely(env-\u003ecleanup_info_cnt)) {\nkernel/bpf/verifier.c-20093-\t\terr = bpf_exc_check_insn(env, insn);\n--\nkernel/bpf/verifier.c=23579=int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n--\nkernel/bpf/verifier.c-23777-\nkernel/bpf/verifier.c:23778:\tif (env-\u003ecleanup_info_cnt || bpf_prog_may_unwind(env)) {\nkernel/bpf/verifier.c-23779-\t\tret = bpf_exc_check_prog(env);\n--\nkernel/bpf/verifier.c-23994-\tkvfree(env-\u003eidoms);\nkernel/bpf/verifier.c:23995:\tkvfree(env-\u003ecleanup_info);\nkernel/bpf/verifier.c-23996-\tkvfree(env);\n"
} |
| 19/3 | 2026/10/17 07:55 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 78114 output: 38 thoughts: 107 Thoughts: **Analyzing the `bpf_prog_get_info_by_fd` Function** Okay, so the initial assumption is that the `bpf_prog_get_info_by_fd` function *hasn't* been updated to provide either `cleanup_info` or `struct bpf_cleanup_info` to userspace. That feels likely, but assumptions are dangerous, especially in kernel development, so let's verify. Let me check if the function actually touches or uses `cleanup_info`, or anything potentially related like `exc`. The quickest way to do this is a direct code search. I'll need to grep for instances of `bpf_prog_get_info_by_fd` within `kernel/bpf/syscall.c` and analyze the results. This will quickly confirm or refute the initial hunch. |
| 20/3 | 2026/10/17 07:55 | tool | grepper |
0mArgs:{
"Expression": "bpf_prog_get_info_by_fd",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/syscall.c=5113=static int set_info_rec_size(struct bpf_prog_info *info)\n--\nkernel/bpf/syscall.c-5143-\nkernel/bpf/syscall.c:5144:static int bpf_prog_get_info_by_fd(struct file *file,\nkernel/bpf/syscall.c-5145-\t\t\t\t struct bpf_prog *prog,\n--\nkernel/bpf/syscall.c=5580=static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,\n--\nkernel/bpf/syscall.c-5590-\tif (fd_file(f)-\u003ef_op == \u0026bpf_prog_fops)\nkernel/bpf/syscall.c:5591:\t\treturn bpf_prog_get_info_by_fd(fd_file(f), fd_file(f)-\u003eprivate_data, attr,\nkernel/bpf/syscall.c-5592-\t\t\t\t\t uattr);\n"
} |
| 21/3 | 2026/10/17 07:55 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 78710 output: 34 thoughts: 2877 Thoughts: **BPF Exception Handling Deep Dive: A Verifier's Perspective** Okay, so this diff isn't touching `bpf_prog_get_info_by_fd`, that's good. But I see the `BPF_PROG_LOAD_LAST_FIELD` update; it's changed from `keyring_id` to `cleanup_info_cnt`. This has to do with exception handling, right? Let's trace it through... The `bpf_exc_check_info` function is where the verification for the cleanup info happens. It looks like it validates the `cleanup_info_cnt` against the program length and makes sure the record size is sane. `kvcalloc` is used to allocate `krecord`. This ensures all the fields are zeroed. Then, the code *copies* `min_size` bytes from user space into `krecord`. Crucially, since `min_size` could be smaller than the struct, any tailing bytes will remain zero, this could be important later. Now, on to `exc_info_for_subprog`. This is building the exception info for subprograms. It iterates through the instructions looking for `cleanup_pad` flags (set by the compiler during JIT), which represent landing pads. If it finds any, it allocates `recs` (using `kvmalloc_array`) and populates `begin_off`, `end_off`, and `landing_pad_off` fields. Notice these are all initialized! This information is then passed to `bpf_exc_attach_info`. Inside `bpf_exc_attach_info`, `kzalloc_obj` is used to allocate `exc`, which is zeroed, and `kvcalloc` is used for `ranges`. The zero initialization of the ranges is important here. Alright, so the zeroed exception info is being constructed. Time to look into JIT and stack unwinding/execution, to see how that influences the verifier. The code then examines the stack walking on x86, using `arch_bpf_stack_walk_ra` to walk the stack frames. This is done to unwind and is key to exception handling. The unwinding rewrites the return addresses for landing pads. `bpf_unwind_rewrite` is the callback function called by the arch-specific stack walk. This is where it identifies the relevant BPF subprogram. The important point is in the `bpf_unwind_rewrite` function. The code determines the landing pad to jump to based on `bpf_exc_pad_for_ip` which gives us the instruction offset of the landing pad. It also uses the aux data to find the `epilogue_ip` for a return. On a landing pad, `bpf_unwind()` is called with `aux`, which is provided by the verifier during program loading. This is where things are tricky, let's now look at the stack frames to see what is happening to the registers. When unwinding frames, the code uses `destroy_dynptrs_in_stack_slots`. After this call, `free_func_state(callee)` is called, the current frame is deallocated, and the code returns to the `pad`. During the unwind process, `clear_caller_saved_regs` is called, which marks the caller-saved registers as uninitialized. Then, it explicitly marks R0 as zero. This seems like a critical point where the verifier is ensuring a consistent state. |
| 22/3 | 2026/10/17 07:55 | tool | grepper |
0mArgs:{
"Expression": "void clear_caller_saved_regs",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/verifier.c=11031=static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)\n--\nkernel/bpf/verifier.c-11056-\nkernel/bpf/verifier.c:11057:static void clear_caller_saved_regs(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-11058-\t\t\t\t struct bpf_reg_state *regs)\n"
} |
| 23/3 | 2026/10/17 07:55 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 82509 output: 38 thoughts: 13 Thoughts: Okay, let's dive into this. Here's my take on those thoughts, as if they're my own: **Analyzing the `clear_caller_saved_regs` Function** Alright, let's get into the weeds of this `clear_caller_saved_regs` function. My initial thought is to understand its purpose within the broader context of whatever system it's operating in. Given the naming convention, it's pretty clear we're dealing with register management, specifically the preservation and restoration of caller-saved registers. I need to figure out exactly *how* it's clearing them. Is it zeroing them out? Writing specific "magic" values? Or are we dealing with a more subtle approach, perhaps utilizing a dedicated register clearing instruction (if such a thing exists in this architecture)? My immediate focus is likely going to be: * **The Architecture:** What architecture are we working with? x86, ARM, RISC-V, something more exotic? That drastically impacts the specific registers involved and the potential clearing methods. * **The Calling Convention:** How does this relate to the established calling convention? Is it part of the standard ABI? Or some custom, project-specific adaptation? This will influence what's considered "caller-saved" and what needs to be managed. * **Scope:** Is this being called at the entry point of a function, a trap handler, or somewhere else? The scope of its usage will give context. Once I have those basic fundamentals answered, I'll move into the code itself, looking for the specific instructions. I'll want to trace any potential side effects. Is it optimizing for speed, safety, or space? I need to understand any assumptions about register usage this function might make. And, of course, I'll be keeping an eye out for any potential vulnerabilities or race conditions in its implementation. |
| 24/3 | 2026/10/17 07:56 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 11055,
"LineCount": 20
}Results: {
"Contents": "11055:\t}\n11056:\t\n11057:\tstatic void clear_caller_saved_regs(struct bpf_verifier_env *env,\n11058:\t\t\t\t\t struct bpf_reg_state *regs)\n11059:\t{\n11060:\t\tint i;\n11061:\t\n11062:\t\tbpf_diag_record_caller_saved(env, regs);\n11063:\t\n11064:\t\t/* after the call registers r0 - r5 were scratched */\n11065:\t\tfor (i = 0; i \u003c CALLER_SAVED_REGS; i++) {\n11066:\t\t\tbpf_mark_reg_not_init(env, \u0026regs[caller_saved[i]]);\n11067:\t\t\t__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);\n11068:\t\t}\n11069:\t}\n11070:\t\n11071:\tstatic void invalidate_outgoing_stack_args(struct bpf_verifier_env *env,\n11072:\t\t\t\t\t\t struct bpf_func_state *state)\n11073:\t{\n11074:\t\tint i, nslots = state-\u003eout_stack_arg_cnt;\n"
} |
| 25/3 | 2026/10/17 07:56 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 83311 output: 36 thoughts: 4102 Thoughts: **KMSAN Audit of BPF Stack Unwinding Patch** Alright, let's break this down. My primary concern here is preventing any potential kernel memory leaks or uninitialized memory reads, especially in the context of BPF and the introduction of stack unwinding. Given my expertise, I need to methodically check this patch against the KMSAN criteria. My first thought is: Did I miss anything? The initial check involving `clear_caller_saved_regs` followed by `mark_reg_unknown` did raise a red flag. Could this allow uninitialized memory reads in the kernel? I remember KMSAN's purpose, explicitly detecting reads of UNINITIALIZED memory. I quickly realize we are dealing with simulated registers in the BPF VM which map to x86 CPU registers. The key is that KMSAN doesn't directly instrument JITed BPF code. However, it does track kernel memory allocations and stack frames. The crucial guideline from the documentation stands out: If KASAN, LOCKDEP, or standard bug detectors catch it, KMSAN is overkill. KMSAN fuzzing incurs resource costs, so use it judiciously. Only if the code introduces or exposes uninitialized memory risks that ONLY KMSAN detects is it appropriate. The four critical conditions for `NeedsKMSAN=true` are then the focus of my attention: kernel structures sent to user space (potential info leaks), conditional logic depending on uninitialized variables, allocation of complex data structures with uninitialized fields, and bounds checks that expose uninitialized buffer bytes. Let's look at each code section: 1. **`arch/arm64/kernel/stacktrace.c`**: In the `bpf_unwind_ra_consume_entry_data` struct the C99 designated initializer zeroes `record` and `seen_first`. This also applies to `arch_bpf_stack_walk_ra`. Thus, the concerns I had were alleviated, and the code looks safe. Furthermore, this code is targeted to amd64, not arm64, but even in that instance, the data is properly initialized. 2. **`arch/x86/net/bpf_jit_comp.c`**: Here, `unwind_start(&state, current, NULL, NULL)` explicitly initializes `unwind_state`. The following code then reads the state and consumes the return address. The code passes the checks. 3. **`kernel/bpf/helpers.c`**: In this section, `ctx` (a `bpf_unwind_ctx` struct) is initialized via a designated initializer, so the field `ctx.cnt` will be set to 0. Inside `bpf_unwind_rewrite`, `prog` and `rec` are checked before use and `*ra` is written with initialized values (`rec->pad` or `prog->aux->epilogue_ip`). No concerns. 4. **`kernel/bpf/exception.c`**: This is a critical section for KMSAN. I need to check all functions. The first thing I note is that allocations use `kvcalloc` and `kzalloc_obj`, which guarantee zero-initialization. `bpf_check_uarg_tail_zero` checks trailing user bytes. `copy_from_bpfptr` copies `min_size` bytes into a new region. The code uses binary search for range rejections. I check `might_unwind`, instruction throw checks, iteration, and checks for offloaded, JIT, epilogue, callback. All allocations are zeroed or the data is populated via copy. I make sure to check `bpf_exc_pad_of_call` and `bpf_exc_pad_for_ip` reads via binary search and that `exc` and `ranges` are zero allocated. All good here. 5. **`kernel/bpf/fixups.c`**: `patch`, `insn_buf`, and `recs` are all explicitly initialized. No issues. This also applies to `bpf_do_misc_fixups`, `insn_buf`, and `cnt` are assigned. 6. **`kernel/bpf/verifier.c`**: `patch` in `add_exits_after_final_calls` is initialized. Also, `bpf_jmp_history_entry` is initialized by `bpf_push_jmp_history`. The fields are initialized when pushed. This is safe. The fields in the struct were also scrutinized, and it seems like padding size was changed in a commit to the flags. Finally, I do a scan for any data copies to user space. There are none. There's no use of `copy_to_user`, `put_user`, or anything of the sort. I have |
| 26/3 | 2026/10/17 07:56 | tool | grepper |
0mArgs:{
"Expression": "kzalloc.*struct bpf_func_state",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/verifier.c=21623=static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_sleepable)\n--\nkernel/bpf/verifier.c-21643-\tstate-\u003ein_sleepable = is_sleepable;\nkernel/bpf/verifier.c:21644:\tstate-\u003eframe[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);\nkernel/bpf/verifier.c-21645-\tif (!state-\u003eframe[0]) {\n"
} |
| 27/3 | 2026/10/17 07:56 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 88630 output: 31 thoughts: 30 Thoughts: Here's my summary, as though I'm thinking through this process: **Reviewing BPF Function State Initialization** Okay, so `kzalloc_obj` is responsible for zeroing out the `bpf_func_state` structure. That's good, a known starting point. Makes sense for memory allocation. But, I should probably double-check that `copy_func_state` doesn't inadvertently bypass this zeroing. It's crucial to ensure that any function state copy operation also accounts for a clean, initialized copy of the memory region. No point in zeroing during allocation if the copy operation introduces uninitialized values later. Let's make sure that's handled correctly as well. Gotta be rigorous about this, particularly with BPF; a small oversight can have big implications. |
| 28/3 | 2026/10/17 07:56 | tool | grepper |
0mArgs:{
"Expression": "copy_func_state",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/verifier.c=1698=void bpf_free_verifier_state(struct bpf_verifier_state *state,\n--\nkernel/bpf/verifier.c-1715- */\nkernel/bpf/verifier.c:1716:static int copy_func_state(struct bpf_func_state *dst,\nkernel/bpf/verifier.c-1717-\t\t\t const struct bpf_func_state *src)\n--\nkernel/bpf/verifier.c=1729=int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,\n--\nkernel/bpf/verifier.c-1771-\t\t}\nkernel/bpf/verifier.c:1772:\t\terr = copy_func_state(dst, src-\u003eframe[i]);\nkernel/bpf/verifier.c-1773-\t\tif (err)\n"
} |
| 29/3 | 2026/10/17 07:56 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 89096 output: 37 thoughts: 33 Thoughts: Here's my take on the thought process, summarized as you requested: **Deconstructing `copy_func_state`** Alright, I need to get into the weeds of this function, `copy_func_state`. I suspect there's a key detail lurking here about how it handles padding, specifically `in_pad`. The crucial question is: is the padding value actually being copied, or is this function taking the shortcut of just using the simpler `*dst = *src` approach? That could have significant implications down the line, depending on how this state is used. I need to dig into the implementation to be absolutely sure. Let's see what the code reveals. |
| 30/3 | 2026/10/17 07:56 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 1715,
"LineCount": 25
}Results: {
"Contents": "1715:\t */\n1716:\tstatic int copy_func_state(struct bpf_func_state *dst,\n1717:\t\t\t\t const struct bpf_func_state *src)\n1718:\t{\n1719:\t\tmemcpy(dst, src, offsetof(struct bpf_func_state, stack));\n1720:\t\t/* Instruction accounting is path-local, not part of verifier state. */\n1721:\t\tdst-\u003einsns_subtotal = 0;\n1722:\t\tdst-\u003eloop_stack = copy_array(dst-\u003eloop_stack, src-\u003eloop_stack, src-\u003eloop_stack_cnt,\n1723:\t\t\t\t\t sizeof(*src-\u003eloop_stack), GFP_KERNEL_ACCOUNT);\n1724:\t\tif (!dst-\u003eloop_stack)\n1725:\t\t\treturn -ENOMEM;\n1726:\t\treturn copy_stack_state(dst, src);\n1727:\t}\n1728:\t\n1729:\tint bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,\n1730:\t\t\t\t const struct bpf_verifier_state *src)\n1731:\t{\n1732:\t\tstruct bpf_func_state *dst;\n1733:\t\tint i, err;\n1734:\t\n1735:\t\tdst_state-\u003ejmp_history = copy_array(dst_state-\u003ejmp_history, src-\u003ejmp_history,\n1736:\t\t\t\t\t\t src-\u003ejmp_history_cnt, sizeof(*dst_state-\u003ejmp_history),\n1737:\t\t\t\t\t\t GFP_KERNEL_ACCOUNT);\n1738:\t\tif (!dst_state-\u003ejmp_history)\n1739:\t\t\treturn -ENOMEM;\n"
} |
| 31/3 | 2026/10/17 07:56 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 89764 output: 38 thoughts: 63 Thoughts: Okay, here's my take on those thoughts, framed as my own mental processing: **Analyzing a `memcpy` and Data Structure Layout** Right, so that `memcpy` call... it's clearly copying data from `src` to `dst`, but the `offsetof` is the interesting part. `memcpy(dst, src, offsetof(struct bpf_func_state, stack));` That's telling me to copy everything *before* the `stack` member of `struct bpf_func_state`. It's a classic technique for partial copying based on structure layout, and a little inefficient but often the right tool for a job. I need to understand what's actually being copied, and therefore what's *not* being copied. I need to remind myself of the structure. Now, where exactly is that `in_pad` field defined relative to `stack` in `struct bpf_func_state`? I'm pretty sure I recall it being a padding element. Need to double-check `include/linux/bpf_verifier.h`. Gotta clarify exactly what data is being moved, or left behind, to understand its implications for performance or, more critically, correctness. Knowing the structure member layout is key to understanding the intent of the programmer. Time to dig into the header file. |
| 32/3 | 2026/10/17 07:56 | tool | read-file |
0mArgs:{
"File": "include/linux/bpf_verifier.h",
"FirstLine": 370,
"LineCount": 30
}Results: {
"Contents": " 370:\t\tu32 subprogno;\n 371:\t\t/* Every bpf_timer_start will increment async_entry_cnt.\n 372:\t\t * It's used to distinguish:\n 373:\t\t * void foo(void) { for(;;); }\n 374:\t\t * void foo(void) { bpf_timer_set_callback(,foo); }\n 375:\t\t */\n 376:\t\tu32 async_entry_cnt;\n 377:\t\tstruct bpf_retval_range callback_ret_range;\n 378:\t\tbool in_callback_fn;\n 379:\t\tbool in_async_callback_fn;\n 380:\t\tbool in_exception_callback_fn;\n 381:\t\tbool no_stack_arg_load;\n 382:\t\tbool in_pad;\n 383:\t\t/* For callback calling functions that limit number of possible\n 384:\t\t * callback executions (e.g. bpf_loop) keeps track of current\n 385:\t\t * simulated iteration number.\n 386:\t\t * Value in frame N refers to number of times callback with frame\n 387:\t\t * N+1 was simulated, e.g. for the following call:\n 388:\t\t *\n 389:\t\t * bpf_loop(..., fn, ...); | suppose current frame is N\n 390:\t\t * | fn would be simulated in frame N+1\n 391:\t\t * | number of simulations is tracked in frame N\n 392:\t\t */\n 393:\t\tu32 callback_depth;\n 394:\t\t/* Instructions processed in this frame and callees on the current path. */\n 395:\t\tu32 insns_subtotal;\n 396:\t\t/*\n 397:\t\t * Control-flow loop nesting at the current insn within this frame's\n 398:\t\t * subprogram (loops never cross subprogram boundaries).\n 399:\t\t */\n"
} |
| 33/3 | 2026/10/17 07:56 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 90655 output: 36 thoughts: 167 Thoughts: **Analyzing BPF Program Auxiliary Data** Okay, so `in_pad` is at line 382. That's significantly earlier than where the `stack` is defined, which comes after registers and stack slots. This means `in_pad` is almost certainly copied using `memcpy`. That seems pretty straightforward. Now, I need to understand more about `bpf_prog_aux`. I remember seeing that struct defined in `include/linux/bpf.h`. Let me take a look at the definition... Yes, I see `might_sleep`, `might_unwind`... and crucially, `struct bpf_exception_info *exc` and `u64 epilogue_ip`. The next key question is *where* is `struct bpf_prog_aux` actually allocated? I'll need to trace its allocation. Let's head over to `kernel/bpf/core.c` and see if I can find the answer there. |
| 34/3 | 2026/10/17 07:56 | tool | grepper |
0mError:no matches Args: {
"Expression": "kzalloc.*struct bpf_prog_aux",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"error": "no matches"
} |
| 35/3 | 2026/10/17 07:56 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 91080 output: 30 thoughts: 22 Thoughts: Okay, here's my summary, tailored for an expert audience, as if I'm thinking these thoughts: **Analyzing BPF Program Auxiliary Allocation** Alright, let's dive into this. I need to understand how `bpf_prog_aux` is being allocated within the kernel's BPF subsystem. My first instinct, given the context, is to jump straight into the code. Time to fire up `grep`. I'll focus on the `kernel/bpf/` directory specifically to narrow down the search and avoid irrelevant results. My aim is to locate the allocation points for `bpf_prog_aux`. I'll be looking for uses of `bpf_prog_aux` itself, and potentially for calls to allocation functions that would return a pointer to that struct. This should quickly give me an overview of the initialization and lifecyle of this data structure within BPF, which will be essential for identifying potential areas for optimization, or tracing the source of bugs. I'm hoping to get a handle on all the contexts where `bpf_prog_aux` is created, used, and freed. |
| 36/3 | 2026/10/17 07:56 | tool | grepper |
0mArgs:{
"Expression": "-\u003eaux = ",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/arraymap.c=1111=static int prog_array_map_poke_track(struct bpf_map *map,\n--\nkernel/bpf/arraymap.c-1135-\t */\nkernel/bpf/arraymap.c:1136:\telem-\u003eaux = prog_aux;\nkernel/bpf/arraymap.c-1137-\n--\nkernel/bpf/arraymap.c=1233=static struct bpf_map *prog_array_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/arraymap.c-1251-\nkernel/bpf/arraymap.c:1252:\tcontainer_of(map, struct bpf_array, map)-\u003eaux = aux;\nkernel/bpf/arraymap.c-1253-\taux-\u003emap = map;\n--\nkernel/bpf/core.c=102=struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)\n--\nkernel/bpf/core.c-126-\tfp-\u003epages = size / PAGE_SIZE;\nkernel/bpf/core.c:127:\tfp-\u003eaux = aux;\nkernel/bpf/core.c-128-\tfp-\u003eaux-\u003emain_prog_aux = aux;\n--\nkernel/bpf/core.c=255=struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,\n--\nkernel/bpf/core.c-275-\t\t */\nkernel/bpf/core.c:276:\t\tfp_old-\u003eaux = NULL;\nkernel/bpf/core.c-277-\t\tfp_old-\u003estats = NULL;\n--\nkernel/bpf/core.c=1541=static void bpf_prog_clone_free(struct bpf_prog *fp)\n--\nkernel/bpf/core.c-1549-\t */\nkernel/bpf/core.c:1550:\tfp-\u003eaux = NULL;\nkernel/bpf/core.c-1551-\tfp-\u003estats = NULL;\n--\nkernel/bpf/fixups.c=1363=static int jit_subprogs(struct bpf_verifier_env *env)\n--\nkernel/bpf/fixups.c-1455-\t\t\t poke-\u003einsn_idx \u003e= subprog_start)\nkernel/bpf/fixups.c:1456:\t\t\t\tpoke-\u003eaux = func[i]-\u003eaux;\nkernel/bpf/fixups.c-1457-\t\t}\n--\nkernel/bpf/helpers.c=3405=static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)\n--\nkernel/bpf/helpers.c-3422-\t\treturn true;\nkernel/bpf/helpers.c:3423:\tctx-\u003eaux = prog-\u003eaux;\nkernel/bpf/helpers.c-3424-\tctx-\u003esp = sp;\n"
} |
| 37/3 | 2026/10/17 07:56 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 92149 output: 36 thoughts: 20 Thoughts: Here's my summary, as if I were thinking these thoughts: **Diving into the BPF Core** Okay, time to get my hands dirty. I need to refresh my memory on the core BPF implementation, specifically how it handles… I think it was that edge case we discussed yesterday. Right, let's head straight to the source. Let's start with `kernel/bpf/core.c`. I have a feeling the relevant logic will be around the more fundamental functions. Time to navigate to line 102 and see what's happening there. Hopefully, that will provide the context I need to solve this. |
| 38/3 | 2026/10/17 07:57 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/core.c",
"FirstLine": 105,
"LineCount": 25
}Results: {
"Contents": " 105:\t\tstruct bpf_prog_aux *aux;\n 106:\t\tstruct bpf_prog *fp;\n 107:\t\n 108:\t\tsize = round_up(size, __PAGE_SIZE);\n 109:\t\tfp = __vmalloc(size, gfp_flags);\n 110:\t\tif (fp == NULL)\n 111:\t\t\treturn NULL;\n 112:\t\n 113:\t\taux = kzalloc_obj(*aux, bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));\n 114:\t\tif (aux == NULL) {\n 115:\t\t\tvfree(fp);\n 116:\t\t\treturn NULL;\n 117:\t\t}\n 118:\t\tfp-\u003eactive = __alloc_percpu_gfp(sizeof(u8[BPF_NR_CONTEXTS]), 4,\n 119:\t\t\t\t\t\tbpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));\n 120:\t\tif (!fp-\u003eactive) {\n 121:\t\t\tvfree(fp);\n 122:\t\t\tkfree(aux);\n 123:\t\t\treturn NULL;\n 124:\t\t}\n 125:\t\n 126:\t\tfp-\u003epages = size / PAGE_SIZE;\n 127:\t\tfp-\u003eaux = aux;\n 128:\t\tfp-\u003eaux-\u003emain_prog_aux = aux;\n 129:\t\tfp-\u003eaux-\u003eprog = fp;\n"
} |
| 39/3 | 2026/10/17 07:57 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 92730 output: 426 thoughts: 2680 Thoughts: **BPF Exception Cleanup KMSAN Evaluation**
Okay, let's break this down. My goal is to determine if this patch necessitates KMSAN. First, I see the basic allocation and freeing: `aux` is zero-initialized with `kzalloc_obj`, and later freed correctly in `__bpf_prog_free` with `bpf_exc_free_info` and `kfree`. The `exc` and `epilogue_ip` fields in `bpf_prog_aux` are handled cleanly during subprogram JITting, with the original `exc` pointer set to `NULL` to prevent double free.
Now, that stack walk and return address rewrite in `arch_bpf_stack_walk_ra`... I have to verify that. It seems to use `unwind_get_return_address_ptr`, and that returns a pointer to the *stack* for the return address. `consume_fn` (specifically `bpf_unwind_rewrite`) modifies `*ra` which is the return address on the stack. The key is to ensure nothing uninitialized is *read* or *copied* during this process. `rec` and `prog` are checked, so it looks safe.
The code in `kernel/bpf/backtrack.c`, `kernel/bpf/liveness.c`, and `kernel/bpf/cfg.c` looks like verifier internal tracking and analysis; none of this seems to introduce any data leaks. And nothing in `kernel/bpf/states.c` is problematic.
The critical part: Does this patch modify anything user-facing? Nope. `bpf_prog_info` *isn't* expanded. It only added fields to `union bpf_attr` under `bpf_prog_load` and defined `struct bpf_cleanup_info`, and we're only copying *from* user space to the kernel via `copy_from_bpfptr` and reading `bpf_attr` so that's safe.
Now, let's step through the KMSAN check criteria:
1. **Kernel structures to userspace:** Nope. No `copy_to_user`, no netlink, nothing. Only copying from user space.
2. **Conditional logic on uninitialized data:** No. Allocations use `kzalloc` or designated initializers; all variables and struct fields used in conditionals (e.g. `seen_first`, `in_pad`, `unwind_exit`, `cleanup_info_cnt`, `might_unwind`, etc.) are explicitly initialized when the structs are allocated (via `kzalloc`, `kvcalloc`, designated initializers `= {0}`, or explicit assignments).
3. **Uninitialized data structures:** All heap structures are allocated with `kvcalloc` or `kzalloc_obj`, and everything gets initialized. Stack variables are also initialized.
4. **Bounds checks exposing uninitialized data:** No. There are no changes to existing buffer accesses that would expose uninitialized memory.
So, standard KASAN, LOCKDEP, and verifier checks are enough here.
What kind of bugs *could* occur? Verifier logic, CFG errors, out-of-bounds insn array accesses, or stack corruption during unwind/rewrite, or locking issues (all handled correctly.) These are caught by KASAN, assertions, and verifier tests. Not KMSAN.
**Therefore, NeedsKMSAN = false.**
This patch introduces BPF exception cleanup landing pads support, with new kfuncs, stack unwinding rewrite, verifier tracking, and loader/linker support. No user-kernel data leaks, no uninitialized reads, all structs are initialized, and no bounds checks are altered, therefore there is no need to set `NeedsKMSAN`. I can set `NeedsKMSAN: false` and `KMSANReasoning: "No user-kernel data copied. All new kernel heap structures are allocated via kzalloc/kvcalloc and initialized. The verifier and unwind logic alterations are covered by standard KASAN checks, verifier checks, and LOCKDEP."` and this should be fine.
|
| 40/3 | 2026/10/17 07:57 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series introduces support for BPF exception cleanup landing pads, adding the `bpf_unwind()` and `bpf_unwind_resume()` kfuncs, stack frame return-address rewriting via `arch_bpf_stack_walk_ra()`, BPF verifier tracking for cleanup pads and unwinding edges, and ELF/loader support for `.bpf_cleanup`.\n\nFrom a memory sanitizer perspective, a dedicated KMSAN fuzzing session is not warranted:\n1. No Kernel-to-User Information Leaks: The patch adds input fields to `union bpf_attr` for `BPF_PROG_LOAD` and copies records from user memory to the kernel, but does not add or modify any data copied back to userspace (no `bpf_prog_info` extensions, `copy_to_user()`, or netlink attributes).\n2. Proper Memory Initialization: All newly introduced kernel heap objects (`struct bpf_exception_info`, `struct bpf_cleanup_range`, `struct bpf_cleanup_info`) are allocated using `kzalloc_obj()` or `kvcalloc()`, and stack variables (`struct bpf_unwind_ctx`, `struct bpf_unwind_ra_consume_entry_data`, instruction patch arrays) are zero-initialized with designated initializers or fully written before use.\n3. KASAN/LOCKDEP Applicability: The primary risks associated with this patch involve control-flow graph exploration, insn patch offsets, return address rewriting on the call stack, and lock/reference tracking across unwinds. These issues manifest as out-of-bounds memory accesses, illegal instruction dereferences, or locking mismatches, which are detected by KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN.\n\nTherefore, running a dedicated KMSAN session would provide no additional benefit over standard KASAN/LOCKDEP testing.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series introduces support for BPF exception cleanup landing pads, adding the `bpf_unwind()` and `bpf_unwind_resume()` kfuncs, stack frame return-address rewriting via `arch_bpf_stack_walk_ra()`, BPF verifier tracking for cleanup pads and unwinding edges, and ELF/loader support for `.bpf_cleanup`.\n\nFrom a memory sanitizer perspective, a dedicated KMSAN fuzzing session is not warranted:\n1. No Kernel-to-User Information Leaks: The patch adds input fields to `union bpf_attr` for `BPF_PROG_LOAD` and copies records from user memory to the kernel, but does not add or modify any data copied back to userspace (no `bpf_prog_info` extensions, `copy_to_user()`, or netlink attributes).\n2. Proper Memory Initialization: All newly introduced kernel heap objects (`struct bpf_exception_info`, `struct bpf_cleanup_range`, `struct bpf_cleanup_info`) are allocated using `kzalloc_obj()` or `kvcalloc()`, and stack variables (`struct bpf_unwind_ctx`, `struct bpf_unwind_ra_consume_entry_data`, instruction patch arrays) are zero-initialized with designated initializers or fully written before use.\n3. KASAN/LOCKDEP Applicability: The primary risks associated with this patch involve control-flow graph exploration, insn patch offsets, return address rewriting on the call stack, and lock/reference tracking across unwinds. These issues manifest as out-of-bounds memory accesses, illegal instruction dereferences, or locking mismatches, which are detected by KASAN, LOCKDEP, and standard kernel debugging facilities rather than KMSAN.\n\nTherefore, running a dedicated KMSAN session would provide no additional benefit over standard KASAN/LOCKDEP testing.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|