PatchworkOS  c9fea19
A non-POSIX operating system.
Loading...
Searching...
No Matches
memcpy_s.c
Go to the documentation of this file.
2#include <errno.h>
3#include <stdint.h>
4#include <stdlib.h>
5#include <string.h>
6
8
9errno_t memcpy_s(void* _RESTRICT s1, rsize_t s1max, const void* _RESTRICT s2, rsize_t n)
10{
11 uint8_t* d = (uint8_t*)s1;
12 const uint8_t* s = (const uint8_t*)s2;
13
14 if (s1 == NULL || s2 == NULL || s1max > RSIZE_MAX || n > RSIZE_MAX || n > s1max)
15 {
16 goto runtime_constraint_violation;
17 }
18
19 if ((d < s && d + n > s) || (s < d && s + n > d))
20 {
21 goto runtime_constraint_violation;
22 }
23
24 while (((uintptr_t)d & 7) && n)
25 {
26 *d++ = *s++;
27 n--;
28 }
29
30 while (n >= 64)
31 {
32 *(uint64_t*)(d + 0) = *(const uint64_t*)(s + 0);
33 *(uint64_t*)(d + 8) = *(const uint64_t*)(s + 8);
34 *(uint64_t*)(d + 16) = *(const uint64_t*)(s + 16);
35 *(uint64_t*)(d + 24) = *(const uint64_t*)(s + 24);
36 *(uint64_t*)(d + 32) = *(const uint64_t*)(s + 32);
37 *(uint64_t*)(d + 40) = *(const uint64_t*)(s + 40);
38 *(uint64_t*)(d + 48) = *(const uint64_t*)(s + 48);
39 *(uint64_t*)(d + 56) = *(const uint64_t*)(s + 56);
40 d += 64;
41 s += 64;
42 n -= 64;
43 }
44
45 while (n >= 8)
46 {
47 *(uint64_t*)d = *(const uint64_t*)s;
48 d += 8;
49 s += 8;
50 n -= 8;
51 }
52
53 while (n--)
54 {
55 *d++ = *s++;
56 }
57
58 return 0;
59
60runtime_constraint_violation:
61 if (s1 != NULL && s1max <= RSIZE_MAX)
62 {
63 memset(s1, 0, s1max);
64 }
65
67 return EINVAL;
68}
constraint_handler_t _constraintHandler
#define _CONSTRAINT_VIOLATION(e)
int errno_t
Definition errno_t.h:4
#define EINVAL
Invalid argument.
Definition errno.h:142
#define NULL
Pointer error value.
Definition NULL.h:23
#define _RESTRICT
Definition config.h:17
errno_t memcpy_s(void *_RESTRICT s1, rsize_t s1max, const void *_RESTRICT s2, rsize_t n)
Definition memcpy_s.c:9
__SIZE_TYPE__ rsize_t
Definition rsize_t.h:4
__UINT64_TYPE__ uint64_t
Definition stdint.h:17
__UINT8_TYPE__ uint8_t
Definition stdint.h:11
__UINTPTR_TYPE__ uintptr_t
Definition stdint.h:43
_PUBLIC void * memset(void *s, int c, size_t n)
Definition memset.c:4