diff --git a/libs/libc/include/string.h b/libs/libc/include/string.h index 22ebd481..0fe64c80 100644 --- a/libs/libc/include/string.h +++ b/libs/libc/include/string.h @@ -1,6 +1,7 @@ #ifndef _STRING_H #define _STRING_H +#include <_/macros.h> #include #ifdef __cplusplus @@ -10,12 +11,18 @@ extern "C" void* memcpy(void*, const void*, size_t); void* memset(void*, int, size_t); - size_t strlen(const char*); - char* strcpy(char*, const char*); - char* strchr(const char*, int); - char* strcat(char*, const char*); void* memclr(void*, size_t); + size_t strlen(const char*); + + deprecated("strcpy is unsafe and should not be used; use strncpy instead") char* strcpy(char*, const char*); + char* strncpy(char*, const char*, size_t); + + char* strchr(const char*, int); + + deprecated("strcat is unsafe and should not be used; use strncat instead") char* strcat(char*, const char*); + char* strncat(char*, const char*, size_t); + #ifdef __cplusplus } #endif diff --git a/libs/libc/src/printf.cpp b/libs/libc/src/printf.cpp index 437a07c7..771ba910 100644 --- a/libs/libc/src/printf.cpp +++ b/libs/libc/src/printf.cpp @@ -290,7 +290,7 @@ extern "C" return internal_printf( format, [&](const char* s) { - if (str) strcat(str, s); + if (str) strncat(str, s, 1025); }, -1, ap); } @@ -300,7 +300,7 @@ extern "C" return internal_printf( format, [&](const char* s) { - if (str) strcat(str, s); + if (str) strncat(str, s, 1025); }, max == 0 ? 0 : max - 1, ap); } diff --git a/libs/libc/src/string.cpp b/libs/libc/src/string.cpp index bf3e288b..15fcd42b 100644 --- a/libs/libc/src/string.cpp +++ b/libs/libc/src/string.cpp @@ -29,6 +29,13 @@ extern "C" return dest; } + char* strncpy(char* dest, const char* src, size_t n) + { + size_t src_len = strlen(src) + 1; // NULL byte + memcpy(dest, src, src_len > n ? n : src_len); + return dest; + } + char* strcat(char* dest, const char* src) { size_t dest_len = strlen(dest); @@ -41,6 +48,18 @@ extern "C" return dest; } + char* strncat(char* dest, const char* src, size_t n) + { + size_t dest_len = strlen(dest); + size_t i; + + for (i = 0; i < n && *(src + i); i++) *(char*)(dest + dest_len + i) = *(char*)(src + i); + + *(char*)(dest + dest_len + i) = '\0'; + + return dest; + } + char* strchr(const char*, int) { NOT_IMPLEMENTED("strchr");