Skip to contentSkip to conversation

bpf: A lookup in an array is not NULL when the largest key is below max_entries

PATCH Applied Alexei Starovoitov 2 participants 4 messages Nov 1 – Nov 3

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

cover bpf: A lookup in an array is not NULL when the largest key is below max_entries

From: Alexei Starovoitov <[email protected]>

A lookup in an array or in a per-cpu array returns NULL only when the key is not below max_entries. The verifier knows that for a key that is a constant. Then the prog needs no NULL check, and the verifier does not examine a NULL branch that the prog cannot take.

Patch 1 does the same for a key that has a range, for example 'cpu & 3'. Patch 2 has the tests.

The counter of a loop is such a key since scalar evolution gives it one range for all iterations. The verifier rejects this loop today, and it accepted the loop before scalar evolution:

  for (i = 0; i < 64; i++) {
          key = i;
          bpf_map_lookup_elem(&array, &key)->cnt = 0;
  }

veristat, progs that load before (A) and after (B):

  progs of               progs  that change   insns
  ---------------------  -----  -----------  -------
  sched-ext/scx            493           29   -4.22%
  scx, as BPF CI has it    428           25  -11.84%
  36 builds of Cilium     5029            0
  selftests               3891            0

No verdict changes. Progs of the two sets of scx that change by more than 5%:

Program            Insns (A)  Insns (B)       Insns (DIFF)
-----------------  ---------  ---------  -----------------
flow_select_cpu       293093     145475  -147618 (-50.37%)
mlfq_running             600        333     -267 (-44.50%)
mlfq_select_cpu         7227       6293     -934 (-12.92%)
mlfq_exit_task            54         50        -4 (-7.41%)
flow_running              92         99        +7 (+7.61%)

forge_init 535 772 +237 (+44.30%)
flow_dispatch (CI) 411387 186252 -225135 (-54.73%)
flow_enqueue (CI) 19362 28793 +9431 (+48.71%)

A prog needs more insns when its key is precise now: two states with different ranges of the key are not equal.

Alexei Starovoitov (2):
bpf: A lookup in an array is not NULL when the largest key is below
max_entries
selftests/bpf: Test array lookups with a key that is not a constant

 include/linux/bpf_verifier.h                  |   2 +-
 kernel/bpf/verifier.c                         |  38 ++--
 .../bpf/progs/verifier_array_access.c         | 165 ++++++++++++++++++
 .../selftests/bpf/progs/verifier_map_in_map.c |  31 ++++
 4 files changed, 220 insertions(+), 16 deletions(-)

base-commit: a30c772627b2ef4bc715332b1b04938a914556cd

Signature · 1 line
2.55.0
#1 lore raw

PATCH 1/2 bpf: A lookup in an array is not NULL when the largest key is below max_entries

From: Alexei Starovoitov <[email protected]>

bpf_map_lookup_elem() in an array or in a per-cpu array returns NULL only when the key is not below max_entries. Since commit d2102f2f5d75 ("bpf: verifier: Support eliding map lookup nullness") the verifier knows that, but only for a key that is a constant:

  u32 key = cpu & 3;                            /* max_entries is 4 */
  bpf_map_lookup_elem(&array, &key)->cnt++;
        R0 invalid mem access 'map_value_or_null'

The counter of a loop is not a constant either. Scalar evolution gives it one range for all iterations. Thus the verifier rejects the loop below. It accepted the loop, one iteration after the other, before commit 6ccf49f79327 ("bpf: Use SCEV to widen bounded loops").

  for (i = 0; i < 64; i++) {                    /* max_entries is 64 */
          key = i;
          bpf_map_lookup_elem(&array, &key)->cnt = 0;
  }

The check does not need a constant. It needs to know that the key is below max_entries. Use umax of the register that the prog stored to the key.

The stack slot has the range of the 64-bit register. The key has only 4 bytes, but max_entries is a u32. Thus a value below max_entries fits in the key, and the helper reads the same value. All other conditions stay:
CAP_BPF, a key on the stack at a constant offset, zeros or a store of exactly 4 bytes, no BPF_F_INNER_MAP.

The verdict now depends on the range of the key. Thus mark the key as precise, as for a constant, but only when it is below max_entries. In the other case the verifier examines the prog with NULL and with a pointer, and this is correct for each key.

The code of the lookup does not change. It compares the key with max_entries at run time, as before.

The verifier does not follow NULL branches that the prog cannot take, and removes them as dead code. In sched-ext/scx 29 of 493 progs change, with 4.2% fewer insns in total. 4 of the 29 need more insns, because states with different keys are not equal.

Fixes 6ccf49f79327 ("bpf: Use SCEV to widen bounded loops")
---
 include/linux/bpf_verifier.h |  2 +-
 kernel/bpf/verifier.c        | 38 ++++++++++++++++++++++--------------
 2 files changed, 24 insertions(+), 16 deletions(-)
include/linux/bpf_verifier.h +1 -1
index 7baeb831281f..1b8bd65ea95d 100644
@@ -1851,7 +1851,7 @@ struct bpf_call_arg_meta {
 
 	/* Only set by helper */
 	u64 msize_max_value;
-	s64 const_map_key;
+	u64 max_map_key;
 	struct btf *ret_btf;
 	struct btf_field *kptr_field;
 };
kernel/bpf/verifier.c +23 -15
index 1b6c0674ff6a..83cbded1f6bd 100644
@@ -9639,11 +9639,14 @@ static int check_arg_const_str(struct bpf_verifier_env *env,
 	return 0;
 }
 
-/* Returns constant key value in `value` if possible, else negative error */
-static int get_constant_map_key(struct bpf_verifier_env *env,
-				struct bpf_reg_state *key,
-				u32 key_size,
-				s64 *value)
+/*
+ * Returns the largest value of the key in `value` if it is below `max_entries`,
+ * else negative error
+ */
+static int get_max_map_key(struct bpf_verifier_env *env,
+			   struct bpf_reg_state *key,
+			   u32 key_size, u32 max_entries,
+			   u64 *value)
 {
 	struct bpf_func_state *state = bpf_func(env, key);
 	struct bpf_stack_state *ss;
@@ -9685,12 +9688,17 @@ static int get_constant_map_key(struct bpf_verifier_env *env,
 	if (spill_size != key_size)
 		return -EOPNOTSUPP;
 
+	/*
+	 * The slot has the range of the 64-bit register that was spilled. A value
+	 * below max_entries fits in the 4 bytes of the key.
+	 */
 	reg = &ss->spilled_ptr;
-	if (!tnum_is_const(reg->var_off))
-		/* Stack value not statically known */
+	if (reg_umax(reg) >= max_entries)
+		/* The lookup can return NULL: nothing depends on the key */
 		return -EOPNOTSUPP;
 
-	/* We are relying on a constant value. So mark as precise
+	/*
+	 * We are relying on the range of the key. So mark as precise
 	 * to prevent pruning on it.
 	 */
 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
@@ -9698,7 +9706,7 @@ static int get_constant_map_key(struct bpf_verifier_env *env,
 	if (err < 0)
 		return err;
 
-	*value = reg->var_off.value;
+	*value = reg_umax(reg);
 	return 0;
 }
 
@@ -9881,9 +9889,10 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 p
 		if (err)
 			return err;
 		if (can_elide_value_nullness(meta->map.ptr)) {
-			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
+			err = get_max_map_key(env, reg, key_size, meta->map.ptr->max_entries,
+					      &meta->max_map_key);
 			if (err < 0) {
-				meta->const_map_key = -1;
+				meta->max_map_key = U64_MAX;
 				if (err == -EOPNOTSUPP)
 					err = 0;
 				else
@@ -12534,8 +12543,8 @@ static int update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
 }
 
 /* Returns whether or not the given map can potentially elide
- * lookup return value nullness check. This is possible if the key
- * is statically known.
+ * lookup return value nullness check. This is possible if the largest
+ * value of the key is statically known.
  */
 static bool can_elide_value_nullness(const struct bpf_map *map)
 {
@@ -12913,8 +12922,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 
 		if (func_id == BPF_FUNC_map_lookup_elem &&
 		    can_elide_value_nullness(meta.map.ptr) &&
-		    meta.const_map_key >= 0 &&
-		    meta.const_map_key < meta.map.ptr->max_entries)
+		    meta.max_map_key < meta.map.ptr->max_entries)
 			ret_flag &= ~PTR_MAYBE_NULL;
 
 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
Signature · 1 line
2.55.0
#2 lore raw

PATCH 2/2 selftests/bpf: Test array lookups with a key that is not a constant

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

No prog has a NULL check. max_entries of the two arrays is 2.

  key                                      result
  ---------------------------------------  ------
  0 or 1                                   loads
  1 or 2                                   reject
  prandom & 1                              loads
  prandom & 1, per-cpu array               loads
  the counter of a loop, [0, 1]            loads
  compared with 1 after the store          loads
  [0, 1] on one path, [2, 3] on the other  reject
  [-1, 0]                                  reject

The verifier examines the path with [0, 1] first. This state must not stand for the state with [2, 3]: the prog loads if the key is not precise.

The last prog uses an inner array with BPF_F_INNER_MAP and max_entries 8. The array at run time can have fewer elements. Thus the verifier rejects the key 'prandom & 7'.

The progs that load also run.

---
 .../bpf/progs/verifier_array_access.c         | 165 ++++++++++++++++++
 .../selftests/bpf/progs/verifier_map_in_map.c |  31 ++++
 2 files changed, 196 insertions(+)
tools/testing/selftests/bpf/progs/verifier_array_access.c +165 -0
index 0a187ff725cc..9333321c3ac8 100644
@@ -680,6 +680,171 @@ unsigned int mixed_const_and_non_const_key_lookup(void)
 	return val->index;
 }
 
+SEC("socket")
+__description("valid map access into an array using one of two constants without nullness")
+__success __retval(4)
+unsigned int an_array_with_one_of_two_constants_no_nullness(void)
+{
+	__u32 __attribute__((aligned(8))) key;
+	struct test_val *val;
+
+	/* the paths meet in front of the one store to key */
+	key = bpf_get_prandom_u32() > 42 ? 1 : 0;
+	val = bpf_map_lookup_elem(&map_array, &key);
+	val->index = offsetof(struct test_val, foo);
+
+	return val->index;
+}
+
+SEC("socket")
+__description("invalid map access into an array using one of two constants without nullness")
+__failure __msg("R0 invalid mem access 'map_value_or_null'")
+unsigned int an_array_with_one_of_two_constants_out_of_bounds(void)
+{
+	__u32 __attribute__((aligned(8))) key;
+	struct test_val *val;
+
+	/* 2 is out of bounds */
+	key = bpf_get_prandom_u32() > 42 ? 1 : 2;
+	val = bpf_map_lookup_elem(&map_array, &key);
+	val->index = offsetof(struct test_val, foo);
+
+	return val->index;
+}
+
+SEC("socket")
+__description("valid map access into an array using a key below max_entries without nullness")
+__success __retval(4)
+unsigned int an_array_with_a_key_in_range_no_nullness(void)
+{
+	__u32 __attribute__((aligned(8))) key;
+	struct test_val *val;
+
+	key = bpf_get_prandom_u32() & 1;
+	val = bpf_map_lookup_elem(&map_array, &key);
+	val->index = offsetof(struct test_val, foo);
+
+	return val->index;
+}
+
+SEC("socket")
+__description("valid map access into a pcpu array using a key below max_entries without nullness")
+__success __retval(4)
+unsigned int a_pcpu_array_with_a_key_in_range_no_nullness(void)
+{
+	__u32 __attribute__((aligned(8))) key;
+	struct test_val *val;
+
+	key = bpf_get_prandom_u32() & 1;
+	val = bpf_map_lookup_elem(&map_array_pcpu, &key);
+	val->index = offsetof(struct test_val, foo);
+
+	return val->index;
+}
+
+/* Scalar evolution gives r6 the range [0, 1] for all iterations */
+SEC("socket")
+__description("valid map access into an array using the counter of a loop without nullness")
+__success __retval(0)
+__naked void an_array_with_a_loop_counter_no_nullness(void)
+{
+	asm volatile ("					\
+	r6 = 0;						\
+l0_%=:	*(u32*)(r10 - 8) = r6;				\
+	r2 = r10;					\
+	r2 += -8;					\
+	r1 = %[map_array] ll;				\
+	call %[bpf_map_lookup_elem];			\
+	r0 = *(u32*)(r0 + 0);				\
+	r6 += 1;					\
+	if r6 < 2 goto l0_%=;				\
+	r0 = 0;						\
+	exit;						\
+"	:
+	: __imm(bpf_map_lookup_elem),
+	  __imm_addr(map_array)
+	: __clobber_all);
+}
+
+/* The slot has the id of r6, so the compare sets the range of the slot too */
+SEC("socket")
+__description("valid map access into an array using a key that is compared after the spill")
+__success __retval(0)
+__naked void an_array_with_a_key_compared_after_the_spill(void)
+{
+	asm volatile ("					\
+	call %[bpf_get_prandom_u32];			\
+	w6 = w0;					\
+	*(u32*)(r10 - 8) = r6;				\
+	if r6 > 1 goto l0_%=;				\
+	r2 = r10;					\
+	r2 += -8;					\
+	r1 = %[map_array] ll;				\
+	call %[bpf_map_lookup_elem];			\
+	r0 = *(u32*)(r0 + 0);				\
+l0_%=:	r0 = 0;						\
+	exit;						\
+"	:
+	: __imm(bpf_get_prandom_u32),
+	  __imm(bpf_map_lookup_elem),
+	  __imm_addr(map_array)
+	: __clobber_all);
+}
+
+/*
+ * The verifier sees the key [0, 1] first, then the key [2, 3]. The first state must not stand
+ * for the second one.
+ */
+SEC("socket")
+__description("invalid map access into an array using a key in range, then a key out of range")
+__failure __msg("R0 invalid mem access 'map_value_or_null'")
+__flag(BPF_F_TEST_STATE_FREQ)
+__naked void an_array_with_a_key_in_range_then_out_of_range(void)
+{
+	asm volatile ("					\
+	call %[bpf_get_prandom_u32];			\
+	r6 = r0;					\
+	r6 &= 3;					\
+	if r6 > 1 goto l0_%=;				\
+	r0 = 0;						\
+l0_%=:	*(u32*)(r10 - 8) = r6;				\
+	r2 = r10;					\
+	r2 += -8;					\
+	r1 = %[map_array] ll;				\
+	call %[bpf_map_lookup_elem];			\
+	r0 = *(u32*)(r0 + 0);				\
+	exit;						\
+"	:
+	: __imm(bpf_get_prandom_u32),
+	  __imm(bpf_map_lookup_elem),
+	  __imm_addr(map_array)
+	: __clobber_all);
+}
+
+/* [-1, 0]: the key is 0xffffffff or 0 */
+SEC("socket")
+__description("invalid map access into an array using a key that can be negative")
+__failure __msg("R0 invalid mem access 'map_value_or_null'")
+__naked void an_array_with_a_key_that_can_be_negative(void)
+{
+	asm volatile ("					\
+	call %[bpf_get_prandom_u32];			\
+	r0 &= 1;					\
+	r0 += -1;					\
+	*(u32*)(r10 - 8) = r0;				\
+	r2 = r10;					\
+	r2 += -8;					\
+	r1 = %[map_array] ll;				\
+	call %[bpf_map_lookup_elem];			\
+	r0 = *(u32*)(r0 + 0);				\
+	exit;						\
+"	:
+	: __imm(bpf_get_prandom_u32),
+	  __imm(bpf_map_lookup_elem),
+	  __imm_addr(map_array)
+	: __clobber_all);
+}
+
 SEC("socket")
 __failure __msg("invalid read from stack R2 off=4096 size=4")
 __naked void key_lookup_at_invalid_fp(void)
tools/testing/selftests/bpf/progs/verifier_map_in_map.c +31 -0
index 621248a02a1f..5ecf53ac9321 100644
@@ -85,6 +85,37 @@ l0_%=:	exit;						\
 	: __clobber_all);
 }
 
+/* max_entries of the map that is there at run time can be below 8 */
+SEC("socket")
+__description("map in map dynamic inner array lookup is nullable, key below max_entries")
+__failure __msg("invalid mem access 'map_value_or_null'")
+__naked void map_in_map_dynamic_inner_array_key_in_range(void)
+{
+	asm volatile ("					\
+	call %[bpf_get_prandom_u32];			\
+	r6 = r0;					\
+	r6 &= 7;					\
+	r1 = 0;						\
+	*(u32*)(r10 - 4) = r1;				\
+	r2 = r10;					\
+	r2 += -4;					\
+	r1 = %[map_in_map_dyn] ll;			\
+	call %[bpf_map_lookup_elem];			\
+	if r0 == 0 goto l0_%=;				\
+	*(u32*)(r10 - 8) = r6;				\
+	r2 = r10;					\
+	r2 += -8;					\
+	r1 = r0;					\
+	call %[bpf_map_lookup_elem];			\
+	r0 = *(u64 *)(r0 + 0);				\
+l0_%=:	exit;						\
+"	:
+	: __imm(bpf_get_prandom_u32),
+	  __imm(bpf_map_lookup_elem),
+	  __imm_addr(map_in_map_dyn)
+	: __clobber_all);
+}
+
 SEC("xdp")
 __description("map in map state pruning")
 __success __msg("processed 15 insns")
Signature · 1 line
2.55.0
#3 lore raw
In reply to Alexei Starovoitov
This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Hello:

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

Quoted 8 lines · On Sun, 1 Nov 2026 17:46:58 +0000 you wrote:

From: Alexei Starovoitov <[email protected]>

A lookup in an array or in a per-cpu array returns NULL only when the key is not below max_entries. The verifier knows that for a key that is a constant. Then the prog needs no NULL check, and the verifier does not examine a NULL branch that the prog cannot take.

[...]

Here is the summary with links:
- [bpf-next,1/2] bpf: A lookup in an array is not NULL when the largest key is below max_entries

    https://git.kernel.org/bpf/bpf-next/c/c1e03c8479e3
  - [bpf-next,2/2] selftests/bpf: Test array lookups with a key that is not a constant
    https://git.kernel.org/bpf/bpf-next/c/2faec15e0153

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html