Skip to content

Commit 6114f02

Browse files
authored
Fix bad access to detached ArrayBuffer in $growMemory. (#24524)
Consider: ```js var m = new WebAssembly.Memory({initial: 64}); var b = m.buffer; m.grow(64); console.log(b.byteLength); ``` This will print `0` instead of the old memory size before growing (or the new memory size after grow), because `b` got detached by the grow. This caused bad assertions error print, and incorrect profiling. To fix, avoid referencing a detached buffer.
1 parent d281980 commit 6114f02

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

src/lib/libcore.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -174,27 +174,24 @@ addToLibrary({
174174
// Grows the wasm memory to the given byte size, and updates the JS views to
175175
// it. Returns 1 on success, 0 on error.
176176
$growMemory: (size) => {
177-
var b = wasmMemory.buffer;
178-
var pages = ((size - b.byteLength + {{{ WASM_PAGE_SIZE - 1 }}}) / {{{ WASM_PAGE_SIZE }}}) | 0;
177+
var oldHeapSize = wasmMemory.buffer.byteLength;
178+
var pages = ((size - oldHeapSize + {{{ WASM_PAGE_SIZE - 1 }}}) / {{{ WASM_PAGE_SIZE }}}) | 0;
179179
#if RUNTIME_DEBUG
180-
dbg(`growMemory: ${size} (+${size - b.byteLength} bytes / ${pages} pages)`);
181-
#endif
182-
#if MEMORYPROFILER
183-
var oldHeapSize = b.byteLength;
180+
dbg(`growMemory: ${size} (+${size - oldHeapSize} bytes / ${pages} pages)`);
184181
#endif
185182
try {
186183
// round size grow request up to wasm page size (fixed 64KB per spec)
187184
wasmMemory.grow({{{ toIndexType('pages') }}}); // .grow() takes a delta compared to the previous size
188185
updateMemoryViews();
189186
#if MEMORYPROFILER
190187
if (typeof emscriptenMemoryProfiler != 'undefined') {
191-
emscriptenMemoryProfiler.onMemoryResize(oldHeapSize, b.byteLength);
188+
emscriptenMemoryProfiler.onMemoryResize(oldHeapSize, wasmMemory.buffer.byteLength);
192189
}
193190
#endif
194191
return 1 /*success*/;
195192
} catch(e) {
196193
#if ASSERTIONS
197-
err(`growMemory: Attempted to grow heap from ${b.byteLength} bytes to ${size} bytes, but got error: ${e}`);
194+
err(`growMemory: Attempted to grow heap from ${oldHeapSize} bytes to ${size} bytes, but got error: ${e}`);
198195
#endif
199196
}
200197
// implicit 0 return to save code size (caller will cast "undefined" into 0

0 commit comments

Comments
 (0)