From mboxrd@z Thu Jan 1 00:00:00 1970 From: Sean Anderson Date: Wed, 24 Mar 2021 20:53:43 -0400 Subject: [PATCH v2 1/5] lib: string: Fix strlcpy return value In-Reply-To: <20210311051545.1886333-2-seanga2@gmail.com> References: <20210311051545.1886333-1-seanga2@gmail.com> <20210311051545.1886333-2-seanga2@gmail.com> Message-ID: List-Id: MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit To: u-boot@lists.denx.de On 3/11/21 12:15 AM, Sean Anderson wrote: > strlcpy should always return the number of bytes copied. We were > accidentally missing the nul-terminator. We also always used to return a It looks like I was a bit bullish in assuming a mistake. After reviewing the man page, it looks like the nul-terminator is intentionally excluded. > The strlcpy() and strlcat() functions return the total length of the > string they tried to create. For strlcpy() that means the length of > src. For strlcat() that means the initial length of dst plus the > length of src. While this may seem somewhat confusing, it was done to > make truncation detection simple. In particular, we should return the length of the string, which may be different from the amount of bytes copied. However, the non-zero return value should be fixed. > 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 > --- > > Changes in v2: > - New > > lib/string.c | 12 ++++++++---- > 1 file changed, 8 insertions(+), 4 deletions(-) > > diff --git a/lib/string.c b/lib/string.c > index 73b984123d..1b867ac09d 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 > >