From: Alexei Starovoitov for (i = 0, n = first; ; i++, n -= 97) { n += 100; if (i == 2) break; use(n); } n is linear at the jump that counts: 'first + 100 + 3 * k'. Behind the jump bpf_clamp_scev_regs() gives it the range of one iteration less. When first is a constant it gets the step 3 and the residue '(first + 100) mod 3' too. When first + 100 goes over S64_MAX the signed value is 2^64 less. 2^64 is not a multiple of 3, so the residue is another one. reg_bounds_sync() rounds the range to numbers that n never is and drops the numbers that it is. What takes n as an index is checked for the wrong numbers. scalar_step_add() drops the step of a sum that can wrap. Set no range at all in this case. The register keeps what the state has. That went through scalar_step_add(), and it has the low bits of n, which bpf_set_reg_range() forgets. 'bounds.base + moved' can overflow s64 when n itself doesn't wrap. Add the residues, as scalar_step_add() does. Fixes: a00c8eafb381 ("bpf: A loop is one iteration shorter behind the jump that counts it") Signed-off-by: Alexei Starovoitov --- kernel/bpf/scev.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c index 5415fcf9df2f..6a9d16ab37f3 100644 --- a/kernel/bpf/scev.c +++ b/kernel/bpf/scev.c @@ -3992,7 +3992,7 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur struct env *header_env; struct bounds bounds; u32 r, r_scev; - s64 moved; + s64 moved, sum; int err; if (entry_state->curframe != cur_func_state->frameno) { @@ -4044,8 +4044,12 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur if (coefs.base_reg == entry->iv_reg && !moved) iv_bounds(&bounds, 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) || + check_add_overflow(cnum64_smax(bounds.r64), moved, &sum)) + continue; bounds.r64 = cnum64_add(bounds.r64, cnum64_from_srange(moved, moved)); - bounds.base = imod(bounds.base + moved, bounds.step); + bounds.base = (bounds.base + imod(moved, bounds.step)) % bounds.step; } if (behind) { /* jumps on the way may have told more */