svn commit: r297633 - in head: sys/cddl/contrib/opensolaris/uts/common/fs/zfs sys/fs/ext2fs sys/kern sys/sys sys/ufs/ffs sys/ufs/ufs sys/vm usr.bin/rctl

Pieter de Goeje pieter at degoeje.nl
Fri Apr 8 07:57:59 UTC 2016


Op 2016-04-07 om 06:23 schreef Edward Tomasz Napierala:
> +static uint64_t
> +xmul(uint64_t a, uint64_t b)
> +{
> +	uint64_t c;
> +
> +	if (a == 0 || b == 0)
> +		return (0);
> +
> +	c = a * b;
> +
> +	if (c < a || c < b)
> +		return (UINT64_MAX);

If the intent is to check for overflow, then this check is insufficient. 
It fails for example if a = 2^32+1 and b = 2^32.

This works for all cases, assuming a != 0:

if(UINT64_MAX / a > b)
	return (UINT64_MAX);

If the extra division is too expensive, GCC and clang provide 
__builtin_mul_overflow().

--
Pieter de Goeje



More information about the svn-src-head mailing list