LibJS: Fix UB in Number.IsSafeInteger

Casting a floating point number to an integer and comparing that against
the original value is not a good way to test if it is a whole number. It
may cause unnecessary narrowing conversion issues and UB. This was the
case, which was caught be Clang's `-fsanitize=float-cast-overflow`.

This commit changes the code to use `is_integral_number`, as suggested
in ECMA-262.
This commit is contained in:
Daniel Bertalan 2021-08-06 18:35:33 +02:00 committed by Andreas Kling
parent fd76e71934
commit 0a05f04d1b
Notes: sideshowbarker 2024-07-18 07:15:30 +09:00

View file

@ -129,8 +129,10 @@ JS_DEFINE_NATIVE_FUNCTION(NumberConstructor::is_safe_integer)
{
if (!vm.argument(0).is_number())
return Value(false);
if (!vm.argument(0).is_integral_number())
return Value(false);
auto value = vm.argument(0).as_double();
return Value((int64_t)value == value && value >= MIN_SAFE_INTEGER_VALUE && value <= MAX_SAFE_INTEGER_VALUE);
return Value(value >= MIN_SAFE_INTEGER_VALUE && value <= MAX_SAFE_INTEGER_VALUE);
}
}