Skip to contentSkip to conversation

bpf: Indirect calls of bpf subprogs (callx)

PATCH Applied Alexei Starovoitov 6 participants 36 messages Sep 24 – Sep 29

Subsystems (11)
Documentation x86 Kselftest BPF +7 more subsystems
lore
Share & tools
lore
#0 lore raw

v2 cover bpf: Indirect calls of bpf subprogs (callx)

From: Alexei Starovoitov <[email protected]>

v1->v2:
- Dropped "bpf: Don't fold loads from insn_array maps into constants". bpf_map_direct_read() rejects insn_array already.
- patch 1: emit the same diag as sort_subprogs_topo() (bpf-ci).
- patch 3 is new: taking the address of a function that is never called hit verifier_bug() in jit_subprogs(). Not related to callx, but callx makes it likely.
- patch 4: BPF_OP() == BPF_CALL in liveness like in const_fold, explained in the comment why slots are live before callx callsite (Eduard).
- patch 5: moved !bpf_is_callx() into nested 'if' (Eduard). JIT support is checked before the type of the register.
- patch 6: sync callbacks are in the call graph too. Stack depth of
a callback whose address is read from .rodata or taken in another subprog was not accounted.
- patch 10:
. check_cfg() explores functions of a table one at a time. It was
losing changes_pkt_data and other effects of the functions in
a table that call each other.
. no cmpxchg64(), it's not available on all 32-bit archs.
. don't reject the prog that reads a pointer to a function that was
removed as dead code (sashiko).
. load of the pointer sets jit_required, so the prog that passes it to
a helper as a callback can't run in the interpreter (bpf-ci).
. tbl[i].data at variable offset is a regular load when none of
the possible offsets overlaps with a pointer (bpf-ci).
- patch 12: append the functions and copy the map only for progs that have callx. The rest use .rodata as-is (bpf-ci). Pass token_fd to map create. Dropped dead bpf_map_lookup_elem() fallback.
- patch 14: light skeleton reserves fd_array slots only when the object has callx.
- selftests: anchored callx_retval_is_tracked to the caller, the tests of global func in a table and of const folding of the pointer test what they claim now, skip without JIT, fixed ASSERT_GT() of u32 and
the comment, added tests for the above (bpf-ci). The table in callx_rodata_lskel test is volatile. clang was turning it into
direct calls, so the test didn't test light skeleton.
- Added acks.
v1: https://lore.kernel.org/bpf/[email protected]/

Introduce BPF_JMP | BPF_CALL | BPF_X 'callx dst_reg' instruction: indirect call of bpf subprog with address in a register. LLVM emits it for calls via function pointer. The verifier rejected it as unknown opcode.

Only static subprogs can be called. The callee is verified in the context of the caller like a direct call of static subprog. No callx into global subprogs, helpers or kfuncs.

All callees are known before the main verifier pass. The address of the callee comes from:

- ld_imm64 BPF_PSEUDO_FUNC, which is allowed for static subprogs only. add_subprogs() and check_cfg() see them already.

- 64-bit load from read-only data: tables of functions, struct ops, vtables, where pointers are mixed with other data. Rust needs that:

    r6 = vtable ll
    r1 = *(u64 *)(r6 + 0)      // data
    r2 = *(u64 *)(r6 + 8)      // pointer to a function
    callx r2

libbpf keeps the data in a frozen read-only array map, one per prog that has callx, and stores byte offset of static function in the prog into the pointer. Progs without callx use .rodata as before. The kernel guesses pointers by that value before check_cfg() (patch 10). Wrong guess is safe. Functions referenced by data only are found via func_info (patch 9). After JIT the kernel replaces the offsets in the map with addresses. The prog must be the only user of the map, since other progs would have been verified with its old content. The prog reads addresses as data, so CAP_PERFMON is required.

Both produce PTR_TO_FUNC.

The passes before the main one don't know the callee and treat callx conservatively (patch 4). The main pass records caller -> callee edges. Recursion and stack depth checks use them afterwards (patch 6).

In C:

  static const struct shape_ops square_ops = { 1, area, 10, perimeter };
  ...
  return ops->area(x) * ops->scale + ops->perimeter(ops->id);

and

  static int (* const handlers[])(struct xdp_md *) = { foo, bar, baz };
  ...
  if (i < ARRAY_SIZE(handlers))
          return handlers[i](ctx);

plus what clang compiles without data: picking one of several functions, passing a function pointer into another function.

Patches 1-3 are fixes I hit along the way: a prog without callx that hangs bpf_prog_load() in check_max_stack_depth(), its test, and verifier_bug() when the address of a function that is never called is taken.

Not supported:
- JITs other than x86-64 and arm64. No interpreter support.
- x86-64 with FineIBT: bpf_jit_supports_callx() returns false.
- tail calls in callees of callx.
- pointers to functions in writable data, misaligned pointers.

Alexei Starovoitov (17):
bpf: Fix infinite loop in check_max_stack_depth() selftests/bpf: Test recursion through a global function and a callback
bpf: Keep functions with address taken when removing dead code
bpf: Prepare static analysis passes for callx instruction
bpf: Add callx instruction to call bpf subprogs indirectly
bpf: Add callx calls to the call graph
bpf, x86: Add JIT support for callx
bpf, arm64: Add JIT support for callx
bpf: Discover subprogs described by func_info
bpf: Recognize pointers to functions in read-only maps
libbpf: Support pointers to static functions in data when linking
libbpf: Resolve pointers to functions in read-only data
libbpf: Treat .data.rel.ro as read-only data
libbpf: Support pointers to functions in read-only data in light
skeleton
selftests/bpf: Add tests for callx
selftests/bpf: Add tests for callx through pointers in read-only data bpf, docs: Document callx instruction

 Documentation/bpf/clang-notes.rst             |    7 +-
 Documentation/bpf/linux-notes.rst             |   31 +-
 arch/arm64/net/bpf_jit_comp.c                 |   16 +
 arch/x86/net/bpf_jit_comp.c                   |   68 ++
 include/linux/bpf.h                           |   10 +
 include/linux/bpf_verifier.h                  |   42 +
 include/linux/filter.h                        |    1 +
 kernel/bpf/backtrack.c                        |   20 +-
 kernel/bpf/cfg.c                              |   76 ++
 kernel/bpf/const_fold.c                       |    6 +-
 kernel/bpf/core.c                             |   12 +
 kernel/bpf/disasm.c                           |    5 +-
 kernel/bpf/fixups.c                           |   94 +-
 kernel/bpf/liveness.c                         |   38 +-
 kernel/bpf/verifier.c                         |  714 ++++++++++-
 tools/lib/bpf/bpf_gen_internal.h              |   13 +-
 tools/lib/bpf/gen_loader.c                    |  172 ++-
 tools/lib/bpf/libbpf.c                        |  443 ++++++-
 tools/lib/bpf/linker.c                        |   18 +
 tools/testing/selftests/bpf/Makefile.skel     |    2 +-
 .../bpf/prog_tests/callx_func_ptr_map.c       |  202 ++++
 .../bpf/prog_tests/callx_rodata_lskel.c       |   63 +
 .../selftests/bpf/prog_tests/verifier.c       |   12 +
 .../selftests/bpf/progs/callx_rodata.c        |   51 +
 .../selftests/bpf/progs/verifier_callx.c      | 1039 +++++++++++++++++
 .../bpf/progs/verifier_callx_rodata.c         |  846 ++++++++++++++
 .../bpf/progs/verifier_global_subprogs.c      |   31 +
 .../selftests/bpf/verifier/basic_call.c       |    2 +-
 28 files changed, 3913 insertions(+), 121 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/callx_func_ptr_map.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/callx_rodata_lskel.c
 create mode 100644 tools/testing/selftests/bpf/progs/callx_rodata.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_callx.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_callx_rodata.c

base-commit: b4d936547f5a3ca5563f48ee81f153c928336027

Signature · 1 line
2.55.0
#1 lore raw

PATCH v2 1/17 bpf: Fix infinite loop in check_max_stack_depth()

From: Alexei Starovoitov <[email protected]>

sort_subprogs_topo() rejects recursion via direct calls, but allows cycles that go through ld_imm64 BPF_PSEUDO_FUNC, since the address could be taken for an async callback. The main verifier pass limits the number of frames, but it doesn't follow calls into global functions.
So the following program passes both:

static int cb(u32 i, void *ctx) { return foo(i); }
static int foo(int x) { return bar(x); }
int bar(int x) { bpf_loop(1, cb, NULL, 0); return 0; }

SEC("socket") int prog(void *ctx) { return cb(0, NULL); }

cb -> foo -> bar -> bpf_loop -> cb is unbounded recursion. check_max_stack_depth_subprog() walks this cycle too. None of the functions use stack and the frame counter is reset by every global function, so neither stack size nor frame limit is hit and bpf_prog_load() spins forever.

Reject a call into a subprog that is already in the chain of callers. Async callbacks are skipped earlier and are not affected.

---
 kernel/bpf/verifier.c | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
kernel/bpf/verifier.c +21 -0
index a7c9e2d8965d..74cf24ce3007 100644
@@ -5510,6 +5510,27 @@ static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
 			}
 		}
 
+		/*
+		 * sort_subprogs_topo() tolerates cycles in the call graph that
+		 * go through the address of a function being taken, since it
+		 * doesn't know what it is taken for. Such cycle is a recursion
+		 * unless it's an async callback, which are skipped above.
+		 * The main verification pass limits the depth of the recursion,
+		 * but it doesn't follow calls of global functions.
+		 */
+		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
+			if (tmp != sidx)
+				continue;
+			verbose(env, "recursive call from %s() to %s()\n",
+				bpf_subprog_name(env, idx), bpf_subprog_name(env, sidx));
+			bpf_diag_program_structure(
+				env, i, "recursive subprogram call",
+				"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
+				"This call or callback would make the subprogram call graph recursive. "
+				"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
+			return -EINVAL;
+		}
+
 		/* store caller info for after we return from callee */
 		dinfo[idx].frame = frame;
 		dinfo[idx].ret_insn = i + 1;
Signature · 1 line
2.55.0
#2 lore raw

PATCH v2 2/17 selftests/bpf: Test recursion through a global function and a callback

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Add a test for recursion
callback -> static func -> global func -> bpf_loop() -> callback that used to hang check_max_stack_depth().

---
 .../bpf/progs/verifier_global_subprogs.c      | 31 +++++++++++++++++++
 1 file changed, 31 insertions(+)
tools/testing/selftests/bpf/progs/verifier_global_subprogs.c +31 -0
index 966f49348787..27fbe54e8795 100644
@@ -536,4 +536,35 @@ int return_from_void_global(struct __sk_buff *skb)
 	return 0;
 }
 
+int global_calls_loop(int x);
+
+static __noinline int static_calls_global(int x)
+{
+	return global_calls_loop(x);
+}
+
+static __noinline int loop_cb_calls_static(u32 i, void *ctx)
+{
+	return static_calls_global(i);
+}
+
+__noinline int global_calls_loop(int x)
+{
+	bpf_loop(1, loop_cb_calls_static, NULL, 0);
+	return 0;
+}
+
+/*
+ * loop_cb_calls_static() -> static_calls_global() -> global_calls_loop() ->
+ * bpf_loop() -> loop_cb_calls_static() is an unbounded recursion that the
+ * main verification pass can't see, because it doesn't follow calls of global
+ * functions. None of the functions use stack.
+ */
+SEC("?raw_tp")
+__failure __msg("recursive call from global_calls_loop() to loop_cb_calls_static()")
+int recursion_via_global_func_and_callback(const void *ctx)
+{
+	return loop_cb_calls_static(0, NULL);
+}
+
 char _license[] SEC("license") = "GPL";
Signature · 1 line
2.55.0
#3 lore raw

PATCH v2 3/17 bpf: Keep functions with address taken when removing dead code

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

ld_imm64 BPF_PSEUDO_FUNC may take the address of a function that nothing calls: the helper call that takes it as a callback is dead code, or the prog only stores or compares the pointer. The function is not seen by the main pass and bpf_opt_remove_dead_code() removes it, while ld_imm64 stays and points to whatever follows. If the function was the last one jit_subprogs() hits:

verifier bug: No program to jit at insn 8 (subprog < 0)

Otherwise the register gets the address of the next function.

Keep the first insn of such function and make it a trap like sanitize_dead_code() does, so the address stays valid and unique.

---
 kernel/bpf/fixups.c | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
kernel/bpf/fixups.c +29 -0
index 2add8001c3ec..75936842d177 100644
@@ -619,12 +619,41 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 	}
 }
 
+/*
+ * The address of a function might be taken by the code that is not dead,
+ * while the function itself is dead code, since nothing calls it. Keep the first
+ * instruction of such function, so that the address remains valid and differs
+ * from the addresses of other functions. Make it a trap like
+ * sanitize_dead_code() does.
+ */
+static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
+	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
+	struct bpf_insn *insn = env->prog->insnsi;
+	int insn_cnt = env->prog->len;
+	int i, t;
+
+	for (i = 0; i < insn_cnt; i++) {
+		if (!aux_data[i].seen || !bpf_pseudo_func(insn + i))
+			continue;
+		t = i + insn[i].imm + 1;
+		if (aux_data[t].seen)
+			continue;
+		memcpy(insn + t, &trap, sizeof(trap));
+		aux_data[t].zext_dst = false;
+		aux_data[t].seen = env->pass_cnt;
+	}
+}
+
 int bpf_opt_remove_dead_code(struct bpf_verifier_env *env)
 {
 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
 	int insn_cnt = env->prog->len;
 	int i, err;
 
+	keep_funcs_with_addr_taken(env);
+
 	for (i = 0; i < insn_cnt; i++) {
 		int j;
 
Signature · 1 line
2.55.0
#4 lore raw

PATCH v2 4/17 bpf: Prepare static analysis passes for callx instruction

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

BPF_JMP | BPF_CALL | BPF_X (callx) will be an indirect call of static subprog with address in dst_reg. The passes that run before the main verifier pass don't know which subprog callx calls.
Teach them to treat callx as a call with unknown callee:

- const_fold: callx clobbers R0-R5 like any other call. Otherwise bpf_prune_dead_branches() could rewrite a live conditional jump.

- live regs: callx uses R1-R5 and dst_reg, defines R0-R5.

- stack liveness: func instances are keyed by (callsite, depth) and cannot describe a callsite with multiple callees. Don't create instances for callees of callx. If any callx argument is derived from fp mark stack of all frames as read at callx insn and keep slots of outer frames alive 'before' the callsite while the callee is verified. Same as for callbacks that are not known statically. The callee is analyzed as standalone instance.

- backtracking: treat callx as a call of static subprog, same as BPF_PSEUDO_CALL.

callx is still rejected as unknown opcode. No functional change.

---
 include/linux/bpf_verifier.h |  6 ++++++
 kernel/bpf/backtrack.c       | 20 +++++++++++--------
 kernel/bpf/const_fold.c      |  3 ++-
 kernel/bpf/liveness.c        | 38 +++++++++++++++++++++++++++++++-----
 4 files changed, 53 insertions(+), 14 deletions(-)
include/linux/bpf_verifier.h +6 -0
index 92f528c45605..6380c851ed24 100644
@@ -1089,6 +1089,12 @@ static inline bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
 }
 
+/* callx: indirect call of a bpf subprog whose address is in insn->dst_reg */
+static inline bool bpf_is_callx(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_JMP | BPF_CALL | BPF_X);
+}
+
 __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log,
 				      const char *fmt, va_list args);
 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
kernel/bpf/backtrack.c +12 -8
index 507a366dffa4..4da99dec0818 100644
@@ -406,15 +406,18 @@ 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)) {
-			int subprog_insn_idx, subprog;
+		if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {
+			int subprog_insn_idx, subprog = -1;
 
-			subprog_insn_idx = idx + insn->imm + 1;
-			subprog = bpf_find_subprog(env, subprog_insn_idx);
-			if (subprog < 0)
-				return -EFAULT;
+			if (bpf_pseudo_call(insn)) {
+				subprog_insn_idx = idx + insn->imm + 1;
+				subprog = bpf_find_subprog(env, subprog_insn_idx);
+				if (subprog < 0)
+					return -EFAULT;
+			}
 
-			if (bpf_subprog_is_global(env, subprog)) {
+			/* callx calls static subprogs only */
+			if (subprog >= 0 && bpf_subprog_is_global(env, subprog)) {
 				/* check that jump history doesn't have any
 				 * extra instructions from subprog; the next
 				 * instruction after call to global subprog
@@ -536,7 +539,8 @@ static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
 			 * never do that.
 			 */
 			from_subprog_call = subseq_idx - 1 >= 0 &&
-					    bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]);
+					    (bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) ||
+					     bpf_is_callx(&env->prog->insnsi[subseq_idx - 1]));
 
 			r0_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_0);
 			r2_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_2);
kernel/bpf/const_fold.c +2 -1
index 7f1b30059cc8..28dec733e596 100644
@@ -191,7 +191,8 @@ static void const_reg_xfer(struct bpf_verifier_env *env, struct const_arg_info *
 		dst->val = val;
 		break;
 	case BPF_JMP:
-		if (opcode != BPF_CALL)
+		/* both 'call imm' and 'callx reg' clobber caller saved registers */
+		if (BPF_OP(insn->code) != BPF_CALL)
 			break;
 process_call:
 		for (r = BPF_REG_0; r <= BPF_REG_5; r++)
kernel/bpf/liveness.c +33 -5
index 44ecdc5b4ec2..a204b492acc8 100644
@@ -356,12 +356,29 @@ int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_
 	return 0;
 }
 
+/*
+ * Stack slots of outer frames that the callee may read are accounted as read
+ * by the @callsite insn itself, i.e. they are live before @callsite and may be
+ * dead after it, when:
+ * - @callsite calls a callback, which may be called several times;
+ * - @callsite is callx. Its callee is not known when stack liveness is
+ *   computed, so there is no func instance for it at @callsite. While
+ *   the verifier is in the callee lookup_instance() finds its standalone
+ *   instance that knows nothing about outer frames. What the callee may read
+ *   there is recorded by record_call_access().
+ */
+static bool callee_stack_access_at_callsite(struct bpf_verifier_env *env, u32 callsite)
+{
+	return bpf_calls_callback(env, callsite) ||
+	       bpf_is_callx(&env->prog->insnsi[callsite]);
+}
+
 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_spi)
 {
 	/*
 	 * 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, otherwise
+	 * - alive before callsite if callsite calls callback or is callx, otherwise
 	 * - alive after callsite
 	 */
 	struct live_stack_query *q = &env->liveness->live_stack_query;
@@ -394,7 +411,7 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp
 		/* Get callsite from verifier state, not from instance callchain */
 		callsite = q->callsites[i];
 
-		alive = bpf_calls_callback(env, callsite)
+		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)
@@ -1439,7 +1456,15 @@ static int record_call_access(struct bpf_verifier_env *env,
 	if (bpf_pseudo_call(insn))
 		return 0;
 
-	if (bpf_get_call_summary(env, insn, &cs))
+	if (bpf_is_callx(insn))
+		/*
+		 * The callee is not known statically. Assume that all arg
+		 * slots are passed and let record_arg_access() conservatively
+		 * mark the stack of all frames as read if any of them is
+		 * derived from a frame pointer.
+		 */
+		arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS + MAX_STACK_ARG_SLOTS;
+	else if (bpf_get_call_summary(env, insn, &cs))
 		arg_slot_cnt = cs.arg_slot_cnt;
 
 	for (r = BPF_REG_1; r < BPF_REG_1 + min(arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); r++) {
@@ -1533,7 +1558,7 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env,
 		bool has_extra = false;
 		u8 cls = BPF_CLASS(insns[idx].code);
 		bool is_ldx_stx_call = cls == BPF_LDX || cls == BPF_STX ||
-				       insns[idx].code == (BPF_JMP | BPF_CALL);
+				       (cls == BPF_JMP && BPF_OP(insns[idx].code) == BPF_CALL);
 
 		verbose(env, "%3d: ", idx);
 		bpf_verbose_insn(env, &insns[idx]);
@@ -1722,7 +1747,7 @@ static int compute_subprog_args(struct bpf_verifier_env *env,
 		if (err)
 			goto err_free;
 
-		if (insn->code == (BPF_JMP | BPF_CALL)) {
+		if (BPF_CLASS(insn->code) == BPF_JMP && BPF_OP(insn->code) == BPF_CALL) {
 			err = record_call_access(env, instance, at_in[i], idx);
 			if (err)
 				goto err_free;
@@ -2202,6 +2227,9 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env,
 				use = GENMASK(min_t(u8, cs.arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS), 1);
 			def = mask_widen(def);
 			use = mask_widen(use);
+			/* callx reads the address of the callee from dst_reg */
+			if (bpf_is_callx(insn))
+				use |= dst;
 			break;
 		default:
 			def = 0;
Signature · 1 line
2.55.0
#5 lore raw

Re: [PATCH bpf-next v2 04/17] bpf: Prepare static analysis passes for callx instruction

The comment and the commit message line "The callee is analyzed as standalone instance" say that a callx callee always has a standalone depth-0 func instance that lookup_instance() finds. Is that…
Quoted 1 line
include/linux/bpf_verifier.h +0 -0

[ ... ]

Quoted 14 lines
kernel/bpf/liveness.c +6 -0
index 44ecdc5b4ec2..a204b492acc8 100644
@@ -356,12 +356,29 @@ int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_
 	return 0;
 }
 
+/*
+ * Stack slots of outer frames that the callee may read are accounted as read
+ * by the @callsite insn itself, i.e. they are live before @callsite and may be
+ * dead after it, when:
+ * - @callsite calls a callback, which may be called several times;
+ * - @callsite is callx. Its callee is not known when stack liveness is

kernel/bpf/liveness.c int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_ · line 374

Quoted 10 lines
kernel/bpf/liveness.c +10 -0
+ *   computed, so there is no func instance for it at @callsite. While
+ *   the verifier is in the callee lookup_instance() finds its standalone
+ *   instance that knows nothing about outer frames. What the callee may read
+ *   there is recorded by record_call_access().
+ */
+static bool callee_stack_access_at_callsite(struct bpf_verifier_env *env, u32 callsite)
+{
+	return bpf_calls_callback(env, callsite) ||
+	       bpf_is_callx(&env->prog->insnsi[callsite]);
+}

The comment and the commit message line "The callee is analyzed as standalone instance" say that a callx callee always has a standalone depth-0 func instance that lookup_instance() finds. Is that accurate for all cases?

Looking at bpf_compute_subprog_arg_access(), the standalone instance is only created for subprogs not already analyzed through a direct call:

kernel/bpf/liveness.c:bpf_compute_subprog_arg_access() {
    ...
    if (info[sub].at_in && !bpf_subprog_is_global(env, sub))
        continue;
    instance = call_instance(env, NULL, 0, sub);
    ...
}

Subprogs are walked callers-first. If a static subprog S is both a callx target and reached by a BPF_PSEUDO_CALL that passes an fp-derived argument, analyze_subprog() has already set info[S].at_in, so no depth-0 instance is created.

With the verifier state in frame S entered through callx, lookup_instance() tries key == callx insn idx at depths frameno..1 (no match, call_instance() is only called for pseudo calls and callbacks), then tries key == S start at depth 0 (does not exist), so it returns NULL.

bpf_live_stack_query_init() stores NULL in q->instances[frame], and bpf_stack_slot_alive() returns true for every slot:

kernel/bpf/liveness.c:bpf_stack_slot_alive() {
    ...
    if (!curframe_instance)
        return true;
    ...
    if (!instance)
        return true;
    ...
}

The result is safe (slots are only treated as more alive), but the comment appears to misdescribe the mechanism. Stack-slot cleaning in __clean_func_state() is also silently lost for the whole callx chain in that case, which reduces state pruning.

At this commit callx is still rejected, so this only matters later when callx is enabled. Could the comment and changelog be reworded to cover the case where lookup_instance() returns NULL, or should the standalone instance be created for address-taken static subprogs as well?

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

maintainer Acked-by on v2 4/17
#6 lore raw

Re: [PATCH bpf-next v2 04/17] bpf: Prepare static analysis passes for callx instruction

In reply to Alexei Starovoitov
Quoted 20 lines · Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

BPF_JMP | BPF_CALL | BPF_X (callx) will be an indirect call of static subprog with address in dst_reg. The passes that run before the main verifier pass don't know which subprog callx calls.
Teach them to treat callx as a call with unknown callee:

- const_fold: callx clobbers R0-R5 like any other call. Otherwise bpf_prune_dead_branches() could rewrite a live conditional jump.

- live regs: callx uses R1-R5 and dst_reg, defines R0-R5.

- stack liveness: func instances are keyed by (callsite, depth) and cannot describe a callsite with multiple callees. Don't create instances for callees of callx. If any callx argument is derived from fp mark stack of all frames as read at callx insn and keep slots of outer frames alive 'before' the callsite while the callee is verified. Same as for callbacks that are not known statically. The callee is analyzed as standalone instance.

Quoted 7 lines

- backtracking: treat callx as a call of static subprog, same as BPF_PSEUDO_CALL.

callx is still rejected as unknown opcode. No functional change.

---

...

#7 lore raw

PATCH v2 5/17 bpf: Add callx instruction to call bpf subprogs indirectly

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Introduce BPF_JMP | BPF_CALL | BPF_X (opcode 0x8d) 'callx dst_reg'
instruction: indirect call of bpf subprog with address in dst_reg. That's the encoding LLVM emits for calls via function pointer. src_reg, off, imm are reserved and must be zero.

dst_reg must be PTR_TO_FUNC produced by ld_imm64 BPF_PSEUDO_FUNC. check_ld_imm() allows it for static subprogs only, so callx cannot call global subprogs or the main prog. Since every callee has its address taken by ld_imm64, add_subprogs() and check_cfg() see all of them before the main pass, and might_sleep, changes_pkt_data, might_throw of the callee are already merged into the subprog that takes the address.

reg->subprogno is the callee. Verify callx as a direct call of that static subprog: split check_func_call() into check_static_func_call() that is shared with new check_func_callx(). Different paths through the same callx may call different subprogs.

Arithmetic on PTR_TO_FUNC is allowed, so check that the pointer wasn't modified. Allow callx while holding a lock like direct calls of static subprogs.

The interpreter doesn't support callx. Set jit_required and add bpf_jit_supports_callx() for JITs to opt in. No JIT does yet, so callx is still rejected.

Print it as "callx rN" in the verifier log and xlated dump.

Adjust "invalid call insn1" test_verifier test that used opcode 0x8d as unknown opcode. It fails with "R0 !read_ok" now.

---
 include/linux/filter.h                        |   1 +
 kernel/bpf/core.c                             |   7 +
 kernel/bpf/disasm.c                           |   5 +-
 kernel/bpf/verifier.c                         | 163 ++++++++++++++----
 .../selftests/bpf/verifier/basic_call.c       |   2 +-
 5 files changed, 145 insertions(+), 33 deletions(-)
include/linux/filter.h +1 -0
index 422284b4fa96..4f0662e42897 100644
@@ -1237,6 +1237,7 @@ bool bpf_jit_inlines_helper_call(s32 imm);
 bool bpf_jit_supports_subprog_tailcalls(void);
 bool bpf_jit_supports_percpu_insn(void);
 bool bpf_jit_supports_kfunc_call(void);
+bool bpf_jit_supports_callx(void);
 bool bpf_jit_supports_kfunc_ret_reg_pair(void);
 bool bpf_jit_supports_stack_args(void);
 bool bpf_jit_supports_arena_args(void);
kernel/bpf/core.c +7 -0
index 227211166dcc..868350977f0c 100644
@@ -1831,6 +1831,7 @@ bool bpf_opcode_in_insntable(u8 code)
 		[BPF_LD | BPF_IND | BPF_H] = true,
 		[BPF_LD | BPF_IND | BPF_W] = true,
 		[BPF_JMP | BPF_JA | BPF_X] = true,
+		[BPF_JMP | BPF_CALL | BPF_X] = true,
 		[BPF_JMP | BPF_JCOND] = true,
 	};
 #undef BPF_INSN_3_TBL
@@ -3287,6 +3288,12 @@ bool __weak bpf_jit_supports_kfunc_call(void)
 	return false;
 }
 
+/* Return TRUE if the JIT backend supports callx (indirect call) instruction. */
+bool __weak bpf_jit_supports_callx(void)
+{
+	return false;
+}
+
 bool __weak bpf_jit_supports_kfunc_ret_reg_pair(void)
 {
 	return false;
kernel/bpf/disasm.c +4 -1
index 3ce8d74b0e40..36d3228d7745 100644
@@ -350,7 +350,10 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		if (opcode == BPF_CALL) {
 			char tmp[64];
 
-			if (insn->src_reg == BPF_PSEUDO_CALL) {
+			if (BPF_SRC(insn->code) == BPF_X) {
+				verbose(cbs->private_data, "(%02x) callx r%d",
+					insn->code, insn->dst_reg);
+			} else if (insn->src_reg == BPF_PSEUDO_CALL) {
 				verbose(cbs->private_data, "(%02x) call pc%s",
 					insn->code,
 					__func_get_name(cbs, insn,
kernel/bpf/verifier.c +132 -31

211 lines not on this page · raw message

tools/testing/selftests/bpf/verifier/basic_call.c +1 -1
index a8c6ab4c1622..0f93c4551f23 100644
@@ -4,7 +4,7 @@
 	BPF_RAW_INSN(BPF_JMP | BPF_CALL | BPF_X, 0, 0, 0, 0),
 	BPF_EXIT_INSN(),
 	},
-	.errstr = "unknown opcode 8d",
+	.errstr = "R0 !read_ok",
 	.result = REJECT,
 },
 {
Signature · 1 line
2.55.0
#8 lore raw

Re: [PATCH bpf-next v2 05/17] bpf: Add callx instruction to call bpf subprogs indirectly

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] selftests/bpf: Test 'invalid call insn1' fails on archs without callx JIT --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] selftests/bpf: Test 'invalid call insn1' fails on archs without callx JIT --

commit ce97408a97c513bf2f81b643bb904a03dbe7cead
Author: Alexei Starovoitov <[email protected]>

bpf: Add callx instruction to call bpf subprogs indirectly

Introduce BPF_JMP | BPF_CALL | BPF_X (opcode 0x8d) 'callx dst_reg'
instruction: indirect call of bpf subprog with address in dst_reg. That's the encoding LLVM emits for calls via function pointer.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 74cf24ce30074..eb014bf6a2e87 100644

[ ... ]

Quoted 14 lines
kernel/bpf/verifier.c +14 -0
+/* there is no support for callx in the interpreter */
+static int require_callx_jit(struct bpf_verifier_env *env)
+{
+	if (!env->prog->jit_requested) {
+		verbose(env, "JIT is required to use callx\n");
+		return -EOPNOTSUPP;
+	}
+	if (!bpf_jit_supports_callx()) {
+		verbose(env, "JIT doesn't support callx\n");
+		return -EOPNOTSUPP;
+	}
+	env->prog->jit_required = true;
+	return 0;
+}

[ ... ]

tools/testing/selftests/bpf/verifier/basic_call.c line 7

Quoted 10 lines
tools/testing/selftests/bpf/verifier/basic_call.c +1 -1
index a8c6ab4c1622f..0f93c4551f235 100644
@@ -4,7 +4,7 @@
 	BPF_RAW_INSN(BPF_JMP | BPF_CALL | BPF_X, 0, 0, 0, 0),
 	BPF_EXIT_INSN(),
 	},
-	.errstr = "unknown opcode 8d",
+	.errstr = "R0 !read_ok",

[Severity: Medium]
Will this strict error string expectation cause the selftest to fail on architectures that lack callx JIT support?

If the architecture's JIT does not support callx (like RISC-V, S390x, or PowerPC), or if JIT is disabled, the verifier will prematurely reject the instruction in require_callx_jit() by emitting "JIT doesn't support callx" or "JIT is required to use callx", and return -EOPNOTSUPP.

Since the test framework expects an exact match for "R0 !read_ok", this test might break CI environments on those architectures because the verifier never reaches the R0 check. Does this test need to handle multiple possible error strings or be skipped when JIT support is missing?

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

PATCH v2 6/17 bpf: Add callx calls to the call graph

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The callee of callx is known to the main verifier pass only, but sort_subprogs_topo() (recursion check) and check_max_stack_depth() (stack size, number of frames, tail_call_reachable, private stack) need the call graph. Both treat ld_imm64 BPF_PSEUDO_FUNC as a call from the subprog that takes the address, which is not where callx calls it:

main: r1 = foo ll; call bar
bar: callx r1

The call chain is main -> bar -> foo, but only main -> bar and main -> foo are seen.

Record caller -> callee edge in a bitmap when the main pass processes callx. It explores all feasible paths, so all feasible edges are there. Then:

- rerun sort_subprogs_topo() after the main pass with callx edges. Unbounded recursion is already rejected by the frame limit. This one catches bounded recursion via callx, same as direct recursion. The call graph is not context sensitive: foo() that calls bar() via callx and bar() that calls foo() is a recursion even if it never happens in the same call chain.

- check_max_stack_depth_subprog() walks all recorded callees at each callx.

The same goes for sync callbacks. The address of a callback may be taken in one subprog and passed to a helper in another one:

main: r1 = cb ll; call bar
bar: r2 = r1; call bpf_loop

Only main -> cb was accounted. Record caller -> callback edge in push_callback_call() and walk the edges at helper and kfunc calls that call callbacks too.

JITs pass tail call counter to the callee in a register. callx doesn't. Reject tail_call_reachable callees of callx.

---
 include/linux/bpf_verifier.h |   7 ++
 kernel/bpf/verifier.c        | 144 +++++++++++++++++++++++++++++------
 2 files changed, 127 insertions(+), 24 deletions(-)
include/linux/bpf_verifier.h +7 -0
index 6380c851ed24..931f305fa440 100644
@@ -965,6 +965,13 @@ struct bpf_verifier_env {
 	struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */
 	/* subprog indices sorted in topological order: leaves first, callers last */
 	int subprog_topo_order[BPF_MAX_SUBPROGS + 2];
+	/*
+	 * Call graph edges created by callx instructions. A bitmap of
+	 * subprog_cnt * subprog_cnt bits, where bit (caller * subprog_cnt + callee)
+	 * is set when the main verification pass sees 'caller' calling 'callee'
+	 * via callx. Allocated when the first such edge is recorded.
+	 */
+	unsigned long *callx_edges;
 	union {
 		struct bpf_idmap idmap_scratch;
 		struct bpf_idset idset_scratch;
kernel/bpf/verifier.c +120 -24

235 lines not on this page · raw message

Signature · 1 line
2.55.0
#10 lore raw

Re: [PATCH bpf-next v2 06/17] bpf: Add callx calls to the call graph

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] bpf: sort_subprogs_topo() misses callback edges, failing to detect bounded recursion --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] bpf: sort_subprogs_topo() misses callback edges, failing to detect bounded recursion --

commit 1cc83e74951c3df35b0b794cf4a90e325a1cff05
Author: Alexei Starovoitov <[email protected]>

bpf: Add callx calls to the call graph

This commit updates the verifier to record caller to callee edges for callx and sync callbacks during the main verification pass. It then uses these recorded edges in sort_subprogs_topo() to detect bounded recursion via indirect calls, and in check_max_stack_depth_subprog() to walk the callees.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index eb014bf6a2e87..d00d0ecab17cf 100644

[ ... ]

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

Quoted 6 lines
kernel/bpf/verifier.c +1 -1
@@ -3195,12 +3233,22 @@ static int sort_subprogs_topo(struct bpf_verifier_env *env)
 				int idx = insn_postorder[j];
 				int callee;
 
-				if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx]))
+				if (bpf_is_callx(&insn[idx])) {

[Severity: Medium]
Does this code miss callback edges when checking for cycles?

The commit message mentions that sync callback edges are recorded, and check_max_stack_depth_subprog() checks both bpf_is_callx() and bpf_calls_callback().

However, this condition only checks for bpf_is_callx(). If a BPF program uses a sync callback (e.g., bpf_loop) to call a subprogram, which then recursively calls the original subprogram, and neither subprogram contains a callx instruction, would sort_subprogs_topo() silently ignore the callback edges and fail to detect the cycle here?

Should this condition be expanded to check for bpf_calls_callback(env, idx) so that callback edges are correctly registered during topological sorting?

Quoted 9 lines
kernel/bpf/verifier.c +9 -0
+					/* find a callee that is not explored yet */
+					callee = -1;
+					do {
+						callee = next_callx_callee(env, cur, callee + 1);
+					} while (callee >= 0 && color[callee] == 2);
+					if (callee < 0)
+						continue;
+				} else if (bpf_pseudo_call(&insn[idx]) || bpf_pseudo_func(&insn[idx])) {
+					callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);

[ ... ]

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

Re: [PATCH bpf-next v2 06/17] bpf: Add callx calls to the call graph

In reply to Alexei Starovoitov
Could the map part of this comment move to a later commit? The comment references check_func_ptr_read() which doesn't exist at this commit.
Quoted 4 lines
include/linux/bpf_verifier.h +0 -0
index 6380c851ed24..931f305fa440 100644

[ ... ]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index eb014bf6a2e8..d00d0ecab17c 100644

[ ... ]

kernel/bpf/verifier.c static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins · line 10704

Quoted 13 lines
kernel/bpf/verifier.c +9 -0
@@ -10615,6 +10693,15 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 		return 0;
 	}
 
+	/*
+	 * The address of the callback might be taken in another function or
+	 * read from a map, see check_func_ptr_read(). Like with callx it's
+	 * known here what is called.
+	 */
+	err = record_callx_edge(env, caller->subprogno, subprog);
+	if (err)
+		return err;
+

Could the map part of this comment move to a later commit? The comment references check_func_ptr_read() which doesn't exist at this commit.

Looking through the tree, check_func_ptr_read() appears in a later commit (0ff120b53396 "bpf: Recognize pointers to functions in read-only maps"). That commit also enables loading PTR_TO_FUNC from map values, which isn't supported here.

Until then the comment has a dangling reference and describes a capability this commit doesn't have. The address-taken-in-another-function case is the only one that applies.

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

maintainer
#12 lore raw

Re: [PATCH bpf-next v2 06/17] bpf: Add callx calls to the call graph

In reply to Alexei Starovoitov

On Thu, 2026-09-24 at 03:10 +0000, Alexei Starovoitov wrote:

...

Quoted 5 lines

/*
* Sort subprogs in topological order so that leaf subprogs come first and
* their callers come later. This is a DFS post-order traversal of the call
* graph. Scan only reachable instructions (those in the computed postorder) of
* the current subprog to discover callees (direct subprogs and sync

Quoted 8 lines

* callbacks).
+ *
+ * The callees of callx are not known before the main verification pass.
+ * When callx is used the sort is repeated after it with the recorded callx
+ * edges added to the call graph to reject recursion through indirect calls. */
static int sort_subprogs_topo(struct bpf_verifier_env *env)
{

Changes to sort_subprogs_topo() and the second sort call are unnecessary. After changes to check_max_stack_depth_subprog() in patch #1 of this series the recursion will be detected there.

...

Quoted 10 lines
kernel/bpf/verifier.c +4 -0
@@ -21978,6 +22069,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	ret = do_check_main(env);
 	ret = ret ?: do_check_subprogs(env);
 
+	/* reject recursion through the callx edges found by the main pass */
+	if (ret == 0 && env->callx_edges)
+		ret = sort_subprogs_topo(env);
+
 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
 		ret = bpf_prog_offload_finalize(env);
#13 lore raw

PATCH v2 7/17 bpf, x86: Add JIT support for callx

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Emit indirect call via the register that holds the address of bpf subprog. ld_imm64 BPF_PSEUDO_FUNC is resolved to func[i]->bpf_func by jit_subprogs() already. It's the same address that is passed to helpers as a callback.

Add emit_indirect_call() similar to emit_indirect_jump() used by tail calls and gotox: use ITS or retpoline thunks when enabled. Save/restore r9 around the call when private stack is used, like direct calls do.

The verifier guarantees that callees of callx are not tail call reachable, so don't pass tail call counter in rax, which may hold the callee address.

FineIBT expects indirect callers to go through CFI preamble. Not done yet. Return false from bpf_jit_supports_callx() in this mode, so such progs are rejected at load time.

---
 arch/x86/net/bpf_jit_comp.c | 68 +++++++++++++++++++++++++++++++++++++
 1 file changed, 68 insertions(+)
arch/x86/net/bpf_jit_comp.c +68 -0
index d4a980140b48..9fbef7504e51 100644
@@ -749,6 +749,46 @@ static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip)
 	*pprog = prog;
 }
 
+static void __emit_indirect_call(u8 **pprog, int reg, bool ereg)
+{
+	u8 *prog = *pprog;
+
+	if (ereg)
+		EMIT1(0x41);
+
+	EMIT2(0xFF, 0xD0 + reg);
+
+	*pprog = prog;
+}
+
+/* call *bpf_reg */
+static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)
+{
+	u8 *prog = *pprog;
+	int reg = reg2hex[bpf_reg];
+	bool ereg = is_ereg(bpf_reg);
+	int err = 0;
+
+	if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) {
+		OPTIMIZER_HIDE_VAR(reg);
+		err = emit_call(&prog, its_static_thunk(reg + 8*ereg), ip);
+	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
+		EMIT_LFENCE();
+		__emit_indirect_call(&prog, reg, ereg);
+	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
+		OPTIMIZER_HIDE_VAR(reg);
+		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
+			err = emit_call(&prog, &__x86_indirect_call_thunk_array[reg + 8*ereg], ip);
+		else
+			err = emit_call(&prog, &__x86_indirect_thunk_array[reg + 8*ereg], ip);
+	} else {
+		__emit_indirect_call(&prog, reg, ereg);
+	}
+
+	*pprog = prog;
+	return err;
+}
+
 static void emit_return(u8 **pprog, u8 *ip)
 {
 	u8 *prog = *pprog;
@@ -2941,6 +2981,24 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			break;
 		}
 
+			/* callx: call of a bpf subprog whose address is in dst_reg */
+		case BPF_JMP | BPF_CALL | BPF_X:
+			/*
+			 * The verifier makes sure that callees of callx are
+			 * not tail call reachable, hence unlike a direct call
+			 * of a subprog there is no need to pass
+			 * tail_call_cnt_ptr in rax.
+			 */
+			if (priv_frame_ptr) {
+				push_r9(&prog);
+				ip += 2;
+			}
+			if (emit_indirect_call(&prog, insn->dst_reg, ip))
+				return -EINVAL;
+			if (priv_frame_ptr)
+				pop_r9(&prog);
+			break;
+
 		case BPF_JMP | BPF_TAIL_CALL:
 			if (imm32)
 				emit_bpf_tail_call_direct(bpf_prog,
@@ -4414,6 +4472,16 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 	return prog;
 }
 
+bool bpf_jit_supports_callx(void)
+{
+	/*
+	 * FineIBT poisons ENDBR at the entry of a JITed function and expects
+	 * indirect callers to go through the CFI preamble instead.
+	 * callx doesn't do that yet.
+	 */
+	return cfi_mode != CFI_FINEIBT;
+}
+
 bool bpf_jit_supports_kfunc_call(void)
 {
 	return true;
Signature · 1 line
2.55.0
maintainer
#14 lore raw

Re: [PATCH bpf-next v2 07/17] bpf, x86: Add JIT support for callx

On Thu, 2026-09-24 at 03:10 +0000, Alexei Starovoitov wrote:

...

Quoted 20 lines
arch/x86/net/bpf_jit_comp.c +12 -0
index d4a980140b48..9fbef7504e51 100644
@@ -749,6 +749,46 @@ static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip)
 	*pprog = prog;
 }
 
+static void __emit_indirect_call(u8 **pprog, int reg, bool ereg)
+{
+	u8 *prog = *pprog;
+
+	if (ereg)
+		EMIT1(0x41);
+
+	EMIT2(0xFF, 0xD0 + reg);
+
+	*pprog = prog;
+}
+

arch/x86/net/bpf_jit_comp.c static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip) · line 773

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +10 -0
+/* call *bpf_reg */
+static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)
+{
+	u8 *prog = *pprog;
+	int reg = reg2hex[bpf_reg];
+	bool ereg = is_ereg(bpf_reg);
+	int err = 0;
+
+	if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) {
+		OPTIMIZER_HIDE_VAR(reg);

This is quite unexpected. LLM points to [1].
A comment would be nice.

[1] commit be8a096521ca ("x86,bpf: Avoid IBT objtool warning")

Quoted 26 lines
arch/x86/net/bpf_jit_comp.c +19 -0
+		err = emit_call(&prog, its_static_thunk(reg + 8*ereg), ip);
+	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
+		EMIT_LFENCE();
+		__emit_indirect_call(&prog, reg, ereg);
+	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
+		OPTIMIZER_HIDE_VAR(reg);
+		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
+			err = emit_call(&prog, &__x86_indirect_call_thunk_array[reg + 8*ereg], ip);
+		else
+			err = emit_call(&prog, &__x86_indirect_thunk_array[reg + 8*ereg], ip);
+	} else {
+		__emit_indirect_call(&prog, reg, ereg);
+	}
+
+	*pprog = prog;
+	return err;
+}
+
 static void emit_return(u8 **pprog, u8 *ip)
 {
 	u8 *prog = *pprog;
@@ -2941,6 +2981,24 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			break;
 		}
 
+			/* callx: call of a bpf subprog whose address is in dst_reg */

arch/x86/net/bpf_jit_comp.c static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * · line 2994

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +10 -0
+		case BPF_JMP | BPF_CALL | BPF_X:
+			/*
+			 * The verifier makes sure that callees of callx are
+			 * not tail call reachable, hence unlike a direct call
+			 * of a subprog there is no need to pass
+			 * tail_call_cnt_ptr in rax.
+			 */
+			if (priv_frame_ptr) {
+				push_r9(&prog);
+				ip += 2;

LLM tells me the following:

This matters when emit_indirect_call() emits a relative call to a mitigation thunk:

displacement = thunk_address - (call_address + 5)

Without ip += 2, that displacement would be calculated from the push’s address, and the call would land two bytes past the intended target.

Which is not obvious at all.
Is it the reason for += 2?

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +7 -0
+			}
+			if (emit_indirect_call(&prog, insn->dst_reg, ip))
+				return -EINVAL;
+			if (priv_frame_ptr)
+				pop_r9(&prog);
+			break;
+
 		case BPF_JMP | BPF_TAIL_CALL:
 			if (imm32)
 				emit_bpf_tail_call_direct(bpf_prog,

...

#15 lore raw

PATCH v2 8/17 bpf, arm64: Add JIT support for callx

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Emit callx as BLR to the register with the address of the subprog and move x0 into BPF_REG_0 like after a direct call.

That's what a direct call of a subprog out of BL range is JITed into already. bpf functions start with BTI JC. The arguments are in x0-x7 and on the stack. Tail call counter ptr and private stack ptr are in callee saved x26 and x27.

---
 arch/arm64/net/bpf_jit_comp.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
arch/arm64/net/bpf_jit_comp.c +16 -0
index 6c04fee46876..9544b2f483e5 100644
@@ -1789,6 +1789,17 @@ static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn
 			emit(A64_MOV(1, r0, A64_R(0)), ctx);
 		break;
 	}
+	/* indirect call of a bpf subprog, dst holds its address */
+	case BPF_JMP | BPF_CALL | BPF_X:
+		/*
+		 * It's the same as a direct call of a subprog that is out of
+		 * range of BL: the subprog starts with BTI JC, the arguments
+		 * are in place, and the registers that hold the tail call
+		 * counter and the private stack are callee saved.
+		 */
+		emit(A64_BLR(dst), ctx);
+		emit(A64_MOV(1, bpf2a64[BPF_REG_0], A64_R(0)), ctx);
+		break;
 	/* tail call */
 	case BPF_JMP | BPF_TAIL_CALL:
 		if (emit_bpf_tail_call(ctx))
@@ -2485,6 +2496,11 @@ bool bpf_jit_supports_subprog_tailcalls(void)
 	return true;
 }
 
+bool bpf_jit_supports_callx(void)
+{
+	return true;
+}
+
 static void invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_node *node,
 			    int bargs_off, int retval_off, int run_ctx_off,
 			    bool save_ret)
Signature · 1 line
2.55.0
#16 lore raw

PATCH v2 9/17 bpf: Discover subprogs described by func_info

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

add_subprogs() finds subprogs by scanning insns for calls and ld_imm64 BPF_PSEUDO_FUNC. A function that is called via callx through a pointer in data only, e.g. a vtable, is not referenced by any insn, but it must be known before check_cfg() and the main pass.

func_info describes all functions of the program and libbpf provides it for every function it puts into the prog. bpf_prepare_btf_info() reads it before add_subprogs(). Register every function from func_info as a subprog.

func_info had to match the subprogs found in insns exactly, so existing programs are not affected. A function that is listed in func_info and not referenced by anything is still rejected by check_cfg() as unreachable.

---
 kernel/bpf/verifier.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
kernel/bpf/verifier.c +16 -0
index d00d0ecab17c..71b8825ffe1d 100644
@@ -3023,6 +3023,22 @@ static int add_subprogs(struct bpf_verifier_env *env)
 			return ret;
 	}
 
+	/*
+	 * func_info describes all functions of the program. Those that are
+	 * referenced only from data, e.g. from a table of functions to be
+	 * called via callx, are not seen by the loop above. They are possible
+	 * callees that have to be known upfront as well.
+	 */
+	if (env->bpf_capable) {
+		struct bpf_prog_aux *aux = env->prog->aux;
+
+		for (i = 1; i < aux->func_info_cnt; i++) {
+			ret = add_subprog(env, aux->func_info[i].insn_off);
+			if (ret < 0)
+				return ret;
+		}
+	}
+
 	ret = bpf_find_exception_callback_insn_off(env);
 	if (ret < 0)
 		return ret;
Signature · 1 line
2.55.0
maintainer Acked-by on v2 9/17
#17 lore raw

Re: [PATCH bpf-next v2 09/17] bpf: Discover subprogs described by func_info

Quoted 12 lines · Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

add_subprogs() finds subprogs by scanning insns for calls and ld_imm64 BPF_PSEUDO_FUNC. A function that is called via callx through a pointer in data only, e.g. a vtable, is not referenced by any insn, but it must be known before check_cfg() and the main pass.

func_info describes all functions of the program and libbpf provides it for every function it puts into the prog. bpf_prepare_btf_info() reads it before add_subprogs(). Register every function from func_info as a subprog.

Quoted 7 lines

func_info had to match the subprogs found in insns exactly, so existing programs are not affected. A function that is listed in func_info and not referenced by anything is still rejected by check_cfg() as unreachable.

---

...

#18 lore raw

PATCH v2 10/17 bpf: Recognize pointers to functions in read-only maps

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Compilers put pointers to functions into read-only data: tables of functions, struct ops, vtables, where they're mixed with sizes, alignments and other data. Rust vtables are like that. Let callx call through them:

r6 = vtable ll
r1 = *(u64 *)(r6 + 0) // data
r2 = *(u64 *)(r6 + 8) // pointer to a function
callx r2

libbpf keeps such data in a frozen read-only array map like .rodata and stores the byte offset of static function within the program into the pointer. The kernel guesses: aligned 64-bit value that is equal to the offset of a static subprog is a pointer to it. If the guess is wrong the program either fails to load, since it uses a pointer as a number, or sees an address instead of the number. Safe either way.

Add resolve_func_ptrs() that scans such maps of a program with callx after the maps are resolved and before check_cfg(), so all callees of callx, including the ones referenced by data only, are known before the main pass. The prog must be the only user of the map and it must be allowed to leak pointers (CAP_PERFMON), since it reads function addresses as data.

- check_cfg() treats ld_imm64 of such map like ld_imm64 BPF_PSEUDO_FUNC for every function in the map: they're reachable, first insns are prune and jump points, effects are merged into the subprog that refers to the map.

- 64-bit load of the pointer is PTR_TO_FUNC. If the offset is variable (tbl[i]) all possible offsets, given bounds and var_off, must be pointers. The verifier forks a state for each. If none of them overlaps with a pointer (tbl[i].data) it's a regular load.

- The value of the pointer is not known until JIT, so reject everything that would const-fold its bytes: narrow or misaligned loads, const strings. bpf_compute_const_regs() skips them too.

- The map has offsets until JIT, so the load of the pointer sets jit_required like callx does. Otherwise the prog that reads the pointer and passes it to a helper as a callback could run in the interpreter.

After JIT jit_subprogs() replaces the offsets in the map with addresses of functions. Other progs that use the map were verified with its old content const-folded, so there must be none. Add 'user' to bpf_map:
__add_used_map() records the first prog that uses the map and marks the map as shared when another prog comes. Only the sole user can store addresses into the map. After that no other prog can use it. The prog that failed to load is not a user. libbpf loads it again to get the log.

The offsets are adjusted when insns are patched or removed, same as subprog starts. Dead function is removed and the pointer becomes NULL. The prog may still read it, e.g. when the load is hoisted above a branch, but callx of it is dead code too.

---
 include/linux/bpf.h          |  10 +
 include/linux/bpf_verifier.h |  29 +++
 kernel/bpf/cfg.c             |  76 +++++++
 kernel/bpf/const_fold.c      |   3 +
 kernel/bpf/core.c            |   5 +
 kernel/bpf/fixups.c          |  65 +++++-
 kernel/bpf/verifier.c        | 386 ++++++++++++++++++++++++++++++++++-
 7 files changed, 565 insertions(+), 9 deletions(-)
include/linux/bpf.h +10 -0
index e7c5e203eddd..9525d3ecd923 100644
@@ -344,8 +344,18 @@ struct bpf_map {
 	s64 __percpu *elem_count;
 	u64 cookie; /* write-once */
 	char *excl_prog_sha;
+	/*
+	 * Which programs use the map, see bpf_map_claim(): 0 - none so far,
+	 * aux of the program - only that one, the same with BPF_MAP_USER_PATCHED
+	 * set - only that one and it stored the addresses of its functions into
+	 * the map, BPF_MAP_USER_MANY - more than one.
+	 */
+	unsigned long user;
 };
 
+#define BPF_MAP_USER_MANY	1UL
+#define BPF_MAP_USER_PATCHED	1UL
+
 static inline const char *btf_field_type_name(enum btf_field_type type)
 {
 	switch (type) {
include/linux/bpf_verifier.h +29 -0
index 931f305fa440..578bccf5cf76 100644
@@ -786,6 +786,21 @@ int bpf_log_attr_finalize(struct bpf_log_attr *attr, struct bpf_verifier_log *lo
 
 #define BPF_MAX_SUBPROGS 256
 
+/*
+ * A pointer to a static subprog in the value of a frozen read-only array map:
+ * a 64-bit value that is the offset in bytes of the first instruction of
+ * the subprog in the program.
+ */
+struct bpf_func_ptr {
+	struct bpf_map *map;
+	u32 map_off;		/* offset of the pointer in the value of the map */
+	u32 orig_off;		/* what the map has: the first instruction of the subprog */
+	u32 xlated_off;		/* the same after instructions were patched and removed */
+};
+
+/* the subprog that a bpf_func_ptr pointed to was removed as dead code */
+#define BPF_FUNC_PTR_DELETED ((u32)-1)
+
 struct bpf_subprog_arg_info {
 	enum bpf_arg_type arg_type;
 	union {
@@ -965,6 +980,13 @@ struct bpf_verifier_env {
 	struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */
 	/* subprog indices sorted in topological order: leaves first, callers last */
 	int subprog_topo_order[BPF_MAX_SUBPROGS + 2];
+	/*
+	 * Pointers to static subprogs found in frozen read-only maps of the
+	 * program, see resolve_func_ptrs(). Sorted by map and map_off.
+	 */
+	struct bpf_func_ptr *func_ptrs;
+	u32 func_ptr_cnt;
+	bool has_callx;
 	/*
 	 * Call graph edges created by callx instructions. A bitmap of
 	 * subprog_cnt * subprog_cnt bits, where bit (caller * subprog_cnt + callee)
@@ -1324,6 +1346,13 @@ static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u
 }
 
 bool bpf_map_is_rdonly(const struct bpf_map *map);
+struct bpf_func_ptr *bpf_map_func_ptrs(struct bpf_verifier_env *env,
+				       const struct bpf_map *map, u32 *cnt);
+struct bpf_func_ptr *bpf_map_range_func_ptrs(struct bpf_verifier_env *env,
+					     const struct bpf_map *map,
+					     u64 off, u64 size, u32 *cnt);
+void bpf_adjust_func_ptrs(struct bpf_verifier_env *env, u32 off, u32 len);
+void bpf_adjust_func_ptrs_after_remove(struct bpf_verifier_env *env, u32 off, u32 len);
 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
 			bool is_ldsx);
 
kernel/bpf/cfg.c +76 -0

93 lines not on this page · raw message

kernel/bpf/const_fold.c +3 -0
index 28dec733e596..b1528adbeb79 100644
@@ -180,9 +180,12 @@ static void const_reg_xfer(struct bpf_verifier_env *env, struct const_arg_info *
 		bool is_ldsx = mode == BPF_MEMSX;
 		int off = src->val + insn->off;
 		u64 val = 0;
+		u32 cnt;
 
 		if (!bpf_map_is_rdonly(map) || !map->ops->map_direct_value_addr ||
 		    off < 0 || off + size > map->value_size ||
+		    /* so are the addresses of functions that the map points to */
+		    bpf_map_range_func_ptrs(env, map, off, size, &cnt) ||
 		    bpf_map_direct_read(map, off, size, &val, is_ldsx)) {
 			*dst = unknown;
 			break;
kernel/bpf/core.c +5 -0
index 868350977f0c..273f74068068 100644
@@ -3029,6 +3029,11 @@ void __bpf_free_used_maps(struct bpf_prog_aux *aux,
 			map->ops->map_poke_untrack(map, aux);
 		if (sleepable)
 			atomic64_dec(&map->sleepable_refcnt);
+		/*
+		 * The program that didn't load is not a user of the map. libbpf
+		 * loads the program again to get the log of the verifier.
+		 */
+		cmpxchg(&map->user, (unsigned long)aux, 0);
 		bpf_map_put(map);
 	}
 }
kernel/bpf/fixups.c +64 -1

96 lines not on this page · raw message

kernel/bpf/verifier.c +378 -8

476 lines not on this page · raw message

Signature · 1 line
2.55.0
#19 lore raw

PATCH v2 11/17 libbpf: Support pointers to static functions in data when linking

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A pointer to a static function in data, e.g.

  static int (* const handlers[])(void *ctx) = { foo, bar };

is R_BPF_64_ABS64 relocation against .text section symbol with the offset of the function stored in place. The linker rejects it:

relocation against STT_SECTION in non-exec section is not supported!

so an object with a table of static functions cannot go through 'bpftool gen object', which all selftests do.

Functions move by the offset of input .text in the output section. Add it to the pointer. Swap bytes if the object is of foreign endianness, since data sections are kept in the byte order of the object.

---
 tools/lib/bpf/linker.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
tools/lib/bpf/linker.c +18 -0
index 78f92c39290a..53f64a1a1f25 100644
@@ -2274,6 +2274,24 @@ static int linker_append_elf_relos(struct bpf_linker *linker, struct src_obj *ob
 						insn->imm += sec->dst_off / sizeof(struct bpf_insn);
 					else
 						insn->imm += sec->dst_off;
+				} else if (sym_type == R_BPF_64_ABS64 &&
+					   (sec->shdr->sh_flags & SHF_EXECINSTR)) {
+					/*
+					 * A pointer to a static function in a data section,
+					 * which is stored in place as an offset of the
+					 * function in its section. Data sections are kept
+					 * in the byte order of the object.
+					 */
+					void *ptr = dst_linked_sec->raw_data + dst_rel->r_offset;
+					__u64 off;
+
+					memcpy(&off, ptr, sizeof(off));
+					if (linker->swapped_endian)
+						off = bswap_64(off);
+					off += sec->dst_off;
+					if (linker->swapped_endian)
+						off = bswap_64(off);
+					memcpy(ptr, &off, sizeof(off));
 				} else {
 					pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
 					return -EINVAL;
Signature · 1 line
2.55.0
#20 lore raw

PATCH v2 12/17 libbpf: Resolve pointers to functions in read-only data

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The kernel recognizes a pointer to a function in frozen read-only array map by value: byte offset of a static function in the program. Make it work for tables of functions, struct ops, vtables in .rodata:

  static const struct shape_ops square_ops = { 1, area, 10, perimeter };
  ...
  return ops->area(x) * ops->scale;

is compiled into

r3 = *(u64 *)(r1 + 8)
callx r3

where 'area' in .rodata is R_BPF_64_ABS64 relocation against .text.

- Collect relocations in .rodata* that are aligned pointers to functions. Relocations in data were ignored. The rest still are.

- Append all static functions that the section points to, since any of them can be called, if the prog refers to the section and has callx. callx cannot call global functions. Don't pull them in. Such pointer is NULL.

- Functions have different offsets in different progs, so create a copy of the map per prog and store the offsets there. The kernel replaces them with addresses at load and the prog must be the only user of the map. The map of the section itself is left as-is.

- Progs without callx cannot call them and the kernel doesn't look for pointers in their data. They keep using the map of the section and nothing is appended to them.

- The kernel treats any aligned u64 that matches an offset of a static function as a pointer. Warn if data has one that isn't.

Light skeleton is not supported yet.

---
 tools/lib/bpf/libbpf.c | 381 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 377 insertions(+), 4 deletions(-)
tools/lib/bpf/libbpf.c +377 -4
index cd1ea1bb53cb..fc9b7540aca6 100644
@@ -497,6 +497,8 @@ struct bpf_program {
 	bool autoload;
 	bool autoattach;
 	bool sym_global;
+	/* the program or a function that it calls has callx */
+	bool has_callx;
 	bool mark_btf_static;
 	enum bpf_prog_type type;
 	enum bpf_attach_type expected_attach_type;
@@ -601,6 +603,9 @@ struct bpf_map {
 	bool autoattach;
 	__u64 map_extra;
 	struct bpf_program *excl_prog;
+	/* pointers to functions in the data of an internal map, see obj->func_ptrs */
+	struct func_ptr *func_ptrs;
+	size_t func_ptr_cnt;
 };
 
 enum extern_type {
@@ -780,6 +785,29 @@ struct bpf_object {
 	} *jumptable_maps;
 	size_t jumptable_map_cnt;
 
+	/*
+	 * Pointers to functions found in read-only data sections: tables of
+	 * functions, structures of operations, vtables. Sorted by section
+	 * and offset.
+	 */
+	struct func_ptr {
+		int sec_idx;		/* ELF section that contains the pointer */
+		size_t sec_off;		/* offset of the pointer in the section */
+		size_t text_off;	/* offset of the function in .text section */
+	} *func_ptrs;
+	size_t func_ptr_cnt;
+
+	/*
+	 * Read-only data with pointers to functions is different for every
+	 * program that uses it, because so are the offsets of the functions.
+	 */
+	struct {
+		struct bpf_program *prog;
+		int map_idx;
+		int fd;
+	} *func_ptr_maps;
+	size_t func_ptr_map_cnt;
+
 	struct kern_feature_cache *feat_cache;
 	char *token_path;
 	int token_fd;
@@ -845,6 +873,16 @@ static bool insn_is_pseudo_func(struct bpf_insn *insn)
 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
 }
 
+static bool prog_has_callx(const struct bpf_program *prog)
+{
+	size_t i;
+
+	for (i = 0; i < prog->insns_cnt; i++)
+		if (prog->insns[i].code == (BPF_JMP | BPF_CALL | BPF_X))
+			return true;
+	return false;
+}
+
 static int
 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
 		      const char *name, size_t sec_idx, const char *sec_name,
@@ -4068,8 +4106,14 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
 			    targ_sec_idx >= obj->efile.sec_cnt)
 				return -LIBBPF_ERRNO__FORMAT;
 
-			/* Only do relo for section with exec instructions */
+			/*
+			 * Only do relo for section with exec instructions,
+			 * struct_ops, maps, and read-only data that might
+			 * have pointers to functions.
+			 */
 			if (!section_have_execinstr(obj, targ_sec_idx) &&
+			    strcmp(name, ".rel" RODATA_SEC) &&
+			    !str_has_pfx(name, ".rel" RODATA_SEC ".") &&
 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
@@ -6471,6 +6515,136 @@ static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struc
 	return err;
 }
 
+/*
+ * The kernel recognizes a pointer to a function in a frozen read-only map by
+ * its value: the offset in bytes of the function in the program. It makes
+ * callx work for tables of functions, structures of operations and vtables,
+ * where pointers are mixed with other data. Functions have different offsets
+ * in different programs, so create a copy of the map for the program.
+ * The kernel replaces the offsets with the addresses of the functions when it
+ * loads the program, which has to be the only user of the map.
+ */
+static int create_func_ptr_map(struct bpf_object *obj, struct bpf_program *prog, int map_idx)
+{
+	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_RDONLY_PROG);
+	struct bpf_map *map = &obj->maps[map_idx];
+	__u32 value_size = map->def.value_size;
+	size_t i, j, cnt, sec_insn_off;
+	struct func_ptr *ptrs;
+	int map_fd, err, zero = 0;
+	__u64 val;
+	void *data, *tmp;
+
+	for (i = 0; i < obj->func_ptr_map_cnt; i++)
+		if (obj->func_ptr_maps[i].prog == prog &&
+		    obj->func_ptr_maps[i].map_idx == map_idx)
+			return obj->func_ptr_maps[i].fd;
+
+	if (obj->gen_loader) {
+		pr_warn("prog '%s': map '%s': pointers to functions in data are not supported by light skeleton\n",
+			prog->name, map->name);
+		return -ENOTSUP;
+	}
+
+	/* the map is not created yet, what it's going to have is in mmaped */
+	if (!map->mmaped)
+		return -EINVAL;
+
+	data = malloc(value_size);
+	if (!data)
+		return -ENOMEM;
+	memcpy(data, map->mmaped, value_size);
+
+	ptrs = map->func_ptrs;
+	cnt = map->func_ptr_cnt;
+	for (i = 0; i < cnt; i++) {
+		if (ptrs[i].sec_off + sizeof(val) > value_size) {
+			err = -LIBBPF_ERRNO__FORMAT;
+			goto err_free;
+		}
+		/*
+		 * Static functions were appended by bpf_object__append_func_ptrs_code().
+		 * A global function is in the program only if the code refers to it.
+		 */
+		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
+		for (j = 0; j < prog->subprog_cnt; j++)
+			if (prog->subprogs[j].sec_insn_off == sec_insn_off)
+				break;
+		if (j == prog->subprog_cnt) {
+			pr_debug("prog '%s': map '%s': no function for the pointer at offset %zu, it's NULL\n",
+				 prog->name, map->name, ptrs[i].sec_off);
+			val = 0;
+		} else {
+			val = (__u64)prog->subprogs[j].sub_insn_off * BPF_INSN_SZ;
+		}
+		memcpy(data + ptrs[i].sec_off, &val, sizeof(val));
+	}
+
+	/*
+	 * The kernel takes any aligned 64-bit value that is equal to the offset
+	 * of a function for a pointer. Tell when it's going to get it wrong.
+	 */
+	for (i = 0, j = 0; i + sizeof(val) <= value_size; i += sizeof(val)) {
+		__u32 k;
+
+		while (j < cnt && ptrs[j].sec_off < i)
+			j++;
+		if (j < cnt && ptrs[j].sec_off == i)
+			continue;
+		memcpy(&val, data + i, sizeof(val));
+		if (!val || val % BPF_INSN_SZ)
+			continue;
+		for (k = 0; k < prog->subprog_cnt; k++) {
+			if ((__u64)prog->subprogs[k].sub_insn_off * BPF_INSN_SZ != val)
+				continue;
+			pr_warn("prog '%s': map '%s': value %llu at offset %zu is the offset of a function, the kernel will treat it as a pointer to it\n",
+				prog->name, map->name, (unsigned long long)val, i);
+			break;
+		}
+	}
+
+	opts.token_fd = obj->token_fd;
+	if (obj->token_fd)
+		opts.map_flags |= BPF_F_TOKEN_FD;
+
+	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, map->name, sizeof(int), value_size, 1, &opts);
+	if (map_fd < 0) {
+		err = map_fd;
+		goto err_free;
+	}
+
+	err = bpf_map_update_elem(map_fd, &zero, data, 0);
+	if (!err)
+		err = bpf_map_freeze(map_fd);
+	if (err) {
+		err = -errno;
+		goto err_close;
+	}
+
+	tmp = libbpf_reallocarray(obj->func_ptr_maps, obj->func_ptr_map_cnt + 1,
+				  sizeof(*obj->func_ptr_maps));
+	if (!tmp) {
+		err = -ENOMEM;
+		goto err_close;
+	}
+	obj->func_ptr_maps = tmp;
+	obj->func_ptr_maps[obj->func_ptr_map_cnt].prog = prog;
+	obj->func_ptr_maps[obj->func_ptr_map_cnt].map_idx = map_idx;
+	obj->func_ptr_maps[obj->func_ptr_map_cnt].fd = map_fd;
+	obj->func_ptr_map_cnt++;
+
+	pr_debug("prog '%s': created a copy of map '%s' with %zu pointers to functions\n",
+		 prog->name, map->name, cnt);
+	free(data);
+	return map_fd;
+
+err_close:
+	close(map_fd);
+err_free:
+	free(data);
+	return err;
+}
+
 /* Relocate data references within program code:
  *  - map references;
  *  - global variable references;
@@ -6508,7 +6682,19 @@ bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
 			if (relo->map_idx == obj->arena_map_idx)
 				insn[1].imm += obj->arena_data_off;
 
-			if (obj->gen_loader) {
+			if (map->autocreate && map->func_ptr_cnt && prog->has_callx) {
+				int map_fd;
+
+				/* the program gets its own map with pointers to its functions */
+				map_fd = create_func_ptr_map(obj, prog, relo->map_idx);
+				if (map_fd < 0) {
+					pr_warn("prog '%s': relo #%d: can't create a copy of map '%s' with pointers to functions\n",
+						prog->name, i, map->name);
+					return map_fd;
+				}
+				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
+				insn[0].imm = map_fd;
+			} else if (obj->gen_loader) {
 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
 				insn[0].imm = relo->map_idx;
 			} else if (map->autocreate) {
@@ -6944,6 +7130,75 @@ bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
 	return 0;
 }
 
+/* Append to the main program all functions that the data of the map points to */
+static int
+bpf_object__append_func_ptrs_code(struct bpf_object *obj, struct bpf_program *main_prog,
+				  const struct bpf_map *map)
+{
+	struct bpf_program *subprog;
+	size_t i, cnt, sec_insn_off;
+	struct func_ptr *ptrs;
+	int err;
+
+	ptrs = map->func_ptrs;
+	cnt = map->func_ptr_cnt;
+	for (i = 0; i < cnt; i++) {
+		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
+		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sec_insn_off);
+		if (!subprog || subprog->sec_insn_off != sec_insn_off) {
+			pr_warn("prog '%s': map '%s': no function at .text+%zu for the pointer at offset %zu\n",
+				main_prog->name, map->name, ptrs[i].text_off, ptrs[i].sec_off);
+			return -LIBBPF_ERRNO__RELOC;
+		}
+
+		/*
+		 * callx can't call global functions. Don't add one to the
+		 * program only because the data points to it.
+		 */
+		if (subprog->sym_global)
+			continue;
+
+		/* see the comment in bpf_object__reloc_code() */
+		if (subprog->sub_insn_off == 0) {
+			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
+			if (err)
+				return err;
+			err = bpf_object__reloc_code(obj, main_prog, subprog);
+			if (err)
+				return err;
+		}
+	}
+	return 0;
+}
+
+/*
+ * The program that has callx might call any function that the data it refers
+ * to points to. Append them. Programs that don't have callx can't call them
+ * and the kernel doesn't look for pointers to functions in their data.
+ */
+static int
+bpf_object__append_func_ptrs(struct bpf_object *obj, struct bpf_program *prog)
+{
+	size_t i;
+	int err;
+
+	prog->has_callx = prog_has_callx(prog);
+	if (!prog->has_callx)
+		return 0;
+
+	/* relocations of the functions that are appended are appended too */
+	for (i = 0; i < prog->nr_reloc; i++) {
+		struct reloc_desc *relo = &prog->reloc_desc[i];
+
+		if (relo->type != RELO_DATA || !obj->maps[relo->map_idx].func_ptr_cnt)
+			continue;
+		err = bpf_object__append_func_ptrs_code(obj, prog, &obj->maps[relo->map_idx]);
+		if (err)
+			return err;
+	}
+	return 0;
+}
+
 /*
  * Relocate sub-program calls.
  *
@@ -7046,7 +7301,7 @@ bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
 	if (err)
 		return err;
 
-	return 0;
+	return bpf_object__append_func_ptrs(obj, prog);
 }
 
 static void
@@ -7757,6 +8012,98 @@ static int bpf_object__collect_map_relos(struct bpf_object *obj,
 	return 0;
 }
 
+/*
+ * Collect pointers to functions in a read-only data section. They are
+ * R_BPF_64_ABS64 relocations against .text section, where the offset of
+ * a static function in the section is stored in place. Relocations in data
+ * sections were ignored before pointers to functions were supported. Those
+ * that are something else, e.g. pointers to data, still are.
+ */
+static int bpf_object__collect_rodata_relos(struct bpf_object *obj,
+					    Elf64_Shdr *shdr, Elf_Data *data)
+{
+	size_t sec_idx = shdr->sh_info, sym_idx;
+	int i, nrels = shdr->sh_size / shdr->sh_entsize;
+	const char *relo_sec_name;
+	struct func_ptr *ptrs;
+	Elf_Data *scn_data;
+	Elf64_Sym *sym;
+	Elf64_Rel *rel;
+	__u64 addend;
+
+	relo_sec_name = elf_sec_str(obj, shdr->sh_name) ?: "<?>";
+	scn_data = obj->efile.secs[sec_idx].data;
+	if (!scn_data)
+		return -LIBBPF_ERRNO__FORMAT;
+
+	for (i = 0; i < nrels; i++) {
+		rel = elf_rel_by_idx(data, i);
+		if (!rel) {
+			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
+			return -LIBBPF_ERRNO__FORMAT;
+		}
+
+		sym_idx = ELF64_R_SYM(rel->r_info);
+		sym = elf_sym_by_idx(obj, sym_idx);
+		if (!sym) {
+			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
+				relo_sec_name, sym_idx, i);
+			return -LIBBPF_ERRNO__FORMAT;
+		}
+
+		if (ELF64_R_TYPE(rel->r_info) != R_BPF_64_ABS64 ||
+		    !sym_is_subprog(sym, obj->efile.text_shndx)) {
+			pr_debug("sec '%s': relo #%d: not a pointer to a function, skipping...\n",
+				 relo_sec_name, i);
+			continue;
+		}
+
+		/* the kernel finds aligned pointers only */
+		if (rel->r_offset % sizeof(__u64) || rel->r_offset >= scn_data->d_size ||
+		    scn_data->d_size - rel->r_offset < sizeof(__u64)) {
+			pr_debug("sec '%s': relo #%d: unsupported offset 0x%zx, skipping...\n",
+				 relo_sec_name, i, (size_t)rel->r_offset);
+			continue;
+		}
+
+		memcpy(&addend, scn_data->d_buf + rel->r_offset, sizeof(addend));
+		if (!is_native_endianness(obj))
+			addend = bswap_64(addend);
+		if ((sym->st_value + addend) % BPF_INSN_SZ) {
+			pr_debug("sec '%s': relo #%d: bad pointer to a function at offset %zu+%llu, skipping...\n",
+				 relo_sec_name, i, (size_t)sym->st_value,
+				 (unsigned long long)addend);
+			continue;
+		}
+
+		ptrs = libbpf_reallocarray(obj->func_ptrs, obj->func_ptr_cnt + 1, sizeof(*ptrs));
+		if (!ptrs)
+			return -ENOMEM;
+		obj->func_ptrs = ptrs;
+
+		ptrs[obj->func_ptr_cnt].sec_idx = sec_idx;
+		ptrs[obj->func_ptr_cnt].sec_off = rel->r_offset;
+		ptrs[obj->func_ptr_cnt].text_off = sym->st_value + addend;
+		obj->func_ptr_cnt++;
+
+		pr_debug("sec '%s': relo #%d: pointer at offset %zu to a function at .text+%zu\n",
+			 relo_sec_name, i, (size_t)rel->r_offset, (size_t)(sym->st_value + addend));
+	}
+	return 0;
+}
+
+static int cmp_func_ptrs(const void *_a, const void *_b)
+{
+	const struct func_ptr *a = _a;
+	const struct func_ptr *b = _b;
+
+	if (a->sec_idx != b->sec_idx)
+		return a->sec_idx < b->sec_idx ? -1 : 1;
+	if (a->sec_off != b->sec_off)
+		return a->sec_off < b->sec_off ? -1 : 1;
+	return 0;
+}
+
 static int bpf_object__collect_relos(struct bpf_object *obj)
 {
 	int i, err;
@@ -7779,7 +8126,9 @@ static int bpf_object__collect_relos(struct bpf_object *obj)
 			return -LIBBPF_ERRNO__INTERNAL;
 		}
 
-		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
+		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_ST_OPS)
 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
 		else if (idx == obj->efile.btf_maps_shndx)
 			err = bpf_object__collect_map_relos(obj, shdr, data);
@@ -7789,6 +8138,25 @@ static int bpf_object__collect_relos(struct bpf_object *obj)
 			return err;
 	}
 
+	/* sort by section, so that pointers in the data of a map are next to each other */
+	if (obj->func_ptr_cnt)
+		qsort(obj->func_ptrs, obj->func_ptr_cnt, sizeof(*obj->func_ptrs), cmp_func_ptrs);
+
+	for (i = 0; i < obj->nr_maps; i++) {
+		struct bpf_map *map = &obj->maps[i];
+		size_t j;
+
+		if (map->libbpf_type != LIBBPF_MAP_RODATA)
+			continue;
+		for (j = 0; j < obj->func_ptr_cnt; j++) {
+			if (obj->func_ptrs[j].sec_idx != map->sec_idx)
+				continue;
+			if (!map->func_ptr_cnt)
+				map->func_ptrs = &obj->func_ptrs[j];
+			map->func_ptr_cnt++;
+		}
+	}
+
 	bpf_object__sort_relos(obj);
 	return 0;
 }
@@ -9749,6 +10117,11 @@ void bpf_object__close(struct bpf_object *obj)
 		close(obj->jumptable_maps[i].fd);
 	zfree(&obj->jumptable_maps);
 
+	for (i = 0; i < obj->func_ptr_map_cnt; i++)
+		close(obj->func_ptr_maps[i].fd);
+	zfree(&obj->func_ptr_maps);
+	zfree(&obj->func_ptrs);
+
 	if (obj->btf_module_allowlist) {
 		for (i = 0; i < obj->btf_module_allowlist_cnt; i++)
 			zfree(&obj->btf_module_allowlist[i]);
Signature · 1 line
2.55.0
#21 lore raw

Re: [PATCH bpf-next v2 12/17] libbpf: Resolve pointers to functions in read-only data

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] bpf: exception callbacks bypass callx and func ptr evaluation --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] bpf: exception callbacks bypass callx and func ptr evaluation
--

commit 977905067f5778d4a89e59b4be93e1e229b29d4a
Author: Alexei Starovoitov <[email protected]>

libbpf: Resolve pointers to functions in read-only data

This patch enables libbpf to resolve pointers to static functions located in read-only data, such as struct ops or vtables. It creates per-program map copies containing the proper offsets, which the kernel later replaces with addresses. Programs utilizing callx automatically have statically referenced subprograms appended during relocation.

Quoted 4 lines
tools/lib/bpf/libbpf.c +0 -0
index cd1ea1bb53cbf..fc9b7540aca63 100644

[ ... ]

tools/lib/bpf/libbpf.c bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog) · line 7306

Quoted 8 lines
tools/lib/bpf/libbpf.c +1 -1
@@ -7046,7 +7301,7 @@ bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
 	if (err)
 		return err;
 
-	return 0;
+	return bpf_object__append_func_ptrs(obj, prog);
 }
 

[Severity: Medium]
Will this miss callx instructions and function pointers used inside exception callbacks?

Looking at bpf_object__relocate() in tools/lib/bpf/libbpf.c, bpf_object__relocate_calls() is executed before exception callbacks are appended:

tools/lib/bpf/libbpf.c:bpf_object__relocate() {
    ...
    err = bpf_object__relocate_calls(obj, prog);
    if (err) {
        ...
    }

    err = bpf_prog_assign_exc_cb(obj, prog);
    if (err)
        return err;

    if (prog->exception_cb_idx >= 0) {
        ...
        if (subprog->sub_insn_off == 0) {
            err = bpf_object__append_subprog_code(obj, prog, subprog);
            ...
        }
    }
    ...
}

If the exception callback contains a callx instruction or references a function pointer map, it seems they would bypass the bpf_object__append_func_ptrs() evaluation. This could cause their read-only maps to be mis-relocated since the has_callx state and subprogram appending are finalized prior to processing the exception callback.

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

PATCH v2 13/17 libbpf: Treat .data.rel.ro as read-only data

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

PIC code keeps constants with pointers, e.g. vtables, in .data.rel.ro instead of .rodata. Nothing writes there after relocation. libbpf treats every .data* section as writable, while the kernel looks for pointers to functions in frozen read-only maps only.

Make .data.rel.ro and .data.rel.ro.* maps read-only and frozen like .rodata and collect pointers to functions there.

---
 tools/lib/bpf/libbpf.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
tools/lib/bpf/libbpf.c +14 -0
index fc9b7540aca6..2e0cf7c5ae23 100644
@@ -546,6 +546,7 @@ struct bpf_struct_ops {
 #define PERCPU_SEC ".percpu"
 #define BSS_SEC ".bss"
 #define RODATA_SEC ".rodata"
+#define DATA_REL_RO_SEC ".data.rel.ro"
 #define KCONFIG_SEC ".kconfig"
 #define KSYMS_SEC ".ksyms"
 #define STRUCT_OPS_SEC ".struct_ops"
@@ -4062,6 +4063,17 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
 				err = bpf_object__add_programs(obj, data, name, idx);
 				if (err)
 					return err;
+			} else if (strcmp(name, DATA_REL_RO_SEC) == 0 ||
+				   str_has_pfx(name, DATA_REL_RO_SEC ".")) {
+				/*
+				 * Constants with pointers in them, e.g. vtables,
+				 * that position independent code keeps here to
+				 * have them relocated. There is nothing that
+				 * writes to it after that.
+				 */
+				sec_desc->sec_type = SEC_RODATA;
+				sec_desc->shdr = sh;
+				sec_desc->data = data;
 			} else if (strcmp(name, DATA_SEC) == 0 ||
 				   str_has_pfx(name, DATA_SEC ".")) {
 				sec_desc->sec_type = SEC_DATA;
@@ -4114,6 +4126,8 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
 			if (!section_have_execinstr(obj, targ_sec_idx) &&
 			    strcmp(name, ".rel" RODATA_SEC) &&
 			    !str_has_pfx(name, ".rel" RODATA_SEC ".") &&
+			    strcmp(name, ".rel" DATA_REL_RO_SEC) &&
+			    !str_has_pfx(name, ".rel" DATA_REL_RO_SEC ".") &&
 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
Signature · 1 line
2.55.0
#23 lore raw

PATCH v2 14/17 libbpf: Support pointers to functions in read-only data in light skeleton

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Light skeleton doesn't create maps. The loader prog does at run time. Teach gen_loader to create a copy of .rodata map with offsets of functions for a prog, see create_func_ptr_map().

- Such maps are not maps of the object and are not in the loader ctx. Reserve slots in fd_array after the maps of the object for them and close their fds when the loader is done or fails. The progs hold them. Which progs have callx is not known when the loader is initialized, so reserve for every prog if .text has callx and for the progs that have callx otherwise.

- Add bpf_gen__func_ptr_map_create() that emits map create, update, freeze and returns the index in fd_array for ld_imm64 BPF_PSEUDO_MAP_IDX_VALUE.

- User space can set .rodata before loading the skeleton, see initial_value in bpf_map_desc. Copy it into the copy of the map as well and store the offsets of functions on top, since user space doesn't have them.

- Light skeleton can be generated for a target of another endianness. Store the offsets in the byte order of the object.

---
 tools/lib/bpf/bpf_gen_internal.h |  13 ++-
 tools/lib/bpf/gen_loader.c       | 172 ++++++++++++++++++++++++-------
 tools/lib/bpf/libbpf.c           |  66 ++++++++++--
 3 files changed, 204 insertions(+), 47 deletions(-)
tools/lib/bpf/bpf_gen_internal.h +12 -1
index 6c5ad6c55e8a..206adf28793d 100644
@@ -51,9 +51,17 @@ struct bpf_gen {
 	__u32 nr_ksyms;
 	int fd_array;
 	int nr_fd_array;
+	/*
+	 * Maps with pointers to functions, that programs get their own copies
+	 * of, take slots in fd_array after nr_obj_maps maps of the object.
+	 */
+	__u32 nr_obj_maps;
+	__u32 nr_func_ptr_maps;
+	__u32 max_func_ptr_maps;
 };
 
-void bpf_gen__init(struct bpf_gen *gen, int log_level, int nr_progs, int nr_maps);
+void bpf_gen__init(struct bpf_gen *gen, int log_level, int nr_progs, int nr_maps,
+		   int max_func_ptr_maps);
 int bpf_gen__finish(struct bpf_gen *gen, int nr_progs, int nr_maps);
 void bpf_gen__free(struct bpf_gen *gen);
 void bpf_gen__load_btf(struct bpf_gen *gen, const void *raw_data, __u32 raw_size);
@@ -68,6 +76,9 @@ void bpf_gen__prog_load(struct bpf_gen *gen,
 void bpf_gen__map_update_elem(struct bpf_gen *gen, int map_idx, void *value, __u32 value_size,
 			      __u64 flags);
 void bpf_gen__map_freeze(struct bpf_gen *gen, int map_idx);
+int bpf_gen__func_ptr_map_create(struct bpf_gen *gen, const char *map_name, int obj_map_idx,
+				 void *value, __u32 value_size, const __u32 *ptr_offs,
+				 const __u64 *ptr_vals, int ptr_cnt);
 void bpf_gen__record_attach_target(struct bpf_gen *gen, const char *name, enum bpf_attach_type type);
 void bpf_gen__record_extern(struct bpf_gen *gen, const char *name, bool is_weak,
 			    bool is_typeless, bool is_ld64, int kind, int insn_idx);
tools/lib/bpf/gen_loader.c +136 -36

220 lines not on this page · raw message

tools/lib/bpf/libbpf.c +56 -10

121 lines not on this page · raw message

Signature · 1 line
2.55.0
#24 lore raw

PATCH v2 15/17 selftests/bpf: Add tests for callx

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Add verifier_callx tests:
- calls via r0, callee saved regs, pointer passed as argument, returned from subprog, spilled/filled, different callees on different paths. These are executed to test JIT.
- invalid operands: scalar, other pointers, modified and variable PTR_TO_FUNC, global functions, reserved fields, JMP32.
- callx under lock.
- bounded and unbounded recursion via callx.
- stack depth of call chains through callx, including address taken several frames above callx.
- tail calls in the callee and the caller of callx.
- stack liveness: caller slots read by callee stay alive.
- no const propagation across callx.
- precision backtracking through callx.
- address of a function that is never called, with and without callx.
- function pointers in C.

callx needs JIT. Add RUN_JITED() to skip the tests when it's off.

---
 .../selftests/bpf/prog_tests/verifier.c       |   10 +
 .../selftests/bpf/progs/verifier_callx.c      | 1039 +++++++++++++++++
 2 files changed, 1049 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_callx.c
tools/testing/selftests/bpf/prog_tests/verifier.c +10 -0
index 8b4be06bb181..bc96a752b1ae 100644
@@ -28,6 +28,7 @@
 #include "verifier_btf_ctx_access.skel.h"
 #include "verifier_btf_unreliable_prog.skel.h"
 #include "verifier_call_large_imm.skel.h"
+#include "verifier_callx.skel.h"
 #include "verifier_cfg.skel.h"
 #include "verifier_cgroup_inv_retcode.skel.h"
 #include "verifier_cgroup_skb.skel.h"
@@ -173,6 +174,14 @@ static void run_tests_aux(const char *skel_name,
 
 #define RUN(skel) run_tests_aux(#skel, skel##__elf_bytes, NULL)
 
+/* for tests of what the interpreter doesn't support */
+#define RUN_JITED(skel) do {		\
+	if (is_jit_enabled())		\
+		RUN(skel);		\
+	else				\
+		test__skip();		\
+} while (0)
+
 void test_arena_kfunc(void)                   { RUN_TESTS(arena_kfunc); }
 
 void test_arena_kfunc_jit(void)               { RUN_TESTS(arena_kfunc_jit); }
@@ -199,6 +208,7 @@ void test_verifier_bswap(void)                { RUN(verifier_bswap); }
 void test_verifier_btf_ctx_access(void)       { RUN(verifier_btf_ctx_access); }
 void test_verifier_btf_unreliable_prog(void)  { RUN(verifier_btf_unreliable_prog); }
 void test_verifier_call_large_imm(void)       { RUN(verifier_call_large_imm); }
+void test_verifier_callx(void)                { RUN_JITED(verifier_callx); }
 void test_verifier_cfg(void)                  { RUN(verifier_cfg); }
 void test_verifier_cgroup_inv_retcode(void)   { RUN(verifier_cgroup_inv_retcode); }
 void test_verifier_cgroup_skb(void)           { RUN(verifier_cgroup_skb); }
tools/testing/selftests/bpf/progs/verifier_callx.c new file +1039 -0

1,039 lines not on this page · raw message

Signature · 1 line
2.55.0
#25 lore raw

Re: [PATCH bpf-next v2 15/17] selftests/bpf: Add tests for callx

Does RUN_JITED() properly check JIT support for callx?
Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/verifier.c +0 -0
index 8b4be06bb181..bc96a752b1ae 100644

[ ... ]

tools/testing/selftests/bpf/prog_tests/verifier.c static void run_tests_aux(const char *skel_name, · line 183

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/verifier.c +7 -0
@@ -173,6 +174,14 @@ static void run_tests_aux(const char *skel_name,
 
 #define RUN(skel) run_tests_aux(#skel, skel##__elf_bytes, NULL)
 
+/* for tests of what the interpreter doesn't support */
+#define RUN_JITED(skel) do {		\
+	if (is_jit_enabled())		\
+		RUN(skel);		\
+	else				\
+		test__skip();		\
+} while (0)

Does RUN_JITED() properly check JIT support for callx?

Looking at the kernel side added in this series, callx is rejected in more cases than just the JIT being off:

kernel/bpf/verifier.c:require_callx_jit() {
    if (!env->prog->jit_requested) {
        verbose(env, "JIT is required to use callx\n");
        return -EOPNOTSUPP;
    }
    if (!bpf_jit_supports_callx()) {
        verbose(env, "JIT doesn't support callx\n");
        return -EOPNOTSUPP;
    }
    ...
}

Only x86 and arm64 implement bpf_jit_supports_callx(). Everywhere else the __weak default in kernel/bpf/core.c returns false: s390x, riscv64, powerpc, loongarch and others. On x86 it also returns false when cfi_mode == CFI_FINEIBT. By default FineIBT is picked on IBT-capable CPUs when the kernel is built with CFI support.

RUN_JITED() only checks whether the JIT is turned on via is_jit_enabled(), which reads /proc/sys/net/core/bpf_jit_enable. In all of the cases where bpf_jit_supports_callx() returns false, bpf_jit_enable is 1, so RUN_JITED() goes ahead with RUN(verifier_callx). Then:

- Every __success program in progs/verifier_callx.c fails with "unexpected_load_failure". check_func_callx() and the rodata read path both call require_callx_jit() and get -EOPNOTSUPP.

- Most __failure __msg(...) programs also fail. The log says "JIT doesn't support callx" instead of the expected message.

None of the 40 programs in verifier_callx.c have __arch_* annotations. DENYLIST.s390x and DENYLIST.riscv64 do not list verifier_callx either, so test_progs will report FAIL, not SKIP, on the s390x BPF CI.

The selftests guide says a missing capability that causes EOPNOTSUPP must lead to a skip with a reason message. Here the test fails, and in the bpf_jit_enable=0 case test__skip() is called with no reason.

Other JIT-only verifier tests already handle this per program, using the __arch_x86_64 / __arch_arm64 annotations together with __load_if_JITed() (see progs/verifier_arena.c:641-642 and progs/arena_kfunc_jit.c). run_subtest() in test_loader.c already applies both the arch mask and the JITED/NO_JITED load mask. Using these annotations, or probing the load of a minimal callx program and skipping on -EOPNOTSUPP, would cover s390x/riscv64 and the rest. Only the runtime probe would also cover x86 with FineIBT.

The later commit in this series, 922d9559e25a ("selftests/bpf: Add tests for callx through pointers in read-only data"), does not fix this. It adds test_verifier_callx_rodata with the same RUN_JITED() gate, so it has the same problem.

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/verifier.c +1 -0
+
 void test_arena_kfunc(void)                   { RUN_TESTS(arena_kfunc); }

[ ... ]

tools/testing/selftests/bpf/prog_tests/verifier.c void test_verifier_bswap(void) { RUN(verifier_bswap); } · line 214

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/verifier.c +1 -0
@@ -199,6 +208,7 @@ void test_verifier_bswap(void)                { RUN(verifier_bswap); }
 void test_verifier_btf_ctx_access(void)       { RUN(verifier_btf_ctx_access); }
 void test_verifier_btf_unreliable_prog(void)  { RUN(verifier_btf_unreliable_prog); }
 void test_verifier_call_large_imm(void)       { RUN(verifier_call_large_imm); }
+void test_verifier_callx(void)                { RUN_JITED(verifier_callx); }
 void test_verifier_cfg(void)                  { RUN(verifier_cfg); }
 void test_verifier_cgroup_inv_retcode(void)   { RUN(verifier_cgroup_inv_retcode); }
 void test_verifier_cgroup_skb(void)           { RUN(verifier_cgroup_skb); }

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

#26 lore raw

PATCH v2 16/17 selftests/bpf: Add tests for callx through pointers in read-only data

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Add verifier_callx_rodata tests where pointers to functions are in .rodata, libbpf stores offsets there and the kernel recognizes them:
- vtable-like data in .rodata and .data.rel.ro, one of two vtables picked at run time, const and variable index, array of structs where the index selects the pointer or the data, address of an element, table without a symbol. These are executed.
- data next to a pointer is still a constant. The pointer is not:
bpf_prune_dead_branches() must not fold a branch on it.
- all functions the index can select are verified. The rest are not.
- index that may select non-pointer, partial and misaligned reads, arithmetic on the pointer.
- pointer to a global function is not recognized.
- prog without callx reads the pointer as a number.
- recursion and stack depth via a table, stack depth of a callback that is read from a table.
- effects of the functions in a table that call each other.
- CAP_BPF without CAP_PERFMON.
- C: array of functions, NULL check of an element, struct ops with data, switch that may become a table, packed struct with misaligned pointers in a prog without callx.

Add callx_func_ptr_map test that doesn't use libbpf logic: map that another prog uses is not scanned, the prog that failed to load is not a user, the offset in the map is replaced at load, the data is not, no other prog including second instance of the same one can use the map after that.

Add callx_rodata_lskel test: two progs with a table of functions in .rodata and one without callx loaded by light skeleton, with .rodata set by user space.

callx needs JIT. Skip the tests when it's off.

---
 tools/testing/selftests/bpf/Makefile.skel     |   2 +-
 .../bpf/prog_tests/callx_func_ptr_map.c       | 202 +++++
 .../bpf/prog_tests/callx_rodata_lskel.c       |  63 ++
 .../selftests/bpf/prog_tests/verifier.c       |   2 +
 .../selftests/bpf/progs/callx_rodata.c        |  51 ++
 .../bpf/progs/verifier_callx_rodata.c         | 846 ++++++++++++++++++
 6 files changed, 1165 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/callx_func_ptr_map.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/callx_rodata_lskel.c
 create mode 100644 tools/testing/selftests/bpf/progs/callx_rodata.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_callx_rodata.c
tools/testing/selftests/bpf/Makefile.skel +1 -1
index 580d1d82c186..3d92cdca62ed 100644
@@ -33,7 +33,7 @@ LINKED_SKELS := test_static_linked.skel.h linked_funcs.skel.h		\
 LSKELS := fexit_sleep.c trace_printk.c trace_vprintk.c map_ptr_kern.c 	\
 	core_kern.c core_kern_overflow.c test_ringbuf.c			\
 	test_ringbuf_n.c test_ringbuf_map_key.c test_ringbuf_write.c    \
-	test_ringbuf_overwrite.c
+	test_ringbuf_overwrite.c callx_rodata.c
 
 LSKELS_SIGNED := fentry_test.c fexit_test.c atomics.c
 
tools/testing/selftests/bpf/prog_tests/callx_func_ptr_map.c new file +202 -0

202 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/callx_rodata_lskel.c new file +63 -0

63 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/verifier.c +2 -0
index bc96a752b1ae..9c3ff7d83fbe 100644
@@ -29,6 +29,7 @@
 #include "verifier_btf_unreliable_prog.skel.h"
 #include "verifier_call_large_imm.skel.h"
 #include "verifier_callx.skel.h"
+#include "verifier_callx_rodata.skel.h"
 #include "verifier_cfg.skel.h"
 #include "verifier_cgroup_inv_retcode.skel.h"
 #include "verifier_cgroup_skb.skel.h"
@@ -209,6 +210,7 @@ void test_verifier_btf_ctx_access(void)       { RUN(verifier_btf_ctx_access); }
 void test_verifier_btf_unreliable_prog(void)  { RUN(verifier_btf_unreliable_prog); }
 void test_verifier_call_large_imm(void)       { RUN(verifier_call_large_imm); }
 void test_verifier_callx(void)                { RUN_JITED(verifier_callx); }
+void test_verifier_callx_rodata(void)         { RUN_JITED(verifier_callx_rodata); }
 void test_verifier_cfg(void)                  { RUN(verifier_cfg); }
 void test_verifier_cgroup_inv_retcode(void)   { RUN(verifier_cgroup_inv_retcode); }
 void test_verifier_cgroup_skb(void)           { RUN(verifier_cgroup_skb); }
tools/testing/selftests/bpf/progs/callx_rodata.c new file +51 -0

51 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_callx_rodata.c new file +846 -0

846 lines not on this page · raw message

Signature · 1 line
2.55.0
#27 lore raw

PATCH v2 17/17 bpf, docs: Document callx instruction

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Document callx: what it does, where the callee address comes from and what is not supported.

---
 Documentation/bpf/clang-notes.rst |  7 +++++--
 Documentation/bpf/linux-notes.rst | 31 +++++++++++++++++++++++++++----
 2 files changed, 32 insertions(+), 6 deletions(-)
Documentation/bpf/clang-notes.rst +5 -2
index 2c872a1ee08e..3ccc7b09d19e 100644
@@ -23,8 +23,11 @@ For CPU versions prior to 3, Clang v7.0 and later can enable ``BPF_ALU`` support
 Jump instructions
 =================
 
-If ``-O0`` is used, Clang will generate the ``BPF_CALL | BPF_X | BPF_JMP`` (0x8d)
-instruction, which is not supported by the Linux kernel verifier.
+Clang generates the ``BPF_CALL | BPF_X | BPF_JMP`` (0x8d) instruction for calls
+through a function pointer. The Linux kernel verifier accepts it only when it
+can prove that the register holds the address of a static BPF function, see
+Documentation/bpf/linux-notes.rst. If ``-O0`` is used, Clang will generate this
+instruction for helper calls as well, which is not supported.
 
 Atomic operations
 =================
Documentation/bpf/linux-notes.rst +27 -4
index 00d2693de025..6c036b54a29f 100644
@@ -15,10 +15,33 @@ Byte swap instructions
 Jump instructions
 =================
 
-``BPF_CALL | BPF_X | BPF_JMP`` (0x8d), where the helper function
-integer would be read from a specified register, is not currently supported
-by the verifier.  Any programs with this instruction will fail to load
-until such support is added.
+``BPF_CALL | BPF_X | BPF_JMP`` (0x8d), ``callx dst``, performs an indirect
+call of a BPF function whose address is held in the ``dst`` register. The
+``src``, ``offset`` and ``imm`` fields are reserved and must be zero.
+
+The address of a BPF function gets into a register in one of two ways:
+
+* it is loaded by a 64-bit immediate instruction with ``src`` =
+  ``BPF_PSEUDO_FUNC``;
+* it is read, with a 64-bit load, from a frozen read-only array map, that no
+  other program uses, that holds its read-only data: tables of functions,
+  structures of operations, vtables, where pointers to functions may be mixed
+  with other data. In the map a pointer to a function is the offset in bytes
+  of its first instruction in the program, and that is how the verifier
+  recognizes it. It is replaced with the address of the function when
+  the program is loaded. The program reads it from there, which requires
+  ``CAP_PERFMON``.
+
+In both cases only static functions can be referenced. Therefore all functions
+that can be called indirectly are known to the verifier before it starts to
+analyze the program, and ``callx`` is verified as a direct call of every
+function that ``dst`` may point to at that instruction. The same rules apply:
+the calls can not be recursive, and the depth of the call chain and its
+combined stack size are limited.
+
+Calling helper or kernel functions through a register, indirect calls of global
+functions, and tail calls in functions that are called via ``callx`` are not
+supported. ``callx`` requires the BPF JIT.
 
 Maps
 ====
Signature · 1 line
2.55.0
#28 lore raw
In reply to Alexei Starovoitov
This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Hello:

This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Quoted 41 lines · On Thu, 24 Sep 2026 03:10:25 +0000 you wrote:

From: Alexei Starovoitov <[email protected]>

v1->v2:
- Dropped "bpf: Don't fold loads from insn_array maps into constants". bpf_map_direct_read() rejects insn_array already.
- patch 1: emit the same diag as sort_subprogs_topo() (bpf-ci).
- patch 3 is new: taking the address of a function that is never called hit verifier_bug() in jit_subprogs(). Not related to callx, but callx makes it likely.
- patch 4: BPF_OP() == BPF_CALL in liveness like in const_fold, explained in the comment why slots are live before callx callsite (Eduard).
- patch 5: moved !bpf_is_callx() into nested 'if' (Eduard). JIT support is checked before the type of the register.
- patch 6: sync callbacks are in the call graph too. Stack depth of
a callback whose address is read from .rodata or taken in another subprog was not accounted.
- patch 10:
. check_cfg() explores functions of a table one at a time. It was
losing changes_pkt_data and other effects of the functions in
a table that call each other.
. no cmpxchg64(), it's not available on all 32-bit archs.
. don't reject the prog that reads a pointer to a function that was
removed as dead code (sashiko).
. load of the pointer sets jit_required, so the prog that passes it to
a helper as a callback can't run in the interpreter (bpf-ci).
. tbl[i].data at variable offset is a regular load when none of
the possible offsets overlaps with a pointer (bpf-ci).
- patch 12: append the functions and copy the map only for progs that have callx. The rest use .rodata as-is (bpf-ci). Pass token_fd to map create. Dropped dead bpf_map_lookup_elem() fallback.
- patch 14: light skeleton reserves fd_array slots only when the object has callx.
- selftests: anchored callx_retval_is_tracked to the caller, the tests of global func in a table and of const folding of the pointer test what they claim now, skip without JIT, fixed ASSERT_GT() of u32 and
the comment, added tests for the above (bpf-ci). The table in callx_rodata_lskel test is volatile. clang was turning it into
direct calls, so the test didn't test light skeleton.
- Added acks.
v1: https://lore.kernel.org/bpf/[email protected]/

Quoted 1 line

[...]

Here is the summary with links:
- [bpf-next,v2,01/17] bpf: Fix infinite loop in check_max_stack_depth()

    https://git.kernel.org/bpf/bpf-next/c/f2c33a159190
  - [bpf-next,v2,02/17] selftests/bpf: Test recursion through a global function and a callback
    https://git.kernel.org/bpf/bpf-next/c/6cec7366b5ce
  - [bpf-next,v2,03/17] bpf: Keep functions with address taken when removing dead code
    https://git.kernel.org/bpf/bpf-next/c/fb1f5ac185b7
  - [bpf-next,v2,04/17] bpf: Prepare static analysis passes for callx instruction
    https://git.kernel.org/bpf/bpf-next/c/373e3fd0bff0
  - [bpf-next,v2,05/17] bpf: Add callx instruction to call bpf subprogs indirectly
    https://git.kernel.org/bpf/bpf-next/c/7f0f66c069ae
  - [bpf-next,v2,06/17] bpf: Add callx calls to the call graph
    https://git.kernel.org/bpf/bpf-next/c/b7151a69bc6e
  - [bpf-next,v2,07/17] bpf, x86: Add JIT support for callx
    https://git.kernel.org/bpf/bpf-next/c/69a30e5fe5a8
  - [bpf-next,v2,08/17] bpf, arm64: Add JIT support for callx
    https://git.kernel.org/bpf/bpf-next/c/11a516144d9a
  - [bpf-next,v2,09/17] bpf: Discover subprogs described by func_info
    https://git.kernel.org/bpf/bpf-next/c/3a03595510dc
  - [bpf-next,v2,10/17] bpf: Recognize pointers to functions in read-only maps
    https://git.kernel.org/bpf/bpf-next/c/a04286f6d828
  - [bpf-next,v2,11/17] libbpf: Support pointers to static functions in data when linking
    https://git.kernel.org/bpf/bpf-next/c/296fd4782754
  - [bpf-next,v2,12/17] libbpf: Resolve pointers to functions in read-only data
    https://git.kernel.org/bpf/bpf-next/c/b223044a68d5
  - [bpf-next,v2,13/17] libbpf: Treat .data.rel.ro as read-only data
    https://git.kernel.org/bpf/bpf-next/c/6ec77f0a7697
  - [bpf-next,v2,14/17] libbpf: Support pointers to functions in read-only data in light skeleton
    https://git.kernel.org/bpf/bpf-next/c/9f99fc05fc92
  - [bpf-next,v2,15/17] selftests/bpf: Add tests for callx
    https://git.kernel.org/bpf/bpf-next/c/e9b22d50796d
  - [bpf-next,v2,16/17] selftests/bpf: Add tests for callx through pointers in read-only data
    https://git.kernel.org/bpf/bpf-next/c/b018e998e645
  - [bpf-next,v2,17/17] bpf, docs: Document callx instruction
    https://git.kernel.org/bpf/bpf-next/c/fd318eab4b09

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html
maintainer
#29 lore raw
Quoted 4 lines · On Thu, 2026-09-24 at 05:50 +0000, [email protected] wrote:

Hello:

This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Well, that was not fair at all.
We agreed that I'll review this code today.
Anyway, if my input is not needed, so be it.

#30 lore raw
Quoted 10 lines · Eduard Zingerman
Quoted 4 lines · On Thu, 2026-09-24 at 05:50 +0000, [email protected] wrote:

Hello:

This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Well, that was not fair at all.
We agreed that I'll review this code today.
Anyway, if my input is not needed, so be it.

Feedback is needed. nits are not.

reviewer
#31 lore raw
In reply to [email protected]
Quoted 4 lines · On 9/23/26 10:50 PM, [email protected] wrote:

Hello:

This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Hi Alexei.

Looks like this broke GCC BPF selftests build:

progs/verifier_callx.c: In function 'apply_op':
progs/verifier_callx.c:977:1: error: indirect call in function, which are not supported by eBPF
977 | }
| ^
GCC-BPF [test_progs-bpf_gcc] verifier_const.bpf.o
GCC-BPF [test_progs-bpf_gcc] verifier_const_or.bpf.o
GCC-BPF [test_progs-bpf_gcc] verifier_ctx.bpf.o
At top level:
cc1: note: unrecognized command-line option '-Wno-initializer-overrides' may have been intended to silence earlier diagnostics
cc1: note: unrecognized command-line option '-Wno-microsoft-anon-tag' may have been intended to silence earlier diagnostics
make[1]: *** [Makefile.skel:92: /codebuild/output/src4258392908/src/actions-runner/_work/bpf/bpf/src/tools/testing/selftests/bpf/bpf_gcc/verifier_callx.bpf.o] Error 1 make[1]: *** Waiting for unfinished jobs....
progs/verifier_callx_rodata.c: In function 'use_shape':
progs/verifier_callx_rodata.c:746:1: error: indirect call in function, which are not supported by eBPF
746 | }
| ^
progs/verifier_callx_rodata.c:746:1: error: indirect call in function, which are not supported by eBPF
At top level:
cc1: note: unrecognized command-line option '-Wno-initializer-overrides' may have been intended to silence earlier diagnostics
cc1: note: unrecognized command-line option '-Wno-microsoft-anon-tag' may have been intended to silence earlier diagnostics
make[1]: *** [Makefile.skel:91: /codebuild/output/src4258392908/src/actions-runner/_work/bpf/bpf/src/tools/testing/selftests/bpf/bpf_gcc/verifier_callx_rodata.bpf.o] Error 1

Could you please take a look?

https://github.com/kernel-patches/bpf/actions/runs/36028658230/job/107735139837

Quoted 3 lines · On Thu, 24 Sep 2026 03:10:25 +0000 you wrote:
Quoted 1 line

[...]

#32 lore raw
Quoted 4 lines · Ihor Solodrai

Looks like this broke GCC BPF selftests build:

progs/verifier_callx.c: In function 'apply_op':
progs/verifier_callx.c:977:1: error: indirect call in function, which are not supported by eBPF

Right. gcc doesn't support indirect calls and the C tests in verifier_callx.c and verifier_callx_rodata.c have them. progs/callx_rodata.c has the same issue.
Fix is on the way.

reviewer
#33 lore raw
In reply to [email protected]
Quoted 4 lines · On 2026-09-23 10:50 p.m., [email protected] wrote:

Hello:

This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Alexei,

We're testing clang 21->22 bump on BPF CI, and something is broken when compiling callx selftests:

2026-09-28T22:12:12.4226025Z error: Undefined temporary symbol .Lswitch.table.call_by_switch
2026-09-28T22:12:12.4229909Z 1 error generated.
2026-09-28T22:12:12.4265848Z make[1]: *** [Makefile.skel:93: /home/runner/work/ci/ci/tools/testing/selftests/bpf/cpuv4/verifier_callx_rodata.bpf.o] Error 1
2026-09-28T22:12:12.4275948Z make: *** [Makefile:533: /home/runner/work/ci/ci/tools/testing/selftests/bpf/test_progs-cpuv4] Error 2
2026-09-28T22:12:12.4291571Z   CLNG-BPF [test_progs-no_alu32] verifier_gotol.bpf.o
2026-09-28T22:12:12.4292514Z make: *** Waiting for unfinished jobs....

See: https://github.com/libbpf/ci/actions/runs/36487754699/job/109148996137

What's the requirements for callx? Does it need bleeding edge clang? If so, let's explicitly skip relevant selftests for clang < N?

Currently CI runs with clang-21.

Quoted 82 lines · On Thu, 24 Sep 2026 03:10:25 +0000 you wrote:
Quoted 41 lines

From: Alexei Starovoitov <[email protected]>

v1->v2:
- Dropped "bpf: Don't fold loads from insn_array maps into constants". bpf_map_direct_read() rejects insn_array already.
- patch 1: emit the same diag as sort_subprogs_topo() (bpf-ci).
- patch 3 is new: taking the address of a function that is never called hit verifier_bug() in jit_subprogs(). Not related to callx, but callx makes it likely.
- patch 4: BPF_OP() == BPF_CALL in liveness like in const_fold, explained in the comment why slots are live before callx callsite (Eduard).
- patch 5: moved !bpf_is_callx() into nested 'if' (Eduard). JIT support is checked before the type of the register.
- patch 6: sync callbacks are in the call graph too. Stack depth of
a callback whose address is read from .rodata or taken in another subprog was not accounted.
- patch 10:
. check_cfg() explores functions of a table one at a time. It was
losing changes_pkt_data and other effects of the functions in
a table that call each other.
. no cmpxchg64(), it's not available on all 32-bit archs.
. don't reject the prog that reads a pointer to a function that was
removed as dead code (sashiko).
. load of the pointer sets jit_required, so the prog that passes it to
a helper as a callback can't run in the interpreter (bpf-ci).
. tbl[i].data at variable offset is a regular load when none of
the possible offsets overlaps with a pointer (bpf-ci).
- patch 12: append the functions and copy the map only for progs that have callx. The rest use .rodata as-is (bpf-ci). Pass token_fd to map create. Dropped dead bpf_map_lookup_elem() fallback.
- patch 14: light skeleton reserves fd_array slots only when the object has callx.
- selftests: anchored callx_retval_is_tracked to the caller, the tests of global func in a table and of const folding of the pointer test what they claim now, skip without JIT, fixed ASSERT_GT() of u32 and
the comment, added tests for the above (bpf-ci). The table in callx_rodata_lskel test is volatile. clang was turning it into
direct calls, so the test didn't test light skeleton.
- Added acks.
v1: https://lore.kernel.org/bpf/[email protected]/

Quoted 1 line

[...]

Here is the summary with links:
- [bpf-next,v2,01/17] bpf: Fix infinite loop in check_max_stack_depth()

     https://git.kernel.org/bpf/bpf-next/c/f2c33a159190
   - [bpf-next,v2,02/17] selftests/bpf: Test recursion through a global function and a callback
     https://git.kernel.org/bpf/bpf-next/c/6cec7366b5ce
   - [bpf-next,v2,03/17] bpf: Keep functions with address taken when removing dead code
     https://git.kernel.org/bpf/bpf-next/c/fb1f5ac185b7
   - [bpf-next,v2,04/17] bpf: Prepare static analysis passes for callx instruction
     https://git.kernel.org/bpf/bpf-next/c/373e3fd0bff0
   - [bpf-next,v2,05/17] bpf: Add callx instruction to call bpf subprogs indirectly
     https://git.kernel.org/bpf/bpf-next/c/7f0f66c069ae
   - [bpf-next,v2,06/17] bpf: Add callx calls to the call graph
     https://git.kernel.org/bpf/bpf-next/c/b7151a69bc6e
   - [bpf-next,v2,07/17] bpf, x86: Add JIT support for callx
     https://git.kernel.org/bpf/bpf-next/c/69a30e5fe5a8
   - [bpf-next,v2,08/17] bpf, arm64: Add JIT support for callx
     https://git.kernel.org/bpf/bpf-next/c/11a516144d9a
   - [bpf-next,v2,09/17] bpf: Discover subprogs described by func_info
     https://git.kernel.org/bpf/bpf-next/c/3a03595510dc
   - [bpf-next,v2,10/17] bpf: Recognize pointers to functions in read-only maps
     https://git.kernel.org/bpf/bpf-next/c/a04286f6d828
   - [bpf-next,v2,11/17] libbpf: Support pointers to static functions in data when linking
     https://git.kernel.org/bpf/bpf-next/c/296fd4782754
   - [bpf-next,v2,12/17] libbpf: Resolve pointers to functions in read-only data
     https://git.kernel.org/bpf/bpf-next/c/b223044a68d5
   - [bpf-next,v2,13/17] libbpf: Treat .data.rel.ro as read-only data
     https://git.kernel.org/bpf/bpf-next/c/6ec77f0a7697
   - [bpf-next,v2,14/17] libbpf: Support pointers to functions in read-only data in light skeleton
     https://git.kernel.org/bpf/bpf-next/c/9f99fc05fc92
   - [bpf-next,v2,15/17] selftests/bpf: Add tests for callx
     https://git.kernel.org/bpf/bpf-next/c/e9b22d50796d
   - [bpf-next,v2,16/17] selftests/bpf: Add tests for callx through pointers in read-only data
     https://git.kernel.org/bpf/bpf-next/c/b018e998e645
   - [bpf-next,v2,17/17] bpf, docs: Document callx instruction
     https://git.kernel.org/bpf/bpf-next/c/fd318eab4b09

You are awesome, thank you!

#34 lore raw
Quoted 5 lines · Ihor Solodrai

We're testing clang 21->22 bump on BPF CI, and something is broken when compiling callx selftests:

2026-09-28T22:12:12.4226025Z error: Undefined temporary symbol

.Lswitch.table.call_by_switch

That's a bug in llvm 22. Not related to callx.
With -mcpu=v4 BPFAsmPrinter::doFinalization() is supposed to remove private arrays of blockaddress that were converted to gotox jump tables, but it removes all private const arrays of pointers.
clang turns the switch in call_by_switch() into such array of pointers to functions.
Yonghong fixed it in llvm 23:
commit 9fc458a1d95b ("[BPF] Fix erroneous removal of non-jump-table globals") It landed after 22.1.8, so no release of 22 has it.

Quoted 2 lines

What's the requirements for callx? Does it need bleeding edge clang? If so, let's explicitly skip relevant selftests for clang < N?

No. clang generates callx for years. clang 21 is fine and 22 is fine with v2 and v3.

I'd bump CI to clang 23.

A bunch of other tests require __clang_major__ >= 23 already.

reviewer
#35 lore raw
Quoted 7 lines · Alexei Starovoitov
Quoted 5 lines · Ihor Solodrai

We're testing clang 21->22 bump on BPF CI, and something is broken when compiling callx selftests:

2026-09-28T22:12:12.4226025Z error: Undefined temporary symbol

.Lswitch.table.call_by_switch

Quoted 9 lines

That's a bug in llvm 22. Not related to callx.
With -mcpu=v4 BPFAsmPrinter::doFinalization() is supposed to remove private arrays of blockaddress that were converted to gotox jump tables, but it removes all private const arrays of pointers.
clang turns the switch in call_by_switch() into such array of pointers to functions.
Yonghong fixed it in llvm 23:
commit 9fc458a1d95b ("[BPF] Fix erroneous removal of non-jump-table globals") It landed after 22.1.8, so no release of 22 has it.

I see, thanks.

Quoted 10 lines
Quoted 3 lines

What's the requirements for callx? Does it need bleeding edge clang? If so, let's explicitly skip relevant selftests for clang < N?

No. clang generates callx for years. clang 21 is fine and 22 is fine with v2 and v3.

I'd bump CI to clang 23.

A bunch of other tests require __clang_major__ >= 23 already.

Even if we bump our CI to 23, I don't think we want the default selftests build to remain broken with 22 due to a compiler bug.

I'll see if we can gracefully handle the bug there.