Skip to content

Commit f9916f4

Browse files
authored
Fix undefined behavior with negating values near INT_MAX/INT_MIN (#29043)
Fixes undefined behavior caused by negating values near INT_MAX/INT_MIN, the negation should be done as an unsigned number so no overflow can occur. Also made sure some variables got initialized properly [Reviewed by @arifthpe]
2 parents b11aa9a + b1fcc9f commit f9916f4

2 files changed

Lines changed: 5 additions & 5 deletions

File tree

runtime/src/chplcast.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,9 @@ static int illegalFirstUnsChar(char c) {
101101
*invalidCh = *str; \
102102
return -1; \
103103
} \
104-
val = (_type(base, width))strtoull(str, &endPtr, numberBase); \
104+
val = (_type(base, width))strtoull(str, &endPtr, numberBase); \
105105
if (negative) { \
106-
val = -1*val; \
106+
val = (_type(base, width))(-(unsigned long long)val); \
107107
} \
108108
while (*endPtr && isspace(*endPtr)) \
109109
endPtr++; \
@@ -314,7 +314,7 @@ _define_string_to_complex_precise(complex, 128, "%lf", 64)
314314
#define _define_string_to_int_type(base, width) \
315315
_type(base, width) c_string_to_##base##width##_t(c_string str, chpl_bool* err,\
316316
int lineno, int32_t filename) { \
317-
int invalid; \
317+
int invalid = 0; \
318318
char invalidStr[2] = "\0\0"; \
319319
_type(base, width) val = 0; \
320320
if (!str) { \
@@ -343,7 +343,7 @@ _define_string_to_int_type(uint, 64)
343343
#define _define_string_to_real_type(base, width) \
344344
_##base##width c_string_to_##base##width(c_string str, chpl_bool* err, \
345345
int lineno, int32_t filename) { \
346-
int invalid; \
346+
int invalid = 0; \
347347
char invalidStr[2] = "\0\0"; \
348348
_##base##width val = 0.0; \
349349
if (!str) { \

runtime/src/qio/qio_formatted.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3683,7 +3683,7 @@ qioerr qio_channel_print_int(const int threadsafe, qio_channel_t* restrict ch, c
36833683
if( issigned ) {
36843684
if (num_s < 0 ) {
36853685
isneg = 1;
3686-
num = - num_s;
3686+
num = - (uint64_t)num_s;
36873687
} else {
36883688
num = num_s;
36893689
}

0 commit comments

Comments
 (0)