Skip to content

Commit 4d8a933

Browse files
authored
Fix UBSan on CI (#7173)
The UBSan builder started failing with an error about a misaligned store in wasm-ctor-eval.cpp. The store was already done via `memcpy` to avoid alignment issues, but apparently this is no longer enough. Use `void*` as the destination type to further avoid giving the impression of guaranteed alignment. Also fix UB when executing std::abs on minimum negative integers in literal.cpp.
1 parent 5ed6cf1 commit 4d8a933

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/tools/wasm-ctor-eval.cpp

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -462,30 +462,30 @@ struct CtorEvalExternalInterface : EvallingModuleRunner::ExternalInterface {
462462
const size_t MaximumMemory = 100 * 1024 * 1024;
463463

464464
// TODO: handle unaligned too, see shell-interface
465-
template<typename T> T* getMemory(Address address, Name memoryName) {
465+
void* getMemory(Address address, Name memoryName, size_t size) {
466466
auto it = memories.find(memoryName);
467467
assert(it != memories.end());
468468
auto& memory = it->second;
469469
// resize the memory buffer as needed.
470-
auto max = address + sizeof(T);
470+
auto max = address + size;
471471
if (max > memory.size()) {
472472
if (max > MaximumMemory) {
473473
throw FailToEvalException("excessively high memory address accessed");
474474
}
475475
memory.resize(max);
476476
}
477-
return (T*)(&memory[address]);
477+
return &memory[address];
478478
}
479479

480480
template<typename T> void doStore(Address address, T value, Name memoryName) {
481-
// do a memcpy to avoid undefined behavior if unaligned
482-
memcpy(getMemory<T>(address, memoryName), &value, sizeof(T));
481+
// Use memcpy to avoid UB if unaligned.
482+
memcpy(getMemory(address, memoryName, sizeof(T)), &value, sizeof(T));
483483
}
484484

485485
template<typename T> T doLoad(Address address, Name memoryName) {
486-
// do a memcpy to avoid undefined behavior if unaligned
486+
// Use memcpy to avoid UB if unaligned.
487487
T ret;
488-
memcpy(&ret, getMemory<T>(address, memoryName), sizeof(T));
488+
memcpy(&ret, getMemory(address, memoryName, sizeof(T)), sizeof(T));
489489
return ret;
490490
}
491491

src/wasm/literal.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -978,8 +978,14 @@ Literal Literal::neg() const {
978978
Literal Literal::abs() const {
979979
switch (type.getBasic()) {
980980
case Type::i32:
981+
if (i32 == std::numeric_limits<int32_t>::min()) {
982+
return *this;
983+
}
981984
return Literal(std::abs(i32));
982985
case Type::i64:
986+
if (i64 == std::numeric_limits<int64_t>::min()) {
987+
return *this;
988+
}
983989
return Literal(std::abs(i64));
984990
case Type::f32:
985991
return Literal(i32 & 0x7fffffff).castToF32();

0 commit comments

Comments
 (0)