From d3358ecc54be0bc3b4dd11f7a63eab0a2842f772 Mon Sep 17 00:00:00 2001 From: Sean Anderson Date: Thu, 11 Mar 2021 00:15:41 -0500 Subject: lib: string: Fix strlcpy return value strlcpy should always return the number of bytes copied. We were accidentally missing the nul-terminator. We also always used to return a non-zero value, even if we did not actually copy anything. Fixes: 23cd138503 ("Integrate USB gadget layer and USB CDC driver layer") Signed-off-by: Sean Anderson --- lib/string.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'lib/string.c') diff --git a/lib/string.c b/lib/string.c index 73b984123dc..1b867ac09d0 100644 --- a/lib/string.c +++ b/lib/string.c @@ -114,17 +114,21 @@ char * strncpy(char * dest,const char *src,size_t count) * NUL-terminated string that fits in the buffer (unless, * of course, the buffer size is zero). It does not pad * out the result like strncpy() does. + * + * Return: the number of bytes copied */ size_t strlcpy(char *dest, const char *src, size_t size) { - size_t ret = strlen(src); - if (size) { - size_t len = (ret >= size) ? size - 1 : ret; + size_t srclen = strlen(src); + size_t len = (srclen >= size) ? size - 1 : srclen; + memcpy(dest, src, len); dest[len] = '\0'; + return len + 1; } - return ret; + + return 0; } #endif -- cgit v1.2.3 From 9af869c4145a668b6db9accdea554eb57895a25e Mon Sep 17 00:00:00 2001 From: Sean Anderson Date: Thu, 11 Mar 2021 00:15:42 -0500 Subject: lib: string: Implement strlcat This introduces strlcat, which provides a safer interface than strncat. It never copies more than its size bytes, including the terminating nul. In addition, it never reads past dest[size - 1], even if dest is not nul-terminated. This also removes the stub for dwc3 now that we have a proper implementation. Signed-off-by: Sean Anderson Reviewed-by: Simon Glass --- lib/string.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'lib/string.c') diff --git a/lib/string.c b/lib/string.c index 1b867ac09d0..a0cff8fe88e 100644 --- a/lib/string.c +++ b/lib/string.c @@ -180,6 +180,25 @@ char * strncat(char *dest, const char *src, size_t count) } #endif +#ifndef __HAVE_ARCH_STRLCAT +/** + * strlcat - Append a length-limited, %NUL-terminated string to another + * @dest: The string to be appended to + * @src: The string to append to it + * @size: The size of @dest + * + * Compatible with *BSD: the result is always a valid NUL-terminated string that + * fits in the buffer (unless, of course, the buffer size is zero). It does not + * write past @size like strncat() does. + */ +size_t strlcat(char *dest, const char *src, size_t size) +{ + size_t len = strnlen(dest, size); + + return len + strlcpy(dest + len, src, size - len); +} +#endif + #ifndef __HAVE_ARCH_STRCMP /** * strcmp - Compare two strings -- cgit v1.2.3