Skip to content

Instantly share code, notes, and snippets.

@sffc
Last active July 11, 2023 21:47
Show Gist options
  • Save sffc/e0fd8fbfe4dade77229dd3cbfdff215a to your computer and use it in GitHub Desktop.
Save sffc/e0fd8fbfe4dade77229dd3cbfdff215a to your computer and use it in GitHub Desktop.
Repro for crbug 13958
// Build this file with:
// rustc --target wasm32-unknown-unknown bigbox.rs
#![crate_type = "cdylib"]
type INNER = Vec<u8>;
#[no_mangle]
pub extern "C" fn make_big_box(len: usize) -> *mut core::ffi::c_void {
let memory: Box<INNER> = Box::new(vec![0; len]);
Box::into_raw(memory) as *mut core::ffi::c_void
}
#[no_mangle]
pub unsafe extern "C" fn free_big_box(ptr: *mut core::ffi::c_void) {
Box::from_raw(ptr as *mut INNER);
}
<!DOCTYPE html>
<!--
View online at:
https://storage.googleapis.com/static-493776/crbug13958/bigbox_frontend.html
-->
<script type="text/javascript">
let wasmInstance;
async function main() {
const wasmResponse = await fetch("./bigbox.wasm");
const wasmBuffer = await wasmResponse.arrayBuffer();
const wasmResult = await WebAssembly.instantiate(wasmBuffer);
wasmInstance = wasmResult.instance;
}
main();
function updateView() {
document.getElementById("wasmsize").innerText = wasmInstance.exports.memory.buffer.byteLength;
}
const registry = new FinalizationRegistry(({ ptr, len }) => {
if (ptr) wasmInstance.exports.free_big_box(ptr);
let s = ptr ? `Wasm object at ${ptr}` : `ArrayBuffer with length ${len}`;
updateView();
const time = new Date().toLocaleString(undefined, { hour: "numeric", minute: "numeric", second: "numeric", fractionalSecondDigits: 3 });
document.getElementById("collected").innerHTML = `<li>${time} - ${s}</li>` + document.getElementById("collected").innerHTML;
});
function createBigBox(len) {
if (!wasmInstance) {
alert("Please wait for the wasm instance to finish loading");
return;
}
const ptr = wasmInstance.exports.make_big_box(len);
const obj = { _inner: ptr };
registry.register(obj, { ptr });
updateView();
return obj;
}
function createBigArrayBuffer(len) {
const buffer = new ArrayBuffer(len);
registry.register(buffer, { len });
}
window.ablen = 1000000;
</script>
<p>
Total WASM linear memory length: <span id="wasmsize"></span>
</p>
<p>
<button onclick="createBigBox(1000000)">Make New 1MB Wasm Object</button>
</p>
<p>
<button onclick="window.ablen++; createBigArrayBuffer(window.ablen)">Make New 1MB ArrayBuffer</button>
</p>
<p>
Objects collected:
<ul id="collected"></ul>
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment