]> git.ipfire.org Git - thirdparty/kernel/linux.git/commit
riscv: lib: Fix ZBB strnlen reading past count boundary
authorMichael Neuling <mikey@neuling.org>
Mon, 13 Apr 2026 01:07:38 +0000 (01:07 +0000)
committerPaul Walmsley <pjw@kernel.org>
Sat, 8 Aug 2026 17:45:33 +0000 (11:45 -0600)
commit5d588c684833e678a0008eb69c33190f01a65f4b
tree2aa29683c6352d42bc5de3f64390a054318624b5
parent994dad686e755477e2b2700cca4e6e1a90a58bdc
riscv: lib: Fix ZBB strnlen reading past count boundary

The ZBB-optimized strnlen loop loads one word ahead before checking the
aligned boundary:

    REG_L   t1, SZREG(t0)       // load next word
    addi    t0, t0, SZREG       // advance
    orc.b   t1, t1
    bgeu    t0, t4, 4f          // boundary check AFTER load

where t4 = (s + count) & -SZREG.  When s is aligned and count is a
multiple of SZREG, t4 equals s + count and the loop loads a full word
starting at exactly s + count.  If s + count falls on a page boundary
with the next page unmapped, this faults.

Fix by computing the aligned boundary from the last valid byte
(s + count - 1) instead of s + count.  This makes the loop stop at the
word containing the last valid byte rather than potentially loading the
word after it.  The count == 0 case is already handled by the beqz
early exit.

Also add a pre-loop guard (bgeu t0, t4) for the case where all valid
bytes fit within the first word.  With the adjusted boundary, t4 can
equal t0, and entering the loop with stale register state from the
first-word processing would produce incorrect results.

The final minu clamp ensures the result is still correct when the last
loaded word extends past s + count - 1 within the same aligned word.

Fixes: 5ba15d419fab ("riscv: lib: add strnlen() implementation")
Signed-off-by: Michael Neuling <mikey@neuling.org>
Assisted-by: Claude Opus4.6 High Thinking
Link: https://patch.msgid.link/20260413010738.1622423-1-mikey@neuling.org
Signed-off-by: Paul Walmsley <pjw@kernel.org>
arch/riscv/lib/strnlen.S