Skip to content

Commit c7b2683

Browse files
authored
Fix out of bounds issue in is_native_addr_in_shared_heap function (#3886)
When checking for integer overflow, you may often write tests like p + i < p. This works fine if p and i are unsigned integers, since any overflow in the addition will cause the value to simply "wrap around." However, using this pattern when p is a pointer is problematic because pointer overflow has undefined behavior according to the C and C++ standards. If the addition overflows and has an undefined result, the comparison will likewise be undefined; it may produce an unintended result, or may be deleted entirely by an optimizing compiler.
1 parent 1138435 commit c7b2683

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

core/iwasm/common/wasm_memory.c

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -420,13 +420,31 @@ is_native_addr_in_shared_heap(WASMModuleInstanceCommon *module_inst,
420420
uint8 *addr, uint32 bytes)
421421
{
422422
WASMSharedHeap *heap = get_shared_heap(module_inst);
423+
uintptr_t base_addr;
424+
uintptr_t addr_int;
425+
uintptr_t end_addr;
423426

424-
if (heap && addr >= heap->base_addr
425-
&& addr + bytes <= heap->base_addr + heap->size
426-
&& addr + bytes > addr) {
427-
return true;
427+
if (!heap) {
428+
return false;
428429
}
429-
return false;
430+
431+
base_addr = (uintptr_t)heap->base_addr;
432+
addr_int = (uintptr_t)addr;
433+
if (addr_int < base_addr) {
434+
return false;
435+
}
436+
437+
end_addr = addr_int + bytes;
438+
/* Check for overflow */
439+
if (end_addr <= addr_int) {
440+
return false;
441+
}
442+
443+
if (end_addr > base_addr + heap->size) {
444+
return false;
445+
}
446+
447+
return true;
430448
}
431449

432450
uint64

0 commit comments

Comments
 (0)