| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/11/14 14:38 | flow | patch-triage |
8mArgs:null Results: {
"EnableConfigs": [
"BPF_SYSCALL"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_scev_next_linked_reg",
"bpf_scev_mem_addr",
"bpf_scev_in_slice_slots",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_half_slot_live_before",
"bpf_clean_verifier_state"
],
"KMSANReasoning": "The patch series updates the BPF verifier to replace dynamic scalar register ID tracking with static Scalar Evolution (SCEV) analysis for linked registers, improving induction variable handling, 32-bit sign extension bounds tracking, and state equivalence comparisons.\n\nKMSAN vs KASAN Applicability Analysis:\n1. No uninitialized memory exposure to user space: The changes do not introduce or modify any kernel data structures copied to user space (no copy_to_user, put_user, netlink skb attributes, or BPF ringbuf/array copy-outs).\n2. Proper initialization: All heap and stack structures added or modified in the patch (such as `struct scev`, `struct env`, `struct scev_linked_reg`, and resized arrays in `grow_exprs`) use `kzalloc`, `__GFP_ZERO`, or explicit full-field initialization before reading. The replacement of `s32 delta` with `u32 unused` in `struct bpf_reg_state` preserves the existing struct layout and padding without introducing uninitialized holes.\n3. Bug profiles: Any bugs introduced by this patch would manifest as incorrect register range / bounds inferences, loop latch count mismatches, or state pruning errors in the verifier. Such bugs can lead to out-of-bounds memory accesses or invalid pointer dereferences at BPF runtime, which are already detected by KASAN and standard kernel debuggers.\n\nBecause there are no uninitialized memory read risks or information leaks uniquely targetable by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false,
"Reasoning": "This patch series significantly revamps linked scalar tracking in the BPF verifier. Dynamic scalar ID and delta tracking across verification states are replaced with static scalar evolution (SCEV) analysis, global value numbering, phi-node expressions, and memory register promotion. Conditional jump operations now query SCEV linked registers to refine bounds. These modifications affect core BPF verifier correctness and state equivalence, which are directly reachable from userspace via the bpf() system call and represent high-value fuzzing targets.",
"WorthFuzzing": true
} |
| 1/1 | 2026/11/14 14:38 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 5688cd04d3b41e9f2094dd2a002289802a0f9401\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Sat Nov 14 14:38:24 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h\nindex 4771c55d8f41f6..598763d128ab8c 100644\n--- a/include/linux/bpf_verifier.h\n+++ b/include/linux/bpf_verifier.h\n@@ -60,10 +60,8 @@ struct bpf_stack_range {\n struct bpf_reg_state {\n \t/* Ordering of fields matters. See regsafe() */\n \tenum bpf_reg_type type;\n-\t/*\n-\t * Constant delta between \"linked\" scalars with the same ID.\n-\t */\n-\ts32 delta;\n+\t/* 0. regsafe() compares the bytes before var_off: there is no hole among them. */\n+\tu32 unused;\n \tunion {\n \t\t/* valid when type == PTR_TO_PACKET */\n \t\tint range;\n@@ -179,18 +177,9 @@ struct bpf_reg_state {\n \t * the dynptr to determine proper reference freeing.\n \t * Similarly to dynptrs, we use ID to track \"belonging\" of a reference\n \t * to a specific instance of bpf_iter.\n+\t * A scalar has no id. The scalars that it is linked to are static: computed before the\n+\t * main pass, see bpf_scev_next_linked_reg().\n \t */\n-\t/*\n-\t * Upper bit of ID is used to remember relationship between \"linked\"\n-\t * registers. Example:\n-\t * r1 = r2; both will have r1-\u003eid == r2-\u003eid == N\n-\t * r1 += 10; r1-\u003eid == N | BPF_ADD_CONST and r1-\u003edelta == 10\n-\t * r3 = r2; both will have r3-\u003eid == r2-\u003eid == N\n-\t * w3 += 10; r3-\u003eid == N | BPF_ADD_CONST32 and r3-\u003edelta == 10\n-\t */\n-#define BPF_ADD_CONST64 (1U \u003c\u003c 31)\n-#define BPF_ADD_CONST32 (1U \u003c\u003c 30)\n-#define BPF_ADD_CONST (BPF_ADD_CONST64 | BPF_ADD_CONST32)\n \tu32 id;\n \t/*\n \t * Tracks the parent object this register was derived from.\n@@ -1112,27 +1101,18 @@ struct bpf_id_pair {\n * comes out for it, only if the same places have the same names.\n * - bpf_flow_return() puts the ids of the call that waits back. All other ids get new values.\n * - What comes out has the ranges of all calls that share the state at the entry. So a name is good\n- * for what holds whatever the ranges are: the same object. Other ids have no name: a number\n- * loses its id, any other argument keeps the frames of the caller, see arg_needs_caller().\n- * - env-\u003eid_gen stays below BPF_MAX_ID. So no id is a name or has a bit of BPF_ADD_CONST.\n+ * for what holds whatever the ranges are: the same object. Other ids have no name: such an\n+ * argument keeps the frames of the caller, see arg_needs_caller().\n+ * - env-\u003eid_gen stays below BPF_MAX_ID. So no id is a name.\n */\n #define BPF_INHERITED_ID\t0x20000000\n #define BPF_MAX_ID\t\t(BPF_INHERITED_ID / 2)\n \n struct bpf_idmap {\n-\tu32 tmp_id_gen;\n \tu32 cnt;\n \tstruct bpf_id_pair map[BPF_ID_MAP_SIZE];\n };\n \n-struct bpf_idset {\n-\tu32 num_ids;\n-\tstruct {\n-\t\tu32 id;\n-\t\tu32 cnt;\n-\t} entries[BPF_ID_MAP_SIZE];\n-};\n-\n struct bpf_liveness;\n struct scev;\n \n@@ -1278,10 +1258,7 @@ struct bpf_verifier_env {\n \t * via callx. Allocated when the first such edge is recorded.\n \t */\n \tunsigned long *callx_edges;\n-\tunion {\n-\t\tstruct bpf_idmap idmap_scratch;\n-\t\tstruct bpf_idset idset_scratch;\n-\t};\n+\tstruct bpf_idmap idmap_scratch;\n \tstruct {\n \t\tint *insn_state;\n \t\tint *insn_stack;\n@@ -1447,12 +1424,6 @@ void bpf_verbose_snum32(struct bpf_verifier_env *env, s32 num);\n \t\tbpf_log(\u0026env-\u003elog, \"verifier bug: \" fmt \"\\n\", ##args);\t\t\t\t\\\n \t})\n \n-static inline void clear_scalar_id(struct bpf_reg_state *reg)\n-{\n-\treg-\u003eid = 0;\n-\treg-\u003edelta = 0;\n-}\n-\n static inline void mark_calls_callback(struct bpf_verifier_env *env, int idx)\n {\n \tenv-\u003einsn_aux_data[idx].calls_callback = true;\n@@ -1589,7 +1560,6 @@ void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,\n void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);\n void bpf_mark_reg_unknown(struct bpf_reg_state *reg);\n int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size);\n-void bpf_clear_singular_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);\n \n static inline int bpf_get_spi(s32 off)\n {\n@@ -1902,6 +1872,7 @@ u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);\n \n int bpf_find_subprog(struct bpf_verifier_env *env, int off);\n bool bpf_is_throw_kfunc(struct bpf_insn *insn);\n+bool bpf_is_dynptr_slice_rdwr_kfunc(struct bpf_insn *insn);\n int bpf_compute_const_regs(struct bpf_verifier_env *env);\n int bpf_prune_dead_branches(struct bpf_verifier_env *env);\n int bpf_check_cfg(struct bpf_verifier_env *env);\n@@ -2078,6 +2049,7 @@ int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_\n const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);\n bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);\n bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);\n+bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi);\n int bpf_compute_live_registers(struct bpf_verifier_env *env);\n \n #define BPF_MAP_KEY_POISON\t(1ULL \u003c\u003c 63)\n@@ -2224,6 +2196,13 @@ int bpf_init_scev(struct bpf_verifier_env *env);\n void bpf_free_scev(struct bpf_verifier_env *env);\n int bpf_compute_scev(struct bpf_verifier_env *env);\n int bpf_scev_jump_counts(struct bpf_verifier_env *env, int header, int n, bool taken_leaves);\n+bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,\n+\t\t\t u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,\n+\t\t\t u32 *bits);\n+bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,\n+\t\t s64 *off);\n+bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg);\n+bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off);\n \n int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\n \t\t\t struct bpf_loop_iters *iters);\ndiff --git a/kernel/bpf/flow.c b/kernel/bpf/flow.c\nindex c9458b3ad114a5..abbadba1e79f61 100644\n--- a/kernel/bpf/flow.c\n+++ b/kernel/bpf/flow.c\n@@ -2603,10 +2603,9 @@ static bool flow_join_makes_up(const struct bpf_flow *flow, struct bpf_verifier_\n \t\t\t struct bpf_verifier_state *b)\n {\n \tstruct bpf_func_state *fa = a-\u003eframe[a-\u003ecurframe], *fb = b-\u003eframe[b-\u003ecurframe];\n-\tconst struct bpf_reg_state *ra, *rb;\n+\tconst struct bpf_reg_state *ra, *rb, *one_a = NULL, *one_b = NULL;\n \tconst struct flow_need *tested = flow-\u003eneed[FLOW_NEED_JUMP], *need;\n-\tu32 fr, i, id = 0;\n-\tbool one = false;\n+\tu32 fr, i, len = offsetof(struct bpf_reg_state, id);\n \n \tif (!tested)\n \t\treturn false;\n@@ -2623,11 +2622,11 @@ static bool flow_join_makes_up(const struct bpf_flow *flow, struct bpf_verifier_\n \t\t\t\tcontinue;\n \t\t\tif (flow_gap(ra, rb))\n \t\t\t\treturn true;\n-\t\t\t/* copies of a number are one number */\n-\t\t\tif (one \u0026\u0026 (!id || id != (ra-\u003eid \u0026 ~BPF_ADD_CONST)))\n+\t\t\t/* copies of a scalar count once: same range and tnum in each state */\n+\t\t\tif (one_a \u0026\u0026 (memcmp(ra, one_a, len) || memcmp(rb, one_b, len)))\n \t\t\t\treturn true;\n-\t\t\tone = true;\n-\t\t\tid = ra-\u003eid \u0026 ~BPF_ADD_CONST;\n+\t\t\tone_a = ra;\n+\t\t\tone_b = rb;\n \t\t}\n \t}\n \tif (!flow_needed_consts_differ(flow, FLOW_NEED_FLAG, a, b))\n@@ -2925,8 +2924,6 @@ static struct flow_state *flow_arrive(struct bpf_verifier_env *env, struct bpf_v\n \t\tflow_free_state(env, s);\n \t\treturn ERR_PTR(err);\n \t}\n-\t/* when the registers that it was shared with are dead, or are those of the caller */\n-\tbpf_clear_singular_ids(env, \u0026s-\u003est);\n \treturn s;\n }\n \ndiff --git a/kernel/bpf/join.c b/kernel/bpf/join.c\nindex cc4494aef18733..2b8c94b7dc5027 100644\n--- a/kernel/bpf/join.c\n+++ b/kernel/bpf/join.c\n@@ -75,18 +75,16 @@ static void jid_mark_bad(struct bpf_join_state *js, u32 a, u32 b)\n \t\t\tjs-\u003epairs[i].bad = true;\n }\n \n-static void jid_note(struct bpf_join_state *js, u32 ida, u32 idb, bool consistent)\n+static void jid_note(struct bpf_join_state *js, u32 a, u32 b)\n {\n-\tu32 a = ida \u0026 ~BPF_ADD_CONST, b = idb \u0026 ~BPF_ADD_CONST;\n+\tbool consistent, other = false;\n \tstruct join_idpair *p;\n-\tbool other = false;\n \tu32 i;\n \n \tif (!a || !b)\n \t\treturn;\n \t/* a name of what the caller has, see BPF_INHERITED_ID */\n-\tif (a != b \u0026\u0026 (a | b) \u003e= BPF_INHERITED_ID)\n-\t\tconsistent = false;\n+\tconsistent = a == b || (a | b) \u003c BPF_INHERITED_ID;\n \tfor (i = 0; i \u003c js-\u003enpairs; i++) {\n \t\tp = \u0026js-\u003epairs[i];\n \t\tif (p-\u003ea == a \u0026\u0026 p-\u003eb == b) {\n@@ -111,15 +109,12 @@ static void jid_note(struct bpf_join_state *js, u32 ida, u32 idb, bool consisten\n \tp-\u003ebad = !consistent;\n }\n \n-static bool jid_good(struct bpf_join_state *js, u32 ida, u32 idb)\n+static bool jid_good(struct bpf_join_state *js, u32 a, u32 b)\n {\n-\tu32 a = ida \u0026 ~BPF_ADD_CONST, b = idb \u0026 ~BPF_ADD_CONST;\n \tu32 i;\n \n \tif (!a || !b || js-\u003epairs_overflow)\n \t\treturn false;\n-\tif ((ida ^ idb) \u0026 BPF_ADD_CONST)\n-\t\treturn false;\n \tfor (i = 0; i \u003c js-\u003enpairs; i++)\n \t\tif (js-\u003epairs[i].a == a \u0026\u0026 js-\u003epairs[i].b == b)\n \t\t\treturn !js-\u003epairs[i].bad;\n@@ -199,15 +194,6 @@ static bool reg_value_equal(const struct bpf_reg_state *ra, const struct bpf_reg\n \treturn !memcmp(ra, rb, offsetof(struct bpf_reg_state, id));\n }\n \n-static bool scalar_link_consistent(const struct bpf_reg_state *ra, const struct bpf_reg_state *rb)\n-{\n-\tif ((ra-\u003eid ^ rb-\u003eid) \u0026 BPF_ADD_CONST)\n-\t\treturn false;\n-\tif ((ra-\u003eid \u0026 BPF_ADD_CONST) \u0026\u0026 ra-\u003edelta != rb-\u003edelta)\n-\t\treturn false;\n-\treturn true;\n-}\n-\n /*\n * Join two registers, regsafe() documents what each type needs.\n * Pass 1 records id pairs, pass 2 computes @dst, which is a copy of @ra on entry.\n@@ -229,16 +215,8 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,\n \tcase SCALAR_VALUE:\n \t\tif (js-\u003eenv-\u003eexplore_alu_limits \u0026\u0026 !reg_value_equal(ra, rb))\n \t\t\treturn false;\n-\t\tif (pass == 1) {\n-\t\t\tjid_note(js, ra-\u003eid, rb-\u003eid, scalar_link_consistent(ra, rb));\n-\t\t\treturn true;\n-\t\t}\n-\t\tjoin_range(js, dst, ra, rb);\n-\t\t/* a link that exists on one side only is dropped */\n-\t\tif (ra-\u003eid \u0026\u0026 !jid_good(js, ra-\u003eid, rb-\u003eid)) {\n-\t\t\tdst-\u003eid = 0;\n-\t\t\tdst-\u003edelta = 0;\n-\t\t}\n+\t\tif (pass == 2)\n+\t\t\tjoin_range(js, dst, ra, rb);\n \t\treturn true;\n \tcase PTR_TO_MAP_KEY:\n \tcase PTR_TO_MAP_VALUE:\n@@ -269,7 +247,7 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,\n \t\tif (ra-\u003er64.base != rb-\u003er64.base)\n \t\t\treturn false;\n \t\tif (pass == 1) {\n-\t\t\tjid_note(js, ra-\u003eid, rb-\u003eid, true);\n+\t\t\tjid_note(js, ra-\u003eid, rb-\u003eid);\n \t\t\treturn true;\n \t\t}\n \t\tif (!jid_strict_ok(js, ra-\u003eid, rb-\u003eid))\n@@ -291,9 +269,9 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,\n \t}\n \n \tif (pass == 1) {\n-\t\tjid_note(js, ra-\u003eid, rb-\u003eid, true);\n-\t\tjid_note(js, ra-\u003eparent_id, rb-\u003eparent_id, true);\n-\t\tjid_note(js, ra-\u003emap_uid, rb-\u003emap_uid, true);\n+\t\tjid_note(js, ra-\u003eid, rb-\u003eid);\n+\t\tjid_note(js, ra-\u003eparent_id, rb-\u003eparent_id);\n+\t\tjid_note(js, ra-\u003emap_uid, rb-\u003emap_uid);\n \t\treturn true;\n \t}\n \tif (!jid_strict_ok(js, ra-\u003eid, rb-\u003eid) ||\n@@ -350,8 +328,8 @@ static bool join_special_slot(struct bpf_join_state *js, const struct bpf_stack_\n \t\tbreak;\n \t}\n \tif (pass == 1) {\n-\t\tjid_note(js, ra-\u003eid, rb-\u003eid, true);\n-\t\tjid_note(js, ra-\u003eparent_id, rb-\u003eparent_id, true);\n+\t\tjid_note(js, ra-\u003eid, rb-\u003eid);\n+\t\tjid_note(js, ra-\u003eparent_id, rb-\u003eparent_id);\n \t\treturn true;\n \t}\n \treturn jid_strict_ok(js, ra-\u003eid, rb-\u003eid) \u0026\u0026\n@@ -563,12 +541,12 @@ static void join_refs_note(struct bpf_join_state *js, const struct bpf_verifier_\n {\n \tint i;\n \n-\tjid_note(js, a-\u003eactive_irq_id, b-\u003eactive_irq_id, true);\n-\tjid_note(js, a-\u003eactive_lock_id, b-\u003eactive_lock_id, true);\n+\tjid_note(js, a-\u003eactive_irq_id, b-\u003eactive_irq_id);\n+\tjid_note(js, a-\u003eactive_lock_id, b-\u003eactive_lock_id);\n \tfor (i = 0; i \u003c a-\u003eacquired_refs; i++) {\n-\t\tjid_note(js, a-\u003erefs[i].id, b-\u003erefs[i].id, true);\n+\t\tjid_note(js, a-\u003erefs[i].id, b-\u003erefs[i].id);\n \t\tif (a-\u003erefs[i].type == REF_TYPE_PTR)\n-\t\t\tjid_note(js, a-\u003erefs[i].parent_id, b-\u003erefs[i].parent_id, true);\n+\t\t\tjid_note(js, a-\u003erefs[i].parent_id, b-\u003erefs[i].parent_id);\n \t}\n }\n \ndiff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c\nindex e930d928afa5b4..63d23d28f2a5c4 100644\n--- a/kernel/bpf/liveness.c\n+++ b/kernel/bpf/liveness.c\n@@ -760,6 +760,19 @@ static void compute_may_write_masks(struct bpf_verifier_env *env)\n \t}\n }\n \n+/* live_stack_before of the insn at @insn_idx for one half-slot */\n+bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi)\n+{\n+\tstruct func_instance *instance;\n+\tint bkt;\n+\n+\thash_for_each(env-\u003eliveness-\u003efunc_instances, bkt, instance, hl_node)\n+\t\tif (insn_idx - instance-\u003esubprog_start \u003c instance-\u003einsn_cnt \u0026\u0026\n+\t\t is_live_before(instance, insn_idx, instance-\u003edepth, half_spi))\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)\n {\n \treturn env-\u003einsn_aux_data[insn_idx].may_write_mask;\n@@ -1398,8 +1411,10 @@ static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf\n \n \t\treturn fill_from_stack(insn, at_out, reg, parent-\u003eat, parent-\u003eslots, ptr-\u003eframe);\n \t}\n+\t/* A frame holds pointers to its own stack and to the stacks of its callers */\n \tif (ptr-\u003eframe == ARG_IMPRECISE \u0026\u0026 !(ptr-\u003emask \u0026 BIT(depth)) \u0026\u0026 ptr-\u003emask)\n-\t\treturn *ptr;\n+\t\treturn (struct arg_track){ .mask = GENMASK(fls(ptr-\u003emask) - 1, 0),\n+\t\t\t\t\t .frame = ARG_IMPRECISE };\n \treturn (struct arg_track){ .frame = ARG_NONE };\n }\n \ndiff --git a/kernel/bpf/log.c b/kernel/bpf/log.c\nindex 84659a757b43ca..ffbec587a9166e 100644\n--- a/kernel/bpf/log.c\n+++ b/kernel/bpf/log.c\n@@ -696,7 +696,7 @@ static void print_reg_state(struct bpf_verifier_env *env,\n \t\tif (state-\u003eframeno != reg-\u003eframeno)\n \t\t\tverbose(env, \"[%d]\", reg-\u003eframeno);\n \t\tif (tnum_is_const(reg-\u003evar_off)) {\n-\t\t\tbpf_verbose_snum(env, reg-\u003evar_off.value + reg-\u003edelta);\n+\t\t\tbpf_verbose_snum(env, reg-\u003evar_off.value);\n \t\t\treturn;\n \t\t}\n \t}\n@@ -704,9 +704,7 @@ static void print_reg_state(struct bpf_verifier_env *env,\n \t\tverbose(env, \"%s\", btf_type_name(reg-\u003ebtf, reg-\u003ebtf_id));\n \tverbose(env, \"(\");\n \tif (reg-\u003eid)\n-\t\tverbose_a(\"id=%d\", reg-\u003eid \u0026 ~BPF_ADD_CONST);\n-\tif (reg-\u003eid \u0026 BPF_ADD_CONST)\n-\t\tverbose(env, \"%+d\", reg-\u003edelta);\n+\t\tverbose_a(\"id=%d\", reg-\u003eid);\n \tif (reg-\u003eparent_id)\n \t\tverbose_a(\"parent_id=%d\", reg-\u003eparent_id);\n \tif (type_is_non_owning_ref(reg-\u003etype))\n@@ -720,10 +718,6 @@ static void print_reg_state(struct bpf_verifier_env *env,\n \t\t\t reg-\u003emap_ptr-\u003ekey_size,\n \t\t\t reg-\u003emap_ptr-\u003evalue_size);\n \t}\n-\tif (t != SCALAR_VALUE \u0026\u0026 reg-\u003edelta) {\n-\t\tverbose_a(\"off=\");\n-\t\tbpf_verbose_snum(env, reg-\u003edelta);\n-\t}\n \tif (type_is_pkt_pointer(t)) {\n \t\tverbose_a(\"r=\");\n \t\tverbose_unum(env, reg-\u003erange);\ndiff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c\nindex 4187ce955be991..e36181a0085852 100644\n--- a/kernel/bpf/scev.c\n+++ b/kernel/bpf/scev.c\n@@ -12,8 +12,13 @@\n #include \u003clinux/overflow.h\u003e\n \n #define REGS_NUM BPF_SCEV_REGS_NUM\n+/* The SCEV registers of an env: r0 - r10, the stack slots and memory locations, see struct env */\n+#define MEM_REGS_NUM 16\n+#define ENV_REGS_NUM (REGS_NUM + MEM_REGS_NUM)\n #define UNKNOWN_EXPR_ID 0\n #define OPAQUE_EXPR_ID 1\n+/* (REG r). UNKNOWN, OPAQUE and (REG r) have fixed ids and are not in the hash table. */\n+#define REG_EXPR_ID(r) (2 + (r))\n \n /*\n * BPF instructions use 'code', 'src_reg', 'off' and 'imm' fields for instruction encoding.\n@@ -44,34 +49,100 @@ enum expr_op {\n \t */\n \tLINEAR_SCEV,\n \t/*\n-\t * param[1], given that register param[0] and the register that param[1] starts from are\n-\t * equal when the loop is entered. Not known otherwise.\n+\t * (add rB rC) is the SCEV of rA: rA == rB + rC at the header in every iteration. rB and rC\n+\t * are the header phis here, not the entry values as below LINEAR_SCEV.\n \t */\n-\tCOPY_SCEV,\n+\tADD_SCEV,\n };\n \n+/*\n+ * An SSA name for a value that no expression describes: the def of the SCEV register 'reg'\n+ * - by the insn at 'idx'. An insn that may write defines too (may_def in liveness.c). A nested loop\n+ * defines at its header what it leaves.\n+ * - by a phi before the insn at 'idx': a join point, a loop header.\n+ * Without its backedges and with nested loops collapsed the body of a loop is acyclic: an insn\n+ * executes at most once per iteration, so a def is one value per iteration. A name is unique within\n+ * the env of one loop.\n+ * The operands of a phi are a set, 8 at most; a phi(a, b) among them is expanded. They have no\n+ * defs, see strip_defs(): (+ r6 %r2.4) and (+ r6 %r2.7) are one operand, (+ r6 _). So they don't\n+ * tell one phi from another: phis are value numbered by their bases, see mk_phi().\n+ * In the env of loop H a phi at H merges the backedge values only, the header phi itself is\n+ * (REG r). In the env of the enclosing loop a phi at H merges the entering edges.\n+ * Op and params of a def by an insn are what that insn computes, see alu64_with_def():\n+ * set_expr_base() and match_linked_add() look through such an add, split_const_offset() and\n+ * match_linked_add() check prevent_zext of the insn. Those of a phi are the shape that its operands\n+ * share, no insn computes them: nothing looks through a phi.\n+ */\n+struct expr_def {\n+\tu32 set:1;\t/* 0: the expression has no def */\n+\tu32 phi:1;\n+\tu32 reg:9;\n+\tu32 idx:21;\n+};\n+/* def.reg of the phi of two bases, see mk_phi() */\n+#define BASE_REG ENV_REGS_NUM\n+static_assert(BASE_REG \u003c 1 \u003c\u003c 9 \u0026\u0026 BPF_COMPLEXITY_LIMIT_INSNS \u003c= 1 \u003c\u003c 21);\n+\n+static const struct expr_def no_def;\n+\n struct expr {\n-\tu32 op;\n+\tu16 op;\n+\t/* A value number: all SCEV registers of an env that have this id hold the same value */\n+\tbool is_vn;\n+\t/* expr == base + off (mod 2^bits), see split_const_offset() */\n+\tu8 bits;\n+\t/*\n+\t * UNKNOWN, OPAQUE and ANY don't describe a value. With a def the id stands for one value,\n+\t * see struct expr_def. Without a def every use of the id can be another value.\n+\t */\n+\tstruct expr_def def;\n \tunion {\n \t\tu32 params[2];\n \t\ts64 imm;\n \t};\n-};\n-\n-struct expr_bucket {\n-\tu32 cnt;\n-\tu32 cap;\n-\tu32 ids[];\n+\tu32 base;\n+\t/*\n+\t * id of the first add on the way to 'base' whose insn may still become ALU32, see\n+\t * prevent_zext. 0: none\n+\t */\n+\tu32 arena_add;\n+\ts64 off;\n };\n \n struct env {\n \tbool empty;\n-\tu32 reg2expr[REGS_NUM];\n+\tu32 reg2expr[ENV_REGS_NUM];\n \tu32 reg2scev[REGS_NUM];\n+\t/*\n+\t * Register promotion of memory that is not behind r10. The SCEV register REGS_NUM + i is\n+\t * the memory at the address mem_addr[i], a value number of this env. 0: not in use.\n+\t * - A store through a pointer defines it like a spill defines a stack slot.\n+\t * - A load defines its register as before, and the memory gets that value number: it holds\n+\t * what a store of the register would leave. No expression of a register depends on\n+\t * memory, which is private only if it is stack. That is not known here.\n+\t * - A join point has a phi. An insn that may write is a may-def, see forget_mem_regs().\n+\t * - A store through r10 is not: the main pass takes the stack of a caller only.\n+\t * A value number of a loop means nothing in the enclosing loop: no memory is tracked at\n+\t * a header, a nested loop is a may-def.\n+\t */\n+\tu32 mem_addr[MEM_REGS_NUM];\n+};\n+\n+/*\n+ * A SCEV register and the id of its expression before a conditional jump. 'addr' is mem_addr[] of\n+ * a memory location.\n+ */\n+struct scev_linked_reg {\n+\tu32 reg;\n+\tu32 id;\n+\tu32 addr;\n };\n \n struct insn_envs {\n \tu32 cnt;\n+\t/* The linked registers of a jump, see find_linked_regs(): linked_cnt of scev-\u003elinked[] */\n+\tu32 linked_first;\n+\tu32 linked_cnt;\n \tstruct {\n \t\tint loop_header;\n \t\tstruct env *env;\n@@ -92,87 +163,216 @@ struct scev {\n \t/* Read-only representatives for stack slots without a saved register. */\n \tstruct bpf_reg_state zero_reg;\n \tstruct bpf_reg_state unknown_reg;\n+\t/* r -\u003e (REG r): before the first insn of a loop every SCEV register is its header phi */\n+\tstruct env identity_env;\n \t/*\n \t * Expressions are identified by id, exprs_ht ensures that\n \t * each expression exists as a unique instance.\n \t * This allows for fast equivalence check: id1 === id2.\n+\t * exprs_ht[hash] is the first id of a chain, exprs_next[id] is the next one, 0 ends it.\n+\t * Both have exprs_cap elements, like exprs[].\n \t */\n-\tstruct expr_bucket **exprs_ht;\n+\tu32 *exprs_ht;\n+\tu32 *exprs_next;\n \tstruct scev_worklist worklist;\n \tstruct insn_envs **envs;\n \tstruct expr *exprs;\n+\tstruct scev_linked_reg *linked;\n+\t/* The stack slots that a store through a dynptr slice may alias, see expr_is_vn() */\n+\tDECLARE_BITMAP(slice_slots, MAX_BPF_STACK_SLOTS);\n \t/*\n \t * Loops are analyzed one by one, this array keeps track if a particular\n \t * instruction was visited on a current pass.\n \t */\n \tu32 *discovered;\n-\tu32 exprs_ht_cnt;\n \tint exprs_cnt;\n \tint exprs_cap;\n+\tu32 linked_cnt;\n+\tu32 linked_cap;\n \tint envs_cnt;\n \tint stack_sz;\n+\tint simplify_depth;\n \tstruct expr_stack_elt expr_stack[EXPR_STACK_DEPTH];\n \tu32 ids_buf[EXPR_STACK_DEPTH];\n };\n \n static u32 expr_hash(struct expr *e)\n {\n-\treturn jhash_3words(e-\u003eop, e-\u003eparams[0], e-\u003eparams[1], 0);\n+\t/* def.phi is not hashed: the def by an insn and the phi before it share a chain */\n+\treturn jhash_3words(e-\u003eop, e-\u003eparams[0], e-\u003eparams[1],\n+\t\t\t e-\u003edef.idx * REGS_NUM + e-\u003edef.reg);\n }\n \n-static int expr_eq(struct expr *a, struct expr *b)\n+static bool same_def(struct expr_def a, struct expr_def b)\n {\n-\treturn a-\u003eop == b-\u003eop \u0026\u0026 a-\u003eimm == b-\u003eimm;\n+\treturn a.set == b.set \u0026\u0026 a.phi == b.phi \u0026\u0026 a.reg == b.reg \u0026\u0026 a.idx == b.idx;\n }\n \n-static int add_expr(struct scev *scev, struct expr e)\n+/* Is @e the expression @id? The base of a phi is a part of its key. 0: the phi is its own base. */\n+static int expr_eq(struct scev *scev, struct expr *e, u32 id)\n+{\n+\tstruct expr *x = \u0026scev-\u003eexprs[id];\n+\n+\tif (e-\u003eop != x-\u003eop || e-\u003eimm != x-\u003eimm || !same_def(e-\u003edef, x-\u003edef))\n+\t\treturn false;\n+\tif (!e-\u003edef.phi)\n+\t\treturn true;\n+\treturn e-\u003ebase ? e-\u003ebase == x-\u003ebase \u0026\u0026 e-\u003eoff == x-\u003eoff : x-\u003ebase == id;\n+}\n+\n+static void exprs_ht_add(struct scev *scev, u32 id)\n+{\n+\tu32 *bucket = \u0026scev-\u003eexprs_ht[expr_hash(\u0026scev-\u003eexprs[id]) \u0026 (scev-\u003eexprs_cap - 1)];\n+\n+\tscev-\u003eexprs_next[id] = *bucket;\n+\t*bucket = id;\n+}\n+\n+/* @cap is a power of two. No warning for a size that kvmalloc() rejects. */\n+static int grow_exprs(struct scev *scev, u32 cap)\n {\n-\tstruct expr_bucket *bucket;\n-\tu32 i, id, hash, new_cap;\n+\tgfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_NOWARN;\n \tvoid *tmp;\n+\tu32 id;\n \n-\thash = expr_hash(\u0026e) \u0026 (scev-\u003eexprs_ht_cnt - 1);\n-\tbucket = scev-\u003eexprs_ht[hash];\n+\ttmp = kvrealloc(scev-\u003eexprs, array_size(cap, sizeof(*scev-\u003eexprs)), gfp);\n+\tif (!tmp)\n+\t\treturn -ENOMEM;\n+\tscev-\u003eexprs = tmp;\n+\ttmp = kvrealloc(scev-\u003eexprs_next, array_size(cap, sizeof(u32)), gfp);\n+\tif (!tmp)\n+\t\treturn -ENOMEM;\n+\tscev-\u003eexprs_next = tmp;\n+\ttmp = kvrealloc(scev-\u003eexprs_ht, array_size(cap, sizeof(u32)), gfp);\n+\tif (!tmp)\n+\t\treturn -ENOMEM;\n+\tscev-\u003eexprs_ht = tmp;\n+\tscev-\u003eexprs_cap = cap;\n+\tmemset(scev-\u003eexprs_ht, 0, array_size(cap, sizeof(u32)));\n+\tfor (id = REG_EXPR_ID(REGS_NUM); id \u003c scev-\u003eexprs_cnt; id++)\n+\t\texprs_ht_add(scev, id);\n+\treturn 0;\n+}\n \n-\tif (bucket) {\n-\t\tfor (i = 0; i \u003c bucket-\u003ecnt; i++) {\n-\t\t\tid = bucket-\u003eids[i];\n-\t\t\tif (expr_eq(\u0026e, \u0026scev-\u003eexprs[id]))\n-\t\t\t\treturn id;\n-\t\t}\n-\t}\n+static u32 op_params_num(u32 op);\n \n-\tif (!bucket || bucket-\u003ecap == bucket-\u003ecnt) {\n-\t\tnew_cap = bucket ? bucket-\u003ecap * 2 : 4;\n-\t\tbucket = kvrealloc(bucket, sizeof(*bucket) + sizeof(u32) * new_cap, GFP_KERNEL_ACCOUNT | __GFP_ZERO);\n-\t\tif (!bucket)\n-\t\t\treturn -ENOMEM;\n-\t\tscev-\u003eexprs_ht[hash] = bucket;\n-\t\tbucket-\u003ecap = new_cap;\n-\t}\n+static bool expr_is_vn(struct scev *scev, struct expr *e)\n+{\n+\tu32 i, reg = e-\u003edef.reg;\n \n-\tif (scev-\u003eexprs_cnt == scev-\u003eexprs_cap) {\n-\t\tnew_cap = scev-\u003eexprs_cap ? scev-\u003eexprs_cap * 2 : 256;\n-\t\ttmp = kvrealloc(scev-\u003eexprs, sizeof(struct expr) * new_cap, GFP_KERNEL_ACCOUNT);\n-\t\tif (!tmp)\n-\t\t\treturn -ENOMEM;\n-\t\tscev-\u003eexprs = tmp;\n-\t\tscev-\u003eexprs_cap = new_cap;\n+\t/*\n+\t * bpf_dynptr_slice_rdwr() can return the buffer that it got. A store through that slice may\n+\t * alias the slots of the buffer and is in no bpf_may_write_mask(): it is no def, so a def\n+\t * of such a slot is no value number. A spill through r10 has the expression of the\n+\t * register, and invalidate_stack_slices() invalidates the slices there. The next slice\n+\t * comes from a call that may write to the slot.\n+\t */\n+\tif (e-\u003edef.set)\n+\t\treturn reg \u003c MAX_BPF_REG || reg \u003e= REGS_NUM ||\n+\t\t !test_bit(reg - MAX_BPF_REG, scev-\u003eslice_slots);\n+\tswitch (e-\u003eop) {\n+\tcase UNKNOWN:\n+\tcase OPAQUE:\n+\tcase ANY:\n+\t/* a partial spill: the other bits of the slot are not known */\n+\tcase SPILL8:\n+\tcase SPILL16:\n+\tcase SPILL32:\n+\t/* a function of the iteration number */\n+\tcase LINEAR_SCEV:\n+\t/* a relation between header phis */\n+\tcase ADD_SCEV:\n+\t\treturn false;\n \t}\n+\tfor (i = 0; i \u003c op_params_num(e-\u003eop); i++)\n+\t\tif (!scev-\u003eexprs[e-\u003eparams[i]].is_vn)\n+\t\t\treturn false;\n+\treturn true;\n+}\n+\n+static u32 op_low_bits(u32 op);\n+\n+/*\n+ * @e gets the id @id. (+ x imm), an extension and a partial spill of x have the base of x, which\n+ * was constructed earlier. Every other expression is its own base. So split_const_offset() does not\n+ * traverse the expression.\n+ */\n+static void set_expr_base(struct scev *scev, struct expr *e, u32 id)\n+{\n+\tu32 low = op_low_bits(e-\u003eop);\n+\tstruct expr *x;\n+\ts64 imm = 0;\n+\n+\te-\u003earena_add = 0;\n+\t/* mk_phi() found the base */\n+\tif (e-\u003edef.phi \u0026\u0026 e-\u003ebase)\n+\t\treturn;\n+\te-\u003ebase = id;\n+\te-\u003eoff = 0;\n+\te-\u003ebits = 64;\n+\t/* nothing looks through a phi, see struct expr_def */\n+\tif (e-\u003edef.phi)\n+\t\treturn;\n+\tif (e-\u003eop == BPF_ADD \u0026\u0026 scev-\u003eexprs[e-\u003eparams[1]].op == IMM)\n+\t\timm = scev-\u003eexprs[e-\u003eparams[1]].imm;\n+\telse if (!low || e-\u003edef.set)\n+\t\treturn;\n+\tx = \u0026scev-\u003eexprs[e-\u003eparams[0]];\n+\te-\u003ebase = x-\u003ebase;\n+\te-\u003eoff = (u64)x-\u003eoff + imm;\n+\te-\u003ebits = low ? min(x-\u003ebits, low) : x-\u003ebits;\n+\te-\u003earena_add = e-\u003edef.set ? id : x-\u003earena_add;\n+}\n+\n+static int add_expr(struct scev *scev, struct expr e)\n+{\n+\tu32 id;\n+\n+\tif (e.op == REG)\n+\t\treturn REG_EXPR_ID(e.params[0]);\n+\tif (!e.def.set \u0026\u0026 !e.imm \u0026\u0026 (e.op == UNKNOWN || e.op == OPAQUE))\n+\t\treturn e.op == UNKNOWN ? UNKNOWN_EXPR_ID : OPAQUE_EXPR_ID;\n+\n+\tid = scev-\u003eexprs_ht[expr_hash(\u0026e) \u0026 (scev-\u003eexprs_cap - 1)];\n+\tfor (; id; id = scev-\u003eexprs_next[id])\n+\t\tif (expr_eq(scev, \u0026e, id))\n+\t\t\treturn id;\n+\n+\tif (scev-\u003eexprs_cnt == scev-\u003eexprs_cap \u0026\u0026 grow_exprs(scev, scev-\u003eexprs_cap * 2))\n+\t\treturn -ENOMEM;\n \n \tid = scev-\u003eexprs_cnt++;\n+\te.is_vn = expr_is_vn(scev, \u0026e);\n+\tset_expr_base(scev, \u0026e, id);\n \tscev-\u003eexprs[id] = e;\n-\tbucket-\u003eids[bucket-\u003ecnt++] = id;\n+\texprs_ht_add(scev, id);\n \treturn id;\n }\n \n+static int simplify(struct scev *scev, u32 id);\n+\n+/*\n+ * An expression is simplified at construction. Its params are simplified already, so simplify()\n+ * rewrites the root only, whatever the depth of the expression.\n+ * The rules construct expressions too, and one rule can enable the next: the depth of (zext32\n+ * (spill32 (+ (spill32 (+ ..) 1)) 1)) is up to the prog. Beyond depth EXPR_STACK_DEPTH an\n+ * expression is correct, but not simplified.\n+ */\n static int expr2(struct scev *scev, u32 op, int a, int b)\n {\n+\tint id;\n+\n \tif (a \u003c 0)\n \t\treturn a;\n \tif (b \u003c 0)\n \t\treturn b;\n-\treturn add_expr(scev, (struct expr){ .op = op, .params = {a, b} });\n+\tid = add_expr(scev, (struct expr){ .op = op, .params = {a, b} });\n+\tif (id \u003c 0 || scev-\u003esimplify_depth == EXPR_STACK_DEPTH)\n+\t\treturn id;\n+\tscev-\u003esimplify_depth++;\n+\tid = simplify(scev, id);\n+\tscev-\u003esimplify_depth--;\n+\treturn id;\n }\n \n static int expr1(struct scev *scev, u32 op, int a)\n@@ -182,14 +382,38 @@ static int expr1(struct scev *scev, u32 op, int a)\n \treturn expr2(scev, op, a, 0);\n }\n \n-static int expr0(struct scev *scev, u32 op)\n+static int imm_expr(struct scev *scev, s64 value)\n {\n-\treturn expr2(scev, op, 0, 0);\n+\treturn add_expr(scev, (struct expr){ .op = IMM, .imm = value });\n }\n \n-static int imm_expr(struct scev *scev, s64 value)\n+/*\n+ * The insn at @idx defines @reg. Without its backedges and with nested loops collapsed the body is\n+ * acyclic: an insn executes at most once per iteration, so a def is one value per iteration. A\n+ * subprog is the outermost loop, which runs once.\n+ */\n+static struct expr_def insn_def(int idx, u32 reg)\n {\n-\treturn add_expr(scev, (struct expr){ .op = IMM, .imm = value });\n+\treturn (struct expr_def){ .set = 1, .reg = reg, .idx = idx };\n+}\n+\n+/* The phi of @reg before the insn at @idx. One value per iteration for the same reason. */\n+static struct expr_def phi_def(int idx, u32 reg)\n+{\n+\treturn (struct expr_def){ .set = 1, .phi = 1, .reg = reg, .idx = idx };\n+}\n+\n+/* @id with another def */\n+static int expr_with_def(struct scev *scev, int id, struct expr_def def)\n+{\n+\tstruct expr e;\n+\n+\tif (id \u003c 0)\n+\t\treturn id;\n+\te = scev-\u003eexprs[id];\n+\te.def = def;\n+\te.base = 0;\n+\treturn add_expr(scev, e);\n }\n \n static bool same_exprs(struct scev *scev, int id_a, int id_b)\n@@ -244,31 +468,74 @@ static bool is_zext32(struct scev *scev, int id, u32 *left)\n \treturn is_unop(scev, ZEXT32, id, left);\n }\n \n-/* The low half of the slot is the low half of @left. The other half is not known. */\n-static bool is_spill32(struct scev *scev, int id, u32 *left)\n+/* (zextN x), (sextN x) and (spillN x) depend on the low N bits of x only */\n+static u32 op_low_bits(u32 op)\n+{\n+\tswitch (op) {\n+\tcase ZEXT8:\n+\tcase SEXT8:\n+\tcase SPILL8:\n+\t\treturn 8;\n+\tcase ZEXT16:\n+\tcase SEXT16:\n+\tcase SPILL16:\n+\t\treturn 16;\n+\tcase ZEXT32:\n+\tcase SEXT32:\n+\tcase SPILL32:\n+\t\treturn 32;\n+\t}\n+\treturn 0;\n+}\n+\n+/* The low @bits bits of the slot are those of @left. The other bits are not known. */\n+static bool is_spill(struct scev *scev, int id, u32 *bits, u32 *left)\n {\n+\tu32 op = scev-\u003eexprs[id].op;\n+\n #ifdef __BIG_ENDIAN\n \t/* '*(u32 *)(r10 - 8) = rX' writes the high half, see mk_fill() */\n \treturn false;\n #endif\n-\treturn is_unop(scev, SPILL32, id, left);\n+\tif (op != SPILL8 \u0026\u0026 op != SPILL16 \u0026\u0026 op != SPILL32)\n+\t\treturn false;\n+\t*bits = op_low_bits(op);\n+\t*left = scev-\u003eexprs[id].params[0];\n+\treturn true;\n }\n \n-static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)\n+static bool is_spill32(struct scev *scev, int id, u32 *left)\n {\n-\treturn is_binop(scev, ANY, id, left, right);\n+\tu32 bits;\n+\n+\treturn is_spill(scev, id, \u0026bits, left) \u0026\u0026 bits == 32;\n }\n \n-static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)\n+/* (zextN x), (sextN x) or (spillN x) with N \u003e= @bits: the low @bits bits are those of @left */\n+static bool is_low_bits(struct scev *scev, int id, u32 bits, u32 *left)\n {\n-\treturn is_binop(scev, LINEAR_SCEV, id, base, slope);\n+\tu32 op = scev-\u003eexprs[id].op;\n+\n+#ifdef __BIG_ENDIAN\n+\t/* see is_spill() */\n+\tif (op == SPILL8 || op == SPILL16 || op == SPILL32)\n+\t\treturn false;\n+#endif\n+\t/* nothing looks through a phi, see struct expr_def */\n+\tif (op_low_bits(op) \u003c bits || scev-\u003eexprs[id].def.phi)\n+\t\treturn false;\n+\t*left = scev-\u003eexprs[id].params[0];\n+\treturn true;\n }\n \n-static bool is_copy(struct scev *scev, int id, u32 *reg, u32 *orig)\n+static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)\n {\n-\tu32 t;\n+\treturn is_binop(scev, ANY, id, left, right);\n+}\n \n-\treturn is_binop(scev, COPY_SCEV, id, \u0026t, orig) \u0026\u0026 is_reg(scev, t, reg);\n+static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)\n+{\n+\treturn is_binop(scev, LINEAR_SCEV, id, base, slope);\n }\n \n static bool is_linear_or_linear32(struct scev *scev, int id, u32 *base, u32 *slope, bool *zext32)\n@@ -296,8 +563,10 @@ static void log_reg(struct bpf_verifier_env *env, u32 reg)\n {\n \tif (reg \u003c MAX_BPF_REG)\n \t\tbpf_log(\u0026env-\u003elog, \"r%d\", reg);\n-\telse\n+\telse if (reg \u003c REGS_NUM)\n \t\tbpf_log(\u0026env-\u003elog, \"*fp%d\", (MAX_BPF_REG - reg - 1) * 8);\n+\telse\n+\t\tbpf_log(\u0026env-\u003elog, \"mem%d\", reg - REGS_NUM);\n }\n \n static const char *op_str(u32 op)\n@@ -331,7 +600,7 @@ static const char *op_str(u32 op)\n \tcase SPILL32: return \"spill32\";\n \tcase ANY: return \"any\";\n \tcase LINEAR_SCEV: return \"linear\";\n-\tcase COPY_SCEV: return \"copy\";\n+\tcase ADD_SCEV: return \"add\";\n \t}\n \treturn NULL;\n }\n@@ -354,7 +623,7 @@ static u32 op_params_num(u32 op)\n \tcase SMOD:\n \tcase ANY:\n \tcase LINEAR_SCEV:\n-\tcase COPY_SCEV:\n+\tcase ADD_SCEV:\n \t\treturn 2;\n \tcase BPF_NEG:\n \tcase SEXT8:\n@@ -428,27 +697,74 @@ static bool expr_next(struct scev *scev, u32 *id, u32 *order)\n \treturn expr_next(scev, id, order);\n }\n \n+/*\n+ * An SSA name is printed as '%', the SCEV register, '.', the insn. A def is printed in full at\n+ * every use: (+ %r8.7=phi(1, 2) 4).\n+ *\t%r0.6\t\t\tinsn 6 defines r0. The value is OPAQUE, '_' without a def\n+ *\t%fp-8.8?\t\tinsn 8 may write fp-8. The value is UNKNOWN, '?' without a def\n+ *\t%r8.7=phi(1, 2)\t\tthe phi of r8 before insn 7\n+ *\t%r0.7=phi(_)\t\ta phi of distinct OPAQUE values\n+ *\t%r6.9=phi(?)\t\ta phi of distinct UNKNOWN values, or of more than 8 values\n+ *\t%r2.12=(+ x 4)\t\tinsn 12 defines r2, see alu64_with_def()\n+ *\t%r2.25=phi((+ x 4))\ttwo adds of one shape, each may have been converted to ALU32:\n+ *\t\t\t\tthe phi is not (+ x 4)\n+ * A name is unique within the env of one loop. In the env of loop H a phi at H merges the backedge\n+ * values only, the header phi itself is (REG r): in 'scev at header 1: r6=%r6.1=phi(r6, (+ r6 1))'\n+ * one backedge leaves r6 as it is, the other one adds 1.\n+ * '%' in front of r or fp is a name, followed by a blank it is BPF_MOD.\n+ */\n+static void log_def(struct bpf_verifier_env *env, struct expr_def def)\n+{\n+\tif (!def.set)\n+\t\treturn;\n+\tif (def.reg \u003c MAX_BPF_REG)\n+\t\tbpf_log(\u0026env-\u003elog, \"%%r%d.%d\", def.reg, def.idx);\n+\telse if (def.reg \u003c REGS_NUM)\n+\t\tbpf_log(\u0026env-\u003elog, \"%%fp%d.%d\", (MAX_BPF_REG - def.reg - 1) * 8, def.idx);\n+\telse\n+\t\tbpf_log(\u0026env-\u003elog, \"%%mem%d.%d\", def.reg - REGS_NUM, def.idx);\n+}\n+\n static void log_expr(struct bpf_verifier_env *env, u32 id)\n {\n \tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tbool operand, bare, first = false;\n \tstruct scev *scev = env-\u003escev;\n+\tu32 order, d, bare_any = 0;\n+\tstruct expr_def def;\n \tstruct expr *expr;\n \tconst char *str;\n-\tu32 order;\n \n \tscev-\u003estack_sz = 0;\n \texpr_stack_push(scev, id);\n \twhile (expr_next(scev, \u0026id, \u0026order)) {\n-\t\tif ((order \u0026 PRE) \u0026\u0026 scev-\u003estack_sz \u003e 1)\n-\t\t\tbpf_log(log, \" \");\n \t\texpr = \u0026scev-\u003eexprs[id];\n+\t\tdef = expr-\u003edef;\n+\t\t/* the depth of @id in expr_stack[], expr_next() pops it before POST */\n+\t\td = order \u0026 PRE ? scev-\u003estack_sz - 1 : scev-\u003estack_sz;\n+\t\toperand = d \u0026\u0026 (bare_any \u0026 BIT(d - 1));\n+\t\t/* No '(any' for the operands of phi(a, b). (any a b) among them is expanded. */\n+\t\tif (order \u0026 PRE) {\n+\t\t\tbare_any \u0026= ~BIT(d);\n+\t\t\tif (expr-\u003eop == ANY \u0026\u0026 (def.set ? def.phi : operand))\n+\t\t\t\tbare_any |= BIT(d);\n+\t\t}\n+\t\tbare = bare_any \u0026 BIT(d);\n+\t\tif ((order \u0026 PRE) \u0026\u0026 (def.set || !bare)) {\n+\t\t\tif (d)\n+\t\t\t\tbpf_log(log, \"%s\", !operand ? \" \" : first ? \"\" : \", \");\n+\t\t\tlog_def(env, def);\n+\t\t\tif (def.phi)\n+\t\t\t\tbpf_log(log, \"=phi(\");\n+\t\t\tfirst = bare;\n+\t\t}\n \t\tswitch (expr-\u003eop) {\n \t\tcase UNKNOWN:\n \t\t\tif (order \u0026 PRE)\n \t\t\t\tbpf_log(log, \"?\");\n \t\t\tbreak;\n \t\tcase OPAQUE:\n-\t\t\tif (order \u0026 PRE)\n+\t\t\tif ((order \u0026 PRE) \u0026\u0026 (!def.set || def.phi))\n \t\t\t\tbpf_log(log, \"_\");\n \t\t\tbreak;\n \t\tcase REG:\n@@ -460,19 +776,23 @@ static void log_expr(struct bpf_verifier_env *env, u32 id)\n \t\t\t\tbpf_log(log, \"%lld\", expr-\u003eimm);\n \t\t\tbreak;\n \t\tdefault:\n-\t\t\tif (order \u0026 PRE) {\n+\t\t\tif ((order \u0026 PRE) \u0026\u0026 !bare) {\n \t\t\t\tstr = op_str(expr-\u003eop);\n-\t\t\t\tbpf_log(log, \"(\");\n+\t\t\t\tbpf_log(log, def.set \u0026\u0026 !def.phi ? \"=(\" : \"(\");\n \t\t\t\tif (str)\n \t\t\t\t\tbpf_log(log, \"%s\", str);\n \t\t\t\telse\n \t\t\t\t\tbpf_log(log, \"bad-expr-op %x\", expr-\u003eop);\n \t\t\t}\n-\t\t\tif (order \u0026 DEPTH_LIMIT)\n-\t\t\t\tbpf_log(log, \"...\");\n-\t\t\tif (order \u0026 POST)\n+\t\t\tif (order \u0026 DEPTH_LIMIT) {\n+\t\t\t\tbpf_log(log, bare \u0026\u0026 !def.set \u0026\u0026 !first ? \", ...\" : \"...\");\n+\t\t\t\tfirst = false;\n+\t\t\t}\n+\t\t\tif ((order \u0026 POST) \u0026\u0026 !bare)\n \t\t\t\tbpf_log(log, \")\");\n \t\t}\n+\t\tif ((order \u0026 POST) \u0026\u0026 def.phi)\n+\t\t\tbpf_log(log, \")\");\n \t}\n }\n \n@@ -481,11 +801,27 @@ static bool reg_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)\n \tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n \tu16 live_regs = aux[insn_idx].live_regs_before;\n \n+\t/* memory */\n+\tif (reg \u003e= REGS_NUM)\n+\t\treturn true;\n \treturn reg \u003c MAX_BPF_REG\n \t ? (BIT(reg) \u0026 live_regs)\n \t : test_bit(reg - MAX_BPF_REG, aux[insn_idx].live_stack_before);\n }\n \n+/* The first bytes of a stack slot are its high bits */\n+static bool is_big_endian_slot(u32 reg)\n+{\n+\treturn IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) \u0026\u0026 reg \u003e= MAX_BPF_REG;\n+}\n+\n+/* Are the upper 32 bits of @reg live before the insn at @insn_idx? */\n+static bool hi32_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)\n+{\n+\treturn reg \u003c MAX_BPF_REG || is_big_endian_slot(reg) ||\n+\t bpf_half_slot_live_before(env, insn_idx, (reg - MAX_BPF_REG) * 2);\n+}\n+\n static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx)\n {\n \tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n@@ -512,7 +848,7 @@ static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx)\n \t\tlog_reg(env, i);\n \t\tbpf_log(log, \"=\");\n \t\tlog_expr(env, e-\u003ereg2expr[i]);\n-\t\tif (e-\u003ereg2expr[i] != UNKNOWN_EXPR_ID) {\n+\t\tif (!is_op(scev, e-\u003ereg2expr[i], UNKNOWN)) {\n \t\t\tbpf_log(log, \" / \");\n \t\t\tlog_expr(env, e-\u003ereg2scev[i]);\n \t\t}\n@@ -554,7 +890,7 @@ static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx\n \tif (!e)\n \t\treturn NULL;\n \n-\ttmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT);\n+\ttmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT | __GFP_ZERO);\n \tif (!tmp) {\n \t\tkfree(e);\n \t\treturn NULL;\n@@ -568,6 +904,25 @@ static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx\n \treturn e;\n }\n \n+/* The env has no users any more */\n+static void free_loop_env(struct scev *scev, int loop_header, int insn_idx)\n+{\n+\tstruct insn_envs *envs = scev-\u003eenvs[insn_idx];\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c envs-\u003ecnt; i++) {\n+\t\tif (envs-\u003eentries[i].loop_header != loop_header)\n+\t\t\tcontinue;\n+\t\tkfree(envs-\u003eentries[i].env);\n+\t\tenvs-\u003eentries[i] = envs-\u003eentries[--envs-\u003ecnt];\n+\t\tbreak;\n+\t}\n+\tif (envs-\u003ecnt || envs-\u003elinked_cnt)\n+\t\treturn;\n+\tkfree(envs);\n+\tscev-\u003eenvs[insn_idx] = NULL;\n+}\n+\n static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)\n {\n \tif (id \u003c 0)\n@@ -576,10 +931,15 @@ static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)\n \treturn 0;\n }\n \n-static int setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, int insn_idx)\n+/* The insn at @idx defines @reg. The value is not tracked: @id is UNKNOWN or OPAQUE. */\n+static int forget_reg(struct scev *scev, struct env *e, u32 reg, int id, int idx)\n {\n-\tstruct scev *scev = env-\u003escev;\n-\tint i, err;\n+\treturn replace_reg(scev, e, reg, expr_with_def(scev, id, insn_def(idx, reg)));\n+}\n+\n+static void setup_initial_loop_env(struct env *e)\n+{\n+\tint i;\n \n \t/*\n \t * Initial assignments are of form rX -\u003e rX are needed as seeds for subsequent\n@@ -587,25 +947,29 @@ static int setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, i\n \t * join() will overwrite the them. compute_header_scevs() accounts for register\n \t * states at loop entry.\n \t */\n-\tfor (i = 0; i \u003c REGS_NUM; i++) {\n-\t\terr = replace_reg(scev, e, i, expr1(scev, REG, i));\n-\t\tif (err)\n-\t\t\treturn err;\n-\t}\n-\treturn 0;\n+\tfor (i = 0; i \u003c REGS_NUM; i++)\n+\t\te-\u003ereg2expr[i] = REG_EXPR_ID(i);\n }\n \n-static void forget_call_regs(struct env *e)\n+/* A subprog can return a pair in r0 and r2: a call defines r1 - r5 too if they are live after it */\n+static int forget_call_regs(struct bpf_verifier_env *env, struct env *e, int idx)\n {\n-\tint i;\n+\tint i, err;\n \n-\tfor (i = BPF_REG_0; i \u003c= BPF_REG_5; i++)\n+\tfor (i = BPF_REG_0; i \u003c= BPF_REG_5; i++) {\n \t\te-\u003ereg2expr[i] = UNKNOWN_EXPR_ID;\n+\t\tif (idx + 1 \u003e= env-\u003eprog-\u003elen || !reg_alive_at(env, i, idx + 1))\n+\t\t\tcontinue;\n+\t\terr = forget_reg(env-\u003escev, e, i, UNKNOWN_EXPR_ID, idx);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\treturn 0;\n }\n \n static u32 spill_spi(struct bpf_insn *insn)\n {\n-\treturn -insn-\u003eoff / BPF_REG_SIZE - 1;\n+\treturn (-insn-\u003eoff - 1) / BPF_REG_SIZE;\n }\n \n static u32 off_to_reg(struct bpf_insn *insn)\n@@ -620,16 +984,19 @@ static bool is_spill_off(int off)\n \t off \u003e= -MAX_BPF_STACK_JIT;\n }\n \n-static void mark_opaque(struct env *e, int off, int size)\n+static int mark_opaque(struct scev *scev, struct env *e, int idx, int off, int size)\n {\n-\tint b, spi;\n+\tint b, spi, err;\n \n \tfor (b = off; b \u003c off + size; b++) {\n \t\tif (b \u003e= 0 || b \u003c -MAX_BPF_STACK_JIT)\n \t\t\tcontinue;\n \t\tspi = (-b - 1) / BPF_REG_SIZE;\n-\t\te-\u003ereg2expr[MAX_BPF_REG + spi] = OPAQUE_EXPR_ID;\n+\t\terr = forget_reg(scev, e, MAX_BPF_REG + spi, OPAQUE_EXPR_ID, idx);\n+\t\tif (err)\n+\t\t\treturn err;\n \t}\n+\treturn 0;\n }\n \n static int mk_spill(struct scev *scev, u8 size, int id)\n@@ -643,18 +1010,40 @@ static int mk_spill(struct scev *scev, u8 size, int id)\n \treturn UNKNOWN_EXPR_ID;\n }\n \n-static int mk_fill(struct scev *scev, int id, u8 code)\n+/* The size of the spill in a slot with the expression @id. It holds the low bytes of *@x. */\n+static u32 expr_spill_size(struct scev *scev, u32 id, u32 *x)\n {\n-\tbool sx = BPF_MODE(code) == BPF_MEMSX;\n+\tstruct expr *e = \u0026scev-\u003eexprs[id];\n+\t/* nothing looks through a phi, see struct expr_def */\n+\tbool partial = (e-\u003eop == SPILL8 || e-\u003eop == SPILL16 || e-\u003eop == SPILL32) \u0026\u0026 !e-\u003edef.phi;\n \n+\t*x = partial ? e-\u003eparams[0] : id;\n+\treturn partial ? op_low_bits(e-\u003eop) / BITS_PER_BYTE : BPF_REG_SIZE;\n+}\n+\n+/* -ENOENT: the value of the fill is not known */\n+static int mk_fill(struct scev *scev, int id, struct bpf_insn *insn)\n+{\n+\tu32 x, spill_size = expr_spill_size(scev, id, \u0026x);\n+\tu32 size = bpf_size_to_bytes(BPF_SIZE(insn-\u003ecode));\n+\tbool sx = BPF_MODE(insn-\u003ecode) == BPF_MEMSX;\n+\n+\t/* The fill reads the low bytes of the spill, as in check_stack_read_fixed_off() */\n+\tif (size \u003c= spill_size \u0026\u0026 bpf_stack_narrow_access_ok(insn-\u003eoff, size, spill_size))\n+\t\tid = x;\n+\telse if (!is_spill_off(insn-\u003eoff))\n+\t\treturn -ENOENT;\n #ifdef __BIG_ENDIAN\n+\t/* No register becomes (spillN x): its low bits would not be those of x */\n+\telse if (spill_size \u003c BPF_REG_SIZE)\n+\t\treturn -ENOENT;\n \t/* A narrow fill reads the high bits of the slot on big-endian. */\n-\tif (BPF_SIZE(code) != BPF_DW)\n+\telse\n \t\treturn expr2(scev, sx ? BPF_ARSH : BPF_RSH, id,\n-\t\t\t imm_expr(scev, 64 - BITS_PER_BYTE * bpf_size_to_bytes(BPF_SIZE(code))));\n+\t\t\t imm_expr(scev, BITS_PER_BYTE * (BPF_REG_SIZE - size)));\n #endif\n \n-\tswitch (BPF_SIZE(code)) {\n+\tswitch (BPF_SIZE(insn-\u003ecode)) {\n \tcase BPF_B: return expr1(scev, sx ? SEXT8 : ZEXT8, id);\n \tcase BPF_H: return expr1(scev, sx ? SEXT16 : ZEXT16, id);\n \tcase BPF_W: return expr1(scev, sx ? SEXT32 : ZEXT32, id);\n@@ -663,7 +1052,7 @@ static int mk_fill(struct scev *scev, int id, u8 code)\n \treturn UNKNOWN_EXPR_ID;\n }\n \n-static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int id)\n+static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int idx, int id)\n {\n \tu8 size = BPF_SIZE(insn-\u003ecode);\n \n@@ -671,25 +1060,205 @@ static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *ins\n \t\treturn 0;\n \tif (is_spill_off(insn-\u003eoff))\n \t\treturn replace_reg(scev, e, off_to_reg(insn), mk_spill(scev, size, id));\n-\tmark_opaque(e, insn-\u003eoff, bpf_size_to_bytes(size));\n-\treturn 0;\n+\treturn mark_opaque(scev, e, idx, insn-\u003eoff, bpf_size_to_bytes(size));\n }\n \n-static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn)\n+static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int idx)\n {\n-\tint id;\n+\tint id = -ENOENT;\n \n-\tif (insn-\u003esrc_reg == BPF_REG_FP \u0026\u0026 is_spill_off(insn-\u003eoff))\n-\t\tid = mk_fill(scev, e-\u003ereg2expr[off_to_reg(insn)], insn-\u003ecode);\n-\telse\n-\t\tid = OPAQUE_EXPR_ID;\n+\tif (insn-\u003esrc_reg == BPF_REG_FP \u0026\u0026 insn-\u003eoff \u003c 0 \u0026\u0026 insn-\u003eoff \u003e= -MAX_BPF_STACK_JIT)\n+\t\tid = e-\u003ereg2expr[off_to_reg(insn)];\n+\t/*\n+\t * The def of a slot that a slice may alias is no value number, see expr_is_vn(): two fills\n+\t * can read distinct values. One fill reads one value: the insn defines the register.\n+\t */\n+\tif (id \u003e= 0 \u0026\u0026 scev-\u003eexprs[id].def.set \u0026\u0026 !scev-\u003eexprs[id].is_vn)\n+\t\tid = -ENOENT;\n+\tif (id \u003e= 0)\n+\t\tid = mk_fill(scev, id, insn);\n+\tif (id == -ENOENT)\n+\t\treturn forget_reg(scev, e, insn-\u003edst_reg, OPAQUE_EXPR_ID, idx);\n \treturn replace_reg(scev, e, insn-\u003edst_reg, id);\n }\n \n+static bool const_diff(struct bpf_verifier_env *env, int h, u32 id_a, u32 id_b, s64 *delta,\n+\t\t u32 *bits);\n+\n+/* The memory location of @e at the address @addr, 0: one that is not in use. MEM_REGS_NUM: none. */\n+static u32 find_mem_reg(const struct env *e, u32 addr)\n+{\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c MEM_REGS_NUM \u0026\u0026 e-\u003emem_addr[i] != addr; i++)\n+\t\t;\n+\treturn i;\n+}\n+\n+static void forget_mem_reg(struct env *e, u32 i)\n+{\n+\te-\u003emem_addr[i] = 0;\n+\te-\u003ereg2expr[REGS_NUM + i] = UNKNOWN_EXPR_ID;\n+}\n+\n+/*\n+ * The insn may write @size bytes at the address @addr, 0: anywhere. A may-def of all memory\n+ * locations but those that have the same address base and don't overlap. Two bases can be two names\n+ * of one memory, 'f(\u0026c, \u0026c)'.\n+ */\n+static void forget_mem_regs(struct bpf_verifier_env *env, struct env *e, u32 addr, u32 size)\n+{\n+\tu32 i, x, bits;\n+\ts64 delta;\n+\n+\tfor (i = 0; i \u003c MEM_REGS_NUM; i++) {\n+\t\t/* the caller defines it */\n+\t\tif (e-\u003emem_addr[i] == addr)\n+\t\t\tcontinue;\n+\t\tif (addr \u0026\u0026 const_diff(env, -1, addr, e-\u003emem_addr[i], \u0026delta, \u0026bits) \u0026\u0026\n+\t\t bits == 64 \u0026\u0026 (delta \u003e= size ||\n+\t\t delta + expr_spill_size(env-\u003escev, e-\u003ereg2expr[REGS_NUM + i], \u0026x) \u003c= 0))\n+\t\t\tcontinue;\n+\t\tforget_mem_reg(e, i);\n+\t}\n+}\n+\n+/*\n+ * A jump tests a register, and a load makes a new value number. So a memory location is dead once\n+ * no register that is live after the insn at @idx has the base of its value: no jump is going to\n+ * link it.\n+ */\n+static void forget_dead_mem_regs(struct bpf_verifier_env *env, struct env *e, int idx)\n+{\n+\tstruct expr *exprs = env-\u003escev-\u003eexprs;\n+\tu32 i, r, base;\n+\n+\tfor (i = 0; i \u003c MEM_REGS_NUM; i++) {\n+\t\tbase = exprs[e-\u003ereg2expr[REGS_NUM + i]].base;\n+\t\tfor (r = 0; r \u003c REGS_NUM; r++)\n+\t\t\tif (exprs[e-\u003ereg2expr[r]].base == base \u0026\u0026 reg_alive_at(env, r, idx + 1))\n+\t\t\t\tbreak;\n+\t\tif (r == REGS_NUM)\n+\t\t\tforget_mem_reg(e, i);\n+\t}\n+}\n+\n+/*\n+ * The address of the load or store at @idx through @reg, 0: the memory is not tracked. r10 has the\n+ * stack slots, r11 and r12 are no SCEV registers. The main pass takes nothing but stack.\n+ */\n+static int mk_mem_addr(struct bpf_verifier_env *env, struct env *e, int idx, u32 reg)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\n+\tif (reg \u003e= BPF_REG_FP || !(env-\u003einsn_aux_data[idx].stack_ptrs \u0026 BIT(reg)) ||\n+\t !scev-\u003eexprs[e-\u003ereg2expr[reg]].is_vn)\n+\t\treturn 0;\n+\treturn expr2(scev, BPF_ADD, e-\u003ereg2expr[reg], imm_expr(scev, env-\u003eprog-\u003einsnsi[idx].off));\n+}\n+\n+/*\n+ * The insn at @idx stored the low bytes of @id at the address @addr, or it loaded them from there.\n+ * The location takes a SCEV register that is not in use, or that of a dead one.\n+ */\n+static int replace_mem_reg(struct bpf_verifier_env *env, struct env *e, int idx, int addr, int id)\n+{\n+\tu32 i;\n+\n+\tif (addr \u003c= 0)\n+\t\treturn addr;\n+\ti = find_mem_reg(e, addr);\n+\tif (i == MEM_REGS_NUM)\n+\t\ti = find_mem_reg(e, 0);\n+\tif (i == MEM_REGS_NUM) {\n+\t\tforget_dead_mem_regs(env, e, idx);\n+\t\ti = find_mem_reg(e, 0);\n+\t}\n+\tif (i == MEM_REGS_NUM)\n+\t\treturn 0;\n+\te-\u003emem_addr[i] = addr;\n+\treturn replace_reg(env-\u003escev, e, REGS_NUM + i,\n+\t\t\t mk_spill(env-\u003escev, BPF_SIZE(env-\u003eprog-\u003einsnsi[idx].code), id));\n+}\n+\n+static int load_mem(struct bpf_verifier_env *env, struct env *e, int idx)\n+{\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\t/* the insn defines dst_reg, which can be src_reg */\n+\tint addr = mk_mem_addr(env, e, idx, insn-\u003esrc_reg);\n+\n+\treturn maybe_load_fp(env-\u003escev, e, insn, idx) ?:\n+\t replace_mem_reg(env, e, idx, addr, e-\u003ereg2expr[insn-\u003edst_reg]);\n+}\n+\n+static int store_mem(struct bpf_verifier_env *env, struct env *e, int idx, int id)\n+{\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\tint addr;\n+\n+\tif (insn-\u003edst_reg == BPF_REG_FP)\n+\t\treturn maybe_store_fp(env-\u003escev, e, insn, idx, id);\n+\taddr = mk_mem_addr(env, e, idx, insn-\u003edst_reg);\n+\tif (addr \u003c 0)\n+\t\treturn addr;\n+\tforget_mem_regs(env, e, addr, bpf_size_to_bytes(BPF_SIZE(insn-\u003ecode)));\n+\treturn replace_mem_reg(env, e, idx, addr, id);\n+}\n+\n+/*\n+ * The low 32 bits of a + b depend on the low 32 bits of a and b only: 'w1 += w2' is\n+ * (zext32 (+ a b)). That doesn't hold for a right shift and for a division. Their operands are zero\n+ * or sign extended and a shift amount is masked, so that every expression is a 64-bit operation.\n+ */\n+static void alu32_operands(struct scev *scev, u32 op, int *a, int *b)\n+{\n+\ts64 imm = 0;\n+\tbool imm_b = *b \u003e= 0 \u0026\u0026 is_imm(scev, *b, \u0026imm);\n+\n+\tswitch (op) {\n+\tcase BPF_RSH:\n+\tcase BPF_ARSH:\n+\t\t*a = expr1(scev, op == BPF_RSH ? ZEXT32 : SEXT32, *a);\n+\t\tfallthrough;\n+\tcase BPF_LSH:\n+\t\t*b = imm_b ? imm_expr(scev, imm \u0026 31) :\n+\t\t\t expr2(scev, BPF_AND, *b, imm_expr(scev, 31));\n+\t\tbreak;\n+\tcase BPF_DIV:\n+\tcase BPF_MOD:\n+\t\t*a = expr1(scev, ZEXT32, *a);\n+\t\t*b = imm_b ? imm_expr(scev, (u32)imm) : expr1(scev, ZEXT32, *b);\n+\t\tbreak;\n+\tcase SDIV:\n+\tcase SMOD:\n+\t\t*a = expr1(scev, SEXT32, *a);\n+\t\t*b = imm_b ? imm_expr(scev, (s32)imm) : expr1(scev, SEXT32, *b);\n+\t\tbreak;\n+\t}\n+}\n+\n+/*\n+ * In a prog with an arena an ALU64 insn is converted to ALU32 at fixup if an operand is a pointer\n+ * to the arena, see adjust_reg_min_max_vals(). Types are not known here. So @id, what the insn at\n+ * @idx computes from @a, gets a def: the value of @dst after the insn, converted or not. See\n+ * split_const_offset() for when the op can be trusted. Constant operands are scalars in every\n+ * state.\n+ */\n+static int alu64_with_def(struct scev *scev, int id, int a, int idx, u32 dst)\n+{\n+\ts64 imm;\n+\n+\tif (id \u003c 0 || is_imm(scev, id, \u0026imm))\n+\t\treturn id;\n+\t/* (+ x 0) is x only if the insn stays ALU64 */\n+\treturn expr_with_def(scev, id == a ? UNKNOWN_EXPR_ID : id, insn_def(idx, dst));\n+}\n+\n static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)\n {\n \tconst bool little_endian = htons(0x3412) == 0x1234;\n \tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\tbool arena = env-\u003eprog-\u003eaux-\u003earena;\n \tstruct scev *scev = env-\u003escev;\n \tu32 *reg2expr = e-\u003ereg2expr;\n \tu8 class = BPF_CLASS(insn-\u003ecode);\n@@ -698,9 +1267,9 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)\n \tu8 mode = BPF_MODE(insn-\u003ecode);\n \tu32 dst = insn-\u003edst_reg;\n \tu32 src = insn-\u003esrc_reg;\n-\tu32 op, sext, l, r;\n+\tu32 op, sext;\n \tbool need_bswap;\n-\tint i, id;\n+\tint i, id, a;\n \ts64 imm;\n \n \t/* reg2expr[12] is a stack slot, not r12 */\n@@ -764,22 +1333,15 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)\n \t\t\telse\n \t\t\t\tgoto mark_dst_unknown;\n \n-\t\t\t/*\n-\t\t\t * 'r1 \u003c\u003c= 32; r1 \u003e\u003e= 32' is (u32)r1 for cpu v1 and v2. Only here both\n-\t\t\t * shifts are known to be 64-bit ones: the result of a 32-bit shift is\n-\t\t\t * (zext32 ...), and (\u003e\u003e x 32) is 'w1 \u003e\u003e= w2' with 32 in w2 as well,\n-\t\t\t * which shifts by 0.\n-\t\t\t */\n-\t\t\tif (class == BPF_ALU64 \u0026\u0026 op == BPF_RSH \u0026\u0026 id \u003e= 0 \u0026\u0026\n-\t\t\t is_imm(scev, id, \u0026imm) \u0026\u0026 imm == 32 \u0026\u0026\n-\t\t\t is_binop(scev, BPF_LSH, reg2expr[dst], \u0026l, \u0026r) \u0026\u0026\n-\t\t\t is_imm(scev, r, \u0026imm) \u0026\u0026 imm == 32)\n-\t\t\t\treturn replace_reg(scev, e, dst, expr1(scev, ZEXT32, l));\n-\n-\t\t\tid = expr2(scev, op, reg2expr[dst], id);\n+\t\t\ta = reg2expr[dst];\n+\t\t\tif (class == BPF_ALU)\n+\t\t\t\talu32_operands(scev, op, \u0026a, \u0026id);\n+\t\t\tid = expr2(scev, op, a, id);\n \n \t\t\tif (class == BPF_ALU)\n \t\t\t\tid = expr1(scev, ZEXT32, id);\n+\t\t\telse if (arena)\n+\t\t\t\tid = alu64_with_def(scev, id, a, idx, dst);\n \n \t\t\treturn replace_reg(scev, e, dst, id);\n \n@@ -829,47 +1391,53 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)\n \t\t\t\timm = env-\u003einsn_aux_data[idx + 1].const_reg_vals[dst];\n \t\t\t\treturn replace_reg(scev, e, dst, imm_expr(scev, imm));\n \t\t\t}\n-\t\t\treturn maybe_load_fp(scev, e, insn);\n+\t\t\treturn load_mem(env, e, idx);\n \t\tdefault:\n \t\t\tgoto mark_dst_unknown;\n \t\t}\n \tcase BPF_STX:\n \t\tswitch (mode) {\n \t\tcase BPF_MEM:\n-\t\t\treturn maybe_store_fp(scev, e, insn, reg2expr[src]);\n+\t\t\treturn store_mem(env, e, idx, reg2expr[src]);\n \t\tcase BPF_ATOMIC:\n \t\t\tif (insn-\u003eimm == BPF_LOAD_ACQ)\n-\t\t\t\treturn maybe_load_fp(scev, e, insn);\n+\t\t\t\treturn maybe_load_fp(scev, e, insn, idx);\n \t\t\tif (insn-\u003eimm == BPF_STORE_REL) {\n-\t\t\t\treturn maybe_store_fp(scev, e, insn, reg2expr[src]);\n+\t\t\t\treturn store_mem(env, e, idx, reg2expr[src]);\n \t\t\t}\n \t\t\t/*\n \t\t\t * verifier does not track other atomic ops precisely,\n \t\t\t * hence mark the results as opaque.\n \t\t\t */\n-\t\t\tif (insn-\u003edst_reg == BPF_REG_FP)\n-\t\t\t\tmark_opaque(e, insn-\u003eoff, bpf_size_to_bytes(BPF_SIZE(insn-\u003ecode)));\n+\t\t\tif (insn-\u003edst_reg == BPF_REG_FP) {\n+\t\t\t\tid = mark_opaque(scev, e, idx, insn-\u003eoff,\n+\t\t\t\t\t\t bpf_size_to_bytes(BPF_SIZE(insn-\u003ecode)));\n+\t\t\t\tif (id \u003c 0)\n+\t\t\t\t\treturn id;\n+\t\t\t} else {\n+\t\t\t\tforget_mem_regs(env, e, 0, 0);\n+\t\t\t}\n \t\t\tif (insn-\u003eimm == BPF_CMPXCHG)\n-\t\t\t\treturn replace_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID);\n+\t\t\t\treturn forget_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID, idx);\n \t\t\tif (insn-\u003eimm \u0026 BPF_FETCH)\n-\t\t\t\treturn replace_reg(scev, e, src, OPAQUE_EXPR_ID);\n+\t\t\t\treturn forget_reg(scev, e, src, OPAQUE_EXPR_ID, idx);\n \t\t\tbreak;\n \t\t}\n \t\tbreak;\n \tcase BPF_ST:\n-\t\tif (insn-\u003edst_reg == BPF_REG_FP) {\n-\t\t\tid = imm_expr(scev, insn-\u003eimm);\n-\t\t\tif (id \u003c 0)\n-\t\t\t\treturn id;\n-\t\t\treturn maybe_store_fp(scev, e, insn, id);\n-\t\t}\n-\t\tbreak;\n+\t\tid = imm_expr(scev, insn-\u003eimm);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t\treturn store_mem(env, e, idx, id);\n \tcase BPF_JMP:\n \tcase BPF_JMP32:\n \t\tif (opcode == BPF_CALL) {\n-\t\t\tforget_call_regs(e);\n+\t\t\tforget_mem_regs(env, e, 0, 0);\n+\t\t\tid = forget_call_regs(env, e, idx);\n+\t\t\tif (id \u003c 0)\n+\t\t\t\treturn id;\n \t\t\t/* made anew, like what is loaded. The parameter tells the two apart. */\n-\t\t\treturn replace_reg(scev, e, BPF_REG_0, expr1(scev, OPAQUE, 1));\n+\t\t\treturn forget_reg(scev, e, BPF_REG_0, expr1(scev, OPAQUE, 1), idx);\n \t\t}\n \t\t/* for non-CALL there are no changes in register states */\n \t\tbreak;\n@@ -883,12 +1451,11 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)\n \t\t\t}\n \t\t\t/* map, map value, BTF id, function */\n \t\t\tif (BPF_SIZE(insn-\u003ecode) == BPF_DW)\n-\t\t\t\treturn replace_reg(scev, e, dst, OPAQUE_EXPR_ID);\n+\t\t\t\treturn forget_reg(scev, e, dst, OPAQUE_EXPR_ID, idx);\n \t\t\tgoto mark_dst_unknown;\n \t\tcase BPF_ABS:\n \t\tcase BPF_IND:\n-\t\t\tforget_call_regs(e);\n-\t\t\tbreak;\n+\t\t\treturn forget_call_regs(env, e, idx);\n \t\tdefault:\n \t\t\tgoto mark_dst_unknown;\n \t\t}\n@@ -897,20 +1464,47 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)\n \t\t/* unknown instruction, nuke state */\n \t\tfor (i = 0; i \u003c REGS_NUM; i++)\n \t\t\treg2expr[i] = UNKNOWN_EXPR_ID;\n+\t\tforget_mem_regs(env, e, 0, 0);\n \t\tbreak;\n \t}\n \treturn 0;\n \n mark_dst_unknown:\n-\treg2expr[dst] = UNKNOWN_EXPR_ID;\n-\treturn 0;\n+\treturn forget_reg(scev, e, dst, UNKNOWN_EXPR_ID, idx);\n+}\n+\n+/*\n+ *\tif (c) sum += a[i]; else sum += b[i];\n+ * @id without defs: (+ r6 %r2.4) -\u003e (+ r6 _). A def tells one load from another. The code that\n+ * analyzes loops asks how a value is computed, and that is the same on both paths.\n+ * Beyond depth EXPR_STACK_DEPTH an expression keeps its defs: no user looks there.\n+ */\n+static int strip_defs(struct scev *scev, u32 id, u32 lvl)\n+{\n+\tstruct expr e = scev-\u003eexprs[id]; /* snapshot the expr before potential realloc */\n+\tint a;\n+\n+\tswitch (op_params_num(e.op)) {\n+\tcase 0:\n+\t\treturn e.def.set ? expr_with_def(scev, id, no_def) : id;\n+\tcase 1:\n+\t\tif (lvl == EXPR_STACK_DEPTH)\n+\t\t\treturn id;\n+\t\treturn expr1(scev, e.op, strip_defs(scev, e.params[0], lvl + 1));\n+\tdefault:\n+\t\tif (lvl == EXPR_STACK_DEPTH)\n+\t\t\treturn id;\n+\t\ta = strip_defs(scev, e.params[0], lvl + 1);\n+\t\treturn expr2(scev, e.op, a, strip_defs(scev, e.params[1], lvl + 1));\n+\t}\n }\n \n /*\n * Construct minimal 'ANY' expression by traversing 'a' and 'b'\n- * and accumulating non-duplicated non-ANY entries.\n+ * and accumulating non-duplicated non-ANY entries, without their defs.\n+ * 'def' is the def of the result, no_def if it has none.\n */\n-static int mk_any(struct scev *scev, int a, int b)\n+static int mk_any(struct scev *scev, int a, int b, struct expr_def def)\n {\n \tstruct expr_stack_elt *elt;\n \tstruct expr *expr;\n@@ -933,14 +1527,18 @@ static int mk_any(struct scev *scev, int a, int b)\n \t\t\tif (expr-\u003eop == ANY) {\n \t\t\t\tif (!expr_stack_push(scev, expr-\u003eparams[1]) ||\n \t\t\t\t !expr_stack_push(scev, expr-\u003eparams[0]))\n-\t\t\t\t\treturn UNKNOWN_EXPR_ID;\n+\t\t\t\t\treturn expr_with_def(scev, UNKNOWN_EXPR_ID, def);\n \t\t\t} else {\n-\t\t\t\tfor (j = 0; j \u003c ids_buf_sz; j++) {\n+\t\t\t\t/* the operands of an ANY have no defs already */\n+\t\t\t\tif (id == roots[i])\n+\t\t\t\t\tid = strip_defs(scev, id, 0);\n+\t\t\t\tif (id \u003c 0)\n+\t\t\t\t\treturn id;\n+\t\t\t\tfor (j = 0; j \u003c ids_buf_sz; j++)\n \t\t\t\t\tif (same_exprs(scev, scev-\u003eids_buf[j], id))\n \t\t\t\t\t\tgoto next;\n-\t\t\t\t}\n \t\t\t\tif (ids_buf_sz == ARRAY_SIZE(scev-\u003eids_buf))\n-\t\t\t\t\treturn UNKNOWN_EXPR_ID;\n+\t\t\t\t\treturn expr_with_def(scev, UNKNOWN_EXPR_ID, def);\n \t\t\t\tscev-\u003eids_buf[ids_buf_sz++] = id;\n \t\t\t}\n next:;\n@@ -954,12 +1552,77 @@ next:;\n \t\tif (id \u003c 0)\n \t\t\treturn id;\n \t}\n-\treturn id;\n+\treturn expr_with_def(scev, id, def);\n+}\n+\n+static void split_const_offset(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off,\n+\t\t\t u32 *bits);\n+\n+/* @id == *@base + *@off in 64 bits: no extension and no partial spill is stripped */\n+static void split_const_offset64(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 bits, l, r;\n+\n+\tsplit_const_offset(env, id, base, off, \u0026bits);\n+\tif (bits == 64)\n+\t\treturn;\n+\t*base = id;\n+\t*off = 0;\n+\tif (!scev-\u003eexprs[id].def.set \u0026\u0026 is_add(scev, id, \u0026l, \u0026r) \u0026\u0026 is_imm(scev, r, off))\n+\t\t*base = l;\n+}\n+\n+/*\n+ *\tif (c) { n = f(); m = n; } else { n = g(); m = n; }\tif (n \u003e 100) return 0;\tuse(m);\n+ * The phi of @reg before the insn at @idx. It merges @a, which came over the edges so far, and @b.\n+ * Phis are value numbered as GVN does it, by join point and operands, up to a constant offset:\n+ * a == base_a + off_a and b == base_b + off_b, so\n+ *\tphi == phi(base_a, base_b + off_b - off_a) + off_a\n+ * The phi of the bases is hashed without @reg. All registers that have a constant difference on\n+ * each edge get the same one, and const_diff() finds them as it finds 'x' and 'x + 4'. The next\n+ * edge merges the phi of the bases with the next base: the id stands for the list of the operands,\n+ * for any number of edges. No edge brings a phi of this join point, so every phi here gets a new\n+ * base with every edge.\n+ */\n+static int mk_phi(struct bpf_verifier_env *env, u32 a, u32 b, int idx, u32 reg)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 base_a, base_b;\n+\ts64 off_a, off_b;\n+\tstruct expr e;\n+\tint id;\n+\n+\tid = mk_any(scev, a, b, no_def);\n+\tif (id \u003c 0)\n+\t\treturn id;\n+\te = scev-\u003eexprs[id];\n+\te.def = phi_def(idx, reg);\n+\te.base = 0;\n+\tsplit_const_offset64(env, a, \u0026base_a, \u0026off_a);\n+\tsplit_const_offset64(env, b, \u0026base_b, \u0026off_b);\n+\tif (!expr_is_vn(scev, \u0026e) || !scev-\u003eexprs[base_a].is_vn || !scev-\u003eexprs[base_b].is_vn)\n+\t\treturn add_expr(scev, e);\n+\tid = base_b;\n+\tif (off_a != off_b)\n+\t\tid = expr2(scev, BPF_ADD, base_b, imm_expr(scev, (u64)off_b - off_a));\n+\tif (id \u003c 0)\n+\t\treturn id;\n+\tid = add_expr(scev, (struct expr){ .op = ANY, .params = { base_a, id },\n+\t\t\t\t\t .def = phi_def(idx, BASE_REG) });\n+\tif (id \u003c 0)\n+\t\treturn id;\n+\te.base = id;\n+\te.off = off_a;\n+\te.bits = 64;\n+\treturn add_expr(scev, e);\n }\n \n-static int join(struct scev *scev, struct env *acc, struct env *cur)\n+/* @acc is the env before the insn at @idx */\n+static int join(struct bpf_verifier_env *env, struct env *acc, struct env *cur, int idx)\n {\n-\tint i, id;\n+\tstruct scev *scev = env-\u003escev;\n+\tint i, j, id;\n \n \tif (acc-\u003eempty) {\n \t\tmemcpy(acc, cur, sizeof(*acc));\n@@ -967,9 +1630,18 @@ static int join(struct scev *scev, struct env *acc, struct env *cur)\n \t\treturn 0;\n \t}\n \n-\tfor (i = 0; i \u003c REGS_NUM; i++) {\n-\t\tif (!same_exprs(scev, acc-\u003ereg2expr[i], cur-\u003ereg2expr[i])) {\n-\t\t\tid = mk_any(scev, acc-\u003ereg2expr[i], cur-\u003ereg2expr[i]);\n+\tfor (i = 0; i \u003c ENV_REGS_NUM; i++) {\n+\t\t/* the address names a memory location. It has a phi if all edges track it. */\n+\t\tj = i \u003c REGS_NUM ? i : REGS_NUM + find_mem_reg(cur, acc-\u003emem_addr[i - REGS_NUM]);\n+\t\tif (j == ENV_REGS_NUM) {\n+\t\t\tforget_mem_reg(acc, i - REGS_NUM);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (!same_exprs(scev, acc-\u003ereg2expr[i], cur-\u003ereg2expr[j])) {\n+\t\t\t/* no phi for a dead register: pruned SSA */\n+\t\t\tid = reg_alive_at(env, i, idx) ?\n+\t\t\t mk_phi(env, acc-\u003ereg2expr[i], cur-\u003ereg2expr[j], idx, i) :\n+\t\t\t UNKNOWN_EXPR_ID;\n \t\t\tif (id \u003c 0)\n \t\t\t\treturn id;\n \t\t\tacc-\u003ereg2expr[i] = id;\n@@ -991,14 +1663,15 @@ static void forget_modified_regs(struct scev *scev, struct env *acc, struct env\n }\n \n /* For a loop H at `header`, mark any register modified as a result of H execution as unknown. */\n-static void forget_non_invariants(struct bpf_verifier_env *env, struct env *acc, int header)\n+static int forget_non_invariants(struct bpf_verifier_env *env, struct env *acc, int header)\n {\n \tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n \tstruct bpf_loop *loop = aux[header].loop;\n \tstruct scev *scev = env-\u003escev;\n-\tint i, idx, h;\n+\tint i, idx, h, err;\n \n \tacc-\u003eempty = false;\n+\tforget_mem_regs(env, acc, 0, 0);\n \tforget_modified_regs(scev, acc, find_header_env(scev, header));\n \tfor (i = 0; i \u003c loop-\u003eexits_cnt; i++) {\n \t\tidx = loop-\u003eexits[i].from;\n@@ -1033,6 +1706,15 @@ static void forget_non_invariants(struct bpf_verifier_env *env, struct env *acc,\n \t\t */\n \t\tforget_modified_regs(scev, acc, find_loop_env(scev, header, idx));\n \t}\n+\t/* the nested loop defines them at its header */\n+\tfor (i = 0; i \u003c REGS_NUM; i++) {\n+\t\tif (acc-\u003ereg2expr[i] != UNKNOWN_EXPR_ID)\n+\t\t\tcontinue;\n+\t\terr = forget_reg(scev, acc, i, UNKNOWN_EXPR_ID, header);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\treturn 0;\n }\n \n /* Order worklist in reverse post-order. */\n@@ -1051,7 +1733,7 @@ static int worklist_push(struct bpf_verifier_env *env, int loop_header, int idx)\n {\n \tstruct scev *scev = env-\u003escev;\n \tstruct scev_worklist *worklist = \u0026scev-\u003eworklist;\n-\tu32 tag = (u32)loop_header + 1;\n+\tu32 tag = loop_header + 2; /* -1 is a subprog */\n \n \tif (scev-\u003ediscovered[idx] == tag)\n \t\treturn 0;\n@@ -1107,7 +1789,7 @@ static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,\n \tlen = log-\u003eend_pos - null_pos;\n \tbpf_log(log, \"%*s\", max(37 - (int)len, 1), \" \");\n \tbpf_log(log, \" ; \");\n-\tfor (r = 0; r \u003c REGS_NUM; r++) {\n+\tfor (r = 0; r \u003c ENV_REGS_NUM; r++) {\n \t\told_id = old-\u003ereg2expr[r];\n \t\tnew_id = new-\u003ereg2expr[r];\n \t\tif (at == LOG_AT_TRANSFER \u0026\u0026 !reg_alive_at_succ(env, r, insn_idx))\n@@ -1122,6 +1804,10 @@ static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,\n \t\tif (any_changes)\n \t\t\tbpf_log(log, \", \");\n \t\tlog_reg(env, r);\n+\t\tif (r \u003e= REGS_NUM \u0026\u0026 new-\u003emem_addr[r - REGS_NUM]) {\n+\t\t\tbpf_log(log, \"=*\");\n+\t\t\tlog_expr(env, new-\u003emem_addr[r - REGS_NUM]);\n+\t\t}\n \t\tbpf_log(log, \" \");\n \t\tlog_expr(env, old_id);\n \t\tbpf_log(log, \" -\u003e \");\n@@ -1149,7 +1835,7 @@ static bool is_probe_read_helper(u32 func_id)\n * If instruction is an indirect write to stack, invalidate SCEVs for spi's\n * that this instruction can touch.\n */\n-static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)\n+static int reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)\n {\n \tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n \tstruct scev *scev = env-\u003escev;\n@@ -1157,19 +1843,24 @@ static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct\n \tconst unsigned long *mask;\n \tu32 spi, reg;\n \tbool opaque;\n+\tint err;\n \n \t/* Direct fp stores are fine. */\n \tif ((class == BPF_ST || class == BPF_STX) \u0026\u0026 insn-\u003edst_reg == BPF_REG_FP)\n-\t\treturn;\n+\t\treturn 0;\n \n \tmask = bpf_may_write_mask(env, idx);\n \topaque = bpf_helper_call(insn) \u0026\u0026 is_probe_read_helper(insn-\u003eimm);\n \tfor_each_set_bit(spi, mask, MAX_BPF_STACK_SLOTS) {\n \t\treg = MAX_BPF_REG + spi;\n-\t\tif (cur_env-\u003ereg2expr[reg] == UNKNOWN_EXPR_ID)\n-\t\t\tcontinue;\n-\t\treplace_reg(scev, cur_env, reg, opaque ? OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID);\n+\t\t/* '?' stays '?' */\n+\t\terr = forget_reg(scev, cur_env, reg,\n+\t\t\t\t opaque \u0026\u0026 !is_op(scev, cur_env-\u003ereg2expr[reg], UNKNOWN) ?\n+\t\t\t\t OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID, idx);\n+\t\tif (err)\n+\t\t\treturn err;\n \t}\n+\treturn 0;\n }\n \n /*\n@@ -1264,77 +1955,469 @@ static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_he\n \t\tif (aux[header].loop_header == cur_header)\n \t\t\treturn header;\n \n-\treturn -1;\n+\treturn -1;\n+}\n+\n+/*\n+ * Join cur_env into the successor's environment and schedule their traversal.\n+ * Map successors in nested loops to their topmost nested header.\n+ * Ignore successors outside the current loop and its nested loops.\n+ */\n+static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,\n+\t\t\t struct env *old_env, struct env *cur_env)\n+{\n+\tbool log_level2 = env-\u003elog.level \u0026 BPF_LOG_LEVEL2;\n+\tstruct scev *scev = env-\u003escev;\n+\tint err, nested_header, idom;\n+\tstruct env *succ_env;\n+\n+\t/*\n+\t * There are several possibilities for a successor:\n+\t * - succ_idx can be a part of a loop outside of the cur_header's loop,\n+\t * such edges are ignored.\n+\t * - succ_idx can be a part of the same loop as cur_header,\n+\t * for such edges succ_idx environment is updated:\n+\t * e[succ_idx] = join(e[succ_idx], cur_env)\n+\t * - succ_idx can be a part of some loop inner to cur_header,\n+\t * in such a case there exists some loop header H,\n+\t * such that H.loop_header == cur_header\n+\t * and H is the same as succ_idx's loop or contains it.\n+\t */\n+\tif (bpf_loop_at_index(env, succ_idx) != cur_header) {\n+\t\t/*\n+\t\t * topmost_nested_loop() either finds H or returns -1,\n+\t\t * in case if succ_idx is a part of a loop outer to cur_header.\n+\t\t */\n+\t\tnested_header = topmost_nested_loop(env, succ_idx, cur_header);\n+\t\tif (nested_header \u003c 0)\n+\t\t\treturn 0;\n+\t\tsucc_idx = nested_header;\n+\t}\n+\tsucc_env = get_loop_env(scev, cur_header, succ_idx);\n+\tif (!succ_env)\n+\t\treturn -ENOMEM;\n+\t/*\n+\t * The header of an irreducible loop does not dominate its body. An insn whose immediate\n+\t * dominator is outside of the loop is reached from a secondary entry, without the header.\n+\t * The env at the source of an entering edge is not known: all '?', like a new env. So the\n+\t * insn is a join point with a phi for every live register, see join_added_edges().\n+\t */\n+\tidom = env-\u003eidoms[succ_idx];\n+\tif (cur_header \u003e= 0 \u0026\u0026 succ_idx != cur_header \u0026\u0026\n+\t env-\u003einsn_aux_data[cur_header].loop-\u003eirreducible \u0026\u0026\n+\t bpf_loop_at_index(env, idom) != cur_header \u0026\u0026\n+\t topmost_nested_loop(env, idom, cur_header) \u003c 0)\n+\t\tsucc_env-\u003eempty = false;\n+\tif (log_level2)\n+\t\tmemcpy(old_env, succ_env, sizeof(*old_env));\n+\terr = join(env, succ_env, cur_env, succ_idx);\n+\tif (err)\n+\t\treturn err;\n+\terr = worklist_push(env, cur_header, succ_idx);\n+\tif (err)\n+\t\treturn err;\n+\tif (log_level2)\n+\t\tlog_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);\n+\treturn 0;\n+}\n+\n+/*\n+ * Recurrences need a natural loop. Unsupported loops get an unknown header environment.\n+ * A nested loop is processed as a single instruction, its exits are the successors: all of\n+ * them are needed. No result for the loop itself depends on the list of its own exits:\n+ * mark_latches() prepares them for the loop around, and compute_max_iters() asks if there is\n+ * only one, which a list that is cut does not have.\n+ */\n+static bool can_compute_loop_scev(const struct bpf_loop *loop)\n+{\n+\treturn !loop-\u003eirreducible \u0026\u0026 !loop-\u003enested_exits_overflow;\n+}\n+\n+/* A loop is a single instruction for the subprog too: no exit list may be truncated. */\n+static bool can_compute_subprog_scev(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)\n+{\n+\tstruct bpf_loop *loop;\n+\tint i;\n+\n+\tfor (i = sub-\u003estart; i \u003c (sub + 1)-\u003estart; i++) {\n+\t\tloop = env-\u003einsn_aux_data[i].loop;\n+\t\tif (loop \u0026\u0026 (loop-\u003eexits_overflow || loop-\u003enested_exits_overflow))\n+\t\t\treturn false;\n+\t}\n+\treturn true;\n+}\n+\n+/*\n+ * The edges that the verifier adds, see bpf_head_guard_target(): bpf_insn_successors() doesn't have\n+ * them. They leave all loops. The env at their source is not known: @cur_env is all '?'. So their\n+ * target is a join point with a phi for every live register.\n+ */\n+static int join_added_edges(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,\n+\t\t\t struct env *old_env, struct env *cur_env)\n+{\n+\tint i, t, err;\n+\n+\tfor (i = sub-\u003estart; i \u003c (sub + 1)-\u003estart; i++) {\n+\t\tt = bpf_head_guard_target(env, i);\n+\t\tif (t \u003c 0)\n+\t\t\tcontinue;\n+\t\terr = join_successor(env, -1, t, old_env, cur_env);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\treturn sub-\u003ebail_insn \u003c 0 ? 0 : join_successor(env, -1, sub-\u003ebail_insn, old_env, cur_env);\n+}\n+\n+/*\n+ * @id == *@base + *@off (mod 2^*@bits): constant offsets, extensions and partial spills are\n+ * stripped, see set_expr_base(). An add with a def holds modulo 2^32 whether its insn is converted\n+ * to ALU32 or not, see alu64_with_def(). It holds modulo 2^64 once the main pass has set\n+ * prevent_zext: it verified the insn without a pointer to the arena and rejects a state that brings\n+ * one. The def dominates every use, and prevent_zext is only ever set: such an add is not checked\n+ * again.\n+ */\n+static void split_const_offset(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off, u32 *bits)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct expr *add, *e = \u0026scev-\u003eexprs[id];\n+\n+\t*base = e-\u003ebase;\n+\t*off = e-\u003eoff;\n+\t*bits = e-\u003ebits;\n+\twhile (e-\u003earena_add) {\n+\t\tadd = \u0026scev-\u003eexprs[e-\u003earena_add];\n+\t\tif (!env-\u003einsn_aux_data[add-\u003edef.idx].prevent_zext) {\n+\t\t\t*bits = min(*bits, 32);\n+\t\t\tbreak;\n+\t\t}\n+\t\te-\u003earena_add = scev-\u003eexprs[add-\u003eparams[0]].arena_add;\n+\t}\n+}\n+\n+static bool const_diff_at_header(struct bpf_verifier_env *env, int h, u32 ra, u32 rb, s64 *delta);\n+\n+/*\n+ * @id_a and @id_b are expressions of one env of the loop at @h, or of a subprog: @h is -1. Do they\n+ * have a constant difference, @id_b == @id_a + *@delta (mod 2^*@bits)?\n+ */\n+static bool const_diff(struct bpf_verifier_env *env, int h, u32 id_a, u32 id_b, s64 *delta,\n+\t\t u32 *bits)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 base_a, base_b, bits_a, ra, rb;\n+\ts64 off_a, c;\n+\n+\tsplit_const_offset(env, id_a, \u0026base_a, \u0026off_a, \u0026bits_a);\n+\tsplit_const_offset(env, id_b, \u0026base_b, delta, bits);\n+\t*delta = (u64)*delta - off_a;\n+\t*bits = min(*bits, bits_a);\n+\t/* copies are equal in all bits */\n+\tif (id_a == id_b \u0026\u0026 scev-\u003eexprs[id_a].is_vn) {\n+\t\t*bits = 64;\n+\t\treturn true;\n+\t}\n+\tif (base_a == base_b)\n+\t\treturn scev-\u003eexprs[base_a].is_vn;\n+\tif (h \u003c 0 || !is_reg(scev, base_a, \u0026ra) || !is_reg(scev, base_b, \u0026rb) ||\n+\t !const_diff_at_header(env, h, ra, rb, \u0026c))\n+\t\treturn false;\n+\t*delta = (u64)*delta + c;\n+\treturn true;\n+}\n+\n+/*\n+ *\told = i = 0; do { i++; if (old \u003e 1021) break; c = buf[old]; old = i; } while (c);\n+ * Does @rb == @ra + *@delta hold at the header of the loop at @h in every iteration? It does if it\n+ * holds at loop entry, by the env of the enclosing loop at @h, and every backedge preserves it: the\n+ * backedge values have this constant difference, or both are the header phi plus one constant.\n+ * Loops nest LOOP_STACK_SIZE deep at most, see bpf_flow_place_guards().\n+ */\n+static bool const_diff_at_header(struct bpf_verifier_env *env, int h, u32 ra, u32 rb, s64 *delta)\n+{\n+\tint outer_header = env-\u003einsn_aux_data[h].loop_header;\n+\tstruct env *entry_env = find_loop_env(env-\u003escev, outer_header, h);\n+\tstruct env *header_env = find_header_env(env-\u003escev, h);\n+\tu32 base_a, base_b, bits_a, bits;\n+\ts64 off_a, c;\n+\n+\tif (!entry_env || !can_compute_loop_scev(env-\u003einsn_aux_data[h].loop) ||\n+\t !const_diff(env, outer_header, entry_env-\u003ereg2expr[ra], entry_env-\u003ereg2expr[rb],\n+\t\t\tdelta, \u0026bits) || bits != 64)\n+\t\treturn false;\n+\tif (const_diff(env, -1, header_env-\u003ereg2expr[ra], header_env-\u003ereg2expr[rb], \u0026c, \u0026bits))\n+\t\treturn bits == 64 \u0026\u0026 c == *delta;\n+\tsplit_const_offset(env, header_env-\u003ereg2expr[ra], \u0026base_a, \u0026off_a, \u0026bits_a);\n+\tsplit_const_offset(env, header_env-\u003ereg2expr[rb], \u0026base_b, \u0026c, \u0026bits);\n+\treturn base_a == REG_EXPR_ID(ra) \u0026\u0026 base_b == REG_EXPR_ID(rb) \u0026\u0026 off_a == c \u0026\u0026\n+\t bits_a == 64 \u0026\u0026 bits == 64;\n+}\n+\n+/*\n+ *\tp = buf + i; if (i \u003e 100) return 0; *p = 0;\n+ * @tested is the expression of the tested register and @id that of p, in one env as for\n+ * const_diff(). Is @id an add, and one operand @tested + a constant? Then\n+ * @id == *@other + @tested + *@delta (mod 2^*@bits). A header phi can be an add, see ADD_SCEV. For\n+ * an add with a def see split_const_offset(). Which operand is the pointer is not known here.\n+ */\n+static bool match_linked_add(struct bpf_verifier_env *env, int h, u32 tested, u32 id, u32 *other,\n+\t\t\t s64 *delta, u32 *bits)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 reg, r, b, op = BPF_ADD;\n+\tstruct expr_def def;\n+\ts64 c;\n+\n+\tsplit_const_offset(env, id, \u0026id, delta, bits);\n+\tif (h \u003e= 0 \u0026\u0026 is_reg(scev, id, \u0026reg)) {\n+\t\tid = find_header_env(scev, h)-\u003ereg2scev[reg];\n+\t\top = ADD_SCEV;\n+\t}\n+\tdef = scev-\u003eexprs[id].def;\n+\tif (!is_binop(scev, op, id, other, \u0026r) || def.phi)\n+\t\treturn false;\n+\tif (def.set \u0026\u0026 !env-\u003einsn_aux_data[def.idx].prevent_zext)\n+\t\t*bits = min(*bits, 32);\n+\tif (!const_diff(env, h, tested, r, \u0026c, \u0026b)) {\n+\t\tswap(*other, r);\n+\t\tif (!const_diff(env, h, tested, r, \u0026c, \u0026b))\n+\t\t\treturn false;\n+\t}\n+\t*delta = (u64)*delta + c;\n+\t*bits = min(*bits, b);\n+\treturn true;\n+}\n+\n+/*\n+ * const_diff() for the SCEV register @reg, which has the expression @id_b. A fill from byte\n+ * *@fill_off of a slot reads these bits. On big endian the low bytes of a spill are the last ones,\n+ * and a narrow fill from the start of a slot is a right shift, see mk_fill().\n+ */\n+static bool const_diff_reg(struct bpf_verifier_env *env, int h, u32 id_a, u32 reg, u32 id_b,\n+\t\t\t u32 *fill_off, s64 *delta, u32 *bits)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct expr *e;\n+\tu32 x;\n+\ts64 k;\n+\n+\t*fill_off = 0;\n+\tif (const_diff(env, h, id_a, id_b, delta, bits)) {\n+\t\tif (is_big_endian_slot(reg))\n+\t\t\t*fill_off = expr_spill_size(scev, id_b, \u0026x) - *bits / BITS_PER_BYTE;\n+\t\treturn true;\n+\t}\n+\tif (!is_big_endian_slot(reg) || !scev-\u003eexprs[id_b].is_vn)\n+\t\treturn false;\n+\tsplit_const_offset(env, id_a, \u0026x, delta, bits);\n+\te = \u0026scev-\u003eexprs[x];\n+\tif ((e-\u003eop != BPF_RSH \u0026\u0026 e-\u003eop != BPF_ARSH) || e-\u003edef.set || e-\u003eparams[0] != id_b ||\n+\t !is_imm(scev, e-\u003eparams[1], \u0026k) || (k != 32 \u0026\u0026 k != 48 \u0026\u0026 k != 56))\n+\t\treturn false;\n+\t*delta = -(u64)*delta;\n+\t*bits = min_t(u32, *bits, 64 - k);\n+\t*fill_off = (64 - k - *bits) / BITS_PER_BYTE;\n+\treturn true;\n+}\n+\n+/* The first of the registers and stack slots @live that holds @id + a constant. REGS_NUM: none. */\n+static u32 find_leader(struct bpf_verifier_env *env, struct env *e, int h,\n+\t\t const unsigned long *live, u32 id)\n+{\n+\tu32 r, bits;\n+\ts64 delta;\n+\n+\tfor_each_set_bit(r, live, REGS_NUM)\n+\t\tif (const_diff(env, h, e-\u003ereg2expr[r], id, \u0026delta, \u0026bits))\n+\t\t\tbreak;\n+\treturn r;\n }\n \n /*\n- * Join cur_env into the successor's environment and schedule their traversal.\n- * Map successors in nested loops to their topmost nested header.\n- * Ignore successors outside the current loop and its nested loops.\n+ *\tn = bpf_get_stack(..); m = n; if (n \u003c 0) ..; use(m);\n+ * The main pass refines the registers that the conditional jump at @idx tests. Find the live SCEV\n+ * registers that are linked to one of them in @e, the env before the jump, and keep them with their\n+ * expressions: what bpf_scev_next_linked_reg() needs of @e.\n */\n-static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,\n-\t\t\t struct env *old_env, struct env *cur_env)\n+static int find_linked_regs(struct bpf_verifier_env *env, struct env *e, int h, int idx)\n {\n-\tbool log_level2 = env-\u003elog.level \u0026 BPF_LOG_LEVEL2;\n+\tstruct bpf_insn_aux_data *aux = \u0026env-\u003einsn_aux_data[idx];\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\tu32 dst = e-\u003ereg2expr[insn-\u003edst_reg], src = dst;\n+\tstruct insn_envs *envs = env-\u003escev-\u003eenvs[idx];\n \tstruct scev *scev = env-\u003escev;\n-\tint err, nested_header;\n-\tstruct env *succ_env;\n+\tu32 r, q, other, id, fill_off, base, base_dst, base_src, bits, cap, tested = 0;\n+\tu32 first = scev-\u003elinked_cnt;\n+\tDECLARE_BITMAP(live, ENV_REGS_NUM) = {};\n+\tDECLARE_BITMAP(found, ENV_REGS_NUM) = {};\n+\tvoid *tmp;\n+\ts64 delta;\n \n-\t/*\n-\t * There are several possibilities for a successor:\n-\t * - succ_idx can be a part of a loop outside of the cur_header's loop,\n-\t * such edges are ignored.\n-\t * - succ_idx can be a part of the same loop as cur_header,\n-\t * for such edges succ_idx environment is updated:\n-\t * e[succ_idx] = join(e[succ_idx], cur_env)\n-\t * - succ_idx can be a part of some loop inner to cur_header,\n-\t * in such a case there exists some loop header H,\n-\t * such that H.loop_header == cur_header\n-\t * and H is the same as succ_idx's loop or contains it.\n-\t */\n-\tif (bpf_loop_at_index(env, succ_idx) != cur_header) {\n-\t\t/*\n-\t\t * topmost_nested_loop() either finds H or returns -1,\n-\t\t * in case if succ_idx is a part of a loop outer to cur_header.\n-\t\t */\n-\t\tnested_header = topmost_nested_loop(env, succ_idx, cur_header);\n-\t\tif (nested_header \u003c 0)\n-\t\t\treturn 0;\n-\t\tsucc_idx = nested_header;\n+\tif (!bpf_insn_is_cond_jump(insn-\u003ecode) || BPF_OP(insn-\u003ecode) == BPF_JCOND)\n+\t\treturn 0;\n+\tif (BPF_SRC(insn-\u003ecode) == BPF_X)\n+\t\tsrc = e-\u003ereg2expr[insn-\u003esrc_reg];\n+\tbitmap_copy(live, aux-\u003elive_stack_before, MAX_BPF_STACK_SLOTS);\n+\tbitmap_shift_left(live, live, MAX_BPF_REG, REGS_NUM);\n+\tlive[0] |= aux-\u003elive_regs_before;\n+\tfor (r = REGS_NUM; r \u003c ENV_REGS_NUM; r++)\n+\t\tif (e-\u003emem_addr[r - REGS_NUM])\n+\t\t\t__set_bit(r, live);\n+\tsplit_const_offset(env, dst, \u0026base_dst, \u0026delta, \u0026bits);\n+\tsplit_const_offset(env, src, \u0026base_src, \u0026delta, \u0026bits);\n+\tfor_each_set_bit(r, live, ENV_REGS_NUM) {\n+\t\tid = e-\u003ereg2expr[r];\n+\t\t/* most are not linked */\n+\t\tsplit_const_offset(env, id, \u0026base, \u0026delta, \u0026bits);\n+\t\tif (base != base_dst \u0026\u0026 base != base_src \u0026\u0026 !is_op(scev, base, BPF_ADD) \u0026\u0026\n+\t\t (h \u003c 0 || !is_op(scev, base, REG)) \u0026\u0026 !is_big_endian_slot(r))\n+\t\t\tcontinue;\n+\t\tif (const_diff_reg(env, h, dst, r, id, \u0026fill_off, \u0026delta, \u0026bits) ||\n+\t\t (src != dst \u0026\u0026 const_diff_reg(env, h, src, r, id, \u0026fill_off, \u0026delta, \u0026bits))) {\n+\t\t\t__set_bit(r, found);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (!match_linked_add(env, h, dst, id, \u0026other, \u0026delta, \u0026bits) \u0026\u0026\n+\t\t (src == dst || !match_linked_add(env, h, src, id, \u0026other, \u0026delta, \u0026bits)))\n+\t\t\tcontinue;\n+\t\t/* an add is of use only with a live register that holds its other operand */\n+\t\tfor_each_set_bit(q, live, REGS_NUM) {\n+\t\t\tif (q == r || !const_diff(env, h, e-\u003ereg2expr[q], other, \u0026delta, \u0026bits))\n+\t\t\t\tcontinue;\n+\t\t\t__set_bit(r, found);\n+\t\t\t__set_bit(q, found);\n+\t\t\tbreak;\n+\t\t}\n \t}\n-\tsucc_env = get_loop_env(scev, cur_header, succ_idx);\n-\tif (!succ_env)\n-\t\treturn -ENOMEM;\n-\tif (log_level2)\n-\t\tmemcpy(old_env, succ_env, sizeof(*old_env));\n-\terr = join(scev, succ_env, cur_env);\n-\tif (err)\n-\t\treturn err;\n-\terr = worklist_push(env, cur_header, succ_idx);\n-\tif (err)\n-\t\treturn err;\n-\tif (log_level2)\n-\t\tlog_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);\n+\t/* the main pass finds memory by a live register that holds its address */\n+\tfor (r = REGS_NUM; r \u003c ENV_REGS_NUM; r++) {\n+\t\tif (!test_bit(r, found))\n+\t\t\tcontinue;\n+\t\tq = find_leader(env, e, h, live, e-\u003emem_addr[r - REGS_NUM]);\n+\t\tif (q \u003c REGS_NUM)\n+\t\t\t__set_bit(q, found);\n+\t\telse\n+\t\t\t__clear_bit(r, found);\n+\t}\n+\tfor_each_set_bit(r, found, ENV_REGS_NUM) {\n+\t\tif (scev-\u003elinked_cnt == scev-\u003elinked_cap) {\n+\t\t\tcap = max(scev-\u003elinked_cap * 2, 16);\n+\t\t\ttmp = kvrealloc(scev-\u003elinked, array_size(cap, sizeof(*scev-\u003elinked)),\n+\t\t\t\t\tGFP_KERNEL_ACCOUNT);\n+\t\t\tif (!tmp)\n+\t\t\t\treturn -ENOMEM;\n+\t\t\tscev-\u003elinked = tmp;\n+\t\t\tscev-\u003elinked_cap = cap;\n+\t\t}\n+\t\ttested += r == insn-\u003edst_reg || (src != dst \u0026\u0026 r == insn-\u003esrc_reg);\n+\t\tscev-\u003elinked[scev-\u003elinked_cnt].reg = r;\n+\t\tscev-\u003elinked[scev-\u003elinked_cnt].addr = r \u003c REGS_NUM ? 0 : e-\u003emem_addr[r - REGS_NUM];\n+\t\tscev-\u003elinked[scev-\u003elinked_cnt++].id = e-\u003ereg2expr[r];\n+\t}\n+\t/* nothing but the tested registers */\n+\tif (scev-\u003elinked_cnt - first == tested) {\n+\t\tscev-\u003elinked_cnt = first;\n+\t\treturn 0;\n+\t}\n+\tif (!envs) {\n+\t\tenvs = kzalloc(sizeof(*envs), GFP_KERNEL_ACCOUNT);\n+\t\tif (!envs)\n+\t\t\treturn -ENOMEM;\n+\t\tscev-\u003eenvs[idx] = envs;\n+\t}\n+\tenvs-\u003elinked_first = first;\n+\tenvs-\u003elinked_cnt = scev-\u003elinked_cnt - first;\n \treturn 0;\n }\n \n /*\n- * Unsupported loops get only an unknown header environment.\n- * A nested loop is processed as a single instruction, its exits are the successors: all of\n- * them are needed. No result for the loop itself depends on the list of its own exits:\n- * mark_latches() prepares them for the loop around, and compute_max_iters() asks if there is\n- * only one, which a list that is cut does not have.\n+ * Find the next SCEV register that is linked to @regno at the conditional jump at @insn_idx: on\n+ * every path to the jump *@linked_regno == @regno + *@delta (mod 2^*@bits). It is live there and of\n+ * the same frame. It is a register, or MAX_BPF_REG + the index of a stack slot: a fill from byte\n+ * *@fill_off of the slot reads these bits. *@pos is the position of the search, 0 at first. False:\n+ * no more links are known. Types are not known here: the caller checks them in its state.\n+ * A linked register can be a pointer: *base_regno + regno + delta. *base_regno is the address base,\n+ * as in store_base_regs. It is -1 for a link without a base.\n+ * BPF_SCEV_REGS_NUM and above is a memory location, see struct env and bpf_scev_mem_addr().\n */\n-static bool can_compute_loop_scev(const struct bpf_loop *loop)\n+bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,\n+\t\t\t u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,\n+\t\t\t u32 *bits)\n {\n-\treturn !loop-\u003eirreducible \u0026\u0026 !loop-\u003enested_exits_overflow;\n+\tstruct insn_envs *envs = env-\u003escev-\u003eenvs[insn_idx];\n+\tint h = bpf_loop_at_index(env, insn_idx);\n+\tstruct scev_linked_reg *linked;\n+\tu32 i, j, other, b;\n+\ts64 c;\n+\n+\tif (!envs || !envs-\u003elinked_cnt)\n+\t\treturn false;\n+\tlinked = \u0026env-\u003escev-\u003elinked[envs-\u003elinked_first];\n+\t/* registers come first */\n+\tfor (i = 0; linked[i].reg != regno; i++)\n+\t\tif (i + 1 == envs-\u003elinked_cnt || linked[i].reg \u003e regno)\n+\t\t\treturn false;\n+\tfor (; *pos \u003c envs-\u003elinked_cnt; ++*pos) {\n+\t\t*linked_regno = linked[*pos].reg;\n+\t\t*base_regno = -1;\n+\t\tif (*pos == i)\n+\t\t\tcontinue;\n+\t\tif (const_diff_reg(env, h, linked[i].id, *linked_regno, linked[*pos].id, fill_off,\n+\t\t\t\t delta, bits))\n+\t\t\treturn true;\n+\t\tif (!match_linked_add(env, h, linked[i].id, linked[*pos].id, \u0026other, delta, bits))\n+\t\t\tcontinue;\n+\t\tfor (j = 0; j \u003c envs-\u003elinked_cnt; j++) {\n+\t\t\tif (j == *pos || !const_diff(env, h, linked[j].id, other, \u0026c, \u0026b))\n+\t\t\t\tcontinue;\n+\t\t\t*base_regno = linked[j].reg;\n+\t\t\t*delta = (u64)*delta + c;\n+\t\t\t*bits = min(*bits, b);\n+\t\t\treturn true;\n+\t\t}\n+\t}\n+\treturn false;\n+}\n+\n+/*\n+ * The memory location @regno is a linked register of the conditional jump at @insn_idx. Its address\n+ * is *@base_regno + *@off. *@base_regno is a live register or stack slot. Which memory it is\n+ * depends on the state.\n+ */\n+bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,\n+\t\t s64 *off)\n+{\n+\tstruct insn_envs *envs = env-\u003escev-\u003eenvs[insn_idx];\n+\tstruct scev_linked_reg *linked = \u0026env-\u003escev-\u003elinked[envs-\u003elinked_first];\n+\tint h = bpf_loop_at_index(env, insn_idx);\n+\tu32 i, j, bits;\n+\n+\tfor (i = 0; linked[i].reg != regno; i++)\n+\t\tif (i + 1 == envs-\u003elinked_cnt)\n+\t\t\treturn false;\n+\tfor (j = 0; linked[j].reg \u003c REGS_NUM; j++) {\n+\t\tif (!const_diff(env, h, linked[j].id, linked[i].addr, off, \u0026bits) || bits != 64)\n+\t\t\tcontinue;\n+\t\t*base_regno = linked[j].reg;\n+\t\treturn true;\n+\t}\n+\treturn false;\n }\n \n-static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)\n+/*\n+ * @cur_header and @first are a loop header. Or -1 and the first insn of a subprog: the subprog is\n+ * the outermost loop, which runs once. (REG r) is the entry value of r, the loops in it are single\n+ * instructions.\n+ * Value numbering works on any CFG: the body of an irreducible loop is walked like any other. Every\n+ * retreating edge of the depth-first search goes to a loop header, see compute_loops_in_subprog(),\n+ * and bpf_compute_postorder() does the same search. So reverse post-order is a topological order of\n+ * this body too.\n+ */\n+static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header, int first)\n {\n \tstruct scev_worklist *worklist = \u0026env-\u003escev-\u003eworklist;\n \tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n-\tstruct bpf_loop *cur_loop = aux[cur_header].loop;\n+\tstruct bpf_loop *cur_loop = cur_header \u003c 0 ? NULL : aux[cur_header].loop;\n+\tstruct bpf_subprog_info *sub = bpf_find_containing_subprog(env, first);\n \tstruct env *header_env;\n \tstruct scev *scev = env-\u003escev;\n \tstruct bpf_loop *nested_loop;\n@@ -1342,26 +2425,15 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)\n \tstruct env *old_env = NULL;\n \tstruct bpf_iarray *succ;\n \tbool log_level2 = env-\u003elog.level \u0026 BPF_LOG_LEVEL2;\n-\tint s, i, err, idx, succ_idx;\n+\tint s, i, err, idx, succ_idx, start;\n \tu32 r;\n \n \tif (log_level2)\n-\t\tbpf_log(\u0026env-\u003elog, \"Computing SCEV for loop at %d:\\n\", cur_header);\n+\t\tbpf_log(\u0026env-\u003elog, \"Computing SCEV for %s at %d:\\n\",\n+\t\t\tcur_loop ? \"loop\" : \"subprog\", first);\n \n-\t/*\n-\t * For irreducible loops, and for loops nesting a loop with a truncated\n-\t * exit list, just assume that everything is clobbered for now.\n-\t */\n-\tif (!can_compute_loop_scev(cur_loop)) {\n-\t\theader_env = get_loop_env(scev, cur_header, cur_header);\n-\t\tif (!header_env)\n-\t\t\treturn -ENOMEM;\n-\t\t/* The freshly allocated environment has all expressions unknown. */\n-\t\tbitmap_fill(cur_loop-\u003estore_base_regs, REGS_NUM);\n-\t\tbitmap_fill(cur_loop-\u003etested_regs, REGS_NUM);\n-\t\theader_env-\u003eempty = false;\n+\tif (!cur_loop \u0026\u0026 !can_compute_subprog_scev(env, sub))\n \t\treturn 0;\n-\t}\n \n \tcur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);\n \tif (!cur_env)\n@@ -1371,19 +2443,33 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)\n \t\tif (!old_env)\n \t\t\tgoto nomem;\n \t}\n-\theader_env = get_loop_env(scev, cur_header, cur_header);\n+\theader_env = get_loop_env(scev, cur_header, first);\n \tif (!header_env)\n \t\tgoto nomem;\n-\terr = setup_initial_loop_env(env, header_env, cur_header);\n-\tif (err)\n-\t\tgoto out;\n-\terr = worklist_push(env, cur_header, cur_header);\n-\tif (err)\n-\t\tgoto out;\n+\tsetup_initial_loop_env(header_env);\n+\t/* The successors of a nested loop with a truncated exit list are not known: no walk */\n+\tif (!cur_loop || !cur_loop-\u003enested_exits_overflow) {\n+\t\terr = worklist_push(env, cur_header, first);\n+\t\tif (err)\n+\t\t\tgoto out;\n+\t}\n+\tif (!cur_loop) {\n+\t\t/* no backedge overwrites it */\n+\t\theader_env-\u003eempty = false;\n+\t\terr = join_added_edges(env, sub, old_env, cur_env);\n+\t\tif (err)\n+\t\t\tgoto out;\n+\t}\n \n \twhile (worklist-\u003enr) {\n \t\tidx = *min_heap_peek_inline(worklist);\n \t\tmin_heap_pop_inline(worklist, \u0026worklist_cb, env-\u003ecfg.postorder_nums);\n+\t\tstart = idx;\n+\t\tif (signal_pending(current)) {\n+\t\t\terr = -EAGAIN;\n+\t\t\tgoto out;\n+\t\t}\n+\t\tcond_resched();\n \n \t\t/* join_successor() maps nested-loop entries to their representative header. */\n \t\tnested_loop = idx != cur_header ? aux[idx].loop : NULL;\n@@ -1395,13 +2481,19 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)\n \t\t\t */\n \t\t\tif (log_level2)\n \t\t\t\tmemcpy(old_env, cur_env, sizeof(*old_env));\n-\t\t\t/* Pull the nested loop's stack-store base dependencies up. */\n-\t\t\tfor_each_set_bit(r, nested_loop-\u003estore_base_regs, BPF_SCEV_REGS_NUM)\n-\t\t\t\tor_expr_regs(env, cur_env-\u003ereg2expr[r], cur_loop-\u003estore_base_regs);\n-\t\t\t/* And what its jumps depend on. */\n-\t\t\tfor_each_set_bit(r, nested_loop-\u003etested_regs, BPF_SCEV_REGS_NUM)\n-\t\t\t\tor_expr_regs(env, cur_env-\u003ereg2expr[r], cur_loop-\u003etested_regs);\n-\t\t\tforget_non_invariants(env, cur_env, idx);\n+\t\t\tif (cur_loop) {\n+\t\t\t\t/* Pull the nested loop's stack-store base dependencies up. */\n+\t\t\t\tfor_each_set_bit(r, nested_loop-\u003estore_base_regs, BPF_SCEV_REGS_NUM)\n+\t\t\t\t\tor_expr_regs(env, cur_env-\u003ereg2expr[r],\n+\t\t\t\t\t\t cur_loop-\u003estore_base_regs);\n+\t\t\t\t/* And what its jumps depend on. */\n+\t\t\t\tfor_each_set_bit(r, nested_loop-\u003etested_regs, BPF_SCEV_REGS_NUM)\n+\t\t\t\t\tor_expr_regs(env, cur_env-\u003ereg2expr[r],\n+\t\t\t\t\t\t cur_loop-\u003etested_regs);\n+\t\t\t}\n+\t\t\terr = forget_non_invariants(env, cur_env, idx);\n+\t\t\tif (err)\n+\t\t\t\tgoto out;\n \t\t\tif (log_level2)\n \t\t\t\tlog_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);\n \t\t\t/*\n@@ -1422,12 +2514,24 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)\n \t\t\tfor (;;) {\n \t\t\t\tif (log_level2)\n \t\t\t\t\tmemcpy(old_env, cur_env, sizeof(*old_env));\n-\t\t\t\tcollect_store_base_regs(env, cur_env, idx, cur_loop-\u003estore_base_regs);\n-\t\t\t\tcollect_tested_regs(env, cur_env, idx, cur_loop-\u003etested_regs);\n+\t\t\t\tif (cur_loop) {\n+\t\t\t\t\tcollect_store_base_regs(env, cur_env, idx,\n+\t\t\t\t\t\t\t\tcur_loop-\u003estore_base_regs);\n+\t\t\t\t\tcollect_tested_regs(env, cur_env, idx,\n+\t\t\t\t\t\t\t cur_loop-\u003etested_regs);\n+\t\t\t\t}\n+\t\t\t\t/* the others wait for the envs of all loop headers */\n+\t\t\t\tif (!aux[idx].need_scev) {\n+\t\t\t\t\terr = find_linked_regs(env, cur_env, -1, idx);\n+\t\t\t\t\tif (err)\n+\t\t\t\t\t\tgoto out;\n+\t\t\t\t}\n \t\t\t\terr = transfer(env, cur_env, idx);\n \t\t\t\tif (err)\n \t\t\t\t\tgoto out;\n-\t\t\t\treset_scevs_at_indirect_writes(env, cur_env, idx);\n+\t\t\t\terr = reset_scevs_at_indirect_writes(env, cur_env, idx);\n+\t\t\t\tif (err)\n+\t\t\t\t\tgoto out;\n \t\t\t\tif (log_level2)\n \t\t\t\t\tlog_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);\n \t\t\t\tsucc = bpf_insn_successors(env, idx);\n@@ -1446,8 +2550,17 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)\n \t\t\t\t\tgoto out;\n \t\t\t}\n \t\t}\n+\t\t/* Reverse post-order: all predecessors came first, the env has no users any more */\n+\t\tif (!aux[start].need_scev)\n+\t\t\tfree_loop_env(scev, cur_header, start);\n \t}\n \n+\t/* For the enclosing loop and for the main pass it clobbers everything */\n+\tif (cur_loop \u0026\u0026 !can_compute_loop_scev(cur_loop)) {\n+\t\tmemset(header_env, 0, sizeof(*header_env));\n+\t\tbitmap_fill(cur_loop-\u003estore_base_regs, REGS_NUM);\n+\t\tbitmap_fill(cur_loop-\u003etested_regs, REGS_NUM);\n+\t}\n \terr = 0;\n out:\n \tkfree(cur_env);\n@@ -1545,29 +2658,10 @@ static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,\n \treturn id \u003c 0 ? id : fn(scev, id, priv);\n }\n \n-static int transform_expr(struct scev *scev, u32 root, void *priv,\n-\t\t\t int (*fn)(struct scev *scev, u32 id, void *priv))\n-{\n-\tint i = 0, id_old, id_new = root;\n-\n-\tdo {\n-\t\t/*\n-\t\t * The depth limit is somewhat arbitrary and is essentially a failsafe.\n-\t\t * oscillation should not really happen. Still, it seems harsh to error out.\n-\t\t */\n-\t\tif (i++ == 4 * EXPR_STACK_DEPTH)\n-\t\t\treturn UNKNOWN_EXPR_ID;\n-\t\tid_old = id_new;\n-\t\tid_new = transform_expr_once(scev, 0, id_old, priv, fn);\n-\t\tif (id_new \u003c 0)\n-\t\t\treturn id_new;\n-\t} while (id_old != id_new);\n-\treturn id_new;\n-}\n-\n-static int simplify(struct scev *scev, u32 id, void *priv)\n+static int simplify(struct scev *scev, u32 id)\n {\n \tint a, b, l, r, t, base, slope;\n+\tu32 op = scev-\u003eexprs[id].op, bits = op_low_bits(op);\n \ts64 imm1, imm2;\n \n \t/* (- x imm) -\u003e (+ x -imm) */\n@@ -1575,13 +2669,24 @@ static int simplify(struct scev *scev, u32 id, void *priv)\n \t is_imm(scev, r, \u0026imm1) \u0026\u0026 imm1 != S64_MIN)\n \t\treturn expr2(scev, BPF_ADD, l, imm_expr(scev, -imm1));\n \n-\t/* (+ (+ x imm) imm) -\u003e (+ x imm) */\n+\t/* (+ x 0) -\u003e x */\n+\tif (is_add(scev, id, \u0026l, \u0026r) \u0026\u0026 is_imm(scev, r, \u0026imm1) \u0026\u0026 !imm1)\n+\t\treturn l;\n+\n+\t/* (+ (+ x imm) imm) -\u003e (+ x imm). Not through a def, see alu64_with_def() */\n \tif (is_add(scev, id, \u0026l, \u0026r) \u0026\u0026\n \t is_imm(scev, r, \u0026imm2) \u0026\u0026\n \t is_add(scev, l, \u0026a, \u0026b) \u0026\u0026\n-\t is_imm(scev, b, \u0026imm1))\n+\t is_imm(scev, b, \u0026imm1) \u0026\u0026 !scev-\u003eexprs[l].def.set)\n \t\treturn expr2(scev, BPF_ADD, a, imm_expr(scev, (s64)((u64)imm1 + (u64)imm2)));\n \n+\t/* 'r1 \u003c\u003c= 32; r1 \u003e\u003e= 32' is (u32)r1 for cpu v1 and v2: (\u003e\u003e (\u003c\u003c x 32) 32) -\u003e (zext32 x) */\n+\tif (is_binop(scev, BPF_RSH, id, \u0026l, \u0026r) \u0026\u0026\n+\t is_imm(scev, r, \u0026imm2) \u0026\u0026 imm2 == 32 \u0026\u0026\n+\t is_binop(scev, BPF_LSH, l, \u0026a, \u0026b) \u0026\u0026\n+\t is_imm(scev, b, \u0026imm1) \u0026\u0026 imm1 == 32 \u0026\u0026 !scev-\u003eexprs[l].def.set)\n+\t\treturn expr1(scev, ZEXT32, a);\n+\n \t/* (+ (linear base slope) imm) -\u003e (linear (+ base imm) slope) */\n \tif (is_add(scev, id, \u0026l, \u0026r) \u0026\u0026\n \t is_linear(scev, l, \u0026base, \u0026slope) \u0026\u0026\n@@ -1599,49 +2704,44 @@ static int simplify(struct scev *scev, u32 id, void *priv)\n \t\treturn imm_expr(scev, (u64)(u32)imm1);\n \n \t/*\n-\t * (zext32 (+ (zext32 $a) $b)) -\u003e (zext32 (+ $a $b))\n-\t * (zext32 (+ $a (zext32 $b))) -\u003e (zext32 (+ $a $b))\n+\t * An extension and a partial spill depend on the low bits of their operand only: look\n+\t * through an extension and a partial spill that is not narrower, below an add too:\n+\t * (sext32 (zext32 $a)) -\u003e (sext32 $a)\n+\t * (sext8 (spill16 $a)) -\u003e (sext8 $a)\n+\t * (zext32 (+ (sext32 $a) $b)) -\u003e (zext32 (+ $a $b))\n+\t * (spill32 (+ $a (zext32 $b))) -\u003e (spill32 (+ $a $b))\n \t */\n-\tif ((is_zext32(scev, id, \u0026t) \u0026\u0026 is_add(scev, t, \u0026l, \u0026b) \u0026\u0026 is_zext32(scev, l, \u0026a)) ||\n-\t (is_zext32(scev, id, \u0026t) \u0026\u0026 is_add(scev, t, \u0026a, \u0026r) \u0026\u0026 is_zext32(scev, r, \u0026b))) {\n-\t\tt = expr2(scev, BPF_ADD, a, b);\n-\t\tt = expr1(scev, ZEXT32, t);\n-\t\treturn t;\n-\t}\n-\n-\t/* (zext32 (zext32 X)) -\u003e (zext32 X) */\n-\tif (is_zext32(scev, id, \u0026a) \u0026\u0026 is_zext32(scev, a, \u0026b))\n-\t\treturn a;\n+\tif (!bits)\n+\t\treturn id;\n+\tt = scev-\u003eexprs[id].params[0];\n+\tif (is_low_bits(scev, t, bits, \u0026a))\n+\t\treturn expr1(scev, op, a);\n+\tif (is_add(scev, t, \u0026l, \u0026r) \u0026\u0026 !scev-\u003eexprs[t].def.phi \u0026\u0026\n+\t (is_low_bits(scev, l, bits, \u0026l) || is_low_bits(scev, r, bits, \u0026r)))\n+\t\treturn expr1(scev, op, expr2(scev, BPF_ADD, l, r));\n \n-\t/*\n-\t * '*(u32 *)(r10 - 8) = rX' stores the low half of rX:\n-\t * (spill32 (zext32 $a)) -\u003e (spill32 $a)\n-\t * (spill32 (+ (zext32 $a) $b)) -\u003e (spill32 (+ $a $b))\n-\t */\n-\tif (is_spill32(scev, id, \u0026t) \u0026\u0026 is_zext32(scev, t, \u0026a))\n-\t\treturn expr1(scev, SPILL32, a);\n-\tif (is_spill32(scev, id, \u0026t) \u0026\u0026 is_add(scev, t, \u0026l, \u0026b) \u0026\u0026 is_zext32(scev, l, \u0026a))\n-\t\treturn expr1(scev, SPILL32, expr2(scev, BPF_ADD, a, b));\n+\treturn id;\n+}\n \n-\t/*\n-\t * 'rX = *(u32 *)(r10 - 8)' loads what was stored:\n-\t * (zext32 (spill32 $a)) -\u003e (zext32 $a)\n-\t * (zext32 (+ (spill32 $a) $b)) -\u003e (zext32 (+ $a $b))\n-\t */\n-\tif (is_zext32(scev, id, \u0026t) \u0026\u0026 is_spill32(scev, t, \u0026a))\n-\t\treturn expr1(scev, ZEXT32, a);\n-\tif (is_zext32(scev, id, \u0026t) \u0026\u0026 is_add(scev, t, \u0026l, \u0026b) \u0026\u0026 is_spill32(scev, l, \u0026a))\n-\t\treturn expr1(scev, ZEXT32, expr2(scev, BPF_ADD, a, b));\n+static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)\n+{\n+\tu32 reg, *reg2scev = priv;\n \n+\t/* (reg r) -\u003e ... equation at header ... */\n+\tif (is_reg(scev, id, \u0026reg))\n+\t\treturn reg2scev[reg];\n+\t/* keep expression shapes */\n \treturn id;\n }\n \n-static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)\n+static int compute_header_scevs(struct bpf_verifier_env *env, int h)\n {\n \tstruct scev *scev = env-\u003escev;\n+\tstruct env *header_env = find_header_env(scev, h);\n \tint l, r, t, id, ra, rb, ra_expr;\n \tbool zext32;\n \ts64 imm;\n+\tu32 op;\n \n \t/*\n \t * Note:\n@@ -1658,10 +2758,13 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header\n \t * ... at exit r1 is in {7,42} ...\n \t */\n \tfor (ra = 0; ra \u003c REGS_NUM; ra++) {\n-\t\tra_expr = transform_expr(scev, header_env-\u003ereg2expr[ra], NULL, simplify);\n+\t\tra_expr = header_env-\u003ereg2expr[ra];\n+\t\t/* Constructed again it has no defs, see alu64_with_def(): they hide the shape */\n+\t\tif (env-\u003eprog-\u003eaux-\u003earena)\n+\t\t\tra_expr = transform_expr_once(scev, 0, ra_expr, scev-\u003eidentity_env.reg2expr,\n+\t\t\t\t\t\t instantiate_header_scevs);\n \t\tif (ra_expr \u003c 0)\n \t\t\treturn ra_expr;\n-\t\theader_env-\u003ereg2expr[ra] = ra_expr;\n \t\t/* rA = (+ rA IMM) -\u003e (linear rA IMM) */\n \t\tif (is_add(scev, ra_expr, \u0026l, \u0026r) \u0026\u0026\n \t\t is_reg(scev, l, \u0026rb) \u0026\u0026\n@@ -1673,30 +2776,24 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header\n \t\t\theader_env-\u003ereg2scev[ra] = id;\n \t\t\tcontinue;\n \t\t}\n-\t\t/* rA = (is_zext32 (+ rA IMM)) -\u003e (is_zext32 (linear rA IMM)) */\n-\t\tif (is_zext32(scev, ra_expr, \u0026t) \u0026\u0026\n-\t\t is_add(scev, t, \u0026l, \u0026r) \u0026\u0026\n-\t\t is_reg(scev, l, \u0026rb) \u0026\u0026\n-\t\t is_imm(scev, r, \u0026imm) \u0026\u0026\n-\t\t ra == rb) {\n-\t\t\tid = expr2(scev, LINEAR_SCEV, l, r);\n-\t\t\tid = expr1(scev, ZEXT32, id);\n-\t\t\tif (id \u003c 0)\n-\t\t\t\treturn id;\n-\t\t\theader_env-\u003ereg2scev[ra] = id;\n-\t\t\tcontinue;\n-\t\t}\n \t\t/*\n+\t\t * A 32-bit induction variable:\n+\t\t * rA = (zext32 (+ rA IMM)) -\u003e (zext32 (linear rA IMM))\n+\t\t * rA = (sext32 (+ rA IMM)) -\u003e (sext32 (linear rA IMM))\n \t\t * rA = (spill32 (+ rA IMM)) -\u003e (spill32 (linear (zext32 rA) IMM))\n-\t\t * The low half of the slot counts. Nothing is known about the other half.\n+\t\t * The last SCEV leaves the upper 32 bits of the slot unknown, so it holds for the\n+\t\t * first two as well. They get it if these bits are dead: the states have a\n+\t\t * 32-bit spill then, see bpf_clean_verifier_state().\n \t\t */\n-\t\tif (is_spill32(scev, ra_expr, \u0026t) \u0026\u0026\n+\t\tif (is_low_bits(scev, ra_expr, 32, \u0026t) \u0026\u0026\n \t\t is_add(scev, t, \u0026l, \u0026r) \u0026\u0026\n \t\t is_reg(scev, l, \u0026rb) \u0026\u0026\n \t\t is_imm(scev, r, \u0026imm) \u0026\u0026\n \t\t ra == rb) {\n-\t\t\tid = expr2(scev, LINEAR_SCEV, expr1(scev, ZEXT32, l), r);\n-\t\t\tid = expr1(scev, SPILL32, id);\n+\t\t\top = hi32_alive_at(env, ra, h) ? scev-\u003eexprs[ra_expr].op : SPILL32;\n+\t\t\tif (op == SPILL32)\n+\t\t\t\tl = expr1(scev, ZEXT32, l);\n+\t\t\tid = expr1(scev, op, expr2(scev, LINEAR_SCEV, l, r));\n \t\t\tif (id \u003c 0)\n \t\t\t\treturn id;\n \t\t\theader_env-\u003ereg2scev[ra] = id;\n@@ -1709,7 +2806,7 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header\n \t\t}\n \t\t/* rA = (any 1 2 3 4 ...) -\u003e (any rA 1 2 3 4 ...) */\n \t\tif (is_any_imm_reg_opaque(scev, ra_expr)) {\n-\t\t\tid = mk_any(scev, expr1(scev, REG, ra), ra_expr);\n+\t\t\tid = mk_any(scev, expr1(scev, REG, ra), ra_expr, no_def);\n \t\t\tif (id \u003c 0)\n \t\t\t\treturn id;\n \t\t\theader_env-\u003ereg2scev[ra] = id;\n@@ -1720,7 +2817,7 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header\n \t/*\n \t *\tdo { i++; if (old \u003e 1021) break; c = buf[old]; old = i; } while (c);\n \t * rA = (+ rB IMM) and rB = (+ rB IMM): an iteration leaves the same number in both. If\n-\t * they are equal when the loop is entered rA is at the header what rB is.\n+\t * they are equal at loop entry too, rA is an induction variable with the same step.\n \t */\n \tfor (ra = 0; ra \u003c REGS_NUM; ra++) {\n \t\tif (header_env-\u003ereg2scev[ra] != UNKNOWN_EXPR_ID ||\n@@ -1730,9 +2827,12 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header\n \t\t\tid = header_env-\u003ereg2scev[rb];\n \t\t\tif (header_env-\u003ereg2expr[rb] != header_env-\u003ereg2expr[ra] ||\n \t\t\t !is_linear_or_linear32(scev, id, \u0026l, \u0026r, \u0026zext32) ||\n-\t\t\t !is_reg(scev, l, \u0026t) || t != rb)\n+\t\t\t !is_reg(scev, l, \u0026t) || t != rb ||\n+\t\t\t !const_diff_at_header(env, h, rb, ra, \u0026imm) || imm)\n \t\t\t\tcontinue;\n-\t\t\tid = expr2(scev, COPY_SCEV, expr1(scev, REG, ra), id);\n+\t\t\tid = expr2(scev, LINEAR_SCEV, expr1(scev, REG, ra), r);\n+\t\t\tif (zext32)\n+\t\t\t\tid = expr1(scev, ZEXT32, id);\n \t\t\tif (id \u003c 0)\n \t\t\t\treturn id;\n \t\t\theader_env-\u003ereg2scev[ra] = id;\n@@ -1742,6 +2842,64 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header\n \treturn 0;\n }\n \n+/*\n+ * Find a SCEV register with the entry value @x and the backedge value @l, and one with @y and @r.\n+ * All that match are copies of each other at the header: take the first.\n+ */\n+static bool find_operands(struct env *entry_env, struct env *header_env, u32 x, u32 y, u32 l, u32 r,\n+\t\t\t u32 *rb, u32 *rc)\n+{\n+\tfor (*rb = 0; *rb \u003c REGS_NUM; ++*rb)\n+\t\tif (entry_env-\u003ereg2expr[*rb] == x \u0026\u0026 header_env-\u003ereg2expr[*rb] == l)\n+\t\t\tbreak;\n+\tfor (*rc = 0; *rc \u003c REGS_NUM; ++*rc)\n+\t\tif (entry_env-\u003ereg2expr[*rc] == y \u0026\u0026 header_env-\u003ereg2expr[*rc] == r)\n+\t\t\tbreak;\n+\treturn *rb \u003c REGS_NUM \u0026\u0026 *rc \u003c REGS_NUM;\n+}\n+\n+/*\n+ *\tp = buf; i = 0; while (*p) { if (i \u003e 512) break; use(p); i += len(p); p = buf + i; }\n+ * rA == rB + rC holds at the header in every iteration: it holds at loop entry and every backedge\n+ * preserves it. The backedge values are rA = (+ l r), rB = l, rC = r. The entry values, by the env\n+ * of the enclosing loop at @h, are rA = x, rB = x, rC = 0 or rA = (+ x y), rB = x, rC = y.\n+ * (add rB rC) keeps the def of (+ l r), see alu64_with_def().\n+ */\n+static int compute_header_adds(struct bpf_verifier_env *env, int h)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct env *entry_env = find_loop_env(scev, env-\u003einsn_aux_data[h].loop_header, h);\n+\tstruct env *header_env = find_header_env(scev, h);\n+\tu32 ra, rb, rc, l, r, x, y, entry_expr;\n+\tstruct expr_def def;\n+\tint id, zero = imm_expr(scev, 0);\n+\n+\tif (zero \u003c 0)\n+\t\treturn zero;\n+\tfor (ra = 0; entry_env \u0026\u0026 ra \u003c REGS_NUM; ra++) {\n+\t\tentry_expr = entry_env-\u003ereg2expr[ra];\n+\t\tif (header_env-\u003ereg2scev[ra] != UNKNOWN_EXPR_ID ||\n+\t\t !is_add(scev, header_env-\u003ereg2expr[ra], \u0026l, \u0026r) ||\n+\t\t !scev-\u003eexprs[entry_expr].is_vn || !scev-\u003eexprs[l].is_vn ||\n+\t\t !scev-\u003eexprs[r].is_vn)\n+\t\t\tcontinue;\n+\t\tif (!find_operands(entry_env, header_env, entry_expr, zero, l, r, \u0026rb, \u0026rc) \u0026\u0026\n+\t\t !find_operands(entry_env, header_env, zero, entry_expr, l, r, \u0026rb, \u0026rc) \u0026\u0026\n+\t\t (scev-\u003eexprs[entry_expr].def.set || !is_add(scev, entry_expr, \u0026x, \u0026y) ||\n+\t\t (!find_operands(entry_env, header_env, x, y, l, r, \u0026rb, \u0026rc) \u0026\u0026\n+\t\t !find_operands(entry_env, header_env, y, x, l, r, \u0026rb, \u0026rc))))\n+\t\t\tcontinue;\n+\t\t/* expr2() can move exprs[] */\n+\t\tdef = scev-\u003eexprs[header_env-\u003ereg2expr[ra]].def;\n+\t\tid = expr_with_def(scev, expr2(scev, ADD_SCEV, REG_EXPR_ID(rb), REG_EXPR_ID(rc)),\n+\t\t\t\t def);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t\theader_env-\u003ereg2scev[ra] = id;\n+\t}\n+\treturn 0;\n+}\n+\n /*\n * 'sum += a[i]', 'if (..) { len -= n; len -= 2; }': is 'id', what an iteration makes of\n * register 'r', the register plus or minus something, or the register as it was?\n@@ -1792,34 +2950,14 @@ static void scev_compute_linear_regs(struct scev *scev, struct bpf_loop *loop,\n \t}\n }\n \n-static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)\n-{\n-\tu32 reg, *reg2scev = priv;\n-\n-\t/* (reg r) -\u003e ... equation at header ... */\n-\tif (is_reg(scev, id, \u0026reg))\n-\t\treturn reg2scev[reg];\n-\t/* keep expression shapes */\n-\treturn id;\n-}\n-\n static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)\n {\n \tstruct scev *scev = env-\u003escev;\n \tint id, reg;\n \n \tfor (reg = 0; reg \u003c REGS_NUM; reg++) {\n-\t\t/*\n-\t\t * Simplify first. 'store, load, test' of a 32-bit counter on the stack with the\n-\t\t * equation of the header in it is deeper than EXPR_STACK_DEPTH.\n-\t\t */\n-\t\tid = transform_expr(scev, einsn-\u003ereg2expr[reg], NULL, simplify);\n-\t\tif (id \u003c 0)\n-\t\t\treturn id;\n-\t\tid = transform_expr_once(scev, 0, id, eheader-\u003ereg2scev, instantiate_header_scevs);\n-\t\tif (id \u003c 0)\n-\t\t\treturn id;\n-\t\tid = transform_expr(scev, id, NULL, simplify);\n+\t\tid = transform_expr_once(scev, 0, einsn-\u003ereg2expr[reg], eheader-\u003ereg2scev,\n+\t\t\t\t\t instantiate_header_scevs);\n \t\tif (id \u003c 0)\n \t\t\treturn id;\n \t\teinsn-\u003ereg2scev[reg] = id;\n@@ -1861,6 +2999,27 @@ static int log_scevs(struct bpf_verifier_env *env)\n \treturn 0;\n }\n \n+/*\n+ * A slice comes from a call that may write to the buffer: the kfunc, or a subprog that calls it.\n+ * See expr_is_vn().\n+ */\n+static void find_slice_slots(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn *insn = env-\u003eprog-\u003einsnsi;\n+\tstruct scev *scev = env-\u003escev;\n+\tbool slices = false;\n+\tu32 i, spi;\n+\n+\tfor (i = 0; i \u003c env-\u003eprog-\u003elen; i++)\n+\t\tslices |= bpf_is_dynptr_slice_rdwr_kfunc(\u0026insn[i]);\n+\tfor (i = 0; slices \u0026\u0026 i \u003c env-\u003eprog-\u003elen; i++)\n+\t\tif (BPF_CLASS(insn[i].code) == BPF_JMP \u0026\u0026 BPF_OP(insn[i].code) == BPF_CALL)\n+\t\t\tbitmap_or(scev-\u003eslice_slots, scev-\u003eslice_slots, bpf_may_write_mask(env, i),\n+\t\t\t\t MAX_BPF_STACK_SLOTS);\n+\tfor_each_set_bit(spi, scev-\u003eslice_slots, MAX_BPF_STACK_SLOTS)\n+\t\tscev-\u003eexprs[REG_EXPR_ID(MAX_BPF_REG + spi)].is_vn = false;\n+}\n+\n int bpf_compute_scev(struct bpf_verifier_env *env)\n {\n \tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n@@ -1869,6 +3028,7 @@ int bpf_compute_scev(struct bpf_verifier_env *env)\n \tint cnt = env-\u003ecfg.cur_postorder;\n \tint i, idx, err, header;\n \n+\tfind_slice_slots(env);\n \tmark_latches(env);\n \t/*\n \t * Visit loop headers in postorder, to guarantee that scevs\n@@ -1878,7 +3038,12 @@ int bpf_compute_scev(struct bpf_verifier_env *env)\n \t\tidx = postorder[i];\n \t\tif (!aux[idx].loop)\n \t\t\tcontinue;\n-\t\terr = compute_scev_for_loop(env, idx);\n+\t\terr = compute_scev_for_loop(env, idx, idx);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++) {\n+\t\terr = compute_scev_for_loop(env, -1, env-\u003esubprog_info[i].start);\n \t\tif (err)\n \t\t\treturn err;\n \t}\n@@ -1892,17 +3057,28 @@ int bpf_compute_scev(struct bpf_verifier_env *env)\n \t\tidx = postorder[i];\n \t\tif (!aux[idx].need_scev)\n \t\t\tcontinue;\n+\t\tif (signal_pending(current))\n+\t\t\treturn -EAGAIN;\n+\t\tcond_resched();\n \t\theader = bpf_loop_at_index(env, idx);\n \t\terr = aux[idx].loop\n-\t\t ? compute_header_scevs(env, find_header_env(scev, header))\n+\t\t ? compute_header_scevs(env, header)\n \t\t : compute_insn_scevs(env,\n \t\t\t\t\t find_header_env(scev, header),\n \t\t\t\t\t find_loop_env(scev, header, idx));\n \t\tif (err)\n \t\t\treturn err;\n-\t\tif (aux[idx].loop)\n+\t\tif (aux[idx].loop) {\n \t\t\tscev_compute_linear_regs(scev, aux[idx].loop,\n \t\t\t\t\t\t find_header_env(scev, header));\n+\t\t\terr = compute_header_adds(env, idx);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t}\n+\t\terr = find_linked_regs(env, aux[idx].loop ? \u0026scev-\u003eidentity_env :\n+\t\t\t\t find_loop_env(scev, header, idx), header, idx);\n+\t\tif (err)\n+\t\t\treturn err;\n \t}\n \n \t/* Now it's known which jumps test a counter: the places of a back edge are for them */\n@@ -1919,6 +3095,21 @@ int bpf_compute_scev(struct bpf_verifier_env *env)\n \treturn 0;\n }\n \n+/*\n+ * Are all slots of the buffer [off, off + size) in slice_slots? Without @fixed_off the buffer is\n+ * somewhere in the range, and the range can be wider than slice_slots: two offsets become a range\n+ * at a join point.\n+ */\n+bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off)\n+{\n+\tint first = bpf_get_spi(off + size - 1), last = bpf_get_spi(off);\n+\tconst unsigned long *slots = env-\u003escev-\u003eslice_slots;\n+\n+\tif (fixed_off)\n+\t\treturn find_next_zero_bit(slots, last + 1, first) \u003e last;\n+\treturn find_next_bit(slots, last + 1, first) \u003c= last;\n+}\n+\n void bpf_free_scev(struct bpf_verifier_env *env)\n {\n \tstruct scev *scev = env-\u003escev;\n@@ -1936,13 +3127,12 @@ void bpf_free_scev(struct bpf_verifier_env *env)\n \t\t\tkfree(envs-\u003eentries[j].env);\n \t\tkfree(envs);\n \t}\n-\tif (scev-\u003eexprs_ht)\n-\t\tfor (i = 0; i \u003c scev-\u003eexprs_ht_cnt; i++)\n-\t\t\tkvfree(scev-\u003eexprs_ht[i]);\n \tkvfree(scev-\u003eexprs_ht);\n+\tkvfree(scev-\u003eexprs_next);\n \tkvfree(scev-\u003eworklist.data);\n \tkvfree(scev-\u003eenvs);\n \tkvfree(scev-\u003eexprs);\n+\tkvfree(scev-\u003elinked);\n \tkvfree(scev-\u003ediscovered);\n \tkfree(scev);\n \tenv-\u003escev = NULL;\n@@ -1951,6 +3141,7 @@ void bpf_free_scev(struct bpf_verifier_env *env)\n int bpf_init_scev(struct bpf_verifier_env *env)\n {\n \tstruct scev *scev;\n+\tu32 r;\n \n \tscev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);\n \tif (!scev)\n@@ -1958,13 +3149,17 @@ int bpf_init_scev(struct bpf_verifier_env *env)\n \tenv-\u003escev = scev;\n \tbpf_mark_reg_known_scalar(\u0026scev-\u003ezero_reg, 0);\n \tbpf_mark_reg_unknown(\u0026scev-\u003eunknown_reg);\n-\t/* A power of two for hash \u0026 (exprs_ht_cnt - 1)` indexing. */\n-\tscev-\u003eexprs_ht_cnt = roundup_pow_of_two(max(256U, DIV_ROUND_UP(env-\u003eprog-\u003elen, 4)));\n-\tscev-\u003eexprs_ht = kvcalloc(scev-\u003eexprs_ht_cnt, sizeof(*scev-\u003eexprs_ht), GFP_KERNEL_ACCOUNT);\n-\tif (!scev-\u003eexprs_ht)\n-\t\tgoto nomem;\n-\tif (expr0(scev, UNKNOWN) \u003c 0 || expr0(scev, OPAQUE) \u003c 0)\n+\tsetup_initial_loop_env(\u0026scev-\u003eidentity_env);\n+\tif (grow_exprs(scev, roundup_pow_of_two(REG_EXPR_ID(REGS_NUM))))\n \t\tgoto nomem;\n+\tscev-\u003eexprs[UNKNOWN_EXPR_ID] = (struct expr){ .op = UNKNOWN };\n+\tscev-\u003eexprs[OPAQUE_EXPR_ID] = (struct expr){ .op = OPAQUE };\n+\tfor (r = 0; r \u003c REGS_NUM; r++)\n+\t\tscev-\u003eexprs[REG_EXPR_ID(r)] = (struct expr){ .op = REG, .is_vn = true,\n+\t\t\t\t\t\t\t .params = { r, 0 } };\n+\tfor (r = 0; r \u003c REG_EXPR_ID(REGS_NUM); r++)\n+\t\tset_expr_base(scev, \u0026scev-\u003eexprs[r], r);\n+\tscev-\u003eexprs_cnt = REG_EXPR_ID(REGS_NUM);\n \tscev-\u003eenvs = kvcalloc(env-\u003eprog-\u003elen, sizeof(*scev-\u003eenvs), GFP_KERNEL_ACCOUNT);\n \tscev-\u003ediscovered = kvcalloc(env-\u003eprog-\u003elen, sizeof(*scev-\u003ediscovered), GFP_KERNEL_ACCOUNT);\n \tif (!scev-\u003eenvs || !scev-\u003ediscovered)\n@@ -2014,24 +3209,15 @@ static struct bpf_reg_state *scev_reg_for_linear(struct bpf_func_state *st, u32\n \treturn \u0026stack-\u003espilled_ptr;\n }\n \n-/* Do the registers or stack slots @a and @b hold the same number in @st? */\n-static bool scev_regs_equal(struct bpf_func_state *st, u32 a, u32 b)\n-{\n-\tconst struct bpf_reg_state *ra = scev_reg_for_linear(st, a);\n-\tconst struct bpf_reg_state *rb = scev_reg_for_linear(st, b);\n-\n-\tif (!ra || !rb || ra-\u003etype != SCALAR_VALUE || rb-\u003etype != SCALAR_VALUE)\n-\t\treturn false;\n-\tif (tnum_is_const(ra-\u003evar_off) \u0026\u0026 tnum_is_const(rb-\u003evar_off))\n-\t\treturn ra-\u003evar_off.value == rb-\u003evar_off.value;\n-\treturn ra-\u003eid \u0026\u0026 ra-\u003eid == rb-\u003eid \u0026\u0026 ra-\u003edelta == rb-\u003edelta;\n-}\n-\n /* '*(u32 *)(r10 - 8) = rX' left a number in the low half of the slot. */\n static struct bpf_reg_state *scev_reg_for_spill32(struct bpf_func_state *st, u32 r)\n {\n \tstruct bpf_stack_state *stack = scev_regno_to_stack(st, r);\n \n+#ifdef __BIG_ENDIAN\n+\t/* a 32-bit spill is in the upper 32 bits of the slot */\n+\treturn NULL;\n+#endif\n \tif (!stack || bpf_spill_size(stack) != 4 || stack-\u003espilled_ptr.type != SCALAR_VALUE)\n \t\treturn NULL;\n \treturn \u0026stack-\u003espilled_ptr;\n@@ -2140,8 +3326,7 @@ static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_sta\n * 'i' is the loop iteration number, starting from 0.\n * 'zext32' indicates the latch is for (zext32 (linear ...)) SCEV.\n * 'jmp32' indicates that the latch is a JMP32 instruction.\n- * 'base_reg' is the register in \u003cbase\u003e. 'copy_reg' is -1, or \u003creg\u003e is made from that register,\n- * which has to be equal to 'base_reg' at the entry of the loop, see COPY_SCEV.\n+ * 'base_reg' is the register in \u003cbase\u003e.\n */\n struct linear_latch {\n \tu32 insn_idx;\n@@ -2149,7 +3334,6 @@ struct linear_latch {\n \tu32 step_expr;\n \tu32 bound_expr;\n \tu32 base_reg;\n-\tint copy_reg;\n \tu8 op;\n \tbool zext32;\n \tbool jmp32;\n@@ -2173,7 +3357,7 @@ static int match_linear_latch(struct bpf_verifier_env *env,\n \tstruct env *latch_env;\n \tu32 src_reg_scev;\n \tu32 dst_reg_scev;\n-\tu32 t, l, r, op;\n+\tu32 l, r, op;\n \tint id;\n \n \top = BPF_OP(insn-\u003ecode);\n@@ -2203,11 +3387,6 @@ static int match_linear_latch(struct bpf_verifier_env *env,\n \t\treturn -EFAULT;\n \tdst_reg_scev = latch_env-\u003ereg2scev[insn-\u003edst_reg];\n \tsrc_reg_scev = latch_env-\u003ereg2scev[insn-\u003esrc_reg];\n-\tlatch-\u003ecopy_reg = -1;\n-\tif (is_copy(scev, dst_reg_scev, \u0026latch-\u003ecopy_reg, \u0026t))\n-\t\tdst_reg_scev = t;\n-\telse if (BPF_SRC(insn-\u003ecode) == BPF_X \u0026\u0026 is_copy(scev, src_reg_scev, \u0026latch-\u003ecopy_reg, \u0026t))\n-\t\tsrc_reg_scev = t;\n \t/*\n \t * Make sure (linear ...) is in dst_reg_scev:\n \t * 'if \u003cinvariant\u003e \u003cop\u003e \u003clinear\u003e' ⇔\n@@ -2905,8 +4084,6 @@ static bool compute_max_iters(struct bpf_verifier_env *env,\n \n \titers-\u003eiv_reg = -1;\n \n-\tif (latch-\u003ecopy_reg \u003e= 0 \u0026\u0026 !scev_regs_equal(st, latch-\u003ecopy_reg, latch-\u003ebase_reg))\n-\t\treturn false;\n \tif (!eval_expr(env, scev, st, latch-\u003ebase_expr, \u0026initial_val) ||\n \t !eval_expr(env, scev, st, latch-\u003estep_expr, \u0026step_val) ||\n \t !eval_expr(env, scev, st, latch-\u003ebound_expr, \u0026bound_val))\n@@ -3051,7 +4228,7 @@ static bool is_unbound_scev_reg(struct bpf_verifier_env *env, const struct bpf_f\n {\n \tconst struct bpf_reg_state *reg = scev_reg_for_read(env, st, r);\n \n-\treturn reg \u0026\u0026 reg-\u003etype == SCALAR_VALUE \u0026\u0026 !reg-\u003eid \u0026\u0026 reg-\u003estep \u003c= 1 \u0026\u0026\n+\treturn reg \u0026\u0026 reg-\u003etype == SCALAR_VALUE \u0026\u0026 reg-\u003estep \u003c= 1 \u0026\u0026\n \t tnum_is_unknown(reg-\u003evar_off) \u0026\u0026\n \t reg-\u003er64.size == U64_MAX \u0026\u0026 reg-\u003er32.size == U32_MAX;\n }\n@@ -3114,7 +4291,7 @@ static bool is_const_scev_reg(struct bpf_verifier_env *env, int insn_idx, u32 r)\n }\n \n /* Main logic in verifier.c forbids varying offsets for certain register types. */\n-static bool is_widenable_reg_type(const struct bpf_reg_state *reg)\n+bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg)\n {\n \tif (type_may_be_null(reg-\u003etype))\n \t\treturn false;\n@@ -3137,9 +4314,6 @@ static bool is_widenable_reg_type(const struct bpf_reg_state *reg)\n static void scratch_widened_reg_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)\n {\n \tswitch (base_type(reg-\u003etype)) {\n-\tcase SCALAR_VALUE:\n-\t\tclear_scalar_id(reg);\n-\t\tbreak;\n \tcase PTR_TO_PACKET:\n \tcase PTR_TO_PACKET_META:\n \t\treg-\u003eid = ++env-\u003eid_gen;\n@@ -3161,7 +4335,7 @@ static bool is_widenable_any(struct bpf_verifier_env *env, struct bpf_func_state\n \tif (!is_any(scev, id, \u0026l, \u0026rr))\n \t\treturn false;\n \treg = scev_reg_for_read(env, loop_entry, r);\n-\tif (!reg || !is_widenable_reg_type(reg))\n+\tif (!reg || !bpf_is_widenable_reg_type(reg))\n \t\treturn false;\n \n \tscev-\u003estack_sz = 0;\n@@ -3219,8 +4393,10 @@ struct linear_coefs {\n \tu32 base_reg;\n \ts64 slope;\n \tbool zext32;\n-\t/* the low half of a stack slot */\n+\t/* with zext32: the low 32 bits of a stack slot */\n \tbool spill32;\n+\t/* with zext32: the low 32 bits are sign extended */\n+\tbool sext32;\n };\n \n static bool is_simple_slope(struct scev *scev, u32 id, s64 *slope)\n@@ -3236,55 +4412,25 @@ static bool is_simple_linear(struct scev *scev, u32 id, struct linear_coefs *out\n \tu32 base, slope;\n \n \tout-\u003espill32 = false;\n-\treturn is_linear_or_linear32(scev, id, \u0026base, \u0026slope, \u0026out-\u003ezext32) \u0026\u0026\n-\t is_reg(scev, base, \u0026out-\u003ebase_reg) \u0026\u0026\n+\tout-\u003esext32 = is_unop(scev, SEXT32, id, \u0026id);\n+\tif (!is_linear_or_linear32(scev, id, \u0026base, \u0026slope, \u0026out-\u003ezext32) ||\n+\t (out-\u003esext32 \u0026\u0026 out-\u003ezext32))\n+\t\treturn false;\n+\tout-\u003ezext32 |= out-\u003esext32;\n+\treturn is_reg(scev, base, \u0026out-\u003ebase_reg) \u0026\u0026\n \t is_simple_slope(scev, slope, \u0026out-\u003eslope);\n }\n \n /*\n- * Is @r 'what it is in @st + slope * k' at the header in iteration k? @id is its SCEV there, @st is\n- * the state that entered the loop. At a jump in the loop @id can be what another register was at\n- * the header. @st says nothing about @r then.\n+ * Is @r 'its entry value + slope * k' at the header in iteration k? @id is its SCEV there. At a\n+ * jump in the loop @id can be linear in the entry value of another register: the entry value of @r\n+ * does not bound it then.\n */\n-static bool is_linear_at_header(struct scev *scev, struct bpf_func_state *st, u32 id, u32 r,\n-\t\t\t\tstruct linear_coefs *out)\n+static bool is_linear_at_header(struct scev *scev, u32 id, u32 r, struct linear_coefs *out)\n {\n-\tu32 copy, orig;\n-\n-\tif (is_copy(scev, id, \u0026copy, \u0026orig))\n-\t\treturn copy == r \u0026\u0026 is_simple_linear(scev, orig, out) \u0026\u0026\n-\t\t scev_regs_equal(st, r, out-\u003ebase_reg);\n \treturn is_simple_linear(scev, id, out) \u0026\u0026 out-\u003ebase_reg == r;\n }\n \n-/*\n- * @st is at the header of a loop that @entry entered. A copy of an induction variable is equal to\n- * it there in every iteration. They got their ranges one by one: give them one id, like 'r2 = r1'\n- * does, so that a test of one of them is a test of both.\n- */\n-static void link_copies(struct bpf_verifier_env *env, struct env *header_env,\n-\t\t\tstruct bpf_func_state *entry, struct bpf_func_state *st)\n-{\n-\tstruct bpf_reg_state *reg, *orig;\n-\tstruct linear_coefs coefs;\n-\tu32 r;\n-\n-\tfor (r = 0; r \u003c REGS_NUM; r++) {\n-\t\tif (!is_linear_at_header(env-\u003escev, entry, header_env-\u003ereg2scev[r], r, \u0026coefs) ||\n-\t\t coefs.base_reg == r)\n-\t\t\tcontinue;\n-\t\treg = scev_reg_for_linear(st, r);\n-\t\torig = scev_reg_for_linear(st, coefs.base_reg);\n-\t\tif (!reg || !orig || reg-\u003etype != SCALAR_VALUE || orig-\u003etype != SCALAR_VALUE ||\n-\t\t tnum_is_const(orig-\u003evar_off))\n-\t\t\tcontinue;\n-\t\tif (!orig-\u003eid)\n-\t\t\torig-\u003eid = ++env-\u003eid_gen;\n-\t\treg-\u003eid = orig-\u003eid;\n-\t\treg-\u003edelta = orig-\u003edelta;\n-\t}\n-}\n-\n /*\n * A 32-bit counter that lives on the stack: the SCEV of slot @r is\n * (spill32 (linear (zext32 @r) slope)) and there is a 32-bit number in the slot in @st.\n@@ -3303,6 +4449,7 @@ static struct bpf_reg_state *spill32_counter(struct scev *scev, struct bpf_func_\n \t\treturn NULL;\n \tout-\u003ezext32 = true;\n \tout-\u003espill32 = true;\n+\tout-\u003esext32 = false;\n \treturn scev_reg_for_spill32(st, r);\n }\n \n@@ -3311,6 +4458,11 @@ static struct cnum64 cnum64_zext32(struct cnum32 r32)\n \treturn cnum64_from_urange(cnum32_umin(r32), cnum32_umax(r32));\n }\n \n+static struct cnum64 cnum64_sext32(struct cnum32 r32)\n+{\n+\treturn cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32));\n+}\n+\n /* Compute the range an induction variable in `reg` spans over the loop. */\n static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,\n \t\t\t struct linear_coefs *coefs, struct bounds *out)\n@@ -3340,12 +4492,14 @@ static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,\n \tr32 = CNUM32_UNBOUNDED;\n \tif (coefs-\u003ezext32) {\n \t\tr32 = cnum32_from_cnum64(r64);\n-\t\tr64 = cnum64_zext32(r32);\n+\t\tr64 = coefs-\u003esext32 ? cnum64_sext32(r32) : cnum64_zext32(r32);\n \t\t/*\n \t\t * 32-bit iteration overflow is equivalent to subtracting N * 2**32:\n \t\t * (base + slope * k) % slope ≠ (base + slope * k - N * 2**32) % slope.\n \t\t */\n-\t\toverflow |= cnum32_contains(r32, 0) \u0026\u0026 cnum32_contains(r32, U32_MAX);\n+\t\toverflow |= coefs-\u003esext32 ?\n+\t\t\t cnum32_contains(r32, S32_MAX) \u0026\u0026 cnum32_contains(r32, S32_MIN) :\n+\t\t\t cnum32_contains(r32, 0) \u0026\u0026 cnum32_contains(r32, U32_MAX);\n \t\t/*\n \t\t * The entry and zero-extended values must agree on how they define `base`,\n \t\t * otherwise `base + slope * k` would define different sets of points between\n@@ -3376,10 +4530,27 @@ static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,\n \tout-\u003er32 = r32;\n }\n \n-static void iv_bounds(struct bounds *bounds, struct cnum64 iv_range)\n+/*\n+ * Is @r the induction variable that the latch tests, or congruent to it: equal to it at the header\n+ * of the loop at @h in every iteration? Then the range of the one is the range of the other.\n+ */\n+static bool is_iv_at_header(struct bpf_verifier_env *env, int h, int iv_reg, u32 r)\n+{\n+\ts64 delta;\n+\n+\tif (iv_reg \u003c 0)\n+\t\treturn false;\n+\treturn r == iv_reg || (const_diff_at_header(env, h, iv_reg, r, \u0026delta) \u0026\u0026 !delta);\n+}\n+\n+static void iv_bounds(struct bounds *bounds, const struct linear_coefs *coefs,\n+\t\t struct cnum64 iv_range)\n {\n \tstruct cnum64 r64 = cnum64_intersect(bounds-\u003er64, iv_range);\n \n+\t/* The latch bounds the zero extension. With bit 31 set the sign extension differs. */\n+\tif (coefs-\u003esext32 \u0026\u0026 cnum64_umax(iv_range) \u003e S32_MAX)\n+\t\treturn;\n \tif (!cnum64_is_empty(r64))\n \t\tbounds-\u003er64 = r64;\n }\n@@ -3693,8 +4864,8 @@ int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_sta\n \t\t\tcontinue;\n \t\t}\n \t\t/* If SCEV for r is (linear \u003creg\u003e \u003cslope\u003e) */\n-\t\tif (reg \u0026\u0026 is_linear_at_header(scev, cur_func, r_scev, r, \u0026coefs) \u0026\u0026\n-\t\t is_widenable_reg_type(reg)) {\n+\t\tif (reg \u0026\u0026 is_linear_at_header(scev, r_scev, r, \u0026coefs) \u0026\u0026\n+\t\t bpf_is_widenable_reg_type(reg)) {\n \t\t\t/* 32-bit ALU operations on pointers convert them to scalars */\n \t\t\tif (coefs.zext32 \u0026\u0026 reg-\u003etype != SCALAR_VALUE)\n \t\t\t\tgoto cant_widen;\n@@ -3891,7 +5062,7 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state\n \t\tif (back \u0026\u0026 (!val || !entry_val || !bpf_reg_union_compatible(val, entry_val)))\n \t\t\tcontinue;\n \t\tif (test_bit(r, iters-\u003emask_regs)) {\n-\t\t\t/* The range stays. It's no longer equal to the registers with its id. */\n+\t\t\t/* the range stays */\n \t\t\terr = scev_reg_for_write(env, cur_func, r, \u0026reg);\n \t\t\tif (!err \u0026\u0026 back)\n \t\t\t\terr = bpf_reg_union(env, reg, entry_val);\n@@ -3903,13 +5074,12 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state\n \t\t\t\tbpf_log(log, \" stays in 0..%llu, it loses bits only\\n\",\n \t\t\t\t\treg_umax(reg));\n \t\t\t}\n-\t\t\tscratch_widened_reg_id(env, reg);\n \t\t\tmark_scev_reg_scratched(env, r);\n \t\t\tcontinue;\n \t\t}\n \n \t\t/* If SCEV for r is (linear \u003creg\u003e \u003cslope\u003e)*/\n-\t\tif (spill32 || is_linear_at_header(scev, entry_func, r_expr, r, \u0026coefs)) {\n+\t\tif (spill32 || is_linear_at_header(scev, r_expr, r, \u0026coefs)) {\n \t\t\t/* the range is derived from @loop_entry: bpf_clamp_scev_regs() */\n \t\t\tif (back)\n \t\t\t\tcontinue;\n@@ -3919,8 +5089,8 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state\n \t\t\tif (err)\n \t\t\t\treturn err;\n \t\t\tlinear_bounds(reg, iters-\u003emax_header_count, \u0026coefs, \u0026bounds);\n-\t\t\tif (coefs.base_reg == iters-\u003eiv_reg)\n-\t\t\t\tiv_bounds(\u0026bounds, iters-\u003eiv_range);\n+\t\t\tif (is_iv_at_header(env, insn_idx, iters-\u003eiv_reg, coefs.base_reg))\n+\t\t\t\tiv_bounds(\u0026bounds, \u0026coefs, iters-\u003eiv_range);\n \t\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2) {\n \t\t\t\tbpf_log(log, \"loop header at %d, widening \", insn_idx);\n \t\t\t\tlog_reg(env, r);\n@@ -3957,7 +5127,6 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state\n \t\t\tmark_scev_reg_scratched(env, r);\n \t\t}\n \t}\n-\tlink_copies(env, header_env, entry_func, cur_func);\n \treturn 1;\n }\n \n@@ -3967,6 +5136,7 @@ static bool is_moved_linear(struct scev *scev, u32 id, struct linear_coefs *out,\n \tu32 base, slope, l, r;\n \n \tout-\u003espill32 = false;\n+\tout-\u003esext32 = false;\n \treturn is_linear_or_linear32(scev, id, \u0026base, \u0026slope, \u0026out-\u003ezext32) \u0026\u0026 !out-\u003ezext32 \u0026\u0026\n \t is_add(scev, base, \u0026l, \u0026r) \u0026\u0026 is_reg(scev, l, \u0026out-\u003ebase_reg) \u0026\u0026\n \t is_imm(scev, r, moved) \u0026\u0026 is_simple_slope(scev, slope, \u0026out-\u003eslope);\n@@ -4014,7 +5184,7 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur\n \t\t\tgoto clamp;\n \n \t\t/* If SCEV for r is (linear \u003creg\u003e \u003cslope\u003e)*/\n-\t\tif (!is_linear_at_header(scev, entry_st, r_scev, r, \u0026coefs) \u0026\u0026\n+\t\tif (!is_linear_at_header(scev, r_scev, r, \u0026coefs) \u0026\u0026\n \t\t !(behind \u0026\u0026 is_moved_linear(scev, r_scev, \u0026coefs, \u0026moved) \u0026\u0026\n \t\t coefs.base_reg == r))\n \t\t\tcontinue;\n@@ -4037,13 +5207,17 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur\n \t\t * bpf_compute_loop_iters() gives no range to a pointer to arena that moves, and\n \t\t * it does not look at dead registers. Set a range only where it would.\n \t\t */\n-\t\tif (!is_widenable_reg_type(entry_reg) ||\n+\t\tif (!bpf_is_widenable_reg_type(entry_reg) ||\n \t\t (coefs.zext32 \u0026\u0026 entry_reg-\u003etype != SCALAR_VALUE))\n \t\t\tcontinue;\n clamp:\n \t\tlinear_bounds(entry_reg, max_header_count, \u0026coefs, \u0026bounds);\n-\t\tif (coefs.base_reg == entry-\u003eiv_reg \u0026\u0026 !moved)\n-\t\t\tiv_bounds(\u0026bounds, entry-\u003eiv_range);\n+\t\t/*\n+\t\t * iv_range is the range at the header. After the latch @r can be the zero extension\n+\t\t * of its header value. @reg went through that insn and has what holds of the range.\n+\t\t */\n+\t\tif (!behind \u0026\u0026 is_iv_at_header(env, insn_idx, entry-\u003eiv_reg, coefs.base_reg))\n+\t\t\tiv_bounds(\u0026bounds, \u0026coefs, entry-\u003eiv_range);\n \t\tif (moved) {\n \t\t\t/* a sum that can wrap has another residue, see scalar_step_add() */\n \t\t\tif (check_add_overflow(cnum64_smin(bounds.r64), moved, \u0026sum) ||\n@@ -4084,8 +5258,5 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur\n \t\t\treturn err;\n \t\tmark_scev_reg_scratched(env, r);\n \t}\n-\t/* behind the jump the variable may have moved on: its copy is what it was at the head */\n-\tif (!behind)\n-\t\tlink_copies(env, header_env, entry_st, cur_func_state);\n \treturn 0;\n }\ndiff --git a/kernel/bpf/states.c b/kernel/bpf/states.c\nindex efc0870b85c2a3..48359e789faadb 100644\n--- a/kernel/bpf/states.c\n+++ b/kernel/bpf/states.c\n@@ -58,7 +58,7 @@ static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)\n \t\treturn true;\n \n \t/* a name of what the caller has, see BPF_INHERITED_ID */\n-\tif (((old_id | cur_id) \u0026 ~BPF_ADD_CONST) \u003e= BPF_INHERITED_ID)\n+\tif ((old_id | cur_id) \u003e= BPF_INHERITED_ID)\n \t\treturn old_id == cur_id;\n \n \tfor (i = 0; i \u003c idmap-\u003ecnt; i++) {\n@@ -85,49 +85,6 @@ static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)\n \treturn false;\n }\n \n-/*\n- * Compare scalar register IDs for state equivalence.\n- *\n- * When old_id == 0, the old register is independent - not linked to any\n- * other register. Any linking in the current state only adds constraints,\n- * making it more restrictive. Since the old state didn't rely on any ID\n- * relationships for this register, it's always safe to accept cur regardless\n- * of its ID. Hence, return true immediately.\n- *\n- * When old_id != 0 but cur_id == 0, we need to ensure that different\n- * independent registers in cur don't incorrectly satisfy the ID matching\n- * requirements of linked registers in old.\n- *\n- * Example: if old has r6.id=X and r7.id=X (linked), but cur has r6.id=0\n- * and r7.id=0 (both independent), without temp IDs both would map old_id=X\n- * to cur_id=0 and pass. With temp IDs: r6 maps X-\u003etemp1, r7 tries to map\n- * X-\u003etemp2, but X is already mapped to temp1, so the check fails correctly.\n- *\n- * When old_id has BPF_ADD_CONST set, the compound id (base | flag) and the\n- * base id (flag stripped) must both map consistently. Example: old has\n- * r2.id=A, r3.id=A|flag (r3 = r2 + delta), cur has r2.id=B, r3.id=C|flag\n- * (r3 derived from unrelated r4). Without the base check, idmap gets two\n- * independent entries A-\u003eB and A|flag-\u003eC|flag, missing that A-\u003eC conflicts\n- * with A-\u003eB. The base ID cross-check catches this.\n- */\n-static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)\n-{\n-\tif (!old_id)\n-\t\treturn true;\n-\n-\tcur_id = cur_id ? cur_id : ++idmap-\u003etmp_id_gen;\n-\n-\tif (!check_ids(old_id, cur_id, idmap))\n-\t\treturn false;\n-\tif (old_id \u0026 BPF_ADD_CONST) {\n-\t\told_id \u0026= ~BPF_ADD_CONST;\n-\t\tcur_id \u0026= ~BPF_ADD_CONST;\n-\t\tif (!check_ids(old_id, cur_id, idmap))\n-\t\t\treturn false;\n-\t}\n-\treturn true;\n-}\n-\n static void __clean_func_state(struct bpf_verifier_env *env,\n \t\t\t struct bpf_func_state *st,\n \t\t\t u16 live_regs, int frame)\n@@ -168,6 +125,16 @@ static void __clean_func_state(struct bpf_verifier_env *env,\n \t\t\t stype == STACK_IRQ_FLAG)\n \t\t\t\tcontinue;\n \n+\t\t\t/*\n+\t\t\t * When the half-slot closer to FP is dead, what remains of a\n+\t\t\t * 64-bit spill looks like a 32-bit spill: the low 32 bits of\n+\t\t\t * the value. On big endian the other half-slot holds the upper\n+\t\t\t * 32 bits.\n+\t\t\t */\n+\t\t\tif (hi_live \u0026\u0026 bpf_spill_size(bpf_stack_slot(st, i)) == BPF_REG_SIZE \u0026\u0026\n+\t\t\t !bpf_stack_narrow_access_ok(0, BPF_REG_SIZE / 2, BPF_REG_SIZE))\n+\t\t\t\tcontinue;\n+\n \t\t\t/*\n \t\t\t * Only scalar spills can be degraded to raw stack bytes\n \t\t\t * when their high half is dead. Pointer spills need the\n@@ -262,65 +229,8 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,\n \t\t\t/* explore_alu_limits disables tnum_in() and range_within()\n \t\t\t * logic and requires everything to be strict\n \t\t\t */\n-\t\t\treturn memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 \u0026\u0026\n-\t\t\t check_scalar_ids(rold-\u003eid, rcur-\u003eid, idmap);\n+\t\t\treturn memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0;\n \t\t}\n-\t\t/*\n-\t\t * Linked register tracking uses rold-\u003eid to detect relationships.\n-\t\t * When rold-\u003eid == 0, the register is independent and any linking\n-\t\t * in rcur only adds constraints. When rold-\u003eid != 0, we must verify\n-\t\t * id mapping and (for BPF_ADD_CONST) offset consistency.\n-\t\t *\n-\t\t * +------------------+-----------+------------------+---------------+\n-\t\t * | | rold-\u003eid | rold + ADD_CONST | rold-\u003eid == 0 |\n-\t\t * |------------------+-----------+------------------+---------------|\n-\t\t * | rcur-\u003eid | range,ids | false | range |\n-\t\t * | rcur + ADD_CONST | false | range,ids,off | range |\n-\t\t * | rcur-\u003eid == 0 | range,ids | false | range |\n-\t\t * +------------------+-----------+------------------+---------------+\n-\t\t *\n-\t\t * Why check_ids() for scalar registers?\n-\t\t *\n-\t\t * Consider the following BPF code:\n-\t\t * 1: r6 = ... unbound scalar, ID=a ...\n-\t\t * 2: r7 = ... unbound scalar, ID=b ...\n-\t\t * 3: if (r6 \u003e r7) goto +1\n-\t\t * 4: r6 = r7\n-\t\t * 5: if (r6 \u003e X) goto ...\n-\t\t * 6: ... memory operation using r7 ...\n-\t\t *\n-\t\t * First verification path is [1-6]:\n-\t\t * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;\n-\t\t * - at (5) r6 would be marked \u003c= X, sync_linked_regs() would also mark\n-\t\t * r7 \u003c= X, because r6 and r7 share same id.\n-\t\t * Next verification path is [1-4, 6].\n-\t\t *\n-\t\t * Instruction (6) would be reached in two states:\n-\t\t * I. r6{.id=b}, r7{.id=b} via path 1-6;\n-\t\t * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.\n-\t\t *\n-\t\t * Use check_ids() to distinguish these states.\n-\t\t * ---\n-\t\t * Also verify that new value satisfies old value range knowledge.\n-\t\t */\n-\n-\t\t/*\n-\t\t * ADD_CONST flags must match exactly: BPF_ADD_CONST32 and\n-\t\t * BPF_ADD_CONST64 have different linking semantics in\n-\t\t * sync_linked_regs() (alu32 zero-extends, alu64 does not),\n-\t\t * so one doesn't stand for the other.\n-\t\t */\n-\t\tif (rold-\u003eid \u0026\u0026\n-\t\t (rold-\u003eid \u0026 BPF_ADD_CONST) != (rcur-\u003eid \u0026 BPF_ADD_CONST))\n-\t\t\treturn false;\n-\n-\t\t/* Both have offset linkage: offsets must match */\n-\t\tif ((rold-\u003eid \u0026 BPF_ADD_CONST) \u0026\u0026 rold-\u003edelta != rcur-\u003edelta)\n-\t\t\treturn false;\n-\n-\t\tif (!check_scalar_ids(rold-\u003eid, rcur-\u003eid, idmap))\n-\t\t\treturn false;\n-\n \t\treturn range_within(rold, rcur) \u0026\u0026 tnum_in(rold-\u003evar_off, rcur-\u003evar_off);\n \tcase PTR_TO_MAP_KEY:\n \tcase PTR_TO_MAP_VALUE:\n@@ -446,11 +356,19 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,\n \t\tif (!cur_slot)\n \t\t\treturn false;\n \n+\t\t/*\n+\t\t * The old spill is the first bytes of a wider spill. On big endian\n+\t\t * these are not the low bytes of the value.\n+\t\t */\n+\t\tif (old_type == STACK_SPILL \u0026\u0026 bpf_is_spilled_reg(cur_slot) \u0026\u0026\n+\t\t !bpf_stack_narrow_access_ok(0, bpf_spill_size(old_slot),\n+\t\t\t\t\t\tbpf_spill_size(cur_slot)))\n+\t\t\treturn false;\n+\n \t\t/*\n \t\t * 64 and 32-bit scalar spills vs MISC/INVALID slots and vice versa.\n \t\t * Load from MISC/INVALID slots produces unbound scalar.\n-\t\t * Construct a fake register for such stack and call\n-\t\t * regsafe() to ensure scalar ids are compared.\n+\t\t * Construct a fake register for such stack and call regsafe().\n \t\t */\n \t\tif (im == 0 || im == 4) {\n \t\t\told_reg = scalar_reg_for_stack(env, old_slot, im);\n@@ -717,7 +635,6 @@ static void reset_idmap_scratch(struct bpf_verifier_env *env)\n {\n \tstruct bpf_idmap *idmap = \u0026env-\u003eidmap_scratch;\n \n-\tidmap-\u003etmp_id_gen = env-\u003eid_gen;\n \tidmap-\u003ecnt = 0;\n }\n \ndiff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c\nindex 9004f2673ccf96..04a3b3c80c74e0 100644\n--- a/kernel/bpf/syscall.c\n+++ b/kernel/bpf/syscall.c\n@@ -6692,7 +6692,7 @@ static const struct bpf_func_proto bpf_sys_bpf_proto = {\n \t.might_sleep\t= true,\n \t.ret_type\t= RET_INTEGER,\n \t.arg1_type\t= ARG_ANYTHING,\n-\t.arg2_type\t= ARG_PTR_TO_MEM | MEM_RDONLY,\n+\t.arg2_type\t= ARG_PTR_TO_MEM | MEM_WRITE,\n \t.arg3_type\t= ARG_MEM_SIZE,\n };\n \ndiff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c\nindex 20b1b9ff574c7d..d549644235c55a 100644\n--- a/kernel/bpf/verifier.c\n+++ b/kernel/bpf/verifier.c\n@@ -2325,6 +2325,36 @@ static bool range_bounds_violation(struct bpf_reg_state *reg)\n \treturn cnum32_is_empty(reg-\u003er32) || cnum64_is_empty(reg-\u003er64);\n }\n \n+/* Do @t and [min, max] overlap: is a member of @t in the range? */\n+static bool tnum_overlaps_urange(struct tnum t, u64 min, u64 max)\n+{\n+\tu64 tnum_next = tnum_step(t, min);\n+\n+\treturn (min \u0026 ~t.mask) == t.value || (tnum_next \u003e min \u0026\u0026 tnum_next \u003c= max);\n+}\n+\n+/* The same for the cnum [@base, @base + @size]. It wraps around at @ut_max. */\n+static bool tnum_overlaps_cnum(struct tnum t, u64 base, u64 size, u64 ut_max)\n+{\n+\tu64 end = (base + size) \u0026 ut_max;\n+\n+\tif (base \u003c= end)\n+\t\treturn tnum_overlaps_urange(t, base, end);\n+\treturn tnum_overlaps_urange(t, base, ut_max) || tnum_overlaps_urange(t, 0, end);\n+}\n+\n+/*\n+ * A range and var_off don't overlap. reg_bounds_sync() compares var_off with umin and umax: it\n+ * doesn't see that [-2, 1], which crosses 0, has no member with 5 in its low three bits.\n+ */\n+static bool reg_is_empty(struct bpf_reg_state *reg)\n+{\n+\treturn range_bounds_violation(reg) ||\n+\t !tnum_overlaps_cnum(reg-\u003evar_off, reg-\u003er64.base, reg-\u003er64.size, U64_MAX) ||\n+\t !tnum_overlaps_cnum(tnum_subreg(reg-\u003evar_off), reg-\u003er32.base, reg-\u003er32.size,\n+\t\t\t\t U32_MAX);\n+}\n+\n static int reg_bounds_sanity_check(struct bpf_verifier_env *env,\n \t\t\t\t struct bpf_reg_state *reg, const char *ctx)\n {\n@@ -3548,30 +3578,6 @@ static void mark_non_stack_access(struct bpf_verifier_env *env, int idx)\n \tenv-\u003einsn_aux_data[idx].non_stack_access = true;\n }\n \n-#define LINKED_REGS_MAX\t5\n-\n-struct linked_reg {\n-\tu8 frameno;\n-\tunion {\n-\t\tu16 spi;\n-\t\tu16 regno;\n-\t};\n-\tbool is_reg;\n-};\n-\n-struct linked_regs {\n-\tint cnt;\n-\tstruct linked_reg entries[LINKED_REGS_MAX];\n-};\n-\n-static struct linked_reg *linked_regs_push(struct linked_regs *s)\n-{\n-\tif (s-\u003ecnt \u003c LINKED_REGS_MAX)\n-\t\treturn \u0026s-\u003eentries[s-\u003ecnt++];\n-\n-\treturn NULL;\n-}\n-\n const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)\n {\n \tconst struct btf_type *func;\n@@ -3628,27 +3634,6 @@ static bool __is_pointer_value(bool allow_ptr_leaks,\n \treturn is_pointer_regtype(reg-\u003etype);\n }\n \n-static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,\n-\t\t\t\t\tstruct bpf_reg_state *src_reg)\n-{\n-\tif (src_reg-\u003etype != SCALAR_VALUE)\n-\t\treturn;\n-\t/*\n-\t * The verifier is processing rX = rY insn and\n-\t * rY-\u003eid has special linked register already.\n-\t * Cleared it, since multiple rX += const are not supported.\n-\t */\n-\tif (src_reg-\u003eid \u0026 BPF_ADD_CONST)\n-\t\tclear_scalar_id(src_reg);\n-\t/*\n-\t * Ensure that src_reg has a valid ID that will be copied to\n-\t * dst_reg and then will be used by sync_linked_regs() to\n-\t * propagate min/max range.\n-\t */\n-\tif (!src_reg-\u003eid \u0026\u0026 !tnum_is_const(src_reg-\u003evar_off))\n-\t\tsrc_reg-\u003eid = ++env-\u003eid_gen;\n-}\n-\n static void save_register_state(struct bpf_verifier_env *env,\n \t\t\t\tstruct bpf_func_state *state,\n \t\t\t\tint spi, struct bpf_reg_state *reg,\n@@ -3675,11 +3660,6 @@ static bool is_bpf_st_mem(struct bpf_insn *insn)\n \treturn BPF_CLASS(insn-\u003ecode) == BPF_ST \u0026\u0026 BPF_MODE(insn-\u003ecode) == BPF_MEM;\n }\n \n-static int get_reg_width(struct bpf_reg_state *reg)\n-{\n-\treturn fls64(reg_umax(reg));\n-}\n-\n /* See comment for mark_fastcall_pattern_for_call() */\n static void check_fastcall_stack_contract(struct bpf_verifier_env *env,\n \t\t\t\t\t struct bpf_func_state *state, int insn_idx, int off)\n@@ -3780,16 +3760,7 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env,\n \n \tmark_stack_slot_scratched(env, spi);\n \tif (reg \u0026\u0026 !(off % BPF_REG_SIZE) \u0026\u0026 reg-\u003etype == SCALAR_VALUE \u0026\u0026 env-\u003ebpf_capable) {\n-\t\tbool reg_value_fits;\n-\n-\t\treg_value_fits = get_reg_width(reg) \u003c= BITS_PER_BYTE * size;\n-\t\t/* Make sure that reg had an ID to build a relation on spill. */\n-\t\tif (reg_value_fits)\n-\t\t\tassign_scalar_id_before_mov(env, reg);\n \t\tsave_register_state(env, state, spi, reg, size);\n-\t\t/* Break the relation on a narrowing spill. */\n-\t\tif (!reg_value_fits)\n-\t\t\tclear_scalar_id(\u0026ss-\u003espilled_ptr);\n \t} else if (!reg \u0026\u0026 !(off % BPF_REG_SIZE) \u0026\u0026 is_bpf_st_mem(insn) \u0026\u0026\n \t\t env-\u003ebpf_capable) {\n \t\tstruct bpf_reg_state *tmp_reg = \u0026env-\u003efake_reg[0];\n@@ -4092,19 +4063,8 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,\n \t\t\t\tif (dst_regno \u003c 0)\n \t\t\t\t\treturn 0;\n \n-\t\t\t\tif (env-\u003ebpf_capable \u0026\u0026 size == 4 \u0026\u0026 spill_size == 4 \u0026\u0026\n-\t\t\t\t get_reg_width(reg) \u003c= 32)\n-\t\t\t\t\t/* Ensure stack slot has an ID to build a relation\n-\t\t\t\t\t * with the destination register on fill.\n-\t\t\t\t\t */\n-\t\t\t\t\tassign_scalar_id_before_mov(env, reg);\n+\t\t\t\t/* coerce_reg_to_size will adjust the boundaries. */\n \t\t\t\tstate-\u003eregs[dst_regno] = *reg;\n-\n-\t\t\t\t/* Break the relation on a narrowing fill.\n-\t\t\t\t * coerce_reg_to_size will adjust the boundaries.\n-\t\t\t\t */\n-\t\t\t\tif (get_reg_width(reg) \u003e size * BITS_PER_BYTE)\n-\t\t\t\t\tclear_scalar_id(\u0026state-\u003eregs[dst_regno]);\n \t\t\t} else {\n \t\t\t\tint spill_cnt = 0, zero_cnt = 0;\n \n@@ -4149,11 +4109,6 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,\n \t\t\t}\n \t\t} else if (dst_regno \u003e= 0) {\n \t\t\t/* restore register state from stack */\n-\t\t\tif (env-\u003ebpf_capable)\n-\t\t\t\t/* Ensure stack slot has an ID to build a relation\n-\t\t\t\t * with the destination register on fill.\n-\t\t\t\t */\n-\t\t\t\tassign_scalar_id_before_mov(env, reg);\n \t\t\tstate-\u003eregs[dst_regno] = *reg;\n \t\t} else if (__is_pointer_value(env-\u003eallow_ptr_leaks, reg)) {\n \t\t\t/* If dst_regno==-1, the caller is asking us whether\n@@ -6441,14 +6396,28 @@ static void set_sext32_default_val(struct bpf_reg_state *reg, int size)\n static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)\n {\n \ts32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;\n+\ts32 field_smin, field_smax;\n \tu32 top_smax_value, top_smin_value;\n \tu32 num_bits = size * 8;\n \n+\tif (size == 1) {\n+\t\tfield_smin = S8_MIN;\n+\t\tfield_smax = S8_MAX;\n+\t} else {\n+\t\t/* size == 2 */\n+\t\tfield_smin = S16_MIN;\n+\t\tfield_smax = S16_MAX;\n+\t}\n+\n \t/*\n-\t * If value fits the non-negative half of the signed N-bit range,\n-\t * sign extension is a noop.\n+\t * The range already fits the signed N-bit range, so (sN)v == v for every\n+\t * value of the low 32 bits and the sign extension is a no-op.\n+\t *\n+\t * This has to precede reg_step_reset() below: the base/step line stays.\n+\t * It is about all 64 bits: zext_32_to_64() in the caller discards it\n+\t * if the upper 32 bits are not zero.\n \t */\n-\tif (reg_umax(reg) \u003c (1ULL \u003c\u003c (num_bits - 1)))\n+\tif (reg_s32_min(reg) \u003e= field_smin \u0026\u0026 reg_s32_max(reg) \u003c= field_smax)\n \t\treturn;\n \n \t/* See comment at reg_step_check_unsigned(). */\n@@ -7669,18 +7638,7 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b\n \t\t\t/* b/h/w load zero-extends, mark upper bits as known 0 */\n \t\t\tcoerce_reg_to_size(\u0026regs[value_regno], size);\n \t\t} else {\n-\t\t\t/*\n-\t\t\t * Sign-extension can change the register value relative\n-\t\t\t * to a scalar it is linked with by id (e.g. a zero-\n-\t\t\t * extending fill of the same spilled stack slot), thus\n-\t\t\t * drop the shared id in that case.\n-\t\t\t */\n-\t\t\tbool no_sext = reg_umax(\u0026regs[value_regno]) \u003c\n-\t\t\t\t\t(1ULL \u003c\u003c (size * BITS_PER_BYTE - 1));\n-\n \t\t\tcoerce_reg_to_size_sx(\u0026regs[value_regno], size);\n-\t\t\tif (!no_sext)\n-\t\t\t\tclear_scalar_id(\u0026regs[value_regno]);\n \t\t}\n \t}\n \n@@ -11716,16 +11674,11 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i\n \tcallee-\u003eentry_rcu_locks = entry.active_rcu_locks;\n \tcallee-\u003eentry_preempt_locks = entry.active_preempt_locks;\n \tfor (i = BPF_REG_1; i \u003c= BPF_REG_5; i++) {\n-\t\t/* what a scalar is linked to stays with the caller, so does the delta to it */\n-\t\tif (callee-\u003eregs[i].type == SCALAR_VALUE)\n-\t\t\tclear_scalar_id(\u0026callee-\u003eregs[i]);\n \t\tcallee-\u003eregs[i].id = inherited_id(state, callee-\u003eregs[i].id);\n \t\tcallee-\u003eregs[i].parent_id = inherited_id(state, callee-\u003eregs[i].parent_id);\n \t\tcallee-\u003eregs[i].map_uid = inherited_id(state, callee-\u003eregs[i].map_uid);\n \t}\n \tfor (i = 0; i \u003c callee-\u003eout_stack_arg_cnt; i++) {\n-\t\tif (callee-\u003estack_arg_regs[i].type == SCALAR_VALUE)\n-\t\t\tclear_scalar_id(\u0026callee-\u003estack_arg_regs[i]);\n \t\tcallee-\u003estack_arg_regs[i].id = inherited_id(state, callee-\u003estack_arg_regs[i].id);\n \t\tcallee-\u003estack_arg_regs[i].parent_id =\n \t\t\tinherited_id(state, callee-\u003estack_arg_regs[i].parent_id);\n@@ -11771,19 +11724,18 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env)\n \n static u32 fresh_id(struct bpf_verifier_env *env, struct bpf_idmap *idmap, u32 id)\n {\n-\tu32 flags = id \u0026 BPF_ADD_CONST, i;\n+\tu32 i;\n \n-\tid \u0026= ~BPF_ADD_CONST;\n \tif (!id)\n \t\treturn 0;\n \tfor (i = 0; i \u003c idmap-\u003ecnt; i++)\n \t\tif (idmap-\u003emap[i].old == id)\n-\t\t\treturn idmap-\u003emap[i].cur | flags;\n+\t\t\treturn idmap-\u003emap[i].cur;\n \tif (idmap-\u003ecnt == BPF_ID_MAP_SIZE)\n \t\treturn 0;\n \tidmap-\u003emap[idmap-\u003ecnt].old = id;\n \tidmap-\u003emap[idmap-\u003ecnt].cur = ++env-\u003eid_gen;\n-\treturn idmap-\u003emap[idmap-\u003ecnt++].cur | flags;\n+\treturn idmap-\u003emap[idmap-\u003ecnt++].cur;\n }\n \n /*\n@@ -15150,6 +15102,12 @@ bool bpf_is_throw_kfunc(struct bpf_insn *insn)\n \t insn-\u003eimm == special_kfunc_list[KF_bpf_throw];\n }\n \n+bool bpf_is_dynptr_slice_rdwr_kfunc(struct bpf_insn *insn)\n+{\n+\treturn bpf_pseudo_kfunc_call(insn) \u0026\u0026 insn-\u003eoff == 0 \u0026\u0026\n+\t insn-\u003eimm == special_kfunc_list[KF_bpf_dynptr_slice_rdwr];\n+}\n+\n static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)\n {\n \treturn btf_id == special_kfunc_list[KF_bpf_wq_set_callback];\n@@ -15974,6 +15932,15 @@ static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg\n \t\tregs[BPF_REG_0].buf = meta-\u003eslice_buf;\n \t\tif (meta-\u003eslice_buf.size)\n \t\t\tenv-\u003eseen_stack_slice = true;\n+\t\t/* No insn stores through a slice of 0 bytes */\n+\t\tif (verifier_bug_if(meta-\u003eslice_buf.size \u0026\u0026 meta-\u003earg_constant.value \u0026\u0026\n+\t\t\t\t !type_is_rdonly_mem(regs[BPF_REG_0].type) \u0026\u0026\n+\t\t\t\t !bpf_scev_in_slice_slots(env, meta-\u003eslice_buf.off,\n+\t\t\t\t\t\t\t meta-\u003eslice_buf.size,\n+\t\t\t\t\t\t\t meta-\u003eslice_buf.size ==\n+\t\t\t\t\t\t\t meta-\u003earg_constant.value),\n+\t\t\t\t env, \"slice buffer is not in scev slice_slots\"))\n+\t\t\treturn -EFAULT;\n \t} else {\n \t\treturn 0;\n \t}\n@@ -17841,13 +17808,6 @@ static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *ins\n \t/* Apply bswap if alu64 or switch between big-endian and little-endian machines */\n \tbool need_bswap = alu64 || (to_le == is_big_endian);\n \n-\t/*\n-\t * If the register is mutated, manually reset its scalar ID to break\n-\t * any existing ties and avoid incorrect bounds propagation.\n-\t */\n-\tif (need_bswap || insn-\u003eimm == 16 || insn-\u003eimm == 32)\n-\t\tclear_scalar_id(dst_reg);\n-\n \tif (need_bswap) {\n \t\tif (insn-\u003eimm == 16)\n \t\t\tdst_reg-\u003evar_off = tnum_bswap16(dst_reg-\u003evar_off);\n@@ -17948,7 +17908,6 @@ static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *ins\n \t * like any other. At this insn the branch is a part of the state that is looked at:\n \t * it must not be compared with it.\n \t */\n-\tclear_scalar_id(reg);\n \treturn adjust_scalar_min_max_vals(env, insn, reg, *src_reg);\n }\n \n@@ -18158,10 +18117,8 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,\n \tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\n \tstruct bpf_reg_state *regs = state-\u003eregs, *dst_reg, *src_reg;\n \tstruct bpf_reg_state *ptr_reg = NULL, off_reg = {0};\n-\tbool alu32 = (BPF_CLASS(insn-\u003ecode) != BPF_ALU64);\n \tstruct bpf_insn_aux_data *aux = cur_aux(env);\n \tu8 opcode = BPF_OP(insn-\u003ecode);\n-\tint err;\n \n \tdst_reg = \u0026regs[insn-\u003edst_reg];\n \tif (BPF_SRC(insn-\u003ecode) == BPF_X)\n@@ -18268,69 +18225,7 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,\n \t\tverbose(env, \"verifier internal error: no src_reg\\n\");\n \t\treturn -EFAULT;\n \t}\n-\t/*\n-\t * For alu32 linked register tracking, we need to check dst_reg's\n-\t * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),\n-\t * alu32 ops will have zero-extended the result, making umax_value \u003c= U32_MAX.\n-\t */\n-\tu64 dst_umax = reg_umax(dst_reg);\n-\n-\terr = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);\n-\tif (err)\n-\t\treturn err;\n-\t/*\n-\t * Compilers can generate the code\n-\t * r1 = r2\n-\t * r1 += 0x1\n-\t * if r2 \u003c 1000 goto ...\n-\t * use r1 in memory access\n-\t * So remember constant delta between r2 and r1 and update r1 after\n-\t * 'if' condition.\n-\t */\n-\tif (env-\u003ebpf_capable \u0026\u0026\n-\t (BPF_OP(insn-\u003ecode) == BPF_ADD || BPF_OP(insn-\u003ecode) == BPF_SUB) \u0026\u0026\n-\t dst_reg-\u003eid \u0026\u0026 is_reg_const(src_reg, alu32) \u0026\u0026\n-\t !(BPF_SRC(insn-\u003ecode) == BPF_X \u0026\u0026 insn-\u003esrc_reg == insn-\u003edst_reg)) {\n-\t\tu64 val = reg_const_value(src_reg, alu32);\n-\t\ts32 off;\n-\n-\t\tif (!alu32 \u0026\u0026 ((s64)val \u003c S32_MIN || (s64)val \u003e S32_MAX))\n-\t\t\tgoto clear_id;\n-\n-\t\tif (alu32 \u0026\u0026 (dst_umax \u003e U32_MAX))\n-\t\t\tgoto clear_id;\n-\n-\t\toff = (s32)val;\n-\n-\t\tif (BPF_OP(insn-\u003ecode) == BPF_SUB) {\n-\t\t\t/* Negating S32_MIN would overflow */\n-\t\t\tif (off == S32_MIN)\n-\t\t\t\tgoto clear_id;\n-\t\t\toff = -off;\n-\t\t}\n-\n-\t\tif (dst_reg-\u003eid \u0026 BPF_ADD_CONST) {\n-\t\t\t/*\n-\t\t\t * If the register already went through rX += val\n-\t\t\t * we cannot accumulate another val into rx-\u003eoff.\n-\t\t\t */\n-clear_id:\n-\t\t\tclear_scalar_id(dst_reg);\n-\t\t} else {\n-\t\t\tif (alu32)\n-\t\t\t\tdst_reg-\u003eid |= BPF_ADD_CONST32;\n-\t\t\telse\n-\t\t\t\tdst_reg-\u003eid |= BPF_ADD_CONST64;\n-\t\t\tdst_reg-\u003edelta = off;\n-\t\t}\n-\t} else {\n-\t\t/*\n-\t\t * Make sure ID is cleared otherwise dst_reg min/max could be\n-\t\t * incorrectly propagated into other registers by sync_linked_regs()\n-\t\t */\n-\t\tclear_scalar_id(dst_reg);\n-\t}\n-\treturn 0;\n+\treturn adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);\n }\n \n /*\n@@ -18544,7 +18439,6 @@ void bpf_reg_union_range(struct bpf_reg_state *acc, const struct bpf_reg_state *\n /*\n * Extends acc's scalar range to include src's scalar range.\n * Caller must ensure that other kinds of metadata is compatible.\n- * Caller must clear acc's scalar ID.\n */\n int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,\n \t\t const struct bpf_reg_state *src)\n@@ -18685,7 +18579,6 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)\n \t\t\t\t\t/* case: R1 = R2\n \t\t\t\t\t * copy register state to dest reg\n \t\t\t\t\t */\n-\t\t\t\t\tassign_scalar_id_before_mov(env, src_reg);\n \t\t\t\t\t*dst_reg = *src_reg;\n \t\t\t\t} else {\n \t\t\t\t\t/* case: R1 = (s8, s16 s32)R2 */\n@@ -18695,14 +18588,7 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)\n \t\t\t\t\t\t\tinsn-\u003esrc_reg);\n \t\t\t\t\t\treturn -EACCES;\n \t\t\t\t\t} else if (src_reg-\u003etype == SCALAR_VALUE) {\n-\t\t\t\t\t\tbool no_sext;\n-\n-\t\t\t\t\t\tno_sext = reg_umax(src_reg) \u003c (1ULL \u003c\u003c (insn-\u003eoff - 1));\n-\t\t\t\t\t\tif (no_sext)\n-\t\t\t\t\t\t\tassign_scalar_id_before_mov(env, src_reg);\n \t\t\t\t\t\t*dst_reg = *src_reg;\n-\t\t\t\t\t\tif (!no_sext)\n-\t\t\t\t\t\t\tclear_scalar_id(dst_reg);\n \t\t\t\t\t\tcoerce_reg_to_size_sx(dst_reg, insn-\u003eoff \u003e\u003e 3);\n \t\t\t\t\t} else {\n \t\t\t\t\t\tmark_reg_unknown(env, regs, insn-\u003edst_reg);\n@@ -18716,29 +18602,10 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)\n \t\t\t\t\t\tinsn-\u003esrc_reg);\n \t\t\t\t\treturn -EACCES;\n \t\t\t\t} else if (src_reg-\u003etype == SCALAR_VALUE) {\n-\t\t\t\t\tif (insn-\u003eoff == 0) {\n-\t\t\t\t\t\tbool is_src_reg_u32 = get_reg_width(src_reg) \u003c= 32;\n-\n-\t\t\t\t\t\tif (is_src_reg_u32)\n-\t\t\t\t\t\t\tassign_scalar_id_before_mov(env, src_reg);\n-\t\t\t\t\t\t*dst_reg = *src_reg;\n-\t\t\t\t\t\t/* Make sure ID is cleared if src_reg is not in u32\n-\t\t\t\t\t\t * range otherwise dst_reg min/max could be incorrectly\n-\t\t\t\t\t\t * propagated into src_reg by sync_linked_regs()\n-\t\t\t\t\t\t */\n-\t\t\t\t\t\tif (!is_src_reg_u32)\n-\t\t\t\t\t\t\tclear_scalar_id(dst_reg);\n-\t\t\t\t\t} else {\n-\t\t\t\t\t\t/* case: W1 = (s8, s16)W2 */\n-\t\t\t\t\t\tbool no_sext = reg_umax(src_reg) \u003c (1ULL \u003c\u003c (insn-\u003eoff - 1));\n-\n-\t\t\t\t\t\tif (no_sext)\n-\t\t\t\t\t\t\tassign_scalar_id_before_mov(env, src_reg);\n-\t\t\t\t\t\t*dst_reg = *src_reg;\n-\t\t\t\t\t\tif (!no_sext)\n-\t\t\t\t\t\t\tclear_scalar_id(dst_reg);\n+\t\t\t\t\t*dst_reg = *src_reg;\n+\t\t\t\t\t/* case: W1 = (s8, s16)W2 */\n+\t\t\t\t\tif (insn-\u003eoff)\n \t\t\t\t\t\tcoerce_subreg_to_size_sx(dst_reg, insn-\u003eoff \u003e\u003e 3);\n-\t\t\t\t\t}\n \t\t\t\t} else {\n \t\t\t\t\tmark_reg_unknown(env, regs,\n \t\t\t\t\t\t\t insn-\u003edst_reg);\n@@ -18902,7 +18769,7 @@ static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode,\n \t * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only\n \t * TRUE branch will be taken.\n \t */\n-\tif (range_bounds_violation(\u0026env-\u003efalse_reg1) || range_bounds_violation(\u0026env-\u003efalse_reg2))\n+\tif (reg_is_empty(\u0026env-\u003efalse_reg1) || reg_is_empty(\u0026env-\u003efalse_reg2))\n \t\treturn 1;\n \n \t/* Jump (TRUE) branch */\n@@ -18914,7 +18781,7 @@ static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode,\n \t * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.\n \t * Only FALSE branch will be taken.\n \t */\n-\tif (range_bounds_violation(\u0026env-\u003etrue_reg1) || range_bounds_violation(\u0026env-\u003etrue_reg2))\n+\tif (reg_is_empty(\u0026env-\u003etrue_reg1) || reg_is_empty(\u0026env-\u003etrue_reg2))\n \t\treturn 0;\n \n \t/* Both branches are possible, we can't determine which one will be taken. */\n@@ -19537,116 +19404,178 @@ static bool try_match_pkt_pointers(const struct bpf_insn *insn,\n \treturn true;\n }\n \n-static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,\n-\t\t\t\t u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)\n+/* a == b (mod 2^N) implies a == b if both fit in uN or both fit in sN. N is @bits. */\n+static bool regs_fit_in_bits(const struct bpf_reg_state *a, const struct bpf_reg_state *b,\n+\t\t\t u32 bits)\n {\n-\tstruct linked_reg *e;\n+\tu64 umax = GENMASK_ULL(bits - 1, 0);\n+\ts64 smax = umax \u003e\u003e 1;\n \n-\tif (reg-\u003etype != SCALAR_VALUE || (reg-\u003eid \u0026 ~BPF_ADD_CONST) != id)\n-\t\treturn;\n+\treturn (reg_umax(a) \u003c= umax \u0026\u0026 reg_umax(b) \u003c= umax) ||\n+\t (reg_smin(a) \u003e= -smax - 1 \u0026\u0026 reg_smax(a) \u003c= smax \u0026\u0026\n+\t\treg_smin(b) \u003e= -smax - 1 \u0026\u0026 reg_smax(b) \u003c= smax);\n+}\n \n-\te = linked_regs_push(reg_set);\n-\tif (e) {\n-\t\te-\u003eframeno = frameno;\n-\t\te-\u003eis_reg = is_reg;\n-\t\te-\u003eregno = spi_or_reg;\n-\t} else {\n-\t\tclear_scalar_id(reg);\n-\t}\n+/*\n+ * The state of the SCEV register @r. As in check_stack_read_fixed_off() a fill of @bits bits from\n+ * byte @fill_off of the slot reads the low bits of the spill.\n+ */\n+static struct bpf_reg_state *scev_reg_for_fill(struct bpf_func_state *frame, u32 r, u32 fill_off,\n+\t\t\t\t\t u32 bits)\n+{\n+\tstruct bpf_stack_state *ss;\n+\n+\tif (r \u003c MAX_BPF_REG)\n+\t\treturn \u0026frame-\u003eregs[r];\n+\tif (r - MAX_BPF_REG \u003e= bpf_stack_nr_slots(frame))\n+\t\treturn NULL;\n+\tss = bpf_stack_slot(frame, r - MAX_BPF_REG);\n+\tif (!bpf_is_spilled_reg(ss) || bpf_spill_size(ss) * BITS_PER_BYTE \u003c bits ||\n+\t !bpf_stack_narrow_access_ok(fill_off, bits / BITS_PER_BYTE, bpf_spill_size(ss)))\n+\t\treturn NULL;\n+\treturn \u0026ss-\u003espilled_ptr;\n }\n \n-/* For all R being scalar registers or spilled scalar registers\n- * in verifier state, save R in linked_regs if R-\u003eid == id.\n- * If there are too many Rs sharing same id, reset id for leftover Rs.\n+/*\n+ * Scalar evolution promoted memory to the SCEV register *@regno, see struct env there, and names\n+ * its address at the jump at @idx. This state knows which memory it is: the frame that is returned,\n+ * its stack slot *@regno, *@fill_off counts from the start of the slot. The stack of a caller only:\n+ * other memory has no state, and a store through r10 is no def of memory for scalar evolution.\n+ * What holds the address is live: it was compared all the way from its def. Every place that\n+ * compares, joins or drops states cleans them of what is dead first, see flow_arrive().\n */\n-static void collect_linked_regs(struct bpf_verifier_env *env,\n-\t\t\t\tstruct bpf_verifier_state *vstate,\n-\t\t\t\tu32 id,\n-\t\t\t\tstruct linked_regs *linked_regs)\n+static struct bpf_func_state *scev_mem_to_slot(struct bpf_verifier_env *env,\n+\t\t\t\t\t struct bpf_verifier_state *vstate, int idx,\n+\t\t\t\t\t u32 *regno, u32 *fill_off)\n {\n-\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n-\tstruct bpf_func_state *func;\n-\tstruct bpf_reg_state *reg;\n-\tu16 live_regs;\n-\tint i, j;\n+\tstruct bpf_reg_state *ptr;\n+\tu32 base_regno;\n+\ts64 addr;\n \n-\tid = id \u0026 ~BPF_ADD_CONST;\n-\tfor (i = vstate-\u003ecurframe; i \u003e= 0; i--) {\n-\t\tlive_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;\n-\t\tfunc = vstate-\u003eframe[i];\n-\t\tfor (j = 0; j \u003c BPF_REG_FP; j++) {\n-\t\t\tif (!(live_regs \u0026 BIT(j)))\n-\t\t\t\tcontinue;\n-\t\t\treg = \u0026func-\u003eregs[j];\n-\t\t\t__collect_linked_regs(linked_regs, reg, id, i, j, true);\n-\t\t}\n-\t\tfor (j = 0; j \u003c bpf_stack_nr_slots(func); j++) {\n-\t\t\tstruct bpf_stack_state *ss = bpf_stack_slot(func, j);\n+\tif (!bpf_scev_mem_addr(env, idx, *regno, \u0026base_regno, \u0026addr))\n+\t\treturn NULL;\n+\tptr = scev_reg_for_fill(vstate-\u003eframe[vstate-\u003ecurframe], base_regno, 0, 64);\n+\tif (!ptr || ptr-\u003etype != PTR_TO_STACK || !tnum_is_const(ptr-\u003evar_off) ||\n+\t ptr-\u003eframeno \u003e= vstate-\u003ecurframe)\n+\t\treturn NULL;\n+\taddr += ptr-\u003evar_off.value + *fill_off;\n+\tif (addr \u003e= 0 || addr \u003c -MAX_BPF_STACK_JIT)\n+\t\treturn NULL;\n+\t*regno = MAX_BPF_REG + bpf_get_spi(addr);\n+\t*fill_off = addr \u0026 (BPF_REG_SIZE - 1);\n+\treturn vstate-\u003eframe[ptr-\u003eframeno];\n+}\n \n-\t\t\tif (!bpf_is_spilled_reg(ss))\n-\t\t\t\tcontinue;\n-\t\t\treg = \u0026ss-\u003espilled_ptr;\n-\t\t\t__collect_linked_regs(linked_regs, reg, id, i, j, false);\n-\t\t}\n-\t}\n+/*\n+ *\tp = buf + i; if (i \u003e 100) return 0; *p = 0;\n+ * p is @dst_reg, x is @ptr_reg, i is @off_reg. Scalar evolution says that p == x + i. So the insns\n+ * 'p = x; p += i' are a no-op at run time, and a state that is sound before them is sound after\n+ * them: apply their transfer function. Type, object and offset of p are taken from x as it is now;\n+ * how p was computed does not matter.\n+ * The old p is replaced, not intersected: a state does not distinguish two values of one hash map,\n+ * and the intersection of an offset into the one with an offset into the other holds for neither.\n+ * It is replaced only if the new range is a subset of the old one. An empty range is a subset too:\n+ * the path is infeasible, p is left as it is.\n+ */\n+static bool recompute_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *dst_reg,\n+\t\t\t const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg)\n+{\n+\tstruct bpf_reg_state sum = *ptr_reg;\n+\n+\t/* the cpu can speculate past the jump with an out-of-bounds index */\n+\tif (!env-\u003ebypass_spec_v1)\n+\t\treturn false;\n+\t/* 'p += i' assigns a new id to a packet pointer */\n+\tif (ptr_reg-\u003etype == SCALAR_VALUE || type_is_pkt_pointer(ptr_reg-\u003etype) ||\n+\t !bpf_is_widenable_reg_type(ptr_reg))\n+\t\treturn false;\n+\t__mark_reg32_unbounded(\u0026sum);\n+\tscalar_step_add(\u0026sum, ptr_reg, off_reg);\n+\tsum.r64 = cnum64_add(ptr_reg-\u003er64, off_reg-\u003er64);\n+\tsum.var_off = tnum_add(ptr_reg-\u003evar_off, off_reg-\u003evar_off);\n+\treg_bounds_sync(\u0026sum);\n+\tif (reg_is_empty(\u0026sum) || const_tnum_range_mismatch(\u0026sum) ||\n+\t const_tnum_range_mismatch_32(\u0026sum))\n+\t\treturn false;\n+\tif (!bpf_reg_union_compatible(dst_reg, \u0026sum) || !cnum64_is_subset(dst_reg-\u003er64, sum.r64))\n+\t\treturn false;\n+\t*dst_reg = sum;\n+\treturn true;\n }\n \n-/* For all R in linked_regs, copy known_reg range into R\n- * if R-\u003eid == known_reg-\u003eid.\n+/*\n+ * The jump at @idx refined @regno. A register that scalar evolution links to it holds\n+ * @regno + delta on every path to the jump: intersect the two. The intersection is empty: no\n+ * execution gets here with this state (the path is infeasible), the register is left as it is.\n */\n-static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,\n-\t\t\t struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)\n+static void refine_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,\n+\t\t\t int idx, u32 regno)\n {\n-\tstruct bpf_reg_state fake_reg;\n-\tstruct bpf_reg_state *reg;\n-\tstruct linked_reg *e;\n-\tint i;\n+\tstruct bpf_func_state *frame = vstate-\u003eframe[vstate-\u003ecurframe], *linked_frame;\n+\tstruct bpf_reg_state *reg, *base_reg, implied, saved;\n+\tu32 pos, linked_regno, fill_off, bits;\n+\tint base_regno;\n+\ts64 delta;\n \n-\tfor (i = 0; i \u003c linked_regs-\u003ecnt; ++i) {\n-\t\te = \u0026linked_regs-\u003eentries[i];\n-\t\treg = e-\u003eis_reg ? \u0026vstate-\u003eframe[e-\u003eframeno]-\u003eregs[e-\u003eregno]\n-\t\t\t\t: \u0026bpf_stack_slot(vstate-\u003eframe[e-\u003eframeno], e-\u003espi)-\u003espilled_ptr;\n-\t\tif (reg-\u003etype != SCALAR_VALUE || reg == known_reg)\n-\t\t\tcontinue;\n-\t\tif ((reg-\u003eid \u0026 ~BPF_ADD_CONST) != (known_reg-\u003eid \u0026 ~BPF_ADD_CONST))\n+\tif (frame-\u003eregs[regno].type != SCALAR_VALUE)\n+\t\treturn;\n+\tfor (pos = 0;\n+\t bpf_scev_next_linked_reg(env, idx, regno, \u0026pos, \u0026linked_regno, \u0026fill_off, \u0026base_regno,\n+\t\t\t\t \u0026delta, \u0026bits);\n+\t pos++) {\n+\t\tlinked_frame = frame;\n+\t\tif (linked_regno \u003e= BPF_SCEV_REGS_NUM)\n+\t\t\tlinked_frame = scev_mem_to_slot(env, vstate, idx, \u0026linked_regno, \u0026fill_off);\n+\t\tif (!linked_frame)\n \t\t\tcontinue;\n+\t\treg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);\n \t\t/*\n-\t\t * Skip mixed 32/64-bit links: the delta relationship doesn't\n-\t\t * hold across different ALU widths.\n+\t\t * The other half-slot of a 64-bit spill is dead: __clean_func_state() left\n+\t\t * a 32-bit spill, the low 32 bits of the value.\n \t\t */\n-\t\tif (((reg-\u003eid ^ known_reg-\u003eid) \u0026 BPF_ADD_CONST) == BPF_ADD_CONST)\n+\t\tif (!reg \u0026\u0026 bits == 64 \u0026\u0026\n+\t\t bpf_stack_narrow_access_ok(fill_off, BPF_REG_SIZE / 2, BPF_REG_SIZE)) {\n+\t\t\tbits = 32;\n+\t\t\treg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);\n+\t\t}\n+\t\tif (!reg || (base_regno \u003c 0 \u0026\u0026 reg-\u003etype != SCALAR_VALUE))\n \t\t\tcontinue;\n-\t\tif ((!(reg-\u003eid \u0026 BPF_ADD_CONST) \u0026\u0026 !(known_reg-\u003eid \u0026 BPF_ADD_CONST)) ||\n-\t\t reg-\u003edelta == known_reg-\u003edelta) {\n-\t\t\t*reg = *known_reg;\n-\t\t} else {\n-\t\t\ts32 saved_off = reg-\u003edelta;\n-\t\t\tu32 saved_id = reg-\u003eid;\n \n-\t\t\tfake_reg.type = SCALAR_VALUE;\n-\t\t\t__mark_reg_known(\u0026fake_reg, (s64)reg-\u003edelta - (s64)known_reg-\u003edelta);\n-\n-\t\t\t/* reg = known_reg; reg += delta */\n-\t\t\t*reg = *known_reg;\n-\t\t\t/*\n-\t\t\t * Must preserve off and id, otherwise another sync_linked_regs()\n-\t\t\t * will be incorrect.\n-\t\t\t */\n-\t\t\treg-\u003edelta = saved_off;\n-\t\t\treg-\u003eid = saved_id;\n-\n-\t\t\tscalar_step_add(reg, reg, \u0026fake_reg);\n-\t\t\tscalar32_min_max_add(reg, \u0026fake_reg);\n-\t\t\tscalar_min_max_add(reg, \u0026fake_reg);\n-\t\t\treg-\u003evar_off = tnum_add(reg-\u003evar_off, fake_reg.var_off);\n-\t\t\tif ((reg-\u003eid | known_reg-\u003eid) \u0026 BPF_ADD_CONST32)\n-\t\t\t\tzext_32_to_64(reg);\n-\t\t\treg_bounds_sync(reg);\n-\t\t}\n-\t\tif (e-\u003eis_reg)\n-\t\t\tmark_reg_scratched(env, e-\u003eregno);\n-\t\telse\n-\t\t\tmark_stack_slot_scratched(env, e-\u003espi);\n+\t\timplied = frame-\u003eregs[regno];\n+\t\tadd_scalar_to_reg(\u0026implied, delta);\n+\t\tif (base_regno \u003e= 0) {\n+\t\t\tbase_reg = scev_reg_for_fill(frame, base_regno, 0, 64);\n+\t\t\tif (base_reg \u0026\u0026 bits == 64 \u0026\u0026 recompute_ptr(env, reg, base_reg, \u0026implied))\n+\t\t\t\tgoto scratch;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (regs_fit_in_bits(reg, \u0026implied, bits))\n+\t\t\tbits = 64;\n+\t\tif (bits \u003c 32)\n+\t\t\tcontinue;\n+\t\t/* tnum_intersect() of two tnums that don't overlap is not empty */\n+\t\tif (!tnum_overlap(bits == 32 ? tnum_subreg(reg-\u003evar_off) : reg-\u003evar_off,\n+\t\t\t\t bits == 32 ? tnum_subreg(implied.var_off) : implied.var_off))\n+\t\t\tcontinue;\n+\t\tsaved = *reg;\n+\t\t/*\n+\t\t * Equal in 64 bits is equal in the low 32 bits too. 'if w1 s\u003e 200' on a zero\n+\t\t * extended int refines nothing but the 32-bit range.\n+\t\t */\n+\t\tregs_refine_cond_op(reg, \u0026implied, BPF_JEQ, true);\n+\t\tif (bits == 64)\n+\t\t\tregs_refine_cond_op(reg, \u0026implied, BPF_JEQ, false);\n+\t\treg_bounds_sync(reg);\n+\t\tif (reg_is_empty(reg) || const_tnum_range_mismatch(reg) ||\n+\t\t const_tnum_range_mismatch_32(reg)) {\n+\t\t\t*reg = saved;\n+\t\t\tcontinue;\n+\t\t}\n+scratch:\n+\t\tif (linked_regno \u003c MAX_BPF_REG)\n+\t\t\tmark_reg_scratched(env, linked_regno);\n+\t\telse if (linked_frame == frame)\n+\t\t\tmark_stack_slot_scratched(env, linked_regno - MAX_BPF_REG);\n \t}\n }\n \n@@ -19677,7 +19606,6 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,\n \tstruct bpf_reg_state *regs = this_branch-\u003eframe[this_branch-\u003ecurframe]-\u003eregs;\n \tstruct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;\n \tstruct bpf_reg_state *eq_branch_regs;\n-\tstruct linked_regs linked_regs = {};\n \tu8 opcode = BPF_OP(insn-\u003ecode);\n \tbool is_jmp32;\n \tint pred = -1;\n@@ -19746,16 +19674,6 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,\n \t\t__mark_reg_known(src_reg, insn-\u003eimm);\n \t}\n \n-\t/*\n-\t * Collect the linked registers before env-\u003e{true,false}_reg{1,2} setup,\n-\t * otherwise ids dropped by collect_linked_regs() would be resurrected\n-\t * when env-\u003e{true,false}_reg{1,2} are copied back.\n-\t */\n-\tif (BPF_SRC(insn-\u003ecode) == BPF_X \u0026\u0026 src_reg-\u003etype == SCALAR_VALUE \u0026\u0026 src_reg-\u003eid)\n-\t\tcollect_linked_regs(env, this_branch, src_reg-\u003eid, \u0026linked_regs);\n-\tif (dst_reg-\u003etype == SCALAR_VALUE \u0026\u0026 dst_reg-\u003eid)\n-\t\tcollect_linked_regs(env, this_branch, dst_reg-\u003eid, \u0026linked_regs);\n-\n \tis_jmp32 = BPF_CLASS(insn-\u003ecode) == BPF_JMP32;\n \tenv-\u003efalse_reg1 = *dst_reg;\n \tenv-\u003efalse_reg2 = *src_reg;\n@@ -19809,18 +19727,13 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,\n \tif (BPF_SRC(insn-\u003ecode) == BPF_X)\n \t\tother_branch_regs[insn-\u003esrc_reg] = env-\u003etrue_reg2;\n \n-\tif (BPF_SRC(insn-\u003ecode) == BPF_X \u0026\u0026\n-\t src_reg-\u003etype == SCALAR_VALUE \u0026\u0026 src_reg-\u003eid \u0026\u0026\n-\t !WARN_ON_ONCE(src_reg-\u003eid != other_branch_regs[insn-\u003esrc_reg].id)) {\n-\t\tsync_linked_regs(env, this_branch, src_reg, \u0026linked_regs);\n-\t\tsync_linked_regs(env, other_branch, \u0026other_branch_regs[insn-\u003esrc_reg],\n-\t\t\t\t \u0026linked_regs);\n-\t}\n-\tif (dst_reg-\u003etype == SCALAR_VALUE \u0026\u0026 dst_reg-\u003eid \u0026\u0026\n-\t !WARN_ON_ONCE(dst_reg-\u003eid != other_branch_regs[insn-\u003edst_reg].id)) {\n-\t\tsync_linked_regs(env, this_branch, dst_reg, \u0026linked_regs);\n-\t\tsync_linked_regs(env, other_branch, \u0026other_branch_regs[insn-\u003edst_reg],\n-\t\t\t\t \u0026linked_regs);\n+\tif (env-\u003ebpf_capable) {\n+\t\tif (BPF_SRC(insn-\u003ecode) == BPF_X) {\n+\t\t\trefine_linked_regs(env, this_branch, *insn_idx, insn-\u003esrc_reg);\n+\t\t\trefine_linked_regs(env, other_branch, *insn_idx, insn-\u003esrc_reg);\n+\t\t}\n+\t\trefine_linked_regs(env, this_branch, *insn_idx, insn-\u003edst_reg);\n+\t\trefine_linked_regs(env, other_branch, *insn_idx, insn-\u003edst_reg);\n \t}\n \n \t/* if one pointer register is compared to another pointer\n@@ -20674,69 +20587,6 @@ static void adjust_btf_func(struct bpf_verifier_env *env)\n \t\taux-\u003efunc_info[i].insn_off = env-\u003esubprog_info[i].start;\n }\n \n-/* Find id in idset and increment its count, or add new entry */\n-static void idset_cnt_inc(struct bpf_idset *idset, u32 id)\n-{\n-\tu32 i;\n-\n-\tfor (i = 0; i \u003c idset-\u003enum_ids; i++) {\n-\t\tif (idset-\u003eentries[i].id == id) {\n-\t\t\tidset-\u003eentries[i].cnt++;\n-\t\t\treturn;\n-\t\t}\n-\t}\n-\t/* New id */\n-\tif (idset-\u003enum_ids \u003c BPF_ID_MAP_SIZE) {\n-\t\tidset-\u003eentries[idset-\u003enum_ids].id = id;\n-\t\tidset-\u003eentries[idset-\u003enum_ids].cnt = 1;\n-\t\tidset-\u003enum_ids++;\n-\t}\n-}\n-\n-/* Find id in idset and return its count, or 0 if not found */\n-static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)\n-{\n-\tu32 i;\n-\n-\tfor (i = 0; i \u003c idset-\u003enum_ids; i++) {\n-\t\tif (idset-\u003eentries[i].id == id)\n-\t\t\treturn idset-\u003eentries[i].cnt;\n-\t}\n-\treturn 0;\n-}\n-\n-/*\n- * Clear singular scalar ids in a state.\n- * A register with a non-zero id is called singular if no other register shares\n- * the same base id. Such registers can be treated as independent (id=0).\n- */\n-void bpf_clear_singular_ids(struct bpf_verifier_env *env,\n-\t\t\t struct bpf_verifier_state *st)\n-{\n-\tstruct bpf_idset *idset = \u0026env-\u003eidset_scratch;\n-\tstruct bpf_func_state *func;\n-\tstruct bpf_reg_state *reg;\n-\n-\tidset-\u003enum_ids = 0;\n-\n-\tbpf_for_each_reg_in_vstate(st, func, reg, ({\n-\t\tif (reg-\u003etype != SCALAR_VALUE)\n-\t\t\tcontinue;\n-\t\tif (!reg-\u003eid)\n-\t\t\tcontinue;\n-\t\tidset_cnt_inc(idset, reg-\u003eid \u0026 ~BPF_ADD_CONST);\n-\t}));\n-\n-\tbpf_for_each_reg_in_vstate(st, func, reg, ({\n-\t\tif (reg-\u003etype != SCALAR_VALUE)\n-\t\t\tcontinue;\n-\t\tif (!reg-\u003eid)\n-\t\t\tcontinue;\n-\t\tif (idset_cnt_get(idset, reg-\u003eid \u0026 ~BPF_ADD_CONST) == 1)\n-\t\t\tclear_scalar_id(reg);\n-\t}));\n-}\n-\n /* Return true if it's OK to have the same insn return a different type. */\n static bool reg_type_mismatch_ok(enum bpf_reg_type type)\n {\ndiff --git a/tools/testing/selftests/bpf/prog_tests/reg_bounds.c b/tools/testing/selftests/bpf/prog_tests/reg_bounds.c\nindex 09f7930733beb0..c2079eb642019e 100644\n--- a/tools/testing/selftests/bpf/prog_tests/reg_bounds.c\n+++ b/tools/testing/selftests/bpf/prog_tests/reg_bounds.c\n@@ -1290,7 +1290,8 @@ static int parse_range_cmp_log(const char *log_buf, struct case_spec spec,\n \t\t * 18: (bf) r0 = r6 ; R0=... R6=...\n \t\t * Different verifier passes may print\n \t\t * 18: (bf) r0 = r6\n-\t\t * as well, but never followed by ';'.\n+\t\t * as well, but never followed by ';'. Except for scalar evolution:\n+\t\t * t 18: (bf) r0 = r6 ; r0 ... -\u003e ...\n \t\t * The branches are in the log in the order the verifier looked at them.\n \t\t */\n \t\tq = log_buf;\n@@ -1299,7 +1300,7 @@ static int parse_range_cmp_log(const char *log_buf, struct case_spec spec,\n \n \t\t\twhile (*s == ' ' || *s == '\\t')\n \t\t\t\ts++;\n-\t\t\tif (*s == ';')\n+\t\t\tif (*s == ';' \u0026\u0026 (q == log_buf || q[-1] == '\\n'))\n \t\t\t\tbreak;\n \t\t\tq = s;\n \t\t}\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_arena.c b/tools/testing/selftests/bpf/progs/verifier_arena.c\nindex cadb13f023d2a3..3931a1d9b6dacf 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_arena.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_arena.c\n@@ -597,6 +597,76 @@ __naked void mixed_arena_scalar_alu64_arena_first(void)\n \t: __clobber_all);\n }\n \n+/* The offset of a pointer to arena is not tracked */\n+#define ARENA_TEST(name, op, expect)\t\t\t\t\t\t\\\n+SEC(\"syscall\")\t\t\t\t\t\t\t\t\t\\\n+__log_level(2)\t\t\t\t\t\t\t\t\t\\\n+expect\t\t\t\t\t\t\t\t\t\t\\\n+__naked void name(void)\t\t\t\t\t\t\t\t\\\n+{\t\t\t\t\t\t\t\t\t\t\\\n+\tasm volatile (\t\t\t\t\t\t\t\t\\\n+\t\"r1 = %[arena] ll;\"\t\t\t\t\t\t\t\\\n+\t\"r6 = 0;\"\t\t\t\t\t\t\t\t\\\n+\t\"r6 = addr_space_cast(r6, 0, 1);\"\t\t\t\t\t\\\n+\t\"r7 = 0;\"\t\t\t\t\t\t\t\t\\\n+\"1:\t*(u64 *)(r6 + 0) = r7;\"\t\t\t\t\t\t\t\\\n+\top\t\t\t\t\t\t\t\t\t\\\n+\t\"r7 += 1;\"\t\t\t\t\t\t\t\t\\\n+\t\"if r7 \u003c 100 goto 1b;\"\t\t\t\t\t\t\t\\\n+\t\"r0 = 0;\"\t\t\t\t\t\t\t\t\\\n+\t\"exit;\"\t\t\t\t\t\t\t\t\t\\\n+\t:: __imm_addr(arena) : __clobber_all);\t\t\t\t\t\\\n+}\n+\n+#define NOT_UNROLLED100\t__msg(\"loop header at 5, widening r7 to 0..99 step 1\")\n+/* A loop that moves the pointer is not unrolled */\n+ARENA_TEST(arena_pointer_moves, \"r6 += 8;\", __success NOT_UNROLLED100)\n+/* The loop makes a number of it: the state that returns to the loop header tells */\n+ARENA_TEST(arena_pointer_becomes_a_number, \"if r7 != 5 goto +1; r6 = 4096;\",\n+\t __failure NOT_UNROLLED100 __msg(\"R6 invalid mem access 'scalar'\"))\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_ARRAY);\n+\t__uint(max_entries, 1);\n+\t__type(key, __u32);\n+\t__type(value, char[64]);\n+} map64 SEC(\".maps\");\n+\n+/*\n+ * r6: 64 bytes. r8: an unbounded scalar. r3, r7: an arena pointer and a copy of it.\n+ * The test leaves an address in r1.\n+ */\n+#define ARENA_LINKED(name, expect, body)\t\t\t\t\t\\\n+SEC(\"syscall\") expect __load_if_JITed()\t\t\t\t\t\t\\\n+__naked void name(void)\t\t\t\t\t\t\t\t\\\n+{\t\t\t\t\t\t\t\t\t\t\\\n+\tasm volatile (\t\t\t\t\t\t\t\t\\\n+\t\"r1 = %[arena] ll; r1 = 0; *(u32 *)(r10 - 4) = r1; r2 = r10; r2 += -4;\"\t\\\n+\t\"r1 = %[map64] ll; call %[bpf_map_lookup_elem]; if r0 == 0 goto out_%=; r6 = r0;\"\t\\\n+\t\"call %[bpf_ktime_get_ns]; r8 = r0; r3 = addr_space_cast(r8, 0, 1); r7 = r3;\"\t\\\n+\tbody\t\t\t\t\t\t\t\t\t\\\n+\t\"r0 = *(u8 *)(r1 + 0);\"\t\t\t\t\t\t\t\\\n+\t\"out_%=: r0 = 0; exit;\"\t\t\t\t\t\t\t\\\n+\t:\t\t\t\t\t\t\t\t\t\\\n+\t: __imm(bpf_map_lookup_elem), __imm(bpf_ktime_get_ns),\t\t\t\\\n+\t __imm_addr(map64), __imm_addr(arena)\t\t\t\t\t\\\n+\t: __clobber_all);\t\t\t\t\t\t\t\\\n+}\n+\n+ARENA_LINKED(scalar_plus_two_constants, __success __retval(0),\n+\t\"r2 = r8; r2 += 1; r2 += 1; if r8 \u003e 61 goto out_%=; r1 = r6; r1 += r2;\")\n+/* 'r3 += 1' is converted to 'w3 += 1': r3 is 0 and not 1 \u003c\u003c 32 */\n+ARENA_LINKED(arena_ptr_plus_constant, __failure,\n+\t\"r3 += 1; r3 = le64 r3; r7 = le64 r7; r2 = 0xffffffff ll; if r7 != r2 goto out_%=;\"\n+\t\"r3 \u003e\u003e= 32; r3 -= 1; r1 = r6; r1 += r3;\")\n+/* At the join point r3 is phi((+ x 1)). The insn there, an add to a scalar, does not define it. */\n+ARENA_LINKED(arena_ptr_plus_constant_on_two_paths, __failure,\n+\t\"if r8 == 0 goto 1f; r3 += 1; goto 2f; 1: r3 += 1; 2: r8 += 1; r3 = le64 r3; r7 = le64 r7;\"\n+\t\"r2 = 0xffffffff ll; if r7 != r2 goto out_%=; r3 \u003e\u003e= 32; r3 -= 1; r1 = r6; r1 += r3;\")\n+/* 'r1 += r2' was verified without a pointer to arena: it stays ALU64 */\n+ARENA_LINKED(index_tested_after_the_add, __success __retval(0),\n+\t\"r2 = r8; r2 \u0026= 255; r1 = r6; r1 += r2; if r2 \u003e 63 goto out_%=; r0 = *(u8 *)(r6 + 0);\")\n+\n SEC(\"syscall\")\n __description(\"arena: a number is not an address in arena\")\n __failure __msg(\"R6 invalid mem access 'scalar'\")\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_array_access.c b/tools/testing/selftests/bpf/progs/verifier_array_access.c\nindex 7f98822889cad5..29bed1e496af60 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_array_access.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_array_access.c\n@@ -762,7 +762,7 @@ l0_%=:\t*(u32*)(r10 - 8) = r6;\t\t\t\t\\\n \t: __clobber_all);\n }\n \n-/* The slot has the id of r6, so the compare sets the range of the slot too */\n+/* The slot holds the low 32 bits of r6, so the compare refines the slot too */\n SEC(\"socket\")\n __description(\"valid map access into an array using a key that is compared after the spill\")\n __success __retval(0)\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_bounds.c b/tools/testing/selftests/bpf/progs/verifier_bounds.c\nindex f55d58af8004a4..b78e7fc96fa704 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_bounds.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_bounds.c\n@@ -1476,7 +1476,7 @@ __naked void sub64_full_overflow(void)\n SEC(\"socket\")\n __description(\"64-bit subtraction, partial overflow, result in unbounded reg\")\n __success __log_level(2)\n-__msg(\"3: (1f) r3 -= r2 {{.*}} R3=scalar(id=1-1)\")\n+__msg(\"3: (1f) r3 -= r2 {{.*}} R3=scalar()\")\n __retval(0)\n __naked void sub64_partial_overflow(void)\n {\n@@ -1572,7 +1572,7 @@ l0_%=:\tr0 = 0;\t\t\t\t\\\n SEC(\"socket\")\n __description(\"bounds deduction cross sign boundary, negative overlap\")\n __success __log_level(2)\n-__msg(\"7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-655,smax=smax32=-146,umin=0xfffffffffffffd71,umax=0xffffffffffffff6e,umin32=0xfffffd71,umax32=0xffffff6e,var_off=(0xfffffffffffffc00; 0x3ff))\")\n+__msg(\"7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-527,smax=smax32=-146,umin=0xfffffffffffffdf1,umax=0xffffffffffffff6e,umin32=0xfffffdf1,umax32=0xffffff6e,var_off=(0xfffffffffffffc00; 0x3ff))\")\n __retval(0)\n __naked void bounds_deduct_negative_overlap(void)\n {\n@@ -1995,6 +1995,39 @@ __naked void bounds_refinement_multiple_overlaps(void *ctx)\n \t: __clobber_all);\n }\n \n+/*\n+ * r0 is x \u003c\u003c 32, the low three bits of x are 5. No such x is in [-2, 1], -3 is in [-3, 1].\n+ * umin and umax are unbounded for a range that crosses 0.\n+ */\n+#define RANGE_CROSSES_0(name, smin)\t\t\\\n+__naked void name(void *ctx)\t\t\t\\\n+{\t\t\t\t\t\t\\\n+\tasm volatile(\t\t\t\t\\\n+\t\"call %[bpf_ktime_get_ns];\"\t\t\\\n+\t\"r0 \u003c\u003c= 35;\"\t\t\t\t\\\n+\t\"r1 = 0x500000000 ll;\"\t\t\t\\\n+\t\"r0 += r1;\"\t\t\t\t\\\n+\t\"r1 = \" #smin \" ll;\"\t\t\t\\\n+\t\"if r0 s\u003c r1 goto 1f;\"\t\t\t\\\n+\t\"r1 = 0x100000000 ll;\"\t\t\t\\\n+\t\"if r0 s\u003e r1 goto 1f;\"\t\t\t\\\n+\t\"r10 = 0;\"\t\t\t\t\\\n+\"1:\texit;\"\t\t\t\t\t\\\n+\t:\t\t\t\t\t\\\n+\t: __imm(bpf_ktime_get_ns)\t\t\\\n+\t: __clobber_all);\t\t\t\\\n+}\n+\n+SEC(\"socket\")\n+__description(\"dead branch: tnum and a range that crosses 0 don't overlap\")\n+__success\n+RANGE_CROSSES_0(range_crossing_0_no_tnum_overlap, -0x200000000)\n+\n+SEC(\"socket\")\n+__description(\"tnum overlaps the negative part of a range that crosses 0\")\n+__failure __msg(\"frame pointer is read only\")\n+RANGE_CROSSES_0(range_crossing_0_tnum_overlap_below_0, -0x300000000)\n+\n SEC(\"socket\")\n __success\n __naked void signed_unsigned_intersection32_case1(void *ctx)\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c\nindex 51b703058cf70b..b42717a825c69e 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c\n@@ -299,7 +299,7 @@ SEC(\"socket\")\n __success __log_level(2)\n __msg(\"r0 += 8 {{.*}}smin=umin=smin32=umin32=8,smax=umax=smax32=umax32=176,{{.*}}step=8+24)\")\n __msg(\"from 4 to 6: R0=scalar(smin=umin=smin32=umin32=32,smax=umax=smax32=umax32=176,{{.*}}step=8+24)\")\n-__msg(\"r1 = r0 {{.*}}R1=scalar(id={{[0-9]+}},smin=umin=smin32=umin32=104,smax=umax=smax32=umax32=176,{{.*}}step=8+24)\")\n+__msg(\"r1 = r0 {{.*}}R1=scalar(smin=umin=smin32=umin32=104,smax=umax=smax32=umax32=176,{{.*}}step=8+24)\")\n __msg(\"r1 += 24 {{.*}}R1=scalar({{.*}}smin=umin=smin32=umin32=128,smax=umax=smax32=umax32=200,{{.*}}step=8+24)\")\n __naked void step_bounds_resync_after_arith(void)\n {\n@@ -336,10 +336,10 @@ l_out_%=:\t\t\t\t\t\t\\\n */\n SEC(\"socket\")\n __success __log_level(2)\n-__msg(\"r1 = (s16)r0 {{.*}}R1=scalar(id={{[0-9]+}},smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)\")\n+__msg(\"r1 = (s16)r0 {{.*}}R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)\")\n __msg(\"r2 = (s16)r0 {{.*}}R2=scalar(smin=smin32=-24,smax=smax32=144,{{.*}}step=0+24)\")\n __msg(\"r3 = (s8)r0 {{.*}}R3=scalar(smin=smin32=-128,smax=smax32=127)\")\n-__msg(\"w4 = (s16)w1 {{.*}}R4=scalar(id={{[0-9]+}},smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)\")\n+__msg(\"w4 = (s16)w1 {{.*}}R4=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)\")\n __msg(\"w5 = (s8)w1 {{.*}}R5=scalar({{.*}}smin32=-128,smax32=127,var_off=(0x0; 0xffffffff))\")\n __naked void step_movsx_bounds_on_line(void)\n {\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c b/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c\nindex 6c1d2014b95b1b..212c08a27058e9 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c\n@@ -569,7 +569,7 @@ l0_%=:\tr0 = 0;\t\t\t\t\t\t\\\n \n SEC(\"tc\")\n __description(\"direct packet access: test23 (x += pkt_ptr, 4)\")\n-__failure __msg(\"invalid access to packet, off=31 size=8, R5(id=3,off=31,r=0)\")\n+__failure __msg(\"invalid access to packet, off=31 size=8, R5(id=1,off=31,r=0)\")\n __flag(BPF_F_ANY_ALIGNMENT)\n __naked void test23_x_pkt_ptr_4(void)\n {\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c\nindex caae67feaf5b70..c8b3690dd810a4 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c\n@@ -190,10 +190,9 @@ l0_%=:\t\t\t\t\t\t\t\\\n \t: __clobber_all);\n }\n \n-/* Double ADD clears the ID (can't accumulate offsets) */\n+/* Double ADD clears the ID. That r1 = r0 + 4 is known all the same: r0 /= 0 is dead code */\n SEC(\"socket\")\n-__failure\n-__msg(\"div by zero\")\n+__success\n __naked void scalars_double_add(void)\n {\n \tasm volatile (\"\t\t\t\t\t\\\n@@ -677,6 +676,7 @@ l_false_%=:\t\t\t\t\t\t\t\\\n \tr2 = r0;\t\t\t\t\t\t\\\n \tr2 \u0026= 0xff;\t\t/* R2 = scalar(id=A) [0,255] */\t\\\n \tr4 = r0;\t\t\t\t\t\t\\\n+\tr4 \u003e\u003e= 8;\t\t\t\t\t\t\\\n \tr4 \u0026= 0xff;\t\t/* R4 = scalar [0,255], id=0 */\t\\\n \tr3 = r2;\t\t/* R3 linked to R2 (id=A) */\t\\\n \tr3 += 10;\t\t/* R3 id=A|ADD_CONST, delta=10 */\\\n@@ -689,6 +689,7 @@ l_true_%=:\t\t\t\t\t\t\t\\\n \tr2 = r0;\t\t\t\t\t\t\\\n \tr2 \u0026= 0xff;\t\t/* R2 = scalar [0,255], id=0 */\t\\\n \tr4 = r0;\t\t\t\t\t\t\\\n+\tr4 \u003e\u003e= 8;\t\t\t\t\t\t\\\n \tr4 \u0026= 0xff;\t\t/* R4 = scalar [0,255], id=0 */\t\\\n \tr3 = r4;\t\t/* R3 linked to R4 (new id=C) */\\\n \tr3 += 10;\t\t/* R3 id=C|ADD_CONST, delta=10 */\\\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_live_stack.c b/tools/testing/selftests/bpf/progs/verifier_live_stack.c\nindex 32bab3cb3fcb9a..d6a6420d219d5c 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_live_stack.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_live_stack.c\n@@ -3143,6 +3143,66 @@ static __used __naked void imprecise_fill_cross_frame(void)\n \t: __clobber_all);\n }\n \n+/*\n+ * fill_older_frame_3() loads through a pointer to the stack of frame 1 or of frame 2. Both slots\n+ * hold a pointer to fp-8 of frame 0: the store is a may_def of that slot at the call in frame 0.\n+ */\n+SEC(\"socket\")\n+__log_level(2)\n+__success\n+__msg(\"3: (85) call pc+2{{ +}}; may_def: fp0-8..-{{[0-9]+}}\")\n+__naked void imprecise_parent_fill_loses_older_frame(void)\n+{\n+\tasm volatile (\n+\t\"*(u64 *)(r10 - 8) = 0;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\t\"call fill_older_frame_1;\"\n+\t\"r0 = *(u64 *)(r10 - 8);\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked void fill_older_frame_1(void)\n+{\n+\tasm volatile (\n+\t\"*(u64 *)(r10 - 8) = r1;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\t\"call fill_older_frame_2;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked void fill_older_frame_2(void)\n+{\n+\tasm volatile (\n+\t\"r2 = *(u64 *)(r1 + 0);\"\n+\t\"*(u64 *)(r10 - 8) = r2;\"\n+\t\"r2 = r10;\"\n+\t\"r2 += -8;\"\n+\t\"call fill_older_frame_3;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked void fill_older_frame_3(void)\n+{\n+\tasm volatile (\n+\t\"r6 = r1;\"\n+\t\"r7 = r2;\"\n+\t\"call %[bpf_get_prandom_u32];\"\n+\t\"if r0 == 0 goto +1;\"\n+\t\"r6 = r7;\"\n+\t/* ARG_IMPRECISE{mask=BIT(1)|BIT(2)} */\n+\t\"r1 = *(u64 *)(r6 + 0);\"\n+\t\"*(u64 *)(r1 + 0) = 7;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n /* Test that spill_to_stack with multi-offset dst (sz=8) joins instead\n * of overwriting. r1 has offsets [-8, -16]. Both slots hold FP-derived\n * pointers. Writing through r1 should join *val with existing values,\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c\nindex 35bb3e16db3dea..17222e1332fdba 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c\n@@ -271,6 +271,51 @@ LOOP(copy_bad, \"r8 = 0; r9 = r8;\", COPY(2047))\n BAD(\"a copy of the counter, another number at the entry\")\n LOOP(copy_other_const, \"r8 = 2047; r9 = 0; r6 += 2047;\", COPY(2046))\n \n+/* the latch exits one iteration later than for an induction variable that starts from 1 */\n+NO_COUNT(\"a copy of the counter, one more at the entry\")\n+LOOP(copy_ahead, \"r8 = 0; r9 = 1;\", COPY(2047))\n+\n+/* r5 is a copy of the pointer r6 from before the increment: an induction variable too */\n+#define PTR_COPY(off)\t\"*(u8 *)(r5 + \" #off \") = r1; r5 = r6; r8 += 1; if r8 \u003c 2048 goto 1b;\"\n+\n+OK(\"a copy of the pointer\", \"2048\") __msg(\"widening r5 to 0..2047 step 1\")\n+LOOP(copy_of_pointer, \"r5 = r6; r8 = 0;\", PTR_COPY(0))\n+\n+BAD(\"a copy of the pointer, one too many\")\n+LOOP(copy_of_pointer_bad, \"r5 = r6; r8 = 0;\", PTR_COPY(1))\n+\n+/* r8 and r9 are computed in the same way from r7: equal by value number, 'r9 = r8' is not needed */\n+OK(\"a copy of the counter, equal by value number\", \"[0..2]\")\n+LOOP(copy_same_value_number,\n+ \"r5 = r6; r8 = r7; r8 \u0026= 1; r8 += 2045; r9 = r7; r9 \u0026= 1; r9 += 2045;\", COPY(2045) AT_R8)\n+\n+/*\n+ * 'for (i = n; i \u003e 0; i--) buf[i - 1] = 0;': r9 is i from before the decrement, the latch tests r8.\n+ * r9 gets the range that the latch implies for r8.\n+ */\n+#define DOWN(off)\t\t\t\t\t\t\t\t\\\n+\t\"r8 += -1; r2 = r5; r2 += r9; *(u8 *)(r2 \" off \") = r1; r9 = r8; if r8 \u003e 0 goto 1b;\"\n+#define FROM_RANGE\t\"if r7 \u003e 2048 goto 9f; if r7 == 0 goto 9f; r5 = r6; r8 = r7; r9 = r7;\"\n+\n+OK(\"a copy of the counter, down from a range\", \"[0..2048]\")\n+LOOP(copy_down_from_range, FROM_RANGE, DOWN(\"- 1\"))\n+\n+BAD(\"a copy of the counter, down from a range, one too many\")\n+LOOP(copy_down_from_range_bad, FROM_RANGE, DOWN(\"+ 0\"))\n+\n+/*\n+ * r9 is zero extended. [1, 2048], its range at the header, is the range of the zero extension too.\n+ * [-1000, 1001] is not: the first store is 4G behind the value.\n+ */\n+OK(\"a copy of the counter, zero extended\", \"[0..2048]\")\n+LOOP(copy_zext, FROM_RANGE, \"w9 = w9;\" DOWN(\"- 1\"))\n+\n+SEC(\"socket\") __description(\"latch: a copy of the counter, zero extended, from below 0\")\n+__failure __msg(\"R4 unbounded memory access\")\n+LOOP(copy_zext_bad, \"r5 = r6; r8 = r7; r8 \u0026= 255; r8 += -1000; r9 = r8;\",\n+ \"w9 = w9; if r8 s\u003e 1000 goto 9f; r4 = r5; r4 += r9; *(u8 *)(r4 + 1000) = r1;\"\n+ \"r8 += 1; r9 = r8; if r7 != 0 goto 1b;\")\n+\n OK(\"a copy of the counter, a range\", \"[0..2]\")\n LOOP(copy_range, \"r5 = r6; r8 = r7; r8 \u0026= 1; r8 += 2045; r9 = r8;\", COPY(2045) AT_R8)\n \n@@ -297,13 +342,13 @@ LOOP(copy_bounds_both, \"r5 = r6; if r7 \u003e 2047 goto 9f; r8 = r7; r9 = r8;\",\n \t\"r4 = r5; r4 += r9; *(u8 *)(r4 \" off \") = r1; 2: r9 = r8; if r7 != 0 goto 1b;\"\n \n OK(\"a copy of the counter, one less behind the jump\", \"[0..2048]\")\n-LOOP(copy_less, \"r5 = r6; r8 = 0; r9 = r8;\", NOT_EQUAL(1, \"\u003e 2046\", \"\u003c 2\", \"- 1\"))\n+LOOP(copy_less, \"r5 = r6; r8 = 0; r9 = r8;\", NOT_EQUAL(1, \"\u003e 2046\", \"\u003c 2\", \"+ 0\"))\n \n BAD(\"a copy of the counter, one less behind the jump, not equal\")\n LOOP(copy_less_bad, \"r5 = r6; r8 = 0; r9 = r8;\", NOT_EQUAL(1, \"\u003e 2046\", \"\u003c 2\", \"- 2\"))\n \n OK(\"a copy of the counter, one more behind the jump\", \"[0..2047]\")\n-LOOP(copy_more, \"r5 = r6; r8 = 2047; r9 = r8;\", NOT_EQUAL(-1, \"s\u003c 2\", \"\u003e 2045\", \"+ 1\"))\n+LOOP(copy_more, \"r5 = r6; r8 = 2047; r9 = r8;\", NOT_EQUAL(-1, \"s\u003c 2\", \"\u003e 2045\", \"+ 0\"))\n \n BAD(\"a copy of the counter, one more behind the jump, not equal\")\n LOOP(copy_more_bad, \"r5 = r6; r8 = 2047; r9 = r8;\", NOT_EQUAL(-1, \"s\u003c 2\", \"\u003e 2045\", \"+ 2\"))\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_movsx.c b/tools/testing/selftests/bpf/progs/verifier_movsx.c\nindex 2f4a678c31c202..6f90dac78fcd10 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_movsx.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_movsx.c\n@@ -202,6 +202,192 @@ l0_%=:\t\t\t\t\t\t\t\\\n \t: __clobber_all);\n }\n \n+/*\n+ * A 32-bit range that already fits the signed N-bit range is unchanged by the sign\n+ * extension. Both of these straddle zero. The guard that follows can only be\n+ * resolved statically if the range survives, and it protects a div by zero.\n+ */\n+SEC(\"socket\")\n+__description(\"MOV32SX, S8, negative range is preserved\")\n+__success __success_unpriv __retval(0)\n+__naked void mov32sx_s8_negative_range(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tw0 \u0026= 0x3f;\t\t\t\t\t\\\n+\tw0 -= 0x3f;\t\t\t\t\t\\\n+\t/* w0 is [-63, 0], already a valid s8 */\t\\\n+\tw0 = (s8)w0;\t\t\t\t\t\\\n+\tif w0 s\u003c -0x3f goto l0_%=;\t\t\t\\\n+\tw0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+l0_%=:\t\t\t\t\t\t\t\\\n+\t/* dead unless the range was widened */\t\t\\\n+\tw0 /= 0;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"socket\")\n+__description(\"MOV32SX, S16, negative range is preserved\")\n+__success __success_unpriv __retval(0)\n+__naked void mov32sx_s16_negative_range(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tw0 \u0026= 0xfff;\t\t\t\t\t\\\n+\tw0 -= 0xfff;\t\t\t\t\t\\\n+\t/* w0 is [-4095, 0], already a valid s16 */\t\\\n+\tw0 = (s16)w0;\t\t\t\t\t\\\n+\tif w0 s\u003c -0xfff goto l0_%=;\t\t\t\\\n+\tw0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+l0_%=:\t\t\t\t\t\t\t\\\n+\t/* dead unless the range was widened */\t\t\\\n+\tw0 /= 0;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * A 32-bit sign extension keeps the low 32 bits, so refining the source\n+ * reaches the destination. The source is a call return, which is the shape\n+ * bpf-gcc builds for \"int err = helper(); if (err) ..\".\n+ */\n+SEC(\"socket\")\n+__success __retval(0)\n+__naked void sext_mov_unlinked_src(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\t\\\n+\tr7 = (s32)r0;\t\t/* r0 as the call defines it */\t\\\n+\tif w0 != -1 goto l0_%=;\t/* refines r0, propagates to r7 */ \\\n+\tif r7 == -1 goto l0_%=;\t/* sign-extended, not 0xffffffff */ \\\n+\tr0 /= 0;\t\t\t\t\t\t\\\n+l0_%=:\t\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * The propagation must not run backwards over the upper 32 bits: a sign extension\n+ * knows nothing about the upper bits of its source. r8's low 32 bits do become\n+ * 2, r8 == 2 does not follow.\n+ */\n+SEC(\"socket\")\n+__failure __msg(\"div by zero\")\n+__naked void sext_no_sync_from_subreg_base(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\t\\\n+\tr7 = (s32)r6;\t\t\t\t\t\t\\\n+\tr8 = r6;\t\t\t\t\t\t\\\n+\tr8 += 3;\t\t\t\t\t\t\\\n+\tif r7 != -1 goto 1f;\t/* pins the low 32 bits of r8 only */ \\\n+\tif r8 == 2 goto 1f;\t/* taken only if r8 wrongly refined */\t\\\n+\tr0 /= 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * r2 is (u32)(r6 + 1) and r7 is (s32)(r6 + 1), so w2 == 1 means r7 == 1.\n+ * bpf-gcc builds \"i += 1\" for an int induction variable into exactly this shape.\n+ */\n+SEC(\"socket\")\n+__success __retval(0)\n+__naked void sext_sync_from_zext_sibling(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\t\\\n+\tr6 \u003c\u003c= 32;\t\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\t\\\n+\tr6 |= r0;\t\t/* r6 = full 64-bit unknown */\t\\\n+\tr2 = r6;\t\t\t\t\t\t\\\n+\tw2 += 1;\t\t/* r2 = (u32)(r6 + 1) */\t\\\n+\tr7 = (s32)r2;\t\t/* r7 = (s32)(r6 + 1) */\t\\\n+\tif w2 != 1 goto 1f;\t/* propagates to r7 */\t\t\\\n+\tif r7 == 1 goto 1f;\t\t\t\t\t\\\n+\tr0 /= 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * \"w6 = w6\" leaves r6 in [0, U32_MAX]. A signed compare on its sign extension\n+ * must not hand r6 the sign-extended value: that drops every r6 \u003e= 2^31 from\n+ * the range and makes the guarded div provably dead.\n+ */\n+SEC(\"socket\")\n+__failure __msg(\"div by zero\")\n+__naked void sext_narrow_base_keeps_high_values(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\t\\\n+\tw6 = w6;\t\t/* r6 in [0, U32_MAX] */\t\\\n+\tr7 = (s32)r6;\t\t\t\t\t\t\\\n+\tr8 = 1;\t\t\t\t\t\t\t\\\n+\tr8 \u003c\u003c= 31;\t\t/* 0x80000000 */\t\t\\\n+\tif r7 s\u003e 100 goto 1f;\t/* r6 is [0,100] or \u003e= 2^31 */\t\\\n+\tif r6 \u003c r8 goto 1f;\t/* reachable: r6 may be \u003e= 2^31 */ \\\n+\tr0 /= 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * A base/step line does not survive the sign extension: it subtracts 2^32,\n+ * and 2^32 is not a multiple of 3. r6 = 0x80000007 is a multiple of 3, so\n+ * r7 = -2147483641 is reachable.\n+ */\n+SEC(\"socket\")\n+__failure __msg(\"div by zero\")\n+__naked void sext_drops_stale_step(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\t\\\n+\tw6 = w6;\t\t\t\t\t\t\\\n+\tr6 *= 3;\t\t/* base 0, step 3 */\t\t\\\n+\tr7 = (s32)r6;\t\t\t\t\t\t\\\n+\tr8 = 1;\t\t\t\t\t\t\t\\\n+\tr8 \u003c\u003c= 31;\t\t\t\t\t\t\\\n+\tr9 = r8;\t\t\t\t\t\t\\\n+\tr9 += 7;\t\t\t\t\t\t\\\n+\tif r6 \u003c r8 goto 1f;\t\t\t\t\t\\\n+\tif r6 \u003e r9 goto 1f;\t/* r6 in [0x80000000, 0x80000007] */ \\\n+\tif r7 != -2147483641 goto 1f; /* reachable: r6 == 0x80000007 */ \\\n+\tr0 /= 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n SEC(\"socket\")\n __description(\"MOV64SX, S16, R10 Sign Extension\")\n __failure __msg(\"R1 type=scalar expected=fp, pkt, pkt_meta, map_key, map_value, mem, ringbuf_mem, buf, trusted_ptr_\")\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_reg_equal.c b/tools/testing/selftests/bpf/progs/verifier_reg_equal.c\nindex dc1d8c30fb0eeb..91daa5b323c9f8 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_reg_equal.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_reg_equal.c\n@@ -31,17 +31,16 @@ l1_%=:\texit;\t\t\t\t\t\t\\\n }\n \n SEC(\"socket\")\n-__description(\"check w reg not equal if r reg upper32 bits not 0\")\n-__failure __msg(\"R1 !read_ok\")\n+__description(\"check w reg equal if r reg upper32 bits not 0\")\n+__success\n __naked void subreg_equality_2(void)\n {\n \tasm volatile (\"\t\t\t\t\t\\\n \tcall %[bpf_ktime_get_ns];\t\t\t\\\n \tr2 = r0;\t\t\t\t\t\\\n-\t/* Upper 4-bytes of r2 may not be 0, thus insn\t\\\n-\t * w3 = w2 should not propagate reg id,\tand\t\\\n-\t * w2 \u003c 9 comparison should not propagate\t\\\n-\t * the range for r3 either.\t\t\t\\\n+\t/* Upper 4-bytes of r2 may not be 0. r3 is the\t\\\n+\t * lower 4-bytes of r2, which is what w2 \u003c 9\t\\\n+\t * compares.\t\t\t\t\t\\\n \t */\t\t\t\t\t\t\\\n \tw3 = w2;\t\t\t\t\t\\\n \tif w2 \u003c 9 goto l0_%=;\t\t\t\t\\\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_regalloc.c b/tools/testing/selftests/bpf/progs/verifier_regalloc.c\nindex ee5ddea87c91c0..cf26617b6ba16f 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_regalloc.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_regalloc.c\n@@ -303,7 +303,6 @@ __naked void regalloc_in_callee(void)\n \tr7 = r0;\t\t\t\t\t\\\n \tcall %[bpf_get_prandom_u32];\t\t\t\\\n \tr1 = r0;\t\t\t\t\t\\\n-\tr2 = r0;\t\t\t\t\t\\\n \tr3 = r7;\t\t\t\t\t\\\n \tcall regalloc_in_callee__1;\t\t\t\\\n l0_%=:\texit;\t\t\t\t\t\t\\\n@@ -318,6 +317,7 @@ static __naked __noinline __attribute__((used))\n void regalloc_in_callee__1(void)\n {\n \tasm volatile (\"\t\t\t\t\t\\\n+\tr2 = r1;\t\t\t\t\t\\\n \tif r1 s\u003e 20 goto l0_%=;\t\t\t\t\\\n \tif r2 s\u003c 0 goto l0_%=;\t\t\t\t\\\n \tr3 += r1;\t\t\t\t\t\\\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c b/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c\nindex 9ea61b16273653..56c2412608a5dc 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c\n@@ -11,11 +11,10 @@ struct {\n \t__type(value, long long);\n } map_hash_8b SEC(\".maps\");\n \n-/* scalar in [0, max] that shares id with other registers, as it is in the log */\n-#define LINKED(id, max, mask) \\\n-\t\"scalar(id=\" id \",smin=smin32=0,smax=umax=smax32=umax32=\" #max \",var_off=(0x0; \" #mask \"))\"\n+/* scalar in [0, max], as it is in the log. @id: the registers that hold copies of one value. */\n #define ALONE(max, mask) \\\n \t\"scalar(smin=smin32=0,smax=umax=smax32=umax32=\" #max \",var_off=(0x0; \" #mask \"))\"\n+#define LINKED(id, max, mask) ALONE(max, mask)\n \n /*\n * Registers r{0,1,2} have the same scalar ID.\n@@ -151,7 +150,7 @@ __naked void linked_regs_broken_link(void)\n SEC(\"socket\")\n __success __log_level(2)\n __msg(\"13: (25) if r1 \u003e 0x7 goto pc+0 ; R1=\" ALONE(7, 0x7))\n-__msg(\"10: R0=0 R6=scalar(id={{.*}}umax32=255,{{.*}} R7=scalar(id={{.*}}umax32=255,\")\n+__msg(\"10: R0=0 R6=scalar({{.*}}umax32=255,{{.*}} R7=scalar({{.*}}umax32=255,\")\n __msg(\"5: R0=0 R6=\" ALONE(255, 0xff))\n __naked void precision_many_frames(void)\n {\n@@ -285,13 +284,8 @@ __naked void precision_two_ids(void)\n \n SEC(\"socket\")\n __success __log_level(2)\n-/*\n- * check that r5 is unlinked after 'if', collect_linked_regs() can't tie\n- * more than 5 registers for a single insn and the register compared by\n- * the jump is not exempt from that.\n- */\n-__msg(\"7: (25) if r5 \u003e 0x7 goto pc+0 ; R5=scalar(smin=\")\n-__msg(\"12: (bf) r5 = r5 ; R5=scalar(id=2\")\n+/* there is no limit of 5 registers for a single insn */\n+__msg(\"7: (25) if r5 \u003e 0x7 goto pc+0 ; R0=\" LINKED(\"1\", 7, 0x7) \" R1=\" LINKED(\"1\", 7, 0x7) \" R2=\" LINKED(\"1\", 7, 0x7) \" R3=\" LINKED(\"1\", 7, 0x7) \" R4=\" LINKED(\"1\", 7, 0x7) \" R5=\" LINKED(\"1\", 7, 0x7))\n __naked void linked_regs_too_many_regs(void)\n {\n \tasm volatile (\n@@ -304,14 +298,12 @@ __naked void linked_regs_too_many_regs(void)\n \t\"r3 = r0;\"\n \t\"r4 = r0;\"\n \t\"r5 = r0;\"\n-\t/* r{0-4} fill the record, r5 does not fit and is unlinked */\n \t\"if r5 \u003e 7 goto +0;\"\n-\t/* keep r{1-4} live */\n+\t/* keep r{1-5} live */\n \t\"r1 = r1;\"\n \t\"r2 = r2;\"\n \t\"r3 = r3;\"\n \t\"r4 = r4;\"\n-\t/* make r5 appear in the log */\n \t\"r5 = r5;\"\n \t\"r7 = r10;\"\n \t\"r7 += r0;\"\n@@ -324,7 +316,7 @@ __naked void linked_regs_too_many_regs(void)\n \n SEC(\"socket\")\n __failure __log_level(2)\n-__msg(\"5: (3d) if r8 \u003e= r0 goto pc+3 ; R0=scalar(umin=1) R7=scalar(id=1,umax=0xfffffffffffffffe) R8=scalar(id=1,umax=0xfffffffffffffffe)\")\n+__msg(\"5: (3d) if r8 \u003e= r0 goto pc+3 ; R0=scalar(umin=1) R7=scalar(umax=0xfffffffffffffffe) R8=scalar(umax=0xfffffffffffffffe)\")\n __msg(\"div by zero\")\n __naked void linked_regs_broken_link_2(void)\n {\n@@ -687,52 +679,6 @@ __naked void two_nil_old_ids_one_cur_id(void)\n \t: __clobber_all);\n }\n \n-/*\n- * Check that two different scalar IDs in the state that is there can't be\n- * mapped to the same scalar ID in the state that arrives.\n- */\n-SEC(\"socket\")\n-__success __log_level(2)\n-__not_msg(\"from 10 to 11: within\")\n-__msg(\"11: R0=0 R6=\" ALONE(255, 0xff) \" R7=\" ALONE(255, 0xff))\n-__naked void two_old_ids_one_cur_id(void)\n-{\n-\tasm volatile (\n-\t/* Give unique scalar IDs to r{6,7} */\n-\t\"call %[bpf_ktime_get_ns];\"\n-\t\"r0 \u0026= 0xff;\"\n-\t\"r6 = r0;\"\n-\t\"r8 = r0;\"\n-\t\"call %[bpf_ktime_get_ns];\"\n-\t\"r0 \u0026= 0xff;\"\n-\t\"r7 = r0;\"\n-\t\"r9 = r0;\"\n-\t\"r0 = 0;\"\n-\t/* Maybe make r{6,7} IDs identical */\n-\t\"if r6 \u003c= r7 goto l1_%=;\"\n-\t\"r6 = r7;\"\n-\"l1_%=:\"\n-\t/*\n-\t * Get here in two states:\n-\t * - first: r6{.id=A}, r7{.id=B}\n-\t * - second: r6{.id=B}, r7{.id=B}\n-\t * Currently we don't want to consider the second one to be within\n-\t * the first one. Thus they are joined.\n-\t */\n-\t\"r2 = r10;\"\n-\t\"r2 += r6;\"\n-\t\"r2 += r7;\"\n-\t/*\n-\t * keep r8 and r9 live, otherwise r6-\u003eid and r7-\u003eid\n-\t * will become singular and reset to zero before if r6 \u003c= r7\n-\t */\n-\t\"r9 += r8;\"\n-\t\"exit;\"\n-\t:\n-\t: __imm(bpf_ktime_get_ns)\n-\t: __clobber_all);\n-}\n-\n SEC(\"socket\")\n /* Note the flag, see verifier.c:opt_subreg_zext_lo32_rnd_hi32() */\n __flag(BPF_F_TEST_RND_HI32)\n@@ -808,7 +754,7 @@ __naked void linked_regs_and_subreg_def(void)\n * at runtime), which must be rejected.\n */\n SEC(\"socket\")\n-__failure __msg(\"R0 max value is outside of the allowed memory range\")\n+__failure __msg(\"invalid access to map value, value_size=8 off=8 size=1\")\n __naked void ldsx_fill_scalar_id_not_shared(void)\n {\n \tasm volatile (\"\t\t\t\t\t\\\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_scev.c b/tools/testing/selftests/bpf/progs/verifier_scev.c\nindex 5c9c832fbbe07e..a79c00a99c8939 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_scev.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_scev.c\n@@ -135,7 +135,7 @@ exit_%=:\t\t\t\t\t\t\\\n SEC(\"xdp\")\n __success\n __log_level(2)\n-__msg(\"8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -\u003e ?\")\n+__msg(\"8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -\u003e %fp-8.8?\")\n __naked void indirect_write_invalidates_scev(void)\n {\n \tasm volatile (\"\t\t\t\t\t\\\n@@ -165,7 +165,7 @@ __noinline int global_noop_counter(__u64 *p)\n SEC(\"xdp\")\n __success\n __log_level(2)\n-__msg(\"8: (85) call pc+{{[0-9]+}} {{.*}}; *fp-8 (+ *fp-8 1) -\u003e ?\")\n+__msg(\"8: (85) call pc+{{[0-9]+}} {{.*}}; *fp-8 (+ *fp-8 1) -\u003e %fp-8.8?\")\n __naked void global_call_invalidates_scev(void)\n {\n \tasm volatile (\n@@ -242,7 +242,7 @@ SEC(\"xdp\")\n __success __retval(0)\n __log_level(2)\n __msg_next(\"scev at header 1:\")\n-__msg_next(\" r6=(any r6 (+ r6 1)) / ?\")\n+__msg_next(\" r6=%r6.1=phi(r6, (+ r6 1)) / ?\")\n __naked void meet_disagrees(void)\n {\n \tasm volatile (\"\t\t\t\t\t\\\n@@ -261,6 +261,37 @@ __naked void meet_disagrees(void)\n \t: __clobber_all);\n }\n \n+/* 'if (c) sum += a; else sum += b;': two loads, one way to compute the sum */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"scev at header 3:\")\n+__msg_next(\" r6=%r6.9=phi((+ r6 _)) / ?\")\n+__naked void phi_operands_have_no_defs(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr9 = r1;\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+\tr7 = 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\\\n+\tif r7 \u0026 1 goto 2f;\t\t\t\t\\\n+\tr2 = *(u32 *)(r9 + %[len]);\t\t\t\\\n+\tr6 += r2;\t\t\t\t\t\\\n+\tgoto 3f;\t\t\t\t\t\\\n+2:\t\t\t\t\t\t\t\\\n+\tr2 = *(u32 *)(r9 + %[mark]);\t\t\t\\\n+\tr6 += r2;\t\t\t\t\t\\\n+3:\t\t\t\t\t\t\t\\\n+\tr7 += 1;\t\t\t\t\t\\\n+\tif r7 \u003c 10 goto 1b;\t\t\t\t\\\n+\tr0 = r6;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm_const(len, offsetof(struct __sk_buff, len)),\n+\t __imm_const(mark, offsetof(struct __sk_buff, mark))\n+\t: __clobber_all);\n+}\n+\n /* Both entry state values for r1 should be accounted for */\n SEC(\"xdp\")\n __success\n@@ -324,30 +355,31 @@ __msg(\"r1 += 2 {{.*}}; r1 r6 -\u003e (+ r6 2)\")\n __msg(\"r1 += r7 {{.*}}; r1 r6 -\u003e (+ r6 r7)\")\n __msg(\"w1 += 2 {{.*}}; r1 r6 -\u003e (zext32 (+ r6 2))\")\n __msg(\"w1 += w7 {{.*}}; r1 r6 -\u003e (zext32 (+ r6 r7))\")\n-__msg(\"r1 -= 2 {{.*}}; r1 r6 -\u003e (- r6 2)\")\n+__msg(\"r1 -= 2 {{.*}}; r1 r6 -\u003e (+ r6 -2)\")\n __msg(\"r1 -= r7 {{.*}}; r1 r6 -\u003e (- r6 r7)\")\n-__msg(\"w1 -= 2 {{.*}}; r1 r6 -\u003e (zext32 (- r6 2))\")\n+__msg(\"w1 -= 2 {{.*}}; r1 r6 -\u003e (zext32 (+ r6 -2))\")\n __msg(\"w1 -= w7 {{.*}}; r1 r6 -\u003e (zext32 (- r6 r7))\")\n+__msg(\"r1 -= 2 {{.*}}; r1 (+ r6 2) -\u003e r6\")\n __msg(\"r1 *= 2 {{.*}}; r1 r6 -\u003e (* r6 2)\")\n __msg(\"r1 *= r7 {{.*}}; r1 r6 -\u003e (* r6 r7)\")\n __msg(\"w1 *= 2 {{.*}}; r1 r6 -\u003e (zext32 (* r6 2))\")\n __msg(\"w1 *= w7 {{.*}}; r1 r6 -\u003e (zext32 (* r6 r7))\")\n __msg(\"r1 /= 2 {{.*}}; r1 r6 -\u003e (/ r6 2)\")\n __msg(\"r1 /= r7 {{.*}}; r1 r6 -\u003e (/ r6 r7)\")\n-__msg(\"w1 /= 2 {{.*}}; r1 r6 -\u003e (zext32 (/ r6 2))\")\n-__msg(\"w1 /= w7 {{.*}}; r1 r6 -\u003e (zext32 (/ r6 r7))\")\n+__msg(\"w1 /= 2 {{.*}}; r1 r6 -\u003e (zext32 (/ (zext32 r6) 2))\")\n+__msg(\"w1 /= w7 {{.*}}; r1 r6 -\u003e (zext32 (/ (zext32 r6) (zext32 r7)))\")\n __msg(\"r1 s/= 2 {{.*}}; r1 r6 -\u003e (s/ r6 2)\")\n __msg(\"r1 s/= r7 {{.*}}; r1 r6 -\u003e (s/ r6 r7)\")\n-__msg(\"w1 s/= 2 {{.*}}; r1 r6 -\u003e (zext32 (s/ r6 2))\")\n-__msg(\"w1 s/= w7 {{.*}}; r1 r6 -\u003e (zext32 (s/ r6 r7))\")\n+__msg(\"w1 s/= 2 {{.*}}; r1 r6 -\u003e (zext32 (s/ (sext32 r6) 2))\")\n+__msg(\"w1 s/= w7 {{.*}}; r1 r6 -\u003e (zext32 (s/ (sext32 r6) (sext32 r7)))\")\n __msg(\"r1 %= 2 {{.*}}; r1 r6 -\u003e (% r6 2)\")\n __msg(\"r1 %= r7 {{.*}}; r1 r6 -\u003e (% r6 r7)\")\n-__msg(\"w1 %= 2 {{.*}}; r1 r6 -\u003e (zext32 (% r6 2))\")\n-__msg(\"w1 %= w7 {{.*}}; r1 r6 -\u003e (zext32 (% r6 r7))\")\n+__msg(\"w1 %= 2 {{.*}}; r1 r6 -\u003e (zext32 (% (zext32 r6) 2))\")\n+__msg(\"w1 %= w7 {{.*}}; r1 r6 -\u003e (zext32 (% (zext32 r6) (zext32 r7)))\")\n __msg(\"r1 s%= 2 {{.*}}; r1 r6 -\u003e (s% r6 2)\")\n __msg(\"r1 s%= r7 {{.*}}; r1 r6 -\u003e (s% r6 r7)\")\n-__msg(\"w1 s%= 2 {{.*}}; r1 r6 -\u003e (zext32 (s% r6 2))\")\n-__msg(\"w1 s%= w7 {{.*}}; r1 r6 -\u003e (zext32 (s% r6 r7))\")\n+__msg(\"w1 s%= 2 {{.*}}; r1 r6 -\u003e (zext32 (s% (sext32 r6) 2))\")\n+__msg(\"w1 s%= w7 {{.*}}; r1 r6 -\u003e (zext32 (s% (sext32 r6) (sext32 r7)))\")\n __msg(\"r1 |= 2 {{.*}}; r1 r6 -\u003e (| r6 2)\")\n __msg(\"r1 |= r7 {{.*}}; r1 r6 -\u003e (| r6 r7)\")\n __msg(\"w1 |= 2 {{.*}}; r1 r6 -\u003e (zext32 (| r6 2))\")\n@@ -363,19 +395,19 @@ __msg(\"w1 ^= w7 {{.*}}; r1 r6 -\u003e (zext32 (^ r6 r7))\")\n __msg(\"r1 \u003c\u003c= 2 {{.*}}; r1 r6 -\u003e (\u003c\u003c r6 2)\")\n __msg(\"r1 \u003c\u003c= r7 {{.*}}; r1 r6 -\u003e (\u003c\u003c r6 r7)\")\n __msg(\"w1 \u003c\u003c= 2 {{.*}}; r1 r6 -\u003e (zext32 (\u003c\u003c r6 2))\")\n-__msg(\"w1 \u003c\u003c= w7 {{.*}}; r1 r6 -\u003e (zext32 (\u003c\u003c r6 r7))\")\n+__msg(\"w1 \u003c\u003c= w7 {{.*}}; r1 r6 -\u003e (zext32 (\u003c\u003c r6 (\u0026 r7 31)))\")\n __msg(\"r1 \u003e\u003e= 2 {{.*}}; r1 r6 -\u003e (\u003e\u003e r6 2)\")\n __msg(\"r1 \u003e\u003e= r7 {{.*}}; r1 r6 -\u003e (\u003e\u003e r6 r7)\")\n-__msg(\"w1 \u003e\u003e= 2 {{.*}}; r1 r6 -\u003e (zext32 (\u003e\u003e r6 2))\")\n-__msg(\"w1 \u003e\u003e= w7 {{.*}}; r1 r6 -\u003e (zext32 (\u003e\u003e r6 r7))\")\n+__msg(\"w1 \u003e\u003e= 2 {{.*}}; r1 r6 -\u003e (zext32 (\u003e\u003e (zext32 r6) 2))\")\n+__msg(\"w1 \u003e\u003e= w7 {{.*}}; r1 r6 -\u003e (zext32 (\u003e\u003e (zext32 r6) (\u0026 r7 31)))\")\n __msg(\"r1 s\u003e\u003e= 2 {{.*}}; r1 r6 -\u003e (s\u003e\u003e r6 2)\")\n __msg(\"r1 s\u003e\u003e= r7 {{.*}}; r1 r6 -\u003e (s\u003e\u003e r6 r7)\")\n-__msg(\"w1 s\u003e\u003e= 2 {{.*}}; r1 r6 -\u003e (zext32 (s\u003e\u003e r6 2))\")\n-__msg(\"w1 s\u003e\u003e= w7 {{.*}}; r1 r6 -\u003e (zext32 (s\u003e\u003e r6 r7))\")\n+__msg(\"w1 s\u003e\u003e= 2 {{.*}}; r1 r6 -\u003e (zext32 (s\u003e\u003e (sext32 r6) 2))\")\n+__msg(\"w1 s\u003e\u003e= w7 {{.*}}; r1 r6 -\u003e (zext32 (s\u003e\u003e (sext32 r6) (\u0026 r7 31)))\")\n __msg(\"r1 = -r1 {{.*}}; r1 r6 -\u003e (- r6)\")\n __msg(\"w1 = -w1 {{.*}}; r1 r6 -\u003e (zext32 (- r6))\")\n __msg(\"r1 = 42 {{.*}}; r1 r6 -\u003e 42\")\n-__msg(\"w1 = 42 {{.*}}; r1 r6 -\u003e (zext32 42)\")\n+__msg(\"w1 = 42 {{.*}}; r1 r6 -\u003e 42\")\n __msg(\"r1 = r7 {{.*}}; r1 r6 -\u003e r7\")\n __msg(\"w1 = w7 {{.*}}; r1 r6 -\u003e (zext32 r7)\")\n __msg(\"r1 = (s8)r6 {{.*}}; r1 r6 -\u003e (sext8 r6)\")\n@@ -417,6 +449,7 @@ __naked void alu_ops_exprs(void)\n \tALU_OP(\"r1 -= r7\")\n \tALU_OP(\"w1 -= 2\")\n \tALU_OP(\"w1 -= w7\")\n+\tALU_OP(\"r1 += 2; r1 -= 2\")\n \tALU_OP(\"r1 *= 2\")\n \tALU_OP(\"r1 *= r7\")\n \tALU_OP(\"w1 *= 2\")\n@@ -511,7 +544,7 @@ __msg(\"*(u16 *)(r10 -8) = r1 {{.*}}; *fp-8 -8 -\u003e (spill16 1)\")\n __msg(\"*(u8 *)(r10 -8) = r1 {{.*}}; *fp-8 -8 -\u003e (spill8 1)\")\n __msg(\"r1 = *(u64 *)(r10 -8) {{.*}}; r1 1 -\u003e -8\")\n #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n-__msg(\"r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -\u003e (zext32 -8)\")\n+__msg(\"r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -\u003e 4294967288\")\n __msg(\"r1 = *(u16 *)(r10 -8) {{.*}}; r1 1 -\u003e (zext16 -8)\")\n __msg(\"r1 = *(u8 *)(r10 -8) {{.*}}; r1 1 -\u003e (zext8 -8)\")\n __msg(\"r1 = *(s32 *)(r10 -8) {{.*}}; r1 1 -\u003e (sext32 -8)\")\n@@ -519,7 +552,7 @@ __msg(\"r1 = *(s16 *)(r10 -8) {{.*}}; r1 1 -\u003e (sext16 -8)\")\n __msg(\"r1 = *(s8 *)(r10 -8) {{.*}}; r1 1 -\u003e (sext8 -8)\")\n __msg(\"r1 = load_acquire((u8 *)(r10 -8)) {{.*}}; r1 1 -\u003e (zext8 -8)\")\n __msg(\"r1 = load_acquire((u16 *)(r10 -8)) {{.*}}; r1 1 -\u003e (zext16 -8)\")\n-__msg(\"r1 = load_acquire((u32 *)(r10 -8)) {{.*}}; r1 1 -\u003e (zext32 -8)\")\n+__msg(\"r1 = load_acquire((u32 *)(r10 -8)) {{.*}}; r1 1 -\u003e 4294967288\")\n #else\n __msg(\"r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -\u003e (\u003e\u003e -8 32)\")\n __msg(\"r1 = *(u16 *)(r10 -8) {{.*}}; r1 1 -\u003e (\u003e\u003e -8 48)\")\n@@ -536,13 +569,18 @@ __msg(\"store_release((u8 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -\u003e (spill8 1)\")\n __msg(\"store_release((u16 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -\u003e (spill16 1)\")\n __msg(\"store_release((u32 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -\u003e (spill32 1)\")\n __msg(\"store_release((u64 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -\u003e 1\")\n-__msg(\"lock *(u64 *)(r10 -8) += r1 {{.*}}; *fp-8 -8 -\u003e _\")\n-__msg(\"r1 = atomic64_fetch_add((u64 *)(r10 -8), r1) {{.*}}; r1 1 -\u003e _, *fp-8 -8 -\u003e _\")\n-__msg(\"r1 = atomic_fetch_add((u32 *)(r10 -8), r1) {{.*}}; r1 1 -\u003e _, *fp-8 -8 -\u003e _\")\n-__msg(\"r1 = atomic64_xchg((u64 *)(r10 -8), r1) {{.*}}; r1 1 -\u003e _, *fp-8 -8 -\u003e _\")\n-__msg(\"r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r2) {{.*}}; r0 0 -\u003e _, *fp-8 -8 -\u003e _\")\n+__msg(\"lock *(u64 *)(r10 -8) += r1 {{.*}}; *fp-8 -8 -\u003e %fp-8.{{[0-9]+}}\")\n+__msg(\"r1 = atomic64_fetch_add((u64 *)(r10 -8), r1) {{.*}}; r1 1 -\u003e %r1.{{[0-9]+}}, *fp-8 -8 -\u003e %fp-8.{{[0-9]+}}\")\n+__msg(\"r1 = atomic_fetch_add((u32 *)(r10 -8), r1) {{.*}}; r1 1 -\u003e %r1.{{[0-9]+}}, *fp-8 -8 -\u003e %fp-8.{{[0-9]+}}\")\n+__msg(\"r1 = atomic64_xchg((u64 *)(r10 -8), r1) {{.*}}; r1 1 -\u003e %r1.{{[0-9]+}}, *fp-8 -8 -\u003e %fp-8.{{[0-9]+}}\")\n+__msg(\"r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r2) {{.*}}; r0 0 -\u003e %r0.{{[0-9]+}}, *fp-8 -8 -\u003e %fp-8.{{[0-9]+}}\")\n __msg(\"*(u64 *)(r10 -8) = 42 {{.*}}; *fp-8 -8 -\u003e 42\")\n-__msg(\"*(u8 *)(r10 -7) = r0 {{.*}}; *fp-8 -8 -\u003e _\")\n+__msg(\"*(u8 *)(r10 -7) = r0 {{.*}}; *fp-8 -8 -\u003e %fp-8.{{[0-9]+}}\")\n+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n+/* a fill that is not wider than the spill reads what was spilled */\n+__msg(\"r1 = *(s8 *)(r10 -8) {{.*}}; r1 r7 -\u003e (sext8 r7)\")\n+__msg(\"r1 = *(u16 *)(r10 -8) {{.*}}; r1 r7 -\u003e (zext16 (spill8 r7))\")\n+#endif\n __naked void store_load_exprs(void)\n {\n \tasm volatile (\n@@ -579,6 +617,9 @@ __naked void store_load_exprs(void)\n \tST_OP(\"*(u64 *)(r10 - 8) = 42\")\n \tST_OP(\"*(u8 *)(r10 - 7) = r0\")\n \n+\tST_OP(\"r1 = r7; *(u16 *)(r10 - 8) = r1; r1 = *(s8 *)(r10 - 8)\")\n+\tST_OP(\"r1 = r7; *(u8 *)(r10 - 8) = r1; r1 = *(u16 *)(r10 - 8)\")\n+\n \t\"r7 += 1;\"\n \t\"if r7 \u003c 2 goto 1b;\"\n \t\"r0 = 0;\"\n@@ -607,10 +648,10 @@ __success\n __log_level(2)\n __msg_next(\"scev at header 1:\")\n __msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n-__msg_next(\" r7=?\")\n+__msg_next(\" r7=%r7.4?\")\n __msg_next(\" scev at latch 1:\")\n __msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n-__msg_next(\" r7=?\")\n+__msg_next(\" r7=%r7.4?\")\n __msg_next(\"scev at header 4:\")\n __msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n __msg_next(\" scev at latch 4:\")\n@@ -647,7 +688,7 @@ __msg_next(\" backedge from 6, latch at 4\")\n __msg_next(\" exit from 4 to 1\")\n __msg(\"scev at header 1:\")\n __msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n-__msg_next(\" r7=?\")\n+__msg_next(\" r7=%r7.4?\")\n __msg_next(\"scev at header 4:\")\n __msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n __msg_next(\" scev at latch 4:\")\n@@ -692,7 +733,7 @@ __msg_next(\" backedge from 5, latch at 5\")\n __msg_next(\" exit from 4 to 2\")\n __msg_next(\" exit from 5 to 6\")\n __msg(\"scev at header 2:\")\n-__msg_next(\" r6=?\")\n+__msg_next(\" r6=%r6.3?\")\n __msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n __msg_next(\"scev at header 3:\")\n __msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n@@ -727,8 +768,8 @@ __log_level(2)\n __flag(BPF_F_TEST_STATE_FREQ)\n __msg(\"loop at 3{{$}}\")\n __msg(\"scev at header 3:\")\n-__msg_next(\" r6=(any r6 (+ r6 1)) / ?\")\n-__msg_next(\" r7=(any (+ r7 1) 0) / ?\")\n+__msg_next(\" r6=%r6.3=phi(r6, (+ r6 1)) / ?\")\n+__msg_next(\" r7=%r7.3=phi((+ r7 1), 0) / ?\")\n __msg_next(\" r8=(+ r8 1) / (linear r8 1)\")\n __msg(\"loop header at 3, can't compute iterations count\")\n __naked void nested_loops_shared_header(void)\n@@ -1159,6 +1200,50 @@ RANGE_TEST(range_ge_dir, \"\", 10, 20, 2, 3, 5, PRE(\"\u003c\"), NO_COUNT)\n RANGE_TEST(range_ne_step2, \"\", 0, 3, 2, 3, 8, PRE(\"==\"), NO_COUNT)\n RANGE_TEST(range_ne_behind, \"\", 0, 4, 1, 3, 8, PRE(\"==\"), NO_COUNT)\n \n+/*\n+ * char buf[8];\n+ * for (int i = first; ...; i++)\n+ * sum += buf[i - first];\n+ *\n+ * GCC adds in 32 bits and keeps the sign extension of the result: a sign-extended 32-bit induction\n+ * variable. r6 or fp-16 is i, r7 is first, r9 counts the iterations. r8 is 0, which the verifier\n+ * doesn't know. In place of an out-of-bounds access to buf r5 is read, which is not initialized.\n+ */\n+#define SEXT32_TEST(name, _first, loop, expect)\t\t\t\t\t\t\t\\\n+SEC(\"socket\")\t\t\t\t\t\t\t\t\t\t\t\\\n+__log_level(2)\t\t\t\t\t\t\t\t\t\t\t\\\n+expect\t\t\t\t\t\t\t\t\t\t\t\t\\\n+__naked void name(void)\t\t\t\t\t\t\t\t\t\t\\\n+{\t\t\t\t\t\t\t\t\t\t\t\t\\\n+\tasm volatile (\t\t\t\t\t\t\t\t\t\t\\\n+\t\t\"r6 = %[first] ll; r7 = r6; r8 = 0; r9 = 0;\"\t\t\t\t\t\\\n+\t\t\"*(u64 *)(r10 - 8) = r8; lock *(u64 *)(r10 - 8) += r8; r8 = *(u64 *)(r10 - 8);\"\t\\\n+\t\t\"*(u64 *)(r10 - 16) = r6;\"\t\t\t\t\t\t\t\\\n+\t\tloop\t\t\t\t\t\t\t\t\t\t\\\n+\t\t\"2: r0 = r9; exit;\"\t\t\t\t\t\t\t\t\\\n+\t\t:\t\t\t\t\t\t\t\t\t\t\\\n+\t\t: __imm_const(first, _first)\t\t\t\t\t\t\t\\\n+\t\t: __clobber_all);\t\t\t\t\t\t\t\t\\\n+}\n+#define BUF(i)\t\t\"r9 += 1; r2 = \" i \"; r2 -= r7; if r2 \u003c= 7 goto +1; r0 = *(u64 *)(r5 + 0);\"\n+#define OOB\t\t__failure __msg(\"R5 !read_ok\")\n+#define ALL_OF_S32\t\"0xffffffff80000000..0x7fffffff \"\n+#define SEXT32_INC\t\"w1 = w6; w1 += 1; r6 = (s32)r1;\"\n+#define SEXT32_LOOP(bound)\t\"1:\" BUF(\"r6\") SEXT32_INC \"if w1 != \" #bound \" goto 1b;\"\n+\n+SEXT32_TEST(sext32_iv, -4, SEXT32_LOOP(4), __success __retval(8)\n+\t __msg(\" r6=(sext32 (+ r6 1)) / (sext32 (linear r6 1))\")\n+\t __msg(\"header_count is 8 \") __msg(\"widening r6 to -4..3 \"))\n+SEXT32_TEST(sext32_iv_oob, -4, SEXT32_LOOP(5), OOB)\n+/* i wraps from INT32_MAX to INT32_MIN. The latch tests 0x7ffffffd .. 0x80000004. */\n+SEXT32_TEST(sext32_iv_wraps, INT32_MAX - 3, SEXT32_LOOP(0x80000004),\n+\t __msg(\"header_count is 8 \") __msg(\"widening r6 to \" ALL_OF_S32) OOB)\n+/* 'i \u003c n' implies the unsigned range 1 .. 0x80000000. Its last value is negative in r6. */\n+SEXT32_TEST(sext32_iv_unsigned_bound, 0,\n+\t \"r8 \u0026= 1; r6 += r8; r4 = 0x80000001 ll;\"\n+\t \"1:\" SEXT32_INC \"if w1 \u003c w4 goto 1b; if r6 s\u003e= 0 goto 2f; r0 = *(u64 *)(r5 + 0);\",\n+\t __msg(\"widening r6 to \" ALL_OF_S32) OOB)\n+\n /*\n * Two back edges:\n *\n@@ -1529,7 +1614,7 @@ __success __retval(7)\n __log_level(2)\n __msg(\"scev at header 1:\")\n __msg_next(\"r6=(+ r6 1) / (linear r6 1)\")\n-__msg_next(\"*fp-8=(any *fp-8 7) / (any *fp-8 7)\")\n+__msg_next(\"*fp-8=%fp-8.3=phi(*fp-8, 7) / (any *fp-8 7)\")\n __msg(\"loop header at 1, widening r6 to 0..2 step 1\")\n __msg(\"3: (79) r0 = *(u64 *)(r10 -8) ; R0=scalar() R10=fp0 loop_stack=1\")\n __naked void widen_any_unallocated_slot(void)\n@@ -1570,7 +1655,7 @@ __success __retval(7)\n __log_level(2)\n __msg(\"scev at header 2:\")\n __msg_next(\"r6=(+ r6 1) / (linear r6 1)\")\n-__msg_next(\"*fp-8=(any *fp-8 7) / (any *fp-8 7)\")\n+__msg_next(\"*fp-8=%fp-8.5=phi(*fp-8, 7) / (any *fp-8 7)\")\n __msg(\"loop header at 2, widening r6 to 0..2 step 1\")\n __msg(\"3: (79) r1 = *(u64 *)(r10 -8) ; R1=scalar() R10=fp0 fp-8=m???????\")\n __naked void widen_any_misc_slot(void)\n@@ -1673,7 +1758,7 @@ __success\n __log_level(2)\n __msg(\"scev at header 4:\")\n __msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n-__msg_next(\" *fp-8=?\")\n+__msg_next(\" *fp-8=%fp-8.7?\")\n __msg(\"loop header at 4, widening r6 to 0..9 step 1\")\n __naked void widen_subprog_probe_read(void)\n {\n@@ -2336,12 +2421,14 @@ __naked __noinline __used static int returns_zero(void)\n * A loop that the compiler unrolls in part has an exit for every 'break' and 'return' in every\n * copy of its body. How many there are says nothing about the number of iterations.\n * Scalar evolution takes a nested loop for one insn, and its exits are the successors of this insn.\n- * The list of exits is not complete: the loop around has no formulas.\n+ * The exit list is truncated: the enclosing loop has no SCEVs, the subprog is not analyzed.\n */\n SEC(\"xdp\")\n __success __log_level(2)\n __msg(\"loop at 1, too many exits, too many exits of a nested loop\")\n __msg(\"loop at 2, nested in 1, too many exits\")\n+__msg(\"Computing SCEV for subprog at 0:\")\n+__msg_next(\"Computing SCEV for subprog at {{[0-9]+}}:\")\n __msg(\"loop header at 1, unsupported loop: too many exits of a nested loop\")\n __msg(\"loop header at 2, header_count is [0..4] \")\n __naked void loop_around_301_exits(void)\n@@ -2594,7 +2681,7 @@ __msg(\"loop at 1{{$}}\")\n __msg(\"loop at 5, nested in 1, irreducible\")\n __msg(\"loop at 11, nested in 5\")\n __msg(\"scev at header 1:\")\n-__msg_next(\" r6=?\")\n+__msg_next(\" r6=%r6.5?\")\n __msg(\"scev at header 11:\")\n __msg_next(\" r9=(+ r9 1) / (linear r9 1)\")\n __msg(\"loop header at 11, widening r9 to 0..2 step 1\")\n@@ -2841,7 +2928,7 @@ __success\n __log_level(2)\n __msg(\"scev at header 2:\")\n __msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n-__msg_next(\" r7=(any r7 100) / (any r7 100)\")\n+__msg_next(\" r7=%r7.6=phi(r7, 100) / (any r7 100)\")\n __msg_next(\" scev at latch 3:\")\n __msg_next(\" r6=(+ r6 1) / (linear (+ r6 1) 1)\")\n __msg_next(\" r7=r7 / (any r7 100)\")\n@@ -3116,12 +3203,12 @@ __naked void name(void)\t\t\t\t\t\t\t\t\\\n #define NOT_UNROLLED\t\"widening r6 to 0..0xf423f step 1\"\n \n /* 'if (...) cnt++' */\n-PARTIAL_SPILL_TEST(partial_spill32_inc, u32, 10, \"can't widen *fp-8, expr is (any *fp-8 (spill32 \",\n+PARTIAL_SPILL_TEST(partial_spill32_inc, u32, 10, \"can't widen *fp-8, expr is %fp-8.{{[0-9]+}}=phi(*fp-8, (spill32 \",\n \tSPILL32_0, \"if r6 \u0026 1 goto 2f;\" SPILL32_INC \"2:\")\n PARTIAL_SPILL_TEST(partial_spill16_inc, u16, 10, \"can't widen *fp-8, expr is (spill16 \",\n \t\"*(u16 *)(r10 - 8) = r1;\", \"r1 = *(u16 *)(r10 - 8); w1 += 1; *(u16 *)(r10 - 8) = r1;\")\n /* A loop in the loop does it */\n-PARTIAL_SPILL_TEST(partial_spill32_inc_in_nested_loop, u32, 10, \"can't widen *fp-8, expr is ?\",\n+PARTIAL_SPILL_TEST(partial_spill32_inc_in_nested_loop, u32, 10, \"can't widen *fp-8, expr is %fp-8.{{[0-9]+}}?\",\n \tSPILL32_0, \"r7 = 0; 2:\" SPILL32_INC \"r7 += 1; if r7 \u003c 3 goto 2b;\")\n /* Two slots feed each other */\n PARTIAL_SPILL_TEST(partial_spill32_two_slots, u32, 10, \"can't widen *fp-8, expr is (spill32 \",\n@@ -3185,6 +3272,14 @@ RANGE_TEST(spill32_first_is_precise, \"\", 0, 0, 1, 0, 1,\n RANGE_TEST(spill32_first_is_64bit, \"\", 0, 0, 1, 5, 5,\n \t \"*(u64 *)(r10 - 8) = r6; 1:\" LIMIT_ITERATIONS SPILL32_INC \"if w1 != w7 goto 1b;\",\n \t SPILL32_COUNTED(5, \"0..4\"))\n+/* A 64-bit spill of i. Its upper 32 bits are dead: the low 32 bits are the induction variable. */\n+#define SEXT32_SPILL_LOOP(bound)\t\t\t\t\t\t\t\t\\\n+\t\"1:\" BUF(\"*(u32 *)(r10 - 16)\") \"w1 = *(u32 *)(r10 - 16); w1 += 1; r3 = (s32)r1;\"\t\\\n+\t\"*(u64 *)(r10 - 16) = r3; if w1 != \" #bound \" goto 1b;\"\n+SEXT32_TEST(sext32_iv_hi32_dead, 0, SEXT32_SPILL_LOOP(8), __success __retval(8)\n+\t __msg(\" *fp-16=(sext32 (+ *fp-16 1)) / (spill32 (linear (zext32 *fp-16) 1))\")\n+\t __msg(\"header_count is 8 \") __msg(\"widening *fp-16 to 0..7 \"))\n+SEXT32_TEST(sext32_iv_hi32_dead_oob, 0, SEXT32_SPILL_LOOP(9), OOB)\n /* The counter makes the address of a spill. Such a loop is not summarized, as with a register. */\n PARTIAL_SPILL_TEST(spill32_is_a_stack_offset, u32, 4,\n \t\"can't widen *fp-8, expr is (spill32 (+ *fp-8 8)), requires exact stack-offset tracking\",\n@@ -3286,7 +3381,7 @@ NOT_LINEAR_TEST(zext32_or_nothing, \"r7 \u003e\u003e= 8;\", \"if r8 == 0 goto +1; w7 = w7;\",\n NOT_LINEAR_TEST(and_64_to_127, \"r7 \u0026= 63; r7 |= 64;\", \"r7 \u0026= 127;\", UNROLLED(\"(\u0026 r7 127)\"))\n /* '\u003e\u003e' does not make a number greater, but iterations one by one tell more: 0 after 8 shifts */\n NOT_LINEAR_TEST(rsh_on_one_path, \"r7 \u0026= 255;\", \"if r8 == 0 goto +1; r7 \u003e\u003e= 1;\",\n-\t\tUNROLLED(\"(any r7 (\u003e\u003e r7 1))\"))\n+\t\tUNROLLED(\"%r7.8=phi(r7, (\u003e\u003e r7 1))\"))\n NOT_LINEAR_TEST(rsh_then_and, \"r7 \u0026= 255;\", \"r7 \u003e\u003e= 1; r7 \u0026= r8;\", UNROLLED(\"(\u0026 (\u003e\u003e r7 1) r8)\"))\n NOT_LINEAR_TEST(lsh_grows, \"r7 \u0026= 15;\", \"r7 \u003c\u003c= 1;\", UNROLLED(\"(\u003c\u003c r7 1)\"))\n \n@@ -3295,42 +3390,293 @@ NOT_LINEAR_TEST(lsh_grows, \"r7 \u0026= 15;\", \"r7 \u003c\u003c= 1;\", UNROLLED(\"(\u003c\u003c r7 1)\"))\n NOT_LINEAR_TEST(same_constant, \"r7 = 17;\", \"r7 \u0026= 31;\", NOT_CHANGED)\n NOT_LINEAR_TEST(same_wide_constant, \"r7 = 0xffffffff00000011 ll;\", \"r7 \u0026= -239;\", NOT_CHANGED)\n \n-#ifdef __BPF_FEATURE_ADDR_SPACE_CAST\n struct {\n-\t__uint(type, BPF_MAP_TYPE_ARENA);\n-\t__uint(map_flags, BPF_F_MMAPABLE);\n+\t__uint(type, BPF_MAP_TYPE_ARRAY);\n \t__uint(max_entries, 1);\n-} arena SEC(\".maps\");\n+\t__type(key, __u32);\n+\t__type(value, char[64]);\n+} map64 SEC(\".maps\");\n \n-/* The offset of a pointer to arena is not tracked */\n-#define ARENA_TEST(name, op, expect)\t\t\t\t\t\t\\\n-SEC(\"syscall\")\t\t\t\t\t\t\t\t\t\\\n-__log_level(2)\t\t\t\t\t\t\t\t\t\\\n-expect\t\t\t\t\t\t\t\t\t\t\\\n+/*\n+ * A conditional jump refines the registers and stack slots that are linked to what it tests.\n+ * r6: 64 bytes. r7: a scalar below 256. r8: an unbounded scalar. r9: the context.\n+ * The test leaves an address in r1.\n+ */\n+#define LINKED_SEC(sec, name, expect, body)\t\t\t\t\t\\\n+SEC(sec) expect\t\t\t\t\t\t\t\t\t\\\n __naked void name(void)\t\t\t\t\t\t\t\t\\\n {\t\t\t\t\t\t\t\t\t\t\\\n \tasm volatile (\t\t\t\t\t\t\t\t\\\n-\t\"r1 = %[arena] ll;\"\t\t\t\t\t\t\t\\\n-\t\"r6 = 0;\"\t\t\t\t\t\t\t\t\\\n-\t\"r6 = addr_space_cast(r6, 0, 1);\"\t\t\t\t\t\\\n-\t\"r7 = 0;\"\t\t\t\t\t\t\t\t\\\n-\"1:\t*(u64 *)(r6 + 0) = r7;\"\t\t\t\t\t\t\t\\\n-\top\t\t\t\t\t\t\t\t\t\\\n-\t\"r7 += 1;\"\t\t\t\t\t\t\t\t\\\n-\t\"if r7 \u003c 100 goto 1b;\"\t\t\t\t\t\t\t\\\n-\t\"r0 = 0;\"\t\t\t\t\t\t\t\t\\\n-\t\"exit;\"\t\t\t\t\t\t\t\t\t\\\n-\t:: __imm_addr(arena) : __clobber_all);\t\t\t\t\t\\\n+\t\"r9 = r1; r1 = 0; *(u32 *)(r10 - 4) = r1; r2 = r10; r2 += -4; r1 = %[map64] ll;\"\t\\\n+\t\"call %[bpf_map_lookup_elem]; if r0 == 0 goto out_%=; r6 = r0;\"\t\t\\\n+\t\"call %[bpf_get_prandom_u32]; r7 = r0; r7 \u0026= 255;\"\t\t\t\\\n+\t\"call %[bpf_ktime_get_ns]; r8 = r0;\"\t\t\t\t\t\\\n+\tbody\t\t\t\t\t\t\t\t\t\\\n+\t\"r0 = *(u8 *)(r1 + 0);\"\t\t\t\t\t\t\t\\\n+\t\"out_%=: r0 = 0; exit;\"\t\t\t\t\t\t\t\\\n+\t:\t\t\t\t\t\t\t\t\t\\\n+\t: __imm(bpf_map_lookup_elem), __imm(bpf_get_prandom_u32), __imm(bpf_ktime_get_ns),\t\\\n+\t __imm(bpf_dynptr_from_skb), __imm(bpf_dynptr_slice_rdwr),\t\t\\\n+\t __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard), __imm(bpf_loop),\t\\\n+\t __imm_addr(map64), __imm_addr(ringbuf)\t\t\t\t\\\n+\t: __clobber_all);\t\t\t\t\t\t\t\\\n+}\n+#define LINKED(name, expect, body)\tLINKED_SEC(\"socket\", name, expect, body)\n+\n+#define VALID\t__success __retval(0)\n+#define MAP_OOB\t__failure __msg(\"invalid access to map value\")\n+#define UNBOUND\t__failure __msg(\"unbounded min value\")\n+\n+/* r3 is the address in r1 as a scalar. It does not bound the offset of r1. */\n+LINKED(pointer_is_not_scalar, __failure,\n+\t\"r7 \u0026= 127; r1 = r6; r1 += r7; r3 = r1; r3 = le64 r3; if r3 \u003c 64 goto out_%=; r1 += -64;\")\n+\n+/*\n+ *\tp = buf + i; if (i \u003e 63) return 0; c = *p;\n+ * The jump bounds i. r1 is r6 + r7 and r6 is live: r1 is recomputed.\n+ */\n+#define USE_R6\t\"r0 = *(u8 *)(r6 + 0);\"\n+\n+LINKED(index_tested_after_the_add, VALID, \"r1 = r6; r1 += r7; if r7 \u003e 63 goto out_%=;\" USE_R6)\n+LINKED(low_32_bits_of_the_index_tested, __failure __msg(\"R1 unbounded memory access\"),\n+\t\"r2 = 0x1000000ff ll; r2 \u0026= r8; r1 = r6; r1 += r2; w3 = w2; if r3 \u003e 63 goto out_%=;\" USE_R6)\n+/* r7 is -2 or 5. Its low 2 bits are not 3: the path is infeasible, and r6 + r7 + 2 is empty. */\n+LINKED(index_is_empty, VALID __flag(BPF_F_TEST_REG_INVARIANTS),\n+\t\"r7 \u0026= 1; r7 *= 7; r7 += -2; r1 = r6; r1 += r7; r1 += 2; if r7 \u0026 1 goto l_%=; goto out_%=;\"\n+\t\"l_%=: if r7 \u0026 2 goto m_%=; goto out_%=; m_%=: r1 += 1;\" USE_R6)\n+\n+/*\n+ *\tstatic void clamp(struct buf *b) { if (b-\u003elen \u003e 63) b-\u003elen = 0; }\n+ *\tclamp(\u0026b); c = b.data[b.len];\n+ * The callee tests memory of its caller: the slot is refined. Not if it may have been written since\n+ * the load. r1 and r4 point to b.len, r2 is not bounded.\n+ */\n+#define CLAMP(name, before_the_jump)\t\t\t\t\t\t\\\n+static __naked __noinline __used void name(void)\t\t\t\t\\\n+{\t\t\t\t\t\t\t\t\t\t\\\n+\tasm volatile (\t\t\t\t\t\t\t\t\\\n+\t\"r3 = *(u64 *)(r1 + 0);\" before_the_jump\t\t\t\t\\\n+\t\"if r3 \u003c= 63 goto +2; r3 = 0; *(u64 *)(r1 + 0) = r3; r0 = 0; exit;\"\t\\\n+\t::: __clobber_all);\t\t\t\t\t\t\t\\\n+}\n+#define CALL(callee)\t\t\t\t\t\t\t\t\\\n+\t\"*(u64 *)(r10 - 16) = r8; r1 = r10; r1 += -16; r4 = r1; r2 = r8; r2 \u003e\u003e= 1;\"\t\\\n+\t\"call \" #callee \"; r2 = *(u64 *)(r10 - 16); r1 = r6; r1 += r2;\"\n+\n+CLAMP(clamp, \"\")\n+LINKED(callee_tests_memory_of_caller, VALID, CALL(clamp))\n+CLAMP(store_and_clamp, \"*(u64 *)(r1 + 0) = r2;\")\n+LINKED(callee_writes_memory_of_caller, __failure, CALL(store_and_clamp))\n+/* a store defines the memory */\n+CLAMP(store_and_test, \"r3 = r2; *(u64 *)(r1 + 0) = r3;\")\n+LINKED(callee_tests_what_it_stored, VALID, CALL(store_and_test))\n+/* the same address base, no overlap */\n+CLAMP(store_next_and_clamp, \"*(u64 *)(r1 + 8) = r2;\")\n+LINKED(callee_writes_next_field, VALID, CALL(store_next_and_clamp))\n+/* another address base can be another name of the memory */\n+CLAMP(store_alias_and_clamp, \"*(u64 *)(r4 + 0) = r2;\")\n+LINKED(callee_writes_through_alias, __failure, CALL(store_alias_and_clamp))\n+\n+/*\n+ *\tstruct { char *buf; u64 len; } c = { buf, 0 };\t\tbpf_loop(100, append, \u0026c, 0);\n+ *\tappend: if (c-\u003elen \u003e 63) return 1; bpf_get_prandom_u32(); c-\u003ebuf[c-\u003elen]; c-\u003elen++;\n+ * The compiler loads c-\u003elen again after a call. c is on the stack of the caller, where len grows\n+ * until it is widened. The jump refines that slot: it still holds what the tested register was\n+ * loaded from.\n+ */\n+#define APPEND(name, before_the_jump)\t\t\t\t\t\t\\\n+static __naked __used void name(void)\t\t\t\t\t\t\\\n+{\t\t\t\t\t\t\t\t\t\t\\\n+\tasm volatile (\t\t\t\t\t\t\t\t\\\n+\t\"r6 = r2; r1 = *(u64 *)(r6 + 8);\" before_the_jump\t\t\t\\\n+\t\"if r1 \u003e 63 goto l_%=;\"\t\t\t\t\t\t\t\\\n+\t\"call %[bpf_get_prandom_u32];\"\t\t\t\t\t\t\\\n+\t\"r2 = *(u64 *)(r6 + 8); r1 = *(u64 *)(r6 + 0); r1 += r2; r0 = *(u8 *)(r1 + 0);\"\t\\\n+\t\"r2 += 1; *(u64 *)(r6 + 8) = r2; r0 = 0; exit;\"\t\t\t\t\\\n+\t\"l_%=: r0 = 1; exit;\"\t\t\t\t\t\t\t\\\n+\t:: __imm(bpf_get_prandom_u32) : __clobber_all);\t\t\t\t\\\n }\n+#define CALL_APPEND(name)\t\t\t\t\t\t\t\\\n+\t\"*(u64 *)(r10 - 16) = r6; r1 = 0; *(u64 *)(r10 - 8) = r1;\"\t\t\\\n+\t\"r1 = 100; r2 = \" #name \" ll; r3 = r10; r3 += -16; r4 = 0; call %[bpf_loop]; r1 = r6;\"\n+\n+APPEND(append, \"\")\n+LINKED(callback_tests_slot_of_caller, VALID, CALL_APPEND(append))\n+/* The slot is written between the load and the jump: len is 0 1 3 7 15 31 63, the slot 126 */\n+APPEND(append_stale, \"r2 = r1; r2 \u003c\u003c= 1; *(u64 *)(r6 + 8) = r2;\")\n+LINKED(callback_tests_stale_copy_of_slot, UNBOUND, CALL_APPEND(append_stale))\n \n-#define NOT_UNROLLED100\t__msg(\"loop header at 5, widening r7 to 0..99 step 1\")\n-/* A loop that moves the pointer is not unrolled */\n-ARENA_TEST(arena_pointer_moves, \"r6 += 8;\", __success NOT_UNROLLED100)\n-/* The loop makes a number of it: the state that returns to the loop header tells */\n-ARENA_TEST(arena_pointer_becomes_a_number, \"if r7 != 5 goto +1; r6 = 4096;\",\n-\t __failure NOT_UNROLLED100 __msg(\"R6 invalid mem access 'scalar'\"))\n+/*\n+ *\tp = buf; i = 0; do { if (i \u003e 62) break; i = *(u16 *)p; p = buf + i; } while (i);\n+ * r1 == r6 + r2 at the header in every iteration: it holds at loop entry, the backedge preserves it\n+ */\n+#define LOOP(add)\t\t\t\t\t\t\t\t\\\n+\t\"l_%=: if r2 \u003e 62 goto out_%=; r2 = *(u16 *)(r1 + 0);\" add\t\t\\\n+\t\"if r2 != 0 goto l_%=; r1 = r6;\"\n+\n+LINKED(base_plus_index_at_loop_header, VALID, \"r1 = r6; r2 = 0;\" LOOP(\"r1 = r6; r1 += r2;\"))\n+LINKED(base_plus_index_at_loop_entry_only, MAP_OOB,\n+\t\"r1 = r6; r2 = 0;\" LOOP(\"r1 = r6; r1 += r2; r2 \u003e\u003e= 1;\"))\n+LINKED(base_plus_index_on_backedge_only, MAP_OOB,\n+\t\"r1 = r6; r1 += r7; r2 = r8; r2 \u0026= 255;\" LOOP(\"r1 = r6; r1 += r2;\"))\n+\n+LINKED(sign_extension_that_fits, VALID, \"r2 = (s8)r8; if r8 \u003e 63 goto out_%=; r1 = r6; r1 += r2;\")\n+\n+/* 'int n' in three registers. 'if w3 s\u003e 63' refines only 32-bit ranges: those of the copies too. */\n+LINKED(copies_get_the_32_bit_range, VALID,\n+\t\"w2 = w8; r3 = r2; r4 = r2; if w3 s\u003e 63 goto out_%=; if w4 s\u003c 0 goto out_%=;\"\n+\t\"r1 = r6; r1 += r2;\")\n+\n+/* A copy on each of two paths: r2 and r3 are phis with the same operands, up to a constant */\n+#define TWO_PATHS(a, b)\t\t\t\t\t\t\t\t\\\n+\t\"if r7 \u003e 9 goto l_%=; r2 = r8; \" a \" goto m_%=; l_%=: r2 = r8; r2 \u003e\u003e= 1; \" b\t\\\n+\t\"m_%=: if r2 \u003e 62 goto out_%=; r1 = r6; r1 += r3;\"\n+\n+LINKED(congruent_phis, VALID, TWO_PATHS(\"r3 = r2; r3 += 1;\", \"r3 = r2; r3 += 1;\"))\n+LINKED(phis_with_other_delta_on_one_path, UNBOUND,\n+ TWO_PATHS(\"r3 = r2; r3 += 1;\", \"r3 = r2; r3 += 2;\"))\n+/* One of three edges brings unrelated values */\n+LINKED(phis_not_linked_on_one_of_three_edges, UNBOUND,\n+\t\"r3 = r8; r3 \u003e\u003e= 2; r2 = 0; if r7 == 20 goto m_%=;\"\n+\tTWO_PATHS(\"r3 = r2; r3 += 1;\", \"r3 = r2; r3 += 1;\"))\n+/* (zext32 x) on both paths: linked in 64 bits */\n+LINKED(congruent_phis_of_zext32, VALID,\n+\t\"if r7 \u003e 9 goto l_%=; w2 = w8; r3 = r2; goto m_%=; l_%=: r2 = r8; r2 \u003e\u003e= 1; w2 = w2;\"\n+\t\"r3 = r2; m_%=: r3 += 1; if r2 \u003e 62 goto out_%=; r1 = r6; r1 += r3;\")\n+\n+/* The low 3 bits of r3 are 5. It is r8 + 5 once r8 fits in s8: no overlap with [-2, 1]. */\n+LINKED(empty_intersection, VALID __flag(BPF_F_TEST_REG_INVARIANTS),\n+\t\"r3 = (s8)r8; if r3 \u0026 7 goto out_%=; r3 += 5; if r3 s\u003e 100 goto out_%=;\"\n+\t\"if r3 s\u003c -100 goto out_%=; if r8 s\u003c -7 goto out_%=; if r8 s\u003e -4 goto out_%=;\"\n+\t\"r3 += 3; r1 = r6;\")\n+\n+/* r2 is even. It is r8 once r8 fits in s8. r8 is odd after the last jump: var_off don't overlap. */\n+LINKED(var_off_dont_overlap, VALID,\n+\t\"r2 = (s8)r8; if r2 \u0026 1 goto out_%=; if r2 s\u003e 100 goto out_%=; if r2 s\u003c -100 goto out_%=;\"\n+\t\"if r8 \u003e 5 goto out_%=; if r8 \u0026 1 goto l_%=; goto out_%=;\"\n+\t\"l_%=: r2 \u0026= 1; r2 \u003c\u003c= 6; r1 = r6; r1 += r2;\")\n+\n+/* The low bytes of the spill to r10 - 16 come first or last */\n+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n+#define FIRST_BYTES_ARE_LOW\tVALID\n+#else\n+#define FIRST_BYTES_ARE_LOW\t__failure __msg(\"R1 unbounded memory access\")\n #endif\n \n+/* r2 is the low 32 bits of the slot. The 32-bit spill is in its first half-slot. */\n+LINKED(spill_32_bits_fill_64_take_low_half, FIRST_BYTES_ARE_LOW,\n+\t\"*(u64 *)(r10 - 16) = r7; *(u32 *)(r10 - 16) = r8; r2 = *(u64 *)(r10 - 16); w2 = w2;\"\n+\t\"w3 = w8; if r2 \u003e 63 goto out_%=; r1 = r6; r1 += r3;\")\n+/* The slot is a phi: two paths spill distinct values to its first half-slot */\n+LINKED(spill_32_bits_on_two_paths_fill_64_take_low_half, FIRST_BYTES_ARE_LOW,\n+\t\"*(u64 *)(r10 - 16) = r7; *(u32 *)(r10 - 16) = r8; if r7 \u003e 9 goto l_%=;\"\n+\t\"r3 = r8; r3 \u003e\u003e= 1; *(u32 *)(r10 - 16) = r3;\"\n+\t\"l_%=: r2 = *(u64 *)(r10 - 16); w2 = w2; if r2 \u003e 63 goto out_%=;\"\n+\t\"r3 = *(u32 *)(r10 - 16); r1 = r6; r1 += r3;\")\n+/* The half-slot at r10 - 12 is dead: at the second jump the state has a 32-bit spill */\n+LINKED(spill_64_bits_fill_32, FIRST_BYTES_ARE_LOW,\n+\t\"*(u64 *)(r10 - 16) = r8; if r8 s\u003e 63 goto out_%=; if r8 s\u003c 0 goto out_%=;\"\n+\t\"r2 = *(u32 *)(r10 - 16); r1 = r6; r1 += r2;\")\n+\n+/* r0 is r10 - 24 when the first 8 bytes of the packet are not in one piece */\n+LINKED_SEC(\"tc\", slot_written_through_a_slice, UNBOUND,\n+\t\"r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];\"\n+\t\"r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -24; r4 = 8;\"\n+\t\"call %[bpf_dynptr_slice_rdwr]; if r0 == 0 goto out_%=;\"\n+\t\"r3 = *(u64 *)(r10 - 24); *(u64 *)(r0 + 0) = r8; r2 = *(u64 *)(r10 - 24);\"\n+\t\"if r3 \u003e 63 goto out_%=; r1 = r6; r1 += r2;\")\n+/* One fill reads one value: r2 is a copy of r3, whatever is stored through the slice */\n+LINKED_SEC(\"tc\", copy_of_a_fill_from_a_slice_buffer, VALID,\n+\t\"r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];\"\n+\t\"r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -24; r4 = 8;\"\n+\t\"call %[bpf_dynptr_slice_rdwr]; if r0 == 0 goto out_%=;\"\n+\t\"r3 = *(u64 *)(r10 - 24); r2 = r3; *(u64 *)(r0 + 0) = r8;\"\n+\t\"if r3 \u003e 63 goto out_%=; r1 = r6; r1 += r2;\")\n+\n+/* The buffer is r10 - 32 or r10 - 48, a range in the state. The call does not write to r10 - 40. */\n+LINKED_SEC(\"tc\", slice_buffer_at_two_offsets, VALID,\n+\t\"r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];\"\n+\t\"*(u64 *)(r10 - 32) = r7; *(u64 *)(r10 - 40) = r7; *(u64 *)(r10 - 48) = r7;\"\n+\t\"r8 = r10; r8 += -48; r9 = r10; r9 += -32; r7 = 0;\"\n+\t\"l_%=: call %[bpf_get_prandom_u32]; if r0 == 0 goto s_%=; r9 = r8;\"\n+\t\"s_%=: r7 += 1; if r7 \u003c 64 goto l_%=;\"\n+\t\"r1 = r10; r1 += -16; r2 = 0; r3 = r9; r4 = 8; call %[bpf_dynptr_slice_rdwr];\"\n+\t\"r1 = *(u64 *)(r10 - 40); r1 = r6;\")\n+/* No insn stores through a slice of 0 bytes, and the call does not write to the buffer */\n+LINKED_SEC(\"tc\", slice_of_0_bytes_at_variable_offset, VALID,\n+\t\"r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];\"\n+\t\"*(u64 *)(r10 - 24) = r7; *(u64 *)(r10 - 32) = r7; r7 \u0026= 8;\"\n+\t\"r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -32; r3 += r7; r4 = 0;\"\n+\t\"call %[bpf_dynptr_slice_rdwr]; r1 = r6;\")\n+\n+/* BTF of the kfuncs that only asm calls */\n+void __kfunc_btf_root(void)\n+{\n+\tbpf_dynptr_from_skb(0, 0, 0);\n+\tbpf_dynptr_slice_rdwr(0, 0, 0, 0);\n+}\n+\n+/* Linked at the header in every iteration: r2 is r3 + 2 at loop entry, both have the step 1 */\n+#define LOOP_HEADER(enter, step)\t\t\t\t\t\t\\\n+\tenter \"l_%=: if r3 \u003e 61 goto out_%=; r1 = r6; r1 += r2; r0 = *(u8 *)(r1 + 0);\" step\t\\\n+\t\"if r0 != 0 goto l_%=;\"\n+\n+LINKED(linked_at_loop_header, VALID,\n+\tLOOP_HEADER(\"r3 = r8; r2 = r8; r2 += 1; r2 += 1;\", \"r2 += 1; r3 += 1;\"))\n+LINKED(linked_at_loop_entry_only, __failure,\n+\tLOOP_HEADER(\"r3 = r8; r2 = r8; r2 += 1; r2 += 1;\", \"r2 += 2; r3 += 1;\"))\n+\n+/*\n+ * An irreducible loop: 'l' is the header, 'm' is a secondary entry. A link that is made in the loop\n+ * holds in the next basic blocks too. Not after 'm' if it is made before 'm': every edge of the\n+ * loop to 'm' has it, the edge that enters the loop there does not. That edge can come from\n+ * a natural loop 'o' around the irreducible one.\n+ * In the last two tests 'o' is the header. The natural loop in it has an env at loop entry. Its\n+ * header can be the secondary entry.\n+ */\n+LINKED(irreducible_loop, VALID,\n+\t\"if r7 \u003e 5 goto m_%=; l_%=: r7 += 1;\"\n+\t\"m_%=: r2 = r8; r2 += 1; r2 += 1; if r8 \u003e 61 goto out_%=; r1 = r6; r1 += r2;\"\n+\t\"r0 = *(u8 *)(r1 + 0); if r7 \u003c 10 goto l_%=;\")\n+LINKED(irreducible_loop_fallthrough_pred, UNBOUND,\n+\t\"r2 = r7; if r7 \u003e 5 goto m_%=; l_%=: r7 += 1; r2 = r8;\"\n+\t\"m_%=: if r8 \u003e 63 goto out_%=; r1 = r6; r1 += r2;\"\n+\t\"r0 = *(u8 *)(r1 + 0); if r7 \u003c 10 goto l_%=;\")\n+LINKED(irreducible_loop_next_bb, VALID,\n+\t\"if r7 \u003e 5 goto m_%=; l_%=: r7 += 1;\"\n+\t\"m_%=: r2 = r8; r2 += 1; r2 += 1; if r7 == 3 goto n_%=; r3 = 0;\"\n+\t\"n_%=: if r8 \u003e 61 goto out_%=; r1 = r6; r1 += r2;\"\n+\t\"r0 = *(u8 *)(r1 + 0); if r7 \u003c 10 goto l_%=;\")\n+LINKED(irreducible_loop_secondary_entry, UNBOUND,\n+\t\"r9 = 0; o_%=: r9 += 1; call %[bpf_ktime_get_ns]; r8 = r0; r2 = r7; if r7 \u003e 5 goto m_%=;\"\n+\t\"l_%=: r7 += 1; r2 = r8; r2 += 1; r2 += 1; if r7 == 3 goto m_%=; r3 = 0;\"\n+\t\"m_%=: if r8 \u003e 61 goto out_%=; r1 = r6; r1 += r2;\"\n+\t\"r0 = *(u8 *)(r1 + 0); if r7 \u003c 10 goto l_%=; if r9 \u003c 3 goto o_%=;\")\n+LINKED(natural_loop_in_irreducible_loop, VALID,\n+\t\"if r7 \u003e 5 goto m_%=; o_%=: r7 += 1; m_%=:\"\n+\tLOOP_HEADER(\"r3 = r8; r2 = r8; r2 += 1; r2 += 1;\", \"r2 += 1; r3 += 1;\")\n+\t\"if r7 \u003c 10 goto o_%=;\")\n+LINKED(natural_loop_is_secondary_entry, MAP_OOB,\n+\t\"r3 = r8; r2 = r7; if r7 \u003e 5 goto l_%=; o_%=: r7 += 1;\"\n+\tLOOP_HEADER(\"r3 = r8; r2 = r8; r2 += 1; r2 += 1;\", \"r2 += 1; r3 += 1;\")\n+\t\"if r7 \u003c 10 goto o_%=;\")\n+\n+/*\n+ * No exit of the inner loop dominates its backedges: may_goto is added before its header. The prog\n+ * holds a reference, so may_goto goes to the exit of the outer loop: an edge that the verifier\n+ * adds. Every iteration of the outer loop restores r3. At the header of the inner one it is r7.\n+ */\n+LINKED(added_edge, UNBOUND,\n+\t\"r1 = %[ringbuf] ll; r2 = 8; r3 = 0; call %[bpf_ringbuf_reserve]; if r0 == 0 goto out_%=;\"\n+\t\"*(u64 *)(r10 - 16) = r0; r3 = r8;\"\n+\t\"o_%=: r2 = r3; r3 = r7;\"\n+\t\"i_%=: r1 = *(u8 *)(r6 + 0); if r1 == 1 goto a_%=; if r1 == 2 goto b_%=; goto i_%=;\"\n+\t\"a_%=: goto i_%=;\"\n+\t\"b_%=: r3 = r2; r1 = *(u8 *)(r6 + 1); if r1 == 3 goto o_%=;\"\n+\t\"r4 = r6; if r8 \u003e 63 goto r_%=; r4 += r3;\"\n+\t\"r_%=: *(u64 *)(r10 - 24) = r4; r1 = *(u64 *)(r10 - 16); r2 = 0;\"\n+\t\"call %[bpf_ringbuf_discard]; r1 = *(u64 *)(r10 - 24);\")\n+\n /*\n * r7 = ctx-\u003edata;\n * r8 = r7\n@@ -3448,9 +3794,9 @@ __failure\n __log_level(2)\n __flag(BPF_F_TEST_STATE_FREQ)\n __msg(\"scev at header 9:\")\n-__msg_next(\" r6=(+ ? 1) / ?\")\n+__msg_next(\" r6=(+ %r6.13? 1) / ?\")\n __msg_next(\" scev at latch 20:\")\n-__msg_next(\" r6=(+ ? 1) / (+ ? 1)\")\n+__msg_next(\" r6=(+ %r6.13? 1) / (+ %r6.13? 1)\")\n __msg_next(\"scev at header 13:\")\n __msg_next(\" r9=(+ r9 1) / (linear r9 1)\")\n __msg_next(\" scev at latch 16:\")\n@@ -3524,7 +3870,7 @@ SEC(\"xdp\")\n __success __retval(3)\n __log_level(2)\n __flag(BPF_F_TEST_STATE_FREQ)\n-__msg(\"r6 = *(u64 *)(r10 -8) {{.*}}; r6 ? -\u003e r6\")\n+__msg(\"r6 = *(u64 *)(r10 -8) {{.*}}; r6 %r6.4? -\u003e r6\")\n __msg(\"scev at header 1:\")\n __msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n __msg_next(\" scev at latch 16:\")\n@@ -3645,7 +3991,7 @@ __success\n __log_level(2)\n __flag(BPF_F_TEST_STATE_FREQ)\n __msg(\"scev at header 4:\")\n-__msg_next(\"r7=(any r7 8) / (any r7 8)\")\n+__msg_next(\"r7=%r7.11=phi(r7, 8) / (any r7 8)\")\n __msg(\"loop header at 4, can't widen r7, expr is {{.*}}, requires exact stack-offset tracking\")\n __naked void no_widen_stack_fill_any(void)\n {\n@@ -4419,7 +4765,7 @@ SEC(\"socket\")\n __success __retval(0)\n __log_level(2)\n __msg(\"header_count is 100000 \")\n-__msg(\"can't widen r6, expr is _\")\n+__msg(\"can't widen r6, expr is %r6.13\")\n __not_msg(\"widening r8\")\n __msg(\"clamping r8 to 0..0x1869f step 1\")\n __naked void index_loaded_in_previous_iteration(void)\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_spill_fill.c b/tools/testing/selftests/bpf/progs/verifier_spill_fill.c\nindex 0baa8e06b8d1ef..623ed5ef3630d4 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_spill_fill.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_spill_fill.c\n@@ -1451,6 +1451,37 @@ __naked void imprecise_scalar_spill_half_dead(void)\n : __clobber_all);\n }\n \n+/*\n+ * The first half-slot of a 64-bit spill holds its low 32 bits on little endian only.\n+ * The test spills to r10 - 8. The first four bytes of the slot are an offset into one byte.\n+ */\n+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n+#define FIRST_HALF_IS_LOW\t__success\n+#else\n+#define FIRST_HALF_IS_LOW\t__failure __msg(\"access may be outside object bounds\")\n+#endif\n+#define FIRST_HALF(name, stores)\t\t\t\t\t\t\\\n+SEC(\"raw_tp\") FIRST_HALF_IS_LOW\t\t\t\t\t\t\t\\\n+__naked void name(void)\t\t\t\t\t\t\t\t\\\n+{\t\t\t\t\t\t\t\t\t\t\\\n+\tasm volatile (\t\t\t\t\t\t\t\t\\\n+\t\"call %[bpf_ktime_get_ns];\"\t\t\t\t\t\t\\\n+\tstores\t\t\t\t\t\t\t\t\t\\\n+\t\"r7 = *(u32 *)(r10 - 8); r1 = %[single_byte_buf] ll; r1 += r7; r0 = *(u8 *)(r1 + 0);\"\t\\\n+\t\"out_%=: r0 = 0; exit;\"\t\t\t\t\t\t\t\\\n+\t:\t\t\t\t\t\t\t\t\t\\\n+\t: __imm(bpf_ktime_get_ns), __imm_addr(single_byte_buf)\t\t\t\\\n+\t: __clobber_all);\t\t\t\t\t\t\t\\\n+}\n+\n+/* The low 32 bits of the value are 0. The second half-slot is dead after the jump. */\n+FIRST_HALF(first_half_of_spill_second_half_dead,\n+\t \"r0 \u003c\u003c= 32; *(u64 *)(r10 - 8) = r0; if r0 == 0 goto out_%=;\")\n+/* One path has a 32-bit spill of r6, whose low 32 bits are 0, the other one a 64-bit spill */\n+FIRST_HALF(spill_of_64_bits_vs_spill_of_32_bits,\n+\t \"r6 = r0; r6 \u003c\u003c= 32; if r0 \u003e 5 goto 1f; *(u32 *)(r10 - 8) = r6; goto 2f;\"\n+\t \"1: r6 = 0x7ffffff000000000 ll; *(u64 *)(r10 - 8) = r6; 2:\")\n+\n /* check valid spill/fill, ptr to tp buffer */\n SEC(\"raw_tracepoint.w\")\n __success\n"
} |
| 2/1 | 2026/11/14 14:38 | agent | patch-evaluator |
2mModel:core Args: null Results: {
"EnableConfigs": [
"BPF_SYSCALL"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_scev_next_linked_reg",
"bpf_scev_mem_addr",
"bpf_scev_in_slice_slots",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_half_slot_live_before",
"bpf_clean_verifier_state"
],
"Reasoning": "This patch series significantly revamps linked scalar tracking in the BPF verifier. Dynamic scalar ID and delta tracking across verification states are replaced with static scalar evolution (SCEV) analysis, global value numbering, phi-node expressions, and memory register promotion. Conditional jump operations now query SCEV linked registers to refine bounds. These modifications affect core BPF verifier correctness and state equivalence, which are directly reachable from userspace via the bpf() system call and represent high-value fuzzing targets.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 5688cd04d3b41e9f2094dd2a002289802a0f9401
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Nov 14 14:38:24 2026 +0000
syz-cluster: applied patch under review
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 4771c55d8f41f6..598763d128ab8c 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -60,10 +60,8 @@ struct bpf_stack_range {
struct bpf_reg_state {
/* Ordering of fields matters. See regsafe() */
enum bpf_reg_type type;
- /*
- * Constant delta between "linked" scalars with the same ID.
- */
- s32 delta;
+ /* 0. regsafe() compares the bytes before var_off: there is no hole among them. */
+ u32 unused;
union {
/* valid when type == PTR_TO_PACKET */
int range;
@@ -179,18 +177,9 @@ struct bpf_reg_state {
* the dynptr to determine proper reference freeing.
* Similarly to dynptrs, we use ID to track "belonging" of a reference
* to a specific instance of bpf_iter.
+ * A scalar has no id. The scalars that it is linked to are static: computed before the
+ * main pass, see bpf_scev_next_linked_reg().
*/
- /*
- * Upper bit of ID is used to remember relationship between "linked"
- * registers. Example:
- * r1 = r2; both will have r1->id == r2->id == N
- * r1 += 10; r1->id == N | BPF_ADD_CONST and r1->delta == 10
- * r3 = r2; both will have r3->id == r2->id == N
- * w3 += 10; r3->id == N | BPF_ADD_CONST32 and r3->delta == 10
- */
-#define BPF_ADD_CONST64 (1U << 31)
-#define BPF_ADD_CONST32 (1U << 30)
-#define BPF_ADD_CONST (BPF_ADD_CONST64 | BPF_ADD_CONST32)
u32 id;
/*
* Tracks the parent object this register was derived from.
@@ -1112,27 +1101,18 @@ struct bpf_id_pair {
* comes out for it, only if the same places have the same names.
* - bpf_flow_return() puts the ids of the call that waits back. All other ids get new values.
* - What comes out has the ranges of all calls that share the state at the entry. So a name is good
- * for what holds whatever the ranges are: the same object. Other ids have no name: a number
- * loses its id, any other argument keeps the frames of the caller, see arg_needs_caller().
- * - env->id_gen stays below BPF_MAX_ID. So no id is a name or has a bit of BPF_ADD_CONST.
+ * for what holds whatever the ranges are: the same object. Other ids have no name: such an
+ * argument keeps the frames of the caller, see arg_needs_caller().
+ * - env->id_gen stays below BPF_MAX_ID. So no id is a name.
*/
#define BPF_INHERITED_ID 0x20000000
#define BPF_MAX_ID (BPF_INHERITED_ID / 2)
struct bpf_idmap {
- u32 tmp_id_gen;
u32 cnt;
struct bpf_id_pair map[BPF_ID_MAP_SIZE];
};
-struct bpf_idset {
- u32 num_ids;
- struct {
- u32 id;
- u32 cnt;
- } entries[BPF_ID_MAP_SIZE];
-};
-
struct bpf_liveness;
struct scev;
@@ -1278,10 +1258,7 @@ struct bpf_verifier_env {
* via callx. Allocated when the first such edge is recorded.
*/
unsigned long *callx_edges;
- union {
- struct bpf_idmap idmap_scratch;
- struct bpf_idset idset_scratch;
- };
+ struct bpf_idmap idmap_scratch;
struct {
int *insn_state;
int *insn_stack;
@@ -1447,12 +1424,6 @@ void bpf_verbose_snum32(struct bpf_verifier_env *env, s32 num);
bpf_log(&env->log, "verifier bug: " fmt "\n", ##args); \
})
-static inline void clear_scalar_id(struct bpf_reg_state *reg)
-{
- reg->id = 0;
- reg->delta = 0;
-}
-
static inline void mark_calls_callback(struct bpf_verifier_env *env, int idx)
{
env->insn_aux_data[idx].calls_callback = true;
@@ -1589,7 +1560,6 @@ void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);
void bpf_mark_reg_unknown(struct bpf_reg_state *reg);
int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size);
-void bpf_clear_singular_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
static inline int bpf_get_spi(s32 off)
{
@@ -1902,6 +1872,7 @@ u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);
int bpf_find_subprog(struct bpf_verifier_env *env, int off);
bool bpf_is_throw_kfunc(struct bpf_insn *insn);
+bool bpf_is_dynptr_slice_rdwr_kfunc(struct bpf_insn *insn);
int bpf_compute_const_regs(struct bpf_verifier_env *env);
int bpf_prune_dead_branches(struct bpf_verifier_env *env);
int bpf_check_cfg(struct bpf_verifier_env *env);
@@ -2078,6 +2049,7 @@ int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_
const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);
bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);
bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);
+bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi);
int bpf_compute_live_registers(struct bpf_verifier_env *env);
#define BPF_MAP_KEY_POISON (1ULL << 63)
@@ -2224,6 +2196,13 @@ int bpf_init_scev(struct bpf_verifier_env *env);
void bpf_free_scev(struct bpf_verifier_env *env);
int bpf_compute_scev(struct bpf_verifier_env *env);
int bpf_scev_jump_counts(struct bpf_verifier_env *env, int header, int n, bool taken_leaves);
+bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,
+ u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,
+ u32 *bits);
+bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,
+ s64 *off);
+bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg);
+bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off);
int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
struct bpf_loop_iters *iters);
diff --git a/kernel/bpf/flow.c b/kernel/bpf/flow.c
index c9458b3ad114a5..abbadba1e79f61 100644
--- a/kernel/bpf/flow.c
+++ b/kernel/bpf/flow.c
@@ -2603,10 +2603,9 @@ static bool flow_join_makes_up(const struct bpf_flow *flow, struct bpf_verifier_
struct bpf_verifier_state *b)
{
struct bpf_func_state *fa = a->frame[a->curframe], *fb = b->frame[b->curframe];
- const struct bpf_reg_state *ra, *rb;
+ const struct bpf_reg_state *ra, *rb, *one_a = NULL, *one_b = NULL;
const struct flow_need *tested = flow->need[FLOW_NEED_JUMP], *need;
- u32 fr, i, id = 0;
- bool one = false;
+ u32 fr, i, len = offsetof(struct bpf_reg_state, id);
if (!tested)
return false;
@@ -2623,11 +2622,11 @@ static bool flow_join_makes_up(const struct bpf_flow *flow, struct bpf_verifier_
continue;
if (flow_gap(ra, rb))
return true;
- /* copies of a number are one number */
- if (one && (!id || id != (ra->id & ~BPF_ADD_CONST)))
+ /* copies of a scalar count once: same range and tnum in each state */
+ if (one_a && (memcmp(ra, one_a, len) || memcmp(rb, one_b, len)))
return true;
- one = true;
- id = ra->id & ~BPF_ADD_CONST;
+ one_a = ra;
+ one_b = rb;
}
}
if (!flow_needed_consts_differ(flow, FLOW_NEED_FLAG, a, b))
@@ -2925,8 +2924,6 @@ static struct flow_state *flow_arrive(struct bpf_verifier_env *env, struct bpf_v
flow_free_state(env, s);
return ERR_PTR(err);
}
- /* when the registers that it was shared with are dead, or are those of the caller */
- bpf_clear_singular_ids(env, &s->st);
return s;
}
diff --git a/kernel/bpf/join.c b/kernel/bpf/join.c
index cc4494aef18733..2b8c94b7dc5027 100644
--- a/kernel/bpf/join.c
+++ b/kernel/bpf/join.c
@@ -75,18 +75,16 @@ static void jid_mark_bad(struct bpf_join_state *js, u32 a, u32 b)
js->pairs[i].bad = true;
}
-static void jid_note(struct bpf_join_state *js, u32 ida, u32 idb, bool consistent)
+static void jid_note(struct bpf_join_state *js, u32 a, u32 b)
{
- u32 a = ida & ~BPF_ADD_CONST, b = idb & ~BPF_ADD_CONST;
+ bool consistent, other = false;
struct join_idpair *p;
- bool other = false;
u32 i;
if (!a || !b)
return;
/* a name of what the caller has, see BPF_INHERITED_ID */
- if (a != b && (a | b) >= BPF_INHERITED_ID)
- consistent = false;
+ consistent = a == b || (a | b) < BPF_INHERITED_ID;
for (i = 0; i < js->npairs; i++) {
p = &js->pairs[i];
if (p->a == a && p->b == b) {
@@ -111,15 +109,12 @@ static void jid_note(struct bpf_join_state *js, u32 ida, u32 idb, bool consisten
p->bad = !consistent;
}
-static bool jid_good(struct bpf_join_state *js, u32 ida, u32 idb)
+static bool jid_good(struct bpf_join_state *js, u32 a, u32 b)
{
- u32 a = ida & ~BPF_ADD_CONST, b = idb & ~BPF_ADD_CONST;
u32 i;
if (!a || !b || js->pairs_overflow)
return false;
- if ((ida ^ idb) & BPF_ADD_CONST)
- return false;
for (i = 0; i < js->npairs; i++)
if (js->pairs[i].a == a && js->pairs[i].b == b)
return !js->pairs[i].bad;
@@ -199,15 +194,6 @@ static bool reg_value_equal(const struct bpf_reg_state *ra, const struct bpf_reg
return !memcmp(ra, rb, offsetof(struct bpf_reg_state, id));
}
-static bool scalar_link_consistent(const struct bpf_reg_state *ra, const struct bpf_reg_state *rb)
-{
- if ((ra->id ^ rb->id) & BPF_ADD_CONST)
- return false;
- if ((ra->id & BPF_ADD_CONST) && ra->delta != rb->delta)
- return false;
- return true;
-}
-
/*
* Join two registers, regsafe() documents what each type needs.
* Pass 1 records id pairs, pass 2 computes @dst, which is a copy of @ra on entry.
@@ -229,16 +215,8 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,
case SCALAR_VALUE:
if (js->env->explore_alu_limits && !reg_value_equal(ra, rb))
return false;
- if (pass == 1) {
- jid_note(js, ra->id, rb->id, scalar_link_consistent(ra, rb));
- return true;
- }
- join_range(js, dst, ra, rb);
- /* a link that exists on one side only is dropped */
- if (ra->id && !jid_good(js, ra->id, rb->id)) {
- dst->id = 0;
- dst->delta = 0;
- }
+ if (pass == 2)
+ join_range(js, dst, ra, rb);
return true;
case PTR_TO_MAP_KEY:
case PTR_TO_MAP_VALUE:
@@ -269,7 +247,7 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,
if (ra->r64.base != rb->r64.base)
return false;
if (pass == 1) {
- jid_note(js, ra->id, rb->id, true);
+ jid_note(js, ra->id, rb->id);
return true;
}
if (!jid_strict_ok(js, ra->id, rb->id))
@@ -291,9 +269,9 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,
}
if (pass == 1) {
- jid_note(js, ra->id, rb->id, true);
- jid_note(js, ra->parent_id, rb->parent_id, true);
- jid_note(js, ra->map_uid, rb->map_uid, true);
+ jid_note(js, ra->id, rb->id);
+ jid_note(js, ra->parent_id, rb->parent_id);
+ jid_note(js, ra->map_uid, rb->map_uid);
return true;
}
if (!jid_strict_ok(js, ra->id, rb->id) ||
@@ -350,8 +328,8 @@ static bool join_special_slot(struct bpf_join_state *js, const struct bpf_stack_
break;
}
if (pass == 1) {
- jid_note(js, ra->id, rb->id, true);
- jid_note(js, ra->parent_id, rb->parent_id, true);
+ jid_note(js, ra->id, rb->id);
+ jid_note(js, ra->parent_id, rb->parent_id);
return true;
}
return jid_strict_ok(js, ra->id, rb->id) &&
@@ -563,12 +541,12 @@ static void join_refs_note(struct bpf_join_state *js, const struct bpf_verifier_
{
int i;
- jid_note(js, a->active_irq_id, b->active_irq_id, true);
- jid_note(js, a->active_lock_id, b->active_lock_id, true);
+ jid_note(js, a->active_irq_id, b->active_irq_id);
+ jid_note(js, a->active_lock_id, b->active_lock_id);
for (i = 0; i < a->acquired_refs; i++) {
- jid_note(js, a->refs[i].id, b->refs[i].id, true);
+ jid_note(js, a->refs[i].id, b->refs[i].id);
if (a->refs[i].type == REF_TYPE_PTR)
- jid_note(js, a->refs[i].parent_id, b->refs[i].parent_id, true);
+ jid_note(js, a->refs[i].parent_id, b->refs[i].parent_id);
}
}
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index e930d928afa5b4..63d23d28f2a5c4 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -760,6 +760,19 @@ static void compute_may_write_masks(struct bpf_verifier_env *env)
}
}
+/* live_stack_before of the insn at @insn_idx for one half-slot */
+bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi)
+{
+ struct func_instance *instance;
+ int bkt;
+
+ hash_for_each(env->liveness->func_instances, bkt, instance, hl_node)
+ if (insn_idx - instance->subprog_start < instance->insn_cnt &&
+ is_live_before(instance, insn_idx, instance->depth, half_spi))
+ return true;
+ return false;
+}
+
const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)
{
return env->insn_aux_data[insn_idx].may_write_mask;
@@ -1398,8 +1411,10 @@ static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf
return fill_from_stack(insn, at_out, reg, parent->at, parent->slots, ptr->frame);
}
+ /* A frame holds pointers to its own stack and to the stacks of its callers */
if (ptr->frame == ARG_IMPRECISE && !(ptr->mask & BIT(depth)) && ptr->mask)
- return *ptr;
+ return (struct arg_track){ .mask = GENMASK(fls(ptr->mask) - 1, 0),
+ .frame = ARG_IMPRECISE };
return (struct arg_track){ .frame = ARG_NONE };
}
diff --git a/kernel/bpf/log.c b/kernel/bpf/log.c
index 84659a757b43ca..ffbec587a9166e 100644
--- a/kernel/bpf/log.c
+++ b/kernel/bpf/log.c
@@ -696,7 +696,7 @@ static void print_reg_state(struct bpf_verifier_env *env,
if (state->frameno != reg->frameno)
verbose(env, "[%d]", reg->frameno);
if (tnum_is_const(reg->var_off)) {
- bpf_verbose_snum(env, reg->var_off.value + reg->delta);
+ bpf_verbose_snum(env, reg->var_off.value);
return;
}
}
@@ -704,9 +704,7 @@ static void print_reg_state(struct bpf_verifier_env *env,
verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
verbose(env, "(");
if (reg->id)
- verbose_a("id=%d", reg->id & ~BPF_ADD_CONST);
- if (reg->id & BPF_ADD_CONST)
- verbose(env, "%+d", reg->delta);
+ verbose_a("id=%d", reg->id);
if (reg->parent_id)
verbose_a("parent_id=%d", reg->parent_id);
if (type_is_non_owning_ref(reg->type))
@@ -720,10 +718,6 @@ static void print_reg_state(struct bpf_verifier_env *env,
reg->map_ptr->key_size,
reg->map_ptr->value_size);
}
- if (t != SCALAR_VALUE && reg->delta) {
- verbose_a("off=");
- bpf_verbose_snum(env, reg->delta);
- }
if (type_is_pkt_pointer(t)) {
verbose_a("r=");
verbose_unum(env, reg->range);
diff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c
index 4187ce955be991..e36181a0085852 100644
--- a/kernel/bpf/scev.c
+++ b/kernel/bpf/scev.c
@@ -12,8 +12,13 @@
#include <linux/overflow.h>
#define REGS_NUM BPF_SCEV_REGS_NUM
+/* The SCEV registers of an env: r0 - r10, the stack slots and memory locations, see struct env */
+#define MEM_REGS_NUM 16
+#define ENV_REGS_NUM (REGS_NUM + MEM_REGS_NUM)
#define UNKNOWN_EXPR_ID 0
#define OPAQUE_EXPR_ID 1
+/* (REG r). UNKNOWN, OPAQUE and (REG r) have fixed ids and are not in the hash table. */
+#define REG_EXPR_ID(r) (2 + (r))
/*
* BPF instructions use 'code', 'src_reg', 'off' and 'imm' fields for instruction encoding.
@@ -44,34 +49,100 @@ enum expr_op {
*/
LINEAR_SCEV,
/*
- * param[1], given that register param[0] and the register that param[1] starts from are
- * equal when the loop is entered. Not known otherwise.
+ * (add rB rC) is the SCEV of rA: rA == rB + rC at the header in every iteration. rB and rC
+ * are the header phis here, not the entry values as below LINEAR_SCEV.
*/
- COPY_SCEV,
+ ADD_SCEV,
};
+/*
+ * An SSA name for a value that no expression describes: the def of the SCEV register 'reg'
+ * - by the insn at 'idx'. An insn that may write defines too (may_def in liveness.c). A nested loop
+ * defines at its header what it leaves.
+ * - by a phi before the insn at 'idx': a join point, a loop header.
+ * Without its backedges and with nested loops collapsed the body of a loop is acyclic: an insn
+ * executes at most once per iteration, so a def is one value per iteration. A name is unique within
+ * the env of one loop.
+ * The operands of a phi are a set, 8 at most; a phi(a, b) among them is expanded. They have no
+ * defs, see strip_defs(): (+ r6 %r2.4) and (+ r6 %r2.7) are one operand, (+ r6 _). So they don't
+ * tell one phi from another: phis are value numbered by their bases, see mk_phi().
+ * In the env of loop H a phi at H merges the backedge values only, the header phi itself is
+ * (REG r). In the env of the enclosing loop a phi at H merges the entering edges.
+ * Op and params of a def by an insn are what that insn computes, see alu64_with_def():
+ * set_expr_base() and match_linked_add() look through such an add, split_const_offset() and
+ * match_linked_add() check prevent_zext of the insn. Those of a phi are the shape that its operands
+ * share, no insn computes them: nothing looks through a phi.
+ */
+struct expr_def {
+ u32 set:1; /* 0: the expression has no def */
+ u32 phi:1;
+ u32 reg:9;
+ u32 idx:21;
+};
+/* def.reg of the phi of two bases, see mk_phi() */
+#define BASE_REG ENV_REGS_NUM
+static_assert(BASE_REG < 1 << 9 && BPF_COMPLEXITY_LIMIT_INSNS <= 1 << 21);
+
+static const struct expr_def no_def;
+
struct expr {
- u32 op;
+ u16 op;
+ /* A value number: all SCEV registers of an env that have this id hold the same value */
+ bool is_vn;
+ /* expr == base + off (mod 2^bits), see split_const_offset() */
+ u8 bits;
+ /*
+ * UNKNOWN, OPAQUE and ANY don't describe a value. With a def the id stands for one value,
+ * see struct expr_def. Without a def every use of the id can be another value.
+ */
+ struct expr_def def;
union {
u32 params[2];
s64 imm;
};
-};
-
-struct expr_bucket {
- u32 cnt;
- u32 cap;
- u32 ids[];
+ u32 base;
+ /*
+ * id of the first add on the way to 'base' whose insn may still become ALU32, see
+ * prevent_zext. 0: none
+ */
+ u32 arena_add;
+ s64 off;
};
struct env {
bool empty;
- u32 reg2expr[REGS_NUM];
+ u32 reg2expr[ENV_REGS_NUM];
u32 reg2scev[REGS_NUM];
+ /*
+ * Register promotion of memory that is not behind r10. The SCEV register REGS_NUM + i is
+ * the memory at the address mem_addr[i], a value number of this env. 0: not in use.
+ * - A store through a pointer defines it like a spill defines a stack slot.
+ * - A load defines its register as before, and the memory gets that value number: it holds
+ * what a store of the register would leave. No expression of a register depends on
+ * memory, which is private only if it is stack. That is not known here.
+ * - A join point has a phi. An insn that may write is a may-def, see forget_mem_regs().
+ * - A store through r10 is not: the main pass takes the stack of a caller only.
+ * A value number of a loop means nothing in the enclosing loop: no memory is tracked at
+ * a header, a nested loop is a may-def.
+ */
+ u32 mem_addr[MEM_REGS_NUM];
+};
+
+/*
+ * A SCEV register and the id of its expression before a conditional jump. 'addr' is mem_addr[] of
+ * a memory location.
+ */
+struct scev_linked_reg {
+ u32 reg;
+ u32 id;
+ u32 addr;
};
struct insn_envs {
u32 cnt;
+ /* The linked registers of a jump, see find_linked_regs(): linked_cnt of scev->linked[] */
+ u32 linked_first;
+ u32 linked_cnt;
struct {
int loop_header;
struct env *env;
@@ -92,87 +163,216 @@ struct scev {
/* Read-only representatives for stack slots without a saved register. */
struct bpf_reg_state zero_reg;
struct bpf_reg_state unknown_reg;
+ /* r -> (REG r): before the first insn of a loop every SCEV register is its header phi */
+ struct env identity_env;
/*
* Expressions are identified by id, exprs_ht ensures that
* each expression exists as a unique instance.
* This allows for fast equivalence check: id1 === id2.
+ * exprs_ht[hash] is the first id of a chain, exprs_next[id] is the next one, 0 ends it.
+ * Both have exprs_cap elements, like exprs[].
*/
- struct expr_bucket **exprs_ht;
+ u32 *exprs_ht;
+ u32 *exprs_next;
struct scev_worklist worklist;
struct insn_envs **envs;
struct expr *exprs;
+ struct scev_linked_reg *linked;
+ /* The stack slots that a store through a dynptr slice may alias, see expr_is_vn() */
+ DECLARE_BITMAP(slice_slots, MAX_BPF_STACK_SLOTS);
/*
* Loops are analyzed one by one, this array keeps track if a particular
* instruction was visited on a current pass.
*/
u32 *discovered;
- u32 exprs_ht_cnt;
int exprs_cnt;
int exprs_cap;
+ u32 linked_cnt;
+ u32 linked_cap;
int envs_cnt;
int stack_sz;
+ int simplify_depth;
struct expr_stack_elt expr_stack[EXPR_STACK_DEPTH];
u32 ids_buf[EXPR_STACK_DEPTH];
};
static u32 expr_hash(struct expr *e)
{
- return jhash_3words(e->op, e->params[0], e->params[1], 0);
+ /* def.phi is not hashed: the def by an insn and the phi before it share a chain */
+ return jhash_3words(e->op, e->params[0], e->params[1],
+ e->def.idx * REGS_NUM + e->def.reg);
}
-static int expr_eq(struct expr *a, struct expr *b)
+static bool same_def(struct expr_def a, struct expr_def b)
{
- return a->op == b->op && a->imm == b->imm;
+ return a.set == b.set && a.phi == b.phi && a.reg == b.reg && a.idx == b.idx;
}
-static int add_expr(struct scev *scev, struct expr e)
+/* Is @e the expression @id? The base of a phi is a part of its key. 0: the phi is its own base. */
+static int expr_eq(struct scev *scev, struct expr *e, u32 id)
+{
+ struct expr *x = &scev->exprs[id];
+
+ if (e->op != x->op || e->imm != x->imm || !same_def(e->def, x->def))
+ return false;
+ if (!e->def.phi)
+ return true;
+ return e->base ? e->base == x->base && e->off == x->off : x->base == id;
+}
+
+static void exprs_ht_add(struct scev *scev, u32 id)
+{
+ u32 *bucket = &scev->exprs_ht[expr_hash(&scev->exprs[id]) & (scev->exprs_cap - 1)];
+
+ scev->exprs_next[id] = *bucket;
+ *bucket = id;
+}
+
+/* @cap is a power of two. No warning for a size that kvmalloc() rejects. */
+static int grow_exprs(struct scev *scev, u32 cap)
{
- struct expr_bucket *bucket;
- u32 i, id, hash, new_cap;
+ gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_NOWARN;
void *tmp;
+ u32 id;
- hash = expr_hash(&e) & (scev->exprs_ht_cnt - 1);
- bucket = scev->exprs_ht[hash];
+ tmp = kvrealloc(scev->exprs, array_size(cap, sizeof(*scev->exprs)), gfp);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs = tmp;
+ tmp = kvrealloc(scev->exprs_next, array_size(cap, sizeof(u32)), gfp);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs_next = tmp;
+ tmp = kvrealloc(scev->exprs_ht, array_size(cap, sizeof(u32)), gfp);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs_ht = tmp;
+ scev->exprs_cap = cap;
+ memset(scev->exprs_ht, 0, array_size(cap, sizeof(u32)));
+ for (id = REG_EXPR_ID(REGS_NUM); id < scev->exprs_cnt; id++)
+ exprs_ht_add(scev, id);
+ return 0;
+}
- if (bucket) {
- for (i = 0; i < bucket->cnt; i++) {
- id = bucket->ids[i];
- if (expr_eq(&e, &scev->exprs[id]))
- return id;
- }
- }
+static u32 op_params_num(u32 op);
- if (!bucket || bucket->cap == bucket->cnt) {
- new_cap = bucket ? bucket->cap * 2 : 4;
- bucket = kvrealloc(bucket, sizeof(*bucket) + sizeof(u32) * new_cap, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
- if (!bucket)
- return -ENOMEM;
- scev->exprs_ht[hash] = bucket;
- bucket->cap = new_cap;
- }
+static bool expr_is_vn(struct scev *scev, struct expr *e)
+{
+ u32 i, reg = e->def.reg;
- if (scev->exprs_cnt == scev->exprs_cap) {
- new_cap = scev->exprs_cap ? scev->exprs_cap * 2 : 256;
- tmp = kvrealloc(scev->exprs, sizeof(struct expr) * new_cap, GFP_KERNEL_ACCOUNT);
- if (!tmp)
- return -ENOMEM;
- scev->exprs = tmp;
- scev->exprs_cap = new_cap;
+ /*
+ * bpf_dynptr_slice_rdwr() can return the buffer that it got. A store through that slice may
+ * alias the slots of the buffer and is in no bpf_may_write_mask(): it is no def, so a def
+ * of such a slot is no value number. A spill through r10 has the expression of the
+ * register, and invalidate_stack_slices() invalidates the slices there. The next slice
+ * comes from a call that may write to the slot.
+ */
+ if (e->def.set)
+ return reg < MAX_BPF_REG || reg >= REGS_NUM ||
+ !test_bit(reg - MAX_BPF_REG, scev->slice_slots);
+ switch (e->op) {
+ case UNKNOWN:
+ case OPAQUE:
+ case ANY:
+ /* a partial spill: the other bits of the slot are not known */
+ case SPILL8:
+ case SPILL16:
+ case SPILL32:
+ /* a function of the iteration number */
+ case LINEAR_SCEV:
+ /* a relation between header phis */
+ case ADD_SCEV:
+ return false;
}
+ for (i = 0; i < op_params_num(e->op); i++)
+ if (!scev->exprs[e->params[i]].is_vn)
+ return false;
+ return true;
+}
+
+static u32 op_low_bits(u32 op);
+
+/*
+ * @e gets the id @id. (+ x imm), an extension and a partial spill of x have the base of x, which
+ * was constructed earlier. Every other expression is its own base. So split_const_offset() does not
+ * traverse the expression.
+ */
+static void set_expr_base(struct scev *scev, struct expr *e, u32 id)
+{
+ u32 low = op_low_bits(e->op);
+ struct expr *x;
+ s64 imm = 0;
+
+ e->arena_add = 0;
+ /* mk_phi() found the base */
+ if (e->def.phi && e->base)
+ return;
+ e->base = id;
+ e->off = 0;
+ e->bits = 64;
+ /* nothing looks through a phi, see struct expr_def */
+ if (e->def.phi)
+ return;
+ if (e->op == BPF_ADD && scev->exprs[e->params[1]].op == IMM)
+ imm = scev->exprs[e->params[1]].imm;
+ else if (!low || e->def.set)
+ return;
+ x = &scev->exprs[e->params[0]];
+ e->base = x->base;
+ e->off = (u64)x->off + imm;
+ e->bits = low ? min(x->bits, low) : x->bits;
+ e->arena_add = e->def.set ? id : x->arena_add;
+}
+
+static int add_expr(struct scev *scev, struct expr e)
+{
+ u32 id;
+
+ if (e.op == REG)
+ return REG_EXPR_ID(e.params[0]);
+ if (!e.def.set && !e.imm && (e.op == UNKNOWN || e.op == OPAQUE))
+ return e.op == UNKNOWN ? UNKNOWN_EXPR_ID : OPAQUE_EXPR_ID;
+
+ id = scev->exprs_ht[expr_hash(&e) & (scev->exprs_cap - 1)];
+ for (; id; id = scev->exprs_next[id])
+ if (expr_eq(scev, &e, id))
+ return id;
+
+ if (scev->exprs_cnt == scev->exprs_cap && grow_exprs(scev, scev->exprs_cap * 2))
+ return -ENOMEM;
id = scev->exprs_cnt++;
+ e.is_vn = expr_is_vn(scev, &e);
+ set_expr_base(scev, &e, id);
scev->exprs[id] = e;
- bucket->ids[bucket->cnt++] = id;
+ exprs_ht_add(scev, id);
return id;
}
+static int simplify(struct scev *scev, u32 id);
+
+/*
+ * An expression is simplified at construction. Its params are simplified already, so simplify()
+ * rewrites the root only, whatever the depth of the expression.
+ * The rules construct expressions too, and one rule can enable the next: the depth of (zext32
+ * (spill32 (+ (spill32 (+ ..) 1)) 1)) is up to the prog. Beyond depth EXPR_STACK_DEPTH an
+ * expression is correct, but not simplified.
+ */
static int expr2(struct scev *scev, u32 op, int a, int b)
{
+ int id;
+
if (a < 0)
return a;
if (b < 0)
return b;
- return add_expr(scev, (struct expr){ .op = op, .params = {a, b} });
+ id = add_expr(scev, (struct expr){ .op = op, .params = {a, b} });
+ if (id < 0 || scev->simplify_depth == EXPR_STACK_DEPTH)
+ return id;
+ scev->simplify_depth++;
+ id = simplify(scev, id);
+ scev->simplify_depth--;
+ return id;
}
static int expr1(struct scev *scev, u32 op, int a)
@@ -182,14 +382,38 @@ static int expr1(struct scev *scev, u32 op, int a)
return expr2(scev, op, a, 0);
}
-static int expr0(struct scev *scev, u32 op)
+static int imm_expr(struct scev *scev, s64 value)
{
- return expr2(scev, op, 0, 0);
+ return add_expr(scev, (struct expr){ .op = IMM, .imm = value });
}
-static int imm_expr(struct scev *scev, s64 value)
+/*
+ * The insn at @idx defines @reg. Without its backedges and with nested loops collapsed the body is
+ * acyclic: an insn executes at most once per iteration, so a def is one value per iteration. A
+ * subprog is the outermost loop, which runs once.
+ */
+static struct expr_def insn_def(int idx, u32 reg)
{
- return add_expr(scev, (struct expr){ .op = IMM, .imm = value });
+ return (struct expr_def){ .set = 1, .reg = reg, .idx = idx };
+}
+
+/* The phi of @reg before the insn at @idx. One value per iteration for the same reason. */
+static struct expr_def phi_def(int idx, u32 reg)
+{
+ return (struct expr_def){ .set = 1, .phi = 1, .reg = reg, .idx = idx };
+}
+
+/* @id with another def */
+static int expr_with_def(struct scev *scev, int id, struct expr_def def)
+{
+ struct expr e;
+
+ if (id < 0)
+ return id;
+ e = scev->exprs[id];
+ e.def = def;
+ e.base = 0;
+ return add_expr(scev, e);
}
static bool same_exprs(struct scev *scev, int id_a, int id_b)
@@ -244,31 +468,74 @@ static bool is_zext32(struct scev *scev, int id, u32 *left)
return is_unop(scev, ZEXT32, id, left);
}
-/* The low half of the slot is the low half of @left. The other half is not known. */
-static bool is_spill32(struct scev *scev, int id, u32 *left)
+/* (zextN x), (sextN x) and (spillN x) depend on the low N bits of x only */
+static u32 op_low_bits(u32 op)
+{
+ switch (op) {
+ case ZEXT8:
+ case SEXT8:
+ case SPILL8:
+ return 8;
+ case ZEXT16:
+ case SEXT16:
+ case SPILL16:
+ return 16;
+ case ZEXT32:
+ case SEXT32:
+ case SPILL32:
+ return 32;
+ }
+ return 0;
+}
+
+/* The low @bits bits of the slot are those of @left. The other bits are not known. */
+static bool is_spill(struct scev *scev, int id, u32 *bits, u32 *left)
{
+ u32 op = scev->exprs[id].op;
+
#ifdef __BIG_ENDIAN
/* '*(u32 *)(r10 - 8) = rX' writes the high half, see mk_fill() */
return false;
#endif
- return is_unop(scev, SPILL32, id, left);
+ if (op != SPILL8 && op != SPILL16 && op != SPILL32)
+ return false;
+ *bits = op_low_bits(op);
+ *left = scev->exprs[id].params[0];
+ return true;
}
-static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)
+static bool is_spill32(struct scev *scev, int id, u32 *left)
{
- return is_binop(scev, ANY, id, left, right);
+ u32 bits;
+
+ return is_spill(scev, id, &bits, left) && bits == 32;
}
-static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)
+/* (zextN x), (sextN x) or (spillN x) with N >= @bits: the low @bits bits are those of @left */
+static bool is_low_bits(struct scev *scev, int id, u32 bits, u32 *left)
{
- return is_binop(scev, LINEAR_SCEV, id, base, slope);
+ u32 op = scev->exprs[id].op;
+
+#ifdef __BIG_ENDIAN
+ /* see is_spill() */
+ if (op == SPILL8 || op == SPILL16 || op == SPILL32)
+ return false;
+#endif
+ /* nothing looks through a phi, see struct expr_def */
+ if (op_low_bits(op) < bits || scev->exprs[id].def.phi)
+ return false;
+ *left = scev->exprs[id].params[0];
+ return true;
}
-static bool is_copy(struct scev *scev, int id, u32 *reg, u32 *orig)
+static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)
{
- u32 t;
+ return is_binop(scev, ANY, id, left, right);
+}
- return is_binop(scev, COPY_SCEV, id, &t, orig) && is_reg(scev, t, reg);
+static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)
+{
+ return is_binop(scev, LINEAR_SCEV, id, base, slope);
}
static bool is_linear_or_linear32(struct scev *scev, int id, u32 *base, u32 *slope, bool *zext32)
@@ -296,8 +563,10 @@ static void log_reg(struct bpf_verifier_env *env, u32 reg)
{
if (reg < MAX_BPF_REG)
bpf_log(&env->log, "r%d", reg);
- else
+ else if (reg < REGS_NUM)
bpf_log(&env->log, "*fp%d", (MAX_BPF_REG - reg - 1) * 8);
+ else
+ bpf_log(&env->log, "mem%d", reg - REGS_NUM);
}
static const char *op_str(u32 op)
@@ -331,7 +600,7 @@ static const char *op_str(u32 op)
case SPILL32: return "spill32";
case ANY: return "any";
case LINEAR_SCEV: return "linear";
- case COPY_SCEV: return "copy";
+ case ADD_SCEV: return "add";
}
return NULL;
}
@@ -354,7 +623,7 @@ static u32 op_params_num(u32 op)
case SMOD:
case ANY:
case LINEAR_SCEV:
- case COPY_SCEV:
+ case ADD_SCEV:
return 2;
case BPF_NEG:
case SEXT8:
@@ -428,27 +697,74 @@ static bool expr_next(struct scev *scev, u32 *id, u32 *order)
return expr_next(scev, id, order);
}
+/*
+ * An SSA name is printed as '%', the SCEV register, '.', the insn. A def is printed in full at
+ * every use: (+ %r8.7=phi(1, 2) 4).
+ * %r0.6 insn 6 defines r0. The value is OPAQUE, '_' without a def
+ * %fp-8.8? insn 8 may write fp-8. The value is UNKNOWN, '?' without a def
+ * %r8.7=phi(1, 2) the phi of r8 before insn 7
+ * %r0.7=phi(_) a phi of distinct OPAQUE values
+ * %r6.9=phi(?) a phi of distinct UNKNOWN values, or of more than 8 values
+ * %r2.12=(+ x 4) insn 12 defines r2, see alu64_with_def()
+ * %r2.25=phi((+ x 4)) two adds of one shape, each may have been converted to ALU32:
+ * the phi is not (+ x 4)
+ * A name is unique within the env of one loop. In the env of loop H a phi at H merges the backedge
+ * values only, the header phi itself is (REG r): in 'scev at header 1: r6=%r6.1=phi(r6, (+ r6 1))'
+ * one backedge leaves r6 as it is, the other one adds 1.
+ * '%' in front of r or fp is a name, followed by a blank it is BPF_MOD.
+ */
+static void log_def(struct bpf_verifier_env *env, struct expr_def def)
+{
+ if (!def.set)
+ return;
+ if (def.reg < MAX_BPF_REG)
+ bpf_log(&env->log, "%%r%d.%d", def.reg, def.idx);
+ else if (def.reg < REGS_NUM)
+ bpf_log(&env->log, "%%fp%d.%d", (MAX_BPF_REG - def.reg - 1) * 8, def.idx);
+ else
+ bpf_log(&env->log, "%%mem%d.%d", def.reg - REGS_NUM, def.idx);
+}
+
static void log_expr(struct bpf_verifier_env *env, u32 id)
{
struct bpf_verifier_log *log = &env->log;
+ bool operand, bare, first = false;
struct scev *scev = env->scev;
+ u32 order, d, bare_any = 0;
+ struct expr_def def;
struct expr *expr;
const char *str;
- u32 order;
scev->stack_sz = 0;
expr_stack_push(scev, id);
while (expr_next(scev, &id, &order)) {
- if ((order & PRE) && scev->stack_sz > 1)
- bpf_log(log, " ");
expr = &scev->exprs[id];
+ def = expr->def;
+ /* the depth of @id in expr_stack[], expr_next() pops it before POST */
+ d = order & PRE ? scev->stack_sz - 1 : scev->stack_sz;
+ operand = d && (bare_any & BIT(d - 1));
+ /* No '(any' for the operands of phi(a, b). (any a b) among them is expanded. */
+ if (order & PRE) {
+ bare_any &= ~BIT(d);
+ if (expr->op == ANY && (def.set ? def.phi : operand))
+ bare_any |= BIT(d);
+ }
+ bare = bare_any & BIT(d);
+ if ((order & PRE) && (def.set || !bare)) {
+ if (d)
+ bpf_log(log, "%s", !operand ? " " : first ? "" : ", ");
+ log_def(env, def);
+ if (def.phi)
+ bpf_log(log, "=phi(");
+ first = bare;
+ }
switch (expr->op) {
case UNKNOWN:
if (order & PRE)
bpf_log(log, "?");
break;
case OPAQUE:
- if (order & PRE)
+ if ((order & PRE) && (!def.set || def.phi))
bpf_log(log, "_");
break;
case REG:
@@ -460,19 +776,23 @@ static void log_expr(struct bpf_verifier_env *env, u32 id)
bpf_log(log, "%lld", expr->imm);
break;
default:
- if (order & PRE) {
+ if ((order & PRE) && !bare) {
str = op_str(expr->op);
- bpf_log(log, "(");
+ bpf_log(log, def.set && !def.phi ? "=(" : "(");
if (str)
bpf_log(log, "%s", str);
else
bpf_log(log, "bad-expr-op %x", expr->op);
}
- if (order & DEPTH_LIMIT)
- bpf_log(log, "...");
- if (order & POST)
+ if (order & DEPTH_LIMIT) {
+ bpf_log(log, bare && !def.set && !first ? ", ..." : "...");
+ first = false;
+ }
+ if ((order & POST) && !bare)
bpf_log(log, ")");
}
+ if ((order & POST) && def.phi)
+ bpf_log(log, ")");
}
}
@@ -481,11 +801,27 @@ static bool reg_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)
struct bpf_insn_aux_data *aux = env->insn_aux_data;
u16 live_regs = aux[insn_idx].live_regs_before;
+ /* memory */
+ if (reg >= REGS_NUM)
+ return true;
return reg < MAX_BPF_REG
? (BIT(reg) & live_regs)
: test_bit(reg - MAX_BPF_REG, aux[insn_idx].live_stack_before);
}
+/* The first bytes of a stack slot are its high bits */
+static bool is_big_endian_slot(u32 reg)
+{
+ return IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) && reg >= MAX_BPF_REG;
+}
+
+/* Are the upper 32 bits of @reg live before the insn at @insn_idx? */
+static bool hi32_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)
+{
+ return reg < MAX_BPF_REG || is_big_endian_slot(reg) ||
+ bpf_half_slot_live_before(env, insn_idx, (reg - MAX_BPF_REG) * 2);
+}
+
static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx)
{
struct bpf_verifier_log *log = &env->log;
@@ -512,7 +848,7 @@ static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx)
log_reg(env, i);
bpf_log(log, "=");
log_expr(env, e->reg2expr[i]);
- if (e->reg2expr[i] != UNKNOWN_EXPR_ID) {
+ if (!is_op(scev, e->reg2expr[i], UNKNOWN)) {
bpf_log(log, " / ");
log_expr(env, e->reg2scev[i]);
}
@@ -554,7 +890,7 @@ static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx
if (!e)
return NULL;
- tmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT);
+ tmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT | __GFP_ZERO);
if (!tmp) {
kfree(e);
return NULL;
@@ -568,6 +904,25 @@ static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx
return e;
}
+/* The env has no users any more */
+static void free_loop_env(struct scev *scev, int loop_header, int insn_idx)
+{
+ struct insn_envs *envs = scev->envs[insn_idx];
+ u32 i;
+
+ for (i = 0; i < envs->cnt; i++) {
+ if (envs->entries[i].loop_header != loop_header)
+ continue;
+ kfree(envs->entries[i].env);
+ envs->entries[i] = envs->entries[--envs->cnt];
+ break;
+ }
+ if (envs->cnt || envs->linked_cnt)
+ return;
+ kfree(envs);
+ scev->envs[insn_idx] = NULL;
+}
+
static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)
{
if (id < 0)
@@ -576,10 +931,15 @@ static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)
return 0;
}
-static int setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, int insn_idx)
+/* The insn at @idx defines @reg. The value is not tracked: @id is UNKNOWN or OPAQUE. */
+static int forget_reg(struct scev *scev, struct env *e, u32 reg, int id, int idx)
{
- struct scev *scev = env->scev;
- int i, err;
+ return replace_reg(scev, e, reg, expr_with_def(scev, id, insn_def(idx, reg)));
+}
+
+static void setup_initial_loop_env(struct env *e)
+{
+ int i;
/*
* Initial assignments are of form rX -> rX are needed as seeds for subsequent
@@ -587,25 +947,29 @@ static int setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, i
* join() will overwrite the them. compute_header_scevs() accounts for register
* states at loop entry.
*/
- for (i = 0; i < REGS_NUM; i++) {
- err = replace_reg(scev, e, i, expr1(scev, REG, i));
- if (err)
- return err;
- }
- return 0;
+ for (i = 0; i < REGS_NUM; i++)
+ e->reg2expr[i] = REG_EXPR_ID(i);
}
-static void forget_call_regs(struct env *e)
+/* A subprog can return a pair in r0 and r2: a call defines r1 - r5 too if they are live after it */
+static int forget_call_regs(struct bpf_verifier_env *env, struct env *e, int idx)
{
- int i;
+ int i, err;
- for (i = BPF_REG_0; i <= BPF_REG_5; i++)
+ for (i = BPF_REG_0; i <= BPF_REG_5; i++) {
e->reg2expr[i] = UNKNOWN_EXPR_ID;
+ if (idx + 1 >= env->prog->len || !reg_alive_at(env, i, idx + 1))
+ continue;
+ err = forget_reg(env->scev, e, i, UNKNOWN_EXPR_ID, idx);
+ if (err)
+ return err;
+ }
+ return 0;
}
static u32 spill_spi(struct bpf_insn *insn)
{
- return -insn->off / BPF_REG_SIZE - 1;
+ return (-insn->off - 1) / BPF_REG_SIZE;
}
static u32 off_to_reg(struct bpf_insn *insn)
@@ -620,16 +984,19 @@ static bool is_spill_off(int off)
off >= -MAX_BPF_STACK_JIT;
}
-static void mark_opaque(struct env *e, int off, int size)
+static int mark_opaque(struct scev *scev, struct env *e, int idx, int off, int size)
{
- int b, spi;
+ int b, spi, err;
for (b = off; b < off + size; b++) {
if (b >= 0 || b < -MAX_BPF_STACK_JIT)
continue;
spi = (-b - 1) / BPF_REG_SIZE;
- e->reg2expr[MAX_BPF_REG + spi] = OPAQUE_EXPR_ID;
+ err = forget_reg(scev, e, MAX_BPF_REG + spi, OPAQUE_EXPR_ID, idx);
+ if (err)
+ return err;
}
+ return 0;
}
static int mk_spill(struct scev *scev, u8 size, int id)
@@ -643,18 +1010,40 @@ static int mk_spill(struct scev *scev, u8 size, int id)
return UNKNOWN_EXPR_ID;
}
-static int mk_fill(struct scev *scev, int id, u8 code)
+/* The size of the spill in a slot with the expression @id. It holds the low bytes of *@x. */
+static u32 expr_spill_size(struct scev *scev, u32 id, u32 *x)
{
- bool sx = BPF_MODE(code) == BPF_MEMSX;
+ struct expr *e = &scev->exprs[id];
+ /* nothing looks through a phi, see struct expr_def */
+ bool partial = (e->op == SPILL8 || e->op == SPILL16 || e->op == SPILL32) && !e->def.phi;
+ *x = partial ? e->params[0] : id;
+ return partial ? op_low_bits(e->op) / BITS_PER_BYTE : BPF_REG_SIZE;
+}
+
+/* -ENOENT: the value of the fill is not known */
+static int mk_fill(struct scev *scev, int id, struct bpf_insn *insn)
+{
+ u32 x, spill_size = expr_spill_size(scev, id, &x);
+ u32 size = bpf_size_to_bytes(BPF_SIZE(insn->code));
+ bool sx = BPF_MODE(insn->code) == BPF_MEMSX;
+
+ /* The fill reads the low bytes of the spill, as in check_stack_read_fixed_off() */
+ if (size <= spill_size && bpf_stack_narrow_access_ok(insn->off, size, spill_size))
+ id = x;
+ else if (!is_spill_off(insn->off))
+ return -ENOENT;
#ifdef __BIG_ENDIAN
+ /* No register becomes (spillN x): its low bits would not be those of x */
+ else if (spill_size < BPF_REG_SIZE)
+ return -ENOENT;
/* A narrow fill reads the high bits of the slot on big-endian. */
- if (BPF_SIZE(code) != BPF_DW)
+ else
return expr2(scev, sx ? BPF_ARSH : BPF_RSH, id,
- imm_expr(scev, 64 - BITS_PER_BYTE * bpf_size_to_bytes(BPF_SIZE(code))));
+ imm_expr(scev, BITS_PER_BYTE * (BPF_REG_SIZE - size)));
#endif
- switch (BPF_SIZE(code)) {
+ switch (BPF_SIZE(insn->code)) {
case BPF_B: return expr1(scev, sx ? SEXT8 : ZEXT8, id);
case BPF_H: return expr1(scev, sx ? SEXT16 : ZEXT16, id);
case BPF_W: return expr1(scev, sx ? SEXT32 : ZEXT32, id);
@@ -663,7 +1052,7 @@ static int mk_fill(struct scev *scev, int id, u8 code)
return UNKNOWN_EXPR_ID;
}
-static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int id)
+static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int idx, int id)
{
u8 size = BPF_SIZE(insn->code);
@@ -671,25 +1060,205 @@ static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *ins
return 0;
if (is_spill_off(insn->off))
return replace_reg(scev, e, off_to_reg(insn), mk_spill(scev, size, id));
- mark_opaque(e, insn->off, bpf_size_to_bytes(size));
- return 0;
+ return mark_opaque(scev, e, idx, insn->off, bpf_size_to_bytes(size));
}
-static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn)
+static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int idx)
{
- int id;
+ int id = -ENOENT;
- if (insn->src_reg == BPF_REG_FP && is_spill_off(insn->off))
- id = mk_fill(scev, e->reg2expr[off_to_reg(insn)], insn->code);
- else
- id = OPAQUE_EXPR_ID;
+ if (insn->src_reg == BPF_REG_FP && insn->off < 0 && insn->off >= -MAX_BPF_STACK_JIT)
+ id = e->reg2expr[off_to_reg(insn)];
+ /*
+ * The def of a slot that a slice may alias is no value number, see expr_is_vn(): two fills
+ * can read distinct values. One fill reads one value: the insn defines the register.
+ */
+ if (id >= 0 && scev->exprs[id].def.set && !scev->exprs[id].is_vn)
+ id = -ENOENT;
+ if (id >= 0)
+ id = mk_fill(scev, id, insn);
+ if (id == -ENOENT)
+ return forget_reg(scev, e, insn->dst_reg, OPAQUE_EXPR_ID, idx);
return replace_reg(scev, e, insn->dst_reg, id);
}
+static bool const_diff(struct bpf_verifier_env *env, int h, u32 id_a, u32 id_b, s64 *delta,
+ u32 *bits);
+
+/* The memory location of @e at the address @addr, 0: one that is not in use. MEM_REGS_NUM: none. */
+static u32 find_mem_reg(const struct env *e, u32 addr)
+{
+ u32 i;
+
+ for (i = 0; i < MEM_REGS_NUM && e->mem_addr[i] != addr; i++)
+ ;
+ return i;
+}
+
+static void forget_mem_reg(struct env *e, u32 i)
+{
+ e->mem_addr[i] = 0;
+ e->reg2expr[REGS_NUM + i] = UNKNOWN_EXPR_ID;
+}
+
+/*
+ * The insn may write @size bytes at the address @addr, 0: anywhere. A may-def of all memory
+ * locations but those that have the same address base and don't overlap. Two bases can be two names
+ * of one memory, 'f(&c, &c)'.
+ */
+static void forget_mem_regs(struct bpf_verifier_env *env, struct env *e, u32 addr, u32 size)
+{
+ u32 i, x, bits;
+ s64 delta;
+
+ for (i = 0; i < MEM_REGS_NUM; i++) {
+ /* the caller defines it */
+ if (e->mem_addr[i] == addr)
+ continue;
+ if (addr && const_diff(env, -1, addr, e->mem_addr[i], &delta, &bits) &&
+ bits == 64 && (delta >= size ||
+ delta + expr_spill_size(env->scev, e->reg2expr[REGS_NUM + i], &x) <= 0))
+ continue;
+ forget_mem_reg(e, i);
+ }
+}
+
+/*
+ * A jump tests a register, and a load makes a new value number. So a memory location is dead once
+ * no register that is live after the insn at @idx has the base of its value: no jump is going to
+ * link it.
+ */
+static void forget_dead_mem_regs(struct bpf_verifier_env *env, struct env *e, int idx)
+{
+ struct expr *exprs = env->scev->exprs;
+ u32 i, r, base;
+
+ for (i = 0; i < MEM_REGS_NUM; i++) {
+ base = exprs[e->reg2expr[REGS_NUM + i]].base;
+ for (r = 0; r < REGS_NUM; r++)
+ if (exprs[e->reg2expr[r]].base == base && reg_alive_at(env, r, idx + 1))
+ break;
+ if (r == REGS_NUM)
+ forget_mem_reg(e, i);
+ }
+}
+
+/*
+ * The address of the load or store at @idx through @reg, 0: the memory is not tracked. r10 has the
+ * stack slots, r11 and r12 are no SCEV registers. The main pass takes nothing but stack.
+ */
+static int mk_mem_addr(struct bpf_verifier_env *env, struct env *e, int idx, u32 reg)
+{
+ struct scev *scev = env->scev;
+
+ if (reg >= BPF_REG_FP || !(env->insn_aux_data[idx].stack_ptrs & BIT(reg)) ||
+ !scev->exprs[e->reg2expr[reg]].is_vn)
+ return 0;
+ return expr2(scev, BPF_ADD, e->reg2expr[reg], imm_expr(scev, env->prog->insnsi[idx].off));
+}
+
+/*
+ * The insn at @idx stored the low bytes of @id at the address @addr, or it loaded them from there.
+ * The location takes a SCEV register that is not in use, or that of a dead one.
+ */
+static int replace_mem_reg(struct bpf_verifier_env *env, struct env *e, int idx, int addr, int id)
+{
+ u32 i;
+
+ if (addr <= 0)
+ return addr;
+ i = find_mem_reg(e, addr);
+ if (i == MEM_REGS_NUM)
+ i = find_mem_reg(e, 0);
+ if (i == MEM_REGS_NUM) {
+ forget_dead_mem_regs(env, e, idx);
+ i = find_mem_reg(e, 0);
+ }
+ if (i == MEM_REGS_NUM)
+ return 0;
+ e->mem_addr[i] = addr;
+ return replace_reg(env->scev, e, REGS_NUM + i,
+ mk_spill(env->scev, BPF_SIZE(env->prog->insnsi[idx].code), id));
+}
+
+static int load_mem(struct bpf_verifier_env *env, struct env *e, int idx)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ /* the insn defines dst_reg, which can be src_reg */
+ int addr = mk_mem_addr(env, e, idx, insn->src_reg);
+
+ return maybe_load_fp(env->scev, e, insn, idx) ?:
+ replace_mem_reg(env, e, idx, addr, e->reg2expr[insn->dst_reg]);
+}
+
+static int store_mem(struct bpf_verifier_env *env, struct env *e, int idx, int id)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ int addr;
+
+ if (insn->dst_reg == BPF_REG_FP)
+ return maybe_store_fp(env->scev, e, insn, idx, id);
+ addr = mk_mem_addr(env, e, idx, insn->dst_reg);
+ if (addr < 0)
+ return addr;
+ forget_mem_regs(env, e, addr, bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ return replace_mem_reg(env, e, idx, addr, id);
+}
+
+/*
+ * The low 32 bits of a + b depend on the low 32 bits of a and b only: 'w1 += w2' is
+ * (zext32 (+ a b)). That doesn't hold for a right shift and for a division. Their operands are zero
+ * or sign extended and a shift amount is masked, so that every expression is a 64-bit operation.
+ */
+static void alu32_operands(struct scev *scev, u32 op, int *a, int *b)
+{
+ s64 imm = 0;
+ bool imm_b = *b >= 0 && is_imm(scev, *b, &imm);
+
+ switch (op) {
+ case BPF_RSH:
+ case BPF_ARSH:
+ *a = expr1(scev, op == BPF_RSH ? ZEXT32 : SEXT32, *a);
+ fallthrough;
+ case BPF_LSH:
+ *b = imm_b ? imm_expr(scev, imm & 31) :
+ expr2(scev, BPF_AND, *b, imm_expr(scev, 31));
+ break;
+ case BPF_DIV:
+ case BPF_MOD:
+ *a = expr1(scev, ZEXT32, *a);
+ *b = imm_b ? imm_expr(scev, (u32)imm) : expr1(scev, ZEXT32, *b);
+ break;
+ case SDIV:
+ case SMOD:
+ *a = expr1(scev, SEXT32, *a);
+ *b = imm_b ? imm_expr(scev, (s32)imm) : expr1(scev, SEXT32, *b);
+ break;
+ }
+}
+
+/*
+ * In a prog with an arena an ALU64 insn is converted to ALU32 at fixup if an operand is a pointer
+ * to the arena, see adjust_reg_min_max_vals(). Types are not known here. So @id, what the insn at
+ * @idx computes from @a, gets a def: the value of @dst after the insn, converted or not. See
+ * split_const_offset() for when the op can be trusted. Constant operands are scalars in every
+ * state.
+ */
+static int alu64_with_def(struct scev *scev, int id, int a, int idx, u32 dst)
+{
+ s64 imm;
+
+ if (id < 0 || is_imm(scev, id, &imm))
+ return id;
+ /* (+ x 0) is x only if the insn stays ALU64 */
+ return expr_with_def(scev, id == a ? UNKNOWN_EXPR_ID : id, insn_def(idx, dst));
+}
+
static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
{
const bool little_endian = htons(0x3412) == 0x1234;
struct bpf_insn *insn = &env->prog->insnsi[idx];
+ bool arena = env->prog->aux->arena;
struct scev *scev = env->scev;
u32 *reg2expr = e->reg2expr;
u8 class = BPF_CLASS(insn->code);
@@ -698,9 +1267,9 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
u8 mode = BPF_MODE(insn->code);
u32 dst = insn->dst_reg;
u32 src = insn->src_reg;
- u32 op, sext, l, r;
+ u32 op, sext;
bool need_bswap;
- int i, id;
+ int i, id, a;
s64 imm;
/* reg2expr[12] is a stack slot, not r12 */
@@ -764,22 +1333,15 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
else
goto mark_dst_unknown;
- /*
- * 'r1 <<= 32; r1 >>= 32' is (u32)r1 for cpu v1 and v2. Only here both
- * shifts are known to be 64-bit ones: the result of a 32-bit shift is
- * (zext32 ...), and (>> x 32) is 'w1 >>= w2' with 32 in w2 as well,
- * which shifts by 0.
- */
- if (class == BPF_ALU64 && op == BPF_RSH && id >= 0 &&
- is_imm(scev, id, &imm) && imm == 32 &&
- is_binop(scev, BPF_LSH, reg2expr[dst], &l, &r) &&
- is_imm(scev, r, &imm) && imm == 32)
- return replace_reg(scev, e, dst, expr1(scev, ZEXT32, l));
-
- id = expr2(scev, op, reg2expr[dst], id);
+ a = reg2expr[dst];
+ if (class == BPF_ALU)
+ alu32_operands(scev, op, &a, &id);
+ id = expr2(scev, op, a, id);
if (class == BPF_ALU)
id = expr1(scev, ZEXT32, id);
+ else if (arena)
+ id = alu64_with_def(scev, id, a, idx, dst);
return replace_reg(scev, e, dst, id);
@@ -829,47 +1391,53 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
imm = env->insn_aux_data[idx + 1].const_reg_vals[dst];
return replace_reg(scev, e, dst, imm_expr(scev, imm));
}
- return maybe_load_fp(scev, e, insn);
+ return load_mem(env, e, idx);
default:
goto mark_dst_unknown;
}
case BPF_STX:
switch (mode) {
case BPF_MEM:
- return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ return store_mem(env, e, idx, reg2expr[src]);
case BPF_ATOMIC:
if (insn->imm == BPF_LOAD_ACQ)
- return maybe_load_fp(scev, e, insn);
+ return maybe_load_fp(scev, e, insn, idx);
if (insn->imm == BPF_STORE_REL) {
- return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ return store_mem(env, e, idx, reg2expr[src]);
}
/*
* verifier does not track other atomic ops precisely,
* hence mark the results as opaque.
*/
- if (insn->dst_reg == BPF_REG_FP)
- mark_opaque(e, insn->off, bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ if (insn->dst_reg == BPF_REG_FP) {
+ id = mark_opaque(scev, e, idx, insn->off,
+ bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ if (id < 0)
+ return id;
+ } else {
+ forget_mem_regs(env, e, 0, 0);
+ }
if (insn->imm == BPF_CMPXCHG)
- return replace_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID);
+ return forget_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID, idx);
if (insn->imm & BPF_FETCH)
- return replace_reg(scev, e, src, OPAQUE_EXPR_ID);
+ return forget_reg(scev, e, src, OPAQUE_EXPR_ID, idx);
break;
}
break;
case BPF_ST:
- if (insn->dst_reg == BPF_REG_FP) {
- id = imm_expr(scev, insn->imm);
- if (id < 0)
- return id;
- return maybe_store_fp(scev, e, insn, id);
- }
- break;
+ id = imm_expr(scev, insn->imm);
+ if (id < 0)
+ return id;
+ return store_mem(env, e, idx, id);
case BPF_JMP:
case BPF_JMP32:
if (opcode == BPF_CALL) {
- forget_call_regs(e);
+ forget_mem_regs(env, e, 0, 0);
+ id = forget_call_regs(env, e, idx);
+ if (id < 0)
+ return id;
/* made anew, like what is loaded. The parameter tells the two apart. */
- return replace_reg(scev, e, BPF_REG_0, expr1(scev, OPAQUE, 1));
+ return forget_reg(scev, e, BPF_REG_0, expr1(scev, OPAQUE, 1), idx);
}
/* for non-CALL there are no changes in register states */
break;
@@ -883,12 +1451,11 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
}
/* map, map value, BTF id, function */
if (BPF_SIZE(insn->code) == BPF_DW)
- return replace_reg(scev, e, dst, OPAQUE_EXPR_ID);
+ return forget_reg(scev, e, dst, OPAQUE_EXPR_ID, idx);
goto mark_dst_unknown;
case BPF_ABS:
case BPF_IND:
- forget_call_regs(e);
- break;
+ return forget_call_regs(env, e, idx);
default:
goto mark_dst_unknown;
}
@@ -897,20 +1464,47 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
/* unknown instruction, nuke state */
for (i = 0; i < REGS_NUM; i++)
reg2expr[i] = UNKNOWN_EXPR_ID;
+ forget_mem_regs(env, e, 0, 0);
break;
}
return 0;
mark_dst_unknown:
- reg2expr[dst] = UNKNOWN_EXPR_ID;
- return 0;
+ return forget_reg(scev, e, dst, UNKNOWN_EXPR_ID, idx);
+}
+
+/*
+ * if (c) sum += a[i]; else sum += b[i];
+ * @id without defs: (+ r6 %r2.4) -> (+ r6 _). A def tells one load from another. The code that
+ * analyzes loops asks how a value is computed, and that is the same on both paths.
+ * Beyond depth EXPR_STACK_DEPTH an expression keeps its defs: no user looks there.
+ */
+static int strip_defs(struct scev *scev, u32 id, u32 lvl)
+{
+ struct expr e = scev->exprs[id]; /* snapshot the expr before potential realloc */
+ int a;
+
+ switch (op_params_num(e.op)) {
+ case 0:
+ return e.def.set ? expr_with_def(scev, id, no_def) : id;
+ case 1:
+ if (lvl == EXPR_STACK_DEPTH)
+ return id;
+ return expr1(scev, e.op, strip_defs(scev, e.params[0], lvl + 1));
+ default:
+ if (lvl == EXPR_STACK_DEPTH)
+ return id;
+ a = strip_defs(scev, e.params[0], lvl + 1);
+ return expr2(scev, e.op, a, strip_defs(scev, e.params[1], lvl + 1));
+ }
}
/*
* Construct minimal 'ANY' expression by traversing 'a' and 'b'
- * and accumulating non-duplicated non-ANY entries.
+ * and accumulating non-duplicated non-ANY entries, without their defs.
+ * 'def' is the def of the result, no_def if it has none.
*/
-static int mk_any(struct scev *scev, int a, int b)
+static int mk_any(struct scev *scev, int a, int b, struct expr_def def)
{
struct expr_stack_elt *elt;
struct expr *expr;
@@ -933,14 +1527,18 @@ static int mk_any(struct scev *scev, int a, int b)
if (expr->op == ANY) {
if (!expr_stack_push(scev, expr->params[1]) ||
!expr_stack_push(scev, expr->params[0]))
- return UNKNOWN_EXPR_ID;
+ return expr_with_def(scev, UNKNOWN_EXPR_ID, def);
} else {
- for (j = 0; j < ids_buf_sz; j++) {
+ /* the operands of an ANY have no defs already */
+ if (id == roots[i])
+ id = strip_defs(scev, id, 0);
+ if (id < 0)
+ return id;
+ for (j = 0; j < ids_buf_sz; j++)
if (same_exprs(scev, scev->ids_buf[j], id))
goto next;
- }
if (ids_buf_sz == ARRAY_SIZE(scev->ids_buf))
- return UNKNOWN_EXPR_ID;
+ return expr_with_def(scev, UNKNOWN_EXPR_ID, def);
scev->ids_buf[ids_buf_sz++] = id;
}
next:;
@@ -954,12 +1552,77 @@ next:;
if (id < 0)
return id;
}
- return id;
+ return expr_with_def(scev, id, def);
+}
+
+static void split_const_offset(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off,
+ u32 *bits);
+
+/* @id == *@base + *@off in 64 bits: no extension and no partial spill is stripped */
+static void split_const_offset64(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off)
+{
+ struct scev *scev = env->scev;
+ u32 bits, l, r;
+
+ split_const_offset(env, id, base, off, &bits);
+ if (bits == 64)
+ return;
+ *base = id;
+ *off = 0;
+ if (!scev->exprs[id].def.set && is_add(scev, id, &l, &r) && is_imm(scev, r, off))
+ *base = l;
+}
+
+/*
+ * if (c) { n = f(); m = n; } else { n = g(); m = n; } if (n > 100) return 0; use(m);
+ * The phi of @reg before the insn at @idx. It merges @a, which came over the edges so far, and @b.
+ * Phis are value numbered as GVN does it, by join point and operands, up to a constant offset:
+ * a == base_a + off_a and b == base_b + off_b, so
+ * phi == phi(base_a, base_b + off_b - off_a) + off_a
+ * The phi of the bases is hashed without @reg. All registers that have a constant difference on
+ * each edge get the same one, and const_diff() finds them as it finds 'x' and 'x + 4'. The next
+ * edge merges the phi of the bases with the next base: the id stands for the list of the operands,
+ * for any number of edges. No edge brings a phi of this join point, so every phi here gets a new
+ * base with every edge.
+ */
+static int mk_phi(struct bpf_verifier_env *env, u32 a, u32 b, int idx, u32 reg)
+{
+ struct scev *scev = env->scev;
+ u32 base_a, base_b;
+ s64 off_a, off_b;
+ struct expr e;
+ int id;
+
+ id = mk_any(scev, a, b, no_def);
+ if (id < 0)
+ return id;
+ e = scev->exprs[id];
+ e.def = phi_def(idx, reg);
+ e.base = 0;
+ split_const_offset64(env, a, &base_a, &off_a);
+ split_const_offset64(env, b, &base_b, &off_b);
+ if (!expr_is_vn(scev, &e) || !scev->exprs[base_a].is_vn || !scev->exprs[base_b].is_vn)
+ return add_expr(scev, e);
+ id = base_b;
+ if (off_a != off_b)
+ id = expr2(scev, BPF_ADD, base_b, imm_expr(scev, (u64)off_b - off_a));
+ if (id < 0)
+ return id;
+ id = add_expr(scev, (struct expr){ .op = ANY, .params = { base_a, id },
+ .def = phi_def(idx, BASE_REG) });
+ if (id < 0)
+ return id;
+ e.base = id;
+ e.off = off_a;
+ e.bits = 64;
+ return add_expr(scev, e);
}
-static int join(struct scev *scev, struct env *acc, struct env *cur)
+/* @acc is the env before the insn at @idx */
+static int join(struct bpf_verifier_env *env, struct env *acc, struct env *cur, int idx)
{
- int i, id;
+ struct scev *scev = env->scev;
+ int i, j, id;
if (acc->empty) {
memcpy(acc, cur, sizeof(*acc));
@@ -967,9 +1630,18 @@ static int join(struct scev *scev, struct env *acc, struct env *cur)
return 0;
}
- for (i = 0; i < REGS_NUM; i++) {
- if (!same_exprs(scev, acc->reg2expr[i], cur->reg2expr[i])) {
- id = mk_any(scev, acc->reg2expr[i], cur->reg2expr[i]);
+ for (i = 0; i < ENV_REGS_NUM; i++) {
+ /* the address names a memory location. It has a phi if all edges track it. */
+ j = i < REGS_NUM ? i : REGS_NUM + find_mem_reg(cur, acc->mem_addr[i - REGS_NUM]);
+ if (j == ENV_REGS_NUM) {
+ forget_mem_reg(acc, i - REGS_NUM);
+ continue;
+ }
+ if (!same_exprs(scev, acc->reg2expr[i], cur->reg2expr[j])) {
+ /* no phi for a dead register: pruned SSA */
+ id = reg_alive_at(env, i, idx) ?
+ mk_phi(env, acc->reg2expr[i], cur->reg2expr[j], idx, i) :
+ UNKNOWN_EXPR_ID;
if (id < 0)
return id;
acc->reg2expr[i] = id;
@@ -991,14 +1663,15 @@ static void forget_modified_regs(struct scev *scev, struct env *acc, struct env
}
/* For a loop H at `header`, mark any register modified as a result of H execution as unknown. */
-static void forget_non_invariants(struct bpf_verifier_env *env, struct env *acc, int header)
+static int forget_non_invariants(struct bpf_verifier_env *env, struct env *acc, int header)
{
struct bpf_insn_aux_data *aux = env->insn_aux_data;
struct bpf_loop *loop = aux[header].loop;
struct scev *scev = env->scev;
- int i, idx, h;
+ int i, idx, h, err;
acc->empty = false;
+ forget_mem_regs(env, acc, 0, 0);
forget_modified_regs(scev, acc, find_header_env(scev, header));
for (i = 0; i < loop->exits_cnt; i++) {
idx = loop->exits[i].from;
@@ -1033,6 +1706,15 @@ static void forget_non_invariants(struct bpf_verifier_env *env, struct env *acc,
*/
forget_modified_regs(scev, acc, find_loop_env(scev, header, idx));
}
+ /* the nested loop defines them at its header */
+ for (i = 0; i < REGS_NUM; i++) {
+ if (acc->reg2expr[i] != UNKNOWN_EXPR_ID)
+ continue;
+ err = forget_reg(scev, acc, i, UNKNOWN_EXPR_ID, header);
+ if (err)
+ return err;
+ }
+ return 0;
}
/* Order worklist in reverse post-order. */
@@ -1051,7 +1733,7 @@ static int worklist_push(struct bpf_verifier_env *env, int loop_header, int idx)
{
struct scev *scev = env->scev;
struct scev_worklist *worklist = &scev->worklist;
- u32 tag = (u32)loop_header + 1;
+ u32 tag = loop_header + 2; /* -1 is a subprog */
if (scev->discovered[idx] == tag)
return 0;
@@ -1107,7 +1789,7 @@ static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,
len = log->end_pos - null_pos;
bpf_log(log, "%*s", max(37 - (int)len, 1), " ");
bpf_log(log, " ; ");
- for (r = 0; r < REGS_NUM; r++) {
+ for (r = 0; r < ENV_REGS_NUM; r++) {
old_id = old->reg2expr[r];
new_id = new->reg2expr[r];
if (at == LOG_AT_TRANSFER && !reg_alive_at_succ(env, r, insn_idx))
@@ -1122,6 +1804,10 @@ static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,
if (any_changes)
bpf_log(log, ", ");
log_reg(env, r);
+ if (r >= REGS_NUM && new->mem_addr[r - REGS_NUM]) {
+ bpf_log(log, "=*");
+ log_expr(env, new->mem_addr[r - REGS_NUM]);
+ }
bpf_log(log, " ");
log_expr(env, old_id);
bpf_log(log, " -> ");
@@ -1149,7 +1835,7 @@ static bool is_probe_read_helper(u32 func_id)
* If instruction is an indirect write to stack, invalidate SCEVs for spi's
* that this instruction can touch.
*/
-static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)
+static int reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)
{
struct bpf_insn *insn = &env->prog->insnsi[idx];
struct scev *scev = env->scev;
@@ -1157,19 +1843,24 @@ static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct
const unsigned long *mask;
u32 spi, reg;
bool opaque;
+ int err;
/* Direct fp stores are fine. */
if ((class == BPF_ST || class == BPF_STX) && insn->dst_reg == BPF_REG_FP)
- return;
+ return 0;
mask = bpf_may_write_mask(env, idx);
opaque = bpf_helper_call(insn) && is_probe_read_helper(insn->imm);
for_each_set_bit(spi, mask, MAX_BPF_STACK_SLOTS) {
reg = MAX_BPF_REG + spi;
- if (cur_env->reg2expr[reg] == UNKNOWN_EXPR_ID)
- continue;
- replace_reg(scev, cur_env, reg, opaque ? OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID);
+ /* '?' stays '?' */
+ err = forget_reg(scev, cur_env, reg,
+ opaque && !is_op(scev, cur_env->reg2expr[reg], UNKNOWN) ?
+ OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID, idx);
+ if (err)
+ return err;
}
+ return 0;
}
/*
@@ -1264,77 +1955,469 @@ static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_he
if (aux[header].loop_header == cur_header)
return header;
- return -1;
+ return -1;
+}
+
+/*
+ * Join cur_env into the successor's environment and schedule their traversal.
+ * Map successors in nested loops to their topmost nested header.
+ * Ignore successors outside the current loop and its nested loops.
+ */
+static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
+ struct env *old_env, struct env *cur_env)
+{
+ bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ struct scev *scev = env->scev;
+ int err, nested_header, idom;
+ struct env *succ_env;
+
+ /*
+ * There are several possibilities for a successor:
+ * - succ_idx can be a part of a loop outside of the cur_header's loop,
+ * such edges are ignored.
+ * - succ_idx can be a part of the same loop as cur_header,
+ * for such edges succ_idx environment is updated:
+ * e[succ_idx] = join(e[succ_idx], cur_env)
+ * - succ_idx can be a part of some loop inner to cur_header,
+ * in such a case there exists some loop header H,
+ * such that H.loop_header == cur_header
+ * and H is the same as succ_idx's loop or contains it.
+ */
+ if (bpf_loop_at_index(env, succ_idx) != cur_header) {
+ /*
+ * topmost_nested_loop() either finds H or returns -1,
+ * in case if succ_idx is a part of a loop outer to cur_header.
+ */
+ nested_header = topmost_nested_loop(env, succ_idx, cur_header);
+ if (nested_header < 0)
+ return 0;
+ succ_idx = nested_header;
+ }
+ succ_env = get_loop_env(scev, cur_header, succ_idx);
+ if (!succ_env)
+ return -ENOMEM;
+ /*
+ * The header of an irreducible loop does not dominate its body. An insn whose immediate
+ * dominator is outside of the loop is reached from a secondary entry, without the header.
+ * The env at the source of an entering edge is not known: all '?', like a new env. So the
+ * insn is a join point with a phi for every live register, see join_added_edges().
+ */
+ idom = env->idoms[succ_idx];
+ if (cur_header >= 0 && succ_idx != cur_header &&
+ env->insn_aux_data[cur_header].loop->irreducible &&
+ bpf_loop_at_index(env, idom) != cur_header &&
+ topmost_nested_loop(env, idom, cur_header) < 0)
+ succ_env->empty = false;
+ if (log_level2)
+ memcpy(old_env, succ_env, sizeof(*old_env));
+ err = join(env, succ_env, cur_env, succ_idx);
+ if (err)
+ return err;
+ err = worklist_push(env, cur_header, succ_idx);
+ if (err)
+ return err;
+ if (log_level2)
+ log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
+ return 0;
+}
+
+/*
+ * Recurrences need a natural loop. Unsupported loops get an unknown header environment.
+ * A nested loop is processed as a single instruction, its exits are the successors: all of
+ * them are needed. No result for the loop itself depends on the list of its own exits:
+ * mark_latches() prepares them for the loop around, and compute_max_iters() asks if there is
+ * only one, which a list that is cut does not have.
+ */
+static bool can_compute_loop_scev(const struct bpf_loop *loop)
+{
+ return !loop->irreducible && !loop->nested_exits_overflow;
+}
+
+/* A loop is a single instruction for the subprog too: no exit list may be truncated. */
+static bool can_compute_subprog_scev(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
+{
+ struct bpf_loop *loop;
+ int i;
+
+ for (i = sub->start; i < (sub + 1)->start; i++) {
+ loop = env->insn_aux_data[i].loop;
+ if (loop && (loop->exits_overflow || loop->nested_exits_overflow))
+ return false;
+ }
+ return true;
+}
+
+/*
+ * The edges that the verifier adds, see bpf_head_guard_target(): bpf_insn_successors() doesn't have
+ * them. They leave all loops. The env at their source is not known: @cur_env is all '?'. So their
+ * target is a join point with a phi for every live register.
+ */
+static int join_added_edges(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,
+ struct env *old_env, struct env *cur_env)
+{
+ int i, t, err;
+
+ for (i = sub->start; i < (sub + 1)->start; i++) {
+ t = bpf_head_guard_target(env, i);
+ if (t < 0)
+ continue;
+ err = join_successor(env, -1, t, old_env, cur_env);
+ if (err)
+ return err;
+ }
+ return sub->bail_insn < 0 ? 0 : join_successor(env, -1, sub->bail_insn, old_env, cur_env);
+}
+
+/*
+ * @id == *@base + *@off (mod 2^*@bits): constant offsets, extensions and partial spills are
+ * stripped, see set_expr_base(). An add with a def holds modulo 2^32 whether its insn is converted
+ * to ALU32 or not, see alu64_with_def(). It holds modulo 2^64 once the main pass has set
+ * prevent_zext: it verified the insn without a pointer to the arena and rejects a state that brings
+ * one. The def dominates every use, and prevent_zext is only ever set: such an add is not checked
+ * again.
+ */
+static void split_const_offset(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off, u32 *bits)
+{
+ struct scev *scev = env->scev;
+ struct expr *add, *e = &scev->exprs[id];
+
+ *base = e->base;
+ *off = e->off;
+ *bits = e->bits;
+ while (e->arena_add) {
+ add = &scev->exprs[e->arena_add];
+ if (!env->insn_aux_data[add->def.idx].prevent_zext) {
+ *bits = min(*bits, 32);
+ break;
+ }
+ e->arena_add = scev->exprs[add->params[0]].arena_add;
+ }
+}
+
+static bool const_diff_at_header(struct bpf_verifier_env *env, int h, u32 ra, u32 rb, s64 *delta);
+
+/*
+ * @id_a and @id_b are expressions of one env of the loop at @h, or of a subprog: @h is -1. Do they
+ * have a constant difference, @id_b == @id_a + *@delta (mod 2^*@bits)?
+ */
+static bool const_diff(struct bpf_verifier_env *env, int h, u32 id_a, u32 id_b, s64 *delta,
+ u32 *bits)
+{
+ struct scev *scev = env->scev;
+ u32 base_a, base_b, bits_a, ra, rb;
+ s64 off_a, c;
+
+ split_const_offset(env, id_a, &base_a, &off_a, &bits_a);
+ split_const_offset(env, id_b, &base_b, delta, bits);
+ *delta = (u64)*delta - off_a;
+ *bits = min(*bits, bits_a);
+ /* copies are equal in all bits */
+ if (id_a == id_b && scev->exprs[id_a].is_vn) {
+ *bits = 64;
+ return true;
+ }
+ if (base_a == base_b)
+ return scev->exprs[base_a].is_vn;
+ if (h < 0 || !is_reg(scev, base_a, &ra) || !is_reg(scev, base_b, &rb) ||
+ !const_diff_at_header(env, h, ra, rb, &c))
+ return false;
+ *delta = (u64)*delta + c;
+ return true;
+}
+
+/*
+ * old = i = 0; do { i++; if (old > 1021) break; c = buf[old]; old = i; } while (c);
+ * Does @rb == @ra + *@delta hold at the header of the loop at @h in every iteration? It does if it
+ * holds at loop entry, by the env of the enclosing loop at @h, and every backedge preserves it: the
+ * backedge values have this constant difference, or both are the header phi plus one constant.
+ * Loops nest LOOP_STACK_SIZE deep at most, see bpf_flow_place_guards().
+ */
+static bool const_diff_at_header(struct bpf_verifier_env *env, int h, u32 ra, u32 rb, s64 *delta)
+{
+ int outer_header = env->insn_aux_data[h].loop_header;
+ struct env *entry_env = find_loop_env(env->scev, outer_header, h);
+ struct env *header_env = find_header_env(env->scev, h);
+ u32 base_a, base_b, bits_a, bits;
+ s64 off_a, c;
+
+ if (!entry_env || !can_compute_loop_scev(env->insn_aux_data[h].loop) ||
+ !const_diff(env, outer_header, entry_env->reg2expr[ra], entry_env->reg2expr[rb],
+ delta, &bits) || bits != 64)
+ return false;
+ if (const_diff(env, -1, header_env->reg2expr[ra], header_env->reg2expr[rb], &c, &bits))
+ return bits == 64 && c == *delta;
+ split_const_offset(env, header_env->reg2expr[ra], &base_a, &off_a, &bits_a);
+ split_const_offset(env, header_env->reg2expr[rb], &base_b, &c, &bits);
+ return base_a == REG_EXPR_ID(ra) && base_b == REG_EXPR_ID(rb) && off_a == c &&
+ bits_a == 64 && bits == 64;
+}
+
+/*
+ * p = buf + i; if (i > 100) return 0; *p = 0;
+ * @tested is the expression of the tested register and @id that of p, in one env as for
+ * const_diff(). Is @id an add, and one operand @tested + a constant? Then
+ * @id == *@other + @tested + *@delta (mod 2^*@bits). A header phi can be an add, see ADD_SCEV. For
+ * an add with a def see split_const_offset(). Which operand is the pointer is not known here.
+ */
+static bool match_linked_add(struct bpf_verifier_env *env, int h, u32 tested, u32 id, u32 *other,
+ s64 *delta, u32 *bits)
+{
+ struct scev *scev = env->scev;
+ u32 reg, r, b, op = BPF_ADD;
+ struct expr_def def;
+ s64 c;
+
+ split_const_offset(env, id, &id, delta, bits);
+ if (h >= 0 && is_reg(scev, id, ®)) {
+ id = find_header_env(scev, h)->reg2scev[reg];
+ op = ADD_SCEV;
+ }
+ def = scev->exprs[id].def;
+ if (!is_binop(scev, op, id, other, &r) || def.phi)
+ return false;
+ if (def.set && !env->insn_aux_data[def.idx].prevent_zext)
+ *bits = min(*bits, 32);
+ if (!const_diff(env, h, tested, r, &c, &b)) {
+ swap(*other, r);
+ if (!const_diff(env, h, tested, r, &c, &b))
+ return false;
+ }
+ *delta = (u64)*delta + c;
+ *bits = min(*bits, b);
+ return true;
+}
+
+/*
+ * const_diff() for the SCEV register @reg, which has the expression @id_b. A fill from byte
+ * *@fill_off of a slot reads these bits. On big endian the low bytes of a spill are the last ones,
+ * and a narrow fill from the start of a slot is a right shift, see mk_fill().
+ */
+static bool const_diff_reg(struct bpf_verifier_env *env, int h, u32 id_a, u32 reg, u32 id_b,
+ u32 *fill_off, s64 *delta, u32 *bits)
+{
+ struct scev *scev = env->scev;
+ struct expr *e;
+ u32 x;
+ s64 k;
+
+ *fill_off = 0;
+ if (const_diff(env, h, id_a, id_b, delta, bits)) {
+ if (is_big_endian_slot(reg))
+ *fill_off = expr_spill_size(scev, id_b, &x) - *bits / BITS_PER_BYTE;
+ return true;
+ }
+ if (!is_big_endian_slot(reg) || !scev->exprs[id_b].is_vn)
+ return false;
+ split_const_offset(env, id_a, &x, delta, bits);
+ e = &scev->exprs[x];
+ if ((e->op != BPF_RSH && e->op != BPF_ARSH) || e->def.set || e->params[0] != id_b ||
+ !is_imm(scev, e->params[1], &k) || (k != 32 && k != 48 && k != 56))
+ return false;
+ *delta = -(u64)*delta;
+ *bits = min_t(u32, *bits, 64 - k);
+ *fill_off = (64 - k - *bits) / BITS_PER_BYTE;
+ return true;
+}
+
+/* The first of the registers and stack slots @live that holds @id + a constant. REGS_NUM: none. */
+static u32 find_leader(struct bpf_verifier_env *env, struct env *e, int h,
+ const unsigned long *live, u32 id)
+{
+ u32 r, bits;
+ s64 delta;
+
+ for_each_set_bit(r, live, REGS_NUM)
+ if (const_diff(env, h, e->reg2expr[r], id, &delta, &bits))
+ break;
+ return r;
}
/*
- * Join cur_env into the successor's environment and schedule their traversal.
- * Map successors in nested loops to their topmost nested header.
- * Ignore successors outside the current loop and its nested loops.
+ * n = bpf_get_stack(..); m = n; if (n < 0) ..; use(m);
+ * The main pass refines the registers that the conditional jump at @idx tests. Find the live SCEV
+ * registers that are linked to one of them in @e, the env before the jump, and keep them with their
+ * expressions: what bpf_scev_next_linked_reg() needs of @e.
*/
-static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
- struct env *old_env, struct env *cur_env)
+static int find_linked_regs(struct bpf_verifier_env *env, struct env *e, int h, int idx)
{
- bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ struct bpf_insn_aux_data *aux = &env->insn_aux_data[idx];
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ u32 dst = e->reg2expr[insn->dst_reg], src = dst;
+ struct insn_envs *envs = env->scev->envs[idx];
struct scev *scev = env->scev;
- int err, nested_header;
- struct env *succ_env;
+ u32 r, q, other, id, fill_off, base, base_dst, base_src, bits, cap, tested = 0;
+ u32 first = scev->linked_cnt;
+ DECLARE_BITMAP(live, ENV_REGS_NUM) = {};
+ DECLARE_BITMAP(found, ENV_REGS_NUM) = {};
+ void *tmp;
+ s64 delta;
- /*
- * There are several possibilities for a successor:
- * - succ_idx can be a part of a loop outside of the cur_header's loop,
- * such edges are ignored.
- * - succ_idx can be a part of the same loop as cur_header,
- * for such edges succ_idx environment is updated:
- * e[succ_idx] = join(e[succ_idx], cur_env)
- * - succ_idx can be a part of some loop inner to cur_header,
- * in such a case there exists some loop header H,
- * such that H.loop_header == cur_header
- * and H is the same as succ_idx's loop or contains it.
- */
- if (bpf_loop_at_index(env, succ_idx) != cur_header) {
- /*
- * topmost_nested_loop() either finds H or returns -1,
- * in case if succ_idx is a part of a loop outer to cur_header.
- */
- nested_header = topmost_nested_loop(env, succ_idx, cur_header);
- if (nested_header < 0)
- return 0;
- succ_idx = nested_header;
+ if (!bpf_insn_is_cond_jump(insn->code) || BPF_OP(insn->code) == BPF_JCOND)
+ return 0;
+ if (BPF_SRC(insn->code) == BPF_X)
+ src = e->reg2expr[insn->src_reg];
+ bitmap_copy(live, aux->live_stack_before, MAX_BPF_STACK_SLOTS);
+ bitmap_shift_left(live, live, MAX_BPF_REG, REGS_NUM);
+ live[0] |= aux->live_regs_before;
+ for (r = REGS_NUM; r < ENV_REGS_NUM; r++)
+ if (e->mem_addr[r - REGS_NUM])
+ __set_bit(r, live);
+ split_const_offset(env, dst, &base_dst, &delta, &bits);
+ split_const_offset(env, src, &base_src, &delta, &bits);
+ for_each_set_bit(r, live, ENV_REGS_NUM) {
+ id = e->reg2expr[r];
+ /* most are not linked */
+ split_const_offset(env, id, &base, &delta, &bits);
+ if (base != base_dst && base != base_src && !is_op(scev, base, BPF_ADD) &&
+ (h < 0 || !is_op(scev, base, REG)) && !is_big_endian_slot(r))
+ continue;
+ if (const_diff_reg(env, h, dst, r, id, &fill_off, &delta, &bits) ||
+ (src != dst && const_diff_reg(env, h, src, r, id, &fill_off, &delta, &bits))) {
+ __set_bit(r, found);
+ continue;
+ }
+ if (!match_linked_add(env, h, dst, id, &other, &delta, &bits) &&
+ (src == dst || !match_linked_add(env, h, src, id, &other, &delta, &bits)))
+ continue;
+ /* an add is of use only with a live register that holds its other operand */
+ for_each_set_bit(q, live, REGS_NUM) {
+ if (q == r || !const_diff(env, h, e->reg2expr[q], other, &delta, &bits))
+ continue;
+ __set_bit(r, found);
+ __set_bit(q, found);
+ break;
+ }
}
- succ_env = get_loop_env(scev, cur_header, succ_idx);
- if (!succ_env)
- return -ENOMEM;
- if (log_level2)
- memcpy(old_env, succ_env, sizeof(*old_env));
- err = join(scev, succ_env, cur_env);
- if (err)
- return err;
- err = worklist_push(env, cur_header, succ_idx);
- if (err)
- return err;
- if (log_level2)
- log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
+ /* the main pass finds memory by a live register that holds its address */
+ for (r = REGS_NUM; r < ENV_REGS_NUM; r++) {
+ if (!test_bit(r, found))
+ continue;
+ q = find_leader(env, e, h, live, e->mem_addr[r - REGS_NUM]);
+ if (q < REGS_NUM)
+ __set_bit(q, found);
+ else
+ __clear_bit(r, found);
+ }
+ for_each_set_bit(r, found, ENV_REGS_NUM) {
+ if (scev->linked_cnt == scev->linked_cap) {
+ cap = max(scev->linked_cap * 2, 16);
+ tmp = kvrealloc(scev->linked, array_size(cap, sizeof(*scev->linked)),
+ GFP_KERNEL_ACCOUNT);
+ if (!tmp)
+ return -ENOMEM;
+ scev->linked = tmp;
+ scev->linked_cap = cap;
+ }
+ tested += r == insn->dst_reg || (src != dst && r == insn->src_reg);
+ scev->linked[scev->linked_cnt].reg = r;
+ scev->linked[scev->linked_cnt].addr = r < REGS_NUM ? 0 : e->mem_addr[r - REGS_NUM];
+ scev->linked[scev->linked_cnt++].id = e->reg2expr[r];
+ }
+ /* nothing but the tested registers */
+ if (scev->linked_cnt - first == tested) {
+ scev->linked_cnt = first;
+ return 0;
+ }
+ if (!envs) {
+ envs = kzalloc(sizeof(*envs), GFP_KERNEL_ACCOUNT);
+ if (!envs)
+ return -ENOMEM;
+ scev->envs[idx] = envs;
+ }
+ envs->linked_first = first;
+ envs->linked_cnt = scev->linked_cnt - first;
return 0;
}
/*
- * Unsupported loops get only an unknown header environment.
- * A nested loop is processed as a single instruction, its exits are the successors: all of
- * them are needed. No result for the loop itself depends on the list of its own exits:
- * mark_latches() prepares them for the loop around, and compute_max_iters() asks if there is
- * only one, which a list that is cut does not have.
+ * Find the next SCEV register that is linked to @regno at the conditional jump at @insn_idx: on
+ * every path to the jump *@linked_regno == @regno + *@delta (mod 2^*@bits). It is live there and of
+ * the same frame. It is a register, or MAX_BPF_REG + the index of a stack slot: a fill from byte
+ * *@fill_off of the slot reads these bits. *@pos is the position of the search, 0 at first. False:
+ * no more links are known. Types are not known here: the caller checks them in its state.
+ * A linked register can be a pointer: *base_regno + regno + delta. *base_regno is the address base,
+ * as in store_base_regs. It is -1 for a link without a base.
+ * BPF_SCEV_REGS_NUM and above is a memory location, see struct env and bpf_scev_mem_addr().
*/
-static bool can_compute_loop_scev(const struct bpf_loop *loop)
+bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,
+ u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,
+ u32 *bits)
{
- return !loop->irreducible && !loop->nested_exits_overflow;
+ struct insn_envs *envs = env->scev->envs[insn_idx];
+ int h = bpf_loop_at_index(env, insn_idx);
+ struct scev_linked_reg *linked;
+ u32 i, j, other, b;
+ s64 c;
+
+ if (!envs || !envs->linked_cnt)
+ return false;
+ linked = &env->scev->linked[envs->linked_first];
+ /* registers come first */
+ for (i = 0; linked[i].reg != regno; i++)
+ if (i + 1 == envs->linked_cnt || linked[i].reg > regno)
+ return false;
+ for (; *pos < envs->linked_cnt; ++*pos) {
+ *linked_regno = linked[*pos].reg;
+ *base_regno = -1;
+ if (*pos == i)
+ continue;
+ if (const_diff_reg(env, h, linked[i].id, *linked_regno, linked[*pos].id, fill_off,
+ delta, bits))
+ return true;
+ if (!match_linked_add(env, h, linked[i].id, linked[*pos].id, &other, delta, bits))
+ continue;
+ for (j = 0; j < envs->linked_cnt; j++) {
+ if (j == *pos || !const_diff(env, h, linked[j].id, other, &c, &b))
+ continue;
+ *base_regno = linked[j].reg;
+ *delta = (u64)*delta + c;
+ *bits = min(*bits, b);
+ return true;
+ }
+ }
+ return false;
+}
+
+/*
+ * The memory location @regno is a linked register of the conditional jump at @insn_idx. Its address
+ * is *@base_regno + *@off. *@base_regno is a live register or stack slot. Which memory it is
+ * depends on the state.
+ */
+bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,
+ s64 *off)
+{
+ struct insn_envs *envs = env->scev->envs[insn_idx];
+ struct scev_linked_reg *linked = &env->scev->linked[envs->linked_first];
+ int h = bpf_loop_at_index(env, insn_idx);
+ u32 i, j, bits;
+
+ for (i = 0; linked[i].reg != regno; i++)
+ if (i + 1 == envs->linked_cnt)
+ return false;
+ for (j = 0; linked[j].reg < REGS_NUM; j++) {
+ if (!const_diff(env, h, linked[j].id, linked[i].addr, off, &bits) || bits != 64)
+ continue;
+ *base_regno = linked[j].reg;
+ return true;
+ }
+ return false;
}
-static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
+/*
+ * @cur_header and @first are a loop header. Or -1 and the first insn of a subprog: the subprog is
+ * the outermost loop, which runs once. (REG r) is the entry value of r, the loops in it are single
+ * instructions.
+ * Value numbering works on any CFG: the body of an irreducible loop is walked like any other. Every
+ * retreating edge of the depth-first search goes to a loop header, see compute_loops_in_subprog(),
+ * and bpf_compute_postorder() does the same search. So reverse post-order is a topological order of
+ * this body too.
+ */
+static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header, int first)
{
struct scev_worklist *worklist = &env->scev->worklist;
struct bpf_insn_aux_data *aux = env->insn_aux_data;
- struct bpf_loop *cur_loop = aux[cur_header].loop;
+ struct bpf_loop *cur_loop = cur_header < 0 ? NULL : aux[cur_header].loop;
+ struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, first);
struct env *header_env;
struct scev *scev = env->scev;
struct bpf_loop *nested_loop;
@@ -1342,26 +2425,15 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
struct env *old_env = NULL;
struct bpf_iarray *succ;
bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
- int s, i, err, idx, succ_idx;
+ int s, i, err, idx, succ_idx, start;
u32 r;
if (log_level2)
- bpf_log(&env->log, "Computing SCEV for loop at %d:\n", cur_header);
+ bpf_log(&env->log, "Computing SCEV for %s at %d:\n",
+ cur_loop ? "loop" : "subprog", first);
- /*
- * For irreducible loops, and for loops nesting a loop with a truncated
- * exit list, just assume that everything is clobbered for now.
- */
- if (!can_compute_loop_scev(cur_loop)) {
- header_env = get_loop_env(scev, cur_header, cur_header);
- if (!header_env)
- return -ENOMEM;
- /* The freshly allocated environment has all expressions unknown. */
- bitmap_fill(cur_loop->store_base_regs, REGS_NUM);
- bitmap_fill(cur_loop->tested_regs, REGS_NUM);
- header_env->empty = false;
+ if (!cur_loop && !can_compute_subprog_scev(env, sub))
return 0;
- }
cur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);
if (!cur_env)
@@ -1371,19 +2443,33 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
if (!old_env)
goto nomem;
}
- header_env = get_loop_env(scev, cur_header, cur_header);
+ header_env = get_loop_env(scev, cur_header, first);
if (!header_env)
goto nomem;
- err = setup_initial_loop_env(env, header_env, cur_header);
- if (err)
- goto out;
- err = worklist_push(env, cur_header, cur_header);
- if (err)
- goto out;
+ setup_initial_loop_env(header_env);
+ /* The successors of a nested loop with a truncated exit list are not known: no walk */
+ if (!cur_loop || !cur_loop->nested_exits_overflow) {
+ err = worklist_push(env, cur_header, first);
+ if (err)
+ goto out;
+ }
+ if (!cur_loop) {
+ /* no backedge overwrites it */
+ header_env->empty = false;
+ err = join_added_edges(env, sub, old_env, cur_env);
+ if (err)
+ goto out;
+ }
while (worklist->nr) {
idx = *min_heap_peek_inline(worklist);
min_heap_pop_inline(worklist, &worklist_cb, env->cfg.postorder_nums);
+ start = idx;
+ if (signal_pending(current)) {
+ err = -EAGAIN;
+ goto out;
+ }
+ cond_resched();
/* join_successor() maps nested-loop entries to their representative header. */
nested_loop = idx != cur_header ? aux[idx].loop : NULL;
@@ -1395,13 +2481,19 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
*/
if (log_level2)
memcpy(old_env, cur_env, sizeof(*old_env));
- /* Pull the nested loop's stack-store base dependencies up. */
- for_each_set_bit(r, nested_loop->store_base_regs, BPF_SCEV_REGS_NUM)
- or_expr_regs(env, cur_env->reg2expr[r], cur_loop->store_base_regs);
- /* And what its jumps depend on. */
- for_each_set_bit(r, nested_loop->tested_regs, BPF_SCEV_REGS_NUM)
- or_expr_regs(env, cur_env->reg2expr[r], cur_loop->tested_regs);
- forget_non_invariants(env, cur_env, idx);
+ if (cur_loop) {
+ /* Pull the nested loop's stack-store base dependencies up. */
+ for_each_set_bit(r, nested_loop->store_base_regs, BPF_SCEV_REGS_NUM)
+ or_expr_regs(env, cur_env->reg2expr[r],
+ cur_loop->store_base_regs);
+ /* And what its jumps depend on. */
+ for_each_set_bit(r, nested_loop->tested_regs, BPF_SCEV_REGS_NUM)
+ or_expr_regs(env, cur_env->reg2expr[r],
+ cur_loop->tested_regs);
+ }
+ err = forget_non_invariants(env, cur_env, idx);
+ if (err)
+ goto out;
if (log_level2)
log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
/*
@@ -1422,12 +2514,24 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
for (;;) {
if (log_level2)
memcpy(old_env, cur_env, sizeof(*old_env));
- collect_store_base_regs(env, cur_env, idx, cur_loop->store_base_regs);
- collect_tested_regs(env, cur_env, idx, cur_loop->tested_regs);
+ if (cur_loop) {
+ collect_store_base_regs(env, cur_env, idx,
+ cur_loop->store_base_regs);
+ collect_tested_regs(env, cur_env, idx,
+ cur_loop->tested_regs);
+ }
+ /* the others wait for the envs of all loop headers */
+ if (!aux[idx].need_scev) {
+ err = find_linked_regs(env, cur_env, -1, idx);
+ if (err)
+ goto out;
+ }
err = transfer(env, cur_env, idx);
if (err)
goto out;
- reset_scevs_at_indirect_writes(env, cur_env, idx);
+ err = reset_scevs_at_indirect_writes(env, cur_env, idx);
+ if (err)
+ goto out;
if (log_level2)
log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
succ = bpf_insn_successors(env, idx);
@@ -1446,8 +2550,17 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
goto out;
}
}
+ /* Reverse post-order: all predecessors came first, the env has no users any more */
+ if (!aux[start].need_scev)
+ free_loop_env(scev, cur_header, start);
}
+ /* For the enclosing loop and for the main pass it clobbers everything */
+ if (cur_loop && !can_compute_loop_scev(cur_loop)) {
+ memset(header_env, 0, sizeof(*header_env));
+ bitmap_fill(cur_loop->store_base_regs, REGS_NUM);
+ bitmap_fill(cur_loop->tested_regs, REGS_NUM);
+ }
err = 0;
out:
kfree(cur_env);
@@ -1545,29 +2658,10 @@ static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,
return id < 0 ? id : fn(scev, id, priv);
}
-static int transform_expr(struct scev *scev, u32 root, void *priv,
- int (*fn)(struct scev *scev, u32 id, void *priv))
-{
- int i = 0, id_old, id_new = root;
-
- do {
- /*
- * The depth limit is somewhat arbitrary and is essentially a failsafe.
- * oscillation should not really happen. Still, it seems harsh to error out.
- */
- if (i++ == 4 * EXPR_STACK_DEPTH)
- return UNKNOWN_EXPR_ID;
- id_old = id_new;
- id_new = transform_expr_once(scev, 0, id_old, priv, fn);
- if (id_new < 0)
- return id_new;
- } while (id_old != id_new);
- return id_new;
-}
-
-static int simplify(struct scev *scev, u32 id, void *priv)
+static int simplify(struct scev *scev, u32 id)
{
int a, b, l, r, t, base, slope;
+ u32 op = scev->exprs[id].op, bits = op_low_bits(op);
s64 imm1, imm2;
/* (- x imm) -> (+ x -imm) */
@@ -1575,13 +2669,24 @@ static int simplify(struct scev *scev, u32 id, void *priv)
is_imm(scev, r, &imm1) && imm1 != S64_MIN)
return expr2(scev, BPF_ADD, l, imm_expr(scev, -imm1));
- /* (+ (+ x imm) imm) -> (+ x imm) */
+ /* (+ x 0) -> x */
+ if (is_add(scev, id, &l, &r) && is_imm(scev, r, &imm1) && !imm1)
+ return l;
+
+ /* (+ (+ x imm) imm) -> (+ x imm). Not through a def, see alu64_with_def() */
if (is_add(scev, id, &l, &r) &&
is_imm(scev, r, &imm2) &&
is_add(scev, l, &a, &b) &&
- is_imm(scev, b, &imm1))
+ is_imm(scev, b, &imm1) && !scev->exprs[l].def.set)
return expr2(scev, BPF_ADD, a, imm_expr(scev, (s64)((u64)imm1 + (u64)imm2)));
+ /* 'r1 <<= 32; r1 >>= 32' is (u32)r1 for cpu v1 and v2: (>> (<< x 32) 32) -> (zext32 x) */
+ if (is_binop(scev, BPF_RSH, id, &l, &r) &&
+ is_imm(scev, r, &imm2) && imm2 == 32 &&
+ is_binop(scev, BPF_LSH, l, &a, &b) &&
+ is_imm(scev, b, &imm1) && imm1 == 32 && !scev->exprs[l].def.set)
+ return expr1(scev, ZEXT32, a);
+
/* (+ (linear base slope) imm) -> (linear (+ base imm) slope) */
if (is_add(scev, id, &l, &r) &&
is_linear(scev, l, &base, &slope) &&
@@ -1599,49 +2704,44 @@ static int simplify(struct scev *scev, u32 id, void *priv)
return imm_expr(scev, (u64)(u32)imm1);
/*
- * (zext32 (+ (zext32 $a) $b)) -> (zext32 (+ $a $b))
- * (zext32 (+ $a (zext32 $b))) -> (zext32 (+ $a $b))
+ * An extension and a partial spill depend on the low bits of their operand only: look
+ * through an extension and a partial spill that is not narrower, below an add too:
+ * (sext32 (zext32 $a)) -> (sext32 $a)
+ * (sext8 (spill16 $a)) -> (sext8 $a)
+ * (zext32 (+ (sext32 $a) $b)) -> (zext32 (+ $a $b))
+ * (spill32 (+ $a (zext32 $b))) -> (spill32 (+ $a $b))
*/
- if ((is_zext32(scev, id, &t) && is_add(scev, t, &l, &b) && is_zext32(scev, l, &a)) ||
- (is_zext32(scev, id, &t) && is_add(scev, t, &a, &r) && is_zext32(scev, r, &b))) {
- t = expr2(scev, BPF_ADD, a, b);
- t = expr1(scev, ZEXT32, t);
- return t;
- }
-
- /* (zext32 (zext32 X)) -> (zext32 X) */
- if (is_zext32(scev, id, &a) && is_zext32(scev, a, &b))
- return a;
+ if (!bits)
+ return id;
+ t = scev->exprs[id].params[0];
+ if (is_low_bits(scev, t, bits, &a))
+ return expr1(scev, op, a);
+ if (is_add(scev, t, &l, &r) && !scev->exprs[t].def.phi &&
+ (is_low_bits(scev, l, bits, &l) || is_low_bits(scev, r, bits, &r)))
+ return expr1(scev, op, expr2(scev, BPF_ADD, l, r));
- /*
- * '*(u32 *)(r10 - 8) = rX' stores the low half of rX:
- * (spill32 (zext32 $a)) -> (spill32 $a)
- * (spill32 (+ (zext32 $a) $b)) -> (spill32 (+ $a $b))
- */
- if (is_spill32(scev, id, &t) && is_zext32(scev, t, &a))
- return expr1(scev, SPILL32, a);
- if (is_spill32(scev, id, &t) && is_add(scev, t, &l, &b) && is_zext32(scev, l, &a))
- return expr1(scev, SPILL32, expr2(scev, BPF_ADD, a, b));
+ return id;
+}
- /*
- * 'rX = *(u32 *)(r10 - 8)' loads what was stored:
- * (zext32 (spill32 $a)) -> (zext32 $a)
- * (zext32 (+ (spill32 $a) $b)) -> (zext32 (+ $a $b))
- */
- if (is_zext32(scev, id, &t) && is_spill32(scev, t, &a))
- return expr1(scev, ZEXT32, a);
- if (is_zext32(scev, id, &t) && is_add(scev, t, &l, &b) && is_spill32(scev, l, &a))
- return expr1(scev, ZEXT32, expr2(scev, BPF_ADD, a, b));
+static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
+{
+ u32 reg, *reg2scev = priv;
+ /* (reg r) -> ... equation at header ... */
+ if (is_reg(scev, id, ®))
+ return reg2scev[reg];
+ /* keep expression shapes */
return id;
}
-static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)
+static int compute_header_scevs(struct bpf_verifier_env *env, int h)
{
struct scev *scev = env->scev;
+ struct env *header_env = find_header_env(scev, h);
int l, r, t, id, ra, rb, ra_expr;
bool zext32;
s64 imm;
+ u32 op;
/*
* Note:
@@ -1658,10 +2758,13 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
* ... at exit r1 is in {7,42} ...
*/
for (ra = 0; ra < REGS_NUM; ra++) {
- ra_expr = transform_expr(scev, header_env->reg2expr[ra], NULL, simplify);
+ ra_expr = header_env->reg2expr[ra];
+ /* Constructed again it has no defs, see alu64_with_def(): they hide the shape */
+ if (env->prog->aux->arena)
+ ra_expr = transform_expr_once(scev, 0, ra_expr, scev->identity_env.reg2expr,
+ instantiate_header_scevs);
if (ra_expr < 0)
return ra_expr;
- header_env->reg2expr[ra] = ra_expr;
/* rA = (+ rA IMM) -> (linear rA IMM) */
if (is_add(scev, ra_expr, &l, &r) &&
is_reg(scev, l, &rb) &&
@@ -1673,30 +2776,24 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
header_env->reg2scev[ra] = id;
continue;
}
- /* rA = (is_zext32 (+ rA IMM)) -> (is_zext32 (linear rA IMM)) */
- if (is_zext32(scev, ra_expr, &t) &&
- is_add(scev, t, &l, &r) &&
- is_reg(scev, l, &rb) &&
- is_imm(scev, r, &imm) &&
- ra == rb) {
- id = expr2(scev, LINEAR_SCEV, l, r);
- id = expr1(scev, ZEXT32, id);
- if (id < 0)
- return id;
- header_env->reg2scev[ra] = id;
- continue;
- }
/*
+ * A 32-bit induction variable:
+ * rA = (zext32 (+ rA IMM)) -> (zext32 (linear rA IMM))
+ * rA = (sext32 (+ rA IMM)) -> (sext32 (linear rA IMM))
* rA = (spill32 (+ rA IMM)) -> (spill32 (linear (zext32 rA) IMM))
- * The low half of the slot counts. Nothing is known about the other half.
+ * The last SCEV leaves the upper 32 bits of the slot unknown, so it holds for the
+ * first two as well. They get it if these bits are dead: the states have a
+ * 32-bit spill then, see bpf_clean_verifier_state().
*/
- if (is_spill32(scev, ra_expr, &t) &&
+ if (is_low_bits(scev, ra_expr, 32, &t) &&
is_add(scev, t, &l, &r) &&
is_reg(scev, l, &rb) &&
is_imm(scev, r, &imm) &&
ra == rb) {
- id = expr2(scev, LINEAR_SCEV, expr1(scev, ZEXT32, l), r);
- id = expr1(scev, SPILL32, id);
+ op = hi32_alive_at(env, ra, h) ? scev->exprs[ra_expr].op : SPILL32;
+ if (op == SPILL32)
+ l = expr1(scev, ZEXT32, l);
+ id = expr1(scev, op, expr2(scev, LINEAR_SCEV, l, r));
if (id < 0)
return id;
header_env->reg2scev[ra] = id;
@@ -1709,7 +2806,7 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
}
/* rA = (any 1 2 3 4 ...) -> (any rA 1 2 3 4 ...) */
if (is_any_imm_reg_opaque(scev, ra_expr)) {
- id = mk_any(scev, expr1(scev, REG, ra), ra_expr);
+ id = mk_any(scev, expr1(scev, REG, ra), ra_expr, no_def);
if (id < 0)
return id;
header_env->reg2scev[ra] = id;
@@ -1720,7 +2817,7 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
/*
* do { i++; if (old > 1021) break; c = buf[old]; old = i; } while (c);
* rA = (+ rB IMM) and rB = (+ rB IMM): an iteration leaves the same number in both. If
- * they are equal when the loop is entered rA is at the header what rB is.
+ * they are equal at loop entry too, rA is an induction variable with the same step.
*/
for (ra = 0; ra < REGS_NUM; ra++) {
if (header_env->reg2scev[ra] != UNKNOWN_EXPR_ID ||
@@ -1730,9 +2827,12 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
id = header_env->reg2scev[rb];
if (header_env->reg2expr[rb] != header_env->reg2expr[ra] ||
!is_linear_or_linear32(scev, id, &l, &r, &zext32) ||
- !is_reg(scev, l, &t) || t != rb)
+ !is_reg(scev, l, &t) || t != rb ||
+ !const_diff_at_header(env, h, rb, ra, &imm) || imm)
continue;
- id = expr2(scev, COPY_SCEV, expr1(scev, REG, ra), id);
+ id = expr2(scev, LINEAR_SCEV, expr1(scev, REG, ra), r);
+ if (zext32)
+ id = expr1(scev, ZEXT32, id);
if (id < 0)
return id;
header_env->reg2scev[ra] = id;
@@ -1742,6 +2842,64 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
return 0;
}
+/*
+ * Find a SCEV register with the entry value @x and the backedge value @l, and one with @y and @r.
+ * All that match are copies of each other at the header: take the first.
+ */
+static bool find_operands(struct env *entry_env, struct env *header_env, u32 x, u32 y, u32 l, u32 r,
+ u32 *rb, u32 *rc)
+{
+ for (*rb = 0; *rb < REGS_NUM; ++*rb)
+ if (entry_env->reg2expr[*rb] == x && header_env->reg2expr[*rb] == l)
+ break;
+ for (*rc = 0; *rc < REGS_NUM; ++*rc)
+ if (entry_env->reg2expr[*rc] == y && header_env->reg2expr[*rc] == r)
+ break;
+ return *rb < REGS_NUM && *rc < REGS_NUM;
+}
+
+/*
+ * p = buf; i = 0; while (*p) { if (i > 512) break; use(p); i += len(p); p = buf + i; }
+ * rA == rB + rC holds at the header in every iteration: it holds at loop entry and every backedge
+ * preserves it. The backedge values are rA = (+ l r), rB = l, rC = r. The entry values, by the env
+ * of the enclosing loop at @h, are rA = x, rB = x, rC = 0 or rA = (+ x y), rB = x, rC = y.
+ * (add rB rC) keeps the def of (+ l r), see alu64_with_def().
+ */
+static int compute_header_adds(struct bpf_verifier_env *env, int h)
+{
+ struct scev *scev = env->scev;
+ struct env *entry_env = find_loop_env(scev, env->insn_aux_data[h].loop_header, h);
+ struct env *header_env = find_header_env(scev, h);
+ u32 ra, rb, rc, l, r, x, y, entry_expr;
+ struct expr_def def;
+ int id, zero = imm_expr(scev, 0);
+
+ if (zero < 0)
+ return zero;
+ for (ra = 0; entry_env && ra < REGS_NUM; ra++) {
+ entry_expr = entry_env->reg2expr[ra];
+ if (header_env->reg2scev[ra] != UNKNOWN_EXPR_ID ||
+ !is_add(scev, header_env->reg2expr[ra], &l, &r) ||
+ !scev->exprs[entry_expr].is_vn || !scev->exprs[l].is_vn ||
+ !scev->exprs[r].is_vn)
+ continue;
+ if (!find_operands(entry_env, header_env, entry_expr, zero, l, r, &rb, &rc) &&
+ !find_operands(entry_env, header_env, zero, entry_expr, l, r, &rb, &rc) &&
+ (scev->exprs[entry_expr].def.set || !is_add(scev, entry_expr, &x, &y) ||
+ (!find_operands(entry_env, header_env, x, y, l, r, &rb, &rc) &&
+ !find_operands(entry_env, header_env, y, x, l, r, &rb, &rc))))
+ continue;
+ /* expr2() can move exprs[] */
+ def = scev->exprs[header_env->reg2expr[ra]].def;
+ id = expr_with_def(scev, expr2(scev, ADD_SCEV, REG_EXPR_ID(rb), REG_EXPR_ID(rc)),
+ def);
+ if (id < 0)
+ return id;
+ header_env->reg2scev[ra] = id;
+ }
+ return 0;
+}
+
/*
* 'sum += a[i]', 'if (..) { len -= n; len -= 2; }': is 'id', what an iteration makes of
* register 'r', the register plus or minus something, or the register as it was?
@@ -1792,34 +2950,14 @@ static void scev_compute_linear_regs(struct scev *scev, struct bpf_loop *loop,
}
}
-static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
-{
- u32 reg, *reg2scev = priv;
-
- /* (reg r) -> ... equation at header ... */
- if (is_reg(scev, id, ®))
- return reg2scev[reg];
- /* keep expression shapes */
- return id;
-}
-
static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)
{
struct scev *scev = env->scev;
int id, reg;
for (reg = 0; reg < REGS_NUM; reg++) {
- /*
- * Simplify first. 'store, load, test' of a 32-bit counter on the stack with the
- * equation of the header in it is deeper than EXPR_STACK_DEPTH.
- */
- id = transform_expr(scev, einsn->reg2expr[reg], NULL, simplify);
- if (id < 0)
- return id;
- id = transform_expr_once(scev, 0, id, eheader->reg2scev, instantiate_header_scevs);
- if (id < 0)
- return id;
- id = transform_expr(scev, id, NULL, simplify);
+ id = transform_expr_once(scev, 0, einsn->reg2expr[reg], eheader->reg2scev,
+ instantiate_header_scevs);
if (id < 0)
return id;
einsn->reg2scev[reg] = id;
@@ -1861,6 +2999,27 @@ static int log_scevs(struct bpf_verifier_env *env)
return 0;
}
+/*
+ * A slice comes from a call that may write to the buffer: the kfunc, or a subprog that calls it.
+ * See expr_is_vn().
+ */
+static void find_slice_slots(struct bpf_verifier_env *env)
+{
+ struct bpf_insn *insn = env->prog->insnsi;
+ struct scev *scev = env->scev;
+ bool slices = false;
+ u32 i, spi;
+
+ for (i = 0; i < env->prog->len; i++)
+ slices |= bpf_is_dynptr_slice_rdwr_kfunc(&insn[i]);
+ for (i = 0; slices && i < env->prog->len; i++)
+ if (BPF_CLASS(insn[i].code) == BPF_JMP && BPF_OP(insn[i].code) == BPF_CALL)
+ bitmap_or(scev->slice_slots, scev->slice_slots, bpf_may_write_mask(env, i),
+ MAX_BPF_STACK_SLOTS);
+ for_each_set_bit(spi, scev->slice_slots, MAX_BPF_STACK_SLOTS)
+ scev->exprs[REG_EXPR_ID(MAX_BPF_REG + spi)].is_vn = false;
+}
+
int bpf_compute_scev(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux = env->insn_aux_data;
@@ -1869,6 +3028,7 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
int cnt = env->cfg.cur_postorder;
int i, idx, err, header;
+ find_slice_slots(env);
mark_latches(env);
/*
* Visit loop headers in postorder, to guarantee that scevs
@@ -1878,7 +3038,12 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
idx = postorder[i];
if (!aux[idx].loop)
continue;
- err = compute_scev_for_loop(env, idx);
+ err = compute_scev_for_loop(env, idx, idx);
+ if (err)
+ return err;
+ }
+ for (i = 0; i < env->subprog_cnt; i++) {
+ err = compute_scev_for_loop(env, -1, env->subprog_info[i].start);
if (err)
return err;
}
@@ -1892,17 +3057,28 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
idx = postorder[i];
if (!aux[idx].need_scev)
continue;
+ if (signal_pending(current))
+ return -EAGAIN;
+ cond_resched();
header = bpf_loop_at_index(env, idx);
err = aux[idx].loop
- ? compute_header_scevs(env, find_header_env(scev, header))
+ ? compute_header_scevs(env, header)
: compute_insn_scevs(env,
find_header_env(scev, header),
find_loop_env(scev, header, idx));
if (err)
return err;
- if (aux[idx].loop)
+ if (aux[idx].loop) {
scev_compute_linear_regs(scev, aux[idx].loop,
find_header_env(scev, header));
+ err = compute_header_adds(env, idx);
+ if (err)
+ return err;
+ }
+ err = find_linked_regs(env, aux[idx].loop ? &scev->identity_env :
+ find_loop_env(scev, header, idx), header, idx);
+ if (err)
+ return err;
}
/* Now it's known which jumps test a counter: the places of a back edge are for them */
@@ -1919,6 +3095,21 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
return 0;
}
+/*
+ * Are all slots of the buffer [off, off + size) in slice_slots? Without @fixed_off the buffer is
+ * somewhere in the range, and the range can be wider than slice_slots: two offsets become a range
+ * at a join point.
+ */
+bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off)
+{
+ int first = bpf_get_spi(off + size - 1), last = bpf_get_spi(off);
+ const unsigned long *slots = env->scev->slice_slots;
+
+ if (fixed_off)
+ return find_next_zero_bit(slots, last + 1, first) > last;
+ return find_next_bit(slots, last + 1, first) <= last;
+}
+
void bpf_free_scev(struct bpf_verifier_env *env)
{
struct scev *scev = env->scev;
@@ -1936,13 +3127,12 @@ void bpf_free_scev(struct bpf_verifier_env *env)
kfree(envs->entries[j].env);
kfree(envs);
}
- if (scev->exprs_ht)
- for (i = 0; i < scev->exprs_ht_cnt; i++)
- kvfree(scev->exprs_ht[i]);
kvfree(scev->exprs_ht);
+ kvfree(scev->exprs_next);
kvfree(scev->worklist.data);
kvfree(scev->envs);
kvfree(scev->exprs);
+ kvfree(scev->linked);
kvfree(scev->discovered);
kfree(scev);
env->scev = NULL;
@@ -1951,6 +3141,7 @@ void bpf_free_scev(struct bpf_verifier_env *env)
int bpf_init_scev(struct bpf_verifier_env *env)
{
struct scev *scev;
+ u32 r;
scev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);
if (!scev)
@@ -1958,13 +3149,17 @@ int bpf_init_scev(struct bpf_verifier_env *env)
env->scev = scev;
bpf_mark_reg_known_scalar(&scev->zero_reg, 0);
bpf_mark_reg_unknown(&scev->unknown_reg);
- /* A power of two for hash & (exprs_ht_cnt - 1)` indexing. */
- scev->exprs_ht_cnt = roundup_pow_of_two(max(256U, DIV_ROUND_UP(env->prog->len, 4)));
- scev->exprs_ht = kvcalloc(scev->exprs_ht_cnt, sizeof(*scev->exprs_ht), GFP_KERNEL_ACCOUNT);
- if (!scev->exprs_ht)
- goto nomem;
- if (expr0(scev, UNKNOWN) < 0 || expr0(scev, OPAQUE) < 0)
+ setup_initial_loop_env(&scev->identity_env);
+ if (grow_exprs(scev, roundup_pow_of_two(REG_EXPR_ID(REGS_NUM))))
goto nomem;
+ scev->exprs[UNKNOWN_EXPR_ID] = (struct expr){ .op = UNKNOWN };
+ scev->exprs[OPAQUE_EXPR_ID] = (struct expr){ .op = OPAQUE };
+ for (r = 0; r < REGS_NUM; r++)
+ scev->exprs[REG_EXPR_ID(r)] = (struct expr){ .op = REG, .is_vn = true,
+ .params = { r, 0 } };
+ for (r = 0; r < REG_EXPR_ID(REGS_NUM); r++)
+ set_expr_base(scev, &scev->exprs[r], r);
+ scev->exprs_cnt = REG_EXPR_ID(REGS_NUM);
scev->envs = kvcalloc(env->prog->len, sizeof(*scev->envs), GFP_KERNEL_ACCOUNT);
scev->discovered = kvcalloc(env->prog->len, sizeof(*scev->discovered), GFP_KERNEL_ACCOUNT);
if (!scev->envs || !scev->discovered)
@@ -2014,24 +3209,15 @@ static struct bpf_reg_state *scev_reg_for_linear(struct bpf_func_state *st, u32
return &stack->spilled_ptr;
}
-/* Do the registers or stack slots @a and @b hold the same number in @st? */
-static bool scev_regs_equal(struct bpf_func_state *st, u32 a, u32 b)
-{
- const struct bpf_reg_state *ra = scev_reg_for_linear(st, a);
- const struct bpf_reg_state *rb = scev_reg_for_linear(st, b);
-
- if (!ra || !rb || ra->type != SCALAR_VALUE || rb->type != SCALAR_VALUE)
- return false;
- if (tnum_is_const(ra->var_off) && tnum_is_const(rb->var_off))
- return ra->var_off.value == rb->var_off.value;
- return ra->id && ra->id == rb->id && ra->delta == rb->delta;
-}
-
/* '*(u32 *)(r10 - 8) = rX' left a number in the low half of the slot. */
static struct bpf_reg_state *scev_reg_for_spill32(struct bpf_func_state *st, u32 r)
{
struct bpf_stack_state *stack = scev_regno_to_stack(st, r);
+#ifdef __BIG_ENDIAN
+ /* a 32-bit spill is in the upper 32 bits of the slot */
+ return NULL;
+#endif
if (!stack || bpf_spill_size(stack) != 4 || stack->spilled_ptr.type != SCALAR_VALUE)
return NULL;
return &stack->spilled_ptr;
@@ -2140,8 +3326,7 @@ static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_sta
* 'i' is the loop iteration number, starting from 0.
* 'zext32' indicates the latch is for (zext32 (linear ...)) SCEV.
* 'jmp32' indicates that the latch is a JMP32 instruction.
- * 'base_reg' is the register in <base>. 'copy_reg' is -1, or <reg> is made from that register,
- * which has to be equal to 'base_reg' at the entry of the loop, see COPY_SCEV.
+ * 'base_reg' is the register in <base>.
*/
struct linear_latch {
u32 insn_idx;
@@ -2149,7 +3334,6 @@ struct linear_latch {
u32 step_expr;
u32 bound_expr;
u32 base_reg;
- int copy_reg;
u8 op;
bool zext32;
bool jmp32;
@@ -2173,7 +3357,7 @@ static int match_linear_latch(struct bpf_verifier_env *env,
struct env *latch_env;
u32 src_reg_scev;
u32 dst_reg_scev;
- u32 t, l, r, op;
+ u32 l, r, op;
int id;
op = BPF_OP(insn->code);
@@ -2203,11 +3387,6 @@ static int match_linear_latch(struct bpf_verifier_env *env,
return -EFAULT;
dst_reg_scev = latch_env->reg2scev[insn->dst_reg];
src_reg_scev = latch_env->reg2scev[insn->src_reg];
- latch->copy_reg = -1;
- if (is_copy(scev, dst_reg_scev, &latch->copy_reg, &t))
- dst_reg_scev = t;
- else if (BPF_SRC(insn->code) == BPF_X && is_copy(scev, src_reg_scev, &latch->copy_reg, &t))
- src_reg_scev = t;
/*
* Make sure (linear ...) is in dst_reg_scev:
* 'if <invariant> <op> <linear>' ⇔
@@ -2905,8 +4084,6 @@ static bool compute_max_iters(struct bpf_verifier_env *env,
iters->iv_reg = -1;
- if (latch->copy_reg >= 0 && !scev_regs_equal(st, latch->copy_reg, latch->base_reg))
- return false;
if (!eval_expr(env, scev, st, latch->base_expr, &initial_val) ||
!eval_expr(env, scev, st, latch->step_expr, &step_val) ||
!eval_expr(env, scev, st, latch->bound_expr, &bound_val))
@@ -3051,7 +4228,7 @@ static bool is_unbound_scev_reg(struct bpf_verifier_env *env, const struct bpf_f
{
const struct bpf_reg_state *reg = scev_reg_for_read(env, st, r);
- return reg && reg->type == SCALAR_VALUE && !reg->id && reg->step <= 1 &&
+ return reg && reg->type == SCALAR_VALUE && reg->step <= 1 &&
tnum_is_unknown(reg->var_off) &&
reg->r64.size == U64_MAX && reg->r32.size == U32_MAX;
}
@@ -3114,7 +4291,7 @@ static bool is_const_scev_reg(struct bpf_verifier_env *env, int insn_idx, u32 r)
}
/* Main logic in verifier.c forbids varying offsets for certain register types. */
-static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
+bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg)
{
if (type_may_be_null(reg->type))
return false;
@@ -3137,9 +4314,6 @@ static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
static void scratch_widened_reg_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
{
switch (base_type(reg->type)) {
- case SCALAR_VALUE:
- clear_scalar_id(reg);
- break;
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
reg->id = ++env->id_gen;
@@ -3161,7 +4335,7 @@ static bool is_widenable_any(struct bpf_verifier_env *env, struct bpf_func_state
if (!is_any(scev, id, &l, &rr))
return false;
reg = scev_reg_for_read(env, loop_entry, r);
- if (!reg || !is_widenable_reg_type(reg))
+ if (!reg || !bpf_is_widenable_reg_type(reg))
return false;
scev->stack_sz = 0;
@@ -3219,8 +4393,10 @@ struct linear_coefs {
u32 base_reg;
s64 slope;
bool zext32;
- /* the low half of a stack slot */
+ /* with zext32: the low 32 bits of a stack slot */
bool spill32;
+ /* with zext32: the low 32 bits are sign extended */
+ bool sext32;
};
static bool is_simple_slope(struct scev *scev, u32 id, s64 *slope)
@@ -3236,55 +4412,25 @@ static bool is_simple_linear(struct scev *scev, u32 id, struct linear_coefs *out
u32 base, slope;
out->spill32 = false;
- return is_linear_or_linear32(scev, id, &base, &slope, &out->zext32) &&
- is_reg(scev, base, &out->base_reg) &&
+ out->sext32 = is_unop(scev, SEXT32, id, &id);
+ if (!is_linear_or_linear32(scev, id, &base, &slope, &out->zext32) ||
+ (out->sext32 && out->zext32))
+ return false;
+ out->zext32 |= out->sext32;
+ return is_reg(scev, base, &out->base_reg) &&
is_simple_slope(scev, slope, &out->slope);
}
/*
- * Is @r 'what it is in @st + slope * k' at the header in iteration k? @id is its SCEV there, @st is
- * the state that entered the loop. At a jump in the loop @id can be what another register was at
- * the header. @st says nothing about @r then.
+ * Is @r 'its entry value + slope * k' at the header in iteration k? @id is its SCEV there. At a
+ * jump in the loop @id can be linear in the entry value of another register: the entry value of @r
+ * does not bound it then.
*/
-static bool is_linear_at_header(struct scev *scev, struct bpf_func_state *st, u32 id, u32 r,
- struct linear_coefs *out)
+static bool is_linear_at_header(struct scev *scev, u32 id, u32 r, struct linear_coefs *out)
{
- u32 copy, orig;
-
- if (is_copy(scev, id, ©, &orig))
- return copy == r && is_simple_linear(scev, orig, out) &&
- scev_regs_equal(st, r, out->base_reg);
return is_simple_linear(scev, id, out) && out->base_reg == r;
}
-/*
- * @st is at the header of a loop that @entry entered. A copy of an induction variable is equal to
- * it there in every iteration. They got their ranges one by one: give them one id, like 'r2 = r1'
- * does, so that a test of one of them is a test of both.
- */
-static void link_copies(struct bpf_verifier_env *env, struct env *header_env,
- struct bpf_func_state *entry, struct bpf_func_state *st)
-{
- struct bpf_reg_state *reg, *orig;
- struct linear_coefs coefs;
- u32 r;
-
- for (r = 0; r < REGS_NUM; r++) {
- if (!is_linear_at_header(env->scev, entry, header_env->reg2scev[r], r, &coefs) ||
- coefs.base_reg == r)
- continue;
- reg = scev_reg_for_linear(st, r);
- orig = scev_reg_for_linear(st, coefs.base_reg);
- if (!reg || !orig || reg->type != SCALAR_VALUE || orig->type != SCALAR_VALUE ||
- tnum_is_const(orig->var_off))
- continue;
- if (!orig->id)
- orig->id = ++env->id_gen;
- reg->id = orig->id;
- reg->delta = orig->delta;
- }
-}
-
/*
* A 32-bit counter that lives on the stack: the SCEV of slot @r is
* (spill32 (linear (zext32 @r) slope)) and there is a 32-bit number in the slot in @st.
@@ -3303,6 +4449,7 @@ static struct bpf_reg_state *spill32_counter(struct scev *scev, struct bpf_func_
return NULL;
out->zext32 = true;
out->spill32 = true;
+ out->sext32 = false;
return scev_reg_for_spill32(st, r);
}
@@ -3311,6 +4458,11 @@ static struct cnum64 cnum64_zext32(struct cnum32 r32)
return cnum64_from_urange(cnum32_umin(r32), cnum32_umax(r32));
}
+static struct cnum64 cnum64_sext32(struct cnum32 r32)
+{
+ return cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32));
+}
+
/* Compute the range an induction variable in `reg` spans over the loop. */
static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,
struct linear_coefs *coefs, struct bounds *out)
@@ -3340,12 +4492,14 @@ static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,
r32 = CNUM32_UNBOUNDED;
if (coefs->zext32) {
r32 = cnum32_from_cnum64(r64);
- r64 = cnum64_zext32(r32);
+ r64 = coefs->sext32 ? cnum64_sext32(r32) : cnum64_zext32(r32);
/*
* 32-bit iteration overflow is equivalent to subtracting N * 2**32:
* (base + slope * k) % slope ≠ (base + slope * k - N * 2**32) % slope.
*/
- overflow |= cnum32_contains(r32, 0) && cnum32_contains(r32, U32_MAX);
+ overflow |= coefs->sext32 ?
+ cnum32_contains(r32, S32_MAX) && cnum32_contains(r32, S32_MIN) :
+ cnum32_contains(r32, 0) && cnum32_contains(r32, U32_MAX);
/*
* The entry and zero-extended values must agree on how they define `base`,
* otherwise `base + slope * k` would define different sets of points between
@@ -3376,10 +4530,27 @@ static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,
out->r32 = r32;
}
-static void iv_bounds(struct bounds *bounds, struct cnum64 iv_range)
+/*
+ * Is @r the induction variable that the latch tests, or congruent to it: equal to it at the header
+ * of the loop at @h in every iteration? Then the range of the one is the range of the other.
+ */
+static bool is_iv_at_header(struct bpf_verifier_env *env, int h, int iv_reg, u32 r)
+{
+ s64 delta;
+
+ if (iv_reg < 0)
+ return false;
+ return r == iv_reg || (const_diff_at_header(env, h, iv_reg, r, &delta) && !delta);
+}
+
+static void iv_bounds(struct bounds *bounds, const struct linear_coefs *coefs,
+ struct cnum64 iv_range)
{
struct cnum64 r64 = cnum64_intersect(bounds->r64, iv_range);
+ /* The latch bounds the zero extension. With bit 31 set the sign extension differs. */
+ if (coefs->sext32 && cnum64_umax(iv_range) > S32_MAX)
+ return;
if (!cnum64_is_empty(r64))
bounds->r64 = r64;
}
@@ -3693,8 +4864,8 @@ int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_sta
continue;
}
/* If SCEV for r is (linear <reg> <slope>) */
- if (reg && is_linear_at_header(scev, cur_func, r_scev, r, &coefs) &&
- is_widenable_reg_type(reg)) {
+ if (reg && is_linear_at_header(scev, r_scev, r, &coefs) &&
+ bpf_is_widenable_reg_type(reg)) {
/* 32-bit ALU operations on pointers convert them to scalars */
if (coefs.zext32 && reg->type != SCALAR_VALUE)
goto cant_widen;
@@ -3891,7 +5062,7 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
if (back && (!val || !entry_val || !bpf_reg_union_compatible(val, entry_val)))
continue;
if (test_bit(r, iters->mask_regs)) {
- /* The range stays. It's no longer equal to the registers with its id. */
+ /* the range stays */
err = scev_reg_for_write(env, cur_func, r, ®);
if (!err && back)
err = bpf_reg_union(env, reg, entry_val);
@@ -3903,13 +5074,12 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
bpf_log(log, " stays in 0..%llu, it loses bits only\n",
reg_umax(reg));
}
- scratch_widened_reg_id(env, reg);
mark_scev_reg_scratched(env, r);
continue;
}
/* If SCEV for r is (linear <reg> <slope>)*/
- if (spill32 || is_linear_at_header(scev, entry_func, r_expr, r, &coefs)) {
+ if (spill32 || is_linear_at_header(scev, r_expr, r, &coefs)) {
/* the range is derived from @loop_entry: bpf_clamp_scev_regs() */
if (back)
continue;
@@ -3919,8 +5089,8 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
if (err)
return err;
linear_bounds(reg, iters->max_header_count, &coefs, &bounds);
- if (coefs.base_reg == iters->iv_reg)
- iv_bounds(&bounds, iters->iv_range);
+ if (is_iv_at_header(env, insn_idx, iters->iv_reg, coefs.base_reg))
+ iv_bounds(&bounds, &coefs, iters->iv_range);
if (log->level & BPF_LOG_LEVEL2) {
bpf_log(log, "loop header at %d, widening ", insn_idx);
log_reg(env, r);
@@ -3957,7 +5127,6 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
mark_scev_reg_scratched(env, r);
}
}
- link_copies(env, header_env, entry_func, cur_func);
return 1;
}
@@ -3967,6 +5136,7 @@ static bool is_moved_linear(struct scev *scev, u32 id, struct linear_coefs *out,
u32 base, slope, l, r;
out->spill32 = false;
+ out->sext32 = false;
return is_linear_or_linear32(scev, id, &base, &slope, &out->zext32) && !out->zext32 &&
is_add(scev, base, &l, &r) && is_reg(scev, l, &out->base_reg) &&
is_imm(scev, r, moved) && is_simple_slope(scev, slope, &out->slope);
@@ -4014,7 +5184,7 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur
goto clamp;
/* If SCEV for r is (linear <reg> <slope>)*/
- if (!is_linear_at_header(scev, entry_st, r_scev, r, &coefs) &&
+ if (!is_linear_at_header(scev, r_scev, r, &coefs) &&
!(behind && is_moved_linear(scev, r_scev, &coefs, &moved) &&
coefs.base_reg == r))
continue;
@@ -4037,13 +5207,17 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur
* bpf_compute_loop_iters() gives no range to a pointer to arena that moves, and
* it does not look at dead registers. Set a range only where it would.
*/
- if (!is_widenable_reg_type(entry_reg) ||
+ if (!bpf_is_widenable_reg_type(entry_reg) ||
(coefs.zext32 && entry_reg->type != SCALAR_VALUE))
continue;
clamp:
linear_bounds(entry_reg, max_header_count, &coefs, &bounds);
- if (coefs.base_reg == entry->iv_reg && !moved)
- iv_bounds(&bounds, entry->iv_range);
+ /*
+ * iv_range is the range at the header. After the latch @r can be the zero extension
+ * of its header value. @reg went through that insn and has what holds of the range.
+ */
+ if (!behind && is_iv_at_header(env, insn_idx, entry->iv_reg, coefs.base_reg))
+ iv_bounds(&bounds, &coefs, entry->iv_range);
if (moved) {
/* a sum that can wrap has another residue, see scalar_step_add() */
if (check_add_overflow(cnum64_smin(bounds.r64), moved, &sum) ||
@@ -4084,8 +5258,5 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur
return err;
mark_scev_reg_scratched(env, r);
}
- /* behind the jump the variable may have moved on: its copy is what it was at the head */
- if (!behind)
- link_copies(env, header_env, entry_st, cur_func_state);
return 0;
}
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index efc0870b85c2a3..48359e789faadb 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -58,7 +58,7 @@ static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
return true;
/* a name of what the caller has, see BPF_INHERITED_ID */
- if (((old_id | cur_id) & ~BPF_ADD_CONST) >= BPF_INHERITED_ID)
+ if ((old_id | cur_id) >= BPF_INHERITED_ID)
return old_id == cur_id;
for (i = 0; i < idmap->cnt; i++) {
@@ -85,49 +85,6 @@ static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
return false;
}
-/*
- * Compare scalar register IDs for state equivalence.
- *
- * When old_id == 0, the old register is independent - not linked to any
- * other register. Any linking in the current state only adds constraints,
- * making it more restrictive. Since the old state didn't rely on any ID
- * relationships for this register, it's always safe to accept cur regardless
- * of its ID. Hence, return true immediately.
- *
- * When old_id != 0 but cur_id == 0, we need to ensure that different
- * independent registers in cur don't incorrectly satisfy the ID matching
- * requirements of linked registers in old.
- *
- * Example: if old has r6.id=X and r7.id=X (linked), but cur has r6.id=0
- * and r7.id=0 (both independent), without temp IDs both would map old_id=X
- * to cur_id=0 and pass. With temp IDs: r6 maps X->temp1, r7 tries to map
- * X->temp2, but X is already mapped to temp1, so the check fails correctly.
- *
- * When old_id has BPF_ADD_CONST set, the compound id (base | flag) and the
- * base id (flag stripped) must both map consistently. Example: old has
- * r2.id=A, r3.id=A|flag (r3 = r2 + delta), cur has r2.id=B, r3.id=C|flag
- * (r3 derived from unrelated r4). Without the base check, idmap gets two
- * independent entries A->B and A|flag->C|flag, missing that A->C conflicts
- * with A->B. The base ID cross-check catches this.
- */
-static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
-{
- if (!old_id)
- return true;
-
- cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
-
- if (!check_ids(old_id, cur_id, idmap))
- return false;
- if (old_id & BPF_ADD_CONST) {
- old_id &= ~BPF_ADD_CONST;
- cur_id &= ~BPF_ADD_CONST;
- if (!check_ids(old_id, cur_id, idmap))
- return false;
- }
- return true;
-}
-
static void __clean_func_state(struct bpf_verifier_env *env,
struct bpf_func_state *st,
u16 live_regs, int frame)
@@ -168,6 +125,16 @@ static void __clean_func_state(struct bpf_verifier_env *env,
stype == STACK_IRQ_FLAG)
continue;
+ /*
+ * When the half-slot closer to FP is dead, what remains of a
+ * 64-bit spill looks like a 32-bit spill: the low 32 bits of
+ * the value. On big endian the other half-slot holds the upper
+ * 32 bits.
+ */
+ if (hi_live && bpf_spill_size(bpf_stack_slot(st, i)) == BPF_REG_SIZE &&
+ !bpf_stack_narrow_access_ok(0, BPF_REG_SIZE / 2, BPF_REG_SIZE))
+ continue;
+
/*
* Only scalar spills can be degraded to raw stack bytes
* when their high half is dead. Pointer spills need the
@@ -262,65 +229,8 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
/* explore_alu_limits disables tnum_in() and range_within()
* logic and requires everything to be strict
*/
- return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
- check_scalar_ids(rold->id, rcur->id, idmap);
+ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0;
}
- /*
- * Linked register tracking uses rold->id to detect relationships.
- * When rold->id == 0, the register is independent and any linking
- * in rcur only adds constraints. When rold->id != 0, we must verify
- * id mapping and (for BPF_ADD_CONST) offset consistency.
- *
- * +------------------+-----------+------------------+---------------+
- * | | rold->id | rold + ADD_CONST | rold->id == 0 |
- * |------------------+-----------+------------------+---------------|
- * | rcur->id | range,ids | false | range |
- * | rcur + ADD_CONST | false | range,ids,off | range |
- * | rcur->id == 0 | range,ids | false | range |
- * +------------------+-----------+------------------+---------------+
- *
- * Why check_ids() for scalar registers?
- *
- * Consider the following BPF code:
- * 1: r6 = ... unbound scalar, ID=a ...
- * 2: r7 = ... unbound scalar, ID=b ...
- * 3: if (r6 > r7) goto +1
- * 4: r6 = r7
- * 5: if (r6 > X) goto ...
- * 6: ... memory operation using r7 ...
- *
- * First verification path is [1-6]:
- * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
- * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
- * r7 <= X, because r6 and r7 share same id.
- * Next verification path is [1-4, 6].
- *
- * Instruction (6) would be reached in two states:
- * I. r6{.id=b}, r7{.id=b} via path 1-6;
- * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
- *
- * Use check_ids() to distinguish these states.
- * ---
- * Also verify that new value satisfies old value range knowledge.
- */
-
- /*
- * ADD_CONST flags must match exactly: BPF_ADD_CONST32 and
- * BPF_ADD_CONST64 have different linking semantics in
- * sync_linked_regs() (alu32 zero-extends, alu64 does not),
- * so one doesn't stand for the other.
- */
- if (rold->id &&
- (rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
- return false;
-
- /* Both have offset linkage: offsets must match */
- if ((rold->id & BPF_ADD_CONST) && rold->delta != rcur->delta)
- return false;
-
- if (!check_scalar_ids(rold->id, rcur->id, idmap))
- return false;
-
return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_KEY:
case PTR_TO_MAP_VALUE:
@@ -446,11 +356,19 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
if (!cur_slot)
return false;
+ /*
+ * The old spill is the first bytes of a wider spill. On big endian
+ * these are not the low bytes of the value.
+ */
+ if (old_type == STACK_SPILL && bpf_is_spilled_reg(cur_slot) &&
+ !bpf_stack_narrow_access_ok(0, bpf_spill_size(old_slot),
+ bpf_spill_size(cur_slot)))
+ return false;
+
/*
* 64 and 32-bit scalar spills vs MISC/INVALID slots and vice versa.
* Load from MISC/INVALID slots produces unbound scalar.
- * Construct a fake register for such stack and call
- * regsafe() to ensure scalar ids are compared.
+ * Construct a fake register for such stack and call regsafe().
*/
if (im == 0 || im == 4) {
old_reg = scalar_reg_for_stack(env, old_slot, im);
@@ -717,7 +635,6 @@ static void reset_idmap_scratch(struct bpf_verifier_env *env)
{
struct bpf_idmap *idmap = &env->idmap_scratch;
- idmap->tmp_id_gen = env->id_gen;
idmap->cnt = 0;
}
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 9004f2673ccf96..04a3b3c80c74e0 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -6692,7 +6692,7 @@ static const struct bpf_func_proto bpf_sys_bpf_proto = {
.might_sleep = true,
.ret_type = RET_INTEGER,
.arg1_type = ARG_ANYTHING,
- .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
+ .arg2_type = ARG_PTR_TO_MEM | MEM_WRITE,
.arg3_type = ARG_MEM_SIZE,
};
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 20b1b9ff574c7d..d549644235c55a 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -2325,6 +2325,36 @@ static bool range_bounds_violation(struct bpf_reg_state *reg)
return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
}
+/* Do @t and [min, max] overlap: is a member of @t in the range? */
+static bool tnum_overlaps_urange(struct tnum t, u64 min, u64 max)
+{
+ u64 tnum_next = tnum_step(t, min);
+
+ return (min & ~t.mask) == t.value || (tnum_next > min && tnum_next <= max);
+}
+
+/* The same for the cnum [@base, @base + @size]. It wraps around at @ut_max. */
+static bool tnum_overlaps_cnum(struct tnum t, u64 base, u64 size, u64 ut_max)
+{
+ u64 end = (base + size) & ut_max;
+
+ if (base <= end)
+ return tnum_overlaps_urange(t, base, end);
+ return tnum_overlaps_urange(t, base, ut_max) || tnum_overlaps_urange(t, 0, end);
+}
+
+/*
+ * A range and var_off don't overlap. reg_bounds_sync() compares var_off with umin and umax: it
+ * doesn't see that [-2, 1], which crosses 0, has no member with 5 in its low three bits.
+ */
+static bool reg_is_empty(struct bpf_reg_state *reg)
+{
+ return range_bounds_violation(reg) ||
+ !tnum_overlaps_cnum(reg->var_off, reg->r64.base, reg->r64.size, U64_MAX) ||
+ !tnum_overlaps_cnum(tnum_subreg(reg->var_off), reg->r32.base, reg->r32.size,
+ U32_MAX);
+}
+
static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
struct bpf_reg_state *reg, const char *ctx)
{
@@ -3548,30 +3578,6 @@ static void mark_non_stack_access(struct bpf_verifier_env *env, int idx)
env->insn_aux_data[idx].non_stack_access = true;
}
-#define LINKED_REGS_MAX 5
-
-struct linked_reg {
- u8 frameno;
- union {
- u16 spi;
- u16 regno;
- };
- bool is_reg;
-};
-
-struct linked_regs {
- int cnt;
- struct linked_reg entries[LINKED_REGS_MAX];
-};
-
-static struct linked_reg *linked_regs_push(struct linked_regs *s)
-{
- if (s->cnt < LINKED_REGS_MAX)
- return &s->entries[s->cnt++];
-
- return NULL;
-}
-
const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
{
const struct btf_type *func;
@@ -3628,27 +3634,6 @@ static bool __is_pointer_value(bool allow_ptr_leaks,
return is_pointer_regtype(reg->type);
}
-static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
- struct bpf_reg_state *src_reg)
-{
- if (src_reg->type != SCALAR_VALUE)
- return;
- /*
- * The verifier is processing rX = rY insn and
- * rY->id has special linked register already.
- * Cleared it, since multiple rX += const are not supported.
- */
- if (src_reg->id & BPF_ADD_CONST)
- clear_scalar_id(src_reg);
- /*
- * Ensure that src_reg has a valid ID that will be copied to
- * dst_reg and then will be used by sync_linked_regs() to
- * propagate min/max range.
- */
- if (!src_reg->id && !tnum_is_const(src_reg->var_off))
- src_reg->id = ++env->id_gen;
-}
-
static void save_register_state(struct bpf_verifier_env *env,
struct bpf_func_state *state,
int spi, struct bpf_reg_state *reg,
@@ -3675,11 +3660,6 @@ static bool is_bpf_st_mem(struct bpf_insn *insn)
return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
}
-static int get_reg_width(struct bpf_reg_state *reg)
-{
- return fls64(reg_umax(reg));
-}
-
/* See comment for mark_fastcall_pattern_for_call() */
static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
struct bpf_func_state *state, int insn_idx, int off)
@@ -3780,16 +3760,7 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
mark_stack_slot_scratched(env, spi);
if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
- bool reg_value_fits;
-
- reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
- /* Make sure that reg had an ID to build a relation on spill. */
- if (reg_value_fits)
- assign_scalar_id_before_mov(env, reg);
save_register_state(env, state, spi, reg, size);
- /* Break the relation on a narrowing spill. */
- if (!reg_value_fits)
- clear_scalar_id(&ss->spilled_ptr);
} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
env->bpf_capable) {
struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
@@ -4092,19 +4063,8 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
if (dst_regno < 0)
return 0;
- if (env->bpf_capable && size == 4 && spill_size == 4 &&
- get_reg_width(reg) <= 32)
- /* Ensure stack slot has an ID to build a relation
- * with the destination register on fill.
- */
- assign_scalar_id_before_mov(env, reg);
+ /* coerce_reg_to_size will adjust the boundaries. */
state->regs[dst_regno] = *reg;
-
- /* Break the relation on a narrowing fill.
- * coerce_reg_to_size will adjust the boundaries.
- */
- if (get_reg_width(reg) > size * BITS_PER_BYTE)
- clear_scalar_id(&state->regs[dst_regno]);
} else {
int spill_cnt = 0, zero_cnt = 0;
@@ -4149,11 +4109,6 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
}
} else if (dst_regno >= 0) {
/* restore register state from stack */
- if (env->bpf_capable)
- /* Ensure stack slot has an ID to build a relation
- * with the destination register on fill.
- */
- assign_scalar_id_before_mov(env, reg);
state->regs[dst_regno] = *reg;
} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
/* If dst_regno==-1, the caller is asking us whether
@@ -6441,14 +6396,28 @@ static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
{
s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
+ s32 field_smin, field_smax;
u32 top_smax_value, top_smin_value;
u32 num_bits = size * 8;
+ if (size == 1) {
+ field_smin = S8_MIN;
+ field_smax = S8_MAX;
+ } else {
+ /* size == 2 */
+ field_smin = S16_MIN;
+ field_smax = S16_MAX;
+ }
+
/*
- * If value fits the non-negative half of the signed N-bit range,
- * sign extension is a noop.
+ * The range already fits the signed N-bit range, so (sN)v == v for every
+ * value of the low 32 bits and the sign extension is a no-op.
+ *
+ * This has to precede reg_step_reset() below: the base/step line stays.
+ * It is about all 64 bits: zext_32_to_64() in the caller discards it
+ * if the upper 32 bits are not zero.
*/
- if (reg_umax(reg) < (1ULL << (num_bits - 1)))
+ if (reg_s32_min(reg) >= field_smin && reg_s32_max(reg) <= field_smax)
return;
/* See comment at reg_step_check_unsigned(). */
@@ -7669,18 +7638,7 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b
/* b/h/w load zero-extends, mark upper bits as known 0 */
coerce_reg_to_size(®s[value_regno], size);
} else {
- /*
- * Sign-extension can change the register value relative
- * to a scalar it is linked with by id (e.g. a zero-
- * extending fill of the same spilled stack slot), thus
- * drop the shared id in that case.
- */
- bool no_sext = reg_umax(®s[value_regno]) <
- (1ULL << (size * BITS_PER_BYTE - 1));
-
coerce_reg_to_size_sx(®s[value_regno], size);
- if (!no_sext)
- clear_scalar_id(®s[value_regno]);
}
}
@@ -11716,16 +11674,11 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
callee->entry_rcu_locks = entry.active_rcu_locks;
callee->entry_preempt_locks = entry.active_preempt_locks;
for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
- /* what a scalar is linked to stays with the caller, so does the delta to it */
- if (callee->regs[i].type == SCALAR_VALUE)
- clear_scalar_id(&callee->regs[i]);
callee->regs[i].id = inherited_id(state, callee->regs[i].id);
callee->regs[i].parent_id = inherited_id(state, callee->regs[i].parent_id);
callee->regs[i].map_uid = inherited_id(state, callee->regs[i].map_uid);
}
for (i = 0; i < callee->out_stack_arg_cnt; i++) {
- if (callee->stack_arg_regs[i].type == SCALAR_VALUE)
- clear_scalar_id(&callee->stack_arg_regs[i]);
callee->stack_arg_regs[i].id = inherited_id(state, callee->stack_arg_regs[i].id);
callee->stack_arg_regs[i].parent_id =
inherited_id(state, callee->stack_arg_regs[i].parent_id);
@@ -11771,19 +11724,18 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env)
static u32 fresh_id(struct bpf_verifier_env *env, struct bpf_idmap *idmap, u32 id)
{
- u32 flags = id & BPF_ADD_CONST, i;
+ u32 i;
- id &= ~BPF_ADD_CONST;
if (!id)
return 0;
for (i = 0; i < idmap->cnt; i++)
if (idmap->map[i].old == id)
- return idmap->map[i].cur | flags;
+ return idmap->map[i].cur;
if (idmap->cnt == BPF_ID_MAP_SIZE)
return 0;
idmap->map[idmap->cnt].old = id;
idmap->map[idmap->cnt].cur = ++env->id_gen;
- return idmap->map[idmap->cnt++].cur | flags;
+ return idmap->map[idmap->cnt++].cur;
}
/*
@@ -15150,6 +15102,12 @@ bool bpf_is_throw_kfunc(struct bpf_insn *insn)
insn->imm == special_kfunc_list[KF_bpf_throw];
}
+bool bpf_is_dynptr_slice_rdwr_kfunc(struct bpf_insn *insn)
+{
+ return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+ insn->imm == special_kfunc_list[KF_bpf_dynptr_slice_rdwr];
+}
+
static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
{
return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
@@ -15974,6 +15932,15 @@ static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg
regs[BPF_REG_0].buf = meta->slice_buf;
if (meta->slice_buf.size)
env->seen_stack_slice = true;
+ /* No insn stores through a slice of 0 bytes */
+ if (verifier_bug_if(meta->slice_buf.size && meta->arg_constant.value &&
+ !type_is_rdonly_mem(regs[BPF_REG_0].type) &&
+ !bpf_scev_in_slice_slots(env, meta->slice_buf.off,
+ meta->slice_buf.size,
+ meta->slice_buf.size ==
+ meta->arg_constant.value),
+ env, "slice buffer is not in scev slice_slots"))
+ return -EFAULT;
} else {
return 0;
}
@@ -17841,13 +17808,6 @@ static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *ins
/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
bool need_bswap = alu64 || (to_le == is_big_endian);
- /*
- * If the register is mutated, manually reset its scalar ID to break
- * any existing ties and avoid incorrect bounds propagation.
- */
- if (need_bswap || insn->imm == 16 || insn->imm == 32)
- clear_scalar_id(dst_reg);
-
if (need_bswap) {
if (insn->imm == 16)
dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
@@ -17948,7 +17908,6 @@ static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *ins
* like any other. At this insn the branch is a part of the state that is looked at:
* it must not be compared with it.
*/
- clear_scalar_id(reg);
return adjust_scalar_min_max_vals(env, insn, reg, *src_reg);
}
@@ -18158,10 +18117,8 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
- bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
struct bpf_insn_aux_data *aux = cur_aux(env);
u8 opcode = BPF_OP(insn->code);
- int err;
dst_reg = ®s[insn->dst_reg];
if (BPF_SRC(insn->code) == BPF_X)
@@ -18268,69 +18225,7 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
verbose(env, "verifier internal error: no src_reg\n");
return -EFAULT;
}
- /*
- * For alu32 linked register tracking, we need to check dst_reg's
- * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
- * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
- */
- u64 dst_umax = reg_umax(dst_reg);
-
- err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
- if (err)
- return err;
- /*
- * Compilers can generate the code
- * r1 = r2
- * r1 += 0x1
- * if r2 < 1000 goto ...
- * use r1 in memory access
- * So remember constant delta between r2 and r1 and update r1 after
- * 'if' condition.
- */
- if (env->bpf_capable &&
- (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
- dst_reg->id && is_reg_const(src_reg, alu32) &&
- !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
- u64 val = reg_const_value(src_reg, alu32);
- s32 off;
-
- if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
- goto clear_id;
-
- if (alu32 && (dst_umax > U32_MAX))
- goto clear_id;
-
- off = (s32)val;
-
- if (BPF_OP(insn->code) == BPF_SUB) {
- /* Negating S32_MIN would overflow */
- if (off == S32_MIN)
- goto clear_id;
- off = -off;
- }
-
- if (dst_reg->id & BPF_ADD_CONST) {
- /*
- * If the register already went through rX += val
- * we cannot accumulate another val into rx->off.
- */
-clear_id:
- clear_scalar_id(dst_reg);
- } else {
- if (alu32)
- dst_reg->id |= BPF_ADD_CONST32;
- else
- dst_reg->id |= BPF_ADD_CONST64;
- dst_reg->delta = off;
- }
- } else {
- /*
- * Make sure ID is cleared otherwise dst_reg min/max could be
- * incorrectly propagated into other registers by sync_linked_regs()
- */
- clear_scalar_id(dst_reg);
- }
- return 0;
+ return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/*
@@ -18544,7 +18439,6 @@ void bpf_reg_union_range(struct bpf_reg_state *acc, const struct bpf_reg_state *
/*
* Extends acc's scalar range to include src's scalar range.
* Caller must ensure that other kinds of metadata is compatible.
- * Caller must clear acc's scalar ID.
*/
int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
const struct bpf_reg_state *src)
@@ -18685,7 +18579,6 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
/* case: R1 = R2
* copy register state to dest reg
*/
- assign_scalar_id_before_mov(env, src_reg);
*dst_reg = *src_reg;
} else {
/* case: R1 = (s8, s16 s32)R2 */
@@ -18695,14 +18588,7 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
insn->src_reg);
return -EACCES;
} else if (src_reg->type == SCALAR_VALUE) {
- bool no_sext;
-
- no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
- if (no_sext)
- assign_scalar_id_before_mov(env, src_reg);
*dst_reg = *src_reg;
- if (!no_sext)
- clear_scalar_id(dst_reg);
coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
} else {
mark_reg_unknown(env, regs, insn->dst_reg);
@@ -18716,29 +18602,10 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
insn->src_reg);
return -EACCES;
} else if (src_reg->type == SCALAR_VALUE) {
- if (insn->off == 0) {
- bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
-
- if (is_src_reg_u32)
- assign_scalar_id_before_mov(env, src_reg);
- *dst_reg = *src_reg;
- /* Make sure ID is cleared if src_reg is not in u32
- * range otherwise dst_reg min/max could be incorrectly
- * propagated into src_reg by sync_linked_regs()
- */
- if (!is_src_reg_u32)
- clear_scalar_id(dst_reg);
- } else {
- /* case: W1 = (s8, s16)W2 */
- bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
-
- if (no_sext)
- assign_scalar_id_before_mov(env, src_reg);
- *dst_reg = *src_reg;
- if (!no_sext)
- clear_scalar_id(dst_reg);
+ *dst_reg = *src_reg;
+ /* case: W1 = (s8, s16)W2 */
+ if (insn->off)
coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
- }
} else {
mark_reg_unknown(env, regs,
insn->dst_reg);
@@ -18902,7 +18769,7 @@ static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode,
* reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
* TRUE branch will be taken.
*/
- if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
+ if (reg_is_empty(&env->false_reg1) || reg_is_empty(&env->false_reg2))
return 1;
/* Jump (TRUE) branch */
@@ -18914,7 +18781,7 @@ static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode,
* reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
* Only FALSE branch will be taken.
*/
- if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
+ if (reg_is_empty(&env->true_reg1) || reg_is_empty(&env->true_reg2))
return 0;
/* Both branches are possible, we can't determine which one will be taken. */
@@ -19537,116 +19404,178 @@ static bool try_match_pkt_pointers(const struct bpf_insn *insn,
return true;
}
-static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
- u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
+/* a == b (mod 2^N) implies a == b if both fit in uN or both fit in sN. N is @bits. */
+static bool regs_fit_in_bits(const struct bpf_reg_state *a, const struct bpf_reg_state *b,
+ u32 bits)
{
- struct linked_reg *e;
+ u64 umax = GENMASK_ULL(bits - 1, 0);
+ s64 smax = umax >> 1;
- if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
- return;
+ return (reg_umax(a) <= umax && reg_umax(b) <= umax) ||
+ (reg_smin(a) >= -smax - 1 && reg_smax(a) <= smax &&
+ reg_smin(b) >= -smax - 1 && reg_smax(b) <= smax);
+}
- e = linked_regs_push(reg_set);
- if (e) {
- e->frameno = frameno;
- e->is_reg = is_reg;
- e->regno = spi_or_reg;
- } else {
- clear_scalar_id(reg);
- }
+/*
+ * The state of the SCEV register @r. As in check_stack_read_fixed_off() a fill of @bits bits from
+ * byte @fill_off of the slot reads the low bits of the spill.
+ */
+static struct bpf_reg_state *scev_reg_for_fill(struct bpf_func_state *frame, u32 r, u32 fill_off,
+ u32 bits)
+{
+ struct bpf_stack_state *ss;
+
+ if (r < MAX_BPF_REG)
+ return &frame->regs[r];
+ if (r - MAX_BPF_REG >= bpf_stack_nr_slots(frame))
+ return NULL;
+ ss = bpf_stack_slot(frame, r - MAX_BPF_REG);
+ if (!bpf_is_spilled_reg(ss) || bpf_spill_size(ss) * BITS_PER_BYTE < bits ||
+ !bpf_stack_narrow_access_ok(fill_off, bits / BITS_PER_BYTE, bpf_spill_size(ss)))
+ return NULL;
+ return &ss->spilled_ptr;
}
-/* For all R being scalar registers or spilled scalar registers
- * in verifier state, save R in linked_regs if R->id == id.
- * If there are too many Rs sharing same id, reset id for leftover Rs.
+/*
+ * Scalar evolution promoted memory to the SCEV register *@regno, see struct env there, and names
+ * its address at the jump at @idx. This state knows which memory it is: the frame that is returned,
+ * its stack slot *@regno, *@fill_off counts from the start of the slot. The stack of a caller only:
+ * other memory has no state, and a store through r10 is no def of memory for scalar evolution.
+ * What holds the address is live: it was compared all the way from its def. Every place that
+ * compares, joins or drops states cleans them of what is dead first, see flow_arrive().
*/
-static void collect_linked_regs(struct bpf_verifier_env *env,
- struct bpf_verifier_state *vstate,
- u32 id,
- struct linked_regs *linked_regs)
+static struct bpf_func_state *scev_mem_to_slot(struct bpf_verifier_env *env,
+ struct bpf_verifier_state *vstate, int idx,
+ u32 *regno, u32 *fill_off)
{
- struct bpf_insn_aux_data *aux = env->insn_aux_data;
- struct bpf_func_state *func;
- struct bpf_reg_state *reg;
- u16 live_regs;
- int i, j;
+ struct bpf_reg_state *ptr;
+ u32 base_regno;
+ s64 addr;
- id = id & ~BPF_ADD_CONST;
- for (i = vstate->curframe; i >= 0; i--) {
- live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
- func = vstate->frame[i];
- for (j = 0; j < BPF_REG_FP; j++) {
- if (!(live_regs & BIT(j)))
- continue;
- reg = &func->regs[j];
- __collect_linked_regs(linked_regs, reg, id, i, j, true);
- }
- for (j = 0; j < bpf_stack_nr_slots(func); j++) {
- struct bpf_stack_state *ss = bpf_stack_slot(func, j);
+ if (!bpf_scev_mem_addr(env, idx, *regno, &base_regno, &addr))
+ return NULL;
+ ptr = scev_reg_for_fill(vstate->frame[vstate->curframe], base_regno, 0, 64);
+ if (!ptr || ptr->type != PTR_TO_STACK || !tnum_is_const(ptr->var_off) ||
+ ptr->frameno >= vstate->curframe)
+ return NULL;
+ addr += ptr->var_off.value + *fill_off;
+ if (addr >= 0 || addr < -MAX_BPF_STACK_JIT)
+ return NULL;
+ *regno = MAX_BPF_REG + bpf_get_spi(addr);
+ *fill_off = addr & (BPF_REG_SIZE - 1);
+ return vstate->frame[ptr->frameno];
+}
- if (!bpf_is_spilled_reg(ss))
- continue;
- reg = &ss->spilled_ptr;
- __collect_linked_regs(linked_regs, reg, id, i, j, false);
- }
- }
+/*
+ * p = buf + i; if (i > 100) return 0; *p = 0;
+ * p is @dst_reg, x is @ptr_reg, i is @off_reg. Scalar evolution says that p == x + i. So the insns
+ * 'p = x; p += i' are a no-op at run time, and a state that is sound before them is sound after
+ * them: apply their transfer function. Type, object and offset of p are taken from x as it is now;
+ * how p was computed does not matter.
+ * The old p is replaced, not intersected: a state does not distinguish two values of one hash map,
+ * and the intersection of an offset into the one with an offset into the other holds for neither.
+ * It is replaced only if the new range is a subset of the old one. An empty range is a subset too:
+ * the path is infeasible, p is left as it is.
+ */
+static bool recompute_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *dst_reg,
+ const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg)
+{
+ struct bpf_reg_state sum = *ptr_reg;
+
+ /* the cpu can speculate past the jump with an out-of-bounds index */
+ if (!env->bypass_spec_v1)
+ return false;
+ /* 'p += i' assigns a new id to a packet pointer */
+ if (ptr_reg->type == SCALAR_VALUE || type_is_pkt_pointer(ptr_reg->type) ||
+ !bpf_is_widenable_reg_type(ptr_reg))
+ return false;
+ __mark_reg32_unbounded(&sum);
+ scalar_step_add(&sum, ptr_reg, off_reg);
+ sum.r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
+ sum.var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
+ reg_bounds_sync(&sum);
+ if (reg_is_empty(&sum) || const_tnum_range_mismatch(&sum) ||
+ const_tnum_range_mismatch_32(&sum))
+ return false;
+ if (!bpf_reg_union_compatible(dst_reg, &sum) || !cnum64_is_subset(dst_reg->r64, sum.r64))
+ return false;
+ *dst_reg = sum;
+ return true;
}
-/* For all R in linked_regs, copy known_reg range into R
- * if R->id == known_reg->id.
+/*
+ * The jump at @idx refined @regno. A register that scalar evolution links to it holds
+ * @regno + delta on every path to the jump: intersect the two. The intersection is empty: no
+ * execution gets here with this state (the path is infeasible), the register is left as it is.
*/
-static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
- struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
+static void refine_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
+ int idx, u32 regno)
{
- struct bpf_reg_state fake_reg;
- struct bpf_reg_state *reg;
- struct linked_reg *e;
- int i;
+ struct bpf_func_state *frame = vstate->frame[vstate->curframe], *linked_frame;
+ struct bpf_reg_state *reg, *base_reg, implied, saved;
+ u32 pos, linked_regno, fill_off, bits;
+ int base_regno;
+ s64 delta;
- for (i = 0; i < linked_regs->cnt; ++i) {
- e = &linked_regs->entries[i];
- reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
- : &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr;
- if (reg->type != SCALAR_VALUE || reg == known_reg)
- continue;
- if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
+ if (frame->regs[regno].type != SCALAR_VALUE)
+ return;
+ for (pos = 0;
+ bpf_scev_next_linked_reg(env, idx, regno, &pos, &linked_regno, &fill_off, &base_regno,
+ &delta, &bits);
+ pos++) {
+ linked_frame = frame;
+ if (linked_regno >= BPF_SCEV_REGS_NUM)
+ linked_frame = scev_mem_to_slot(env, vstate, idx, &linked_regno, &fill_off);
+ if (!linked_frame)
continue;
+ reg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);
/*
- * Skip mixed 32/64-bit links: the delta relationship doesn't
- * hold across different ALU widths.
+ * The other half-slot of a 64-bit spill is dead: __clean_func_state() left
+ * a 32-bit spill, the low 32 bits of the value.
*/
- if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
+ if (!reg && bits == 64 &&
+ bpf_stack_narrow_access_ok(fill_off, BPF_REG_SIZE / 2, BPF_REG_SIZE)) {
+ bits = 32;
+ reg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);
+ }
+ if (!reg || (base_regno < 0 && reg->type != SCALAR_VALUE))
continue;
- if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
- reg->delta == known_reg->delta) {
- *reg = *known_reg;
- } else {
- s32 saved_off = reg->delta;
- u32 saved_id = reg->id;
- fake_reg.type = SCALAR_VALUE;
- __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
-
- /* reg = known_reg; reg += delta */
- *reg = *known_reg;
- /*
- * Must preserve off and id, otherwise another sync_linked_regs()
- * will be incorrect.
- */
- reg->delta = saved_off;
- reg->id = saved_id;
-
- scalar_step_add(reg, reg, &fake_reg);
- scalar32_min_max_add(reg, &fake_reg);
- scalar_min_max_add(reg, &fake_reg);
- reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
- if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
- zext_32_to_64(reg);
- reg_bounds_sync(reg);
- }
- if (e->is_reg)
- mark_reg_scratched(env, e->regno);
- else
- mark_stack_slot_scratched(env, e->spi);
+ implied = frame->regs[regno];
+ add_scalar_to_reg(&implied, delta);
+ if (base_regno >= 0) {
+ base_reg = scev_reg_for_fill(frame, base_regno, 0, 64);
+ if (base_reg && bits == 64 && recompute_ptr(env, reg, base_reg, &implied))
+ goto scratch;
+ continue;
+ }
+ if (regs_fit_in_bits(reg, &implied, bits))
+ bits = 64;
+ if (bits < 32)
+ continue;
+ /* tnum_intersect() of two tnums that don't overlap is not empty */
+ if (!tnum_overlap(bits == 32 ? tnum_subreg(reg->var_off) : reg->var_off,
+ bits == 32 ? tnum_subreg(implied.var_off) : implied.var_off))
+ continue;
+ saved = *reg;
+ /*
+ * Equal in 64 bits is equal in the low 32 bits too. 'if w1 s> 200' on a zero
+ * extended int refines nothing but the 32-bit range.
+ */
+ regs_refine_cond_op(reg, &implied, BPF_JEQ, true);
+ if (bits == 64)
+ regs_refine_cond_op(reg, &implied, BPF_JEQ, false);
+ reg_bounds_sync(reg);
+ if (reg_is_empty(reg) || const_tnum_range_mismatch(reg) ||
+ const_tnum_range_mismatch_32(reg)) {
+ *reg = saved;
+ continue;
+ }
+scratch:
+ if (linked_regno < MAX_BPF_REG)
+ mark_reg_scratched(env, linked_regno);
+ else if (linked_frame == frame)
+ mark_stack_slot_scratched(env, linked_regno - MAX_BPF_REG);
}
}
@@ -19677,7 +19606,6 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
struct bpf_reg_state *eq_branch_regs;
- struct linked_regs linked_regs = {};
u8 opcode = BPF_OP(insn->code);
bool is_jmp32;
int pred = -1;
@@ -19746,16 +19674,6 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
__mark_reg_known(src_reg, insn->imm);
}
- /*
- * Collect the linked registers before env->{true,false}_reg{1,2} setup,
- * otherwise ids dropped by collect_linked_regs() would be resurrected
- * when env->{true,false}_reg{1,2} are copied back.
- */
- if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
- collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
- if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
- collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
-
is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
env->false_reg1 = *dst_reg;
env->false_reg2 = *src_reg;
@@ -19809,18 +19727,13 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
if (BPF_SRC(insn->code) == BPF_X)
other_branch_regs[insn->src_reg] = env->true_reg2;
- if (BPF_SRC(insn->code) == BPF_X &&
- src_reg->type == SCALAR_VALUE && src_reg->id &&
- !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
- sync_linked_regs(env, this_branch, src_reg, &linked_regs);
- sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
- &linked_regs);
- }
- if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
- !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
- sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
- sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
- &linked_regs);
+ if (env->bpf_capable) {
+ if (BPF_SRC(insn->code) == BPF_X) {
+ refine_linked_regs(env, this_branch, *insn_idx, insn->src_reg);
+ refine_linked_regs(env, other_branch, *insn_idx, insn->src_reg);
+ }
+ refine_linked_regs(env, this_branch, *insn_idx, insn->dst_reg);
+ refine_linked_regs(env, other_branch, *insn_idx, insn->dst_reg);
}
/* if one pointer register is compared to another pointer
@@ -20674,69 +20587,6 @@ static void adjust_btf_func(struct bpf_verifier_env *env)
aux->func_info[i].insn_off = env->subprog_info[i].start;
}
-/* Find id in idset and increment its count, or add new entry */
-static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
-{
- u32 i;
-
- for (i = 0; i < idset->num_ids; i++) {
- if (idset->entries[i].id == id) {
- idset->entries[i].cnt++;
- return;
- }
- }
- /* New id */
- if (idset->num_ids < BPF_ID_MAP_SIZE) {
- idset->entries[idset->num_ids].id = id;
- idset->entries[idset->num_ids].cnt = 1;
- idset->num_ids++;
- }
-}
-
-/* Find id in idset and return its count, or 0 if not found */
-static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
-{
- u32 i;
-
- for (i = 0; i < idset->num_ids; i++) {
- if (idset->entries[i].id == id)
- return idset->entries[i].cnt;
- }
- return 0;
-}
-
-/*
- * Clear singular scalar ids in a state.
- * A register with a non-zero id is called singular if no other register shares
- * the same base id. Such registers can be treated as independent (id=0).
- */
-void bpf_clear_singular_ids(struct bpf_verifier_env *env,
- struct bpf_verifier_state *st)
-{
- struct bpf_idset *idset = &env->idset_scratch;
- struct bpf_func_state *func;
- struct bpf_reg_state *reg;
-
- idset->num_ids = 0;
-
- bpf_for_each_reg_in_vstate(st, func, reg, ({
- if (reg->type != SCALAR_VALUE)
- continue;
- if (!reg->id)
- continue;
- idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
- }));
-
- bpf_for_each_reg_in_vstate(st, func, reg, ({
- if (reg->type != SCALAR_VALUE)
- continue;
- if (!reg->id)
- continue;
- if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
- clear_scalar_id(reg);
- }));
-}
-
/* Return true if it's OK to have the same insn return a different type. */
static bool reg_type_mismatch_ok(enum bpf_reg_type type)
{
diff --git a/tools/testing/selftests/bpf/prog_tests/reg_bounds.c b/tools/testing/selftests/bpf/prog_tests/reg_bounds.c
index 09f7930733beb0..c2079eb642019e 100644
--- a/tools/testing/selftests/bpf/prog_tests/reg_bounds.c
+++ b/tools/testing/selftests/bpf/prog_tests/reg_bounds.c
@@ -1290,7 +1290,8 @@ static int parse_range_cmp_log(const char *log_buf, struct case_spec spec,
* 18: (bf) r0 = r6 ; R0=... R6=...
* Different verifier passes may print
* 18: (bf) r0 = r6
- * as well, but never followed by ';'.
+ * as well, but never followed by ';'. Except for scalar evolution:
+ * t 18: (bf) r0 = r6 ; r0 ... -> ...
* The branches are in the log in the order the verifier looked at them.
*/
q = log_buf;
@@ -1299,7 +1300,7 @@ static int parse_range_cmp_log(const char *log_buf, struct case_spec spec,
while (*s == ' ' || *s == '\t')
s++;
- if (*s == ';')
+ if (*s == ';' && (q == log_buf || q[-1] == '\n'))
break;
q = s;
}
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena.c b/tools/testing/selftests/bpf/progs/verifier_arena.c
index cadb13f023d2a3..3931a1d9b6dacf 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena.c
@@ -597,6 +597,76 @@ __naked void mixed_arena_scalar_alu64_arena_first(void)
: __clobber_all);
}
+/* The offset of a pointer to arena is not tracked */
+#define ARENA_TEST(name, op, expect) \
+SEC("syscall") \
+__log_level(2) \
+expect \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "r1 = %[arena] ll;" \
+ "r6 = 0;" \
+ "r6 = addr_space_cast(r6, 0, 1);" \
+ "r7 = 0;" \
+"1: *(u64 *)(r6 + 0) = r7;" \
+ op \
+ "r7 += 1;" \
+ "if r7 < 100 goto 1b;" \
+ "r0 = 0;" \
+ "exit;" \
+ :: __imm_addr(arena) : __clobber_all); \
+}
+
+#define NOT_UNROLLED100 __msg("loop header at 5, widening r7 to 0..99 step 1")
+/* A loop that moves the pointer is not unrolled */
+ARENA_TEST(arena_pointer_moves, "r6 += 8;", __success NOT_UNROLLED100)
+/* The loop makes a number of it: the state that returns to the loop header tells */
+ARENA_TEST(arena_pointer_becomes_a_number, "if r7 != 5 goto +1; r6 = 4096;",
+ __failure NOT_UNROLLED100 __msg("R6 invalid mem access 'scalar'"))
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, char[64]);
+} map64 SEC(".maps");
+
+/*
+ * r6: 64 bytes. r8: an unbounded scalar. r3, r7: an arena pointer and a copy of it.
+ * The test leaves an address in r1.
+ */
+#define ARENA_LINKED(name, expect, body) \
+SEC("syscall") expect __load_if_JITed() \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "r1 = %[arena] ll; r1 = 0; *(u32 *)(r10 - 4) = r1; r2 = r10; r2 += -4;" \
+ "r1 = %[map64] ll; call %[bpf_map_lookup_elem]; if r0 == 0 goto out_%=; r6 = r0;" \
+ "call %[bpf_ktime_get_ns]; r8 = r0; r3 = addr_space_cast(r8, 0, 1); r7 = r3;" \
+ body \
+ "r0 = *(u8 *)(r1 + 0);" \
+ "out_%=: r0 = 0; exit;" \
+ : \
+ : __imm(bpf_map_lookup_elem), __imm(bpf_ktime_get_ns), \
+ __imm_addr(map64), __imm_addr(arena) \
+ : __clobber_all); \
+}
+
+ARENA_LINKED(scalar_plus_two_constants, __success __retval(0),
+ "r2 = r8; r2 += 1; r2 += 1; if r8 > 61 goto out_%=; r1 = r6; r1 += r2;")
+/* 'r3 += 1' is converted to 'w3 += 1': r3 is 0 and not 1 << 32 */
+ARENA_LINKED(arena_ptr_plus_constant, __failure,
+ "r3 += 1; r3 = le64 r3; r7 = le64 r7; r2 = 0xffffffff ll; if r7 != r2 goto out_%=;"
+ "r3 >>= 32; r3 -= 1; r1 = r6; r1 += r3;")
+/* At the join point r3 is phi((+ x 1)). The insn there, an add to a scalar, does not define it. */
+ARENA_LINKED(arena_ptr_plus_constant_on_two_paths, __failure,
+ "if r8 == 0 goto 1f; r3 += 1; goto 2f; 1: r3 += 1; 2: r8 += 1; r3 = le64 r3; r7 = le64 r7;"
+ "r2 = 0xffffffff ll; if r7 != r2 goto out_%=; r3 >>= 32; r3 -= 1; r1 = r6; r1 += r3;")
+/* 'r1 += r2' was verified without a pointer to arena: it stays ALU64 */
+ARENA_LINKED(index_tested_after_the_add, __success __retval(0),
+ "r2 = r8; r2 &= 255; r1 = r6; r1 += r2; if r2 > 63 goto out_%=; r0 = *(u8 *)(r6 + 0);")
+
SEC("syscall")
__description("arena: a number is not an address in arena")
__failure __msg("R6 invalid mem access 'scalar'")
diff --git a/tools/testing/selftests/bpf/progs/verifier_array_access.c b/tools/testing/selftests/bpf/progs/verifier_array_access.c
index 7f98822889cad5..29bed1e496af60 100644
--- a/tools/testing/selftests/bpf/progs/verifier_array_access.c
+++ b/tools/testing/selftests/bpf/progs/verifier_array_access.c
@@ -762,7 +762,7 @@ l0_%=: *(u32*)(r10 - 8) = r6; \
: __clobber_all);
}
-/* The slot has the id of r6, so the compare sets the range of the slot too */
+/* The slot holds the low 32 bits of r6, so the compare refines the slot too */
SEC("socket")
__description("valid map access into an array using a key that is compared after the spill")
__success __retval(0)
diff --git a/tools/testing/selftests/bpf/progs/verifier_bounds.c b/tools/testing/selftests/bpf/progs/verifier_bounds.c
index f55d58af8004a4..b78e7fc96fa704 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bounds.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bounds.c
@@ -1476,7 +1476,7 @@ __naked void sub64_full_overflow(void)
SEC("socket")
__description("64-bit subtraction, partial overflow, result in unbounded reg")
__success __log_level(2)
-__msg("3: (1f) r3 -= r2 {{.*}} R3=scalar(id=1-1)")
+__msg("3: (1f) r3 -= r2 {{.*}} R3=scalar()")
__retval(0)
__naked void sub64_partial_overflow(void)
{
@@ -1572,7 +1572,7 @@ l0_%=: r0 = 0; \
SEC("socket")
__description("bounds deduction cross sign boundary, negative overlap")
__success __log_level(2)
-__msg("7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-655,smax=smax32=-146,umin=0xfffffffffffffd71,umax=0xffffffffffffff6e,umin32=0xfffffd71,umax32=0xffffff6e,var_off=(0xfffffffffffffc00; 0x3ff))")
+__msg("7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-527,smax=smax32=-146,umin=0xfffffffffffffdf1,umax=0xffffffffffffff6e,umin32=0xfffffdf1,umax32=0xffffff6e,var_off=(0xfffffffffffffc00; 0x3ff))")
__retval(0)
__naked void bounds_deduct_negative_overlap(void)
{
@@ -1995,6 +1995,39 @@ __naked void bounds_refinement_multiple_overlaps(void *ctx)
: __clobber_all);
}
+/*
+ * r0 is x << 32, the low three bits of x are 5. No such x is in [-2, 1], -3 is in [-3, 1].
+ * umin and umax are unbounded for a range that crosses 0.
+ */
+#define RANGE_CROSSES_0(name, smin) \
+__naked void name(void *ctx) \
+{ \
+ asm volatile( \
+ "call %[bpf_ktime_get_ns];" \
+ "r0 <<= 35;" \
+ "r1 = 0x500000000 ll;" \
+ "r0 += r1;" \
+ "r1 = " #smin " ll;" \
+ "if r0 s< r1 goto 1f;" \
+ "r1 = 0x100000000 ll;" \
+ "if r0 s> r1 goto 1f;" \
+ "r10 = 0;" \
+"1: exit;" \
+ : \
+ : __imm(bpf_ktime_get_ns) \
+ : __clobber_all); \
+}
+
+SEC("socket")
+__description("dead branch: tnum and a range that crosses 0 don't overlap")
+__success
+RANGE_CROSSES_0(range_crossing_0_no_tnum_overlap, -0x200000000)
+
+SEC("socket")
+__description("tnum overlaps the negative part of a range that crosses 0")
+__failure __msg("frame pointer is read only")
+RANGE_CROSSES_0(range_crossing_0_tnum_overlap_below_0, -0x300000000)
+
SEC("socket")
__success
__naked void signed_unsigned_intersection32_case1(void *ctx)
diff --git a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
index 51b703058cf70b..b42717a825c69e 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
@@ -299,7 +299,7 @@ SEC("socket")
__success __log_level(2)
__msg("r0 += 8 {{.*}}smin=umin=smin32=umin32=8,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
__msg("from 4 to 6: R0=scalar(smin=umin=smin32=umin32=32,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
-__msg("r1 = r0 {{.*}}R1=scalar(id={{[0-9]+}},smin=umin=smin32=umin32=104,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
+__msg("r1 = r0 {{.*}}R1=scalar(smin=umin=smin32=umin32=104,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
__msg("r1 += 24 {{.*}}R1=scalar({{.*}}smin=umin=smin32=umin32=128,smax=umax=smax32=umax32=200,{{.*}}step=8+24)")
__naked void step_bounds_resync_after_arith(void)
{
@@ -336,10 +336,10 @@ l_out_%=: \
*/
SEC("socket")
__success __log_level(2)
-__msg("r1 = (s16)r0 {{.*}}R1=scalar(id={{[0-9]+}},smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
+__msg("r1 = (s16)r0 {{.*}}R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
__msg("r2 = (s16)r0 {{.*}}R2=scalar(smin=smin32=-24,smax=smax32=144,{{.*}}step=0+24)")
__msg("r3 = (s8)r0 {{.*}}R3=scalar(smin=smin32=-128,smax=smax32=127)")
-__msg("w4 = (s16)w1 {{.*}}R4=scalar(id={{[0-9]+}},smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
+__msg("w4 = (s16)w1 {{.*}}R4=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
__msg("w5 = (s8)w1 {{.*}}R5=scalar({{.*}}smin32=-128,smax32=127,var_off=(0x0; 0xffffffff))")
__naked void step_movsx_bounds_on_line(void)
{
diff --git a/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c b/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c
index 6c1d2014b95b1b..212c08a27058e9 100644
--- a/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c
+++ b/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c
@@ -569,7 +569,7 @@ l0_%=: r0 = 0; \
SEC("tc")
__description("direct packet access: test23 (x += pkt_ptr, 4)")
-__failure __msg("invalid access to packet, off=31 size=8, R5(id=3,off=31,r=0)")
+__failure __msg("invalid access to packet, off=31 size=8, R5(id=1,off=31,r=0)")
__flag(BPF_F_ANY_ALIGNMENT)
__naked void test23_x_pkt_ptr_4(void)
{
diff --git a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
index caae67feaf5b70..c8b3690dd810a4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
+++ b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
@@ -190,10 +190,9 @@ l0_%=: \
: __clobber_all);
}
-/* Double ADD clears the ID (can't accumulate offsets) */
+/* Double ADD clears the ID. That r1 = r0 + 4 is known all the same: r0 /= 0 is dead code */
SEC("socket")
-__failure
-__msg("div by zero")
+__success
__naked void scalars_double_add(void)
{
asm volatile (" \
@@ -677,6 +676,7 @@ l_false_%=: \
r2 = r0; \
r2 &= 0xff; /* R2 = scalar(id=A) [0,255] */ \
r4 = r0; \
+ r4 >>= 8; \
r4 &= 0xff; /* R4 = scalar [0,255], id=0 */ \
r3 = r2; /* R3 linked to R2 (id=A) */ \
r3 += 10; /* R3 id=A|ADD_CONST, delta=10 */\
@@ -689,6 +689,7 @@ l_true_%=: \
r2 = r0; \
r2 &= 0xff; /* R2 = scalar [0,255], id=0 */ \
r4 = r0; \
+ r4 >>= 8; \
r4 &= 0xff; /* R4 = scalar [0,255], id=0 */ \
r3 = r4; /* R3 linked to R4 (new id=C) */\
r3 += 10; /* R3 id=C|ADD_CONST, delta=10 */\
diff --git a/tools/testing/selftests/bpf/progs/verifier_live_stack.c b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
index 32bab3cb3fcb9a..d6a6420d219d5c 100644
--- a/tools/testing/selftests/bpf/progs/verifier_live_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
@@ -3143,6 +3143,66 @@ static __used __naked void imprecise_fill_cross_frame(void)
: __clobber_all);
}
+/*
+ * fill_older_frame_3() loads through a pointer to the stack of frame 1 or of frame 2. Both slots
+ * hold a pointer to fp-8 of frame 0: the store is a may_def of that slot at the call in frame 0.
+ */
+SEC("socket")
+__log_level(2)
+__success
+__msg("3: (85) call pc+2{{ +}}; may_def: fp0-8..-{{[0-9]+}}")
+__naked void imprecise_parent_fill_loses_older_frame(void)
+{
+ asm volatile (
+ "*(u64 *)(r10 - 8) = 0;"
+ "r1 = r10;"
+ "r1 += -8;"
+ "call fill_older_frame_1;"
+ "r0 = *(u64 *)(r10 - 8);"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void fill_older_frame_1(void)
+{
+ asm volatile (
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = r10;"
+ "r1 += -8;"
+ "call fill_older_frame_2;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void fill_older_frame_2(void)
+{
+ asm volatile (
+ "r2 = *(u64 *)(r1 + 0);"
+ "*(u64 *)(r10 - 8) = r2;"
+ "r2 = r10;"
+ "r2 += -8;"
+ "call fill_older_frame_3;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void fill_older_frame_3(void)
+{
+ asm volatile (
+ "r6 = r1;"
+ "r7 = r2;"
+ "call %[bpf_get_prandom_u32];"
+ "if r0 == 0 goto +1;"
+ "r6 = r7;"
+ /* ARG_IMPRECISE{mask=BIT(1)|BIT(2)} */
+ "r1 = *(u64 *)(r6 + 0);"
+ "*(u64 *)(r1 + 0) = 7;"
+ "r0 = 0;"
+ "exit;"
+ :: __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
/* Test that spill_to_stack with multi-offset dst (sz=8) joins instead
* of overwriting. r1 has offsets [-8, -16]. Both slots hold FP-derived
* pointers. Writing through r1 should join *val with existing values,
diff --git a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
index 35bb3e16db3dea..17222e1332fdba 100644
--- a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
+++ b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
@@ -271,6 +271,51 @@ LOOP(copy_bad, "r8 = 0; r9 = r8;", COPY(2047))
BAD("a copy of the counter, another number at the entry")
LOOP(copy_other_const, "r8 = 2047; r9 = 0; r6 += 2047;", COPY(2046))
+/* the latch exits one iteration later than for an induction variable that starts from 1 */
+NO_COUNT("a copy of the counter, one more at the entry")
+LOOP(copy_ahead, "r8 = 0; r9 = 1;", COPY(2047))
+
+/* r5 is a copy of the pointer r6 from before the increment: an induction variable too */
+#define PTR_COPY(off) "*(u8 *)(r5 + " #off ") = r1; r5 = r6; r8 += 1; if r8 < 2048 goto 1b;"
+
+OK("a copy of the pointer", "2048") __msg("widening r5 to 0..2047 step 1")
+LOOP(copy_of_pointer, "r5 = r6; r8 = 0;", PTR_COPY(0))
+
+BAD("a copy of the pointer, one too many")
+LOOP(copy_of_pointer_bad, "r5 = r6; r8 = 0;", PTR_COPY(1))
+
+/* r8 and r9 are computed in the same way from r7: equal by value number, 'r9 = r8' is not needed */
+OK("a copy of the counter, equal by value number", "[0..2]")
+LOOP(copy_same_value_number,
+ "r5 = r6; r8 = r7; r8 &= 1; r8 += 2045; r9 = r7; r9 &= 1; r9 += 2045;", COPY(2045) AT_R8)
+
+/*
+ * 'for (i = n; i > 0; i--) buf[i - 1] = 0;': r9 is i from before the decrement, the latch tests r8.
+ * r9 gets the range that the latch implies for r8.
+ */
+#define DOWN(off) \
+ "r8 += -1; r2 = r5; r2 += r9; *(u8 *)(r2 " off ") = r1; r9 = r8; if r8 > 0 goto 1b;"
+#define FROM_RANGE "if r7 > 2048 goto 9f; if r7 == 0 goto 9f; r5 = r6; r8 = r7; r9 = r7;"
+
+OK("a copy of the counter, down from a range", "[0..2048]")
+LOOP(copy_down_from_range, FROM_RANGE, DOWN("- 1"))
+
+BAD("a copy of the counter, down from a range, one too many")
+LOOP(copy_down_from_range_bad, FROM_RANGE, DOWN("+ 0"))
+
+/*
+ * r9 is zero extended. [1, 2048], its range at the header, is the range of the zero extension too.
+ * [-1000, 1001] is not: the first store is 4G behind the value.
+ */
+OK("a copy of the counter, zero extended", "[0..2048]")
+LOOP(copy_zext, FROM_RANGE, "w9 = w9;" DOWN("- 1"))
+
+SEC("socket") __description("latch: a copy of the counter, zero extended, from below 0")
+__failure __msg("R4 unbounded memory access")
+LOOP(copy_zext_bad, "r5 = r6; r8 = r7; r8 &= 255; r8 += -1000; r9 = r8;",
+ "w9 = w9; if r8 s> 1000 goto 9f; r4 = r5; r4 += r9; *(u8 *)(r4 + 1000) = r1;"
+ "r8 += 1; r9 = r8; if r7 != 0 goto 1b;")
+
OK("a copy of the counter, a range", "[0..2]")
LOOP(copy_range, "r5 = r6; r8 = r7; r8 &= 1; r8 += 2045; r9 = r8;", COPY(2045) AT_R8)
@@ -297,13 +342,13 @@ LOOP(copy_bounds_both, "r5 = r6; if r7 > 2047 goto 9f; r8 = r7; r9 = r8;",
"r4 = r5; r4 += r9; *(u8 *)(r4 " off ") = r1; 2: r9 = r8; if r7 != 0 goto 1b;"
OK("a copy of the counter, one less behind the jump", "[0..2048]")
-LOOP(copy_less, "r5 = r6; r8 = 0; r9 = r8;", NOT_EQUAL(1, "> 2046", "< 2", "- 1"))
+LOOP(copy_less, "r5 = r6; r8 = 0; r9 = r8;", NOT_EQUAL(1, "> 2046", "< 2", "+ 0"))
BAD("a copy of the counter, one less behind the jump, not equal")
LOOP(copy_less_bad, "r5 = r6; r8 = 0; r9 = r8;", NOT_EQUAL(1, "> 2046", "< 2", "- 2"))
OK("a copy of the counter, one more behind the jump", "[0..2047]")
-LOOP(copy_more, "r5 = r6; r8 = 2047; r9 = r8;", NOT_EQUAL(-1, "s< 2", "> 2045", "+ 1"))
+LOOP(copy_more, "r5 = r6; r8 = 2047; r9 = r8;", NOT_EQUAL(-1, "s< 2", "> 2045", "+ 0"))
BAD("a copy of the counter, one more behind the jump, not equal")
LOOP(copy_more_bad, "r5 = r6; r8 = 2047; r9 = r8;", NOT_EQUAL(-1, "s< 2", "> 2045", "+ 2"))
diff --git a/tools/testing/selftests/bpf/progs/verifier_movsx.c b/tools/testing/selftests/bpf/progs/verifier_movsx.c
index 2f4a678c31c202..6f90dac78fcd10 100644
--- a/tools/testing/selftests/bpf/progs/verifier_movsx.c
+++ b/tools/testing/selftests/bpf/progs/verifier_movsx.c
@@ -202,6 +202,192 @@ l0_%=: \
: __clobber_all);
}
+/*
+ * A 32-bit range that already fits the signed N-bit range is unchanged by the sign
+ * extension. Both of these straddle zero. The guard that follows can only be
+ * resolved statically if the range survives, and it protects a div by zero.
+ */
+SEC("socket")
+__description("MOV32SX, S8, negative range is preserved")
+__success __success_unpriv __retval(0)
+__naked void mov32sx_s8_negative_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ w0 &= 0x3f; \
+ w0 -= 0x3f; \
+ /* w0 is [-63, 0], already a valid s8 */ \
+ w0 = (s8)w0; \
+ if w0 s< -0x3f goto l0_%=; \
+ w0 = 0; \
+ exit; \
+l0_%=: \
+ /* dead unless the range was widened */ \
+ w0 /= 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("socket")
+__description("MOV32SX, S16, negative range is preserved")
+__success __success_unpriv __retval(0)
+__naked void mov32sx_s16_negative_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ w0 &= 0xfff; \
+ w0 -= 0xfff; \
+ /* w0 is [-4095, 0], already a valid s16 */ \
+ w0 = (s16)w0; \
+ if w0 s< -0xfff goto l0_%=; \
+ w0 = 0; \
+ exit; \
+l0_%=: \
+ /* dead unless the range was widened */ \
+ w0 /= 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * A 32-bit sign extension keeps the low 32 bits, so refining the source
+ * reaches the destination. The source is a call return, which is the shape
+ * bpf-gcc builds for "int err = helper(); if (err) ..".
+ */
+SEC("socket")
+__success __retval(0)
+__naked void sext_mov_unlinked_src(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r7 = (s32)r0; /* r0 as the call defines it */ \
+ if w0 != -1 goto l0_%=; /* refines r0, propagates to r7 */ \
+ if r7 == -1 goto l0_%=; /* sign-extended, not 0xffffffff */ \
+ r0 /= 0; \
+l0_%=: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * The propagation must not run backwards over the upper 32 bits: a sign extension
+ * knows nothing about the upper bits of its source. r8's low 32 bits do become
+ * 2, r8 == 2 does not follow.
+ */
+SEC("socket")
+__failure __msg("div by zero")
+__naked void sext_no_sync_from_subreg_base(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r7 = (s32)r6; \
+ r8 = r6; \
+ r8 += 3; \
+ if r7 != -1 goto 1f; /* pins the low 32 bits of r8 only */ \
+ if r8 == 2 goto 1f; /* taken only if r8 wrongly refined */ \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * r2 is (u32)(r6 + 1) and r7 is (s32)(r6 + 1), so w2 == 1 means r7 == 1.
+ * bpf-gcc builds "i += 1" for an int induction variable into exactly this shape.
+ */
+SEC("socket")
+__success __retval(0)
+__naked void sext_sync_from_zext_sibling(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r6 <<= 32; \
+ call %[bpf_get_prandom_u32]; \
+ r6 |= r0; /* r6 = full 64-bit unknown */ \
+ r2 = r6; \
+ w2 += 1; /* r2 = (u32)(r6 + 1) */ \
+ r7 = (s32)r2; /* r7 = (s32)(r6 + 1) */ \
+ if w2 != 1 goto 1f; /* propagates to r7 */ \
+ if r7 == 1 goto 1f; \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * "w6 = w6" leaves r6 in [0, U32_MAX]. A signed compare on its sign extension
+ * must not hand r6 the sign-extended value: that drops every r6 >= 2^31 from
+ * the range and makes the guarded div provably dead.
+ */
+SEC("socket")
+__failure __msg("div by zero")
+__naked void sext_narrow_base_keeps_high_values(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ w6 = w6; /* r6 in [0, U32_MAX] */ \
+ r7 = (s32)r6; \
+ r8 = 1; \
+ r8 <<= 31; /* 0x80000000 */ \
+ if r7 s> 100 goto 1f; /* r6 is [0,100] or >= 2^31 */ \
+ if r6 < r8 goto 1f; /* reachable: r6 may be >= 2^31 */ \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * A base/step line does not survive the sign extension: it subtracts 2^32,
+ * and 2^32 is not a multiple of 3. r6 = 0x80000007 is a multiple of 3, so
+ * r7 = -2147483641 is reachable.
+ */
+SEC("socket")
+__failure __msg("div by zero")
+__naked void sext_drops_stale_step(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ w6 = w6; \
+ r6 *= 3; /* base 0, step 3 */ \
+ r7 = (s32)r6; \
+ r8 = 1; \
+ r8 <<= 31; \
+ r9 = r8; \
+ r9 += 7; \
+ if r6 < r8 goto 1f; \
+ if r6 > r9 goto 1f; /* r6 in [0x80000000, 0x80000007] */ \
+ if r7 != -2147483641 goto 1f; /* reachable: r6 == 0x80000007 */ \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
SEC("socket")
__description("MOV64SX, S16, R10 Sign Extension")
__failure __msg("R1 type=scalar expected=fp, pkt, pkt_meta, map_key, map_value, mem, ringbuf_mem, buf, trusted_ptr_")
diff --git a/tools/testing/selftests/bpf/progs/verifier_reg_equal.c b/tools/testing/selftests/bpf/progs/verifier_reg_equal.c
index dc1d8c30fb0eeb..91daa5b323c9f8 100644
--- a/tools/testing/selftests/bpf/progs/verifier_reg_equal.c
+++ b/tools/testing/selftests/bpf/progs/verifier_reg_equal.c
@@ -31,17 +31,16 @@ l1_%=: exit; \
}
SEC("socket")
-__description("check w reg not equal if r reg upper32 bits not 0")
-__failure __msg("R1 !read_ok")
+__description("check w reg equal if r reg upper32 bits not 0")
+__success
__naked void subreg_equality_2(void)
{
asm volatile (" \
call %[bpf_ktime_get_ns]; \
r2 = r0; \
- /* Upper 4-bytes of r2 may not be 0, thus insn \
- * w3 = w2 should not propagate reg id, and \
- * w2 < 9 comparison should not propagate \
- * the range for r3 either. \
+ /* Upper 4-bytes of r2 may not be 0. r3 is the \
+ * lower 4-bytes of r2, which is what w2 < 9 \
+ * compares. \
*/ \
w3 = w2; \
if w2 < 9 goto l0_%=; \
diff --git a/tools/testing/selftests/bpf/progs/verifier_regalloc.c b/tools/testing/selftests/bpf/progs/verifier_regalloc.c
index ee5ddea87c91c0..cf26617b6ba16f 100644
--- a/tools/testing/selftests/bpf/progs/verifier_regalloc.c
+++ b/tools/testing/selftests/bpf/progs/verifier_regalloc.c
@@ -303,7 +303,6 @@ __naked void regalloc_in_callee(void)
r7 = r0; \
call %[bpf_get_prandom_u32]; \
r1 = r0; \
- r2 = r0; \
r3 = r7; \
call regalloc_in_callee__1; \
l0_%=: exit; \
@@ -318,6 +317,7 @@ static __naked __noinline __attribute__((used))
void regalloc_in_callee__1(void)
{
asm volatile (" \
+ r2 = r1; \
if r1 s> 20 goto l0_%=; \
if r2 s< 0 goto l0_%=; \
r3 += r1; \
diff --git a/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c b/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c
index 9ea61b16273653..56c2412608a5dc 100644
--- a/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c
+++ b/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c
@@ -11,11 +11,10 @@ struct {
__type(value, long long);
} map_hash_8b SEC(".maps");
-/* scalar in [0, max] that shares id with other registers, as it is in the log */
-#define LINKED(id, max, mask) \
- "scalar(id=" id ",smin=smin32=0,smax=umax=smax32=umax32=" #max ",var_off=(0x0; " #mask "))"
+/* scalar in [0, max], as it is in the log. @id: the registers that hold copies of one value. */
#define ALONE(max, mask) \
"scalar(smin=smin32=0,smax=umax=smax32=umax32=" #max ",var_off=(0x0; " #mask "))"
+#define LINKED(id, max, mask) ALONE(max, mask)
/*
* Registers r{0,1,2} have the same scalar ID.
@@ -151,7 +150,7 @@ __naked void linked_regs_broken_link(void)
SEC("socket")
__success __log_level(2)
__msg("13: (25) if r1 > 0x7 goto pc+0 ; R1=" ALONE(7, 0x7))
-__msg("10: R0=0 R6=scalar(id={{.*}}umax32=255,{{.*}} R7=scalar(id={{.*}}umax32=255,")
+__msg("10: R0=0 R6=scalar({{.*}}umax32=255,{{.*}} R7=scalar({{.*}}umax32=255,")
__msg("5: R0=0 R6=" ALONE(255, 0xff))
__naked void precision_many_frames(void)
{
@@ -285,13 +284,8 @@ __naked void precision_two_ids(void)
SEC("socket")
__success __log_level(2)
-/*
- * check that r5 is unlinked after 'if', collect_linked_regs() can't tie
- * more than 5 registers for a single insn and the register compared by
- * the jump is not exempt from that.
- */
-__msg("7: (25) if r5 > 0x7 goto pc+0 ; R5=scalar(smin=")
-__msg("12: (bf) r5 = r5 ; R5=scalar(id=2")
+/* there is no limit of 5 registers for a single insn */
+__msg("7: (25) if r5 > 0x7 goto pc+0 ; R0=" LINKED("1", 7, 0x7) " R1=" LINKED("1", 7, 0x7) " R2=" LINKED("1", 7, 0x7) " R3=" LINKED("1", 7, 0x7) " R4=" LINKED("1", 7, 0x7) " R5=" LINKED("1", 7, 0x7))
__naked void linked_regs_too_many_regs(void)
{
asm volatile (
@@ -304,14 +298,12 @@ __naked void linked_regs_too_many_regs(void)
"r3 = r0;"
"r4 = r0;"
"r5 = r0;"
- /* r{0-4} fill the record, r5 does not fit and is unlinked */
"if r5 > 7 goto +0;"
- /* keep r{1-4} live */
+ /* keep r{1-5} live */
"r1 = r1;"
"r2 = r2;"
"r3 = r3;"
"r4 = r4;"
- /* make r5 appear in the log */
"r5 = r5;"
"r7 = r10;"
"r7 += r0;"
@@ -324,7 +316,7 @@ __naked void linked_regs_too_many_regs(void)
SEC("socket")
__failure __log_level(2)
-__msg("5: (3d) if r8 >= r0 goto pc+3 ; R0=scalar(umin=1) R7=scalar(id=1,umax=0xfffffffffffffffe) R8=scalar(id=1,umax=0xfffffffffffffffe)")
+__msg("5: (3d) if r8 >= r0 goto pc+3 ; R0=scalar(umin=1) R7=scalar(umax=0xfffffffffffffffe) R8=scalar(umax=0xfffffffffffffffe)")
__msg("div by zero")
__naked void linked_regs_broken_link_2(void)
{
@@ -687,52 +679,6 @@ __naked void two_nil_old_ids_one_cur_id(void)
: __clobber_all);
}
-/*
- * Check that two different scalar IDs in the state that is there can't be
- * mapped to the same scalar ID in the state that arrives.
- */
-SEC("socket")
-__success __log_level(2)
-__not_msg("from 10 to 11: within")
-__msg("11: R0=0 R6=" ALONE(255, 0xff) " R7=" ALONE(255, 0xff))
-__naked void two_old_ids_one_cur_id(void)
-{
- asm volatile (
- /* Give unique scalar IDs to r{6,7} */
- "call %[bpf_ktime_get_ns];"
- "r0 &= 0xff;"
- "r6 = r0;"
- "r8 = r0;"
- "call %[bpf_ktime_get_ns];"
- "r0 &= 0xff;"
- "r7 = r0;"
- "r9 = r0;"
- "r0 = 0;"
- /* Maybe make r{6,7} IDs identical */
- "if r6 <= r7 goto l1_%=;"
- "r6 = r7;"
-"l1_%=:"
- /*
- * Get here in two states:
- * - first: r6{.id=A}, r7{.id=B}
- * - second: r6{.id=B}, r7{.id=B}
- * Currently we don't want to consider the second one to be within
- * the first one. Thus they are joined.
- */
- "r2 = r10;"
- "r2 += r6;"
- "r2 += r7;"
- /*
- * keep r8 and r9 live, otherwise r6->id and r7->id
- * will become singular and reset to zero before if r6 <= r7
- */
- "r9 += r8;"
- "exit;"
- :
- : __imm(bpf_ktime_get_ns)
- : __clobber_all);
-}
-
SEC("socket")
/* Note the flag, see verifier.c:opt_subreg_zext_lo32_rnd_hi32() */
__flag(BPF_F_TEST_RND_HI32)
@@ -808,7 +754,7 @@ __naked void linked_regs_and_subreg_def(void)
* at runtime), which must be rejected.
*/
SEC("socket")
-__failure __msg("R0 max value is outside of the allowed memory range")
+__failure __msg("invalid access to map value, value_size=8 off=8 size=1")
__naked void ldsx_fill_scalar_id_not_shared(void)
{
asm volatile (" \
diff --git a/tools/testing/selftests/bpf/progs/verifier_scev.c b/tools/testing/selftests/bpf/progs/verifier_scev.c
index 5c9c832fbbe07e..a79c00a99c8939 100644
--- a/tools/testing/selftests/bpf/progs/verifier_scev.c
+++ b/tools/testing/selftests/bpf/progs/verifier_scev.c
@@ -135,7 +135,7 @@ exit_%=: \
SEC("xdp")
__success
__log_level(2)
-__msg("8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -> ?")
+__msg("8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -> %fp-8.8?")
__naked void indirect_write_invalidates_scev(void)
{
asm volatile (" \
@@ -165,7 +165,7 @@ __noinline int global_noop_counter(__u64 *p)
SEC("xdp")
__success
__log_level(2)
-__msg("8: (85) call pc+{{[0-9]+}} {{.*}}; *fp-8 (+ *fp-8 1) -> ?")
+__msg("8: (85) call pc+{{[0-9]+}} {{.*}}; *fp-8 (+ *fp-8 1) -> %fp-8.8?")
__naked void global_call_invalidates_scev(void)
{
asm volatile (
@@ -242,7 +242,7 @@ SEC("xdp")
__success __retval(0)
__log_level(2)
__msg_next("scev at header 1:")
-__msg_next(" r6=(any r6 (+ r6 1)) / ?")
+__msg_next(" r6=%r6.1=phi(r6, (+ r6 1)) / ?")
__naked void meet_disagrees(void)
{
asm volatile (" \
@@ -261,6 +261,37 @@ __naked void meet_disagrees(void)
: __clobber_all);
}
+/* 'if (c) sum += a; else sum += b;': two loads, one way to compute the sum */
+SEC("socket")
+__success
+__log_level(2)
+__msg("scev at header 3:")
+__msg_next(" r6=%r6.9=phi((+ r6 _)) / ?")
+__naked void phi_operands_have_no_defs(void)
+{
+ asm volatile (" \
+ r9 = r1; \
+ r6 = 0; \
+ r7 = 0; \
+1: \
+ if r7 & 1 goto 2f; \
+ r2 = *(u32 *)(r9 + %[len]); \
+ r6 += r2; \
+ goto 3f; \
+2: \
+ r2 = *(u32 *)(r9 + %[mark]); \
+ r6 += r2; \
+3: \
+ r7 += 1; \
+ if r7 < 10 goto 1b; \
+ r0 = r6; \
+ exit; \
+" :
+ : __imm_const(len, offsetof(struct __sk_buff, len)),
+ __imm_const(mark, offsetof(struct __sk_buff, mark))
+ : __clobber_all);
+}
+
/* Both entry state values for r1 should be accounted for */
SEC("xdp")
__success
@@ -324,30 +355,31 @@ __msg("r1 += 2 {{.*}}; r1 r6 -> (+ r6 2)")
__msg("r1 += r7 {{.*}}; r1 r6 -> (+ r6 r7)")
__msg("w1 += 2 {{.*}}; r1 r6 -> (zext32 (+ r6 2))")
__msg("w1 += w7 {{.*}}; r1 r6 -> (zext32 (+ r6 r7))")
-__msg("r1 -= 2 {{.*}}; r1 r6 -> (- r6 2)")
+__msg("r1 -= 2 {{.*}}; r1 r6 -> (+ r6 -2)")
__msg("r1 -= r7 {{.*}}; r1 r6 -> (- r6 r7)")
-__msg("w1 -= 2 {{.*}}; r1 r6 -> (zext32 (- r6 2))")
+__msg("w1 -= 2 {{.*}}; r1 r6 -> (zext32 (+ r6 -2))")
__msg("w1 -= w7 {{.*}}; r1 r6 -> (zext32 (- r6 r7))")
+__msg("r1 -= 2 {{.*}}; r1 (+ r6 2) -> r6")
__msg("r1 *= 2 {{.*}}; r1 r6 -> (* r6 2)")
__msg("r1 *= r7 {{.*}}; r1 r6 -> (* r6 r7)")
__msg("w1 *= 2 {{.*}}; r1 r6 -> (zext32 (* r6 2))")
__msg("w1 *= w7 {{.*}}; r1 r6 -> (zext32 (* r6 r7))")
__msg("r1 /= 2 {{.*}}; r1 r6 -> (/ r6 2)")
__msg("r1 /= r7 {{.*}}; r1 r6 -> (/ r6 r7)")
-__msg("w1 /= 2 {{.*}}; r1 r6 -> (zext32 (/ r6 2))")
-__msg("w1 /= w7 {{.*}}; r1 r6 -> (zext32 (/ r6 r7))")
+__msg("w1 /= 2 {{.*}}; r1 r6 -> (zext32 (/ (zext32 r6) 2))")
+__msg("w1 /= w7 {{.*}}; r1 r6 -> (zext32 (/ (zext32 r6) (zext32 r7)))")
__msg("r1 s/= 2 {{.*}}; r1 r6 -> (s/ r6 2)")
__msg("r1 s/= r7 {{.*}}; r1 r6 -> (s/ r6 r7)")
-__msg("w1 s/= 2 {{.*}}; r1 r6 -> (zext32 (s/ r6 2))")
-__msg("w1 s/= w7 {{.*}}; r1 r6 -> (zext32 (s/ r6 r7))")
+__msg("w1 s/= 2 {{.*}}; r1 r6 -> (zext32 (s/ (sext32 r6) 2))")
+__msg("w1 s/= w7 {{.*}}; r1 r6 -> (zext32 (s/ (sext32 r6) (sext32 r7)))")
__msg("r1 %= 2 {{.*}}; r1 r6 -> (% r6 2)")
__msg("r1 %= r7 {{.*}}; r1 r6 -> (% r6 r7)")
-__msg("w1 %= 2 {{.*}}; r1 r6 -> (zext32 (% r6 2))")
-__msg("w1 %= w7 {{.*}}; r1 r6 -> (zext32 (% r6 r7))")
+__msg("w1 %= 2 {{.*}}; r1 r6 -> (zext32 (% (zext32 r6) 2))")
+__msg("w1 %= w7 {{.*}}; r1 r6 -> (zext32 (% (zext32 r6) (zext32 r7)))")
__msg("r1 s%= 2 {{.*}}; r1 r6 -> (s% r6 2)")
__msg("r1 s%= r7 {{.*}}; r1 r6 -> (s% r6 r7)")
-__msg("w1 s%= 2 {{.*}}; r1 r6 -> (zext32 (s% r6 2))")
-__msg("w1 s%= w7 {{.*}}; r1 r6 -> (zext32 (s% r6 r7))")
+__msg("w1 s%= 2 {{.*}}; r1 r6 -> (zext32 (s% (sext32 r6) 2))")
+__msg("w1 s%= w7 {{.*}}; r1 r6 -> (zext32 (s% (sext32 r6) (sext32 r7)))")
__msg("r1 |= 2 {{.*}}; r1 r6 -> (| r6 2)")
__msg("r1 |= r7 {{.*}}; r1 r6 -> (| r6 r7)")
__msg("w1 |= 2 {{.*}}; r1 r6 -> (zext32 (| r6 2))")
@@ -363,19 +395,19 @@ __msg("w1 ^= w7 {{.*}}; r1 r6 -> (zext32 (^ r6 r7))")
__msg("r1 <<= 2 {{.*}}; r1 r6 -> (<< r6 2)")
__msg("r1 <<= r7 {{.*}}; r1 r6 -> (<< r6 r7)")
__msg("w1 <<= 2 {{.*}}; r1 r6 -> (zext32 (<< r6 2))")
-__msg("w1 <<= w7 {{.*}}; r1 r6 -> (zext32 (<< r6 r7))")
+__msg("w1 <<= w7 {{.*}}; r1 r6 -> (zext32 (<< r6 (& r7 31)))")
__msg("r1 >>= 2 {{.*}}; r1 r6 -> (>> r6 2)")
__msg("r1 >>= r7 {{.*}}; r1 r6 -> (>> r6 r7)")
-__msg("w1 >>= 2 {{.*}}; r1 r6 -> (zext32 (>> r6 2))")
-__msg("w1 >>= w7 {{.*}}; r1 r6 -> (zext32 (>> r6 r7))")
+__msg("w1 >>= 2 {{.*}}; r1 r6 -> (zext32 (>> (zext32 r6) 2))")
+__msg("w1 >>= w7 {{.*}}; r1 r6 -> (zext32 (>> (zext32 r6) (& r7 31)))")
__msg("r1 s>>= 2 {{.*}}; r1 r6 -> (s>> r6 2)")
__msg("r1 s>>= r7 {{.*}}; r1 r6 -> (s>> r6 r7)")
-__msg("w1 s>>= 2 {{.*}}; r1 r6 -> (zext32 (s>> r6 2))")
-__msg("w1 s>>= w7 {{.*}}; r1 r6 -> (zext32 (s>> r6 r7))")
+__msg("w1 s>>= 2 {{.*}}; r1 r6 -> (zext32 (s>> (sext32 r6) 2))")
+__msg("w1 s>>= w7 {{.*}}; r1 r6 -> (zext32 (s>> (sext32 r6) (& r7 31)))")
__msg("r1 = -r1 {{.*}}; r1 r6 -> (- r6)")
__msg("w1 = -w1 {{.*}}; r1 r6 -> (zext32 (- r6))")
__msg("r1 = 42 {{.*}}; r1 r6 -> 42")
-__msg("w1 = 42 {{.*}}; r1 r6 -> (zext32 42)")
+__msg("w1 = 42 {{.*}}; r1 r6 -> 42")
__msg("r1 = r7 {{.*}}; r1 r6 -> r7")
__msg("w1 = w7 {{.*}}; r1 r6 -> (zext32 r7)")
__msg("r1 = (s8)r6 {{.*}}; r1 r6 -> (sext8 r6)")
@@ -417,6 +449,7 @@ __naked void alu_ops_exprs(void)
ALU_OP("r1 -= r7")
ALU_OP("w1 -= 2")
ALU_OP("w1 -= w7")
+ ALU_OP("r1 += 2; r1 -= 2")
ALU_OP("r1 *= 2")
ALU_OP("r1 *= r7")
ALU_OP("w1 *= 2")
@@ -511,7 +544,7 @@ __msg("*(u16 *)(r10 -8) = r1 {{.*}}; *fp-8 -8 -> (spill16 1)")
__msg("*(u8 *)(r10 -8) = r1 {{.*}}; *fp-8 -8 -> (spill8 1)")
__msg("r1 = *(u64 *)(r10 -8) {{.*}}; r1 1 -> -8")
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-__msg("r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -> (zext32 -8)")
+__msg("r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -> 4294967288")
__msg("r1 = *(u16 *)(r10 -8) {{.*}}; r1 1 -> (zext16 -8)")
__msg("r1 = *(u8 *)(r10 -8) {{.*}}; r1 1 -> (zext8 -8)")
__msg("r1 = *(s32 *)(r10 -8) {{.*}}; r1 1 -> (sext32 -8)")
@@ -519,7 +552,7 @@ __msg("r1 = *(s16 *)(r10 -8) {{.*}}; r1 1 -> (sext16 -8)")
__msg("r1 = *(s8 *)(r10 -8) {{.*}}; r1 1 -> (sext8 -8)")
__msg("r1 = load_acquire((u8 *)(r10 -8)) {{.*}}; r1 1 -> (zext8 -8)")
__msg("r1 = load_acquire((u16 *)(r10 -8)) {{.*}}; r1 1 -> (zext16 -8)")
-__msg("r1 = load_acquire((u32 *)(r10 -8)) {{.*}}; r1 1 -> (zext32 -8)")
+__msg("r1 = load_acquire((u32 *)(r10 -8)) {{.*}}; r1 1 -> 4294967288")
#else
__msg("r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -> (>> -8 32)")
__msg("r1 = *(u16 *)(r10 -8) {{.*}}; r1 1 -> (>> -8 48)")
@@ -536,13 +569,18 @@ __msg("store_release((u8 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> (spill8 1)")
__msg("store_release((u16 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> (spill16 1)")
__msg("store_release((u32 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> (spill32 1)")
__msg("store_release((u64 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> 1")
-__msg("lock *(u64 *)(r10 -8) += r1 {{.*}}; *fp-8 -8 -> _")
-__msg("r1 = atomic64_fetch_add((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> _, *fp-8 -8 -> _")
-__msg("r1 = atomic_fetch_add((u32 *)(r10 -8), r1) {{.*}}; r1 1 -> _, *fp-8 -8 -> _")
-__msg("r1 = atomic64_xchg((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> _, *fp-8 -8 -> _")
-__msg("r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r2) {{.*}}; r0 0 -> _, *fp-8 -8 -> _")
+__msg("lock *(u64 *)(r10 -8) += r1 {{.*}}; *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r1 = atomic64_fetch_add((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> %r1.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r1 = atomic_fetch_add((u32 *)(r10 -8), r1) {{.*}}; r1 1 -> %r1.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r1 = atomic64_xchg((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> %r1.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r2) {{.*}}; r0 0 -> %r0.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
__msg("*(u64 *)(r10 -8) = 42 {{.*}}; *fp-8 -8 -> 42")
-__msg("*(u8 *)(r10 -7) = r0 {{.*}}; *fp-8 -8 -> _")
+__msg("*(u8 *)(r10 -7) = r0 {{.*}}; *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+/* a fill that is not wider than the spill reads what was spilled */
+__msg("r1 = *(s8 *)(r10 -8) {{.*}}; r1 r7 -> (sext8 r7)")
+__msg("r1 = *(u16 *)(r10 -8) {{.*}}; r1 r7 -> (zext16 (spill8 r7))")
+#endif
__naked void store_load_exprs(void)
{
asm volatile (
@@ -579,6 +617,9 @@ __naked void store_load_exprs(void)
ST_OP("*(u64 *)(r10 - 8) = 42")
ST_OP("*(u8 *)(r10 - 7) = r0")
+ ST_OP("r1 = r7; *(u16 *)(r10 - 8) = r1; r1 = *(s8 *)(r10 - 8)")
+ ST_OP("r1 = r7; *(u8 *)(r10 - 8) = r1; r1 = *(u16 *)(r10 - 8)")
+
"r7 += 1;"
"if r7 < 2 goto 1b;"
"r0 = 0;"
@@ -607,10 +648,10 @@ __success
__log_level(2)
__msg_next("scev at header 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=?")
+__msg_next(" r7=%r7.4?")
__msg_next(" scev at latch 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=?")
+__msg_next(" r7=%r7.4?")
__msg_next("scev at header 4:")
__msg_next(" r7=(+ r7 1) / (linear r7 1)")
__msg_next(" scev at latch 4:")
@@ -647,7 +688,7 @@ __msg_next(" backedge from 6, latch at 4")
__msg_next(" exit from 4 to 1")
__msg("scev at header 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=?")
+__msg_next(" r7=%r7.4?")
__msg_next("scev at header 4:")
__msg_next(" r7=(+ r7 1) / (linear r7 1)")
__msg_next(" scev at latch 4:")
@@ -692,7 +733,7 @@ __msg_next(" backedge from 5, latch at 5")
__msg_next(" exit from 4 to 2")
__msg_next(" exit from 5 to 6")
__msg("scev at header 2:")
-__msg_next(" r6=?")
+__msg_next(" r6=%r6.3?")
__msg_next(" r7=(+ r7 1) / (linear r7 1)")
__msg_next("scev at header 3:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
@@ -727,8 +768,8 @@ __log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
__msg("loop at 3{{$}}")
__msg("scev at header 3:")
-__msg_next(" r6=(any r6 (+ r6 1)) / ?")
-__msg_next(" r7=(any (+ r7 1) 0) / ?")
+__msg_next(" r6=%r6.3=phi(r6, (+ r6 1)) / ?")
+__msg_next(" r7=%r7.3=phi((+ r7 1), 0) / ?")
__msg_next(" r8=(+ r8 1) / (linear r8 1)")
__msg("loop header at 3, can't compute iterations count")
__naked void nested_loops_shared_header(void)
@@ -1159,6 +1200,50 @@ RANGE_TEST(range_ge_dir, "", 10, 20, 2, 3, 5, PRE("<"), NO_COUNT)
RANGE_TEST(range_ne_step2, "", 0, 3, 2, 3, 8, PRE("=="), NO_COUNT)
RANGE_TEST(range_ne_behind, "", 0, 4, 1, 3, 8, PRE("=="), NO_COUNT)
+/*
+ * char buf[8];
+ * for (int i = first; ...; i++)
+ * sum += buf[i - first];
+ *
+ * GCC adds in 32 bits and keeps the sign extension of the result: a sign-extended 32-bit induction
+ * variable. r6 or fp-16 is i, r7 is first, r9 counts the iterations. r8 is 0, which the verifier
+ * doesn't know. In place of an out-of-bounds access to buf r5 is read, which is not initialized.
+ */
+#define SEXT32_TEST(name, _first, loop, expect) \
+SEC("socket") \
+__log_level(2) \
+expect \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "r6 = %[first] ll; r7 = r6; r8 = 0; r9 = 0;" \
+ "*(u64 *)(r10 - 8) = r8; lock *(u64 *)(r10 - 8) += r8; r8 = *(u64 *)(r10 - 8);" \
+ "*(u64 *)(r10 - 16) = r6;" \
+ loop \
+ "2: r0 = r9; exit;" \
+ : \
+ : __imm_const(first, _first) \
+ : __clobber_all); \
+}
+#define BUF(i) "r9 += 1; r2 = " i "; r2 -= r7; if r2 <= 7 goto +1; r0 = *(u64 *)(r5 + 0);"
+#define OOB __failure __msg("R5 !read_ok")
+#define ALL_OF_S32 "0xffffffff80000000..0x7fffffff "
+#define SEXT32_INC "w1 = w6; w1 += 1; r6 = (s32)r1;"
+#define SEXT32_LOOP(bound) "1:" BUF("r6") SEXT32_INC "if w1 != " #bound " goto 1b;"
+
+SEXT32_TEST(sext32_iv, -4, SEXT32_LOOP(4), __success __retval(8)
+ __msg(" r6=(sext32 (+ r6 1)) / (sext32 (linear r6 1))")
+ __msg("header_count is 8 ") __msg("widening r6 to -4..3 "))
+SEXT32_TEST(sext32_iv_oob, -4, SEXT32_LOOP(5), OOB)
+/* i wraps from INT32_MAX to INT32_MIN. The latch tests 0x7ffffffd .. 0x80000004. */
+SEXT32_TEST(sext32_iv_wraps, INT32_MAX - 3, SEXT32_LOOP(0x80000004),
+ __msg("header_count is 8 ") __msg("widening r6 to " ALL_OF_S32) OOB)
+/* 'i < n' implies the unsigned range 1 .. 0x80000000. Its last value is negative in r6. */
+SEXT32_TEST(sext32_iv_unsigned_bound, 0,
+ "r8 &= 1; r6 += r8; r4 = 0x80000001 ll;"
+ "1:" SEXT32_INC "if w1 < w4 goto 1b; if r6 s>= 0 goto 2f; r0 = *(u64 *)(r5 + 0);",
+ __msg("widening r6 to " ALL_OF_S32) OOB)
+
/*
* Two back edges:
*
@@ -1529,7 +1614,7 @@ __success __retval(7)
__log_level(2)
__msg("scev at header 1:")
__msg_next("r6=(+ r6 1) / (linear r6 1)")
-__msg_next("*fp-8=(any *fp-8 7) / (any *fp-8 7)")
+__msg_next("*fp-8=%fp-8.3=phi(*fp-8, 7) / (any *fp-8 7)")
__msg("loop header at 1, widening r6 to 0..2 step 1")
__msg("3: (79) r0 = *(u64 *)(r10 -8) ; R0=scalar() R10=fp0 loop_stack=1")
__naked void widen_any_unallocated_slot(void)
@@ -1570,7 +1655,7 @@ __success __retval(7)
__log_level(2)
__msg("scev at header 2:")
__msg_next("r6=(+ r6 1) / (linear r6 1)")
-__msg_next("*fp-8=(any *fp-8 7) / (any *fp-8 7)")
+__msg_next("*fp-8=%fp-8.5=phi(*fp-8, 7) / (any *fp-8 7)")
__msg("loop header at 2, widening r6 to 0..2 step 1")
__msg("3: (79) r1 = *(u64 *)(r10 -8) ; R1=scalar() R10=fp0 fp-8=m???????")
__naked void widen_any_misc_slot(void)
@@ -1673,7 +1758,7 @@ __success
__log_level(2)
__msg("scev at header 4:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" *fp-8=?")
+__msg_next(" *fp-8=%fp-8.7?")
__msg("loop header at 4, widening r6 to 0..9 step 1")
__naked void widen_subprog_probe_read(void)
{
@@ -2336,12 +2421,14 @@ __naked __noinline __used static int returns_zero(void)
* A loop that the compiler unrolls in part has an exit for every 'break' and 'return' in every
* copy of its body. How many there are says nothing about the number of iterations.
* Scalar evolution takes a nested loop for one insn, and its exits are the successors of this insn.
- * The list of exits is not complete: the loop around has no formulas.
+ * The exit list is truncated: the enclosing loop has no SCEVs, the subprog is not analyzed.
*/
SEC("xdp")
__success __log_level(2)
__msg("loop at 1, too many exits, too many exits of a nested loop")
__msg("loop at 2, nested in 1, too many exits")
+__msg("Computing SCEV for subprog at 0:")
+__msg_next("Computing SCEV for subprog at {{[0-9]+}}:")
__msg("loop header at 1, unsupported loop: too many exits of a nested loop")
__msg("loop header at 2, header_count is [0..4] ")
__naked void loop_around_301_exits(void)
@@ -2594,7 +2681,7 @@ __msg("loop at 1{{$}}")
__msg("loop at 5, nested in 1, irreducible")
__msg("loop at 11, nested in 5")
__msg("scev at header 1:")
-__msg_next(" r6=?")
+__msg_next(" r6=%r6.5?")
__msg("scev at header 11:")
__msg_next(" r9=(+ r9 1) / (linear r9 1)")
__msg("loop header at 11, widening r9 to 0..2 step 1")
@@ -2841,7 +2928,7 @@ __success
__log_level(2)
__msg("scev at header 2:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=(any r7 100) / (any r7 100)")
+__msg_next(" r7=%r7.6=phi(r7, 100) / (any r7 100)")
__msg_next(" scev at latch 3:")
__msg_next(" r6=(+ r6 1) / (linear (+ r6 1) 1)")
__msg_next(" r7=r7 / (any r7 100)")
@@ -3116,12 +3203,12 @@ __naked void name(void) \
#define NOT_UNROLLED "widening r6 to 0..0xf423f step 1"
/* 'if (...) cnt++' */
-PARTIAL_SPILL_TEST(partial_spill32_inc, u32, 10, "can't widen *fp-8, expr is (any *fp-8 (spill32 ",
+PARTIAL_SPILL_TEST(partial_spill32_inc, u32, 10, "can't widen *fp-8, expr is %fp-8.{{[0-9]+}}=phi(*fp-8, (spill32 ",
SPILL32_0, "if r6 & 1 goto 2f;" SPILL32_INC "2:")
PARTIAL_SPILL_TEST(partial_spill16_inc, u16, 10, "can't widen *fp-8, expr is (spill16 ",
"*(u16 *)(r10 - 8) = r1;", "r1 = *(u16 *)(r10 - 8); w1 += 1; *(u16 *)(r10 - 8) = r1;")
/* A loop in the loop does it */
-PARTIAL_SPILL_TEST(partial_spill32_inc_in_nested_loop, u32, 10, "can't widen *fp-8, expr is ?",
+PARTIAL_SPILL_TEST(partial_spill32_inc_in_nested_loop, u32, 10, "can't widen *fp-8, expr is %fp-8.{{[0-9]+}}?",
SPILL32_0, "r7 = 0; 2:" SPILL32_INC "r7 += 1; if r7 < 3 goto 2b;")
/* Two slots feed each other */
PARTIAL_SPILL_TEST(partial_spill32_two_slots, u32, 10, "can't widen *fp-8, expr is (spill32 ",
@@ -3185,6 +3272,14 @@ RANGE_TEST(spill32_first_is_precise, "", 0, 0, 1, 0, 1,
RANGE_TEST(spill32_first_is_64bit, "", 0, 0, 1, 5, 5,
"*(u64 *)(r10 - 8) = r6; 1:" LIMIT_ITERATIONS SPILL32_INC "if w1 != w7 goto 1b;",
SPILL32_COUNTED(5, "0..4"))
+/* A 64-bit spill of i. Its upper 32 bits are dead: the low 32 bits are the induction variable. */
+#define SEXT32_SPILL_LOOP(bound) \
+ "1:" BUF("*(u32 *)(r10 - 16)") "w1 = *(u32 *)(r10 - 16); w1 += 1; r3 = (s32)r1;" \
+ "*(u64 *)(r10 - 16) = r3; if w1 != " #bound " goto 1b;"
+SEXT32_TEST(sext32_iv_hi32_dead, 0, SEXT32_SPILL_LOOP(8), __success __retval(8)
+ __msg(" *fp-16=(sext32 (+ *fp-16 1)) / (spill32 (linear (zext32 *fp-16) 1))")
+ __msg("header_count is 8 ") __msg("widening *fp-16 to 0..7 "))
+SEXT32_TEST(sext32_iv_hi32_dead_oob, 0, SEXT32_SPILL_LOOP(9), OOB)
/* The counter makes the address of a spill. Such a loop is not summarized, as with a register. */
PARTIAL_SPILL_TEST(spill32_is_a_stack_offset, u32, 4,
"can't widen *fp-8, expr is (spill32 (+ *fp-8 8)), requires exact stack-offset tracking",
@@ -3286,7 +3381,7 @@ NOT_LINEAR_TEST(zext32_or_nothing, "r7 >>= 8;", "if r8 == 0 goto +1; w7 = w7;",
NOT_LINEAR_TEST(and_64_to_127, "r7 &= 63; r7 |= 64;", "r7 &= 127;", UNROLLED("(& r7 127)"))
/* '>>' does not make a number greater, but iterations one by one tell more: 0 after 8 shifts */
NOT_LINEAR_TEST(rsh_on_one_path, "r7 &= 255;", "if r8 == 0 goto +1; r7 >>= 1;",
- UNROLLED("(any r7 (>> r7 1))"))
+ UNROLLED("%r7.8=phi(r7, (>> r7 1))"))
NOT_LINEAR_TEST(rsh_then_and, "r7 &= 255;", "r7 >>= 1; r7 &= r8;", UNROLLED("(& (>> r7 1) r8)"))
NOT_LINEAR_TEST(lsh_grows, "r7 &= 15;", "r7 <<= 1;", UNROLLED("(<< r7 1)"))
@@ -3295,42 +3390,293 @@ NOT_LINEAR_TEST(lsh_grows, "r7 &= 15;", "r7 <<= 1;", UNROLLED("(<< r7 1)"))
NOT_LINEAR_TEST(same_constant, "r7 = 17;", "r7 &= 31;", NOT_CHANGED)
NOT_LINEAR_TEST(same_wide_constant, "r7 = 0xffffffff00000011 ll;", "r7 &= -239;", NOT_CHANGED)
-#ifdef __BPF_FEATURE_ADDR_SPACE_CAST
struct {
- __uint(type, BPF_MAP_TYPE_ARENA);
- __uint(map_flags, BPF_F_MMAPABLE);
+ __uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
-} arena SEC(".maps");
+ __type(key, __u32);
+ __type(value, char[64]);
+} map64 SEC(".maps");
-/* The offset of a pointer to arena is not tracked */
-#define ARENA_TEST(name, op, expect) \
-SEC("syscall") \
-__log_level(2) \
-expect \
+/*
+ * A conditional jump refines the registers and stack slots that are linked to what it tests.
+ * r6: 64 bytes. r7: a scalar below 256. r8: an unbounded scalar. r9: the context.
+ * The test leaves an address in r1.
+ */
+#define LINKED_SEC(sec, name, expect, body) \
+SEC(sec) expect \
__naked void name(void) \
{ \
asm volatile ( \
- "r1 = %[arena] ll;" \
- "r6 = 0;" \
- "r6 = addr_space_cast(r6, 0, 1);" \
- "r7 = 0;" \
-"1: *(u64 *)(r6 + 0) = r7;" \
- op \
- "r7 += 1;" \
- "if r7 < 100 goto 1b;" \
- "r0 = 0;" \
- "exit;" \
- :: __imm_addr(arena) : __clobber_all); \
+ "r9 = r1; r1 = 0; *(u32 *)(r10 - 4) = r1; r2 = r10; r2 += -4; r1 = %[map64] ll;" \
+ "call %[bpf_map_lookup_elem]; if r0 == 0 goto out_%=; r6 = r0;" \
+ "call %[bpf_get_prandom_u32]; r7 = r0; r7 &= 255;" \
+ "call %[bpf_ktime_get_ns]; r8 = r0;" \
+ body \
+ "r0 = *(u8 *)(r1 + 0);" \
+ "out_%=: r0 = 0; exit;" \
+ : \
+ : __imm(bpf_map_lookup_elem), __imm(bpf_get_prandom_u32), __imm(bpf_ktime_get_ns), \
+ __imm(bpf_dynptr_from_skb), __imm(bpf_dynptr_slice_rdwr), \
+ __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard), __imm(bpf_loop), \
+ __imm_addr(map64), __imm_addr(ringbuf) \
+ : __clobber_all); \
+}
+#define LINKED(name, expect, body) LINKED_SEC("socket", name, expect, body)
+
+#define VALID __success __retval(0)
+#define MAP_OOB __failure __msg("invalid access to map value")
+#define UNBOUND __failure __msg("unbounded min value")
+
+/* r3 is the address in r1 as a scalar. It does not bound the offset of r1. */
+LINKED(pointer_is_not_scalar, __failure,
+ "r7 &= 127; r1 = r6; r1 += r7; r3 = r1; r3 = le64 r3; if r3 < 64 goto out_%=; r1 += -64;")
+
+/*
+ * p = buf + i; if (i > 63) return 0; c = *p;
+ * The jump bounds i. r1 is r6 + r7 and r6 is live: r1 is recomputed.
+ */
+#define USE_R6 "r0 = *(u8 *)(r6 + 0);"
+
+LINKED(index_tested_after_the_add, VALID, "r1 = r6; r1 += r7; if r7 > 63 goto out_%=;" USE_R6)
+LINKED(low_32_bits_of_the_index_tested, __failure __msg("R1 unbounded memory access"),
+ "r2 = 0x1000000ff ll; r2 &= r8; r1 = r6; r1 += r2; w3 = w2; if r3 > 63 goto out_%=;" USE_R6)
+/* r7 is -2 or 5. Its low 2 bits are not 3: the path is infeasible, and r6 + r7 + 2 is empty. */
+LINKED(index_is_empty, VALID __flag(BPF_F_TEST_REG_INVARIANTS),
+ "r7 &= 1; r7 *= 7; r7 += -2; r1 = r6; r1 += r7; r1 += 2; if r7 & 1 goto l_%=; goto out_%=;"
+ "l_%=: if r7 & 2 goto m_%=; goto out_%=; m_%=: r1 += 1;" USE_R6)
+
+/*
+ * static void clamp(struct buf *b) { if (b->len > 63) b->len = 0; }
+ * clamp(&b); c = b.data[b.len];
+ * The callee tests memory of its caller: the slot is refined. Not if it may have been written since
+ * the load. r1 and r4 point to b.len, r2 is not bounded.
+ */
+#define CLAMP(name, before_the_jump) \
+static __naked __noinline __used void name(void) \
+{ \
+ asm volatile ( \
+ "r3 = *(u64 *)(r1 + 0);" before_the_jump \
+ "if r3 <= 63 goto +2; r3 = 0; *(u64 *)(r1 + 0) = r3; r0 = 0; exit;" \
+ ::: __clobber_all); \
+}
+#define CALL(callee) \
+ "*(u64 *)(r10 - 16) = r8; r1 = r10; r1 += -16; r4 = r1; r2 = r8; r2 >>= 1;" \
+ "call " #callee "; r2 = *(u64 *)(r10 - 16); r1 = r6; r1 += r2;"
+
+CLAMP(clamp, "")
+LINKED(callee_tests_memory_of_caller, VALID, CALL(clamp))
+CLAMP(store_and_clamp, "*(u64 *)(r1 + 0) = r2;")
+LINKED(callee_writes_memory_of_caller, __failure, CALL(store_and_clamp))
+/* a store defines the memory */
+CLAMP(store_and_test, "r3 = r2; *(u64 *)(r1 + 0) = r3;")
+LINKED(callee_tests_what_it_stored, VALID, CALL(store_and_test))
+/* the same address base, no overlap */
+CLAMP(store_next_and_clamp, "*(u64 *)(r1 + 8) = r2;")
+LINKED(callee_writes_next_field, VALID, CALL(store_next_and_clamp))
+/* another address base can be another name of the memory */
+CLAMP(store_alias_and_clamp, "*(u64 *)(r4 + 0) = r2;")
+LINKED(callee_writes_through_alias, __failure, CALL(store_alias_and_clamp))
+
+/*
+ * struct { char *buf; u64 len; } c = { buf, 0 }; bpf_loop(100, append, &c, 0);
+ * append: if (c->len > 63) return 1; bpf_get_prandom_u32(); c->buf[c->len]; c->len++;
+ * The compiler loads c->len again after a call. c is on the stack of the caller, where len grows
+ * until it is widened. The jump refines that slot: it still holds what the tested register was
+ * loaded from.
+ */
+#define APPEND(name, before_the_jump) \
+static __naked __used void name(void) \
+{ \
+ asm volatile ( \
+ "r6 = r2; r1 = *(u64 *)(r6 + 8);" before_the_jump \
+ "if r1 > 63 goto l_%=;" \
+ "call %[bpf_get_prandom_u32];" \
+ "r2 = *(u64 *)(r6 + 8); r1 = *(u64 *)(r6 + 0); r1 += r2; r0 = *(u8 *)(r1 + 0);" \
+ "r2 += 1; *(u64 *)(r6 + 8) = r2; r0 = 0; exit;" \
+ "l_%=: r0 = 1; exit;" \
+ :: __imm(bpf_get_prandom_u32) : __clobber_all); \
}
+#define CALL_APPEND(name) \
+ "*(u64 *)(r10 - 16) = r6; r1 = 0; *(u64 *)(r10 - 8) = r1;" \
+ "r1 = 100; r2 = " #name " ll; r3 = r10; r3 += -16; r4 = 0; call %[bpf_loop]; r1 = r6;"
+
+APPEND(append, "")
+LINKED(callback_tests_slot_of_caller, VALID, CALL_APPEND(append))
+/* The slot is written between the load and the jump: len is 0 1 3 7 15 31 63, the slot 126 */
+APPEND(append_stale, "r2 = r1; r2 <<= 1; *(u64 *)(r6 + 8) = r2;")
+LINKED(callback_tests_stale_copy_of_slot, UNBOUND, CALL_APPEND(append_stale))
-#define NOT_UNROLLED100 __msg("loop header at 5, widening r7 to 0..99 step 1")
-/* A loop that moves the pointer is not unrolled */
-ARENA_TEST(arena_pointer_moves, "r6 += 8;", __success NOT_UNROLLED100)
-/* The loop makes a number of it: the state that returns to the loop header tells */
-ARENA_TEST(arena_pointer_becomes_a_number, "if r7 != 5 goto +1; r6 = 4096;",
- __failure NOT_UNROLLED100 __msg("R6 invalid mem access 'scalar'"))
+/*
+ * p = buf; i = 0; do { if (i > 62) break; i = *(u16 *)p; p = buf + i; } while (i);
+ * r1 == r6 + r2 at the header in every iteration: it holds at loop entry, the backedge preserves it
+ */
+#define LOOP(add) \
+ "l_%=: if r2 > 62 goto out_%=; r2 = *(u16 *)(r1 + 0);" add \
+ "if r2 != 0 goto l_%=; r1 = r6;"
+
+LINKED(base_plus_index_at_loop_header, VALID, "r1 = r6; r2 = 0;" LOOP("r1 = r6; r1 += r2;"))
+LINKED(base_plus_index_at_loop_entry_only, MAP_OOB,
+ "r1 = r6; r2 = 0;" LOOP("r1 = r6; r1 += r2; r2 >>= 1;"))
+LINKED(base_plus_index_on_backedge_only, MAP_OOB,
+ "r1 = r6; r1 += r7; r2 = r8; r2 &= 255;" LOOP("r1 = r6; r1 += r2;"))
+
+LINKED(sign_extension_that_fits, VALID, "r2 = (s8)r8; if r8 > 63 goto out_%=; r1 = r6; r1 += r2;")
+
+/* 'int n' in three registers. 'if w3 s> 63' refines only 32-bit ranges: those of the copies too. */
+LINKED(copies_get_the_32_bit_range, VALID,
+ "w2 = w8; r3 = r2; r4 = r2; if w3 s> 63 goto out_%=; if w4 s< 0 goto out_%=;"
+ "r1 = r6; r1 += r2;")
+
+/* A copy on each of two paths: r2 and r3 are phis with the same operands, up to a constant */
+#define TWO_PATHS(a, b) \
+ "if r7 > 9 goto l_%=; r2 = r8; " a " goto m_%=; l_%=: r2 = r8; r2 >>= 1; " b \
+ "m_%=: if r2 > 62 goto out_%=; r1 = r6; r1 += r3;"
+
+LINKED(congruent_phis, VALID, TWO_PATHS("r3 = r2; r3 += 1;", "r3 = r2; r3 += 1;"))
+LINKED(phis_with_other_delta_on_one_path, UNBOUND,
+ TWO_PATHS("r3 = r2; r3 += 1;", "r3 = r2; r3 += 2;"))
+/* One of three edges brings unrelated values */
+LINKED(phis_not_linked_on_one_of_three_edges, UNBOUND,
+ "r3 = r8; r3 >>= 2; r2 = 0; if r7 == 20 goto m_%=;"
+ TWO_PATHS("r3 = r2; r3 += 1;", "r3 = r2; r3 += 1;"))
+/* (zext32 x) on both paths: linked in 64 bits */
+LINKED(congruent_phis_of_zext32, VALID,
+ "if r7 > 9 goto l_%=; w2 = w8; r3 = r2; goto m_%=; l_%=: r2 = r8; r2 >>= 1; w2 = w2;"
+ "r3 = r2; m_%=: r3 += 1; if r2 > 62 goto out_%=; r1 = r6; r1 += r3;")
+
+/* The low 3 bits of r3 are 5. It is r8 + 5 once r8 fits in s8: no overlap with [-2, 1]. */
+LINKED(empty_intersection, VALID __flag(BPF_F_TEST_REG_INVARIANTS),
+ "r3 = (s8)r8; if r3 & 7 goto out_%=; r3 += 5; if r3 s> 100 goto out_%=;"
+ "if r3 s< -100 goto out_%=; if r8 s< -7 goto out_%=; if r8 s> -4 goto out_%=;"
+ "r3 += 3; r1 = r6;")
+
+/* r2 is even. It is r8 once r8 fits in s8. r8 is odd after the last jump: var_off don't overlap. */
+LINKED(var_off_dont_overlap, VALID,
+ "r2 = (s8)r8; if r2 & 1 goto out_%=; if r2 s> 100 goto out_%=; if r2 s< -100 goto out_%=;"
+ "if r8 > 5 goto out_%=; if r8 & 1 goto l_%=; goto out_%=;"
+ "l_%=: r2 &= 1; r2 <<= 6; r1 = r6; r1 += r2;")
+
+/* The low bytes of the spill to r10 - 16 come first or last */
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#define FIRST_BYTES_ARE_LOW VALID
+#else
+#define FIRST_BYTES_ARE_LOW __failure __msg("R1 unbounded memory access")
#endif
+/* r2 is the low 32 bits of the slot. The 32-bit spill is in its first half-slot. */
+LINKED(spill_32_bits_fill_64_take_low_half, FIRST_BYTES_ARE_LOW,
+ "*(u64 *)(r10 - 16) = r7; *(u32 *)(r10 - 16) = r8; r2 = *(u64 *)(r10 - 16); w2 = w2;"
+ "w3 = w8; if r2 > 63 goto out_%=; r1 = r6; r1 += r3;")
+/* The slot is a phi: two paths spill distinct values to its first half-slot */
+LINKED(spill_32_bits_on_two_paths_fill_64_take_low_half, FIRST_BYTES_ARE_LOW,
+ "*(u64 *)(r10 - 16) = r7; *(u32 *)(r10 - 16) = r8; if r7 > 9 goto l_%=;"
+ "r3 = r8; r3 >>= 1; *(u32 *)(r10 - 16) = r3;"
+ "l_%=: r2 = *(u64 *)(r10 - 16); w2 = w2; if r2 > 63 goto out_%=;"
+ "r3 = *(u32 *)(r10 - 16); r1 = r6; r1 += r3;")
+/* The half-slot at r10 - 12 is dead: at the second jump the state has a 32-bit spill */
+LINKED(spill_64_bits_fill_32, FIRST_BYTES_ARE_LOW,
+ "*(u64 *)(r10 - 16) = r8; if r8 s> 63 goto out_%=; if r8 s< 0 goto out_%=;"
+ "r2 = *(u32 *)(r10 - 16); r1 = r6; r1 += r2;")
+
+/* r0 is r10 - 24 when the first 8 bytes of the packet are not in one piece */
+LINKED_SEC("tc", slot_written_through_a_slice, UNBOUND,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -24; r4 = 8;"
+ "call %[bpf_dynptr_slice_rdwr]; if r0 == 0 goto out_%=;"
+ "r3 = *(u64 *)(r10 - 24); *(u64 *)(r0 + 0) = r8; r2 = *(u64 *)(r10 - 24);"
+ "if r3 > 63 goto out_%=; r1 = r6; r1 += r2;")
+/* One fill reads one value: r2 is a copy of r3, whatever is stored through the slice */
+LINKED_SEC("tc", copy_of_a_fill_from_a_slice_buffer, VALID,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -24; r4 = 8;"
+ "call %[bpf_dynptr_slice_rdwr]; if r0 == 0 goto out_%=;"
+ "r3 = *(u64 *)(r10 - 24); r2 = r3; *(u64 *)(r0 + 0) = r8;"
+ "if r3 > 63 goto out_%=; r1 = r6; r1 += r2;")
+
+/* The buffer is r10 - 32 or r10 - 48, a range in the state. The call does not write to r10 - 40. */
+LINKED_SEC("tc", slice_buffer_at_two_offsets, VALID,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "*(u64 *)(r10 - 32) = r7; *(u64 *)(r10 - 40) = r7; *(u64 *)(r10 - 48) = r7;"
+ "r8 = r10; r8 += -48; r9 = r10; r9 += -32; r7 = 0;"
+ "l_%=: call %[bpf_get_prandom_u32]; if r0 == 0 goto s_%=; r9 = r8;"
+ "s_%=: r7 += 1; if r7 < 64 goto l_%=;"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r9; r4 = 8; call %[bpf_dynptr_slice_rdwr];"
+ "r1 = *(u64 *)(r10 - 40); r1 = r6;")
+/* No insn stores through a slice of 0 bytes, and the call does not write to the buffer */
+LINKED_SEC("tc", slice_of_0_bytes_at_variable_offset, VALID,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "*(u64 *)(r10 - 24) = r7; *(u64 *)(r10 - 32) = r7; r7 &= 8;"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -32; r3 += r7; r4 = 0;"
+ "call %[bpf_dynptr_slice_rdwr]; r1 = r6;")
+
+/* BTF of the kfuncs that only asm calls */
+void __kfunc_btf_root(void)
+{
+ bpf_dynptr_from_skb(0, 0, 0);
+ bpf_dynptr_slice_rdwr(0, 0, 0, 0);
+}
+
+/* Linked at the header in every iteration: r2 is r3 + 2 at loop entry, both have the step 1 */
+#define LOOP_HEADER(enter, step) \
+ enter "l_%=: if r3 > 61 goto out_%=; r1 = r6; r1 += r2; r0 = *(u8 *)(r1 + 0);" step \
+ "if r0 != 0 goto l_%=;"
+
+LINKED(linked_at_loop_header, VALID,
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 1; r3 += 1;"))
+LINKED(linked_at_loop_entry_only, __failure,
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 2; r3 += 1;"))
+
+/*
+ * An irreducible loop: 'l' is the header, 'm' is a secondary entry. A link that is made in the loop
+ * holds in the next basic blocks too. Not after 'm' if it is made before 'm': every edge of the
+ * loop to 'm' has it, the edge that enters the loop there does not. That edge can come from
+ * a natural loop 'o' around the irreducible one.
+ * In the last two tests 'o' is the header. The natural loop in it has an env at loop entry. Its
+ * header can be the secondary entry.
+ */
+LINKED(irreducible_loop, VALID,
+ "if r7 > 5 goto m_%=; l_%=: r7 += 1;"
+ "m_%=: r2 = r8; r2 += 1; r2 += 1; if r8 > 61 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=;")
+LINKED(irreducible_loop_fallthrough_pred, UNBOUND,
+ "r2 = r7; if r7 > 5 goto m_%=; l_%=: r7 += 1; r2 = r8;"
+ "m_%=: if r8 > 63 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=;")
+LINKED(irreducible_loop_next_bb, VALID,
+ "if r7 > 5 goto m_%=; l_%=: r7 += 1;"
+ "m_%=: r2 = r8; r2 += 1; r2 += 1; if r7 == 3 goto n_%=; r3 = 0;"
+ "n_%=: if r8 > 61 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=;")
+LINKED(irreducible_loop_secondary_entry, UNBOUND,
+ "r9 = 0; o_%=: r9 += 1; call %[bpf_ktime_get_ns]; r8 = r0; r2 = r7; if r7 > 5 goto m_%=;"
+ "l_%=: r7 += 1; r2 = r8; r2 += 1; r2 += 1; if r7 == 3 goto m_%=; r3 = 0;"
+ "m_%=: if r8 > 61 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=; if r9 < 3 goto o_%=;")
+LINKED(natural_loop_in_irreducible_loop, VALID,
+ "if r7 > 5 goto m_%=; o_%=: r7 += 1; m_%=:"
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 1; r3 += 1;")
+ "if r7 < 10 goto o_%=;")
+LINKED(natural_loop_is_secondary_entry, MAP_OOB,
+ "r3 = r8; r2 = r7; if r7 > 5 goto l_%=; o_%=: r7 += 1;"
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 1; r3 += 1;")
+ "if r7 < 10 goto o_%=;")
+
+/*
+ * No exit of the inner loop dominates its backedges: may_goto is added before its header. The prog
+ * holds a reference, so may_goto goes to the exit of the outer loop: an edge that the verifier
+ * adds. Every iteration of the outer loop restores r3. At the header of the inner one it is r7.
+ */
+LINKED(added_edge, UNBOUND,
+ "r1 = %[ringbuf] ll; r2 = 8; r3 = 0; call %[bpf_ringbuf_reserve]; if r0 == 0 goto out_%=;"
+ "*(u64 *)(r10 - 16) = r0; r3 = r8;"
+ "o_%=: r2 = r3; r3 = r7;"
+ "i_%=: r1 = *(u8 *)(r6 + 0); if r1 == 1 goto a_%=; if r1 == 2 goto b_%=; goto i_%=;"
+ "a_%=: goto i_%=;"
+ "b_%=: r3 = r2; r1 = *(u8 *)(r6 + 1); if r1 == 3 goto o_%=;"
+ "r4 = r6; if r8 > 63 goto r_%=; r4 += r3;"
+ "r_%=: *(u64 *)(r10 - 24) = r4; r1 = *(u64 *)(r10 - 16); r2 = 0;"
+ "call %[bpf_ringbuf_discard]; r1 = *(u64 *)(r10 - 24);")
+
/*
* r7 = ctx->data;
* r8 = r7
@@ -3448,9 +3794,9 @@ __failure
__log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
__msg("scev at header 9:")
-__msg_next(" r6=(+ ? 1) / ?")
+__msg_next(" r6=(+ %r6.13? 1) / ?")
__msg_next(" scev at latch 20:")
-__msg_next(" r6=(+ ? 1) / (+ ? 1)")
+__msg_next(" r6=(+ %r6.13? 1) / (+ %r6.13? 1)")
__msg_next("scev at header 13:")
__msg_next(" r9=(+ r9 1) / (linear r9 1)")
__msg_next(" scev at latch 16:")
@@ -3524,7 +3870,7 @@ SEC("xdp")
__success __retval(3)
__log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
-__msg("r6 = *(u64 *)(r10 -8) {{.*}}; r6 ? -> r6")
+__msg("r6 = *(u64 *)(r10 -8) {{.*}}; r6 %r6.4? -> r6")
__msg("scev at header 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
__msg_next(" scev at latch 16:")
@@ -3645,7 +3991,7 @@ __success
__log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
__msg("scev at header 4:")
-__msg_next("r7=(any r7 8) / (any r7 8)")
+__msg_next("r7=%r7.11=phi(r7, 8) / (any r7 8)")
__msg("loop header at 4, can't widen r7, expr is {{.*}}, requires exact stack-offset tracking")
__naked void no_widen_stack_fill_any(void)
{
@@ -4419,7 +4765,7 @@ SEC("socket")
__success __retval(0)
__log_level(2)
__msg("header_count is 100000 ")
-__msg("can't widen r6, expr is _")
+__msg("can't widen r6, expr is %r6.13")
__not_msg("widening r8")
__msg("clamping r8 to 0..0x1869f step 1")
__naked void index_loaded_in_previous_iteration(void)
diff --git a/tools/testing/selftests/bpf/progs/verifier_spill_fill.c b/tools/testing/selftests/bpf/progs/verifier_spill_fill.c
index 0baa8e06b8d1ef..623ed5ef3630d4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_spill_fill.c
+++ b/tools/testing/selftests/bpf/progs/verifier_spill_fill.c
@@ -1451,6 +1451,37 @@ __naked void imprecise_scalar_spill_half_dead(void)
: __clobber_all);
}
+/*
+ * The first half-slot of a 64-bit spill holds its low 32 bits on little endian only.
+ * The test spills to r10 - 8. The first four bytes of the slot are an offset into one byte.
+ */
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#define FIRST_HALF_IS_LOW __success
+#else
+#define FIRST_HALF_IS_LOW __failure __msg("access may be outside object bounds")
+#endif
+#define FIRST_HALF(name, stores) \
+SEC("raw_tp") FIRST_HALF_IS_LOW \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "call %[bpf_ktime_get_ns];" \
+ stores \
+ "r7 = *(u32 *)(r10 - 8); r1 = %[single_byte_buf] ll; r1 += r7; r0 = *(u8 *)(r1 + 0);" \
+ "out_%=: r0 = 0; exit;" \
+ : \
+ : __imm(bpf_ktime_get_ns), __imm_addr(single_byte_buf) \
+ : __clobber_all); \
+}
+
+/* The low 32 bits of the value are 0. The second half-slot is dead after the jump. */
+FIRST_HALF(first_half_of_spill_second_half_dead,
+ "r0 <<= 32; *(u64 *)(r10 - 8) = r0; if r0 == 0 goto out_%=;")
+/* One path has a 32-bit spill of r6, whose low 32 bits are 0, the other one a 64-bit spill */
+FIRST_HALF(spill_of_64_bits_vs_spill_of_32_bits,
+ "r6 = r0; r6 <<= 32; if r0 > 5 goto 1f; *(u32 *)(r10 - 8) = r6; goto 2f;"
+ "1: r6 = 0x7ffffff000000000 ll; *(u64 *)(r10 - 8) = r6; 2:")
+
/* check valid spill/fill, ptr to tp buffer */
SEC("raw_tracepoint.w")
__success
|
| 3/2 | 2026/11/14 14:38 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 102477 output: 33 thoughts: 1336 Thoughts: **BPF Verifier Patch Analysis for Syzkaller Fuzzing** Okay, so I've got this patch series for the BPF verifier in front of me, and my job is to determine if it's worth fuzzing with syzkaller. Alright, let's break this down systematically. First thing I see is that it's touching quite a bit of code, specifically within `include/linux/bpf_verifier.h`, and then extensively within the kernel BPF directory: `flow.c`, `join.c`, `liveness.c`, `log.c`, `scev.c`, `states.c`, `syscall.c`, and `verifier.c`, along with some selftests. This is a pretty massive change, and the BPF verifier is a core part of the system! It's completely reachable via unprivileged and privileged `sys_bpf` syscalls. Given that this touches SCEV, linked register tracking, scalar IDs, value numbering, phi functions, range deduction, and various critical functions like `regsafe()`, `check_cond_jmp_op()`, `refine_linked_regs()`, `bpf_compute_scev()`, `mk_phi()`, and `split_const_offset()`, it's clear the changes directly touch executable code within a core subsystem. According to the criteria, any modification in core subsystems like BPF warrants fuzzing. So, `WorthFuzzing` is definitely `true`. Now, the next part is finding the fuzzing entry points. I need to identify specific functions to target, those that aren't ubiquitous lifecycle hot-paths, but rather the feature logic or entrypoints that are added or altered. I want to avoid generic, ubiquitous functions and focus on these entrypoints. Let's see what stands out: In `kernel/bpf/verifier.c`: the new functions `bpf_is_dynptr_slice_rdwr_kfunc`, `recompute_ptr`, `scev_mem_to_slot`, `reg_is_empty`, `tnum_overlaps_cnum`, `tnum_overlaps_urange`, and `refine_linked_regs` and modifications to `check_cond_jmp_op`, `check_special_kfunc`, `coerce_subreg_to_size_sx`, `adjust_reg_min_max_vals` are all interesting. In `kernel/bpf/scev.c`: the new functions `bpf_scev_next_linked_reg`, `bpf_scev_mem_addr`, `bpf_is_widenable_reg_type`, `bpf_scev_in_slice_slots`, `find_linked_regs` and `mk_phi` and modifications to `bpf_compute_scev`, `bpf_init_scev`, `bpf_widen_scev_regs`, `bpf_clamp_scev_regs`, `bpf_compute_loop_iters`, `compute_scev_for_loop` appear to be relevant to the change. In `kernel/bpf/liveness.c`: new function `bpf_half_slot_live_before` and modification of `arg_track_deref`. In `kernel/bpf/join.c`: modified `join_reg`, `jid_note`, `jid_good`. In `kernel/bpf/states.c`: modified `regsafe`, `stacksafe`, `__clean_func_state`. In `kernel/bpf/flow.c`: modified `flow_join_makes_up`, `flow_arrive`. In `kernel/bpf/syscall.c`: modified `bpf_sys_bpf_proto`. I'll need to go through `scev.c` and `verifier.c`, check whether these functions are static or exported, and whether they are in the symbol table or vmlinux, perhaps running `grepper` or checking the source files. I'll need to run this to ensure syzkaller targets the right functions. **So, the preliminary evaluation is `WorthFuzzing = true`. The next step is to finalize `FocusSymbols` based on the symbol checks, `EnableConfigs` to include any required kernel config flags, and a concise `Reasoning` for the evaluation.** |
| 4/2 | 2026/11/14 14:38 | tool | grepper |
0mArgs:{
"Expression": "bpf_compute_scev",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/scev.c=3006=static void find_slice_slots(struct bpf_verifier_env *env)\n--\nkernel/bpf/scev.c-3022-\nkernel/bpf/scev.c:3023:int bpf_compute_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-3024-{\n--\nkernel/bpf/verifier.c=25159=int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n--\nkernel/bpf/verifier.c-25391-\nkernel/bpf/verifier.c:25392:\tret = bpf_compute_scev(env);\nkernel/bpf/verifier.c-25393-\tif (ret \u003c 0)\n"
} |
| 5/2 | 2026/11/14 14:38 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 105023 output: 31 thoughts: 45 Thoughts: Okay, let's dive into this. Here's how I'd approach this task, walking through my thought process: **Investigating BPF/Verifier/SCEV Kconfig Dependencies** Alright, so I'm trying to figure out which Kconfig options ultimately control the compilation and behavior of BPF, the verifier, and the Static Compiler for Enhanced Verification (SCEV). I know where to start, and where to look. First, my instinct is to understand the overarching configuration. I'll need to confirm the dependencies for including this functionality in the kernel. My thought is, "Okay, where does the main logic live? What's the best entry point?" And the answer is usually within the `kernel/bpf` directory. Specifically, I'll go straight to `kernel/bpf/Makefile` to start exploring. That's usually the best place to find the conditional compilation rules. From there, I can trace dependencies and understand under which configuration options `scev.c` is compiled. |
| 6/2 | 2026/11/14 14:38 | tool | grepper |
0mArgs:{
"Expression": "scev\\.o",
"PathPrefixes": [
"kernel/bpf/Makefile"
]
}Results: {
"Output": "kernel/bpf/Makefile=7=CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)\nkernel/bpf/Makefile-8-\nkernel/bpf/Makefile:9:obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o loops.o scev.o\nkernel/bpf/Makefile-10-obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o\n"
} |
| 7/2 | 2026/11/14 14:38 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 105485 output: 38 thoughts: 100 Thoughts: **My BPF Compilation Thoughts** Okay, so `CONFIG_BPF_SYSCALL` triggers the build of a whole slew of BPF-related object files: `syscall.o`, `verifier.o`, `inode.o`, the helpers and tnum, cnum, log, token, liveness, const_fold, diagnostics, loops, and scev. That’s a pretty comprehensive suite of components. It's a solid foundation. Now, my experience tells me that BPF functionality can be distributed across other files in the kernel as well. Let me quickly double-check that this is the complete list. I have a feeling I've seen files like `flow.o`, `join.o`, or `states.o` involved in BPF before. Best to be thorough, I'll `grep` for those in `kernel/bpf/Makefile` to make sure I'm not missing anything crucial. Gotta ensure I have the full picture for any further analysis. |
| 8/2 | 2026/11/14 14:39 | tool | grepper |
0mArgs:{
"Expression": "flow\\.o|join\\.o|states\\.o",
"PathPrefixes": [
"kernel/bpf/Makefile"
]
}Results: {
"Output": "kernel/bpf/Makefile=13=obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o\nkernel/bpf/Makefile:14:obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o check_btf.o flow.o join.o\nkernel/bpf/Makefile-15-obj-${CONFIG_BPF_LSM}\t += bpf_inode_storage.o\n"
} |
| 9/2 | 2026/11/14 14:39 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 105963 output: 40 thoughts: 35 Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, and delivered as a first-person summary: **Digging into BPF Syscall Dependencies** Right, so, as I understand it, everything here is predicated on the `CONFIG_BPF_SYSCALL` Kconfig option. Let's start with that assumption and dive right into the heart of the matter. I need to fully understand the dependency landscape. My next step is obviously to go and check the `BPF_SYSCALL` dependencies within Kconfig. I want to see precisely what other features, hardware architectures, or kernel subsystems need to be in place for this whole thing to work. What other options are pulled in automatically? Are there any hidden gotchas? Where are the potential conflicts? It's all about mapping the dependencies now, the critical path to understanding. |
| 10/2 | 2026/11/14 14:39 | tool | grepper |
0mArgs:{
"Expression": "config BPF_SYSCALL",
"PathPrefixes": [
"init/Kconfig",
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/Kconfig=34=menu \"BPF subsystem\"\nkernel/bpf/Kconfig-35-\nkernel/bpf/Kconfig:36:config BPF_SYSCALL\nkernel/bpf/Kconfig-37-\tbool \"Enable bpf() system call\"\n"
} |
| 11/2 | 2026/11/14 14:39 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 106302 output: 34 thoughts: 19 Thoughts: Here's my take on the kernel's BPF Kconfig file, focusing around line 36: **Delving into BPF's Configuration** Okay, time to dig into the BPF kernel configuration. I'm specifically targeting `kernel/bpf/Kconfig`, and I'm going to start my analysis around line 36. My initial hunch is that this area likely deals with fundamental BPF enablement options or perhaps some of the more core feature flags. I expect to see the basic building blocks here – whether BPF is even *compiled* into the kernel in the first place, or if we're dealing with more granular control over specific BPF functionalities. Let's see what the developers have deemed important enough to be configurable at compile time and what trade-offs they've accounted for. From experience, line 36 is probably where the really important stuff resides and it might give hints about what dependencies exist. I'm ready to find out! |
| 12/2 | 2026/11/14 14:39 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/Kconfig",
"FirstLine": 34,
"LineCount": 30
}Results: {
"Contents": " 34:\tmenu \"BPF subsystem\"\n 35:\t\n 36:\tconfig BPF_SYSCALL\n 37:\t\tbool \"Enable bpf() system call\"\n 38:\t\tselect BPF\n 39:\t\tselect IRQ_WORK\n 40:\t\tselect NEED_TASKS_RCU\n 41:\t\tselect TASKS_TRACE_RCU\n 42:\t\tselect BINARY_PRINTF\n 43:\t\tselect NET_SOCK_MSG if NET\n 44:\t\tselect NET_XGRESS if NET\n 45:\t\tselect PAGE_POOL if NET\n 46:\t\tdefault n\n 47:\t\thelp\n 48:\t\t Enable the bpf() system call that allows to manipulate BPF programs\n 49:\t\t and maps via file descriptors.\n 50:\t\n 51:\tconfig BPF_JIT\n 52:\t\tbool \"Enable BPF Just In Time compiler\"\n 53:\t\tdepends on BPF\n 54:\t\tdepends on HAVE_CBPF_JIT || HAVE_EBPF_JIT\n 55:\t\tselect EXECMEM\n 56:\t\thelp\n 57:\t\t BPF programs are normally handled by a BPF interpreter. This option\n 58:\t\t allows the kernel to generate native code when a program is loaded\n 59:\t\t into the kernel. This will significantly speed-up processing of BPF\n 60:\t\t programs.\n 61:\t\n 62:\t\t Note, an admin should enable this feature changing:\n 63:\t\t /proc/sys/net/core/bpf_jit_enable\n"
} |
| 13/2 | 2026/11/14 14:39 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 106967 output: 33 thoughts: 45 Thoughts: Here's my understanding, as if I were thinking it: **BPF_SYSCALL Dependency Analysis** Okay, so I'm looking at `BPF_SYSCALL` in the kernel configuration. I need to figure out its dependencies. It's nestled inside a `menu "BPF subsystem"`, which suggests a degree of containment, but that doesn't tell me everything. My initial approach is to check the configuration file, specifically lines 1 to 34 of `kernel/bpf/Kconfig`. Based on the way the config structure is organized, the parent menu statement suggests that this option should be largely independent in terms of direct dependencies. So I'll analyze those lines and see if anything is explicitly stated. I'm expecting to find a clean, straightforward structure. |
| 14/2 | 2026/11/14 14:39 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/Kconfig",
"FirstLine": 1,
"LineCount": 35
}Results: {
"Contents": " 1:\t# SPDX-License-Identifier: GPL-2.0-only\n 2:\t\n 3:\t# BPF interpreter that, for example, classic socket filters depend on.\n 4:\tconfig BPF\n 5:\t\tbool\n 6:\t\tselect CRYPTO_LIB_SHA256\n 7:\t\n 8:\t# Used by archs to tell that they support BPF JIT compiler plus which\n 9:\t# flavour. Only one of the two can be selected for a specific arch since\n 10:\t# eBPF JIT supersedes the cBPF JIT.\n 11:\t\n 12:\t# Classic BPF JIT (cBPF)\n 13:\tconfig HAVE_CBPF_JIT\n 14:\t\tbool\n 15:\t\n 16:\t# Extended BPF JIT (eBPF)\n 17:\tconfig HAVE_EBPF_JIT\n 18:\t\tbool\n 19:\t\n 20:\t# KASAN support for JIT compiler\n 21:\tconfig HAVE_EBPF_JIT_KASAN\n 22:\t\tbool\n 23:\t\n 24:\t# Used by archs to tell that they want the BPF JIT compiler enabled by\n 25:\t# default for kernels that were compiled with BPF JIT support.\n 26:\tconfig ARCH_WANT_DEFAULT_BPF_JIT\n 27:\t\tbool\n 28:\t\n 29:\t# Used by archs to tell that kernels that were compiled with BPF JIT support\n 30:\t# have no BPF interpreter.\n 31:\tconfig ARCH_WANT_BPF_JIT_ALWAYS_ON\n 32:\t\tbool\n 33:\t\n 34:\tmenu \"BPF subsystem\"\n 35:\t\n"
} |
| 15/2 | 2026/11/14 14:39 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 107677 output: 32 thoughts: 95 Thoughts: **My BPF Configuration Audit** Okay, so I'm diving into this `BPF_SYSCALL` thing. First thought: it seems pretty standalone, just a direct selection of `BPF`. No immediate dependencies jumping out at me, which is good. But I need to be thorough. I can't just assume anything, especially with BPF. Now, the question is, are there *any* other configurations, even indirectly related, that I need to be aware of? Even if `BPF_SYSCALL` is clean, what about the arena-related features? Arena, like any complex subsystem, could potentially require its own specialized config options that aren't immediately obvious. Let's dig in. I recall seeing arena usage in `tools/testing/selftests/bpf/progs/verifier_arena.c`. Ah, yes, it uses `BPF_MAP_TYPE_ARENA`. This makes me think - does the `ARENA` map type itself demand its own configuration flag? That's the key. I need to be certain there isn't a separate, dedicated `BPF_ARENA` configuration or some dependency on another feature. That's the next line of inquiry. |
| 16/2 | 2026/11/14 14:40 | tool | grepper |
0mArgs:{
"Expression": "config BPF_ARENA",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "no matches"
} |
| 17/2 | 2026/11/14 14:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 108079 output: 29 thoughts: 18 Thoughts: Okay, here's my summary, presented as a stream of thought: **Checking BPF Arena Configuration** Alright, let's dive into this. My initial thought is to zero in on the BPF arena functionality within the kernel. Given my familiarity with the codebase, the logical place to start is the `Kconfig` file, specifically within the `kernel/bpf` directory. That's where I'd expect to find the configuration options related to it. My instinct is to use `grep` to quickly search that file for instances of "arena." This should give me a rapid overview of the configuration parameters, dependencies, and any other relevant settings associated with the BPF arena implementation. I'm aiming for a quick and targeted scan to understand the current configuration options. |
| 18/2 | 2026/11/14 14:40 | tool | grepper |
0mArgs:{
"Expression": "arena",
"PathPrefixes": [
"kernel/bpf/Kconfig"
]
}Results: {
"Output": "no matches"
} |
| 19/2 | 2026/11/14 14:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 108302 output: 50 thoughts: 85 Thoughts: **Analyzing the BPF System Call Configuration and Patch** Okay, let's start by getting a handle on `CONFIG_BPF_SYSCALL` more broadly. I need to refresh my understanding of how it fits into the kernel's architecture and the overall BPF landscape. Now, I'll dive into this particular patch. I want to really understand the nitty-gritty: what specifically does this patch *do*, and most importantly, *why* was it necessary? I need to identify the key modifications and their implications. This requires a sharp eye for the FocusSymbols – figuring out which elements are truly significant here. The commit message itself is a starting point, referencing "syz-cluster: applied patch under review". That's a helpful clue, suggesting automated testing and review involvement. To get the full context and understand the evolution of this change, I'll now consult the `git log`. I'll look at prior commits and try to discern the history, especially the commit subjects, to grasp the rationale behind this patch and any potential related issues or discussions. |
| 20/2 | 2026/11/14 14:40 | tool | grepper |
0mArgs:{
"Expression": "bpf_scev_next_linked_reg",
"PathPrefixes": [
"include/linux/bpf_verifier.h",
"kernel/bpf/"
]
}Results: {
"Output": "include/linux/bpf_verifier.h=60=struct bpf_reg_state {\n--\ninclude/linux/bpf_verifier.h-180-\t * A scalar has no id. The scalars that it is linked to are static: computed before the\ninclude/linux/bpf_verifier.h:181:\t * main pass, see bpf_scev_next_linked_reg().\ninclude/linux/bpf_verifier.h-182-\t */\n--\ninclude/linux/bpf_verifier.h=2198=int bpf_scev_jump_counts(struct bpf_verifier_env *env, int header, int n, bool taken_leaves);\ninclude/linux/bpf_verifier.h:2199:bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,\ninclude/linux/bpf_verifier.h-2200-\t\t\t u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,\n--\nkernel/bpf/scev.c=2223=static u32 find_leader(struct bpf_verifier_env *env, struct env *e, int h,\n--\nkernel/bpf/scev.c-2238- * registers that are linked to one of them in @e, the env before the jump, and keep them with their\nkernel/bpf/scev.c:2239: * expressions: what bpf_scev_next_linked_reg() needs of @e.\nkernel/bpf/scev.c-2240- */\nkernel/bpf/scev.c=2241=static int find_linked_regs(struct bpf_verifier_env *env, struct env *e, int h, int idx)\n--\nkernel/bpf/scev.c-2341- */\nkernel/bpf/scev.c:2342:bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,\nkernel/bpf/scev.c-2343-\t\t\t u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,\n--\nkernel/bpf/verifier.c=19511=static void refine_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,\n--\nkernel/bpf/verifier.c-19522-\tfor (pos = 0;\nkernel/bpf/verifier.c:19523:\t bpf_scev_next_linked_reg(env, idx, regno, \u0026pos, \u0026linked_regno, \u0026fill_off, \u0026base_regno,\nkernel/bpf/verifier.c-19524-\t\t\t\t \u0026delta, \u0026bits);\n"
} |
| 21/2 | 2026/11/14 14:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 109406 output: 81 thoughts: 1305 Thoughts: **eBPF Scalar Tracking: A Paradigm Shift and Fuzzing Target** Alright, let's break this down. This patch is a major overhaul of how we track linked scalar registers within the eBPF verifier. Previously, we were using a system of `id` and `delta` within `bpf_reg_state` for dynamic tracking, handled through a series of functions like `assign_scalar_id_before_mov()`, `collect_linked_regs()`, and so on. Now, that's gone. What's changed? Scalar registers no longer have their own `id` or `delta` directly within `bpf_reg_state`. We've eliminated the tracking from various other functions too, like `regsafe` and `check_alu_op`. Instead, linked scalars are now computed statically *before* the main verification pass, during scalar evolution (SCEV) in `kernel/bpf/scev.c`. During SCEV, `find_linked_regs()` calculates linked registers and their expressions, crucial for conditional jumps. Then, during verification, at conditional jumps (`check_cond_jmp_op`), we call `refine_linked_regs()`, which queries `bpf_scev_next_linked_reg()` to update bounds and ranges using `recompute_ptr`, `regs_refine_cond_op`, etc. This also involves promoting memory locations during SCEV using functions like `find_mem_reg`, `replace_mem_reg`, and so on. We're also handling dynptr slice buffer aliasing with stack slots. The icing on the cake is that `bpf_compute_scev` is now also run for subprograms, which means we can compute SCEV and SSA value numbering across subprograms. Finally, `reg_is_empty()` checks `tnum_overlaps_cnum` and `tnum_overlaps_urange`. This is a fundamental shift in architecture for how scalar bounds and ranges are managed. This is a huge area for soundless verifier issues, where we might allow a BPF program to bypass the sandbox, and achieve local privilege escalation. This could also lead to verifier panics or crashes, resulting in denial of service or heap corruption, or even out-of-bounds accesses. Is it worth fuzzing? Absolutely. The BPF verifier's security is critical, and any changes in this area are high-risk. Now, let's identify some good "FocusSymbols" for fuzzing. We need to avoid ubiquitous, hot-path functions. We want to target the specific logic added or altered by the patch, or the direct API entrypoints for this subsystem. Static inline functions in headers are useless, so we look for non-static functions in .c files. Looking at the .c files, here are the key non-static functions we need to focus on: From `kernel/bpf/scev.c`: * `bpf_compute_scev` * `bpf_scev_next_linked_reg` * `bpf_scev_mem_addr` * `bpf_is_widenable_reg_type` * `bpf_scev_in_slice_slots` * `bpf_init_scev` * `bpf_free_scev` * `bpf_widen_scev_regs` * `bpf_clamp_scev_regs` From `kernel/bpf/verifier.c`: * `bpf_check` (the main entrypoint) * `bpf_is_dynptr_slice_rdwr_kfunc` From `kernel/bpf/liveness.c`: * `bpf_half_slot_live_before` I need to confirm the static/non-static status of `check_cond_jmp_op` and `refine_linked_regs` in `verifier.c` and make sure my list is complete. But I'm going to fuzz this *hard*. |
| 22/2 | 2026/11/14 14:40 | tool | grepper |
0mArgs:{
"Expression": "^(bool|int|void) (bpf_|check_cond_jmp_op|refine_linked_regs|regsafe)",
"PathPrefixes": [
"kernel/bpf/verifier.c",
"kernel/bpf/states.c",
"kernel/bpf/scev.c"
]
}Results: {
"Output": "\nFull output is too long, showing 200 out of 327 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (3 files in total):\nkernel/bpf/scev.c:11\nkernel/bpf/states.c:2\nkernel/bpf/verifier.c:47\n\nkernel/bpf/scev.c=2241=static int find_linked_regs(struct bpf_verifier_env *env, struct env *e, int h, int idx)\n--\nkernel/bpf/scev.c-2341- */\nkernel/bpf/scev.c:2342:bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,\nkernel/bpf/scev.c-2343-\t\t\t u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,\n--\nkernel/bpf/scev.c-2385- */\nkernel/bpf/scev.c:2386:bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,\nkernel/bpf/scev.c-2387-\t\t s64 *off)\n--\nkernel/bpf/scev.c=3006=static void find_slice_slots(struct bpf_verifier_env *env)\n--\nkernel/bpf/scev.c-3022-\nkernel/bpf/scev.c:3023:int bpf_compute_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-3024-{\n--\nkernel/bpf/scev.c-3102- */\nkernel/bpf/scev.c:3103:bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off)\nkernel/bpf/scev.c-3104-{\n--\nkernel/bpf/scev.c-3112-\nkernel/bpf/scev.c:3113:void bpf_free_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-3114-{\n--\nkernel/bpf/scev.c-3140-\nkernel/bpf/scev.c:3141:int bpf_init_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-3142-{\n--\nkernel/bpf/scev.c=3350=static int match_linear_latch(struct bpf_verifier_env *env,\n--\nkernel/bpf/scev.c-3443- */\nkernel/bpf/scev.c:3444:int bpf_scev_jump_counts(struct bpf_verifier_env *env, int header, int n, bool taken_leaves)\nkernel/bpf/scev.c-3445-{\n--\nkernel/bpf/scev.c=4285=static bool is_const_scev_reg(struct bpf_verifier_env *env, int insn_idx, u32 r)\n--\nkernel/bpf/scev.c-4293-/* Main logic in verifier.c forbids varying offsets for certain register types. */\nkernel/bpf/scev.c:4294:bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg)\nkernel/bpf/scev.c-4295-{\n--\nkernel/bpf/scev.c=4690=static bool same_latch(const struct linear_latch *a, const struct linear_latch *b)\n--\nkernel/bpf/scev.c-4696-\nkernel/bpf/scev.c:4697:int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\nkernel/bpf/scev.c-4698-\t\t\t struct bpf_loop_iters *iters)\n--\nkernel/bpf/scev.c=4962=static int union_any_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,\n--\nkernel/bpf/scev.c-5010- */\nkernel/bpf/scev.c:5011:int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\nkernel/bpf/scev.c-5012-\t\t\tstruct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters,\n--\nkernel/bpf/scev.c=5134=static bool is_moved_linear(struct scev *scev, u32 id, struct linear_coefs *out, s64 *moved)\n--\nkernel/bpf/scev.c-5152- */\nkernel/bpf/scev.c:5153:int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur_func_state, u32 insn_idx,\nkernel/bpf/scev.c-5154-\t\t\tconst struct loop_stack_entry *entry, bool behind)\n--\nkernel/bpf/states.c=88=static void __clean_func_state(struct bpf_verifier_env *env,\n--\nkernel/bpf/states.c-167-\nkernel/bpf/states.c:168:int bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *st)\nkernel/bpf/states.c-169-{\n--\nkernel/bpf/states.c=634=static void reset_idmap_scratch(struct bpf_verifier_env *env)\n--\nkernel/bpf/states.c-641-/* Everything that @cur describes is described by @old. */\nkernel/bpf/states.c:642:bool bpf_state_subsumes(struct bpf_verifier_env *env, struct bpf_verifier_state *old,\nkernel/bpf/states.c-643-\t\t\tstruct bpf_verifier_state *cur)\n--\nkernel/bpf/verifier.c=379=static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)\n--\nkernel/bpf/verifier.c-393-\nkernel/bpf/verifier.c:394:bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)\nkernel/bpf/verifier.c-395-{\n--\nkernel/bpf/verifier.c=467=const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog)\n--\nkernel/bpf/verifier.c-477-\nkernel/bpf/verifier.c:478:void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)\nkernel/bpf/verifier.c-479-{\n--\nkernel/bpf/verifier.c=555=static bool is_callback_calling_function(enum bpf_func_id func_id)\n--\nkernel/bpf/verifier.c-560-\nkernel/bpf/verifier.c:561:bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn)\nkernel/bpf/verifier.c-562-{\n--\nkernel/bpf/verifier.c-566-\nkernel/bpf/verifier.c:567:bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn)\nkernel/bpf/verifier.c-568-{\n--\nkernel/bpf/verifier.c=593=static void mark_sleepable_async_cb(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-604-\nkernel/bpf/verifier.c:605:bool bpf_is_may_goto_insn(struct bpf_insn *insn)\nkernel/bpf/verifier.c-606-{\n--\nkernel/bpf/verifier.c=1478=static int resize_reference_state(struct bpf_verifier_state *state, size_t n)\n--\nkernel/bpf/verifier.c-1491- */\nkernel/bpf/verifier.c:1492:int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)\nkernel/bpf/verifier.c-1493-{\n--\nkernel/bpf/verifier.c=1736=static void free_func_state(struct bpf_func_state *state)\n--\nkernel/bpf/verifier.c-1745-\nkernel/bpf/verifier.c:1746:void bpf_free_verifier_state(struct bpf_verifier_state *state,\nkernel/bpf/verifier.c-1747-\t\t\t bool free_self)\n--\nkernel/bpf/verifier.c=1763=static int copy_func_state(struct bpf_func_state *dst,\n--\nkernel/bpf/verifier.c-1775-\nkernel/bpf/verifier.c:1776:int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,\nkernel/bpf/verifier.c-1777-\t\t\t const struct bpf_verifier_state *src)\n--\nkernel/bpf/verifier.c=2003=static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)\n--\nkernel/bpf/verifier.c-2013-\nkernel/bpf/verifier.c:2014:void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)\nkernel/bpf/verifier.c-2015-{\n--\nkernel/bpf/verifier.c=2358=static int reg_bounds_sanity_check(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-2399-/* Mark a register as having a completely unknown (scalar) value. */\nkernel/bpf/verifier.c:2400:void bpf_mark_reg_unknown(struct bpf_reg_state *reg)\nkernel/bpf/verifier.c-2401-{\n--\nkernel/bpf/verifier.c=2415=static int __mark_reg_s32_range(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-2434-\nkernel/bpf/verifier.c:2435:void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-2436-\t\t\t struct bpf_reg_state *reg)\n--\nkernel/bpf/verifier.c=2543=struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)\n--\nkernel/bpf/verifier.c-2563-/* Find subprogram that starts exactly at 'off' */\nkernel/bpf/verifier.c:2564:int bpf_find_subprog(struct bpf_verifier_env *env, int off)\nkernel/bpf/verifier.c-2565-{\n--\nkernel/bpf/verifier.c=2694=find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)\n--\nkernel/bpf/verifier.c-2706-\nkernel/bpf/verifier.c:2707:int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,\nkernel/bpf/verifier.c-2708-\t\t u16 desc_idx, u8 **func_addr)\n--\nkernel/bpf/verifier.c=2801=static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-2850-\nkernel/bpf/verifier.c:2851:void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)\nkernel/bpf/verifier.c-2852-{\n--\nkernel/bpf/verifier.c=2991=static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-2993-\nkernel/bpf/verifier.c:2994:int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)\nkernel/bpf/verifier.c-2995-{\n--\nkernel/bpf/verifier.c=3581=const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)\n--\nkernel/bpf/verifier.c-3598-\nkernel/bpf/verifier.c:3599:void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)\nkernel/bpf/verifier.c-3600-{\n--\nkernel/bpf/verifier.c=6396=static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)\n--\nkernel/bpf/verifier.c-6465-\nkernel/bpf/verifier.c:6466:bool bpf_map_is_rdonly(const struct bpf_map *map)\nkernel/bpf/verifier.c-6467-{\n--\nkernel/bpf/verifier.c-6485-\nkernel/bpf/verifier.c:6486:int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,\nkernel/bpf/verifier.c-6487-\t\t\tbool is_ldsx)\n--\nkernel/bpf/verifier.c=10500=static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)\n--\nkernel/bpf/verifier.c-10532-\nkernel/bpf/verifier.c:10533:bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-10534-{\n--\nkernel/bpf/verifier.c=11725=static u32 fresh_id(struct bpf_verifier_env *env, struct bpf_idmap *idmap, u32 id)\n--\nkernel/bpf/verifier.c-11745- */\nkernel/bpf/verifier.c:11746:int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,\nkernel/bpf/verifier.c-11747-\t\t const struct bpf_verifier_state *exit, int call_idx)\n--\nkernel/bpf/verifier.c=12961=static bool can_elide_value_nullness(const struct bpf_map *map)\n--\nkernel/bpf/verifier.c-12974-\nkernel/bpf/verifier.c:12975:int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,\nkernel/bpf/verifier.c-12976-\t\t\t const struct bpf_func_proto **ptr)\n--\nkernel/bpf/verifier.c=14230=static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta)\n--\nkernel/bpf/verifier.c-14235-/* void * in the prototype. What it returns points to an object of the kernel. */\nkernel/bpf/verifier.c:14236:bool bpf_is_cast_kfunc(const struct bpf_call_arg_meta *meta)\nkernel/bpf/verifier.c-14237-{\n--\nkernel/bpf/verifier.c=14353=static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta)\n--\n\n"
} |
| 23/2 | 2026/11/14 14:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 115939 output: 36 thoughts: 50 Thoughts: Okay, let's dive into this code. **Investigating `check_cond_jmp_op` and `bpf_check`** My immediate concern is how `check_cond_jmp_op` is handled, and I need to remind myself – right, it's a static function within `verifier.c`. Next, what's the story with `bpf_check`? I need to find its definition. Where is that residing? That's the key question now. Let me locate it quickly. |
| 24/2 | 2026/11/14 14:40 | tool | grepper |
0mArgs:{
"Expression": "^int bpf_check\\(",
"PathPrefixes": [
"kernel/bpf/verifier.c"
]
}Results: {
"Output": "kernel/bpf/verifier.c=25125=static void log_program(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-25158-\nkernel/bpf/verifier.c:25159:int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\nkernel/bpf/verifier.c-25160-\t struct bpf_log_attr *attr_log)\n"
} |
| 25/2 | 2026/11/14 14:40 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 116278 output: 237 thoughts: 2233 Thoughts: **eBPF Verifier Focus for Enhanced Fuzzing**
Alright, let's break this down. My primary concern is ensuring we effectively fuzz the core changes introduced by this patch within the BPF verifier. `bpf_check` is the main entry point, the first place the verifier hits, so that's definitely on the radar. But, what about the new functions, or the ones significantly modified by this patch?
I'm starting by listing out the potentially relevant non-static functions directly touched by these changes: in `kernel/bpf/scev.c`, there's `bpf_compute_scev`, `bpf_scev_next_linked_reg`, `bpf_scev_mem_addr`, `bpf_scev_in_slice_slots`, `bpf_widen_scev_regs`, `bpf_clamp_scev_regs`, `bpf_half_slot_live_before`, and `bpf_clean_verifier_state`. There's also `bpf_is_dynptr_slice_rdwr_kfunc` in `kernel/bpf/verifier.c`. Also `bpf_state_subsumes`, `bpf_clean_verifier_state` in `kernel/bpf/states.c`.
A key consideration is static functions. Can they be targeted? The guidance says that compiler-inlined static functions in headers are a no-go for symbol coverage filters, as they lack distinct addresses. But static functions *within .c files* are still potentially in kallsyms and could be included. The key is to select non-static, *feature-specific* functions that exercise those static helpers.
So, let's hone in on the most relevant non-static functions within `kernel/bpf/scev.c` and `kernel/bpf/verifier.c`: `bpf_compute_scev` which is the core scalar evolution computation logic; `bpf_scev_next_linked_reg`, which is a new function; `bpf_scev_mem_addr` which is linked to memory address resolution; and `bpf_scev_in_slice_slots`, checking if dynptr slice buffer is in SCEV slice slots; `bpf_widen_scev_regs`, and `bpf_clamp_scev_regs`. Then `bpf_half_slot_live_before` from liveness.c; and `bpf_is_dynptr_slice_rdwr_kfunc` from `verifier.c`, `bpf_clean_verifier_state`, and `bpf_state_subsumes` from `states.c`. `bpf_check` is the main verifier entry point.
We should also check if the static functions `refine_linked_regs` and `check_cond_jmp_op` are not inlined. If they are not inlined, they are also candidates. But the non-static symbols are safer and more accurate targets.
The guidelines are pretty clear: target specific feature logic and entry points. This series significantly changes how the verifier works, so these are directly relevant and targeted. Non-static is ideal as they are guaranteed to have symbols.
Now, on to the configuration. `BPF_SYSCALL` seems like the essential config here, as it enables the `bpf()` syscall and, by extension, the verifier. It selects `BPF` which makes sense. The changes are in the verifier, not the JIT compiler, so `BPF_JIT` doesn't directly influence the choice. There aren't any architecture-specific `#ifdef`s in the relevant files, so that's simple. So, `BPF_SYSCALL` is all we really need.
Let's do a sanity check on all the instructions:
1. **Core Triage:** Reachability is assured through the standard `bpf(BPF_PROG_LOAD)` syscall on amd64 in QEMU/GCE. The patch fundamentally changes how the verifier works. It replaces dynamic scalar ID tracking with static SCEV, adds memory promotion, and modifies register bounds, and slice slots, so it is definitely worth fuzzing.
2. **EnableConfigs:** `["BPF_SYSCALL"]`
3. **FocusSymbols:**
* `bpf_compute_scev`
* `bpf_scev_next_linked_reg`
* `bpf_scev_mem_addr`
* `bpf_scev_in_slice_slots`
* `bpf_widen_scev_regs`
*
|
| 26/2 | 2026/11/14 14:41 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"BPF_SYSCALL"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_scev_next_linked_reg",
"bpf_scev_mem_addr",
"bpf_scev_in_slice_slots",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_half_slot_live_before",
"bpf_clean_verifier_state"
],
"Reasoning": "This patch series significantly revamps linked scalar tracking in the BPF verifier. Dynamic scalar ID and delta tracking across verification states are replaced with static scalar evolution (SCEV) analysis, global value numbering, phi-node expressions, and memory register promotion. Conditional jump operations now query SCEV linked registers to refine bounds. These modifications affect core BPF verifier correctness and state equivalence, which are directly reachable from userspace via the bpf() system call and represent high-value fuzzing targets.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"BPF_SYSCALL"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_scev_next_linked_reg",
"bpf_scev_mem_addr",
"bpf_scev_in_slice_slots",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_half_slot_live_before",
"bpf_clean_verifier_state"
],
"Reasoning": "This patch series significantly revamps linked scalar tracking in the BPF verifier. Dynamic scalar ID and delta tracking across verification states are replaced with static scalar evolution (SCEV) analysis, global value numbering, phi-node expressions, and memory register promotion. Conditional jump operations now query SCEV linked registers to refine bounds. These modifications affect core BPF verifier correctness and state equivalence, which are directly reachable from userspace via the bpf() system call and represent high-value fuzzing targets.",
"WorthFuzzing": true
} |
| 27/1 | 2026/11/14 14:41 | action | If |
5mArgs:{
"WorthFuzzing": true
}Results: null |
| 28/2 | 2026/11/14 14:41 | agent | kmsan-evaluator |
5mModel:core Args: null Results: {
"KMSANReasoning": "The patch series updates the BPF verifier to replace dynamic scalar register ID tracking with static Scalar Evolution (SCEV) analysis for linked registers, improving induction variable handling, 32-bit sign extension bounds tracking, and state equivalence comparisons.\n\nKMSAN vs KASAN Applicability Analysis:\n1. No uninitialized memory exposure to user space: The changes do not introduce or modify any kernel data structures copied to user space (no copy_to_user, put_user, netlink skb attributes, or BPF ringbuf/array copy-outs).\n2. Proper initialization: All heap and stack structures added or modified in the patch (such as `struct scev`, `struct env`, `struct scev_linked_reg`, and resized arrays in `grow_exprs`) use `kzalloc`, `__GFP_ZERO`, or explicit full-field initialization before reading. The replacement of `s32 delta` with `u32 unused` in `struct bpf_reg_state` preserves the existing struct layout and padding without introducing uninitialized holes.\n3. Bug profiles: Any bugs introduced by this patch would manifest as incorrect register range / bounds inferences, loop latch count mismatches, or state pruning errors in the verifier. Such bugs can lead to out-of-bounds memory accesses or invalid pointer dereferences at BPF runtime, which are already detected by KASAN and standard kernel debuggers.\n\nBecause there are no uninitialized memory read risks or information leaks uniquely targetable by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 5688cd04d3b41e9f2094dd2a002289802a0f9401
Author: syz-cluster <triage@syzkaller.com>
Date: Sat Nov 14 14:38:24 2026 +0000
syz-cluster: applied patch under review
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 4771c55d8f41f6..598763d128ab8c 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -60,10 +60,8 @@ struct bpf_stack_range {
struct bpf_reg_state {
/* Ordering of fields matters. See regsafe() */
enum bpf_reg_type type;
- /*
- * Constant delta between "linked" scalars with the same ID.
- */
- s32 delta;
+ /* 0. regsafe() compares the bytes before var_off: there is no hole among them. */
+ u32 unused;
union {
/* valid when type == PTR_TO_PACKET */
int range;
@@ -179,18 +177,9 @@ struct bpf_reg_state {
* the dynptr to determine proper reference freeing.
* Similarly to dynptrs, we use ID to track "belonging" of a reference
* to a specific instance of bpf_iter.
+ * A scalar has no id. The scalars that it is linked to are static: computed before the
+ * main pass, see bpf_scev_next_linked_reg().
*/
- /*
- * Upper bit of ID is used to remember relationship between "linked"
- * registers. Example:
- * r1 = r2; both will have r1->id == r2->id == N
- * r1 += 10; r1->id == N | BPF_ADD_CONST and r1->delta == 10
- * r3 = r2; both will have r3->id == r2->id == N
- * w3 += 10; r3->id == N | BPF_ADD_CONST32 and r3->delta == 10
- */
-#define BPF_ADD_CONST64 (1U << 31)
-#define BPF_ADD_CONST32 (1U << 30)
-#define BPF_ADD_CONST (BPF_ADD_CONST64 | BPF_ADD_CONST32)
u32 id;
/*
* Tracks the parent object this register was derived from.
@@ -1112,27 +1101,18 @@ struct bpf_id_pair {
* comes out for it, only if the same places have the same names.
* - bpf_flow_return() puts the ids of the call that waits back. All other ids get new values.
* - What comes out has the ranges of all calls that share the state at the entry. So a name is good
- * for what holds whatever the ranges are: the same object. Other ids have no name: a number
- * loses its id, any other argument keeps the frames of the caller, see arg_needs_caller().
- * - env->id_gen stays below BPF_MAX_ID. So no id is a name or has a bit of BPF_ADD_CONST.
+ * for what holds whatever the ranges are: the same object. Other ids have no name: such an
+ * argument keeps the frames of the caller, see arg_needs_caller().
+ * - env->id_gen stays below BPF_MAX_ID. So no id is a name.
*/
#define BPF_INHERITED_ID 0x20000000
#define BPF_MAX_ID (BPF_INHERITED_ID / 2)
struct bpf_idmap {
- u32 tmp_id_gen;
u32 cnt;
struct bpf_id_pair map[BPF_ID_MAP_SIZE];
};
-struct bpf_idset {
- u32 num_ids;
- struct {
- u32 id;
- u32 cnt;
- } entries[BPF_ID_MAP_SIZE];
-};
-
struct bpf_liveness;
struct scev;
@@ -1278,10 +1258,7 @@ struct bpf_verifier_env {
* via callx. Allocated when the first such edge is recorded.
*/
unsigned long *callx_edges;
- union {
- struct bpf_idmap idmap_scratch;
- struct bpf_idset idset_scratch;
- };
+ struct bpf_idmap idmap_scratch;
struct {
int *insn_state;
int *insn_stack;
@@ -1447,12 +1424,6 @@ void bpf_verbose_snum32(struct bpf_verifier_env *env, s32 num);
bpf_log(&env->log, "verifier bug: " fmt "\n", ##args); \
})
-static inline void clear_scalar_id(struct bpf_reg_state *reg)
-{
- reg->id = 0;
- reg->delta = 0;
-}
-
static inline void mark_calls_callback(struct bpf_verifier_env *env, int idx)
{
env->insn_aux_data[idx].calls_callback = true;
@@ -1589,7 +1560,6 @@ void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);
void bpf_mark_reg_unknown(struct bpf_reg_state *reg);
int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size);
-void bpf_clear_singular_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
static inline int bpf_get_spi(s32 off)
{
@@ -1902,6 +1872,7 @@ u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);
int bpf_find_subprog(struct bpf_verifier_env *env, int off);
bool bpf_is_throw_kfunc(struct bpf_insn *insn);
+bool bpf_is_dynptr_slice_rdwr_kfunc(struct bpf_insn *insn);
int bpf_compute_const_regs(struct bpf_verifier_env *env);
int bpf_prune_dead_branches(struct bpf_verifier_env *env);
int bpf_check_cfg(struct bpf_verifier_env *env);
@@ -2078,6 +2049,7 @@ int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_
const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);
bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);
bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);
+bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi);
int bpf_compute_live_registers(struct bpf_verifier_env *env);
#define BPF_MAP_KEY_POISON (1ULL << 63)
@@ -2224,6 +2196,13 @@ int bpf_init_scev(struct bpf_verifier_env *env);
void bpf_free_scev(struct bpf_verifier_env *env);
int bpf_compute_scev(struct bpf_verifier_env *env);
int bpf_scev_jump_counts(struct bpf_verifier_env *env, int header, int n, bool taken_leaves);
+bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,
+ u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,
+ u32 *bits);
+bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,
+ s64 *off);
+bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg);
+bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off);
int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
struct bpf_loop_iters *iters);
diff --git a/kernel/bpf/flow.c b/kernel/bpf/flow.c
index c9458b3ad114a5..abbadba1e79f61 100644
--- a/kernel/bpf/flow.c
+++ b/kernel/bpf/flow.c
@@ -2603,10 +2603,9 @@ static bool flow_join_makes_up(const struct bpf_flow *flow, struct bpf_verifier_
struct bpf_verifier_state *b)
{
struct bpf_func_state *fa = a->frame[a->curframe], *fb = b->frame[b->curframe];
- const struct bpf_reg_state *ra, *rb;
+ const struct bpf_reg_state *ra, *rb, *one_a = NULL, *one_b = NULL;
const struct flow_need *tested = flow->need[FLOW_NEED_JUMP], *need;
- u32 fr, i, id = 0;
- bool one = false;
+ u32 fr, i, len = offsetof(struct bpf_reg_state, id);
if (!tested)
return false;
@@ -2623,11 +2622,11 @@ static bool flow_join_makes_up(const struct bpf_flow *flow, struct bpf_verifier_
continue;
if (flow_gap(ra, rb))
return true;
- /* copies of a number are one number */
- if (one && (!id || id != (ra->id & ~BPF_ADD_CONST)))
+ /* copies of a scalar count once: same range and tnum in each state */
+ if (one_a && (memcmp(ra, one_a, len) || memcmp(rb, one_b, len)))
return true;
- one = true;
- id = ra->id & ~BPF_ADD_CONST;
+ one_a = ra;
+ one_b = rb;
}
}
if (!flow_needed_consts_differ(flow, FLOW_NEED_FLAG, a, b))
@@ -2925,8 +2924,6 @@ static struct flow_state *flow_arrive(struct bpf_verifier_env *env, struct bpf_v
flow_free_state(env, s);
return ERR_PTR(err);
}
- /* when the registers that it was shared with are dead, or are those of the caller */
- bpf_clear_singular_ids(env, &s->st);
return s;
}
diff --git a/kernel/bpf/join.c b/kernel/bpf/join.c
index cc4494aef18733..2b8c94b7dc5027 100644
--- a/kernel/bpf/join.c
+++ b/kernel/bpf/join.c
@@ -75,18 +75,16 @@ static void jid_mark_bad(struct bpf_join_state *js, u32 a, u32 b)
js->pairs[i].bad = true;
}
-static void jid_note(struct bpf_join_state *js, u32 ida, u32 idb, bool consistent)
+static void jid_note(struct bpf_join_state *js, u32 a, u32 b)
{
- u32 a = ida & ~BPF_ADD_CONST, b = idb & ~BPF_ADD_CONST;
+ bool consistent, other = false;
struct join_idpair *p;
- bool other = false;
u32 i;
if (!a || !b)
return;
/* a name of what the caller has, see BPF_INHERITED_ID */
- if (a != b && (a | b) >= BPF_INHERITED_ID)
- consistent = false;
+ consistent = a == b || (a | b) < BPF_INHERITED_ID;
for (i = 0; i < js->npairs; i++) {
p = &js->pairs[i];
if (p->a == a && p->b == b) {
@@ -111,15 +109,12 @@ static void jid_note(struct bpf_join_state *js, u32 ida, u32 idb, bool consisten
p->bad = !consistent;
}
-static bool jid_good(struct bpf_join_state *js, u32 ida, u32 idb)
+static bool jid_good(struct bpf_join_state *js, u32 a, u32 b)
{
- u32 a = ida & ~BPF_ADD_CONST, b = idb & ~BPF_ADD_CONST;
u32 i;
if (!a || !b || js->pairs_overflow)
return false;
- if ((ida ^ idb) & BPF_ADD_CONST)
- return false;
for (i = 0; i < js->npairs; i++)
if (js->pairs[i].a == a && js->pairs[i].b == b)
return !js->pairs[i].bad;
@@ -199,15 +194,6 @@ static bool reg_value_equal(const struct bpf_reg_state *ra, const struct bpf_reg
return !memcmp(ra, rb, offsetof(struct bpf_reg_state, id));
}
-static bool scalar_link_consistent(const struct bpf_reg_state *ra, const struct bpf_reg_state *rb)
-{
- if ((ra->id ^ rb->id) & BPF_ADD_CONST)
- return false;
- if ((ra->id & BPF_ADD_CONST) && ra->delta != rb->delta)
- return false;
- return true;
-}
-
/*
* Join two registers, regsafe() documents what each type needs.
* Pass 1 records id pairs, pass 2 computes @dst, which is a copy of @ra on entry.
@@ -229,16 +215,8 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,
case SCALAR_VALUE:
if (js->env->explore_alu_limits && !reg_value_equal(ra, rb))
return false;
- if (pass == 1) {
- jid_note(js, ra->id, rb->id, scalar_link_consistent(ra, rb));
- return true;
- }
- join_range(js, dst, ra, rb);
- /* a link that exists on one side only is dropped */
- if (ra->id && !jid_good(js, ra->id, rb->id)) {
- dst->id = 0;
- dst->delta = 0;
- }
+ if (pass == 2)
+ join_range(js, dst, ra, rb);
return true;
case PTR_TO_MAP_KEY:
case PTR_TO_MAP_VALUE:
@@ -269,7 +247,7 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,
if (ra->r64.base != rb->r64.base)
return false;
if (pass == 1) {
- jid_note(js, ra->id, rb->id, true);
+ jid_note(js, ra->id, rb->id);
return true;
}
if (!jid_strict_ok(js, ra->id, rb->id))
@@ -291,9 +269,9 @@ static bool join_reg(struct bpf_join_state *js, struct bpf_reg_state *dst,
}
if (pass == 1) {
- jid_note(js, ra->id, rb->id, true);
- jid_note(js, ra->parent_id, rb->parent_id, true);
- jid_note(js, ra->map_uid, rb->map_uid, true);
+ jid_note(js, ra->id, rb->id);
+ jid_note(js, ra->parent_id, rb->parent_id);
+ jid_note(js, ra->map_uid, rb->map_uid);
return true;
}
if (!jid_strict_ok(js, ra->id, rb->id) ||
@@ -350,8 +328,8 @@ static bool join_special_slot(struct bpf_join_state *js, const struct bpf_stack_
break;
}
if (pass == 1) {
- jid_note(js, ra->id, rb->id, true);
- jid_note(js, ra->parent_id, rb->parent_id, true);
+ jid_note(js, ra->id, rb->id);
+ jid_note(js, ra->parent_id, rb->parent_id);
return true;
}
return jid_strict_ok(js, ra->id, rb->id) &&
@@ -563,12 +541,12 @@ static void join_refs_note(struct bpf_join_state *js, const struct bpf_verifier_
{
int i;
- jid_note(js, a->active_irq_id, b->active_irq_id, true);
- jid_note(js, a->active_lock_id, b->active_lock_id, true);
+ jid_note(js, a->active_irq_id, b->active_irq_id);
+ jid_note(js, a->active_lock_id, b->active_lock_id);
for (i = 0; i < a->acquired_refs; i++) {
- jid_note(js, a->refs[i].id, b->refs[i].id, true);
+ jid_note(js, a->refs[i].id, b->refs[i].id);
if (a->refs[i].type == REF_TYPE_PTR)
- jid_note(js, a->refs[i].parent_id, b->refs[i].parent_id, true);
+ jid_note(js, a->refs[i].parent_id, b->refs[i].parent_id);
}
}
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index e930d928afa5b4..63d23d28f2a5c4 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -760,6 +760,19 @@ static void compute_may_write_masks(struct bpf_verifier_env *env)
}
}
+/* live_stack_before of the insn at @insn_idx for one half-slot */
+bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi)
+{
+ struct func_instance *instance;
+ int bkt;
+
+ hash_for_each(env->liveness->func_instances, bkt, instance, hl_node)
+ if (insn_idx - instance->subprog_start < instance->insn_cnt &&
+ is_live_before(instance, insn_idx, instance->depth, half_spi))
+ return true;
+ return false;
+}
+
const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)
{
return env->insn_aux_data[insn_idx].may_write_mask;
@@ -1398,8 +1411,10 @@ static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf
return fill_from_stack(insn, at_out, reg, parent->at, parent->slots, ptr->frame);
}
+ /* A frame holds pointers to its own stack and to the stacks of its callers */
if (ptr->frame == ARG_IMPRECISE && !(ptr->mask & BIT(depth)) && ptr->mask)
- return *ptr;
+ return (struct arg_track){ .mask = GENMASK(fls(ptr->mask) - 1, 0),
+ .frame = ARG_IMPRECISE };
return (struct arg_track){ .frame = ARG_NONE };
}
diff --git a/kernel/bpf/log.c b/kernel/bpf/log.c
index 84659a757b43ca..ffbec587a9166e 100644
--- a/kernel/bpf/log.c
+++ b/kernel/bpf/log.c
@@ -696,7 +696,7 @@ static void print_reg_state(struct bpf_verifier_env *env,
if (state->frameno != reg->frameno)
verbose(env, "[%d]", reg->frameno);
if (tnum_is_const(reg->var_off)) {
- bpf_verbose_snum(env, reg->var_off.value + reg->delta);
+ bpf_verbose_snum(env, reg->var_off.value);
return;
}
}
@@ -704,9 +704,7 @@ static void print_reg_state(struct bpf_verifier_env *env,
verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
verbose(env, "(");
if (reg->id)
- verbose_a("id=%d", reg->id & ~BPF_ADD_CONST);
- if (reg->id & BPF_ADD_CONST)
- verbose(env, "%+d", reg->delta);
+ verbose_a("id=%d", reg->id);
if (reg->parent_id)
verbose_a("parent_id=%d", reg->parent_id);
if (type_is_non_owning_ref(reg->type))
@@ -720,10 +718,6 @@ static void print_reg_state(struct bpf_verifier_env *env,
reg->map_ptr->key_size,
reg->map_ptr->value_size);
}
- if (t != SCALAR_VALUE && reg->delta) {
- verbose_a("off=");
- bpf_verbose_snum(env, reg->delta);
- }
if (type_is_pkt_pointer(t)) {
verbose_a("r=");
verbose_unum(env, reg->range);
diff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c
index 4187ce955be991..e36181a0085852 100644
--- a/kernel/bpf/scev.c
+++ b/kernel/bpf/scev.c
@@ -12,8 +12,13 @@
#include <linux/overflow.h>
#define REGS_NUM BPF_SCEV_REGS_NUM
+/* The SCEV registers of an env: r0 - r10, the stack slots and memory locations, see struct env */
+#define MEM_REGS_NUM 16
+#define ENV_REGS_NUM (REGS_NUM + MEM_REGS_NUM)
#define UNKNOWN_EXPR_ID 0
#define OPAQUE_EXPR_ID 1
+/* (REG r). UNKNOWN, OPAQUE and (REG r) have fixed ids and are not in the hash table. */
+#define REG_EXPR_ID(r) (2 + (r))
/*
* BPF instructions use 'code', 'src_reg', 'off' and 'imm' fields for instruction encoding.
@@ -44,34 +49,100 @@ enum expr_op {
*/
LINEAR_SCEV,
/*
- * param[1], given that register param[0] and the register that param[1] starts from are
- * equal when the loop is entered. Not known otherwise.
+ * (add rB rC) is the SCEV of rA: rA == rB + rC at the header in every iteration. rB and rC
+ * are the header phis here, not the entry values as below LINEAR_SCEV.
*/
- COPY_SCEV,
+ ADD_SCEV,
};
+/*
+ * An SSA name for a value that no expression describes: the def of the SCEV register 'reg'
+ * - by the insn at 'idx'. An insn that may write defines too (may_def in liveness.c). A nested loop
+ * defines at its header what it leaves.
+ * - by a phi before the insn at 'idx': a join point, a loop header.
+ * Without its backedges and with nested loops collapsed the body of a loop is acyclic: an insn
+ * executes at most once per iteration, so a def is one value per iteration. A name is unique within
+ * the env of one loop.
+ * The operands of a phi are a set, 8 at most; a phi(a, b) among them is expanded. They have no
+ * defs, see strip_defs(): (+ r6 %r2.4) and (+ r6 %r2.7) are one operand, (+ r6 _). So they don't
+ * tell one phi from another: phis are value numbered by their bases, see mk_phi().
+ * In the env of loop H a phi at H merges the backedge values only, the header phi itself is
+ * (REG r). In the env of the enclosing loop a phi at H merges the entering edges.
+ * Op and params of a def by an insn are what that insn computes, see alu64_with_def():
+ * set_expr_base() and match_linked_add() look through such an add, split_const_offset() and
+ * match_linked_add() check prevent_zext of the insn. Those of a phi are the shape that its operands
+ * share, no insn computes them: nothing looks through a phi.
+ */
+struct expr_def {
+ u32 set:1; /* 0: the expression has no def */
+ u32 phi:1;
+ u32 reg:9;
+ u32 idx:21;
+};
+/* def.reg of the phi of two bases, see mk_phi() */
+#define BASE_REG ENV_REGS_NUM
+static_assert(BASE_REG < 1 << 9 && BPF_COMPLEXITY_LIMIT_INSNS <= 1 << 21);
+
+static const struct expr_def no_def;
+
struct expr {
- u32 op;
+ u16 op;
+ /* A value number: all SCEV registers of an env that have this id hold the same value */
+ bool is_vn;
+ /* expr == base + off (mod 2^bits), see split_const_offset() */
+ u8 bits;
+ /*
+ * UNKNOWN, OPAQUE and ANY don't describe a value. With a def the id stands for one value,
+ * see struct expr_def. Without a def every use of the id can be another value.
+ */
+ struct expr_def def;
union {
u32 params[2];
s64 imm;
};
-};
-
-struct expr_bucket {
- u32 cnt;
- u32 cap;
- u32 ids[];
+ u32 base;
+ /*
+ * id of the first add on the way to 'base' whose insn may still become ALU32, see
+ * prevent_zext. 0: none
+ */
+ u32 arena_add;
+ s64 off;
};
struct env {
bool empty;
- u32 reg2expr[REGS_NUM];
+ u32 reg2expr[ENV_REGS_NUM];
u32 reg2scev[REGS_NUM];
+ /*
+ * Register promotion of memory that is not behind r10. The SCEV register REGS_NUM + i is
+ * the memory at the address mem_addr[i], a value number of this env. 0: not in use.
+ * - A store through a pointer defines it like a spill defines a stack slot.
+ * - A load defines its register as before, and the memory gets that value number: it holds
+ * what a store of the register would leave. No expression of a register depends on
+ * memory, which is private only if it is stack. That is not known here.
+ * - A join point has a phi. An insn that may write is a may-def, see forget_mem_regs().
+ * - A store through r10 is not: the main pass takes the stack of a caller only.
+ * A value number of a loop means nothing in the enclosing loop: no memory is tracked at
+ * a header, a nested loop is a may-def.
+ */
+ u32 mem_addr[MEM_REGS_NUM];
+};
+
+/*
+ * A SCEV register and the id of its expression before a conditional jump. 'addr' is mem_addr[] of
+ * a memory location.
+ */
+struct scev_linked_reg {
+ u32 reg;
+ u32 id;
+ u32 addr;
};
struct insn_envs {
u32 cnt;
+ /* The linked registers of a jump, see find_linked_regs(): linked_cnt of scev->linked[] */
+ u32 linked_first;
+ u32 linked_cnt;
struct {
int loop_header;
struct env *env;
@@ -92,87 +163,216 @@ struct scev {
/* Read-only representatives for stack slots without a saved register. */
struct bpf_reg_state zero_reg;
struct bpf_reg_state unknown_reg;
+ /* r -> (REG r): before the first insn of a loop every SCEV register is its header phi */
+ struct env identity_env;
/*
* Expressions are identified by id, exprs_ht ensures that
* each expression exists as a unique instance.
* This allows for fast equivalence check: id1 === id2.
+ * exprs_ht[hash] is the first id of a chain, exprs_next[id] is the next one, 0 ends it.
+ * Both have exprs_cap elements, like exprs[].
*/
- struct expr_bucket **exprs_ht;
+ u32 *exprs_ht;
+ u32 *exprs_next;
struct scev_worklist worklist;
struct insn_envs **envs;
struct expr *exprs;
+ struct scev_linked_reg *linked;
+ /* The stack slots that a store through a dynptr slice may alias, see expr_is_vn() */
+ DECLARE_BITMAP(slice_slots, MAX_BPF_STACK_SLOTS);
/*
* Loops are analyzed one by one, this array keeps track if a particular
* instruction was visited on a current pass.
*/
u32 *discovered;
- u32 exprs_ht_cnt;
int exprs_cnt;
int exprs_cap;
+ u32 linked_cnt;
+ u32 linked_cap;
int envs_cnt;
int stack_sz;
+ int simplify_depth;
struct expr_stack_elt expr_stack[EXPR_STACK_DEPTH];
u32 ids_buf[EXPR_STACK_DEPTH];
};
static u32 expr_hash(struct expr *e)
{
- return jhash_3words(e->op, e->params[0], e->params[1], 0);
+ /* def.phi is not hashed: the def by an insn and the phi before it share a chain */
+ return jhash_3words(e->op, e->params[0], e->params[1],
+ e->def.idx * REGS_NUM + e->def.reg);
}
-static int expr_eq(struct expr *a, struct expr *b)
+static bool same_def(struct expr_def a, struct expr_def b)
{
- return a->op == b->op && a->imm == b->imm;
+ return a.set == b.set && a.phi == b.phi && a.reg == b.reg && a.idx == b.idx;
}
-static int add_expr(struct scev *scev, struct expr e)
+/* Is @e the expression @id? The base of a phi is a part of its key. 0: the phi is its own base. */
+static int expr_eq(struct scev *scev, struct expr *e, u32 id)
+{
+ struct expr *x = &scev->exprs[id];
+
+ if (e->op != x->op || e->imm != x->imm || !same_def(e->def, x->def))
+ return false;
+ if (!e->def.phi)
+ return true;
+ return e->base ? e->base == x->base && e->off == x->off : x->base == id;
+}
+
+static void exprs_ht_add(struct scev *scev, u32 id)
+{
+ u32 *bucket = &scev->exprs_ht[expr_hash(&scev->exprs[id]) & (scev->exprs_cap - 1)];
+
+ scev->exprs_next[id] = *bucket;
+ *bucket = id;
+}
+
+/* @cap is a power of two. No warning for a size that kvmalloc() rejects. */
+static int grow_exprs(struct scev *scev, u32 cap)
{
- struct expr_bucket *bucket;
- u32 i, id, hash, new_cap;
+ gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_NOWARN;
void *tmp;
+ u32 id;
- hash = expr_hash(&e) & (scev->exprs_ht_cnt - 1);
- bucket = scev->exprs_ht[hash];
+ tmp = kvrealloc(scev->exprs, array_size(cap, sizeof(*scev->exprs)), gfp);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs = tmp;
+ tmp = kvrealloc(scev->exprs_next, array_size(cap, sizeof(u32)), gfp);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs_next = tmp;
+ tmp = kvrealloc(scev->exprs_ht, array_size(cap, sizeof(u32)), gfp);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs_ht = tmp;
+ scev->exprs_cap = cap;
+ memset(scev->exprs_ht, 0, array_size(cap, sizeof(u32)));
+ for (id = REG_EXPR_ID(REGS_NUM); id < scev->exprs_cnt; id++)
+ exprs_ht_add(scev, id);
+ return 0;
+}
- if (bucket) {
- for (i = 0; i < bucket->cnt; i++) {
- id = bucket->ids[i];
- if (expr_eq(&e, &scev->exprs[id]))
- return id;
- }
- }
+static u32 op_params_num(u32 op);
- if (!bucket || bucket->cap == bucket->cnt) {
- new_cap = bucket ? bucket->cap * 2 : 4;
- bucket = kvrealloc(bucket, sizeof(*bucket) + sizeof(u32) * new_cap, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
- if (!bucket)
- return -ENOMEM;
- scev->exprs_ht[hash] = bucket;
- bucket->cap = new_cap;
- }
+static bool expr_is_vn(struct scev *scev, struct expr *e)
+{
+ u32 i, reg = e->def.reg;
- if (scev->exprs_cnt == scev->exprs_cap) {
- new_cap = scev->exprs_cap ? scev->exprs_cap * 2 : 256;
- tmp = kvrealloc(scev->exprs, sizeof(struct expr) * new_cap, GFP_KERNEL_ACCOUNT);
- if (!tmp)
- return -ENOMEM;
- scev->exprs = tmp;
- scev->exprs_cap = new_cap;
+ /*
+ * bpf_dynptr_slice_rdwr() can return the buffer that it got. A store through that slice may
+ * alias the slots of the buffer and is in no bpf_may_write_mask(): it is no def, so a def
+ * of such a slot is no value number. A spill through r10 has the expression of the
+ * register, and invalidate_stack_slices() invalidates the slices there. The next slice
+ * comes from a call that may write to the slot.
+ */
+ if (e->def.set)
+ return reg < MAX_BPF_REG || reg >= REGS_NUM ||
+ !test_bit(reg - MAX_BPF_REG, scev->slice_slots);
+ switch (e->op) {
+ case UNKNOWN:
+ case OPAQUE:
+ case ANY:
+ /* a partial spill: the other bits of the slot are not known */
+ case SPILL8:
+ case SPILL16:
+ case SPILL32:
+ /* a function of the iteration number */
+ case LINEAR_SCEV:
+ /* a relation between header phis */
+ case ADD_SCEV:
+ return false;
}
+ for (i = 0; i < op_params_num(e->op); i++)
+ if (!scev->exprs[e->params[i]].is_vn)
+ return false;
+ return true;
+}
+
+static u32 op_low_bits(u32 op);
+
+/*
+ * @e gets the id @id. (+ x imm), an extension and a partial spill of x have the base of x, which
+ * was constructed earlier. Every other expression is its own base. So split_const_offset() does not
+ * traverse the expression.
+ */
+static void set_expr_base(struct scev *scev, struct expr *e, u32 id)
+{
+ u32 low = op_low_bits(e->op);
+ struct expr *x;
+ s64 imm = 0;
+
+ e->arena_add = 0;
+ /* mk_phi() found the base */
+ if (e->def.phi && e->base)
+ return;
+ e->base = id;
+ e->off = 0;
+ e->bits = 64;
+ /* nothing looks through a phi, see struct expr_def */
+ if (e->def.phi)
+ return;
+ if (e->op == BPF_ADD && scev->exprs[e->params[1]].op == IMM)
+ imm = scev->exprs[e->params[1]].imm;
+ else if (!low || e->def.set)
+ return;
+ x = &scev->exprs[e->params[0]];
+ e->base = x->base;
+ e->off = (u64)x->off + imm;
+ e->bits = low ? min(x->bits, low) : x->bits;
+ e->arena_add = e->def.set ? id : x->arena_add;
+}
+
+static int add_expr(struct scev *scev, struct expr e)
+{
+ u32 id;
+
+ if (e.op == REG)
+ return REG_EXPR_ID(e.params[0]);
+ if (!e.def.set && !e.imm && (e.op == UNKNOWN || e.op == OPAQUE))
+ return e.op == UNKNOWN ? UNKNOWN_EXPR_ID : OPAQUE_EXPR_ID;
+
+ id = scev->exprs_ht[expr_hash(&e) & (scev->exprs_cap - 1)];
+ for (; id; id = scev->exprs_next[id])
+ if (expr_eq(scev, &e, id))
+ return id;
+
+ if (scev->exprs_cnt == scev->exprs_cap && grow_exprs(scev, scev->exprs_cap * 2))
+ return -ENOMEM;
id = scev->exprs_cnt++;
+ e.is_vn = expr_is_vn(scev, &e);
+ set_expr_base(scev, &e, id);
scev->exprs[id] = e;
- bucket->ids[bucket->cnt++] = id;
+ exprs_ht_add(scev, id);
return id;
}
+static int simplify(struct scev *scev, u32 id);
+
+/*
+ * An expression is simplified at construction. Its params are simplified already, so simplify()
+ * rewrites the root only, whatever the depth of the expression.
+ * The rules construct expressions too, and one rule can enable the next: the depth of (zext32
+ * (spill32 (+ (spill32 (+ ..) 1)) 1)) is up to the prog. Beyond depth EXPR_STACK_DEPTH an
+ * expression is correct, but not simplified.
+ */
static int expr2(struct scev *scev, u32 op, int a, int b)
{
+ int id;
+
if (a < 0)
return a;
if (b < 0)
return b;
- return add_expr(scev, (struct expr){ .op = op, .params = {a, b} });
+ id = add_expr(scev, (struct expr){ .op = op, .params = {a, b} });
+ if (id < 0 || scev->simplify_depth == EXPR_STACK_DEPTH)
+ return id;
+ scev->simplify_depth++;
+ id = simplify(scev, id);
+ scev->simplify_depth--;
+ return id;
}
static int expr1(struct scev *scev, u32 op, int a)
@@ -182,14 +382,38 @@ static int expr1(struct scev *scev, u32 op, int a)
return expr2(scev, op, a, 0);
}
-static int expr0(struct scev *scev, u32 op)
+static int imm_expr(struct scev *scev, s64 value)
{
- return expr2(scev, op, 0, 0);
+ return add_expr(scev, (struct expr){ .op = IMM, .imm = value });
}
-static int imm_expr(struct scev *scev, s64 value)
+/*
+ * The insn at @idx defines @reg. Without its backedges and with nested loops collapsed the body is
+ * acyclic: an insn executes at most once per iteration, so a def is one value per iteration. A
+ * subprog is the outermost loop, which runs once.
+ */
+static struct expr_def insn_def(int idx, u32 reg)
{
- return add_expr(scev, (struct expr){ .op = IMM, .imm = value });
+ return (struct expr_def){ .set = 1, .reg = reg, .idx = idx };
+}
+
+/* The phi of @reg before the insn at @idx. One value per iteration for the same reason. */
+static struct expr_def phi_def(int idx, u32 reg)
+{
+ return (struct expr_def){ .set = 1, .phi = 1, .reg = reg, .idx = idx };
+}
+
+/* @id with another def */
+static int expr_with_def(struct scev *scev, int id, struct expr_def def)
+{
+ struct expr e;
+
+ if (id < 0)
+ return id;
+ e = scev->exprs[id];
+ e.def = def;
+ e.base = 0;
+ return add_expr(scev, e);
}
static bool same_exprs(struct scev *scev, int id_a, int id_b)
@@ -244,31 +468,74 @@ static bool is_zext32(struct scev *scev, int id, u32 *left)
return is_unop(scev, ZEXT32, id, left);
}
-/* The low half of the slot is the low half of @left. The other half is not known. */
-static bool is_spill32(struct scev *scev, int id, u32 *left)
+/* (zextN x), (sextN x) and (spillN x) depend on the low N bits of x only */
+static u32 op_low_bits(u32 op)
+{
+ switch (op) {
+ case ZEXT8:
+ case SEXT8:
+ case SPILL8:
+ return 8;
+ case ZEXT16:
+ case SEXT16:
+ case SPILL16:
+ return 16;
+ case ZEXT32:
+ case SEXT32:
+ case SPILL32:
+ return 32;
+ }
+ return 0;
+}
+
+/* The low @bits bits of the slot are those of @left. The other bits are not known. */
+static bool is_spill(struct scev *scev, int id, u32 *bits, u32 *left)
{
+ u32 op = scev->exprs[id].op;
+
#ifdef __BIG_ENDIAN
/* '*(u32 *)(r10 - 8) = rX' writes the high half, see mk_fill() */
return false;
#endif
- return is_unop(scev, SPILL32, id, left);
+ if (op != SPILL8 && op != SPILL16 && op != SPILL32)
+ return false;
+ *bits = op_low_bits(op);
+ *left = scev->exprs[id].params[0];
+ return true;
}
-static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)
+static bool is_spill32(struct scev *scev, int id, u32 *left)
{
- return is_binop(scev, ANY, id, left, right);
+ u32 bits;
+
+ return is_spill(scev, id, &bits, left) && bits == 32;
}
-static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)
+/* (zextN x), (sextN x) or (spillN x) with N >= @bits: the low @bits bits are those of @left */
+static bool is_low_bits(struct scev *scev, int id, u32 bits, u32 *left)
{
- return is_binop(scev, LINEAR_SCEV, id, base, slope);
+ u32 op = scev->exprs[id].op;
+
+#ifdef __BIG_ENDIAN
+ /* see is_spill() */
+ if (op == SPILL8 || op == SPILL16 || op == SPILL32)
+ return false;
+#endif
+ /* nothing looks through a phi, see struct expr_def */
+ if (op_low_bits(op) < bits || scev->exprs[id].def.phi)
+ return false;
+ *left = scev->exprs[id].params[0];
+ return true;
}
-static bool is_copy(struct scev *scev, int id, u32 *reg, u32 *orig)
+static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)
{
- u32 t;
+ return is_binop(scev, ANY, id, left, right);
+}
- return is_binop(scev, COPY_SCEV, id, &t, orig) && is_reg(scev, t, reg);
+static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)
+{
+ return is_binop(scev, LINEAR_SCEV, id, base, slope);
}
static bool is_linear_or_linear32(struct scev *scev, int id, u32 *base, u32 *slope, bool *zext32)
@@ -296,8 +563,10 @@ static void log_reg(struct bpf_verifier_env *env, u32 reg)
{
if (reg < MAX_BPF_REG)
bpf_log(&env->log, "r%d", reg);
- else
+ else if (reg < REGS_NUM)
bpf_log(&env->log, "*fp%d", (MAX_BPF_REG - reg - 1) * 8);
+ else
+ bpf_log(&env->log, "mem%d", reg - REGS_NUM);
}
static const char *op_str(u32 op)
@@ -331,7 +600,7 @@ static const char *op_str(u32 op)
case SPILL32: return "spill32";
case ANY: return "any";
case LINEAR_SCEV: return "linear";
- case COPY_SCEV: return "copy";
+ case ADD_SCEV: return "add";
}
return NULL;
}
@@ -354,7 +623,7 @@ static u32 op_params_num(u32 op)
case SMOD:
case ANY:
case LINEAR_SCEV:
- case COPY_SCEV:
+ case ADD_SCEV:
return 2;
case BPF_NEG:
case SEXT8:
@@ -428,27 +697,74 @@ static bool expr_next(struct scev *scev, u32 *id, u32 *order)
return expr_next(scev, id, order);
}
+/*
+ * An SSA name is printed as '%', the SCEV register, '.', the insn. A def is printed in full at
+ * every use: (+ %r8.7=phi(1, 2) 4).
+ * %r0.6 insn 6 defines r0. The value is OPAQUE, '_' without a def
+ * %fp-8.8? insn 8 may write fp-8. The value is UNKNOWN, '?' without a def
+ * %r8.7=phi(1, 2) the phi of r8 before insn 7
+ * %r0.7=phi(_) a phi of distinct OPAQUE values
+ * %r6.9=phi(?) a phi of distinct UNKNOWN values, or of more than 8 values
+ * %r2.12=(+ x 4) insn 12 defines r2, see alu64_with_def()
+ * %r2.25=phi((+ x 4)) two adds of one shape, each may have been converted to ALU32:
+ * the phi is not (+ x 4)
+ * A name is unique within the env of one loop. In the env of loop H a phi at H merges the backedge
+ * values only, the header phi itself is (REG r): in 'scev at header 1: r6=%r6.1=phi(r6, (+ r6 1))'
+ * one backedge leaves r6 as it is, the other one adds 1.
+ * '%' in front of r or fp is a name, followed by a blank it is BPF_MOD.
+ */
+static void log_def(struct bpf_verifier_env *env, struct expr_def def)
+{
+ if (!def.set)
+ return;
+ if (def.reg < MAX_BPF_REG)
+ bpf_log(&env->log, "%%r%d.%d", def.reg, def.idx);
+ else if (def.reg < REGS_NUM)
+ bpf_log(&env->log, "%%fp%d.%d", (MAX_BPF_REG - def.reg - 1) * 8, def.idx);
+ else
+ bpf_log(&env->log, "%%mem%d.%d", def.reg - REGS_NUM, def.idx);
+}
+
static void log_expr(struct bpf_verifier_env *env, u32 id)
{
struct bpf_verifier_log *log = &env->log;
+ bool operand, bare, first = false;
struct scev *scev = env->scev;
+ u32 order, d, bare_any = 0;
+ struct expr_def def;
struct expr *expr;
const char *str;
- u32 order;
scev->stack_sz = 0;
expr_stack_push(scev, id);
while (expr_next(scev, &id, &order)) {
- if ((order & PRE) && scev->stack_sz > 1)
- bpf_log(log, " ");
expr = &scev->exprs[id];
+ def = expr->def;
+ /* the depth of @id in expr_stack[], expr_next() pops it before POST */
+ d = order & PRE ? scev->stack_sz - 1 : scev->stack_sz;
+ operand = d && (bare_any & BIT(d - 1));
+ /* No '(any' for the operands of phi(a, b). (any a b) among them is expanded. */
+ if (order & PRE) {
+ bare_any &= ~BIT(d);
+ if (expr->op == ANY && (def.set ? def.phi : operand))
+ bare_any |= BIT(d);
+ }
+ bare = bare_any & BIT(d);
+ if ((order & PRE) && (def.set || !bare)) {
+ if (d)
+ bpf_log(log, "%s", !operand ? " " : first ? "" : ", ");
+ log_def(env, def);
+ if (def.phi)
+ bpf_log(log, "=phi(");
+ first = bare;
+ }
switch (expr->op) {
case UNKNOWN:
if (order & PRE)
bpf_log(log, "?");
break;
case OPAQUE:
- if (order & PRE)
+ if ((order & PRE) && (!def.set || def.phi))
bpf_log(log, "_");
break;
case REG:
@@ -460,19 +776,23 @@ static void log_expr(struct bpf_verifier_env *env, u32 id)
bpf_log(log, "%lld", expr->imm);
break;
default:
- if (order & PRE) {
+ if ((order & PRE) && !bare) {
str = op_str(expr->op);
- bpf_log(log, "(");
+ bpf_log(log, def.set && !def.phi ? "=(" : "(");
if (str)
bpf_log(log, "%s", str);
else
bpf_log(log, "bad-expr-op %x", expr->op);
}
- if (order & DEPTH_LIMIT)
- bpf_log(log, "...");
- if (order & POST)
+ if (order & DEPTH_LIMIT) {
+ bpf_log(log, bare && !def.set && !first ? ", ..." : "...");
+ first = false;
+ }
+ if ((order & POST) && !bare)
bpf_log(log, ")");
}
+ if ((order & POST) && def.phi)
+ bpf_log(log, ")");
}
}
@@ -481,11 +801,27 @@ static bool reg_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)
struct bpf_insn_aux_data *aux = env->insn_aux_data;
u16 live_regs = aux[insn_idx].live_regs_before;
+ /* memory */
+ if (reg >= REGS_NUM)
+ return true;
return reg < MAX_BPF_REG
? (BIT(reg) & live_regs)
: test_bit(reg - MAX_BPF_REG, aux[insn_idx].live_stack_before);
}
+/* The first bytes of a stack slot are its high bits */
+static bool is_big_endian_slot(u32 reg)
+{
+ return IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) && reg >= MAX_BPF_REG;
+}
+
+/* Are the upper 32 bits of @reg live before the insn at @insn_idx? */
+static bool hi32_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)
+{
+ return reg < MAX_BPF_REG || is_big_endian_slot(reg) ||
+ bpf_half_slot_live_before(env, insn_idx, (reg - MAX_BPF_REG) * 2);
+}
+
static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx)
{
struct bpf_verifier_log *log = &env->log;
@@ -512,7 +848,7 @@ static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx)
log_reg(env, i);
bpf_log(log, "=");
log_expr(env, e->reg2expr[i]);
- if (e->reg2expr[i] != UNKNOWN_EXPR_ID) {
+ if (!is_op(scev, e->reg2expr[i], UNKNOWN)) {
bpf_log(log, " / ");
log_expr(env, e->reg2scev[i]);
}
@@ -554,7 +890,7 @@ static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx
if (!e)
return NULL;
- tmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT);
+ tmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT | __GFP_ZERO);
if (!tmp) {
kfree(e);
return NULL;
@@ -568,6 +904,25 @@ static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx
return e;
}
+/* The env has no users any more */
+static void free_loop_env(struct scev *scev, int loop_header, int insn_idx)
+{
+ struct insn_envs *envs = scev->envs[insn_idx];
+ u32 i;
+
+ for (i = 0; i < envs->cnt; i++) {
+ if (envs->entries[i].loop_header != loop_header)
+ continue;
+ kfree(envs->entries[i].env);
+ envs->entries[i] = envs->entries[--envs->cnt];
+ break;
+ }
+ if (envs->cnt || envs->linked_cnt)
+ return;
+ kfree(envs);
+ scev->envs[insn_idx] = NULL;
+}
+
static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)
{
if (id < 0)
@@ -576,10 +931,15 @@ static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)
return 0;
}
-static int setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, int insn_idx)
+/* The insn at @idx defines @reg. The value is not tracked: @id is UNKNOWN or OPAQUE. */
+static int forget_reg(struct scev *scev, struct env *e, u32 reg, int id, int idx)
{
- struct scev *scev = env->scev;
- int i, err;
+ return replace_reg(scev, e, reg, expr_with_def(scev, id, insn_def(idx, reg)));
+}
+
+static void setup_initial_loop_env(struct env *e)
+{
+ int i;
/*
* Initial assignments are of form rX -> rX are needed as seeds for subsequent
@@ -587,25 +947,29 @@ static int setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, i
* join() will overwrite the them. compute_header_scevs() accounts for register
* states at loop entry.
*/
- for (i = 0; i < REGS_NUM; i++) {
- err = replace_reg(scev, e, i, expr1(scev, REG, i));
- if (err)
- return err;
- }
- return 0;
+ for (i = 0; i < REGS_NUM; i++)
+ e->reg2expr[i] = REG_EXPR_ID(i);
}
-static void forget_call_regs(struct env *e)
+/* A subprog can return a pair in r0 and r2: a call defines r1 - r5 too if they are live after it */
+static int forget_call_regs(struct bpf_verifier_env *env, struct env *e, int idx)
{
- int i;
+ int i, err;
- for (i = BPF_REG_0; i <= BPF_REG_5; i++)
+ for (i = BPF_REG_0; i <= BPF_REG_5; i++) {
e->reg2expr[i] = UNKNOWN_EXPR_ID;
+ if (idx + 1 >= env->prog->len || !reg_alive_at(env, i, idx + 1))
+ continue;
+ err = forget_reg(env->scev, e, i, UNKNOWN_EXPR_ID, idx);
+ if (err)
+ return err;
+ }
+ return 0;
}
static u32 spill_spi(struct bpf_insn *insn)
{
- return -insn->off / BPF_REG_SIZE - 1;
+ return (-insn->off - 1) / BPF_REG_SIZE;
}
static u32 off_to_reg(struct bpf_insn *insn)
@@ -620,16 +984,19 @@ static bool is_spill_off(int off)
off >= -MAX_BPF_STACK_JIT;
}
-static void mark_opaque(struct env *e, int off, int size)
+static int mark_opaque(struct scev *scev, struct env *e, int idx, int off, int size)
{
- int b, spi;
+ int b, spi, err;
for (b = off; b < off + size; b++) {
if (b >= 0 || b < -MAX_BPF_STACK_JIT)
continue;
spi = (-b - 1) / BPF_REG_SIZE;
- e->reg2expr[MAX_BPF_REG + spi] = OPAQUE_EXPR_ID;
+ err = forget_reg(scev, e, MAX_BPF_REG + spi, OPAQUE_EXPR_ID, idx);
+ if (err)
+ return err;
}
+ return 0;
}
static int mk_spill(struct scev *scev, u8 size, int id)
@@ -643,18 +1010,40 @@ static int mk_spill(struct scev *scev, u8 size, int id)
return UNKNOWN_EXPR_ID;
}
-static int mk_fill(struct scev *scev, int id, u8 code)
+/* The size of the spill in a slot with the expression @id. It holds the low bytes of *@x. */
+static u32 expr_spill_size(struct scev *scev, u32 id, u32 *x)
{
- bool sx = BPF_MODE(code) == BPF_MEMSX;
+ struct expr *e = &scev->exprs[id];
+ /* nothing looks through a phi, see struct expr_def */
+ bool partial = (e->op == SPILL8 || e->op == SPILL16 || e->op == SPILL32) && !e->def.phi;
+ *x = partial ? e->params[0] : id;
+ return partial ? op_low_bits(e->op) / BITS_PER_BYTE : BPF_REG_SIZE;
+}
+
+/* -ENOENT: the value of the fill is not known */
+static int mk_fill(struct scev *scev, int id, struct bpf_insn *insn)
+{
+ u32 x, spill_size = expr_spill_size(scev, id, &x);
+ u32 size = bpf_size_to_bytes(BPF_SIZE(insn->code));
+ bool sx = BPF_MODE(insn->code) == BPF_MEMSX;
+
+ /* The fill reads the low bytes of the spill, as in check_stack_read_fixed_off() */
+ if (size <= spill_size && bpf_stack_narrow_access_ok(insn->off, size, spill_size))
+ id = x;
+ else if (!is_spill_off(insn->off))
+ return -ENOENT;
#ifdef __BIG_ENDIAN
+ /* No register becomes (spillN x): its low bits would not be those of x */
+ else if (spill_size < BPF_REG_SIZE)
+ return -ENOENT;
/* A narrow fill reads the high bits of the slot on big-endian. */
- if (BPF_SIZE(code) != BPF_DW)
+ else
return expr2(scev, sx ? BPF_ARSH : BPF_RSH, id,
- imm_expr(scev, 64 - BITS_PER_BYTE * bpf_size_to_bytes(BPF_SIZE(code))));
+ imm_expr(scev, BITS_PER_BYTE * (BPF_REG_SIZE - size)));
#endif
- switch (BPF_SIZE(code)) {
+ switch (BPF_SIZE(insn->code)) {
case BPF_B: return expr1(scev, sx ? SEXT8 : ZEXT8, id);
case BPF_H: return expr1(scev, sx ? SEXT16 : ZEXT16, id);
case BPF_W: return expr1(scev, sx ? SEXT32 : ZEXT32, id);
@@ -663,7 +1052,7 @@ static int mk_fill(struct scev *scev, int id, u8 code)
return UNKNOWN_EXPR_ID;
}
-static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int id)
+static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int idx, int id)
{
u8 size = BPF_SIZE(insn->code);
@@ -671,25 +1060,205 @@ static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *ins
return 0;
if (is_spill_off(insn->off))
return replace_reg(scev, e, off_to_reg(insn), mk_spill(scev, size, id));
- mark_opaque(e, insn->off, bpf_size_to_bytes(size));
- return 0;
+ return mark_opaque(scev, e, idx, insn->off, bpf_size_to_bytes(size));
}
-static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn)
+static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int idx)
{
- int id;
+ int id = -ENOENT;
- if (insn->src_reg == BPF_REG_FP && is_spill_off(insn->off))
- id = mk_fill(scev, e->reg2expr[off_to_reg(insn)], insn->code);
- else
- id = OPAQUE_EXPR_ID;
+ if (insn->src_reg == BPF_REG_FP && insn->off < 0 && insn->off >= -MAX_BPF_STACK_JIT)
+ id = e->reg2expr[off_to_reg(insn)];
+ /*
+ * The def of a slot that a slice may alias is no value number, see expr_is_vn(): two fills
+ * can read distinct values. One fill reads one value: the insn defines the register.
+ */
+ if (id >= 0 && scev->exprs[id].def.set && !scev->exprs[id].is_vn)
+ id = -ENOENT;
+ if (id >= 0)
+ id = mk_fill(scev, id, insn);
+ if (id == -ENOENT)
+ return forget_reg(scev, e, insn->dst_reg, OPAQUE_EXPR_ID, idx);
return replace_reg(scev, e, insn->dst_reg, id);
}
+static bool const_diff(struct bpf_verifier_env *env, int h, u32 id_a, u32 id_b, s64 *delta,
+ u32 *bits);
+
+/* The memory location of @e at the address @addr, 0: one that is not in use. MEM_REGS_NUM: none. */
+static u32 find_mem_reg(const struct env *e, u32 addr)
+{
+ u32 i;
+
+ for (i = 0; i < MEM_REGS_NUM && e->mem_addr[i] != addr; i++)
+ ;
+ return i;
+}
+
+static void forget_mem_reg(struct env *e, u32 i)
+{
+ e->mem_addr[i] = 0;
+ e->reg2expr[REGS_NUM + i] = UNKNOWN_EXPR_ID;
+}
+
+/*
+ * The insn may write @size bytes at the address @addr, 0: anywhere. A may-def of all memory
+ * locations but those that have the same address base and don't overlap. Two bases can be two names
+ * of one memory, 'f(&c, &c)'.
+ */
+static void forget_mem_regs(struct bpf_verifier_env *env, struct env *e, u32 addr, u32 size)
+{
+ u32 i, x, bits;
+ s64 delta;
+
+ for (i = 0; i < MEM_REGS_NUM; i++) {
+ /* the caller defines it */
+ if (e->mem_addr[i] == addr)
+ continue;
+ if (addr && const_diff(env, -1, addr, e->mem_addr[i], &delta, &bits) &&
+ bits == 64 && (delta >= size ||
+ delta + expr_spill_size(env->scev, e->reg2expr[REGS_NUM + i], &x) <= 0))
+ continue;
+ forget_mem_reg(e, i);
+ }
+}
+
+/*
+ * A jump tests a register, and a load makes a new value number. So a memory location is dead once
+ * no register that is live after the insn at @idx has the base of its value: no jump is going to
+ * link it.
+ */
+static void forget_dead_mem_regs(struct bpf_verifier_env *env, struct env *e, int idx)
+{
+ struct expr *exprs = env->scev->exprs;
+ u32 i, r, base;
+
+ for (i = 0; i < MEM_REGS_NUM; i++) {
+ base = exprs[e->reg2expr[REGS_NUM + i]].base;
+ for (r = 0; r < REGS_NUM; r++)
+ if (exprs[e->reg2expr[r]].base == base && reg_alive_at(env, r, idx + 1))
+ break;
+ if (r == REGS_NUM)
+ forget_mem_reg(e, i);
+ }
+}
+
+/*
+ * The address of the load or store at @idx through @reg, 0: the memory is not tracked. r10 has the
+ * stack slots, r11 and r12 are no SCEV registers. The main pass takes nothing but stack.
+ */
+static int mk_mem_addr(struct bpf_verifier_env *env, struct env *e, int idx, u32 reg)
+{
+ struct scev *scev = env->scev;
+
+ if (reg >= BPF_REG_FP || !(env->insn_aux_data[idx].stack_ptrs & BIT(reg)) ||
+ !scev->exprs[e->reg2expr[reg]].is_vn)
+ return 0;
+ return expr2(scev, BPF_ADD, e->reg2expr[reg], imm_expr(scev, env->prog->insnsi[idx].off));
+}
+
+/*
+ * The insn at @idx stored the low bytes of @id at the address @addr, or it loaded them from there.
+ * The location takes a SCEV register that is not in use, or that of a dead one.
+ */
+static int replace_mem_reg(struct bpf_verifier_env *env, struct env *e, int idx, int addr, int id)
+{
+ u32 i;
+
+ if (addr <= 0)
+ return addr;
+ i = find_mem_reg(e, addr);
+ if (i == MEM_REGS_NUM)
+ i = find_mem_reg(e, 0);
+ if (i == MEM_REGS_NUM) {
+ forget_dead_mem_regs(env, e, idx);
+ i = find_mem_reg(e, 0);
+ }
+ if (i == MEM_REGS_NUM)
+ return 0;
+ e->mem_addr[i] = addr;
+ return replace_reg(env->scev, e, REGS_NUM + i,
+ mk_spill(env->scev, BPF_SIZE(env->prog->insnsi[idx].code), id));
+}
+
+static int load_mem(struct bpf_verifier_env *env, struct env *e, int idx)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ /* the insn defines dst_reg, which can be src_reg */
+ int addr = mk_mem_addr(env, e, idx, insn->src_reg);
+
+ return maybe_load_fp(env->scev, e, insn, idx) ?:
+ replace_mem_reg(env, e, idx, addr, e->reg2expr[insn->dst_reg]);
+}
+
+static int store_mem(struct bpf_verifier_env *env, struct env *e, int idx, int id)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ int addr;
+
+ if (insn->dst_reg == BPF_REG_FP)
+ return maybe_store_fp(env->scev, e, insn, idx, id);
+ addr = mk_mem_addr(env, e, idx, insn->dst_reg);
+ if (addr < 0)
+ return addr;
+ forget_mem_regs(env, e, addr, bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ return replace_mem_reg(env, e, idx, addr, id);
+}
+
+/*
+ * The low 32 bits of a + b depend on the low 32 bits of a and b only: 'w1 += w2' is
+ * (zext32 (+ a b)). That doesn't hold for a right shift and for a division. Their operands are zero
+ * or sign extended and a shift amount is masked, so that every expression is a 64-bit operation.
+ */
+static void alu32_operands(struct scev *scev, u32 op, int *a, int *b)
+{
+ s64 imm = 0;
+ bool imm_b = *b >= 0 && is_imm(scev, *b, &imm);
+
+ switch (op) {
+ case BPF_RSH:
+ case BPF_ARSH:
+ *a = expr1(scev, op == BPF_RSH ? ZEXT32 : SEXT32, *a);
+ fallthrough;
+ case BPF_LSH:
+ *b = imm_b ? imm_expr(scev, imm & 31) :
+ expr2(scev, BPF_AND, *b, imm_expr(scev, 31));
+ break;
+ case BPF_DIV:
+ case BPF_MOD:
+ *a = expr1(scev, ZEXT32, *a);
+ *b = imm_b ? imm_expr(scev, (u32)imm) : expr1(scev, ZEXT32, *b);
+ break;
+ case SDIV:
+ case SMOD:
+ *a = expr1(scev, SEXT32, *a);
+ *b = imm_b ? imm_expr(scev, (s32)imm) : expr1(scev, SEXT32, *b);
+ break;
+ }
+}
+
+/*
+ * In a prog with an arena an ALU64 insn is converted to ALU32 at fixup if an operand is a pointer
+ * to the arena, see adjust_reg_min_max_vals(). Types are not known here. So @id, what the insn at
+ * @idx computes from @a, gets a def: the value of @dst after the insn, converted or not. See
+ * split_const_offset() for when the op can be trusted. Constant operands are scalars in every
+ * state.
+ */
+static int alu64_with_def(struct scev *scev, int id, int a, int idx, u32 dst)
+{
+ s64 imm;
+
+ if (id < 0 || is_imm(scev, id, &imm))
+ return id;
+ /* (+ x 0) is x only if the insn stays ALU64 */
+ return expr_with_def(scev, id == a ? UNKNOWN_EXPR_ID : id, insn_def(idx, dst));
+}
+
static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
{
const bool little_endian = htons(0x3412) == 0x1234;
struct bpf_insn *insn = &env->prog->insnsi[idx];
+ bool arena = env->prog->aux->arena;
struct scev *scev = env->scev;
u32 *reg2expr = e->reg2expr;
u8 class = BPF_CLASS(insn->code);
@@ -698,9 +1267,9 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
u8 mode = BPF_MODE(insn->code);
u32 dst = insn->dst_reg;
u32 src = insn->src_reg;
- u32 op, sext, l, r;
+ u32 op, sext;
bool need_bswap;
- int i, id;
+ int i, id, a;
s64 imm;
/* reg2expr[12] is a stack slot, not r12 */
@@ -764,22 +1333,15 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
else
goto mark_dst_unknown;
- /*
- * 'r1 <<= 32; r1 >>= 32' is (u32)r1 for cpu v1 and v2. Only here both
- * shifts are known to be 64-bit ones: the result of a 32-bit shift is
- * (zext32 ...), and (>> x 32) is 'w1 >>= w2' with 32 in w2 as well,
- * which shifts by 0.
- */
- if (class == BPF_ALU64 && op == BPF_RSH && id >= 0 &&
- is_imm(scev, id, &imm) && imm == 32 &&
- is_binop(scev, BPF_LSH, reg2expr[dst], &l, &r) &&
- is_imm(scev, r, &imm) && imm == 32)
- return replace_reg(scev, e, dst, expr1(scev, ZEXT32, l));
-
- id = expr2(scev, op, reg2expr[dst], id);
+ a = reg2expr[dst];
+ if (class == BPF_ALU)
+ alu32_operands(scev, op, &a, &id);
+ id = expr2(scev, op, a, id);
if (class == BPF_ALU)
id = expr1(scev, ZEXT32, id);
+ else if (arena)
+ id = alu64_with_def(scev, id, a, idx, dst);
return replace_reg(scev, e, dst, id);
@@ -829,47 +1391,53 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
imm = env->insn_aux_data[idx + 1].const_reg_vals[dst];
return replace_reg(scev, e, dst, imm_expr(scev, imm));
}
- return maybe_load_fp(scev, e, insn);
+ return load_mem(env, e, idx);
default:
goto mark_dst_unknown;
}
case BPF_STX:
switch (mode) {
case BPF_MEM:
- return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ return store_mem(env, e, idx, reg2expr[src]);
case BPF_ATOMIC:
if (insn->imm == BPF_LOAD_ACQ)
- return maybe_load_fp(scev, e, insn);
+ return maybe_load_fp(scev, e, insn, idx);
if (insn->imm == BPF_STORE_REL) {
- return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ return store_mem(env, e, idx, reg2expr[src]);
}
/*
* verifier does not track other atomic ops precisely,
* hence mark the results as opaque.
*/
- if (insn->dst_reg == BPF_REG_FP)
- mark_opaque(e, insn->off, bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ if (insn->dst_reg == BPF_REG_FP) {
+ id = mark_opaque(scev, e, idx, insn->off,
+ bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ if (id < 0)
+ return id;
+ } else {
+ forget_mem_regs(env, e, 0, 0);
+ }
if (insn->imm == BPF_CMPXCHG)
- return replace_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID);
+ return forget_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID, idx);
if (insn->imm & BPF_FETCH)
- return replace_reg(scev, e, src, OPAQUE_EXPR_ID);
+ return forget_reg(scev, e, src, OPAQUE_EXPR_ID, idx);
break;
}
break;
case BPF_ST:
- if (insn->dst_reg == BPF_REG_FP) {
- id = imm_expr(scev, insn->imm);
- if (id < 0)
- return id;
- return maybe_store_fp(scev, e, insn, id);
- }
- break;
+ id = imm_expr(scev, insn->imm);
+ if (id < 0)
+ return id;
+ return store_mem(env, e, idx, id);
case BPF_JMP:
case BPF_JMP32:
if (opcode == BPF_CALL) {
- forget_call_regs(e);
+ forget_mem_regs(env, e, 0, 0);
+ id = forget_call_regs(env, e, idx);
+ if (id < 0)
+ return id;
/* made anew, like what is loaded. The parameter tells the two apart. */
- return replace_reg(scev, e, BPF_REG_0, expr1(scev, OPAQUE, 1));
+ return forget_reg(scev, e, BPF_REG_0, expr1(scev, OPAQUE, 1), idx);
}
/* for non-CALL there are no changes in register states */
break;
@@ -883,12 +1451,11 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
}
/* map, map value, BTF id, function */
if (BPF_SIZE(insn->code) == BPF_DW)
- return replace_reg(scev, e, dst, OPAQUE_EXPR_ID);
+ return forget_reg(scev, e, dst, OPAQUE_EXPR_ID, idx);
goto mark_dst_unknown;
case BPF_ABS:
case BPF_IND:
- forget_call_regs(e);
- break;
+ return forget_call_regs(env, e, idx);
default:
goto mark_dst_unknown;
}
@@ -897,20 +1464,47 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
/* unknown instruction, nuke state */
for (i = 0; i < REGS_NUM; i++)
reg2expr[i] = UNKNOWN_EXPR_ID;
+ forget_mem_regs(env, e, 0, 0);
break;
}
return 0;
mark_dst_unknown:
- reg2expr[dst] = UNKNOWN_EXPR_ID;
- return 0;
+ return forget_reg(scev, e, dst, UNKNOWN_EXPR_ID, idx);
+}
+
+/*
+ * if (c) sum += a[i]; else sum += b[i];
+ * @id without defs: (+ r6 %r2.4) -> (+ r6 _). A def tells one load from another. The code that
+ * analyzes loops asks how a value is computed, and that is the same on both paths.
+ * Beyond depth EXPR_STACK_DEPTH an expression keeps its defs: no user looks there.
+ */
+static int strip_defs(struct scev *scev, u32 id, u32 lvl)
+{
+ struct expr e = scev->exprs[id]; /* snapshot the expr before potential realloc */
+ int a;
+
+ switch (op_params_num(e.op)) {
+ case 0:
+ return e.def.set ? expr_with_def(scev, id, no_def) : id;
+ case 1:
+ if (lvl == EXPR_STACK_DEPTH)
+ return id;
+ return expr1(scev, e.op, strip_defs(scev, e.params[0], lvl + 1));
+ default:
+ if (lvl == EXPR_STACK_DEPTH)
+ return id;
+ a = strip_defs(scev, e.params[0], lvl + 1);
+ return expr2(scev, e.op, a, strip_defs(scev, e.params[1], lvl + 1));
+ }
}
/*
* Construct minimal 'ANY' expression by traversing 'a' and 'b'
- * and accumulating non-duplicated non-ANY entries.
+ * and accumulating non-duplicated non-ANY entries, without their defs.
+ * 'def' is the def of the result, no_def if it has none.
*/
-static int mk_any(struct scev *scev, int a, int b)
+static int mk_any(struct scev *scev, int a, int b, struct expr_def def)
{
struct expr_stack_elt *elt;
struct expr *expr;
@@ -933,14 +1527,18 @@ static int mk_any(struct scev *scev, int a, int b)
if (expr->op == ANY) {
if (!expr_stack_push(scev, expr->params[1]) ||
!expr_stack_push(scev, expr->params[0]))
- return UNKNOWN_EXPR_ID;
+ return expr_with_def(scev, UNKNOWN_EXPR_ID, def);
} else {
- for (j = 0; j < ids_buf_sz; j++) {
+ /* the operands of an ANY have no defs already */
+ if (id == roots[i])
+ id = strip_defs(scev, id, 0);
+ if (id < 0)
+ return id;
+ for (j = 0; j < ids_buf_sz; j++)
if (same_exprs(scev, scev->ids_buf[j], id))
goto next;
- }
if (ids_buf_sz == ARRAY_SIZE(scev->ids_buf))
- return UNKNOWN_EXPR_ID;
+ return expr_with_def(scev, UNKNOWN_EXPR_ID, def);
scev->ids_buf[ids_buf_sz++] = id;
}
next:;
@@ -954,12 +1552,77 @@ next:;
if (id < 0)
return id;
}
- return id;
+ return expr_with_def(scev, id, def);
+}
+
+static void split_const_offset(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off,
+ u32 *bits);
+
+/* @id == *@base + *@off in 64 bits: no extension and no partial spill is stripped */
+static void split_const_offset64(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off)
+{
+ struct scev *scev = env->scev;
+ u32 bits, l, r;
+
+ split_const_offset(env, id, base, off, &bits);
+ if (bits == 64)
+ return;
+ *base = id;
+ *off = 0;
+ if (!scev->exprs[id].def.set && is_add(scev, id, &l, &r) && is_imm(scev, r, off))
+ *base = l;
+}
+
+/*
+ * if (c) { n = f(); m = n; } else { n = g(); m = n; } if (n > 100) return 0; use(m);
+ * The phi of @reg before the insn at @idx. It merges @a, which came over the edges so far, and @b.
+ * Phis are value numbered as GVN does it, by join point and operands, up to a constant offset:
+ * a == base_a + off_a and b == base_b + off_b, so
+ * phi == phi(base_a, base_b + off_b - off_a) + off_a
+ * The phi of the bases is hashed without @reg. All registers that have a constant difference on
+ * each edge get the same one, and const_diff() finds them as it finds 'x' and 'x + 4'. The next
+ * edge merges the phi of the bases with the next base: the id stands for the list of the operands,
+ * for any number of edges. No edge brings a phi of this join point, so every phi here gets a new
+ * base with every edge.
+ */
+static int mk_phi(struct bpf_verifier_env *env, u32 a, u32 b, int idx, u32 reg)
+{
+ struct scev *scev = env->scev;
+ u32 base_a, base_b;
+ s64 off_a, off_b;
+ struct expr e;
+ int id;
+
+ id = mk_any(scev, a, b, no_def);
+ if (id < 0)
+ return id;
+ e = scev->exprs[id];
+ e.def = phi_def(idx, reg);
+ e.base = 0;
+ split_const_offset64(env, a, &base_a, &off_a);
+ split_const_offset64(env, b, &base_b, &off_b);
+ if (!expr_is_vn(scev, &e) || !scev->exprs[base_a].is_vn || !scev->exprs[base_b].is_vn)
+ return add_expr(scev, e);
+ id = base_b;
+ if (off_a != off_b)
+ id = expr2(scev, BPF_ADD, base_b, imm_expr(scev, (u64)off_b - off_a));
+ if (id < 0)
+ return id;
+ id = add_expr(scev, (struct expr){ .op = ANY, .params = { base_a, id },
+ .def = phi_def(idx, BASE_REG) });
+ if (id < 0)
+ return id;
+ e.base = id;
+ e.off = off_a;
+ e.bits = 64;
+ return add_expr(scev, e);
}
-static int join(struct scev *scev, struct env *acc, struct env *cur)
+/* @acc is the env before the insn at @idx */
+static int join(struct bpf_verifier_env *env, struct env *acc, struct env *cur, int idx)
{
- int i, id;
+ struct scev *scev = env->scev;
+ int i, j, id;
if (acc->empty) {
memcpy(acc, cur, sizeof(*acc));
@@ -967,9 +1630,18 @@ static int join(struct scev *scev, struct env *acc, struct env *cur)
return 0;
}
- for (i = 0; i < REGS_NUM; i++) {
- if (!same_exprs(scev, acc->reg2expr[i], cur->reg2expr[i])) {
- id = mk_any(scev, acc->reg2expr[i], cur->reg2expr[i]);
+ for (i = 0; i < ENV_REGS_NUM; i++) {
+ /* the address names a memory location. It has a phi if all edges track it. */
+ j = i < REGS_NUM ? i : REGS_NUM + find_mem_reg(cur, acc->mem_addr[i - REGS_NUM]);
+ if (j == ENV_REGS_NUM) {
+ forget_mem_reg(acc, i - REGS_NUM);
+ continue;
+ }
+ if (!same_exprs(scev, acc->reg2expr[i], cur->reg2expr[j])) {
+ /* no phi for a dead register: pruned SSA */
+ id = reg_alive_at(env, i, idx) ?
+ mk_phi(env, acc->reg2expr[i], cur->reg2expr[j], idx, i) :
+ UNKNOWN_EXPR_ID;
if (id < 0)
return id;
acc->reg2expr[i] = id;
@@ -991,14 +1663,15 @@ static void forget_modified_regs(struct scev *scev, struct env *acc, struct env
}
/* For a loop H at `header`, mark any register modified as a result of H execution as unknown. */
-static void forget_non_invariants(struct bpf_verifier_env *env, struct env *acc, int header)
+static int forget_non_invariants(struct bpf_verifier_env *env, struct env *acc, int header)
{
struct bpf_insn_aux_data *aux = env->insn_aux_data;
struct bpf_loop *loop = aux[header].loop;
struct scev *scev = env->scev;
- int i, idx, h;
+ int i, idx, h, err;
acc->empty = false;
+ forget_mem_regs(env, acc, 0, 0);
forget_modified_regs(scev, acc, find_header_env(scev, header));
for (i = 0; i < loop->exits_cnt; i++) {
idx = loop->exits[i].from;
@@ -1033,6 +1706,15 @@ static void forget_non_invariants(struct bpf_verifier_env *env, struct env *acc,
*/
forget_modified_regs(scev, acc, find_loop_env(scev, header, idx));
}
+ /* the nested loop defines them at its header */
+ for (i = 0; i < REGS_NUM; i++) {
+ if (acc->reg2expr[i] != UNKNOWN_EXPR_ID)
+ continue;
+ err = forget_reg(scev, acc, i, UNKNOWN_EXPR_ID, header);
+ if (err)
+ return err;
+ }
+ return 0;
}
/* Order worklist in reverse post-order. */
@@ -1051,7 +1733,7 @@ static int worklist_push(struct bpf_verifier_env *env, int loop_header, int idx)
{
struct scev *scev = env->scev;
struct scev_worklist *worklist = &scev->worklist;
- u32 tag = (u32)loop_header + 1;
+ u32 tag = loop_header + 2; /* -1 is a subprog */
if (scev->discovered[idx] == tag)
return 0;
@@ -1107,7 +1789,7 @@ static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,
len = log->end_pos - null_pos;
bpf_log(log, "%*s", max(37 - (int)len, 1), " ");
bpf_log(log, " ; ");
- for (r = 0; r < REGS_NUM; r++) {
+ for (r = 0; r < ENV_REGS_NUM; r++) {
old_id = old->reg2expr[r];
new_id = new->reg2expr[r];
if (at == LOG_AT_TRANSFER && !reg_alive_at_succ(env, r, insn_idx))
@@ -1122,6 +1804,10 @@ static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,
if (any_changes)
bpf_log(log, ", ");
log_reg(env, r);
+ if (r >= REGS_NUM && new->mem_addr[r - REGS_NUM]) {
+ bpf_log(log, "=*");
+ log_expr(env, new->mem_addr[r - REGS_NUM]);
+ }
bpf_log(log, " ");
log_expr(env, old_id);
bpf_log(log, " -> ");
@@ -1149,7 +1835,7 @@ static bool is_probe_read_helper(u32 func_id)
* If instruction is an indirect write to stack, invalidate SCEVs for spi's
* that this instruction can touch.
*/
-static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)
+static int reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)
{
struct bpf_insn *insn = &env->prog->insnsi[idx];
struct scev *scev = env->scev;
@@ -1157,19 +1843,24 @@ static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct
const unsigned long *mask;
u32 spi, reg;
bool opaque;
+ int err;
/* Direct fp stores are fine. */
if ((class == BPF_ST || class == BPF_STX) && insn->dst_reg == BPF_REG_FP)
- return;
+ return 0;
mask = bpf_may_write_mask(env, idx);
opaque = bpf_helper_call(insn) && is_probe_read_helper(insn->imm);
for_each_set_bit(spi, mask, MAX_BPF_STACK_SLOTS) {
reg = MAX_BPF_REG + spi;
- if (cur_env->reg2expr[reg] == UNKNOWN_EXPR_ID)
- continue;
- replace_reg(scev, cur_env, reg, opaque ? OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID);
+ /* '?' stays '?' */
+ err = forget_reg(scev, cur_env, reg,
+ opaque && !is_op(scev, cur_env->reg2expr[reg], UNKNOWN) ?
+ OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID, idx);
+ if (err)
+ return err;
}
+ return 0;
}
/*
@@ -1264,77 +1955,469 @@ static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_he
if (aux[header].loop_header == cur_header)
return header;
- return -1;
+ return -1;
+}
+
+/*
+ * Join cur_env into the successor's environment and schedule their traversal.
+ * Map successors in nested loops to their topmost nested header.
+ * Ignore successors outside the current loop and its nested loops.
+ */
+static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
+ struct env *old_env, struct env *cur_env)
+{
+ bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ struct scev *scev = env->scev;
+ int err, nested_header, idom;
+ struct env *succ_env;
+
+ /*
+ * There are several possibilities for a successor:
+ * - succ_idx can be a part of a loop outside of the cur_header's loop,
+ * such edges are ignored.
+ * - succ_idx can be a part of the same loop as cur_header,
+ * for such edges succ_idx environment is updated:
+ * e[succ_idx] = join(e[succ_idx], cur_env)
+ * - succ_idx can be a part of some loop inner to cur_header,
+ * in such a case there exists some loop header H,
+ * such that H.loop_header == cur_header
+ * and H is the same as succ_idx's loop or contains it.
+ */
+ if (bpf_loop_at_index(env, succ_idx) != cur_header) {
+ /*
+ * topmost_nested_loop() either finds H or returns -1,
+ * in case if succ_idx is a part of a loop outer to cur_header.
+ */
+ nested_header = topmost_nested_loop(env, succ_idx, cur_header);
+ if (nested_header < 0)
+ return 0;
+ succ_idx = nested_header;
+ }
+ succ_env = get_loop_env(scev, cur_header, succ_idx);
+ if (!succ_env)
+ return -ENOMEM;
+ /*
+ * The header of an irreducible loop does not dominate its body. An insn whose immediate
+ * dominator is outside of the loop is reached from a secondary entry, without the header.
+ * The env at the source of an entering edge is not known: all '?', like a new env. So the
+ * insn is a join point with a phi for every live register, see join_added_edges().
+ */
+ idom = env->idoms[succ_idx];
+ if (cur_header >= 0 && succ_idx != cur_header &&
+ env->insn_aux_data[cur_header].loop->irreducible &&
+ bpf_loop_at_index(env, idom) != cur_header &&
+ topmost_nested_loop(env, idom, cur_header) < 0)
+ succ_env->empty = false;
+ if (log_level2)
+ memcpy(old_env, succ_env, sizeof(*old_env));
+ err = join(env, succ_env, cur_env, succ_idx);
+ if (err)
+ return err;
+ err = worklist_push(env, cur_header, succ_idx);
+ if (err)
+ return err;
+ if (log_level2)
+ log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
+ return 0;
+}
+
+/*
+ * Recurrences need a natural loop. Unsupported loops get an unknown header environment.
+ * A nested loop is processed as a single instruction, its exits are the successors: all of
+ * them are needed. No result for the loop itself depends on the list of its own exits:
+ * mark_latches() prepares them for the loop around, and compute_max_iters() asks if there is
+ * only one, which a list that is cut does not have.
+ */
+static bool can_compute_loop_scev(const struct bpf_loop *loop)
+{
+ return !loop->irreducible && !loop->nested_exits_overflow;
+}
+
+/* A loop is a single instruction for the subprog too: no exit list may be truncated. */
+static bool can_compute_subprog_scev(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
+{
+ struct bpf_loop *loop;
+ int i;
+
+ for (i = sub->start; i < (sub + 1)->start; i++) {
+ loop = env->insn_aux_data[i].loop;
+ if (loop && (loop->exits_overflow || loop->nested_exits_overflow))
+ return false;
+ }
+ return true;
+}
+
+/*
+ * The edges that the verifier adds, see bpf_head_guard_target(): bpf_insn_successors() doesn't have
+ * them. They leave all loops. The env at their source is not known: @cur_env is all '?'. So their
+ * target is a join point with a phi for every live register.
+ */
+static int join_added_edges(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,
+ struct env *old_env, struct env *cur_env)
+{
+ int i, t, err;
+
+ for (i = sub->start; i < (sub + 1)->start; i++) {
+ t = bpf_head_guard_target(env, i);
+ if (t < 0)
+ continue;
+ err = join_successor(env, -1, t, old_env, cur_env);
+ if (err)
+ return err;
+ }
+ return sub->bail_insn < 0 ? 0 : join_successor(env, -1, sub->bail_insn, old_env, cur_env);
+}
+
+/*
+ * @id == *@base + *@off (mod 2^*@bits): constant offsets, extensions and partial spills are
+ * stripped, see set_expr_base(). An add with a def holds modulo 2^32 whether its insn is converted
+ * to ALU32 or not, see alu64_with_def(). It holds modulo 2^64 once the main pass has set
+ * prevent_zext: it verified the insn without a pointer to the arena and rejects a state that brings
+ * one. The def dominates every use, and prevent_zext is only ever set: such an add is not checked
+ * again.
+ */
+static void split_const_offset(struct bpf_verifier_env *env, u32 id, u32 *base, s64 *off, u32 *bits)
+{
+ struct scev *scev = env->scev;
+ struct expr *add, *e = &scev->exprs[id];
+
+ *base = e->base;
+ *off = e->off;
+ *bits = e->bits;
+ while (e->arena_add) {
+ add = &scev->exprs[e->arena_add];
+ if (!env->insn_aux_data[add->def.idx].prevent_zext) {
+ *bits = min(*bits, 32);
+ break;
+ }
+ e->arena_add = scev->exprs[add->params[0]].arena_add;
+ }
+}
+
+static bool const_diff_at_header(struct bpf_verifier_env *env, int h, u32 ra, u32 rb, s64 *delta);
+
+/*
+ * @id_a and @id_b are expressions of one env of the loop at @h, or of a subprog: @h is -1. Do they
+ * have a constant difference, @id_b == @id_a + *@delta (mod 2^*@bits)?
+ */
+static bool const_diff(struct bpf_verifier_env *env, int h, u32 id_a, u32 id_b, s64 *delta,
+ u32 *bits)
+{
+ struct scev *scev = env->scev;
+ u32 base_a, base_b, bits_a, ra, rb;
+ s64 off_a, c;
+
+ split_const_offset(env, id_a, &base_a, &off_a, &bits_a);
+ split_const_offset(env, id_b, &base_b, delta, bits);
+ *delta = (u64)*delta - off_a;
+ *bits = min(*bits, bits_a);
+ /* copies are equal in all bits */
+ if (id_a == id_b && scev->exprs[id_a].is_vn) {
+ *bits = 64;
+ return true;
+ }
+ if (base_a == base_b)
+ return scev->exprs[base_a].is_vn;
+ if (h < 0 || !is_reg(scev, base_a, &ra) || !is_reg(scev, base_b, &rb) ||
+ !const_diff_at_header(env, h, ra, rb, &c))
+ return false;
+ *delta = (u64)*delta + c;
+ return true;
+}
+
+/*
+ * old = i = 0; do { i++; if (old > 1021) break; c = buf[old]; old = i; } while (c);
+ * Does @rb == @ra + *@delta hold at the header of the loop at @h in every iteration? It does if it
+ * holds at loop entry, by the env of the enclosing loop at @h, and every backedge preserves it: the
+ * backedge values have this constant difference, or both are the header phi plus one constant.
+ * Loops nest LOOP_STACK_SIZE deep at most, see bpf_flow_place_guards().
+ */
+static bool const_diff_at_header(struct bpf_verifier_env *env, int h, u32 ra, u32 rb, s64 *delta)
+{
+ int outer_header = env->insn_aux_data[h].loop_header;
+ struct env *entry_env = find_loop_env(env->scev, outer_header, h);
+ struct env *header_env = find_header_env(env->scev, h);
+ u32 base_a, base_b, bits_a, bits;
+ s64 off_a, c;
+
+ if (!entry_env || !can_compute_loop_scev(env->insn_aux_data[h].loop) ||
+ !const_diff(env, outer_header, entry_env->reg2expr[ra], entry_env->reg2expr[rb],
+ delta, &bits) || bits != 64)
+ return false;
+ if (const_diff(env, -1, header_env->reg2expr[ra], header_env->reg2expr[rb], &c, &bits))
+ return bits == 64 && c == *delta;
+ split_const_offset(env, header_env->reg2expr[ra], &base_a, &off_a, &bits_a);
+ split_const_offset(env, header_env->reg2expr[rb], &base_b, &c, &bits);
+ return base_a == REG_EXPR_ID(ra) && base_b == REG_EXPR_ID(rb) && off_a == c &&
+ bits_a == 64 && bits == 64;
+}
+
+/*
+ * p = buf + i; if (i > 100) return 0; *p = 0;
+ * @tested is the expression of the tested register and @id that of p, in one env as for
+ * const_diff(). Is @id an add, and one operand @tested + a constant? Then
+ * @id == *@other + @tested + *@delta (mod 2^*@bits). A header phi can be an add, see ADD_SCEV. For
+ * an add with a def see split_const_offset(). Which operand is the pointer is not known here.
+ */
+static bool match_linked_add(struct bpf_verifier_env *env, int h, u32 tested, u32 id, u32 *other,
+ s64 *delta, u32 *bits)
+{
+ struct scev *scev = env->scev;
+ u32 reg, r, b, op = BPF_ADD;
+ struct expr_def def;
+ s64 c;
+
+ split_const_offset(env, id, &id, delta, bits);
+ if (h >= 0 && is_reg(scev, id, ®)) {
+ id = find_header_env(scev, h)->reg2scev[reg];
+ op = ADD_SCEV;
+ }
+ def = scev->exprs[id].def;
+ if (!is_binop(scev, op, id, other, &r) || def.phi)
+ return false;
+ if (def.set && !env->insn_aux_data[def.idx].prevent_zext)
+ *bits = min(*bits, 32);
+ if (!const_diff(env, h, tested, r, &c, &b)) {
+ swap(*other, r);
+ if (!const_diff(env, h, tested, r, &c, &b))
+ return false;
+ }
+ *delta = (u64)*delta + c;
+ *bits = min(*bits, b);
+ return true;
+}
+
+/*
+ * const_diff() for the SCEV register @reg, which has the expression @id_b. A fill from byte
+ * *@fill_off of a slot reads these bits. On big endian the low bytes of a spill are the last ones,
+ * and a narrow fill from the start of a slot is a right shift, see mk_fill().
+ */
+static bool const_diff_reg(struct bpf_verifier_env *env, int h, u32 id_a, u32 reg, u32 id_b,
+ u32 *fill_off, s64 *delta, u32 *bits)
+{
+ struct scev *scev = env->scev;
+ struct expr *e;
+ u32 x;
+ s64 k;
+
+ *fill_off = 0;
+ if (const_diff(env, h, id_a, id_b, delta, bits)) {
+ if (is_big_endian_slot(reg))
+ *fill_off = expr_spill_size(scev, id_b, &x) - *bits / BITS_PER_BYTE;
+ return true;
+ }
+ if (!is_big_endian_slot(reg) || !scev->exprs[id_b].is_vn)
+ return false;
+ split_const_offset(env, id_a, &x, delta, bits);
+ e = &scev->exprs[x];
+ if ((e->op != BPF_RSH && e->op != BPF_ARSH) || e->def.set || e->params[0] != id_b ||
+ !is_imm(scev, e->params[1], &k) || (k != 32 && k != 48 && k != 56))
+ return false;
+ *delta = -(u64)*delta;
+ *bits = min_t(u32, *bits, 64 - k);
+ *fill_off = (64 - k - *bits) / BITS_PER_BYTE;
+ return true;
+}
+
+/* The first of the registers and stack slots @live that holds @id + a constant. REGS_NUM: none. */
+static u32 find_leader(struct bpf_verifier_env *env, struct env *e, int h,
+ const unsigned long *live, u32 id)
+{
+ u32 r, bits;
+ s64 delta;
+
+ for_each_set_bit(r, live, REGS_NUM)
+ if (const_diff(env, h, e->reg2expr[r], id, &delta, &bits))
+ break;
+ return r;
}
/*
- * Join cur_env into the successor's environment and schedule their traversal.
- * Map successors in nested loops to their topmost nested header.
- * Ignore successors outside the current loop and its nested loops.
+ * n = bpf_get_stack(..); m = n; if (n < 0) ..; use(m);
+ * The main pass refines the registers that the conditional jump at @idx tests. Find the live SCEV
+ * registers that are linked to one of them in @e, the env before the jump, and keep them with their
+ * expressions: what bpf_scev_next_linked_reg() needs of @e.
*/
-static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
- struct env *old_env, struct env *cur_env)
+static int find_linked_regs(struct bpf_verifier_env *env, struct env *e, int h, int idx)
{
- bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ struct bpf_insn_aux_data *aux = &env->insn_aux_data[idx];
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ u32 dst = e->reg2expr[insn->dst_reg], src = dst;
+ struct insn_envs *envs = env->scev->envs[idx];
struct scev *scev = env->scev;
- int err, nested_header;
- struct env *succ_env;
+ u32 r, q, other, id, fill_off, base, base_dst, base_src, bits, cap, tested = 0;
+ u32 first = scev->linked_cnt;
+ DECLARE_BITMAP(live, ENV_REGS_NUM) = {};
+ DECLARE_BITMAP(found, ENV_REGS_NUM) = {};
+ void *tmp;
+ s64 delta;
- /*
- * There are several possibilities for a successor:
- * - succ_idx can be a part of a loop outside of the cur_header's loop,
- * such edges are ignored.
- * - succ_idx can be a part of the same loop as cur_header,
- * for such edges succ_idx environment is updated:
- * e[succ_idx] = join(e[succ_idx], cur_env)
- * - succ_idx can be a part of some loop inner to cur_header,
- * in such a case there exists some loop header H,
- * such that H.loop_header == cur_header
- * and H is the same as succ_idx's loop or contains it.
- */
- if (bpf_loop_at_index(env, succ_idx) != cur_header) {
- /*
- * topmost_nested_loop() either finds H or returns -1,
- * in case if succ_idx is a part of a loop outer to cur_header.
- */
- nested_header = topmost_nested_loop(env, succ_idx, cur_header);
- if (nested_header < 0)
- return 0;
- succ_idx = nested_header;
+ if (!bpf_insn_is_cond_jump(insn->code) || BPF_OP(insn->code) == BPF_JCOND)
+ return 0;
+ if (BPF_SRC(insn->code) == BPF_X)
+ src = e->reg2expr[insn->src_reg];
+ bitmap_copy(live, aux->live_stack_before, MAX_BPF_STACK_SLOTS);
+ bitmap_shift_left(live, live, MAX_BPF_REG, REGS_NUM);
+ live[0] |= aux->live_regs_before;
+ for (r = REGS_NUM; r < ENV_REGS_NUM; r++)
+ if (e->mem_addr[r - REGS_NUM])
+ __set_bit(r, live);
+ split_const_offset(env, dst, &base_dst, &delta, &bits);
+ split_const_offset(env, src, &base_src, &delta, &bits);
+ for_each_set_bit(r, live, ENV_REGS_NUM) {
+ id = e->reg2expr[r];
+ /* most are not linked */
+ split_const_offset(env, id, &base, &delta, &bits);
+ if (base != base_dst && base != base_src && !is_op(scev, base, BPF_ADD) &&
+ (h < 0 || !is_op(scev, base, REG)) && !is_big_endian_slot(r))
+ continue;
+ if (const_diff_reg(env, h, dst, r, id, &fill_off, &delta, &bits) ||
+ (src != dst && const_diff_reg(env, h, src, r, id, &fill_off, &delta, &bits))) {
+ __set_bit(r, found);
+ continue;
+ }
+ if (!match_linked_add(env, h, dst, id, &other, &delta, &bits) &&
+ (src == dst || !match_linked_add(env, h, src, id, &other, &delta, &bits)))
+ continue;
+ /* an add is of use only with a live register that holds its other operand */
+ for_each_set_bit(q, live, REGS_NUM) {
+ if (q == r || !const_diff(env, h, e->reg2expr[q], other, &delta, &bits))
+ continue;
+ __set_bit(r, found);
+ __set_bit(q, found);
+ break;
+ }
}
- succ_env = get_loop_env(scev, cur_header, succ_idx);
- if (!succ_env)
- return -ENOMEM;
- if (log_level2)
- memcpy(old_env, succ_env, sizeof(*old_env));
- err = join(scev, succ_env, cur_env);
- if (err)
- return err;
- err = worklist_push(env, cur_header, succ_idx);
- if (err)
- return err;
- if (log_level2)
- log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
+ /* the main pass finds memory by a live register that holds its address */
+ for (r = REGS_NUM; r < ENV_REGS_NUM; r++) {
+ if (!test_bit(r, found))
+ continue;
+ q = find_leader(env, e, h, live, e->mem_addr[r - REGS_NUM]);
+ if (q < REGS_NUM)
+ __set_bit(q, found);
+ else
+ __clear_bit(r, found);
+ }
+ for_each_set_bit(r, found, ENV_REGS_NUM) {
+ if (scev->linked_cnt == scev->linked_cap) {
+ cap = max(scev->linked_cap * 2, 16);
+ tmp = kvrealloc(scev->linked, array_size(cap, sizeof(*scev->linked)),
+ GFP_KERNEL_ACCOUNT);
+ if (!tmp)
+ return -ENOMEM;
+ scev->linked = tmp;
+ scev->linked_cap = cap;
+ }
+ tested += r == insn->dst_reg || (src != dst && r == insn->src_reg);
+ scev->linked[scev->linked_cnt].reg = r;
+ scev->linked[scev->linked_cnt].addr = r < REGS_NUM ? 0 : e->mem_addr[r - REGS_NUM];
+ scev->linked[scev->linked_cnt++].id = e->reg2expr[r];
+ }
+ /* nothing but the tested registers */
+ if (scev->linked_cnt - first == tested) {
+ scev->linked_cnt = first;
+ return 0;
+ }
+ if (!envs) {
+ envs = kzalloc(sizeof(*envs), GFP_KERNEL_ACCOUNT);
+ if (!envs)
+ return -ENOMEM;
+ scev->envs[idx] = envs;
+ }
+ envs->linked_first = first;
+ envs->linked_cnt = scev->linked_cnt - first;
return 0;
}
/*
- * Unsupported loops get only an unknown header environment.
- * A nested loop is processed as a single instruction, its exits are the successors: all of
- * them are needed. No result for the loop itself depends on the list of its own exits:
- * mark_latches() prepares them for the loop around, and compute_max_iters() asks if there is
- * only one, which a list that is cut does not have.
+ * Find the next SCEV register that is linked to @regno at the conditional jump at @insn_idx: on
+ * every path to the jump *@linked_regno == @regno + *@delta (mod 2^*@bits). It is live there and of
+ * the same frame. It is a register, or MAX_BPF_REG + the index of a stack slot: a fill from byte
+ * *@fill_off of the slot reads these bits. *@pos is the position of the search, 0 at first. False:
+ * no more links are known. Types are not known here: the caller checks them in its state.
+ * A linked register can be a pointer: *base_regno + regno + delta. *base_regno is the address base,
+ * as in store_base_regs. It is -1 for a link without a base.
+ * BPF_SCEV_REGS_NUM and above is a memory location, see struct env and bpf_scev_mem_addr().
*/
-static bool can_compute_loop_scev(const struct bpf_loop *loop)
+bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *pos,
+ u32 *linked_regno, u32 *fill_off, int *base_regno, s64 *delta,
+ u32 *bits)
{
- return !loop->irreducible && !loop->nested_exits_overflow;
+ struct insn_envs *envs = env->scev->envs[insn_idx];
+ int h = bpf_loop_at_index(env, insn_idx);
+ struct scev_linked_reg *linked;
+ u32 i, j, other, b;
+ s64 c;
+
+ if (!envs || !envs->linked_cnt)
+ return false;
+ linked = &env->scev->linked[envs->linked_first];
+ /* registers come first */
+ for (i = 0; linked[i].reg != regno; i++)
+ if (i + 1 == envs->linked_cnt || linked[i].reg > regno)
+ return false;
+ for (; *pos < envs->linked_cnt; ++*pos) {
+ *linked_regno = linked[*pos].reg;
+ *base_regno = -1;
+ if (*pos == i)
+ continue;
+ if (const_diff_reg(env, h, linked[i].id, *linked_regno, linked[*pos].id, fill_off,
+ delta, bits))
+ return true;
+ if (!match_linked_add(env, h, linked[i].id, linked[*pos].id, &other, delta, bits))
+ continue;
+ for (j = 0; j < envs->linked_cnt; j++) {
+ if (j == *pos || !const_diff(env, h, linked[j].id, other, &c, &b))
+ continue;
+ *base_regno = linked[j].reg;
+ *delta = (u64)*delta + c;
+ *bits = min(*bits, b);
+ return true;
+ }
+ }
+ return false;
+}
+
+/*
+ * The memory location @regno is a linked register of the conditional jump at @insn_idx. Its address
+ * is *@base_regno + *@off. *@base_regno is a live register or stack slot. Which memory it is
+ * depends on the state.
+ */
+bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,
+ s64 *off)
+{
+ struct insn_envs *envs = env->scev->envs[insn_idx];
+ struct scev_linked_reg *linked = &env->scev->linked[envs->linked_first];
+ int h = bpf_loop_at_index(env, insn_idx);
+ u32 i, j, bits;
+
+ for (i = 0; linked[i].reg != regno; i++)
+ if (i + 1 == envs->linked_cnt)
+ return false;
+ for (j = 0; linked[j].reg < REGS_NUM; j++) {
+ if (!const_diff(env, h, linked[j].id, linked[i].addr, off, &bits) || bits != 64)
+ continue;
+ *base_regno = linked[j].reg;
+ return true;
+ }
+ return false;
}
-static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
+/*
+ * @cur_header and @first are a loop header. Or -1 and the first insn of a subprog: the subprog is
+ * the outermost loop, which runs once. (REG r) is the entry value of r, the loops in it are single
+ * instructions.
+ * Value numbering works on any CFG: the body of an irreducible loop is walked like any other. Every
+ * retreating edge of the depth-first search goes to a loop header, see compute_loops_in_subprog(),
+ * and bpf_compute_postorder() does the same search. So reverse post-order is a topological order of
+ * this body too.
+ */
+static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header, int first)
{
struct scev_worklist *worklist = &env->scev->worklist;
struct bpf_insn_aux_data *aux = env->insn_aux_data;
- struct bpf_loop *cur_loop = aux[cur_header].loop;
+ struct bpf_loop *cur_loop = cur_header < 0 ? NULL : aux[cur_header].loop;
+ struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, first);
struct env *header_env;
struct scev *scev = env->scev;
struct bpf_loop *nested_loop;
@@ -1342,26 +2425,15 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
struct env *old_env = NULL;
struct bpf_iarray *succ;
bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
- int s, i, err, idx, succ_idx;
+ int s, i, err, idx, succ_idx, start;
u32 r;
if (log_level2)
- bpf_log(&env->log, "Computing SCEV for loop at %d:\n", cur_header);
+ bpf_log(&env->log, "Computing SCEV for %s at %d:\n",
+ cur_loop ? "loop" : "subprog", first);
- /*
- * For irreducible loops, and for loops nesting a loop with a truncated
- * exit list, just assume that everything is clobbered for now.
- */
- if (!can_compute_loop_scev(cur_loop)) {
- header_env = get_loop_env(scev, cur_header, cur_header);
- if (!header_env)
- return -ENOMEM;
- /* The freshly allocated environment has all expressions unknown. */
- bitmap_fill(cur_loop->store_base_regs, REGS_NUM);
- bitmap_fill(cur_loop->tested_regs, REGS_NUM);
- header_env->empty = false;
+ if (!cur_loop && !can_compute_subprog_scev(env, sub))
return 0;
- }
cur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);
if (!cur_env)
@@ -1371,19 +2443,33 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
if (!old_env)
goto nomem;
}
- header_env = get_loop_env(scev, cur_header, cur_header);
+ header_env = get_loop_env(scev, cur_header, first);
if (!header_env)
goto nomem;
- err = setup_initial_loop_env(env, header_env, cur_header);
- if (err)
- goto out;
- err = worklist_push(env, cur_header, cur_header);
- if (err)
- goto out;
+ setup_initial_loop_env(header_env);
+ /* The successors of a nested loop with a truncated exit list are not known: no walk */
+ if (!cur_loop || !cur_loop->nested_exits_overflow) {
+ err = worklist_push(env, cur_header, first);
+ if (err)
+ goto out;
+ }
+ if (!cur_loop) {
+ /* no backedge overwrites it */
+ header_env->empty = false;
+ err = join_added_edges(env, sub, old_env, cur_env);
+ if (err)
+ goto out;
+ }
while (worklist->nr) {
idx = *min_heap_peek_inline(worklist);
min_heap_pop_inline(worklist, &worklist_cb, env->cfg.postorder_nums);
+ start = idx;
+ if (signal_pending(current)) {
+ err = -EAGAIN;
+ goto out;
+ }
+ cond_resched();
/* join_successor() maps nested-loop entries to their representative header. */
nested_loop = idx != cur_header ? aux[idx].loop : NULL;
@@ -1395,13 +2481,19 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
*/
if (log_level2)
memcpy(old_env, cur_env, sizeof(*old_env));
- /* Pull the nested loop's stack-store base dependencies up. */
- for_each_set_bit(r, nested_loop->store_base_regs, BPF_SCEV_REGS_NUM)
- or_expr_regs(env, cur_env->reg2expr[r], cur_loop->store_base_regs);
- /* And what its jumps depend on. */
- for_each_set_bit(r, nested_loop->tested_regs, BPF_SCEV_REGS_NUM)
- or_expr_regs(env, cur_env->reg2expr[r], cur_loop->tested_regs);
- forget_non_invariants(env, cur_env, idx);
+ if (cur_loop) {
+ /* Pull the nested loop's stack-store base dependencies up. */
+ for_each_set_bit(r, nested_loop->store_base_regs, BPF_SCEV_REGS_NUM)
+ or_expr_regs(env, cur_env->reg2expr[r],
+ cur_loop->store_base_regs);
+ /* And what its jumps depend on. */
+ for_each_set_bit(r, nested_loop->tested_regs, BPF_SCEV_REGS_NUM)
+ or_expr_regs(env, cur_env->reg2expr[r],
+ cur_loop->tested_regs);
+ }
+ err = forget_non_invariants(env, cur_env, idx);
+ if (err)
+ goto out;
if (log_level2)
log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
/*
@@ -1422,12 +2514,24 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
for (;;) {
if (log_level2)
memcpy(old_env, cur_env, sizeof(*old_env));
- collect_store_base_regs(env, cur_env, idx, cur_loop->store_base_regs);
- collect_tested_regs(env, cur_env, idx, cur_loop->tested_regs);
+ if (cur_loop) {
+ collect_store_base_regs(env, cur_env, idx,
+ cur_loop->store_base_regs);
+ collect_tested_regs(env, cur_env, idx,
+ cur_loop->tested_regs);
+ }
+ /* the others wait for the envs of all loop headers */
+ if (!aux[idx].need_scev) {
+ err = find_linked_regs(env, cur_env, -1, idx);
+ if (err)
+ goto out;
+ }
err = transfer(env, cur_env, idx);
if (err)
goto out;
- reset_scevs_at_indirect_writes(env, cur_env, idx);
+ err = reset_scevs_at_indirect_writes(env, cur_env, idx);
+ if (err)
+ goto out;
if (log_level2)
log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
succ = bpf_insn_successors(env, idx);
@@ -1446,8 +2550,17 @@ static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
goto out;
}
}
+ /* Reverse post-order: all predecessors came first, the env has no users any more */
+ if (!aux[start].need_scev)
+ free_loop_env(scev, cur_header, start);
}
+ /* For the enclosing loop and for the main pass it clobbers everything */
+ if (cur_loop && !can_compute_loop_scev(cur_loop)) {
+ memset(header_env, 0, sizeof(*header_env));
+ bitmap_fill(cur_loop->store_base_regs, REGS_NUM);
+ bitmap_fill(cur_loop->tested_regs, REGS_NUM);
+ }
err = 0;
out:
kfree(cur_env);
@@ -1545,29 +2658,10 @@ static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,
return id < 0 ? id : fn(scev, id, priv);
}
-static int transform_expr(struct scev *scev, u32 root, void *priv,
- int (*fn)(struct scev *scev, u32 id, void *priv))
-{
- int i = 0, id_old, id_new = root;
-
- do {
- /*
- * The depth limit is somewhat arbitrary and is essentially a failsafe.
- * oscillation should not really happen. Still, it seems harsh to error out.
- */
- if (i++ == 4 * EXPR_STACK_DEPTH)
- return UNKNOWN_EXPR_ID;
- id_old = id_new;
- id_new = transform_expr_once(scev, 0, id_old, priv, fn);
- if (id_new < 0)
- return id_new;
- } while (id_old != id_new);
- return id_new;
-}
-
-static int simplify(struct scev *scev, u32 id, void *priv)
+static int simplify(struct scev *scev, u32 id)
{
int a, b, l, r, t, base, slope;
+ u32 op = scev->exprs[id].op, bits = op_low_bits(op);
s64 imm1, imm2;
/* (- x imm) -> (+ x -imm) */
@@ -1575,13 +2669,24 @@ static int simplify(struct scev *scev, u32 id, void *priv)
is_imm(scev, r, &imm1) && imm1 != S64_MIN)
return expr2(scev, BPF_ADD, l, imm_expr(scev, -imm1));
- /* (+ (+ x imm) imm) -> (+ x imm) */
+ /* (+ x 0) -> x */
+ if (is_add(scev, id, &l, &r) && is_imm(scev, r, &imm1) && !imm1)
+ return l;
+
+ /* (+ (+ x imm) imm) -> (+ x imm). Not through a def, see alu64_with_def() */
if (is_add(scev, id, &l, &r) &&
is_imm(scev, r, &imm2) &&
is_add(scev, l, &a, &b) &&
- is_imm(scev, b, &imm1))
+ is_imm(scev, b, &imm1) && !scev->exprs[l].def.set)
return expr2(scev, BPF_ADD, a, imm_expr(scev, (s64)((u64)imm1 + (u64)imm2)));
+ /* 'r1 <<= 32; r1 >>= 32' is (u32)r1 for cpu v1 and v2: (>> (<< x 32) 32) -> (zext32 x) */
+ if (is_binop(scev, BPF_RSH, id, &l, &r) &&
+ is_imm(scev, r, &imm2) && imm2 == 32 &&
+ is_binop(scev, BPF_LSH, l, &a, &b) &&
+ is_imm(scev, b, &imm1) && imm1 == 32 && !scev->exprs[l].def.set)
+ return expr1(scev, ZEXT32, a);
+
/* (+ (linear base slope) imm) -> (linear (+ base imm) slope) */
if (is_add(scev, id, &l, &r) &&
is_linear(scev, l, &base, &slope) &&
@@ -1599,49 +2704,44 @@ static int simplify(struct scev *scev, u32 id, void *priv)
return imm_expr(scev, (u64)(u32)imm1);
/*
- * (zext32 (+ (zext32 $a) $b)) -> (zext32 (+ $a $b))
- * (zext32 (+ $a (zext32 $b))) -> (zext32 (+ $a $b))
+ * An extension and a partial spill depend on the low bits of their operand only: look
+ * through an extension and a partial spill that is not narrower, below an add too:
+ * (sext32 (zext32 $a)) -> (sext32 $a)
+ * (sext8 (spill16 $a)) -> (sext8 $a)
+ * (zext32 (+ (sext32 $a) $b)) -> (zext32 (+ $a $b))
+ * (spill32 (+ $a (zext32 $b))) -> (spill32 (+ $a $b))
*/
- if ((is_zext32(scev, id, &t) && is_add(scev, t, &l, &b) && is_zext32(scev, l, &a)) ||
- (is_zext32(scev, id, &t) && is_add(scev, t, &a, &r) && is_zext32(scev, r, &b))) {
- t = expr2(scev, BPF_ADD, a, b);
- t = expr1(scev, ZEXT32, t);
- return t;
- }
-
- /* (zext32 (zext32 X)) -> (zext32 X) */
- if (is_zext32(scev, id, &a) && is_zext32(scev, a, &b))
- return a;
+ if (!bits)
+ return id;
+ t = scev->exprs[id].params[0];
+ if (is_low_bits(scev, t, bits, &a))
+ return expr1(scev, op, a);
+ if (is_add(scev, t, &l, &r) && !scev->exprs[t].def.phi &&
+ (is_low_bits(scev, l, bits, &l) || is_low_bits(scev, r, bits, &r)))
+ return expr1(scev, op, expr2(scev, BPF_ADD, l, r));
- /*
- * '*(u32 *)(r10 - 8) = rX' stores the low half of rX:
- * (spill32 (zext32 $a)) -> (spill32 $a)
- * (spill32 (+ (zext32 $a) $b)) -> (spill32 (+ $a $b))
- */
- if (is_spill32(scev, id, &t) && is_zext32(scev, t, &a))
- return expr1(scev, SPILL32, a);
- if (is_spill32(scev, id, &t) && is_add(scev, t, &l, &b) && is_zext32(scev, l, &a))
- return expr1(scev, SPILL32, expr2(scev, BPF_ADD, a, b));
+ return id;
+}
- /*
- * 'rX = *(u32 *)(r10 - 8)' loads what was stored:
- * (zext32 (spill32 $a)) -> (zext32 $a)
- * (zext32 (+ (spill32 $a) $b)) -> (zext32 (+ $a $b))
- */
- if (is_zext32(scev, id, &t) && is_spill32(scev, t, &a))
- return expr1(scev, ZEXT32, a);
- if (is_zext32(scev, id, &t) && is_add(scev, t, &l, &b) && is_spill32(scev, l, &a))
- return expr1(scev, ZEXT32, expr2(scev, BPF_ADD, a, b));
+static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
+{
+ u32 reg, *reg2scev = priv;
+ /* (reg r) -> ... equation at header ... */
+ if (is_reg(scev, id, ®))
+ return reg2scev[reg];
+ /* keep expression shapes */
return id;
}
-static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)
+static int compute_header_scevs(struct bpf_verifier_env *env, int h)
{
struct scev *scev = env->scev;
+ struct env *header_env = find_header_env(scev, h);
int l, r, t, id, ra, rb, ra_expr;
bool zext32;
s64 imm;
+ u32 op;
/*
* Note:
@@ -1658,10 +2758,13 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
* ... at exit r1 is in {7,42} ...
*/
for (ra = 0; ra < REGS_NUM; ra++) {
- ra_expr = transform_expr(scev, header_env->reg2expr[ra], NULL, simplify);
+ ra_expr = header_env->reg2expr[ra];
+ /* Constructed again it has no defs, see alu64_with_def(): they hide the shape */
+ if (env->prog->aux->arena)
+ ra_expr = transform_expr_once(scev, 0, ra_expr, scev->identity_env.reg2expr,
+ instantiate_header_scevs);
if (ra_expr < 0)
return ra_expr;
- header_env->reg2expr[ra] = ra_expr;
/* rA = (+ rA IMM) -> (linear rA IMM) */
if (is_add(scev, ra_expr, &l, &r) &&
is_reg(scev, l, &rb) &&
@@ -1673,30 +2776,24 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
header_env->reg2scev[ra] = id;
continue;
}
- /* rA = (is_zext32 (+ rA IMM)) -> (is_zext32 (linear rA IMM)) */
- if (is_zext32(scev, ra_expr, &t) &&
- is_add(scev, t, &l, &r) &&
- is_reg(scev, l, &rb) &&
- is_imm(scev, r, &imm) &&
- ra == rb) {
- id = expr2(scev, LINEAR_SCEV, l, r);
- id = expr1(scev, ZEXT32, id);
- if (id < 0)
- return id;
- header_env->reg2scev[ra] = id;
- continue;
- }
/*
+ * A 32-bit induction variable:
+ * rA = (zext32 (+ rA IMM)) -> (zext32 (linear rA IMM))
+ * rA = (sext32 (+ rA IMM)) -> (sext32 (linear rA IMM))
* rA = (spill32 (+ rA IMM)) -> (spill32 (linear (zext32 rA) IMM))
- * The low half of the slot counts. Nothing is known about the other half.
+ * The last SCEV leaves the upper 32 bits of the slot unknown, so it holds for the
+ * first two as well. They get it if these bits are dead: the states have a
+ * 32-bit spill then, see bpf_clean_verifier_state().
*/
- if (is_spill32(scev, ra_expr, &t) &&
+ if (is_low_bits(scev, ra_expr, 32, &t) &&
is_add(scev, t, &l, &r) &&
is_reg(scev, l, &rb) &&
is_imm(scev, r, &imm) &&
ra == rb) {
- id = expr2(scev, LINEAR_SCEV, expr1(scev, ZEXT32, l), r);
- id = expr1(scev, SPILL32, id);
+ op = hi32_alive_at(env, ra, h) ? scev->exprs[ra_expr].op : SPILL32;
+ if (op == SPILL32)
+ l = expr1(scev, ZEXT32, l);
+ id = expr1(scev, op, expr2(scev, LINEAR_SCEV, l, r));
if (id < 0)
return id;
header_env->reg2scev[ra] = id;
@@ -1709,7 +2806,7 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
}
/* rA = (any 1 2 3 4 ...) -> (any rA 1 2 3 4 ...) */
if (is_any_imm_reg_opaque(scev, ra_expr)) {
- id = mk_any(scev, expr1(scev, REG, ra), ra_expr);
+ id = mk_any(scev, expr1(scev, REG, ra), ra_expr, no_def);
if (id < 0)
return id;
header_env->reg2scev[ra] = id;
@@ -1720,7 +2817,7 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
/*
* do { i++; if (old > 1021) break; c = buf[old]; old = i; } while (c);
* rA = (+ rB IMM) and rB = (+ rB IMM): an iteration leaves the same number in both. If
- * they are equal when the loop is entered rA is at the header what rB is.
+ * they are equal at loop entry too, rA is an induction variable with the same step.
*/
for (ra = 0; ra < REGS_NUM; ra++) {
if (header_env->reg2scev[ra] != UNKNOWN_EXPR_ID ||
@@ -1730,9 +2827,12 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
id = header_env->reg2scev[rb];
if (header_env->reg2expr[rb] != header_env->reg2expr[ra] ||
!is_linear_or_linear32(scev, id, &l, &r, &zext32) ||
- !is_reg(scev, l, &t) || t != rb)
+ !is_reg(scev, l, &t) || t != rb ||
+ !const_diff_at_header(env, h, rb, ra, &imm) || imm)
continue;
- id = expr2(scev, COPY_SCEV, expr1(scev, REG, ra), id);
+ id = expr2(scev, LINEAR_SCEV, expr1(scev, REG, ra), r);
+ if (zext32)
+ id = expr1(scev, ZEXT32, id);
if (id < 0)
return id;
header_env->reg2scev[ra] = id;
@@ -1742,6 +2842,64 @@ static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header
return 0;
}
+/*
+ * Find a SCEV register with the entry value @x and the backedge value @l, and one with @y and @r.
+ * All that match are copies of each other at the header: take the first.
+ */
+static bool find_operands(struct env *entry_env, struct env *header_env, u32 x, u32 y, u32 l, u32 r,
+ u32 *rb, u32 *rc)
+{
+ for (*rb = 0; *rb < REGS_NUM; ++*rb)
+ if (entry_env->reg2expr[*rb] == x && header_env->reg2expr[*rb] == l)
+ break;
+ for (*rc = 0; *rc < REGS_NUM; ++*rc)
+ if (entry_env->reg2expr[*rc] == y && header_env->reg2expr[*rc] == r)
+ break;
+ return *rb < REGS_NUM && *rc < REGS_NUM;
+}
+
+/*
+ * p = buf; i = 0; while (*p) { if (i > 512) break; use(p); i += len(p); p = buf + i; }
+ * rA == rB + rC holds at the header in every iteration: it holds at loop entry and every backedge
+ * preserves it. The backedge values are rA = (+ l r), rB = l, rC = r. The entry values, by the env
+ * of the enclosing loop at @h, are rA = x, rB = x, rC = 0 or rA = (+ x y), rB = x, rC = y.
+ * (add rB rC) keeps the def of (+ l r), see alu64_with_def().
+ */
+static int compute_header_adds(struct bpf_verifier_env *env, int h)
+{
+ struct scev *scev = env->scev;
+ struct env *entry_env = find_loop_env(scev, env->insn_aux_data[h].loop_header, h);
+ struct env *header_env = find_header_env(scev, h);
+ u32 ra, rb, rc, l, r, x, y, entry_expr;
+ struct expr_def def;
+ int id, zero = imm_expr(scev, 0);
+
+ if (zero < 0)
+ return zero;
+ for (ra = 0; entry_env && ra < REGS_NUM; ra++) {
+ entry_expr = entry_env->reg2expr[ra];
+ if (header_env->reg2scev[ra] != UNKNOWN_EXPR_ID ||
+ !is_add(scev, header_env->reg2expr[ra], &l, &r) ||
+ !scev->exprs[entry_expr].is_vn || !scev->exprs[l].is_vn ||
+ !scev->exprs[r].is_vn)
+ continue;
+ if (!find_operands(entry_env, header_env, entry_expr, zero, l, r, &rb, &rc) &&
+ !find_operands(entry_env, header_env, zero, entry_expr, l, r, &rb, &rc) &&
+ (scev->exprs[entry_expr].def.set || !is_add(scev, entry_expr, &x, &y) ||
+ (!find_operands(entry_env, header_env, x, y, l, r, &rb, &rc) &&
+ !find_operands(entry_env, header_env, y, x, l, r, &rb, &rc))))
+ continue;
+ /* expr2() can move exprs[] */
+ def = scev->exprs[header_env->reg2expr[ra]].def;
+ id = expr_with_def(scev, expr2(scev, ADD_SCEV, REG_EXPR_ID(rb), REG_EXPR_ID(rc)),
+ def);
+ if (id < 0)
+ return id;
+ header_env->reg2scev[ra] = id;
+ }
+ return 0;
+}
+
/*
* 'sum += a[i]', 'if (..) { len -= n; len -= 2; }': is 'id', what an iteration makes of
* register 'r', the register plus or minus something, or the register as it was?
@@ -1792,34 +2950,14 @@ static void scev_compute_linear_regs(struct scev *scev, struct bpf_loop *loop,
}
}
-static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
-{
- u32 reg, *reg2scev = priv;
-
- /* (reg r) -> ... equation at header ... */
- if (is_reg(scev, id, ®))
- return reg2scev[reg];
- /* keep expression shapes */
- return id;
-}
-
static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)
{
struct scev *scev = env->scev;
int id, reg;
for (reg = 0; reg < REGS_NUM; reg++) {
- /*
- * Simplify first. 'store, load, test' of a 32-bit counter on the stack with the
- * equation of the header in it is deeper than EXPR_STACK_DEPTH.
- */
- id = transform_expr(scev, einsn->reg2expr[reg], NULL, simplify);
- if (id < 0)
- return id;
- id = transform_expr_once(scev, 0, id, eheader->reg2scev, instantiate_header_scevs);
- if (id < 0)
- return id;
- id = transform_expr(scev, id, NULL, simplify);
+ id = transform_expr_once(scev, 0, einsn->reg2expr[reg], eheader->reg2scev,
+ instantiate_header_scevs);
if (id < 0)
return id;
einsn->reg2scev[reg] = id;
@@ -1861,6 +2999,27 @@ static int log_scevs(struct bpf_verifier_env *env)
return 0;
}
+/*
+ * A slice comes from a call that may write to the buffer: the kfunc, or a subprog that calls it.
+ * See expr_is_vn().
+ */
+static void find_slice_slots(struct bpf_verifier_env *env)
+{
+ struct bpf_insn *insn = env->prog->insnsi;
+ struct scev *scev = env->scev;
+ bool slices = false;
+ u32 i, spi;
+
+ for (i = 0; i < env->prog->len; i++)
+ slices |= bpf_is_dynptr_slice_rdwr_kfunc(&insn[i]);
+ for (i = 0; slices && i < env->prog->len; i++)
+ if (BPF_CLASS(insn[i].code) == BPF_JMP && BPF_OP(insn[i].code) == BPF_CALL)
+ bitmap_or(scev->slice_slots, scev->slice_slots, bpf_may_write_mask(env, i),
+ MAX_BPF_STACK_SLOTS);
+ for_each_set_bit(spi, scev->slice_slots, MAX_BPF_STACK_SLOTS)
+ scev->exprs[REG_EXPR_ID(MAX_BPF_REG + spi)].is_vn = false;
+}
+
int bpf_compute_scev(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux = env->insn_aux_data;
@@ -1869,6 +3028,7 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
int cnt = env->cfg.cur_postorder;
int i, idx, err, header;
+ find_slice_slots(env);
mark_latches(env);
/*
* Visit loop headers in postorder, to guarantee that scevs
@@ -1878,7 +3038,12 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
idx = postorder[i];
if (!aux[idx].loop)
continue;
- err = compute_scev_for_loop(env, idx);
+ err = compute_scev_for_loop(env, idx, idx);
+ if (err)
+ return err;
+ }
+ for (i = 0; i < env->subprog_cnt; i++) {
+ err = compute_scev_for_loop(env, -1, env->subprog_info[i].start);
if (err)
return err;
}
@@ -1892,17 +3057,28 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
idx = postorder[i];
if (!aux[idx].need_scev)
continue;
+ if (signal_pending(current))
+ return -EAGAIN;
+ cond_resched();
header = bpf_loop_at_index(env, idx);
err = aux[idx].loop
- ? compute_header_scevs(env, find_header_env(scev, header))
+ ? compute_header_scevs(env, header)
: compute_insn_scevs(env,
find_header_env(scev, header),
find_loop_env(scev, header, idx));
if (err)
return err;
- if (aux[idx].loop)
+ if (aux[idx].loop) {
scev_compute_linear_regs(scev, aux[idx].loop,
find_header_env(scev, header));
+ err = compute_header_adds(env, idx);
+ if (err)
+ return err;
+ }
+ err = find_linked_regs(env, aux[idx].loop ? &scev->identity_env :
+ find_loop_env(scev, header, idx), header, idx);
+ if (err)
+ return err;
}
/* Now it's known which jumps test a counter: the places of a back edge are for them */
@@ -1919,6 +3095,21 @@ int bpf_compute_scev(struct bpf_verifier_env *env)
return 0;
}
+/*
+ * Are all slots of the buffer [off, off + size) in slice_slots? Without @fixed_off the buffer is
+ * somewhere in the range, and the range can be wider than slice_slots: two offsets become a range
+ * at a join point.
+ */
+bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off)
+{
+ int first = bpf_get_spi(off + size - 1), last = bpf_get_spi(off);
+ const unsigned long *slots = env->scev->slice_slots;
+
+ if (fixed_off)
+ return find_next_zero_bit(slots, last + 1, first) > last;
+ return find_next_bit(slots, last + 1, first) <= last;
+}
+
void bpf_free_scev(struct bpf_verifier_env *env)
{
struct scev *scev = env->scev;
@@ -1936,13 +3127,12 @@ void bpf_free_scev(struct bpf_verifier_env *env)
kfree(envs->entries[j].env);
kfree(envs);
}
- if (scev->exprs_ht)
- for (i = 0; i < scev->exprs_ht_cnt; i++)
- kvfree(scev->exprs_ht[i]);
kvfree(scev->exprs_ht);
+ kvfree(scev->exprs_next);
kvfree(scev->worklist.data);
kvfree(scev->envs);
kvfree(scev->exprs);
+ kvfree(scev->linked);
kvfree(scev->discovered);
kfree(scev);
env->scev = NULL;
@@ -1951,6 +3141,7 @@ void bpf_free_scev(struct bpf_verifier_env *env)
int bpf_init_scev(struct bpf_verifier_env *env)
{
struct scev *scev;
+ u32 r;
scev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);
if (!scev)
@@ -1958,13 +3149,17 @@ int bpf_init_scev(struct bpf_verifier_env *env)
env->scev = scev;
bpf_mark_reg_known_scalar(&scev->zero_reg, 0);
bpf_mark_reg_unknown(&scev->unknown_reg);
- /* A power of two for hash & (exprs_ht_cnt - 1)` indexing. */
- scev->exprs_ht_cnt = roundup_pow_of_two(max(256U, DIV_ROUND_UP(env->prog->len, 4)));
- scev->exprs_ht = kvcalloc(scev->exprs_ht_cnt, sizeof(*scev->exprs_ht), GFP_KERNEL_ACCOUNT);
- if (!scev->exprs_ht)
- goto nomem;
- if (expr0(scev, UNKNOWN) < 0 || expr0(scev, OPAQUE) < 0)
+ setup_initial_loop_env(&scev->identity_env);
+ if (grow_exprs(scev, roundup_pow_of_two(REG_EXPR_ID(REGS_NUM))))
goto nomem;
+ scev->exprs[UNKNOWN_EXPR_ID] = (struct expr){ .op = UNKNOWN };
+ scev->exprs[OPAQUE_EXPR_ID] = (struct expr){ .op = OPAQUE };
+ for (r = 0; r < REGS_NUM; r++)
+ scev->exprs[REG_EXPR_ID(r)] = (struct expr){ .op = REG, .is_vn = true,
+ .params = { r, 0 } };
+ for (r = 0; r < REG_EXPR_ID(REGS_NUM); r++)
+ set_expr_base(scev, &scev->exprs[r], r);
+ scev->exprs_cnt = REG_EXPR_ID(REGS_NUM);
scev->envs = kvcalloc(env->prog->len, sizeof(*scev->envs), GFP_KERNEL_ACCOUNT);
scev->discovered = kvcalloc(env->prog->len, sizeof(*scev->discovered), GFP_KERNEL_ACCOUNT);
if (!scev->envs || !scev->discovered)
@@ -2014,24 +3209,15 @@ static struct bpf_reg_state *scev_reg_for_linear(struct bpf_func_state *st, u32
return &stack->spilled_ptr;
}
-/* Do the registers or stack slots @a and @b hold the same number in @st? */
-static bool scev_regs_equal(struct bpf_func_state *st, u32 a, u32 b)
-{
- const struct bpf_reg_state *ra = scev_reg_for_linear(st, a);
- const struct bpf_reg_state *rb = scev_reg_for_linear(st, b);
-
- if (!ra || !rb || ra->type != SCALAR_VALUE || rb->type != SCALAR_VALUE)
- return false;
- if (tnum_is_const(ra->var_off) && tnum_is_const(rb->var_off))
- return ra->var_off.value == rb->var_off.value;
- return ra->id && ra->id == rb->id && ra->delta == rb->delta;
-}
-
/* '*(u32 *)(r10 - 8) = rX' left a number in the low half of the slot. */
static struct bpf_reg_state *scev_reg_for_spill32(struct bpf_func_state *st, u32 r)
{
struct bpf_stack_state *stack = scev_regno_to_stack(st, r);
+#ifdef __BIG_ENDIAN
+ /* a 32-bit spill is in the upper 32 bits of the slot */
+ return NULL;
+#endif
if (!stack || bpf_spill_size(stack) != 4 || stack->spilled_ptr.type != SCALAR_VALUE)
return NULL;
return &stack->spilled_ptr;
@@ -2140,8 +3326,7 @@ static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_sta
* 'i' is the loop iteration number, starting from 0.
* 'zext32' indicates the latch is for (zext32 (linear ...)) SCEV.
* 'jmp32' indicates that the latch is a JMP32 instruction.
- * 'base_reg' is the register in <base>. 'copy_reg' is -1, or <reg> is made from that register,
- * which has to be equal to 'base_reg' at the entry of the loop, see COPY_SCEV.
+ * 'base_reg' is the register in <base>.
*/
struct linear_latch {
u32 insn_idx;
@@ -2149,7 +3334,6 @@ struct linear_latch {
u32 step_expr;
u32 bound_expr;
u32 base_reg;
- int copy_reg;
u8 op;
bool zext32;
bool jmp32;
@@ -2173,7 +3357,7 @@ static int match_linear_latch(struct bpf_verifier_env *env,
struct env *latch_env;
u32 src_reg_scev;
u32 dst_reg_scev;
- u32 t, l, r, op;
+ u32 l, r, op;
int id;
op = BPF_OP(insn->code);
@@ -2203,11 +3387,6 @@ static int match_linear_latch(struct bpf_verifier_env *env,
return -EFAULT;
dst_reg_scev = latch_env->reg2scev[insn->dst_reg];
src_reg_scev = latch_env->reg2scev[insn->src_reg];
- latch->copy_reg = -1;
- if (is_copy(scev, dst_reg_scev, &latch->copy_reg, &t))
- dst_reg_scev = t;
- else if (BPF_SRC(insn->code) == BPF_X && is_copy(scev, src_reg_scev, &latch->copy_reg, &t))
- src_reg_scev = t;
/*
* Make sure (linear ...) is in dst_reg_scev:
* 'if <invariant> <op> <linear>' ⇔
@@ -2905,8 +4084,6 @@ static bool compute_max_iters(struct bpf_verifier_env *env,
iters->iv_reg = -1;
- if (latch->copy_reg >= 0 && !scev_regs_equal(st, latch->copy_reg, latch->base_reg))
- return false;
if (!eval_expr(env, scev, st, latch->base_expr, &initial_val) ||
!eval_expr(env, scev, st, latch->step_expr, &step_val) ||
!eval_expr(env, scev, st, latch->bound_expr, &bound_val))
@@ -3051,7 +4228,7 @@ static bool is_unbound_scev_reg(struct bpf_verifier_env *env, const struct bpf_f
{
const struct bpf_reg_state *reg = scev_reg_for_read(env, st, r);
- return reg && reg->type == SCALAR_VALUE && !reg->id && reg->step <= 1 &&
+ return reg && reg->type == SCALAR_VALUE && reg->step <= 1 &&
tnum_is_unknown(reg->var_off) &&
reg->r64.size == U64_MAX && reg->r32.size == U32_MAX;
}
@@ -3114,7 +4291,7 @@ static bool is_const_scev_reg(struct bpf_verifier_env *env, int insn_idx, u32 r)
}
/* Main logic in verifier.c forbids varying offsets for certain register types. */
-static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
+bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg)
{
if (type_may_be_null(reg->type))
return false;
@@ -3137,9 +4314,6 @@ static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
static void scratch_widened_reg_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
{
switch (base_type(reg->type)) {
- case SCALAR_VALUE:
- clear_scalar_id(reg);
- break;
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
reg->id = ++env->id_gen;
@@ -3161,7 +4335,7 @@ static bool is_widenable_any(struct bpf_verifier_env *env, struct bpf_func_state
if (!is_any(scev, id, &l, &rr))
return false;
reg = scev_reg_for_read(env, loop_entry, r);
- if (!reg || !is_widenable_reg_type(reg))
+ if (!reg || !bpf_is_widenable_reg_type(reg))
return false;
scev->stack_sz = 0;
@@ -3219,8 +4393,10 @@ struct linear_coefs {
u32 base_reg;
s64 slope;
bool zext32;
- /* the low half of a stack slot */
+ /* with zext32: the low 32 bits of a stack slot */
bool spill32;
+ /* with zext32: the low 32 bits are sign extended */
+ bool sext32;
};
static bool is_simple_slope(struct scev *scev, u32 id, s64 *slope)
@@ -3236,55 +4412,25 @@ static bool is_simple_linear(struct scev *scev, u32 id, struct linear_coefs *out
u32 base, slope;
out->spill32 = false;
- return is_linear_or_linear32(scev, id, &base, &slope, &out->zext32) &&
- is_reg(scev, base, &out->base_reg) &&
+ out->sext32 = is_unop(scev, SEXT32, id, &id);
+ if (!is_linear_or_linear32(scev, id, &base, &slope, &out->zext32) ||
+ (out->sext32 && out->zext32))
+ return false;
+ out->zext32 |= out->sext32;
+ return is_reg(scev, base, &out->base_reg) &&
is_simple_slope(scev, slope, &out->slope);
}
/*
- * Is @r 'what it is in @st + slope * k' at the header in iteration k? @id is its SCEV there, @st is
- * the state that entered the loop. At a jump in the loop @id can be what another register was at
- * the header. @st says nothing about @r then.
+ * Is @r 'its entry value + slope * k' at the header in iteration k? @id is its SCEV there. At a
+ * jump in the loop @id can be linear in the entry value of another register: the entry value of @r
+ * does not bound it then.
*/
-static bool is_linear_at_header(struct scev *scev, struct bpf_func_state *st, u32 id, u32 r,
- struct linear_coefs *out)
+static bool is_linear_at_header(struct scev *scev, u32 id, u32 r, struct linear_coefs *out)
{
- u32 copy, orig;
-
- if (is_copy(scev, id, ©, &orig))
- return copy == r && is_simple_linear(scev, orig, out) &&
- scev_regs_equal(st, r, out->base_reg);
return is_simple_linear(scev, id, out) && out->base_reg == r;
}
-/*
- * @st is at the header of a loop that @entry entered. A copy of an induction variable is equal to
- * it there in every iteration. They got their ranges one by one: give them one id, like 'r2 = r1'
- * does, so that a test of one of them is a test of both.
- */
-static void link_copies(struct bpf_verifier_env *env, struct env *header_env,
- struct bpf_func_state *entry, struct bpf_func_state *st)
-{
- struct bpf_reg_state *reg, *orig;
- struct linear_coefs coefs;
- u32 r;
-
- for (r = 0; r < REGS_NUM; r++) {
- if (!is_linear_at_header(env->scev, entry, header_env->reg2scev[r], r, &coefs) ||
- coefs.base_reg == r)
- continue;
- reg = scev_reg_for_linear(st, r);
- orig = scev_reg_for_linear(st, coefs.base_reg);
- if (!reg || !orig || reg->type != SCALAR_VALUE || orig->type != SCALAR_VALUE ||
- tnum_is_const(orig->var_off))
- continue;
- if (!orig->id)
- orig->id = ++env->id_gen;
- reg->id = orig->id;
- reg->delta = orig->delta;
- }
-}
-
/*
* A 32-bit counter that lives on the stack: the SCEV of slot @r is
* (spill32 (linear (zext32 @r) slope)) and there is a 32-bit number in the slot in @st.
@@ -3303,6 +4449,7 @@ static struct bpf_reg_state *spill32_counter(struct scev *scev, struct bpf_func_
return NULL;
out->zext32 = true;
out->spill32 = true;
+ out->sext32 = false;
return scev_reg_for_spill32(st, r);
}
@@ -3311,6 +4458,11 @@ static struct cnum64 cnum64_zext32(struct cnum32 r32)
return cnum64_from_urange(cnum32_umin(r32), cnum32_umax(r32));
}
+static struct cnum64 cnum64_sext32(struct cnum32 r32)
+{
+ return cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32));
+}
+
/* Compute the range an induction variable in `reg` spans over the loop. */
static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,
struct linear_coefs *coefs, struct bounds *out)
@@ -3340,12 +4492,14 @@ static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,
r32 = CNUM32_UNBOUNDED;
if (coefs->zext32) {
r32 = cnum32_from_cnum64(r64);
- r64 = cnum64_zext32(r32);
+ r64 = coefs->sext32 ? cnum64_sext32(r32) : cnum64_zext32(r32);
/*
* 32-bit iteration overflow is equivalent to subtracting N * 2**32:
* (base + slope * k) % slope ≠ (base + slope * k - N * 2**32) % slope.
*/
- overflow |= cnum32_contains(r32, 0) && cnum32_contains(r32, U32_MAX);
+ overflow |= coefs->sext32 ?
+ cnum32_contains(r32, S32_MAX) && cnum32_contains(r32, S32_MIN) :
+ cnum32_contains(r32, 0) && cnum32_contains(r32, U32_MAX);
/*
* The entry and zero-extended values must agree on how they define `base`,
* otherwise `base + slope * k` would define different sets of points between
@@ -3376,10 +4530,27 @@ static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count,
out->r32 = r32;
}
-static void iv_bounds(struct bounds *bounds, struct cnum64 iv_range)
+/*
+ * Is @r the induction variable that the latch tests, or congruent to it: equal to it at the header
+ * of the loop at @h in every iteration? Then the range of the one is the range of the other.
+ */
+static bool is_iv_at_header(struct bpf_verifier_env *env, int h, int iv_reg, u32 r)
+{
+ s64 delta;
+
+ if (iv_reg < 0)
+ return false;
+ return r == iv_reg || (const_diff_at_header(env, h, iv_reg, r, &delta) && !delta);
+}
+
+static void iv_bounds(struct bounds *bounds, const struct linear_coefs *coefs,
+ struct cnum64 iv_range)
{
struct cnum64 r64 = cnum64_intersect(bounds->r64, iv_range);
+ /* The latch bounds the zero extension. With bit 31 set the sign extension differs. */
+ if (coefs->sext32 && cnum64_umax(iv_range) > S32_MAX)
+ return;
if (!cnum64_is_empty(r64))
bounds->r64 = r64;
}
@@ -3693,8 +4864,8 @@ int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_sta
continue;
}
/* If SCEV for r is (linear <reg> <slope>) */
- if (reg && is_linear_at_header(scev, cur_func, r_scev, r, &coefs) &&
- is_widenable_reg_type(reg)) {
+ if (reg && is_linear_at_header(scev, r_scev, r, &coefs) &&
+ bpf_is_widenable_reg_type(reg)) {
/* 32-bit ALU operations on pointers convert them to scalars */
if (coefs.zext32 && reg->type != SCALAR_VALUE)
goto cant_widen;
@@ -3891,7 +5062,7 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
if (back && (!val || !entry_val || !bpf_reg_union_compatible(val, entry_val)))
continue;
if (test_bit(r, iters->mask_regs)) {
- /* The range stays. It's no longer equal to the registers with its id. */
+ /* the range stays */
err = scev_reg_for_write(env, cur_func, r, ®);
if (!err && back)
err = bpf_reg_union(env, reg, entry_val);
@@ -3903,13 +5074,12 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
bpf_log(log, " stays in 0..%llu, it loses bits only\n",
reg_umax(reg));
}
- scratch_widened_reg_id(env, reg);
mark_scev_reg_scratched(env, r);
continue;
}
/* If SCEV for r is (linear <reg> <slope>)*/
- if (spill32 || is_linear_at_header(scev, entry_func, r_expr, r, &coefs)) {
+ if (spill32 || is_linear_at_header(scev, r_expr, r, &coefs)) {
/* the range is derived from @loop_entry: bpf_clamp_scev_regs() */
if (back)
continue;
@@ -3919,8 +5089,8 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
if (err)
return err;
linear_bounds(reg, iters->max_header_count, &coefs, &bounds);
- if (coefs.base_reg == iters->iv_reg)
- iv_bounds(&bounds, iters->iv_range);
+ if (is_iv_at_header(env, insn_idx, iters->iv_reg, coefs.base_reg))
+ iv_bounds(&bounds, &coefs, iters->iv_range);
if (log->level & BPF_LOG_LEVEL2) {
bpf_log(log, "loop header at %d, widening ", insn_idx);
log_reg(env, r);
@@ -3957,7 +5127,6 @@ int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state
mark_scev_reg_scratched(env, r);
}
}
- link_copies(env, header_env, entry_func, cur_func);
return 1;
}
@@ -3967,6 +5136,7 @@ static bool is_moved_linear(struct scev *scev, u32 id, struct linear_coefs *out,
u32 base, slope, l, r;
out->spill32 = false;
+ out->sext32 = false;
return is_linear_or_linear32(scev, id, &base, &slope, &out->zext32) && !out->zext32 &&
is_add(scev, base, &l, &r) && is_reg(scev, l, &out->base_reg) &&
is_imm(scev, r, moved) && is_simple_slope(scev, slope, &out->slope);
@@ -4014,7 +5184,7 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur
goto clamp;
/* If SCEV for r is (linear <reg> <slope>)*/
- if (!is_linear_at_header(scev, entry_st, r_scev, r, &coefs) &&
+ if (!is_linear_at_header(scev, r_scev, r, &coefs) &&
!(behind && is_moved_linear(scev, r_scev, &coefs, &moved) &&
coefs.base_reg == r))
continue;
@@ -4037,13 +5207,17 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur
* bpf_compute_loop_iters() gives no range to a pointer to arena that moves, and
* it does not look at dead registers. Set a range only where it would.
*/
- if (!is_widenable_reg_type(entry_reg) ||
+ if (!bpf_is_widenable_reg_type(entry_reg) ||
(coefs.zext32 && entry_reg->type != SCALAR_VALUE))
continue;
clamp:
linear_bounds(entry_reg, max_header_count, &coefs, &bounds);
- if (coefs.base_reg == entry->iv_reg && !moved)
- iv_bounds(&bounds, entry->iv_range);
+ /*
+ * iv_range is the range at the header. After the latch @r can be the zero extension
+ * of its header value. @reg went through that insn and has what holds of the range.
+ */
+ if (!behind && is_iv_at_header(env, insn_idx, entry->iv_reg, coefs.base_reg))
+ iv_bounds(&bounds, &coefs, entry->iv_range);
if (moved) {
/* a sum that can wrap has another residue, see scalar_step_add() */
if (check_add_overflow(cnum64_smin(bounds.r64), moved, &sum) ||
@@ -4084,8 +5258,5 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur
return err;
mark_scev_reg_scratched(env, r);
}
- /* behind the jump the variable may have moved on: its copy is what it was at the head */
- if (!behind)
- link_copies(env, header_env, entry_st, cur_func_state);
return 0;
}
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index efc0870b85c2a3..48359e789faadb 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -58,7 +58,7 @@ static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
return true;
/* a name of what the caller has, see BPF_INHERITED_ID */
- if (((old_id | cur_id) & ~BPF_ADD_CONST) >= BPF_INHERITED_ID)
+ if ((old_id | cur_id) >= BPF_INHERITED_ID)
return old_id == cur_id;
for (i = 0; i < idmap->cnt; i++) {
@@ -85,49 +85,6 @@ static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
return false;
}
-/*
- * Compare scalar register IDs for state equivalence.
- *
- * When old_id == 0, the old register is independent - not linked to any
- * other register. Any linking in the current state only adds constraints,
- * making it more restrictive. Since the old state didn't rely on any ID
- * relationships for this register, it's always safe to accept cur regardless
- * of its ID. Hence, return true immediately.
- *
- * When old_id != 0 but cur_id == 0, we need to ensure that different
- * independent registers in cur don't incorrectly satisfy the ID matching
- * requirements of linked registers in old.
- *
- * Example: if old has r6.id=X and r7.id=X (linked), but cur has r6.id=0
- * and r7.id=0 (both independent), without temp IDs both would map old_id=X
- * to cur_id=0 and pass. With temp IDs: r6 maps X->temp1, r7 tries to map
- * X->temp2, but X is already mapped to temp1, so the check fails correctly.
- *
- * When old_id has BPF_ADD_CONST set, the compound id (base | flag) and the
- * base id (flag stripped) must both map consistently. Example: old has
- * r2.id=A, r3.id=A|flag (r3 = r2 + delta), cur has r2.id=B, r3.id=C|flag
- * (r3 derived from unrelated r4). Without the base check, idmap gets two
- * independent entries A->B and A|flag->C|flag, missing that A->C conflicts
- * with A->B. The base ID cross-check catches this.
- */
-static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
-{
- if (!old_id)
- return true;
-
- cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
-
- if (!check_ids(old_id, cur_id, idmap))
- return false;
- if (old_id & BPF_ADD_CONST) {
- old_id &= ~BPF_ADD_CONST;
- cur_id &= ~BPF_ADD_CONST;
- if (!check_ids(old_id, cur_id, idmap))
- return false;
- }
- return true;
-}
-
static void __clean_func_state(struct bpf_verifier_env *env,
struct bpf_func_state *st,
u16 live_regs, int frame)
@@ -168,6 +125,16 @@ static void __clean_func_state(struct bpf_verifier_env *env,
stype == STACK_IRQ_FLAG)
continue;
+ /*
+ * When the half-slot closer to FP is dead, what remains of a
+ * 64-bit spill looks like a 32-bit spill: the low 32 bits of
+ * the value. On big endian the other half-slot holds the upper
+ * 32 bits.
+ */
+ if (hi_live && bpf_spill_size(bpf_stack_slot(st, i)) == BPF_REG_SIZE &&
+ !bpf_stack_narrow_access_ok(0, BPF_REG_SIZE / 2, BPF_REG_SIZE))
+ continue;
+
/*
* Only scalar spills can be degraded to raw stack bytes
* when their high half is dead. Pointer spills need the
@@ -262,65 +229,8 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
/* explore_alu_limits disables tnum_in() and range_within()
* logic and requires everything to be strict
*/
- return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
- check_scalar_ids(rold->id, rcur->id, idmap);
+ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0;
}
- /*
- * Linked register tracking uses rold->id to detect relationships.
- * When rold->id == 0, the register is independent and any linking
- * in rcur only adds constraints. When rold->id != 0, we must verify
- * id mapping and (for BPF_ADD_CONST) offset consistency.
- *
- * +------------------+-----------+------------------+---------------+
- * | | rold->id | rold + ADD_CONST | rold->id == 0 |
- * |------------------+-----------+------------------+---------------|
- * | rcur->id | range,ids | false | range |
- * | rcur + ADD_CONST | false | range,ids,off | range |
- * | rcur->id == 0 | range,ids | false | range |
- * +------------------+-----------+------------------+---------------+
- *
- * Why check_ids() for scalar registers?
- *
- * Consider the following BPF code:
- * 1: r6 = ... unbound scalar, ID=a ...
- * 2: r7 = ... unbound scalar, ID=b ...
- * 3: if (r6 > r7) goto +1
- * 4: r6 = r7
- * 5: if (r6 > X) goto ...
- * 6: ... memory operation using r7 ...
- *
- * First verification path is [1-6]:
- * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
- * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
- * r7 <= X, because r6 and r7 share same id.
- * Next verification path is [1-4, 6].
- *
- * Instruction (6) would be reached in two states:
- * I. r6{.id=b}, r7{.id=b} via path 1-6;
- * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
- *
- * Use check_ids() to distinguish these states.
- * ---
- * Also verify that new value satisfies old value range knowledge.
- */
-
- /*
- * ADD_CONST flags must match exactly: BPF_ADD_CONST32 and
- * BPF_ADD_CONST64 have different linking semantics in
- * sync_linked_regs() (alu32 zero-extends, alu64 does not),
- * so one doesn't stand for the other.
- */
- if (rold->id &&
- (rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
- return false;
-
- /* Both have offset linkage: offsets must match */
- if ((rold->id & BPF_ADD_CONST) && rold->delta != rcur->delta)
- return false;
-
- if (!check_scalar_ids(rold->id, rcur->id, idmap))
- return false;
-
return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_KEY:
case PTR_TO_MAP_VALUE:
@@ -446,11 +356,19 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
if (!cur_slot)
return false;
+ /*
+ * The old spill is the first bytes of a wider spill. On big endian
+ * these are not the low bytes of the value.
+ */
+ if (old_type == STACK_SPILL && bpf_is_spilled_reg(cur_slot) &&
+ !bpf_stack_narrow_access_ok(0, bpf_spill_size(old_slot),
+ bpf_spill_size(cur_slot)))
+ return false;
+
/*
* 64 and 32-bit scalar spills vs MISC/INVALID slots and vice versa.
* Load from MISC/INVALID slots produces unbound scalar.
- * Construct a fake register for such stack and call
- * regsafe() to ensure scalar ids are compared.
+ * Construct a fake register for such stack and call regsafe().
*/
if (im == 0 || im == 4) {
old_reg = scalar_reg_for_stack(env, old_slot, im);
@@ -717,7 +635,6 @@ static void reset_idmap_scratch(struct bpf_verifier_env *env)
{
struct bpf_idmap *idmap = &env->idmap_scratch;
- idmap->tmp_id_gen = env->id_gen;
idmap->cnt = 0;
}
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 9004f2673ccf96..04a3b3c80c74e0 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -6692,7 +6692,7 @@ static const struct bpf_func_proto bpf_sys_bpf_proto = {
.might_sleep = true,
.ret_type = RET_INTEGER,
.arg1_type = ARG_ANYTHING,
- .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
+ .arg2_type = ARG_PTR_TO_MEM | MEM_WRITE,
.arg3_type = ARG_MEM_SIZE,
};
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 20b1b9ff574c7d..d549644235c55a 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -2325,6 +2325,36 @@ static bool range_bounds_violation(struct bpf_reg_state *reg)
return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
}
+/* Do @t and [min, max] overlap: is a member of @t in the range? */
+static bool tnum_overlaps_urange(struct tnum t, u64 min, u64 max)
+{
+ u64 tnum_next = tnum_step(t, min);
+
+ return (min & ~t.mask) == t.value || (tnum_next > min && tnum_next <= max);
+}
+
+/* The same for the cnum [@base, @base + @size]. It wraps around at @ut_max. */
+static bool tnum_overlaps_cnum(struct tnum t, u64 base, u64 size, u64 ut_max)
+{
+ u64 end = (base + size) & ut_max;
+
+ if (base <= end)
+ return tnum_overlaps_urange(t, base, end);
+ return tnum_overlaps_urange(t, base, ut_max) || tnum_overlaps_urange(t, 0, end);
+}
+
+/*
+ * A range and var_off don't overlap. reg_bounds_sync() compares var_off with umin and umax: it
+ * doesn't see that [-2, 1], which crosses 0, has no member with 5 in its low three bits.
+ */
+static bool reg_is_empty(struct bpf_reg_state *reg)
+{
+ return range_bounds_violation(reg) ||
+ !tnum_overlaps_cnum(reg->var_off, reg->r64.base, reg->r64.size, U64_MAX) ||
+ !tnum_overlaps_cnum(tnum_subreg(reg->var_off), reg->r32.base, reg->r32.size,
+ U32_MAX);
+}
+
static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
struct bpf_reg_state *reg, const char *ctx)
{
@@ -3548,30 +3578,6 @@ static void mark_non_stack_access(struct bpf_verifier_env *env, int idx)
env->insn_aux_data[idx].non_stack_access = true;
}
-#define LINKED_REGS_MAX 5
-
-struct linked_reg {
- u8 frameno;
- union {
- u16 spi;
- u16 regno;
- };
- bool is_reg;
-};
-
-struct linked_regs {
- int cnt;
- struct linked_reg entries[LINKED_REGS_MAX];
-};
-
-static struct linked_reg *linked_regs_push(struct linked_regs *s)
-{
- if (s->cnt < LINKED_REGS_MAX)
- return &s->entries[s->cnt++];
-
- return NULL;
-}
-
const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
{
const struct btf_type *func;
@@ -3628,27 +3634,6 @@ static bool __is_pointer_value(bool allow_ptr_leaks,
return is_pointer_regtype(reg->type);
}
-static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
- struct bpf_reg_state *src_reg)
-{
- if (src_reg->type != SCALAR_VALUE)
- return;
- /*
- * The verifier is processing rX = rY insn and
- * rY->id has special linked register already.
- * Cleared it, since multiple rX += const are not supported.
- */
- if (src_reg->id & BPF_ADD_CONST)
- clear_scalar_id(src_reg);
- /*
- * Ensure that src_reg has a valid ID that will be copied to
- * dst_reg and then will be used by sync_linked_regs() to
- * propagate min/max range.
- */
- if (!src_reg->id && !tnum_is_const(src_reg->var_off))
- src_reg->id = ++env->id_gen;
-}
-
static void save_register_state(struct bpf_verifier_env *env,
struct bpf_func_state *state,
int spi, struct bpf_reg_state *reg,
@@ -3675,11 +3660,6 @@ static bool is_bpf_st_mem(struct bpf_insn *insn)
return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
}
-static int get_reg_width(struct bpf_reg_state *reg)
-{
- return fls64(reg_umax(reg));
-}
-
/* See comment for mark_fastcall_pattern_for_call() */
static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
struct bpf_func_state *state, int insn_idx, int off)
@@ -3780,16 +3760,7 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
mark_stack_slot_scratched(env, spi);
if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
- bool reg_value_fits;
-
- reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
- /* Make sure that reg had an ID to build a relation on spill. */
- if (reg_value_fits)
- assign_scalar_id_before_mov(env, reg);
save_register_state(env, state, spi, reg, size);
- /* Break the relation on a narrowing spill. */
- if (!reg_value_fits)
- clear_scalar_id(&ss->spilled_ptr);
} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
env->bpf_capable) {
struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
@@ -4092,19 +4063,8 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
if (dst_regno < 0)
return 0;
- if (env->bpf_capable && size == 4 && spill_size == 4 &&
- get_reg_width(reg) <= 32)
- /* Ensure stack slot has an ID to build a relation
- * with the destination register on fill.
- */
- assign_scalar_id_before_mov(env, reg);
+ /* coerce_reg_to_size will adjust the boundaries. */
state->regs[dst_regno] = *reg;
-
- /* Break the relation on a narrowing fill.
- * coerce_reg_to_size will adjust the boundaries.
- */
- if (get_reg_width(reg) > size * BITS_PER_BYTE)
- clear_scalar_id(&state->regs[dst_regno]);
} else {
int spill_cnt = 0, zero_cnt = 0;
@@ -4149,11 +4109,6 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
}
} else if (dst_regno >= 0) {
/* restore register state from stack */
- if (env->bpf_capable)
- /* Ensure stack slot has an ID to build a relation
- * with the destination register on fill.
- */
- assign_scalar_id_before_mov(env, reg);
state->regs[dst_regno] = *reg;
} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
/* If dst_regno==-1, the caller is asking us whether
@@ -6441,14 +6396,28 @@ static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
{
s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
+ s32 field_smin, field_smax;
u32 top_smax_value, top_smin_value;
u32 num_bits = size * 8;
+ if (size == 1) {
+ field_smin = S8_MIN;
+ field_smax = S8_MAX;
+ } else {
+ /* size == 2 */
+ field_smin = S16_MIN;
+ field_smax = S16_MAX;
+ }
+
/*
- * If value fits the non-negative half of the signed N-bit range,
- * sign extension is a noop.
+ * The range already fits the signed N-bit range, so (sN)v == v for every
+ * value of the low 32 bits and the sign extension is a no-op.
+ *
+ * This has to precede reg_step_reset() below: the base/step line stays.
+ * It is about all 64 bits: zext_32_to_64() in the caller discards it
+ * if the upper 32 bits are not zero.
*/
- if (reg_umax(reg) < (1ULL << (num_bits - 1)))
+ if (reg_s32_min(reg) >= field_smin && reg_s32_max(reg) <= field_smax)
return;
/* See comment at reg_step_check_unsigned(). */
@@ -7669,18 +7638,7 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b
/* b/h/w load zero-extends, mark upper bits as known 0 */
coerce_reg_to_size(®s[value_regno], size);
} else {
- /*
- * Sign-extension can change the register value relative
- * to a scalar it is linked with by id (e.g. a zero-
- * extending fill of the same spilled stack slot), thus
- * drop the shared id in that case.
- */
- bool no_sext = reg_umax(®s[value_regno]) <
- (1ULL << (size * BITS_PER_BYTE - 1));
-
coerce_reg_to_size_sx(®s[value_regno], size);
- if (!no_sext)
- clear_scalar_id(®s[value_regno]);
}
}
@@ -11716,16 +11674,11 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
callee->entry_rcu_locks = entry.active_rcu_locks;
callee->entry_preempt_locks = entry.active_preempt_locks;
for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
- /* what a scalar is linked to stays with the caller, so does the delta to it */
- if (callee->regs[i].type == SCALAR_VALUE)
- clear_scalar_id(&callee->regs[i]);
callee->regs[i].id = inherited_id(state, callee->regs[i].id);
callee->regs[i].parent_id = inherited_id(state, callee->regs[i].parent_id);
callee->regs[i].map_uid = inherited_id(state, callee->regs[i].map_uid);
}
for (i = 0; i < callee->out_stack_arg_cnt; i++) {
- if (callee->stack_arg_regs[i].type == SCALAR_VALUE)
- clear_scalar_id(&callee->stack_arg_regs[i]);
callee->stack_arg_regs[i].id = inherited_id(state, callee->stack_arg_regs[i].id);
callee->stack_arg_regs[i].parent_id =
inherited_id(state, callee->stack_arg_regs[i].parent_id);
@@ -11771,19 +11724,18 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env)
static u32 fresh_id(struct bpf_verifier_env *env, struct bpf_idmap *idmap, u32 id)
{
- u32 flags = id & BPF_ADD_CONST, i;
+ u32 i;
- id &= ~BPF_ADD_CONST;
if (!id)
return 0;
for (i = 0; i < idmap->cnt; i++)
if (idmap->map[i].old == id)
- return idmap->map[i].cur | flags;
+ return idmap->map[i].cur;
if (idmap->cnt == BPF_ID_MAP_SIZE)
return 0;
idmap->map[idmap->cnt].old = id;
idmap->map[idmap->cnt].cur = ++env->id_gen;
- return idmap->map[idmap->cnt++].cur | flags;
+ return idmap->map[idmap->cnt++].cur;
}
/*
@@ -15150,6 +15102,12 @@ bool bpf_is_throw_kfunc(struct bpf_insn *insn)
insn->imm == special_kfunc_list[KF_bpf_throw];
}
+bool bpf_is_dynptr_slice_rdwr_kfunc(struct bpf_insn *insn)
+{
+ return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+ insn->imm == special_kfunc_list[KF_bpf_dynptr_slice_rdwr];
+}
+
static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
{
return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
@@ -15974,6 +15932,15 @@ static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg
regs[BPF_REG_0].buf = meta->slice_buf;
if (meta->slice_buf.size)
env->seen_stack_slice = true;
+ /* No insn stores through a slice of 0 bytes */
+ if (verifier_bug_if(meta->slice_buf.size && meta->arg_constant.value &&
+ !type_is_rdonly_mem(regs[BPF_REG_0].type) &&
+ !bpf_scev_in_slice_slots(env, meta->slice_buf.off,
+ meta->slice_buf.size,
+ meta->slice_buf.size ==
+ meta->arg_constant.value),
+ env, "slice buffer is not in scev slice_slots"))
+ return -EFAULT;
} else {
return 0;
}
@@ -17841,13 +17808,6 @@ static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *ins
/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
bool need_bswap = alu64 || (to_le == is_big_endian);
- /*
- * If the register is mutated, manually reset its scalar ID to break
- * any existing ties and avoid incorrect bounds propagation.
- */
- if (need_bswap || insn->imm == 16 || insn->imm == 32)
- clear_scalar_id(dst_reg);
-
if (need_bswap) {
if (insn->imm == 16)
dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
@@ -17948,7 +17908,6 @@ static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *ins
* like any other. At this insn the branch is a part of the state that is looked at:
* it must not be compared with it.
*/
- clear_scalar_id(reg);
return adjust_scalar_min_max_vals(env, insn, reg, *src_reg);
}
@@ -18158,10 +18117,8 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
- bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
struct bpf_insn_aux_data *aux = cur_aux(env);
u8 opcode = BPF_OP(insn->code);
- int err;
dst_reg = ®s[insn->dst_reg];
if (BPF_SRC(insn->code) == BPF_X)
@@ -18268,69 +18225,7 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
verbose(env, "verifier internal error: no src_reg\n");
return -EFAULT;
}
- /*
- * For alu32 linked register tracking, we need to check dst_reg's
- * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
- * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
- */
- u64 dst_umax = reg_umax(dst_reg);
-
- err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
- if (err)
- return err;
- /*
- * Compilers can generate the code
- * r1 = r2
- * r1 += 0x1
- * if r2 < 1000 goto ...
- * use r1 in memory access
- * So remember constant delta between r2 and r1 and update r1 after
- * 'if' condition.
- */
- if (env->bpf_capable &&
- (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
- dst_reg->id && is_reg_const(src_reg, alu32) &&
- !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
- u64 val = reg_const_value(src_reg, alu32);
- s32 off;
-
- if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
- goto clear_id;
-
- if (alu32 && (dst_umax > U32_MAX))
- goto clear_id;
-
- off = (s32)val;
-
- if (BPF_OP(insn->code) == BPF_SUB) {
- /* Negating S32_MIN would overflow */
- if (off == S32_MIN)
- goto clear_id;
- off = -off;
- }
-
- if (dst_reg->id & BPF_ADD_CONST) {
- /*
- * If the register already went through rX += val
- * we cannot accumulate another val into rx->off.
- */
-clear_id:
- clear_scalar_id(dst_reg);
- } else {
- if (alu32)
- dst_reg->id |= BPF_ADD_CONST32;
- else
- dst_reg->id |= BPF_ADD_CONST64;
- dst_reg->delta = off;
- }
- } else {
- /*
- * Make sure ID is cleared otherwise dst_reg min/max could be
- * incorrectly propagated into other registers by sync_linked_regs()
- */
- clear_scalar_id(dst_reg);
- }
- return 0;
+ return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/*
@@ -18544,7 +18439,6 @@ void bpf_reg_union_range(struct bpf_reg_state *acc, const struct bpf_reg_state *
/*
* Extends acc's scalar range to include src's scalar range.
* Caller must ensure that other kinds of metadata is compatible.
- * Caller must clear acc's scalar ID.
*/
int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
const struct bpf_reg_state *src)
@@ -18685,7 +18579,6 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
/* case: R1 = R2
* copy register state to dest reg
*/
- assign_scalar_id_before_mov(env, src_reg);
*dst_reg = *src_reg;
} else {
/* case: R1 = (s8, s16 s32)R2 */
@@ -18695,14 +18588,7 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
insn->src_reg);
return -EACCES;
} else if (src_reg->type == SCALAR_VALUE) {
- bool no_sext;
-
- no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
- if (no_sext)
- assign_scalar_id_before_mov(env, src_reg);
*dst_reg = *src_reg;
- if (!no_sext)
- clear_scalar_id(dst_reg);
coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
} else {
mark_reg_unknown(env, regs, insn->dst_reg);
@@ -18716,29 +18602,10 @@ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
insn->src_reg);
return -EACCES;
} else if (src_reg->type == SCALAR_VALUE) {
- if (insn->off == 0) {
- bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
-
- if (is_src_reg_u32)
- assign_scalar_id_before_mov(env, src_reg);
- *dst_reg = *src_reg;
- /* Make sure ID is cleared if src_reg is not in u32
- * range otherwise dst_reg min/max could be incorrectly
- * propagated into src_reg by sync_linked_regs()
- */
- if (!is_src_reg_u32)
- clear_scalar_id(dst_reg);
- } else {
- /* case: W1 = (s8, s16)W2 */
- bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
-
- if (no_sext)
- assign_scalar_id_before_mov(env, src_reg);
- *dst_reg = *src_reg;
- if (!no_sext)
- clear_scalar_id(dst_reg);
+ *dst_reg = *src_reg;
+ /* case: W1 = (s8, s16)W2 */
+ if (insn->off)
coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
- }
} else {
mark_reg_unknown(env, regs,
insn->dst_reg);
@@ -18902,7 +18769,7 @@ static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode,
* reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
* TRUE branch will be taken.
*/
- if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
+ if (reg_is_empty(&env->false_reg1) || reg_is_empty(&env->false_reg2))
return 1;
/* Jump (TRUE) branch */
@@ -18914,7 +18781,7 @@ static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode,
* reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
* Only FALSE branch will be taken.
*/
- if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
+ if (reg_is_empty(&env->true_reg1) || reg_is_empty(&env->true_reg2))
return 0;
/* Both branches are possible, we can't determine which one will be taken. */
@@ -19537,116 +19404,178 @@ static bool try_match_pkt_pointers(const struct bpf_insn *insn,
return true;
}
-static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
- u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
+/* a == b (mod 2^N) implies a == b if both fit in uN or both fit in sN. N is @bits. */
+static bool regs_fit_in_bits(const struct bpf_reg_state *a, const struct bpf_reg_state *b,
+ u32 bits)
{
- struct linked_reg *e;
+ u64 umax = GENMASK_ULL(bits - 1, 0);
+ s64 smax = umax >> 1;
- if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
- return;
+ return (reg_umax(a) <= umax && reg_umax(b) <= umax) ||
+ (reg_smin(a) >= -smax - 1 && reg_smax(a) <= smax &&
+ reg_smin(b) >= -smax - 1 && reg_smax(b) <= smax);
+}
- e = linked_regs_push(reg_set);
- if (e) {
- e->frameno = frameno;
- e->is_reg = is_reg;
- e->regno = spi_or_reg;
- } else {
- clear_scalar_id(reg);
- }
+/*
+ * The state of the SCEV register @r. As in check_stack_read_fixed_off() a fill of @bits bits from
+ * byte @fill_off of the slot reads the low bits of the spill.
+ */
+static struct bpf_reg_state *scev_reg_for_fill(struct bpf_func_state *frame, u32 r, u32 fill_off,
+ u32 bits)
+{
+ struct bpf_stack_state *ss;
+
+ if (r < MAX_BPF_REG)
+ return &frame->regs[r];
+ if (r - MAX_BPF_REG >= bpf_stack_nr_slots(frame))
+ return NULL;
+ ss = bpf_stack_slot(frame, r - MAX_BPF_REG);
+ if (!bpf_is_spilled_reg(ss) || bpf_spill_size(ss) * BITS_PER_BYTE < bits ||
+ !bpf_stack_narrow_access_ok(fill_off, bits / BITS_PER_BYTE, bpf_spill_size(ss)))
+ return NULL;
+ return &ss->spilled_ptr;
}
-/* For all R being scalar registers or spilled scalar registers
- * in verifier state, save R in linked_regs if R->id == id.
- * If there are too many Rs sharing same id, reset id for leftover Rs.
+/*
+ * Scalar evolution promoted memory to the SCEV register *@regno, see struct env there, and names
+ * its address at the jump at @idx. This state knows which memory it is: the frame that is returned,
+ * its stack slot *@regno, *@fill_off counts from the start of the slot. The stack of a caller only:
+ * other memory has no state, and a store through r10 is no def of memory for scalar evolution.
+ * What holds the address is live: it was compared all the way from its def. Every place that
+ * compares, joins or drops states cleans them of what is dead first, see flow_arrive().
*/
-static void collect_linked_regs(struct bpf_verifier_env *env,
- struct bpf_verifier_state *vstate,
- u32 id,
- struct linked_regs *linked_regs)
+static struct bpf_func_state *scev_mem_to_slot(struct bpf_verifier_env *env,
+ struct bpf_verifier_state *vstate, int idx,
+ u32 *regno, u32 *fill_off)
{
- struct bpf_insn_aux_data *aux = env->insn_aux_data;
- struct bpf_func_state *func;
- struct bpf_reg_state *reg;
- u16 live_regs;
- int i, j;
+ struct bpf_reg_state *ptr;
+ u32 base_regno;
+ s64 addr;
- id = id & ~BPF_ADD_CONST;
- for (i = vstate->curframe; i >= 0; i--) {
- live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
- func = vstate->frame[i];
- for (j = 0; j < BPF_REG_FP; j++) {
- if (!(live_regs & BIT(j)))
- continue;
- reg = &func->regs[j];
- __collect_linked_regs(linked_regs, reg, id, i, j, true);
- }
- for (j = 0; j < bpf_stack_nr_slots(func); j++) {
- struct bpf_stack_state *ss = bpf_stack_slot(func, j);
+ if (!bpf_scev_mem_addr(env, idx, *regno, &base_regno, &addr))
+ return NULL;
+ ptr = scev_reg_for_fill(vstate->frame[vstate->curframe], base_regno, 0, 64);
+ if (!ptr || ptr->type != PTR_TO_STACK || !tnum_is_const(ptr->var_off) ||
+ ptr->frameno >= vstate->curframe)
+ return NULL;
+ addr += ptr->var_off.value + *fill_off;
+ if (addr >= 0 || addr < -MAX_BPF_STACK_JIT)
+ return NULL;
+ *regno = MAX_BPF_REG + bpf_get_spi(addr);
+ *fill_off = addr & (BPF_REG_SIZE - 1);
+ return vstate->frame[ptr->frameno];
+}
- if (!bpf_is_spilled_reg(ss))
- continue;
- reg = &ss->spilled_ptr;
- __collect_linked_regs(linked_regs, reg, id, i, j, false);
- }
- }
+/*
+ * p = buf + i; if (i > 100) return 0; *p = 0;
+ * p is @dst_reg, x is @ptr_reg, i is @off_reg. Scalar evolution says that p == x + i. So the insns
+ * 'p = x; p += i' are a no-op at run time, and a state that is sound before them is sound after
+ * them: apply their transfer function. Type, object and offset of p are taken from x as it is now;
+ * how p was computed does not matter.
+ * The old p is replaced, not intersected: a state does not distinguish two values of one hash map,
+ * and the intersection of an offset into the one with an offset into the other holds for neither.
+ * It is replaced only if the new range is a subset of the old one. An empty range is a subset too:
+ * the path is infeasible, p is left as it is.
+ */
+static bool recompute_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *dst_reg,
+ const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg)
+{
+ struct bpf_reg_state sum = *ptr_reg;
+
+ /* the cpu can speculate past the jump with an out-of-bounds index */
+ if (!env->bypass_spec_v1)
+ return false;
+ /* 'p += i' assigns a new id to a packet pointer */
+ if (ptr_reg->type == SCALAR_VALUE || type_is_pkt_pointer(ptr_reg->type) ||
+ !bpf_is_widenable_reg_type(ptr_reg))
+ return false;
+ __mark_reg32_unbounded(&sum);
+ scalar_step_add(&sum, ptr_reg, off_reg);
+ sum.r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
+ sum.var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
+ reg_bounds_sync(&sum);
+ if (reg_is_empty(&sum) || const_tnum_range_mismatch(&sum) ||
+ const_tnum_range_mismatch_32(&sum))
+ return false;
+ if (!bpf_reg_union_compatible(dst_reg, &sum) || !cnum64_is_subset(dst_reg->r64, sum.r64))
+ return false;
+ *dst_reg = sum;
+ return true;
}
-/* For all R in linked_regs, copy known_reg range into R
- * if R->id == known_reg->id.
+/*
+ * The jump at @idx refined @regno. A register that scalar evolution links to it holds
+ * @regno + delta on every path to the jump: intersect the two. The intersection is empty: no
+ * execution gets here with this state (the path is infeasible), the register is left as it is.
*/
-static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
- struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
+static void refine_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
+ int idx, u32 regno)
{
- struct bpf_reg_state fake_reg;
- struct bpf_reg_state *reg;
- struct linked_reg *e;
- int i;
+ struct bpf_func_state *frame = vstate->frame[vstate->curframe], *linked_frame;
+ struct bpf_reg_state *reg, *base_reg, implied, saved;
+ u32 pos, linked_regno, fill_off, bits;
+ int base_regno;
+ s64 delta;
- for (i = 0; i < linked_regs->cnt; ++i) {
- e = &linked_regs->entries[i];
- reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
- : &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr;
- if (reg->type != SCALAR_VALUE || reg == known_reg)
- continue;
- if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
+ if (frame->regs[regno].type != SCALAR_VALUE)
+ return;
+ for (pos = 0;
+ bpf_scev_next_linked_reg(env, idx, regno, &pos, &linked_regno, &fill_off, &base_regno,
+ &delta, &bits);
+ pos++) {
+ linked_frame = frame;
+ if (linked_regno >= BPF_SCEV_REGS_NUM)
+ linked_frame = scev_mem_to_slot(env, vstate, idx, &linked_regno, &fill_off);
+ if (!linked_frame)
continue;
+ reg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);
/*
- * Skip mixed 32/64-bit links: the delta relationship doesn't
- * hold across different ALU widths.
+ * The other half-slot of a 64-bit spill is dead: __clean_func_state() left
+ * a 32-bit spill, the low 32 bits of the value.
*/
- if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
+ if (!reg && bits == 64 &&
+ bpf_stack_narrow_access_ok(fill_off, BPF_REG_SIZE / 2, BPF_REG_SIZE)) {
+ bits = 32;
+ reg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);
+ }
+ if (!reg || (base_regno < 0 && reg->type != SCALAR_VALUE))
continue;
- if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
- reg->delta == known_reg->delta) {
- *reg = *known_reg;
- } else {
- s32 saved_off = reg->delta;
- u32 saved_id = reg->id;
- fake_reg.type = SCALAR_VALUE;
- __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
-
- /* reg = known_reg; reg += delta */
- *reg = *known_reg;
- /*
- * Must preserve off and id, otherwise another sync_linked_regs()
- * will be incorrect.
- */
- reg->delta = saved_off;
- reg->id = saved_id;
-
- scalar_step_add(reg, reg, &fake_reg);
- scalar32_min_max_add(reg, &fake_reg);
- scalar_min_max_add(reg, &fake_reg);
- reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
- if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
- zext_32_to_64(reg);
- reg_bounds_sync(reg);
- }
- if (e->is_reg)
- mark_reg_scratched(env, e->regno);
- else
- mark_stack_slot_scratched(env, e->spi);
+ implied = frame->regs[regno];
+ add_scalar_to_reg(&implied, delta);
+ if (base_regno >= 0) {
+ base_reg = scev_reg_for_fill(frame, base_regno, 0, 64);
+ if (base_reg && bits == 64 && recompute_ptr(env, reg, base_reg, &implied))
+ goto scratch;
+ continue;
+ }
+ if (regs_fit_in_bits(reg, &implied, bits))
+ bits = 64;
+ if (bits < 32)
+ continue;
+ /* tnum_intersect() of two tnums that don't overlap is not empty */
+ if (!tnum_overlap(bits == 32 ? tnum_subreg(reg->var_off) : reg->var_off,
+ bits == 32 ? tnum_subreg(implied.var_off) : implied.var_off))
+ continue;
+ saved = *reg;
+ /*
+ * Equal in 64 bits is equal in the low 32 bits too. 'if w1 s> 200' on a zero
+ * extended int refines nothing but the 32-bit range.
+ */
+ regs_refine_cond_op(reg, &implied, BPF_JEQ, true);
+ if (bits == 64)
+ regs_refine_cond_op(reg, &implied, BPF_JEQ, false);
+ reg_bounds_sync(reg);
+ if (reg_is_empty(reg) || const_tnum_range_mismatch(reg) ||
+ const_tnum_range_mismatch_32(reg)) {
+ *reg = saved;
+ continue;
+ }
+scratch:
+ if (linked_regno < MAX_BPF_REG)
+ mark_reg_scratched(env, linked_regno);
+ else if (linked_frame == frame)
+ mark_stack_slot_scratched(env, linked_regno - MAX_BPF_REG);
}
}
@@ -19677,7 +19606,6 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
struct bpf_reg_state *eq_branch_regs;
- struct linked_regs linked_regs = {};
u8 opcode = BPF_OP(insn->code);
bool is_jmp32;
int pred = -1;
@@ -19746,16 +19674,6 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
__mark_reg_known(src_reg, insn->imm);
}
- /*
- * Collect the linked registers before env->{true,false}_reg{1,2} setup,
- * otherwise ids dropped by collect_linked_regs() would be resurrected
- * when env->{true,false}_reg{1,2} are copied back.
- */
- if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
- collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
- if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
- collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
-
is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
env->false_reg1 = *dst_reg;
env->false_reg2 = *src_reg;
@@ -19809,18 +19727,13 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
if (BPF_SRC(insn->code) == BPF_X)
other_branch_regs[insn->src_reg] = env->true_reg2;
- if (BPF_SRC(insn->code) == BPF_X &&
- src_reg->type == SCALAR_VALUE && src_reg->id &&
- !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
- sync_linked_regs(env, this_branch, src_reg, &linked_regs);
- sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
- &linked_regs);
- }
- if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
- !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
- sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
- sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
- &linked_regs);
+ if (env->bpf_capable) {
+ if (BPF_SRC(insn->code) == BPF_X) {
+ refine_linked_regs(env, this_branch, *insn_idx, insn->src_reg);
+ refine_linked_regs(env, other_branch, *insn_idx, insn->src_reg);
+ }
+ refine_linked_regs(env, this_branch, *insn_idx, insn->dst_reg);
+ refine_linked_regs(env, other_branch, *insn_idx, insn->dst_reg);
}
/* if one pointer register is compared to another pointer
@@ -20674,69 +20587,6 @@ static void adjust_btf_func(struct bpf_verifier_env *env)
aux->func_info[i].insn_off = env->subprog_info[i].start;
}
-/* Find id in idset and increment its count, or add new entry */
-static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
-{
- u32 i;
-
- for (i = 0; i < idset->num_ids; i++) {
- if (idset->entries[i].id == id) {
- idset->entries[i].cnt++;
- return;
- }
- }
- /* New id */
- if (idset->num_ids < BPF_ID_MAP_SIZE) {
- idset->entries[idset->num_ids].id = id;
- idset->entries[idset->num_ids].cnt = 1;
- idset->num_ids++;
- }
-}
-
-/* Find id in idset and return its count, or 0 if not found */
-static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
-{
- u32 i;
-
- for (i = 0; i < idset->num_ids; i++) {
- if (idset->entries[i].id == id)
- return idset->entries[i].cnt;
- }
- return 0;
-}
-
-/*
- * Clear singular scalar ids in a state.
- * A register with a non-zero id is called singular if no other register shares
- * the same base id. Such registers can be treated as independent (id=0).
- */
-void bpf_clear_singular_ids(struct bpf_verifier_env *env,
- struct bpf_verifier_state *st)
-{
- struct bpf_idset *idset = &env->idset_scratch;
- struct bpf_func_state *func;
- struct bpf_reg_state *reg;
-
- idset->num_ids = 0;
-
- bpf_for_each_reg_in_vstate(st, func, reg, ({
- if (reg->type != SCALAR_VALUE)
- continue;
- if (!reg->id)
- continue;
- idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
- }));
-
- bpf_for_each_reg_in_vstate(st, func, reg, ({
- if (reg->type != SCALAR_VALUE)
- continue;
- if (!reg->id)
- continue;
- if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
- clear_scalar_id(reg);
- }));
-}
-
/* Return true if it's OK to have the same insn return a different type. */
static bool reg_type_mismatch_ok(enum bpf_reg_type type)
{
diff --git a/tools/testing/selftests/bpf/prog_tests/reg_bounds.c b/tools/testing/selftests/bpf/prog_tests/reg_bounds.c
index 09f7930733beb0..c2079eb642019e 100644
--- a/tools/testing/selftests/bpf/prog_tests/reg_bounds.c
+++ b/tools/testing/selftests/bpf/prog_tests/reg_bounds.c
@@ -1290,7 +1290,8 @@ static int parse_range_cmp_log(const char *log_buf, struct case_spec spec,
* 18: (bf) r0 = r6 ; R0=... R6=...
* Different verifier passes may print
* 18: (bf) r0 = r6
- * as well, but never followed by ';'.
+ * as well, but never followed by ';'. Except for scalar evolution:
+ * t 18: (bf) r0 = r6 ; r0 ... -> ...
* The branches are in the log in the order the verifier looked at them.
*/
q = log_buf;
@@ -1299,7 +1300,7 @@ static int parse_range_cmp_log(const char *log_buf, struct case_spec spec,
while (*s == ' ' || *s == '\t')
s++;
- if (*s == ';')
+ if (*s == ';' && (q == log_buf || q[-1] == '\n'))
break;
q = s;
}
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena.c b/tools/testing/selftests/bpf/progs/verifier_arena.c
index cadb13f023d2a3..3931a1d9b6dacf 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena.c
@@ -597,6 +597,76 @@ __naked void mixed_arena_scalar_alu64_arena_first(void)
: __clobber_all);
}
+/* The offset of a pointer to arena is not tracked */
+#define ARENA_TEST(name, op, expect) \
+SEC("syscall") \
+__log_level(2) \
+expect \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "r1 = %[arena] ll;" \
+ "r6 = 0;" \
+ "r6 = addr_space_cast(r6, 0, 1);" \
+ "r7 = 0;" \
+"1: *(u64 *)(r6 + 0) = r7;" \
+ op \
+ "r7 += 1;" \
+ "if r7 < 100 goto 1b;" \
+ "r0 = 0;" \
+ "exit;" \
+ :: __imm_addr(arena) : __clobber_all); \
+}
+
+#define NOT_UNROLLED100 __msg("loop header at 5, widening r7 to 0..99 step 1")
+/* A loop that moves the pointer is not unrolled */
+ARENA_TEST(arena_pointer_moves, "r6 += 8;", __success NOT_UNROLLED100)
+/* The loop makes a number of it: the state that returns to the loop header tells */
+ARENA_TEST(arena_pointer_becomes_a_number, "if r7 != 5 goto +1; r6 = 4096;",
+ __failure NOT_UNROLLED100 __msg("R6 invalid mem access 'scalar'"))
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, char[64]);
+} map64 SEC(".maps");
+
+/*
+ * r6: 64 bytes. r8: an unbounded scalar. r3, r7: an arena pointer and a copy of it.
+ * The test leaves an address in r1.
+ */
+#define ARENA_LINKED(name, expect, body) \
+SEC("syscall") expect __load_if_JITed() \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "r1 = %[arena] ll; r1 = 0; *(u32 *)(r10 - 4) = r1; r2 = r10; r2 += -4;" \
+ "r1 = %[map64] ll; call %[bpf_map_lookup_elem]; if r0 == 0 goto out_%=; r6 = r0;" \
+ "call %[bpf_ktime_get_ns]; r8 = r0; r3 = addr_space_cast(r8, 0, 1); r7 = r3;" \
+ body \
+ "r0 = *(u8 *)(r1 + 0);" \
+ "out_%=: r0 = 0; exit;" \
+ : \
+ : __imm(bpf_map_lookup_elem), __imm(bpf_ktime_get_ns), \
+ __imm_addr(map64), __imm_addr(arena) \
+ : __clobber_all); \
+}
+
+ARENA_LINKED(scalar_plus_two_constants, __success __retval(0),
+ "r2 = r8; r2 += 1; r2 += 1; if r8 > 61 goto out_%=; r1 = r6; r1 += r2;")
+/* 'r3 += 1' is converted to 'w3 += 1': r3 is 0 and not 1 << 32 */
+ARENA_LINKED(arena_ptr_plus_constant, __failure,
+ "r3 += 1; r3 = le64 r3; r7 = le64 r7; r2 = 0xffffffff ll; if r7 != r2 goto out_%=;"
+ "r3 >>= 32; r3 -= 1; r1 = r6; r1 += r3;")
+/* At the join point r3 is phi((+ x 1)). The insn there, an add to a scalar, does not define it. */
+ARENA_LINKED(arena_ptr_plus_constant_on_two_paths, __failure,
+ "if r8 == 0 goto 1f; r3 += 1; goto 2f; 1: r3 += 1; 2: r8 += 1; r3 = le64 r3; r7 = le64 r7;"
+ "r2 = 0xffffffff ll; if r7 != r2 goto out_%=; r3 >>= 32; r3 -= 1; r1 = r6; r1 += r3;")
+/* 'r1 += r2' was verified without a pointer to arena: it stays ALU64 */
+ARENA_LINKED(index_tested_after_the_add, __success __retval(0),
+ "r2 = r8; r2 &= 255; r1 = r6; r1 += r2; if r2 > 63 goto out_%=; r0 = *(u8 *)(r6 + 0);")
+
SEC("syscall")
__description("arena: a number is not an address in arena")
__failure __msg("R6 invalid mem access 'scalar'")
diff --git a/tools/testing/selftests/bpf/progs/verifier_array_access.c b/tools/testing/selftests/bpf/progs/verifier_array_access.c
index 7f98822889cad5..29bed1e496af60 100644
--- a/tools/testing/selftests/bpf/progs/verifier_array_access.c
+++ b/tools/testing/selftests/bpf/progs/verifier_array_access.c
@@ -762,7 +762,7 @@ l0_%=: *(u32*)(r10 - 8) = r6; \
: __clobber_all);
}
-/* The slot has the id of r6, so the compare sets the range of the slot too */
+/* The slot holds the low 32 bits of r6, so the compare refines the slot too */
SEC("socket")
__description("valid map access into an array using a key that is compared after the spill")
__success __retval(0)
diff --git a/tools/testing/selftests/bpf/progs/verifier_bounds.c b/tools/testing/selftests/bpf/progs/verifier_bounds.c
index f55d58af8004a4..b78e7fc96fa704 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bounds.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bounds.c
@@ -1476,7 +1476,7 @@ __naked void sub64_full_overflow(void)
SEC("socket")
__description("64-bit subtraction, partial overflow, result in unbounded reg")
__success __log_level(2)
-__msg("3: (1f) r3 -= r2 {{.*}} R3=scalar(id=1-1)")
+__msg("3: (1f) r3 -= r2 {{.*}} R3=scalar()")
__retval(0)
__naked void sub64_partial_overflow(void)
{
@@ -1572,7 +1572,7 @@ l0_%=: r0 = 0; \
SEC("socket")
__description("bounds deduction cross sign boundary, negative overlap")
__success __log_level(2)
-__msg("7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-655,smax=smax32=-146,umin=0xfffffffffffffd71,umax=0xffffffffffffff6e,umin32=0xfffffd71,umax32=0xffffff6e,var_off=(0xfffffffffffffc00; 0x3ff))")
+__msg("7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-527,smax=smax32=-146,umin=0xfffffffffffffdf1,umax=0xffffffffffffff6e,umin32=0xfffffdf1,umax32=0xffffff6e,var_off=(0xfffffffffffffc00; 0x3ff))")
__retval(0)
__naked void bounds_deduct_negative_overlap(void)
{
@@ -1995,6 +1995,39 @@ __naked void bounds_refinement_multiple_overlaps(void *ctx)
: __clobber_all);
}
+/*
+ * r0 is x << 32, the low three bits of x are 5. No such x is in [-2, 1], -3 is in [-3, 1].
+ * umin and umax are unbounded for a range that crosses 0.
+ */
+#define RANGE_CROSSES_0(name, smin) \
+__naked void name(void *ctx) \
+{ \
+ asm volatile( \
+ "call %[bpf_ktime_get_ns];" \
+ "r0 <<= 35;" \
+ "r1 = 0x500000000 ll;" \
+ "r0 += r1;" \
+ "r1 = " #smin " ll;" \
+ "if r0 s< r1 goto 1f;" \
+ "r1 = 0x100000000 ll;" \
+ "if r0 s> r1 goto 1f;" \
+ "r10 = 0;" \
+"1: exit;" \
+ : \
+ : __imm(bpf_ktime_get_ns) \
+ : __clobber_all); \
+}
+
+SEC("socket")
+__description("dead branch: tnum and a range that crosses 0 don't overlap")
+__success
+RANGE_CROSSES_0(range_crossing_0_no_tnum_overlap, -0x200000000)
+
+SEC("socket")
+__description("tnum overlaps the negative part of a range that crosses 0")
+__failure __msg("frame pointer is read only")
+RANGE_CROSSES_0(range_crossing_0_tnum_overlap_below_0, -0x300000000)
+
SEC("socket")
__success
__naked void signed_unsigned_intersection32_case1(void *ctx)
diff --git a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
index 51b703058cf70b..b42717a825c69e 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
@@ -299,7 +299,7 @@ SEC("socket")
__success __log_level(2)
__msg("r0 += 8 {{.*}}smin=umin=smin32=umin32=8,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
__msg("from 4 to 6: R0=scalar(smin=umin=smin32=umin32=32,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
-__msg("r1 = r0 {{.*}}R1=scalar(id={{[0-9]+}},smin=umin=smin32=umin32=104,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
+__msg("r1 = r0 {{.*}}R1=scalar(smin=umin=smin32=umin32=104,smax=umax=smax32=umax32=176,{{.*}}step=8+24)")
__msg("r1 += 24 {{.*}}R1=scalar({{.*}}smin=umin=smin32=umin32=128,smax=umax=smax32=umax32=200,{{.*}}step=8+24)")
__naked void step_bounds_resync_after_arith(void)
{
@@ -336,10 +336,10 @@ l_out_%=: \
*/
SEC("socket")
__success __log_level(2)
-__msg("r1 = (s16)r0 {{.*}}R1=scalar(id={{[0-9]+}},smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
+__msg("r1 = (s16)r0 {{.*}}R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
__msg("r2 = (s16)r0 {{.*}}R2=scalar(smin=smin32=-24,smax=smax32=144,{{.*}}step=0+24)")
__msg("r3 = (s8)r0 {{.*}}R3=scalar(smin=smin32=-128,smax=smax32=127)")
-__msg("w4 = (s16)w1 {{.*}}R4=scalar(id={{[0-9]+}},smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
+__msg("w4 = (s16)w1 {{.*}}R4=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
__msg("w5 = (s8)w1 {{.*}}R5=scalar({{.*}}smin32=-128,smax32=127,var_off=(0x0; 0xffffffff))")
__naked void step_movsx_bounds_on_line(void)
{
diff --git a/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c b/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c
index 6c1d2014b95b1b..212c08a27058e9 100644
--- a/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c
+++ b/tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c
@@ -569,7 +569,7 @@ l0_%=: r0 = 0; \
SEC("tc")
__description("direct packet access: test23 (x += pkt_ptr, 4)")
-__failure __msg("invalid access to packet, off=31 size=8, R5(id=3,off=31,r=0)")
+__failure __msg("invalid access to packet, off=31 size=8, R5(id=1,off=31,r=0)")
__flag(BPF_F_ANY_ALIGNMENT)
__naked void test23_x_pkt_ptr_4(void)
{
diff --git a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
index caae67feaf5b70..c8b3690dd810a4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
+++ b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
@@ -190,10 +190,9 @@ l0_%=: \
: __clobber_all);
}
-/* Double ADD clears the ID (can't accumulate offsets) */
+/* Double ADD clears the ID. That r1 = r0 + 4 is known all the same: r0 /= 0 is dead code */
SEC("socket")
-__failure
-__msg("div by zero")
+__success
__naked void scalars_double_add(void)
{
asm volatile (" \
@@ -677,6 +676,7 @@ l_false_%=: \
r2 = r0; \
r2 &= 0xff; /* R2 = scalar(id=A) [0,255] */ \
r4 = r0; \
+ r4 >>= 8; \
r4 &= 0xff; /* R4 = scalar [0,255], id=0 */ \
r3 = r2; /* R3 linked to R2 (id=A) */ \
r3 += 10; /* R3 id=A|ADD_CONST, delta=10 */\
@@ -689,6 +689,7 @@ l_true_%=: \
r2 = r0; \
r2 &= 0xff; /* R2 = scalar [0,255], id=0 */ \
r4 = r0; \
+ r4 >>= 8; \
r4 &= 0xff; /* R4 = scalar [0,255], id=0 */ \
r3 = r4; /* R3 linked to R4 (new id=C) */\
r3 += 10; /* R3 id=C|ADD_CONST, delta=10 */\
diff --git a/tools/testing/selftests/bpf/progs/verifier_live_stack.c b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
index 32bab3cb3fcb9a..d6a6420d219d5c 100644
--- a/tools/testing/selftests/bpf/progs/verifier_live_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
@@ -3143,6 +3143,66 @@ static __used __naked void imprecise_fill_cross_frame(void)
: __clobber_all);
}
+/*
+ * fill_older_frame_3() loads through a pointer to the stack of frame 1 or of frame 2. Both slots
+ * hold a pointer to fp-8 of frame 0: the store is a may_def of that slot at the call in frame 0.
+ */
+SEC("socket")
+__log_level(2)
+__success
+__msg("3: (85) call pc+2{{ +}}; may_def: fp0-8..-{{[0-9]+}}")
+__naked void imprecise_parent_fill_loses_older_frame(void)
+{
+ asm volatile (
+ "*(u64 *)(r10 - 8) = 0;"
+ "r1 = r10;"
+ "r1 += -8;"
+ "call fill_older_frame_1;"
+ "r0 = *(u64 *)(r10 - 8);"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void fill_older_frame_1(void)
+{
+ asm volatile (
+ "*(u64 *)(r10 - 8) = r1;"
+ "r1 = r10;"
+ "r1 += -8;"
+ "call fill_older_frame_2;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void fill_older_frame_2(void)
+{
+ asm volatile (
+ "r2 = *(u64 *)(r1 + 0);"
+ "*(u64 *)(r10 - 8) = r2;"
+ "r2 = r10;"
+ "r2 += -8;"
+ "call fill_older_frame_3;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void fill_older_frame_3(void)
+{
+ asm volatile (
+ "r6 = r1;"
+ "r7 = r2;"
+ "call %[bpf_get_prandom_u32];"
+ "if r0 == 0 goto +1;"
+ "r6 = r7;"
+ /* ARG_IMPRECISE{mask=BIT(1)|BIT(2)} */
+ "r1 = *(u64 *)(r6 + 0);"
+ "*(u64 *)(r1 + 0) = 7;"
+ "r0 = 0;"
+ "exit;"
+ :: __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
/* Test that spill_to_stack with multi-offset dst (sz=8) joins instead
* of overwriting. r1 has offsets [-8, -16]. Both slots hold FP-derived
* pointers. Writing through r1 should join *val with existing values,
diff --git a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
index 35bb3e16db3dea..17222e1332fdba 100644
--- a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
+++ b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
@@ -271,6 +271,51 @@ LOOP(copy_bad, "r8 = 0; r9 = r8;", COPY(2047))
BAD("a copy of the counter, another number at the entry")
LOOP(copy_other_const, "r8 = 2047; r9 = 0; r6 += 2047;", COPY(2046))
+/* the latch exits one iteration later than for an induction variable that starts from 1 */
+NO_COUNT("a copy of the counter, one more at the entry")
+LOOP(copy_ahead, "r8 = 0; r9 = 1;", COPY(2047))
+
+/* r5 is a copy of the pointer r6 from before the increment: an induction variable too */
+#define PTR_COPY(off) "*(u8 *)(r5 + " #off ") = r1; r5 = r6; r8 += 1; if r8 < 2048 goto 1b;"
+
+OK("a copy of the pointer", "2048") __msg("widening r5 to 0..2047 step 1")
+LOOP(copy_of_pointer, "r5 = r6; r8 = 0;", PTR_COPY(0))
+
+BAD("a copy of the pointer, one too many")
+LOOP(copy_of_pointer_bad, "r5 = r6; r8 = 0;", PTR_COPY(1))
+
+/* r8 and r9 are computed in the same way from r7: equal by value number, 'r9 = r8' is not needed */
+OK("a copy of the counter, equal by value number", "[0..2]")
+LOOP(copy_same_value_number,
+ "r5 = r6; r8 = r7; r8 &= 1; r8 += 2045; r9 = r7; r9 &= 1; r9 += 2045;", COPY(2045) AT_R8)
+
+/*
+ * 'for (i = n; i > 0; i--) buf[i - 1] = 0;': r9 is i from before the decrement, the latch tests r8.
+ * r9 gets the range that the latch implies for r8.
+ */
+#define DOWN(off) \
+ "r8 += -1; r2 = r5; r2 += r9; *(u8 *)(r2 " off ") = r1; r9 = r8; if r8 > 0 goto 1b;"
+#define FROM_RANGE "if r7 > 2048 goto 9f; if r7 == 0 goto 9f; r5 = r6; r8 = r7; r9 = r7;"
+
+OK("a copy of the counter, down from a range", "[0..2048]")
+LOOP(copy_down_from_range, FROM_RANGE, DOWN("- 1"))
+
+BAD("a copy of the counter, down from a range, one too many")
+LOOP(copy_down_from_range_bad, FROM_RANGE, DOWN("+ 0"))
+
+/*
+ * r9 is zero extended. [1, 2048], its range at the header, is the range of the zero extension too.
+ * [-1000, 1001] is not: the first store is 4G behind the value.
+ */
+OK("a copy of the counter, zero extended", "[0..2048]")
+LOOP(copy_zext, FROM_RANGE, "w9 = w9;" DOWN("- 1"))
+
+SEC("socket") __description("latch: a copy of the counter, zero extended, from below 0")
+__failure __msg("R4 unbounded memory access")
+LOOP(copy_zext_bad, "r5 = r6; r8 = r7; r8 &= 255; r8 += -1000; r9 = r8;",
+ "w9 = w9; if r8 s> 1000 goto 9f; r4 = r5; r4 += r9; *(u8 *)(r4 + 1000) = r1;"
+ "r8 += 1; r9 = r8; if r7 != 0 goto 1b;")
+
OK("a copy of the counter, a range", "[0..2]")
LOOP(copy_range, "r5 = r6; r8 = r7; r8 &= 1; r8 += 2045; r9 = r8;", COPY(2045) AT_R8)
@@ -297,13 +342,13 @@ LOOP(copy_bounds_both, "r5 = r6; if r7 > 2047 goto 9f; r8 = r7; r9 = r8;",
"r4 = r5; r4 += r9; *(u8 *)(r4 " off ") = r1; 2: r9 = r8; if r7 != 0 goto 1b;"
OK("a copy of the counter, one less behind the jump", "[0..2048]")
-LOOP(copy_less, "r5 = r6; r8 = 0; r9 = r8;", NOT_EQUAL(1, "> 2046", "< 2", "- 1"))
+LOOP(copy_less, "r5 = r6; r8 = 0; r9 = r8;", NOT_EQUAL(1, "> 2046", "< 2", "+ 0"))
BAD("a copy of the counter, one less behind the jump, not equal")
LOOP(copy_less_bad, "r5 = r6; r8 = 0; r9 = r8;", NOT_EQUAL(1, "> 2046", "< 2", "- 2"))
OK("a copy of the counter, one more behind the jump", "[0..2047]")
-LOOP(copy_more, "r5 = r6; r8 = 2047; r9 = r8;", NOT_EQUAL(-1, "s< 2", "> 2045", "+ 1"))
+LOOP(copy_more, "r5 = r6; r8 = 2047; r9 = r8;", NOT_EQUAL(-1, "s< 2", "> 2045", "+ 0"))
BAD("a copy of the counter, one more behind the jump, not equal")
LOOP(copy_more_bad, "r5 = r6; r8 = 2047; r9 = r8;", NOT_EQUAL(-1, "s< 2", "> 2045", "+ 2"))
diff --git a/tools/testing/selftests/bpf/progs/verifier_movsx.c b/tools/testing/selftests/bpf/progs/verifier_movsx.c
index 2f4a678c31c202..6f90dac78fcd10 100644
--- a/tools/testing/selftests/bpf/progs/verifier_movsx.c
+++ b/tools/testing/selftests/bpf/progs/verifier_movsx.c
@@ -202,6 +202,192 @@ l0_%=: \
: __clobber_all);
}
+/*
+ * A 32-bit range that already fits the signed N-bit range is unchanged by the sign
+ * extension. Both of these straddle zero. The guard that follows can only be
+ * resolved statically if the range survives, and it protects a div by zero.
+ */
+SEC("socket")
+__description("MOV32SX, S8, negative range is preserved")
+__success __success_unpriv __retval(0)
+__naked void mov32sx_s8_negative_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ w0 &= 0x3f; \
+ w0 -= 0x3f; \
+ /* w0 is [-63, 0], already a valid s8 */ \
+ w0 = (s8)w0; \
+ if w0 s< -0x3f goto l0_%=; \
+ w0 = 0; \
+ exit; \
+l0_%=: \
+ /* dead unless the range was widened */ \
+ w0 /= 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("socket")
+__description("MOV32SX, S16, negative range is preserved")
+__success __success_unpriv __retval(0)
+__naked void mov32sx_s16_negative_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ w0 &= 0xfff; \
+ w0 -= 0xfff; \
+ /* w0 is [-4095, 0], already a valid s16 */ \
+ w0 = (s16)w0; \
+ if w0 s< -0xfff goto l0_%=; \
+ w0 = 0; \
+ exit; \
+l0_%=: \
+ /* dead unless the range was widened */ \
+ w0 /= 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * A 32-bit sign extension keeps the low 32 bits, so refining the source
+ * reaches the destination. The source is a call return, which is the shape
+ * bpf-gcc builds for "int err = helper(); if (err) ..".
+ */
+SEC("socket")
+__success __retval(0)
+__naked void sext_mov_unlinked_src(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r7 = (s32)r0; /* r0 as the call defines it */ \
+ if w0 != -1 goto l0_%=; /* refines r0, propagates to r7 */ \
+ if r7 == -1 goto l0_%=; /* sign-extended, not 0xffffffff */ \
+ r0 /= 0; \
+l0_%=: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * The propagation must not run backwards over the upper 32 bits: a sign extension
+ * knows nothing about the upper bits of its source. r8's low 32 bits do become
+ * 2, r8 == 2 does not follow.
+ */
+SEC("socket")
+__failure __msg("div by zero")
+__naked void sext_no_sync_from_subreg_base(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r7 = (s32)r6; \
+ r8 = r6; \
+ r8 += 3; \
+ if r7 != -1 goto 1f; /* pins the low 32 bits of r8 only */ \
+ if r8 == 2 goto 1f; /* taken only if r8 wrongly refined */ \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * r2 is (u32)(r6 + 1) and r7 is (s32)(r6 + 1), so w2 == 1 means r7 == 1.
+ * bpf-gcc builds "i += 1" for an int induction variable into exactly this shape.
+ */
+SEC("socket")
+__success __retval(0)
+__naked void sext_sync_from_zext_sibling(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r6 <<= 32; \
+ call %[bpf_get_prandom_u32]; \
+ r6 |= r0; /* r6 = full 64-bit unknown */ \
+ r2 = r6; \
+ w2 += 1; /* r2 = (u32)(r6 + 1) */ \
+ r7 = (s32)r2; /* r7 = (s32)(r6 + 1) */ \
+ if w2 != 1 goto 1f; /* propagates to r7 */ \
+ if r7 == 1 goto 1f; \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * "w6 = w6" leaves r6 in [0, U32_MAX]. A signed compare on its sign extension
+ * must not hand r6 the sign-extended value: that drops every r6 >= 2^31 from
+ * the range and makes the guarded div provably dead.
+ */
+SEC("socket")
+__failure __msg("div by zero")
+__naked void sext_narrow_base_keeps_high_values(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ w6 = w6; /* r6 in [0, U32_MAX] */ \
+ r7 = (s32)r6; \
+ r8 = 1; \
+ r8 <<= 31; /* 0x80000000 */ \
+ if r7 s> 100 goto 1f; /* r6 is [0,100] or >= 2^31 */ \
+ if r6 < r8 goto 1f; /* reachable: r6 may be >= 2^31 */ \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * A base/step line does not survive the sign extension: it subtracts 2^32,
+ * and 2^32 is not a multiple of 3. r6 = 0x80000007 is a multiple of 3, so
+ * r7 = -2147483641 is reachable.
+ */
+SEC("socket")
+__failure __msg("div by zero")
+__naked void sext_drops_stale_step(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ w6 = w6; \
+ r6 *= 3; /* base 0, step 3 */ \
+ r7 = (s32)r6; \
+ r8 = 1; \
+ r8 <<= 31; \
+ r9 = r8; \
+ r9 += 7; \
+ if r6 < r8 goto 1f; \
+ if r6 > r9 goto 1f; /* r6 in [0x80000000, 0x80000007] */ \
+ if r7 != -2147483641 goto 1f; /* reachable: r6 == 0x80000007 */ \
+ r0 /= 0; \
+1: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
SEC("socket")
__description("MOV64SX, S16, R10 Sign Extension")
__failure __msg("R1 type=scalar expected=fp, pkt, pkt_meta, map_key, map_value, mem, ringbuf_mem, buf, trusted_ptr_")
diff --git a/tools/testing/selftests/bpf/progs/verifier_reg_equal.c b/tools/testing/selftests/bpf/progs/verifier_reg_equal.c
index dc1d8c30fb0eeb..91daa5b323c9f8 100644
--- a/tools/testing/selftests/bpf/progs/verifier_reg_equal.c
+++ b/tools/testing/selftests/bpf/progs/verifier_reg_equal.c
@@ -31,17 +31,16 @@ l1_%=: exit; \
}
SEC("socket")
-__description("check w reg not equal if r reg upper32 bits not 0")
-__failure __msg("R1 !read_ok")
+__description("check w reg equal if r reg upper32 bits not 0")
+__success
__naked void subreg_equality_2(void)
{
asm volatile (" \
call %[bpf_ktime_get_ns]; \
r2 = r0; \
- /* Upper 4-bytes of r2 may not be 0, thus insn \
- * w3 = w2 should not propagate reg id, and \
- * w2 < 9 comparison should not propagate \
- * the range for r3 either. \
+ /* Upper 4-bytes of r2 may not be 0. r3 is the \
+ * lower 4-bytes of r2, which is what w2 < 9 \
+ * compares. \
*/ \
w3 = w2; \
if w2 < 9 goto l0_%=; \
diff --git a/tools/testing/selftests/bpf/progs/verifier_regalloc.c b/tools/testing/selftests/bpf/progs/verifier_regalloc.c
index ee5ddea87c91c0..cf26617b6ba16f 100644
--- a/tools/testing/selftests/bpf/progs/verifier_regalloc.c
+++ b/tools/testing/selftests/bpf/progs/verifier_regalloc.c
@@ -303,7 +303,6 @@ __naked void regalloc_in_callee(void)
r7 = r0; \
call %[bpf_get_prandom_u32]; \
r1 = r0; \
- r2 = r0; \
r3 = r7; \
call regalloc_in_callee__1; \
l0_%=: exit; \
@@ -318,6 +317,7 @@ static __naked __noinline __attribute__((used))
void regalloc_in_callee__1(void)
{
asm volatile (" \
+ r2 = r1; \
if r1 s> 20 goto l0_%=; \
if r2 s< 0 goto l0_%=; \
r3 += r1; \
diff --git a/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c b/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c
index 9ea61b16273653..56c2412608a5dc 100644
--- a/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c
+++ b/tools/testing/selftests/bpf/progs/verifier_scalar_ids.c
@@ -11,11 +11,10 @@ struct {
__type(value, long long);
} map_hash_8b SEC(".maps");
-/* scalar in [0, max] that shares id with other registers, as it is in the log */
-#define LINKED(id, max, mask) \
- "scalar(id=" id ",smin=smin32=0,smax=umax=smax32=umax32=" #max ",var_off=(0x0; " #mask "))"
+/* scalar in [0, max], as it is in the log. @id: the registers that hold copies of one value. */
#define ALONE(max, mask) \
"scalar(smin=smin32=0,smax=umax=smax32=umax32=" #max ",var_off=(0x0; " #mask "))"
+#define LINKED(id, max, mask) ALONE(max, mask)
/*
* Registers r{0,1,2} have the same scalar ID.
@@ -151,7 +150,7 @@ __naked void linked_regs_broken_link(void)
SEC("socket")
__success __log_level(2)
__msg("13: (25) if r1 > 0x7 goto pc+0 ; R1=" ALONE(7, 0x7))
-__msg("10: R0=0 R6=scalar(id={{.*}}umax32=255,{{.*}} R7=scalar(id={{.*}}umax32=255,")
+__msg("10: R0=0 R6=scalar({{.*}}umax32=255,{{.*}} R7=scalar({{.*}}umax32=255,")
__msg("5: R0=0 R6=" ALONE(255, 0xff))
__naked void precision_many_frames(void)
{
@@ -285,13 +284,8 @@ __naked void precision_two_ids(void)
SEC("socket")
__success __log_level(2)
-/*
- * check that r5 is unlinked after 'if', collect_linked_regs() can't tie
- * more than 5 registers for a single insn and the register compared by
- * the jump is not exempt from that.
- */
-__msg("7: (25) if r5 > 0x7 goto pc+0 ; R5=scalar(smin=")
-__msg("12: (bf) r5 = r5 ; R5=scalar(id=2")
+/* there is no limit of 5 registers for a single insn */
+__msg("7: (25) if r5 > 0x7 goto pc+0 ; R0=" LINKED("1", 7, 0x7) " R1=" LINKED("1", 7, 0x7) " R2=" LINKED("1", 7, 0x7) " R3=" LINKED("1", 7, 0x7) " R4=" LINKED("1", 7, 0x7) " R5=" LINKED("1", 7, 0x7))
__naked void linked_regs_too_many_regs(void)
{
asm volatile (
@@ -304,14 +298,12 @@ __naked void linked_regs_too_many_regs(void)
"r3 = r0;"
"r4 = r0;"
"r5 = r0;"
- /* r{0-4} fill the record, r5 does not fit and is unlinked */
"if r5 > 7 goto +0;"
- /* keep r{1-4} live */
+ /* keep r{1-5} live */
"r1 = r1;"
"r2 = r2;"
"r3 = r3;"
"r4 = r4;"
- /* make r5 appear in the log */
"r5 = r5;"
"r7 = r10;"
"r7 += r0;"
@@ -324,7 +316,7 @@ __naked void linked_regs_too_many_regs(void)
SEC("socket")
__failure __log_level(2)
-__msg("5: (3d) if r8 >= r0 goto pc+3 ; R0=scalar(umin=1) R7=scalar(id=1,umax=0xfffffffffffffffe) R8=scalar(id=1,umax=0xfffffffffffffffe)")
+__msg("5: (3d) if r8 >= r0 goto pc+3 ; R0=scalar(umin=1) R7=scalar(umax=0xfffffffffffffffe) R8=scalar(umax=0xfffffffffffffffe)")
__msg("div by zero")
__naked void linked_regs_broken_link_2(void)
{
@@ -687,52 +679,6 @@ __naked void two_nil_old_ids_one_cur_id(void)
: __clobber_all);
}
-/*
- * Check that two different scalar IDs in the state that is there can't be
- * mapped to the same scalar ID in the state that arrives.
- */
-SEC("socket")
-__success __log_level(2)
-__not_msg("from 10 to 11: within")
-__msg("11: R0=0 R6=" ALONE(255, 0xff) " R7=" ALONE(255, 0xff))
-__naked void two_old_ids_one_cur_id(void)
-{
- asm volatile (
- /* Give unique scalar IDs to r{6,7} */
- "call %[bpf_ktime_get_ns];"
- "r0 &= 0xff;"
- "r6 = r0;"
- "r8 = r0;"
- "call %[bpf_ktime_get_ns];"
- "r0 &= 0xff;"
- "r7 = r0;"
- "r9 = r0;"
- "r0 = 0;"
- /* Maybe make r{6,7} IDs identical */
- "if r6 <= r7 goto l1_%=;"
- "r6 = r7;"
-"l1_%=:"
- /*
- * Get here in two states:
- * - first: r6{.id=A}, r7{.id=B}
- * - second: r6{.id=B}, r7{.id=B}
- * Currently we don't want to consider the second one to be within
- * the first one. Thus they are joined.
- */
- "r2 = r10;"
- "r2 += r6;"
- "r2 += r7;"
- /*
- * keep r8 and r9 live, otherwise r6->id and r7->id
- * will become singular and reset to zero before if r6 <= r7
- */
- "r9 += r8;"
- "exit;"
- :
- : __imm(bpf_ktime_get_ns)
- : __clobber_all);
-}
-
SEC("socket")
/* Note the flag, see verifier.c:opt_subreg_zext_lo32_rnd_hi32() */
__flag(BPF_F_TEST_RND_HI32)
@@ -808,7 +754,7 @@ __naked void linked_regs_and_subreg_def(void)
* at runtime), which must be rejected.
*/
SEC("socket")
-__failure __msg("R0 max value is outside of the allowed memory range")
+__failure __msg("invalid access to map value, value_size=8 off=8 size=1")
__naked void ldsx_fill_scalar_id_not_shared(void)
{
asm volatile (" \
diff --git a/tools/testing/selftests/bpf/progs/verifier_scev.c b/tools/testing/selftests/bpf/progs/verifier_scev.c
index 5c9c832fbbe07e..a79c00a99c8939 100644
--- a/tools/testing/selftests/bpf/progs/verifier_scev.c
+++ b/tools/testing/selftests/bpf/progs/verifier_scev.c
@@ -135,7 +135,7 @@ exit_%=: \
SEC("xdp")
__success
__log_level(2)
-__msg("8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -> ?")
+__msg("8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -> %fp-8.8?")
__naked void indirect_write_invalidates_scev(void)
{
asm volatile (" \
@@ -165,7 +165,7 @@ __noinline int global_noop_counter(__u64 *p)
SEC("xdp")
__success
__log_level(2)
-__msg("8: (85) call pc+{{[0-9]+}} {{.*}}; *fp-8 (+ *fp-8 1) -> ?")
+__msg("8: (85) call pc+{{[0-9]+}} {{.*}}; *fp-8 (+ *fp-8 1) -> %fp-8.8?")
__naked void global_call_invalidates_scev(void)
{
asm volatile (
@@ -242,7 +242,7 @@ SEC("xdp")
__success __retval(0)
__log_level(2)
__msg_next("scev at header 1:")
-__msg_next(" r6=(any r6 (+ r6 1)) / ?")
+__msg_next(" r6=%r6.1=phi(r6, (+ r6 1)) / ?")
__naked void meet_disagrees(void)
{
asm volatile (" \
@@ -261,6 +261,37 @@ __naked void meet_disagrees(void)
: __clobber_all);
}
+/* 'if (c) sum += a; else sum += b;': two loads, one way to compute the sum */
+SEC("socket")
+__success
+__log_level(2)
+__msg("scev at header 3:")
+__msg_next(" r6=%r6.9=phi((+ r6 _)) / ?")
+__naked void phi_operands_have_no_defs(void)
+{
+ asm volatile (" \
+ r9 = r1; \
+ r6 = 0; \
+ r7 = 0; \
+1: \
+ if r7 & 1 goto 2f; \
+ r2 = *(u32 *)(r9 + %[len]); \
+ r6 += r2; \
+ goto 3f; \
+2: \
+ r2 = *(u32 *)(r9 + %[mark]); \
+ r6 += r2; \
+3: \
+ r7 += 1; \
+ if r7 < 10 goto 1b; \
+ r0 = r6; \
+ exit; \
+" :
+ : __imm_const(len, offsetof(struct __sk_buff, len)),
+ __imm_const(mark, offsetof(struct __sk_buff, mark))
+ : __clobber_all);
+}
+
/* Both entry state values for r1 should be accounted for */
SEC("xdp")
__success
@@ -324,30 +355,31 @@ __msg("r1 += 2 {{.*}}; r1 r6 -> (+ r6 2)")
__msg("r1 += r7 {{.*}}; r1 r6 -> (+ r6 r7)")
__msg("w1 += 2 {{.*}}; r1 r6 -> (zext32 (+ r6 2))")
__msg("w1 += w7 {{.*}}; r1 r6 -> (zext32 (+ r6 r7))")
-__msg("r1 -= 2 {{.*}}; r1 r6 -> (- r6 2)")
+__msg("r1 -= 2 {{.*}}; r1 r6 -> (+ r6 -2)")
__msg("r1 -= r7 {{.*}}; r1 r6 -> (- r6 r7)")
-__msg("w1 -= 2 {{.*}}; r1 r6 -> (zext32 (- r6 2))")
+__msg("w1 -= 2 {{.*}}; r1 r6 -> (zext32 (+ r6 -2))")
__msg("w1 -= w7 {{.*}}; r1 r6 -> (zext32 (- r6 r7))")
+__msg("r1 -= 2 {{.*}}; r1 (+ r6 2) -> r6")
__msg("r1 *= 2 {{.*}}; r1 r6 -> (* r6 2)")
__msg("r1 *= r7 {{.*}}; r1 r6 -> (* r6 r7)")
__msg("w1 *= 2 {{.*}}; r1 r6 -> (zext32 (* r6 2))")
__msg("w1 *= w7 {{.*}}; r1 r6 -> (zext32 (* r6 r7))")
__msg("r1 /= 2 {{.*}}; r1 r6 -> (/ r6 2)")
__msg("r1 /= r7 {{.*}}; r1 r6 -> (/ r6 r7)")
-__msg("w1 /= 2 {{.*}}; r1 r6 -> (zext32 (/ r6 2))")
-__msg("w1 /= w7 {{.*}}; r1 r6 -> (zext32 (/ r6 r7))")
+__msg("w1 /= 2 {{.*}}; r1 r6 -> (zext32 (/ (zext32 r6) 2))")
+__msg("w1 /= w7 {{.*}}; r1 r6 -> (zext32 (/ (zext32 r6) (zext32 r7)))")
__msg("r1 s/= 2 {{.*}}; r1 r6 -> (s/ r6 2)")
__msg("r1 s/= r7 {{.*}}; r1 r6 -> (s/ r6 r7)")
-__msg("w1 s/= 2 {{.*}}; r1 r6 -> (zext32 (s/ r6 2))")
-__msg("w1 s/= w7 {{.*}}; r1 r6 -> (zext32 (s/ r6 r7))")
+__msg("w1 s/= 2 {{.*}}; r1 r6 -> (zext32 (s/ (sext32 r6) 2))")
+__msg("w1 s/= w7 {{.*}}; r1 r6 -> (zext32 (s/ (sext32 r6) (sext32 r7)))")
__msg("r1 %= 2 {{.*}}; r1 r6 -> (% r6 2)")
__msg("r1 %= r7 {{.*}}; r1 r6 -> (% r6 r7)")
-__msg("w1 %= 2 {{.*}}; r1 r6 -> (zext32 (% r6 2))")
-__msg("w1 %= w7 {{.*}}; r1 r6 -> (zext32 (% r6 r7))")
+__msg("w1 %= 2 {{.*}}; r1 r6 -> (zext32 (% (zext32 r6) 2))")
+__msg("w1 %= w7 {{.*}}; r1 r6 -> (zext32 (% (zext32 r6) (zext32 r7)))")
__msg("r1 s%= 2 {{.*}}; r1 r6 -> (s% r6 2)")
__msg("r1 s%= r7 {{.*}}; r1 r6 -> (s% r6 r7)")
-__msg("w1 s%= 2 {{.*}}; r1 r6 -> (zext32 (s% r6 2))")
-__msg("w1 s%= w7 {{.*}}; r1 r6 -> (zext32 (s% r6 r7))")
+__msg("w1 s%= 2 {{.*}}; r1 r6 -> (zext32 (s% (sext32 r6) 2))")
+__msg("w1 s%= w7 {{.*}}; r1 r6 -> (zext32 (s% (sext32 r6) (sext32 r7)))")
__msg("r1 |= 2 {{.*}}; r1 r6 -> (| r6 2)")
__msg("r1 |= r7 {{.*}}; r1 r6 -> (| r6 r7)")
__msg("w1 |= 2 {{.*}}; r1 r6 -> (zext32 (| r6 2))")
@@ -363,19 +395,19 @@ __msg("w1 ^= w7 {{.*}}; r1 r6 -> (zext32 (^ r6 r7))")
__msg("r1 <<= 2 {{.*}}; r1 r6 -> (<< r6 2)")
__msg("r1 <<= r7 {{.*}}; r1 r6 -> (<< r6 r7)")
__msg("w1 <<= 2 {{.*}}; r1 r6 -> (zext32 (<< r6 2))")
-__msg("w1 <<= w7 {{.*}}; r1 r6 -> (zext32 (<< r6 r7))")
+__msg("w1 <<= w7 {{.*}}; r1 r6 -> (zext32 (<< r6 (& r7 31)))")
__msg("r1 >>= 2 {{.*}}; r1 r6 -> (>> r6 2)")
__msg("r1 >>= r7 {{.*}}; r1 r6 -> (>> r6 r7)")
-__msg("w1 >>= 2 {{.*}}; r1 r6 -> (zext32 (>> r6 2))")
-__msg("w1 >>= w7 {{.*}}; r1 r6 -> (zext32 (>> r6 r7))")
+__msg("w1 >>= 2 {{.*}}; r1 r6 -> (zext32 (>> (zext32 r6) 2))")
+__msg("w1 >>= w7 {{.*}}; r1 r6 -> (zext32 (>> (zext32 r6) (& r7 31)))")
__msg("r1 s>>= 2 {{.*}}; r1 r6 -> (s>> r6 2)")
__msg("r1 s>>= r7 {{.*}}; r1 r6 -> (s>> r6 r7)")
-__msg("w1 s>>= 2 {{.*}}; r1 r6 -> (zext32 (s>> r6 2))")
-__msg("w1 s>>= w7 {{.*}}; r1 r6 -> (zext32 (s>> r6 r7))")
+__msg("w1 s>>= 2 {{.*}}; r1 r6 -> (zext32 (s>> (sext32 r6) 2))")
+__msg("w1 s>>= w7 {{.*}}; r1 r6 -> (zext32 (s>> (sext32 r6) (& r7 31)))")
__msg("r1 = -r1 {{.*}}; r1 r6 -> (- r6)")
__msg("w1 = -w1 {{.*}}; r1 r6 -> (zext32 (- r6))")
__msg("r1 = 42 {{.*}}; r1 r6 -> 42")
-__msg("w1 = 42 {{.*}}; r1 r6 -> (zext32 42)")
+__msg("w1 = 42 {{.*}}; r1 r6 -> 42")
__msg("r1 = r7 {{.*}}; r1 r6 -> r7")
__msg("w1 = w7 {{.*}}; r1 r6 -> (zext32 r7)")
__msg("r1 = (s8)r6 {{.*}}; r1 r6 -> (sext8 r6)")
@@ -417,6 +449,7 @@ __naked void alu_ops_exprs(void)
ALU_OP("r1 -= r7")
ALU_OP("w1 -= 2")
ALU_OP("w1 -= w7")
+ ALU_OP("r1 += 2; r1 -= 2")
ALU_OP("r1 *= 2")
ALU_OP("r1 *= r7")
ALU_OP("w1 *= 2")
@@ -511,7 +544,7 @@ __msg("*(u16 *)(r10 -8) = r1 {{.*}}; *fp-8 -8 -> (spill16 1)")
__msg("*(u8 *)(r10 -8) = r1 {{.*}}; *fp-8 -8 -> (spill8 1)")
__msg("r1 = *(u64 *)(r10 -8) {{.*}}; r1 1 -> -8")
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-__msg("r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -> (zext32 -8)")
+__msg("r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -> 4294967288")
__msg("r1 = *(u16 *)(r10 -8) {{.*}}; r1 1 -> (zext16 -8)")
__msg("r1 = *(u8 *)(r10 -8) {{.*}}; r1 1 -> (zext8 -8)")
__msg("r1 = *(s32 *)(r10 -8) {{.*}}; r1 1 -> (sext32 -8)")
@@ -519,7 +552,7 @@ __msg("r1 = *(s16 *)(r10 -8) {{.*}}; r1 1 -> (sext16 -8)")
__msg("r1 = *(s8 *)(r10 -8) {{.*}}; r1 1 -> (sext8 -8)")
__msg("r1 = load_acquire((u8 *)(r10 -8)) {{.*}}; r1 1 -> (zext8 -8)")
__msg("r1 = load_acquire((u16 *)(r10 -8)) {{.*}}; r1 1 -> (zext16 -8)")
-__msg("r1 = load_acquire((u32 *)(r10 -8)) {{.*}}; r1 1 -> (zext32 -8)")
+__msg("r1 = load_acquire((u32 *)(r10 -8)) {{.*}}; r1 1 -> 4294967288")
#else
__msg("r1 = *(u32 *)(r10 -8) {{.*}}; r1 1 -> (>> -8 32)")
__msg("r1 = *(u16 *)(r10 -8) {{.*}}; r1 1 -> (>> -8 48)")
@@ -536,13 +569,18 @@ __msg("store_release((u8 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> (spill8 1)")
__msg("store_release((u16 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> (spill16 1)")
__msg("store_release((u32 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> (spill32 1)")
__msg("store_release((u64 *)(r10 -8), r1) {{.*}}; *fp-8 -8 -> 1")
-__msg("lock *(u64 *)(r10 -8) += r1 {{.*}}; *fp-8 -8 -> _")
-__msg("r1 = atomic64_fetch_add((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> _, *fp-8 -8 -> _")
-__msg("r1 = atomic_fetch_add((u32 *)(r10 -8), r1) {{.*}}; r1 1 -> _, *fp-8 -8 -> _")
-__msg("r1 = atomic64_xchg((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> _, *fp-8 -8 -> _")
-__msg("r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r2) {{.*}}; r0 0 -> _, *fp-8 -8 -> _")
+__msg("lock *(u64 *)(r10 -8) += r1 {{.*}}; *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r1 = atomic64_fetch_add((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> %r1.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r1 = atomic_fetch_add((u32 *)(r10 -8), r1) {{.*}}; r1 1 -> %r1.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r1 = atomic64_xchg((u64 *)(r10 -8), r1) {{.*}}; r1 1 -> %r1.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+__msg("r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r2) {{.*}}; r0 0 -> %r0.{{[0-9]+}}, *fp-8 -8 -> %fp-8.{{[0-9]+}}")
__msg("*(u64 *)(r10 -8) = 42 {{.*}}; *fp-8 -8 -> 42")
-__msg("*(u8 *)(r10 -7) = r0 {{.*}}; *fp-8 -8 -> _")
+__msg("*(u8 *)(r10 -7) = r0 {{.*}}; *fp-8 -8 -> %fp-8.{{[0-9]+}}")
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+/* a fill that is not wider than the spill reads what was spilled */
+__msg("r1 = *(s8 *)(r10 -8) {{.*}}; r1 r7 -> (sext8 r7)")
+__msg("r1 = *(u16 *)(r10 -8) {{.*}}; r1 r7 -> (zext16 (spill8 r7))")
+#endif
__naked void store_load_exprs(void)
{
asm volatile (
@@ -579,6 +617,9 @@ __naked void store_load_exprs(void)
ST_OP("*(u64 *)(r10 - 8) = 42")
ST_OP("*(u8 *)(r10 - 7) = r0")
+ ST_OP("r1 = r7; *(u16 *)(r10 - 8) = r1; r1 = *(s8 *)(r10 - 8)")
+ ST_OP("r1 = r7; *(u8 *)(r10 - 8) = r1; r1 = *(u16 *)(r10 - 8)")
+
"r7 += 1;"
"if r7 < 2 goto 1b;"
"r0 = 0;"
@@ -607,10 +648,10 @@ __success
__log_level(2)
__msg_next("scev at header 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=?")
+__msg_next(" r7=%r7.4?")
__msg_next(" scev at latch 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=?")
+__msg_next(" r7=%r7.4?")
__msg_next("scev at header 4:")
__msg_next(" r7=(+ r7 1) / (linear r7 1)")
__msg_next(" scev at latch 4:")
@@ -647,7 +688,7 @@ __msg_next(" backedge from 6, latch at 4")
__msg_next(" exit from 4 to 1")
__msg("scev at header 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=?")
+__msg_next(" r7=%r7.4?")
__msg_next("scev at header 4:")
__msg_next(" r7=(+ r7 1) / (linear r7 1)")
__msg_next(" scev at latch 4:")
@@ -692,7 +733,7 @@ __msg_next(" backedge from 5, latch at 5")
__msg_next(" exit from 4 to 2")
__msg_next(" exit from 5 to 6")
__msg("scev at header 2:")
-__msg_next(" r6=?")
+__msg_next(" r6=%r6.3?")
__msg_next(" r7=(+ r7 1) / (linear r7 1)")
__msg_next("scev at header 3:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
@@ -727,8 +768,8 @@ __log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
__msg("loop at 3{{$}}")
__msg("scev at header 3:")
-__msg_next(" r6=(any r6 (+ r6 1)) / ?")
-__msg_next(" r7=(any (+ r7 1) 0) / ?")
+__msg_next(" r6=%r6.3=phi(r6, (+ r6 1)) / ?")
+__msg_next(" r7=%r7.3=phi((+ r7 1), 0) / ?")
__msg_next(" r8=(+ r8 1) / (linear r8 1)")
__msg("loop header at 3, can't compute iterations count")
__naked void nested_loops_shared_header(void)
@@ -1159,6 +1200,50 @@ RANGE_TEST(range_ge_dir, "", 10, 20, 2, 3, 5, PRE("<"), NO_COUNT)
RANGE_TEST(range_ne_step2, "", 0, 3, 2, 3, 8, PRE("=="), NO_COUNT)
RANGE_TEST(range_ne_behind, "", 0, 4, 1, 3, 8, PRE("=="), NO_COUNT)
+/*
+ * char buf[8];
+ * for (int i = first; ...; i++)
+ * sum += buf[i - first];
+ *
+ * GCC adds in 32 bits and keeps the sign extension of the result: a sign-extended 32-bit induction
+ * variable. r6 or fp-16 is i, r7 is first, r9 counts the iterations. r8 is 0, which the verifier
+ * doesn't know. In place of an out-of-bounds access to buf r5 is read, which is not initialized.
+ */
+#define SEXT32_TEST(name, _first, loop, expect) \
+SEC("socket") \
+__log_level(2) \
+expect \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "r6 = %[first] ll; r7 = r6; r8 = 0; r9 = 0;" \
+ "*(u64 *)(r10 - 8) = r8; lock *(u64 *)(r10 - 8) += r8; r8 = *(u64 *)(r10 - 8);" \
+ "*(u64 *)(r10 - 16) = r6;" \
+ loop \
+ "2: r0 = r9; exit;" \
+ : \
+ : __imm_const(first, _first) \
+ : __clobber_all); \
+}
+#define BUF(i) "r9 += 1; r2 = " i "; r2 -= r7; if r2 <= 7 goto +1; r0 = *(u64 *)(r5 + 0);"
+#define OOB __failure __msg("R5 !read_ok")
+#define ALL_OF_S32 "0xffffffff80000000..0x7fffffff "
+#define SEXT32_INC "w1 = w6; w1 += 1; r6 = (s32)r1;"
+#define SEXT32_LOOP(bound) "1:" BUF("r6") SEXT32_INC "if w1 != " #bound " goto 1b;"
+
+SEXT32_TEST(sext32_iv, -4, SEXT32_LOOP(4), __success __retval(8)
+ __msg(" r6=(sext32 (+ r6 1)) / (sext32 (linear r6 1))")
+ __msg("header_count is 8 ") __msg("widening r6 to -4..3 "))
+SEXT32_TEST(sext32_iv_oob, -4, SEXT32_LOOP(5), OOB)
+/* i wraps from INT32_MAX to INT32_MIN. The latch tests 0x7ffffffd .. 0x80000004. */
+SEXT32_TEST(sext32_iv_wraps, INT32_MAX - 3, SEXT32_LOOP(0x80000004),
+ __msg("header_count is 8 ") __msg("widening r6 to " ALL_OF_S32) OOB)
+/* 'i < n' implies the unsigned range 1 .. 0x80000000. Its last value is negative in r6. */
+SEXT32_TEST(sext32_iv_unsigned_bound, 0,
+ "r8 &= 1; r6 += r8; r4 = 0x80000001 ll;"
+ "1:" SEXT32_INC "if w1 < w4 goto 1b; if r6 s>= 0 goto 2f; r0 = *(u64 *)(r5 + 0);",
+ __msg("widening r6 to " ALL_OF_S32) OOB)
+
/*
* Two back edges:
*
@@ -1529,7 +1614,7 @@ __success __retval(7)
__log_level(2)
__msg("scev at header 1:")
__msg_next("r6=(+ r6 1) / (linear r6 1)")
-__msg_next("*fp-8=(any *fp-8 7) / (any *fp-8 7)")
+__msg_next("*fp-8=%fp-8.3=phi(*fp-8, 7) / (any *fp-8 7)")
__msg("loop header at 1, widening r6 to 0..2 step 1")
__msg("3: (79) r0 = *(u64 *)(r10 -8) ; R0=scalar() R10=fp0 loop_stack=1")
__naked void widen_any_unallocated_slot(void)
@@ -1570,7 +1655,7 @@ __success __retval(7)
__log_level(2)
__msg("scev at header 2:")
__msg_next("r6=(+ r6 1) / (linear r6 1)")
-__msg_next("*fp-8=(any *fp-8 7) / (any *fp-8 7)")
+__msg_next("*fp-8=%fp-8.5=phi(*fp-8, 7) / (any *fp-8 7)")
__msg("loop header at 2, widening r6 to 0..2 step 1")
__msg("3: (79) r1 = *(u64 *)(r10 -8) ; R1=scalar() R10=fp0 fp-8=m???????")
__naked void widen_any_misc_slot(void)
@@ -1673,7 +1758,7 @@ __success
__log_level(2)
__msg("scev at header 4:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" *fp-8=?")
+__msg_next(" *fp-8=%fp-8.7?")
__msg("loop header at 4, widening r6 to 0..9 step 1")
__naked void widen_subprog_probe_read(void)
{
@@ -2336,12 +2421,14 @@ __naked __noinline __used static int returns_zero(void)
* A loop that the compiler unrolls in part has an exit for every 'break' and 'return' in every
* copy of its body. How many there are says nothing about the number of iterations.
* Scalar evolution takes a nested loop for one insn, and its exits are the successors of this insn.
- * The list of exits is not complete: the loop around has no formulas.
+ * The exit list is truncated: the enclosing loop has no SCEVs, the subprog is not analyzed.
*/
SEC("xdp")
__success __log_level(2)
__msg("loop at 1, too many exits, too many exits of a nested loop")
__msg("loop at 2, nested in 1, too many exits")
+__msg("Computing SCEV for subprog at 0:")
+__msg_next("Computing SCEV for subprog at {{[0-9]+}}:")
__msg("loop header at 1, unsupported loop: too many exits of a nested loop")
__msg("loop header at 2, header_count is [0..4] ")
__naked void loop_around_301_exits(void)
@@ -2594,7 +2681,7 @@ __msg("loop at 1{{$}}")
__msg("loop at 5, nested in 1, irreducible")
__msg("loop at 11, nested in 5")
__msg("scev at header 1:")
-__msg_next(" r6=?")
+__msg_next(" r6=%r6.5?")
__msg("scev at header 11:")
__msg_next(" r9=(+ r9 1) / (linear r9 1)")
__msg("loop header at 11, widening r9 to 0..2 step 1")
@@ -2841,7 +2928,7 @@ __success
__log_level(2)
__msg("scev at header 2:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
-__msg_next(" r7=(any r7 100) / (any r7 100)")
+__msg_next(" r7=%r7.6=phi(r7, 100) / (any r7 100)")
__msg_next(" scev at latch 3:")
__msg_next(" r6=(+ r6 1) / (linear (+ r6 1) 1)")
__msg_next(" r7=r7 / (any r7 100)")
@@ -3116,12 +3203,12 @@ __naked void name(void) \
#define NOT_UNROLLED "widening r6 to 0..0xf423f step 1"
/* 'if (...) cnt++' */
-PARTIAL_SPILL_TEST(partial_spill32_inc, u32, 10, "can't widen *fp-8, expr is (any *fp-8 (spill32 ",
+PARTIAL_SPILL_TEST(partial_spill32_inc, u32, 10, "can't widen *fp-8, expr is %fp-8.{{[0-9]+}}=phi(*fp-8, (spill32 ",
SPILL32_0, "if r6 & 1 goto 2f;" SPILL32_INC "2:")
PARTIAL_SPILL_TEST(partial_spill16_inc, u16, 10, "can't widen *fp-8, expr is (spill16 ",
"*(u16 *)(r10 - 8) = r1;", "r1 = *(u16 *)(r10 - 8); w1 += 1; *(u16 *)(r10 - 8) = r1;")
/* A loop in the loop does it */
-PARTIAL_SPILL_TEST(partial_spill32_inc_in_nested_loop, u32, 10, "can't widen *fp-8, expr is ?",
+PARTIAL_SPILL_TEST(partial_spill32_inc_in_nested_loop, u32, 10, "can't widen *fp-8, expr is %fp-8.{{[0-9]+}}?",
SPILL32_0, "r7 = 0; 2:" SPILL32_INC "r7 += 1; if r7 < 3 goto 2b;")
/* Two slots feed each other */
PARTIAL_SPILL_TEST(partial_spill32_two_slots, u32, 10, "can't widen *fp-8, expr is (spill32 ",
@@ -3185,6 +3272,14 @@ RANGE_TEST(spill32_first_is_precise, "", 0, 0, 1, 0, 1,
RANGE_TEST(spill32_first_is_64bit, "", 0, 0, 1, 5, 5,
"*(u64 *)(r10 - 8) = r6; 1:" LIMIT_ITERATIONS SPILL32_INC "if w1 != w7 goto 1b;",
SPILL32_COUNTED(5, "0..4"))
+/* A 64-bit spill of i. Its upper 32 bits are dead: the low 32 bits are the induction variable. */
+#define SEXT32_SPILL_LOOP(bound) \
+ "1:" BUF("*(u32 *)(r10 - 16)") "w1 = *(u32 *)(r10 - 16); w1 += 1; r3 = (s32)r1;" \
+ "*(u64 *)(r10 - 16) = r3; if w1 != " #bound " goto 1b;"
+SEXT32_TEST(sext32_iv_hi32_dead, 0, SEXT32_SPILL_LOOP(8), __success __retval(8)
+ __msg(" *fp-16=(sext32 (+ *fp-16 1)) / (spill32 (linear (zext32 *fp-16) 1))")
+ __msg("header_count is 8 ") __msg("widening *fp-16 to 0..7 "))
+SEXT32_TEST(sext32_iv_hi32_dead_oob, 0, SEXT32_SPILL_LOOP(9), OOB)
/* The counter makes the address of a spill. Such a loop is not summarized, as with a register. */
PARTIAL_SPILL_TEST(spill32_is_a_stack_offset, u32, 4,
"can't widen *fp-8, expr is (spill32 (+ *fp-8 8)), requires exact stack-offset tracking",
@@ -3286,7 +3381,7 @@ NOT_LINEAR_TEST(zext32_or_nothing, "r7 >>= 8;", "if r8 == 0 goto +1; w7 = w7;",
NOT_LINEAR_TEST(and_64_to_127, "r7 &= 63; r7 |= 64;", "r7 &= 127;", UNROLLED("(& r7 127)"))
/* '>>' does not make a number greater, but iterations one by one tell more: 0 after 8 shifts */
NOT_LINEAR_TEST(rsh_on_one_path, "r7 &= 255;", "if r8 == 0 goto +1; r7 >>= 1;",
- UNROLLED("(any r7 (>> r7 1))"))
+ UNROLLED("%r7.8=phi(r7, (>> r7 1))"))
NOT_LINEAR_TEST(rsh_then_and, "r7 &= 255;", "r7 >>= 1; r7 &= r8;", UNROLLED("(& (>> r7 1) r8)"))
NOT_LINEAR_TEST(lsh_grows, "r7 &= 15;", "r7 <<= 1;", UNROLLED("(<< r7 1)"))
@@ -3295,42 +3390,293 @@ NOT_LINEAR_TEST(lsh_grows, "r7 &= 15;", "r7 <<= 1;", UNROLLED("(<< r7 1)"))
NOT_LINEAR_TEST(same_constant, "r7 = 17;", "r7 &= 31;", NOT_CHANGED)
NOT_LINEAR_TEST(same_wide_constant, "r7 = 0xffffffff00000011 ll;", "r7 &= -239;", NOT_CHANGED)
-#ifdef __BPF_FEATURE_ADDR_SPACE_CAST
struct {
- __uint(type, BPF_MAP_TYPE_ARENA);
- __uint(map_flags, BPF_F_MMAPABLE);
+ __uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
-} arena SEC(".maps");
+ __type(key, __u32);
+ __type(value, char[64]);
+} map64 SEC(".maps");
-/* The offset of a pointer to arena is not tracked */
-#define ARENA_TEST(name, op, expect) \
-SEC("syscall") \
-__log_level(2) \
-expect \
+/*
+ * A conditional jump refines the registers and stack slots that are linked to what it tests.
+ * r6: 64 bytes. r7: a scalar below 256. r8: an unbounded scalar. r9: the context.
+ * The test leaves an address in r1.
+ */
+#define LINKED_SEC(sec, name, expect, body) \
+SEC(sec) expect \
__naked void name(void) \
{ \
asm volatile ( \
- "r1 = %[arena] ll;" \
- "r6 = 0;" \
- "r6 = addr_space_cast(r6, 0, 1);" \
- "r7 = 0;" \
-"1: *(u64 *)(r6 + 0) = r7;" \
- op \
- "r7 += 1;" \
- "if r7 < 100 goto 1b;" \
- "r0 = 0;" \
- "exit;" \
- :: __imm_addr(arena) : __clobber_all); \
+ "r9 = r1; r1 = 0; *(u32 *)(r10 - 4) = r1; r2 = r10; r2 += -4; r1 = %[map64] ll;" \
+ "call %[bpf_map_lookup_elem]; if r0 == 0 goto out_%=; r6 = r0;" \
+ "call %[bpf_get_prandom_u32]; r7 = r0; r7 &= 255;" \
+ "call %[bpf_ktime_get_ns]; r8 = r0;" \
+ body \
+ "r0 = *(u8 *)(r1 + 0);" \
+ "out_%=: r0 = 0; exit;" \
+ : \
+ : __imm(bpf_map_lookup_elem), __imm(bpf_get_prandom_u32), __imm(bpf_ktime_get_ns), \
+ __imm(bpf_dynptr_from_skb), __imm(bpf_dynptr_slice_rdwr), \
+ __imm(bpf_ringbuf_reserve), __imm(bpf_ringbuf_discard), __imm(bpf_loop), \
+ __imm_addr(map64), __imm_addr(ringbuf) \
+ : __clobber_all); \
+}
+#define LINKED(name, expect, body) LINKED_SEC("socket", name, expect, body)
+
+#define VALID __success __retval(0)
+#define MAP_OOB __failure __msg("invalid access to map value")
+#define UNBOUND __failure __msg("unbounded min value")
+
+/* r3 is the address in r1 as a scalar. It does not bound the offset of r1. */
+LINKED(pointer_is_not_scalar, __failure,
+ "r7 &= 127; r1 = r6; r1 += r7; r3 = r1; r3 = le64 r3; if r3 < 64 goto out_%=; r1 += -64;")
+
+/*
+ * p = buf + i; if (i > 63) return 0; c = *p;
+ * The jump bounds i. r1 is r6 + r7 and r6 is live: r1 is recomputed.
+ */
+#define USE_R6 "r0 = *(u8 *)(r6 + 0);"
+
+LINKED(index_tested_after_the_add, VALID, "r1 = r6; r1 += r7; if r7 > 63 goto out_%=;" USE_R6)
+LINKED(low_32_bits_of_the_index_tested, __failure __msg("R1 unbounded memory access"),
+ "r2 = 0x1000000ff ll; r2 &= r8; r1 = r6; r1 += r2; w3 = w2; if r3 > 63 goto out_%=;" USE_R6)
+/* r7 is -2 or 5. Its low 2 bits are not 3: the path is infeasible, and r6 + r7 + 2 is empty. */
+LINKED(index_is_empty, VALID __flag(BPF_F_TEST_REG_INVARIANTS),
+ "r7 &= 1; r7 *= 7; r7 += -2; r1 = r6; r1 += r7; r1 += 2; if r7 & 1 goto l_%=; goto out_%=;"
+ "l_%=: if r7 & 2 goto m_%=; goto out_%=; m_%=: r1 += 1;" USE_R6)
+
+/*
+ * static void clamp(struct buf *b) { if (b->len > 63) b->len = 0; }
+ * clamp(&b); c = b.data[b.len];
+ * The callee tests memory of its caller: the slot is refined. Not if it may have been written since
+ * the load. r1 and r4 point to b.len, r2 is not bounded.
+ */
+#define CLAMP(name, before_the_jump) \
+static __naked __noinline __used void name(void) \
+{ \
+ asm volatile ( \
+ "r3 = *(u64 *)(r1 + 0);" before_the_jump \
+ "if r3 <= 63 goto +2; r3 = 0; *(u64 *)(r1 + 0) = r3; r0 = 0; exit;" \
+ ::: __clobber_all); \
+}
+#define CALL(callee) \
+ "*(u64 *)(r10 - 16) = r8; r1 = r10; r1 += -16; r4 = r1; r2 = r8; r2 >>= 1;" \
+ "call " #callee "; r2 = *(u64 *)(r10 - 16); r1 = r6; r1 += r2;"
+
+CLAMP(clamp, "")
+LINKED(callee_tests_memory_of_caller, VALID, CALL(clamp))
+CLAMP(store_and_clamp, "*(u64 *)(r1 + 0) = r2;")
+LINKED(callee_writes_memory_of_caller, __failure, CALL(store_and_clamp))
+/* a store defines the memory */
+CLAMP(store_and_test, "r3 = r2; *(u64 *)(r1 + 0) = r3;")
+LINKED(callee_tests_what_it_stored, VALID, CALL(store_and_test))
+/* the same address base, no overlap */
+CLAMP(store_next_and_clamp, "*(u64 *)(r1 + 8) = r2;")
+LINKED(callee_writes_next_field, VALID, CALL(store_next_and_clamp))
+/* another address base can be another name of the memory */
+CLAMP(store_alias_and_clamp, "*(u64 *)(r4 + 0) = r2;")
+LINKED(callee_writes_through_alias, __failure, CALL(store_alias_and_clamp))
+
+/*
+ * struct { char *buf; u64 len; } c = { buf, 0 }; bpf_loop(100, append, &c, 0);
+ * append: if (c->len > 63) return 1; bpf_get_prandom_u32(); c->buf[c->len]; c->len++;
+ * The compiler loads c->len again after a call. c is on the stack of the caller, where len grows
+ * until it is widened. The jump refines that slot: it still holds what the tested register was
+ * loaded from.
+ */
+#define APPEND(name, before_the_jump) \
+static __naked __used void name(void) \
+{ \
+ asm volatile ( \
+ "r6 = r2; r1 = *(u64 *)(r6 + 8);" before_the_jump \
+ "if r1 > 63 goto l_%=;" \
+ "call %[bpf_get_prandom_u32];" \
+ "r2 = *(u64 *)(r6 + 8); r1 = *(u64 *)(r6 + 0); r1 += r2; r0 = *(u8 *)(r1 + 0);" \
+ "r2 += 1; *(u64 *)(r6 + 8) = r2; r0 = 0; exit;" \
+ "l_%=: r0 = 1; exit;" \
+ :: __imm(bpf_get_prandom_u32) : __clobber_all); \
}
+#define CALL_APPEND(name) \
+ "*(u64 *)(r10 - 16) = r6; r1 = 0; *(u64 *)(r10 - 8) = r1;" \
+ "r1 = 100; r2 = " #name " ll; r3 = r10; r3 += -16; r4 = 0; call %[bpf_loop]; r1 = r6;"
+
+APPEND(append, "")
+LINKED(callback_tests_slot_of_caller, VALID, CALL_APPEND(append))
+/* The slot is written between the load and the jump: len is 0 1 3 7 15 31 63, the slot 126 */
+APPEND(append_stale, "r2 = r1; r2 <<= 1; *(u64 *)(r6 + 8) = r2;")
+LINKED(callback_tests_stale_copy_of_slot, UNBOUND, CALL_APPEND(append_stale))
-#define NOT_UNROLLED100 __msg("loop header at 5, widening r7 to 0..99 step 1")
-/* A loop that moves the pointer is not unrolled */
-ARENA_TEST(arena_pointer_moves, "r6 += 8;", __success NOT_UNROLLED100)
-/* The loop makes a number of it: the state that returns to the loop header tells */
-ARENA_TEST(arena_pointer_becomes_a_number, "if r7 != 5 goto +1; r6 = 4096;",
- __failure NOT_UNROLLED100 __msg("R6 invalid mem access 'scalar'"))
+/*
+ * p = buf; i = 0; do { if (i > 62) break; i = *(u16 *)p; p = buf + i; } while (i);
+ * r1 == r6 + r2 at the header in every iteration: it holds at loop entry, the backedge preserves it
+ */
+#define LOOP(add) \
+ "l_%=: if r2 > 62 goto out_%=; r2 = *(u16 *)(r1 + 0);" add \
+ "if r2 != 0 goto l_%=; r1 = r6;"
+
+LINKED(base_plus_index_at_loop_header, VALID, "r1 = r6; r2 = 0;" LOOP("r1 = r6; r1 += r2;"))
+LINKED(base_plus_index_at_loop_entry_only, MAP_OOB,
+ "r1 = r6; r2 = 0;" LOOP("r1 = r6; r1 += r2; r2 >>= 1;"))
+LINKED(base_plus_index_on_backedge_only, MAP_OOB,
+ "r1 = r6; r1 += r7; r2 = r8; r2 &= 255;" LOOP("r1 = r6; r1 += r2;"))
+
+LINKED(sign_extension_that_fits, VALID, "r2 = (s8)r8; if r8 > 63 goto out_%=; r1 = r6; r1 += r2;")
+
+/* 'int n' in three registers. 'if w3 s> 63' refines only 32-bit ranges: those of the copies too. */
+LINKED(copies_get_the_32_bit_range, VALID,
+ "w2 = w8; r3 = r2; r4 = r2; if w3 s> 63 goto out_%=; if w4 s< 0 goto out_%=;"
+ "r1 = r6; r1 += r2;")
+
+/* A copy on each of two paths: r2 and r3 are phis with the same operands, up to a constant */
+#define TWO_PATHS(a, b) \
+ "if r7 > 9 goto l_%=; r2 = r8; " a " goto m_%=; l_%=: r2 = r8; r2 >>= 1; " b \
+ "m_%=: if r2 > 62 goto out_%=; r1 = r6; r1 += r3;"
+
+LINKED(congruent_phis, VALID, TWO_PATHS("r3 = r2; r3 += 1;", "r3 = r2; r3 += 1;"))
+LINKED(phis_with_other_delta_on_one_path, UNBOUND,
+ TWO_PATHS("r3 = r2; r3 += 1;", "r3 = r2; r3 += 2;"))
+/* One of three edges brings unrelated values */
+LINKED(phis_not_linked_on_one_of_three_edges, UNBOUND,
+ "r3 = r8; r3 >>= 2; r2 = 0; if r7 == 20 goto m_%=;"
+ TWO_PATHS("r3 = r2; r3 += 1;", "r3 = r2; r3 += 1;"))
+/* (zext32 x) on both paths: linked in 64 bits */
+LINKED(congruent_phis_of_zext32, VALID,
+ "if r7 > 9 goto l_%=; w2 = w8; r3 = r2; goto m_%=; l_%=: r2 = r8; r2 >>= 1; w2 = w2;"
+ "r3 = r2; m_%=: r3 += 1; if r2 > 62 goto out_%=; r1 = r6; r1 += r3;")
+
+/* The low 3 bits of r3 are 5. It is r8 + 5 once r8 fits in s8: no overlap with [-2, 1]. */
+LINKED(empty_intersection, VALID __flag(BPF_F_TEST_REG_INVARIANTS),
+ "r3 = (s8)r8; if r3 & 7 goto out_%=; r3 += 5; if r3 s> 100 goto out_%=;"
+ "if r3 s< -100 goto out_%=; if r8 s< -7 goto out_%=; if r8 s> -4 goto out_%=;"
+ "r3 += 3; r1 = r6;")
+
+/* r2 is even. It is r8 once r8 fits in s8. r8 is odd after the last jump: var_off don't overlap. */
+LINKED(var_off_dont_overlap, VALID,
+ "r2 = (s8)r8; if r2 & 1 goto out_%=; if r2 s> 100 goto out_%=; if r2 s< -100 goto out_%=;"
+ "if r8 > 5 goto out_%=; if r8 & 1 goto l_%=; goto out_%=;"
+ "l_%=: r2 &= 1; r2 <<= 6; r1 = r6; r1 += r2;")
+
+/* The low bytes of the spill to r10 - 16 come first or last */
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#define FIRST_BYTES_ARE_LOW VALID
+#else
+#define FIRST_BYTES_ARE_LOW __failure __msg("R1 unbounded memory access")
#endif
+/* r2 is the low 32 bits of the slot. The 32-bit spill is in its first half-slot. */
+LINKED(spill_32_bits_fill_64_take_low_half, FIRST_BYTES_ARE_LOW,
+ "*(u64 *)(r10 - 16) = r7; *(u32 *)(r10 - 16) = r8; r2 = *(u64 *)(r10 - 16); w2 = w2;"
+ "w3 = w8; if r2 > 63 goto out_%=; r1 = r6; r1 += r3;")
+/* The slot is a phi: two paths spill distinct values to its first half-slot */
+LINKED(spill_32_bits_on_two_paths_fill_64_take_low_half, FIRST_BYTES_ARE_LOW,
+ "*(u64 *)(r10 - 16) = r7; *(u32 *)(r10 - 16) = r8; if r7 > 9 goto l_%=;"
+ "r3 = r8; r3 >>= 1; *(u32 *)(r10 - 16) = r3;"
+ "l_%=: r2 = *(u64 *)(r10 - 16); w2 = w2; if r2 > 63 goto out_%=;"
+ "r3 = *(u32 *)(r10 - 16); r1 = r6; r1 += r3;")
+/* The half-slot at r10 - 12 is dead: at the second jump the state has a 32-bit spill */
+LINKED(spill_64_bits_fill_32, FIRST_BYTES_ARE_LOW,
+ "*(u64 *)(r10 - 16) = r8; if r8 s> 63 goto out_%=; if r8 s< 0 goto out_%=;"
+ "r2 = *(u32 *)(r10 - 16); r1 = r6; r1 += r2;")
+
+/* r0 is r10 - 24 when the first 8 bytes of the packet are not in one piece */
+LINKED_SEC("tc", slot_written_through_a_slice, UNBOUND,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -24; r4 = 8;"
+ "call %[bpf_dynptr_slice_rdwr]; if r0 == 0 goto out_%=;"
+ "r3 = *(u64 *)(r10 - 24); *(u64 *)(r0 + 0) = r8; r2 = *(u64 *)(r10 - 24);"
+ "if r3 > 63 goto out_%=; r1 = r6; r1 += r2;")
+/* One fill reads one value: r2 is a copy of r3, whatever is stored through the slice */
+LINKED_SEC("tc", copy_of_a_fill_from_a_slice_buffer, VALID,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -24; r4 = 8;"
+ "call %[bpf_dynptr_slice_rdwr]; if r0 == 0 goto out_%=;"
+ "r3 = *(u64 *)(r10 - 24); r2 = r3; *(u64 *)(r0 + 0) = r8;"
+ "if r3 > 63 goto out_%=; r1 = r6; r1 += r2;")
+
+/* The buffer is r10 - 32 or r10 - 48, a range in the state. The call does not write to r10 - 40. */
+LINKED_SEC("tc", slice_buffer_at_two_offsets, VALID,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "*(u64 *)(r10 - 32) = r7; *(u64 *)(r10 - 40) = r7; *(u64 *)(r10 - 48) = r7;"
+ "r8 = r10; r8 += -48; r9 = r10; r9 += -32; r7 = 0;"
+ "l_%=: call %[bpf_get_prandom_u32]; if r0 == 0 goto s_%=; r9 = r8;"
+ "s_%=: r7 += 1; if r7 < 64 goto l_%=;"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r9; r4 = 8; call %[bpf_dynptr_slice_rdwr];"
+ "r1 = *(u64 *)(r10 - 40); r1 = r6;")
+/* No insn stores through a slice of 0 bytes, and the call does not write to the buffer */
+LINKED_SEC("tc", slice_of_0_bytes_at_variable_offset, VALID,
+ "r1 = r9; r2 = 0; r3 = r10; r3 += -16; call %[bpf_dynptr_from_skb];"
+ "*(u64 *)(r10 - 24) = r7; *(u64 *)(r10 - 32) = r7; r7 &= 8;"
+ "r1 = r10; r1 += -16; r2 = 0; r3 = r10; r3 += -32; r3 += r7; r4 = 0;"
+ "call %[bpf_dynptr_slice_rdwr]; r1 = r6;")
+
+/* BTF of the kfuncs that only asm calls */
+void __kfunc_btf_root(void)
+{
+ bpf_dynptr_from_skb(0, 0, 0);
+ bpf_dynptr_slice_rdwr(0, 0, 0, 0);
+}
+
+/* Linked at the header in every iteration: r2 is r3 + 2 at loop entry, both have the step 1 */
+#define LOOP_HEADER(enter, step) \
+ enter "l_%=: if r3 > 61 goto out_%=; r1 = r6; r1 += r2; r0 = *(u8 *)(r1 + 0);" step \
+ "if r0 != 0 goto l_%=;"
+
+LINKED(linked_at_loop_header, VALID,
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 1; r3 += 1;"))
+LINKED(linked_at_loop_entry_only, __failure,
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 2; r3 += 1;"))
+
+/*
+ * An irreducible loop: 'l' is the header, 'm' is a secondary entry. A link that is made in the loop
+ * holds in the next basic blocks too. Not after 'm' if it is made before 'm': every edge of the
+ * loop to 'm' has it, the edge that enters the loop there does not. That edge can come from
+ * a natural loop 'o' around the irreducible one.
+ * In the last two tests 'o' is the header. The natural loop in it has an env at loop entry. Its
+ * header can be the secondary entry.
+ */
+LINKED(irreducible_loop, VALID,
+ "if r7 > 5 goto m_%=; l_%=: r7 += 1;"
+ "m_%=: r2 = r8; r2 += 1; r2 += 1; if r8 > 61 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=;")
+LINKED(irreducible_loop_fallthrough_pred, UNBOUND,
+ "r2 = r7; if r7 > 5 goto m_%=; l_%=: r7 += 1; r2 = r8;"
+ "m_%=: if r8 > 63 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=;")
+LINKED(irreducible_loop_next_bb, VALID,
+ "if r7 > 5 goto m_%=; l_%=: r7 += 1;"
+ "m_%=: r2 = r8; r2 += 1; r2 += 1; if r7 == 3 goto n_%=; r3 = 0;"
+ "n_%=: if r8 > 61 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=;")
+LINKED(irreducible_loop_secondary_entry, UNBOUND,
+ "r9 = 0; o_%=: r9 += 1; call %[bpf_ktime_get_ns]; r8 = r0; r2 = r7; if r7 > 5 goto m_%=;"
+ "l_%=: r7 += 1; r2 = r8; r2 += 1; r2 += 1; if r7 == 3 goto m_%=; r3 = 0;"
+ "m_%=: if r8 > 61 goto out_%=; r1 = r6; r1 += r2;"
+ "r0 = *(u8 *)(r1 + 0); if r7 < 10 goto l_%=; if r9 < 3 goto o_%=;")
+LINKED(natural_loop_in_irreducible_loop, VALID,
+ "if r7 > 5 goto m_%=; o_%=: r7 += 1; m_%=:"
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 1; r3 += 1;")
+ "if r7 < 10 goto o_%=;")
+LINKED(natural_loop_is_secondary_entry, MAP_OOB,
+ "r3 = r8; r2 = r7; if r7 > 5 goto l_%=; o_%=: r7 += 1;"
+ LOOP_HEADER("r3 = r8; r2 = r8; r2 += 1; r2 += 1;", "r2 += 1; r3 += 1;")
+ "if r7 < 10 goto o_%=;")
+
+/*
+ * No exit of the inner loop dominates its backedges: may_goto is added before its header. The prog
+ * holds a reference, so may_goto goes to the exit of the outer loop: an edge that the verifier
+ * adds. Every iteration of the outer loop restores r3. At the header of the inner one it is r7.
+ */
+LINKED(added_edge, UNBOUND,
+ "r1 = %[ringbuf] ll; r2 = 8; r3 = 0; call %[bpf_ringbuf_reserve]; if r0 == 0 goto out_%=;"
+ "*(u64 *)(r10 - 16) = r0; r3 = r8;"
+ "o_%=: r2 = r3; r3 = r7;"
+ "i_%=: r1 = *(u8 *)(r6 + 0); if r1 == 1 goto a_%=; if r1 == 2 goto b_%=; goto i_%=;"
+ "a_%=: goto i_%=;"
+ "b_%=: r3 = r2; r1 = *(u8 *)(r6 + 1); if r1 == 3 goto o_%=;"
+ "r4 = r6; if r8 > 63 goto r_%=; r4 += r3;"
+ "r_%=: *(u64 *)(r10 - 24) = r4; r1 = *(u64 *)(r10 - 16); r2 = 0;"
+ "call %[bpf_ringbuf_discard]; r1 = *(u64 *)(r10 - 24);")
+
/*
* r7 = ctx->data;
* r8 = r7
@@ -3448,9 +3794,9 @@ __failure
__log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
__msg("scev at header 9:")
-__msg_next(" r6=(+ ? 1) / ?")
+__msg_next(" r6=(+ %r6.13? 1) / ?")
__msg_next(" scev at latch 20:")
-__msg_next(" r6=(+ ? 1) / (+ ? 1)")
+__msg_next(" r6=(+ %r6.13? 1) / (+ %r6.13? 1)")
__msg_next("scev at header 13:")
__msg_next(" r9=(+ r9 1) / (linear r9 1)")
__msg_next(" scev at latch 16:")
@@ -3524,7 +3870,7 @@ SEC("xdp")
__success __retval(3)
__log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
-__msg("r6 = *(u64 *)(r10 -8) {{.*}}; r6 ? -> r6")
+__msg("r6 = *(u64 *)(r10 -8) {{.*}}; r6 %r6.4? -> r6")
__msg("scev at header 1:")
__msg_next(" r6=(+ r6 1) / (linear r6 1)")
__msg_next(" scev at latch 16:")
@@ -3645,7 +3991,7 @@ __success
__log_level(2)
__flag(BPF_F_TEST_STATE_FREQ)
__msg("scev at header 4:")
-__msg_next("r7=(any r7 8) / (any r7 8)")
+__msg_next("r7=%r7.11=phi(r7, 8) / (any r7 8)")
__msg("loop header at 4, can't widen r7, expr is {{.*}}, requires exact stack-offset tracking")
__naked void no_widen_stack_fill_any(void)
{
@@ -4419,7 +4765,7 @@ SEC("socket")
__success __retval(0)
__log_level(2)
__msg("header_count is 100000 ")
-__msg("can't widen r6, expr is _")
+__msg("can't widen r6, expr is %r6.13")
__not_msg("widening r8")
__msg("clamping r8 to 0..0x1869f step 1")
__naked void index_loaded_in_previous_iteration(void)
diff --git a/tools/testing/selftests/bpf/progs/verifier_spill_fill.c b/tools/testing/selftests/bpf/progs/verifier_spill_fill.c
index 0baa8e06b8d1ef..623ed5ef3630d4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_spill_fill.c
+++ b/tools/testing/selftests/bpf/progs/verifier_spill_fill.c
@@ -1451,6 +1451,37 @@ __naked void imprecise_scalar_spill_half_dead(void)
: __clobber_all);
}
+/*
+ * The first half-slot of a 64-bit spill holds its low 32 bits on little endian only.
+ * The test spills to r10 - 8. The first four bytes of the slot are an offset into one byte.
+ */
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#define FIRST_HALF_IS_LOW __success
+#else
+#define FIRST_HALF_IS_LOW __failure __msg("access may be outside object bounds")
+#endif
+#define FIRST_HALF(name, stores) \
+SEC("raw_tp") FIRST_HALF_IS_LOW \
+__naked void name(void) \
+{ \
+ asm volatile ( \
+ "call %[bpf_ktime_get_ns];" \
+ stores \
+ "r7 = *(u32 *)(r10 - 8); r1 = %[single_byte_buf] ll; r1 += r7; r0 = *(u8 *)(r1 + 0);" \
+ "out_%=: r0 = 0; exit;" \
+ : \
+ : __imm(bpf_ktime_get_ns), __imm_addr(single_byte_buf) \
+ : __clobber_all); \
+}
+
+/* The low 32 bits of the value are 0. The second half-slot is dead after the jump. */
+FIRST_HALF(first_half_of_spill_second_half_dead,
+ "r0 <<= 32; *(u64 *)(r10 - 8) = r0; if r0 == 0 goto out_%=;")
+/* One path has a 32-bit spill of r6, whose low 32 bits are 0, the other one a 64-bit spill */
+FIRST_HALF(spill_of_64_bits_vs_spill_of_32_bits,
+ "r6 = r0; r6 <<= 32; if r0 > 5 goto 1f; *(u32 *)(r10 - 8) = r6; goto 2f;"
+ "1: r6 = 0x7ffffff000000000 ll; *(u64 *)(r10 - 8) = r6; 2:")
+
/* check valid spill/fill, ptr to tp buffer */
SEC("raw_tracepoint.w")
__success
|
| 29/3 | 2026/11/14 14:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 101689 output: 39 thoughts: 918 Thoughts: **KMSAN Fuzzing Session Assessment for BPF Patch** Alright, let's break this down. The objective is to determine if this BPF patch justifies a dedicated KMSAN fuzzing session. The key is distinguishing between KASAN and KMSAN. Standard KASAN setups already handle a lot – out-of-bounds, use-after-free, double frees, and all that. KMSAN is *specifically* for uninitialized memory reads and kernel-to-user leaks, and we only spin up a full KMSAN session if that's the *only* thing at risk. If KASAN, LOCKDEP, or any of those other checkers would catch the issue, we don't need KMSAN. It's a resource hog, so we're not going to waste cycles. The criteria for *needing* KMSAN involve introducing or modifying kernel structures sent to userspace where initialization might be skipped, conditional logic on uninitialized variables, allocating complex data structures with potential uninitialized fields that later get read, or manipulating bounds/lengths in a way that allows access to uninitialized parts of existing buffers. Conversely, if we're dealing with standard OOB, NULL pointer dereferences, locks, or fully initialized structures, then we don't need it. So, the patch touches `include/linux/bpf_verifier.h`, and a slew of BPF-related `.c` files, plus some selftests. Okay, let's dive into the code. The first thing I see is the `include/linux/bpf_verifier.h` header, where the `bpf_reg_state` struct is defined. Hmm, it's changed. The old `s32 delta` is now `u32 unused`. The comment says something about `regsafe()` and comparing bytes before `var_off`, no "hole". Why `unused`? Wait, what? Does this struct get compared with `memcmp`? That's interesting... In `kernel/bpf/states.c`, I see a `memcmp` call. Is it comparing the structure *before* `var_off`, or before `id`? Need to check that `bpf_reg_state` definition to confirm the order. Need to quickly `read-file` or `grepper` that `bpf_reg_state` definition to clarify this. Gotta trace the actual memory comparison being done. |
| 30/3 | 2026/11/14 14:41 | tool | grepper |
0mArgs:{
"Expression": "struct bpf_reg_state \\{",
"PathPrefixes": [
"include/linux/bpf_verifier.h"
]
}Results: {
"Output": "include/linux/bpf_verifier.h=54=struct bpf_stack_range {\n--\ninclude/linux/bpf_verifier.h-59-\ninclude/linux/bpf_verifier.h:60:struct bpf_reg_state {\ninclude/linux/bpf_verifier.h-61-\t/* Ordering of fields matters. See regsafe() */\n"
} |
| 31/3 | 2026/11/14 14:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 103271 output: 37 thoughts: 22 Thoughts: Here's a summary of my thought process, as requested: **Diving into the BPF Verifier Header** Alright, let's get down to brass tacks. I'm going to start by looking at `include/linux/bpf_verifier.h`, and I'm particularly interested in the code around line 60. I need to refresh my memory on the specifics of the BPF verifier's internals, and that header file is the most likely place to find the relevant definitions and structures I'm after. It's the core of the verification process, which is, of course, critical to the overall security and stability of eBPF. I'm expecting to find some crucial structs related to program analysis there, and potentially some key function prototypes for the verifier itself. This is my starting point for understanding a particular area I'm currently researching. I need to be exact, so my approach has to be methodical. |
| 32/3 | 2026/11/14 14:41 | tool | read-file |
0mArgs:{
"File": "include/linux/bpf_verifier.h",
"FirstLine": 58,
"LineCount": 80
}Results: {
"Contents": " 58:\t};\n 59:\t\n 60:\tstruct bpf_reg_state {\n 61:\t\t/* Ordering of fields matters. See regsafe() */\n 62:\t\tenum bpf_reg_type type;\n 63:\t\t/* 0. regsafe() compares the bytes before var_off: there is no hole among them. */\n 64:\t\tu32 unused;\n 65:\t\tunion {\n 66:\t\t\t/* valid when type == PTR_TO_PACKET */\n 67:\t\t\tint range;\n 68:\t\t\t/*\n 69:\t\t\t * Valid when type == PTR_TO_STACK. Inside the callee two registers\n 70:\t\t\t * can be both PTR_TO_STACK like R1=fp-8 and R2=fp-8, but one of them\n 71:\t\t\t * points to this function stack while another to the caller's stack.\n 72:\t\t\t * To differentiate them 'frameno' is used which is an index in\n 73:\t\t\t * bpf_verifier_state-\u003eframe[] array pointing to bpf_func_state.\n 74:\t\t\t */\n 75:\t\t\tu8 frameno;\n 76:\t\n 77:\t\t\t/*\n 78:\t\t\t * For CONST_PTR_TO_MAP, PTR_TO_MAP_KEY, PTR_TO_MAP_VALUE and\n 79:\t\t\t * PTR_TO_INSN.\n 80:\t\t\t */\n 81:\t\t\tstruct bpf_map *map_ptr;\n 82:\t\n 83:\t\t\t/* for PTR_TO_BTF_ID */\n 84:\t\t\tstruct {\n 85:\t\t\t\tstruct btf *btf;\n 86:\t\t\t\tu32 btf_id;\n 87:\t\t\t};\n 88:\t\n 89:\t\t\tstruct { /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */\n 90:\t\t\t\tu32 mem_size;\n 91:\t\t\t\t/*\n 92:\t\t\t\t * bpf_dynptr_slice() and bpf_dynptr_slice_rdwr() return the\n 93:\t\t\t\t * buffer when the data is not contiguous: the register may\n 94:\t\t\t\t * point to this part of the stack.\n 95:\t\t\t\t */\n 96:\t\t\t\tstruct bpf_stack_range buf;\n 97:\t\t\t};\n 98:\t\n 99:\t\t\t/* For dynptr stack slots */\n 100:\t\t\tstruct {\n 101:\t\t\t\tenum bpf_dynptr_type type;\n 102:\t\t\t\t/* A dynptr is 16 bytes so it takes up 2 stack slots.\n 103:\t\t\t\t * We need to track which slot is the first slot\n 104:\t\t\t\t * to protect against cases where the user may try to\n 105:\t\t\t\t * pass in an address starting at the second slot of the\n 106:\t\t\t\t * dynptr.\n 107:\t\t\t\t */\n 108:\t\t\t\tbool first_slot;\n 109:\t\t\t} dynptr;\n 110:\t\n 111:\t\t\t/* For bpf_iter stack slots */\n 112:\t\t\tstruct {\n 113:\t\t\t\t/* BTF container and BTF type ID describing\n 114:\t\t\t\t * struct bpf_iter_\u003ctype\u003e of an iterator state\n 115:\t\t\t\t */\n 116:\t\t\t\tstruct btf *btf;\n 117:\t\t\t\tu32 btf_id;\n 118:\t\t\t\t/* packing following two fields to fit iter state into 16 bytes */\n 119:\t\t\t\tenum bpf_iter_state state:2;\n 120:\t\t\t\t/*\n 121:\t\t\t\t * The number of loops, in all frames, that the program was in\n 122:\t\t\t\t * when it made the iterator, see iter_stops_loops().\n 123:\t\t\t\t */\n 124:\t\t\t\tu32 loops:30;\n 125:\t\t\t} iter;\n 126:\t\n 127:\t\t\t/* For irq stack slots */\n 128:\t\t\tstruct {\n 129:\t\t\t\tenum {\n 130:\t\t\t\t\tIRQ_NATIVE_KFUNC,\n 131:\t\t\t\t\tIRQ_LOCK_KFUNC,\n 132:\t\t\t\t} kfunc_class;\n 133:\t\t\t} irq;\n 134:\t\n 135:\t\t\t/* Max size from any of the above. */\n 136:\t\t\tstruct {\n 137:\t\t\t\tunsigned long raw1;\n"
} |
| 33/3 | 2026/11/14 14:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 104652 output: 38 thoughts: 27 Thoughts: Okay, here's my attempt at summarizing lines 138-200 of `include/linux/bpf_verifier.h` as a first-person expert perspective: **Diving into the BPF Verifier: A Closer Look at the Rules** Alright, let's get down to brass tacks. I'm focusing in on lines 138-200 of `bpf_verifier.h`. This section... Ah, yes, it's where we get into the nitty-gritty of some key verification rules. Specifically, I see we're dealing with how the verifier handles *register constraints* and ensuring that BPF programs adhere to them. I can tell that we're talking about conditions, maybe to determine what the actual values of registers can be. We're probably working with how we can set rules to determine the relationship between register contents with things like function arguments. I'm guessing this relates to preventing out-of-bounds reads or writes, and ensuring the program behaves in a safe manner. I expect to be seeing things like how to handle different types of data, such as pointers and integers. I'm scanning the code now, and it looks like a lot of this is aimed at building a robust model of what's possible, not just what's explicitly declared. I'm focusing here on the edge cases. I'm looking for conditions that are checked, like overflow, underflow, or perhaps invalid memory accesses. I'm assuming that this section of code handles several different scenarios, maybe things like checking the validity of loads and stores, and preventing programs from writing to read-only regions. Okay, I'm expecting this to be quite a dense set of conditions, so I'll need to read it carefully to ensure I understand how this verification code keeps things safe for the kernel. This is a crucial section. Gotta make sure we catch anything that might lead to an exploit! |
| 34/3 | 2026/11/14 14:41 | tool | read-file |
0mArgs:{
"File": "include/linux/bpf_verifier.h",
"FirstLine": 138,
"LineCount": 70
}Results: {
"Contents": " 138:\t\t\t\tunsigned long raw2;\n 139:\t\t\t} raw;\n 140:\t\n 141:\t\t\tstruct { /* for PTR_TO_FUNC */\n 142:\t\t\t\tu32 subprogno;\n 143:\t\t\t\t/* if not 0: one of env-\u003efunc_sets[func_set - 1], subprogno is 0 */\n 144:\t\t\t\tu32 func_set;\n 145:\t\t\t};\n 146:\t\t};\n 147:\t\t/* For scalar types (SCALAR_VALUE), this represents our knowledge of\n 148:\t\t * the actual value.\n 149:\t\t * For pointer types, this represents the variable part of the offset\n 150:\t\t * from the pointed-to object, and is shared with all bpf_reg_states\n 151:\t\t * with the same id as us.\n 152:\t\t */\n 153:\t\tstruct tnum var_off;\n 154:\t\t/* Used to determine if any memory access using this register will\n 155:\t\t * result in a bad access.\n 156:\t\t * These refer to the same value as var_off, not necessarily the actual\n 157:\t\t * contents of the register.\n 158:\t\t */\n 159:\t\tstruct cnum64 r64; /* 64-bit range as circular number */\n 160:\t\tstruct cnum32 r32; /* 32-bit range as circular number */\n 161:\t\t/*\n 162:\t\t * The value described by this register, interpreted as s64, lies on\n 163:\t\t * a line described by a linear equation base + step * k.\n 164:\t\t * Invariant: base \u003c step.\n 165:\t\t */\n 166:\t\tu16 base;\n 167:\t\tu16 step;\n 168:\t\t/* For PTR_TO_PACKET, used to find other pointers with the same variable\n 169:\t\t * offset, so they can share range knowledge.\n 170:\t\t * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we\n 171:\t\t * came from, when one is tested for != NULL.\n 172:\t\t * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation\n 173:\t\t * for the purpose of tracking that it's freed.\n 174:\t\t * For PTR_TO_SOCKET this is used to share which pointers retain the\n 175:\t\t * same reference to the socket, to determine proper reference freeing.\n 176:\t\t * For stack slots that are dynptrs, this is used to track references to\n 177:\t\t * the dynptr to determine proper reference freeing.\n 178:\t\t * Similarly to dynptrs, we use ID to track \"belonging\" of a reference\n 179:\t\t * to a specific instance of bpf_iter.\n 180:\t\t * A scalar has no id. The scalars that it is linked to are static: computed before the\n 181:\t\t * main pass, see bpf_scev_next_linked_reg().\n 182:\t\t */\n 183:\t\tu32 id;\n 184:\t\t/*\n 185:\t\t * Tracks the parent object this register was derived from.\n 186:\t\t * Used for cascading invalidation: when the parent object is\n 187:\t\t * released or invalidated, all registers with matching parent_id\n 188:\t\t * are also invalidated. For example, a slice from bpf_dynptr_data()\n 189:\t\t * gets parent_id set to the dynptr's id.\n 190:\t\t */\n 191:\t\tu32 parent_id;\n 192:\t\t/*\n 193:\t\t * Distinguishes inner-map lookups and their keys and values. Zero for\n 194:\t\t * other registers. Kept outside the metadata union for ID remapping\n 195:\t\t * during state comparisons.\n 196:\t\t */\n 197:\t\tu32 map_uid;\n 198:\t};\n 199:\t\n 200:\tstatic inline s64 reg_smin(const struct bpf_reg_state *reg)\n 201:\t{\n 202:\t\treturn cnum64_smin(reg-\u003er64);\n 203:\t}\n 204:\t\n 205:\tstatic inline s64 reg_smax(const struct bpf_reg_state *reg)\n 206:\t{\n 207:\t\treturn cnum64_smax(reg-\u003er64);\n"
} |
| 35/3 | 2026/11/14 14:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 106312 output: 37 thoughts: 880 Thoughts: **Analyzing `struct bpf_reg_state` for Potential Padding and Initialization Quirks**
Okay, let's dissect `struct bpf_reg_state`. I'm focusing on potential padding or initialization issues, as these things can lead to unexpected behavior in the verifier.
First, I see `type` is an `enum bpf_reg_type` (4 bytes). Then there was a change from `s32 delta` to `u32 unused` (4 bytes). Next, we have a union, whose largest element is `struct { unsigned long raw1; unsigned long raw2; } raw;` (16 bytes). Finally we have `struct tnum var_off`, and there is a critical comment mentioning `regsafe()`, which does a byte comparison before `var_off`, meaning there's no padding amongst those members.
My initial question: Does `bpf_reg_state` get initialized to zero? Because of the change from `s32 delta` to `u32 unused`, how is `unused` handled? I then recall that `bpf_reg_state` resides within `bpf_func_state` as `regs[MAX_BPF_REG]`. When `bpf_func_state` is allocated, it's `kzalloc`'d. But what about when we allocate a fake register or temp register? I see those are initialized with `{0}` or `memset` or copied from another register.
Now, the important check is how state comparisons are done! Checking `memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))` in `states.c` catches my eye. Looking around line 229, `explore_alu_limits` seems to use `memcmp` up to the `id` field. That is, it uses the byte comparison! I need to be careful with this, because I noticed similar checks in `kernel/bpf/flow.c` and `kernel/bpf/join.c`: in those, `memcmp` is used up to `id` for various state comparisons (`flow_join_makes_up` and `reg_value_equal`).
The real question: Is there any padding or a "hole" in the struct *before* the `id` field, which isn't being accounted for when the byte comparison is done? Let's trace it back to the fields: `type` (4 bytes), `unused` (4 bytes), the `union raw` with two `unsigned long`s (8 + 8 = 16 bytes, but aligned to 8), and then `struct tnum var_off`, that is `struct tnum { u64 value; u64 mask; }` (16 bytes, aligned to 8 bytes).
So, `bpf_reg_state`'s fields are: `enum bpf_reg_type type`, `u32 unused`, `union raw`, and `struct tnum var_off`.
And there's `struct cnum64 r64`. Let me check that.
|
| 36/3 | 2026/11/14 14:42 | tool | grepper |
0mArgs:{
"Expression": "struct cnum64 \\{",
"PathPrefixes": [
"include/",
"kernel/bpf/"
]
}Results: {
"Output": "include/linux/cnum.h=52=bool cnum32_is_subset(struct cnum32 outer, struct cnum32 inner);\n--\ninclude/linux/cnum.h-54-/* Same as cnum32 but for 64-bit ranges */\ninclude/linux/cnum.h:55:struct cnum64 {\ninclude/linux/cnum.h-56-\tu64 base;\n"
} |
| 37/3 | 2026/11/14 14:42 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 108016 output: 35 thoughts: 20 Thoughts: Here's a summary of my thought process, tailored for an expert like you: **Diving into the Kernel's NUMA Implementation** Okay, time to get my hands dirty. I'm focusing on NUMA, specifically within the kernel. My first instinct, given what I'm looking for, is to check `include/linux/cnum.h`. That header file is a classic place to start when digging into NUMA-related concepts and definitions. My gut tells me there's something relevant around line 55. I'm expecting to find some crucial macro or structure definition that's key to how the kernel models or interacts with CPU and memory node information. Let's see if my intuition holds true! |
| 38/3 | 2026/11/14 14:42 | tool | read-file |
0mArgs:{
"File": "include/linux/cnum.h",
"FirstLine": 45,
"LineCount": 30
}Results: {
"Contents": " 45:\tvoid cnum32_intersect_with_urange(struct cnum32 *dst, u32 min, u32 max);\n 46:\tvoid cnum32_intersect_with_srange(struct cnum32 *dst, s32 min, s32 max);\n 47:\tbool cnum32_contains(struct cnum32 cnum, u32 v);\n 48:\tbool cnum32_is_const(struct cnum32 cnum);\n 49:\tbool cnum32_is_empty(struct cnum32 cnum);\n 50:\tstruct cnum32 cnum32_add(struct cnum32 a, struct cnum32 b);\n 51:\tstruct cnum32 cnum32_negate(struct cnum32 a);\n 52:\tbool cnum32_is_subset(struct cnum32 outer, struct cnum32 inner);\n 53:\t\n 54:\t/* Same as cnum32 but for 64-bit ranges */\n 55:\tstruct cnum64 {\n 56:\t\tu64 base;\n 57:\t\tu64 size;\n 58:\t};\n 59:\t\n 60:\t#define CNUM64_UNBOUNDED ((struct cnum64){ .base = 0, .size = U64_MAX })\n 61:\t#define CNUM64_EMPTY ((struct cnum64){ .base = U64_MAX, .size = U64_MAX })\n 62:\t\n 63:\tstruct cnum64 cnum64_from_urange(u64 min, u64 max);\n 64:\tstruct cnum64 cnum64_from_srange(s64 min, s64 max);\n 65:\tu64 cnum64_umin(struct cnum64 cnum);\n 66:\tu64 cnum64_umax(struct cnum64 cnum);\n 67:\ts64 cnum64_smin(struct cnum64 cnum);\n 68:\ts64 cnum64_smax(struct cnum64 cnum);\n 69:\tstruct cnum64 cnum64_union(struct cnum64 a, struct cnum64 b);\n 70:\tstruct cnum64 cnum64_intersect(struct cnum64 a, struct cnum64 b);\n 71:\tvoid cnum64_intersect_with(struct cnum64 *dst, struct cnum64 src);\n 72:\tvoid cnum64_intersect_with_urange(struct cnum64 *dst, u64 min, u64 max);\n 73:\tvoid cnum64_intersect_with_srange(struct cnum64 *dst, s64 min, s64 max);\n 74:\tbool cnum64_contains(struct cnum64 cnum, u64 v);\n"
} |
| 39/3 | 2026/11/14 14:42 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 108990 output: 34 thoughts: 31 Thoughts: Okay, let's dive into this. Here's my thought process on this: **Investigating `cnum32`** Alright, so `cnum32` is the thing that's caught my attention. I need to understand what this represents within the context of the Linux kernel. Where would I begin? Well, the obvious place to start is the header file, `include/linux/cnum.h`. That's where kernel developers define their core data structures and functions related to something like this. Let's start with lines 1-44 as that should give me the core structure definition and potentially the main purpose of this item. That's usually how they structure these headers. That will be a great start to understanding what I'm looking at. From there, I'll be able to decide if I need to dig further or whether this is all I require to understand the concept. |
| 40/3 | 2026/11/14 14:42 | tool | read-file |
0mArgs:{
"File": "include/linux/cnum.h",
"FirstLine": 1,
"LineCount": 44
}Results: {
"Contents": " 1:\t/* SPDX-License-Identifier: GPL-2.0-only */\n 2:\t/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n 3:\t\n 4:\t#ifndef _LINUX_CNUM_H\n 5:\t#define _LINUX_CNUM_H\n 6:\t\n 7:\t#include \u003clinux/types.h\u003e\n 8:\t\n 9:\t/*\n 10:\t * cnum32: a circular number.\n 11:\t * A unified representation for signed and unsigned ranges.\n 12:\t *\n 13:\t * Assume that a 32-bit range is a circle, with 0 being in the 12 o'clock\n 14:\t * position, numbers placed sequentially in clockwise order and U32_MAX\n 15:\t * in the 11 o'clock position. Signed values map onto the same circle:\n 16:\t * S32_MAX sits at 5 o'clock, S32_MIN sits at 6 o'clock (opposite 0),\n 17:\t * negative values occupy the left half and positive values the right half.\n 18:\t *\n 19:\t * @cnum32 represents an arc on this circle drawn clockwise.\n 20:\t * @base corresponds to the first value of the range.\n 21:\t * @size corresponds to the number of integers in the range excluding @base.\n 22:\t * (The @base is excluded to avoid integer overflow when representing the full\n 23:\t * 0..U32_MAX range, which corresponds to 2^32, which can't be stored in u32).\n 24:\t *\n 25:\t * For example: {U32_MAX, 1} corresponds to signed range [-1, 0],\n 26:\t * {S32_MAX, 1} corresponds to unsigned range [S32_MAX, S32_MIN].\n 27:\t */\n 28:\tstruct cnum32 {\n 29:\t\tu32 base;\n 30:\t\tu32 size;\n 31:\t};\n 32:\t\n 33:\t#define CNUM32_UNBOUNDED ((struct cnum32){ .base = 0, .size = U32_MAX })\n 34:\t#define CNUM32_EMPTY ((struct cnum32){ .base = U32_MAX, .size = U32_MAX })\n 35:\t\n 36:\tstruct cnum32 cnum32_from_urange(u32 min, u32 max);\n 37:\tstruct cnum32 cnum32_from_srange(s32 min, s32 max);\n 38:\tu32 cnum32_umin(struct cnum32 cnum);\n 39:\tu32 cnum32_umax(struct cnum32 cnum);\n 40:\ts32 cnum32_smin(struct cnum32 cnum);\n 41:\ts32 cnum32_smax(struct cnum32 cnum);\n 42:\tstruct cnum32 cnum32_union(struct cnum32 a, struct cnum32 b);\n 43:\tstruct cnum32 cnum32_intersect(struct cnum32 a, struct cnum32 b);\n 44:\tvoid cnum32_intersect_with(struct cnum32 *dst, struct cnum32 src);\n"
} |
| 41/3 | 2026/11/14 14:42 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 110135 output: 37 thoughts: 936 Thoughts: **Analyzing a BPF Verifier Change: No Structural Layout Change, but Significant Logic Shift** Okay, so I'm digging into this patch. The initial observation is about the `bpf_reg_state` struct. I'm focusing on the layout. Specifically: `cnum32` is 8 bytes, and within `bpf_reg_state`, we have `r32`, `base`, `step`, and `id`. The old calculations confirmed the `id` field starts at offset 68, which is crucial because it aligns to a 4-byte boundary. Crucially, the patch *didn't* change the size or layout of the struct itself. `unused` in place of `delta`, means 4 bytes were just used differently. So the existing `memcmp` comparisons *should* be fine. The core of the patch is not structure. The commit message mentions this is a "syz-cluster: applied patch under review". From my expert understanding, it is the removal of BPF scalar ID tracking, i.e., `assign_scalar_id_before_mov`, `clear_scalar_id`, `check_scalar_ids`, `bpf_clear_singular_ids`, etc, and the use of SCEV (Scalar Evolution) instead! This is a *significant* change in the verifier's approach. The commit explicitly states that scalars no longer have IDs; instead, the scalars they're linked to are determined statically before the main pass, via `bpf_scev_next_linked_reg()`. The old `sync_linked_regs` function is now replaced by `refine_linked_regs`. `bpf_scev_next_linked_reg` computes these static linked registers. I'm now cross-referencing this verifier change to the `kernel/bpf/syscall.c`. Specifically, I am interested in `bpf_sys_bpf_proto` and what it does. I need to understand how the system call interaction with memory has been altered. Specifically, in `kernel/bpf/syscall.c`, I noticed a change in line 6692; the `arg2_type` changed from `ARG_PTR_TO_MEM | MEM_RDONLY` to `ARG_PTR_TO_MEM | MEM_WRITE`. This makes me want to pause here and read the context of this change: a memory write is taking place. This is where I need to focus my attention. It is possible the shift to SCEV is linked to this change in the syscall. |
| 42/3 | 2026/11/14 14:42 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/syscall.c",
"FirstLine": 6680,
"LineCount": 40
}Results: {
"Contents": "6680:\t\t\tbpf_prog_put(prog);\n6681:\t\t\treturn 0;\n6682:\t#endif\n6683:\t\tdefault:\n6684:\t\t\treturn ____bpf_sys_bpf(cmd, attr, size);\n6685:\t\t}\n6686:\t}\n6687:\tEXPORT_SYMBOL_NS(kern_sys_bpf, \"BPF_INTERNAL\");\n6688:\t\n6689:\tstatic const struct bpf_func_proto bpf_sys_bpf_proto = {\n6690:\t\t.func\t\t= bpf_sys_bpf,\n6691:\t\t.gpl_only\t= false,\n6692:\t\t.might_sleep\t= true,\n6693:\t\t.ret_type\t= RET_INTEGER,\n6694:\t\t.arg1_type\t= ARG_ANYTHING,\n6695:\t\t.arg2_type\t= ARG_PTR_TO_MEM | MEM_WRITE,\n6696:\t\t.arg3_type\t= ARG_MEM_SIZE,\n6697:\t};\n6698:\t\n6699:\tconst struct bpf_func_proto * __weak\n6700:\ttracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)\n6701:\t{\n6702:\t\treturn bpf_base_func_proto(func_id, prog);\n6703:\t}\n6704:\t\n6705:\tBPF_CALL_1(bpf_sys_close, u32, fd)\n6706:\t{\n6707:\t\t/* When bpf program calls this helper there should not be\n6708:\t\t * an fdget() without matching completed fdput().\n6709:\t\t * This helper is allowed in the following callchain only:\n6710:\t\t * sys_bpf-\u003eprog_test_run-\u003ebpf_prog-\u003ebpf_sys_close\n6711:\t\t */\n6712:\t\treturn close_fd(fd);\n6713:\t}\n6714:\t\n6715:\tstatic const struct bpf_func_proto bpf_sys_close_proto = {\n6716:\t\t.func\t\t= bpf_sys_close,\n6717:\t\t.gpl_only\t= false,\n6718:\t\t.might_sleep\t= true,\n6719:\t\t.ret_type\t= RET_INTEGER,\n"
} |
| 43/3 | 2026/11/14 14:42 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 112309 output: 37 thoughts: 43 Thoughts: Okay, let's dive into this. I'm curious about the inner workings of `bpf_sys_bpf`, so I'm going to take a look at the source code. Specifically, I want to zero in on lines 6640 through 6689 of `kernel/bpf/syscall.c`. This section should reveal the core functionality of this system call. I need to understand its behavior, how it's implemented, and what interactions it facilitates within the BPF ecosystem. Let's see what gems are hidden in this snippet of code! I'm expecting to find details regarding arguments it takes, the types of operations it supports, and how it handles various BPF-related tasks. |
| 44/3 | 2026/11/14 14:42 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/syscall.c",
"FirstLine": 6640,
"LineCount": 45
}Results: {
"Contents": "6640:\t/* To shut up -Wmissing-prototypes.\n6641:\t * This function is used by the kernel light skeleton\n6642:\t * to load bpf programs when modules are loaded or during kernel boot.\n6643:\t * See tools/lib/bpf/skel_internal.h\n6644:\t */\n6645:\tint kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);\n6646:\t\n6647:\tint kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)\n6648:\t{\n6649:\t\tstruct bpf_prog * __maybe_unused prog;\n6650:\t\tstruct bpf_tramp_run_ctx __maybe_unused run_ctx;\n6651:\t\n6652:\t\tswitch (cmd) {\n6653:\t#ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */\n6654:\t\tcase BPF_PROG_TEST_RUN:\n6655:\t\t\tif (attr-\u003etest.data_in || attr-\u003etest.data_out ||\n6656:\t\t\t attr-\u003etest.ctx_out || attr-\u003etest.duration ||\n6657:\t\t\t attr-\u003etest.repeat || attr-\u003etest.flags)\n6658:\t\t\t\treturn -EINVAL;\n6659:\t\n6660:\t\t\tprog = bpf_prog_get_type(attr-\u003etest.prog_fd, BPF_PROG_TYPE_SYSCALL);\n6661:\t\t\tif (IS_ERR(prog))\n6662:\t\t\t\treturn PTR_ERR(prog);\n6663:\t\n6664:\t\t\tif (attr-\u003etest.ctx_size_in \u003c prog-\u003eaux-\u003emax_ctx_offset ||\n6665:\t\t\t attr-\u003etest.ctx_size_in \u003e U16_MAX) {\n6666:\t\t\t\tbpf_prog_put(prog);\n6667:\t\t\t\treturn -EINVAL;\n6668:\t\t\t}\n6669:\t\n6670:\t\t\trun_ctx.bpf_cookie = 0;\n6671:\t\t\tif (!__bpf_prog_enter_sleepable_recur(prog, \u0026run_ctx)) {\n6672:\t\t\t\t/* recursion detected */\n6673:\t\t\t\t__bpf_prog_exit_sleepable_recur(prog, 0, \u0026run_ctx);\n6674:\t\t\t\tbpf_prog_put(prog);\n6675:\t\t\t\treturn -EBUSY;\n6676:\t\t\t}\n6677:\t\t\tattr-\u003etest.retval = bpf_prog_run(prog, (void *) (long) attr-\u003etest.ctx_in);\n6678:\t\t\t__bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,\n6679:\t\t\t\t\t\t\t\u0026run_ctx);\n6680:\t\t\tbpf_prog_put(prog);\n6681:\t\t\treturn 0;\n6682:\t#endif\n6683:\t\tdefault:\n6684:\t\t\treturn ____bpf_sys_bpf(cmd, attr, size);\n"
} |
| 45/3 | 2026/11/14 14:42 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 113368 output: 43 thoughts: 30 Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person: **Diving into the `bpf_sys_bpf` System Call** Alright, let's get down to brass tacks. I need to understand what's happening with `bpf_sys_bpf`. My initial focus is the function definition itself. I need to immediately understand the signature, arguments, and return value. Knowing that will give me the building blocks to interpret the call within the broader BPF context. I'm essentially going to deconstruct this system call – understand its input parameters, what it's trying to accomplish, and what signals it's sending back. I'll be looking for things like the type of the `cmd` argument, any potential security implications, and how it interacts with the BPF subsystem. I’m thinking about what the kernel is expecting here. From there, I can start forming a mental model of how it fits into the overall BPF ecosystem. This is where I start to form my initial understanding of this system call and how it influences behavior. |
| 46/3 | 2026/11/14 14:43 | tool | grepper |
0mArgs:{
"Expression": "BPF_CALL_3\\(bpf_sys_bpf",
"PathPrefixes": [
"kernel/bpf/syscall.c"
]
}Results: {
"Output": "kernel/bpf/syscall.c=6610=static bool syscall_prog_is_valid_access(int off, int size,\n--\nkernel/bpf/syscall.c-6620-\nkernel/bpf/syscall.c:6621:BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)\nkernel/bpf/syscall.c-6622-{\n"
} |
| 47/3 | 2026/11/14 14:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 113804 output: 37 thoughts: 24 Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person: **Diving into the BPF System Call Implementation** Alright, time to get my hands dirty. I'm thinking I should start digging into `bpf_sys_bpf`. Given my knowledge of BPF, the best starting point is going to be the source code itself, so let's navigate to `kernel/bpf/syscall.c`. I'm already anticipating the structure – I'll be looking for the entry point for the BPF system call. I'll need to examine how the kernel handles the arguments passed from user space, the dispatch logic that determines which BPF operation is requested (load, attach, detach, etc.), and the underlying error handling. I'll be focused on understanding the security checks, resource management, and potential bottlenecks within this system call as well. I'm keen to see the interaction with the verifier and how it validates the provided BPF bytecode. Should be a good deep dive. |
| 48/3 | 2026/11/14 14:43 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/syscall.c",
"FirstLine": 6620,
"LineCount": 25
}Results: {
"Contents": "6620:\t\n6621:\tBPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)\n6622:\t{\n6623:\t\tswitch (cmd) {\n6624:\t\tcase BPF_MAP_CREATE:\n6625:\t\tcase BPF_MAP_DELETE_ELEM:\n6626:\t\tcase BPF_MAP_UPDATE_ELEM:\n6627:\t\tcase BPF_MAP_FREEZE:\n6628:\t\tcase BPF_MAP_GET_FD_BY_ID:\n6629:\t\tcase BPF_PROG_LOAD:\n6630:\t\tcase BPF_BTF_LOAD:\n6631:\t\tcase BPF_LINK_CREATE:\n6632:\t\tcase BPF_RAW_TRACEPOINT_OPEN:\n6633:\t\t\tbreak;\n6634:\t\tdefault:\n6635:\t\t\treturn -EINVAL;\n6636:\t\t}\n6637:\t\treturn __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size, KERNEL_BPFPTR(NULL), 0);\n6638:\t}\n6639:\t\n6640:\t/* To shut up -Wmissing-prototypes.\n6641:\t * This function is used by the kernel light skeleton\n6642:\t * to load bpf programs when modules are loaded or during kernel boot.\n6643:\t * See tools/lib/bpf/skel_internal.h\n6644:\t */\n"
} |
| 49/3 | 2026/11/14 14:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 114505 output: 37 thoughts: 163 Thoughts: **Investigating the `bpf_sys_bpf_proto` Change** Okay, so I'm digging into this `bpf_sys_bpf_proto` change and I'm immediately stuck on why the `arg2_type` was shifted from `ARG_PTR_TO_MEM | MEM_RDONLY` to `ARG_PTR_TO_MEM | MEM_WRITE`. That seems like a pretty significant shift in memory access semantics, doesn't it? The core of my concern revolves around how the verifier actually handles these memory access flags within the context of helper function calls. I need to understand the implications of this change. Specifically, what does the difference between `MEM_WRITE` and `MEM_RDONLY` *actually* represent in the verifier's logic? I need to understand what it means in the context of `check_helper_call` or more generally helper proto checking. My next step is clear: I need to scrutinize the verifier's code to understand how it interprets these flags. I'll need to drill down into the code associated with `ARG_PTR_TO_MEM | MEM_WRITE` and `MEM_RDONLY`, looking specifically at `check_helper_mem_access` and `check_func_arg`. Grepping for `MEM_WRITE` and `MEM_RDONLY` within `kernel/bpf/verifier.c` will be a good starting point to quickly find relevant sections of code. This should allow me to see how the verifier enforces restrictions. |
| 50/3 | 2026/11/14 14:43 | tool | grepper |
0mArgs:{
"Expression": "MEM_RDONLY|MEM_WRITE",
"PathPrefixes": [
"kernel/bpf/verifier.c"
]
}Results: {
"Output": "kernel/bpf/verifier.c=497=static bool type_is_rdonly_mem(u32 type)\nkernel/bpf/verifier.c-498-{\nkernel/bpf/verifier.c:499:\treturn type \u0026 MEM_RDONLY;\nkernel/bpf/verifier.c-500-}\n--\nkernel/bpf/verifier.c=9220=static const struct bpf_reg_types ctx_out_types = {\nkernel/bpf/verifier.c:9221:\t.types = { PTR_TO_MEM | MEM_RDONLY | PTR_TRUSTED },\nkernel/bpf/verifier.c-9222-};\n--\nkernel/bpf/verifier.c=9420=static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,\n--\nkernel/bpf/verifier.c-9448-\t */\nkernel/bpf/verifier.c:9449:\tif (arg_type \u0026 MEM_RDONLY)\nkernel/bpf/verifier.c:9450:\t\ttype \u0026= ~MEM_RDONLY;\nkernel/bpf/verifier.c-9451-\tif (arg_type \u0026 PTR_MAYBE_NULL)\n--\nkernel/bpf/verifier.c=9509=static int check_func_arg_reg_off(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-9549-\tcase PTR_TO_MEM:\nkernel/bpf/verifier.c:9550:\tcase PTR_TO_MEM | MEM_RDONLY:\nkernel/bpf/verifier.c-9551-\tcase PTR_TO_MEM | MEM_RINGBUF:\nkernel/bpf/verifier.c-9552-\tcase PTR_TO_BUF:\nkernel/bpf/verifier.c:9553:\tcase PTR_TO_BUF | MEM_RDONLY:\nkernel/bpf/verifier.c-9554-\tcase PTR_TO_ARENA:\n--\nkernel/bpf/verifier.c=9721=static int process_map_ptr_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-9761-/*\nkernel/bpf/verifier.c:9762: * MEM_WRITE alone denotes an input/output buffer. MEM_UNINIT marks an output\nkernel/bpf/verifier.c-9763- * whose incoming contents are not read.\n--\nkernel/bpf/verifier.c=9765=static enum bpf_access_type func_arg_access_type(enum bpf_arg_type arg_type)\nkernel/bpf/verifier.c-9766-{\nkernel/bpf/verifier.c:9767:\tif (!(arg_type \u0026 MEM_WRITE))\nkernel/bpf/verifier.c-9768-\t\treturn BPF_READ;\n--\nkernel/bpf/verifier.c=9774=static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,\n--\nkernel/bpf/verifier.c-9918-\t\terr = check_helper_mem_access(env, reg, argno, meta-\u003emap.ptr-\u003evalue_size,\nkernel/bpf/verifier.c:9919:\t\t\t\t\t arg_type \u0026 MEM_WRITE ? BPF_WRITE : BPF_READ,\nkernel/bpf/verifier.c-9920-\t\t\t\t\t false, meta, NULL);\n--\nkernel/bpf/verifier.c=10905=static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)\n--\nkernel/bpf/verifier.c-10915-\t\t\tcontinue;\nkernel/bpf/verifier.c:10916:\t\tif (!(arg_type \u0026 (MEM_WRITE | MEM_RDONLY)))\nkernel/bpf/verifier.c-10917-\t\t\treturn false;\n--\nkernel/bpf/verifier.c=11311=static void gen_subprog_arg_proto(const struct bpf_subprog_info *sub, const struct btf *btf,\n--\nkernel/bpf/verifier.c-11332-\t\t\tproto-\u003earg_size[arg] = sub-\u003eargs[slot].mem_size;\nkernel/bpf/verifier.c:11333:\t\t\targ_type |= MEM_FIXED_SIZE | MEM_WRITE;\nkernel/bpf/verifier.c-11334-\t\t} else if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) {\n--\nkernel/bpf/verifier.c=13040=static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-13376-\t\t\t} else {\nkernel/bpf/verifier.c:13377:\t\t\t\t/* MEM_RDONLY may be carried from ret_flag, but it\nkernel/bpf/verifier.c-13378-\t\t\t\t * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise\n--\nkernel/bpf/verifier.c-13381-\t\t\t\t */\nkernel/bpf/verifier.c:13382:\t\t\t\tret_flag \u0026= ~MEM_RDONLY;\nkernel/bpf/verifier.c-13383-\t\t\t\tregs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;\n--\nkernel/bpf/verifier.c=13636=static enum bpf_type_flag kfunc_arg_mem_flag(const struct btf *btf,\n--\nkernel/bpf/verifier.c-13645-\t\tif (btf_kind(t) == BTF_KIND_CONST)\nkernel/bpf/verifier.c:13646:\t\t\treturn MEM_RDONLY;\nkernel/bpf/verifier.c-13647-\t}\nkernel/bpf/verifier.c:13648:\treturn MEM_WRITE;\nkernel/bpf/verifier.c-13649-}\n--\nkernel/bpf/verifier.c=15770=static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-15893-\t\t\tmark_reg_known_zero(env, regs, BPF_REG_0);\nkernel/bpf/verifier.c:15894:\t\t\tregs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;\nkernel/bpf/verifier.c-15895-\t\t\tregs[BPF_REG_0].mem_size = 0;\n--\nkernel/bpf/verifier.c-15917-\t\tif (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice])) {\nkernel/bpf/verifier.c:15918:\t\t\tregs[BPF_REG_0].type |= MEM_RDONLY;\nkernel/bpf/verifier.c-15919-\t\t} else {\n--\nkernel/bpf/verifier.c=15953=static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-16353-\t\t\tif (meta.r0_rdonly)\nkernel/bpf/verifier.c:16354:\t\t\t\tregs[BPF_REG_0].type |= MEM_RDONLY;\nkernel/bpf/verifier.c-16355-\n--\nkernel/bpf/verifier.c=20632=static enum bpf_reg_type merge_ptr_types(enum bpf_reg_type type_a,\n--\nkernel/bpf/verifier.c-20638-\tif (bpf_may_fault_on_deref(type_a) || bpf_may_fault_on_deref(type_b))\nkernel/bpf/verifier.c:20639:\t\ttype_merged |= to_mem ? MEM_RDONLY | PTR_UNTRUSTED :\nkernel/bpf/verifier.c-20640-\t\t\t\t\tPTR_UNTRUSTED;\nkernel/bpf/verifier.c-20641-\telse\nkernel/bpf/verifier.c:20642:\t\ttype_merged |= ((type_a | type_b) \u0026 MEM_RDONLY);\nkernel/bpf/verifier.c-20643-\treturn type_merged;\n--\nkernel/bpf/verifier.c=22000=static int __check_pseudo_btf_id(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-22036-\tif (btf_type_is_func(t)) {\nkernel/bpf/verifier.c:22037:\t\taux-\u003ebtf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;\nkernel/bpf/verifier.c-22038-\t\taux-\u003ebtf_var.mem_size = 0;\n--\nkernel/bpf/verifier.c-22071-\t\t}\nkernel/bpf/verifier.c:22072:\t\taux-\u003ebtf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;\nkernel/bpf/verifier.c-22073-\t\taux-\u003ebtf_var.mem_size = tsize;\n--\nkernel/bpf/verifier.c=23020=static int do_check_common(struct bpf_verifier_env *env, int subprog,\n--\nkernel/bpf/verifier.c-23108-\t\t\t\treg-\u003etype |= arg-\u003earg_type \u0026\nkernel/bpf/verifier.c:23109:\t\t\t\t\t (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);\nkernel/bpf/verifier.c-23110-\t\t\t\tmark_reg_known_zero(env, regs, i);\n"
} |
| 51/3 | 2026/11/14 14:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 117593 output: 34 thoughts: 380 Thoughts: **Analyzing BPF Verifier and Memory Access** Okay, let's dive in. I'm looking at `kernel/bpf/verifier.c`, specifically the `func_arg_access_type` function. Interesting, it defines `MEM_WRITE` as an input/output buffer and `MEM_UNINIT` as an output with uninitialized incoming contents. The code clearly states that if `arg_type` *doesn't* include `MEM_WRITE`, it's a `BPF_READ` access. Makes perfect sense. But then, hold on a second. I remember seeing a change in `bpf_sys_bpf_proto`. Previously, the second argument (`arg2_type`) was `ARG_PTR_TO_MEM | MEM_RDONLY`. Now, it's `ARG_PTR_TO_MEM | MEM_WRITE`. Why the change to `MEM_WRITE`? This is suspicious. We've got a read only argument, being changed to write. I need to understand the implications of this. My mind goes to `kernel/bpf/liveness.c`, considering indirect writes. I suspect that this change is tied to more relaxed memory access controls. Let's dig in and check the logic around write masking. Specifically, I need to see what's happening with `bpf_may_write_mask(env, idx)`. Where is this function actually *computed*? I'm betting the answer lies in `kernel/bpf/liveness.c`. Time to see what's going on with the write permissions. |
| 52/3 | 2026/11/14 14:43 | tool | grepper |
0mArgs:{
"Expression": "bpf_may_write_mask",
"PathPrefixes": [
"kernel/bpf/"
]
}Results: {
"Output": "kernel/bpf/liveness.c=764=bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi)\n--\nkernel/bpf/liveness.c-775-\nkernel/bpf/liveness.c:776:const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)\nkernel/bpf/liveness.c-777-{\n--\nkernel/bpf/scev.c=259=static bool expr_is_vn(struct scev *scev, struct expr *e)\n--\nkernel/bpf/scev.c-264-\t * bpf_dynptr_slice_rdwr() can return the buffer that it got. A store through that slice may\nkernel/bpf/scev.c:265:\t * alias the slots of the buffer and is in no bpf_may_write_mask(): it is no def, so a def\nkernel/bpf/scev.c-266-\t * of such a slot is no value number. A spill through r10 has the expression of the\n--\nkernel/bpf/scev.c=1838=static int reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)\n--\nkernel/bpf/scev.c-1851-\nkernel/bpf/scev.c:1852:\tmask = bpf_may_write_mask(env, idx);\nkernel/bpf/scev.c-1853-\topaque = bpf_helper_call(insn) \u0026\u0026 is_probe_read_helper(insn-\u003eimm);\n--\nkernel/bpf/scev.c=3006=static void find_slice_slots(struct bpf_verifier_env *env)\n--\nkernel/bpf/scev.c-3016-\t\tif (BPF_CLASS(insn[i].code) == BPF_JMP \u0026\u0026 BPF_OP(insn[i].code) == BPF_CALL)\nkernel/bpf/scev.c:3017:\t\t\tbitmap_or(scev-\u003eslice_slots, scev-\u003eslice_slots, bpf_may_write_mask(env, i),\nkernel/bpf/scev.c-3018-\t\t\t\t MAX_BPF_STACK_SLOTS);\n"
} |
| 53/3 | 2026/11/14 14:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 118963 output: 35 thoughts: 26 Thoughts: Here's a summary of my thought process, as requested: **Tracing the Initialization of `may_write_mask`** Okay, so I need to understand how this `may_write_mask` variable gets set up. My starting point is going to be within `kernel/bpf/liveness.c`. The most direct approach is to pinpoint its initialization. I'll need to meticulously scan that file, looking for where `may_write_mask` is *first* assigned a value. I'm expecting to see an explicit declaration and assignment, potentially as part of a struct initialization or within a function that is central to the BPF liveness analysis. I'll be keeping an eye out for any interactions with other related structures or functions that might be involved. I'm looking for the defining moment, the origin of this mask. |
| 54/3 | 2026/11/14 14:43 | tool | grepper |
0mArgs:{
"Expression": "may_write_mask",
"PathPrefixes": [
"kernel/bpf/liveness.c"
]
}Results: {
"Output": "kernel/bpf/liveness.c=726=static void half_spis_to_slots(unsigned long *slots, const unsigned long *mask, u32 nbits)\n--\nkernel/bpf/liveness.c-739- */\nkernel/bpf/liveness.c:740:static void compute_may_write_masks(struct bpf_verifier_env *env)\nkernel/bpf/liveness.c-741-{\n--\nkernel/bpf/liveness.c-754-\t\tfor (i = 0; i \u003c instance-\u003einsn_cnt; i++) {\nkernel/bpf/liveness.c:755:\t\t\thalf_spis_to_slots(aux[instance-\u003esubprog_start + i].may_write_mask,\nkernel/bpf/liveness.c-756-\t\t\t\t\t rel_mask(fm, i, FM_MAY_WRITE), nbits);\n--\nkernel/bpf/liveness.c=764=bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi)\n--\nkernel/bpf/liveness.c-775-\nkernel/bpf/liveness.c:776:const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)\nkernel/bpf/liveness.c-777-{\nkernel/bpf/liveness.c:778:\treturn env-\u003einsn_aux_data[insn_idx].may_write_mask;\nkernel/bpf/liveness.c-779-}\n--\nkernel/bpf/liveness.c=2504=int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env)\n--\nkernel/bpf/liveness.c-2551-\nkernel/bpf/liveness.c:2552:\tcompute_may_write_masks(env);\nkernel/bpf/liveness.c-2553-\n"
} |
| 55/3 | 2026/11/14 14:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 119724 output: 37 thoughts: 426 Thoughts: **Analyzing the BPF System Call Memory Handling** Okay, so I'm diving into this `bpf_sys_bpf` function. It calls `__sys_bpf`, and it's taking an `attr` struct. Now, a key point: `__sys_bpf` *might* write to that `attr` struct. I'm thinking about things like `attr->test.retval`, `attr->raw_tracepoint.cookie` – that kind of thing. Hold on... I need to make sure the memory buffer passed to `bpf_sys_bpf` is properly initialized. Did changing `MEM_RDONLY` to `MEM_WRITE` have any effect on initialization checks? Let's clarify this, the use of `MEM_WRITE` alone means it's an input/output buffer and that `MEM_UNINIT` is *not* set. The `bpf_sys_bpf_proto` uses `ARG_PTR_TO_MEM | MEM_WRITE`, which tells me it does *not* have `MEM_UNINIT`. That means the buffer passed to `bpf_sys_bpf` *has* to be initialized, right? But wait a minute, even when it was `MEM_RDONLY`, it was read-only, which also required the buffer to be initialized, because its contents were being read. Why the change from `MEM_RDONLY` to `MEM_WRITE`? Ah, got it. Because `__sys_bpf` *can* write to `attr`, especially if a syscall program calls `bpf_sys_bpf(BPF_PROG_TEST_RUN, ...)` or something like that. Marking it `MEM_WRITE` tells the verifier that the helper might write to that memory, which means it should *not* be a read-only map value or read-only memory. But, does this allow uninitialized memory to be read? No, because the absence of `MEM_UNINIT` implies that `check_helper_mem_access` checks the memory is initialized if read. Okay, I need to confirm this. Let's go straight to the source. I need to verify what `check_helper_mem_access` actually does when `MEM_WRITE` is passed without `MEM_UNINIT`. Time to check `check_helper_mem_access` in `kernel/bpf/verifier.c`. |
| 56/3 | 2026/11/14 14:43 | tool | grepper |
0mArgs:{
"Expression": "check_helper_mem_access\\(",
"PathPrefixes": [
"kernel/bpf/verifier.c"
]
}Results: {
"Output": "kernel/bpf/verifier.c=7918=static int check_stack_range_initialized(\n--\nkernel/bpf/verifier.c-8049-\nkernel/bpf/verifier.c:8050:static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\nkernel/bpf/verifier.c-8051-\t\t\t\t argno_t argno, int access_size,\n--\nkernel/bpf/verifier.c=8155=static int check_mem_size_reg(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-8207-\tif (access_type \u0026 BPF_READ)\nkernel/bpf/verifier.c:8208:\t\terr = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),\nkernel/bpf/verifier.c-8209-\t\t\t\t\t BPF_READ, zero_size_allowed, meta, NULL);\nkernel/bpf/verifier.c-8210-\tif (!err \u0026\u0026 access_type \u0026 BPF_WRITE)\nkernel/bpf/verifier.c:8211:\t\terr = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),\nkernel/bpf/verifier.c-8212-\t\t\t\t\t BPF_WRITE, zero_size_allowed, meta, NULL);\n--\nkernel/bpf/verifier.c=8229=static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-8253-\tif (access_type \u0026 BPF_READ)\nkernel/bpf/verifier.c:8254:\t\terr = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, meta,\nkernel/bpf/verifier.c-8255-\t\t\t\t\t known_memory);\nkernel/bpf/verifier.c-8256-\tif (!err \u0026\u0026 (access_type \u0026 BPF_WRITE))\nkernel/bpf/verifier.c:8257:\t\terr = check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, meta,\nkernel/bpf/verifier.c-8258-\t\t\t\t\t known_memory);\n--\nkernel/bpf/verifier.c=9774=static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,\n--\nkernel/bpf/verifier.c-9888-\t\tkey_size = meta-\u003emap.ptr-\u003ekey_size;\nkernel/bpf/verifier.c:9889:\t\terr = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, meta,\nkernel/bpf/verifier.c-9890-\t\t\t\t\t NULL);\n--\nkernel/bpf/verifier.c-9917-\nkernel/bpf/verifier.c:9918:\t\terr = check_helper_mem_access(env, reg, argno, meta-\u003emap.ptr-\u003evalue_size,\nkernel/bpf/verifier.c-9919-\t\t\t\t\t arg_type \u0026 MEM_WRITE ? BPF_WRITE : BPF_READ,\n--\nkernel/bpf/verifier.c=14422=get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-14598-\t\t * Otherwise this is a fixed-size memory buffer supported by\nkernel/bpf/verifier.c:14599:\t\t * check_helper_mem_access(): a pointer to a scalar or a struct of\nkernel/bpf/verifier.c-14600-\t\t * scalars. The access size is derived from the pointed-to BTF type.\n"
} |
| 57/3 | 2026/11/14 14:43 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 121716 output: 37 thoughts: 183 Thoughts: **Analyzing Memory Access Checks in BPF Code** Alright, let's dive into this BPF code. I see we're at lines 8207-8212, and the core of it seems to be checking memory access. The code first tests if `access_type` includes `BPF_READ`. If so, it calls `check_helper_mem_access` to validate the read. Then, it checks if `access_type` includes `BPF_WRITE`, and if so, calls `check_helper_mem_access` again, this time to check the write. It's pretty straightforward, covering both read and write access separately. The intriguing part is `access_type`. I need to figure out what that represents. What are its values? Where is it defined? Knowing what it holds is key to understanding the conditional logic and the overall intention of the code. To get a better picture, I should look at `check_mem_size_reg`, which covers lines 8190-8220. Let's trace back from there, or at least understand what is happening in the surrounding area. From there, I should have a good idea of how memory access is checked, and by extension, secured. |
| 58/3 | 2026/11/14 14:44 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 8190,
"LineCount": 30
}Results: {
"Contents": "8190:\t\t\tgoto size_error;\n8191:\t\t}\n8192:\t\n8193:\t\tif (reg_umin(size_reg) == 0 \u0026\u0026 !zero_size_allowed) {\n8194:\t\t\tverbose(env, \"%s invalid zero-sized read: u64=[%lld,%lld]\\n\",\n8195:\t\t\t\treg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg));\n8196:\t\t\terr = -EACCES;\n8197:\t\t\tgoto size_error;\n8198:\t\t}\n8199:\t\n8200:\t\tif (reg_umax(size_reg) \u003e= BPF_MAX_VAR_SIZ) {\n8201:\t\t\tverbose(env, \"%s unbounded memory access, use 'var \u0026= const' or 'if (var \u003c const)'\\n\",\n8202:\t\t\t\treg_arg_name(env, size_argno));\n8203:\t\t\terr = -EACCES;\n8204:\t\t\tgoto size_error;\n8205:\t\t}\n8206:\t\n8207:\t\tif (access_type \u0026 BPF_READ)\n8208:\t\t\terr = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),\n8209:\t\t\t\t\t\t BPF_READ, zero_size_allowed, meta, NULL);\n8210:\t\tif (!err \u0026\u0026 access_type \u0026 BPF_WRITE)\n8211:\t\t\terr = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),\n8212:\t\t\t\t\t\t BPF_WRITE, zero_size_allowed, meta, NULL);\n8213:\t\tif (err \u0026\u0026 failure)\n8214:\t\t\t*failure = BPF_MEM_SIZE_FAIL_MEMORY;\n8215:\t\n8216:\t\treturn err;\n8217:\t\n8218:\tsize_error:\n8219:\t\tif (failure)\n"
} |
| 59/3 | 2026/11/14 14:44 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 122743 output: 37 thoughts: 45 Thoughts: Okay, let's dive into this. Here's my thought process on dissecting the code, presented from my perspective as an expert: **Tracing `access_type` in `check_mem_size_reg`** Alright, I'm going to track down the source of `access_type` as it relates to `check_mem_size_reg`. Seems like a critical variable and function for memory management. I need to understand where this crucial `access_type` is actually *set* for this specific function. Line numbers are a great starting point for navigation, so I'll zero in on the surrounding code around line 9800 – that's often where the action is. My initial focus is to pinpoint *where* that `access_type` value is decided. Then I will need to look at what calls `check_mem_size_reg` around line 9800 to understand the context. This will show how `access_type` is used. |
| 60/3 | 2026/11/14 14:44 | tool | grepper |
0mArgs:{
"Expression": "check_mem_size_reg\\(",
"PathPrefixes": [
"kernel/bpf/verifier.c"
]
}Results: {
"Output": "kernel/bpf/verifier.c=8144=enum bpf_mem_size_failure {\n--\nkernel/bpf/verifier.c-8154- */\nkernel/bpf/verifier.c:8155:static int check_mem_size_reg(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-8156-\t\t\t struct bpf_reg_state *mem_reg,\n--\nkernel/bpf/verifier.c=9774=static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,\n--\nkernel/bpf/verifier.c-10137-\nkernel/bpf/verifier.c:10138:\t\terr = check_mem_size_reg(env, buff_reg, reg, buff_argno, argno,\nkernel/bpf/verifier.c-10139-\t\t\t\t\t access_type, zero_size_allowed, meta, \u0026failure);\n"
} |
| 61/3 | 2026/11/14 14:44 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 123300 output: 36 thoughts: 4626 Thoughts: **Deep Dive into Potential KMSAN Issues in BPF Verifier Patch** Okay, let's break this down. My primary concern here is ensuring this patch doesn't introduce or exacerbate uninitialized memory reads, particularly those that KMSAN would catch *and* that wouldn't be caught by KASAN or other standard tools. My expertise dictates a meticulous review of allocations, data structures, and how they interact with the BPF verifier's state. First, I examined `func_arg_access_type` and its relation to `MEM_WRITE` and `MEM_UNINIT`. It correctly interprets `ARG_PTR_TO_MEM | MEM_WRITE` as an in/out buffer, which is standard. Then I reviewed the rules for KMSAN, focusing on rules (2), (3) and (4) to see if this patch introduces risks. This involves scrutinizing data structures. I drilled down into `struct scev`: This is the core of this patch, as it's the structure used for symbolic constant expression variables within the verifier. So I meticulously examined the allocation and usage of its members: `exprs_ht`, `exprs_next`, `linked`, and `slice_slots`. The most critical points arise in the allocation and usage of `scev->exprs` and its related arrays. The `grow_exprs` function, specifically the `kvrealloc` calls *without* `__GFP_ZERO`, immediately raised a red flag. This means that the newly allocated memory for `scev->exprs`, `exprs_next`, and `exprs_ht` isn't initialized to zero. However, through careful reading of `add_expr`, I confirmed that `scev->exprs[id]` *is* completely overwritten before `exprs_ht_add` is called, ensuring that data is initialized before use. Moreover, `scev->exprs_next` is populated and used correctly, and `scev->exprs_ht` is set to 0. Also, `bpf_init_scev` explicitly initializes all of the initial entries from 0 up to `REG_EXPR_ID(REGS_NUM) - 1`. Next, I looked carefully at `struct expr`. The concern around `expr_hash` and the union between `params` and `imm` was quickly resolved. `imm` overlaps the `params` in a union, which means that `params[0]` and `params[1]` are set when `imm` is set, and aren't left uninitialized. `expr_eq` also does not use uninitialized memory. Then, I turned my attention to `scev->linked`, and, from the context, determined it's properly allocated and initialized through the structure `struct scev_linked_reg` (whose members are assigned). Also `envs` has `kzalloc` which will ensure that it is initialized to zero, addressing any uninitialized memory concern there. Finally, I carefully considered KMSAN's actual role in this scenario. I went through the scenarios one by one, and eliminated them. I determined that the patch doesn't copy anything to user space. It also *doesn't* introduce any direct kernel reads of uninitialized memory. KMSAN's purpose isn't to detect bugs easily detected through existing kernel tools, so the key is to determine if BPF verifier bugs can cause a read of uninitialized memory in kernel. The key question is whether these changes alter BPF stack initialization or introduce new ways to read uninitialized stack data within a BPF program that could then lead to a read of uninitialized memory on the kernel stack through the BPF interpreter or JIT. Examining the changes to `__clean_func_state` and `stacksafe` is *critical* in addressing this question. I will need to understand the logic changes around lines 125-180 of `kernel/bpf/states.c` to be completely certain. |
| 62/3 | 2026/11/14 14:44 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/states.c",
"FirstLine": 115,
"LineCount": 70
}Results: {
"Contents": " 115:\t\t\t\tu8 stype = bpf_stack_slot(st, i)-\u003eslot_type[7];\n 116:\t\n 117:\t\t\t\t/*\n 118:\t\t\t\t * Don't clear special slots.\n 119:\t\t\t\t * destroy_if_dynptr_stack_slot() needs STACK_DYNPTR to\n 120:\t\t\t\t * detect overwrites and invalidate associated data slices.\n 121:\t\t\t\t * is_iter_reg_valid_uninit() and is_irq_flag_reg_valid_uninit()\n 122:\t\t\t\t * check for their respective slot types to detect double-create.\n 123:\t\t\t\t */\n 124:\t\t\t\tif (stype == STACK_DYNPTR || stype == STACK_ITER ||\n 125:\t\t\t\t stype == STACK_IRQ_FLAG)\n 126:\t\t\t\t\tcontinue;\n 127:\t\n 128:\t\t\t\t/*\n 129:\t\t\t\t * When the half-slot closer to FP is dead, what remains of a\n 130:\t\t\t\t * 64-bit spill looks like a 32-bit spill: the low 32 bits of\n 131:\t\t\t\t * the value. On big endian the other half-slot holds the upper\n 132:\t\t\t\t * 32 bits.\n 133:\t\t\t\t */\n 134:\t\t\t\tif (hi_live \u0026\u0026 bpf_spill_size(bpf_stack_slot(st, i)) == BPF_REG_SIZE \u0026\u0026\n 135:\t\t\t\t !bpf_stack_narrow_access_ok(0, BPF_REG_SIZE / 2, BPF_REG_SIZE))\n 136:\t\t\t\t\tcontinue;\n 137:\t\n 138:\t\t\t\t/*\n 139:\t\t\t\t * Only scalar spills can be degraded to raw stack bytes\n 140:\t\t\t\t * when their high half is dead. Pointer spills need the\n 141:\t\t\t\t * saved spilled_ptr metadata so partial fills keep\n 142:\t\t\t\t * rejecting as non-scalar register fills.\n 143:\t\t\t\t */\n 144:\t\t\t\tif (!hi_live) {\n 145:\t\t\t\t\tstruct bpf_reg_state *spill = \u0026bpf_stack_slot(st, i)-\u003espilled_ptr;\n 146:\t\n 147:\t\t\t\t\tif (lo_live \u0026\u0026 stype == STACK_SPILL) {\n 148:\t\t\t\t\t\tif (spill-\u003etype != SCALAR_VALUE)\n 149:\t\t\t\t\t\t\tcontinue;\n 150:\t\t\t\t\t\t/* keep what is known about the low half */\n 151:\t\t\t\t\t\tif (bpf_register_is_null(spill))\n 152:\t\t\t\t\t\t\tcontinue;\n 153:\t\t\t\t\t\tfor (j = 0; j \u003c 4; j++) {\n 154:\t\t\t\t\t\t\tu8 *t = \u0026bpf_stack_slot(st, i)-\u003eslot_type[j];\n 155:\t\n 156:\t\t\t\t\t\t\tif (*t == STACK_SPILL)\n 157:\t\t\t\t\t\t\t\t*t = STACK_MISC;\n 158:\t\t\t\t\t\t}\n 159:\t\t\t\t\t}\n 160:\t\t\t\t\tbpf_mark_reg_not_init(env, spill);\n 161:\t\t\t\t}\n 162:\t\t\t\tfor (j = start; j \u003c end; j++)\n 163:\t\t\t\t\tbpf_stack_slot(st, i)-\u003eslot_type[j] = STACK_POISON;\n 164:\t\t\t}\n 165:\t\t}\n 166:\t}\n 167:\t\n 168:\tint bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *st)\n 169:\t{\n 170:\t\tint i, err;\n 171:\t\n 172:\t\terr = bpf_live_stack_query_init(env, st);\n 173:\t\tif (err)\n 174:\t\t\treturn err;\n 175:\t\tfor (i = 0; i \u003c= st-\u003ecurframe; i++) {\n 176:\t\t\tu32 ip = bpf_frame_insn_idx(st, i);\n 177:\t\t\tu16 live_regs = env-\u003einsn_aux_data[ip].live_regs_before;\n 178:\t\n 179:\t\t\t__clean_func_state(env, st-\u003eframe[i], live_regs, i);\n 180:\t\t}\n 181:\t\treturn 0;\n 182:\t}\n 183:\t\n 184:\tstatic bool regs_exact(const struct bpf_reg_state *rold,\n"
} |
| 63/3 | 2026/11/14 14:44 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 129996 output: 34 thoughts: 395 Thoughts: **Analyzing State Optimization in BPF Verification** Okay, let's dive into this `__clean_func_state` function. My initial impression is that this is the mechanism for state pruning during verification, specifically aimed at optimizing state comparisons. The core idea seems to be cleaning up the state when a "high half" is dead, which makes the subsequent comparisons more efficient. But hold on... I need to consider `bpf_half_slot_live_before` in `kernel/bpf/liveness.c`. This looks crucial. This function determines if a particular half-slot within the stack is live before a specific instruction. It iterates through function instances within the environment, checking if the current instruction falls within the scope of a running instance and if the slot is marked as live. That's good, but how does this relate to the cleanup? Ah, I see a related section of code. Here, there are conditions relating to the `arg_track` structure and frames. It looks like frames hold pointers to the current stack and caller stacks. I notice a significant optimization when a frame is deemed imprecise, and specific bits aren't set in the mask. In this case, there's a modification to the `arg_track` structure. The mask is being updated to reflect live parts, potentially trimming what's tracked. But, I need to know more about what `arg_track` actually *does*. Let's dig into that struct definition in `kernel/bpf/liveness.c`. The context has been set - Let's see how `arg_track` helps! |
| 64/3 | 2026/11/14 14:45 | tool | grepper |
0mArgs:{
"Expression": "struct arg_track",
"PathPrefixes": [
"kernel/bpf/liveness.c"
]
}Results: {
"Output": "\nFull output is too long, showing 200 out of 250 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (1 files in total):\nkernel/bpf/liveness.c:77\n\nkernel/bpf/liveness.c=66=struct live_stack_query {\n--\nkernel/bpf/liveness.c-72-\nkernel/bpf/liveness.c:73:struct arg_track;\nkernel/bpf/liveness.c-74-\nkernel/bpf/liveness.c=75=struct bpf_liveness {\n--\nkernel/bpf/liveness.c-79-\t/* MAX_AT_TRACK_REGS for every depth: analyze_subprog() calls itself, keep its frame small */\nkernel/bpf/liveness.c:80:\tstruct arg_track *callee_args;\nkernel/bpf/liveness.c-81-};\n--\nkernel/bpf/liveness.c=782=static int print_instances(struct bpf_verifier_env *env)\n--\nkernel/bpf/liveness.c-830-\nkernel/bpf/liveness.c:831:struct arg_track {\nkernel/bpf/liveness.c-832-\tunion {\n--\nkernel/bpf/liveness.c=851=struct spill_snapshot {\nkernel/bpf/liveness.c-852-\tu32 slots;\nkernel/bpf/liveness.c:853:\tstruct arg_track at[];\nkernel/bpf/liveness.c-854-};\n--\nkernel/bpf/liveness.c=862=static int stack_arg_off_to_slot(s16 off)\n--\nkernel/bpf/liveness.c-870-\nkernel/bpf/liveness.c:871:static bool arg_is_visited(const struct arg_track *at)\nkernel/bpf/liveness.c-872-{\n--\nkernel/bpf/liveness.c-875-\nkernel/bpf/liveness.c:876:static bool arg_is_fp(const struct arg_track *at)\nkernel/bpf/liveness.c-877-{\n--\nkernel/bpf/liveness.c-880-\nkernel/bpf/liveness.c:881:static void verbose_arg_track(struct bpf_verifier_env *env, struct arg_track *at)\nkernel/bpf/liveness.c-882-{\n--\nkernel/bpf/liveness.c-903-\nkernel/bpf/liveness.c:904:static bool arg_track_eq(const struct arg_track *a, const struct arg_track *b)\nkernel/bpf/liveness.c-905-{\n--\nkernel/bpf/liveness.c-921-\nkernel/bpf/liveness.c:922:static struct arg_track arg_single(s8 arg, s16 off)\nkernel/bpf/liveness.c-923-{\nkernel/bpf/liveness.c:924:\tstruct arg_track at = {};\nkernel/bpf/liveness.c-925-\n--\nkernel/bpf/liveness.c-936- */\nkernel/bpf/liveness.c:937:static struct arg_track arg_merge_offsets(struct arg_track a, struct arg_track b)\nkernel/bpf/liveness.c-938-{\nkernel/bpf/liveness.c:939:\tstruct arg_track result = { .frame = a.frame };\nkernel/bpf/liveness.c:940:\tstruct arg_track imp = { .frame = a.frame };\nkernel/bpf/liveness.c-941-\tint i = 0, j = 0, k = 0;\n--\nkernel/bpf/liveness.c-978- */\nkernel/bpf/liveness.c:979:static struct arg_track arg_join_imprecise(struct arg_track a, struct arg_track b)\nkernel/bpf/liveness.c-980-{\n--\nkernel/bpf/liveness.c-992-\nkernel/bpf/liveness.c:993:\treturn (struct arg_track){ .mask = m, .frame = ARG_IMPRECISE };\nkernel/bpf/liveness.c-994-}\n--\nkernel/bpf/liveness.c-999- */\nkernel/bpf/liveness.c:1000:static struct arg_track arg_or_none(struct arg_track a)\nkernel/bpf/liveness.c-1001-{\n--\nkernel/bpf/liveness.c-1004-\tif (!a.off[0])\nkernel/bpf/liveness.c:1005:\t\treturn (struct arg_track){ .frame = a.frame };\nkernel/bpf/liveness.c-1006-\treturn arg_merge_offsets(a, arg_single(a.frame, 0));\n--\nkernel/bpf/liveness.c-1009-/* Join two arg_track values at merge points */\nkernel/bpf/liveness.c:1010:static struct arg_track __arg_track_join(struct arg_track a, struct arg_track b)\nkernel/bpf/liveness.c-1011-{\n--\nkernel/bpf/liveness.c-1018-\t\tif (a.off_cnt == 0 || b.off_cnt == 0)\nkernel/bpf/liveness.c:1019:\t\t\treturn (struct arg_track){ .frame = a.frame };\nkernel/bpf/liveness.c-1020-\t\t/* Merge offset sets; falls back to off_cnt=0 if \u003e4 */\n--\nkernel/bpf/liveness.c=1041=static bool arg_track_join(struct bpf_verifier_env *env, int idx, int target, int r,\nkernel/bpf/liveness.c:1042:\t\t\t struct arg_track *in, struct arg_track out)\nkernel/bpf/liveness.c-1043-{\nkernel/bpf/liveness.c:1044:\tstruct arg_track old = *in;\nkernel/bpf/liveness.c:1045:\tstruct arg_track new_val = __arg_track_join(old, out);\nkernel/bpf/liveness.c-1046-\n--\nkernel/bpf/liveness.c=1071=static bool arg_track_join_all(struct bpf_verifier_env *env, int idx, int target,\nkernel/bpf/liveness.c:1072:\t\t\t struct arg_track *in, struct arg_track *stack_in,\nkernel/bpf/liveness.c:1073:\t\t\t const struct arg_track *out, const struct arg_track *stack_out,\nkernel/bpf/liveness.c-1074-\t\t\t u32 nslots)\n--\nkernel/bpf/liveness.c-1091- */\nkernel/bpf/liveness.c:1092:static void arg_track_alu64(struct arg_track *dst, const struct arg_track *src)\nkernel/bpf/liveness.c-1093-{\n--\nkernel/bpf/liveness.c=1121=static bool arg_add(s16 off, s64 delta, s16 *out)\n--\nkernel/bpf/liveness.c-1129-\nkernel/bpf/liveness.c:1130:static void arg_padd(struct arg_track *at, s64 delta)\nkernel/bpf/liveness.c-1131-{\n--\nkernel/bpf/liveness.c=1199=static int fp_off_to_slot(s16 off, u32 nslots)\n--\nkernel/bpf/liveness.c-1207-\nkernel/bpf/liveness.c:1208:static struct arg_track fill_from_stack(struct bpf_insn *insn,\nkernel/bpf/liveness.c:1209:\t\t\t\t\tstruct arg_track *at_out, int reg,\nkernel/bpf/liveness.c:1210:\t\t\t\t\tstruct arg_track *at_stack_out, u32 nslots,\nkernel/bpf/liveness.c-1211-\t\t\t\t\tint depth)\nkernel/bpf/liveness.c-1212-{\nkernel/bpf/liveness.c:1213:\tstruct arg_track imp = {\nkernel/bpf/liveness.c-1214-\t\t.mask = GENMASK(depth, 0),\n--\nkernel/bpf/liveness.c-1216-\t};\nkernel/bpf/liveness.c:1217:\tstruct arg_track result = { .frame = ARG_NONE };\nkernel/bpf/liveness.c-1218-\tint cnt, i;\n--\nkernel/bpf/liveness.c-1247- */\nkernel/bpf/liveness.c:1248:static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out,\nkernel/bpf/liveness.c:1249:\t\t\t int reg, struct arg_track *at_stack_out, u32 nslots,\nkernel/bpf/liveness.c:1250:\t\t\t struct arg_track *val, u32 sz)\nkernel/bpf/liveness.c-1251-{\nkernel/bpf/liveness.c:1252:\tstruct arg_track none = { .frame = ARG_NONE };\nkernel/bpf/liveness.c:1253:\tstruct arg_track new_val = sz == 8 ? *val : none;\nkernel/bpf/liveness.c-1254-\tint cnt, i;\n--\nkernel/bpf/liveness.c-1288- */\nkernel/bpf/liveness.c:1289:static void clear_overlapping_stack_slots(struct arg_track *at_stack, u32 nslots, s16 off,\nkernel/bpf/liveness.c-1290-\t\t\t\t\t u32 sz, int cnt)\nkernel/bpf/liveness.c-1291-{\nkernel/bpf/liveness.c:1292:\tstruct arg_track none = { .frame = ARG_NONE };\nkernel/bpf/liveness.c-1293-\n--\nkernel/bpf/liveness.c=1315=static void clear_stack_for_all_offs(struct bpf_insn *insn,\nkernel/bpf/liveness.c:1316:\t\t\t\t struct arg_track *at_out, int reg,\nkernel/bpf/liveness.c:1317:\t\t\t\t struct arg_track *at_stack_out, u32 nslots, u32 sz)\nkernel/bpf/liveness.c-1318-{\n--\nkernel/bpf/liveness.c=1341=static void arg_track_log(struct bpf_verifier_env *env, struct bpf_insn *insn, int idx,\nkernel/bpf/liveness.c:1342:\t\t\t struct arg_track *at_in, struct arg_track *at_stack_in,\nkernel/bpf/liveness.c:1343:\t\t\t struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots)\nkernel/bpf/liveness.c-1344-{\n--\nkernel/bpf/liveness.c-1389-\nkernel/bpf/liveness.c:1390:static bool can_be_local_fp(int depth, int regno, struct arg_track *at)\nkernel/bpf/liveness.c-1391-{\n--\nkernel/bpf/liveness.c-1399- */\nkernel/bpf/liveness.c:1400:static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf_insn *insn,\nkernel/bpf/liveness.c:1401:\t\t\t\t\tstruct arg_track *at_out, int reg,\nkernel/bpf/liveness.c:1402:\t\t\t\t\tstruct arg_track *at_stack_out, u32 nslots,\nkernel/bpf/liveness.c-1403-\t\t\t\t\tint depth, u32 *callsites)\nkernel/bpf/liveness.c-1404-{\nkernel/bpf/liveness.c:1405:\tstruct arg_track *ptr = \u0026at_out[reg];\nkernel/bpf/liveness.c-1406-\n--\nkernel/bpf/liveness.c-1415-\tif (ptr-\u003eframe == ARG_IMPRECISE \u0026\u0026 !(ptr-\u003emask \u0026 BIT(depth)) \u0026\u0026 ptr-\u003emask)\nkernel/bpf/liveness.c:1416:\t\treturn (struct arg_track){ .mask = GENMASK(fls(ptr-\u003emask) - 1, 0),\nkernel/bpf/liveness.c-1417-\t\t\t\t\t .frame = ARG_IMPRECISE };\nkernel/bpf/liveness.c:1418:\treturn (struct arg_track){ .frame = ARG_NONE };\nkernel/bpf/liveness.c-1419-}\n--\nkernel/bpf/liveness.c=1427=static bool subprog_gets_local_fp(struct bpf_verifier_env *env, struct bpf_insn *insn, int insn_idx,\nkernel/bpf/liveness.c:1428:\t\t\t\t struct arg_track *at, int depth)\nkernel/bpf/liveness.c-1429-{\n--\nkernel/bpf/liveness.c=1451=static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn,\nkernel/bpf/liveness.c-1452-\t\t\t int insn_idx,\nkernel/bpf/liveness.c:1453:\t\t\t struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots,\nkernel/bpf/liveness.c:1454:\t\t\t const struct arg_track *at_stack_arg_entry,\nkernel/bpf/liveness.c-1455-\t\t\t struct func_instance *instance,\n--\nkernel/bpf/liveness.c-1460-\tu8 code = BPF_OP(insn-\u003ecode);\nkernel/bpf/liveness.c:1461:\tstruct arg_track *dst = \u0026at_out[insn-\u003edst_reg];\nkernel/bpf/liveness.c:1462:\tstruct arg_track *src = \u0026at_out[insn-\u003esrc_reg];\nkernel/bpf/liveness.c:1463:\tstruct arg_track none = { .frame = ARG_NONE };\nkernel/bpf/liveness.c-1464-\tint r, slot;\n--\nkernel/bpf/liveness.c-1566-\t\t\t/* BPF_XCHG, BPF_CMPXCHG or BPF_{ADD,AND,OR,XOR} | [BPF_FETCH] */\nkernel/bpf/liveness.c:1567:\t\t\tstruct arg_track old = none;\nkernel/bpf/liveness.c-1568-\n--\nkernel/bpf/liveness.c-1593- */\nkernel/bpf/liveness.c:1594:static int record_stack_access_off(struct func_instance *instance, const struct arg_track *arg,\nkernel/bpf/liveness.c-1595-\t\t\t\t s64 off_idx, struct arg_access_info info,\n--\nkernel/bpf/liveness.c=1638=static int record_stack_access(struct bpf_verifier_env *env,\nkernel/bpf/liveness.c-1639-\t\t\t struct func_instance *instance,\nkernel/bpf/liveness.c:1640:\t\t\t const struct arg_track *arg,\nkernel/bpf/liveness.c-1641-\t\t\t struct arg_access_info info, u32 frame, u32 insn_idx)\n--\nkernel/bpf/liveness.c=1695=static int record_load_store_access(struct bpf_verifier_env *env,\nkernel/bpf/liveness.c-1696-\t\t\t\t struct func_instance *instance,\nkernel/bpf/liveness.c:1697:\t\t\t\t struct arg_track *at, int insn_idx)\nkernel/bpf/liveness.c-1698-{\n--\nkernel/bpf/liveness.c-1703-\tbool read = false, write = false;\nkernel/bpf/liveness.c:1704:\tstruct arg_track resolved, *ptr;\nkernel/bpf/liveness.c-1705-\tint oi;\n--\nkernel/bpf/liveness.c=1781=static int record_arg_access(struct bpf_verifier_env *env,\n--\nkernel/bpf/liveness.c-1783-\t\t\t struct bpf_insn *insn,\n\n"
} |
| 65/3 | 2026/11/14 14:45 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 135157 output: 38 thoughts: 1181 Thoughts: **Analyzing BPF Verifier Changes** Okay, let's dive into these BPF verifier changes. My initial thought is to cross-reference with `kernel/bpf/liveness.c` to understand the bigger picture of stack slot tracking and dead code elimination – it's crucial for understanding the optimization context. First, I'm noting the math-centric updates: the `tnum_overlaps_urange`, `tnum_overlaps_cnum`, and `reg_is_empty` changes. It looks like this focuses on strengthening range check logic. This is about ensuring branch feasibility and avoiding empty or infeasible branches. The comment on `reg_bounds_sync()` and the discussion of bit representation immediately clicks in my mind, this is tight math. It's not about uninitialized memory issues. Now, the removal of the linked register tracking is interesting. They've removed `struct linked_regs` and related code. The previous use of `reg->id` and `reg->delta` up to 5 linked registers seems to be gone. Also, the removal of `assign_scalar_id_before_mov`, `dst_reg->delta`, and `BPF_ADD_CONST` flags on scalar ids indicate a significant simplification of scalar ID management. This seems like a move away from dynamic linked register tracking. The `coerce_subreg_to_size_sx` change is about refining the sign-extension check. Specifically, there's a new check `reg_s32_min()` and `reg_s32_max()`, and that it now directly tests the range against the signed N-bit range. This is about efficiently verifying that a value is within the range, no extension is required, so short-circuit. It's a nice, focused refinement. Next, I'm picking up on `call_func_on_its_own` and `fresh_id`. Removing `clear_scalar_id` and the `BPF_ADD_CONST` handling indicates further simplification in how scalar IDs are managed, which is consistent with the earlier change. The addition in `check_special_kfunc` with the slice buffer check seems significant. The verifier now actively prevents storing through a zero-byte slice, and there's a check related to read-only memory, `!type_is_rdonly_mem`, slice buffer and constant value size. This is a safety measure to avoid potential memory corruption in slices. Looking at `adjust_reg_min_max_vals`, the removal of scalar ID propagation and direct return of `adjust_scalar_min_max_vals` further strengthens the impression of simplification around scalar ID handling. The cleanup in `check_alu_op` with the removal of `assign_scalar_id_before_mov` and `clear_scalar_id` further reinforces the simplification trend. Finally, I'll examine the functions `regs_fit_in_bits`, `scev_reg_for_fill`, `scev_mem_to_slot`, `recompute_ptr`, and `refine_linked_regs` more closely. I should read through lines 19400-19570 of `kernel/bpf/verifier.c` to see if there are any subtle changes related to the previous simplification steps. I anticipate this will relate to tighter handling and simplification of register bounds. |
| 66/3 | 2026/11/14 14:45 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 19400,
"LineCount": 85
}Results: {
"Contents": "19400:\t\tdefault:\n19401:\t\t\treturn false;\n19402:\t\t}\n19403:\t\n19404:\t\treturn true;\n19405:\t}\n19406:\t\n19407:\t/* a == b (mod 2^N) implies a == b if both fit in uN or both fit in sN. N is @bits. */\n19408:\tstatic bool regs_fit_in_bits(const struct bpf_reg_state *a, const struct bpf_reg_state *b,\n19409:\t\t\t\t u32 bits)\n19410:\t{\n19411:\t\tu64 umax = GENMASK_ULL(bits - 1, 0);\n19412:\t\ts64 smax = umax \u003e\u003e 1;\n19413:\t\n19414:\t\treturn (reg_umax(a) \u003c= umax \u0026\u0026 reg_umax(b) \u003c= umax) ||\n19415:\t\t (reg_smin(a) \u003e= -smax - 1 \u0026\u0026 reg_smax(a) \u003c= smax \u0026\u0026\n19416:\t\t\treg_smin(b) \u003e= -smax - 1 \u0026\u0026 reg_smax(b) \u003c= smax);\n19417:\t}\n19418:\t\n19419:\t/*\n19420:\t * The state of the SCEV register @r. As in check_stack_read_fixed_off() a fill of @bits bits from\n19421:\t * byte @fill_off of the slot reads the low bits of the spill.\n19422:\t */\n19423:\tstatic struct bpf_reg_state *scev_reg_for_fill(struct bpf_func_state *frame, u32 r, u32 fill_off,\n19424:\t\t\t\t\t\t u32 bits)\n19425:\t{\n19426:\t\tstruct bpf_stack_state *ss;\n19427:\t\n19428:\t\tif (r \u003c MAX_BPF_REG)\n19429:\t\t\treturn \u0026frame-\u003eregs[r];\n19430:\t\tif (r - MAX_BPF_REG \u003e= bpf_stack_nr_slots(frame))\n19431:\t\t\treturn NULL;\n19432:\t\tss = bpf_stack_slot(frame, r - MAX_BPF_REG);\n19433:\t\tif (!bpf_is_spilled_reg(ss) || bpf_spill_size(ss) * BITS_PER_BYTE \u003c bits ||\n19434:\t\t !bpf_stack_narrow_access_ok(fill_off, bits / BITS_PER_BYTE, bpf_spill_size(ss)))\n19435:\t\t\treturn NULL;\n19436:\t\treturn \u0026ss-\u003espilled_ptr;\n19437:\t}\n19438:\t\n19439:\t/*\n19440:\t * Scalar evolution promoted memory to the SCEV register *@regno, see struct env there, and names\n19441:\t * its address at the jump at @idx. This state knows which memory it is: the frame that is returned,\n19442:\t * its stack slot *@regno, *@fill_off counts from the start of the slot. The stack of a caller only:\n19443:\t * other memory has no state, and a store through r10 is no def of memory for scalar evolution.\n19444:\t * What holds the address is live: it was compared all the way from its def. Every place that\n19445:\t * compares, joins or drops states cleans them of what is dead first, see flow_arrive().\n19446:\t */\n19447:\tstatic struct bpf_func_state *scev_mem_to_slot(struct bpf_verifier_env *env,\n19448:\t\t\t\t\t\t struct bpf_verifier_state *vstate, int idx,\n19449:\t\t\t\t\t\t u32 *regno, u32 *fill_off)\n19450:\t{\n19451:\t\tstruct bpf_reg_state *ptr;\n19452:\t\tu32 base_regno;\n19453:\t\ts64 addr;\n19454:\t\n19455:\t\tif (!bpf_scev_mem_addr(env, idx, *regno, \u0026base_regno, \u0026addr))\n19456:\t\t\treturn NULL;\n19457:\t\tptr = scev_reg_for_fill(vstate-\u003eframe[vstate-\u003ecurframe], base_regno, 0, 64);\n19458:\t\tif (!ptr || ptr-\u003etype != PTR_TO_STACK || !tnum_is_const(ptr-\u003evar_off) ||\n19459:\t\t ptr-\u003eframeno \u003e= vstate-\u003ecurframe)\n19460:\t\t\treturn NULL;\n19461:\t\taddr += ptr-\u003evar_off.value + *fill_off;\n19462:\t\tif (addr \u003e= 0 || addr \u003c -MAX_BPF_STACK_JIT)\n19463:\t\t\treturn NULL;\n19464:\t\t*regno = MAX_BPF_REG + bpf_get_spi(addr);\n19465:\t\t*fill_off = addr \u0026 (BPF_REG_SIZE - 1);\n19466:\t\treturn vstate-\u003eframe[ptr-\u003eframeno];\n19467:\t}\n19468:\t\n19469:\t/*\n19470:\t *\tp = buf + i; if (i \u003e 100) return 0; *p = 0;\n19471:\t * p is @dst_reg, x is @ptr_reg, i is @off_reg. Scalar evolution says that p == x + i. So the insns\n19472:\t * 'p = x; p += i' are a no-op at run time, and a state that is sound before them is sound after\n19473:\t * them: apply their transfer function. Type, object and offset of p are taken from x as it is now;\n19474:\t * how p was computed does not matter.\n19475:\t * The old p is replaced, not intersected: a state does not distinguish two values of one hash map,\n19476:\t * and the intersection of an offset into the one with an offset into the other holds for neither.\n19477:\t * It is replaced only if the new range is a subset of the old one. An empty range is a subset too:\n19478:\t * the path is infeasible, p is left as it is.\n19479:\t */\n19480:\tstatic bool recompute_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *dst_reg,\n19481:\t\t\t\t const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg)\n19482:\t{\n19483:\t\tstruct bpf_reg_state sum = *ptr_reg;\n19484:\t\n"
} |
| 67/3 | 2026/11/14 14:45 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 138940 output: 38 thoughts: 29 Thoughts: Okay, here's my interpretation of what I'd be thinking, summarizing lines 19485 to 19570 of `kernel/bpf/verifier.c`, as if I were immersed in the code: **Diving Deep into the BPF Verifier** Alright, let's zero in on lines 19485 to 19570 within the BPF verifier. From this range, I'm expecting to encounter some crucial verification logic – likely related to register state tracking or perhaps constraint propagation, given the length and context. I'll need to pay close attention to the data structures involved, the loops, and the conditional branches. What are the key variables being examined and updated within these lines? Are we looking at handling of specific BPF instructions, or maybe some general validation of the program's structure? Are there any obvious potential vulnerabilities or areas for optimization that jump out? I'll be watching for any nuances related to memory access verification, stack frame analysis, or the handling of function calls. Hopefully, this block of code is well-commented. If not, I'll need to dissect it carefully, tracing the flow of control and deducing the intent of each operation. I'm keen to see how the verifier ensures that the BPF program adheres to the established safety rules, especially concerning resource limits and preventing unauthorized access. This section could contain a vital check against some form of program exploitation, and it's important to understand the details. My goal is to extract the core algorithm and how it's implemented. |
| 68/3 | 2026/11/14 14:45 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 19485,
"LineCount": 85
}Results: {
"Contents": "19485:\t\t/* the cpu can speculate past the jump with an out-of-bounds index */\n19486:\t\tif (!env-\u003ebypass_spec_v1)\n19487:\t\t\treturn false;\n19488:\t\t/* 'p += i' assigns a new id to a packet pointer */\n19489:\t\tif (ptr_reg-\u003etype == SCALAR_VALUE || type_is_pkt_pointer(ptr_reg-\u003etype) ||\n19490:\t\t !bpf_is_widenable_reg_type(ptr_reg))\n19491:\t\t\treturn false;\n19492:\t\t__mark_reg32_unbounded(\u0026sum);\n19493:\t\tscalar_step_add(\u0026sum, ptr_reg, off_reg);\n19494:\t\tsum.r64 = cnum64_add(ptr_reg-\u003er64, off_reg-\u003er64);\n19495:\t\tsum.var_off = tnum_add(ptr_reg-\u003evar_off, off_reg-\u003evar_off);\n19496:\t\treg_bounds_sync(\u0026sum);\n19497:\t\tif (reg_is_empty(\u0026sum) || const_tnum_range_mismatch(\u0026sum) ||\n19498:\t\t const_tnum_range_mismatch_32(\u0026sum))\n19499:\t\t\treturn false;\n19500:\t\tif (!bpf_reg_union_compatible(dst_reg, \u0026sum) || !cnum64_is_subset(dst_reg-\u003er64, sum.r64))\n19501:\t\t\treturn false;\n19502:\t\t*dst_reg = sum;\n19503:\t\treturn true;\n19504:\t}\n19505:\t\n19506:\t/*\n19507:\t * The jump at @idx refined @regno. A register that scalar evolution links to it holds\n19508:\t * @regno + delta on every path to the jump: intersect the two. The intersection is empty: no\n19509:\t * execution gets here with this state (the path is infeasible), the register is left as it is.\n19510:\t */\n19511:\tstatic void refine_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,\n19512:\t\t\t\t int idx, u32 regno)\n19513:\t{\n19514:\t\tstruct bpf_func_state *frame = vstate-\u003eframe[vstate-\u003ecurframe], *linked_frame;\n19515:\t\tstruct bpf_reg_state *reg, *base_reg, implied, saved;\n19516:\t\tu32 pos, linked_regno, fill_off, bits;\n19517:\t\tint base_regno;\n19518:\t\ts64 delta;\n19519:\t\n19520:\t\tif (frame-\u003eregs[regno].type != SCALAR_VALUE)\n19521:\t\t\treturn;\n19522:\t\tfor (pos = 0;\n19523:\t\t bpf_scev_next_linked_reg(env, idx, regno, \u0026pos, \u0026linked_regno, \u0026fill_off, \u0026base_regno,\n19524:\t\t\t\t\t \u0026delta, \u0026bits);\n19525:\t\t pos++) {\n19526:\t\t\tlinked_frame = frame;\n19527:\t\t\tif (linked_regno \u003e= BPF_SCEV_REGS_NUM)\n19528:\t\t\t\tlinked_frame = scev_mem_to_slot(env, vstate, idx, \u0026linked_regno, \u0026fill_off);\n19529:\t\t\tif (!linked_frame)\n19530:\t\t\t\tcontinue;\n19531:\t\t\treg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);\n19532:\t\t\t/*\n19533:\t\t\t * The other half-slot of a 64-bit spill is dead: __clean_func_state() left\n19534:\t\t\t * a 32-bit spill, the low 32 bits of the value.\n19535:\t\t\t */\n19536:\t\t\tif (!reg \u0026\u0026 bits == 64 \u0026\u0026\n19537:\t\t\t bpf_stack_narrow_access_ok(fill_off, BPF_REG_SIZE / 2, BPF_REG_SIZE)) {\n19538:\t\t\t\tbits = 32;\n19539:\t\t\t\treg = scev_reg_for_fill(linked_frame, linked_regno, fill_off, bits);\n19540:\t\t\t}\n19541:\t\t\tif (!reg || (base_regno \u003c 0 \u0026\u0026 reg-\u003etype != SCALAR_VALUE))\n19542:\t\t\t\tcontinue;\n19543:\t\n19544:\t\t\timplied = frame-\u003eregs[regno];\n19545:\t\t\tadd_scalar_to_reg(\u0026implied, delta);\n19546:\t\t\tif (base_regno \u003e= 0) {\n19547:\t\t\t\tbase_reg = scev_reg_for_fill(frame, base_regno, 0, 64);\n19548:\t\t\t\tif (base_reg \u0026\u0026 bits == 64 \u0026\u0026 recompute_ptr(env, reg, base_reg, \u0026implied))\n19549:\t\t\t\t\tgoto scratch;\n19550:\t\t\t\tcontinue;\n19551:\t\t\t}\n19552:\t\t\tif (regs_fit_in_bits(reg, \u0026implied, bits))\n19553:\t\t\t\tbits = 64;\n19554:\t\t\tif (bits \u003c 32)\n19555:\t\t\t\tcontinue;\n19556:\t\t\t/* tnum_intersect() of two tnums that don't overlap is not empty */\n19557:\t\t\tif (!tnum_overlap(bits == 32 ? tnum_subreg(reg-\u003evar_off) : reg-\u003evar_off,\n19558:\t\t\t\t\t bits == 32 ? tnum_subreg(implied.var_off) : implied.var_off))\n19559:\t\t\t\tcontinue;\n19560:\t\t\tsaved = *reg;\n19561:\t\t\t/*\n19562:\t\t\t * Equal in 64 bits is equal in the low 32 bits too. 'if w1 s\u003e 200' on a zero\n19563:\t\t\t * extended int refines nothing but the 32-bit range.\n19564:\t\t\t */\n19565:\t\t\tregs_refine_cond_op(reg, \u0026implied, BPF_JEQ, true);\n19566:\t\t\tif (bits == 64)\n19567:\t\t\t\tregs_refine_cond_op(reg, \u0026implied, BPF_JEQ, false);\n19568:\t\t\treg_bounds_sync(reg);\n19569:\t\t\tif (reg_is_empty(reg) || const_tnum_range_mismatch(reg) ||\n"
} |
| 69/3 | 2026/11/14 14:45 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 141158 output: 38 thoughts: 21 Thoughts: Okay, here's the summary, framed as your own internal thought process, designed for an expert audience: **Focused Review of Specific Lines** Alright, let's zero in. I'm going to take a closer look at lines 19570 through 19610. I need to refresh my memory, and make sure that this section contains information relevant to the current query I am working through. Given my existing understanding, I anticipate this range will be key to understanding the nuance I am hoping to unearth. Time to dive in and confirm my hypothesis. |
| 70/3 | 2026/11/14 14:45 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 19570,
"LineCount": 40
}Results: {
"Contents": "19570:\t\t\t const_tnum_range_mismatch_32(reg)) {\n19571:\t\t\t\t*reg = saved;\n19572:\t\t\t\tcontinue;\n19573:\t\t\t}\n19574:\tscratch:\n19575:\t\t\tif (linked_regno \u003c MAX_BPF_REG)\n19576:\t\t\t\tmark_reg_scratched(env, linked_regno);\n19577:\t\t\telse if (linked_frame == frame)\n19578:\t\t\t\tmark_stack_slot_scratched(env, linked_regno - MAX_BPF_REG);\n19579:\t\t}\n19580:\t}\n19581:\t\n19582:\t/* It's known which way the jump at env-\u003einsn_idx goes */\n19583:\tstatic void mark_loop_exit_decided(struct bpf_verifier_env *env, struct bpf_verifier_state *st)\n19584:\t{\n19585:\t\tstruct bpf_func_state *frame = st-\u003eframe[st-\u003ecurframe];\n19586:\t\tbool flag = bpf_flow_flag_regs(env, env-\u003einsn_idx);\n19587:\t\tstruct loop_stack_entry *entry;\n19588:\t\tu32 i;\n19589:\t\n19590:\t\tfor (i = 0; i \u003c frame-\u003eloop_stack_cnt; i++) {\n19591:\t\t\tentry = \u0026frame-\u003eloop_stack[i];\n19592:\t\t\t/* only because the states are kept apart. That holds for the first such jump. */\n19593:\t\t\tif (entry-\u003eflag_apart \u0026\u0026 flag)\n19594:\t\t\t\tentry-\u003eflag_apart = false;\n19595:\t\t\telse if (entry-\u003eapart \u0026\u0026 entry-\u003eprobe \u0026\u0026\n19596:\t\t\t\t bpf_jump_leaves_loop(env, entry-\u003eloop_id, env-\u003einsn_idx))\n19597:\t\t\t\tentry-\u003edecided = true;\n19598:\t\t}\n19599:\t}\n19600:\t\n19601:\tstatic int check_cond_jmp_op(struct bpf_verifier_env *env,\n19602:\t\t\t\t struct bpf_insn *insn, int *insn_idx)\n19603:\t{\n19604:\t\tstruct bpf_verifier_state *this_branch = env-\u003ecur_state;\n19605:\t\tstruct bpf_verifier_state *other_branch;\n19606:\t\tstruct bpf_reg_state *regs = this_branch-\u003eframe[this_branch-\u003ecurframe]-\u003eregs;\n19607:\t\tstruct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;\n19608:\t\tstruct bpf_reg_state *eq_branch_regs;\n19609:\t\tu8 opcode = BPF_OP(insn-\u003ecode);\n"
} |
| 71/3 | 2026/11/14 14:45 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 142126 output: 354 thoughts: 7846 Thoughts: **Analysis of BPF Verifier Patch and KMSAN Justification**
Okay, so I've been digging into this BPF verifier patch. My initial focus was on potential information leaks or uninitialized memory reads, especially since we're modifying the verifier. I started by looking at how the `refine_linked_regs` and `recompute_ptr` functions work, noticing those copies of `bpf_reg_state` structs. The key thing there is that `frame->regs` is already initialized, and these copies ensure we're working with known states.
Then I dived into `scev.c`, the heart of the Scalar Evolution analysis. I went through the `struct expr`, `struct expr_def`, and `struct env` definitions carefully. Seeing those structures allocated with `kzalloc` (zeroing) immediately made me feel better. I checked the `join` function, because that's a spot where state merging can go wrong, but `memcpy(acc, cur, sizeof(*acc));` safely copies all of `struct env`. The comparisons like `reg_value_equal`, which use `memcmp`, gave me pause, especially with that "unused" field, but the existing structure layout and initialization practices make that safe and fully initialized.
Now, I scrutinized the code for places where data might be sent to userspace – verifier logs, system calls, anything that copies kernel data to userland. I examined all the call paths. The verifier log just prints formatted strings based on register states, which are internal and not directly passed to user space. It has no uninitialized data.
Then, I looked for conditional logic that depends on uninitialized variables or struct fields within the modified functions like `bpf_half_slot_live_before`, `grow_exprs`, `mk_phi`, and others in `scev.c`. I confirmed that all local variables, structure members, and other data structures are either initialized during allocation or explicitly before their use. The bitmaps were initialized with `{}`. The out parameters in `bpf_scev_next_linked_reg` were all initialized.
Next, I considered possible bug scenarios given the changes this patch introduces – primarily the SCEV-based register analysis, bounds tracking, and loop analysis. The most likely bugs there are related to incorrect bounds propagation, potentially causing the verifier to misjudge a program's safety. However, this primarily results in either verifier bypass (leading to a KASAN-detectable out-of-bounds access) or incorrect program rejection, which can be detected by tests. KMSAN catches *uninitialized* memory reads, so the question is whether the changes introduce any of those risks.
I checked `check_stack_read_fixed_off` and `check_stack_write_fixed_off`, and confirmed that this patch did *not* change the critical logic regarding initialized memory reads/writes from stack slots and registers. I reviewed the rules about when to set `NeedsKMSAN`. No kernel structures are sent to user space. Local variables and struct fields are correctly initialized. There are no allocations of complex data structures where uninitialized fields could be read, and no changes to memory management, padding, or data transfer that might introduce uninitialized reads. KASAN catches the majority of the risk, so KMSAN is not justified.
I'm confident we've got a sound argument. `NeedsKMSAN = false`. We can call `set-results` with that, and move on.
|
| 72/3 | 2026/11/14 14:46 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series updates the BPF verifier to replace dynamic scalar register ID tracking with static Scalar Evolution (SCEV) analysis for linked registers, improving induction variable handling, 32-bit sign extension bounds tracking, and state equivalence comparisons.\n\nKMSAN vs KASAN Applicability Analysis:\n1. No uninitialized memory exposure to user space: The changes do not introduce or modify any kernel data structures copied to user space (no copy_to_user, put_user, netlink skb attributes, or BPF ringbuf/array copy-outs).\n2. Proper initialization: All heap and stack structures added or modified in the patch (such as `struct scev`, `struct env`, `struct scev_linked_reg`, and resized arrays in `grow_exprs`) use `kzalloc`, `__GFP_ZERO`, or explicit full-field initialization before reading. The replacement of `s32 delta` with `u32 unused` in `struct bpf_reg_state` preserves the existing struct layout and padding without introducing uninitialized holes.\n3. Bug profiles: Any bugs introduced by this patch would manifest as incorrect register range / bounds inferences, loop latch count mismatches, or state pruning errors in the verifier. Such bugs can lead to out-of-bounds memory accesses or invalid pointer dereferences at BPF runtime, which are already detected by KASAN and standard kernel debuggers.\n\nBecause there are no uninitialized memory read risks or information leaks uniquely targetable by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series updates the BPF verifier to replace dynamic scalar register ID tracking with static Scalar Evolution (SCEV) analysis for linked registers, improving induction variable handling, 32-bit sign extension bounds tracking, and state equivalence comparisons.\n\nKMSAN vs KASAN Applicability Analysis:\n1. No uninitialized memory exposure to user space: The changes do not introduce or modify any kernel data structures copied to user space (no copy_to_user, put_user, netlink skb attributes, or BPF ringbuf/array copy-outs).\n2. Proper initialization: All heap and stack structures added or modified in the patch (such as `struct scev`, `struct env`, `struct scev_linked_reg`, and resized arrays in `grow_exprs`) use `kzalloc`, `__GFP_ZERO`, or explicit full-field initialization before reading. The replacement of `s32 delta` with `u32 unused` in `struct bpf_reg_state` preserves the existing struct layout and padding without introducing uninitialized holes.\n3. Bug profiles: Any bugs introduced by this patch would manifest as incorrect register range / bounds inferences, loop latch count mismatches, or state pruning errors in the verifier. Such bugs can lead to out-of-bounds memory accesses or invalid pointer dereferences at BPF runtime, which are already detected by KASAN and standard kernel debuggers.\n\nBecause there are no uninitialized memory read risks or information leaks uniquely targetable by KMSAN, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|