Files
open-amp/lib/utils/utilities.c
Arnaud Pouliquen 9aa3ee53c7 lib: utils: implement internal safe_strcpy function
The strlcpy() function has only recently become available in glibc.
While this function prevents destination buffer overflow, it seems
that it cannot guarantee read access only within the source buffer.
this is for instance the case if the source string is not terminated by
a'\0' character.
Implement a safe_strcpy to ensure that no access is done out of the
source and destination buffer ranges.

Signed-off-by: Arnaud Pouliquen <arnaud.pouliquen@foss.st.com>
2024-10-18 16:13:30 +02:00

36 lines
646 B
C

/*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2024, STMicroelectronics
*
*/
#include <internal/utilities.h>
#include <metal/io.h>
#include <metal/utilities.h>
size_t safe_strcpy(char *dst, size_t d_size, const char *src, size_t s_size)
{
size_t size = metal_min(s_size, d_size);
size_t nleft = size + 1;
char *d = dst;
if (!d_size)
return 0;
/* Copy as many bytes as will fit. */
while (--nleft != 0) {
*dst = *src++;
if (*dst++ == '\0')
break;
}
/* Fill last characters with '\0' */
if (size < d_size)
memset(dst, '\0', d_size - size + nleft);
else
d[d_size - 1] = '\0';
return size - nleft;
}