Skip to content

Commit 25e6767

Browse files
committed
Fix UB in gdtoa hexadecimal float scanf and strtod
When reading hexadecimal floats, cosmopolitan would previously sometimes print a number of warnings relating to undefined behavior on left shift: third_party/gdtoa/gethex.c:172: ubsan warning: signed left shift changed sign bit or overflowed 12 'int' 28 'int' is undefined behavior This is because gdtoa assumes left shifts are safe when overflow happens even on signed integers - this is false: the C standard considers it UB. This is easy to fix, by simply casting the shifted value to unsigned, as doing so does not change the value or the semantics of the left shifting (except for avoiding the undefined behavior, as the C standard specifies that unsigned overflow yields wraparound, avoiding undefined behaviour). This commit does this, and adds a testcase that previously triggered UB. (this also adds test macros to test for exact float equality, instead of the existing {EXPECT,ASSERT}_FLOAT_EQ macros which only tests inputs for being "almost equal" (with a significant epsilon) whereas exact equality makes more sense for certain things such as reading floats from strings, and modifies other testcases for sscanf/fscanf of floats to utilize it).
1 parent 462ba69 commit 25e6767

File tree

6 files changed

+88
-14
lines changed

6 files changed

+88
-14
lines changed

libc/testlib/BUILD.mk

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ LIBC_TESTLIB_A_SRCS_C = \
5050
libc/testlib/clearxmmregisters.c \
5151
libc/testlib/contains.c \
5252
libc/testlib/endswith.c \
53+
libc/testlib/exactlyequallongdouble.c \
5354
libc/testlib/extract.c \
5455
libc/testlib/ezbenchcontrol.c \
5556
libc/testlib/ezbenchreport.c \

libc/testlib/exactlyequallongdouble.c

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
2+
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
3+
╞══════════════════════════════════════════════════════════════════════════════╡
4+
│ Copyright 2024 Justine Alexandra Roberts Tunney │
5+
│ │
6+
│ Permission to use, copy, modify, and/or distribute this software for │
7+
│ any purpose with or without fee is hereby granted, provided that the │
8+
│ above copyright notice and this permission notice appear in all copies. │
9+
│ │
10+
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
11+
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
12+
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
13+
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
14+
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
15+
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
16+
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
17+
│ PERFORMANCE OF THIS SOFTWARE. │
18+
╚─────────────────────────────────────────────────────────────────────────────*/
19+
#include "libc/math.h"
20+
#include "libc/testlib/testlib.h"
21+
22+
bool testlib_exactlyequallongdouble(long double x, long double y) {
23+
if (isnan(x) && isnan(y))
24+
return true;
25+
// Check that we don't have e.g. one input denormal and the other not
26+
// (a denormal and a non-denormal can sometimes compare equal)
27+
if (fpclassify(x) != fpclassify(y))
28+
return false;
29+
// Check that we don't have -0 and 0
30+
if (signbit(x) != signbit(y))
31+
return false;
32+
if (x != y)
33+
return false;
34+
return true;
35+
}

libc/testlib/testlib.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,13 @@ void TearDownOnce(void);
195195
#define ASSERT_LDBL_LT(VAL, GOT) \
196196
assertLongDoubleLessThan(VAL, GOT, #VAL " < " #GOT, true)
197197

198+
#define ASSERT_FLOAT_EXACTLY_EQ(WANT, GOT) \
199+
assertLongDoubleExactlyEquals(FILIFU WANT, GOT, #GOT, true)
200+
#define ASSERT_DOUBLE_EXACTLY_EQ(WANT, GOT) \
201+
assertLongDoubleExactlyEquals(FILIFU WANT, GOT, #GOT, true)
202+
#define ASSERT_LDBL_EXACTLY_EQ(WANT, GOT) \
203+
assertLongDoubleExactlyEquals(FILIFU WANT, GOT, #GOT, true)
204+
198205
/*───────────────────────────────────────────────────────────────────────────│─╗
199206
│ cosmopolitan § testing library » assert or log ─╬─│┼
200207
╚────────────────────────────────────────────────────────────────────────────│*/
@@ -271,6 +278,13 @@ void TearDownOnce(void);
271278
#define EXPECT_LGBL_LT(VAL, GOT) \
272279
expectLongDoubleLessThan(VAL, GOT, #VAL " < " #GOT, false)
273280

281+
#define EXPECT_FLOAT_EXACTLY_EQ(WANT, GOT) \
282+
assertLongDoubleExactlyEquals(FILIFU WANT, GOT, #GOT, false)
283+
#define EXPECT_DOUBLE_EXACTLY_EQ(WANT, GOT) \
284+
assertLongDoubleExactlyEquals(FILIFU WANT, GOT, #GOT, false)
285+
#define EXPECT_LDBL_EXACTLY_EQ(WANT, GOT) \
286+
assertLongDoubleExactlyEquals(FILIFU WANT, GOT, #GOT, false)
287+
274288
/*───────────────────────────────────────────────────────────────────────────│─╗
275289
│ cosmopolitan § testing library » implementation details ─╬─│┼
276290
╚────────────────────────────────────────────────────────────────────────────│*/
@@ -404,6 +418,7 @@ void testlib_formatbinaryashex(const char *, const void *, size_t, char **,
404418
void testlib_formatbinaryasglyphs(const char16_t *, const void *, size_t,
405419
char **, char **);
406420
bool testlib_almostequallongdouble(long double, long double);
421+
bool testlib_exactlyequallongdouble(long double, long double);
407422
void testlib_incrementfailed(void);
408423
void testlib_clearxmmregisters(void);
409424

@@ -696,5 +711,20 @@ forceinline void assertLongDoubleEquals(FILIFU_ARGS long double want,
696711
testlib_onfail2(isfatal);
697712
}
698713

714+
forceinline void assertLongDoubleExactlyEquals(FILIFU_ARGS long double want,
715+
long double got,
716+
const char *gotcode,
717+
bool isfatal) {
718+
++g_testlib_ran;
719+
if (testlib_exactlyequallongdouble(want, got))
720+
return;
721+
if (g_testlib_shoulddebugbreak)
722+
DebugBreak();
723+
testlib_showerror(file, line, func, "assertLongDoubleExactlyEquals", "≠",
724+
gotcode, testlib_formatfloat(want),
725+
testlib_formatfloat(got));
726+
testlib_onfail2(isfatal);
727+
}
728+
699729
COSMOPOLITAN_C_END_
700730
#endif /* COSMOPOLITAN_LIBC_TESTLIB_H_ */

test/libc/stdio/fscanf_test.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ TEST(fscanf, test_readAfterFloat) {
2727
EXPECT_EQ(4, fscanf(f, "%f%x%f%x", &f1, &i1, &f2, &i2));
2828
EXPECT_TRUE(isinf(f1));
2929
EXPECT_EQ(0xDEAD, i1);
30-
EXPECT_EQ(-0.125e-2f, f2);
30+
EXPECT_FLOAT_EXACTLY_EQ(-0.125e-2f, f2);
3131
EXPECT_EQ(0xBEEF, i2);
3232
fclose(f);
3333
}

test/libc/stdio/sscanf_test.c

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -338,17 +338,17 @@ TEST(sscanf, flexdecimal_hex) {
338338
TEST(sscanf, floating_point_simple) {
339339
float x = 666.666f, y = x, z = y;
340340
EXPECT_EQ(3, sscanf("0.3715 .3715 3715", "%f %f %f", &x, &y, &z));
341-
EXPECT_EQ(0.3715f, x);
342-
EXPECT_EQ(0.3715f, y);
343-
EXPECT_EQ(3715.0f, z);
341+
EXPECT_FLOAT_EXACTLY_EQ(0.3715f, x);
342+
EXPECT_FLOAT_EXACTLY_EQ(0.3715f, y);
343+
EXPECT_FLOAT_EXACTLY_EQ(3715.0f, z);
344344
}
345345

346346
TEST(sscanf, floating_point_simple_double_precision) {
347347
double x = 666.666, y = x, z = y;
348348
EXPECT_EQ(3, sscanf("0.3715 .3715 3715", "%lf %lf %lf", &x, &y, &z));
349-
EXPECT_EQ(0.3715, x);
350-
EXPECT_EQ(0.3715, y);
351-
EXPECT_EQ(3715.0, z);
349+
EXPECT_DOUBLE_EXACTLY_EQ(0.3715, x);
350+
EXPECT_DOUBLE_EXACTLY_EQ(0.3715, y);
351+
EXPECT_DOUBLE_EXACTLY_EQ(3715.0, z);
352352
}
353353

354354
TEST(sscanf, floating_point_nan) {
@@ -426,12 +426,12 @@ TEST(sscanf, floating_point_documentation_examples) {
426426
2, sscanf("0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz -0.0000000123junk junk",
427427
"%f %f %f %f %f", &f, &g, &h, &i, &j));
428428

429-
EXPECT_EQ(111.11f, a);
430-
EXPECT_EQ(-2.22f, b);
429+
EXPECT_FLOAT_EXACTLY_EQ(111.11f, a);
430+
EXPECT_FLOAT_EXACTLY_EQ(-2.22f, b);
431431
EXPECT_TRUE(isnan(c));
432432
EXPECT_TRUE(isnan(d));
433433
EXPECT_TRUE(isinf(e));
434-
EXPECT_EQ(0X1.BC70A3D70A3D7P+6f, f);
434+
EXPECT_FLOAT_EXACTLY_EQ(0X1.BC70A3D70A3D7P+6f, f);
435435
EXPECT_TRUE(isinf(g));
436436
}
437437

@@ -445,12 +445,12 @@ TEST(sscanf, floating_point_documentation_examples_double_precision) {
445445
2, sscanf("0X1.BC70A3D70A3D7P+6 1.18973e+4932zzz -0.0000000123junk junk",
446446
"%lf %lf %lf %lf %lf", &f, &g, &h, &i, &j));
447447

448-
EXPECT_EQ(111.11, a);
449-
EXPECT_EQ(-2.22, b);
448+
EXPECT_DOUBLE_EXACTLY_EQ(111.11, a);
449+
EXPECT_DOUBLE_EXACTLY_EQ(-2.22, b);
450450
EXPECT_TRUE(isnan(c));
451451
EXPECT_TRUE(isnan(d));
452452
EXPECT_TRUE(isinf(e));
453-
EXPECT_EQ(0X1.BC70A3D70A3D7P+6, f);
453+
EXPECT_DOUBLE_EXACTLY_EQ(0X1.BC70A3D70A3D7P+6, f);
454454
EXPECT_TRUE(isinf(g));
455455
}
456456

@@ -506,3 +506,9 @@ TEST(scanf, n) {
506506
ASSERT_EQ(1848, port);
507507
ASSERT_EQ(12, len);
508508
}
509+
510+
TEST(sscanf, floating_point_hexadecimal) {
511+
double a = 0;
512+
ASSERT_EQ(1, sscanf("0x1.5014c3472bc2c0000000p-123", "%lf", &a));
513+
ASSERT_DOUBLE_EXACTLY_EQ(0x1.5014c3472bc2c0000000p-123, a);
514+
}

third_party/gdtoa/gethex.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,9 @@ __gdtoa_gethex(const char **sp, const FPI *fpi,
169169
L = 0;
170170
n = 0;
171171
}
172-
L |= (__gdtoa_hexdig[*s1] & 0x0f) << n;
172+
// We can shift in a way that changes the sign bit or overflows,
173+
// so we need to cast to unsigned to avoid undefined behavior
174+
L |= (unsigned)(__gdtoa_hexdig[*s1] & 0x0f) << n;
173175
n += 4;
174176
}
175177
*x++ = L;

0 commit comments

Comments
 (0)