1 /*
2  * Copyright (c) 2013-2023, Arm Limited and Contributors. All rights reserved.
3  * Copyright (c) 2023, Intel Corporation. All rights reserved.
4  *
5  * SPDX-License-Identifier: BSD-3-Clause
6  */
7 
8 #include <errno.h>
9 #include <stddef.h>
10 #include <string.h>
11 
memcpy_s(void * dst,size_t dsize,void * src,size_t ssize)12 int memcpy_s(void *dst, size_t dsize, void *src, size_t ssize)
13 {
14 	unsigned int *s = (unsigned int *)src;
15 	unsigned int *d = (unsigned int *)dst;
16 
17 	/*
18 	 * Check source and destination size is NULL
19 	 */
20 	if ((dst == NULL) || (src == NULL)) {
21 		return -ENOMEM;
22 	}
23 
24 	/*
25 	 * Check source and destination size validity
26 	 */
27 	if ((dsize == 0) || (ssize == 0)) {
28 		return -ERANGE;
29 	}
30 
31 	/*
32 	 * Check both source and destination size range
33 	 */
34 	if ((ssize > dsize) || (dsize > ssize)) {
35 		return -EINVAL;
36 	}
37 
38 	/*
39 	 * Check both source and destination address overlapping
40 	 * When (s > d < s + ssize)
41 	 * Or (d > s < d + dsize)
42 	 */
43 
44 	if (d > s) {
45 		if ((d) < (s + ssize)) {
46 			return -EOPNOTSUPP;
47 		}
48 	}
49 
50 	if (s > d) {
51 		if ((s) < (d + dsize)) {
52 			return -EOPNOTSUPP;
53 		}
54 	}
55 
56 	/*
57 	 * Start copy process when there is no error
58 	 */
59 	while (ssize--) {
60 		d[ssize] = s[ssize];
61 	}
62 
63 	return 0;
64 }
65