Make more functions friendly to Address Sanitizer

This commit is contained in:
Justine Tunney 2021-02-02 03:45:31 -08:00
parent 3ab76b2312
commit cbfd4ccd1e
70 changed files with 1267 additions and 291 deletions

View file

@ -18,6 +18,12 @@
*/
#include "libc/str/str.h"
static inline noasan uint64_t UncheckedAlignedRead64(unsigned char *p) {
return (uint64_t)p[7] << 070 | (uint64_t)p[6] << 060 | (uint64_t)p[5] << 050 |
(uint64_t)p[4] << 040 | (uint64_t)p[3] << 030 | (uint64_t)p[2] << 020 |
(uint64_t)p[1] << 010 | (uint64_t)p[0] << 000;
}
/**
* Compares NUL-terminated strings.
*
@ -28,7 +34,25 @@
*/
int strcmp(const char *a, const char *b) {
size_t i = 0;
uint64_t v, w, d;
if (a == b) return 0;
while (a[i] == b[i] && b[i]) ++i;
return (a[i] & 0xff) - (b[i] & 0xff);
if (((uintptr_t)a & 7) == ((uintptr_t)b & 7)) {
for (; (uintptr_t)a & 7; ++i) {
if (a[i] != b[i] || !b[i]) {
return (a[i] & 0xff) - (b[i] & 0xff);
}
}
for (;; i += 8) {
v = UncheckedAlignedRead64(a + i);
w = UncheckedAlignedRead64(b + i);
w = (v ^ w) | (~v & (v - 0x0101010101010101) & 0x8080808080808080);
if (w) {
i += (unsigned)__builtin_ctzll(w) >> 3;
return (a[i] & 0xff) - (b[i] & 0xff);
}
}
} else {
while (a[i] == b[i] && b[i]) ++i;
return (a[i] & 0xff) - (b[i] & 0xff);
}
}