diff --git a/libc/include/string.h b/libc/include/string.h index 9f2055e3..613c187d 100644 --- a/libc/include/string.h +++ b/libc/include/string.h @@ -32,12 +32,21 @@ extern "C" /* Compare two null-terminated strings. */ int strcmp(const char* a, const char* b); + /* Compare two fixed-size null-terminated strings. */ + int strncmp(const char* a, const char* b, size_t max); + /* Copy the null-terminated string src into dest. Should be avoided to prevent buffer overflow attacks. */ __deprecated char* strcpy(char* dest, const char* src); + /* Copy the fixed-size null-terminated string src into dest. */ + char* strncpy(char* dest, const char* src, size_t max); + /* Concatenate the null-terminated string src onto dest. Should be avoided to prevent buffer overflow attacks. */ __deprecated char* strcat(char* dest, const char* src); + /* Concatenate the fixed-size null-terminated string src onto dest. */ + char* strncat(char* dest, const char* src, size_t max); + /* Return a pointer to the first occurrence of the character c in str, or NULL if it could not be found. */ char* strchr(const char* str, int c); diff --git a/libluna/include/luna/CString.h b/libluna/include/luna/CString.h index d66ab557..d5a13b16 100644 --- a/libluna/include/luna/CString.h +++ b/libluna/include/luna/CString.h @@ -12,6 +12,7 @@ extern "C" usize strnlen(const char* str, usize max); int strcmp(const char* a, const char* b); + int strncmp(const char* a, const char* b, usize max); usize strspn(const char* str, const char* accept); usize strcspn(const char* str, const char* reject); @@ -28,6 +29,9 @@ extern "C" [[deprecated]] char* strcpy(char* dst, const char* src); [[deprecated]] char* strcat(char* dst, const char* src); + char* strncpy(char* dest, const char* src, size_t max); + char* strncat(char* dest, const char* src, size_t max); + char* strchr(const char* str, int c); char* strrchr(const char* str, int c); } diff --git a/libluna/src/CString.cpp b/libluna/src/CString.cpp index 397c911e..caf5d59a 100644 --- a/libluna/src/CString.cpp +++ b/libluna/src/CString.cpp @@ -64,6 +64,17 @@ extern "C" return *(const u8*)a - *(const u8*)b; } + int strncmp(const char* a, const char* b, usize max) + { + const char* s = a; + while (*a && (*a == *b) && (size_t)(a - s) < (max - 1)) + { + a++; + b++; + } + return *(const u8*)a - *(const u8*)b; + } + usize wcslen(const wchar_t* str) { const wchar_t* i = str; @@ -113,6 +124,26 @@ extern "C" return s; } + char* strncpy(char* dest, const char* src, size_t max) + { + size_t i; + for (i = 0; i < max && src[i] != 0; i++) dest[i] = src[i]; + for (; i < max; i++) dest[i] = 0; + return dest; + } + + char* strncat(char* dest, const char* src, size_t max) + { + size_t len = strlen(dest); + size_t i; + + for (i = 0; i < max && *(src + i); i++) *(dest + len + i) = *(src + i); + + *(dest + len + i) = '\0'; + + return dest; + } + char* strchr(const char* str, int c) { while (*str && *str != c) str++;