Repository navigation
[wasm2c] Avoid size_t overflow in wasm_rt_grow table reallocation - #2756
Conversation
|
Can we write a test for this somehow? |
|
The awkward part is that the truncation only happens on an ILP32 target. On LP64 the guard can't fire: new_elems is already clamped to max_size (<= UINT32_MAX) by the check right above, and SIZE_MAX / sizeof(elem) is ~2^60 there, so new_elems * sizeof never wraps. With no 32-bit job in the matrix, a 64-bit run-wasm2c test of a huge grow would just hit a giant realloc that fails and returns -1, which never touches this guard. Same reason #2752 landed without one. It does reproduce directly against the real table API when built -m32: #include "wasm-rt.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
int main(void) {
wasm_rt_funcref_table_t t;
wasm_rt_funcref_t init;
memset(&init, 0, sizeof init);
/* table with no declared max -> max_size = UINT32_MAX */
wasm_rt_allocate_funcref_table(&t, 0, UINT32_MAX);
/* new_elems = 230000000, * sizeof(funcref) = 4.6e9 bytes,
truncated to 305032704 when narrowed to realloc's size_t on ILP32 */
uint32_t r = wasm_rt_grow_funcref_table(&t, 230000000u, init);
/* before: short buffer, the init loop writes 230000000 elems past it
-> heap-buffer-overflow (ASan aborts here).
after: grow is rejected. */
assert(r == (uint32_t)-1);
wasm_rt_free_funcref_table(&t);
return 0;
}Under ASan on a -m32 build that aborts before the patch and passes after. On LP64 it just allocates ~4.6GB and succeeds, so it's a no-op there. Happy to wire it up as a 32-bit-guarded check if you want it in the tree, though it won't run under the current CI. |
|
I think we can land as is. |
On a 32-bit (ILP32) build, growing a funcref table in
wasm_rt_grow:new_elemsis auint64_tbut only bounded bytable->max_size, which can beUINT32_MAX. The element is a multi-pointer struct, so the byte count crosses 2^32 long beforenew_elemsdoes. The product is then narrowed torealloc'ssize_tparameter, so the reallocation is far too small. The loop right after writesnew_elemselements into it. A guesttable.growwith a large delta on a table with a large max reaches this.Found while reading the table path looking for the realloc-side equivalent of the recent wasi size fix.
callocinwasm_rt_allocateis safe because it overflows-checks its two operands; the grow path does the multiply itself and hands the result straight torealloc, which does not.Reject the grow when the byte size would not fit in
size_t, before the realloc. No effect on 64-bit. The shared include covers the funcref, externref and exnref variants.