Skip to contentSkip to conversation

BPF indirect jumps

PATCH Superseded Anton Protopopov 4 participants 48 messages Sep 30, 2025 – Oct 15, 2025

Subsystems (8)
x86 Kselftest BPF BPF selftests +4 more subsystems

v5 of 11 Superseded Latest is v11 →

lore
Share & tools
lore
#0 lore raw

v5 cover BPF indirect jumps

This patchset implements a new type of map, instruction set, and uses it to build support for indirect branches in BPF (on x86). (The same map will be later used to provide support for indirect calls and static keys.) See [1], [2] for more context.

Short table of contents:

* Patches 1-7 implement the new map of type BPF_MAP_TYPE_INSN_SET and corresponding selftests. This map can be used to track the "original -> xlated -> jitted mapping" for a given program. Patches 6,7 add support for "blinded" variant.

* Patches 8,9,10,11 implement the support for indirect jumps

* Patches 12,13,14,15 add support for LLVM-compiled programs containing indirect jumps.

Since the v3 the jump table support was merged to LLVM and now can be enabled with -mcpu=v4. See [3] for the PR which added the support.

There is still a list of TBDs for selftests, mainly, to test all the error conditions introduce by the patch "bpf, x86: add support for indirect jumps" in a new "verifier_indirect_jumps" style, but I wanted to see the kernel side calming down before doing this.

See individual patches for more details on the implementation details.

v3 -> v4 -> v5 (this series):

* [v4 -> v5] rebased on top of the last bpf-next/master

* instruction arrays:
* add copyright (Alexei)
* remove mutexes, add frozen back (Alexei)
* setup 1:1 prog-map correspondence using atomic_xchg
* do not copy/paste array_map_get_next_key, add a common helper (Alexei)
* misc minor code cleanups (Alexei)

* indirect jumps, kernel side:
* remove jt_allocated, just check if insn is gotox (Eduard)
* use copy_register_state instead of individual copies (Eduard)
* in push_stack is_speculative should be inherited (Eduard)
* a few cleanups for insn_successors, including omitting error path (Eduard)
* check if reserved fields are used when considering gotox instruction (Eduard)
* read size and alignment of read from insn_array should be 8 (Eduard)
* put buffer for sorting in subfun info and realloc to grow as needed (Eduard)
* properly do jump_point / prune_point from push_gotox_edge (Eduard)
* use range_within to check states (Eduard)
* some minor cleanups and fix commit message (Eduard)

* indirect jumps, libbpf side:
* close map_fd in some error paths in create_jt_map (Andrii)
* maps for jump tables are actually not closed at all, fix this (Andrii)
* rename map from jt to .jumptables (Andrii)
* use errstr in an error message (Andrii)
* rephrase error message to look more standard (Andrii)
* misc other minor renames and cleanups (Andrii)

* selftests:
* add the frozen selftest back
* add a selftest for two jumps loading same table

* some other changes:
* rebase and split insn_successor changes into separate patch
* use PTR_ERR_OR_ZERO in the push stack patch (Eduard)
* indirect jumps on x86: properly re-read *pprog (Eduard)

v2 -> v3 (https://lore.kernel.org/bpf/[email protected]/):

* fix build failure when CONFIG_BPF_SYSCALL is not set (kbuild-bot)
* reformat bpftool help messages (Quentin)

v1 -> v2 (https://lore.kernel.org/bpf/[email protected]/):

* push_stack changes:
* sanitize_speculative_path should just return int (Eduard)
* return code from sanitize_speculative_path, not EFAULT (Eduard)
* when BPF_COMPLEXITY_LIMIT_JMP_SEQ is reached, return E2BIG (Eduard)

* indirect jumps:
* omit support for .imm=fd in gotox, as we're not using it for now (Eduard)
* struct jt -> struct bpf_iarray (Eduard)
* insn_successors: rewrite the interface to just return a pointer (Eduard)
* remove min_index/max_index, use umin_value/umax_value instead (Alexei, Eduard)
* move emit_indirect_jump args change to the previous patch (Eduard)
* add a comment to map_mem_size() (Eduard)
* use verifier_bug for some error cases in check_indirect_jump (Eduard)
* clear_insn_aux_data: use start,len instead of start,end (Eduard)
* make regs[insn->dst_reg].type = PTR_TO_INSN part of check_mem_access (Eduard)

* constant blinding changes:
* make subprog_start adjustment better readable (Eduard)
* do not set subprog len, it is already set (Eduard)

* libbpf:
* remove check that relocations from .rodata are ok (Anton)
* do not freeze the map, it is not necessary anymore (Anton)
* rename the goto_x -> gotox everywhere (Anton)
* use u64 when parsing LLVM jump tables (Eduard)
* split patch in two due to spaces->tabs change (Eduard)
* split bpftool changes to bpftool patch (Andrii)
* make sym_size it a union with ext_idx (Andrii)
* properly copy/free the jumptables_data section from elf (Andrii)
* a few cosmetic changes around create_jt_map (Andrii)
* fix some comments + rewrite patch description (Andrii)
* inline bpf_prog__append_subprog_offsets (Andrii)
* subprog_sec_offst -> subprog_sec_off (Andrii)
* !strcmp -> strcmp() == 0 (Andrii)
* make some function names more readable (Andrii)
* allocate table of subfunc offsets via libbpf_reallocarray (Andrii)

* selftests:
* squash insn_array* tests together (Anton)

* fixed build warnings (kernel test robot)

RFC -> v1 (https://lore.kernel.org/bpf/[email protected]/):

* I've tried to address all the comments provided by Alexei and Eduard in RFC. Will try to list the most important of them below.
* One big change: move from older LLVM version [5] to newer [4]. Now LLVM generates jump tables as symbols in the new special section ".jumptables". Another part of this change is that libbpf now doesn't try to link map load and goto *rX, as
1) this is absolutely not reliable 2) for some use cases this is impossible (namely, when more than one jump table can be used in the same gotox instruction).
* Added insn_successors() support (Alexei, Eduard). This includes getting rid of the ugly bpf_insn_set_iter_xlated_offset() interface (Eduard).
* Removed hack for the unreachable instruction, as new LLVM thank to Eduard doesn't generate it.
* Set mem_size for direct map access properly instead of hacking. Remove off>0 check. (Alexei)
* Do not allocate new memory for min_index/max_index (Alexei, Eduard)
* Information required during check_cfg is now cached to be reused later (Alexei + general logic for supporting multiple JT per jump)
* Properly compare registers in regsafe (Alexei, Eduard)
* Remove support for JMP32 (Eduard)
* Better checks in adjust_ptr_min_max_vals (Eduard)
* More selftests were added (but still there's room for more) which directly use gotox (Alexei)
* More checks and verbose messages added
* "unique pointers" are no more in the map

Links:
1. https://lpc.events/event/18/contributions/1941/
2. https://lwn.net/Articles/1017439/
3. https://github.com/llvm/llvm-project/pull/149715
4. https://github.com/llvm/llvm-project/pull/149715#issuecomment-3274833753
6. rfc: https://lore.kernel.org/bpf/[email protected]/

Anton Protopopov (15):
bpf: fix the return value of push_stack
bpf: save the start of functions in bpf_prog_aux
bpf: generalize and export map_get_next_key for arrays bpf, x86: add new map type: instructions array selftests/bpf: add selftests for new insn_array map
bpf: support instructions arrays with constants blinding selftests/bpf: test instructions arrays with blinding bpf, x86: allow indirect jumps to r8...r15
bpf: make bpf_insn_successors to return a pointer bpf, x86: add support for indirect jumps
bpf: disasm: add support for BPF_JMP|BPF_JA|BPF_X
libbpf: fix formatting of bpf_object__append_subprog_code
libbpf: support llvm-generated indirect jumps
bpftool: Recognize insn_array map type selftests/bpf: add selftests for indirect jumps

 arch/x86/net/bpf_jit_comp.c                   |  39 +-
 include/linux/bpf.h                           |  46 ++
 include/linux/bpf_types.h                     |   1 +
 include/linux/bpf_verifier.h                  |  27 +-
 include/uapi/linux/bpf.h                      |  11 +
 kernel/bpf/Makefile                           |   2 +-
 kernel/bpf/arraymap.c                         |  19 +-
 kernel/bpf/bpf_insn_array.c                   | 300 +++++++++
 kernel/bpf/core.c                             |  21 +
 kernel/bpf/disasm.c                           |   9 +
 kernel/bpf/liveness.c                         |  39 +-
 kernel/bpf/log.c                              |   1 +
 kernel/bpf/syscall.c                          |  22 +
 kernel/bpf/verifier.c                         | 596 ++++++++++++++++--
 .../bpf/bpftool/Documentation/bpftool-map.rst |   3 +-
 tools/bpf/bpftool/map.c                       |   3 +-
 tools/include/uapi/linux/bpf.h                |  11 +
 tools/lib/bpf/libbpf.c                        | 263 +++++++-
 tools/lib/bpf/libbpf_probes.c                 |   4 +
 tools/lib/bpf/linker.c                        |  10 +-
 tools/testing/selftests/bpf/Makefile          |   4 +-
 .../selftests/bpf/prog_tests/bpf_gotox.c      | 177 ++++++
 .../selftests/bpf/prog_tests/bpf_insn_array.c | 574 +++++++++++++++++
 tools/testing/selftests/bpf/progs/bpf_gotox.c | 411 ++++++++++++
 24 files changed, 2466 insertions(+), 127 deletions(-)
 create mode 100644 kernel/bpf/bpf_insn_array.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/bpf_gotox.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c
 create mode 100644 tools/testing/selftests/bpf/progs/bpf_gotox.c
Signature · 1 line
2.34.1
#1 lore raw

PATCH v5 1/15 bpf: fix the return value of push_stack

In [1] Eduard mentioned that on push_stack failure verifier code should return -ENOMEM instead of -EFAULT. After checking with the other call sites I've found that code randomly returns either -ENOMEM or -EFAULT. This patch unifies the return values for the push_stack (and similar push_async_cb) functions such that error codes are always assigned properly.

[1] https://lore.kernel.org/bpf/[email protected]

---
 kernel/bpf/verifier.c | 80 +++++++++++++++++++++----------------------
 1 file changed, 40 insertions(+), 40 deletions(-)
kernel/bpf/verifier.c +40 -40
index e892df386eed..5313ed905dc4 100644
@@ -2093,7 +2093,7 @@ static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
 
 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
 	if (!elem)
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 
 	elem->insn_idx = insn_idx;
 	elem->prev_insn_idx = prev_insn_idx;
@@ -2103,12 +2103,12 @@ static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
 	env->stack_size++;
 	err = copy_verifier_state(&elem->st, cur);
 	if (err)
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 	elem->st.speculative |= speculative;
 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
 		verbose(env, "The sequence of %d jumps is too complex.\n",
 			env->stack_size);
-		return NULL;
+		return ERR_PTR(-E2BIG);
 	}
 	if (elem->st.parent) {
 		++elem->st.parent->branches;
@@ -2903,7 +2903,7 @@ static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
 
 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
 	if (!elem)
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 
 	elem->insn_idx = insn_idx;
 	elem->prev_insn_idx = prev_insn_idx;
@@ -2915,7 +2915,7 @@ static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
 		verbose(env,
 			"The sequence of %d jumps is too complex for async cb.\n",
 			env->stack_size);
-		return NULL;
+		return ERR_PTR(-E2BIG);
 	}
 	/* Unlike push_stack() do not copy_verifier_state().
 	 * The caller state doesn't matter.
@@ -2926,7 +2926,7 @@ static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
 	elem->st.in_sleepable = is_sleepable;
 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
 	if (!frame)
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 	init_func_state(env, frame,
 			BPF_MAIN_FUNC /* callsite */,
 			0 /* frameno within this callchain */,
@@ -9014,8 +9014,8 @@ static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
 		/* branch out active iter state */
 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
-		if (!queued_st)
-			return -ENOMEM;
+		if (IS_ERR(queued_st))
+			return PTR_ERR(queued_st);
 
 		queued_iter = get_iter_from_state(queued_st, meta);
 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
@@ -10588,8 +10588,8 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 					 insn_idx, subprog,
 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm) ||
 					 is_task_work_add_kfunc(insn->imm));
-		if (!async_cb)
-			return -EFAULT;
+		if (IS_ERR(async_cb))
+			return PTR_ERR(async_cb);
 		callee = async_cb->frame[0];
 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
 
@@ -10605,8 +10605,8 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	 * proceed with next instruction within current frame.
 	 */
 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
-	if (!callback_state)
-		return -ENOMEM;
+	if (IS_ERR(callback_state))
+		return PTR_ERR(callback_state);
 
 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
 			       callback_state);
@@ -13827,9 +13827,9 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		struct bpf_reg_state *regs;
 
 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
-		if (!branch) {
+		if (IS_ERR(branch)) {
 			verbose(env, "failed to push state for failed lock acquisition\n");
-			return -ENOMEM;
+			return PTR_ERR(branch);
 		}
 
 		regs = branch->frame[branch->curframe]->regs;
@@ -14280,16 +14280,15 @@ struct bpf_sanitize_info {
 	bool mask_to_left;
 };
 
-static struct bpf_verifier_state *
-sanitize_speculative_path(struct bpf_verifier_env *env,
-			  const struct bpf_insn *insn,
-			  u32 next_idx, u32 curr_idx)
+static int sanitize_speculative_path(struct bpf_verifier_env *env,
+				     const struct bpf_insn *insn,
+				     u32 next_idx, u32 curr_idx)
 {
 	struct bpf_verifier_state *branch;
 	struct bpf_reg_state *regs;
 
 	branch = push_stack(env, next_idx, curr_idx, true);
-	if (branch && insn) {
+	if (!IS_ERR(branch) && insn) {
 		regs = branch->frame[branch->curframe]->regs;
 		if (BPF_SRC(insn->code) == BPF_K) {
 			mark_reg_unknown(env, regs, insn->dst_reg);
@@ -14298,7 +14297,7 @@ sanitize_speculative_path(struct bpf_verifier_env *env,
 			mark_reg_unknown(env, regs, insn->src_reg);
 		}
 	}
-	return branch;
+	return PTR_ERR_OR_ZERO(branch);
 }
 
 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
@@ -14317,7 +14316,6 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env,
 	u8 opcode = BPF_OP(insn->code);
 	u32 alu_state, alu_limit;
 	struct bpf_reg_state tmp;
-	bool ret;
 	int err;
 
 	if (can_skip_alu_sanitation(env, insn))
@@ -14390,11 +14388,12 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env,
 		tmp = *dst_reg;
 		copy_register_state(dst_reg, ptr_reg);
 	}
-	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
-					env->insn_idx);
-	if (!ptr_is_dst_reg && ret)
+	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
+	if (err < 0)
+		return REASON_STACK;
+	if (!ptr_is_dst_reg)
 		*dst_reg = tmp;
-	return !ret ? REASON_STACK : 0;
+	return 0;
 }
 
 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
@@ -16713,8 +16712,8 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 
 		/* branch out 'fallthrough' insn as a new state to explore */
 		queued_st = push_stack(env, idx + 1, idx, false);
-		if (!queued_st)
-			return -ENOMEM;
+		if (IS_ERR(queued_st))
+			return PTR_ERR(queued_st);
 
 		queued_st->may_goto_depth++;
 		if (prev_st)
@@ -16792,10 +16791,11 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 		 * the fall-through branch for simulation under speculative
 		 * execution.
 		 */
-		if (!env->bypass_spec_v1 &&
-		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
-					       *insn_idx))
-			return -EFAULT;
+		if (!env->bypass_spec_v1) {
+			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
+			if (err < 0)
+				return err;
+		}
 		if (env->log.level & BPF_LOG_LEVEL)
 			print_insn_state(env, this_branch, this_branch->curframe);
 		*insn_idx += insn->off;
@@ -16805,11 +16805,12 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 		 * program will go. If needed, push the goto branch for
 		 * simulation under speculative execution.
 		 */
-		if (!env->bypass_spec_v1 &&
-		    !sanitize_speculative_path(env, insn,
-					       *insn_idx + insn->off + 1,
-					       *insn_idx))
-			return -EFAULT;
+		if (!env->bypass_spec_v1) {
+			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
+							*insn_idx);
+			if (err < 0)
+				return err;
+		}
 		if (env->log.level & BPF_LOG_LEVEL)
 			print_insn_state(env, this_branch, this_branch->curframe);
 		return 0;
@@ -16830,10 +16831,9 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 			return err;
 	}
 
-	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
-				  false);
-	if (!other_branch)
-		return -EFAULT;
+	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
+	if (IS_ERR(other_branch))
+		return PTR_ERR(other_branch);
 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
 
 	if (BPF_SRC(insn->code) == BPF_X) {
Signature · 1 line
2.34.1
#2 lore raw

PATCH v5 2/15 bpf: save the start of functions in bpf_prog_aux

In reply to Anton Protopopov

Introduce a new subprog_start field in bpf_prog_aux. This field may be used by JIT compilers wanting to know the real absolute xlated offset of the function being jitted. The func_info[func_id] may have served this purpose, but func_info may be NULL, so JIT compilers can't rely on it.

---
 include/linux/bpf.h   | 1 +
 kernel/bpf/verifier.c | 1 +
 2 files changed, 2 insertions(+)
include/linux/bpf.h +1 -0
index a98c83346134..8ad666a02c29 100644
@@ -1616,6 +1616,7 @@ struct bpf_prog_aux {
 	u32 ctx_arg_info_size;
 	u32 max_rdonly_access;
 	u32 max_rdwr_access;
+	u32 subprog_start;
 	struct btf *attach_btf;
 	struct bpf_ctx_arg_aux *ctx_arg_info;
 	void __percpu *priv_stack_ptr;
kernel/bpf/verifier.c +1 -0
index 5313ed905dc4..cc43116d283c 100644
@@ -21570,6 +21570,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 		func[i]->aux->func_idx = i;
 		/* Below members will be freed only at prog->aux */
 		func[i]->aux->btf = prog->aux->btf;
+		func[i]->aux->subprog_start = subprog_start;
 		func[i]->aux->func_info = prog->aux->func_info;
 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
 		func[i]->aux->poke_tab = prog->aux->poke_tab;
Signature · 1 line
2.34.1
maintainer Acked-by on v5 2/15
#3 lore raw

Re: [PATCH v5 bpf-next 02/15] bpf: save the start of functions in bpf_prog_aux

Quoted 8 lines · Anton Protopopov

Introduce a new subprog_start field in bpf_prog_aux. This field may be used by JIT compilers wanting to know the real absolute xlated offset of the function being jitted. The func_info[func_id] may have served this purpose, but func_info may be NULL, so JIT compilers can't rely on it.

---

[...]

#4 lore raw

PATCH v5 3/15 bpf: generalize and export map_get_next_key for arrays

In reply to Anton Protopopov

The kernel/bpf/array.c file defines the array_map_get_next_key() function which finds the next key for array maps. It actually doesn't use any map fields besides the generic max_entries field. Generalize it, and export as bpf_array_get_next_key() such that it can be re-used by other array-like maps.

---
 include/linux/bpf.h   |  6 ++++++
 kernel/bpf/arraymap.c | 19 +++++++++----------
 2 files changed, 15 insertions(+), 10 deletions(-)
include/linux/bpf.h +6 -0
index 8ad666a02c29..85fb3fb17c0f 100644
@@ -2100,6 +2100,12 @@ struct bpf_array {
 	};
 };
 
+/*
+ * The bpf_array_get_next_key() function may be used for all array-like
+ * maps, i.e., maps with u32 keys with range [0 ,..., max_entries)
+ */
+int bpf_array_get_next_key(struct bpf_map *map, void *key, void *next_key);
+
 #define BPF_COMPLEXITY_LIMIT_INSNS      1000000 /* yes. 1M insns */
 #define MAX_TAIL_CALL_CNT 33
 
kernel/bpf/arraymap.c +9 -10
index 80b1765a3159..493b9841ebd0 100644
@@ -335,18 +335,17 @@ int bpf_percpu_array_copy(struct bpf_map *map, void *key, void *value)
 }
 
 /* Called from syscall */
-static int array_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
+int bpf_array_get_next_key(struct bpf_map *map, void *key, void *next_key)
 {
-	struct bpf_array *array = container_of(map, struct bpf_array, map);
 	u32 index = key ? *(u32 *)key : U32_MAX;
 	u32 *next = (u32 *)next_key;
 
-	if (index >= array->map.max_entries) {
+	if (index >= map->max_entries) {
 		*next = 0;
 		return 0;
 	}
 
-	if (index == array->map.max_entries - 1)
+	if (index == map->max_entries - 1)
 		return -ENOENT;
 
 	*next = index + 1;
@@ -796,7 +795,7 @@ const struct bpf_map_ops array_map_ops = {
 	.map_alloc_check = array_map_alloc_check,
 	.map_alloc = array_map_alloc,
 	.map_free = array_map_free,
-	.map_get_next_key = array_map_get_next_key,
+	.map_get_next_key = bpf_array_get_next_key,
 	.map_release_uref = array_map_free_internal_structs,
 	.map_lookup_elem = array_map_lookup_elem,
 	.map_update_elem = array_map_update_elem,
@@ -822,7 +821,7 @@ const struct bpf_map_ops percpu_array_map_ops = {
 	.map_alloc_check = array_map_alloc_check,
 	.map_alloc = array_map_alloc,
 	.map_free = array_map_free,
-	.map_get_next_key = array_map_get_next_key,
+	.map_get_next_key = bpf_array_get_next_key,
 	.map_lookup_elem = percpu_array_map_lookup_elem,
 	.map_gen_lookup = percpu_array_map_gen_lookup,
 	.map_update_elem = array_map_update_elem,
@@ -1211,7 +1210,7 @@ const struct bpf_map_ops prog_array_map_ops = {
 	.map_poke_track = prog_array_map_poke_track,
 	.map_poke_untrack = prog_array_map_poke_untrack,
 	.map_poke_run = prog_array_map_poke_run,
-	.map_get_next_key = array_map_get_next_key,
+	.map_get_next_key = bpf_array_get_next_key,
 	.map_lookup_elem = fd_array_map_lookup_elem,
 	.map_delete_elem = fd_array_map_delete_elem,
 	.map_fd_get_ptr = prog_fd_array_get_ptr,
@@ -1315,7 +1314,7 @@ const struct bpf_map_ops perf_event_array_map_ops = {
 	.map_alloc_check = fd_array_map_alloc_check,
 	.map_alloc = array_map_alloc,
 	.map_free = perf_event_fd_array_map_free,
-	.map_get_next_key = array_map_get_next_key,
+	.map_get_next_key = bpf_array_get_next_key,
 	.map_lookup_elem = fd_array_map_lookup_elem,
 	.map_delete_elem = fd_array_map_delete_elem,
 	.map_fd_get_ptr = perf_event_fd_array_get_ptr,
@@ -1351,7 +1350,7 @@ const struct bpf_map_ops cgroup_array_map_ops = {
 	.map_alloc_check = fd_array_map_alloc_check,
 	.map_alloc = array_map_alloc,
 	.map_free = cgroup_fd_array_free,
-	.map_get_next_key = array_map_get_next_key,
+	.map_get_next_key = bpf_array_get_next_key,
 	.map_lookup_elem = fd_array_map_lookup_elem,
 	.map_delete_elem = fd_array_map_delete_elem,
 	.map_fd_get_ptr = cgroup_fd_array_get_ptr,
@@ -1436,7 +1435,7 @@ const struct bpf_map_ops array_of_maps_map_ops = {
 	.map_alloc_check = fd_array_map_alloc_check,
 	.map_alloc = array_of_map_alloc,
 	.map_free = array_of_map_free,
-	.map_get_next_key = array_map_get_next_key,
+	.map_get_next_key = bpf_array_get_next_key,
 	.map_lookup_elem = array_of_map_lookup_elem,
 	.map_delete_elem = fd_array_map_delete_elem,
 	.map_fd_get_ptr = bpf_map_fd_get_ptr,
Signature · 1 line
2.34.1
maintainer Acked-by on v5 3/15
#5 lore raw

Re: [PATCH v5 bpf-next 03/15] bpf: generalize and export map_get_next_key for arrays

Quoted 8 lines · Anton Protopopov

The kernel/bpf/array.c file defines the array_map_get_next_key() function which finds the next key for array maps. It actually doesn't use any map fields besides the generic max_entries field. Generalize it, and export as bpf_array_get_next_key() such that it can be re-used by other array-like maps.

---

[...]

#6 lore raw

PATCH v5 4/15 bpf, x86: add new map type: instructions array

In reply to Anton Protopopov

On bpf(BPF_PROG_LOAD) syscall user-supplied BPF programs are translated by the verifier into "xlated" BPF programs. During this process the original instructions offsets might be adjusted and/or individual instructions might be replaced by new sets of instructions, or deleted.

Add a new BPF map type which is aimed to keep track of how, for a given program, the original instructions were relocated during the verification. Also, besides keeping track of the original -> xlated mapping, make x86 JIT to build the xlated -> jitted mapping for every instruction listed in an instruction array. This is required for every future application of instruction arrays: static keys, indirect jumps and indirect calls.

A map of the BPF_MAP_TYPE_INSN_ARRAY type must be created with a u32 keys and value of size 8. The values have different semantics for userspace and for BPF space. For userspace a value consists of two u32 values – xlated and jitted offsets. For BPF side the value is a real pointer to a jitted instruction.

On map creation/initialization, before loading the program, each element of the map should be initialized to point to an instruction offset within the program. Before the program load such maps should be made frozen. After the program verification xlated and jitted offsets can be read via the bpf(2) syscall.

If a tracked instruction is removed by the verifier, then the xlated offset is set to (u32)-1 which is considered to be too big for a valid BPF program offset.

One such a map can, obviously, be used to track one and only one BPF program. If the verification process was unsuccessful, then the same map can be re-used to verify the program with a different log level. However, if the program was loaded fine, then such a map, being frozen in any case, can't be reused by other programs even after the program release.

Example. Consider the following original and xlated programs:

    Original prog:                      Xlated prog:

     0:  r1 = 0x0                        0: r1 = 0
     1:  *(u32 *)(r10 - 0x4) = r1        1: *(u32 *)(r10 -4) = r1
     2:  r2 = r10                        2: r2 = r10
     3:  r2 += -0x4                      3: r2 += -4
     4:  r1 = 0x0 ll                     4: r1 = map[id:88]
     6:  call 0x1                        6: r1 += 272
                                         7: r0 = *(u32 *)(r2 +0)
                                         8: if r0 >= 0x1 goto pc+3
                                         9: r0 <<= 3
                                        10: r0 += r1
                                        11: goto pc+1
                                        12: r0 = 0
     7:  r6 = r0                        13: r6 = r0
     8:  if r6 == 0x0 goto +0x2         14: if r6 == 0x0 goto pc+4
     9:  call 0x76                      15: r0 = 0xffffffff8d2079c0
                                        17: r0 = *(u64 *)(r0 +0)
    10:  *(u64 *)(r6 + 0x0) = r0        18: *(u64 *)(r6 +0) = r0
    11:  r0 = 0x0                       19: r0 = 0x0
    12:  exit                           20: exit

An instruction array map, containing, e.g., instructions [0,4,7,12] will be translated by the verifier to [0,4,13,20]. A map with index 5 (the middle of 16-byte instruction) or indexes greater than 12 (outside the program boundaries) would be rejected.

The functionality provided by this patch will be extended in consequent patches to implement BPF Static Keys, indirect jumps, and indirect calls.

---
 arch/x86/net/bpf_jit_comp.c    |   8 +
 include/linux/bpf.h            |  38 +++++
 include/linux/bpf_types.h      |   1 +
 include/linux/bpf_verifier.h   |   2 +
 include/uapi/linux/bpf.h       |  11 ++
 kernel/bpf/Makefile            |   2 +-
 kernel/bpf/bpf_insn_array.c    | 285 +++++++++++++++++++++++++++++++++
 kernel/bpf/syscall.c           |  22 +++
 kernel/bpf/verifier.c          |  43 +++++
 tools/include/uapi/linux/bpf.h |  11 ++
 10 files changed, 422 insertions(+), 1 deletion(-)
 create mode 100644 kernel/bpf/bpf_insn_array.c
arch/x86/net/bpf_jit_comp.c +8 -0
index fc13306af15f..8ff841e73512 100644
@@ -1691,6 +1691,7 @@ static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image, u8 *rw_image
 	prog = temp;
 
 	for (i = 1; i <= insn_cnt; i++, insn++) {
+		u32 abs_xlated_off = bpf_prog->aux->subprog_start + i - 1;
 		const s32 imm32 = insn->imm;
 		u32 dst_reg = insn->dst_reg;
 		u32 src_reg = insn->src_reg;
@@ -2751,6 +2752,13 @@ st:			if (is_imm8(insn->off))
 				return -EFAULT;
 			}
 			memcpy(rw_image + proglen, temp, ilen);
+
+			/*
+			 * Instruction arrays need to know how xlated code
+			 * maps to jitted code
+			 */
+			bpf_prog_update_insn_ptr(bpf_prog, abs_xlated_off, proglen,
+						 image + proglen);
 		}
 		proglen += ilen;
 		addrs[i] = proglen;
include/linux/bpf.h +38 -0
index 85fb3fb17c0f..f878d94593e3 100644
@@ -3775,4 +3775,42 @@ int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char *
 			   const char **linep, int *nump);
 struct bpf_prog *bpf_prog_find_from_stack(void);
 
+int bpf_insn_array_init(struct bpf_map *map, const struct bpf_prog *prog);
+int bpf_insn_array_ready(struct bpf_map *map);
+void bpf_insn_array_release(struct bpf_map *map);
+void bpf_insn_array_adjust(struct bpf_map *map, u32 off, u32 len);
+void bpf_insn_array_adjust_after_remove(struct bpf_map *map, u32 off, u32 len);
+
+/*
+ * The struct bpf_insn_ptr structure describes a pointer to a
+ * particular instruction in a loaded BPF program. Initially
+ * it is initialised from userspace via user_value.xlated_off.
+ * During the program verification all other fields are populated
+ * accordingly:
+ *
+ *   jitted_ip:       address of the instruction in the jitted image
+ *   user_value:      user-visible xlated and jitted offsets
+ *   orig_xlated_off: original offset of the instruction
+ */
+struct bpf_insn_ptr {
+	void *jitted_ip;
+	struct bpf_insn_array_value user_value;
+	u32 orig_xlated_off;
+};
+
+#ifdef CONFIG_BPF_SYSCALL
+void bpf_prog_update_insn_ptr(struct bpf_prog *prog,
+			      u32 xlated_off,
+			      u32 jitted_off,
+			      void *jitted_ip);
+#else
+static inline void
+bpf_prog_update_insn_ptr(struct bpf_prog *prog,
+			 u32 xlated_off,
+			 u32 jitted_off,
+			 void *jitted_ip)
+{
+}
+#endif
+
 #endif /* _LINUX_BPF_H */
include/linux/bpf_types.h +1 -0
index fa78f49d4a9a..b13de31e163f 100644
@@ -133,6 +133,7 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_RINGBUF, ringbuf_map_ops)
 BPF_MAP_TYPE(BPF_MAP_TYPE_BLOOM_FILTER, bloom_filter_map_ops)
 BPF_MAP_TYPE(BPF_MAP_TYPE_USER_RINGBUF, user_ringbuf_map_ops)
 BPF_MAP_TYPE(BPF_MAP_TYPE_ARENA, arena_map_ops)
+BPF_MAP_TYPE(BPF_MAP_TYPE_INSN_ARRAY, insn_array_map_ops)
 
 BPF_LINK_TYPE(BPF_LINK_TYPE_RAW_TRACEPOINT, raw_tracepoint)
 BPF_LINK_TYPE(BPF_LINK_TYPE_TRACING, tracing)
include/linux/bpf_verifier.h +2 -0
index 4c497e839526..cc06e6d57faa 100644
@@ -745,8 +745,10 @@ struct bpf_verifier_env {
 	struct list_head free_list;	/* list of struct bpf_verifier_state_list */
 	struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
 	struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */
+	struct bpf_map *insn_array_maps[MAX_USED_MAPS]; /* array of INSN_ARRAY map's to be relocated */
 	u32 used_map_cnt;		/* number of used maps */
 	u32 used_btf_cnt;		/* number of used BTF objects */
+	u32 insn_array_map_cnt;		/* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */
 	u32 id_gen;			/* used to generate unique reg IDs */
 	u32 hidden_subprog_cnt;		/* number of hidden subprogs */
 	int exception_callback_subprog;
include/uapi/linux/bpf.h +11 -0
index ae83d8649ef1..2aa634942af8 100644
@@ -1026,6 +1026,7 @@ enum bpf_map_type {
 	BPF_MAP_TYPE_USER_RINGBUF,
 	BPF_MAP_TYPE_CGRP_STORAGE,
 	BPF_MAP_TYPE_ARENA,
+	BPF_MAP_TYPE_INSN_ARRAY,
 	__MAX_BPF_MAP_TYPE
 };
 
@@ -7645,4 +7646,14 @@ enum bpf_kfunc_flags {
 	BPF_F_PAD_ZEROS = (1ULL << 0),
 };
 
+/*
+ * Values of a BPF_MAP_TYPE_INSN_ARRAY entry must be of this type.
+ * On updates jitted_off must be equal to 0.
+ */
+struct bpf_insn_array_value {
+	__u32 jitted_off;
+	__u32 xlated_off;
+};
+
+
 #endif /* _UAPI__LINUX_BPF_H__ */
kernel/bpf/Makefile +1 -1
index 7fd0badfacb1..232cbc97434d 100644
@@ -9,7 +9,7 @@ CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
 obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o log.o token.o liveness.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o
 obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
-obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o
+obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
 obj-${CONFIG_BPF_LSM}	  += bpf_inode_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
kernel/bpf/bpf_insn_array.c new file +285 -0

285 lines not on this page · raw message

kernel/bpf/syscall.c +22 -0
index a48fa86f82a7..dbedcdaa515c 100644
@@ -1478,6 +1478,7 @@ static int map_create(union bpf_attr *attr, bpfptr_t uattr)
 	case BPF_MAP_TYPE_STRUCT_OPS:
 	case BPF_MAP_TYPE_CPUMAP:
 	case BPF_MAP_TYPE_ARENA:
+	case BPF_MAP_TYPE_INSN_ARRAY:
 		if (!bpf_token_capable(token, CAP_BPF))
 			goto put_token;
 		break;
@@ -2838,6 +2839,23 @@ static int bpf_prog_verify_signature(struct bpf_prog *prog, union bpf_attr *attr
 	return err;
 }
 
+static int bpf_prog_mark_insn_arrays_ready(struct bpf_prog *prog)
+{
+	int err;
+	int i;
+
+	for (i = 0; i < prog->aux->used_map_cnt; i++) {
+		if (prog->aux->used_maps[i]->map_type != BPF_MAP_TYPE_INSN_ARRAY)
+			continue;
+
+		err = bpf_insn_array_ready(prog->aux->used_maps[i]);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+
 /* last field in 'union bpf_attr' used by this command */
 #define BPF_PROG_LOAD_LAST_FIELD keyring_id
 
@@ -3067,6 +3085,10 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
 	if (err < 0)
 		goto free_used_maps;
 
+	err = bpf_prog_mark_insn_arrays_ready(prog);
+	if (err < 0)
+		goto free_used_maps;
+
 	err = bpf_prog_alloc_id(prog);
 	if (err)
 		goto free_used_maps;
kernel/bpf/verifier.c +43 -0

79 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +11 -0
index ae83d8649ef1..2aa634942af8 100644
@@ -1026,6 +1026,7 @@ enum bpf_map_type {
 	BPF_MAP_TYPE_USER_RINGBUF,
 	BPF_MAP_TYPE_CGRP_STORAGE,
 	BPF_MAP_TYPE_ARENA,
+	BPF_MAP_TYPE_INSN_ARRAY,
 	__MAX_BPF_MAP_TYPE
 };
 
@@ -7645,4 +7646,14 @@ enum bpf_kfunc_flags {
 	BPF_F_PAD_ZEROS = (1ULL << 0),
 };
 
+/*
+ * Values of a BPF_MAP_TYPE_INSN_ARRAY entry must be of this type.
+ * On updates jitted_off must be equal to 0.
+ */
+struct bpf_insn_array_value {
+	__u32 jitted_off;
+	__u32 xlated_off;
+};
+
+
 #endif /* _UAPI__LINUX_BPF_H__ */
Signature · 1 line
2.34.1
maintainer
#7 lore raw

Re: [PATCH v5 bpf-next 04/15] bpf, x86: add new map type: instructions array

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

Overall I think this patch is fine.
We discussed this some time ago, but I can't find the previous discussion:
would it be possible to make this map element a tuple of three elements (orig_off, xlated_off, jitted_off)?
Visible to user as well.

[...]

Quoted 4 lines
include/linux/bpf_verifier.h +0 -0
index 4c497e839526..cc06e6d57faa 100644

[...]

include/linux/bpf_verifier.h enum bpf_kfunc_flags { · line 7656

Quoted 12 lines
include/linux/bpf_verifier.h +8 -0
@@ -7645,4 +7646,14 @@ enum bpf_kfunc_flags {
 	BPF_F_PAD_ZEROS = (1ULL << 0),
 };
 
+/*
+ * Values of a BPF_MAP_TYPE_INSN_ARRAY entry must be of this type.
+ * On updates jitted_off must be equal to 0.
+ */
+struct bpf_insn_array_value {
+	__u32 jitted_off;
+	__u32 xlated_off;
+};

Could you please expand the comment a bit? Describe the meaning of the fields both before and after program load.

Quoted 3 lines
include/linux/bpf_verifier.h +2 -0
+
+
 #endif /* _UAPI__LINUX_BPF_H__ */

[...]

include/linux/bpf_verifier.h line 6

Quoted 7 lines
include/linux/bpf_verifier.h +6 -0
@@ -0,0 +1,285 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2025 Isovalent */
+
+#include <linux/bpf.h>
+
+#define MAX_INSN_ARRAY_ENTRIES 256

Hm, did not notice this before. We probably need an option limiting max number of jump table alternatives.

Yonghong, wdyt?

[...]

include/linux/bpf_verifier.h line 17

Quoted 11 lines
include/linux/bpf_verifier.h +11 -0
+void bpf_insn_array_adjust_after_remove(struct bpf_map *map, u32 off, u32 len)
+{
+	struct bpf_insn_array *insn_array = cast_insn_array(map);
+	int i;
+
+	for (i = 0; i < map->max_entries; i++) {
+		if (insn_array->ptrs[i].user_value.xlated_off < off)
+			continue;
+		if (insn_array->ptrs[i].user_value.xlated_off == INSN_DELETED)
+			continue;
+		if (insn_array->ptrs[i].user_value.xlated_off >= off &&
                                                              ^^^^^^

Nit: this condition is redundant

Quoted 14 lines
include/linux/bpf_verifier.h +14 -0
+		    insn_array->ptrs[i].user_value.xlated_off < off + len)
+			insn_array->ptrs[i].user_value.xlated_off = INSN_DELETED;
+		else
+			insn_array->ptrs[i].user_value.xlated_off -= len;
+	}
+}
+
+void bpf_prog_update_insn_ptr(struct bpf_prog *prog,
+			      u32 xlated_off,
+			      u32 jitted_off,
+			      void *jitted_ip)
+{
+	struct bpf_insn_array *insn_array;
+	struct bpf_map *map;

include/linux/bpf_verifier.h line 41

Quoted 10 lines
include/linux/bpf_verifier.h +10 -0
+	int i, j;
+
+	for (i = 0; i < prog->aux->used_map_cnt; i++) {
+		map = prog->aux->used_maps[i];
+		if (!is_insn_array(map))
+			continue;
+
+		insn_array = cast_insn_array(map);
+		for (j = 0; j < map->max_entries; j++) {
+			if (insn_array->ptrs[j].user_value.xlated_off == xlated_off) {

If this would check for insn_array->ptrs[j].orig_xlated_off == xlated_off there would be no need in user_value.xlated_off = orig_xlated_off in the bpf_insn_array_init(), right?

Quoted 7 lines
include/linux/bpf_verifier.h +7 -0
+				insn_array->ips[j] = (long)jitted_ip;
+				insn_array->ptrs[j].jitted_ip = jitted_ip;
+				insn_array->ptrs[j].user_value.jitted_off = jitted_off;
+			}
+		}
+	}
+}

[...]

#8 lore raw

Re: [PATCH v5 bpf-next 04/15] bpf, x86: add new map type: instructions array

Quoted 7 lines · Eduard Zingerman

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

Overall I think this patch is fine.
We discussed this some time ago, but I can't find the previous discussion:
would it be possible to make this map element a tuple of three elements (orig_off, xlated_off, jitted_off)?
Visible to user as well.

See https://lore.kernel.org/bpf/[email protected]/

In short, this will make the map element to be of different size from userspace and kernel (BPF) perspective.

(Userspace can build the orig_off -> xlated_off mapping easily, if needed, just keep a copy of the map before the load.)

Quoted 13 lines

[...]

Quoted 4 lines
include/linux/bpf_verifier.h +0 -0
index 4c497e839526..cc06e6d57faa 100644

[...]

Quoted 4 lines
include/linux/bpf_verifier.h +0 -0
@@ -7645,4 +7646,14 @@ enum bpf_kfunc_flags {
 	BPF_F_PAD_ZEROS = (1ULL << 0),
 };
 
Quoted 11 lines

include/linux/bpf_verifier.h enum bpf_kfunc_flags { · line 7656

Quoted 8 lines
include/linux/bpf_verifier.h +8 -0
+/*
+ * Values of a BPF_MAP_TYPE_INSN_ARRAY entry must be of this type.
+ * On updates jitted_off must be equal to 0.
+ */
+struct bpf_insn_array_value {
+	__u32 jitted_off;
+	__u32 xlated_off;
+};

Could you please expand the comment a bit? Describe the meaning of the fields both before and after program load.

Sure.

Quoted 17 lines
Quoted 3 lines
include/linux/bpf_verifier.h +2 -0
+
+
 #endif /* _UAPI__LINUX_BPF_H__ */

[...]

include/linux/bpf_verifier.h line 6

Quoted 7 lines
include/linux/bpf_verifier.h +6 -0
@@ -0,0 +1,285 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2025 Isovalent */
+
+#include <linux/bpf.h>
+
+#define MAX_INSN_ARRAY_ENTRIES 256

Hm, did not notice this before. We probably need an option limiting max number of jump table alternatives.

Quoted 1 line

Yonghong, wdyt?

This one comes from the fact I've mentioned in the other place: need to optimize the lookup from jit (not it is brute force). Then this limitation will go away.

But also curious, what LLVM thinks about this. Will it, theoretically, create say 65K tables or so?

Quoted 14 lines

[...]

include/linux/bpf_verifier.h

Quoted 11 lines
include/linux/bpf_verifier.h +11 -0
+void bpf_insn_array_adjust_after_remove(struct bpf_map *map, u32 off, u32 len)
+{
+	struct bpf_insn_array *insn_array = cast_insn_array(map);
+	int i;
+
+	for (i = 0; i < map->max_entries; i++) {
+		if (insn_array->ptrs[i].user_value.xlated_off < off)
+			continue;
+		if (insn_array->ptrs[i].user_value.xlated_off == INSN_DELETED)
+			continue;
+		if (insn_array->ptrs[i].user_value.xlated_off >= off &&
                                                              ^^^^^^
Quoted 1 line

Nit: this condition is redundant

True, thanks, will remove it.

Quoted 21 lines
Quoted 21 lines
include/linux/bpf_verifier.h +20 -0
+		    insn_array->ptrs[i].user_value.xlated_off < off + len)
+			insn_array->ptrs[i].user_value.xlated_off = INSN_DELETED;
+		else
+			insn_array->ptrs[i].user_value.xlated_off -= len;
+	}
+}
+
+void bpf_prog_update_insn_ptr(struct bpf_prog *prog,
+			      u32 xlated_off,
+			      u32 jitted_off,
+			      void *jitted_ip)
+{
+	struct bpf_insn_array *insn_array;
+	struct bpf_map *map;
+	int i, j;
+
+	for (i = 0; i < prog->aux->used_map_cnt; i++) {
+		map = prog->aux->used_maps[i];
+		if (!is_insn_array(map))
+			continue;
Quoted 8 lines

include/linux/bpf_verifier.h

Quoted 4 lines
include/linux/bpf_verifier.h +4 -0
+
+		insn_array = cast_insn_array(map);
+		for (j = 0; j < map->max_entries; j++) {
+			if (insn_array->ptrs[j].user_value.xlated_off == xlated_off) {

If this would check for insn_array->ptrs[j].orig_xlated_off == xlated_off there would be no need in user_value.xlated_off = orig_xlated_off in the bpf_insn_array_init(), right?

The copy of the original offset is kept inside the map for the following reason. When the map is first loaded, it is frozen. Thus user can't update it anymore. During load some of xlated_off are changed (together with program code). If the program load fails, it is common to reload it with a log buffer. If map was changed, it now will point to incorrect instructions. So in this case the map should be seen as the original one, and the orig_xlated_off is used to reset it.

Quoted 9 lines
Quoted 7 lines
include/linux/bpf_verifier.h +7 -0
+				insn_array->ips[j] = (long)jitted_ip;
+				insn_array->ptrs[j].jitted_ip = jitted_ip;
+				insn_array->ptrs[j].user_value.jitted_off = jitted_off;
+			}
+		}
+	}
+}

[...]

maintainer
#9 lore raw

Re: [PATCH v5 bpf-next 04/15] bpf, x86: add new map type: instructions array

Quoted 9 lines · Anton Protopopov
Quoted 7 lines · Eduard Zingerman

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

Overall I think this patch is fine.
We discussed this some time ago, but I can't find the previous discussion:
would it be possible to make this map element a tuple of three elements (orig_off, xlated_off, jitted_off)?
Visible to user as well.

Quoted 4 lines

See https://lore.kernel.org/bpf/[email protected]/

In short, this will make the map element to be of different size from userspace and kernel (BPF) perspective.

But why does map element size has to be different between kernel and user? For internal use there is an ips array and that has to be 64-bit. For external use, it appears that any structure can be used.
I probably don't understand something.

Quoted 2 lines

(Userspace can build the orig_off -> xlated_off mapping easily, if needed, just keep a copy of the map before the load.)

[...]

Quoted 4 lines
Quoted 4 lines
Quoted 1 line

+#define MAX_INSN_ARRAY_ENTRIES 256

Hm, did not notice this before. We probably need an option limiting max number of jump table alternatives.

(I meant LLVM option, but you probably inferred)

Quoted 9 lines
Quoted 2 lines

Yonghong, wdyt?

This one comes from the fact I've mentioned in the other place: need to optimize the lookup from jit (not it is brute force). Then this limitation will go away.

But also curious, what LLVM thinks about this. Will it, theoretically, create say 65K tables or so?

This generates a 4K jump table for me:

  $ cat gen-foo.py
  import random as r

print('int foo(int i) {')
print(' switch(i) {')
for c in r.sample(range(0, 4096), 1024):

      print(f'  case {c}: return {r.randint(-10000, 10000)};')

print(' }')
print(' return 0;')
print('}')

  $ python3 gen-foo.py | clang -xc -O2 -S -o - - | grep '.quad' | wc -l
  4093

[...]

Quoted 22 lines
Quoted 13 lines
Quoted 13 lines
kernel/bpf/bpf_insn_array.c new file +13 -0
+void bpf_prog_update_insn_ptr(struct bpf_prog *prog,
+			      u32 xlated_off,
+			      u32 jitted_off,
+			      void *jitted_ip)
+{
+	struct bpf_insn_array *insn_array;
+	struct bpf_map *map;
+	int i, j;
+
+	for (i = 0; i < prog->aux->used_map_cnt; i++) {
+		map = prog->aux->used_maps[i];
+		if (!is_insn_array(map))
+			continue;
Quoted 8 lines

kernel/bpf/bpf_insn_array.c line 278

Quoted 4 lines
kernel/bpf/bpf_insn_array.c new file +4 -0
+
+		insn_array = cast_insn_array(map);
+		for (j = 0; j < map->max_entries; j++) {
+			if (insn_array->ptrs[j].user_value.xlated_off == xlated_off) {

If this would check for insn_array->ptrs[j].orig_xlated_off == xlated_off there would be no need in user_value.xlated_off = orig_xlated_off in the bpf_insn_array_init(), right?

Quoted 8 lines

The copy of the original offset is kept inside the map for the following reason. When the map is first loaded, it is frozen. Thus user can't update it anymore. During load some of xlated_off are changed (together with program code). If the program load fails, it is common to reload it with a log buffer. If map was changed, it now will point to incorrect instructions. So in this case the map should be seen as the original one, and the orig_xlated_off is used to reset it.

Missed this part:

Quoted 1 line

'If map was changed, it now will point to incorrect instructions.'

Makes sense, thank you for explaining.

[...]

#10 lore raw

Re: [PATCH v5 bpf-next 04/15] bpf, x86: add new map type: instructions array

Quoted 12 lines · Eduard Zingerman
Quoted 11 lines · Anton Protopopov
Quoted 7 lines · Eduard Zingerman

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

Overall I think this patch is fine.
We discussed this some time ago, but I can't find the previous discussion:
would it be possible to make this map element a tuple of three elements (orig_off, xlated_off, jitted_off)?
Visible to user as well.

See https://lore.kernel.org/bpf/[email protected]/

Quoted 7 lines
Quoted 2 lines

In short, this will make the map element to be of different size from userspace and kernel (BPF) perspective.

But why does map element size has to be different between kernel and user? For internal use there is an ips array and that has to be 64-bit. For external use, it appears that any structure can be used.
I probably don't understand something.

I think that map->value_size is expected to be between user space and kernel code (verifier). For this map we use PTR_TO_MAP_VALUE, etc.

But before diving deeper into this topic, what is missing, really? The orig->xlated mapping is easy to keep from userspace, if needed, why is this not sufficient?

Quoted 30 lines
Quoted 2 lines

(Userspace can build the orig_off -> xlated_off mapping easily, if needed, just keep a copy of the map before the load.)

[...]

Quoted 4 lines
Quoted 4 lines
Quoted 1 line

+#define MAX_INSN_ARRAY_ENTRIES 256

Hm, did not notice this before. We probably need an option limiting max number of jump table alternatives.

(I meant LLVM option, but you probably inferred)

Quoted 9 lines
Quoted 2 lines

Yonghong, wdyt?

This one comes from the fact I've mentioned in the other place: need to optimize the lookup from jit (not it is brute force). Then this limitation will go away.

But also curious, what LLVM thinks about this. Will it, theoretically, create say 65K tables or so?

This generates a 4K jump table for me:

  $ cat gen-foo.py
  import random as r

print('int foo(int i) {')
print(' switch(i) {')
for c in r.sample(range(0, 4096), 1024):

Quoted 7 lines
      print(f'  case {c}: return {r.randint(-10000, 10000)};')

print(' }')
print(' return 0;')
print('}')

  $ python3 gen-foo.py | clang -xc -O2 -S -o - - | grep '.quad' | wc -l
  4093

Thanks for the example.

Quoted 40 lines

[...]

Quoted 22 lines
Quoted 13 lines
Quoted 13 lines
kernel/bpf/bpf_insn_array.c new file +13 -0
+void bpf_prog_update_insn_ptr(struct bpf_prog *prog,
+			      u32 xlated_off,
+			      u32 jitted_off,
+			      void *jitted_ip)
+{
+	struct bpf_insn_array *insn_array;
+	struct bpf_map *map;
+	int i, j;
+
+	for (i = 0; i < prog->aux->used_map_cnt; i++) {
+		map = prog->aux->used_maps[i];
+		if (!is_insn_array(map))
+			continue;
Quoted 8 lines

kernel/bpf/bpf_insn_array.c line 278

Quoted 4 lines
kernel/bpf/bpf_insn_array.c new file +4 -0
+
+		insn_array = cast_insn_array(map);
+		for (j = 0; j < map->max_entries; j++) {
+			if (insn_array->ptrs[j].user_value.xlated_off == xlated_off) {

If this would check for insn_array->ptrs[j].orig_xlated_off == xlated_off there would be no need in user_value.xlated_off = orig_xlated_off in the bpf_insn_array_init(), right?

Quoted 8 lines

The copy of the original offset is kept inside the map for the following reason. When the map is first loaded, it is frozen. Thus user can't update it anymore. During load some of xlated_off are changed (together with program code). If the program load fails, it is common to reload it with a log buffer. If map was changed, it now will point to incorrect instructions. So in this case the map should be seen as the original one, and the orig_xlated_off is used to reset it.

Missed this part:

Quoted 1 line

'If map was changed, it now will point to incorrect instructions.'

Makes sense, thank you for explaining.

[...]

maintainer
#11 lore raw

Re: [PATCH v5 bpf-next 04/15] bpf, x86: add new map type: instructions array

Quoted 16 lines · Anton Protopopov
Quoted 15 lines · Eduard Zingerman
Quoted 13 lines · Anton Protopopov
Quoted 7 lines · Eduard Zingerman

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

Overall I think this patch is fine.
We discussed this some time ago, but I can't find the previous discussion:
would it be possible to make this map element a tuple of three elements (orig_off, xlated_off, jitted_off)?
Visible to user as well.

See https://lore.kernel.org/bpf/[email protected]/

In short, this will make the map element to be of different size from userspace and kernel (BPF) perspective.

Quoted 8 lines
Quoted 4 lines

But why does map element size has to be different between kernel and user? For internal use there is an ips array and that has to be 64-bit. For external use, it appears that any structure can be used.
I probably don't understand something.

I think that map->value_size is expected to be between user space and kernel code (verifier). For this map we use PTR_TO_MAP_VALUE, etc.

Looking at the code, it appears you already changed the only place in verifier that cares about map->value_size, by introducing the map_mem_size() function.

All other map->value_size uses are about value lookup/update when communicating with user-space, and thus need no modification.

Quoted 3 lines

But before diving deeper into this topic, what is missing, really? The orig->xlated mapping is easy to keep from userspace, if needed, why is this not sufficient?

It is just more convenient to have all three values at hand, The values are maintained by the kernel anyway.

[...]

#12 lore raw

PATCH v5 5/15 selftests/bpf: add selftests for new insn_array map

In reply to Anton Protopopov

Add the following selftests for new insn_array map:

* Incorrect instruction indexes are rejected
* Two programs can't use the same map
* BPF progs can't operate the map
* no changes to code => map is the same
* expected changes when instructions are added
* expected changes when instructions are deleted
* expected changes when multiple functions are present

---
 .../selftests/bpf/prog_tests/bpf_insn_array.c | 479 ++++++++++++++++++
 1 file changed, 479 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +479 -0
new file mode 100644
index 000000000000..9406a4e2faad
@@ -0,0 +1,479 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <bpf/bpf.h>
+#include <test_progs.h>
+
+static int map_create(__u32 map_type, __u32 max_entries)
+{
+	const char *map_name = "insn_array";
+	__u32 key_size = 4;
+	__u32 value_size = sizeof(struct bpf_insn_array_value);
+
+	return bpf_map_create(map_type, map_name, key_size, value_size, max_entries, NULL);
+}
+
+static int prog_load(struct bpf_insn *insns, __u32 insn_cnt, int *fd_array, __u32 fd_array_cnt)
+{
+	LIBBPF_OPTS(bpf_prog_load_opts, opts);
+
+	opts.fd_array = fd_array;
+	opts.fd_array_cnt = fd_array_cnt;
+
+	return bpf_prog_load(BPF_PROG_TYPE_XDP, NULL, "GPL", insns, insn_cnt, &opts);
+}
+
+/*
+ * Load a program, which will not be anyhow mangled by the verifier.  Add an
+ * insn_array map pointing to every instruction. Check that it hasn't changed
+ * after the program load.
+ */
+static void check_one_to_one_mapping(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 4),
+		BPF_MOV64_IMM(BPF_REG_0, 3),
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = i;
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0, "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, i, "val should be equal i");
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+/*
+ * Try to load a program with a map which points to outside of the program
+ */
+static void check_out_of_bounds_index(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 4),
+		BPF_MOV64_IMM(BPF_REG_0, 3),
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd, map_fd;
+	struct bpf_insn_array_value val = {};
+	int key;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, 1);
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	key = 0;
+	val.xlated_off = ARRAY_SIZE(insns); /* too big */
+	if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &key, &val, 0), 0, "bpf_map_update_elem"))
+		goto cleanup;
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	errno = 0;
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_EQ(prog_fd, -EINVAL, "program should have been rejected (prog_fd != -EINVAL)")) {
+		close(prog_fd);
+		goto cleanup;
+	}
+
+cleanup:
+	close(map_fd);
+}
+
+/*
+ * Try to load a program with a map which points to the middle of 16-bit insn
+ */
+static void check_mid_insn_index(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_LD_IMM64(BPF_REG_0, 0), /* 2 x 8 */
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd, map_fd;
+	struct bpf_insn_array_value val = {};
+	int key;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, 1);
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	key = 0;
+	val.xlated_off = 1; /* middle of 16-byte instruction */
+	if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &key, &val, 0), 0, "bpf_map_update_elem"))
+		goto cleanup;
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	errno = 0;
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_EQ(prog_fd, -EINVAL, "program should have been rejected (prog_fd != -EINVAL)")) {
+		close(prog_fd);
+		goto cleanup;
+	}
+
+cleanup:
+	close(map_fd);
+}
+
+static void check_incorrect_index(void)
+{
+	check_out_of_bounds_index();
+	check_mid_insn_index();
+}
+
+/*
+ * Load a program with two patches (get jiffies, for simplicity). Add an
+ * insn_array map pointing to every instruction. Check how it was changed
+ * after the program load.
+ */
+static void check_simple(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	__u32 map_in[] = {0, 1, 2, 3, 4, 5};
+	__u32 map_out[] = {0, 1, 4, 5, 8, 9};
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = map_in[i];
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0,
+			       "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, map_out[i], "val should be equal map_out[i]");
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+/*
+ * Verifier can delete code in two cases: nops & dead code. From insn
+ * array's point of view, the two cases are the same, so test using
+ * the simplest method: by loading some nops
+ */
+static void check_deletions(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	__u32 map_in[] = {0, 1, 2, 3, 4, 5};
+	__u32 map_out[] = {0, -1, 1, -1, 2, 3};
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = map_in[i];
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0,
+			       "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, map_out[i], "val should be equal map_out[i]");
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+static void check_with_functions(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 1, 0, 2),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_EXIT_INSN(),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	__u32 map_in[] =  { 0, 1,  2, 3, 4, 5, /* func */  6, 7,  8, 9, 10};
+	__u32 map_out[] = {-1, 0, -1, 3, 4, 5, /* func */ -1, 6, -1, 9, 10};
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = map_in[i];
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0,
+			       "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, map_out[i], "val should be equal map_out[i]");
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+/* Once map was initialized, it should be frozen */
+static void check_load_unfrozen_map(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = i;
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0, "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	errno = 0;
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_EQ(prog_fd, -EINVAL, "program should have been rejected (prog_fd != -EINVAL)"))
+		goto cleanup;
+
+	/* correctness: now freeze the map, the program should load fine */
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, i, "val should be equal i");
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+/* Map can be used only by one BPF program */
+static void check_no_map_reuse(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd, extra_fd = -1;
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = i;
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0, "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, i, "val should be equal i");
+	}
+
+	errno = 0;
+	extra_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_EQ(extra_fd, -EBUSY, "program should have been rejected (extra_fd != -EBUSY)"))
+		goto cleanup;
+
+	/* correctness: check that prog is still loadable without fd_array */
+	extra_fd = prog_load(insns, ARRAY_SIZE(insns), NULL, 0);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD): expected no error"))
+		goto cleanup;
+
+cleanup:
+	close(extra_fd);
+	close(prog_fd);
+	close(map_fd);
+}
+
+static void check_bpf_no_lookup(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_LD_MAP_FD(BPF_REG_1, 0),
+		BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
+		BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
+		BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, 1);
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	insns[0].imm = map_fd;
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	errno = 0;
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), NULL, 0);
+	if (!ASSERT_EQ(prog_fd, -EINVAL, "program should have been rejected (prog_fd != -EINVAL)"))
+		goto cleanup;
+
+	/* correctness: check that prog is still loadable with normal map */
+	close(map_fd);
+	map_fd = map_create(BPF_MAP_TYPE_ARRAY, 1);
+	insns[0].imm = map_fd;
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), NULL, 0);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+static void check_bpf_side(void)
+{
+	check_bpf_no_lookup();
+}
+
+void test_bpf_insn_array(void)
+{
+	/* Test if offsets are adjusted properly */
+
+	if (test__start_subtest("one2one"))
+		check_one_to_one_mapping();
+
+	if (test__start_subtest("simple"))
+		check_simple();
+
+	if (test__start_subtest("deletions"))
+		check_deletions();
+
+	if (test__start_subtest("multiple-functions"))
+		check_with_functions();
+
+	/* Check all kinds of operations and related restrictions */
+
+	if (test__start_subtest("incorrect-index"))
+		check_incorrect_index();
+
+	if (test__start_subtest("load-unfrozen-map"))
+		check_load_unfrozen_map();
+
+	if (test__start_subtest("no-map-reuse"))
+		check_no_map_reuse();
+
+	if (test__start_subtest("bpf-side-ops"))
+		check_bpf_side();
+}
Signature · 1 line
2.34.1
maintainer
#13 lore raw

Re: [PATCH v5 bpf-next 05/15] selftests/bpf: add selftests for new insn_array map

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

Overall lgtm, some code duplication worth removing, I think.

[...]

Quoted 20 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +20 -0
+/*
+ * Try to load a program with a map which points to outside of the program
+ */
+static void check_out_of_bounds_index(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 4),
+		BPF_MOV64_IMM(BPF_REG_0, 3),
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd, map_fd;
+	struct bpf_insn_array_value val = {};
+	int key;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, 1);
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;

tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c line 102

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +10 -0
+
+	key = 0;
+	val.xlated_off = ARRAY_SIZE(insns); /* too big */
+	if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &key, &val, 0), 0, "bpf_map_update_elem"))
+		goto cleanup;
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	errno = 0;

Nit: errno is not used in the check below, hence there is no need to reset it.
(here and in other tests below)

Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +9 -0
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_EQ(prog_fd, -EINVAL, "program should have been rejected (prog_fd != -EINVAL)")) {
+		close(prog_fd);
+		goto cleanup;
+	}
+
+cleanup:
+	close(map_fd);
+}

[...]

Quoted 34 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +34 -0
+/*
+ * Load a program with two patches (get jiffies, for simplicity). Add an
+ * insn_array map pointing to every instruction. Check how it was changed
+ * after the program load.
+ */
+static void check_simple(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	__u32 map_in[] = {0, 1, 2, 3, 4, 5};
+	__u32 map_out[] = {0, 1, 4, 5, 8, 9};
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = map_in[i];
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0,
+			       "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;

tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c line 198

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +10 -0
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, map_out[i], "val should be equal map_out[i]");

Nit: maybe print i, xlated_off and map_out[i] here?

If this test fails, debugging it with -vvv would be inconvenient, as there is no way to see xlated program. Maybe extend load_prog() to check debug level and add capability to print xlated? See __xlated annotation implementation in selftests.

Quoted 12 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +12 -0
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+/*
+ * Verifier can delete code in two cases: nops & dead code. From insn
+ * array's point of view, the two cases are the same, so test using
+ * the simplest method: by loading some nops
+ */

tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c line 220

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +10 -0
+static void check_deletions(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};

Success test cases follow identical pattern, ultimately having 3 input parameters:
- program
- map_in
- map_out

Would it make sense to write a generic utility function accepting exactly these three params and hiding the boilerplate?

Quoted 35 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +35 -0
+	int prog_fd = -1, map_fd;
+	__u32 map_in[] = {0, 1, 2, 3, 4, 5};
+	__u32 map_out[] = {0, -1, 1, -1, 2, 3};
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = map_in[i];
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0,
+			       "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, map_out[i], "val should be equal map_out[i]");
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}

[...]

#14 lore raw

Re: [PATCH v5 bpf-next 05/15] selftests/bpf: add selftests for new insn_array map

Quoted 31 lines · Eduard Zingerman

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

Overall lgtm, some code duplication worth removing, I think.

[...]

Quoted 25 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +25 -0
+/*
+ * Try to load a program with a map which points to outside of the program
+ */
+static void check_out_of_bounds_index(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 4),
+		BPF_MOV64_IMM(BPF_REG_0, 3),
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd, map_fd;
+	struct bpf_insn_array_value val = {};
+	int key;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, 1);
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	key = 0;
+	val.xlated_off = ARRAY_SIZE(insns); /* too big */
+	if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &key, &val, 0), 0, "bpf_map_update_elem"))
+		goto cleanup;
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c line 102

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +5 -0
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	errno = 0;

Nit: errno is not used in the check below, hence there is no need to reset it.
(here and in other tests below)

Ok, will do.

Quoted 50 lines
Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +9 -0
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_EQ(prog_fd, -EINVAL, "program should have been rejected (prog_fd != -EINVAL)")) {
+		close(prog_fd);
+		goto cleanup;
+	}
+
+cleanup:
+	close(map_fd);
+}

[...]

Quoted 38 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +38 -0
+/*
+ * Load a program with two patches (get jiffies, for simplicity). Add an
+ * insn_array map pointing to every instruction. Check how it was changed
+ * after the program load.
+ */
+static void check_simple(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	__u32 map_in[] = {0, 1, 2, 3, 4, 5};
+	__u32 map_out[] = {0, 1, 4, 5, 8, 9};
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = map_in[i];
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0,
+			       "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c line 198

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +6 -0
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, map_out[i], "val should be equal map_out[i]");

Nit: maybe print i, xlated_off and map_out[i] here?

+1

Quoted 4 lines

If this test fails, debugging it with -vvv would be inconvenient, as there is no way to see xlated program. Maybe extend load_prog() to check debug level and add capability to print xlated? See __xlated annotation implementation in selftests.

Ok, nice, will do.

Just in case, typically, when I write selftests I add smth like

    if (getenv("HANG") && *(getenv("HANG")))
        for (;;)
            pause();

before destroying skeleton, so I can examine what was loaded, if needed.

Quoted 30 lines
Quoted 13 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +12 -0
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}
+
+/*
+ * Verifier can delete code in two cases: nops & dead code. From insn
+ * array's point of view, the two cases are the same, so test using
+ * the simplest method: by loading some nops
+ */

tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c line 220

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +10 -0
+static void check_deletions(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_JMP_IMM(BPF_JA, 0, 0, 0), /* nop */
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_EXIT_INSN(),
+	};

Success test cases follow identical pattern, ultimately having 3 input parameters:
- program
- map_in
- map_out

Quoted 2 lines

Would it make sense to write a generic utility function accepting exactly these three params and hiding the boilerplate?

Will do.

Are you ok with the contexts of tests? Any more test cases, maybe?

Quoted 37 lines
Quoted 35 lines
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c new file +35 -0
+	int prog_fd = -1, map_fd;
+	__u32 map_in[] = {0, 1, 2, 3, 4, 5};
+	__u32 map_out[] = {0, -1, 1, -1, 2, 3};
+	struct bpf_insn_array_value val = {};
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = map_in[i];
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0,
+			       "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		ASSERT_EQ(val.xlated_off, map_out[i], "val should be equal map_out[i]");
+	}
+
+cleanup:
+	close(prog_fd);
+	close(map_fd);
+}

[...]

maintainer
#15 lore raw

Re: [PATCH v5 bpf-next 05/15] selftests/bpf: add selftests for new insn_array map

On Fri, 2025-10-03 at 07:46 +0000, Anton Protopopov wrote:

[...]

Quoted 7 lines
Quoted 4 lines

If this test fails, debugging it with -vvv would be inconvenient, as there is no way to see xlated program. Maybe extend load_prog() to check debug level and add capability to print xlated? See __xlated annotation implementation in selftests.

Ok, nice, will do.

Quoted 7 lines

Just in case, typically, when I write selftests I add smth like

    if (getenv("HANG") && *(getenv("HANG")))
        for (;;)
            pause();

before destroying skeleton, so I can examine what was loaded, if needed.

I mean, yeah, but I regularly find myself adding options to print verifier log in selftests that are not within test_loader framework (which handles -vvv uniformly), and it is annoying every time.

[...]

Quoted 6 lines
Quoted 6 lines

Success test cases follow identical pattern, ultimately having 3 input parameters:
- program
- map_in
- map_out

Quoted 6 lines
Quoted 2 lines

Would it make sense to write a generic utility function accepting exactly these three params and hiding the boilerplate?

Will do.

Are you ok with the contexts of tests? Any more test cases, maybe?

I think you covered interesting cases.
We will add more tests once bugs are reported and addressed :)

[...]

#16 lore raw

PATCH v5 6/15 bpf: support instructions arrays with constants blinding

In reply to Anton Protopopov

When bpf_jit_harden is enabled, all constants in the BPF code are blinded to prevent JIT spraying attacks. This happens during JIT phase. Adjust all the related instruction arrays accordingly.

---
 kernel/bpf/core.c     | 20 ++++++++++++++++++++
 kernel/bpf/verifier.c | 11 ++++++++++-
 2 files changed, 30 insertions(+), 1 deletion(-)
kernel/bpf/core.c +20 -0
index d595fe512498..4b62a03d6df5 100644
@@ -1450,6 +1450,23 @@ void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
 	bpf_prog_clone_free(fp_other);
 }
 
+static void adjust_insn_arrays(struct bpf_prog *prog, u32 off, u32 len)
+{
+#ifdef CONFIG_BPF_SYSCALL
+	struct bpf_map *map;
+	int i;
+
+	if (len <= 1)
+		return;
+
+	for (i = 0; i < prog->aux->used_map_cnt; i++) {
+		map = prog->aux->used_maps[i];
+		if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
+			bpf_insn_array_adjust(map, off, len);
+	}
+#endif
+}
+
 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
 {
 	struct bpf_insn insn_buff[16], aux[2];
@@ -1505,6 +1522,9 @@ struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
 		clone = tmp;
 		insn_delta = rewritten - 1;
 
+		/* Instructions arrays must be updated using absolute xlated offsets */
+		adjust_insn_arrays(clone, prog->aux->subprog_start + i, rewritten);
+
 		/* Walk new program and skip insns we just inserted. */
 		insn = clone->insnsi + i + insn_delta;
 		insn_cnt += insn_delta;
kernel/bpf/verifier.c +10 -1
index 4704bbdea785..705535711d10 100644
@@ -21537,6 +21537,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 	struct bpf_insn *insn;
 	void *old_bpf_func;
 	int err, num_exentries;
+	int old_len, subprog_start_adjustment = 0;
 
 	if (env->subprog_cnt <= 1)
 		return 0;
@@ -21611,7 +21612,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 		func[i]->aux->func_idx = i;
 		/* Below members will be freed only at prog->aux */
 		func[i]->aux->btf = prog->aux->btf;
-		func[i]->aux->subprog_start = subprog_start;
+		func[i]->aux->subprog_start = subprog_start + subprog_start_adjustment;
 		func[i]->aux->func_info = prog->aux->func_info;
 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
 		func[i]->aux->poke_tab = prog->aux->poke_tab;
@@ -21665,7 +21666,15 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
 		if (!i)
 			func[i]->aux->exception_boundary = env->seen_exception;
+
+		/*
+		 * To properly pass the absolute subprog start to jit
+		 * all instruction adjustments should be accumulated
+		 */
+		old_len = func[i]->len;
 		func[i] = bpf_int_jit_compile(func[i]);
+		subprog_start_adjustment += func[i]->len - old_len;
+
 		if (!func[i]->jited) {
 			err = -ENOTSUPP;
 			goto out_free;
Signature · 1 line
2.34.1
maintainer Reviewed-by on v5 6/15
#17 lore raw

Re: [PATCH v5 bpf-next 06/15] bpf: support instructions arrays with constants blinding

Quoted 6 lines · Anton Protopopov

When bpf_jit_harden is enabled, all constants in the BPF code are blinded to prevent JIT spraying attacks. This happens during JIT phase. Adjust all the related instruction arrays accordingly.

---

I have to reluctantly agree that this is the simplest way to handle this.

[...]

#18 lore raw

PATCH v5 7/15 selftests/bpf: test instructions arrays with blinding

In reply to Anton Protopopov

Add a specific test for instructions arrays with blinding enabled.

---
 .../selftests/bpf/prog_tests/bpf_insn_array.c | 95 +++++++++++++++++++
 1 file changed, 95 insertions(+)
tools/testing/selftests/bpf/prog_tests/bpf_insn_array.c +95 -0
index 9406a4e2faad..22a6f0ec66f6 100644
@@ -305,6 +305,98 @@ static void check_with_functions(void)
 	close(map_fd);
 }
 
+static int set_bpf_jit_harden(char *level)
+{
+	char old_level;
+	int err = -1;
+	int fd = -1;
+
+	fd = open("/proc/sys/net/core/bpf_jit_harden", O_RDWR | O_NONBLOCK);
+	if (fd < 0) {
+		ASSERT_FAIL("open .../bpf_jit_harden returned %d (errno=%d)", fd, errno);
+		return -1;
+	}
+
+	err = read(fd, &old_level, 1);
+	if (err != 1) {
+		ASSERT_FAIL("read from .../bpf_jit_harden returned %d (errno=%d)", err, errno);
+		err = -1;
+		goto end;
+	}
+
+	lseek(fd, 0, SEEK_SET);
+
+	err = write(fd, level, 1);
+	if (err != 1) {
+		ASSERT_FAIL("write to .../bpf_jit_harden returned %d (errno=%d)", err, errno);
+		err = -1;
+		goto end;
+	}
+
+	err = 0;
+	*level = old_level;
+end:
+	if (fd >= 0)
+		close(fd);
+	return err;
+}
+
+static void check_blindness(void)
+{
+	struct bpf_insn insns[] = {
+		BPF_MOV64_IMM(BPF_REG_0, 4),
+		BPF_MOV64_IMM(BPF_REG_0, 3),
+		BPF_MOV64_IMM(BPF_REG_0, 2),
+		BPF_MOV64_IMM(BPF_REG_0, 1),
+		BPF_EXIT_INSN(),
+	};
+	int prog_fd = -1, map_fd;
+	struct bpf_insn_array_value val = {};
+	char bpf_jit_harden = '@'; /* non-exizsting value */
+	int i;
+
+	map_fd = map_create(BPF_MAP_TYPE_INSN_ARRAY, ARRAY_SIZE(insns));
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		val.xlated_off = i;
+		if (!ASSERT_EQ(bpf_map_update_elem(map_fd, &i, &val, 0), 0, "bpf_map_update_elem"))
+			goto cleanup;
+	}
+
+	if (!ASSERT_EQ(bpf_map_freeze(map_fd), 0, "bpf_map_freeze"))
+		goto cleanup;
+
+	bpf_jit_harden = '2';
+	if (set_bpf_jit_harden(&bpf_jit_harden)) {
+		bpf_jit_harden = '@'; /* open, read or write failed => no write was done */
+		goto cleanup;
+	}
+
+	prog_fd = prog_load(insns, ARRAY_SIZE(insns), &map_fd, 1);
+	if (!ASSERT_GE(prog_fd, 0, "bpf(BPF_PROG_LOAD)"))
+		goto cleanup;
+
+	for (i = 0; i < ARRAY_SIZE(insns); i++) {
+		char fmt[32];
+
+		if (!ASSERT_EQ(bpf_map_lookup_elem(map_fd, &i, &val), 0, "bpf_map_lookup_elem"))
+			goto cleanup;
+
+		snprintf(fmt, sizeof(fmt), "val should be equal 3*%d", i);
+		ASSERT_EQ(val.xlated_off, i * 3, fmt);
+	}
+
+cleanup:
+	/* restore the old one */
+	if (bpf_jit_harden != '@')
+		set_bpf_jit_harden(&bpf_jit_harden);
+
+	close(prog_fd);
+	close(map_fd);
+}
+
 /* Once map was initialized, it should be frozen */
 static void check_load_unfrozen_map(void)
 {
@@ -463,6 +555,9 @@ void test_bpf_insn_array(void)
 	if (test__start_subtest("multiple-functions"))
 		check_with_functions();
 
+	if (test__start_subtest("blindness"))
+		check_blindness();
+
 	/* Check all kinds of operations and related restrictions */
 
 	if (test__start_subtest("incorrect-index"))
Signature · 1 line
2.34.1
#20 lore raw

PATCH v5 8/15 bpf, x86: allow indirect jumps to r8...r15

In reply to Anton Protopopov

Currently the emit_indirect_jump() function only accepts one of the RAX, RCX, ..., RBP registers as the destination. Make it to accept R8, R9, ..., R15 as well, and make callers to pass BPF registers, not native registers. This is required to enable indirect jumps support in eBPF.

---
 arch/x86/net/bpf_jit_comp.c | 28 +++++++++++++++++++++-------
 1 file changed, 21 insertions(+), 7 deletions(-)
arch/x86/net/bpf_jit_comp.c +21 -7
index 8ff841e73512..f79ac77e5a39 100644
@@ -660,24 +660,38 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
 
 #define EMIT_LFENCE()	EMIT3(0x0F, 0xAE, 0xE8)
 
-static void emit_indirect_jump(u8 **pprog, int reg, u8 *ip)
+static void __emit_indirect_jump(u8 **pprog, int reg, bool ereg)
 {
 	u8 *prog = *pprog;
 
+	if (ereg)
+		EMIT1(0x41);
+
+	EMIT2(0xFF, 0xE0 + reg);
+
+	*pprog = prog;
+}
+
+static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip)
+{
+	u8 *prog = *pprog;
+	int reg = reg2hex[bpf_reg];
+	bool ereg = is_ereg(bpf_reg);
+
 	if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) {
 		OPTIMIZER_HIDE_VAR(reg);
 		emit_jump(&prog, its_static_thunk(reg), ip);
 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
 		EMIT_LFENCE();
-		EMIT2(0xFF, 0xE0 + reg);
+		__emit_indirect_jump(&prog, reg, ereg);
 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
 		OPTIMIZER_HIDE_VAR(reg);
 		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
-			emit_jump(&prog, &__x86_indirect_jump_thunk_array[reg], ip);
+			emit_jump(&prog, &__x86_indirect_jump_thunk_array[reg + 8*ereg], ip);
 		else
-			emit_jump(&prog, &__x86_indirect_thunk_array[reg], ip);
+			emit_jump(&prog, &__x86_indirect_thunk_array[reg + 8*ereg], ip);
 	} else {
-		EMIT2(0xFF, 0xE0 + reg);	/* jmp *%\reg */
+		__emit_indirect_jump(&prog, reg, ereg);
 		if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) || IS_ENABLED(CONFIG_MITIGATION_SLS))
 			EMIT1(0xCC);		/* int3 */
 	}
@@ -797,7 +811,7 @@ static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
 	 * rdi == ctx (1st arg)
 	 * rcx == prog->bpf_func + X86_TAIL_CALL_OFFSET
 	 */
-	emit_indirect_jump(&prog, 1 /* rcx */, ip + (prog - start));
+	emit_indirect_jump(&prog, BPF_REG_4 /* R4 -> rcx */, ip + (prog - start));
 
 	/* out: */
 	ctx->tail_call_indirect_label = prog - start;
@@ -3551,7 +3565,7 @@ static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image,
 		if (err)
 			return err;
 
-		emit_indirect_jump(&prog, 2 /* rdx */, image + (prog - buf));
+		emit_indirect_jump(&prog, BPF_REG_3 /* R3 -> rdx */, image + (prog - buf));
 
 		*pprog = prog;
 		return 0;
Signature · 1 line
2.34.1
maintainer Acked-by on v5 8/15
#21 lore raw

Re: [PATCH v5 bpf-next 08/15] bpf, x86: allow indirect jumps to r8...r15

Quoted 8 lines · Anton Protopopov

Currently the emit_indirect_jump() function only accepts one of the RAX, RCX, ..., RBP registers as the destination. Make it to accept R8, R9, ..., R15 as well, and make callers to pass BPF registers, not native registers. This is required to enable indirect jumps support in eBPF.

---

[...]

#22 lore raw

PATCH v5 9/15 bpf: make bpf_insn_successors to return a pointer

In reply to Anton Protopopov

The bpf_insn_successors() function is used to return successors to a BPF instruction. So far, an instruction could have 0, 1 or 2 successors. Prepare the verifier code to introduction of instructions with more than 2 successors (namely, indirect jumps).

To do this, introduce a new struct, struct bpf_iarray, containing an array of bpf instruction indexes and make bpf_insn_successors to return a pointer of that type. The storage for all instructions is allocated in the env->succ, which holds an array of size 2, to be used for all instructions.

---
 include/linux/bpf_verifier.h | 12 ++++++-
 kernel/bpf/liveness.c        | 36 ++++++++++++-------
 kernel/bpf/verifier.c        | 70 +++++++++++++++++++++++++-----------
 3 files changed, 85 insertions(+), 33 deletions(-)
include/linux/bpf_verifier.h +11 -1
index cc06e6d57faa..19d579f1f829 100644
@@ -509,6 +509,15 @@ struct bpf_map_ptr_state {
 #define BPF_ALU_SANITIZE		(BPF_ALU_SANITIZE_SRC | \
 					 BPF_ALU_SANITIZE_DST)
 
+/*
+ * An array of BPF instructions.
+ * Primary usage: return value of bpf_insn_successors.
+ */
+struct bpf_iarray {
+	int off_cnt;
+	u32 off[];
+};
+
 struct bpf_insn_aux_data {
 	union {
 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
@@ -830,6 +839,7 @@ struct bpf_verifier_env {
 	/* array of pointers to bpf_scc_info indexed by SCC id */
 	struct bpf_scc_info **scc_info;
 	u32 scc_cnt;
+	struct bpf_iarray *succ;
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1052,7 +1062,7 @@ void print_insn_state(struct bpf_verifier_env *env, const struct bpf_verifier_st
 
 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off);
 int bpf_jmp_offset(struct bpf_insn *insn);
-int bpf_insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2]);
+struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask);
 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx);
 
kernel/bpf/liveness.c +24 -12
index 3c611aba7f52..9312cd6b24d3 100644
@@ -34,7 +34,7 @@
  *   - read and write marks propagation.
  * - The propagation phase is a textbook live variable data flow analysis:
  *
- *     state[cc, i].live_after = U [state[cc, s].live_before for s in insn_successors(i)]
+ *     state[cc, i].live_after = U [state[cc, s].live_before for s in bpf_insn_successors(i)]
  *     state[cc, i].live_before =
  *       (state[cc, i].live_after / state[cc, i].must_write) U state[i].may_read
  *
@@ -54,7 +54,7 @@
  *   The equation for "must_write_acc" propagation looks as follows:
  *
  *     state[cc, i].must_write_acc =
- *       ∩ [state[cc, s].must_write_acc for s in insn_successors(i)]
+ *       ∩ [state[cc, s].must_write_acc for s in bpf_insn_successors(i)]
  *       U state[cc, i].must_write
  *
  *   (An intersection of all "must_write_acc" for instruction successors
@@ -445,7 +445,12 @@ int bpf_jmp_offset(struct bpf_insn *insn)
 __diag_push();
 __diag_ignore_all("-Woverride-init", "Allow field initialization overrides for opcode_info_tbl");
 
-inline int bpf_insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2])
+/*
+ * Returns an array of instructions succ, with succ->off[0], ...,
+ * succ->off[n-1] with successor instructions, where n=succ->off_cnt
+ */
+inline struct bpf_iarray *
+bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
 {
 	static const struct opcode_info {
 		bool can_jump;
@@ -472,19 +477,25 @@ inline int bpf_insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2])
 		_J(BPF_JSET,  {.can_jump = true,  .can_fallthrough = true}),
 	#undef _J
 	};
+	struct bpf_prog *prog = env->prog;
 	struct bpf_insn *insn = &prog->insnsi[idx];
 	const struct opcode_info *opcode_info;
-	int i = 0, insn_sz;
+	struct bpf_iarray *succ;
+	int insn_sz;
+
+	/* pre-allocated array of size up to 2; reset cnt, as it may have been used already */
+	succ = env->succ;
+	succ->off_cnt = 0;
 
 	opcode_info = &opcode_info_tbl[BPF_CLASS(insn->code) | BPF_OP(insn->code)];
 	insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
 	if (opcode_info->can_fallthrough)
-		succ[i++] = idx + insn_sz;
+		succ->off[succ->off_cnt++] = idx + insn_sz;
 
 	if (opcode_info->can_jump)
-		succ[i++] = idx + bpf_jmp_offset(insn) + 1;
+		succ->off[succ->off_cnt++] = idx + bpf_jmp_offset(insn) + 1;
 
-	return i;
+	return succ;
 }
 
 __diag_pop();
@@ -544,11 +555,12 @@ static inline bool update_insn(struct bpf_verifier_env *env,
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	u64 new_before, new_after, must_write_acc;
 	struct per_frame_masks *insn, *succ_insn;
-	u32 succ_num, s, succ[2];
+	struct bpf_iarray *succ;
+	u32 s;
 	bool changed;
 
-	succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
-	if (unlikely(succ_num == 0))
+	succ = bpf_insn_successors(env, insn_idx);
+	if (succ->off_cnt == 0)
 		return false;
 
 	changed = false;
@@ -560,8 +572,8 @@ static inline bool update_insn(struct bpf_verifier_env *env,
 	 * of successors plus all "must_write" slots of instruction itself.
 	 */
 	must_write_acc = U64_MAX;
-	for (s = 0; s < succ_num; ++s) {
-		succ_insn = get_frame_masks(instance, frame, succ[s]);
+	for (s = 0; s < succ->off_cnt; ++s) {
+		succ_insn = get_frame_masks(instance, frame, succ->off[s]);
 		new_after |= succ_insn->live_before;
 		must_write_acc &= succ_insn->must_write_acc;
 	}
kernel/bpf/verifier.c +50 -20

132 lines not on this page · raw message

Signature · 1 line
2.34.1
maintainer Acked-by on v5 9/15
#23 lore raw

Re: [PATCH v5 bpf-next 09/15] bpf: make bpf_insn_successors to return a pointer

Quoted 5 lines · Anton Protopopov

The bpf_insn_successors() function is used to return successors to a BPF instruction. So far, an instruction could have 0, 1 or 2 successors. Prepare the verifier code to introduction of instructions with more than 2 successors (namely, indirect jumps).

Quoted 8 lines

To do this, introduce a new struct, struct bpf_iarray, containing an array of bpf instruction indexes and make bpf_insn_successors to return a pointer of that type. The storage for all instructions is allocated in the env->succ, which holds an array of size 2, to be used for all instructions.

---

(but please fix the IS_ERR things, see below).

[...]

Quoted 5 lines
include/linux/bpf_verifier.h +0 -0
@@ -509,6 +509,15 @@ struct bpf_map_ptr_state {
 #define BPF_ALU_SANITIZE		(BPF_ALU_SANITIZE_SRC | \
 					 BPF_ALU_SANITIZE_DST)

include/linux/bpf_verifier.h struct bpf_map_ptr_state { · line 520

Quoted 10 lines
include/linux/bpf_verifier.h +9 -0
 
+/*
+ * An array of BPF instructions.
+ * Primary usage: return value of bpf_insn_successors.
+ */
+struct bpf_iarray {
+	int off_cnt;
+	u32 off[];
+};
+

Tbh, the names off and off_cnt are a bit strange in context of instruction successors.

[...]

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

Quoted 11 lines
kernel/bpf/verifier.c +3 -0
index 705535711d10..6c742d2f4c04 100644
@@ -17770,6 +17770,22 @@ static int mark_fastcall_patterns(struct bpf_verifier_env *env)
 	return 0;
 }
 
+static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
+{
+	size_t new_size = sizeof(struct bpf_iarray) + n_elem * 4;

Nit: n_elem * 4 -> n_elem * sizeof(*old->off) ?

Quoted 12 lines
kernel/bpf/verifier.c +12 -0
+	struct bpf_iarray *new;
+
+	new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
+	if (!new) {
+		/* this is what callers always want, so simplify the call site */
+		kvfree(old);
+		return NULL;
+	}
+
+	new->off_cnt = n_elem;
+	return new;
+}

[...]

Quoted 5 lines
kernel/bpf/verifier.c +0 -1
@@ -24325,14 +24342,18 @@ static int compute_live_registers(struct bpf_verifier_env *env)
 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
 			int insn_idx = env->cfg.insn_postorder[i];
 			struct insn_live_regs *live = &state[insn_idx];
-			int succ_num;

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

Quoted 10 lines
kernel/bpf/verifier.c +3 -4
-			u32 succ[2];
+			struct bpf_iarray *succ;
 			u16 new_out = 0;
 			u16 new_in = 0;
 
-			succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
-			for (int s = 0; s < succ_num; ++s)
-				new_out |= state[succ[s]].in;
+			succ = bpf_insn_successors(env, insn_idx);
+			if (IS_ERR(succ)) {

This error check is no longer necessary.

Quoted 9 lines
kernel/bpf/verifier.c +6 -0
+				err = PTR_ERR(succ);
+				goto out;
+
+			}
+			for (int s = 0; s < succ->off_cnt; ++s)
+				new_out |= state[succ->off[s]].in;
 			new_in = (new_out & ~live->def) | live->use;
 			if (new_out != live->out || new_in != live->in) {
 				live->in = new_in;

[...]

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

Quoted 10 lines
kernel/bpf/verifier.c +2 -4
@@ -24496,12 +24517,17 @@ static int compute_scc(struct bpf_verifier_env *env)
 				stack[stack_sz++] = w;
 			}
 			/* Visit 'w' successors */
-			succ_cnt = bpf_insn_successors(env->prog, w, succ);
-			for (j = 0; j < succ_cnt; ++j) {
-				if (pre[succ[j]]) {
-					low[w] = min(low[w], low[succ[j]]);
+			succ = bpf_insn_successors(env, w);
+			if (IS_ERR(succ)) {

Same here.

Quoted 13 lines
kernel/bpf/verifier.c +8 -1
+				err = PTR_ERR(succ);
+				goto exit;
+
+			}
+			for (j = 0; j < succ->off_cnt; ++j) {
+				if (pre[succ->off[j]]) {
+					low[w] = min(low[w], low[succ->off[j]]);
 				} else {
-					dfs[dfs_sz++] = succ[j];
+					dfs[dfs_sz++] = succ->off[j];
 					goto dfs_continue;
 				}
 			}

[...]

#24 lore raw

Re: [PATCH v5 bpf-next 09/15] bpf: make bpf_insn_successors to return a pointer

Quoted 82 lines · Eduard Zingerman
Quoted 5 lines · Anton Protopopov

The bpf_insn_successors() function is used to return successors to a BPF instruction. So far, an instruction could have 0, 1 or 2 successors. Prepare the verifier code to introduction of instructions with more than 2 successors (namely, indirect jumps).

Quoted 8 lines

To do this, introduce a new struct, struct bpf_iarray, containing an array of bpf instruction indexes and make bpf_insn_successors to return a pointer of that type. The storage for all instructions is allocated in the env->succ, which holds an array of size 2, to be used for all instructions.

---

(but please fix the IS_ERR things, see below).

[...]

Quoted 5 lines
include/linux/bpf_verifier.h +0 -0
@@ -509,6 +509,15 @@ struct bpf_map_ptr_state {
 #define BPF_ALU_SANITIZE             (BPF_ALU_SANITIZE_SRC | \
                                       BPF_ALU_SANITIZE_DST)

include/linux/bpf_verifier.h struct bpf_map_ptr_state { · line 520

Quoted 10 lines
include/linux/bpf_verifier.h +9 -0
 
+/*
+ * An array of BPF instructions.
+ * Primary usage: return value of bpf_insn_successors.
+ */
+struct bpf_iarray {
+     int off_cnt;
+     u32 off[];
+};
+

Tbh, the names off and off_cnt are a bit strange in context of instruction successors.

[...]

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

Quoted 11 lines
kernel/bpf/verifier.c +3 -0
index 705535711d10..6c742d2f4c04 100644
@@ -17770,6 +17770,22 @@ static int mark_fastcall_patterns(struct bpf_verifier_env *env)
      return 0;
 }
 
+static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
+{
+     size_t new_size = sizeof(struct bpf_iarray) + n_elem * 4;

Nit: n_elem * 4 -> n_elem * sizeof(*old->off) ?

Quoted 12 lines
kernel/bpf/verifier.c +12 -0
+     struct bpf_iarray *new;
+
+     new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
+     if (!new) {
+             /* this is what callers always want, so simplify the call site */
+             kvfree(old);
+             return NULL;
+     }
+
+     new->off_cnt = n_elem;
+     return new;
+}

[...]

Quoted 10 lines
kernel/bpf/verifier.c +1 -2
@@ -24325,14 +24342,18 @@ static int compute_live_registers(struct bpf_verifier_env *env)
              for (i = 0; i < env->cfg.cur_postorder; ++i) {
                      int insn_idx = env->cfg.insn_postorder[i];
                      struct insn_live_regs *live = &state[insn_idx];
-                     int succ_num;
-                     u32 succ[2];
+                     struct bpf_iarray *succ;
                      u16 new_out = 0;
                      u16 new_in = 0;
 
Quoted 7 lines

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

Quoted 5 lines
kernel/bpf/verifier.c +2 -3
-                     succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
-                     for (int s = 0; s < succ_num; ++s)
-                             new_out |= state[succ[s]].in;
+                     succ = bpf_insn_successors(env, insn_idx);
+                     if (IS_ERR(succ)) {

This error check is no longer necessary.

Speaking of IS_ERR checks...
https://github.com/kernel-patches/bpf/pull/9895#issuecomment-3352016682

AI for-the-win!

#25 lore raw

Re: [PATCH v5 bpf-next 09/15] bpf: make bpf_insn_successors to return a pointer

Quoted 91 lines · Alexei Starovoitov
Quoted 82 lines · Eduard Zingerman
Quoted 5 lines · Anton Protopopov

The bpf_insn_successors() function is used to return successors to a BPF instruction. So far, an instruction could have 0, 1 or 2 successors. Prepare the verifier code to introduction of instructions with more than 2 successors (namely, indirect jumps).

Quoted 8 lines

To do this, introduce a new struct, struct bpf_iarray, containing an array of bpf instruction indexes and make bpf_insn_successors to return a pointer of that type. The storage for all instructions is allocated in the env->succ, which holds an array of size 2, to be used for all instructions.

---

(but please fix the IS_ERR things, see below).

[...]

Quoted 5 lines
include/linux/bpf_verifier.h +0 -0
@@ -509,6 +509,15 @@ struct bpf_map_ptr_state {
 #define BPF_ALU_SANITIZE             (BPF_ALU_SANITIZE_SRC | \
                                       BPF_ALU_SANITIZE_DST)

include/linux/bpf_verifier.h struct bpf_map_ptr_state { · line 520

Quoted 10 lines
include/linux/bpf_verifier.h +9 -0
 
+/*
+ * An array of BPF instructions.
+ * Primary usage: return value of bpf_insn_successors.
+ */
+struct bpf_iarray {
+     int off_cnt;
+     u32 off[];
+};
+

Tbh, the names off and off_cnt are a bit strange in context of instruction successors.

[...]

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

Quoted 11 lines
kernel/bpf/verifier.c +3 -0
index 705535711d10..6c742d2f4c04 100644
@@ -17770,6 +17770,22 @@ static int mark_fastcall_patterns(struct bpf_verifier_env *env)
      return 0;
 }
 
+static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
+{
+     size_t new_size = sizeof(struct bpf_iarray) + n_elem * 4;

Nit: n_elem * 4 -> n_elem * sizeof(*old->off) ?

Quoted 12 lines
kernel/bpf/verifier.c +12 -0
+     struct bpf_iarray *new;
+
+     new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
+     if (!new) {
+             /* this is what callers always want, so simplify the call site */
+             kvfree(old);
+             return NULL;
+     }
+
+     new->off_cnt = n_elem;
+     return new;
+}

[...]

Quoted 10 lines
kernel/bpf/verifier.c +1 -2
@@ -24325,14 +24342,18 @@ static int compute_live_registers(struct bpf_verifier_env *env)
              for (i = 0; i < env->cfg.cur_postorder; ++i) {
                      int insn_idx = env->cfg.insn_postorder[i];
                      struct insn_live_regs *live = &state[insn_idx];
-                     int succ_num;
-                     u32 succ[2];
+                     struct bpf_iarray *succ;
                      u16 new_out = 0;
                      u16 new_in = 0;
 
Quoted 7 lines

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

Quoted 5 lines
kernel/bpf/verifier.c +2 -3
-                     succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
-                     for (int s = 0; s < succ_num; ++s)
-                             new_out |= state[succ[s]].in;
+                     succ = bpf_insn_successors(env, insn_idx);
+                     if (IS_ERR(succ)) {

This error check is no longer necessary.

Quoted 4 lines

Speaking of IS_ERR checks...
https://github.com/kernel-patches/bpf/pull/9895#issuecomment-3352016682

AI for-the-win!

Nice! Won't be surprised if it was trained just based on Eduard's reviews :)

(Actually, are there any details anywhere about this AI?)

#26 lore raw

Re: [PATCH v5 bpf-next 09/15] bpf: make bpf_insn_successors to return a pointer

Quoted 10 lines · Anton Protopopov
Quoted 6 lines

Speaking of IS_ERR checks...
https://github.com/kernel-patches/bpf/pull/9895#issuecomment-3352016682

AI for-the-win!

Nice! Won't be surprised if it was trained just based on Eduard's reviews :)

(Actually, are there any details anywhere about this AI?)

you mean where to find it?
It runs for every patch. If 'Logs for ai-review' is red, click on it, or better click on 'PR summary' and scroll down.
The actual mechanism is still being fleshed out,
but the false positive rate is quite low.
Eventually it will start sending emails with reviews.

#27 lore raw

Re: [PATCH v5 bpf-next 09/15] bpf: make bpf_insn_successors to return a pointer

In reply to Eduard Zingerman
Quoted 27 lines · Eduard Zingerman
Quoted 5 lines · Anton Protopopov

The bpf_insn_successors() function is used to return successors to a BPF instruction. So far, an instruction could have 0, 1 or 2 successors. Prepare the verifier code to introduction of instructions with more than 2 successors (namely, indirect jumps).

Quoted 8 lines

To do this, introduce a new struct, struct bpf_iarray, containing an array of bpf instruction indexes and make bpf_insn_successors to return a pointer of that type. The storage for all instructions is allocated in the env->succ, which holds an array of size 2, to be used for all instructions.

---

(but please fix the IS_ERR things, see below).

[...]

Quoted 6 lines
include/linux/bpf_verifier.h +0 -0
@@ -509,6 +509,15 @@ struct bpf_map_ptr_state {
 #define BPF_ALU_SANITIZE		(BPF_ALU_SANITIZE_SRC | \
 					 BPF_ALU_SANITIZE_DST)
 
Quoted 12 lines

include/linux/bpf_verifier.h struct bpf_map_ptr_state { · line 520

Quoted 9 lines
include/linux/bpf_verifier.h +9 -0
+/*
+ * An array of BPF instructions.
+ * Primary usage: return value of bpf_insn_successors.
+ */
+struct bpf_iarray {
+	int off_cnt;
+	u32 off[];
+};
+

Tbh, the names off and off_cnt are a bit strange in context of instruction successors.

insn_offsets / insn_offset_cnt?

Quoted 10 lines

[...]

Quoted 8 lines
kernel/bpf/verifier.c +0 -0
index 705535711d10..6c742d2f4c04 100644
@@ -17770,6 +17770,22 @@ static int mark_fastcall_patterns(struct bpf_verifier_env *env)
 	return 0;
 }
 
Quoted 5 lines

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

Quoted 3 lines
kernel/bpf/verifier.c +3 -0
+static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
+{
+	size_t new_size = sizeof(struct bpf_iarray) + n_elem * 4;

Nit: n_elem * 4 -> n_elem * sizeof(*old->off) ?

Yes, thanks.

Quoted 25 lines
Quoted 12 lines
kernel/bpf/verifier.c +12 -0
+	struct bpf_iarray *new;
+
+	new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
+	if (!new) {
+		/* this is what callers always want, so simplify the call site */
+		kvfree(old);
+		return NULL;
+	}
+
+	new->off_cnt = n_elem;
+	return new;
+}

[...]

Quoted 10 lines
kernel/bpf/verifier.c +1 -2
@@ -24325,14 +24342,18 @@ static int compute_live_registers(struct bpf_verifier_env *env)
 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
 			int insn_idx = env->cfg.insn_postorder[i];
 			struct insn_live_regs *live = &state[insn_idx];
-			int succ_num;
-			u32 succ[2];
+			struct bpf_iarray *succ;
 			u16 new_out = 0;
 			u16 new_in = 0;
 
Quoted 7 lines

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

Quoted 5 lines
kernel/bpf/verifier.c +2 -3
-			succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
-			for (int s = 0; s < succ_num; ++s)
-				new_out |= state[succ[s]].in;
+			succ = bpf_insn_successors(env, insn_idx);
+			if (IS_ERR(succ)) {

This error check is no longer necessary.

Yes, thanks. I've removed these checks, but these chunks escaped to the "indirect jumps" patch. Moved them back.

Quoted 1 line

[...]

maintainer
#28 lore raw

Re: [PATCH v5 bpf-next 09/15] bpf: make bpf_insn_successors to return a pointer

On Thu, 2025-10-02 at 08:16 +0000, Anton Protopopov wrote:

[...]

Quoted 13 lines
Quoted 4 lines
Quoted 4 lines

+/*
+ * An array of BPF instructions.
+ * Primary usage: return value of bpf_insn_successors.
+ */

Quoted 8 lines

include/linux/bpf_verifier.h struct bpf_map_ptr_state { · line 520

Quoted 5 lines
include/linux/bpf_verifier.h +5 -0
+struct bpf_iarray {
+	int off_cnt;
+	u32 off[];
+};
+

Tbh, the names off and off_cnt are a bit strange in context of instruction successors.

Quoted 1 line

insn_offsets / insn_offset_cnt?

Idk, this is a generic u32 array wrapper, so I'd name these items/cnt. If you don't like that, lets stick with off/off_cnt, as these are short.

[...]

#29 lore raw

PATCH v5 10/15 bpf, x86: add support for indirect jumps

In reply to Anton Protopopov

Add support for a new instruction

    BPF_JMP|BPF_X|BPF_JA, SRC=0, DST=Rx, off=0, imm=0

which does an indirect jump to a location stored in Rx. The register Rx should have type PTR_TO_INSN. This new type assures that the Rx register contains a value (or a range of values) loaded from a correct jump table – map of type instruction array.

For example, for a C switch LLVM will generate the following code:

    0:   r3 = r1                    # "switch (r3)"
    1:   if r3 > 0x13 goto +0x666   # check r3 boundaries
    2:   r3 <<= 0x3                 # adjust to an index in array of addresses
    3:   r1 = 0xbeef ll             # r1 is PTR_TO_MAP_VALUE, r1->map_ptr=M
    5:   r1 += r3                   # r1 inherits boundaries from r3
    6:   r1 = *(u64 *)(r1 + 0x0)    # r1 now has type INSN_TO_PTR
    7:   gotox r1                   # jit will generate proper code

Here the gotox instruction corresponds to one particular map. This is possible however to have a gotox instruction which can be loaded from different maps, e.g.

    0:   r1 &= 0x1
    1:   r2 <<= 0x3
    2:   r3 = 0x0 ll                # load from map M_1
    4:   r3 += r2
    5:   if r1 == 0x0 goto +0x4
    6:   r1 <<= 0x3
    7:   r3 = 0x0 ll                # load from map M_2
    9:   r3 += r1
    A:   r1 = *(u64 *)(r3 + 0x0)
    B:   gotox r1                   # jump to target loaded from M_1 or M_2

During check_cfg stage the verifier will collect all the maps which point to inside the subprog being verified. When building the config, the high 16 bytes of the insn_state are used, so this patch (theoretically) supports jump tables of up to 2^16 slots.

During the later stage, in check_indirect_jump, it is checked that the register Rx was loaded from a particular instruction array.

---
 arch/x86/net/bpf_jit_comp.c  |   3 +
 include/linux/bpf.h          |   1 +
 include/linux/bpf_verifier.h |  13 ++
 kernel/bpf/bpf_insn_array.c  |  15 ++
 kernel/bpf/core.c            |   1 +
 kernel/bpf/liveness.c        |   3 +
 kernel/bpf/log.c             |   1 +
 kernel/bpf/verifier.c        | 413 +++++++++++++++++++++++++++++++++--
 8 files changed, 431 insertions(+), 19 deletions(-)
arch/x86/net/bpf_jit_comp.c +3 -0
index f79ac77e5a39..53feed4889f1 100644
@@ -2629,6 +2629,9 @@ st:			if (is_imm8(insn->off))
 
 			break;
 
+		case BPF_JMP | BPF_JA | BPF_X:
+			emit_indirect_jump(&prog, insn->dst_reg, image + addrs[i - 1]);
+			break;
 		case BPF_JMP | BPF_JA:
 		case BPF_JMP32 | BPF_JA:
 			if (BPF_CLASS(insn->code) == BPF_JMP) {
include/linux/bpf.h +1 -0
index f878d94593e3..132f1cb3b0a4 100644
@@ -988,6 +988,7 @@ enum bpf_reg_type {
 	PTR_TO_ARENA,
 	PTR_TO_BUF,		 /* reg points to a read/write buffer */
 	PTR_TO_FUNC,		 /* reg points to a bpf program function */
+	PTR_TO_INSN,		 /* reg points to a bpf program instruction */
 	CONST_PTR_TO_DYNPTR,	 /* reg points to a const struct bpf_dynptr */
 	__BPF_REG_TYPE_MAX,
 
include/linux/bpf_verifier.h +13 -0
index 19d579f1f829..52e8dc652260 100644
@@ -527,6 +527,7 @@ struct bpf_insn_aux_data {
 		struct {
 			u32 map_index;		/* index into used_maps[] */
 			u32 map_off;		/* offset from value base address */
+			struct bpf_iarray *jt;	/* jump table for gotox instruction */
 		};
 		struct {
 			enum bpf_reg_type reg_type;	/* type of pseudo_btf_id */
@@ -571,6 +572,9 @@ struct bpf_insn_aux_data {
 	u8 fastcall_spills_num:3;
 	u8 arg_prog:4;
 
+	/* true if jt->off was allocated */
+	bool jt_allocated;
+
 	/* below fields are initialized once */
 	unsigned int orig_idx; /* original instruction index */
 	bool jmp_point;
@@ -840,6 +844,8 @@ struct bpf_verifier_env {
 	struct bpf_scc_info **scc_info;
 	u32 scc_cnt;
 	struct bpf_iarray *succ;
+	u32 *gotox_tmp_buf;
+	size_t gotox_tmp_buf_size;
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1050,6 +1056,13 @@ static inline bool bpf_stack_narrow_access_ok(int off, int fill_size, int spill_
 	return !(off % BPF_REG_SIZE);
 }
 
+static inline bool insn_is_gotox(struct bpf_insn *insn)
+{
+	return BPF_CLASS(insn->code) == BPF_JMP &&
+	       BPF_OP(insn->code) == BPF_JA &&
+	       BPF_SRC(insn->code) == BPF_X;
+}
+
 const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type);
 const char *dynptr_type_str(enum bpf_dynptr_type type);
 const char *iter_type_str(const struct btf *btf, u32 btf_id);
kernel/bpf/bpf_insn_array.c +15 -0
index ac0243b78169..e771bc433351 100644
@@ -126,6 +126,20 @@ static u64 insn_array_mem_usage(const struct bpf_map *map)
 	return insn_array_alloc_size(map->max_entries) + extra_size;
 }
 
+static int insn_array_map_direct_value_addr(const struct bpf_map *map, u64 *imm, u32 off)
+{
+	struct bpf_insn_array *insn_array = cast_insn_array(map);
+
+	if ((off % sizeof(long)) != 0 ||
+	    (off / sizeof(long)) >= map->max_entries)
+		return -EINVAL;
+
+	/* from BPF's point of view, this map is a jump table */
+	*imm = (unsigned long)insn_array->ips + off;
+
+	return 0;
+}
+
 BTF_ID_LIST_SINGLE(insn_array_btf_ids, struct, bpf_insn_array)
 
 const struct bpf_map_ops insn_array_map_ops = {
@@ -138,6 +152,7 @@ const struct bpf_map_ops insn_array_map_ops = {
 	.map_delete_elem = insn_array_delete_elem,
 	.map_check_btf = insn_array_check_btf,
 	.map_mem_usage = insn_array_mem_usage,
+	.map_direct_value_addr = insn_array_map_direct_value_addr,
 	.map_btf_id = &insn_array_btf_ids[0],
 };
 
kernel/bpf/core.c +1 -0
index 4b62a03d6df5..ef4448f18aad 100644
@@ -1708,6 +1708,7 @@ bool bpf_opcode_in_insntable(u8 code)
 		[BPF_LD | BPF_IND | BPF_B] = true,
 		[BPF_LD | BPF_IND | BPF_H] = true,
 		[BPF_LD | BPF_IND | BPF_W] = true,
+		[BPF_JMP | BPF_JA | BPF_X] = true,
 		[BPF_JMP | BPF_JCOND] = true,
 	};
 #undef BPF_INSN_3_TBL
kernel/bpf/liveness.c +3 -0
index 9312cd6b24d3..b8edc5b45290 100644
@@ -483,6 +483,9 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
 	struct bpf_iarray *succ;
 	int insn_sz;
 
+	if (unlikely(insn_is_gotox(insn)))
+		return env->insn_aux_data[idx].jt;
+
 	/* pre-allocated array of size up to 2; reset cnt, as it may have been used already */
 	succ = env->succ;
 	succ->off_cnt = 0;
kernel/bpf/log.c +1 -0
index f50533169cc3..3fb56617af36 100644
@@ -461,6 +461,7 @@ const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type)
 		[PTR_TO_ARENA]		= "arena",
 		[PTR_TO_BUF]		= "buf",
 		[PTR_TO_FUNC]		= "func",
+		[PTR_TO_INSN]		= "insn",
 		[PTR_TO_MAP_KEY]	= "map_key",
 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
 	};
kernel/bpf/verifier.c +394 -19

553 lines not on this page · raw message

Signature · 1 line
2.34.1
maintainer
#30 lore raw

Re: [PATCH v5 bpf-next 10/15] bpf, x86: add support for indirect jumps

Quoted 44 lines · Anton Protopopov

Add support for a new instruction

    BPF_JMP|BPF_X|BPF_JA, SRC=0, DST=Rx, off=0, imm=0

which does an indirect jump to a location stored in Rx. The register Rx should have type PTR_TO_INSN. This new type assures that the Rx register contains a value (or a range of values) loaded from a correct jump table – map of type instruction array.

For example, for a C switch LLVM will generate the following code:

    0:   r3 = r1                    # "switch (r3)"
    1:   if r3 > 0x13 goto +0x666   # check r3 boundaries
    2:   r3 <<= 0x3                 # adjust to an index in array of addresses
    3:   r1 = 0xbeef ll             # r1 is PTR_TO_MAP_VALUE, r1->map_ptr=M
    5:   r1 += r3                   # r1 inherits boundaries from r3
    6:   r1 = *(u64 *)(r1 + 0x0)    # r1 now has type INSN_TO_PTR
    7:   gotox r1                   # jit will generate proper code

Here the gotox instruction corresponds to one particular map. This is possible however to have a gotox instruction which can be loaded from different maps, e.g.

    0:   r1 &= 0x1
    1:   r2 <<= 0x3
    2:   r3 = 0x0 ll                # load from map M_1
    4:   r3 += r2
    5:   if r1 == 0x0 goto +0x4
    6:   r1 <<= 0x3
    7:   r3 = 0x0 ll                # load from map M_2
    9:   r3 += r1
    A:   r1 = *(u64 *)(r3 + 0x0)
    B:   gotox r1                   # jump to target loaded from M_1 or M_2

During check_cfg stage the verifier will collect all the maps which point to inside the subprog being verified. When building the config, the high 16 bytes of the insn_state are used, so this patch (theoretically) supports jump tables of up to 2^16 slots.

During the later stage, in check_indirect_jump, it is checked that the register Rx was loaded from a particular instruction array.

---

[...]

include/linux/bpf_verifier.h struct bpf_insn_aux_data { · line 577

Quoted 7 lines
include/linux/bpf_verifier.h +3 -0
@@ -571,6 +572,9 @@ struct bpf_insn_aux_data {
 	u8 fastcall_spills_num:3;
 	u8 arg_prog:4;
 
+	/* true if jt->off was allocated */
+	bool jt_allocated;
+

This is a leftover from v3, no longer used.

Quoted 10 lines
include/linux/bpf_verifier.h +2 -0
 	/* below fields are initialized once */
 	unsigned int orig_idx; /* original instruction index */
 	bool jmp_point;
@@ -840,6 +844,8 @@ struct bpf_verifier_env {
 	struct bpf_scc_info **scc_info;
 	u32 scc_cnt;
 	struct bpf_iarray *succ;
+	u32 *gotox_tmp_buf;
+	size_t gotox_tmp_buf_size;
 };

[...]

kernel/bpf/verifier.c static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, · line 14730

Quoted 9 lines
kernel/bpf/verifier.c +5 -0
@@ -14685,6 +14723,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
 				dst);
 			return -EACCES;
 		}
+		if (ptr_to_insn_array) {
+			verbose(env, "R%d subtraction from pointer to instruction prohibited\n",
+				dst);
+			return -EACCES;
+		}

Is anything going to break if subtraction is allowed? The bounds are still maintained, so seem to be ok.

Quoted 3 lines
kernel/bpf/verifier.c +0 -0
 		if (known && (ptr_reg->off - smin_val ==
 			      (s64)(s32)(ptr_reg->off - smin_val))) {
 			/* pointer -= K.  Subtract it from fixed offset */

[...]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -17786,6 +17830,210 @@ static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
 	return new;
 }
 

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 17842

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+#define SET_HIGH(STATE, LAST)	STATE = (STATE & 0xffffU) | ((LAST) << 16)
+#define GET_HIGH(STATE)		((u16)((STATE) >> 16))
+
+static int push_gotox_edge(int t, struct bpf_verifier_env *env, struct bpf_iarray *jt)
+{
+	int *insn_stack = env->cfg.insn_stack;
+	int *insn_state = env->cfg.insn_state;
+	u16 prev;
+	int w;
+

push_insn() checks if t is in range [0, env->prog->len], is the same check needed here?

Quoted 7 lines
kernel/bpf/verifier.c +7 -0
+	for (prev = GET_HIGH(insn_state[t]); prev < jt->off_cnt; prev++) {
+		w = jt->off[prev];
+		mark_jmp_point(env, w);
+
+		/* EXPLORED || DISCOVERED */
+		if (insn_state[w])
+			continue;

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 17859

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+
+		break;
+	}
+
+	if (prev == jt->off_cnt)
+		return DONE_EXPLORING;
+
+	if (env->cfg.cur_stack >= env->prog->len)
+		return -E2BIG;
+	insn_stack[env->cfg.cur_stack++] = w;

I think insn_state[w] |= DISCOVERED; is missing here.

Quoted 4 lines
kernel/bpf/verifier.c +4 -0
+
+	SET_HIGH(insn_state[t], prev + 1);
+	return KEEP_EXPLORING;
+}

[...]

Quoted 6 lines
kernel/bpf/verifier.c +6 -0
+static struct bpf_iarray *
+create_jt(int t, struct bpf_verifier_env *env, int fd)
+{
+	static struct bpf_subprog_info *subprog;
+	int subprog_idx, subprog_start, subprog_end;
+	struct bpf_iarray *jt;

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 18000

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	int i;
+
+	if (env->subprog_cnt == 0)
+		return ERR_PTR(-EFAULT);
+
+	subprog_idx = bpf_find_containing_subprog_idx(env, t);
+	if (subprog_idx < 0) {
+		verbose(env, "can't find subprog containing instruction %d\n", t);
+		return ERR_PTR(-EFAULT);
+	}

Nit: There is now verifier_bug() for such cases.
Also, it seems that all bpf_find_containing_subprog() users assume that the function can't fail.
Like in this case, there is already access jt = env->insn_aux_data[t].jt; in visit_gotox_insn() that will be an error if t is bogus.

Quoted 21 lines
kernel/bpf/verifier.c +21 -0
+	subprog = &env->subprog_info[subprog_idx];
+	subprog_start = subprog->start;
+	subprog_end = (subprog + 1)->start;
+	jt = jt_from_subprog(env, subprog_start, subprog_end);
+	if (IS_ERR(jt))
+		return jt;
+
+	/* Check that the every element of the jump table fits within the given subprogram */
+	for (i = 0; i < jt->off_cnt; i++) {
+		if (jt->off[i] < subprog_start || jt->off[i] >= subprog_end) {
+			verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]",
+					t, subprog_start, subprog_end);
+			return ERR_PTR(-EINVAL);
+		}
+	}
+
+	return jt;
+}
+
+/* "conditional jump with N edges" */
+static int visit_gotox_insn(int t, struct bpf_verifier_env *env, int fd)

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 18031

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+{
+	struct bpf_iarray *jt;
+
+	jt = env->insn_aux_data[t].jt;
+	if (!jt) {
+		jt = create_jt(t, env, fd);
+		if (IS_ERR(jt))
+			return PTR_ERR(jt);
+	}
+	env->insn_aux_data[t].jt = jt;

Nit: move this assignment up into the if (!jt) body?

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 18036

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+
+	mark_prune_point(env, t);
+	return push_gotox_edge(t, env, jt);
+}
+

I think the following implementation should achieve the same result:

  /* "conditional jump with N edges" */
  static int visit_gotox_insn(int t, struct bpf_verifier_env *env, int fd)
  {
        int *insn_stack = env->cfg.insn_stack;
        int *insn_state = env->cfg.insn_state;
        bool keep_exploring = false;
        struct bpf_iarray *jt;
        int i, w;
        jt = env->insn_aux_data[t].jt;
        if (!jt) {
                jt = create_jt(t, env, fd);
                if (IS_ERR(ptr: jt))
                        return PTR_ERR(ptr: jt);

                env->insn_aux_data[t].jt = jt;
        }

        mark_prune_point(env, idx: t);
        for (i = 0; i < jt->off_cnt; i++) {
                w = jt->off[i];
                mark_jmp_point(env, idx: w);

                /* EXPLORED || DISCOVERED */
                if (insn_state[w])
                        continue;

                if (env->cfg.cur_stack >= env->prog->len)
                        return -E2BIG;

                insn_stack[env->cfg.cur_stack++] = w;
                insn_state[w] |= DISCOVERED;
                keep_exploring = true;
        }

        return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;

}

But w/o GET_HIGH/SET_HIGH things. Wdyt?

[...]

Quoted 20 lines
kernel/bpf/verifier.c +16 -0
@@ -19817,6 +20068,103 @@ static int process_bpf_exit_full(struct bpf_verifier_env *env,
 	return PROCESS_BPF_EXIT;
 }
 
+static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
+				       int regno,
+				       struct bpf_map *map,
+				       u32 *pmin_index, u32 *pmax_index)
+{
+	struct bpf_reg_state *reg = reg_state(env, regno);
+	u64 min_index, max_index;
+	const u32 size = 8;
+
+	if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
+		(min_index > (u64) U32_MAX * size)) {
+		verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
+			     regno, reg->umin_value, reg->off);
+		return -ERANGE;
+	}
+	if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20096

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+		(max_index > (u64) U32_MAX * size)) {
+		verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
+			     regno, reg->umax_value, reg->off);
+		return -ERANGE;
+	}
+
+	min_index /= size;
+	max_index /= size;
+
+	if (min_index >= map->max_entries || max_index >= map->max_entries) {

Nit: it is guaranteed that reg->umin_value <= reg->umax_value,
so checking max_index should be sufficient.

Quoted 27 lines
kernel/bpf/verifier.c +27 -0
+		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
+			     regno, min_index, max_index, map->max_entries);
+		return -EINVAL;
+	}
+
+	*pmin_index = min_index;
+	*pmax_index = max_index;
+	return 0;
+}
+
+/* gotox *dst_reg */
+static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
+{
+	struct bpf_verifier_state *other_branch;
+	struct bpf_reg_state *dst_reg;
+	struct bpf_map *map;
+	u32 min_index, max_index;
+	size_t new_size;
+	u32 *new_buf;
+	int err = 0;
+	int n;
+	int i;
+
+	dst_reg = reg_state(env, insn->dst_reg);
+	if (dst_reg->type != PTR_TO_INSN) {
+		verbose(env, "R%d has type %d, expected PTR_TO_INSN\n",
+			     insn->dst_reg, dst_reg->type);

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20133

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+		return -EINVAL;
+	}
+
+	map = dst_reg->map_ptr;
+	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
+		return -EFAULT;
+
+	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
+			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
+		return -EFAULT;

Are you sure this is a verifier bug?
The program can be written in a way, such that e.g. hash map pointer is passed as a parameter for gotox, that would be an incorrect program, not a verifier bug.

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20146

Quoted 13 lines
kernel/bpf/verifier.c +13 -0
+
+	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
+	if (err)
+		return err;
+
+	/* Ensure that the buffer is large enough */
+	new_size = sizeof(u32) * (max_index - min_index + 1);
+	if (env->gotox_tmp_buf_size < new_size) {
+		new_buf = kvrealloc(env->gotox_tmp_buf, new_size, GFP_KERNEL_ACCOUNT);
+		if (!new_buf)
+			return -ENOMEM;
+		env->gotox_tmp_buf = new_buf;
+		env->gotox_tmp_buf_size = new_size;

Can gotox_tmp_buf be an bpf_iarray instance?
If it can, iarray_realloc() can be reused here.

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20149

Quoted 3 lines
kernel/bpf/verifier.c +3 -0
+	}
+
+	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf);

I still think this might be a problem for big jump tables if gotox is in a loop body. Can you check a perf report for such scenario? E.g. 256 entries in the jump table, some duplicates, dispatched in a loop.

Quoted 21 lines
kernel/bpf/verifier.c +18 -0
+	if (n < 0)
+		return n;
+	if (n == 0) {
+		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
+			     insn->dst_reg, map->id);
+		return -EINVAL;
+	}
+
+	for (i = 0; i < n - 1; i++) {
+		other_branch = push_stack(env, env->gotox_tmp_buf[i],
+					  env->insn_idx, env->cur_state->speculative);
+		if (IS_ERR(other_branch))
+			return PTR_ERR(other_branch);
+	}
+	env->insn_idx = env->gotox_tmp_buf[n-1];
+	return 0;
+}
+
 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 {
 	int err;

[...]

#31 lore raw

Re: [PATCH v5 bpf-next 10/15] bpf, x86: add support for indirect jumps

Quoted 53 lines · Eduard Zingerman
Quoted 44 lines · Anton Protopopov

Add support for a new instruction

    BPF_JMP|BPF_X|BPF_JA, SRC=0, DST=Rx, off=0, imm=0

which does an indirect jump to a location stored in Rx. The register Rx should have type PTR_TO_INSN. This new type assures that the Rx register contains a value (or a range of values) loaded from a correct jump table – map of type instruction array.

For example, for a C switch LLVM will generate the following code:

    0:   r3 = r1                    # "switch (r3)"
    1:   if r3 > 0x13 goto +0x666   # check r3 boundaries
    2:   r3 <<= 0x3                 # adjust to an index in array of addresses
    3:   r1 = 0xbeef ll             # r1 is PTR_TO_MAP_VALUE, r1->map_ptr=M
    5:   r1 += r3                   # r1 inherits boundaries from r3
    6:   r1 = *(u64 *)(r1 + 0x0)    # r1 now has type INSN_TO_PTR
    7:   gotox r1                   # jit will generate proper code

Here the gotox instruction corresponds to one particular map. This is possible however to have a gotox instruction which can be loaded from different maps, e.g.

    0:   r1 &= 0x1
    1:   r2 <<= 0x3
    2:   r3 = 0x0 ll                # load from map M_1
    4:   r3 += r2
    5:   if r1 == 0x0 goto +0x4
    6:   r1 <<= 0x3
    7:   r3 = 0x0 ll                # load from map M_2
    9:   r3 += r1
    A:   r1 = *(u64 *)(r3 + 0x0)
    B:   gotox r1                   # jump to target loaded from M_1 or M_2

During check_cfg stage the verifier will collect all the maps which point to inside the subprog being verified. When building the config, the high 16 bytes of the insn_state are used, so this patch (theoretically) supports jump tables of up to 2^16 slots.

During the later stage, in check_indirect_jump, it is checked that the register Rx was loaded from a particular instruction array.

---

[...]

Quoted 4 lines
include/linux/bpf_verifier.h +0 -0
@@ -571,6 +572,9 @@ struct bpf_insn_aux_data {
 	u8 fastcall_spills_num:3;
 	u8 arg_prog:4;
 
Quoted 5 lines

include/linux/bpf_verifier.h struct bpf_insn_aux_data { · line 577

Quoted 3 lines
include/linux/bpf_verifier.h +3 -0
+	/* true if jt->off was allocated */
+	bool jt_allocated;
+

This is a leftover from v3, no longer used.

Thanks.

Quoted 13 lines
Quoted 10 lines
include/linux/bpf_verifier.h +2 -0
 	/* below fields are initialized once */
 	unsigned int orig_idx; /* original instruction index */
 	bool jmp_point;
@@ -840,6 +844,8 @@ struct bpf_verifier_env {
 	struct bpf_scc_info **scc_info;
 	u32 scc_cnt;
 	struct bpf_iarray *succ;
+	u32 *gotox_tmp_buf;
+	size_t gotox_tmp_buf_size;
 };

[...]

Quoted 12 lines

kernel/bpf/verifier.c static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, · line 14730

Quoted 9 lines
kernel/bpf/verifier.c +5 -0
@@ -14685,6 +14723,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
 				dst);
 			return -EACCES;
 		}
+		if (ptr_to_insn_array) {
+			verbose(env, "R%d subtraction from pointer to instruction prohibited\n",
+				dst);
+			return -EACCES;
+		}

Is anything going to break if subtraction is allowed? The bounds are still maintained, so seem to be ok.

Ok, I just haven't seen any reason to add because such code is not generated on practice. I will add in the next version.

Quoted 10 lines
Quoted 3 lines
kernel/bpf/verifier.c +0 -0
 		if (known && (ptr_reg->off - smin_val ==
 			      (s64)(s32)(ptr_reg->off - smin_val))) {
 			/* pointer -= K.  Subtract it from fixed offset */

[...]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -17786,6 +17830,210 @@ static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
 	return new;
 }
 
Quoted 13 lines

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 17842

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+#define SET_HIGH(STATE, LAST)	STATE = (STATE & 0xffffU) | ((LAST) << 16)
+#define GET_HIGH(STATE)		((u16)((STATE) >> 16))
+
+static int push_gotox_edge(int t, struct bpf_verifier_env *env, struct bpf_iarray *jt)
+{
+	int *insn_stack = env->cfg.insn_stack;
+	int *insn_state = env->cfg.insn_state;
+	u16 prev;
+	int w;
+

push_insn() checks if t is in range [0, env->prog->len], is the same check needed here?

You wanted to say w? (I think t is guaranteed to be a valid one.) In cas of push_gotox_edge w is taken from a jump table which is guaranteed to have only correct instructions.

Quoted 11 lines
Quoted 11 lines
kernel/bpf/verifier.c +11 -0
+	for (prev = GET_HIGH(insn_state[t]); prev < jt->off_cnt; prev++) {
+		w = jt->off[prev];
+		mark_jmp_point(env, w);
+
+		/* EXPLORED || DISCOVERED */
+		if (insn_state[w])
+			continue;
+
+		break;
+	}
+
Quoted 8 lines

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 17859

Quoted 6 lines
kernel/bpf/verifier.c +6 -0
+	if (prev == jt->off_cnt)
+		return DONE_EXPLORING;
+
+	if (env->cfg.cur_stack >= env->prog->len)
+		return -E2BIG;
+	insn_stack[env->cfg.cur_stack++] = w;

I think insn_state[w] |= DISCOVERED; is missing here.

Hmm, yes, thanks.

Quoted 21 lines
Quoted 4 lines
kernel/bpf/verifier.c +4 -0
+
+	SET_HIGH(insn_state[t], prev + 1);
+	return KEEP_EXPLORING;
+}

[...]

Quoted 14 lines
kernel/bpf/verifier.c +14 -0
+static struct bpf_iarray *
+create_jt(int t, struct bpf_verifier_env *env, int fd)
+{
+	static struct bpf_subprog_info *subprog;
+	int subprog_idx, subprog_start, subprog_end;
+	struct bpf_iarray *jt;
+	int i;
+
+	if (env->subprog_cnt == 0)
+		return ERR_PTR(-EFAULT);
+
+	subprog_idx = bpf_find_containing_subprog_idx(env, t);
+	if (subprog_idx < 0) {
+		verbose(env, "can't find subprog containing instruction %d\n", t);
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+		return ERR_PTR(-EFAULT);
+	}

Nit: There is now verifier_bug() for such cases.
Also, it seems that all bpf_find_containing_subprog() users assume that the function can't fail.
Like in this case, there is already access jt = env->insn_aux_data[t].jt; in visit_gotox_insn() that will be an error if t is bogus.

Could you please explain this once again? The error from bpf_find_containing_subprog* funcs is checked in this code.

Quoted 25 lines
Quoted 25 lines
kernel/bpf/verifier.c +25 -0
+	subprog = &env->subprog_info[subprog_idx];
+	subprog_start = subprog->start;
+	subprog_end = (subprog + 1)->start;
+	jt = jt_from_subprog(env, subprog_start, subprog_end);
+	if (IS_ERR(jt))
+		return jt;
+
+	/* Check that the every element of the jump table fits within the given subprogram */
+	for (i = 0; i < jt->off_cnt; i++) {
+		if (jt->off[i] < subprog_start || jt->off[i] >= subprog_end) {
+			verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]",
+					t, subprog_start, subprog_end);
+			return ERR_PTR(-EINVAL);
+		}
+	}
+
+	return jt;
+}
+
+/* "conditional jump with N edges" */
+static int visit_gotox_insn(int t, struct bpf_verifier_env *env, int fd)
+{
+	struct bpf_iarray *jt;
+
+	jt = env->insn_aux_data[t].jt;
Quoted 8 lines

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 18031

Quoted 6 lines
kernel/bpf/verifier.c +6 -0
+	if (!jt) {
+		jt = create_jt(t, env, fd);
+		if (IS_ERR(jt))
+			return PTR_ERR(jt);
+	}
+	env->insn_aux_data[t].jt = jt;

Nit: move this assignment up into the if (!jt) body?

Sure, thanks

Quoted 17 lines

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 18036

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+
+	mark_prune_point(env, t);
+	return push_gotox_edge(t, env, jt);
+}
+

I think the following implementation should achieve the same result:

  /* "conditional jump with N edges" */
  static int visit_gotox_insn(int t, struct bpf_verifier_env *env, int fd)
  {
        int *insn_stack = env->cfg.insn_stack;
        int *insn_state = env->cfg.insn_state;
        bool keep_exploring = false;
        struct bpf_iarray *jt;
        int i, w;
Quoted 4 lines
        jt = env->insn_aux_data[t].jt;
        if (!jt) {
                jt = create_jt(t, env, fd);
                if (IS_ERR(ptr: jt))

(BTW, out of curiosity, do these "ptr: jt" type hints and alike come from your environment? What is it, if this is not a secret?)

Quoted 23 lines
                        return PTR_ERR(ptr: jt);

                env->insn_aux_data[t].jt = jt;
        }

        mark_prune_point(env, idx: t);
        for (i = 0; i < jt->off_cnt; i++) {
                w = jt->off[i];
                mark_jmp_point(env, idx: w);

                /* EXPLORED || DISCOVERED */
                if (insn_state[w])
                        continue;

                if (env->cfg.cur_stack >= env->prog->len)
                        return -E2BIG;

                insn_stack[env->cfg.cur_stack++] = w;
                insn_state[w] |= DISCOVERED;
                keep_exploring = true;
        }

        return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;
Quoted 3 lines

}

But w/o GET_HIGH/SET_HIGH things. Wdyt?

Awesome, thanks, this should work!

Quoted 28 lines

[...]

Quoted 25 lines
kernel/bpf/verifier.c +21 -0
@@ -19817,6 +20068,103 @@ static int process_bpf_exit_full(struct bpf_verifier_env *env,
 	return PROCESS_BPF_EXIT;
 }
 
+static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
+				       int regno,
+				       struct bpf_map *map,
+				       u32 *pmin_index, u32 *pmax_index)
+{
+	struct bpf_reg_state *reg = reg_state(env, regno);
+	u64 min_index, max_index;
+	const u32 size = 8;
+
+	if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
+		(min_index > (u64) U32_MAX * size)) {
+		verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
+			     regno, reg->umin_value, reg->off);
+		return -ERANGE;
+	}
+	if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||
+		(max_index > (u64) U32_MAX * size)) {
+		verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
+			     regno, reg->umax_value, reg->off);
+		return -ERANGE;
+	}
Quoted 8 lines

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20096

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+
+	min_index /= size;
+	max_index /= size;
+
+	if (min_index >= map->max_entries || max_index >= map->max_entries) {

Nit: it is guaranteed that reg->umin_value <= reg->umax_value,
so checking max_index should be sufficient.

Ok, thanks, removed.

Quoted 34 lines
Quoted 34 lines
kernel/bpf/verifier.c +34 -0
+		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
+			     regno, min_index, max_index, map->max_entries);
+		return -EINVAL;
+	}
+
+	*pmin_index = min_index;
+	*pmax_index = max_index;
+	return 0;
+}
+
+/* gotox *dst_reg */
+static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
+{
+	struct bpf_verifier_state *other_branch;
+	struct bpf_reg_state *dst_reg;
+	struct bpf_map *map;
+	u32 min_index, max_index;
+	size_t new_size;
+	u32 *new_buf;
+	int err = 0;
+	int n;
+	int i;
+
+	dst_reg = reg_state(env, insn->dst_reg);
+	if (dst_reg->type != PTR_TO_INSN) {
+		verbose(env, "R%d has type %d, expected PTR_TO_INSN\n",
+			     insn->dst_reg, dst_reg->type);
+		return -EINVAL;
+	}
+
+	map = dst_reg->map_ptr;
+	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
+		return -EFAULT;
+
Quoted 8 lines

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20133

Quoted 3 lines
kernel/bpf/verifier.c +3 -0
+	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
+			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
+		return -EFAULT;

Are you sure this is a verifier bug?
The program can be written in a way, such that e.g. hash map pointer is passed as a parameter for gotox, that would be an incorrect program, not a verifier bug.

Yeah, sure, thanks.

Quoted 8 lines
Quoted 8 lines
kernel/bpf/verifier.c +8 -0
+
+	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
+	if (err)
+		return err;
+
+	/* Ensure that the buffer is large enough */
+	new_size = sizeof(u32) * (max_index - min_index + 1);
+	if (env->gotox_tmp_buf_size < new_size) {
Quoted 8 lines

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20146

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+		new_buf = kvrealloc(env->gotox_tmp_buf, new_size, GFP_KERNEL_ACCOUNT);
+		if (!new_buf)
+			return -ENOMEM;
+		env->gotox_tmp_buf = new_buf;
+		env->gotox_tmp_buf_size = new_size;

Can gotox_tmp_buf be an bpf_iarray instance?
If it can, iarray_realloc() can be reused here.

Ah, nice, will use it :)

Quoted 7 lines

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20149

Quoted 3 lines
kernel/bpf/verifier.c +3 -0
+	}
+
+	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf);

I still think this might be a problem for big jump tables if gotox is in a loop body. Can you check a perf report for such scenario? E.g. 256 entries in the jump table, some duplicates, dispatched in a loop.

Well, for "big jump tables" I want to follow up with some changes in any case, just didn't get there with this patchset yet. Namely, the insn_inxed \mapto jump table map must be optimized, otherwise the JIT spends too much time on this. So, this would require bin/serach or better a hash to optimize this. In the latter case, this piece might also be optimized by caching a lookup (by the "map[start,end]" key).

Quoted 23 lines
Quoted 21 lines
kernel/bpf/verifier.c +18 -0
+	if (n < 0)
+		return n;
+	if (n == 0) {
+		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
+			     insn->dst_reg, map->id);
+		return -EINVAL;
+	}
+
+	for (i = 0; i < n - 1; i++) {
+		other_branch = push_stack(env, env->gotox_tmp_buf[i],
+					  env->insn_idx, env->cur_state->speculative);
+		if (IS_ERR(other_branch))
+			return PTR_ERR(other_branch);
+	}
+	env->insn_idx = env->gotox_tmp_buf[n-1];
+	return 0;
+}
+
 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 {
 	int err;

[...]

maintainer
#32 lore raw

Re: [PATCH v5 bpf-next 10/15] bpf, x86: add support for indirect jumps

On Thu, 2025-10-02 at 09:27 +0000, Anton Protopopov wrote:

[...]

Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -14685,6 +14723,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
 				dst);
 			return -EACCES;
 		}
Quoted 8 lines

kernel/bpf/verifier.c static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, · line 14730

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+		if (ptr_to_insn_array) {
+			verbose(env, "R%d subtraction from pointer to instruction prohibited\n",
+				dst);
+			return -EACCES;
+		}

Is anything going to break if subtraction is allowed? The bounds are still maintained, so seem to be ok.

Quoted 2 lines

Ok, I just haven't seen any reason to add because such code is not generated on practice. I will add in the next version.

Just less code and less tests if there is no special case.

[...]

Quoted 18 lines
Quoted 4 lines
Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -17786,6 +17830,210 @@ static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
 	return new;
 }
 
Quoted 13 lines

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 17842

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+#define SET_HIGH(STATE, LAST)	STATE = (STATE & 0xffffU) | ((LAST) << 16)
+#define GET_HIGH(STATE)		((u16)((STATE) >> 16))
+
+static int push_gotox_edge(int t, struct bpf_verifier_env *env, struct bpf_iarray *jt)
+{
+	int *insn_stack = env->cfg.insn_stack;
+	int *insn_state = env->cfg.insn_state;
+	u16 prev;
+	int w;
+

push_insn() checks if t is in range [0, env->prog->len], is the same check needed here?

Quoted 3 lines

You wanted to say w? (I think t is guaranteed to be a valid one.) In cas of push_gotox_edge w is taken from a jump table which is guaranteed to have only correct instructions.

Yes, I meant w, sorry.
So, the invalid offsets would be rejected at map construction time? I'd put a check here just to be consistent with push_insn, but skip it if you think it's not really necessary.

[...]

Quoted 23 lines
Quoted 14 lines
Quoted 14 lines
kernel/bpf/verifier.c +14 -0
+static struct bpf_iarray *
+create_jt(int t, struct bpf_verifier_env *env, int fd)
+{
+	static struct bpf_subprog_info *subprog;
+	int subprog_idx, subprog_start, subprog_end;
+	struct bpf_iarray *jt;
+	int i;
+
+	if (env->subprog_cnt == 0)
+		return ERR_PTR(-EFAULT);
+
+	subprog_idx = bpf_find_containing_subprog_idx(env, t);
+	if (subprog_idx < 0) {
+		verbose(env, "can't find subprog containing instruction %d\n", t);
Quoted 8 lines

Review static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 17858

Quoted 2 lines
(quoted diff) +2 -0
+		return ERR_PTR(-EFAULT);
+	}

Nit: There is now verifier_bug() for such cases.
Also, it seems that all bpf_find_containing_subprog() users assume that the function can't fail.
Like in this case, there is already access jt = env->insn_aux_data[t].jt; in visit_gotox_insn() that will be an error if t is bogus.

Quoted 2 lines

Could you please explain this once again? The error from bpf_find_containing_subprog* funcs is checked in this code.

Point being that there is no need to check if bpf_find_containing_subprog() returns error:
- If we guarantee that t is within program bounds it can't fail (which I think we do). In other places where this function is called it's return value is not checked for errors.
- In case if we don't guarantee that t is within program bounds, then just before call to create_jt() there is an access jt = env->insn_aux_data[t].jt; which would read from some undefined location. So, it's already too late to check here.

[...]

Quoted 9 lines
Quoted 9 lines
  /* "conditional jump with N edges" */
  static int visit_gotox_insn(int t, struct bpf_verifier_env *env, int fd)
  {
        int *insn_stack = env->cfg.insn_stack;
        int *insn_state = env->cfg.insn_state;
        bool keep_exploring = false;
        struct bpf_iarray *jt;
        int i, w;
Quoted 7 lines
Quoted 4 lines
        jt = env->insn_aux_data[t].jt;
        if (!jt) {
                jt = create_jt(t, env, fd);
                if (IS_ERR(ptr: jt))

(BTW, out of curiosity, do these "ptr: jt" type hints and alike come from your environment? What is it, if this is not a secret?)

Oh... sorry about that, I'll suppress those moving forward. It's a copy-paste from tmux window.
In tmux there is a terminal running emacs in console mode. Emacs uses eglot mode to integrate with clangd language server. Eglot displays these parameter name hints, provided by clangd. The whole thing ends up in copy-paste because in console mode all of this is just text. Had I run emacs in gui mode, it wouldn't be copy-pasted. But that's a remote machine, so here were are.

[...]

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
kernel/bpf/verifier.c +2 -0
+static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
+{

[...]

Quoted 6 lines
Quoted 5 lines

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20149

Quoted 1 line
kernel/bpf/verifier.c +1 -0
+	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf);

I still think this might be a problem for big jump tables if gotox is in a loop body. Can you check a perf report for such scenario? E.g. 256 entries in the jump table, some duplicates, dispatched in a loop.

Quoted 6 lines

Well, for "big jump tables" I want to follow up with some changes in any case, just didn't get there with this patchset yet. Namely, the insn_inxed \mapto jump table map must be optimized, otherwise the JIT spends too much time on this. So, this would require bin/serach or better a hash to optimize this. In the latter case, this piece might also be optimized by caching a lookup (by the "map[start,end]" key).

Ok, if follow-up is planned, we can stick with a simple implementation for this patch.

[...]

#33 lore raw

Re: [PATCH v5 bpf-next 10/15] bpf, x86: add support for indirect jumps

Quoted 42 lines · Eduard Zingerman

On Thu, 2025-10-02 at 09:27 +0000, Anton Protopopov wrote:

[...]

Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -14685,6 +14723,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
 				dst);
 			return -EACCES;
 		}
Quoted 8 lines

kernel/bpf/verifier.c static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, · line 14730

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+		if (ptr_to_insn_array) {
+			verbose(env, "R%d subtraction from pointer to instruction prohibited\n",
+				dst);
+			return -EACCES;
+		}

Is anything going to break if subtraction is allowed? The bounds are still maintained, so seem to be ok.

Quoted 2 lines

Ok, I just haven't seen any reason to add because such code is not generated on practice. I will add in the next version.

Just less code and less tests if there is no special case.

[...]

Quoted 18 lines
Quoted 17 lines
Quoted 4 lines
kernel/bpf/verifier.c +0 -0
@@ -17786,6 +17830,210 @@ static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
 	return new;
 }
 

kernel/bpf/verifier.c static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem) · line 17842

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+#define SET_HIGH(STATE, LAST)	STATE = (STATE & 0xffffU) | ((LAST) << 16)
+#define GET_HIGH(STATE)		((u16)((STATE) >> 16))
+
+static int push_gotox_edge(int t, struct bpf_verifier_env *env, struct bpf_iarray *jt)
+{
+	int *insn_stack = env->cfg.insn_stack;
+	int *insn_state = env->cfg.insn_state;
+	u16 prev;
+	int w;
+

push_insn() checks if t is in range [0, env->prog->len], is the same check needed here?

Quoted 8 lines
Quoted 3 lines

You wanted to say w? (I think t is guaranteed to be a valid one.) In cas of push_gotox_edge w is taken from a jump table which is guaranteed to have only correct instructions.

Yes, I meant w, sorry.
So, the invalid offsets would be rejected at map construction time? I'd put a check here just to be consistent with push_insn, but skip it if you think it's not really necessary.

I will add a check for consistency.

Quoted 28 lines

[...]

Quoted 23 lines
Quoted 14 lines
Quoted 14 lines
kernel/bpf/verifier.c +14 -0
+static struct bpf_iarray *
+create_jt(int t, struct bpf_verifier_env *env, int fd)
+{
+	static struct bpf_subprog_info *subprog;
+	int subprog_idx, subprog_start, subprog_end;
+	struct bpf_iarray *jt;
+	int i;
+
+	if (env->subprog_cnt == 0)
+		return ERR_PTR(-EFAULT);
+
+	subprog_idx = bpf_find_containing_subprog_idx(env, t);
+	if (subprog_idx < 0) {
+		verbose(env, "can't find subprog containing instruction %d\n", t);
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+		return ERR_PTR(-EFAULT);
+	}

Nit: There is now verifier_bug() for such cases.
Also, it seems that all bpf_find_containing_subprog() users assume that the function can't fail.
Like in this case, there is already access jt = env->insn_aux_data[t].jt; in visit_gotox_insn() that will be an error if t is bogus.

Quoted 2 lines

Could you please explain this once again? The error from bpf_find_containing_subprog* funcs is checked in this code.

Quoted 9 lines

Point being that there is no need to check if bpf_find_containing_subprog() returns error:
- If we guarantee that t is within program bounds it can't fail (which I think we do). In other places where this function is called it's return value is not checked for errors.
- In case if we don't guarantee that t is within program bounds, then just before call to create_jt() there is an access jt = env->insn_aux_data[t].jt; which would read from some undefined location. So, it's already too late to check here.

Ah, ok, I see, thanks.

Quoted 19 lines

[...]

Quoted 9 lines
Quoted 9 lines
  /* "conditional jump with N edges" */
  static int visit_gotox_insn(int t, struct bpf_verifier_env *env, int fd)
  {
        int *insn_stack = env->cfg.insn_stack;
        int *insn_state = env->cfg.insn_state;
        bool keep_exploring = false;
        struct bpf_iarray *jt;
        int i, w;
Quoted 7 lines
Quoted 4 lines
        jt = env->insn_aux_data[t].jt;
        if (!jt) {
                jt = create_jt(t, env, fd);
                if (IS_ERR(ptr: jt))

(BTW, out of curiosity, do these "ptr: jt" type hints and alike come from your environment? What is it, if this is not a secret?)

Quoted 8 lines

Oh... sorry about that, I'll suppress those moving forward. It's a copy-paste from tmux window.
In tmux there is a terminal running emacs in console mode. Emacs uses eglot mode to integrate with clangd language server. Eglot displays these parameter name hints, provided by clangd. The whole thing ends up in copy-paste because in console mode all of this is just text. Had I run emacs in gui mode, it wouldn't be copy-pasted. But that's a remote machine, so here were are.

Thanks for the explanations. (Also, no problem if this appears.)

Quoted 24 lines

[...]

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
kernel/bpf/verifier.c +2 -0
+static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
+{

[...]

Quoted 6 lines
Quoted 5 lines

kernel/bpf/verifier.c static int process_bpf_exit_full(struct bpf_verifier_env *env, · line 20149

Quoted 1 line
kernel/bpf/verifier.c +1 -0
+	n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf);

I still think this might be a problem for big jump tables if gotox is in a loop body. Can you check a perf report for such scenario? E.g. 256 entries in the jump table, some duplicates, dispatched in a loop.

Quoted 6 lines

Well, for "big jump tables" I want to follow up with some changes in any case, just didn't get there with this patchset yet. Namely, the insn_inxed \mapto jump table map must be optimized, otherwise the JIT spends too much time on this. So, this would require bin/serach or better a hash to optimize this. In the latter case, this piece might also be optimized by caching a lookup (by the "map[start,end]" key).

Ok, if follow-up is planned, we can stick with a simple implementation for this patch.

[...]

#34 lore raw

PATCH v5 11/15 bpf: disasm: add support for BPF_JMP|BPF_JA|BPF_X

In reply to Anton Protopopov

Add support for indirect jump instruction.

Example output from bpftool:

0: (79) r3 = *(u64 *)(r1 +0)
1: (25) if r3 > 0x4 goto pc+666
2: (67) r3 <<= 3
3: (18) r1 = 0xffffbeefspameggs
5: (0f) r1 += r3
6: (79) r1 = *(u64 *)(r1 +0)
7: (0d) gotox r1

---
 kernel/bpf/disasm.c | 9 +++++++++
 1 file changed, 9 insertions(+)
kernel/bpf/disasm.c +9 -0
index 20883c6b1546..4a1ecc6f7582 100644
@@ -183,6 +183,13 @@ static inline bool is_mov_percpu_addr(const struct bpf_insn *insn)
 	return insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->off == BPF_ADDR_PERCPU;
 }
 
+static void print_bpf_ja_indirect(bpf_insn_print_t verbose,
+				  void *private_data,
+				  const struct bpf_insn *insn)
+{
+	verbose(private_data, "(%02x) gotox r%d\n", insn->code, insn->dst_reg);
+}
+
 void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		    const struct bpf_insn *insn,
 		    bool allow_ptr_leaks)
@@ -358,6 +365,8 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		} else if (insn->code == (BPF_JMP | BPF_JA)) {
 			verbose(cbs->private_data, "(%02x) goto pc%+d\n",
 				insn->code, insn->off);
+		} else if (insn->code == (BPF_JMP | BPF_JA | BPF_X)) {
+			print_bpf_ja_indirect(verbose, cbs->private_data, insn);
 		} else if (insn->code == (BPF_JMP | BPF_JCOND) &&
 			   insn->src_reg == BPF_MAY_GOTO) {
 			verbose(cbs->private_data, "(%02x) may_goto pc%+d\n",
Signature · 1 line
2.34.1
maintainer
#35 lore raw

Re: [PATCH v5 bpf-next 11/15] bpf: disasm: add support for BPF_JMP|BPF_JA|BPF_X

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

[...]

Quoted 5 lines
kernel/bpf/disasm.c +0 -0
index 20883c6b1546..4a1ecc6f7582 100644

kernel/bpf/disasm.c static inline bool is_mov_percpu_addr(const struct bpf_insn *insn) · line 192

Quoted 10 lines
kernel/bpf/disasm.c +7 -0
@@ -183,6 +183,13 @@ static inline bool is_mov_percpu_addr(const struct bpf_insn *insn)
 	return insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->off == BPF_ADDR_PERCPU;
 }
 
+static void print_bpf_ja_indirect(bpf_insn_print_t verbose,
+				  void *private_data,
+				  const struct bpf_insn *insn)
+{
+	verbose(private_data, "(%02x) gotox r%d\n", insn->code, insn->dst_reg);
+}
+

Nit: there is no need for this to be a separate function,
can be a direct verbose call, like for any other instruction.

Quoted 12 lines
kernel/bpf/disasm.c +2 -0
 void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		    const struct bpf_insn *insn,
 		    bool allow_ptr_leaks)
@@ -358,6 +365,8 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		} else if (insn->code == (BPF_JMP | BPF_JA)) {
 			verbose(cbs->private_data, "(%02x) goto pc%+d\n",
 				insn->code, insn->off);
+		} else if (insn->code == (BPF_JMP | BPF_JA | BPF_X)) {
+			print_bpf_ja_indirect(verbose, cbs->private_data, insn);
 		} else if (insn->code == (BPF_JMP | BPF_JCOND) &&
 			   insn->src_reg == BPF_MAY_GOTO) {
 			verbose(cbs->private_data, "(%02x) may_goto pc%+d\n",
#36 lore raw

Re: [PATCH v5 bpf-next 11/15] bpf: disasm: add support for BPF_JMP|BPF_JA|BPF_X

Quoted 12 lines · Eduard Zingerman

On Tue, 2025-09-30 at 12:51 +0000, Anton Protopopov wrote:

[...]

Quoted 8 lines
kernel/bpf/disasm.c +0 -0
index 20883c6b1546..4a1ecc6f7582 100644
@@ -183,6 +183,13 @@ static inline bool is_mov_percpu_addr(const struct bpf_insn *insn)
 	return insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->off == BPF_ADDR_PERCPU;
 }
 
Quoted 10 lines

kernel/bpf/disasm.c static inline bool is_mov_percpu_addr(const struct bpf_insn *insn) · line 192

Quoted 7 lines
kernel/bpf/disasm.c +7 -0
+static void print_bpf_ja_indirect(bpf_insn_print_t verbose,
+				  void *private_data,
+				  const struct bpf_insn *insn)
+{
+	verbose(private_data, "(%02x) gotox r%d\n", insn->code, insn->dst_reg);
+}
+

Nit: there is no need for this to be a separate function,
can be a direct verbose call, like for any other instruction.

Thanks, removed. (The function was part of the statick keys patch to print all ja-related insns.)

Quoted 12 lines
Quoted 12 lines
kernel/bpf/disasm.c +2 -0
 void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		    const struct bpf_insn *insn,
 		    bool allow_ptr_leaks)
@@ -358,6 +365,8 @@ void print_bpf_insn(const struct bpf_insn_cbs *cbs,
 		} else if (insn->code == (BPF_JMP | BPF_JA)) {
 			verbose(cbs->private_data, "(%02x) goto pc%+d\n",
 				insn->code, insn->off);
+		} else if (insn->code == (BPF_JMP | BPF_JA | BPF_X)) {
+			print_bpf_ja_indirect(verbose, cbs->private_data, insn);
 		} else if (insn->code == (BPF_JMP | BPF_JCOND) &&
 			   insn->src_reg == BPF_MAY_GOTO) {
 			verbose(cbs->private_data, "(%02x) may_goto pc%+d\n",
#37 lore raw

PATCH v5 12/15 libbpf: fix formatting of bpf_object__append_subprog_code

In reply to Anton Protopopov

The commit 6c918709bd30 ("libbpf: Refactor bpf_object__reloc_code") added the bpf_object__append_subprog_code() with incorrect indentations. Use tabs instead. (This also makes a consequent commit better readable.)

---
 tools/lib/bpf/libbpf.c | 52 +++++++++++++++++++++---------------------
 1 file changed, 26 insertions(+), 26 deletions(-)
tools/lib/bpf/libbpf.c +26 -26
index f92083f51bdb..083ec3ca4813 100644
@@ -6440,32 +6440,32 @@ static int
 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
 				struct bpf_program *subprog)
 {
-       struct bpf_insn *insns;
-       size_t new_cnt;
-       int err;
-
-       subprog->sub_insn_off = main_prog->insns_cnt;
-
-       new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
-       insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
-       if (!insns) {
-               pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
-               return -ENOMEM;
-       }
-       main_prog->insns = insns;
-       main_prog->insns_cnt = new_cnt;
-
-       memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
-              subprog->insns_cnt * sizeof(*insns));
-
-       pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
-                main_prog->name, subprog->insns_cnt, subprog->name);
-
-       /* The subprog insns are now appended. Append its relos too. */
-       err = append_subprog_relos(main_prog, subprog);
-       if (err)
-               return err;
-       return 0;
+	struct bpf_insn *insns;
+	size_t new_cnt;
+	int err;
+
+	subprog->sub_insn_off = main_prog->insns_cnt;
+
+	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
+	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
+	if (!insns) {
+		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
+		return -ENOMEM;
+	}
+	main_prog->insns = insns;
+	main_prog->insns_cnt = new_cnt;
+
+	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
+	       subprog->insns_cnt * sizeof(*insns));
+
+	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
+		 main_prog->name, subprog->insns_cnt, subprog->name);
+
+	/* The subprog insns are now appended. Append its relos too. */
+	err = append_subprog_relos(main_prog, subprog);
+	if (err)
+		return err;
+	return 0;
 }
 
 static int
Signature · 1 line
2.34.1
#38 lore raw

PATCH v5 13/15 libbpf: support llvm-generated indirect jumps

In reply to Anton Protopopov

For v5 instruction set LLVM is allowed to generate indirect jumps for switch statements and for 'goto *rX' assembly. Every such a jump will be accompanied by necessary metadata, e.g. (llvm-objdump -Sr ...):

       0:       r2 = 0x0 ll
                0000000000000030:  R_BPF_64_64  BPF.JT.0.0

Here BPF.JT.1.0 is a symbol residing in the .jumptables section:

    Symbol table:
       4: 0000000000000000   240 OBJECT  GLOBAL DEFAULT     4 BPF.JT.0.0

The -bpf-min-jump-table-entries llvm option may be used to control the minimal size of a switch which will be converted to an indirect jumps.

---
 tools/lib/bpf/libbpf.c        | 221 +++++++++++++++++++++++++++++++++-
 tools/lib/bpf/libbpf_probes.c |   4 +
 tools/lib/bpf/linker.c        |  10 +-
 3 files changed, 232 insertions(+), 3 deletions(-)
tools/lib/bpf/libbpf.c +220 -1
index 083ec3ca4813..b6fbba1a42d5 100644
@@ -192,6 +192,7 @@ static const char * const map_type_name[] = {
 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
 	[BPF_MAP_TYPE_ARENA]			= "arena",
+	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
 };
 
 static const char * const prog_type_name[] = {
@@ -373,6 +374,7 @@ enum reloc_type {
 	RELO_EXTERN_CALL,
 	RELO_SUBPROG_ADDR,
 	RELO_CORE,
+	RELO_INSN_ARRAY,
 };
 
 struct reloc_desc {
@@ -383,7 +385,10 @@ struct reloc_desc {
 		struct {
 			int map_idx;
 			int sym_off;
-			int ext_idx;
+			union {
+				int ext_idx;
+				int sym_size;
+			};
 		};
 	};
 };
@@ -425,6 +430,11 @@ struct bpf_sec_def {
 	libbpf_prog_attach_fn_t prog_attach_fn;
 };
 
+struct bpf_light_subprog {
+	__u32 sec_insn_off;
+	__u32 sub_insn_off;
+};
+
 /*
  * bpf_prog should be a better name but it has been used in
  * linux/filter.h.
@@ -498,6 +508,9 @@ struct bpf_program {
 	__u32 line_info_cnt;
 	__u32 prog_flags;
 	__u8  hash[SHA256_DIGEST_LENGTH];
+
+	struct bpf_light_subprog *subprogs;
+	__u32 subprog_cnt;
 };
 
 struct bpf_struct_ops {
@@ -527,6 +540,7 @@ struct bpf_struct_ops {
 #define STRUCT_OPS_SEC ".struct_ops"
 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
 #define ARENA_SEC ".addr_space.1"
+#define JUMPTABLES_SEC ".jumptables"
 
 enum libbpf_map_type {
 	LIBBPF_MAP_UNSPEC,
@@ -671,6 +685,7 @@ struct elf_state {
 	int symbols_shndx;
 	bool has_st_ops;
 	int arena_data_shndx;
+	int jumptables_data_shndx;
 };
 
 struct usdt_manager;
@@ -742,6 +757,16 @@ struct bpf_object {
 	void *arena_data;
 	size_t arena_data_sz;
 
+	void *jumptables_data;
+	size_t jumptables_data_sz;
+
+	struct {
+		struct bpf_program *prog;
+		int off;
+		int fd;
+	} *jumptable_maps;
+	size_t jumptable_map_cnt;
+
 	struct kern_feature_cache *feat_cache;
 	char *token_path;
 	int token_fd;
@@ -768,6 +793,7 @@ void bpf_program__unload(struct bpf_program *prog)
 
 	zfree(&prog->func_info);
 	zfree(&prog->line_info);
+	zfree(&prog->subprogs);
 }
 
 static void bpf_program__exit(struct bpf_program *prog)
@@ -3946,6 +3972,13 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
 			} else if (strcmp(name, ARENA_SEC) == 0) {
 				obj->efile.arena_data = data;
 				obj->efile.arena_data_shndx = idx;
+			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
+				obj->jumptables_data = malloc(data->d_size);
+				if (!obj->jumptables_data)
+					return -ENOMEM;
+				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
+				obj->jumptables_data_sz = data->d_size;
+				obj->efile.jumptables_data_shndx = idx;
 			} else {
 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
 					idx, name);
@@ -4638,6 +4671,16 @@ static int bpf_program__record_reloc(struct bpf_program *prog,
 		return 0;
 	}
 
+	/* jump table data relocation */
+	if (shdr_idx == obj->efile.jumptables_data_shndx) {
+		reloc_desc->type = RELO_INSN_ARRAY;
+		reloc_desc->insn_idx = insn_idx;
+		reloc_desc->map_idx = -1;
+		reloc_desc->sym_off = sym->st_value;
+		reloc_desc->sym_size = sym->st_size;
+		return 0;
+	}
+
 	/* generic map reference relocation */
 	if (type == LIBBPF_MAP_UNSPEC) {
 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
@@ -6148,6 +6191,131 @@ static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
 }
 
+static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, int off)
+{
+	size_t i;
+
+	for (i = 0; i < obj->jumptable_map_cnt; i++) {
+		/*
+		 * This might happen that same offset is used for two different
+		 * programs (as jump tables can be the same). However, for
+		 * different programs different maps should be created.
+		 */
+		if (obj->jumptable_maps[i].off == off &&
+		    obj->jumptable_maps[i].prog == prog)
+			return obj->jumptable_maps[i].fd;
+	}
+
+	return -ENOENT;
+}
+
+static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, int off, int map_fd)
+{
+	size_t new_cnt = obj->jumptable_map_cnt + 1;
+	size_t size = sizeof(obj->jumptable_maps[0]);
+	void *tmp;
+
+	tmp = libbpf_reallocarray(obj->jumptable_maps, new_cnt, size);
+	if (!tmp)
+		return -ENOMEM;
+
+	obj->jumptable_maps = tmp;
+	obj->jumptable_maps[new_cnt - 1].prog = prog;
+	obj->jumptable_maps[new_cnt - 1].off = off;
+	obj->jumptable_maps[new_cnt - 1].fd = map_fd;
+	obj->jumptable_map_cnt = new_cnt;
+
+	return 0;
+}
+
+static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog,
+			 int off, int size, int adjust_off)
+{
+	const __u32 value_size = sizeof(struct bpf_insn_array_value);
+	const __u32 max_entries = size / value_size;
+	struct bpf_insn_array_value val = {};
+	int map_fd, err;
+	__u64 xlated_off;
+	__u64 *jt;
+	__u32 i;
+
+	map_fd = find_jt_map(obj, prog, off);
+	if (map_fd >= 0)
+		return map_fd;
+
+	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
+				4, value_size, max_entries, NULL);
+	if (map_fd < 0)
+		return map_fd;
+
+	if (!obj->jumptables_data) {
+		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
+		err = -EINVAL;
+		goto err_close;
+	}
+	if (off + size > obj->jumptables_data_sz) {
+		pr_warn("jumptables_data size is %zd, trying to access %d\n",
+			obj->jumptables_data_sz, off + size);
+		err = -EINVAL;
+		goto err_close;
+	}
+
+	jt = (__u64 *)(obj->jumptables_data + off);
+	for (i = 0; i < max_entries; i++) {
+		/*
+		 * LLVM-generated jump tables contain u64 records, however
+		 * should contain values that fit in u32.
+		 * The adjust_off provided by the caller adjusts the offset to
+		 * be relative to the beginning of the main function
+		 */
+		xlated_off = jt[i]/sizeof(struct bpf_insn) + adjust_off;
+		if (xlated_off > UINT32_MAX) {
+			pr_warn("invalid jump table value %llx at offset %d (adjust_off %d)\n",
+				jt[i], off + i, adjust_off);
+			err = -EINVAL;
+			goto err_close;
+		}
+
+		val.xlated_off = xlated_off;
+		err = bpf_map_update_elem(map_fd, &i, &val, 0);
+		if (err)
+			goto err_close;
+	}
+
+	err = bpf_map_freeze(map_fd);
+	if (err)
+		goto err_close;
+
+	err = add_jt_map(obj, prog, off, map_fd);
+	if (err)
+		goto err_close;
+
+	return map_fd;
+
+err_close:
+	close(map_fd);
+	return err;
+}
+
+/*
+ * In LLVM the .jumptables section contains jump tables entries relative to the
+ * section start. The BPF kernel-side code expects jump table offsets relative
+ * to the beginning of the program (passed in bpf(BPF_PROG_LOAD)). This helper
+ * computes a delta to be added when creating a map.
+ */
+static int jt_adjust_off(struct bpf_program *prog, int insn_idx)
+{
+	int i;
+
+	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
+		if (insn_idx >= prog->subprogs[i].sub_insn_off)
+			return prog->subprogs[i].sub_insn_off - prog->subprogs[i].sec_insn_off;
+	}
+
+	return -prog->sec_insn_off;
+}
+
+
 /* Relocate data references within program code:
  *  - map references;
  *  - global variable references;
@@ -6239,6 +6407,21 @@ bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
 		case RELO_CORE:
 			/* will be handled by bpf_program_record_relos() */
 			break;
+		case RELO_INSN_ARRAY: {
+			int map_fd;
+
+			map_fd = create_jt_map(obj, prog, relo->sym_off, relo->sym_size,
+					       jt_adjust_off(prog, relo->insn_idx));
+			if (map_fd < 0) {
+				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
+						prog->name, i, relo->sym_off);
+				return map_fd;
+			}
+			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
+			insn->imm = map_fd;
+			insn->off = 0;
+		}
+			break;
 		default:
 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
 				prog->name, i, relo->type);
@@ -6436,6 +6619,24 @@ static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_progra
 	return 0;
 }
 
+static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
+{
+	size_t size = sizeof(main_prog->subprogs[0]);
+	int new_cnt = main_prog->subprog_cnt + 1;
+	void *tmp;
+
+	tmp = libbpf_reallocarray(main_prog->subprogs, new_cnt, size);
+	if (!tmp)
+		return -ENOMEM;
+
+	main_prog->subprogs = tmp;
+	main_prog->subprogs[new_cnt - 1].sec_insn_off = subprog->sec_insn_off;
+	main_prog->subprogs[new_cnt - 1].sub_insn_off = subprog->sub_insn_off;
+	main_prog->subprog_cnt = new_cnt;
+
+	return 0;
+}
+
 static int
 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
 				struct bpf_program *subprog)
@@ -6465,6 +6666,15 @@ bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main
 	err = append_subprog_relos(main_prog, subprog);
 	if (err)
 		return err;
+
+	/* Save subprogram offsets */
+	err = save_subprog_offsets(main_prog, subprog);
+	if (err) {
+		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
+			main_prog->name, errstr(err));
+		return err;
+	}
+
 	return 0;
 }
 
@@ -9232,6 +9442,15 @@ void bpf_object__close(struct bpf_object *obj)
 
 	zfree(&obj->arena_data);
 
+	zfree(&obj->jumptables_data);
+	obj->jumptables_data_sz = 0;
+
+	if (obj->jumptable_maps && obj->jumptable_map_cnt) {
+		for (i = 0; i < obj->jumptable_map_cnt; i++)
+			close(obj->jumptable_maps[i].fd);
+	}
+	zfree(&obj->jumptable_maps);
+
 	free(obj);
 }
 
tools/lib/bpf/libbpf_probes.c +4 -0
index 9dfbe7750f56..bccf4bb747e1 100644
@@ -364,6 +364,10 @@ static int probe_map_create(enum bpf_map_type map_type)
 	case BPF_MAP_TYPE_SOCKHASH:
 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
 		break;
+	case BPF_MAP_TYPE_INSN_ARRAY:
+		key_size	= sizeof(__u32);
+		value_size	= sizeof(struct bpf_insn_array_value);
+		break;
 	case BPF_MAP_TYPE_UNSPEC:
 	default:
 		return -EOPNOTSUPP;
tools/lib/bpf/linker.c +8 -2
index a469e5d4fee7..60dbf3edfa54 100644
@@ -28,6 +28,8 @@
 #include "str_error.h"
 
 #define BTF_EXTERN_SEC ".extern"
+#define JUMPTABLES_SEC ".jumptables"
+#define JUMPTABLES_REL_SEC ".rel.jumptables"
 
 struct src_sec {
 	const char *sec_name;
@@ -2026,6 +2028,9 @@ static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
 			obj->sym_map[src_sym_idx] = dst_sec->sec_sym_idx;
 			return 0;
 		}
+
+		if (strcmp(src_sec->sec_name, JUMPTABLES_SEC) == 0)
+			goto add_sym;
 	}
 
 	if (sym_bind == STB_LOCAL)
@@ -2272,8 +2277,9 @@ 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 {
-					pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
+				} else if (strcmp(src_sec->sec_name, JUMPTABLES_REL_SEC) != 0) {
+					pr_warn("relocation against STT_SECTION in section %s is not supported!\n",
+						src_sec->sec_name);
 					return -EINVAL;
 				}
 			}
Signature · 1 line
2.34.1
maintainer
#39 lore raw

Re: [PATCH v5 bpf-next 13/15] libbpf: support llvm-generated indirect jumps

Quoted 9 lines · Anton Protopopov

For v5 instruction set LLVM is allowed to generate indirect jumps for switch statements and for 'goto *rX' assembly. Every such a jump will be accompanied by necessary metadata, e.g. (llvm-objdump -Sr ...):

       0:       r2 = 0x0 ll
                0000000000000030:  R_BPF_64_64  BPF.JT.0.0

Here BPF.JT.1.0 is a symbol residing in the .jumptables section:

Quoted 8 lines
    Symbol table:
       4: 0000000000000000   240 OBJECT  GLOBAL DEFAULT     4 BPF.JT.0.0

The -bpf-min-jump-table-entries llvm option may be used to control the minimal size of a switch which will be converted to an indirect jumps.

---

I think structurally this is fine.
Left a few nitpicks below.

Quoted 26 lines
 tools/lib/bpf/libbpf.c        | 221 +++++++++++++++++++++++++++++++++-
 tools/lib/bpf/libbpf_probes.c |   4 +
 tools/lib/bpf/linker.c        |  10 +-
 3 files changed, 232 insertions(+), 3 deletions(-)
tools/lib/bpf/libbpf.c +2 -0
index 083ec3ca4813..b6fbba1a42d5 100644
@@ -192,6 +192,7 @@ static const char * const map_type_name[] = {
 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
 	[BPF_MAP_TYPE_ARENA]			= "arena",
+	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
 };
 
 static const char * const prog_type_name[] = {
@@ -373,6 +374,7 @@ enum reloc_type {
 	RELO_EXTERN_CALL,
 	RELO_SUBPROG_ADDR,
 	RELO_CORE,
+	RELO_INSN_ARRAY,
 };
 
 struct reloc_desc {

tools/lib/bpf/libbpf.c struct reloc_desc { · line 390

Quoted 7 lines
tools/lib/bpf/libbpf.c +3 -1
@@ -383,7 +385,10 @@ struct reloc_desc {
 		struct {
 			int map_idx;
 			int sym_off;
-			int ext_idx;
+			union {
+				int ext_idx;
+				int sym_size;

Nit: maybe add a comment, stating when each alternative is active?

Quoted 17 lines
tools/lib/bpf/libbpf.c +6 -0
+			};
 		};
 	};
 };
@@ -425,6 +430,11 @@ struct bpf_sec_def {
 	libbpf_prog_attach_fn_t prog_attach_fn;
 };
 
+struct bpf_light_subprog {
+	__u32 sec_insn_off;
+	__u32 sub_insn_off;
+};
+
 /*
  * bpf_prog should be a better name but it has been used in
  * linux/filter.h.

tools/lib/bpf/libbpf.c struct bpf_program { · line 513

Quoted 6 lines
tools/lib/bpf/libbpf.c +3 -0
@@ -498,6 +508,9 @@ struct bpf_program {
 	__u32 line_info_cnt;
 	__u32 prog_flags;
 	__u8  hash[SHA256_DIGEST_LENGTH];
+
+	struct bpf_light_subprog *subprogs;
+	__u32 subprog_cnt;

Just to clarify: this cannot be an array of bpf_program pointers, because bpf_object__append_subprog_code() mutates subprog->sub_insn_off between bpf_object__reloc_code() and bpf_object__relocate_data() calls, right?

Quoted 37 lines
tools/lib/bpf/libbpf.c +12 -0
 };
 
 struct bpf_struct_ops {
@@ -527,6 +540,7 @@ struct bpf_struct_ops {
 #define STRUCT_OPS_SEC ".struct_ops"
 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
 #define ARENA_SEC ".addr_space.1"
+#define JUMPTABLES_SEC ".jumptables"
 
 enum libbpf_map_type {
 	LIBBPF_MAP_UNSPEC,
@@ -671,6 +685,7 @@ struct elf_state {
 	int symbols_shndx;
 	bool has_st_ops;
 	int arena_data_shndx;
+	int jumptables_data_shndx;
 };
 
 struct usdt_manager;
@@ -742,6 +757,16 @@ struct bpf_object {
 	void *arena_data;
 	size_t arena_data_sz;
 
+	void *jumptables_data;
+	size_t jumptables_data_sz;
+
+	struct {
+		struct bpf_program *prog;
+		int off;
+		int fd;
+	} *jumptable_maps;
+	size_t jumptable_map_cnt;
+
 	struct kern_feature_cache *feat_cache;
 	char *token_path;
 	int token_fd;

tools/lib/bpf/libbpf.c void bpf_program__unload(struct bpf_program *prog) · line 796

Quoted 4 lines
tools/lib/bpf/libbpf.c +1 -0
@@ -768,6 +793,7 @@ void bpf_program__unload(struct bpf_program *prog)
 
 	zfree(&prog->func_info);
 	zfree(&prog->line_info);
+	zfree(&prog->subprogs);

Maybe move this to bpf_object__free_relocs()? subprogs are only needed during relocation resolution, and free_relocs() is called from bpf_object__load_progs().

Quoted 59 lines
tools/lib/bpf/libbpf.c +38 -0
 }
 
 static void bpf_program__exit(struct bpf_program *prog)
@@ -3946,6 +3972,13 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
 			} else if (strcmp(name, ARENA_SEC) == 0) {
 				obj->efile.arena_data = data;
 				obj->efile.arena_data_shndx = idx;
+			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
+				obj->jumptables_data = malloc(data->d_size);
+				if (!obj->jumptables_data)
+					return -ENOMEM;
+				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
+				obj->jumptables_data_sz = data->d_size;
+				obj->efile.jumptables_data_shndx = idx;
 			} else {
 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
 					idx, name);
@@ -4638,6 +4671,16 @@ static int bpf_program__record_reloc(struct bpf_program *prog,
 		return 0;
 	}
 
+	/* jump table data relocation */
+	if (shdr_idx == obj->efile.jumptables_data_shndx) {
+		reloc_desc->type = RELO_INSN_ARRAY;
+		reloc_desc->insn_idx = insn_idx;
+		reloc_desc->map_idx = -1;
+		reloc_desc->sym_off = sym->st_value;
+		reloc_desc->sym_size = sym->st_size;
+		return 0;
+	}
+
 	/* generic map reference relocation */
 	if (type == LIBBPF_MAP_UNSPEC) {
 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
@@ -6148,6 +6191,131 @@ static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
 }
 
+static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, int off)
+{
+	size_t i;
+
+	for (i = 0; i < obj->jumptable_map_cnt; i++) {
+		/*
+		 * This might happen that same offset is used for two different
+		 * programs (as jump tables can be the same). However, for
+		 * different programs different maps should be created.
+		 */
+		if (obj->jumptable_maps[i].off == off &&
+		    obj->jumptable_maps[i].prog == prog)
+			return obj->jumptable_maps[i].fd;
+	}
+
+	return -ENOENT;
+}
+
+static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, int off, int map_fd)
+{
+	size_t new_cnt = obj->jumptable_map_cnt + 1;

tools/lib/bpf/libbpf.c static void poison_kfunc_call(struct bpf_program *prog, int relo_idx, · line 6224

Quoted 10 lines
tools/lib/bpf/libbpf.c +10 -0
+	size_t size = sizeof(obj->jumptable_maps[0]);
+	void *tmp;
+
+	tmp = libbpf_reallocarray(obj->jumptable_maps, new_cnt, size);
+	if (!tmp)
+		return -ENOMEM;
+
+	obj->jumptable_maps = tmp;
+	obj->jumptable_maps[new_cnt - 1].prog = prog;
+	obj->jumptable_maps[new_cnt - 1].off = off;
                                         ^^^

Nit: Could you please rename this and corresponding
parameters of {create,add}_jt_map to sym_off?

Quoted 27 lines
tools/lib/bpf/libbpf.c +27 -0
+	obj->jumptable_maps[new_cnt - 1].fd = map_fd;
+	obj->jumptable_map_cnt = new_cnt;
+
+	return 0;
+}
+
+static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog,
+			 int off, int size, int adjust_off)
+{
+	const __u32 value_size = sizeof(struct bpf_insn_array_value);
+	const __u32 max_entries = size / value_size;
+	struct bpf_insn_array_value val = {};
+	int map_fd, err;
+	__u64 xlated_off;
+	__u64 *jt;
+	__u32 i;
+
+	map_fd = find_jt_map(obj, prog, off);
+	if (map_fd >= 0)
+		return map_fd;
+
+	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
+				4, value_size, max_entries, NULL);
+	if (map_fd < 0)
+		return map_fd;
+
+	if (!obj->jumptables_data) {

tools/lib/bpf/libbpf.c static void poison_kfunc_call(struct bpf_program *prog, int relo_idx, · line 6261

Quoted 10 lines
tools/lib/bpf/libbpf.c +10 -0
+		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
+		err = -EINVAL;
+		goto err_close;
+	}
+	if (off + size > obj->jumptables_data_sz) {
+		pr_warn("jumptables_data size is %zd, trying to access %d\n",
+			obj->jumptables_data_sz, off + size);
+		err = -EINVAL;
+		goto err_close;
+	}

Maybe also check that size and off are 8-bytes aligned?

Quoted 45 lines
tools/lib/bpf/libbpf.c +45 -0
+
+	jt = (__u64 *)(obj->jumptables_data + off);
+	for (i = 0; i < max_entries; i++) {
+		/*
+		 * LLVM-generated jump tables contain u64 records, however
+		 * should contain values that fit in u32.
+		 * The adjust_off provided by the caller adjusts the offset to
+		 * be relative to the beginning of the main function
+		 */
+		xlated_off = jt[i]/sizeof(struct bpf_insn) + adjust_off;
+		if (xlated_off > UINT32_MAX) {
+			pr_warn("invalid jump table value %llx at offset %d (adjust_off %d)\n",
+				jt[i], off + i, adjust_off);
+			err = -EINVAL;
+			goto err_close;
+		}
+
+		val.xlated_off = xlated_off;
+		err = bpf_map_update_elem(map_fd, &i, &val, 0);
+		if (err)
+			goto err_close;
+	}
+
+	err = bpf_map_freeze(map_fd);
+	if (err)
+		goto err_close;
+
+	err = add_jt_map(obj, prog, off, map_fd);
+	if (err)
+		goto err_close;
+
+	return map_fd;
+
+err_close:
+	close(map_fd);
+	return err;
+}
+
+/*
+ * In LLVM the .jumptables section contains jump tables entries relative to the
+ * section start. The BPF kernel-side code expects jump table offsets relative
+ * to the beginning of the program (passed in bpf(BPF_PROG_LOAD)). This helper
+ * computes a delta to be added when creating a map.
+ */
+static int jt_adjust_off(struct bpf_program *prog, int insn_idx)

tools/lib/bpf/libbpf.c static void poison_kfunc_call(struct bpf_program *prog, int relo_idx, · line 6316

Quoted 10 lines
tools/lib/bpf/libbpf.c +10 -0
+{
+	int i;
+
+	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
+		if (insn_idx >= prog->subprogs[i].sub_insn_off)
+			return prog->subprogs[i].sub_insn_off - prog->subprogs[i].sec_insn_off;
+	}
+
+	return -prog->sec_insn_off;
+}

Nit: the docstring for sub_insn_off says that it is 0 for main sub-program.

     meaning that last return is unreachable. I'd rewrite the above as follows:

       static int jt_adjust_off(struct bpf_program *prog, int insn_idx)
       {
         int i;

         for (i = prog->subprog_cnt - 1; i >= 0; i--)
                if (insn_idx >= prog->subprogs[i].sub_insn_off)
                        break;

         return prog->subprogs[i].sub_insn_off - prog->subprogs[i].sec_insn_off;
       }

    Or rename this thing to find_subprog_idx(), pass relo object into
    create_jt_map(), call find_subprog_idx() there, and do the following:

      xlated_off = jt[i] / sizeof(struct bpf_insn);
      /* make xlated_off relative to subprogram start */
      xlated_off -= prog->subprogs[subprog_idx].sec_insn_off;
      /* make xlated_off relative to main subprogram start */
      xlated_off += prog->subprogs[subprog_idx].sub_insn_off;

I think it's easier to grasp what this adjustment does this way.

Quoted 134 lines
tools/lib/bpf/libbpf.c +53 -0
+
+
 /* Relocate data references within program code:
  *  - map references;
  *  - global variable references;
@@ -6239,6 +6407,21 @@ bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
 		case RELO_CORE:
 			/* will be handled by bpf_program_record_relos() */
 			break;
+		case RELO_INSN_ARRAY: {
+			int map_fd;
+
+			map_fd = create_jt_map(obj, prog, relo->sym_off, relo->sym_size,
+					       jt_adjust_off(prog, relo->insn_idx));
+			if (map_fd < 0) {
+				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
+						prog->name, i, relo->sym_off);
+				return map_fd;
+			}
+			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
+			insn->imm = map_fd;
+			insn->off = 0;
+		}
+			break;
 		default:
 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
 				prog->name, i, relo->type);
@@ -6436,6 +6619,24 @@ static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_progra
 	return 0;
 }
 
+static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
+{
+	size_t size = sizeof(main_prog->subprogs[0]);
+	int new_cnt = main_prog->subprog_cnt + 1;
+	void *tmp;
+
+	tmp = libbpf_reallocarray(main_prog->subprogs, new_cnt, size);
+	if (!tmp)
+		return -ENOMEM;
+
+	main_prog->subprogs = tmp;
+	main_prog->subprogs[new_cnt - 1].sec_insn_off = subprog->sec_insn_off;
+	main_prog->subprogs[new_cnt - 1].sub_insn_off = subprog->sub_insn_off;
+	main_prog->subprog_cnt = new_cnt;
+
+	return 0;
+}
+
 static int
 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
 				struct bpf_program *subprog)
@@ -6465,6 +6666,15 @@ bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main
 	err = append_subprog_relos(main_prog, subprog);
 	if (err)
 		return err;
+
+	/* Save subprogram offsets */
+	err = save_subprog_offsets(main_prog, subprog);
+	if (err) {
+		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
+			main_prog->name, errstr(err));
+		return err;
+	}
+
 	return 0;
 }
 
@@ -9232,6 +9442,15 @@ void bpf_object__close(struct bpf_object *obj)
 
 	zfree(&obj->arena_data);
 
+	zfree(&obj->jumptables_data);
+	obj->jumptables_data_sz = 0;
+
+	if (obj->jumptable_maps && obj->jumptable_map_cnt) {
+		for (i = 0; i < obj->jumptable_map_cnt; i++)
+			close(obj->jumptable_maps[i].fd);
+	}
+	zfree(&obj->jumptable_maps);
+
 	free(obj);
 }
 
tools/lib/bpf/libbpf_probes.c +4 -0
index 9dfbe7750f56..bccf4bb747e1 100644
@@ -364,6 +364,10 @@ static int probe_map_create(enum bpf_map_type map_type)
 	case BPF_MAP_TYPE_SOCKHASH:
 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
 		break;
+	case BPF_MAP_TYPE_INSN_ARRAY:
+		key_size	= sizeof(__u32);
+		value_size	= sizeof(struct bpf_insn_array_value);
+		break;
 	case BPF_MAP_TYPE_UNSPEC:
 	default:
 		return -EOPNOTSUPP;
tools/lib/bpf/linker.c +8 -2
index a469e5d4fee7..60dbf3edfa54 100644
@@ -28,6 +28,8 @@
 #include "str_error.h"
 
 #define BTF_EXTERN_SEC ".extern"
+#define JUMPTABLES_SEC ".jumptables"
+#define JUMPTABLES_REL_SEC ".rel.jumptables"
 
 struct src_sec {
 	const char *sec_name;
@@ -2026,6 +2028,9 @@ static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
 			obj->sym_map[src_sym_idx] = dst_sec->sec_sym_idx;
 			return 0;
 		}
+
+		if (strcmp(src_sec->sec_name, JUMPTABLES_SEC) == 0)
+			goto add_sym;
 	}
 
 	if (sym_bind == STB_LOCAL)
@@ -2272,8 +2277,9 @@ 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 {
-					pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
+				} else if (strcmp(src_sec->sec_name, JUMPTABLES_REL_SEC) != 0) {
+					pr_warn("relocation against STT_SECTION in section %s is not supported!\n",
+						src_sec->sec_name);
 					return -EINVAL;
 				}
 			}
#40 lore raw

Re: [PATCH v5 bpf-next 13/15] libbpf: support llvm-generated indirect jumps

Quoted 46 lines · Eduard Zingerman
Quoted 9 lines · Anton Protopopov

For v5 instruction set LLVM is allowed to generate indirect jumps for switch statements and for 'goto *rX' assembly. Every such a jump will be accompanied by necessary metadata, e.g. (llvm-objdump -Sr ...):

       0:       r2 = 0x0 ll
                0000000000000030:  R_BPF_64_64  BPF.JT.0.0

Here BPF.JT.1.0 is a symbol residing in the .jumptables section:

Quoted 8 lines
    Symbol table:
       4: 0000000000000000   240 OBJECT  GLOBAL DEFAULT     4 BPF.JT.0.0

The -bpf-min-jump-table-entries llvm option may be used to control the minimal size of a switch which will be converted to an indirect jumps.

---

I think structurally this is fine.
Left a few nitpicks below.

Quoted 24 lines
 tools/lib/bpf/libbpf.c        | 221 +++++++++++++++++++++++++++++++++-
 tools/lib/bpf/libbpf_probes.c |   4 +
 tools/lib/bpf/linker.c        |  10 +-
 3 files changed, 232 insertions(+), 3 deletions(-)
tools/lib/bpf/libbpf.c +2 -0
index 083ec3ca4813..b6fbba1a42d5 100644
@@ -192,6 +192,7 @@ static const char * const map_type_name[] = {
 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
 	[BPF_MAP_TYPE_ARENA]			= "arena",
+	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
 };
 
 static const char * const prog_type_name[] = {
@@ -373,6 +374,7 @@ enum reloc_type {
 	RELO_EXTERN_CALL,
 	RELO_SUBPROG_ADDR,
 	RELO_CORE,
+	RELO_INSN_ARRAY,
 };
 
Quoted 11 lines

tools/lib/bpf/libbpf.c struct reloc_desc { · line 390

Quoted 9 lines
tools/lib/bpf/libbpf.c +3 -1
 struct reloc_desc {
@@ -383,7 +385,10 @@ struct reloc_desc {
 		struct {
 			int map_idx;
 			int sym_off;
-			int ext_idx;
+			union {
+				int ext_idx;
+				int sym_size;

Nit: maybe add a comment, stating when each alternative is active?

Sure.

Quoted 20 lines
Quoted 20 lines
tools/lib/bpf/libbpf.c +6 -0
+			};
 		};
 	};
 };
@@ -425,6 +430,11 @@ struct bpf_sec_def {
 	libbpf_prog_attach_fn_t prog_attach_fn;
 };
 
+struct bpf_light_subprog {
+	__u32 sec_insn_off;
+	__u32 sub_insn_off;
+};
+
 /*
  * bpf_prog should be a better name but it has been used in
  * linux/filter.h.
@@ -498,6 +508,9 @@ struct bpf_program {
 	__u32 line_info_cnt;
 	__u32 prog_flags;
 	__u8  hash[SHA256_DIGEST_LENGTH];
Quoted 8 lines

tools/lib/bpf/libbpf.c struct bpf_program { · line 513

Quoted 3 lines
tools/lib/bpf/libbpf.c +3 -0
+
+	struct bpf_light_subprog *subprogs;
+	__u32 subprog_cnt;

Just to clarify: this cannot be an array of bpf_program pointers, because bpf_object__append_subprog_code() mutates subprog->sub_insn_off between bpf_object__reloc_code() and bpf_object__relocate_data() calls, right?

Yes, it's private (and just the data we need, thus "light")

Quoted 38 lines
Quoted 38 lines
tools/lib/bpf/libbpf.c +12 -0
 };
 
 struct bpf_struct_ops {
@@ -527,6 +540,7 @@ struct bpf_struct_ops {
 #define STRUCT_OPS_SEC ".struct_ops"
 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
 #define ARENA_SEC ".addr_space.1"
+#define JUMPTABLES_SEC ".jumptables"
 
 enum libbpf_map_type {
 	LIBBPF_MAP_UNSPEC,
@@ -671,6 +685,7 @@ struct elf_state {
 	int symbols_shndx;
 	bool has_st_ops;
 	int arena_data_shndx;
+	int jumptables_data_shndx;
 };
 
 struct usdt_manager;
@@ -742,6 +757,16 @@ struct bpf_object {
 	void *arena_data;
 	size_t arena_data_sz;
 
+	void *jumptables_data;
+	size_t jumptables_data_sz;
+
+	struct {
+		struct bpf_program *prog;
+		int off;
+		int fd;
+	} *jumptable_maps;
+	size_t jumptable_map_cnt;
+
 	struct kern_feature_cache *feat_cache;
 	char *token_path;
 	int token_fd;
@@ -768,6 +793,7 @@ void bpf_program__unload(struct bpf_program *prog)
 
Quoted 7 lines

tools/lib/bpf/libbpf.c void bpf_program__unload(struct bpf_program *prog) · line 796

Quoted 3 lines
tools/lib/bpf/libbpf.c +1 -0
 	zfree(&prog->func_info);
 	zfree(&prog->line_info);
+	zfree(&prog->subprogs);

Maybe move this to bpf_object__free_relocs()? subprogs are only needed during relocation resolution, and free_relocs() is called from bpf_object__load_progs().

I've put it here because it simplifies error paths. Say, if realloc for subprogs failed, then bpf_object__free_relocs() will not be called, but bpf_program__unload() will be.

Quoted 70 lines
Quoted 59 lines
tools/lib/bpf/libbpf.c +38 -0
 }
 
 static void bpf_program__exit(struct bpf_program *prog)
@@ -3946,6 +3972,13 @@ static int bpf_object__elf_collect(struct bpf_object *obj)
 			} else if (strcmp(name, ARENA_SEC) == 0) {
 				obj->efile.arena_data = data;
 				obj->efile.arena_data_shndx = idx;
+			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
+				obj->jumptables_data = malloc(data->d_size);
+				if (!obj->jumptables_data)
+					return -ENOMEM;
+				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
+				obj->jumptables_data_sz = data->d_size;
+				obj->efile.jumptables_data_shndx = idx;
 			} else {
 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
 					idx, name);
@@ -4638,6 +4671,16 @@ static int bpf_program__record_reloc(struct bpf_program *prog,
 		return 0;
 	}
 
+	/* jump table data relocation */
+	if (shdr_idx == obj->efile.jumptables_data_shndx) {
+		reloc_desc->type = RELO_INSN_ARRAY;
+		reloc_desc->insn_idx = insn_idx;
+		reloc_desc->map_idx = -1;
+		reloc_desc->sym_off = sym->st_value;
+		reloc_desc->sym_size = sym->st_size;
+		return 0;
+	}
+
 	/* generic map reference relocation */
 	if (type == LIBBPF_MAP_UNSPEC) {
 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
@@ -6148,6 +6191,131 @@ static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
 }
 
+static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, int off)
+{
+	size_t i;
+
+	for (i = 0; i < obj->jumptable_map_cnt; i++) {
+		/*
+		 * This might happen that same offset is used for two different
+		 * programs (as jump tables can be the same). However, for
+		 * different programs different maps should be created.
+		 */
+		if (obj->jumptable_maps[i].off == off &&
+		    obj->jumptable_maps[i].prog == prog)
+			return obj->jumptable_maps[i].fd;
+	}
+
+	return -ENOENT;
+}
+
+static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, int off, int map_fd)
+{
+	size_t new_cnt = obj->jumptable_map_cnt + 1;

tools/lib/bpf/libbpf.c static void poison_kfunc_call(struct bpf_program *prog, int relo_idx, · line 6224

Quoted 10 lines
tools/lib/bpf/libbpf.c +10 -0
+	size_t size = sizeof(obj->jumptable_maps[0]);
+	void *tmp;
+
+	tmp = libbpf_reallocarray(obj->jumptable_maps, new_cnt, size);
+	if (!tmp)
+		return -ENOMEM;
+
+	obj->jumptable_maps = tmp;
+	obj->jumptable_maps[new_cnt - 1].prog = prog;
+	obj->jumptable_maps[new_cnt - 1].off = off;
                                         ^^^
Quoted 2 lines

Nit: Could you please rename this and corresponding
parameters of {create,add}_jt_map to sym_off?

Yes, sure.

Quoted 31 lines
Quoted 31 lines
tools/lib/bpf/libbpf.c +31 -0
+	obj->jumptable_maps[new_cnt - 1].fd = map_fd;
+	obj->jumptable_map_cnt = new_cnt;
+
+	return 0;
+}
+
+static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog,
+			 int off, int size, int adjust_off)
+{
+	const __u32 value_size = sizeof(struct bpf_insn_array_value);
+	const __u32 max_entries = size / value_size;
+	struct bpf_insn_array_value val = {};
+	int map_fd, err;
+	__u64 xlated_off;
+	__u64 *jt;
+	__u32 i;
+
+	map_fd = find_jt_map(obj, prog, off);
+	if (map_fd >= 0)
+		return map_fd;
+
+	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
+				4, value_size, max_entries, NULL);
+	if (map_fd < 0)
+		return map_fd;
+
+	if (!obj->jumptables_data) {
+		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
+		err = -EINVAL;
+		goto err_close;
+	}
Quoted 8 lines

tools/lib/bpf/libbpf.c static void poison_kfunc_call(struct bpf_program *prog, int relo_idx, · line 6261

Quoted 6 lines
tools/lib/bpf/libbpf.c +6 -0
+	if (off + size > obj->jumptables_data_sz) {
+		pr_warn("jumptables_data size is %zd, trying to access %d\n",
+			obj->jumptables_data_sz, off + size);
+		err = -EINVAL;
+		goto err_close;
+	}

Maybe also check that size and off are 8-bytes aligned?

Will do, thanks.

Quoted 49 lines
Quoted 49 lines
tools/lib/bpf/libbpf.c +49 -0
+
+	jt = (__u64 *)(obj->jumptables_data + off);
+	for (i = 0; i < max_entries; i++) {
+		/*
+		 * LLVM-generated jump tables contain u64 records, however
+		 * should contain values that fit in u32.
+		 * The adjust_off provided by the caller adjusts the offset to
+		 * be relative to the beginning of the main function
+		 */
+		xlated_off = jt[i]/sizeof(struct bpf_insn) + adjust_off;
+		if (xlated_off > UINT32_MAX) {
+			pr_warn("invalid jump table value %llx at offset %d (adjust_off %d)\n",
+				jt[i], off + i, adjust_off);
+			err = -EINVAL;
+			goto err_close;
+		}
+
+		val.xlated_off = xlated_off;
+		err = bpf_map_update_elem(map_fd, &i, &val, 0);
+		if (err)
+			goto err_close;
+	}
+
+	err = bpf_map_freeze(map_fd);
+	if (err)
+		goto err_close;
+
+	err = add_jt_map(obj, prog, off, map_fd);
+	if (err)
+		goto err_close;
+
+	return map_fd;
+
+err_close:
+	close(map_fd);
+	return err;
+}
+
+/*
+ * In LLVM the .jumptables section contains jump tables entries relative to the
+ * section start. The BPF kernel-side code expects jump table offsets relative
+ * to the beginning of the program (passed in bpf(BPF_PROG_LOAD)). This helper
+ * computes a delta to be added when creating a map.
+ */
+static int jt_adjust_off(struct bpf_program *prog, int insn_idx)
+{
+	int i;
+
+	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
Quoted 8 lines

tools/lib/bpf/libbpf.c static void poison_kfunc_call(struct bpf_program *prog, int relo_idx, · line 6316

Quoted 6 lines
tools/lib/bpf/libbpf.c +6 -0
+		if (insn_idx >= prog->subprogs[i].sub_insn_off)
+			return prog->subprogs[i].sub_insn_off - prog->subprogs[i].sec_insn_off;
+	}
+
+	return -prog->sec_insn_off;
+}

Nit: the docstring for sub_insn_off says that it is 0 for main sub-program.

But this is not sub in the last line, it's sec?

Anyway, I got it that this is still not super developer-friendly (Andrii also had questions around here). I will take another look, thanks for the suggestions below.

Quoted 158 lines
     meaning that last return is unreachable. I'd rewrite the above as follows:

       static int jt_adjust_off(struct bpf_program *prog, int insn_idx)
       {
         int i;

         for (i = prog->subprog_cnt - 1; i >= 0; i--)
                if (insn_idx >= prog->subprogs[i].sub_insn_off)
                        break;

         return prog->subprogs[i].sub_insn_off - prog->subprogs[i].sec_insn_off;
       }

    Or rename this thing to find_subprog_idx(), pass relo object into
    create_jt_map(), call find_subprog_idx() there, and do the following:

      xlated_off = jt[i] / sizeof(struct bpf_insn);
      /* make xlated_off relative to subprogram start */
      xlated_off -= prog->subprogs[subprog_idx].sec_insn_off;
      /* make xlated_off relative to main subprogram start */
      xlated_off += prog->subprogs[subprog_idx].sub_insn_off;

I think it's easier to grasp what this adjustment does this way.

Quoted 134 lines
tools/lib/bpf/libbpf.c +53 -0
+
+
 /* Relocate data references within program code:
  *  - map references;
  *  - global variable references;
@@ -6239,6 +6407,21 @@ bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
 		case RELO_CORE:
 			/* will be handled by bpf_program_record_relos() */
 			break;
+		case RELO_INSN_ARRAY: {
+			int map_fd;
+
+			map_fd = create_jt_map(obj, prog, relo->sym_off, relo->sym_size,
+					       jt_adjust_off(prog, relo->insn_idx));
+			if (map_fd < 0) {
+				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
+						prog->name, i, relo->sym_off);
+				return map_fd;
+			}
+			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
+			insn->imm = map_fd;
+			insn->off = 0;
+		}
+			break;
 		default:
 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
 				prog->name, i, relo->type);
@@ -6436,6 +6619,24 @@ static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_progra
 	return 0;
 }
 
+static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
+{
+	size_t size = sizeof(main_prog->subprogs[0]);
+	int new_cnt = main_prog->subprog_cnt + 1;
+	void *tmp;
+
+	tmp = libbpf_reallocarray(main_prog->subprogs, new_cnt, size);
+	if (!tmp)
+		return -ENOMEM;
+
+	main_prog->subprogs = tmp;
+	main_prog->subprogs[new_cnt - 1].sec_insn_off = subprog->sec_insn_off;
+	main_prog->subprogs[new_cnt - 1].sub_insn_off = subprog->sub_insn_off;
+	main_prog->subprog_cnt = new_cnt;
+
+	return 0;
+}
+
 static int
 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
 				struct bpf_program *subprog)
@@ -6465,6 +6666,15 @@ bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main
 	err = append_subprog_relos(main_prog, subprog);
 	if (err)
 		return err;
+
+	/* Save subprogram offsets */
+	err = save_subprog_offsets(main_prog, subprog);
+	if (err) {
+		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
+			main_prog->name, errstr(err));
+		return err;
+	}
+
 	return 0;
 }
 
@@ -9232,6 +9442,15 @@ void bpf_object__close(struct bpf_object *obj)
 
 	zfree(&obj->arena_data);
 
+	zfree(&obj->jumptables_data);
+	obj->jumptables_data_sz = 0;
+
+	if (obj->jumptable_maps && obj->jumptable_map_cnt) {
+		for (i = 0; i < obj->jumptable_map_cnt; i++)
+			close(obj->jumptable_maps[i].fd);
+	}
+	zfree(&obj->jumptable_maps);
+
 	free(obj);
 }
 
tools/lib/bpf/libbpf_probes.c +4 -0
index 9dfbe7750f56..bccf4bb747e1 100644
@@ -364,6 +364,10 @@ static int probe_map_create(enum bpf_map_type map_type)
 	case BPF_MAP_TYPE_SOCKHASH:
 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
 		break;
+	case BPF_MAP_TYPE_INSN_ARRAY:
+		key_size	= sizeof(__u32);
+		value_size	= sizeof(struct bpf_insn_array_value);
+		break;
 	case BPF_MAP_TYPE_UNSPEC:
 	default:
 		return -EOPNOTSUPP;
tools/lib/bpf/linker.c +8 -2
index a469e5d4fee7..60dbf3edfa54 100644
@@ -28,6 +28,8 @@
 #include "str_error.h"
 
 #define BTF_EXTERN_SEC ".extern"
+#define JUMPTABLES_SEC ".jumptables"
+#define JUMPTABLES_REL_SEC ".rel.jumptables"
 
 struct src_sec {
 	const char *sec_name;
@@ -2026,6 +2028,9 @@ static int linker_append_elf_sym(struct bpf_linker *linker, struct src_obj *obj,
 			obj->sym_map[src_sym_idx] = dst_sec->sec_sym_idx;
 			return 0;
 		}
+
+		if (strcmp(src_sec->sec_name, JUMPTABLES_SEC) == 0)
+			goto add_sym;
 	}
 
 	if (sym_bind == STB_LOCAL)
@@ -2272,8 +2277,9 @@ 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 {
-					pr_warn("relocation against STT_SECTION in non-exec section is not supported!\n");
+				} else if (strcmp(src_sec->sec_name, JUMPTABLES_REL_SEC) != 0) {
+					pr_warn("relocation against STT_SECTION in section %s is not supported!\n",
+						src_sec->sec_name);
 					return -EINVAL;
 				}
 			}
reviewer
#41 lore raw

Re: [PATCH v5 bpf-next 13/15] libbpf: support llvm-generated indirect jumps

In reply to Anton Protopopov
Quoted 1 line · Anton Protopopov

For v5 instruction set LLVM is allowed to generate indirect jumps for

FYI. The llvm jump table support is still cpu v4.

Quoted 15 lines

switch statements and for 'goto *rX' assembly. Every such a jump will be accompanied by necessary metadata, e.g. (llvm-objdump -Sr ...):

        0:       r2 = 0x0 ll
                 0000000000000030:  R_BPF_64_64  BPF.JT.0.0

Here BPF.JT.1.0 is a symbol residing in the .jumptables section:

     Symbol table:
        4: 0000000000000000   240 OBJECT  GLOBAL DEFAULT     4 BPF.JT.0.0

The -bpf-min-jump-table-entries llvm option may be used to control the minimal size of a switch which will be converted to an indirect jumps.

[...]

#42 lore raw

Re: [PATCH v5 bpf-next 13/15] libbpf: support llvm-generated indirect jumps

Quoted 6 lines · Yonghong Song
Quoted 1 line · Anton Protopopov

For v5 instruction set LLVM is allowed to generate indirect jumps for

FYI. The llvm jump table support is still cpu v4.

Yes, thanks! I've fixed the message.

Quoted 18 lines
Quoted 15 lines

switch statements and for 'goto *rX' assembly. Every such a jump will be accompanied by necessary metadata, e.g. (llvm-objdump -Sr ...):

        0:       r2 = 0x0 ll
                 0000000000000030:  R_BPF_64_64  BPF.JT.0.0

Here BPF.JT.1.0 is a symbol residing in the .jumptables section:

     Symbol table:
        4: 0000000000000000   240 OBJECT  GLOBAL DEFAULT     4 BPF.JT.0.0

The -bpf-min-jump-table-entries llvm option may be used to control the minimal size of a switch which will be converted to an indirect jumps.

[...]

#43 lore raw

PATCH v5 14/15 bpftool: Recognize insn_array map type

In reply to Anton Protopopov

Teach bpftool to recognize instruction array map type.

---
 tools/bpf/bpftool/Documentation/bpftool-map.rst | 3 ++-
 tools/bpf/bpftool/map.c                         | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)
tools/bpf/bpftool/Documentation/bpftool-map.rst +2 -1
index 252e4c538edb..1af3305ea2b2 100644
@@ -55,7 +55,8 @@ MAP COMMANDS
 |     | **devmap** | **devmap_hash** | **sockmap** | **cpumap** | **xskmap** | **sockhash**
 |     | **cgroup_storage** | **reuseport_sockarray** | **percpu_cgroup_storage**
 |     | **queue** | **stack** | **sk_storage** | **struct_ops** | **ringbuf** | **inode_storage**
-|     | **task_storage** | **bloom_filter** | **user_ringbuf** | **cgrp_storage** | **arena** }
+|     | **task_storage** | **bloom_filter** | **user_ringbuf** | **cgrp_storage** | **arena**
+|     | **insn_array** }
 
 DESCRIPTION
 ===========
tools/bpf/bpftool/map.c +2 -1
index c9de44a45778..7ebf7dbcfba4 100644
@@ -1477,7 +1477,8 @@ static int do_help(int argc, char **argv)
 		"                 devmap | devmap_hash | sockmap | cpumap | xskmap | sockhash |\n"
 		"                 cgroup_storage | reuseport_sockarray | percpu_cgroup_storage |\n"
 		"                 queue | stack | sk_storage | struct_ops | ringbuf | inode_storage |\n"
-		"                 task_storage | bloom_filter | user_ringbuf | cgrp_storage | arena }\n"
+		"                 task_storage | bloom_filter | user_ringbuf | cgrp_storage | arena |\n"
+		"                 insn_array }\n"
 		"       " HELP_SPEC_OPTIONS " |\n"
 		"                    {-f|--bpffs} | {-n|--nomount} }\n"
 		"",
Signature · 1 line
2.34.1
#44 lore raw

PATCH v5 15/15 selftests/bpf: add selftests for indirect jumps

In reply to Anton Protopopov

Add selftests for indirect jumps. All the indirect jumps are generated from C switch statements, so, if compiled by a compiler which doesn't support indirect jumps, then should pass as well.

---
 tools/testing/selftests/bpf/Makefile          |   4 +-
 .../selftests/bpf/prog_tests/bpf_gotox.c      | 177 ++++++++
 tools/testing/selftests/bpf/progs/bpf_gotox.c | 411 ++++++++++++++++++
 3 files changed, 591 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/bpf_gotox.c
 create mode 100644 tools/testing/selftests/bpf/progs/bpf_gotox.c
tools/testing/selftests/bpf/Makefile +3 -1
index f00587d4ede6..513464ad1d39 100644
@@ -453,7 +453,9 @@ BPF_CFLAGS = -g -Wall -Werror -D__TARGET_ARCH_$(SRCARCH) $(MENDIAN)	\
 	     -I$(abspath $(OUTPUT)/../usr/include)			\
 	     -std=gnu11		 					\
 	     -fno-strict-aliasing 					\
-	     -Wno-compare-distinct-pointer-types
+	     -Wno-compare-distinct-pointer-types			\
+	     -Wno-initializer-overrides					\
+	     #
 # TODO: enable me -Wsign-compare
 
 CLANG_CFLAGS = $(CLANG_SYS_INCLUDES)
tools/testing/selftests/bpf/prog_tests/bpf_gotox.c new file +177 -0

177 lines not on this page · raw message

tools/testing/selftests/bpf/progs/bpf_gotox.c new file +411 -0

411 lines not on this page · raw message

Signature · 1 line
2.34.1
maintainer
#45 lore raw

Re: [PATCH v5 bpf-next 15/15] selftests/bpf: add selftests for indirect jumps

Quoted 6 lines · Anton Protopopov

Add selftests for indirect jumps. All the indirect jumps are generated from C switch statements, so, if compiled by a compiler which doesn't support indirect jumps, then should pass as well.

---

Could you please add proper unit tests in the next revision? The way I commented in v3:
https://lore.kernel.org/bpf/[email protected]/

[...]

#46 lore raw

Re: [PATCH v5 bpf-next 15/15] selftests/bpf: add selftests for indirect jumps

Quoted 5 lines · Eduard Zingerman
Quoted 4 lines · Anton Protopopov

Add selftests for indirect jumps. All the indirect jumps are generated from C switch statements, so, if compiled by a compiler which doesn't support indirect jumps, then should pass as well.

Quoted 8 lines
Quoted 2 lines

---

Could you please add proper unit tests in the next revision? The way I commented in v3:
https://lore.kernel.org/bpf/[email protected]/

[...]

Yes, I plan to split tests into unit tests and libbpf tests, and aslo add tests to compute_live_registers. (Just, as I have mentioned in the cover letter, I wanted to see that kernel part doesn't change too much before starting to write unit tests.)

maintainer
#47 lore raw

Re: [PATCH v5 bpf-next 15/15] selftests/bpf: add selftests for indirect jumps

Quoted 13 lines · Anton Protopopov
Quoted 12 lines · Eduard Zingerman
Quoted 6 lines · Anton Protopopov

Add selftests for indirect jumps. All the indirect jumps are generated from C switch statements, so, if compiled by a compiler which doesn't support indirect jumps, then should pass as well.

---

Could you please add proper unit tests in the next revision? The way I commented in v3:
https://lore.kernel.org/bpf/[email protected]/

Quoted 6 lines
Quoted 1 line

[...]

Yes, I plan to split tests into unit tests and libbpf tests, and aslo add tests to compute_live_registers. (Just, as I have mentioned in the cover letter, I wanted to see that kernel part doesn't change too much before starting to write unit tests.)

I think kernel part is pretty solid at this point. At-least verifier part is solid for sure.