Skip to content

Commit 34d232c

Browse files
ratat-8ch
authored andcommitted
tools/nolibc: Fix strlcat() return code and size usage
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>
1 parent 689230b commit 34d232c

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

tools/include/nolibc/string.h

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -187,22 +187,31 @@ char *strndup(const char *str, size_t maxlen)
187187
static __attribute__((unused))
188188
size_t strlcat(char *dst, const char *src, size_t size)
189189
{
190-
size_t len;
191-
char c;
190+
size_t len = 0;
192191

193-
for (len = 0; dst[len]; len++)
194-
;
192+
for (; len < size; len++) {
193+
if (dst[len] == '\0')
194+
break;
195+
}
195196

196-
for (;;) {
197-
c = *src;
198-
if (len < size)
199-
dst[len] = c;
200-
if (!c)
197+
/*
198+
* We want len < size-1. But as size is unsigned and can wrap
199+
* around, we use len + 1 instead.
200+
*/
201+
while (len + 1 < size) {
202+
dst[len] = *src;
203+
if (*src == '\0')
201204
break;
202205
len++;
203206
src++;
204207
}
205208

209+
if (len < size)
210+
dst[len] = '\0';
211+
212+
while (*src++)
213+
len++;
214+
206215
return len;
207216
}
208217

0 commit comments

Comments
 (0)