Truly independent web browser
LibWebView: Add opt-in process statistics logs
Andreas Kling021163b6dd40
diff --git a/Documentation/StatsLog.md b/Documentation/StatsLog.mdnew file mode 100644index 00000000000..5b7b8cccffe--- /dev/null+++ b/Documentation/StatsLog.md@@ -0,0 +1,135 @@+<!--+Copyright (c) 2026-present, the Ladybird developers.++SPDX-License-Identifier: BSD-2-Clause+-->++# Process statistics++Start Ladybird or WebDriver with `--stats-log-dir=/absolute/path` to record engine statistics. The+directory is created if necessary. Use a fresh directory and a separate browser profile for each+run. WebDriver forwards the option to the browser, which forwards it to its helper processes,+including helpers started later or restarted after a crash. A browser started with the option+never hands its URLs to a browser that is already running. Logging is disabled by default.++Each process appends UTF-8 JSON lines to `<directory>/<process>.<pid>.jsonl` and prints its file+path to stderr. Files are opened with mode 0600 and are closed on exec. Existing files are appended+to, never truncated. Opening failures fail startup. Writing failures print the path and error and+quit the process's event loop with exit code 1. A forcibly terminated process can leave an+incomplete final line.++Every record has these fields:++| Field | Meaning |+| --- | --- |+| `type` | `sample` or `event` |+| `time_ns` | Integer nanoseconds from `CLOCK_MONOTONIC`, shared across processes on a host |+| `process` | `Ladybird`, `WebDriver`, `WebContent`, `WebWorker`, `RequestServer`, `Compositor`, `ImageDecoder`, `AudioServer`, `MediaServer`, `VideoDecoderServer`, or `WasmCompiler` |+| `pid` | Integer operating system process ID |++For example:++```json+{"type":"sample","time_ns":1234567890,"process":"WebContent","pid":123,"values":{"gc.heap_blocks":42}}+{"type":"event","time_ns":1234567891,"process":"WebContent","pid":123,"name":"load","data":{"page_id":1,"navigable_id":"1:1","document_id":"1:1","url":"https://example.com/"}}+```++Samples have a `values` object containing only numbers with dotted keys. Each process takes an+initial sample after initialization and then samples every 100 ms on its main event loop. Busy+processes can delay samples. The logger neither interrupts JavaScript nor reads GC or graphics state+from another thread. Add process-specific counters in the callback passed to+`Core::StatsLog::start_sampling()` using `values.set("category.name"sv, value)`.++## Sample values++All sizes are bytes. Counts are integers. Duration units are given by their key suffixes.+Unsupported values are omitted, rather than reported as zero.++| Key | Source |+| --- | --- |+| `mimalloc.current_rss_bytes` | `mi_process_info()` current RSS estimate. On Linux mimalloc 2.2 uses its committed-byte count as the estimate, not actual process RSS. |+| `mimalloc.peak_rss_bytes` | `mi_process_info()` peak process RSS. On Linux this is `getrusage(RUSAGE_SELF).ru_maxrss`, converted to bytes. |+| `mimalloc.current_commit_bytes` | `mi_process_info()` current commit result |+| `mimalloc.peak_commit_bytes` | `mi_process_info()` peak commit result |+| `malloc.arena_bytes` | glibc `mallinfo2().arena`, memory obtained for system malloc arenas |+| `malloc.allocated_bytes` | glibc `mallinfo2().uordblks`, allocated arena bytes |+| `malloc.free_bytes` | glibc `mallinfo2().fordblks`, free arena bytes |+| `malloc.mmap_bytes` | glibc `mallinfo2().hblkhd`, memory obtained for system malloc mmap allocations |+| `gc.allocated_bytes_total` | Heap's existing cumulative allocation counter, including external allocation notifications and storage cells |+| `gc.allocated_bytes_since_gc` | Heap's existing allocation threshold counter, adjusted by external frees |+| `gc.heap_blocks` | Number of currently owned GC heap blocks |+| `gc.heap_block_bytes` | `gc.heap_blocks` times the heap block size, including block headers and unused cell slots |+| `gc.cell_allocators` | Number of registered type-isolating cell allocators in this heap |+| `gc.threshold_bytes` | Current GC allocation threshold |+| `gc.live_cell_bytes` | Cell slots surviving the most recently completed sweep |+| `gc.live_external_bytes` | External memory reported by those surviving cells |+| `gc.collections` | Number of collections started since logging was enabled |+| `gc.completed_collections` | Number of collections whose sweeps have finished |+| `gc.total_duration_ns` | Sum of active GC durations for completed collections |+| `gc.last_duration_ns` | Active duration of the last completed collection |+| `gpu.skia_resource_cache_bytes` | Compositor's main Skia GPU context resource cache usage |+| `requests.clients` | RequestServer's data client connection map size, excluding the browser control connection |+| `requests.transfer_leases` | RequestServer's outstanding request transfer lease map size |+| `dom.documents` | WebContent main event loop's registered document count, including detached and decoded SVG documents pending collection |+| `images.available_entries` | Sum of registered documents' lists of available images map sizes |+| `images.shared_requests` | Sum of registered documents' shared image request map sizes, including pending requests |+| `css.document_style_sheet_entries` | Sum of document style scopes' sheet vector sizes, excluding shadow scopes and adopted sheets |+| `fonts.face_entries` | Sum of registered documents' `FontFaceSet` sizes, including loading faces |+| `fonts.system_fallback_cache_entries` | Process-wide system fallback font cache map size, including cached misses, read under its mutex |+| `rendering.updates` | Main event loop's rendering updates run counter |+| `rendering.paints` | Main event loop's paint counter |+| `rendering.update_duration_us` | Main event loop's rendering update time counter, in microseconds |++GC values belong to the main VM heap in WebContent and WebWorker. Live sizes and completed durations+start at zero until the first sweep finishes. Heap block bytes exclude the reserved address range,+unused type-isolated chunks, weak blocks, and blocks retained for reuse or awaiting background+decommit. They are not a measurement of resident memory or committed memory. No heap walk is+performed for a sample.++AK uses mimalloc on supported platforms except address and thread sanitizer builds, where its sample+keys are omitted. System malloc values are present on glibc 2.33 or newer and cover allocations+served by glibc, not allocations served by mimalloc or the GC block allocator. The Skia key is+omitted with CPU painting. Skia cache usage does not include every GPU allocation, driver+allocation, or backing store.++WebContent structural samples read existing container sizes in O(1) per registered document. They+enumerate the document registry without sorting it, walking trees, creating wrappers, or forcing a+render-thread read. Entries are counted per document and can refer to the same underlying image,+sheet, or font. Counts include detached documents until collection. The rendering counters are the+existing diagnostic counters and can be reset by the test-only internals API. DOM node and realm+counts have no existing constant-time total. Layout and paintable state belongs to the render+thread; its diagnostic accessor forces a synchronous read. Decoded image bytes require visiting+image data and SVG caches. These values are deliberately omitted.++## Events++Events have a `name` string and a `data` object. Navigation and document lifecycle events cover+top-level traversables. IDs are scoped to a browser instance. Cross-process IDs are strings of the+form `namespace:local`, preserving their exact values in floating-point JSON consumers.++| Name | Process | Data |+| --- | --- | --- |+| `navigation_start` | Ladybird | `navigable_id` (cross-process ID string), `navigation_id` (string), `url` (string) |+| `DOMContentLoaded` | WebContent | `page_id` (integer), `navigable_id` (cross-process ID string), `document_id` (cross-process ID string), `url` (string) |+| `load` | WebContent | Same fields as `DOMContentLoaded` |+| `gc` | WebContent or WebWorker | `collection`, `duration_ns`, `pause_duration_ns`, `sweep_duration_ns`, `bytes_before`, `bytes_after`, `live_cell_bytes`, `live_external_bytes` (integers) |++Navigation starts are recorded when the browser admits a navigation. Lifecycle markers are recorded+immediately before DOM event dispatch, excluding event handlers. Match them by `navigable_id`.+A navigation can move to a new WebContent process and page ID. Same-document navigations can have a+start without new lifecycle events. Canceled navigations may never produce lifecycle events.+Detached documents and decoded SVG image documents do not produce lifecycle markers.++GC events are written after sweeping finishes. Durations measure active collection work, excluding+idle time between incremental sweep slices. Byte counts describe the heap's existing accounting,+not process RSS.++## Sandboxing and overhead++Each helper opens its own file before installing its sandbox. Linux retains the open descriptor;+macOS grants write access to that exact file. Sandboxes remain enabled. The directory must be+absolute and files must be regular files. Symlinks are rejected.++Logging disabled leaves no logger, sampling timer or pending-work state. Hooks check a+constant-initialized thread-local pointer before collecting statistics. Logging enabled adds JSON+serialization and synchronous file writes, so use a local filesystem for performance investigation.diff --git a/Libraries/LibCore/CMakeLists.txt b/Libraries/LibCore/CMakeLists.txtindex 650b454a7cb..84d7ed28bc0 100644--- a/Libraries/LibCore/CMakeLists.txt+++ b/Libraries/LibCore/CMakeLists.txt@@ -24,6 +24,7 @@ set(SOURCESSharedVersion.cppSocketAddress.cppStandardPaths.cpp+ StatsLog.cppSystemServerTakeover.cppThreadEventQueue.cppTimer.cpp@@ -111,7 +112,7 @@ if (APPLE)endif()ladybird_lib(LibCore core EXPLICIT_SYMBOL_EXPORT)-target_link_libraries(LibCore PRIVATE Threads::Threads LibUnicode LibTextCodec)+target_link_libraries(LibCore PRIVATE Threads::Threads LibUnicode LibTextCodec mimalloc)if (${CMAKE_SYSTEM_NAME} MATCHES "NetBSD")# NetBSD has its shm_open and shm_unlink functions in librt so we need to link thatdiff --git a/Libraries/LibCore/Forward.h b/Libraries/LibCore/Forward.hindex a53e69109db..b1752200dc7 100644--- a/Libraries/LibCore/Forward.h+++ b/Libraries/LibCore/Forward.h@@ -37,6 +37,7 @@ class Promise;template<typename Result, typename TError = AK::Error>class ThreadedPromise;class SocketAddress;+class StatsLog;class TCPServer;class TCPSocket;class Timer;diff --git a/Libraries/LibCore/Process.cpp b/Libraries/LibCore/Process.cppindex 9be7e41b0be..cdfd62095f9 100644--- a/Libraries/LibCore/Process.cpp+++ b/Libraries/LibCore/Process.cpp@@ -448,7 +448,7 @@ ErrorOr<Process> Process::spawn(StringView path, ReadonlySpan<ByteString> argume{auto process = TRY(spawn({.executable = path,- .arguments = Vector<ByteString> { arguments },+ .arguments = arguments,}));return process;diff --git a/Libraries/LibCore/Process.h b/Libraries/LibCore/Process.hindex 9854241b625..dea77d7ac5e 100644--- a/Libraries/LibCore/Process.h+++ b/Libraries/LibCore/Process.h@@ -11,7 +11,9 @@#include <AK/ByteString.h>#include <AK/Forward.h>+#include <AK/Span.h>#include <AK/String.h>+#include <AK/Vector.h>#include <LibCore/Export.h>#include <LibCore/File.h>@@ -43,7 +45,7 @@ struct ProcessSpawnOptions {bool search_for_executable_in_path { false };// On supported platforms, ask the kernel to terminate this process when its parent dies.bool die_with_parent { false };- Vector<ByteString> const& arguments {};+ ReadonlySpan<ByteString> arguments {};// The child's whole environment, as NAME=value strings. Without it, the child inherits the environment of this// process.Optional<Vector<ByteString>> environment {};diff --git a/Libraries/LibCore/ProcessWindows.cpp b/Libraries/LibCore/ProcessWindows.cppindex 1c6b502e840..dd217242525 100644--- a/Libraries/LibCore/ProcessWindows.cpp+++ b/Libraries/LibCore/ProcessWindows.cpp@@ -182,7 +182,7 @@ ErrorOr<Process> Process::spawn(StringView path, ReadonlySpan<ByteString> argume{return spawn({.executable = path,- .arguments = Vector<ByteString> { arguments },+ .arguments = arguments,});}diff --git a/Libraries/LibCore/StatsLog.cpp b/Libraries/LibCore/StatsLog.cppnew file mode 100644index 00000000000..3893e7085d9--- /dev/null+++ b/Libraries/LibCore/StatsLog.cpp@@ -0,0 +1,138 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/LexicalPath.h>+#include <AK/StringBuilder.h>+#include <AK/Time.h>+#include <LibCore/Directory.h>+#include <LibCore/EventLoop.h>+#include <LibCore/File.h>+#include <LibCore/StatsLog.h>+#include <LibCore/System.h>+#include <LibCore/Timer.h>++#if !__has_feature(address_sanitizer) && !defined(__SANITIZE_ADDRESS__) && !defined(HAS_THREAD_SANITIZER)+# include <mimalloc.h>+#endif++#if defined(__GLIBC__)+# if __GLIBC_PREREQ(2, 33)+# include <malloc.h>+# define HAVE_MALLINFO2 1+# endif+#endif++namespace Core {++// NB: Not a static data member, since a thread-local member of a DLL-exported class cannot be exported.+static constinit thread_local StatsLog* s_instance = nullptr;++StatsLog* StatsLog::the()+{+ return s_instance;+}++ErrorOr<OwnPtr<StatsLog>> StatsLog::create(StringView directory, StringView process_name)+{+ if (directory.is_empty())+ return OwnPtr<StatsLog> {};+ if (!LexicalPath(directory).is_absolute())+ return Error::from_string_literal("--stats-log-dir must be an absolute path");+ VERIFY(!s_instance);+ if (auto result = Directory::create(directory, Directory::CreateDirectories::Yes); result.is_error()) {+ warnln("Could not create stats log directory '{}': {}", directory, result.error());+ return result.release_error();+ }+ auto path = ByteString::formatted("{}/{}.{}.jsonl", directory, process_name, System::getpid());+ auto file = File::open(path, File::OpenMode::Write | File::OpenMode::Append | File::OpenMode::NoFollow | File::OpenMode::Nonblocking, 0600);+ if (file.is_error()) {+ warnln("Could not open stats log '{}': {}", path, file.error());+ return file.release_error();+ }+ if (!S_ISREG(TRY(file.value()->stat()).st_mode)) {+ warnln("Stats log '{}' is not a regular file", path);+ return Error::from_string_literal("Stats log must be a regular file");+ }+ return adopt_own(*new StatsLog(directory, move(path), process_name, file.release_value()));+}++StatsLog::StatsLog(ByteString directory, ByteString path, ByteString process_name, NonnullOwnPtr<File> file)+ : m_directory(move(directory))+ , m_path(move(path))+ , m_process_name(move(process_name))+ , m_file(move(file))+{+ s_instance = this;+ warnln("Stats log: {}", m_path);+}++StatsLog::~StatsLog()+{+ if (m_timer)+ m_timer->stop();+ s_instance = nullptr;+}++void StatsLog::start_sampling(Function<void(JsonObject&)> collect_values)+{+ VERIFY(!m_timer);+ m_collect_values = move(collect_values);+ m_timer = Timer::create_repeating(AK::Duration::from_milliseconds(100), [this] { sample(); });+ m_timer->start();+ sample();+}++void StatsLog::sample()+{+ JsonObject values;+#if !__has_feature(address_sanitizer) && !defined(__SANITIZE_ADDRESS__) && !defined(HAS_THREAD_SANITIZER)+ size_t current_rss = 0, peak_rss = 0, current_commit = 0, peak_commit = 0;+ mi_process_info(nullptr, nullptr, nullptr, ¤t_rss, &peak_rss, ¤t_commit, &peak_commit, nullptr);+ values.set("mimalloc.current_rss_bytes"sv, current_rss);+ values.set("mimalloc.peak_rss_bytes"sv, peak_rss);+ values.set("mimalloc.current_commit_bytes"sv, current_commit);+ values.set("mimalloc.peak_commit_bytes"sv, peak_commit);+#endif+#ifdef HAVE_MALLINFO2+ auto info = mallinfo2();+ values.set("malloc.arena_bytes"sv, info.arena);+ values.set("malloc.allocated_bytes"sv, info.uordblks);+ values.set("malloc.free_bytes"sv, info.fordblks);+ values.set("malloc.mmap_bytes"sv, info.hblkhd);+#endif+ if (m_collect_values)+ m_collect_values(values);+ JsonObject record;+ record.set("type"sv, "sample"sv);+ record.set("values"sv, move(values));+ write_record(move(record));+}++void StatsLog::event(StringView name, JsonObject data)+{+ JsonObject record;+ record.set("type"sv, "event"sv);+ record.set("name"sv, name);+ record.set("data"sv, move(data));+ write_record(move(record));+}++void StatsLog::write_record(JsonObject record)+{+ record.set("time_ns"sv, MonotonicTime::now().nanoseconds());+ record.set("process"sv, m_process_name.view());+ record.set("pid"sv, System::getpid());+ StringBuilder builder;+ record.serialize(builder);+ builder.append('\n');+ if (auto result = m_file->write_until_depleted(builder.string_view().bytes()); result.is_error()) {+ warnln("Could not write stats log '{}': {}", m_path, result.error());+ // A partial timeline must not be mistaken for a successful measurement.+ EventLoop::current().quit(1);+ }+}++}diff --git a/Libraries/LibCore/StatsLog.h b/Libraries/LibCore/StatsLog.hnew file mode 100644index 00000000000..9fa433c94d9--- /dev/null+++ b/Libraries/LibCore/StatsLog.h@@ -0,0 +1,50 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/ByteString.h>+#include <AK/Function.h>+#include <AK/JsonObject.h>+#include <AK/OwnPtr.h>+#include <AK/RefPtr.h>+#include <LibCore/Export.h>+#include <LibCore/Forward.h>++namespace Core {++// Owned by the process's main thread. Sampling and events run on that thread's event loop.+class CORE_API StatsLog {+ AK_MAKE_NONCOPYABLE(StatsLog);+ AK_MAKE_NONMOVABLE(StatsLog);++public:+ AK_ALLOC_WITH_KMALLOC;++ // An empty directory leaves logging disabled, without opening a file or creating a timer.+ static ErrorOr<OwnPtr<StatsLog>> create(StringView directory, StringView process_name);+ static StatsLog* the();+ ~StatsLog();++ StringView directory() const { return m_directory; }+ StringView path() const { return m_path; }+ void start_sampling(Function<void(JsonObject&)> = {});+ void event(StringView name, JsonObject data);++private:+ StatsLog(ByteString directory, ByteString path, ByteString process_name, NonnullOwnPtr<File>);+ void sample();+ void write_record(JsonObject);++ ByteString m_directory;+ ByteString m_path;+ ByteString m_process_name;+ NonnullOwnPtr<File> m_file;+ RefPtr<Timer> m_timer;+ Function<void(JsonObject&)> m_collect_values;+};++}diff --git a/Libraries/LibDevTools/FirefoxClient.cpp b/Libraries/LibDevTools/FirefoxClient.cppindex ad29ae353a3..c8548f9dba3 100644--- a/Libraries/LibDevTools/FirefoxClient.cpp+++ b/Libraries/LibDevTools/FirefoxClient.cpp@@ -109,7 +109,7 @@ static bool flatpak_firefox_is_installed(LexicalPath const& flatpak).name = "find-firefox-flatpak"sv,.executable = flatpak.string(),.die_with_parent = true,- .arguments = {+ .arguments = Vector<ByteString> {"info"sv,"org.mozilla.firefox"sv,},diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 4b3a3d7332a..687e2efcacb 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -25,6 +25,7 @@#include <LibCore/ElapsedTimer.h>#include <LibCore/File.h>#include <LibCore/StandardPaths.h>+#include <LibCore/StatsLog.h>#include <LibCore/Timer.h>#include <LibGC/BlockAllocator.h>#include <LibGC/CellAllocator.h>@@ -319,6 +320,51 @@ Heap::~Heap()m_incoming_cross_heap_members.clear();}+void Heap::enable_stats()+{+ VERIFY(!m_stats);+ VERIFY(!is_incremental_sweep_active());+ m_stats = make<Stats>();+}++void Heap::add_stats(AK::JsonObject& values) const+{+ VERIFY(m_stats);+ values.set("gc.allocated_bytes_total"sv, m_total_allocated_bytes);+ values.set("gc.allocated_bytes_since_gc"sv, m_allocated_bytes_since_last_gc);+ values.set("gc.heap_blocks"sv, m_live_heap_blocks.size());+ values.set("gc.heap_block_bytes"sv, m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE);+ values.set("gc.cell_allocators"sv, m_cell_allocators_by_type.size());+ values.set("gc.threshold_bytes"sv, m_gc_bytes_threshold);+ values.set("gc.live_cell_bytes"sv, m_stats->live_cell_bytes);+ values.set("gc.live_external_bytes"sv, m_stats->live_external_bytes);+ values.set("gc.collections"sv, m_stats->collections);+ values.set("gc.completed_collections"sv, m_stats->completed_collections);+ values.set("gc.total_duration_ns"sv, m_stats->total_duration_ns);+ values.set("gc.last_duration_ns"sv, m_stats->last_duration_ns);+}++void Heap::finish_stats_collection()+{+ VERIFY(m_stats);+ auto& stats = *m_stats;+ stats.last_duration_ns = stats.pause_duration_ns + stats.sweep_duration_ns;+ stats.total_duration_ns += stats.last_duration_ns;+ ++stats.completed_collections;+ if (auto* log = Core::StatsLog::the()) {+ AK::JsonObject data;+ data.set("collection"sv, stats.collections);+ data.set("duration_ns"sv, stats.last_duration_ns);+ data.set("pause_duration_ns"sv, stats.pause_duration_ns);+ data.set("sweep_duration_ns"sv, stats.sweep_duration_ns);+ data.set("bytes_before"sv, stats.bytes_before);+ data.set("bytes_after"sv, m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE);+ data.set("live_cell_bytes"sv, stats.live_cell_bytes);+ data.set("live_external_bytes"sv, stats.live_external_bytes);+ log->event("gc"sv, move(data));+ }+}+void Heap::will_allocate(size_t size, TriggersCollection triggers_collection){ASSERT(!heap_access_is_forbidden_on_this_thread());@@ -367,6 +413,10 @@ void Heap::did_free_external_memory(size_t size)void Heap::update_gc_bytes_threshold(size_t live_cell_bytes, size_t live_external_bytes){+ if (m_stats) {+ m_stats->live_cell_bytes = live_cell_bytes;+ m_stats->live_external_bytes = live_external_bytes;+ }Checked<size_t> live_bytes = live_cell_bytes;live_bytes += live_external_bytes;@@ -678,6 +728,7 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, CollectiVERIFY(!m_collecting_garbage);finish_pending_incremental_sweep();+ auto stats_start_ns = m_stats ? MonotonicTime::now().nanoseconds() : 0;give_back_local_free_lists();g_next_incremental_sweep_should_report = false;@@ -699,11 +750,16 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti}ScopeGuard stop_recording = [&] { g_recording_phase_timings = false; };+ if (collection_type == CollectionType::CollectGarbage && m_gc_deferrals) {+ m_should_gc_when_deferral_ends = true;+ return;+ }+ if (m_stats) {+ ++m_stats->collections;+ m_stats->bytes_before = m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE;+ m_stats->sweep_duration_ns = 0;+ }if (collection_type == CollectionType::CollectGarbage) {- if (m_gc_deferrals) {- m_should_gc_when_deferral_ends = true;- return;- }HashMap<Cell*, HeapRoot> roots;{ScopedPhaseTimer timer { report, g_phase_timings.gather_roots_us };@@ -747,6 +803,12 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collectielseg_next_incremental_sweep_should_report = false;+ if (m_stats) {+ m_stats->pause_duration_ns = MonotonicTime::now().nanoseconds() - stats_start_ns;+ if (!m_incremental_sweep_active)+ finish_stats_collection();+ }+run_post_gc_tasks();// A collection just happened: restart the idle policy's episode (peak rate and watchdog tick count) from here, so@@ -1348,6 +1410,13 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measurevoid Heap::sweep_block(HeapBlock& block){+ // A destructor can allocate and sweep another block. Its time is included in the outermost sweep.+ bool record_stats = m_stats && m_block_sweeps_in_progress == 0;+ auto stats_start_ns = record_stats ? MonotonicTime::now().nanoseconds() : 0;+ ScopeGuard record_duration = [&] {+ if (record_stats)+ m_stats->sweep_duration_ns += MonotonicTime::now().nanoseconds() - stats_start_ns;+ };++m_block_sweeps_in_progress;ScopeGuard finish_block_sweep = [&] { --m_block_sweeps_in_progress; };@@ -1473,6 +1542,8 @@ void Heap::finish_incremental_sweep()m_cells_allocated_during_sweep.clear();m_incremental_sweep_active = false;+ if (m_stats)+ finish_stats_collection();stop_incremental_sweep_timer();diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex 3092def6ac6..d46a16454eb 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -11,6 +11,7 @@#include <AK/HashTable.h>#include <AK/Noncopyable.h>#include <AK/NonnullOwnPtr.h>+#include <AK/OwnPtr.h>#include <AK/RefPtr.h>#include <AK/StackInfo.h>#include <AK/String.h>@@ -118,6 +119,9 @@ public:void did_create_weak_container(Badge<WeakContainer>, WeakContainer&);void did_destroy_weak_container(Badge<WeakContainer>, WeakContainer&);+ void enable_stats();+ void add_stats(AK::JsonObject&) const;+void register_sweep_callback(AK::Function<void()>);void register_cell_allocator(Badge<CellAllocator>, CellAllocator&);@@ -152,6 +156,7 @@ private:void undefer_gc();void dump_allocators();+ void finish_stats_collection();template<typename T, typename... Args>Ref<T> construct_cell(Cell* memory, Args&&... args)@@ -268,6 +273,21 @@ private:}}+ struct Stats {+ AK_ALLOC_WITH_KMALLOC;++ u64 collections { 0 };+ u64 completed_collections { 0 };+ u64 total_duration_ns { 0 };+ u64 last_duration_ns { 0 };+ u64 pause_duration_ns { 0 };+ u64 sweep_duration_ns { 0 };+ size_t bytes_before { 0 };+ size_t live_cell_bytes { 0 };+ size_t live_external_bytes { 0 };+ };+ OwnPtr<Stats> m_stats;+size_t m_gc_bytes_threshold { 0 };size_t m_allocated_bytes_since_last_gc { 0 };diff --git a/Libraries/LibGfx/SkiaBackendContext.cpp b/Libraries/LibGfx/SkiaBackendContext.cppindex 46be8d07047..eca5ca75673 100644--- a/Libraries/LibGfx/SkiaBackendContext.cpp+++ b/Libraries/LibGfx/SkiaBackendContext.cpp@@ -131,6 +131,14 @@ void SkiaBackendContext::perform_post_flush_cleanup()context->purgeUnlockedResources(GrPurgeResourceOptions::kScratchResourcesOnly);}+size_t SkiaBackendContext::resource_cache_bytes() const+{+ size_t bytes = 0;+ if (auto* context = sk_context())+ context->getResourceCacheUsage(nullptr, &bytes);+ return bytes;+}+void SkiaBackendContext::initialize_gpu_backend(){VERIFY(!main_thread_context());diff --git a/Libraries/LibGfx/SkiaBackendContext.h b/Libraries/LibGfx/SkiaBackendContext.hindex 76b38884d6c..806529ba1da 100644--- a/Libraries/LibGfx/SkiaBackendContext.h+++ b/Libraries/LibGfx/SkiaBackendContext.h@@ -59,6 +59,7 @@ public:void flush_and_submit(PaintingSurface&);void flush_and_submit_async(PaintingSurface&, Function<void()>&&);void check_async_work_completion();+ size_t resource_cache_bytes() const;virtual GrDirectContext* sk_context() const = 0;virtual MetalContext& metal_context() = 0;diff --git a/Libraries/LibSandbox/CMakeLists.txt b/Libraries/LibSandbox/CMakeLists.txtindex 960a4162519..5c940a5b80b 100644--- a/Libraries/LibSandbox/CMakeLists.txt+++ b/Libraries/LibSandbox/CMakeLists.txt@@ -12,6 +12,6 @@ endif()ladybird_lib(LibSandbox sandbox)-if (LINUX)+if (LINUX OR APPLE)target_link_libraries(LibSandbox PRIVATE LibCore)endif()diff --git a/Libraries/LibSandbox/Sandbox.cpp b/Libraries/LibSandbox/Sandbox.cppindex a1d1e3018c0..3c39d111267 100644--- a/Libraries/LibSandbox/Sandbox.cpp+++ b/Libraries/LibSandbox/Sandbox.cpp@@ -26,6 +26,7 @@#if defined(AK_OS_MACOS)# include <AK/LexicalPath.h># include <AK/StringBuilder.h>+# include <LibCore/StatsLog.h># include <errno.h># include <limits.h># include <sandbox.h>@@ -715,6 +716,12 @@ ErrorOr<void> apply_macos_sandbox(SeatbeltProfile const& options)TRY(append_allowed_ancestor_directories(profile, options.paths));TRY(append_allowed_paths(profile, "file-map-executable"sv, options.paths, SeatbeltPath::Access::ReadAndExecute));TRY(append_allowed_paths(profile, "file-write*"sv, options.paths, SeatbeltPath::Access::ReadWrite));+ if (auto* log = Core::StatsLog::the()) {+ Vector<SeatbeltPath> log_paths;+ TRY(add_seatbelt_path_if_exists(log_paths, log->path(), SeatbeltPath::Access::ReadWrite));+ // Only append to this process's already-open log, without granting access to the statistics directory.+ TRY(append_allowed_paths(profile, "file-write-data"sv, log_paths, SeatbeltPath::Access::ReadWrite));+ }TRY(append_allowed_paths(profile, "file-lock"sv, options.paths, SeatbeltPath::Access::ReadWrite));TRY(append_allowed_path_extensions(profile, options.paths, SeatbeltPath::Access::ReadOnly));TRY(append_allowed_path_extensions(profile, options.paths, SeatbeltPath::Access::ReadWrite));diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cppindex 63395b14da9..eaa0a333f96 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp@@ -7,6 +7,7 @@#include <AK/AnyOf.h>#include <AK/Debug.h>+#include <AK/JsonObject.h>#include <AK/TemporaryChange.h>#include <LibCore/EventLoop.h>#include <LibGC/Heap.h>@@ -17,6 +18,7 @@#include <LibWeb/CSS/CSSTransition.h>#include <LibWeb/CSS/FontFaceSet.h>#include <LibWeb/CSS/StyleComputer.h>+#include <LibWeb/CSS/StyleScope.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/HTML/AnimationFrameCallbackDriver.h>@@ -25,6 +27,7 @@#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/EventLoop/FrameCompletion.h>#include <LibWeb/HTML/HTMLMediaElement.h>+#include <LibWeb/HTML/ListOfAvailableImages.h>#include <LibWeb/HTML/LocalTraversableNavigable.h>#include <LibWeb/HTML/NavigableContainer.h>#include <LibWeb/HTML/Scripting/Agent.h>@@ -1591,6 +1594,31 @@ void EventLoop::register_document(Badge<DOM::Document>, DOM::Document& document)m_documents_sort_dirty = true;}+void EventLoop::add_stats(JsonObject& values) const+{+ // NB: Read container sizes from the existing document registry, without sorting it or walking any trees.+ size_t available_images = 0;+ size_t shared_image_requests = 0;+ size_t style_sheets = 0;+ size_t font_faces = 0;+ for (auto const& document : m_documents) {+ if (!document)+ continue;+ available_images += document->list_of_available_images().size();+ shared_image_requests += document->shared_resource_requests().size();+ style_sheets += document->style_scope().style_sheets().size();+ font_faces += document->fonts()->set_size();+ }+ values.set("dom.documents"sv, m_documents.size());+ values.set("images.available_entries"sv, available_images);+ values.set("images.shared_requests"sv, shared_image_requests);+ values.set("css.document_style_sheet_entries"sv, style_sheets);+ values.set("fonts.face_entries"sv, font_faces);+ values.set("rendering.updates"sv, m_rendering_scheduler_counters.updates_run);+ values.set("rendering.paints"sv, m_rendering_scheduler_counters.paints);+ values.set("rendering.update_duration_us"sv, m_rendering_scheduler_counters.update_microseconds);+}+void EventLoop::unregister_document(Badge<DOM::Document>, DOM::Document& document){bool did_remove = m_documents.remove_first_matching([&](auto& entry) { return entry.ptr().ptr() == &document; });diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h b/Libraries/LibWeb/HTML/EventLoop/EventLoop.hindex 4df98907127..eb83ef14266 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.h+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.h@@ -6,6 +6,7 @@#pragma once+#include <AK/Forward.h>#include <AK/Function.h>#include <AK/Noncopyable.h>#include <AK/OwnPtr.h>@@ -134,6 +135,7 @@ public:void document_navigable_did_change(Badge<DOM::Document>);[[nodiscard]] Vector<GC::Root<DOM::Document>> documents_in_this_event_loop_matching(Function<bool(DOM::Document&)> callback) const;+ void add_stats(JsonObject&) const;Vector<GC::Root<HTML::Window>> same_loop_windows() const;diff --git a/Libraries/LibWeb/HTML/ListOfAvailableImages.h b/Libraries/LibWeb/HTML/ListOfAvailableImages.hindex 72b55d3540c..bc3604a5681 100644--- a/Libraries/LibWeb/HTML/ListOfAvailableImages.h+++ b/Libraries/LibWeb/HTML/ListOfAvailableImages.h@@ -58,6 +58,7 @@ public:void remove(Key const&);void prune_to_limits(size_t external_memory_limit, size_t count_limit);[[nodiscard]] Entry* get(Key const&);+ size_t size() const { return m_images.size(); }void visit_edges(JS::Cell::Visitor& visitor) override;diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cppindex f4da534b1a4..c4e749f2239 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp@@ -13,6 +13,7 @@#include <AK/FFIHelpers.h>#include <AK/NeverDestroyed.h>#include <AK/UnicodeUtils.h>+#include <LibCore/StatsLog.h>#include <LibGC/Heap.h>#include <LibGC/RootVector.h>#include <LibTextCodec/Decoder.h>@@ -63,6 +64,7 @@#include <LibWeb/HTMLTokenizerRustFFI.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Namespace.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/SVG/SVGDecodedImageData.h>#include <LibWeb/SVG/SVGScriptElement.h>@@ -833,6 +835,22 @@ void HTMLParserEndState::check_progress()}}+static void log_document_stats_event(DOM::Document const& document, StringView name)+{+ auto* log = Core::StatsLog::the();+ if (!log || document.is_decoded_svg() || !document.is_active())+ return;+ auto navigable = document.navigable();+ if (!navigable || !navigable->is_top_level_traversable())+ return;+ JsonObject data;+ data.set("page_id"sv, document.page().client().id().value());+ data.set("navigable_id"sv, MUST(String::formatted("{}", navigable->id())));+ data.set("document_id"sv, MUST(String::formatted("{}", document.id())));+ data.set("url"sv, document.url().serialize());+ log->event(name, move(data));+}+void HTMLParserEndState::advance_to_dom_content_loaded_phase(){// AD-HOC: We need to scroll to the fragment on page load somewhere.@@ -860,6 +878,9 @@ void HTMLParserEndState::advance_to_dom_content_loaded_phase()// 1. Set the Document's load timing info's DOM content loaded event start time to the current high resolution time given the Document's relevant global object.document->load_timing_info().dom_content_loaded_event_start_time = HighResolutionTime::current_high_resolution_time(relevant_global_object(*document));+ if (Core::StatsLog::the())+ log_document_stats_event(*document, "DOMContentLoaded"sv);+// 2. Fire an event named DOMContentLoaded at the Document object, with its bubbles attribute initialized to true.auto content_loaded_event = DOM::Event::create(HTML::EventNames::DOMContentLoaded,@@ -964,6 +985,9 @@ void HTMLParserEndState::complete()// 4. Set the Document's load timing info's load event start time to the current high resolution time given window.document->load_timing_info().load_event_start_time = HighResolutionTime::current_high_resolution_time(relevant_global_object(window));+ if (Core::StatsLog::the())+ log_document_stats_event(*document, "load"sv);+// 5. Fire an event named load at window, with legacy target override flag set.// FIXME: The legacy target override flag is currently set by a virtual override of dispatch_event()// We should reorganize this so that the flag appears explicitly here instead.diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 4df69efc71f..4ecf3d70f97 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -19,6 +19,7 @@#include <LibCore/Environment.h>#include <LibCore/File.h>#include <LibCore/StandardPaths.h>+#include <LibCore/StatsLog.h>#include <LibCore/System.h>#include <LibCore/TimeZoneWatcher.h>#include <LibCore/Timer.h>@@ -301,6 +302,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)Optional<StringView> screenshot_path;bool new_window = false;bool force_new_process = false;+ StringView stats_log_directory;Optional<StringView> profile_name;Optional<StringView> profile_path;bool temporary_profile = false;@@ -387,6 +389,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)args_parser.add_option(new_window, "Force opening in a new window", "new-window", 'n');#if !defined(AK_OS_ANDROID)args_parser.add_option(force_new_process, "Force creation of a new browser process", "force-new-process");+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(profile_name, "Select or create a named profile", "profile", 0, "name");args_parser.add_option(profile_path, "Use a self-contained profile at an absolute path", "profile-path", 0, "path");args_parser.add_option(temporary_profile, "Use a temporary profile that is removed on clean shutdown", "temporary-profile");@@ -492,6 +495,8 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)create_platform_arguments(args_parser);args_parser.parse(m_arguments);+ m_stats_log = TRY(Core::StatsLog::create(stats_log_directory, "Ladybird"sv));+#if !defined(AK_OS_ANDROID)ProfileSelection profile_selection;if (force_new_process) {@@ -529,8 +534,9 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)m_profile = TRY(Profile::create(profile_selection, profile_roots));#endif- // Browsers launched by WebDriver are driven directly and must never join an existing browser process.- bool coordinate_browser_process = !headless_mode.has_value() && !webdriver_browser_endpoint.has_value() && should_coordinate_browser_process();+ // Browsers launched by WebDriver are driven directly and must never join an existing browser process. A browser+ // that logs process statistics must not join one either, since that browser would not sample them.+ bool coordinate_browser_process = !headless_mode.has_value() && !webdriver_browser_endpoint.has_value() && !m_stats_log && should_coordinate_browser_process();// Synchronous IPC used to forward URLs to an existing browser process requires an event loop.if (coordinate_browser_process) {@@ -727,6 +733,8 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)// NB: The host's thread makes an event loop, which would install the default event loop manager if the platform// one were not installed yet.m_font_service_host = FontServiceHost::create(*m_font_service);+ if (m_stats_log)+ m_stats_log->start_sampling();TRY(launch_services());if (m_web_content_options.is_test_mode == IsTestMode::No && m_browser_options.enable_content_blocker == EnableContentBlocker::Yes) {diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex 6e6fee447a1..116f57d1b3f 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -589,6 +589,7 @@ private:OwnPtr<AutocompleteService> m_autocomplete_service;Main::Arguments m_arguments;+ OwnPtr<Core::StatsLog> m_stats_log;BrowserOptions m_browser_options;Optional<Core::Process> m_cpu_profiler_process;OwnPtr<Core::File> m_cpu_profiler_control_socket;diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cppindex 91dea60a763..2320365f787 100644--- a/Libraries/LibWebView/CanonicalNavigable.cpp+++ b/Libraries/LibWebView/CanonicalNavigable.cpp@@ -8,6 +8,7 @@#include <AK/AnyOf.h>#include <AK/Random.h>+#include <LibCore/StatsLog.h>#include <LibWebCommon/HTML/BrowsingContext.h>#include <LibWebCommon/HTML/HistoryOperation.h>#include <LibWebCommon/HTML/SerializationRecords.h>@@ -1310,6 +1311,14 @@ void CanonicalNavigable::set_the_ongoing_navigation(OngoingNavigation value)void CanonicalNavigable::set_ongoing_navigation(CanonicalNavigation::Start navigation){+ if (auto* log = Core::StatsLog::the(); log && is_top_level_traversable()) {+ JsonObject data;+ data.set("navigable_id"sv, MUST(String::formatted("{}", id())));+ data.set("navigation_id"sv, navigation.navigation_id.to_utf8());+ data.set("url"sv, navigation.url.serialize());+ log->event("navigation_start"sv, move(data));+ }+// NB: Taken before the handle covering this navigation's start is dropped below, so that a revoked entry is not// let go of in between.auto blob_url = BlobURLHandle::for_url(blob_url_store(), navigation.url);diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex 455c47c2a14..1e2c00a9ae0 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -188,7 +188,7 @@ static ErrorOr<pid_t> launch_helper_process(StringView server_name, Vector<ByteSfor (auto [i, path] : enumerate(candidate_server_paths)) {auto process_arguments = arguments;- Core::ProcessSpawnOptions options { .name = server_name, .arguments = process_arguments };+ Core::ProcessSpawnOptions options { .name = server_name };if (browser_options.profile_helper_process == process_type && browser_options.profile_tool == ProfileTool::Callgrind) {options.executable = "valgrind"sv;@@ -242,6 +242,7 @@ static ErrorOr<pid_t> launch_helper_process(StringView server_name, Vector<ByteS}#endif+ options.arguments = process_arguments;bool capture_output = WebView::Application::the().should_capture_web_content_output();auto result = spawn(options, capture_output);diff --git a/Libraries/LibWebView/Process.cpp b/Libraries/LibWebView/Process.cppindex 3637ef5a448..3d634d70b17 100644--- a/Libraries/LibWebView/Process.cpp+++ b/Libraries/LibWebView/Process.cpp@@ -11,6 +11,7 @@#include <LibCore/Process.h>#include <LibCore/Socket.h>#include <LibCore/StandardPaths.h>+#include <LibCore/StatsLog.h>#include <LibCore/System.h>#include <LibFileSystem/FileSystem.h>#include <LibWebView/Process.h>@@ -180,8 +181,14 @@ ErrorOr<Process::ProcessAndIPCTransport> Process::spawn_and_connect_to_process([Array<int, 2> stdout_pipe {};Array<int, 2> stderr_pipe {};- Core::ProcessSpawnOptions spawn_options = options;+ auto spawn_options = options;spawn_options.die_with_parent = true;+ Vector<ByteString> arguments_with_stats;+ if (auto* stats_log = Core::StatsLog::the()) {+ arguments_with_stats = Vector<ByteString> { options.arguments };+ arguments_with_stats.append(ByteString::formatted("--stats-log-dir={}", stats_log->directory()));+ spawn_options.arguments = arguments_with_stats;+ }#if defined(AK_OS_MACOS) || defined(AK_OS_LINUX)spawn_options.environment = helper_process_environment(type);#endifdiff --git a/Services/AudioServer/main.cpp b/Services/AudioServer/main.cppindex 6c0bf9ca9ec..6f9d021fa53 100644--- a/Services/AudioServer/main.cpp+++ b/Services/AudioServer/main.cpp@@ -17,6 +17,7 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibCore/StatsLog.h>#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>#include <LibSandbox/ConnectBroker.h>@@ -32,7 +33,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool disable_sandbox = false;bool is_headless = false;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");args_parser.add_option(connect_broker_fd, "Descriptor for the sandbox connection broker", "connect-broker-fd", 0, "fd");args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");@@ -41,6 +44,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(is_headless, "Discard the mixed output instead of playing it", "headless");args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "AudioServer"sv));+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());@@ -82,5 +87,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto client = TRY(IPC::take_over_accepted_client_from_system_server<AudioServer::ControlConnection>(mach_server_name));AudioServer::Tabs::the().set_control_connection(*client);+ if (stats_log)+ stats_log->start_sampling();+return event_loop.exec();}diff --git a/Services/Compositor/main.cpp b/Services/Compositor/main.cppindex 114f36f3627..d2b348e7970 100644--- a/Services/Compositor/main.cpp+++ b/Services/Compositor/main.cpp@@ -13,6 +13,7 @@#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>#include <LibCore/ResourceImplementationFile.h>+#include <LibCore/StatsLog.h>#include <LibGfx/Font/Font.h>#include <LibGfx/Font/FontDatabase.h>#include <LibGfx/GpuDeviceIdentity.h>@@ -34,7 +35,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool disable_sandbox = false;int crash_report_fd = -1;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");args_parser.add_option(cache_path, "Path to the profile cache", "cache-path", 0, "path");@@ -46,6 +49,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "Compositor"sv));+if (resource_root.is_empty())return Error::from_string_literal("--resource-root is required");@@ -95,5 +100,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)mach_server_name, move(skia_backend_context)));client->async_gpu_device_identity_reported(move(gpu_device_identity));+ if (stats_log)+ stats_log->start_sampling([](JsonObject& values) {+ if (auto context = Gfx::SkiaBackendContext::the_main_thread_context())+ values.set("gpu.skia_resource_cache_bytes"sv, context->resource_cache_bytes());+ });+return event_loop.exec();}diff --git a/Services/ImageDecoder/main.cpp b/Services/ImageDecoder/main.cppindex e2cc910ec40..598e1cd094e 100644--- a/Services/ImageDecoder/main.cpp+++ b/Services/ImageDecoder/main.cpp@@ -14,6 +14,7 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibCore/StatsLog.h>#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>@@ -22,7 +23,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)AK::set_rich_debug_enabled(true);int crash_report_fd = -1;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");StringView mach_server_name;bool wait_for_debugger = false;@@ -33,6 +36,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "ImageDecoder"sv));+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());@@ -53,5 +58,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto client = TRY(IPC::take_over_accepted_client_from_system_server<ImageDecoder::ConnectionFromClient>(mach_server_name));+ if (stats_log)+ stats_log->start_sampling();+return event_loop.exec();}diff --git a/Services/MediaServer/main.cpp b/Services/MediaServer/main.cppindex 6e2809ccc8a..d66d7842897 100644--- a/Services/MediaServer/main.cpp+++ b/Services/MediaServer/main.cpp@@ -11,6 +11,7 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibCore/StatsLog.h>#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>#include <LibMedia/DecoderRegistrations.h>@@ -31,13 +32,17 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool wait_for_debugger = false;bool disable_sandbox = false;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");args_parser.add_option(wait_for_debugger, "Wait for debugger", "wait-for-debugger");args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "MediaServer"sv));+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());@@ -75,5 +80,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)client->request_video_decoder_server_transport(move(callback));});+ if (stats_log)+ stats_log->start_sampling();+return event_loop.exec();}diff --git a/Services/RequestServer/main.cpp b/Services/RequestServer/main.cppindex f40605023bc..6777b8258a9 100644--- a/Services/RequestServer/main.cpp+++ b/Services/RequestServer/main.cpp@@ -15,6 +15,7 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibCore/StatsLog.h>#include <LibCore/System.h>#include <LibFileSystem/FileSystem.h>#include <LibHTTP/Cache/DiskCache.h>@@ -55,7 +56,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool disable_sandbox = false;int crash_report_fd = -1;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");args_parser.add_option(certificates, "Path to a certificate file", "certificate", 'C', "certificate");args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");@@ -67,6 +70,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "RequestServer"sv));+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());@@ -143,5 +148,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)request_transfer_leases,disk_cache));+ if (stats_log)+ stats_log->start_sampling([&](JsonObject& values) {+ values.set("requests.clients"sv, connections.size());+ values.set("requests.transfer_leases"sv, request_transfer_leases.size());+ });+return event_loop.exec();}diff --git a/Services/VideoDecoderServer/main.cpp b/Services/VideoDecoderServer/main.cppindex 7fac63835a8..7bdd6fc6b83 100644--- a/Services/VideoDecoderServer/main.cpp+++ b/Services/VideoDecoderServer/main.cpp@@ -11,6 +11,7 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibCore/StatsLog.h>#include <LibGfx/GpuDeviceIdentity.h>#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>@@ -45,6 +46,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)AK::set_rich_debug_enabled(true);int crash_report_fd = -1;+ StringView stats_log_directory;StringView mach_server_name;bool wait_for_debugger = false;bool disable_sandbox = false;@@ -52,6 +54,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)StringView gpu_device;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics logs", "stats-log-dir", 0, "directory");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");args_parser.add_option(wait_for_debugger, "Wait for debugger", "wait-for-debugger");@@ -74,6 +77,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)warnln("Could not set main thread QoS: {}", result.error());auto& event_loop = Core::EventLoop::initialize_for_current_thread();+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "VideoDecoderServer"sv));Optional<Gfx::GpuDeviceIdentity> gpu_device_identity;if (!gpu_device.is_empty()) {@@ -114,5 +118,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto client = TRY(IPC::take_over_accepted_client_from_system_server<VideoDecoderServer::ControlConnection>(mach_server_name, hosted_decoders));+ if (stats_log)+ stats_log->start_sampling();+return event_loop.exec();}diff --git a/Services/WasmCompiler/main.cpp b/Services/WasmCompiler/main.cppindex d4d5118fae2..b9c0b339cb5 100644--- a/Services/WasmCompiler/main.cpp+++ b/Services/WasmCompiler/main.cpp@@ -10,6 +10,7 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibCore/StatsLog.h>#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>#include <WasmCompiler/Compiler.h>@@ -21,7 +22,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)AK::set_rich_debug_enabled(true);int crash_report_fd = -1;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");StringView mach_server_name;bool wait_for_debugger = false;@@ -32,6 +35,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "WasmCompiler"sv));+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());@@ -54,5 +59,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto client = TRY(IPC::take_over_accepted_client_from_system_server<WasmCompiler::ConnectionFromClient>(mach_server_name, compiler, WasmCompiler::ConnectionFromClient::Role::Controller));+ if (stats_log)+ stats_log->start_sampling();+return event_loop.exec();}diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex 2f426a2c252..2a49b3db558 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -15,11 +15,13 @@#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>#include <LibCore/Resource.h>+#include <LibCore/StatsLog.h>#include <LibCore/System.h>#include <LibCore/TimeZone.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/OpenSSLForward.h>#include <LibGfx/Font/FontDatabase.h>+#include <LibGfx/Font/SystemFallbackFonts.h>#include <LibIPC/ConnectionFromClient.h>#include <LibIPC/TransportHandle.h>#include <LibMain/Main.h>@@ -30,6 +32,7 @@#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/Fetch/Fetching/Fetching.h>+#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/Internals/Internals.h>@@ -193,7 +196,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)StringView default_time_zone {};bool file_origins_are_tuple_origins = false;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");args_parser.add_option(enable_test_mode, "Enable test mode", "test-mode");args_parser.add_option(expose_experimental_interfaces, "Expose experimental IDL interfaces", "expose-experimental-interfaces");@@ -227,6 +232,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "WebContent"sv));+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());@@ -274,6 +281,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Web::HTML::WindowOrWorkerGlobalScopeMixin::set_experimental_interfaces_exposed(expose_experimental_interfaces);Web::Bindings::initialize_main_thread_vm(Web::HTML::AgentType::SimilarOriginWindow);+ if (stats_log)+ Web::Bindings::main_thread_vm().heap().enable_stats();if (collect_garbage_on_every_allocation)Web::Bindings::main_thread_vm().heap().set_should_collect_on_every_allocation(true);@@ -315,6 +324,14 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)};#endif+ if (stats_log) {+ stats_log->start_sampling([&heap](JsonObject& values) {+ heap.add_stats(values);+ Web::HTML::main_thread_event_loop().add_stats(values);+ values.set("fonts.system_fallback_cache_entries"sv, Gfx::system_fallback_font_cache_size());+ });+ }+return event_loop.exec();}diff --git a/Services/WebDriver/main.cpp b/Services/WebDriver/main.cppindex 1fa159cefec..f4d39027638 100644--- a/Services/WebDriver/main.cpp+++ b/Services/WebDriver/main.cpp@@ -12,6 +12,7 @@#include <LibCore/EventLoop.h>#include <LibCore/Process.h>#include <LibCore/StandardPaths.h>+#include <LibCore/StatsLog.h>#include <LibCore/System.h>#include <LibCore/TCPServer.h>#include <LibFileSystem/FileSystem.h>@@ -87,6 +88,9 @@ static Vector<ByteString> create_arguments(ByteString const& webdriver_endpoint,arguments.append(ByteString::formatted("--site-isolation={}", site_isolation_mode));+ if (auto* stats_log = Core::StatsLog::the())+ arguments.append(ByteString::formatted("--stats-log-dir={}", stats_log->directory()));+arguments.append("about:blank"sv);return arguments;}@@ -116,7 +120,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Optional<StringView> resource_substitution_map_path;StringView site_isolation_mode = "iframe"sv;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(listen_address, "IP address to listen on", "listen-address", 'l', "listen_address");args_parser.add_option(port, "Port to listen on", "port", 'p', "port");args_parser.add_option(certificates, "Path to a certificate file", "certificate", 'C', "certificate");@@ -145,6 +151,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)});args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "WebDriver"sv));+auto profile_selector_count = static_cast<unsigned>(profile_name.has_value())+ static_cast<unsigned>(profile_path.has_value())+ static_cast<unsigned>(profiles_directory.has_value());@@ -191,6 +199,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)}auto& loop = Core::EventLoop::initialize_for_current_thread();+ if (stats_log)+ stats_log->start_sampling();Core::EventLoop::register_signal(SIGINT, handle_signal);Core::EventLoop::register_signal(SIGTERM, handle_signal);auto server = TRY(Core::TCPServer::try_create());diff --git a/Services/WebWorker/main.cpp b/Services/WebWorker/main.cppindex 225b6556f78..e3b4142996a 100644--- a/Services/WebWorker/main.cpp+++ b/Services/WebWorker/main.cpp@@ -10,6 +10,7 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibCore/StatsLog.h>#include <LibCore/System.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/OpenSSLForward.h>@@ -71,7 +72,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool enable_test_mode = false;int crash_report_fd = -1;+ StringView stats_log_directory;Core::ArgsParser args_parser;+ args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");args_parser.add_option(serenity_resource_root, "Absolute path to directory for serenity resources", "serenity-resource-root", 'r', "serenity-resource-root");args_parser.add_option(certificates, "Path to a certificate file", "certificate", 'C', "certificate");@@ -99,6 +102,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.parse(arguments);+ auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "WebWorker"sv));+if (crash_report_fd >= 0) {if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())warnln("Could not install crash report handler: {}", result.error());@@ -131,6 +136,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Web::Platform::EventLoopPlugin::install(*new Web::Platform::EventLoopPlugin);Web::Bindings::initialize_main_thread_vm(worker_type);+ if (stats_log)+ Web::Bindings::main_thread_vm().heap().enable_stats();if (!disable_sandbox)TRY(RendererSandbox::apply_sandbox(mach_server_name));@@ -161,6 +168,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)};#endif+ if (stats_log)+ stats_log->start_sampling([&heap](JsonObject& values) { heap.add_stats(values); });+return event_loop.exec();}diff --git a/Tests/LibCore/TestLibCoreProcess.cpp b/Tests/LibCore/TestLibCoreProcess.cppindex 85af91dfc45..27c1c7254bb 100644--- a/Tests/LibCore/TestLibCoreProcess.cpp+++ b/Tests/LibCore/TestLibCoreProcess.cpp@@ -71,7 +71,7 @@ TEST_CASE(spawned_process_only_inherits_the_standard_streams_and_the_given_descrSTDERR_FILENO, unrelated[0], given_child_fd);auto output = run_and_read_output({.executable = "/bin/sh"sv,- .arguments = { "-c"sv, script },+ .arguments = Vector<ByteString> { "-c"sv, script },.file_actions = { Core::FileAction::DupFd { .write_fd = given[0], .fd = given_child_fd } },});@@ -88,7 +88,7 @@ TEST_CASE(spawned_process_gets_a_close_on_exec_descriptor_duplicated_onto_itselfauto script = ByteString::formatted("if {{ true >&{}; }} 2>/dev/null; then echo open; else echo closed; fi", given[1]);auto output = run_and_read_output({.executable = "/bin/sh"sv,- .arguments = { "-c"sv, script },+ .arguments = Vector<ByteString> { "-c"sv, script },.file_actions = { Core::FileAction::DupFd { .write_fd = given[1], .fd = given[1] } },});diff --git a/Tests/LibWeb/test-web/main.cpp b/Tests/LibWeb/test-web/main.cppindex f717a289dfe..645fc6b86bf 100644--- a/Tests/LibWeb/test-web/main.cpp+++ b/Tests/LibWeb/test-web/main.cpp@@ -831,7 +831,7 @@ static void run_screenshot_test(TestWebView& view, TestRunContext& context, Testauto optipng_or_error = Core::Process::spawn({.executable = "optipng"sv,.search_for_executable_in_path = true,- .arguments = { "-strip"sv, "all"sv, test.expectation_path },+ .arguments = Vector<ByteString> { "-strip"sv, "all"sv, test.expectation_path },});if (optipng_or_error.is_error()) {warnln("Warning: Failed to run optipng: {}", optipng_or_error.error());diff --git a/Utilities/wasm.cpp b/Utilities/wasm.cppindex 25cdd948940..a60ec6ab50c 100644--- a/Utilities/wasm.cpp+++ b/Utilities/wasm.cpp@@ -1132,14 +1132,14 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments).name = "ndisasm"sv,.executable = "ndisasm"sv,.search_for_executable_in_path = true,- .arguments = { "-b"sv, (sizeof(void*) == sizeof(u64) ? "64"sv : "32"sv), tmp_path },+ .arguments = Vector<ByteString> { "-b"sv, (sizeof(void*) == sizeof(u64) ? "64"sv : "32"sv), tmp_path },});#elif defined(AK_OS_MACOS)auto cmd = ByteString::formatted("/usr/bin/objdump -d {} | tail -n +7", tmp_path);auto result = Core::Process::spawn({.name = "sh"sv,.executable = "/bin/sh"sv,- .arguments = { "-c"sv, cmd },+ .arguments = Vector<ByteString> { "-c"sv, cmd },});#else# if ARCH(X86_64)@@ -1152,7 +1152,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto result = Core::Process::spawn({.name = "sh"sv,.executable = "/bin/sh"sv,- .arguments = { "-c"sv, cmd },+ .arguments = Vector<ByteString> { "-c"sv, cmd },});#endifif (!result.is_error())