qemu_strnlen() uses a byte-at-a-time loop with an XXX TODO
comment noting that the host strnlen() could be used instead.
strnlen() is POSIX.1-2008 and is available on all platforms QEMU
supports (guaranteed by qemu/osdep.h). The host C library
implementation typically uses word-at-a-time or SIMD scanning,
which is significantly faster for long strings.
Replace the loop with a direct call to strnlen(). Add an explicit
cast from size_t to int since qemu_strnlen() returns int while
strnlen() returns size_t; the cast is safe because max_len (the
upper bound on the return value) is already int.
Signed-off-by: Bin Guo <guobin@linux.alibaba.com>
---
util/cutils.c | 10 +---------
1 file changed, 1 insertion(+), 9 deletions(-)
diff --git a/util/cutils.c b/util/cutils.c
index 76a9442085..9869d8842d 100644
--- a/util/cutils.c
+++ b/util/cutils.c
@@ -118,17 +118,9 @@ int stristart(const char *str, const char *val, const char **ptr)
return 1;
}
-/* XXX: use host strnlen if available ? */
int qemu_strnlen(const char *s, int max_len)
{
- int i;
-
- for(i = 0; i < max_len; i++) {
- if (s[i] == '\0') {
- break;
- }
- }
- return i;
+ return (int)strnlen(s, max_len);
}
char *qemu_strsep(char **input, const char *delim)
--
2.50.1 (Apple Git-155)
Hi, On 29/5/26 04:38, Bin Guo wrote: > qemu_strnlen() uses a byte-at-a-time loop with an XXX TODO > comment noting that the host strnlen() could be used instead. > > strnlen() is POSIX.1-2008 and is available on all platforms QEMU > supports (guaranteed by qemu/osdep.h). If so, there are only 3 uses in the code base. Maybe drop qemu_strnlen() altogether, using size_t in the callers? > The host C library > implementation typically uses word-at-a-time or SIMD scanning, > which is significantly faster for long strings. > > Replace the loop with a direct call to strnlen(). Add an explicit > cast from size_t to int since qemu_strnlen() returns int while > strnlen() returns size_t; the cast is safe because max_len (the > upper bound on the return value) is already int. > > Signed-off-by: Bin Guo <guobin@linux.alibaba.com> > --- > util/cutils.c | 10 +--------- > 1 file changed, 1 insertion(+), 9 deletions(-)
On Fri, 29 May 2026 08:02:41 +0200, Philippe Mathieu-Daude wrote: > there are only 3 uses in the code base. Maybe drop qemu_strnlen() > altogether, using size_t in the callers? Good suggestion. I've sent a v2 that drops qemu_strnlen() entirely and switches all callers to strnlen() directly. I also aligned bsd-user/uaccess.c to use size_t for max_len/len, matching linux-user/uaccess.c. New patch: https://lore.kernel.org/qemu-devel/20260529072803.99475-1-guobin@linux.alibaba.com/ Thanks, Bin Guo
© 2016 - 2026 Red Hat, Inc.