Skip to content

Truly independent web browser

LibCore: Report a process's own memory on Linux

Andreas Klingfd187520a96b
diff --git a/Libraries/LibCore/Platform/ProcessStatisticsLinux.cpp b/Libraries/LibCore/Platform/ProcessStatisticsLinux.cpp
index 1482b626180..4208f14197c 100644
--- a/Libraries/LibCore/Platform/ProcessStatisticsLinux.cpp
+++ b/Libraries/LibCore/Platform/ProcessStatisticsLinux.cpp
@@ -15,9 +15,55 @@
namespace Core::Platform {
static auto user_hz = sysconf(_SC_CLK_TCK);
-static auto page_size = sysconf(_SC_PAGESIZE);
static auto ncpu_online = sysconf(_SC_NPROCESSORS_ONLN);
+// The memory a process keeps alive: its anonymous and shared memory pages, and what it has in swap. Pages of files are
+// the page cache's, shared with every other process that maps the same libraries, so they are left out.
+// NB: Shared memory counts in every process that maps it. Decoded images and backing stores live there, so leaving it
+// out would hide most of the memory a renderer spends on pixels.
+// NB: Pages freed with MADV_FREE stay counted until the kernel reclaims them. Only /proc/pid/smaps_rollup tells them
+// apart, and reading it walks every page of the process, which takes tens of milliseconds for a large one.
+static Optional<u64> own_memory_bytes(pid_t pid)
+{
+ auto file = Core::File::open(ByteString::formatted("/proc/{}/status", pid), Core::File::OpenMode::Read);
+ if (file.is_error())
+ return {};
+ auto contents = file.value()->read_until_eof();
+ if (contents.is_error())
+ return {};
+
+ Optional<u64> anonymous_kib;
+ Optional<u64> shared_memory_kib;
+ Optional<u64> swap_kib;
+ StringView { contents.value() }.for_each_split_view('\n', SplitBehavior::Nothing, [&](StringView line) {
+ auto parse_kib = [&](StringView name) -> Optional<u64> {
+ if (!line.starts_with(name))
+ return {};
+ auto value = line.substring_view(name.length()).trim_whitespace();
+ if (!value.ends_with(" kB"sv))
+ return {};
+ return value.substring_view(0, value.length() - 3).trim_whitespace().to_number<u64>();
+ };
+ if (auto value = parse_kib("RssAnon:"sv); value.has_value())
+ anonymous_kib = value;
+ else if (auto value = parse_kib("RssShmem:"sv); value.has_value())
+ shared_memory_kib = value;
+ else if (auto value = parse_kib("VmSwap:"sv); value.has_value())
+ swap_kib = value;
+ });
+ if (!anonymous_kib.has_value() || !shared_memory_kib.has_value())
+ return {};
+
+ Checked<u64> bytes = *anonymous_kib;
+ bytes += *shared_memory_kib;
+ // NB: A kernel without swap support may leave the line out.
+ bytes += swap_kib.value_or(0);
+ bytes *= 1024;
+ if (bytes.has_overflow())
+ return {};
+ return bytes.value();
+}
+
ErrorOr<void> update_process_statistics(ProcessStatistics& statistics)
{
// Read the total time scheduled from /proc/stat, and each process's usage from /proc/pid/stat
@@ -54,16 +100,16 @@ ErrorOr<void> update_process_statistics(ProcessStatistics& statistics)
auto proc_pid_stat = proc_pid_stat_or_error.release_value();
line = TRY(proc_pid_stat->read_some(buffer));
- // We only care about fields 14 (utime), 15 (stime), and 24 (rss)
+ // We only care about fields 14 (utime) and 15 (stime)
unsigned long utime = 0;
unsigned long stime = 0;
- long rss = 0;
- // 1 2 3 4 5 6 7 8 9 10 11 12 13 14* 15* 16 17 18 19 20 21 22 23 24*
- res = sscanf(reinterpret_cast<char const*>(line.data()), "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu %*d %*d %*d %*d %*d %*d %*u %*u %ld", &utime, &stime, &rss);
- if (res != 3)
+ // 1 2 3 4 5 6 7 8 9 10 11 12 13 14* 15*
+ res = sscanf(reinterpret_cast<char const*>(line.data()), "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", &utime, &stime);
+ if (res != 2)
return Error::from_string_literal("Failed to parse /proc/pid/stat");
- process->memory_usage_bytes = rss * page_size;
+ if (auto footprint = own_memory_bytes(process->pid); footprint.has_value())
+ process->memory_usage_bytes = *footprint;
u64 const time_process = utime + stime;
float const time_scheduled_diff = time_process - process->time_spent_in_process;
@@ -97,29 +143,15 @@ Optional<ProcessResourceUsage> process_resource_usage(ProcessInfo const& process
auto system = fields[12].to_number<u64>();
if (!user.has_value() || !system.has_value() || user_hz <= 0)
return {};
- auto memory_file = Core::File::open(MUST(String::formatted("/proc/{}/statm", process.pid)), Core::File::OpenMode::Read);
- if (memory_file.is_error())
- return {};
- auto memory_contents = memory_file.value()->read_until_eof();
- if (memory_contents.is_error())
- return {};
- auto memory_fields = StringView(memory_contents.value()).split_view(' ');
- if (memory_fields.size() < 3)
- return {};
- auto resident = memory_fields[1].to_number<u64>();
- auto shared = memory_fields[2].to_number<u64>();
- if (!resident.has_value() || !shared.has_value() || *resident < *shared || page_size <= 0)
+ auto memory = own_memory_bytes(process.pid);
+ if (!memory.has_value())
return {};
- // NB: statm's resident minus shared is a cheap private resident estimate. It omits
- // file-backed private pages and does not include swapped-out memory.
Checked<u64> cpu_time = *user;
cpu_time += *system;
cpu_time *= 1'000'000;
- Checked<u64> memory = *resident - *shared;
- memory *= page_size;
- if (cpu_time.has_overflow() || memory.has_overflow())
+ if (cpu_time.has_overflow())
return {};
- return ProcessResourceUsage { cpu_time.value() / user_hz, memory.value() };
+ return ProcessResourceUsage { cpu_time.value() / user_hz, *memory };
}
}
diff --git a/Tests/LibCore/CMakeLists.txt b/Tests/LibCore/CMakeLists.txt
index 3ed97d7bf90..2a2543393ee 100644
--- a/Tests/LibCore/CMakeLists.txt
+++ b/Tests/LibCore/CMakeLists.txt
@@ -18,6 +18,7 @@ set(TEST_SOURCES
if (LINUX)
list(APPEND TEST_SOURCES
TestLibCoreFileWatcher.cpp
+ TestLibCoreProcessStatistics.cpp
)
endif()
diff --git a/Tests/LibCore/TestLibCoreProcessStatistics.cpp b/Tests/LibCore/TestLibCoreProcessStatistics.cpp
new file mode 100644
index 00000000000..0bc95b4ed53
--- /dev/null
+++ b/Tests/LibCore/TestLibCoreProcessStatistics.cpp
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/LexicalPath.h>
+#include <LibCore/AnonymousBuffer.h>
+#include <LibCore/Platform/ProcessResourceUsage.h>
+#include <LibCore/Platform/ProcessStatistics.h>
+#include <LibCore/System.h>
+#include <LibTest/TestCase.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+static constexpr size_t mapping_size = 32 * MiB;
+
+static u64 own_memory_usage()
+{
+ Core::Platform::ProcessStatistics statistics;
+ statistics.processes.append(make<Core::Platform::ProcessInfo>(Core::System::getpid()));
+ MUST(Core::Platform::update_process_statistics(statistics));
+ return statistics.processes[0]->memory_usage_bytes;
+}
+
+static u64 own_attributed_memory()
+{
+ auto usage = Core::Platform::process_resource_usage(Core::Platform::ProcessInfo { Core::System::getpid() });
+ VERIFY(usage.has_value());
+ return usage->attributed_memory_bytes;
+}
+
+// NB: The task manager shows the memory usage of each process, and the per-tab performance monitor adds up the attributed
+// memory of a tab's processes, so the two have to agree on every process.
+TEST_CASE(memory_usage_and_attributed_memory_agree)
+{
+ auto usage = own_memory_usage();
+ auto attributed = own_attributed_memory();
+ auto difference = usage > attributed ? usage - attributed : attributed - usage;
+ EXPECT(difference < 4 * MiB);
+}
+
+TEST_CASE(anonymous_memory_counts)
+{
+ auto before_usage = own_memory_usage();
+ auto before_attributed = own_attributed_memory();
+
+ auto* memory = static_cast<u8*>(mmap(nullptr, mapping_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
+ VERIFY(memory != MAP_FAILED);
+ __builtin_memset(memory, 1, mapping_size);
+
+ EXPECT(own_memory_usage() >= before_usage + mapping_size / 2);
+ EXPECT(own_attributed_memory() >= before_attributed + mapping_size / 2);
+
+ VERIFY(munmap(memory, mapping_size) == 0);
+}
+
+TEST_CASE(shared_memory_counts)
+{
+ auto before_usage = own_memory_usage();
+ auto before_attributed = own_attributed_memory();
+
+ auto buffer = MUST(Core::AnonymousBuffer::create_with_size(mapping_size));
+ __builtin_memset(buffer.data<u8>(), 1, mapping_size);
+
+ EXPECT(own_memory_usage() >= before_usage + mapping_size / 2);
+ EXPECT(own_attributed_memory() >= before_attributed + mapping_size / 2);
+}
+
+TEST_CASE(file_backed_memory_does_not_count)
+{
+ // NB: The page cache shares these pages with every other process that maps the file, so they are no one's own.
+ // The file goes next to the executable, as a temporary directory may be in memory and so count as shared memory.
+ auto path = ByteString::formatted("{}/.TestLibCoreProcessStatistics.{}", LexicalPath::dirname(MUST(Core::System::current_executable_path())), Core::System::getpid());
+ auto fd = MUST(Core::System::open(path, O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0600));
+ MUST(Core::System::unlink(path));
+ VERIFY(ftruncate(fd, mapping_size) == 0);
+ auto* memory = static_cast<u8*>(mmap(nullptr, mapping_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
+ VERIFY(memory != MAP_FAILED);
+ MUST(Core::System::close(fd));
+
+ auto before_usage = own_memory_usage();
+ auto before_attributed = own_attributed_memory();
+ __builtin_memset(memory, 1, mapping_size);
+
+ EXPECT(own_memory_usage() < before_usage + mapping_size / 2);
+ EXPECT(own_attributed_memory() < before_attributed + mapping_size / 2);
+
+ VERIFY(munmap(memory, mapping_size) == 0);
+}