From 4d0a82170a25464c39522d7190b9fe302045ddb2 Mon Sep 17 00:00:00 2001 From: Rich Felker Date: Wed, 26 Sep 2018 14:39:10 -0400 Subject: fix aliasing-based undefined behavior in string functions use the GNU C may_alias attribute if available, and fallback to naive byte-by-byte loops if __GNUC__ is not defined. this patch has been written to minimize changes so that history remains reviewable; it does not attempt to bring the affected code into a more consistent or elegant form. --- src/string/memchr.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src/string/memchr.c') diff --git a/src/string/memchr.c b/src/string/memchr.c index 4daff7bb..65f0d789 100644 --- a/src/string/memchr.c +++ b/src/string/memchr.c @@ -12,12 +12,16 @@ void *memchr(const void *src, int c, size_t n) { const unsigned char *s = src; c = (unsigned char)c; +#ifdef __GNUC__ for (; ((uintptr_t)s & ALIGN) && n && *s != c; s++, n--); if (n && *s != c) { - const size_t *w; + typedef size_t __attribute__((__may_alias__)) word; + const word *w; size_t k = ONES * c; for (w = (const void *)s; n>=SS && !HASZERO(*w^k); w++, n-=SS); - for (s = (const void *)w; n && *s != c; s++, n--); + s = (const void *)w; } +#endif + for (; n && *s != c; s++, n--); return n ? (void *)s : 0; } -- cgit v1.2.1