1 #define _BSD_SOURCE
2 #include <string.h>
3 #include <stdint.h>
4 #include <limits.h>
5
6 #define ALIGN (sizeof(size_t)-1)
7 #define ONES ((size_t)-1/UCHAR_MAX)
8 #define HIGHS (ONES * (UCHAR_MAX/2+1))
9 #define HASZERO(x) ((x)-ONES & ~(x) & HIGHS)
10
11 #ifdef ENABLE_HWASAN
12 __attribute__((no_sanitize("hwaddress")))
13 #endif
strlcpy(char * d,const char * s,size_t n)14 size_t strlcpy(char *d, const char *s, size_t n)
15 {
16 char *d0 = d;
17 size_t *wd;
18
19 if (!n--) goto finish;
20 #ifdef __GNUC__
21 typedef size_t __attribute__((__may_alias__)) word;
22 const word *ws;
23 if (((uintptr_t)s & ALIGN) == ((uintptr_t)d & ALIGN)) {
24 for (; ((uintptr_t)s & ALIGN) && n && (*d=*s); n--, s++, d++);
25 if (n && *s) {
26 wd=(void *)d; ws=(const void *)s;
27 for (; n>=sizeof(size_t) && !HASZERO(*ws);
28 n-=sizeof(size_t), ws++, wd++) *wd = *ws;
29 d=(void *)wd; s=(const void *)ws;
30 }
31 }
32 #endif
33 for (; n && (*d=*s); n--, s++, d++);
34 *d = 0;
35 finish:
36 return d-d0 + strlen(s);
37 }
38