From: Guest0x0 Date: Sat, 14 Sep 2024 06:09:26 +0000 (+0000) Subject: fix UB in constant folding of double -> signed integer conversion X-Git-Url: https://repo.or.cz/w/tinycc.git/commitdiff_plain/HEAD fix UB in constant folding of double -> signed integer conversion --- diff --git a/tccgen.c b/tccgen.c index 57bc493f..94315823 100644 --- a/tccgen.c +++ b/tccgen.c @@ -3249,7 +3249,10 @@ error: 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 new file mode 100644 index 00000000..a9f5e0ed --- /dev/null +++ b/tests/tests2/134_double_to_signed.c @@ -0,0 +1,10 @@ +#include +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 new file mode 100644 index 00000000..468a382d --- /dev/null +++ b/tests/tests2/134_double_to_signed.expect @@ -0,0 +1,4 @@ +-1 +-1 +-2147483648 +-2147483648