|
From: | name unknown |
Subject: | [Tinycc-devel] [fix] UB in constant folding of double -> signed integer conversion |
Date: | Sat, 14 Sep 2024 06:32:38 +0000 |
bug report:
https://savannah.nongnu.org/bugs/?66214
turn out a one-liner fix is adequate, so I added a patch:
https://repo.or.cz/tinycc.git/commitdiff/b8b6a5fd7b4e8cab8e5a5d01064cf5bf2b5eed95
diff --git
a/tccgen.c
b/tccgen.c
--- a/tccgen.c
+++ b/tccgen.c
vtop->c.i = (vtop->c.ld != 0);
} else {
if(sf)
- vtop->c.i = vtop->c.ld;
+ /* the range of [int64_t] is enough to hold the integer part of any float value.
+ Meanwhile, converting negative double to unsigned integer is UB.
+ So first convert to [int64_t] here. */
+ vtop->c.i = (int64_t)vtop->c.ld;
else if (sbt_bt == VT_LLONG || (PTR_SIZE == 8 && sbt == VT_PTR))
;
else if (sbt & VT_UNSIGNED)
diff --git a/tests/tests2/134_double_to_signed.c
b/tests/tests2/134_double_to_signed.c
--- /dev/null
@@ -0,0
+1,10 @@
+#include <stdio.h>
+int main() {
+ printf("%d\n", (int)-1.0);
+ double d = -1.0;
+ printf("%d\n", (int)d);
+
+ printf("%d\n", (int)-2147483648.0);
+ d = -2147483648.0;
+ printf("%d\n", (int)d);
+}
diff --git a/tests/tests2/134_double_to_signed.expect
b/tests/tests2/134_double_to_signed.expect
--- /dev/null
@@ -0,0
+1,4 @@
+-1
+-1
+-2147483648
+-2147483648
The UB happens to have correct behavior on x86, so the bug can only be reproduced on other platforms, for example arm64. I tested the fix on amd64 and arm64(M2).
|
[Prev in Thread] | Current Thread | [Next in Thread] |