Browse Source

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.
Daniel Bertalan 4 năm trước cách đây
mục cha
commit
0a05f04d1b
1 tập tin đã thay đổi với 3 bổ sung1 xóa
  1. 3 1
      Userland/Libraries/LibJS/Runtime/NumberConstructor.cpp

+ 3 - 1
Userland/Libraries/LibJS/Runtime/NumberConstructor.cpp

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