blob: 6f8de2982df5d4287018cb3896c8559393a47e3f [file] [log] [blame]
Jit Loon Lim012a9d92025-03-17 16:25:53 +08001/*
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
12int 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}