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
This commit is contained in:
Alfonso 2021-07-24 12:52:31 -04:00 committed by Warner Losh
parent 0cec5b99b3
commit 70164d957e

View file

@ -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)