1 #define _BSD_SOURCE
2 #include "libc.h"
3 #include <limits.h>
4 #include <stdint.h>
5 #include <string.h>
6
7 #define ALIGN (sizeof(size_t) - 1)
8 #define ONES ((size_t)-1 / UCHAR_MAX)
9 #define HIGHS (ONES * (UCHAR_MAX / 2 + 1))
10 #define HASZERO(x) (((x)-ONES) & ~(x)&HIGHS)
11
strlcpy(char * d,const char * s,size_t n)12 size_t strlcpy(char* d, const char* s, size_t n) {
13 char* d0 = d;
14
15 if (!n--)
16 goto finish;
17 #if !__has_feature(address_sanitizer)
18 // This reads past the end of the string, which is usually OK since
19 // it won't cross a page boundary. But under ASan, even one byte
20 // past the actual end is diagnosed.
21 if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
22 for (; ((uintptr_t)s & ALIGN) && n && (*d = *s); n--, s++, d++)
23 ;
24 if (n && *s) {
25 size_t* wd = (void*)d;
26 const size_t* ws = (const void*)s;
27 for (; n >= sizeof(size_t) && !HASZERO(*ws); n -= sizeof(size_t), ws++, wd++)
28 *wd = *ws;
29 d = (void*)wd;
30 s = (const void*)ws;
31 }
32 }
33 #endif
34 for (; n && (*d = *s); n--, s++, d++)
35 ;
36 *d = 0;
37 finish:
38 return d - d0 + strlen(s);
39 }
40