Skip to contentSkip to conversation

bpf: Run exception cleanup landing pads when bpf_unwind() unwinds

PATCH Superseded Yonghong Song 4 participants 49 messages Oct 9 – Oct 14

Subsystems (9)
x86 Kselftest BPF arm64 +5 more subsystems

v10 of 12 Superseded Latest is v12 →

lore
Share & tools
lore

Yonghong Song

author reviewer
#0 lore raw

v10 cover bpf: Run exception cleanup landing pads when bpf_unwind() unwinds

bpf_throw() walks the BPF call stack to the exception boundary and discards every frame in between. A frame that owns something -- an RCU read lock, a preemption-disabled section, a referenced kptr -- never gets to give it back, so the verifier refuses to let such a frame throw at all. That is the whole reason a Rust program cannot use bpf_throw() as its panic path right now: Rust's Drop glue *is* that give-back, and there is nowhere to run it.

LLVM 23 added the compiler half ([1]). A Rust function that owns a value across a call that can unwind

    fn foo() {
        let _guard = RcuReadGuard::new();  /* bpf_rcu_read_lock()   */
        may_throw();                       /* extern "C-unwind"     */
    }                                      /* Drop: rcu_read_unlock */

lowers to an invoke with a cleanup landing pad holding the Drop call, and the BPF backend writes one record per invoke region into a .bpf_cleanup
section: a flat table of 12-byte (begin, end, landing_pad) triples, each field a byte offset into the code section. The rule is "a frame suspended at a call in [begin, end) resumes at landing_pad when an unwind passes through". A pad ends with a call to _Unwind_Resume(), which the kernel provides as the bpf_unwind_resume() kfunc.

Rather than overload bpf_throw(), which keeps its own meaning -- leave for the exception boundary with the frames in between discarded -- a new bpf_unwind() kfunc raises the unwind this series dispatches.

This series is the kernel half: take that table at BPF_PROG_LOAD, teach the verifier to follow an unwind to the landing pad it reaches, and have bpf_unwind() send each frame it leaves there.

C has no unwinding, so the selftests spell out by hand what a frontend emits -- a call site bracketed by two labels, a landing pad, and a record tying them together. The frame above, written that way:

"call bpf_rcu_read_lock;"
"1:" "call foo3;" /* cleanup region */
"2:"
... normal path, ends in bpf_rcu_read_unlock ...
"6:" /* landing pad */
"call bpf_rcu_read_unlock;"
"call bpf_unwind_resume;" CLEANUP_REC("1b", "2b", "6b")

Design
======

A pad runs in the frame that owns it, entered by an ordinary return. bpf_unwind() walks the frames with arch_bpf_stack_walk_ra(), which hands out the slot each frame's return address came from, and rewrites that slot for every frame above the one that called it: to the landing pad where a record covers the call the address returns into, and to that frame's epilogue where nothing does. It finds the frames in the calling program itself, whose aux the verifier passes it as an implicit argument. Then it returns. The frame that called it goes on after the call, where the fixups put 'r0 = 0' and then a jump to its own pad, or an exit where no record covers the call.

Each frame therefore runs its own pad, on its own stack, and leaves through its own epilogue -- which is what puts its caller's r6-r9 back. The unwind needs no trampoline, no spill area and no per-frame metadata beyond the table itself. The fixups lower a pad's bpf_unwind_resume() to 'r0 = 0; exit', so the frame returns and the address rewritten below it carries the unwind on to the next pad. For main -> A -> B -> C with only A's call to B covered, an unwind raised in C runs:

  frame   runs
  -----   ----------------------------------------------------------
  C       'r0 = 0; exit', patched in after its bpf_unwind()
  B       its epilogue, putting back A's r6-r9
  A       its pad, which drops A's resources; the resume is an exit
  main    its epilogue, returning 0 to the kernel

The verifier follows the same path. A bpf_unwind() goes on at its own frame's pad, or pops frames to the first pad that covers a call, or to the main program's exit, where nothing may still be held and the zero returned has to suit the program type. Only there are an unwind's resources checked, since a pad may drop what another frame acquired, as when Rust moves a value into a callee. A resume goes on below its frame the same way. The pad is entered from the state the unwind leaves, not from a snapshot at the call: before unwinding, a callee may have written its caller's stack through a pointer, overwritten a spilled pointer, or changed packet data, and the callee's epilogue puts back none of that. A global subprog is verified on its own, so a call to one that can unwind gets a second successor, the unwind, taken from the state the call returns in. Precision backtracking follows the same edges back, into the frame the unwind left.

1 pack bpf_insn_aux_data's flags into bit fields, so the flags this
series adds cost bits rather than bytes
2-3 uapi: cleanup_info in BPF_PROG_LOAD and struct bpf_cleanup_info;
the bpf_unwind() and bpf_unwind_resume() kfuncs
4-6 keep a call site's pad in insn_aux_data, mark the covered call
sites, refuse what cannot carry a table, and make the landing pads reachable in the CFG and in liveness
7 verifier: follow an unwind through landing pads and epilogues
8-10 refuse a callback that can unwind and a pad that does not
resume; no private stack for a program that can unwind
11 lower the unwind and resume calls, build the native cleanup
tables, and keep an exit in every function the walk can pass

  12     bpf_unwind(): rewrite the return addresses as it walks
  13     refuse a trampoline that calls a subprog that can unwind
  14-15  x86-64 and arm64 JITs
  16-20  libbpf: resolve _Unwind_Resume, collect .bpf_cleanup and pass it

to the kernel, carry it through the light skeleton and the static linker
21-24 selftests

Limitations
===========

- Cleanup pads only. A catch pad, which Rust's catch_unwind would need, is refused: bpf_unwind() rewrites every frame in one pass.
- Needs a JIT that dispatches pads: x86-64 with CONFIG_UNWINDER_ORC, and arm64. Elsewhere the load fails with -EOPNOTSUPP.
- Not with offload, a private stack, a verifier_ops epilogue, bpf_throw() or an exception callback.
- In a pad's frame: no tail call, BPF_LD_[ABS|IND] or indirect jump, and no second unwind in the pad or anything it calls.
- A subprog that can unwind cannot be a callback, nor be attached by fexit, fmod_ret or fsession. One with a callx counts as able to unwind when any subprog whose address is taken can.
- A subprog an unwind passes through must have an exit.
- Until the Rust toolchain supports BPF exception handling, the selftests write their tables by hand in inline asm.

[1] https://github.com/llvm/llvm-project/pull/192164
llvm commit 9d51c891b719 ("[BPF] Add exception handling support with .bpf_cleanup section")

Changelog
=========
v9 -> v10:
- v9: https://lore.kernel.org/bpf/[email protected]/
- Split the callback refusal into its own patch 8.
- Fix a verifier_bug() when a global call's pad is the next insn.
- On a cleanup_info record with a nonzero tail, fail with -E2BIG without writing a record size back into the attr.
v8 -> v9:
- v8: https://lore.kernel.org/bpf/[email protected]/
- unwind_frames() destroys popped frames' dynptrs.
- Drop patch 8: it refused a callee's pad dropping a reference its caller acquired, which is how Rust compiles moving a value into a callee. Held resources are checked only where main or a global subprog returns.
- Drop the per-insn in/outside-pad marks; compare in_pad when pruning.
- Split patch 11 into 10 (prepare the JITed program) and 11 (the walk).
- bpf_unwind() finds frames in its program's aux (KF_IMPLICIT_ARGS), not in kallsyms, which can go while an instance still runs.
- New patch 12: refuse fexit/fmod_ret/fsession on an unwinding subprog.
- x86, arm64: make bpf_unwind() notrace and NOKPROBE, drop the hooked-return warning; arm64: drop the PAC modifier check.
- Fix an unwind out of main inside a loop, and a global subprog returning in R0:R2; narrow the callx might_unwind marking.
- libbpf: skip records of an overridden weak function; leave table checks to the kernel.
v7 -> v8:
- v7: https://lore.kernel.org/bpf/[email protected]/
- Follow an unwind to its pad from the state it leaves, not from a snapshot at the call; patch 7 is renamed to match.
- Follow the unwind out of a call to a global subprogram as well: the call continues at the next insn and, from the state it returns in, at its pad or further out.
- Backtrack precision across an unwind; clear r1-r5 at a main-frame unwind exit.
- bpf_unwind() leaves its own caller alone; the fixups put 'r0 = 0' and a jump to its pad after the call.
- Refuse bpf_throw() and an exception callback with any unwind, not only with a table.
- Refuse a subprogram an unwind passes through that has no exit.
- Patch 8's rule that a frame an unwind leaves holds what it entered with no longer keeps the pads safe; it stays to refuse a program at the frame at fault.
- A speculative walk leaves no in-pad or outside-pad mark.
- x86, arm64: warn on a hooked return. arm64: take the PAC modifier as record + 16, and allow a shadow call stack.
- libbpf: narrow the _Unwind_Resume translation, close the opts hole, size the light skeleton's attr by need, and tighten the linker check.
v6 -> v7:
- v6: https://lore.kernel.org/bpf/[email protected]/
- New patch: require an unwind to leave a frame holding what it entered with, including at a call it passes through with no record over it.
- A resume ends the verifier's path instead of walking back to the instruction after the call, where an unwind never returns.
- Refuse a private stack for any program that can unwind, not only one carrying a table.
- Refuse a table for a program whose verifier_ops plants an epilogue, and scan the whole instruction stream for bpf_throw().
- Keep the last exit of every subprogram an unwind can pass through, not only the one after a bpf_unwind() call, and search for it.
- Fix precision backtracking across a resume, push a landing pad by itself so the CFG walk's DFS invariant holds, and mark callx sites.
- x86: leave a frame whose return a tracer has hooked alone; no ENDBR at a pad head, which is only ever reached by a return.
- arm64: no BTI at a pad head; ask the build whether a return address is signed; refuse cleanup pads where a shadow call stack is in use.
- Answer a speculative walk reaching a pad with a barrier, not a refusal.
- selftests: add the negative shapes for the above, allow repeated __set_global()/__ret_global(), and drop duplicate accepted shapes.
v5 -> v6:
- v5: https://lore.kernel.org/bpf/[email protected]/
- Run a pad in the frame that owns it: bpf_unwind() rewrites each frame's saved return address rather than calling the pad as a subroutine of the walker. The bpf_cleanup_pad.S trampolines, the per-frame spill area and the pad-entry register header all go away.
- Raise the unwind with a new bpf_unwind() kfunc, so that bpf_throw() keeps its meaning.
- Add arch_bpf_stack_walk_ra(), which also hands out the slot a return address came from. arm64 re-signs the address it writes there.
- A pad is an ordinary second successor of a covered call, so the verifier needs no unwind edge of its own: the cross-frame precision and liveness work is gone, with the v5 fixes it needed, and two patches become one.
- Refuse the undispatchable shapes per instruction in do_check(), keyed on a per-frame mark, rather than by walking each pad.
- Allow on-stack call arguments in a pad, which now has its own frame.
- Add __set_global() and __ret_global() test tags, so RUN_TESTS() drives the shapes and test_shapes() goes away (suggested by Eduard).
- Drop the shapes that needed a driver of their own, and the three extension objects with them.
v4 -> v5:
- v4: https://lore.kernel.org/bpf/[email protected]/
- Rebase on bpf-next.
- Clear r0 where a throw enters a landing pad: no instruction defines it, so a precision request for it outlived the state and oopsed the verifier.
- Defer entering the frames an unwind edge crossed until the backtrack reads an instruction from them; entering at the landing pad could leave bt->frame past the parent state's frames and oops the verifier.
- Stamp the popped frame count inside bpf_push_jmp_history(), so a pad's entry carries it even when the prune path is what creates the entry.
- Replace the hand-rolled CFG traversal and its separate pass with per-instruction checks in do_check(), keyed on the verifier's unwinding state; kernel/bpf/exception.c halves.
- Add a first patch packing bpf_insn_aux_data's flags into one bit field word, 144 bytes to 128, so the flags this series adds cost bits.
- Drop the per-subprogram arrays the JITs consulted for throw sites, resume sites and pad bodies, and read insn_aux_data, which a JIT already has.
- Drop the pad-entry r0 header: r0 at a pad is an unknown scalar, and a dispatcher writes a defined value there only to keep a kernel one out of BPF.
- Take the bool arguments back out of verifier_remove_insns() and the site collector, and share pop_frame() with prepare_func_exit().
- Rename the recorded call sites to throw_call and resume_call, give the exported functions a bpf_exc_ prefix, and drop cleanup_ from the statics.
v3 -> v4:
- v3: https://lore.kernel.org/bpf/[email protected]/
- Rebase on bpf-next due to conflict.
- Reserve the throw-site spill area only in a (sub)program that calls bpf_throw(): 40 bytes of stack per frame on x86-64, 80 on arm64.
- Bound the record count by the number of instructions in the program, and name both in the message.
- Refuse a .bpf_cleanup section in libbpf whose record count cannot be handed to the kernel as a count times a record size in an int.
- Fix the static linker's new bounds check, which could itself wrap, and refuse a section too small to hold one field.
- WARN once if the body of bpf_unwind_resume() is ever reached, the way bpf_throw() does where its exception callback should never return.
- Rename nr_pad_body to pad_body_bits, use BTF_ID_LIST_SINGLE, move cleanup_pad out of insn_aux_data's bools, drop an arm64 include.
v2 -> v3:
- v2: https://lore.kernel.org/bpf/[email protected]/
- Keep a landing pad's record when opt_remove_nops() deletes a pad that is a nop, instead of dropping it after the verifier has already checked the call site against it.
- Refuse a BPF_LD_[ABS|IND] in a pad body.
- Teach mark_chain_precision() about the throw-to-pad edge, which crosses frames with no instruction to account for them.
- Refuse a bpf_unwind_resume() in any frame but the one whose landing pad the walker entered.
- Check raw_data, alignment and bounds before the static linker writes through a relocation in a non-executable section, which may be SHT_NOBITS.
v1 -> v2:
- v1: https://lore.kernel.org/bpf/[email protected]/
- Consolidate all usages of kern_extern_name() in a single patch in libbpf.
- Avoid compiler warning and add proper cleanup_info_cnt guard in libbpf when collecting .bpf_cleanup records.
- Add cleanup_info_cnt condition for emit_rel_store() with cleanup_info.

Yonghong Song (24):
bpf: Pack bpf_insn_aux_data flags into bit fields
bpf: Accept the compiler's exception cleanup table at program load
bpf: Add the bpf_unwind() and bpf_unwind_resume() kfuncs
bpf: Keep a call site's landing pad in insn_aux_data, add lookups
bpf: Mark covered call sites and check a program can take a table
bpf: Make exception landing pads reachable in the CFG
bpf: Verify an unwind through landing pads and epilogues
bpf: Refuse a callback that can unwind
bpf: Refuse a landing pad that does not resume
bpf: Do not use a private stack for a program that can unwind
bpf: Prepare JITed programs for dispatching cleanup pads
bpf: Dispatch cleanup pads by rewriting return addresses
bpf: Refuse a trampoline that calls a subprog that can unwind bpf, x86: Dispatch exception cleanup pads at run time
bpf, arm64: Dispatch exception cleanup pads at run time
libbpf: Resolve the compiler's _Unwind_Resume to the kernel's kfunc
libbpf: Add cleanup_info to bpf_prog_load_opts
libbpf: Collect .bpf_cleanup records and pass them to the kernel
libbpf: Carry the exception cleanup table through the light skeleton
libbpf: Let the static linker carry .bpf_cleanup relocations selftests/bpf: Add end-to-end and negative .bpf_cleanup exception
tests
selftests/bpf: Add __set_global() and __ret_global() test tags selftests/bpf: Cover more accepted .bpf_cleanup exception shapes selftests/bpf: Load an exception cleanup program from a light skeleton

 arch/arm64/kernel/stacktrace.c                |   74 ++
 arch/arm64/net/bpf_jit_comp.c                 |   16 +
 arch/x86/net/bpf_jit_comp.c                   |   36 +
 include/linux/bpf.h                           |   31 +
 include/linux/bpf_verifier.h                  |   63 +-
 include/linux/filter.h                        |    3 +
 include/uapi/linux/bpf.h                      |   14 +
 kernel/bpf/Makefile                           |    2 +-
 kernel/bpf/backtrack.c                        |   40 +-
 kernel/bpf/cfg.c                              |  126 ++
 kernel/bpf/core.c                             |   12 +
 kernel/bpf/exception.c                        |  386 ++++++
 kernel/bpf/exception.h                        |   30 +
 kernel/bpf/fixups.c                           |  164 ++-
 kernel/bpf/helpers.c                          |   79 ++
 kernel/bpf/liveness.c                         |   24 +-
 kernel/bpf/states.c                           |   11 +-
 kernel/bpf/syscall.c                          |    2 +-
 kernel/bpf/verifier.c                         |  216 +++-
 tools/include/uapi/linux/bpf.h                |   14 +
 tools/lib/bpf/bpf.c                           |    6 +-
 tools/lib/bpf/bpf.h                           |   10 +-
 tools/lib/bpf/gen_loader.c                    |   29 +-
 tools/lib/bpf/libbpf.c                        |  330 ++++-
 tools/lib/bpf/libbpf_internal.h               |   10 +
 tools/lib/bpf/linker.c                        |   37 +-
 tools/testing/selftests/bpf/Makefile.skel     |    2 +-
 .../selftests/bpf/exceptions_cleanup.h        |   47 +
 .../bpf/prog_tests/exceptions_cleanup.c       |  149 +++
 tools/testing/selftests/bpf/progs/bpf_misc.h  |   12 +
 .../selftests/bpf/progs/exceptions_cleanup.c  |  160 +++
 .../bpf/progs/exceptions_cleanup_fail.c       |  947 ++++++++++++++
 .../bpf/progs/exceptions_cleanup_shapes.c     | 1141 +++++++++++++++++
 .../bpf/progs/exceptions_cleanup_tracing.c    |   23 +
 tools/testing/selftests/bpf/test_loader.c     |  319 ++++-
 35 files changed, 4508 insertions(+), 57 deletions(-)
 create mode 100644 kernel/bpf/exception.c
 create mode 100644 kernel/bpf/exception.h
 create mode 100644 tools/testing/selftests/bpf/exceptions_cleanup.h
 create mode 100644 tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup.c
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c
Signature · 1 line
2.53.0-Meta
author reviewer
#1 lore raw

PATCH v10 1/24 bpf: Pack bpf_insn_aux_data flags into bit fields

struct bpf_insn_aux_data spreads its flags over nine bools, a u8 of three bit fields and a u32 group with 25 of its 32 bits spare. Put them all in one u64 word, alu_state with them, with orig_idx packing into the word's upper half. The structure goes from 128 bytes to 120, and stays there when a later patch adds a u32, which takes the tail padding.

No functional change.

---
 include/linux/bpf_verifier.h | 45 ++++++++++++++++++------------------
 1 file changed, 23 insertions(+), 22 deletions(-)
include/linux/bpf_verifier.h +23 -22
index c51083c761cf..68636e1f048b 100644
@@ -664,42 +664,43 @@ struct bpf_insn_aux_data {
 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
 	u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
-	bool nospec; /* do not execute this instruction speculatively */
-	bool nospec_result; /* result is unsafe under speculation, nospec must follow */
-	bool zext_dst; /* this insn zero extends dst reg */
-	bool needs_zext; /* alu op needs to clear upper bits */
-	bool prevent_zext; /* alu op cannot be zext (already used with 64-bit scalars) */
-	bool non_sleepable; /* helper/kfunc may be called from non-sleepable context */
-	bool is_iter_next; /* bpf_iter_<type>_next() kfunc call */
-	bool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */
-	bool arena_scalar; /* ldx/stx/st/atomic through a number, it's an address in arena */
-	u8 alu_state; /* used in combination with alu_limit */
+	u64 nospec:1; /* do not execute this instruction speculatively */
+	u64 nospec_result:1; /* result is unsafe under speculation, nospec must follow */
+	u64 zext_dst:1; /* this insn zero extends dst reg */
+	u64 needs_zext:1; /* alu op needs to clear upper bits */
+	u64 prevent_zext:1; /* alu op cannot be zext (already used with 64-bit scalars) */
+	u64 non_sleepable:1; /* helper/kfunc may be called from non-sleepable context */
+	u64 is_iter_next:1; /* bpf_iter_<type>_next() kfunc call */
+	u64 call_with_percpu_alloc_ptr:1; /* {this,per}_cpu_ptr() with prog percpu alloc */
+	u64 arena_scalar:1; /* ldx/stx/st/atomic through a number, it's an address in arena */
+	u64 alu_state:8; /* used in combination with alu_limit */
 	/* true if STX or LDX instruction is a part of a spill/fill
 	 * pattern for a bpf_fastcall call.
 	 */
-	u8 fastcall_pattern:1;
+	u64 fastcall_pattern:1;
 	/* for CALL instructions, a number of spill/fill pairs in the
 	 * bpf_fastcall pattern.
 	 */
-	u8 fastcall_spills_num:3;
-	u8 arg_prog:4;
+	u64 fastcall_spills_num:3;
+	u64 arg_prog:4;
 
-	/* below fields are initialized once */
-	unsigned int orig_idx; /* original instruction index */
-	u32 jmp_point:1;
-	u32 prune_point:1;
+	/* below flags are initialized once */
+	u64 jmp_point:1;
+	u64 prune_point:1;
 	/* ensure we check state equivalence and save state checkpoint and
 	 * this instruction, regardless of any heuristics
 	 */
-	u32 force_checkpoint:1;
+	u64 force_checkpoint:1;
 	/* true if instruction is a call to a helper function that
 	 * accepts callback function as a parameter.
 	 */
-	u32 calls_callback:1;
-	u32 indirect_target:1; /* if it is an indirect jump target */
-	u32 non_stack_access:1; /* instruction can access non-stack memory */
+	u64 calls_callback:1;
+	u64 indirect_target:1; /* if it is an indirect jump target */
+	u64 non_stack_access:1; /* instruction can access non-stack memory */
 	/* true if some jump or call instruction targets this instruction */
-	u32 jump_target:1;
+	u64 jump_target:1;
+
+	unsigned int orig_idx; /* original instruction index, initialized once */
 	/*
 	 * CFG strongly connected component this instruction belongs to,
 	 * zero if it is a singleton SCC.
Signature · 1 line
2.53.0-Meta
author reviewer
#2 lore raw

PATCH v10 2/24 bpf: Accept the compiler's exception cleanup table at program load

In reply to Yonghong Song

LLVM 23 added exception handling for BPF with the .bpf_cleanup section [1]: Rust code compiled with panic=unwind runs cleanup code (Drop glue) when an unwind passes through, and the BPF backend emits the section from the landing pads. rustc does not fully support BPF exception handling yet, and C can produce the section only with inline asm, which is enough to test it.

Add the UAPI to carry the table to BPF_PROG_LOAD: cleanup_info, cleanup_info_cnt and cleanup_info_rec_size. A record, struct bpf_cleanup_info, says that calls in [begin_off, end_off) that unwind resume at landing_pad_off, all instruction indices.

bpf_exc_check_info() checks the table at load time: records sorted by begin_off, with non-empty and disjoint ranges, each inside one subprog, no landing pad inside any range, and no offset naming the second half of an ld_imm64. A record longer than the kernel's is taken only if the rest is zero, and, unlike func_info, no size is written back for the loader to zero the rest and retry: a field the kernel does not know could change what a pad does. Nothing reads the table yet.

---
 include/linux/bpf_verifier.h   |   2 +
 include/uapi/linux/bpf.h       |  14 ++++
 kernel/bpf/Makefile            |   2 +-
 kernel/bpf/exception.c         | 137 +++++++++++++++++++++++++++++++++
 kernel/bpf/exception.h         |  15 ++++
 kernel/bpf/syscall.c           |   2 +-
 kernel/bpf/verifier.c          |   6 ++
 tools/include/uapi/linux/bpf.h |  14 ++++
 8 files changed, 190 insertions(+), 2 deletions(-)
 create mode 100644 kernel/bpf/exception.c
 create mode 100644 kernel/bpf/exception.h
include/linux/bpf_verifier.h +2 -0
index 68636e1f048b..a5f493876993 100644
@@ -1021,6 +1021,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 */
include/uapi/linux/bpf.h +14 -0
index e0ed44b1bbcb..15dfba087201 100644
@@ -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 */
@@ -7644,6 +7647,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;
 };
kernel/bpf/Makefile +1 -1
index c1f9b0d3468d..8a6947b3d13a 100644
@@ -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
kernel/bpf/exception.c new file +137 -0

137 lines not on this page · raw message

kernel/bpf/exception.h new file +15 -0
new file mode 100644
index 000000000000..cf099dcc5b74
@@ -0,0 +1,15 @@
+/* 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;
+
+int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
+		       bpfptr_t uattr);
+
+#endif /* __BPF_EXCEPTION_H */
kernel/bpf/syscall.c +1 -1
index 654f896af265..10e0a693a06d 100644
@@ -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)
 {
kernel/bpf/verifier.c +6 -0
index 353bde9ae227..60413bf0ad3f 100644
@@ -37,6 +37,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) \
@@ -22706,6 +22707,10 @@ 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;
+
 	/* Validate instructions and resolve the program's referenced resources. */
 	ret = check_and_resolve_insns(env);
 	if (ret < 0)
@@ -22923,6 +22928,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	kvfree(env->callx_edges);
 	kvfree(env->func_ptrs);
 	bpf_diag_free(env);
+	kvfree(env->cleanup_info);
 	kvfree(env);
 	return ret;
 }
tools/include/uapi/linux/bpf.h +14 -0
index e0ed44b1bbcb..15dfba087201 100644
@@ -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 */
@@ -7644,6 +7647,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;
 };
Signature · 1 line
2.53.0-Meta
author reviewer
#3 lore raw

PATCH v10 3/24 bpf: Add the bpf_unwind() and bpf_unwind_resume() kfuncs

In reply to Yonghong Song

An exception cleanup needs two terminators:

- bpf_unwind() begins an unwind: the frames it leaves run their landing pads on the way out to the program's exit. It is separate from bpf_throw(), which discards the frames in between.
- bpf_unwind_resume() ends a landing pad, carrying the unwind on. The compiler calls it _Unwind_Resume, which a later libbpf patch resolves to this name, and passes it the exception object, which the kfunc takes as ptr__ign.

Neither is registered yet: that waits for the patch that dispatches pads at run time.

---
 kernel/bpf/helpers.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
kernel/bpf/helpers.c +14 -0
index a284f20c97d5..4eccd6742eba 100644
@@ -3424,6 +3424,10 @@ static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
 	return false;
 }
 
+__bpf_kfunc void bpf_unwind(void)
+{
+}
+
 __bpf_kfunc void bpf_throw(u64 cookie)
 {
 	struct bpf_throw_ctx ctx = {};
@@ -3445,6 +3449,16 @@ __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)
+{
+	/*
+	 * Never reached: the verifier accepts this kfunc only as a frame
+	 * terminator and bpf_do_misc_fixups() lowers every one of them to
+	 * 'r0 = 0; exit', so no call to this body survives to run.
+	 */
+	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;
Signature · 1 line
2.53.0-Meta
author reviewer
#4 lore raw

PATCH v10 4/24 bpf: Keep a call site's landing pad in insn_aux_data, add lookups

In reply to Yonghong Song

A call site's landing pad, if any, is kept in insn_aux_data as cleanup_pad. adjust_insn_aux_data(), which every instruction patch goes through, and verifier_remove_insns() keep it in step, and bpf_opt_remove_nops() moves a pad off a nop to the next instruction before removing the nop. Add lookups for it and for calls to bpf_unwind() and bpf_unwind_resume(); their users come in later patches.

---
 include/linux/bpf_verifier.h |  5 +++++
 kernel/bpf/exception.c       | 24 ++++++++++++++++++++++++
 kernel/bpf/exception.h       |  4 ++++
 kernel/bpf/fixups.c          | 26 +++++++++++++++++++++++++-
 4 files changed, 58 insertions(+), 1 deletion(-)
include/linux/bpf_verifier.h +5 -0
index a5f493876993..e6bde421ab3b 100644
@@ -701,6 +701,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.
kernel/bpf/exception.c +24 -0
index c2de6ecf54bb..2fef417dc090 100644
@@ -2,6 +2,8 @@
 /* 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"
 
@@ -135,3 +137,25 @@ int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
 	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)
+
+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];
+}
+
+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;
+}
kernel/bpf/exception.h +4 -0
index cf099dcc5b74..d5c6ac459870 100644
@@ -8,8 +8,12 @@
 
 union bpf_attr;
 struct bpf_verifier_env;
+struct bpf_insn;
 
 int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
 		       bpfptr_t uattr);
+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);
 
 #endif /* __BPF_EXCEPTION_H */
kernel/bpf/fixups.c +25 -1
index 206cc9a614a9..64baee1a37e6 100644
@@ -244,11 +244,18 @@ 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;
 		} 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
@@ -595,6 +602,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;
@@ -623,6 +631,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;
 }
 
@@ -728,7 +747,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));
@@ -739,6 +758,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 (env->insn_aux_data[j].cleanup_pad == i + 1)
+					env->insn_aux_data[j].cleanup_pad = i + 2;
+
 		err = verifier_remove_insns(env, i, 1);
 		if (err)
 			return err;
Signature · 1 line
2.53.0-Meta
author reviewer
#7 lore raw

PATCH v10 5/24 bpf: Mark covered call sites and check a program can take a table

In reply to Yonghong Song

- bpf_exc_prepare(), run before the CFG walk, records the landing pad of every call in a cleanup record's range that can unwind: a BPF-to-BPF call, direct or indirect, or bpf_unwind().

- bpf_exc_check_prog() refuses a table where pad dispatch cannot work:

- an offloaded program, or one without a JIT that dispatches pads
- a verifier_ops gen_epilogue, as bpf_qdisc's: it is planted on the exits bpf_convert_ctx_accesses() sees, and the exits an unwind returns through are added after it
- an exception callback or a bpf_throw() anywhere: a throw leaves without rewriting return addresses, so no pad would run

It runs after check_attach_btf_id(), since a struct_ops program's gen_epilogue is only known then, and marks what passes jit_required. bpf_jit_supports_cleanup_pads() says no until the arch patches.

---
 include/linux/filter.h |  1 +
 kernel/bpf/core.c      |  5 +++
 kernel/bpf/exception.c | 70 ++++++++++++++++++++++++++++++++++++++++++
 kernel/bpf/exception.h |  2 ++
 kernel/bpf/verifier.c  |  9 ++++++
 5 files changed, 87 insertions(+)
include/linux/filter.h +1 -0
index 9339c6131f8f..c8ca863e352a 100644
@@ -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);
kernel/bpf/core.c +5 -0
index 05c89396119a..078bcccaf242 100644
@@ -3528,6 +3528,11 @@ void __weak arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp,
 {
 }
 
+bool __weak bpf_jit_supports_cleanup_pads(void)
+{
+	return false;
+}
+
 bool __weak bpf_jit_supports_timed_may_goto(void)
 {
 	return false;
kernel/bpf/exception.c +70 -0

76 lines not on this page · raw message

kernel/bpf/exception.h +2 -0
index d5c6ac459870..9b75e556c82e 100644
@@ -12,6 +12,8 @@ struct bpf_insn;
 
 int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
 		       bpfptr_t uattr);
+void bpf_exc_prepare(struct bpf_verifier_env *env);
+int bpf_exc_check_prog(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);
kernel/bpf/verifier.c +9 -0
index 60413bf0ad3f..0cf30220b777 100644
@@ -22711,6 +22711,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t 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_prepare(env);
+
 	/* Validate instructions and resolve the program's referenced resources. */
 	ret = check_and_resolve_insns(env);
 	if (ret < 0)
@@ -22748,6 +22751,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) {
+		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;
Signature · 1 line
2.53.0-Meta
author reviewer
#10 lore raw

PATCH v10 6/24 bpf: Make exception landing pads reachable in the CFG

In reply to Yonghong Song

A call that a cleanup record covers can also reach the record's landing pad. Add that edge to the CFG walk, to bpf_insn_successors(), and to stack liveness, where a slot is alive across a call when the call's pad reads it.

The CFG walk pushes the pad in a visit of its own, and the fall-through on the next visit. bpf_check_cfg() re-visits the top of its stack until DONE_EXPLORING, so a visit pushing both would leave the pad DISCOVERED off the current path, and push_insn() would take a branch from one pad into another -- how a frame with two regions chains them -- for a back-edge.

Without the liveness change, a slot only the pad reads looked dead, and clean_verifier_state() poisoned it while the callee ran.

---
 kernel/bpf/cfg.c      | 38 ++++++++++++++++++++++++++++++++++++++
 kernel/bpf/liveness.c | 24 +++++++++++++++++++++++-
 2 files changed, 61 insertions(+), 1 deletion(-)
kernel/bpf/cfg.c +38 -0
index d8a579680e5b..63afbc5fb296 100644
@@ -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)
 
@@ -160,6 +161,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 +200,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)
kernel/bpf/liveness.c +23 -1
index cd9523f69298..2e7eead71c93 100644
@@ -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)
 
 /*
@@ -384,6 +386,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;
 }
 
@@ -510,7 +524,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;
@@ -545,6 +560,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;
 	}
Signature · 1 line
2.53.0-Meta
author reviewer
#11 lore raw

PATCH v10 7/24 bpf: Verify an unwind through landing pads and epilogues

In reply to Yonghong Song

Once a later patch makes bpf_unwind() dispatch pads, an unwind rewrites the return address of every frame it passes: to the pad where a record covers the frame's call, else to the frame's epilogue. Each frame then returns normally, a pad through its resume, which is lowered to 'r0 = 0; exit'. The verifier follows the unwind the same way: into the pad of each frame that has one, out of each frame that does not, and out of main as a program exit.

  instruction                          goes on at
  -----------------------------------  ---------------------------------
  bpf_unwind(), record over it         its own frame's pad
  bpf_unwind(), no record over it      unwind_frames()
  bpf_unwind_resume()                  unwind_frames()
  call to a global subprog that can    next insn, and the unwind from the
  unwind                               returned state: to the call's pad,

or on through unwind_frames()

Whether a subprog can unwind is worked out on the CFG, as might_throw
is: a call to bpf_unwind() marks its subprog might_unwind, and merge_callee_effects() carries the mark to its callers. A callx goes around merge_callee_effects(), so if any subprog whose address is taken can unwind, mark_callx_might_unwind() marks every subprog holding a callx, and its callers. That is conservative, as only the main walk knows which subprog a callx calls.

unwind_frames(), for main -> A -> B -> C where only A's call is covered:

  program                              run time: bpf_unwind() in C
  -----------------------------------  ---------------------------------
  main:     call A                     main returns via its epilogue
  A:     1: call B     [1, 2) -> P     A resumes at P
         2: ...
         P: <drop A's resources>
            call bpf_unwind_resume
  B:        call C     no record       B returns via its epilogue
  C:        call bpf_unwind            C returns via 'r0 = 0; exit'
  frame   at C's bpf_unwind()   unwind_frames()     at P's resume
  -----   -------------------   -----------------   -----------------
    3     C  <- curframe        popped
    2     B                     popped
    1     A                     A  <- curframe, P   popped
    0     main                  main                exit with r0 = 0

P gets A's frame as B and C left it, with r0 unknown and r1-r5 cleared. Main returning goes through process_bpf_exit_full(), the only place an unwind's resources are checked: a frame it pops may leave something for a caller's pad to drop.

The pad's state comes from the unwind, not from a snapshot at the call:
before unwinding, the callee may have written the caller's stack through a pointer, overwritten a spilled pointer, reinitialised a dynptr or an iterator, or changed packet data, none of which its epilogue restores. A global subprog is verified on its own, so the unwind out of a call to one starts from the state the call returns in, after check_func_call().

Precision backtracking gets three new edges:

  edge                     frame
  -----------------------  ---------------------------------------------
  global call <- its pad   stays in the caller (subseq_idx is the pad)
  unwind <- pad            moves to the frame the unwind left, recorded

in its history entry under INSN_F_UNWIND
unwind <- main's exit the same, after a jump from the unwinding insn
to where the path ends

Where no frame has a pad, the path ends at E, the insn it exits from in place of a BPF_EXIT: main's call into the popped frames, else the unwinding insn U itself. Backtracking for the return check starts at E without processing it, while r0 is set at U, Q being U's predecessor:

frames popped none popped

main: E: call A main: Q: r6 = 0
A: call B E = U: call bpf_unwind
B: Q: r6 = 0
U: call bpf_unwind

walk: E -> U -> Q -> ... walk: E -> U -> Q -> ...
^ skipped ^ skipped

The jump from U to E takes the walk to U rather than to the insn before E; where E is U, it is what gets U processed at all. U's INSN_F_UNWIND mark matters there only for an unwinding global call, which backtracking would otherwise take for one that returned.

Unlike a BPF_EXIT in main, the end of such a path can be inside a loop, where maybe_exit_scc() finds no visit info for it. The new unwind_exit in the state tells it that the path ended there.

---
 include/linux/bpf_verifier.h |   9 ++-
 kernel/bpf/backtrack.c       |  40 +++++++++-
 kernel/bpf/cfg.c             |  88 +++++++++++++++++++++
 kernel/bpf/states.c          |   8 +-
 kernel/bpf/verifier.c        | 148 ++++++++++++++++++++++++++++++++++-
 5 files changed, 283 insertions(+), 10 deletions(-)
include/linux/bpf_verifier.h +7 -2
index e6bde421ab3b..d3740ad20235 100644
@@ -383,6 +383,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 */
@@ -393,8 +395,8 @@ struct bpf_jmp_history_entry {
 	u32 idx : 20;
 	u32 frame : 4;	/* stack access frame number */
 	/* 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 */
 	/*
@@ -480,6 +482,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 */
 	u32 first_insn_idx;
@@ -837,6 +841,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;
kernel/bpf/backtrack.c +36 -4
index 0e38b9575328..bf5bfad94406 100644
@@ -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 */
kernel/bpf/cfg.c +88 -0

118 lines not on this page · raw message

kernel/bpf/states.c +6 -2
index 18bf7b660c2f..4ffa5b7ebf0f 100644
@@ -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;
kernel/bpf/verifier.c +146 -2

178 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author reviewer
#17 lore raw

PATCH v10 9/24 bpf: Refuse a landing pad that does not resume

In reply to Yonghong Song

A cleanup pad runs drop glue and calls bpf_unwind_resume(), so its frame returns and the unwind goes on. A catch pad carries on in its frame instead. Only the first is supported: bpf_unwind() rewrites every frame's return address in one pass, so a catch pad's caller would still resume at a pad.

Nothing in the record says which kind a pad is, but the code does: a cleanup pad reaches _Unwind_Resume, a catch pad a return. So the unwind marks the frame whose pad it enters, and refuses in the marked code:

  refused                                  where
  ---------------------------------------  ----------------------------
  an exit: how a catch pad ends            the pad's own frame
  a tail call, a BPF_LD_[ABS|IND]: it      the pad's own frame

leaves through an exit on a failed
load
an indirect jump: nothing a compiler the pad's own frame
frontend emits in a pad needs one
a bpf_unwind(), a call to a global the pad and its callees
subprog that might_unwind
a bpf_unwind_resume() outside a pad any program

The first three are refused only in the pad's own frame: a subprog the pad calls may do them and still come back.

---
 include/linux/bpf_verifier.h |  1 +
 kernel/bpf/exception.c       | 59 ++++++++++++++++++++++++++++++++++++
 kernel/bpf/exception.h       |  1 +
 kernel/bpf/states.c          |  3 ++
 kernel/bpf/verifier.c        | 20 +++++++++++-
 5 files changed, 83 insertions(+), 1 deletion(-)
include/linux/bpf_verifier.h +1 -0
index d3740ad20235..6449e4babc60 100644
@@ -339,6 +339,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.
kernel/bpf/exception.c +59 -0

65 lines not on this page · raw message

kernel/bpf/exception.h +1 -0
index 983b9af16a19..1d7fc795619f 100644
@@ -18,5 +18,6 @@ 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);
 
 #endif /* __BPF_EXCEPTION_H */
kernel/bpf/states.c +3 -0
index 4ffa5b7ebf0f..eaf95d6e81bc 100644
@@ -956,6 +956,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],
kernel/bpf/verifier.c +19 -1
index 4ab838ba21eb..59b275bfc949 100644
@@ -15243,8 +15243,13 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 
 	if (bpf_is_unwind_kfunc(insn))
 		return process_bpf_unwind(env, insn_idx_p, NULL);
-	if (bpf_is_unwind_resume_kfunc(insn))
+	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;
 }
@@ -19251,6 +19256,7 @@ static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state)
 			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;
@@ -19326,6 +19332,7 @@ static int process_global_call_unwind(struct bpf_verifier_env *env,
 	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;
@@ -19341,6 +19348,7 @@ static int process_bpf_unwind(struct bpf_verifier_env *env, int *insn_idx,
 		return unwind_frames(env, do_print_state);
 	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;
 }
@@ -19712,6 +19720,16 @@ static int do_check(struct bpf_verifier_env *env)
 			}
 		}
 
+		if (unlikely(env->cleanup_info_cnt)) {
+			err = bpf_exc_check_insn(env, insn);
+			if (error_recoverable_with_nospec(err) && state->speculative) {
+				insn_aux->nospec = true;
+				goto process_bpf_exit;
+			}
+			if (err)
+				return err;
+		}
+
 		if (bpf_is_prune_point(env, env->insn_idx)) {
 			err = bpf_is_state_visited(env, env->insn_idx);
 			if (err < 0)
Signature · 1 line
2.53.0-Meta
author reviewer
#16 lore raw

PATCH v10 8/24 bpf: Refuse a callback that can unwind

In reply to Yonghong Song

A callback is not called by the program but by kernel code, a helper or a kfunc such as bpf_loop(), which the callback returns to and which then returns to the program:

main -> A -> bpf_loop() -> cb -> C C calls bpf_unwind()

Once a later patch makes bpf_unwind() dispatch pads, it rewrites the return address of each of the program's frames and stops at the first frame that is not one, here bpf_loop(): kernel code with its own frame and state, which the walk cannot send cb past. So cb returns into bpf_loop(), which goes on looping and then returns to A after its call, while the verifier follows the unwind from cb straight into A.

Refuse a callback subprog marked might_unwind. The check does not depend on a cleanup table: without one, bpf_unwind() still sends every frame it walks through its epilogue and still stops at bpf_loop(), so the mismatch is the same.

---
 kernel/bpf/exception.c | 9 +++++++++
 kernel/bpf/exception.h | 1 +
 kernel/bpf/verifier.c  | 4 ++++
 3 files changed, 14 insertions(+)
kernel/bpf/exception.c +9 -0
index 21bc1294227c..a0f088e225ac 100644
@@ -141,6 +141,15 @@ int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
 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;
kernel/bpf/exception.h +1 -0
index 9b75e556c82e..983b9af16a19 100644
@@ -17,5 +17,6 @@ int bpf_exc_check_prog(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);
 
 #endif /* __BPF_EXCEPTION_H */
kernel/bpf/verifier.c +4 -0
index 1553c7d5bbdb..4ab838ba21eb 100644
@@ -10997,6 +10997,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",
Signature · 1 line
2.53.0-Meta
author reviewer
#20 lore raw

PATCH v10 10/24 bpf: Do not use a private stack for a program that can unwind

In reply to Yonghong Song

A private stack keeps its frame pointer in %r9 on x86-64, saved and restored around every call. An unwind skips the restore: a frame resumed at its pad then addresses its stack through a stale pointer, and one sent to its epilogue pops its callee-saved registers one slot off.

So force NO_PRIV_STACK for a program that can unwind, with a table or not, on every arch for now.

---
 kernel/bpf/exception.c | 10 ++++++++++
 kernel/bpf/exception.h |  1 +
 kernel/bpf/verifier.c  | 11 +++++++++++
 3 files changed, 22 insertions(+)
kernel/bpf/exception.c +10 -0
index 2b9640099269..f45dd3157f7f 100644
@@ -183,6 +183,16 @@ static void mark_call_sites(struct bpf_verifier_env *env)
 	}
 }
 
+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;
kernel/bpf/exception.h +1 -0
index 1d7fc795619f..dea45c7e4925 100644
@@ -14,6 +14,7 @@ int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,
 		       bpfptr_t uattr);
 void bpf_exc_prepare(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);
kernel/bpf/verifier.c +11 -0
index 59b275bfc949..35013a5d8401 100644
@@ -5801,6 +5801,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);
 
Signature · 1 line
2.53.0-Meta
author reviewer
#28 lore raw

PATCH v10 12/24 bpf: Dispatch cleanup pads by rewriting return addresses

In reply to Yonghong Song

bpf_unwind() now walks the BPF frames through arch_bpf_stack_walk_ra() and rewrites the saved return address of each frame above the one that called it: to the pad where a record covers the call, else to the frame's epilogue. The walk stops after the main function. For the verifier patch's example, main -> A -> B -> C with only A's call to B covered:

  slot                    points into               rewritten to
  ----------------------  ------------------------  ---------------------
  bpf_unwind()'s return   C, after its unwind call  left alone
  C's return              B, after 'call C'         B's epilogue
  B's return              A, after 'call B'         P, A's pad
  A's return              main, after 'call A'      main's epilogue
  main's return           the kernel                left alone

Each frame then just returns: C through the 'r0 = 0; exit' after its bpf_unwind(), B and main through their epilogues, A through its pad P and P's resume.

The walk finds the frames in the calling program, not with bpf_prog_ksym_find(). A running instance holds no reference to its program, so user space can drop the last one, by closing the program's fds and links, while the instance still runs: the kallsyms entries go at once, and only freeing the program waits for the RCU or RCU Tasks Trace grace period. An unwind in between, say in a sleepable program blocked in bpf_copy_from_user(), would find none of its frames, so no pad would run. So bpf_unwind() takes the program's aux as a KF_IMPLICIT_ARGS argument, which keeps its BTF prototype void(void), and matches each return address against aux->func[], or the program itself. To get the implicit argument loaded, adjust_insn_aux_data() moves arg_prog, as it moves cleanup_pad, to the slot the original instruction kept: the unwind call stays first in its patch.

Both kfuncs become callable here. bpf_unwind() is notrace and NOKPROBE:
a tracer hooking its return would leave a trampoline in the slot of the frame that called it, which the walk cannot rewrite.

---
 kernel/bpf/fixups.c  |  2 ++
 kernel/bpf/helpers.c | 67 +++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 68 insertions(+), 1 deletion(-)
kernel/bpf/fixups.c +2 -0
index 1cc025c45ecd..c29e14ffc475 100644
@@ -247,6 +247,8 @@ static void adjust_insn_aux_data(struct bpf_verifier_env *env,
 			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;
 		}
kernel/bpf/helpers.c +66 -1

89 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author reviewer
#23 lore raw

PATCH v10 11/24 bpf: Prepare JITed programs for dispatching cleanup pads

In reply to Yonghong Song

The next patch makes bpf_unwind() rewrite the saved return address of each frame above its caller: to the pad covering the call, else to the frame's epilogue. Every frame then just returns, its epilogue restoring its caller's r6-r9. This patch adds what that relies on:

- Each bpf_unwind() call is followed by 'r0 = 0' and a jump to its pad, or an exit: the walk leaves the calling frame alone.
- A pad's resume lowers to 'r0 = 0; exit'.
- Each JITed function gets a table of its covered calls as native address ranges, looked up by bpf_exc_pad_for_ip(). The main function's table, and its epilogue_ip, go to the outer program.
- Every function the walk can pass needs an epilogue, which x86 emits at a function's first exit. keep_subprog_exits() keeps one through dead code removal, and refuses a function with none.
- arch_bpf_stack_walk_ra() walks the stack handing out each return-address slot. Where an arch has only the weak stub, nothing is dispatched, so any program that can unwind, table or not, is now held to bpf_exc_check_prog().

---
 include/linux/bpf.h          |  30 ++++++++
 include/linux/bpf_verifier.h |   1 +
 include/linux/filter.h       |   2 +
 kernel/bpf/core.c            |   7 ++
 kernel/bpf/exception.c       |  77 ++++++++++++++++++++
 kernel/bpf/exception.h       |   6 ++
 kernel/bpf/fixups.c          | 135 ++++++++++++++++++++++++++++++++++-
 kernel/bpf/verifier.c        |   5 +-
 8 files changed, 261 insertions(+), 2 deletions(-)
include/linux/bpf.h +30 -0
index 54144372281c..7f23f4efde01 100644
@@ -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;
@@ -1922,6 +1950,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
include/linux/bpf_verifier.h +1 -0
index 6449e4babc60..8f67126719fe 100644
@@ -1853,6 +1853,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);
 
include/linux/filter.h +2 -0
index c8ca863e352a..a61a78675d11 100644
@@ -1291,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);
kernel/bpf/core.c +7 -0
index 078bcccaf242..9ed9da581ed5 100644
@@ -293,6 +293,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);
@@ -3528,6 +3529,12 @@ 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;
kernel/bpf/exception.c +77 -0

80 lines not on this page · raw message

kernel/bpf/exception.h +6 -0
index dea45c7e4925..b55ce5c2b9c6 100644
@@ -9,6 +9,10 @@
 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);
@@ -20,5 +24,7 @@ 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 */
kernel/bpf/fixups.c +134 -1

189 lines not on this page · raw message

kernel/bpf/verifier.c +4 -1
index 35013a5d8401..3d9ed6cb15e0 100644
@@ -22928,7 +22928,7 @@ 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) {
+	if (env->cleanup_info_cnt || bpf_prog_may_unwind(env)) {
 		ret = bpf_exc_check_prog(env);
 		if (ret)
 			goto skip_full_check;
@@ -23005,6 +23005,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);
 
Signature · 1 line
2.53.0-Meta
author reviewer
#29 lore raw

PATCH v10 13/24 bpf: Refuse a trampoline that calls a subprog that can unwind

In reply to Yonghong Song

bpf_unwind() walks up the stack rewriting return addresses. It expects every frame up to the main function to be one of the program's own BPF functions, and stops at the first frame that is not. A trampoline attached to a subprog with fexit, fmod_ret or fsession is such a frame:
it calls the subprog, so it sits between the subprog and its caller:

main -> A -> trampoline -> B -> C C calls bpf_unwind()

The walk rewrites the return into B but stops at the trampoline, so B returns through it to A after its call, instead of to A's pad or
epilogue: a path the verifier never walked for an unwind.

Refuse such an attachment to a subprog marked might_unwind, now copied into each function's aux. Nothing else puts a frame between two of a program's frames: fentry leaves none, a trampoline on main is above where the walk stops, freplace is a program of its own whose unwind ends as a normal return to its caller, a callback that can unwind is refused, kprobes and fgraph cannot hook JIT code, and a tail call replaces a frame.

---
 include/linux/bpf.h   |  1 +
 kernel/bpf/fixups.c   |  1 +
 kernel/bpf/verifier.c | 17 +++++++++++++++++
 3 files changed, 19 insertions(+)
include/linux/bpf.h +1 -0
index 7f23f4efde01..1b3b6ee05c09 100644
@@ -1910,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;
kernel/bpf/fixups.c +1 -0
index c29e14ffc475..6f719e1b083e 100644
@@ -1462,6 +1462,7 @@ 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;
kernel/bpf/verifier.c +17 -0
index 3d9ed6cb15e0..7354b8cc8b36 100644
@@ -21600,6 +21600,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) {
Signature · 1 line
2.53.0-Meta
author reviewer
#33 lore raw

PATCH v10 15/24 bpf, arm64: Dispatch exception cleanup pads at run time

In reply to Yonghong Song

Add what bpf_unwind() relies on to send each frame of a program to its landing pad or its epilogue on arm64, as the previous patch does for x86-64:

- arch_bpf_stack_walk_ra(): walks the frame records with the kernel unwinder, handing each return address to the consumer and storing a new one back into the record it was read from. The first frame, whose return into bpf_unwind() comes from the walk's own record, is skipped.
- With CONFIG_ARM64_PTR_AUTH_KERNEL and a CPU that supports address authentication, the new address is signed as the BPF prologue signs the link register, with PACIASP and the record + 16 as modifier.
- Once the image is final, the JIT fills in the native cleanup table and records each function's epilogue address in aux->epilogue_ip, where an unwind sends a frame with no pad.
- bpf_jit_supports_cleanup_pads() says yes, also with a shadow call
stack: only JITed frames' records are written, and JITed code keeps no x18 copy of its return address.

A pad needs no BTI: it is only reached as a return address.

---
 arch/arm64/kernel/stacktrace.c | 74 ++++++++++++++++++++++++++++++++++
 arch/arm64/net/bpf_jit_comp.c  | 16 ++++++++
 2 files changed, 90 insertions(+)
arch/arm64/kernel/stacktrace.c +74 -0
index 3ebcf8c53fb0..56d1310eca32 100644
@@ -445,6 +445,80 @@ 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;
+};
+
+static u64 bpf_unwind_sign_ra(u64 ra, u64 modifier)
+{
+	asm volatile(ARM64_ASM_PREAMBLE
+		     ".arch_extension pauth\n"
+		     "	pacia %0, %1"
+		     : "+r" (ra) : "r" (modifier));
+	return ra;
+}
+
+/* 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) {
arch/arm64/net/bpf_jit_comp.c +16 -0
index 08725cde0c5a..11e94e3bf859 100644
@@ -2423,6 +2423,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;
Signature · 1 line
2.53.0-Meta
author reviewer
#30 lore raw

PATCH v10 14/24 bpf, x86: Dispatch exception cleanup pads at run time

In reply to Yonghong Song

Add what bpf_unwind() relies on to send each frame of a program to its landing pad or its epilogue on x86-64:

- arch_bpf_stack_walk_ra(): the ORC walk, handing out each frame's return address, state.ip, and the slot it was read from, unwind_get_return_address_ptr(). A BPF frame is unwound through its frame pointer, which the JIT always sets up.
- aux->epilogue_ip: the address of the one epilogue the JIT emits per function, at the offset it keeps as ctx->cleanup_addr.
- Once the image is final, the JIT fills in the native cleanup table.
- bpf_jit_supports_cleanup_pads() says yes with CONFIG_UNWINDER_ORC, as bpf_jit_supports_exceptions() does.

A pad needs no ENDBR: it is only reached as a return address.

---
 arch/x86/net/bpf_jit_comp.c | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
arch/x86/net/bpf_jit_comp.c +36 -0
index 083fcd6cf15b..d434871b5a11 100644
@@ -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>
@@ -3279,6 +3280,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))
@@ -4462,6 +4465,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
@@ -4600,6 +4610,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;
@@ -4621,6 +4636,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)
 {
Signature · 1 line
2.53.0-Meta
author reviewer
#37 lore raw

PATCH v10 17/24 libbpf: Add cleanup_info to bpf_prog_load_opts

In reply to Yonghong Song

Let a caller hand the kernel an exception cleanup table:
bpf_prog_load_opts grows cleanup_info_cnt, cleanup_info and cleanup_info_rec_size, which bpf_prog_load() passes on to BPF_PROG_LOAD. cleanup_info_cnt comes first to fill the hole after fd_array_cnt.

---
 tools/lib/bpf/bpf.c |  6 +++++-
 tools/lib/bpf/bpf.h | 10 +++++++++-
 2 files changed, 14 insertions(+), 2 deletions(-)
tools/lib/bpf/bpf.c +5 -1
index b49822d212ae..b4031f62bdee 100644
@@ -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;
tools/lib/bpf/bpf.h +9 -1
index 826d9cc9ab65..64699e0e4e1a 100644
@@ -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,
Signature · 1 line
2.53.0-Meta
author reviewer
#36 lore raw

PATCH v10 16/24 libbpf: Resolve the compiler's _Unwind_Resume to the kernel's kfunc

In reply to Yonghong Song

LLVM ends a cleanup landing pad with a call to _Unwind_Resume, the unwind ABI's name for carrying an unwind on. The kernel's kfunc is
bpf_unwind_resume: _Unwind_Resume in the kernel's own symbol table, for a function whose body never runs, would only confuse.

The compiler emits the call but no declaration, and libbpf refuses an extern it has no BTF for, so the program declares it itself (extern void _Unwind_Resume(void *) __ksym;), as a language runtime has to. libbpf only translates the name, both where it resolves the kfunc itself and where it records the name for a light skeleton's loader to resolve.

---
 tools/lib/bpf/libbpf.c | 45 ++++++++++++++++++++++++++++++++----------
 1 file changed, 35 insertions(+), 10 deletions(-)
tools/lib/bpf/libbpf.c +35 -10
index cb09ded90773..5f41d3ba2822 100644
@@ -9187,6 +9187,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 +9212,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 +9221,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 = {
@@ -9684,17 +9702,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;
 	}
 
Signature · 1 line
2.53.0-Meta
author reviewer
#39 lore raw

PATCH v10 18/24 libbpf: Collect .bpf_cleanup records and pass them to the kernel

In reply to Yonghong Song

Parse the compiler-emitted .bpf_cleanup section and hand the table to BPF_PROG_LOAD:

- At open, each record field, a byte offset into a code section, is resolved through its .rel.bpf_cleanup relocation: R_BPF_64_NODYLD32 from LLVM or R_BPF_64_ABS32 from GNU as.
- At relocation, once a main program's subprogs are appended, the records in the main program and in those subprogs get final instruction indices and are sorted by begin_off, as the kernel wants. A record in code no function claims belongs to a weak function the static linker kept after overriding it, and is skipped, as that code's relocations are.
- At load, the table goes through the bpf_prog_load() options, from bpf_object_load_prog() and from bpf_program__clone(), the path veristat uses.

---
 tools/lib/bpf/libbpf.c          | 285 +++++++++++++++++++++++++++++++-
 tools/lib/bpf/libbpf_internal.h |   3 +
 2 files changed, 286 insertions(+), 2 deletions(-)
tools/lib/bpf/libbpf.c +283 -2
index 5f41d3ba2822..a0e307a4aa5a 100644
@@ -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,217 @@ 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 __u32 *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;
+
+		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.
+		 */
+		off = (native ? vals[slot] : bswap_32(vals[slot])) + 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 +8446,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 +8817,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 +9115,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 */
@@ -9460,6 +9724,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;
 
@@ -10597,6 +10862,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);
@@ -11006,6 +11274,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);
tools/lib/bpf/libbpf_internal.h +3 -0
index 546f65b95cf4..f1630f03d5f5 100644
@@ -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
Signature · 1 line
2.53.0-Meta
author reviewer
#41 lore raw

PATCH v10 20/24 libbpf: Let the static linker carry .bpf_cleanup relocations

In reply to Yonghong Song

Each field of a .bpf_cleanup record is a byte offset into a code
section: a 32-bit relocation against that section's symbol, with the offset as the implicit addend. The linker refuses it: it does not know LLVM's R_BPF_64_NODYLD32, and from a non-executable section it takes a relocation against a section symbol only as a 64-bit pointer to code.

Take it in both spellings, R_BPF_64_NODYLD32 from LLVM and R_BPF_64_ABS32 from GNU as, adding the code section's new start to the stored byte offset. Since any non-executable section can now reach that path, it checks itself what the old refusal covered: that the target has data, and that r_offset is aligned and in bounds.

---
 tools/lib/bpf/linker.c | 37 ++++++++++++++++++++++++++++++++++++-
 1 file changed, 36 insertions(+), 1 deletion(-)
tools/lib/bpf/linker.c +36 -1
index f3f71c452f00..c607f51e3cb4 100644
@@ -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,39 @@ 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.
+					 *
+					 * r_offset is checked only for an
+					 * executable section, and SHT_NOBITS
+					 * has no raw_data, so bound it here --
+					 * subtracting, 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;
Signature · 1 line
2.53.0-Meta
author reviewer
#40 lore raw

PATCH v10 19/24 libbpf: Carry the exception cleanup table through the light skeleton

In reply to Yonghong Song

A light skeleton does not call bpf_prog_load(): its loader program builds the attr itself, so a program loaded this way reached the kernel without its table and was refused with "unreachable insn". Carry the table the way func_info and line_info are carried: the records in the loader's blob, the count and record size in the attr, and a relocation for the blob's address.

Only a program with records grows the attr to cleanup_info_cnt, so light skeletons without them are unchanged.

---
 tools/lib/bpf/gen_loader.c      | 29 ++++++++++++++++++++++++++---
 tools/lib/bpf/libbpf_internal.h |  7 +++++++
 2 files changed, 33 insertions(+), 3 deletions(-)
tools/lib/bpf/gen_loader.c +26 -3
index 251392aa8b41..0aa87ea685e7 100644
@@ -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 there is no blob of them to point the attr at */
+	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);
 
tools/lib/bpf/libbpf_internal.h +7 -0
index f1630f03d5f5..9d341839ca74 100644
@@ -572,6 +572,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,
Signature · 1 line
2.53.0-Meta
author reviewer
#42 lore raw

PATCH v10 21/24 selftests/bpf: Add end-to-end and negative .bpf_cleanup exception tests

In reply to Yonghong Song

C has no unwinding, so the frames that own a resource are written in inline assembly, spelling out what a frontend emits: a call site between two labels, a landing pad, and a .bpf_cleanup record tying them together.

The end-to-end test runs a five-frame call chain whose frames hold an RCU read lock or have preemption disabled, unwinds it from different frames, and checks which landing pads ran. It also checks that an fentry program can attach to a subprog an unwind passes through and an fexit program cannot.

The negative tests cover the shapes the kernel refuses: catch pads, unsupported instructions or a second unwind in a pad, resumes outside a pad, callbacks that can unwind, misplaced records, stale stack slots trusted by a pad, and resources an unwind leaves held or drops twice.

The test skips where the JIT cannot dispatch landing pads.

---
 .../selftests/bpf/exceptions_cleanup.h        |  27 +
 .../bpf/prog_tests/exceptions_cleanup.c       | 116 +++
 .../selftests/bpf/progs/exceptions_cleanup.c  | 160 +++
 .../bpf/progs/exceptions_cleanup_fail.c       | 947 ++++++++++++++++++
 .../bpf/progs/exceptions_cleanup_tracing.c    |  23 +
 5 files changed, 1273 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/exceptions_cleanup.h
 create mode 100644 tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup.c
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c
tools/testing/selftests/bpf/exceptions_cleanup.h new file +27 -0
new file mode 100644
index 000000000000..96effd2c1361
@@ -0,0 +1,27 @@
+/* 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
+
+#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__ */
tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c new file +116 -0

116 lines not on this page · raw message

tools/testing/selftests/bpf/progs/exceptions_cleanup.c new file +160 -0

160 lines not on this page · raw message

tools/testing/selftests/bpf/progs/exceptions_cleanup_fail.c new file +947 -0

947 lines not on this page · raw message

tools/testing/selftests/bpf/progs/exceptions_cleanup_tracing.c new file +23 -0
new file mode 100644
index 000000000000..6216b09d4472
@@ -0,0 +1,23 @@
+// 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;
+}
+
+SEC("?fentry")
+int BPF_PROG(fentry_unwinding_subprog)
+{
+	return 0;
+}
+
+char _license[] SEC("license") = "GPL";
Signature · 1 line
2.53.0-Meta
author reviewer
#43 lore raw

PATCH v10 22/24 selftests/bpf: Add __set_global() and __ret_global() test tags

In reply to Yonghong Song

A test that looks at a program's state after it ran needs a driver of its own, though the loader already runs programs for __retval(). What is missing is reaching their globals:

- __set_global(var, value) writes one before the run, __ret_global(var, value) checks one after it. Both make the loader run the program; without __retval() it must return 0. Each may be given several times, up to MAX_GLOBAL_VARS.
- The variable is found the way veristat finds one, in ".bss" or ".data", and must be a four or eight byte int or enum.
- A value is held to its variable's range and narrowed to its width, signedness taken from BTF as in veristat, so a negative literal means the same to both tags.
- A value may be a '|' separated list, so a bitmask reads as it is written in the program.

---
 tools/testing/selftests/bpf/progs/bpf_misc.h |  12 +
 tools/testing/selftests/bpf/test_loader.c    | 319 ++++++++++++++++++-
 2 files changed, 330 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/progs/bpf_misc.h +12 -0
index f3dbc3b59bff..a80798a8f28f 100644
@@ -103,6 +103,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.
@@ -161,6 +171,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)
tools/testing/selftests/bpf/test_loader.c +318 -1

379 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author reviewer
#44 lore raw

PATCH v10 23/24 selftests/bpf: Cover more accepted .bpf_cleanup exception shapes

In reply to Yonghong Song

Add the shapes the end-to-end test does not reach:

- a pad reading its frame's callee-saved registers
- a region ending on a 16-byte instruction
- a pad ending in _Unwind_Resume rather than bpf_unwind_resume
- a pad whose first instruction is a nop
- a pad indexing its frame by a register set before the call
- two pads with an uncovered frame between them
- precision chains from a pad back across the resume that led to it, and back into the frame the unwind left
- a frame above an unwind that never returns, whose kept exit is not its last instruction
- a region covering an indirect call, and a subprog calling an unwinding one through a pointer it was handed
- a frame holding a reference across a covered call, released by its pad
- a pad reading a slot its static or global callee wrote before unwinding
- unwinds out of a global subprog called with no record, one returning in R0:R2 among them
- a reference moved into a callee, as rustc does for a by-value argument
- a bpf_unwind() inside a loop, in a subprog and in main
- a frame's own pad finding r0 zero after its bpf_unwind()
- an unwind reaching main's exit in a program type that checks r0, out of a static callee and out of a global call
- a pad touching a global of each width and sign a tag can name
- two speculative walks, into a pad and to an exit in one, loaded without CAP_PERFMON; each checks the translated program for the barrier, so it cannot pass without the walk

Each shape that runs is driven by __set_global(), __retval() and __ret_global() through RUN_TESTS().

---
 .../selftests/bpf/exceptions_cleanup.h        |   20 +
 .../bpf/prog_tests/exceptions_cleanup.c       |    2 +
 .../bpf/progs/exceptions_cleanup_shapes.c     | 1141 +++++++++++++++++
 3 files changed, 1163 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c
tools/testing/selftests/bpf/exceptions_cleanup.h +20 -0
index 96effd2c1361..caa8e7b0cfb0 100644
@@ -10,6 +10,26 @@
 #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_HELD_REF		0x400
+#define RAN_CALLEE_WRITE	0x800
+#define RAN_CALLEE_OFFSET	0x1000
+#define RAN_GLOBAL_WRITE	0x2000
+#define RAN_THROUGH_GLOBAL	0x4000
+#define RAN_OWN_PAD_R0		0x8000
+#define RAN_PAIR_GLOBAL		0x10000
+#define RAN_MOVE		0x20000
+
 #define CLEANUP_REC(begin, end, landing_pad)			\
 	".pushsection .bpf_cleanup,\"a\",@progbits;"		\
 	".long " begin ";"					\
tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c +2 -0
index 3e46e17ef9b4..7c5dffd4b861 100644
@@ -4,6 +4,7 @@
 #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"
 
 /* foo3 unwound: every frame that has a pad ran it. */
@@ -113,4 +114,5 @@ void test_exceptions_cleanup(void)
 	exceptions_cleanup__destroy(skel);
 
 	RUN_TESTS(exceptions_cleanup_fail);
+	RUN_TESTS(exceptions_cleanup_shapes);
 }
tools/testing/selftests/bpf/progs/exceptions_cleanup_shapes.c new file +1141 -0

1,141 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author reviewer
#45 lore raw

PATCH v10 24/24 selftests/bpf: Load an exception cleanup program from a light skeleton

In reply to Yonghong Song

A light skeleton loads a program by a path of its own: its loader program builds the attr and resolves kfunc names when it runs. Build progs/exceptions_cleanup.c as a light skeleton too, and run the case in which every pad runs: a table that lost records or came out at the wrong offsets would fail to load, or run the wrong pads.

---
 tools/testing/selftests/bpf/Makefile.skel     |  2 +-
 .../bpf/prog_tests/exceptions_cleanup.c       | 31 +++++++++++++++++++
 2 files changed, 32 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/Makefile.skel +1 -1
index 06e297a17156..d9cbe8ac85b7 100644
@@ -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
tools/testing/selftests/bpf/prog_tests/exceptions_cleanup.c +31 -0
index 7c5dffd4b861..1493c3efa599 100644
@@ -6,6 +6,7 @@
 #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 \
@@ -63,6 +64,33 @@ static int load_tracer(struct exceptions_cleanup *tgt, bool fexit)
 	return err;
 }
 
+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] = {};
@@ -113,6 +141,9 @@ void test_exceptions_cleanup(void)
 
 	exceptions_cleanup__destroy(skel);
 
+	if (test__start_subtest("light_skeleton"))
+		test_light_skeleton();
+
 	RUN_TESTS(exceptions_cleanup_fail);
 	RUN_TESTS(exceptions_cleanup_shapes);
 }
Signature · 1 line
2.53.0-Meta
#38 lore raw

Re: [PATCH bpf-next v10 17/24] libbpf: Add cleanup_info to bpf_prog_load_opts

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] bpf: multi-line comment style violation in bpf.h --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] bpf: multi-line comment style violation in bpf.h
--

commit 2303147a5a35e813efcbbbd93de02e9883d03746
Author: Yonghong Song <[email protected]>

libbpf: Add cleanup_info to bpf_prog_load_opts

This commit extends struct bpf_prog_load_opts by adding cleanup_info, cleanup_info_cnt, and cleanup_info_rec_size fields. This allows a caller to pass an exception cleanup table to the kernel via bpf_prog_load.

tools/lib/bpf/bpf.h struct bpf_prog_load_opts { · line 135

Quoted 13 lines
tools/lib/bpf/bpf.h +5 -0
index 826d9cc9ab65d..64699e0e4e1a8 100644
@@ -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
+	 */

[Severity: Low]
This isn't a functional bug, but does this multi-line comment in struct bpf_prog_load_opts follow the preferred BPF subsystem style?

The BPF subsystem style guide mandates that all multi-line comments should have the opening /* on its own line, with the comment text starting on the subsequent line.

Quoted 7 lines
tools/lib/bpf/bpf.h +4 -1
+	__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
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
#5 lore raw

Re: [PATCH bpf-next v10 04/24] bpf: Keep a call site's landing pad in insn_aux_data, add lookups

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf: adjust_insn_aux_data fails to shift cleanup_pad for BPF_PATCH_MOVE_TARGET --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: adjust_insn_aux_data fails to shift cleanup_pad for BPF_PATCH_MOVE_TARGET --

commit 8654da066c194611f7e2de5fef00da7ac62a0070
Author: Yonghong Song <[email protected]>

bpf: Keep a call site's landing pad in insn_aux_data, add lookups

This commit tracks a call site's landing pad in insn_aux_data as cleanup_pad. It updates adjust_insn_aux_data(), verifier_remove_insns(), and bpf_opt_remove_nops() to keep this data in sync when instructions are patched or removed.

Quoted 4 lines
kernel/bpf/fixups.c +0 -0
index 206cc9a614a95..64baee1a37e60 100644

[ ... ]

Quoted 5 lines
kernel/bpf/fixups.c +1 -0
@@ -244,11 +244,18 @@ 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;

kernel/bpf/fixups.c static void adjust_insn_aux_data(struct bpf_verifier_env *env, · line 257

Quoted 10 lines
kernel/bpf/fixups.c +5 -0
+			data[off + cnt - 1].cleanup_pad = 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;

[Severity: High]
Does this check properly account for the BPF_PATCH_MOVE_TARGET patch mode?

When bpf_patch_insn_data() is called with BPF_PATCH_MOVE_TARGET (for example, when inserting a prologue), the original instruction is shifted to the end of the newly inserted sequence. If a landing pad points exactly to the patched instruction:

    data[i].cleanup_pad == off + 1

This condition would evaluate to false, leaving the cleanup_pad unadjusted.

As a result, if a subprogram with a landing pad at its first instruction receives a prologue, wouldn't the unwinder incorrectly jump to the prologue instead of the original instruction?

Could this lead to stack or frame pointer corruption by re-executing prologue stack setups during unwinding? Other locations handling jumps typically use a ternary to handle this, such as checking if it is greater than:

    (mode == BPF_PATCH_MOVE_TARGET) ? off : off + 1
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#34 lore raw

Re: [PATCH bpf-next v10 15/24] bpf, arm64: Dispatch exception cleanup pads at run time

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] arm64/bpf: PAC modifier mismatch for bpf_throw's C frame causes FPAC panic --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] arm64/bpf: PAC modifier mismatch for bpf_throw's C frame causes FPAC panic --

commit 2f751c03b321c9d53d97196968f653cf6c3fa289
Author: Yonghong Song <[email protected]>

bpf, arm64: Dispatch exception cleanup pads at run time

This commit adds arm64 support for unwinding BPF frames and redirecting their return addresses to cleanup pads. It signs the modified return addresses using PAC when address authentication is enabled.

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

[ ... ]

Quoted 6 lines
arch/arm64/kernel/stacktrace.c +6 -0
+/* 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;
+
+	/*

arch/arm64/kernel/stacktrace.c noinline noinstr void arch_bpf_stack_walk(bool (*consume_entry)(void *cookie, u6 · line 479

Quoted 10 lines
arch/arm64/kernel/stacktrace.c +10 -0
+	 * 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));

[Severity: High]
Will this hardcoded PAC modifier cause an FPAC panic when returning from bpf_throw()?

The unwinder uses bpf_unwind_store_ra() to redirect the return address for the first BPF frame. The caller of this first BPF frame is the C function bpf_throw().

While record + sizeof(struct frame_record) correctly assumes a strict BPF JIT prologue where the entry SP is FP + 16, bpf_throw() is a compiled C function. Its actual frame size is compiler-dependent and may be larger than 16 bytes due to local variables.

When bpf_throw() returns, its epilogue will authenticate the return address using its actual entry SP. If we sign it here using FP + 16 instead of the actual entry SP, could authentication fail and trigger a kernel panic on PAC-enabled kernels?

Quoted 2 lines
arch/arm64/kernel/stacktrace.c +2 -0
+	WRITE_ONCE(rec->lr, ra);
+}

[ ... ]

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

Re: [PATCH bpf-next v10 14/24] bpf, x86: Dispatch exception cleanup pads at run time

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf: Exception unwinder cleanup pad executes in caller's stack frame context --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: Exception unwinder cleanup pad executes in caller's stack frame context --

commit 9d03eddc4bc6be397e72d866390a80929337af59
Author: Yonghong Song <[email protected]>

bpf, x86: Dispatch exception cleanup pads at run time

Add what bpf_unwind() relies on to send each frame of a program to its landing pad or its epilogue on x86-64. This includes arch_bpf_stack_walk_ra(), aux->epilogue_ip assignment, and bpf_exc_fill_native_ranges() call.

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +0 -0
index 083fcd6cf15b7..d434871b5a11c 100644

[ ... ]

Quoted 15 lines
arch/x86/net/bpf_jit_comp.c +2 -0
@@ -3279,6 +3280,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))
arch/x86/net/bpf_jit_comp.c +0 -0
 					return -EINVAL;
 			}
 			/* Deallocate outgoing args 7+ area. */
 			emit_add_rsp(&prog, outgoing_rsp);
 			if (bpf_prog->aux->exception_boundary) {
 				pop_callee_regs(&prog, all_callee_regs_used);

arch/x86/net/bpf_jit_comp.c

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +0 -0
 				pop_r12(&prog);
 			} else {
 				pop_callee_regs(&prog, callee_regs_used);
 				if (arena_vm_start)
 					pop_r12(&prog);
 			}
 			EMIT1(0xC9);         /* leave */
 			bpf_prog->aux->ksym.fp_end = prog - temp;
 
 			emit_return(&prog, image + addrs[i - 1] + (prog - temp));

[Severity: High]
Does this execute the cleanup pad in the wrong stack frame context?

During exception unwinding, arch_bpf_stack_walk_ra() walks the stack and yields the return address pointer (ra) for the current frame N, which points to the instruction in frame N-1.

In bpf_unwind_rewrite(), *ra is overwritten with the address of frame N's cleanup pad or epilogue_ip:

kernel/bpf/helpers.c:bpf_unwind_rewrite() {
    ...
    rec = bpf_exc_pad_for_ip(prog, ip);
    *ra = rec ? rec->pad : prog->aux->epilogue_ip;
    ...
}

This forces frame N to jump to its cleanup pad when it returns.

However, the JIT epilogue executes "leave" before "ret". The "leave" instruction completely tears down frame N's stack and restores frame N-1's stack pointer and frame pointer.

The "ret" instruction then pops the modified return address and jumps to frame N's pad. As a result, the pad executes while frame N-1's context is active.

Can this cause any stack accesses inside the pad (using rbp, mapped to r10 in BPF) to incorrectly access frame N-1's stack variables, leading to memory corruption, use-after-free, or garbage reads during cleanup?

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

Re: [PATCH bpf-next v10 05/24] bpf: Mark covered call sites and check a program can take a table

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf: exception landing pad target fails to shift under BPF_PATCH_MOVE_TARGET --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: exception landing pad target fails to shift under BPF_PATCH_MOVE_TARGET --

commit 12354911ea762dbd3bb3462885368e582fd7efd5
Author: Yonghong Song <[email protected]>

bpf: Mark covered call sites and check a program can take a table

bpf_exc_prepare() records the landing pad of every call in a cleanup record's range. bpf_exc_check_prog() refuses offloaded programs, programs without JIT support, and programs with epilogues or exception callbacks.

Quoted 5 lines
kernel/bpf/exception.c +0 -0
index 2fef417dc090f..21bc1294227c1 100644
@@ -141,6 +141,76 @@ int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,

[ ... ]

Quoted 4 lines
kernel/bpf/exception.c +4 -0
+static void mark_call_sites(struct bpf_verifier_env *env)
+{
+	u32 i, j;
+

kernel/bpf/exception.c int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr, · line 172

Quoted 10 lines
kernel/bpf/exception.c +10 -0
+	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;

[Severity: High]
If a landing pad is at the exact start of the program or subprogram (landing_pad_off == 0), how does this interact with BPF_PATCH_MOVE_TARGET when prepending instructions?

Because kernel/bpf/exception.c:bpf_exc_check_info() permits landing_pad_off to be 0 or subprog_start, this structural layout is possible. When it happens, the shift logic in kernel/bpf/fixups.c:adjust_insn_aux_data() uses a strict greater-than condition:

    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;

If cleanup_pad == off + 1 (e.g., when off=0), it doesn't get shifted. But BPF_PATCH_MOVE_TARGET prepends instructions at off=0, such as when gen_prologue is called in kernel/bpf/fixups.c:bpf_convert_ctx_accesses().

Will this leave the unwinder jumping into the newly prepended verifier instructions rather than the program's original first instruction, potentially causing issues like out-of-bounds reads or infinite loops if registers are clobbered?

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

Re: [PATCH bpf-next v10 11/24] bpf: Prepare JITed programs for dispatching cleanup pads

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf: backward jump offsets in bpf_exc_patch_unwind_calls are corrupted by bpf_adj_branches --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: backward jump offsets in bpf_exc_patch_unwind_calls are corrupted by bpf_adj_branches --

commit b2a75ebf7c80cc3231a5eb34881ba1928dafcd3b
Author: Yonghong Song <[email protected]>

bpf: Prepare JITed programs for dispatching cleanup pads

This patch prepares JITed programs to dispatch exception cleanup pads. It updates the verifier to patch bpf_unwind() calls with a sequence that clears r0 and jumps to the exception pad or exits.

Quoted 4 lines
kernel/bpf/fixups.c +0 -0
index 64baee1a37e60..1cc025c45ecda 100644

[ ... ]

Quoted 1 line
kernel/bpf/fixups.c +0 -0
@@ -1733,6 +1805,48 @@ static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off,

[ ... ]

Quoted 21 lines
kernel/bpf/fixups.c +21 -0
+/*
+ * 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;
+

kernel/bpf/fixups.c static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off, · line 1838

Quoted 10 lines
kernel/bpf/fixups.c +10 -0
+		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);

[Severity: High]
Does this manually calculated offset get corrupted if the landing pad is located before the unwind call (pad < call)?

bpf_patch_insn_data() is called immediately after this, which delegates to bpf_adj_branches() to adjust all relative offsets in the program.

When bpf_adj_branches() processes the newly inserted goto instruction, it evaluates it as if it were a shifted original instruction (because curr >= end_new evaluates to true). If the jump is backwards, bpf_adj_branches() might erroneously subtract the insertion delta (2) from the already-correct offset.

Could this result in the jump target being shifted 2 instructions before the actual landing pad, potentially leading to the execution of unintended or unverified bytecode during exception unwinding?

Quoted 10 lines
kernel/bpf/fixups.c +10 -0
+		}
+
+		new_prog = bpf_patch_insn_data(env, call, insn_buf, 3);
+		if (!new_prog)
+			return -ENOMEM;
+		delta += 2;
+		env->prog = new_prog;
+	}
+	return 0;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#12 lore raw

Re: [PATCH bpf-next v10 07/24] bpf: Verify an unwind through landing pads and epilogues

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] bpf: skipped exception pad verification for global subprogs that throw and unwind - [Medium] bpf…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] bpf: skipped exception pad verification for global subprogs that throw and unwind
- [Medium] bpf: Soft lockup in mark_callx_might_unwind() due to O(N^2) instruction traversal --

commit 54596ff7029b639349bb84341497b649e38e027e
Author: Yonghong Song <[email protected]>

bpf: Verify an unwind through landing pads and epilogues

This commit adds verifier support for tracking control flow through unwind landing pads and epilogues. It calculates whether a subprogram might unwind by propagating the might_unwind flag along the CFG, and integrates backtracking through these new paths.

Quoted 4 lines
kernel/bpf/cfg.c +0 -0
@@ -716,6 +753,82 @@

[ ... ]

Quoted 12 lines
kernel/bpf/cfg.c +12 -0
+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;
+

kernel/bpf/cfg.c static int visit_insn(int t, struct bpf_verifier_env *env) · line 774

Quoted 10 lines
kernel/bpf/cfg.c +10 -0
+	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;

[Severity: Medium]
Could this loop cause a CPU soft lockup for very large BPF programs?

The loop iterates up to len times (which can be up to 1 million) and repeatedly calls bpf_find_containing_subprog(), which performs a binary search. Because this propagates upward through the call graph, the do-while loop could execute many times (e.g., up to 256 for the maximum call depth).

Without a cond_resched(), this might stall the CPU in kernel space for an extended period.

[ ... ]

Quoted 5 lines
kernel/bpf/verifier.c +0 -0
@@ -19464,8 +19602,14 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 				cur_func(env)->no_stack_arg_load = true;

kernel/bpf/verifier.c static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) · line 19610

Quoted 10 lines
kernel/bpf/verifier.c +6 -2
 			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;

[Severity: High]
If a global subprogram has the might_throw flag set, check_func_call() simulates the exception exit and returns PROCESS_BPF_EXIT (which is 1).

Because err is positive, does the check here mistakenly return early, bypassing the subsequent call to process_global_call_unwind()?

If the subprogram can both throw and unwind, its landing pad might never be visited by the verifier, potentially leading to a dead code sanitization trap at runtime.

Quoted 5 lines
kernel/bpf/verifier.c +2 -0
+				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);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#21 lore raw

Re: [PATCH bpf-next v10 10/24] bpf: Do not use a private stack for a program that can unwind

In reply to Yonghong Song
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf: bpf_prog_may_unwind misses might_throw, causing private stack corruption --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: bpf_prog_may_unwind misses might_throw, causing private stack corruption --

commit 38438f251d7fce91364c50842e5e55c25b6033f4
Author: Yonghong Song <[email protected]>

bpf: Do not use a private stack for a program that can unwind

This patch aims to prevent BPF programs that can unwind from using a private stack. A private stack keeps its frame pointer in %r9 on x86-64, and an unwind skips the restore, leading to stack addressing issues. The fix forces NO_PRIV_STACK for programs that might unwind.

Quoted 4 lines
kernel/bpf/exception.c +0 -0
index 2b9640099269e..f45dd3157f7fb 100644

[ ... ]

kernel/bpf/exception.c static void mark_call_sites(struct bpf_verifier_env *env) · line 191

Quoted 10 lines
kernel/bpf/exception.c +6 -0
@@ -183,6 +183,16 @@ static void mark_call_sites(struct bpf_verifier_env *env)
 	}
 }
 
+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)

[Severity: High]
Does bpf_prog_may_unwind() miss the might_throw condition?

Since might_unwind and might_throw are tracked separately in bpf_subprog_info, it appears a BPF program using bpf_throw() would bypass this check and still be compiled with a private stack.

Quoted 6 lines
kernel/bpf/exception.c +4 -0
+			return true;
+	return false;
+}
+
 int bpf_exc_check_prog(struct bpf_verifier_env *env)
 {

[ ... ]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 59b275bfc949d..35013a5d84019 100644

[ ... ]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -5801,6 +5801,17 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
 		}
 	}
 

kernel/bpf/verifier.c static int check_max_stack_depth(struct bpf_verifier_env *env) · line 5813

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	/*
+	 * 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;

[Severity: High]
Will this leave programs that throw exceptions vulnerable to stack shifting in check_max_stack_depth()?

If a program uses bpf_throw() and is compiled with a private stack (PRIV_STACK_ADAPTIVE), the x86 JIT pushes the private frame pointer (%r9) before every call.

When bpf_throw() is called, the ORC unwinder calculates the boundary frame's stack pointer as the value of %rsp before the call, which includes the un-popped %r9 (shifting it by -8 bytes). Then bpf_exception_cb() uses this value to restore the boundary frame's callee-saved registers.

Because of the unaccounted %r9 push, the stack pointer is off by 8 bytes. Could this cause pop_callee_regs to pop the stale %r9 into a callee-saved register, shift all other registers by one slot, and ultimately corrupt the callee-saved registers?

Quoted 4 lines
kernel/bpf/verifier.c +1 -0
+
 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
 
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#26 lore raw

Re: [PATCH bpf-next v10 11/24] bpf: Prepare JITed programs for dispatching cleanup pads

In reply to Yonghong Song
TL;DR: keep_subprog_exits() may mark an exit seen in a never-entered subprog, so dead-code removal can miscompute subprog starts and drop main's exit, letting JITed main fall off its image end.
Quoted 1 line

bpf: Prepare JITed programs for dispatching cleanup pads

TL;DR: keep_subprog_exits() may mark an exit seen in a never-entered subprog, so dead-code removal can miscompute subprog starts and drop main's exit, letting JITed main fall off its image end.

Quoted 4 lines
kernel/bpf/fixups.c +0 -0
index 64baee1a37e6..1cc025c45ecd 100644

[ ... ]

Quoted 9 lines
kernel/bpf/fixups.c +5 -0
@@ -715,6 +716,32 @@ static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env)
 	}
 }
 
+static int keep_subprog_exits(struct bpf_verifier_env *env)
+{
+	u32 i, j;
+
+	for (i = 0; i < env->subprog_cnt; i++) {

kernel/bpf/fixups.c static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env) · line 733

Quoted 10 lines
kernel/bpf/fixups.c +10 -0
+		bool found = false;
+		u32 start;
+
+		if (!env->subprog_info[i].might_unwind)
+			continue;
+		start = env->subprog_info[i].start;
+		for (j = env->subprog_info[i + 1].start; j-- > start; ) {
+			if (env->prog->insnsi[j].code != (BPF_JMP | BPF_EXIT))
+				continue;
+			env->insn_aux_data[j].seen = env->pass_cnt;

Can this mark an exit as seen in a subprog the verifier never entered?

might_unwind is set statically while walking the control flow, so it is also set on a static subprog that is only called from a path the verifier proves dead, for example one guarded by a .rodata constant or a constant register. None of that subprog's instructions are seen, but the loop above still marks its last exit as seen.

Before this patch a live subprog was always entered at its first instruction, and adjust_subprog_starts_after_remove() relies on that. Now the first instruction of a subprog can be dead while a later exit is kept. bpf_opt_remove_dead_code() removes each contiguous run of unseen instructions even when the run crosses a subprog boundary, so one run can cover the end of the previous code and the head of this subprog, and stop at the kept exit.

Here is a trace (privileged loader, with bpf_unwind registered and the x86 cleanup pad support from later patches in the series):

main: 0: r1 = 0

         1: if r1 == 0 goto +2   ; always taken
         2: call P               ; dead
         3: call A               ; dead
         4: r0 = 0
         5: exit
  P:     6: r0 = 1               ; static, never entered, no unwind
         7: exit

A: 8: call bpf_unwind ; static, never entered, might_unwind
9: r0 = 0
10: exit ; kept by keep_subprog_exits()

The first dead run, [2,3], is removed correctly, leaving P.start = 4, A.start = 6 and the fake subprog at 9.

The next dead run is [4..7]: all of P plus A's call and 'r0 = 0'. It stops at A's kept exit, so off = 4 and cnt = 4.

In adjust_subprog_starts_after_remove(), i is P. The j loop reaches the fake subprog, whose start (9) is not off + cnt (8), so:

	if (env->subprog_info[j].start != off + cnt)
		j--;

gives j = A. Since j > i, P's entry is dropped and A moves into its slot, and then the start adjustment gives A.start = 6 - 4 = 2. The correct value is 4.

The program is now:

0: r1 = 0
1: ja +0
2: r0 = 0
3: exit
4: exit

with subprog starts main = 0 and A = 2, so main has lost its own 'r0 = 0; exit'. After bpf_opt_remove_nops() main is just [r1 = 0]. jit_subprogs() then JITs func[0] with no exit, so it has no epilogue and no ret, and the first run of the program falls off the end of main's image. If main had kept a jump into the reassigned tail, do_jit() would also read addrs[] past func[0]->len.

The same miscalculation happens when P is a live subprog with only a dead tail (the i == j case, where start != off).

Would it make sense to skip subprogs that were never entered, since they can never be on the stack during an unwind, for example:

	if (!env->insn_aux_data[start].seen)
		continue;

Alternatively, could adjust_subprog_starts_after_remove() set the start of a partially removed subprog to off?

None of the later commits in this series appear to change keep_subprog_exits() or adjust_subprog_starts_after_remove().

kernel/bpf/fixups.c static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env) · line 744

Quoted 11 lines
kernel/bpf/fixups.c +11 -0
+			found = true;
+			break;
+		}
+		if (!found) {
+			verbose(env, "subprog %u can be unwound through but has no exit\n", i);
+			return -EINVAL;
+		}
+	}
+	return 0;
+}
+

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/37884246994

#14 lore raw

Re: [PATCH bpf-next v10 07/24] bpf: Verify an unwind through landing pads and epilogues

In reply to Yonghong Song
TL;DR: Nit only: unwind_frames() sets r0 to zero in two calls; __mark_reg_const_zero() could do it in one, as process_iter_next_call() does, and the explanatory comment could go. No bug.
Quoted 1 line

bpf: Verify an unwind through landing pads and epilogues

TL;DR: Nit only: unwind_frames() sets r0 to zero in two calls; __mark_reg_const_zero() could do it in one, as process_iter_next_call() does, and the explanatory comment could go. No bug.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 0cf30220b777..1553c7d5bbdb 100644

[ ... ]

Quoted 1 line
kernel/bpf/verifier.c +0 -0
@@ -19203,6 +19212,135 @@ enum {

[ ... ]

Quoted 2 lines
kernel/bpf/verifier.c +2 -0
+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state)
+{

[ ... ]

kernel/bpf/verifier.c enum { · line 19288

Quoted 8 lines
kernel/bpf/verifier.c +8 -0
+	/*
+	 * The call clobbered r1-r5, and r0 holds the zero the fixups put
+	 * there. Mark r0 unknown first: the known-zero helper keeps a NOT_INIT
+	 * type.
+	 */
+	clear_caller_saved_regs(env, cur_regs(env));
+	mark_reg_unknown(env, cur_regs(env), BPF_REG_0);
+	mark_reg_known_zero(env, cur_regs(env), BPF_REG_0);

this isn't a bug, but could this use __mark_reg_const_zero(env, &cur_regs(env)[BPF_REG_0]), as process_iter_next_call() does, and drop the part of the comment that explains why two calls are needed?

unwind_frames() sets r0 to a scalar zero in two steps here:
mark_reg_unknown() sets the SCALAR_VALUE type, then mark_reg_known_zero() sets the value. __mark_reg_const_zero() already sets the type to SCALAR_VALUE, the value to known zero, and precise to !bpf_capable in one call. process_iter_next_call() and check_kfunc_call() both use it for r0 this way.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/37884246994

author reviewer
#6 lore raw

Re: [PATCH bpf-next v10 04/24] bpf: Keep a call site's landing pad in insn_aux_data, add lookups

In reply to [email protected]
Quoted 51 lines · On 10/9/26 6:28 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: adjust_insn_aux_data fails to shift cleanup_pad for BPF_PATCH_MOVE_TARGET --

commit 8654da066c194611f7e2de5fef00da7ac62a0070
Author: Yonghong Song <[email protected]>

bpf: Keep a call site's landing pad in insn_aux_data, add lookups

This commit tracks a call site's landing pad in insn_aux_data as cleanup_pad. It updates adjust_insn_aux_data(), verifier_remove_insns(), and bpf_opt_remove_nops() to keep this data in sync when instructions are patched or removed.

Quoted 4 lines
kernel/bpf/fixups.c +0 -0
index 206cc9a614a95..64baee1a37e60 100644

[ ... ]

Quoted 5 lines
kernel/bpf/fixups.c +1 -0
@@ -244,11 +244,18 @@ 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;

kernel/bpf/fixups.c static void adjust_insn_aux_data(struct bpf_verifier_env *env, · line 257

Quoted 10 lines
kernel/bpf/fixups.c +5 -0
+			data[off + cnt - 1].cleanup_pad = 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;

[Severity: High]
Does this check properly account for the BPF_PATCH_MOVE_TARGET patch mode?

When bpf_patch_insn_data() is called with BPF_PATCH_MOVE_TARGET (for example, when inserting a prologue), the original instruction is shifted to the end of the newly inserted sequence. If a landing pad points exactly to the patched instruction:

     data[i].cleanup_pad == off + 1

This condition would evaluate to false, leaving the cleanup_pad unadjusted.

As a result, if a subprogram with a landing pad at its first instruction receives a prologue, wouldn't the unwinder incorrectly jump to the prologue instead of the original instruction?

Quoted 5 lines

Could this lead to stack or frame pointer corruption by re-executing prologue stack setups during unwinding? Other locations handling jumps typically use a ternary to handle this, such as checking if it is greater than:

     (mode == BPF_PATCH_MOVE_TARGET) ? off : off + 1

Looks like there are no new change with BPF_PATCH_MOVE_TARGET, so I think we do not need to do the above. The below is the comment in v9:

====

Okay, commit "bpf: Retarget indirect jump targets across prologue prepends" introduced BPF_PATCH_MOVE_TARGET and merged last Friday. It solved three cases for ops->gen_epilogue, ops->gen_prologue || env->seen_direct_write, and stack slots for subprogs. ops->gen_epilogue has been rejected in patch 5. We cannot allow ops->gen_epilogue since it may silently exit.
For other cases in "bpf: Retarget indirect jump targets across prologue prepends", The above commit should already handle this.

For the other two, cleanup_pad == off + 1 cannot happen, because MOVE only patches an entry insn and a landing pad cannot start at insn 0: the entry is always walked outside a pad first, so reaching it again from an unwind fails bpf_exc_check_insn() with "insn %u runs both inside and outside a landing pad". Pads after off are shifted by the existing > off + 1, and a covered call at off moves with its insn_aux_data.

====

author reviewer
#9 lore raw

Re: [PATCH bpf-next v10 05/24] bpf: Mark covered call sites and check a program can take a table

In reply to [email protected]
Quoted 48 lines · On 10/9/26 6:34 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: exception landing pad target fails to shift under BPF_PATCH_MOVE_TARGET --

commit 12354911ea762dbd3bb3462885368e582fd7efd5
Author: Yonghong Song <[email protected]>

bpf: Mark covered call sites and check a program can take a table

bpf_exc_prepare() records the landing pad of every call in a cleanup record's range. bpf_exc_check_prog() refuses offloaded programs, programs without JIT support, and programs with epilogues or exception callbacks.

Quoted 5 lines
kernel/bpf/exception.c +0 -0
index 2fef417dc090f..21bc1294227c1 100644
@@ -141,6 +141,76 @@ int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr,

[ ... ]

Quoted 4 lines
kernel/bpf/exception.c +4 -0
+static void mark_call_sites(struct bpf_verifier_env *env)
+{
+	u32 i, j;
+

kernel/bpf/exception.c int bpf_exc_check_info(struct bpf_verifier_env *env, const union bpf_attr *attr, · line 172

Quoted 10 lines
kernel/bpf/exception.c +10 -0
+	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;

[Severity: High]
If a landing pad is at the exact start of the program or subprogram (landing_pad_off == 0), how does this interact with BPF_PATCH_MOVE_TARGET when prepending instructions?

Because kernel/bpf/exception.c:bpf_exc_check_info() permits landing_pad_off to be 0 or subprog_start, this structural layout is possible. When it happens, the shift logic in kernel/bpf/fixups.c:adjust_insn_aux_data() uses a strict greater-than condition:

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

If cleanup_pad == off + 1 (e.g., when off=0), it doesn't get shifted. But BPF_PATCH_MOVE_TARGET prepends instructions at off=0, such as when gen_prologue is called in kernel/bpf/fixups.c:bpf_convert_ctx_accesses().

Will this leave the unwinder jumping into the newly prepended verifier instructions rather than the program's original first instruction, potentially causing issues like out-of-bounds reads or infinite loops if registers are clobbered?

The same as patch 4, BPF_PATCH_MOVE_TARGET is not needed.

author reviewer
#13 lore raw

Re: [PATCH bpf-next v10 07/24] bpf: Verify an unwind through landing pads and epilogues

In reply to [email protected]
Quoted 46 lines · On 10/9/26 6:40 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] bpf: skipped exception pad verification for global subprogs that throw and unwind
- [Medium] bpf: Soft lockup in mark_callx_might_unwind() due to O(N^2) instruction traversal --

commit 54596ff7029b639349bb84341497b649e38e027e
Author: Yonghong Song <[email protected]>

bpf: Verify an unwind through landing pads and epilogues

This commit adds verifier support for tracking control flow through unwind landing pads and epilogues. It calculates whether a subprogram might unwind by propagating the might_unwind flag along the CFG, and integrates backtracking through these new paths.

Quoted 4 lines
kernel/bpf/cfg.c +0 -0
@@ -716,6 +753,82 @@

[ ... ]

Quoted 12 lines
kernel/bpf/cfg.c +12 -0
+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;
+

kernel/bpf/cfg.c static int visit_insn(int t, struct bpf_verifier_env *env) · line 774

Quoted 10 lines
kernel/bpf/cfg.c +10 -0
+	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;

[Severity: Medium]
Could this loop cause a CPU soft lockup for very large BPF programs?

Quoted 7 lines

The loop iterates up to len times (which can be up to 1 million) and repeatedly calls bpf_find_containing_subprog(), which performs a binary search. Because this propagates upward through the call graph, the do-while loop could execute many times (e.g., up to 256 for the maximum call depth).

Without a cond_resched(), this might stall the CPU in kernel space for an extended period.

It is a little bit premature to add cond_resched(). If later on, we have such a case, we can add then.

Quoted 22 lines

[ ... ]

Quoted 5 lines
kernel/bpf/verifier.c +0 -0
@@ -19464,8 +19602,14 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
  				cur_func(env)->no_stack_arg_load = true;

kernel/bpf/verifier.c static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) · line 19610

Quoted 10 lines
kernel/bpf/verifier.c +6 -2
  			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;

[Severity: High]
If a global subprogram has the might_throw flag set, check_func_call() simulates the exception exit and returns PROCESS_BPF_EXIT (which is 1).

Quoted 6 lines

Because err is positive, does the check here mistakenly return early, bypassing the subsequent call to process_global_call_unwind()?

If the subprogram can both throw and unwind, its landing pad might never be visited by the verifier, potentially leading to a dead code sanitization trap at runtime.

In bpf_check(), we have

        if (env->cleanup_info_cnt || bpf_prog_may_unwind(env)) {
                ret = bpf_exc_check_prog(env);
                if (ret)
                        goto skip_full_check;
        }

where bpf_prog_may_unwind(env) is added in later patch. With the above 'if' condition, bpf_throw() will be rejected if (env->cleanup_info_cnt || bpf_prog_may_unwind(env)) is true.

Quoted 6 lines
Quoted 6 lines
kernel/bpf/verifier.c +2 -0
+				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);
author reviewer
#15 lore raw

Re: [PATCH bpf-next v10 07/24] bpf: Verify an unwind through landing pads and epilogues

In reply to [email protected]
Quoted 29 lines · On 10/9/26 7:13 AM, [email protected] wrote:
Quoted 1 line

bpf: Verify an unwind through landing pads and epilogues

TL;DR: Nit only: unwind_frames() sets r0 to zero in two calls; __mark_reg_const_zero() could do it in one, as process_iter_next_call() does, and the explanatory comment could go. No bug.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 0cf30220b777..1553c7d5bbdb 100644

[ ... ]

Quoted 1 line
kernel/bpf/verifier.c +0 -0
@@ -19203,6 +19212,135 @@ enum {

[ ... ]

Quoted 2 lines
kernel/bpf/verifier.c +2 -0
+static int unwind_frames(struct bpf_verifier_env *env, bool *do_print_state)
+{

[ ... ]

kernel/bpf/verifier.c enum { · line 19288

Quoted 8 lines
kernel/bpf/verifier.c +8 -0
+	/*
+	 * The call clobbered r1-r5, and r0 holds the zero the fixups put
+	 * there. Mark r0 unknown first: the known-zero helper keeps a NOT_INIT
+	 * type.
+	 */
+	clear_caller_saved_regs(env, cur_regs(env));
+	mark_reg_unknown(env, cur_regs(env), BPF_REG_0);
+	mark_reg_known_zero(env, cur_regs(env), BPF_REG_0);

this isn't a bug, but could this use __mark_reg_const_zero(env, &cur_regs(env)[BPF_REG_0]), as process_iter_next_call() does, and drop the part of the comment that explains why two calls are needed?

Quoted 6 lines

unwind_frames() sets r0 to a scalar zero in two steps here:
mark_reg_unknown() sets the SCALAR_VALUE type, then mark_reg_known_zero() sets the value. __mark_reg_const_zero() already sets the type to SCALAR_VALUE, the value to known zero, and precise to !bpf_capable in one call. process_iter_next_call() and check_kfunc_call() both use it for r0 this way.

Okay, will do (with better code) in the next revision.

Quoted 7 lines

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/37884246994

author reviewer
#22 lore raw

Re: [PATCH bpf-next v10 10/24] bpf: Do not use a private stack for a program that can unwind

In reply to [email protected]
Quoted 33 lines · On 10/9/26 6:45 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: bpf_prog_may_unwind misses might_throw, causing private stack corruption --

commit 38438f251d7fce91364c50842e5e55c25b6033f4
Author: Yonghong Song <[email protected]>

bpf: Do not use a private stack for a program that can unwind

This patch aims to prevent BPF programs that can unwind from using a private stack. A private stack keeps its frame pointer in %r9 on x86-64, and an unwind skips the restore, leading to stack addressing issues. The fix forces NO_PRIV_STACK for programs that might unwind.

Quoted 4 lines
kernel/bpf/exception.c +0 -0
index 2b9640099269e..f45dd3157f7fb 100644

[ ... ]

kernel/bpf/exception.c static void mark_call_sites(struct bpf_verifier_env *env) · line 191

Quoted 10 lines
kernel/bpf/exception.c +6 -0
@@ -183,6 +183,16 @@ static void mark_call_sites(struct bpf_verifier_env *env)
  	}
  }
 
+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)

[Severity: High]
Does bpf_prog_may_unwind() miss the might_throw condition?

Quoted 3 lines

Since might_unwind and might_throw are tracked separately in bpf_subprog_info, it appears a BPF program using bpf_throw() would bypass this check and still be compiled with a private stack.

If only might_throw (bpf_throw), private stack can be used. Here, we have might_unwind() as well, in such cases, we have

        if (env->cleanup_info_cnt || bpf_prog_may_unwind(env)) {
                ret = bpf_exc_check_prog(env);
                if (ret)
                        goto skip_full_check;
        }

and bpf_exc_check_prog(env) will reject bpf_throw(), i.e., if bpf_unwind() and bpf_throw() co-exist, verification will fail.

Quoted 42 lines
Quoted 7 lines
kernel/bpf/exception.c +4 -0
+			return true;
+	return false;
+}
+
  int bpf_exc_check_prog(struct bpf_verifier_env *env)
  {

[ ... ]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 59b275bfc949d..35013a5d84019 100644

[ ... ]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -5801,6 +5801,17 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
  		}
  	}
 

kernel/bpf/verifier.c static int check_max_stack_depth(struct bpf_verifier_env *env) · line 5813

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	/*
+	 * 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;

[Severity: High]
Will this leave programs that throw exceptions vulnerable to stack shifting in check_max_stack_depth()?

If a program uses bpf_throw() and is compiled with a private stack (PRIV_STACK_ADAPTIVE), the x86 JIT pushes the private frame pointer (%r9) before every call.

When bpf_throw() is called, the ORC unwinder calculates the boundary frame's stack pointer as the value of %rsp before the call, which includes the un-popped %r9 (shifting it by -8 bytes). Then bpf_exception_cb() uses this value to restore the boundary frame's callee-saved registers.

Quoted 4 lines

Because of the unaccounted %r9 push, the stack pointer is off by 8 bytes. Could this cause pop_callee_regs to pop the stale %r9 into a callee-saved register, shift all other registers by one slot, and ultimately corrupt the callee-saved registers?

See above, bpf_throw() and bpf_unwind() cannot co-exist in the same bpf prog.

Quoted 5 lines
Quoted 5 lines
kernel/bpf/verifier.c +1 -0
+
  	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
  		priv_stack_mode = bpf_enable_priv_stack(env->prog);
 
author reviewer
#25 lore raw

Re: [PATCH bpf-next v10 11/24] bpf: Prepare JITed programs for dispatching cleanup pads

In reply to [email protected]
Quoted 46 lines · On 10/9/26 6:35 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: backward jump offsets in bpf_exc_patch_unwind_calls are corrupted by bpf_adj_branches --

commit b2a75ebf7c80cc3231a5eb34881ba1928dafcd3b
Author: Yonghong Song <[email protected]>

bpf: Prepare JITed programs for dispatching cleanup pads

This patch prepares JITed programs to dispatch exception cleanup pads. It updates the verifier to patch bpf_unwind() calls with a sequence that clears r0 and jumps to the exception pad or exits.

Quoted 4 lines
kernel/bpf/fixups.c +0 -0
index 64baee1a37e60..1cc025c45ecda 100644

[ ... ]

Quoted 1 line
kernel/bpf/fixups.c +0 -0
@@ -1733,6 +1805,48 @@ static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off,

[ ... ]

Quoted 26 lines
kernel/bpf/fixups.c +26 -0
+/*
+ * 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) {
Quoted 8 lines

kernel/bpf/fixups.c static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off, · line 1838

Quoted 5 lines
kernel/bpf/fixups.c +5 -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);

[Severity: High]
Does this manually calculated offset get corrupted if the landing pad is located before the unwind call (pad < call)?

I think this cannot happen. See below.

Quoted 10 lines

bpf_patch_insn_data() is called immediately after this, which delegates to bpf_adj_branches() to adjust all relative offsets in the program.

When bpf_adj_branches() processes the newly inserted goto instruction, it evaluates it as if it were a shifted original instruction (because curr >= end_new evaluates to true). If the jump is backwards, bpf_adj_branches() might erroneously subtract the insertion delta (2) from the already-correct offset.

Quoted 3 lines

Could this result in the jump target being shifted 2 instructions before the actual landing pad, potentially leading to the execution of unintended or unverified bytecode during exception unwinding?

The offset is already right, and no change for bpf_adj_branches(). The goto is inside the patch [call, call + 3). bpf_adj_delta_to_off() only rewrites a jump that sits before pos or at or after end_new, i.e. one that was outside the patch.

Quoted 11 lines
Quoted 11 lines
kernel/bpf/fixups.c +10 -0
+		}
+
+		new_prog = bpf_patch_insn_data(env, call, insn_buf, 3);
+		if (!new_prog)
+			return -ENOMEM;
+		delta += 2;
+		env->prog = new_prog;
+	}
+	return 0;
+}
author reviewer
#27 lore raw

Re: [PATCH bpf-next v10 11/24] bpf: Prepare JITed programs for dispatching cleanup pads

In reply to [email protected]
Quoted 92 lines · On 10/9/26 7:13 AM, [email protected] wrote:
Quoted 1 line

bpf: Prepare JITed programs for dispatching cleanup pads

TL;DR: keep_subprog_exits() may mark an exit seen in a never-entered subprog, so dead-code removal can miscompute subprog starts and drop main's exit, letting JITed main fall off its image end.

Quoted 4 lines
kernel/bpf/fixups.c +0 -0
index 64baee1a37e6..1cc025c45ecd 100644

[ ... ]

Quoted 9 lines
kernel/bpf/fixups.c +5 -0
@@ -715,6 +716,32 @@ static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env)
  	}
  }
 
+static int keep_subprog_exits(struct bpf_verifier_env *env)
+{
+	u32 i, j;
+
+	for (i = 0; i < env->subprog_cnt; i++) {

kernel/bpf/fixups.c static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env) · line 733

Quoted 10 lines
kernel/bpf/fixups.c +10 -0
+		bool found = false;
+		u32 start;
+
+		if (!env->subprog_info[i].might_unwind)
+			continue;
+		start = env->subprog_info[i].start;
+		for (j = env->subprog_info[i + 1].start; j-- > start; ) {
+			if (env->prog->insnsi[j].code != (BPF_JMP | BPF_EXIT))
+				continue;
+			env->insn_aux_data[j].seen = env->pass_cnt;

Can this mark an exit as seen in a subprog the verifier never entered?

might_unwind is set statically while walking the control flow, so it is also set on a static subprog that is only called from a path the verifier proves dead, for example one guarded by a .rodata constant or a constant register. None of that subprog's instructions are seen, but the loop above still marks its last exit as seen.

Before this patch a live subprog was always entered at its first instruction, and adjust_subprog_starts_after_remove() relies on that. Now the first instruction of a subprog can be dead while a later exit is kept. bpf_opt_remove_dead_code() removes each contiguous run of unseen instructions even when the run crosses a subprog boundary, so one run can cover the end of the previous code and the head of this subprog, and stop at the kept exit.

Here is a trace (privileged loader, with bpf_unwind registered and the x86 cleanup pad support from later patches in the series):

   main:  0: r1 = 0
          1: if r1 == 0 goto +2   ; always taken
          2: call P               ; dead
          3: call A               ; dead
          4: r0 = 0
          5: exit
   P:     6: r0 = 1               ; static, never entered, no unwind
          7: exit
   A:     8: call bpf_unwind      ; static, never entered, might_unwind
          9: r0 = 0
         10: exit                 ; kept by keep_subprog_exits()

The first dead run, [2,3], is removed correctly, leaving P.start = 4, A.start = 6 and the fake subprog at 9.

The next dead run is [4..7]: all of P plus A's call and 'r0 = 0'. It stops at A's kept exit, so off = 4 and cnt = 4.

In adjust_subprog_starts_after_remove(), i is P. The j loop reaches the fake subprog, whose start (9) is not off + cnt (8), so:

	if (env->subprog_info[j].start != off + cnt)
		j--;

gives j = A. Since j > i, P's entry is dropped and A moves into its slot, and then the start adjustment gives A.start = 6 - 4 = 2. The correct value is 4.

The program is now:

   0: r1 = 0
   1: ja +0
   2: r0 = 0
   3: exit
   4: exit

with subprog starts main = 0 and A = 2, so main has lost its own 'r0 = 0; exit'. After bpf_opt_remove_nops() main is just [r1 = 0]. jit_subprogs() then JITs func[0] with no exit, so it has no epilogue and no ret, and the first run of the program falls off the end of main's image. If main had kept a jump into the reassigned tail, do_jit() would also read addrs[] past func[0]->len.

Quoted 8 lines

The same miscalculation happens when P is a live subprog with only a dead tail (the i == j case, where start != off).

Would it make sense to skip subprogs that were never entered, since they can never be on the stack during an unwind, for example:

	if (!env->insn_aux_data[start].seen)
		continue;

Indeed, this is a bug. Will fix.

Quoted 24 lines

Alternatively, could adjust_subprog_starts_after_remove() set the start of a partially removed subprog to off?

None of the later commits in this series appear to change keep_subprog_exits() or adjust_subprog_starts_after_remove().

kernel/bpf/fixups.c static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env) · line 744

Quoted 11 lines
kernel/bpf/fixups.c +11 -0
+			found = true;
+			break;
+		}
+		if (!found) {
+			verbose(env, "subprog %u can be unwound through but has no exit\n", i);
+			return -EINVAL;
+		}
+	}
+	return 0;
+}
+

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/37884246994

author reviewer
#32 lore raw

Re: [PATCH bpf-next v10 14/24] bpf, x86: Dispatch exception cleanup pads at run time

In reply to [email protected]
Quoted 46 lines · On 10/9/26 6:32 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: Exception unwinder cleanup pad executes in caller's stack frame context --

commit 9d03eddc4bc6be397e72d866390a80929337af59
Author: Yonghong Song <[email protected]>

bpf, x86: Dispatch exception cleanup pads at run time

Add what bpf_unwind() relies on to send each frame of a program to its landing pad or its epilogue on x86-64. This includes arch_bpf_stack_walk_ra(), aux->epilogue_ip assignment, and bpf_exc_fill_native_ranges() call.

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +0 -0
index 083fcd6cf15b7..d434871b5a11c 100644

[ ... ]

Quoted 17 lines
arch/x86/net/bpf_jit_comp.c +2 -0
@@ -3279,6 +3280,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))
  					return -EINVAL;
  			}
  			/* Deallocate outgoing args 7+ area. */
  			emit_add_rsp(&prog, outgoing_rsp);
  			if (bpf_prog->aux->exception_boundary) {
  				pop_callee_regs(&prog, all_callee_regs_used);
  				pop_r12(&prog);
  			} else {
Quoted 8 lines
  				pop_callee_regs(&prog, callee_regs_used);
  				if (arena_vm_start)
  					pop_r12(&prog);
  			}
  			EMIT1(0xC9);         /* leave */
  			bpf_prog->aux->ksym.fp_end = prog - temp;
  
  			emit_return(&prog, image + addrs[i - 1] + (prog - temp));

[Severity: High]
Does this execute the cleanup pad in the wrong stack frame context?

Quoted 6 lines

During exception unwinding, arch_bpf_stack_walk_ra() walks the stack and yields the return address pointer (ra) for the current frame N, which points to the instruction in frame N-1.

In bpf_unwind_rewrite(), *ra is overwritten with the address of frame N's cleanup pad or epilogue_ip:

We should be okay. Here, the address is from frame N-1 and the address is filled in frame N. Not as in the above mentioned that the overwritten with the address of frame N's cleanup pad or epilogue_ip.

Quoted 22 lines
kernel/bpf/helpers.c:bpf_unwind_rewrite() {
     ...
     rec = bpf_exc_pad_for_ip(prog, ip);
     *ra = rec ? rec->pad : prog->aux->epilogue_ip;
     ...
}

This forces frame N to jump to its cleanup pad when it returns.

However, the JIT epilogue executes "leave" before "ret". The "leave" instruction completely tears down frame N's stack and restores frame N-1's stack pointer and frame pointer.

The "ret" instruction then pops the modified return address and jumps to frame N's pad. As a result, the pad executes while frame N-1's context is active.

Can this cause any stack accesses inside the pad (using rbp, mapped to r10 in BPF) to incorrectly access frame N-1's stack variables, leading to memory corruption, use-after-free, or garbage reads during cleanup?

author reviewer
#35 lore raw

Re: [PATCH bpf-next v10 15/24] bpf, arm64: Dispatch exception cleanup pads at run time

In reply to [email protected]
Quoted 30 lines · On 10/9/26 6:30 AM, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] arm64/bpf: PAC modifier mismatch for bpf_throw's C frame causes FPAC panic --

commit 2f751c03b321c9d53d97196968f653cf6c3fa289
Author: Yonghong Song <[email protected]>

bpf, arm64: Dispatch exception cleanup pads at run time

This commit adds arm64 support for unwinding BPF frames and redirecting their return addresses to cleanup pads. It signs the modified return addresses using PAC when address authentication is enabled.

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

[ ... ]

Quoted 11 lines
arch/arm64/kernel/stacktrace.c +11 -0
+/* 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
Quoted 8 lines

arch/arm64/kernel/stacktrace.c noinline noinstr void arch_bpf_stack_walk(bool (*consume_entry)(void *cookie, u6 · line 479

Quoted 5 lines
arch/arm64/kernel/stacktrace.c +5 -0
+	 * 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));

[Severity: High]
Will this hardcoded PAC modifier cause an FPAC panic when returning from bpf_throw()?

bpf_throw() cannot go together with bpf_unwind().

Quoted 19 lines

The unwinder uses bpf_unwind_store_ra() to redirect the return address for the first BPF frame. The caller of this first BPF frame is the C function bpf_throw().

While record + sizeof(struct frame_record) correctly assumes a strict BPF JIT prologue where the entry SP is FP + 16, bpf_throw() is a compiled C function. Its actual frame size is compiler-dependent and may be larger than 16 bytes due to local variables.

When bpf_throw() returns, its epilogue will authenticate the return address using its actual entry SP. If we sign it here using FP + 16 instead of the actual entry SP, could authentication fail and trigger a kernel panic on PAC-enabled kernels?

Quoted 2 lines
arch/arm64/kernel/stacktrace.c +2 -0
+	WRITE_ONCE(rec->lr, ra);
+}

[ ... ]

#18 lore raw

Re: [PATCH bpf-next v10 09/24] bpf: Refuse a landing pad that does not resume

In reply to Yonghong Song

# CARRIED OVER from the unsent v9 draft (leftover of your v8 09 mail). Delete this line, or the file if you dropped it on purpose.

kernel/bpf/verifier.c static int do_check(struct bpf_verifier_env *env) · line 19733

Quoted 11 lines · Yonghong Song
kernel/bpf/verifier.c +10 -0
+		if (unlikely(env->cleanup_info_cnt)) {
+			err = bpf_exc_check_insn(env, insn);
+			if (error_recoverable_with_nospec(err) && state->speculative) {
+				insn_aux->nospec = true;
+				goto process_bpf_exit;
+			}
+			if (err)
+				return err;
+		}
+
 		if (bpf_is_prune_point(env, env->insn_idx)) {

since you're going to respin consider the following feedback:

The special case for speculative paths is still here. in_pad is compared in func_states_equal() now, so there is no need to check before pruning.
Call bpf_exc_check_insn() from do_check_insn() ? error_recoverable_with_nospec() after it does the same thing, and the error will be printed after the insn instead of before it.

#46 lore raw
In reply to Yonghong Song

# CARRIED OVER from the unsent v9 draft (nothing was sent on v9, v10 has only bot fixes). Delete this line, or the file if you dropped it on purpose.

Quoted 3 lines · Yonghong Song

- A subprog an unwind passes through must have an exit.
- Until the Rust toolchain supports BPF exception handling, the selftests write their tables by hand in inline asm.

rustc can do it already.
For example,
take RUSTC_BPF from selftests/bpf/Makefile.buildvars, replace panic=abort with panic=unwind, build core, then --emit=llvm-bc and clang -c like Makefile.skel does for progs/*.rs.

#[inline(never)]
fn fail() -> ! { unsafe { bpf_unwind() }; loop {} }

#[inline(never)]
fn check(i: u32) -> u32 { if i > 7 { fail() } i }

  pub extern "C-unwind" fn prog(ctx: *const u32) -> u32 {
      let _g = RcuReadGuard::new();
      check(unsafe { *ctx })
  }

The object has .bpf_cleanup with the right record and this code:

fail:
call bpf_unwind
L0: goto L0
check:

      if w1 > 0x7 goto L0
      w0 = w1
      exit
  L0: call fail
  prog:
      r6 = r1
      call bpf_rcu_read_lock
      w6 = *(u32 *)(r6 + 0x0)
      w1 = w6
      call check
      call bpf_rcu_read_unlock
      w0 = w6
      exit
      r6 = r0
      call bpf_rcu_read_unlock
      r1 = r6
      call _Unwind_Resume

They won't pass the verifier,
because
_Unwind_Resume() and fail() don't return, so LLVM emits nothing after the call. check_subprogs() refuses prog() and check() with
"last insn is not an exit or jmp".
rust-bpf hack adds 'exit' and replaces call with 'call bpf_unwind_resume'. We need to get rid of rust-bpf IR rewrite,
so let's try to do so now?
'call _Unwind_Resume' can be replaced by LLVM, by libbpf, or by the verifier with an exit. I feel that the verifier is right place to do it, but open to suggestions.

but since rustc doesn't emit debug info for extern fn, so there is no BTF for _Unwind_Resume, so libbpf may be a better place?
Not sure, let's discuss.

pw-bot: cr

author reviewer
#47 lore raw
Quoted 46 lines · Alexei Starovoitov

# CARRIED OVER from the unsent v9 draft (nothing was sent on v9, v10 has only bot fixes). Delete this line, or the file if you dropped it on purpose.

Quoted 3 lines · Yonghong Song

- A subprog an unwind passes through must have an exit.
- Until the Rust toolchain supports BPF exception handling, the selftests write their tables by hand in inline asm.

rustc can do it already.
For example,
take RUSTC_BPF from selftests/bpf/Makefile.buildvars, replace panic=abort with panic=unwind, build core, then --emit=llvm-bc and clang -c like Makefile.skel does for progs/*.rs.

   #[inline(never)]
   fn fail() -> ! { unsafe { bpf_unwind() }; loop {} }

   #[inline(never)]
   fn check(i: u32) -> u32 { if i > 7 { fail() } i }

   pub extern "C-unwind" fn prog(ctx: *const u32) -> u32 {
       let _g = RcuReadGuard::new();
       check(unsafe { *ctx })
   }

The object has .bpf_cleanup with the right record and this code:

   fail:
       call bpf_unwind
   L0: goto L0
   check:
       if w1 > 0x7 goto L0
       w0 = w1
       exit
   L0: call fail
   prog:
       r6 = r1
       call bpf_rcu_read_lock
       w6 = *(u32 *)(r6 + 0x0)
       w1 = w6
       call check
       call bpf_rcu_read_unlock
       w0 = w6
       exit
       r6 = r0
       call bpf_rcu_read_unlock
       r1 = r6
       call _Unwind_Resume
Quoted 6 lines

They won't pass the verifier,
because
_Unwind_Resume() and fail() don't return, so LLVM emits nothing after the call. check_subprogs() refuses prog() and check() with "last insn is not an exit or jmp".
rust-bpf hack adds 'exit' and replaces call with 'call bpf_unwind_resume'.

The following is what I have:

$ cat exc_review.rs
#![no_std]
#![no_main]
#![feature(lang_items)]
#![allow(internal_features)]
unsafe extern "C-unwind" {
    fn bpf_unwind();
}
unsafe extern "C" {
    fn bpf_rcu_read_lock();
    fn bpf_rcu_read_unlock();
}

struct RcuReadGuard;

impl RcuReadGuard {
    #[inline(always)]
    fn new() -> Self {
        unsafe { bpf_rcu_read_lock() };
        RcuReadGuard
    }
}
impl Drop for RcuReadGuard {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe { bpf_rcu_read_unlock() };
    }
}

#[inline(never)]
#[unsafe(no_mangle)]

fn fail() -> ! {
    unsafe { bpf_unwind() };
    loop {}
}

#[inline(never)]
#[unsafe(no_mangle)]

fn check(i: u32) -> u32 {
    if i > 7 {
        fail()
    }
    i
}

#[unsafe(no_mangle)]
#[unsafe(link_section = "syscall")]
pub extern "C-unwind" fn prog(ctx: *const u32) -> u32 {
let _g = RcuReadGuard::new();
check(unsafe { *ctx })
}

#[panic_handler]

fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {}
}

#[lang = "eh_personality"]
extern "C" fn rust_eh_personality() {}

#[used]
#[unsafe(link_section = "license")]
static LICENSE: [u8; 4] = *b"GPL\0";

$ cat run.sh
R=~/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/rustc
CL=/home/yhs/work/llvm-project/llvm/build.23/Release/bin

$R -Z unstable-options --print target-spec-json --target bpfel-unknown-none | \
sed 's/"obj-is-bitcode": true/"obj-is-bitcode": false/' > bpfel-elf.json
T=$PWD/bpfel-elf.json; D=$PWD/core-elf; mkdir -p $D
SRC=$($R --print sysroot)/lib/rustlib/src/rust/library/core/src/lib.rs
$R -Z unstable-options -Z always-encode-mir -O -C panic=unwind --crate-type rlib \
--target $T -A warnings --edition 2024 --crate-name core --emit=metadata --out-dir $D $SRC
echo '#![feature(compiler_builtins)] #![compiler_builtins] #![no_std]' | \
$R -Z unstable-options -O -C panic=unwind --crate-type rlib --target $T -L $D \
-A warnings --crate-name compiler_builtins --emit=metadata --out-dir $D -

$R -Z unstable-options -Z function-sections=no -O -C panic=unwind --crate-type rlib \
--target $T -L $D --edition 2021 -C debuginfo=2 -C target-cpu=v3 \
--emit=asm -s exc_review.s exc_review.rs

and below exc_review.s:

check:

        if w1 > 7 goto .LBB1_2
        w0 = w1
        exit

.LBB1_2:
call fail
fail:
call bpf_unwind
.LBB2_1:

        goto .LBB2_1
prog:
        r6 = r1
        call bpf_rcu_read_lock
        w6 = *(u32 *)(r6 + 0)
        w1 = w6
        call check
        call bpf_rcu_read_unlock
        w0 = w6
        exit
        r6 = r0
        call bpf_rcu_read_unlock
        r1 = r6
        call _Unwind_Resume

So it pretty similar to the above.

However, we have a big issue for BTF.

$ bpftool btf dump file exc_review.bpf.o
[1] PTR '(anon)' type_id=2
[2] STRUCT 'PanicInfo' size=24 vlen=4
        'message' type_id=3 bits_offset=0
        'location' type_id=4 bits_offset=64
        'can_unwind' type_id=5 bits_offset=128
        'force_no_backtrace' type_id=5 bits_offset=136
[3] PTR '(anon)' type_id=23
[4] PTR '(anon)' type_id=24
[5] INT 'bool' size=1 bits_offset=0 nr_bits=8 encoding=BOOL
[6] FUNC_PROTO '(anon)' ret_type_id=0 vlen=1
        '_info' type_id=1
[7] FUNC 'panic' type_id=6 linkage=global
[8] INT 'u32' size=4 bits_offset=0 nr_bits=32 encoding=(none)
[9] FUNC_PROTO '(anon)' ret_type_id=8 vlen=1
        'i' type_id=8
[10] FUNC 'check' type_id=9 linkage=global
[11] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[12] FUNC 'fail' type_id=11 linkage=global
[13] PTR '(anon)' type_id=8
[14] FUNC_PROTO '(anon)' ret_type_id=8 vlen=1
        'ctx' type_id=13
[15] FUNC 'prog' type_id=14 linkage=global
[16] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[17] FUNC 'rust_eh_personality' type_id=16 linkage=global
[18] INT 'u8' size=1 bits_offset=0 nr_bits=8 encoding=(none)
[19] ARRAY '(anon)' type_id=18 index_type_id=20 nr_elems=4
[20] INT '__ARRAY_SIZE_TYPE__' size=4 bits_offset=0 nr_bits=32 encoding=(none)
[21] VAR '_RNvCs63bSbDYK0Bo_10exc_review7LICENSE' type_id=19, linkage=global
[22] DATASEC 'license' size=0 vlen=1
        type_id=21 offset=0 size=4 (VAR '_RNvCs63bSbDYK0Bo_10exc_review7LICENSE')
[23] FWD 'Arguments' fwd_kind=struct
[24] FWD 'Location' fwd_kind=struct

There is no BTF for bpf_unwind, bpf_rcu_read_lock, _Unwind_Resume, etc.

In llvm, we have two commits in clang frontend to allow generate extern functions BTF. See below:
commit e3d8ee35e4ad: reland "[DebugInfo] Support to emit debugInfo for extern variables" commit a2a3ca8d9796: BPF: emit debuginfo for Function of DeclRefExpr if requested

I think the best way is for rustc supports the above two commits.

Quoted 2 lines

We need to get rid of rust-bpf IR rewrite,
so let's try to do so now?

Yes, the best way is for rustc to support generating proper debuginfo for extern variables.

Alternatively, we use use __kfunc_btf_anchor() thing to force btf generation where __kfunc_btf_anchor() has been used in various bpf selftests.
Use clang to generate a .bc files (with __kfunc_btf_anchor()) and then merge (through llvm-link) this .bc file and another .bc file generated from rustc and then finally clang to generate .s or .o file. But this seems still a hack. See
exceptions_cleanup.c, exceptions_cleanup_fail.c and exceptions_cleanup_shapes.c

Quoted 3 lines

'call _Unwind_Resume' can be replaced by LLVM, by libbpf, or by the verifier with an exit. I feel that the verifier is right place to do it, but open to suggestions.

Yes, _Unwind_Resume can be replaced with bpf_unwind_resume() kfunc. I think we should do libbpf or verifier since llvm has used _Unwind_Resume for x86_64, arm64, riscv, powerPC, loongArch, etc.

Currently my patch already used bpf_unwind_resume() in the kernel. In libbpf, a little bit code to rename _Unwind_Resume to bpf_unwind_rename for some logs.

Quoted 4 lines

but since rustc doesn't emit debug info for extern fn, so there is no BTF for _Unwind_Resume, so libbpf may be a better place?
Not sure, let's discuss.

The best option is for rustc to support generating extern func debug info. But if that is not possible, the libbpf will need to generate btf and amend them to the prog btf before loading.

Quoted 2 lines

pw-bot: cr

author reviewer
#19 lore raw

Re: [PATCH bpf-next v10 09/24] bpf: Refuse a landing pad that does not resume

In reply to Alexei Starovoitov
Quoted 11 lines · Alexei Starovoitov

# CARRIED OVER from the unsent v9 draft (leftover of your v8 09 mail). Delete this line, or the file if you dropped it on purpose.

kernel/bpf/verifier.c static int do_check(struct bpf_verifier_env *env) · line 19731

Quoted 9 lines · Yonghong Song
kernel/bpf/verifier.c +9 -0
+		if (unlikely(env->cleanup_info_cnt)) {
+			err = bpf_exc_check_insn(env, insn);
+			if (error_recoverable_with_nospec(err) && state->speculative) {
+				insn_aux->nospec = true;
+				goto process_bpf_exit;
+			}
+			if (err)
+				return err;
+		}

Remove the error_recoverable_with_nospec():

+ if (error_recoverable_with_nospec(err) && state->speculative) {
+ insn_aux->nospec = true;
+ goto process_bpf_exit;
+ }

For selftest:

/* A pad whose speculative walk reaches an exit: a barrier, not a refusal. */ static __used __naked __noinline __u64 spec_exit_pad_frame(void)

{
        asm volatile (
        "r1 = %[input] ll;"
        "r6 = *(u64 *)(r1 + 0);"
        "r6 &= 7;"
"1:"    "call always_unwind;"           /* cleanup region */
"2:"
        "r0 = 0;"
        "exit;"

"3:" /* landing pad */
"if r6 > 7 goto 4f;" /* never taken: walked speculatively */
"call bpf_unwind_resume;"
"4:"

        "exit;"
        CLEANUP_REC("1b", "2b", "3b")
        :
        : __imm_addr(input)
        : __clobber_all);
}

SEC("?syscall")
__success __caps_unpriv(CAP_BPF) __success_unpriv
__xlated_unpriv("nospec")
int entry_spec_exit_pad(void *ctx)

{
        return spec_exit_pad_frame();
}

and get the following failure:

libbpf: prog 'entry_spec_exit_pad': BPF program load failed: -EINVAL
libbpf: prog 'entry_spec_exit_pad': failed to load: -EINVAL
libbpf: failed to load object 'exceptions_cleanup_shapes' run_subtest:FAIL:unexpected_load_failure unexpected error: -22 (errno 22) VERIFIER LOG:
=============
arg#0 reference type('UNKNOWN ') size cannot be determined: -22 0: R10=fp0
; return spec_exit_pad_frame(); @ exceptions_cleanup_shapes.c:1091 0: (85) call pc+1
caller:
R10=fp0
callee:
frame1: R10=fp0
2: frame1: R10=fp0
; asm volatile ( @ exceptions_cleanup_shapes.c:1067

2: (18) r1 = 0x0                      ; frame1: R1=map_value(map=exceptio.bss,ks=4,vs=40)
4: (79) r6 = *(u64 *)(r1 +0)          ; frame1: R1=map_value(map=exceptio.bss,ks=4,vs=40) R6=scalar()
5: (57) r6 &= 7                       ; frame1: R6=scalar(smin=smin32=0,smax=umax=smax32=umax32=7,var_off=(0x0; 0x7))

6: (85) call pc+5
caller:
frame1: R6=scalar(smin=smin32=0,smax=umax=smax32=umax32=7,var_off=(0x0; 0x7)) R10=fp0
callee:
frame2: R1=map_value(map=exceptio.bss,ks=4,vs=40) R10=fp0
12: frame2: R1=map_value(map=exceptio.bss,ks=4,vs=40) R10=fp0
; asm volatile ( @ exceptions_cleanup_shapes.c:390
12: (85) call bpf_unwind#87213 ; frame1: R0=scalar()
; asm volatile ( @ exceptions_cleanup_shapes.c:1067
9: (25) if r6 > 0x7 goto pc+1
exit at insn 11 ends a landing pad: a catch pad is not supported yet, only cleanup pads that resume processed 9 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0
=============
#134/56 exceptions_cleanup/entry_spec_exit_pad @unpriv:FAIL

Quoted 8 lines
Quoted 2 lines

+
if (bpf_is_prune_point(env, env->insn_idx)) {

since you're going to respin consider the following feedback:

The special case for speculative paths is still here. in_pad is compared in func_states_equal() now, so there is no need to check before pruning.
Call bpf_exc_check_insn() from do_check_insn() ?

Moving bpf_exc_check_insn() to do_check_insn() makes sense. The above selftest succeeded (w.r.t speculative path).

Quoted 2 lines

error_recoverable_with_nospec() after it does the same thing, and the error will be printed after the insn instead of before it.

author reviewer
#48 lore raw
In reply to Yonghong Song
Quoted 212 lines · Yonghong Song
Quoted 46 lines · Alexei Starovoitov

# CARRIED OVER from the unsent v9 draft (nothing was sent on v9, v10 has only bot fixes). Delete this line, or the file if you dropped it on purpose.

Quoted 3 lines · Yonghong Song

   - A subprog an unwind passes through must have an exit.
   - Until the Rust toolchain supports BPF exception handling, the selftests write their tables by hand in inline asm.

rustc can do it already.
For example,
take RUSTC_BPF from selftests/bpf/Makefile.buildvars, replace panic=abort with panic=unwind, build core, then --emit=llvm-bc and clang -c like Makefile.skel does for progs/*.rs.

   #[inline(never)]
   fn fail() -> ! { unsafe { bpf_unwind() }; loop {} }

   #[inline(never)]
   fn check(i: u32) -> u32 { if i > 7 { fail() } i }

   pub extern "C-unwind" fn prog(ctx: *const u32) -> u32 { let _g = RcuReadGuard::new();
       check(unsafe { *ctx })
   }

The object has .bpf_cleanup with the right record and this code:

   fail:
       call bpf_unwind
   L0: goto L0
   check:
       if w1 > 0x7 goto L0
       w0 = w1
       exit
   L0: call fail
   prog:
       r6 = r1
       call bpf_rcu_read_lock
       w6 = *(u32 *)(r6 + 0x0)
       w1 = w6
       call check
       call bpf_rcu_read_unlock
       w0 = w6
       exit
       r6 = r0
       call bpf_rcu_read_unlock
       r1 = r6
       call _Unwind_Resume

Quoted 6 lines

They won't pass the verifier,
because
_Unwind_Resume() and fail() don't return, so LLVM emits nothing after the call. check_subprogs() refuses prog() and check() with "last insn is not an exit or jmp".
rust-bpf hack adds 'exit' and replaces call with 'call bpf_unwind_resume'.

The following is what I have:

$ cat exc_review.rs
#![no_std]
#![no_main]
#![feature(lang_items)]
#![allow(internal_features)]

unsafe extern "C-unwind" {
    fn bpf_unwind();
}

unsafe extern "C" {
    fn bpf_rcu_read_lock();
    fn bpf_rcu_read_unlock();
}

struct RcuReadGuard;

impl RcuReadGuard {
    #[inline(always)]
    fn new() -> Self {
        unsafe { bpf_rcu_read_lock() };
        RcuReadGuard
    }
}

impl Drop for RcuReadGuard {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe { bpf_rcu_read_unlock() };
    }
}

#[inline(never)]
#[unsafe(no_mangle)]
fn fail() -> ! {
    unsafe { bpf_unwind() };
    loop {}
}

#[inline(never)]
#[unsafe(no_mangle)]
fn check(i: u32) -> u32 {
    if i > 7 {
        fail()
    }
    i
}

#[unsafe(no_mangle)]
#[unsafe(link_section = "syscall")]
pub extern "C-unwind" fn prog(ctx: *const u32) -> u32 { let _g = RcuReadGuard::new();
    check(unsafe { *ctx })
}

#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {}
}

#[lang = "eh_personality"]
extern "C" fn rust_eh_personality() {}

#[used]
#[unsafe(link_section = "license")]
static LICENSE: [u8; 4] = *b"GPL\0";

$ cat run.sh
R=~/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/rustc
CL=/home/yhs/work/llvm-project/llvm/build.23/Release/bin

$R -Z unstable-options --print target-spec-json --target bpfel-unknown-none | \
   sed 's/"obj-is-bitcode": true/"obj-is-bitcode": false/' > bpfel-elf.json T=$PWD/bpfel-elf.json; D=$PWD/core-elf; mkdir -p $D
SRC=$($R --print sysroot)/lib/rustlib/src/rust/library/core/src/lib.rs $R -Z unstable-options -Z always-encode-mir -O -C panic=unwind --crate-type rlib \
   --target $T -A warnings --edition 2024 --crate-name core --emit=metadata --out-dir $D $SRC
echo '#![feature(compiler_builtins)] #![compiler_builtins] #![no_std]' | \
   $R -Z unstable-options -O -C panic=unwind --crate-type rlib --target $T -L $D \
   -A warnings --crate-name compiler_builtins --emit=metadata --out-dir $D -

$R -Z unstable-options -Z function-sections=no -O -C panic=unwind --crate-type rlib \
   --target $T -L $D --edition 2021 -C debuginfo=2 -C target-cpu=v3 \
   --emit=asm -s exc_review.s exc_review.rs

and below exc_review.s:

check:
        if w1 > 7 goto .LBB1_2
        w0 = w1
        exit
.LBB1_2:
        call fail
fail:
        call bpf_unwind
.LBB2_1:
        goto .LBB2_1
prog:
        r6 = r1
        call bpf_rcu_read_lock
        w6 = *(u32 *)(r6 + 0)
        w1 = w6
        call check
        call bpf_rcu_read_unlock
        w0 = w6
        exit
        r6 = r0
        call bpf_rcu_read_unlock
        r1 = r6
        call _Unwind_Resume

So it pretty similar to the above.

However, we have a big issue for BTF.

$ bpftool btf dump file exc_review.bpf.o
[1] PTR '(anon)' type_id=2
[2] STRUCT 'PanicInfo' size=24 vlen=4
        'message' type_id=3 bits_offset=0
        'location' type_id=4 bits_offset=64
        'can_unwind' type_id=5 bits_offset=128
        'force_no_backtrace' type_id=5 bits_offset=136
[3] PTR '(anon)' type_id=23
[4] PTR '(anon)' type_id=24
[5] INT 'bool' size=1 bits_offset=0 nr_bits=8 encoding=BOOL
[6] FUNC_PROTO '(anon)' ret_type_id=0 vlen=1
        '_info' type_id=1
[7] FUNC 'panic' type_id=6 linkage=global
[8] INT 'u32' size=4 bits_offset=0 nr_bits=32 encoding=(none)
[9] FUNC_PROTO '(anon)' ret_type_id=8 vlen=1
        'i' type_id=8
[10] FUNC 'check' type_id=9 linkage=global
[11] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[12] FUNC 'fail' type_id=11 linkage=global
[13] PTR '(anon)' type_id=8
[14] FUNC_PROTO '(anon)' ret_type_id=8 vlen=1
        'ctx' type_id=13
[15] FUNC 'prog' type_id=14 linkage=global
[16] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[17] FUNC 'rust_eh_personality' type_id=16 linkage=global
[18] INT 'u8' size=1 bits_offset=0 nr_bits=8 encoding=(none)
[19] ARRAY '(anon)' type_id=18 index_type_id=20 nr_elems=4
[20] INT '__ARRAY_SIZE_TYPE__' size=4 bits_offset=0 nr_bits=32 encoding=(none)
[21] VAR '_RNvCs63bSbDYK0Bo_10exc_review7LICENSE' type_id=19, linkage=global
[22] DATASEC 'license' size=0 vlen=1
        type_id=21 offset=0 size=4 (VAR '_RNvCs63bSbDYK0Bo_10exc_review7LICENSE')
[23] FWD 'Arguments' fwd_kind=struct
[24] FWD 'Location' fwd_kind=struct
Quoted 8 lines

There is no BTF for bpf_unwind, bpf_rcu_read_lock, _Unwind_Resume, etc.

In llvm, we have two commits in clang frontend to allow generate extern functions BTF. See below:
  commit e3d8ee35e4ad: reland "[DebugInfo] Support to emit debugInfo for extern variables" commit a2a3ca8d9796: BPF: emit debuginfo for Function of DeclRefExpr if requested

I think the best way is for rustc supports the above two commits.

I hacked rust compiler (https://github.com/rust-lang/rust) and the rust compiler is able to support to emit btf for extern variables.

The following is a portion of rust example code. Some of them could be simplified with macro, e.g., for link_section '.ksyms'...

...

unsafe extern "C-unwind" {
    #[link_section = ".ksyms"]
    fn bpf_unwind() -> !;
}
unsafe extern "C" {
    #[link_section = ".ksyms"]
    fn bpf_rcu_read_lock();
    #[link_section = ".ksyms"]
    fn bpf_rcu_read_unlock();
    #[link_section = ".ksyms"]
    fn bpf_preempt_disable();
    #[link_section = ".ksyms"]
    fn bpf_preempt_enable();
    #[link_section = ".ksyms"]
    fn bpf_local_irq_save(flags: *mut u64);
    #[link_section = ".ksyms"]
    fn bpf_local_irq_restore(flags: *mut u64);
}

// LLVM ends each cleanup landing pad with a call to _Unwind_Resume, and libbpf maps that // extern onto the bpf_unwind_resume kfunc, so it needs BTF in .ksyms like the rest. The // call reuses this declaration when the module already has one, but rustc only declares // an extern that is used, and nothing in Rust calls it; the static keeps it referenced.

unsafe extern "C" {
    #[link_section = ".ksyms"]
    fn _Unwind_Resume(exception: *mut c_void);
}

#[used]
static UNWIND_RESUME_ANCHOR: unsafe extern "C" fn(*mut c_void) = _Unwind_Resume;

// One bit per landing-pad Drop. Must match prog_tests/rust_exceptions.c in the kernel tree, // which runs this program and reads PADS_RAN back out of .bss.
const RAN_FOO3_PREEMPT: u64 = 0x1;
const RAN_FOO2_RCU: u64 = 0x2;
const RAN_FOO2_TRACKER: u64 = 0x4;
const RAN_FOO3_IRQ: u64 = 0x8;

#[no_mangle]
pub static mut PADS_RAN: u64 = 0;

// Volatile, because nothing in the program reads PADS_RAN back: plain stores would be dead. #[inline(always)]

fn pad_ran(bit: u64) {
    unsafe {
        let p = &raw mut PADS_RAN;
        write_volatile(p, *p | bit);
    }
}

// -- RAII guards --

struct PreemptGuard;

impl PreemptGuard {
    #[inline(always)]
    fn disable() -> PreemptGuard {
        unsafe { bpf_preempt_disable() };
        PreemptGuard
    }
}
impl Drop for PreemptGuard {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe { bpf_preempt_enable() };
        pad_ran(RAN_FOO3_PREEMPT);
    }
}

// The verifier tracks the saved flags by their stack slot, so the owning frame // builds the guard in place rather than receiving it from a constructor.

struct IrqGuard {
    flags: u64,
}
impl IrqGuard {
    #[inline(always)]
    fn save(&mut self) {
        unsafe { bpf_local_irq_save(&mut self.flags) };
    }
}
impl Drop for IrqGuard {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe { bpf_local_irq_restore(&mut self.flags) };
        pad_ran(RAN_FOO3_IRQ);
    }
}

...

// -- level 2: two invoke regions sharing one landing pad --

#[inline(never)]
#[no_mangle]

pub extern "C-unwind" fn foo2(fail3: bool, fail2: bool, val: u64) -> u64 {
    let _tracker = Tracker;
    let _rcu = RcuGuard::lock();

    let r = foo3(fail3, val);

    if fail2 {
        unsafe { bpf_unwind() };
    }

    black_box(r)
}

// -- level 1: no resources, so no .bpf_cleanup entry --

#[inline(never)]
#[no_mangle]

pub extern "C-unwind" fn foo1(fail3: bool, fail2: bool, val: u64) -> u64 {
    foo2(fail3, fail2, val)
}

#[unsafe(link_section = "syscall")]
#[no_mangle]

pub extern "C-unwind" fn entry(_ctx: *mut u8) -> i32 {
    foo1(black_box(true), black_box(false), black_box(101)) as i32
}

// The verifier only lets a GPL-compatible program call kfuncs. #[unsafe(link_section = "license")]
#[no_mangle]
static _LICENSE: [u8; 4] = [b'G', b'P', b'L', 0];

// -- unwinding runtime bits --

// Referenced by every function with a landing pad; never called on BPF, where // the kernel dispatches to the pads itself.
#[lang = "eh_personality"]
extern "C" fn rust_eh_personality() {}

#[lang = "panic_in_cleanup"]

fn panic_in_cleanup() -> ! {
    loop {}
}

The compilation is all from rustc.

The following is the objdump dump:

Disassembly of section .text:

0000000000000000 <foo1>:
; foo2(fail3, fail2, val)

       0:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000000:  R_BPF_64_32  foo2
; }
       1:       95 00 00 00 00 00 00 00 exit

0000000000000010 <foo2>:

; pub extern "C-unwind" fn foo2(fail3: bool, fail2: bool, val: u64) -> u64 {
       2:       bf 37 00 00 00 00 00 00 r7 = r3
       3:       bf 26 00 00 00 00 00 00 r6 = r2
       4:       bf 18 00 00 00 00 00 00 r8 = r1
;         unsafe { bpf_rcu_read_lock() };
       5:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000028:  R_BPF_64_32  bpf_rcu_read_lock
;     let r = foo3(fail3, val);
       6:       bf 81 00 00 00 00 00 00 r1 = r8
       7:       bf 72 00 00 00 00 00 00 r2 = r7
       8:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000040:  R_BPF_64_32  foo3
;     if fail2 {
       9:       15 06 02 00 00 00 00 00 if r6 == 0x0 goto +0x2 <L0>
;         unsafe { bpf_unwind() };
      10:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000050:  R_BPF_64_32  bpf_unwind
      11:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000058:  R_BPF_64_32  __bpf_trap
<L0>:
;         unsafe { black_box(dummy) }
      12:       7b 0a f8 ff 00 00 00 00 *(u64 *)(r10 - 0x8) = r0
      13:       bf a1 00 00 00 00 00 00 r1 = r10
      14:       07 01 00 00 f8 ff ff ff r1 += -0x8
;         unsafe { bpf_rcu_read_unlock() };
      15:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000078:  R_BPF_64_32  bpf_rcu_read_unlock
;         write_volatile(p, *p | bit);
      16:       18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0x0 ll
                0000000000000080:  R_BPF_64_64  PADS_RAN
      18:       79 12 00 00 00 00 00 00 r2 = *(u64 *)(r1 + 0x0)
      19:       bf 23 00 00 00 00 00 00 r3 = r2
      20:       47 03 00 00 02 00 00 00 r3 |= 0x2
;         unsafe { volatile_store(dst, src) };
      21:       7b 31 00 00 00 00 00 00 *(u64 *)(r1 + 0x0) = r3
;         write_volatile(p, *p | bit);
      22:       47 02 00 00 06 00 00 00 r2 |= 0x6
;         unsafe { volatile_store(dst, src) };
      23:       7b 21 00 00 00 00 00 00 *(u64 *)(r1 + 0x0) = r2
; }
      24:       79 a0 f8 ff 00 00 00 00 r0 = *(u64 *)(r10 - 0x8)
      25:       95 00 00 00 00 00 00 00 exit
      26:       bf 06 00 00 00 00 00 00 r6 = r0
;         unsafe { bpf_rcu_read_unlock() };
      27:       85 10 00 00 ff ff ff ff call -0x1
                00000000000000d8:  R_BPF_64_32  bpf_rcu_read_unlock
;         write_volatile(p, *p | bit);
      28:       18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0x0 ll
                00000000000000e0:  R_BPF_64_64  PADS_RAN
      30:       79 12 00 00 00 00 00 00 r2 = *(u64 *)(r1 + 0x0)
      31:       bf 23 00 00 00 00 00 00 r3 = r2
      32:       47 03 00 00 02 00 00 00 r3 |= 0x2
;         unsafe { volatile_store(dst, src) };
      33:       7b 31 00 00 00 00 00 00 *(u64 *)(r1 + 0x0) = r3
;         write_volatile(p, *p | bit);
      34:       47 02 00 00 06 00 00 00 r2 |= 0x6
;         unsafe { volatile_store(dst, src) };
      35:       7b 21 00 00 00 00 00 00 *(u64 *)(r1 + 0x0) = r2
      36:       bf 61 00 00 00 00 00 00 r1 = r6
      37:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000128:  R_BPF_64_32  _Unwind_Resume

0000000000000130 <foo3>:

; pub extern "C-unwind" fn foo3(fail: bool, val: u64) -> u64 {
      38:       bf 26 00 00 00 00 00 00 r6 = r2
      39:       bf 17 00 00 00 00 00 00 r7 = r1
;         unsafe { bpf_preempt_disable() };
      40:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000140:  R_BPF_64_32  bpf_preempt_disable
...
;         unsafe { volatile_store(dst, src) };
      78:       7b 17 00 00 00 00 00 00 *(u64 *)(r7 + 0x0) = r1
      79:       bf 61 00 00 00 00 00 00 r1 = r6
      80:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000280:  R_BPF_64_32  _Unwind_Resume

0000000000000288 <rust_eh_personality>:
; extern "C" fn rust_eh_personality() {}

      81:       95 00 00 00 00 00 00 00 exit

Disassembly of section syscall:

0000000000000000 <entry>:
; unsafe { black_box(dummy) }

       0:       b7 01 00 00 01 00 00 00 r1 = 0x1
       1:       73 1a f6 ff 00 00 00 00 *(u8 *)(r10 - 0xa) = w1
       2:       bf a1 00 00 00 00 00 00 r1 = r10
       3:       07 01 00 00 f6 ff ff ff r1 += -0xa
       4:       b7 01 00 00 00 00 00 00 r1 = 0x0
       5:       73 1a f7 ff 00 00 00 00 *(u8 *)(r10 - 0x9) = w1
       6:       bf a1 00 00 00 00 00 00 r1 = r10
       7:       07 01 00 00 f7 ff ff ff r1 += -0x9
       8:       b7 01 00 00 65 00 00 00 r1 = 0x65
       9:       7b 1a f8 ff 00 00 00 00 *(u64 *)(r10 - 0x8) = r1
      10:       bf a1 00 00 00 00 00 00 r1 = r10
      11:       07 01 00 00 f8 ff ff ff r1 += -0x8
;     foo1(black_box(true), black_box(false), black_box(101)) as i32
      12:       79 a3 f8 ff 00 00 00 00 r3 = *(u64 *)(r10 - 0x8)
      13:       71 a2 f7 ff 00 00 00 00 w2 = *(u8 *)(r10 - 0x9)
      14:       71 a1 f6 ff 00 00 00 00 w1 = *(u8 *)(r10 - 0xa)
      15:       85 10 00 00 ff ff ff ff call -0x1
                0000000000000078:  R_BPF_64_32  foo1
; }
      16:       95 00 00 00 00 00 00 00 exit
$ bpftool btf
 dump file exc_cleanup.o
[1] PTR '(anon)' type_id=2
[2] INT 'u8' size=1 bits_offset=0 nr_bits=8 encoding=(none)
[3] FUNC_PROTO '(anon)' ret_type_id=4 vlen=1
        '_ctx' type_id=1
[4] INT 'i32' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[5] FUNC 'entry' type_id=3 linkage=global
[6] INT 'bool' size=1 bits_offset=0 nr_bits=8 encoding=BOOL
[7] INT 'u64' size=8 bits_offset=0 nr_bits=64 encoding=(none)
[8] FUNC_PROTO '(anon)' ret_type_id=7 vlen=3
        'fail3' type_id=6
        'fail2' type_id=6
        'val' type_id=7
[9] FUNC 'foo1' type_id=8 linkage=global
[10] FUNC_PROTO '(anon)' ret_type_id=7 vlen=3
        'fail3' type_id=6
        'fail2' type_id=6
        'val' type_id=7
[11] FUNC 'foo2' type_id=10 linkage=global
[12] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[13] FUNC 'bpf_rcu_read_lock' type_id=12 linkage=extern
[14] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[15] FUNC 'bpf_unwind' type_id=14 linkage=extern
[16] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[17] FUNC '__bpf_trap' type_id=16 linkage=extern
[18] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[19] FUNC 'bpf_rcu_read_unlock' type_id=18 linkage=extern
[20] FUNC_PROTO '(anon)' ret_type_id=0 vlen=1
        '(anon)' type_id=21
[21] PTR '(anon)' type_id=0
[22] FUNC '_Unwind_Resume' type_id=20 linkage=extern
[23] FUNC_PROTO '(anon)' ret_type_id=7 vlen=2
        'fail' type_id=6
        'val' type_id=7
[24] FUNC 'foo3' type_id=23 linkage=global
[25] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[26] FUNC 'bpf_preempt_disable' type_id=25 linkage=extern
[27] FUNC_PROTO '(anon)' ret_type_id=0 vlen=1
        '(anon)' type_id=28
[28] PTR '(anon)' type_id=7
[29] FUNC 'bpf_local_irq_save' type_id=27 linkage=extern
[30] FUNC_PROTO '(anon)' ret_type_id=0 vlen=1
        '(anon)' type_id=28
[31] FUNC 'bpf_local_irq_restore' type_id=30 linkage=extern
[32] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[33] FUNC 'bpf_preempt_enable' type_id=32 linkage=extern
[34] FUNC_PROTO '(anon)' ret_type_id=0 vlen=0
[35] FUNC 'rust_eh_personality' type_id=34 linkage=global
[36] ARRAY '(anon)' type_id=2 index_type_id=37 nr_elems=4
[37] INT '__ARRAY_SIZE_TYPE__' size=4 bits_offset=0 nr_bits=32 encoding=(none)
[38] VAR '_LICENSE' type_id=36, linkage=global
[39] PTR '(anon)' type_id=20
[40] VAR '_RNvCsl8ViJ65pEud_19bpf_exc_cleanup_btf20UNWIND_RESUME_ANCHOR' type_id=39, linkage=global
[41] VAR 'PADS_RAN' type_id=7, linkage=global
[42] DATASEC '.bss' size=0 vlen=1
        type_id=41 offset=0 size=8 (VAR 'PADS_RAN')
[43] DATASEC '.data.rel.ro._RNvCsl8ViJ65pEud_19bpf_exc_cleanup_btf20UNWIND_RESUME_ANCHOR' size=0 vlen=1
        type_id=40 offset=0 size=8 (VAR '_RNvCsl8ViJ65pEud_19bpf_exc_cleanup_btf20UNWIND_RESUME_ANCHOR')
[44] DATASEC '.ksyms' size=0 vlen=9
        type_id=13 offset=0 size=0 (FUNC 'bpf_rcu_read_lock')
        type_id=15 offset=0 size=0 (FUNC 'bpf_unwind')
        type_id=17 offset=0 size=0 (FUNC '__bpf_trap')
        type_id=19 offset=0 size=0 (FUNC 'bpf_rcu_read_unlock')
        type_id=22 offset=0 size=0 (FUNC '_Unwind_Resume')
        type_id=26 offset=0 size=0 (FUNC 'bpf_preempt_disable')
        type_id=29 offset=0 size=0 (FUNC 'bpf_local_irq_save')
        type_id=31 offset=0 size=0 (FUNC 'bpf_local_irq_restore')
        type_id=33 offset=0 size=0 (FUNC 'bpf_preempt_enable')
[45] DATASEC 'license' size=0 vlen=1
        type_id=38 offset=0 size=4 (VAR '_LICENSE')

And I tried the following user space check:

+#define RUST_OBJ_FILE "progs_rust/exc_cleanup.o"
+
+/* exc_cleanup.rs: one bit per Drop, innermost frame first. */

+#define RUST_RAN_FOO3_PREEMPT  0x1
+#define RUST_RAN_FOO2_RCU      0x2
+#define RUST_RAN_FOO2_TRACKER  0x4
+#define RUST_RAN_FOO3_IRQ      0x8

+
+#define RUST_PADS_RAN \
+ (RUST_RAN_FOO3_PREEMPT | RUST_RAN_FOO2_RCU | RUST_RAN_FOO2_TRACKER | \
+ RUST_RAN_FOO3_IRQ)
+
+void test_rust_exceptions(void)
+{
+ char log[8192] = {};
+ LIBBPF_OPTS(bpf_object_open_opts, opts,
+ .kernel_log_buf = log,
+ .kernel_log_size = sizeof(log));

+       struct bpf_program *prog;
+       struct bpf_object *obj;
+       struct bpf_map *bss;
+       __u64 pads_ran, ctx = 0;
+       __u32 key = 0;
+       int err;

+
+ LIBBPF_OPTS(bpf_test_run_opts, topts,
+ .ctx_in = &ctx,
+ .ctx_size_in = sizeof(ctx),
+ );
+
+ if (access(RUST_OBJ_FILE, R_OK)) {
+ printf("%s:SKIP: no %s, see the comment in %s\n", __func__,
+ RUST_OBJ_FILE, __FILE__);
+ test__skip();
+ return;
+ }
+
+ obj = bpf_object__open_file(RUST_OBJ_FILE, &opts);
+ if (!ASSERT_OK_PTR(obj, "open"))
+ return;
+
+ err = bpf_object__load(obj);
+ if (err) {
+ if (err == -EOPNOTSUPP &&
+ strstr(log, "exception cleanup needs a JIT that can dispatch landing pads"))
+ test__skip();
+ else if (!ASSERT_OK(err, "load"))
+ fprintf(stderr, "%s", log);
+ goto out;
+ }
+
+ prog = bpf_object__find_program_by_name(obj, "entry");
+ if (!ASSERT_OK_PTR(prog, "find entry"))
+ goto out;
+

+       /* PADS_RAN is the whole of the object's .bss. */
+       bss = bpf_object__find_map_by_name(obj, ".bss");
+       if (!ASSERT_OK_PTR(bss, "find .bss"))

+ goto out;
+
+ err = bpf_prog_test_run_opts(bpf_program__fd(prog), &topts);
+ if (!ASSERT_OK(err, "run"))
+ goto out;
+
+ /* The unwind leaves entry too, and an unwound program returns 0. */
+ ASSERT_EQ(topts.retval, 0, "retval");
+
+ err = bpf_map__lookup_elem(bss, &key, sizeof(key), &pads_ran,
+ sizeof(pads_ran), 0);
+ if (!ASSERT_OK(err, "lookup PADS_RAN"))
+ goto out;
+ ASSERT_EQ(pads_ran, RUST_PADS_RAN, "pads_ran");
+out:
+ bpf_object__close(obj);
+}

And it works properly.

Quoted 3 lines
Quoted 3 lines

We need to get rid of rust-bpf IR rewrite,
so let's try to do so now?

Yes, currently I hacked into rustc compiler with AI help. Will need to understand better for this.

Quoted 14 lines

Yes, the best way is for rustc to support generating proper debuginfo for extern variables.

Alternatively, we use use __kfunc_btf_anchor() thing to force btf generation where __kfunc_btf_anchor() has been used in various bpf selftests.
Use clang to generate a .bc files (with __kfunc_btf_anchor()) and then merge (through llvm-link) this .bc file and another .bc file generated from rustc and then finally clang to generate .s or .o file. But this seems still a hack. See
  exceptions_cleanup.c, exceptions_cleanup_fail.c and exceptions_cleanup_shapes.c

Quoted 3 lines

'call _Unwind_Resume' can be replaced by LLVM, by libbpf, or by the verifier with an exit. I feel that the verifier is right place to do it, but open to suggestions.

I agree, using bpf_unwind_resume() in kernel is a better choice. In libbpf, we just simply change _Unwind_Resume names to bpf_unwind_resume() to satisfy log's.

Quoted 12 lines

Yes, _Unwind_Resume can be replaced with bpf_unwind_resume() kfunc. I think we should do libbpf or verifier since llvm has used _Unwind_Resume for x86_64, arm64, riscv, powerPC, loongArch, etc.

Currently my patch already used bpf_unwind_resume() in the kernel. In libbpf, a little bit code to rename _Unwind_Resume to bpf_unwind_rename for some logs.

Quoted 4 lines

but since rustc doesn't emit debug info for extern fn, so there is no BTF for _Unwind_Resume, so libbpf may be a better place?
Not sure, let's discuss.

Yes, I hacked in rustc and it seems working. I will continue to explore.

Quoted 9 lines

The best option is for rustc to support generating extern func debug info. But if that is not possible, the libbpf will need to generate btf and amend them to the prog btf before loading.

Quoted 2 lines

pw-bot: cr