From 70164d957eb2d1147e0b52a4b1da45f64be8af8e Mon Sep 17 00:00:00 2001 From: Alfonso Date: Sat, 24 Jul 2021 12:52:31 -0400 Subject: [PATCH] Fix truncation when ssize_t is larger than MAX_INT Casting to int truncates size on some platforms, resulting swab not copying all the data. Cast len to size_t to avoid right shifting a signed value: we know here it's > 0, so we can safely cast it w/o losing precision. In addition, be more careful with signedness of char pointers and temporaries. Downgrade tmp from unsigned long to unsigned char since we're only reading and writing characters. Reviewed by: imp Pull Request: https://github.com/freebsd/freebsd-src/pull/516 --- lib/libc/string/swab.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/lib/libc/string/swab.c b/lib/libc/string/swab.c index 1a30ce81378..724ee48ea0c 100644 --- a/lib/libc/string/swab.c +++ b/lib/libc/string/swab.c @@ -43,15 +43,16 @@ __FBSDID("$FreeBSD$"); void swab(const void * __restrict from, void * __restrict to, ssize_t len) { - unsigned long temp; - int n; - char *fp, *tp; + unsigned char temp; + size_t n; + const unsigned char *fp; + unsigned char *tp; if (len <= 0) return; - n = len >> 1; - fp = (char *)from; - tp = (char *)to; + n = (size_t)len >> 1; + fp = (const unsigned char *)from; + tp = (unsigned char *)to; #define STEP temp = *fp++,*tp++ = *fp++,*tp++ = temp /* round to multiple of 8 */ for (; n & 0x7; --n)