Skip to content

Commit 25f7408

Browse files
MaskRayMarkus Armbruster
authored and
Markus Armbruster
committed
util/cutils: Fix incorrect integer->float conversion caught by clang
Clang does not like do_strtosz()'s code to guard against overflow: qemu/util/cutils.c:245:23: error: implicit conversion from 'unsigned long' to 'double' changes value from 18446744073709550592 to 18446744073709551616 [-Werror,-Wimplicit-int-float-conversion] The warning will be enabled by default in clang 10. It is not available for clang <= 9. val * mul >= 0xfffffffffffffc00 is indeed wrong. 0xfffffffffffffc00 is not representable exactly as double. It's half-way between the representable values 0xfffffffffffff800 and 0x10000000000000000. Which one we get is implementation-defined. Bad. We want val * mul > (the largest uint64_t exactly representable as double). That's 0xfffffffffffff800. Write it as nextafter(0x1p64, 0) with a suitable comment. Signed-off-by: Fangrui Song <[email protected]> Reviewed-by: Markus Armbruster <[email protected]> [Patch split, commit message improved] Signed-off-by: Markus Armbruster <[email protected]> Message-Id: <[email protected]> Reviewed-by: Richard Henderson <[email protected]> Reviewed-by: Juan Quintela <[email protected]>
1 parent 2061735 commit 25f7408

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

util/cutils.c

+5-3
Original file line numberDiff line numberDiff line change
@@ -239,10 +239,12 @@ static int do_strtosz(const char *nptr, const char **end,
239239
goto out;
240240
}
241241
/*
242-
* Values >= 0xfffffffffffffc00 overflow uint64_t after their trip
243-
* through double (53 bits of precision).
242+
* Values near UINT64_MAX overflow to 2**64 when converting to double
243+
* precision. Compare against the maximum representable double precision
244+
* value below 2**64, computed as "the next value after 2**64 (0x1p64) in
245+
* the direction of 0".
244246
*/
245-
if ((val * mul >= 0xfffffffffffffc00) || val < 0) {
247+
if ((val * mul > nextafter(0x1p64, 0)) || val < 0) {
246248
retval = -ERANGE;
247249
goto out;
248250
}

0 commit comments

Comments
 (0)