vcos: Add vcos_safe_strncpy and VCOS_SAFE_STRNCPY

Add a src-length-limited version of VCOS_SAFE_STRCPY. For some
reason the vc4 linker complained about not being able to find strnlen,
hence the open-coded version.
This commit is contained in:
Phil Elwell
2022-02-01 15:36:12 +00:00
committed by Dom Cobley
parent 14b90ff9d9
commit 3ff42d6972
2 changed files with 42 additions and 0 deletions

View File

@@ -90,3 +90,34 @@ size_t vcos_safe_strcpy(char *dst, const char *src, size_t dstlen, size_t offset
return offset;
}
/** Copies at most srclen characters from string src to dst at the specified offset.
* Output is truncated to fit in dstlen bytes, i.e. the string is at most
* (buflen - 1) characters long. Unlike strncpy, exactly one NUL is written
* to dst, which is always NUL-terminated.
* Returns the string length before/without truncation.
*/
size_t vcos_safe_strncpy(char *dst, const char *src, size_t srclen, size_t dstlen, size_t offset)
{
if (offset < dstlen)
{
const char *p = src;
const char *srcend = src + srclen;
char *endp = dst + dstlen -1;
dst += offset;
for (; p != srcend && *p!='\0' && dst != endp; dst++, p++)
*dst = *p;
*dst = '\0';
}
// Open-code strnlen
while (*src && srclen)
{
offset++;
srclen--;
}
return offset;
}

View File

@@ -99,6 +99,17 @@ VCOSPRE_ size_t VCOSPOST_ vcos_safe_strcpy(char *dst, const char *src, size_t ds
#define VCOS_SAFE_STRCPY(dst, src, offset) \
vcos_safe_strcpy(dst, src, sizeof(dst) + ((char (*)[sizeof(dst)])dst - &(dst)), offset)
/** Copies at most srclen characters from string src to dst at the specified offset.
* Output is truncated to fit in dstlen bytes, i.e. the string is at most
* (buflen - 1) characters long. Unlike strncpy, exactly one NUL is written
* to dst, which is always NUL-terminated.
* Returns the string length before/without truncation.
*/
VCOSPRE_ size_t VCOSPOST_ vcos_safe_strncpy(char *dst, const char *src, size_t srclen, size_t dstlen, size_t offset);
#define VCOS_SAFE_STRNCPY(dst, src, srclen, offset) \
vcos_safe_strncpy(dst, src, srclen, sizeof(dst) + ((char (*)[sizeof(dst)])dst - &(dst)), offset)
VCOS_STATIC_INLINE
int vcos_strlen(const char *s) { return (int)strlen(s); }