libc: Add strncpy and strncat, and deprecate strcpy and strcat (which, since we're building with -Werror, is an instant ban from using these functions)

This commit is contained in:
apio 2022-10-04 19:08:59 +02:00
parent a050ed9133
commit 48b858af5a
3 changed files with 32 additions and 6 deletions

View File

@ -1,6 +1,7 @@
#ifndef _STRING_H
#define _STRING_H
#include <_/macros.h>
#include <stddef.h>
#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

View File

@ -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);
}

View File

@ -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");