[Tarantool-patches] [PATCH luajit 1/2] Fix tonumber("-0").

Sergey Kaplun skaplun at tarantool.org
Wed Jan 26 15:19:33 MSK 2022


From: Mike Pall <mike>

Reported by bluecheetah001.

(cherry picked from 45a7e5073ce0a59465fef0b80bb08bd4e76b7979)

Common case for scanning a string containing a number is a string with a
decimal number. For this case, a decimal number first casts to int32_t
and later to double (lua_Number) if necessary. Information about sign of
0 is lost during the cast to int32_t. So resulting TValue contains `0.`
instead of `-0.`.

This patch removes cast to int32_t for the case when resulting TValue
contains double value.

Sergey Kaplun:
* added the description and the test for the problem

Part of tarantool/tarantool#6548
---
 src/lj_strscan.c                              |  5 ++---
 .../lj-528-tonumber-0.test.lua                | 19 +++++++++++++++++++
 2 files changed, 21 insertions(+), 3 deletions(-)
 create mode 100644 test/tarantool-tests/lj-528-tonumber-0.test.lua

diff --git a/src/lj_strscan.c b/src/lj_strscan.c
index 08f41f19..4e4ef6d3 100644
--- a/src/lj_strscan.c
+++ b/src/lj_strscan.c
@@ -495,12 +495,11 @@ StrScanFmt lj_strscan_scan(const uint8_t *p, MSize len, TValue *o,
     /* Fast path for decimal 32 bit integers. */
     if (fmt == STRSCAN_INT && base == 10 &&
 	(dig < 10 || (dig == 10 && *sp <= '2' && x < 0x80000000u+neg))) {
-      int32_t y = neg ? -(int32_t)x : (int32_t)x;
       if ((opt & STRSCAN_OPT_TONUM)) {
-	o->n = (double)y;
+	o->n = neg ? -(double)x : (double)x;
 	return STRSCAN_NUM;
       } else {
-	o->i = y;
+	o->i = neg ? -(int32_t)x : (int32_t)x;
 	return STRSCAN_INT;
       }
     }
diff --git a/test/tarantool-tests/lj-528-tonumber-0.test.lua b/test/tarantool-tests/lj-528-tonumber-0.test.lua
new file mode 100644
index 00000000..03ba2aff
--- /dev/null
+++ b/test/tarantool-tests/lj-528-tonumber-0.test.lua
@@ -0,0 +1,19 @@
+local tap = require('tap')
+
+-- Test disabled for DUALNUM mode default for some arches.
+-- See also https://github.com/LuaJIT/LuaJIT/pull/787.
+require("utils").skipcond(
+  jit.arch ~= "x86" and jit.arch ~= "x64",
+  jit.arch.." in DUALNUM mode is clumsy for now"
+)
+
+-- Test file to demonstrate LuaJIT `tonumber('-0')` incorrect
+-- behaviour.
+-- See also https://github.com/LuaJIT/LuaJIT/issues/528.
+local test = tap.test('lj-528-tonumber-0')
+test:plan(1)
+
+-- As numbers `-0 == 0`, so convert it back to string.
+test:ok(tostring(tonumber('-0')) == '-0', 'correct "-0" string parsing')
+
+os.exit(test:check() and 0 or 1)
-- 
2.34.1



More information about the Tarantool-patches mailing list