From: Vineet Gupta A fix of precision in the main pass. It stands alone in this series. Its tests come with the tests of sign extensions of linked registers. 1: w0 &= 63 2: w0 -= 63 3: w0 = (s8)w0 4: if w0 s< 0xffffffc1 goto pc+2 .. 7: w0 /= 0 div by zero w0 is in [-63, 0] before 3. Every value of that range fits in s8, so the sign extension is a no-op. The verifier drops the range all the same: after 3 w0 is in [-128, 127], is_branch_taken() cannot tell at 4, and 7 is verified though that branch is dead. coerce_subreg_to_size_sx() keeps a range if both bounds have the same bits above the low 8 or 16 bits. In a range that crosses 0 they differ: all ones in -63, all zeros in 0. The check before that one is on umax, which is huge when the range has a negative value. Return early if the 32-bit range fits in s8 or s16. A register that passed the check of umax has such a range, so that check goes. coerce_reg_to_size_sx() does the same in 64 bits since commit 0892ef2a7ef3 ("bpf: Representation for intervals with steps"). No verdict of the selftests changes. Fixes: 8100928c8814 ("bpf: Support new sign-extension mov insns") Signed-off-by: Vineet Gupta Signed-off-by: Alexei Starovoitov --- kernel/bpf/verifier.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 20b1b9ff574c..5bffc1e288f6 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -6441,14 +6441,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(). */ -- 2.55.0