[PATCH v3] riscv: fix strnlen() overflow in Zbb implementation

Paul Walmsley pjw at kernel.org
Mon Oct 5 10:17:46 PDT 2026


Hi Gao Rui,

On Wed, 30 Sep 2026, gao.rui at zte.com.cn wrote:

> riscv: fix strnlen() overflow in Zbb implementation
> 
> The RISC-V Zbb optimized strnlen() implementation can return incorrect
> results when very large count values are supplied.
> 
> The previous implementation calculates an end address based on the
> input pointer and count. When count is close to SIZE_MAX, the address
> calculation may overflow, resulting in incorrect termination checks and
> wrong return values.
> 
> This issue was observed while running device-mapper tests:
> 
> dmsetup create testname9 --table "0 8 zero"
> cat /sys/block/dm-*/dm/name
> dmsetup remove testname9
> 
> Rework the Zbb implementation to use a word counter instead of an end
> address. This removes the dependency on end-address calculations,
> avoids overflow entirely, and simplifies the termination condition of
> the word scanning loop. The final length is calculated using the saved
> original pointer.
> 
> Performance was evaluated with string_bench_strnlen:
> 
> New Implementation Previous Implementation
> 
> len=0 : 71 ns/call 70 ns/call
> len=1 : 82 ns/call 81 ns/call
> len=7 : 83 ns/call 81 ns/call
> len=8 : 83 ns/call 81 ns/call
> len=16 : 94 ns/call 90 ns/call
> len=31 : 117 ns/call 113 ns/call
> len=64 : 175 ns/call 167 ns/call
> len=127 : 259 ns/call 258 ns/call
> len=512 : 802 ns/call 833 ns/call
> len=1024 : 1512 ns/call 1536 ns/call
> len=3173 : 4581 ns/call 4640 ns/call
> len=4096 : 6256 ns/call 6068 ns/call
> 
> Results show comparable performance to the previous implementation
> while fixing the overflow issue.
> 
> Fixes: 5ba15d419fab ("riscv: lib: add strnlen() implementation")
> Suggested-by: DavidLaight <david.laight.linux at gmail.com>
> Signed-off-by: Gao Rui <gao.rui at zte.com.cn>

Thanks for your patch.  I took Shao Mingyin's patch for this instead, 
although I would have preferred that he work with you to clean up your 
patch instead, for the reasons described in

https://lore.kernel.org/linux-riscv/970c63ed-9fa8-9d1f-4521-0a7119b9d6e5@kernel.org/

If you think that Shao Mingyin's approach can be improved upon, please 
send a followup patch.


- Paul



More information about the linux-riscv mailing list