Repository navigation
Check size overflow and calloc failure in wasm_rt_allocate_memory - #2786
Conversation
c8b2a89 to
06a9beb
Compare
| #endif | ||
|
|
||
| memory->data = (MEMORY_CELL_TYPE)calloc(byte_length, 1); | ||
| if (byte_length != 0 && !memory->data) { |
There was a problem hiding this comment.
I'm not sure about the byte_length check here.
What happens if somebody creates a memory with an initial size of zero pages? Does it still hit this path?
If the answer is yes, then I guess we probably need a different fix.
If the answer is no, then we probably just what to assert initial_pages > 0 at the top of the function.
We can also add an assert for page_size > 0 since zero page size is not valid.
There was a problem hiding this comment.
Oops, accidentally hit merge too soon before seeing your comment. It makes sense to add an explicit runtime check for page_size > 0 if the page_size = 0 is considered invalid (I would avoid assert as some compilers compile this to a no-op on release builds). This can hopefully be added in a follow up fix.
There was a problem hiding this comment.
page_size = 0 would be a validation error so I think its ok to just be an assert here.
The memory64 overflow fix in 1c7bca9 only touched grow_memory_impl. wasm_rt_allocate_memory in the same file builds the byte length the same way and was left unchecked.
A memory64 module may declare an initial page count the validator accepts (up to ~2^48 pages at 64 KiB). At 2^47 pages the byte length is 2^63; calloc cannot satisfy it and returns NULL, but the result is never checked. data is left NULL while size holds the full length, so every generated RANGE_CHECK passes for any guest offset below size and each access writes to NULL + offset.
The multiply is unchecked too, so an initial near 2^48 wraps the length instead. grow_memory_impl already routes both cases through u64_mult_overflow and treats failure as fatal, and the mmap branch here already aborts on failure. The calloc branch did neither.
Now the length goes through u64_mult_overflow with an abort on overflow, and calloc returning NULL for a non-zero length aborts, matching the mmap branch. Valid modules allocate as before.
Found while reading the follow-up to 1c7bca9. Reproduced by calling wasm_rt_allocate_memory with is64 and 2^47 initial pages: before, data is NULL with size 2^63; after, it aborts during instantiation.