Skip to contentSkip to conversation

util/cutils: replace hand-rolled qemu_strnlen() with strnlen()

PATCH In review Bin Guo 2 participants 3 messages May 29

lore
Share & tools
lore

Bin Guo

author
#0 lore raw

PATCH 1/1 util/cutils: replace hand-rolled qemu_strnlen() with strnlen()

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.

---
 util/cutils.c | 10 +---------
 1 file changed, 1 insertion(+), 9 deletions(-)
util/cutils.c +1 -9
index 76a9442085..9869d8842d 100644
@@ -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)
Signature · 1 line
2.50.1 (Apple Git-155)
#1 lore raw

Hi,

Quoted 5 lines · Bin Guo

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?

Quoted 13 lines

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.

---
  util/cutils.c | 10 +---------
  1 file changed, 1 insertion(+), 9 deletions(-)
author
#2 lore raw
Quoted 2 lines · Philippe Mathieu-Daude

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/[email protected]/

Thanks,
Bin Guo