Skip to content

Truly independent web browser

LibGC+LibJS+LibWeb+WebContent: Release memory when the browser asks

Andreas Kling345fc3152d06
diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cpp
index 0c49833c4d9..6e99931e187 100644
--- a/Libraries/LibGC/CAPI.cpp
+++ b/Libraries/LibGC/CAPI.cpp
@@ -238,6 +238,11 @@ bool gc_heap_is_marking_for_collection(GCHeap const* heap)
return as_heap(heap).is_marking_for_collection();
}
+bool gc_heap_is_returning_memory_to_system(GCHeap const* heap)
+{
+ return as_heap(heap).is_returning_memory_to_system();
+}
+
void gc_heap_defer_gc(GCHeap* heap)
{
CAPI::defer_gc(as_heap(heap));
diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.h
index df70a69270f..0bfb74d9d0f 100644
--- a/Libraries/LibGC/CAPI.h
+++ b/Libraries/LibGC/CAPI.h
@@ -117,6 +117,8 @@ GC_API void gc_heap_collect_garbage(GCHeap*, int collection_type, bool print_rep
GC_API bool gc_heap_is_collecting_everything(GCHeap const*);
// Whether the heap gathers its roots and marks the live cells for a collection now, rather than for a graph dump.
GC_API bool gc_heap_is_marking_for_collection(GCHeap const*);
+// Whether the collection that runs is there to give memory back to the system, for a process that is short of it.
+GC_API bool gc_heap_is_returning_memory_to_system(GCHeap const*);
GC_API void gc_heap_defer_gc(GCHeap*);
GC_API void gc_heap_undefer_gc(GCHeap*);
GC_API void gc_heap_deferral_state(GCHeap*, size_t** deferrals, bool** collect_when_deferrals_end);
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index ec580dc70d7..a88624cf9b7 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -2070,6 +2070,25 @@ void Heap::collect_garbage_from_timer()
collect_garbage();
}
+void Heap::collect_garbage_and_return_memory_to_system()
+{
+ // NB: A collection that has to wait for a deferral to end still lets go of as much as this one would. What it
+ // frees goes back to the system some seconds later, as after any other collection.
+ if (is_gc_deferred()) {
+ m_should_gc_when_deferral_ends = true;
+ m_should_return_memory_when_deferral_ends = true;
+ return;
+ }
+ {
+ TemporaryChange change { m_is_returning_memory_to_system, true };
+ collect_garbage();
+ finish_pending_incremental_sweep();
+ }
+ for (auto& allocator : m_all_cell_allocators)
+ allocator.block_allocator().return_freed_blocks_to_system();
+ ak_kmalloc_collect();
+}
+
void Heap::schedule_release_of_abandoned_object_graph_memory()
{
// NB: A timer, since a sweep can finish in the middle of any allocation, and the allocator can't be collected from
@@ -2106,8 +2125,12 @@ void Heap::undefer_gc()
if (m_block_sweeps_in_progress > 0)
return;
- collect_garbage();
+ {
+ TemporaryChange change { m_is_returning_memory_to_system, m_should_return_memory_when_deferral_ends };
+ collect_garbage();
+ }
m_should_gc_when_deferral_ends = false;
+ m_should_return_memory_when_deferral_ends = false;
}
void Heap::uproot_cell(Cell* cell)
diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.h
index bae6d3c60d2..2bfe445563f 100644
--- a/Libraries/LibGC/Heap.h
+++ b/Libraries/LibGC/Heap.h
@@ -86,6 +86,11 @@ public:
// NO_SANITIZE_ADDRESS so that the capture buffer stays on the real stack rather than ASan's fake one.
NEVER_INLINE void collect_garbage(CollectionType = CollectionType::CollectGarbage, bool print_report = false);
+ // Collects garbage and gives the memory that this frees back to the system before it returns. Otherwise the sweep
+ // happens bit by bit after a collection, and the freed memory goes back to the system some time after that. For a
+ // process that is short of memory now.
+ void collect_garbage_and_return_memory_to_system();
+
// Collects without taking any root from the stack or the registers, so no stale or lookalike word there keeps a
// cell alive. Only safe where every cell the stack refers to is rooted some other way, as in the outermost turn of
// the event loop.
@@ -123,6 +128,10 @@ public:
// Whether a collection that marks the live cells runs, as opposed to one that only sweeps or a graph dump.
bool is_marking_for_collection() const { return m_collecting_garbage && m_current_collection_type == CollectionType::CollectGarbage; }
+ // Whether collect_garbage_and_return_memory_to_system() runs, so that what hangs off the heap can let go of more
+ // than it does in other collections.
+ bool is_returning_memory_to_system() const { return m_is_returning_memory_to_system; }
+
void set_incremental_sweep_enabled(bool enabled) { m_incremental_sweep_enabled = enabled; }
void set_should_collect_on_every_allocation(bool);
@@ -360,12 +369,14 @@ private:
HashTable<CrossHeapMemberBase*> m_incoming_cross_heap_members;
HeapGroup* m_group { nullptr };
bool m_incremental_sweep_enabled { true };
+ bool m_is_returning_memory_to_system { false };
WeakContainer::List m_weak_containers;
Vector<Ptr<Cell>> m_uprooted_cells;
size_t m_gc_deferrals { 0 };
bool m_should_gc_when_deferral_ends { false };
+ bool m_should_return_memory_when_deferral_ends { false };
bool m_collecting_garbage { false };
bool m_weak_pointers_to_dead_cells_are_cleared { false };
diff --git a/Libraries/LibGfx/Rust/src/text_layout.rs b/Libraries/LibGfx/Rust/src/text_layout.rs
index 8e1f25049fd..c7ae0480ab8 100644
--- a/Libraries/LibGfx/Rust/src/text_layout.rs
+++ b/Libraries/LibGfx/Rust/src/text_layout.rs
@@ -1018,6 +1018,16 @@ thread_local! {
static SHAPING_CACHE: std::cell::RefCell<ShapingCache> = std::cell::RefCell::new(ShapingCache::default());
}
+/// Lets go of every shaped text the calling thread keeps, for a process that is short of memory.
+pub fn clear_shaping_cache() {
+ // NB: A thread that is in the middle of using a shape from the cache keeps it borrowed, and keeps its cache.
+ SHAPING_CACHE.with(|cache| {
+ if let Ok(mut cache) = cache.try_borrow_mut() {
+ *cache = ShapingCache::default();
+ }
+ });
+}
+
fn shape_text_uncached(font: &FontHandle, text: &[u16], params: ShapeParams) -> CachedShape {
unsafe extern "C" fn emit(
sink: *mut c_void,
diff --git a/Libraries/LibJS/Rust/src/bytecode/flushing.rs b/Libraries/LibJS/Rust/src/bytecode/flushing.rs
index 700633d77ae..c1d5ab1a7cf 100644
--- a/Libraries/LibJS/Rust/src/bytecode/flushing.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/flushing.rs
@@ -155,6 +155,8 @@ struct Pass {
now: Instant,
/// The layers in which to flush whatever nothing else holds, whatever its age, by bit (see `FlushLayer`).
forced_layers: u8,
+ /// Whether the pass is there to give memory back to the system, for a process that is short of it.
+ releases_memory: bool,
}
impl Pass {
@@ -225,7 +227,12 @@ impl CodeFlushing {
// NB: The candidates are not traced, so none may outlive the collection that found them, flush pass or not.
self.bytecode_candidates.borrow_mut().clear();
self.jit_candidates.borrow_mut().clear();
- let forced_layers = self.flush_at_next_collection.replace(0);
+ let mut forced_layers = self.flush_at_next_collection.replace(0);
+ // NB: A process that is short of memory is better off compiling its code again than keeping it.
+ let releases_memory = vm.heap().is_returning_memory_to_system();
+ if releases_memory {
+ forced_layers = ALL_FLUSH_LAYERS;
+ }
if !(self.options.enabled || forced_layers != 0) || vm.debugging_enabled() {
return;
}
@@ -236,6 +243,7 @@ impl CodeFlushing {
} else {
forced_layers
},
+ releases_memory,
}));
CodeFlushingStats::count(&self.stats.passes, 1);
ACTIVE_PASS.set(Some(NonNull::from(self)));
@@ -244,7 +252,9 @@ impl CodeFlushing {
/// Whether the idle time of an executable that idled for `idle_collections` collections is long enough to flush
/// it in `layer` in this pass, for a function that was compiled again `recompiles` times after flushes there.
fn idled_long_enough(&self, pass: Pass, layer: FlushLayer, idle_collections: u8, recompiles: u8) -> bool {
- if recompiles >= self.options.max_recompiles {
+ // NB: The most recompiles are there to stop a function from being flushed and compiled over and over, which
+ // is no reason to keep its code in a process that is short of memory.
+ if recompiles >= self.options.max_recompiles && !pass.releases_memory {
return false;
}
if pass.forces(layer) {
diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rs
index e1d962de651..28e44ef5b36 100644
--- a/Libraries/LibJS/Rust/src/gc/capi.rs
+++ b/Libraries/LibJS/Rust/src/gc/capi.rs
@@ -97,6 +97,7 @@ unsafe extern "C" {
pub safe fn gc_heap_collect_garbage(heap: &GCHeap, collection_type: i32, print_report: bool);
pub safe fn gc_heap_is_collecting_everything(heap: &GCHeap) -> bool;
pub safe fn gc_heap_is_marking_for_collection(heap: &GCHeap) -> bool;
+ pub safe fn gc_heap_is_returning_memory_to_system(heap: &GCHeap) -> bool;
pub safe fn gc_heap_undefer_gc(heap: &GCHeap);
pub safe fn gc_heap_deferral_state(
heap: &GCHeap,
diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rs
index 0beffc296b3..c6418e811a9 100644
--- a/Libraries/LibJS/Rust/src/gc/heap.rs
+++ b/Libraries/LibJS/Rust/src/gc/heap.rs
@@ -733,6 +733,11 @@ impl Heap {
capi::gc_heap_is_marking_for_collection(self.handle())
}
+ /// Whether the collection that runs is there to give memory back to the system, for a process that is short of it.
+ pub fn is_returning_memory_to_system(&self) -> bool {
+ capi::gc_heap_is_returning_memory_to_system(self.handle())
+ }
+
pub fn should_collect_on_every_allocation(&self) -> bool {
capi::gc_heap_should_collect_on_every_allocation(self.handle())
}
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 8734b2059e5..87025034cc1 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -2421,7 +2421,13 @@ unsafe extern "C" fn sweep(context: *mut c_void) {
let sweep = unsafe { Sweep::new(vm) };
vm.code_flushing.finish_pass(vm, &sweep);
crate::parser::release_idle_reparse_contexts();
- crate::source_text::park_idle_source_texts();
+ // NB: The VM has no heap anymore when this runs for the last collection of a heap that goes away.
+ if vm.heap.get().is_some_and(Heap::is_returning_memory_to_system) {
+ crate::source_text::park_all_source_texts();
+ crate::runtime::regexp_prototype::clear_regex_cache();
+ } else {
+ crate::source_text::park_idle_source_texts();
+ }
vm.remove_dead_async_waits(&sweep);
vm.remove_dead_cells_from_weak_containers(&sweep);
vm.remove_dead_strings_from_weak_caches(&sweep);
diff --git a/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs b/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
index 684cf6bc45b..e87851d922e 100644
--- a/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/regexp_prototype.rs
@@ -246,6 +246,15 @@ thread_local! {
RefCell::new(HashMap::default());
}
+/// Lets go of the compiled regexes of the calling thread that no RegExp object holds, for a process that is short of
+/// memory.
+pub(crate) fn clear_regex_cache() {
+ REGEX_CACHE.with_borrow_mut(|cache| {
+ cache.clear();
+ cache.shrink_to_fit();
+ });
+}
+
fn get_or_compile_regex(regexp_object: &RegExpObject) -> Option<Rc<EcmaScriptRegex>> {
// Fast path: check the inline cache on the RegExpObject.
if let Some(cached) = regexp_object.cached_regex() {
diff --git a/Libraries/LibJS/Rust/src/source_text.rs b/Libraries/LibJS/Rust/src/source_text.rs
index 7fa7900c29b..39c1dd2bf26 100644
--- a/Libraries/LibJS/Rust/src/source_text.rs
+++ b/Libraries/LibJS/Rust/src/source_text.rs
@@ -316,11 +316,21 @@ pub fn park_all_source_texts_now() -> usize {
/// Parks the texts that nothing asked for in a while, on a thread of their own. Collections call this.
pub fn park_idle_source_texts() {
+ park_source_texts_idle_for(IDLE_TIME_BEFORE_PARKING);
+}
+
+/// Parks every text that can be parked, whatever its age, on a thread of their own. Collections of a process that is
+/// short of memory call this.
+pub fn park_all_source_texts() {
+ park_source_texts_idle_for(Duration::ZERO);
+}
+
+fn park_source_texts_idle_for(idle_time: Duration) {
static IS_PARKING: AtomicBool = AtomicBool::new(false);
if IS_PARKING.swap(true, Ordering::Acquire) {
return;
}
- let candidates = parking_candidates(IDLE_TIME_BEFORE_PARKING);
+ let candidates = parking_candidates(idle_time);
if candidates.is_empty() {
IS_PARKING.store(false, Ordering::Release);
return;
diff --git a/Libraries/LibWeb/CSS/StyleScope.cpp b/Libraries/LibWeb/CSS/StyleScope.cpp
index 39449ac5cd1..1dc3fc4742e 100644
--- a/Libraries/LibWeb/CSS/StyleScope.cpp
+++ b/Libraries/LibWeb/CSS/StyleScope.cpp
@@ -383,6 +383,11 @@ void StyleScope::release_kept_data()
Parser::ValueParserFFI::rust_style_release_kept_data();
}
+void StyleScope::release_shaped_texts()
+{
+ Parser::ValueParserFFI::rust_style_release_shaped_texts();
+}
+
void StyleScope::for_each_user_agent_stylesheet(bool include_quirks_mode_stylesheet, bool include_mathml_and_svg_stylesheets, Function<void(CSS::StyleSheetState&, StyleSheetIdentifier const&)> const& callback)
{
auto callback_with_identifier = [&](StyleSheetState& sheet, Utf16String url) {
diff --git a/Libraries/LibWeb/CSS/StyleScope.h b/Libraries/LibWeb/CSS/StyleScope.h
index c2cbf53145d..34130add9c5 100644
--- a/Libraries/LibWeb/CSS/StyleScope.h
+++ b/Libraries/LibWeb/CSS/StyleScope.h
@@ -133,6 +133,8 @@ public:
static void prepare_user_agent_rules(DOM::Document&);
// Lets go of the parsed sheets and sheet segments only the process keeps, past the documents that used them.
static WEB_API void release_kept_data();
+ // Lets go of the shaped texts that this thread and the style and layout threads keep, for a process short of memory.
+ static WEB_API void release_shaped_texts();
static WEB_API void for_each_user_agent_stylesheet(bool include_quirks_mode_stylesheet, bool include_mathml_and_svg_stylesheets, Function<void(CSS::StyleSheetState&, StyleSheetIdentifier const&)> const&);
void build_user_style_sheet_if_needed();
diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
index df99f373b79..1f71ea02345 100644
--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
@@ -592,6 +592,14 @@ pub extern "C" fn rust_style_release_kept_data() {
crate::render_state::process_style().release_kept_past_release();
}
+/// Lets go of the shaped texts that the calling thread and the style and layout threads keep, for a process short of
+/// memory.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_style_release_shaped_texts() {
+ libgfx_rust::text_layout::clear_shaping_cache();
+ crate::render_state::release_caches_of_style_layout_threads();
+}
+
/// Writes whether the conditions of each rule hold, for the rules the engine has.
fn write_rule_conditions(host: &crate::render_state::DocumentHost, conditions: Vec<(u64, bool)>) {
if conditions.is_empty() {
diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rs
index 6fa7b2d3074..66e5187e554 100644
--- a/Libraries/LibWeb/Rust/src/render_state.rs
+++ b/Libraries/LibWeb/Rust/src/render_state.rs
@@ -20,7 +20,9 @@ mod clock;
mod devtools;
mod document_host;
mod owner;
-pub(crate) use owner::{process_style, release_unused_memory_of_style_layout_threads};
+pub(crate) use owner::{
+ process_style, release_caches_of_style_layout_threads, release_unused_memory_of_style_layout_threads,
+};
mod wait;
pub use clock::hover::FfiHoverPlanInputs;
diff --git a/Libraries/LibWeb/Rust/src/render_state/owner.rs b/Libraries/LibWeb/Rust/src/render_state/owner.rs
index aefedb2db03..342c2f5977f 100644
--- a/Libraries/LibWeb/Rust/src/render_state/owner.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/owner.rs
@@ -153,6 +153,18 @@ pub(crate) fn release_unused_memory_of_style_layout_threads() {
#[cfg(not(feature = "allocator"))]
pub(crate) fn release_unused_memory_of_style_layout_threads() {}
+/// Has the style and layout threads of the process let go of what they keep to work faster, and give that memory
+/// back, for a process that is short of memory. Each does so between its jobs, and this does not wait for them.
+pub(crate) fn release_caches_of_style_layout_threads() {
+ if let Some(pool) = SLOT.style_layout_pool.started() {
+ pool.spawn_broadcast(|_| {
+ libgfx_rust::text_layout::clear_shaping_cache();
+ #[cfg(feature = "allocator")]
+ ak::release_unused_allocator_memory();
+ });
+ }
+}
+
/// The style data every document's style engine shares with the others, which any thread reaches without the slot: only
/// what it guards itself is written once it is made.
pub(crate) fn process_style() -> &'static Arc<crate::css::style::ProcessStyle> {
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index ac3e8f1ee18..b9233afbd11 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -150,6 +150,35 @@ void ConnectionFromClient::die()
Core::Process::terminate_immediately(0);
}
+// What the main thread and each worker thread give up when the process is short of memory.
+static void release_memory_of_this_thread()
+{
+ Web::Fetch::Fetching::clear_http_memory_cache();
+ // NB: This comes last, so that what the steps before it let go of goes back to the system as well.
+ GC::Heap::the().collect_garbage_and_return_memory_to_system();
+}
+
+// The browser asks for this when the process is near its memory limit, or when its tabs were hidden for a while. The
+// process gives up everything it can work without. What it gives up may cost time to make again.
+void ConnectionFromClient::release_memory()
+{
+ // NB: The browser asks for more than one reason, and one release serves all requests that wait for it.
+ static bool is_pending = false;
+ if (is_pending)
+ return;
+ is_pending = true;
+
+ Web::CSS::StyleScope::release_kept_data();
+ Web::CSS::StyleScope::release_shaped_texts();
+
+ WebWorker::post_to_worker_threads(release_memory_of_this_thread);
+ // NB: This is deferred so that garbage collection runs with as little on the stack as possible.
+ Core::deferred_invoke([] {
+ is_pending = false;
+ release_memory_of_this_thread();
+ });
+}
+
void ConnectionFromClient::set_font_service(IPC::TransportHandle handle, IPC::File catalog, u64 catalog_size, u64 generation)
{
auto* font_provider = MUST(Compositing::install_font_service(move(handle), move(catalog), catalog_size, generation));
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index 505c7298370..b5e73a89fe2 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -94,6 +94,7 @@ private:
Optional<PageClient const&> page(Web::PageId index, SourceLocation = SourceLocation::current()) const;
virtual void set_font_service(IPC::TransportHandle, IPC::File catalog, u64 catalog_size, u64 generation) override;
+ virtual void release_memory() override;
virtual void initialize(Web::PageId initial_page_id, Vector<Web::HTML::RemoteNavigableDescriptor> remote_navigables, Web::HTML::CrossProcessId root_navigable_id, Web::HTML::CrossProcessIdAllocator cross_process_id_allocator, Web::HTML::SessionHistoryEntryDescriptor initial_history_entry, Web::HTML::CrossProcessId initial_document_id, Web::HTML::VisibilityState system_visibility_state) override;
virtual void create_representing_page(Web::PageId page_id, Vector<Web::HTML::RemoteNavigableDescriptor> remote_navigables) override;
virtual void create_embedded_page(Web::PageId page_id, Vector<Web::HTML::RemoteNavigableDescriptor> remote_navigables, Web::HTML::CrossProcessId root_navigable_id, Web::HTML::SessionHistoryEntryDescriptor initial_history_entry, Web::HTML::VisibilityState system_visibility_state) override;
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index dc4c4ea8632..faef6f4b00e 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -73,6 +73,7 @@
endpoint WebContentServer routed by Web::PageId page_id
{
set_font_service(IPC::TransportHandle handle, IPC::File catalog, u64 catalog_size, u64 generation) =|
+ release_memory() =|
[NotRouted] initialize(Web::PageId initial_page_id, Vector<Web::HTML::RemoteNavigableDescriptor> remote_navigables, Web::HTML::CrossProcessId root_navigable_id, Web::HTML::CrossProcessIdAllocator cross_process_id_allocator, Web::HTML::SessionHistoryEntryDescriptor initial_history_entry, Web::HTML::CrossProcessId initial_document_id, Web::HTML::VisibilityState system_visibility_state) =|
[NotRouted] create_representing_page(Web::PageId page_id, Vector<Web::HTML::RemoteNavigableDescriptor> remote_navigables) =|
create_embedded_page(Web::PageId page_id, Vector<Web::HTML::RemoteNavigableDescriptor> remote_navigables, Web::HTML::CrossProcessId root_navigable_id, Web::HTML::SessionHistoryEntryDescriptor initial_history_entry, Web::HTML::VisibilityState system_visibility_state) =|