Skip to content

Commit

Permalink
Fix undefined behavior in test_int53 (#22895)
Browse files Browse the repository at this point in the history
The test uses numbers such as 0x8000000000000000ull but was converting
to int64_t and overflowing,
leading to UB and different behavior when using saturating conversions.
  • Loading branch information
dschuff authored Nov 11, 2024
1 parent e6ed9d3 commit 9e0121c
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions test/core/test_int53.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ void writeI53ToI64_int64(int64_t *heapAddress, int64_t num) {
#endif
}

void writeI53ToI64_uint64(uint64_t *heapAddress, uint64_t num) {
#ifdef GENERATE_ANSWERS
*heapAddress = num;
#else
EM_ASM(writeI53ToI64($0, $1), heapAddress, (double)num);
#endif
}

void writeI53ToI64_double(int64_t *heapAddress, double num) {
#ifdef GENERATE_ANSWERS
if (num > 0 || num <= -9223372036854775808.0 /* underflow, garbage in-garbage out situation: just produce a value that matches current JS impl*/)
Expand Down Expand Up @@ -119,6 +127,14 @@ int64_t readI53FromU64_toInt64(uint64_t *heapAddress) {
#endif
}

uint64_t readI53FromU64_toUInt64(uint64_t *heapAddress) {
#ifdef GENERATE_ANSWERS
return (uint64_t)*heapAddress;
#else
return (uint64_t)EM_ASM_DOUBLE(return readI53FromU64($0), heapAddress);
#endif
}

double readI53FromU64(uint64_t *heapAddress) {
#ifdef GENERATE_ANSWERS
return (double)*heapAddress;
Expand All @@ -137,13 +153,13 @@ int64_t convertI32PairToI53(int32_t lo, int32_t hi) {
#endif
}

int64_t convertU32PairToI53(uint32_t lo, uint32_t hi) {
uint64_t convertU32PairToI53(uint32_t lo, uint32_t hi) {
#ifdef GENERATE_ANSWERS
uint64_t val = (uint32_t)lo;
val |= ((uint64_t)(uint32_t)hi) << 32;
return val;
#else
return (int64_t)EM_ASM_DOUBLE(return convertU32PairToI53($0, $1), lo, hi);
return (uint64_t)EM_ASM_DOUBLE(return convertU32PairToI53($0, $1), lo, hi);
#endif
}

Expand All @@ -154,7 +170,7 @@ int64_t testconvertI32PairToI53(int64_t val) {
return convertI32PairToI53(lo, hi);
}

int64_t testconvertU32PairToI53(uint64_t val) {
uint64_t testconvertU32PairToI53(uint64_t val) {
uint32_t lo = (uint32_t)val;
uint32_t hi = val >> 32;
return convertU32PairToI53(lo, hi);
Expand All @@ -174,8 +190,8 @@ int64_t testReadWriteI64AsI53(int64_t num) {

uint64_t testReadWriteU64AsI53(uint64_t num) {
uint64_t addr = 0;
writeI53ToI64_int64((int64_t*)&addr, num);
return readI53FromU64_toInt64(&addr);
writeI53ToI64_uint64((uint64_t*)&addr, num);
return readI53FromU64_toUInt64(&addr);
}

int main() {
Expand Down

0 comments on commit 9e0121c

Please sign in to comment.