1 /* 2 * Copyright (c) 2024-2025, Altera Corporation. All rights reserved. 3 * 4 * SPDX-License-Identifier: BSD-3-Clause 5 */ 6 7 #include <errno.h> 8 #include <stddef.h> 9 #include <string.h> 10 #include <stdint.h> 11 12 int strcpy_secure(char *restrict dest, size_t dest_size, const char *restrict src) 13 { 14 /* Check for null pointers */ 15 if ((dest == NULL) || (src == NULL)) { 16 return -EINVAL; 17 } 18 19 /* Check the destination size valid range */ 20 if (dest_size == 0) { 21 return -ERANGE; 22 } 23 24 /* Calculate the length of the source string */ 25 size_t src_len = strnlen_secure(src, dest_size); 26 27 /* Check if the source string fits in the destination buffer */ 28 if (src_len >= dest_size) { 29 /* Set destination to an empty string */ 30 dest[0] = '\0'; 31 return -ERANGE; 32 } 33 34 /* Copy the source string to the destination */ 35 for (dest[src_len] = '\0'; src_len > 0; src_len--) { 36 dest[src_len - 1] = src[src_len - 1]; 37 } 38 39 return 0; 40 } 41