From c8db92b7b716a97de7c36e907e170f62cd562d1b Mon Sep 17 00:00:00 2001 From: Florian Fischer Date: Wed, 21 Feb 2024 16:24:34 +0100 Subject: [PATCH] fix str[n]len implementations The current implementations do not count the length of empty strings correctly. The following buffer content "\0foo\0" is considered a string with length 4, because the iteration pointer is incremented before it is dereferenced to check for a null char. Replace the broken strlen functions with the implementation of musl libc. --- libc/src/string.c | 9 ++++----- mentos/src/klib/string.c | 9 ++++----- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/libc/src/string.c b/libc/src/string.c index 338ad17c..14cc4209 100644 --- a/libc/src/string.c +++ b/libc/src/string.c @@ -489,15 +489,14 @@ char *strcpy(char *dst, const char *src) size_t strlen(const char *s) { const char *it = s; - while (*(++it) != 0) {} - return ((it - s) < 0) ? 0 : (size_t)(it - s); + for (; *it; it++); + return (size_t)(it - s); } size_t strnlen(const char *s, size_t count) { - const char *it = s; - while ((*(++it) != 0) && --count) {} - return ((it - s) < 0) ? 0 : (size_t)(it - s); + const char *p = memchr(s, 0, count); + return p ? (size_t)(p-s) : count; } int strcmp(const char *s1, const char *s2) diff --git a/mentos/src/klib/string.c b/mentos/src/klib/string.c index 9f035312..7579da94 100644 --- a/mentos/src/klib/string.c +++ b/mentos/src/klib/string.c @@ -488,15 +488,14 @@ char *strcpy(char *dst, const char *src) size_t strlen(const char *s) { const char *it = s; - while (*(++it) != 0) {} - return ((it - s) < 0) ? 0 : (size_t)(it - s); + for(; *it; it++); + return (size_t)(it - s); } size_t strnlen(const char *s, size_t count) { - const char *it = s; - while ((*(++it) != 0) && --count) {} - return ((it - s) < 0) ? 0 : (size_t)(it - s); + const char *p = memchr(s, 0, count); + return p ? (size_t)(p-s) : count; } int strcmp(const char *s1, const char *s2)