]> git.ipfire.org Git - thirdparty/kernel/linux.git/commitdiff
tools/nolibc: Fix strlcat() return code and size usage
authorRodrigo Campos <rodrigo@sdfg.com.ar>
Sun, 18 Feb 2024 19:51:04 +0000 (16:51 -0300)
committerThomas Weißschuh <linux@weissschuh.net>
Wed, 10 Apr 2024 21:19:01 +0000 (23:19 +0200)
The return code should always be strlen(src) + strnlen(dst, size).

Let's make sure to copy at most size-1 bytes from src and null-terminate
the dst buffer if we did copied something.

While we can use strnlen() and strncpy() to implement strlcat(), this is
simple enough and results in shorter code when compiled.

Signed-off-by: Rodrigo Campos <rodrigo@sdfg.com.ar>
Signed-off-by: Thomas Weißschuh <linux@weissschuh.net>
tools/include/nolibc/string.h

index ed15c22b1b2ae746fcd57b93201a4cd69a0b65e2..cc51fd6b63d02b19b324c9a589cba197f73b6a3b 100644 (file)
@@ -187,22 +187,31 @@ char *strndup(const char *str, size_t maxlen)
 static __attribute__((unused))
 size_t strlcat(char *dst, const char *src, size_t size)
 {
-       size_t len;
-       char c;
+       size_t len = 0;
 
-       for (len = 0; dst[len]; len++)
-               ;
+       for (; len < size; len++) {
+               if (dst[len] == '\0')
+                       break;
+       }
 
-       for (;;) {
-               c = *src;
-               if (len < size)
-                       dst[len] = c;
-               if (!c)
+       /*
+        * We want len < size-1. But as size is unsigned and can wrap
+        * around, we use len + 1 instead.
+        */
+       while (len + 1 < size) {
+               dst[len] = *src;
+               if (*src == '\0')
                        break;
                len++;
                src++;
        }
 
+       if (len < size)
+               dst[len] = '\0';
+
+       while (*src++)
+               len++;
+
        return len;
 }