[PATCH 2/4] tools/nolibc: Fix strlcat() return code and size usage

From: Rodrigo Campos
Date: Mon Jan 29 2024 - 09:15:55 EST


The return code should always be strlen(src) + strlen(dst), but dst is
considered shorter if size is less than strlen(dst).

While we are there, make sure to copy at most size-1 bytes and
null-terminate the dst buffer.

Signed-off-by: Rodrigo Campos <rodrigo@xxxxxxxxxxx>
---
tools/include/nolibc/string.h | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/tools/include/nolibc/string.h b/tools/include/nolibc/string.h
index ed15c22b1b2a..b2149e1342a8 100644
--- a/tools/include/nolibc/string.h
+++ b/tools/include/nolibc/string.h
@@ -187,23 +187,23 @@ 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 = strlen(dst);
+ size_t ret = strlen(src) + (size < len? size: len);

- for (len = 0; dst[len]; len++)
- ;
-
- for (;;) {
+ for (;len < size;) {
c = *src;
- if (len < size)
+ if (len < size - 1)
dst[len] = c;
+ if (len == size - 1)
+ dst[len] = '\0';
if (!c)
break;
len++;
src++;
}

- return len;
+ return ret;
}

static __attribute__((unused))
--
2.43.0