Skip to content

Truly independent web browser

LibWasm: Collect garbage before failing to allocate a memory

Andreas Klingf1defaa77a48
diff --git a/Libraries/LibWasm/Engine/src/runtime/heap.rs b/Libraries/LibWasm/Engine/src/runtime/heap.rs
index 76a13cd91ab..b29c8577c4d 100644
--- a/Libraries/LibWasm/Engine/src/runtime/heap.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/heap.rs
@@ -317,6 +317,8 @@ pub struct GcHeap {
pub interface: GcInterface,
layout: GcLayout,
allocators: &'static Allocators,
+ /// How many defer_gc() calls have no matching undefer_gc() yet.
+ deferrals: core::cell::Cell<u32>,
}
pub enum Heap {
@@ -352,6 +354,7 @@ impl Heap {
interface,
layout,
allocators,
+ deferrals: core::cell::Cell::new(0),
}))
}
@@ -414,15 +417,22 @@ impl Heap {
/// does not look.
pub fn defer_gc(&self) {
if let Self::Gc(heap) = self {
+ heap.deferrals.set(heap.deferrals.get() + 1);
unsafe { (heap.interface.gc_heap_defer_gc)(heap.interface.heap) };
}
}
pub fn undefer_gc(&self) {
if let Self::Gc(heap) = self {
+ heap.deferrals.set(heap.deferrals.get() - 1);
unsafe { (heap.interface.gc_heap_undefer_gc)(heap.interface.heap) };
}
}
+
+ /// Whether this runtime deferred garbage collection, with defer_gc().
+ pub fn is_gc_deferred(&self) -> bool {
+ matches!(self, Self::Gc(heap) if heap.deferrals.get() != 0)
+ }
}
impl GcHeap {
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index d7e695d54b8..f308ae5a941 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -355,6 +355,8 @@ impl Instance {
}
}
+const MEMORY_ALLOCATION_FAILED: &str = "cannot allocate memory";
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstantiationError {
Link(String),
@@ -645,10 +647,39 @@ impl Store {
}
pub fn allocate_memory(&mut self, ty: crate::types::MemoryType) -> Option<MemoryAddress> {
- let memory = MemoryInstance::new(ty, &self.heap)?;
+ let memory = match MemoryInstance::new(ty, &self.heap) {
+ Some(memory) => memory,
+ None => {
+ // NB: Collections are deferred while a module instantiates, which retries once they are not.
+ if !self.release_reservations_of_dead_memories() {
+ return None;
+ }
+ MemoryInstance::new(ty, &self.heap)?
+ }
+ };
Some(entity::allocate(&self.heap, memory))
}
+ /// Collects garbage so that the memories that died release their reservations, before failing to allocate one.
+ /// Each memory reserves gigabytes of address space, which a memory that died keeps until a collection sweeps it, and
+ /// nothing counts the reservations towards a collection. So a page that makes memories in a loop runs out of address
+ /// space with most of them dead. Returns whether it collected.
+ fn release_reservations_of_dead_memories(&self) -> bool {
+ let Some(gc) = self.heap.gc() else {
+ return false;
+ };
+ if self.heap.is_gc_deferred() {
+ return false;
+ }
+ // NB: A collection leaves the sweep of what it found dead to later. The next one finishes that sweep first,
+ // which releases the reservations.
+ for _ in 0..2 {
+ // SAFETY: The heap is live, and allocating memory is a point where garbage may be collected.
+ unsafe { (gc.interface.gc_heap_collect_garbage)(gc.interface.heap, 0, false) };
+ }
+ true
+ }
+
/// Add a table of `ty.limits.min` elements set to `initial`. Returns None if it would be too large.
pub fn allocate_table(&mut self, ty: TableType, initial: u64) -> Option<TableAddress> {
if ty.limits.min > MAX_TABLE_SIZE {
@@ -675,9 +706,14 @@ impl Store {
) -> Result<InstanceAddress, InstantiationError> {
// Instantiation keeps references in places the collector does not look, like the values of constant
// expressions on their way into globals and segments. The start function runs once they are in place.
- self.heap.defer_gc();
- let instance = self.instantiate_without_starting(module, imports);
- self.heap.undefer_gc();
+ let mut instance = self.instantiate_deferring_gc(&module, imports);
+ if matches!(&instance, Err(InstantiationError::Link(message)) if message == MEMORY_ALLOCATION_FAILED)
+ && self.release_reservations_of_dead_memories()
+ {
+ // NB: Nothing the failed attempt did is visible yet: a module's memories are allocated before any segment
+ // is written to what it imports.
+ instance = self.instantiate_deferring_gc(&module, imports);
+ }
let (instance, start) = instance?;
jit::instantiated(self, instance);
if let Some(start) = start {
@@ -686,6 +722,19 @@ impl Store {
Ok(instance)
}
+ fn instantiate_deferring_gc(
+ &mut self,
+ module: &Arc<Module>,
+ imports: &[ExternValue],
+ ) -> Result<(InstanceAddress, Option<FunctionAddress>), InstantiationError> {
+ // Instantiation keeps references in places the collector does not look, like the values of constant
+ // expressions on their way into globals and segments. The start function runs once they are in place.
+ self.heap.defer_gc();
+ let instance = self.instantiate_without_starting(Arc::clone(module), imports);
+ self.heap.undefer_gc();
+ instance
+ }
+
fn instantiate_without_starting(
&mut self,
module: Arc<Module>,
@@ -898,7 +947,7 @@ impl Store {
for memory in &module.memories {
let address = self
.allocate_memory(*memory)
- .ok_or_else(|| InstantiationError::Link("cannot allocate memory".to_string()))?;
+ .ok_or_else(|| InstantiationError::Link(MEMORY_ALLOCATION_FAILED.to_string()))?;
memories.push(address);
}
instance.memories = memories;
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-Memory-many-made-in-a-loop.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-Memory-many-made-in-a-loop.txt
new file mode 100644
index 00000000000..1ec3295689b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-Memory-many-made-in-a-loop.txt
@@ -0,0 +1,2 @@
+new WebAssembly.Memory(): made 20000
+new WebAssembly.Instance(): made 20000
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-Memory-many-made-in-a-loop.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-Memory-many-made-in-a-loop.html
new file mode 100644
index 00000000000..2541e602588
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-Memory-many-made-in-a-loop.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Each memory reserves gigabytes of address space, which more memories than this would run out of if the dead ones
+ // kept theirs.
+ function makeMany(name, make) {
+ let made = 0;
+ try {
+ for (let i = 0; i < 20000; ++i) {
+ make();
+ ++made;
+ }
+ } catch (e) {
+ println(`${name}: ${e.name}: ${e.message}`);
+ }
+ println(`${name}: made ${made}`);
+ }
+
+ test(() => {
+ makeMany("new WebAssembly.Memory()", () => new WebAssembly.Memory({ initial: 1 }));
+
+ // A module with a memory of one page, and nothing else.
+ const module = new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 0, 1]));
+ makeMany("new WebAssembly.Instance()", () => new WebAssembly.Instance(module));
+ });
+</script>