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

From: Rodrigo Campos
Date: Mon Jan 29 2024 - 09:16:22 EST


The return code should always be strlen(src), and we should copy at most
size-1 bytes.

While we are there, make sure to null-terminate the dst buffer.

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

diff --git a/tools/include/nolibc/string.h b/tools/include/nolibc/string.h
index b2149e1342a8..e4bc0302967d 100644
--- a/tools/include/nolibc/string.h
+++ b/tools/include/nolibc/string.h
@@ -212,15 +212,16 @@ size_t strlcpy(char *dst, const char *src, size_t size)
size_t len;
char c;

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

static __attribute__((unused))
--
2.43.0