tools: include: add proper strscpy() declaration
PATCH v2 2/2 tools: include: add proper strscpy() declaration
Currently, strscpy() is defined as a macro for strcpy() in the tools headers. This is unsafe and prevents using the real strscpy() logic that provides better buffer overflow protection.
Remove the macro hack and add a proper extern declaration for strscpy(). This allows tools to use the safer string copying API once the implementation is provided.
--- tools/include/linux/string.h | 5 ++++- tools/lib/string.c | 37 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-)
tools/include/linux/string.h +4 -1
@@ -12,7 +12,6 @@ void argv_free(char **argv);int strtobool (const char *s,bool *res); -#define strscpy strcpy/* * glibc based builds needs the extern while uClibc doesn't.
@@ -30,6 +29,10 @@ extern size_t strlcpy(char *dest, const char *src, size_t size);#endif #endif +extern ssize_t strscpy (char *dest,const char *src,size_t count); + +char *str_error_r (int errnum,char *buf,size_t buflen); +char *str_error_r (int errnum,char *buf,size_t buflen);char *strreplace (char *s,char old,char new);
tools/lib/string.c +37 -0
@@ -36,6 +36,43 @@ void *memdup(const void *src, size_t len)return p; } +/** +* strscpy - Copy a C-string into a sized buffer +* @dest: Where to copy the string to +* @src: Where to copy the string from +* @count: Size of destination buffer +* +* Copy the source string to the destination buffer. The result is +* always a valid NUL-terminated string that fits in the buffer. +* +* Return: +* * The number of characters copied (not including the trailing NUL) +* * -E2BIG if count is 0 or @src was truncated. +*/ +ssize_t strscpy (char *dest,const char *src,size_t count) +{ +size_t res =0 ; + +if (count ==0 ) +return -E2BIG ; + +while (count) { +char c = src[res]; + + dest[res] = c; +if (!c) +return res; + res++; + count--; + } + +/* Hit buffer length without finding a NUL; force NUL-termination. */ +if (res) + dest[res-1 ] ='\0' ; + +return -E2BIG ; +} +/** * strtobool - convert common user inputs into boolean values * @s: input string
Signature · 1 line
2.54.0
Quoted 9 lines · Lucas Poupeau
Currently,
strscpy()is defined as a macro forstrcpy()in the tools headers. This is unsafe and prevents using the realstrscpy()logic that provides better buffer overflow protection.Remove the macro hack and add a proper extern declaration for
strscpy(). This allows tools to use the safer string copying API once the implementation is provided.
Quoted 7 lines
Suggested-by Maxwell Doose <[email protected]>Signed-off-by Lucas Poupeau <[email protected]>--- tools/include/linux/string.h | 5 ++++- tools/lib/string.c | 37 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-)
[snip]
Didn't you already submit this? Doesn't look like anything changed if this is a v2.
best regards,
max