Thanks to visit codestin.com
Credit goes to chromium.googlesource.com

blob: e71c0bf27e97574aa4346b11427ce5294ce5d469 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2013 The Chromium Authors
[email protected]669a09332013-08-30 22:59:142// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Tom Sepez8726d30e2025-01-29 02:11:085#ifdef UNSAFE_BUFFERS_BUILD
6// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
7#pragma allow_unsafe_libc_calls
8#endif
9
[email protected]669a09332013-08-30 22:59:1410#include "base/process/process_metrics.h"
11
avibeced7c2015-12-24 06:47:5912#include <stddef.h>
13#include <stdint.h>
14
Peter Kasting025a94252025-01-29 21:28:3715#include <algorithm>
Arthur Sonzogni0844a992024-12-12 11:36:2016#include <array>
Peter Boström6b701822021-04-15 03:53:0817#include <memory>
[email protected]669a09332013-08-30 22:59:1418#include <sstream>
19#include <string>
Joe Masonf4812182024-01-19 01:12:3720#include <utility>
Benoit Lize448ee882017-08-31 13:32:1221#include <vector>
[email protected]669a09332013-08-30 22:59:1422
Avi Drissmanc4404ffc2025-08-05 21:48:0623#include "base/byte_count.h"
thestigcf4c85b2015-12-16 08:33:3024#include "base/command_line.h"
25#include "base/files/file.h"
Joe Masonf4812182024-01-19 01:12:3726#include "base/files/file_path.h"
thestigcf4c85b2015-12-16 08:33:3027#include "base/files/file_util.h"
28#include "base/files/scoped_temp_dir.h"
Avi Drissman63e1f992023-01-13 18:54:4329#include "base/functional/bind.h"
arthursonzogni38d9bf472019-04-15 13:00:1130#include "base/memory/shared_memory_mapping.h"
31#include "base/memory/writable_shared_memory_region.h"
Joe Masonf4812182024-01-19 01:12:3732#include "base/process/launch.h"
33#include "base/process/process.h"
34#include "base/process/process_handle.h"
afakhry8c03da072015-12-03 01:26:1935#include "base/strings/string_number_conversions.h"
Eric Secklerdbc29da2020-07-10 11:54:0536#include "base/strings/string_util.h"
Robert Sesek3aff3362019-01-23 20:16:1637#include "base/strings/stringprintf.h"
Sebastien Marchand75a7cdf2018-11-13 23:47:0338#include "base/system/sys_info.h"
Joe Mason550eed62024-03-25 18:07:3139#include "base/test/gmock_expected_support.h"
Joe Masonf4812182024-01-19 01:12:3740#include "base/test/gtest_util.h"
thestigcf4c85b2015-12-16 08:33:3041#include "base/test/multiprocess_test.h"
Joe Masonf4812182024-01-19 01:12:3742#include "base/test/test_timeouts.h"
[email protected]cf46e3752013-12-02 01:01:0143#include "base/threading/thread.h"
Joe Mason550eed62024-03-25 18:07:3144#include "base/types/expected.h"
Joe Masonf4812182024-01-19 01:12:3745#include "build/blink_buildflags.h"
avibeced7c2015-12-24 06:47:5946#include "build/build_config.h"
Joe Masonba145282024-03-12 20:18:1947#include "testing/gmock/include/gmock/gmock.h"
[email protected]669a09332013-08-30 22:59:1448#include "testing/gtest/include/gtest/gtest.h"
thestigcf4c85b2015-12-16 08:33:3049#include "testing/multiprocess_func_list.h"
[email protected]669a09332013-08-30 22:59:1450
Xiaohan Wang37e81612022-01-15 18:27:0051#if BUILDFLAG(IS_APPLE)
erikchen863e4742017-03-31 19:57:4352#include <sys/mman.h>
53#endif
54
Dave Tapuska828a495c2024-03-26 17:33:0355#if BUILDFLAG(IS_MAC)
Joe Masonf4812182024-01-19 01:12:3756#include <mach/mach.h>
57
58#include "base/apple/mach_logging.h"
Mark Roweced178d2024-10-08 21:16:0959#include "base/apple/mach_port_rendezvous.h"
Joe Masonf4812182024-01-19 01:12:3760#include "base/apple/scoped_mach_port.h"
Joe Masonf4812182024-01-19 01:12:3761#include "base/process/port_provider_mac.h"
Eric Secklerdbc29da2020-07-10 11:54:0562#endif
63
Georg Neisff37fb52025-02-05 09:05:2664#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN) || \
Joe Masonf75bf182023-10-17 22:16:2565 BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_APPLE)
66#define ENABLE_CPU_TESTS 1
67#else
68#define ENABLE_CPU_TESTS 0
69#endif
70
71namespace base::debug {
Fabrice de Gans4072fcf2021-08-20 21:35:2972
afakhry8c03da072015-12-03 01:26:1973namespace {
74
Joe Mason550eed62024-03-25 18:07:3175using base::test::ErrorIs;
76using base::test::ValueIs;
77using ::testing::_;
Joe Masonba145282024-03-12 20:18:1978using ::testing::AssertionFailure;
79using ::testing::AssertionResult;
80using ::testing::AssertionSuccess;
81using ::testing::Ge;
Joe Masonba145282024-03-12 20:18:1982
Joe Masonf75bf182023-10-17 22:16:2583#if ENABLE_CPU_TESTS
84
afakhry8c03da072015-12-03 01:26:1985void BusyWork(std::vector<std::string>* vec) {
86 int64_t test_value = 0;
87 for (int i = 0; i < 100000; ++i) {
88 ++test_value;
Raul Tambrea9c13642019-03-25 13:34:4289 vec->push_back(NumberToString(test_value));
afakhry8c03da072015-12-03 01:26:1990 }
91}
92
Joe Masonba145282024-03-12 20:18:1993// Tests that GetCumulativeCPUUsage() returns a valid result that's equal to or
94// greater than `prev_cpu_usage`, and returns the result. If
95// GetCumulativeCPUUsage() returns an error, records a failed expectation and
96// returns an empty TimeDelta so that each test doesn't need to check for
97// nullopt repeatedly.
Joe Masonc2c3f722023-10-17 19:51:1798TimeDelta TestCumulativeCPU(ProcessMetrics* metrics, TimeDelta prev_cpu_usage) {
Joe Mason550eed62024-03-25 18:07:3199 const base::expected<TimeDelta, ProcessCPUUsageError> current_cpu_usage =
Joe Masonba145282024-03-12 20:18:19100 metrics->GetCumulativeCPUUsage();
Joe Mason550eed62024-03-25 18:07:31101 EXPECT_THAT(current_cpu_usage, ValueIs(Ge(prev_cpu_usage)));
102 EXPECT_THAT(metrics->GetPlatformIndependentCPUUsage(), ValueIs(Ge(0.0)));
Joe Masonba145282024-03-12 20:18:19103 return current_cpu_usage.value_or(TimeDelta());
Joe Masonc2c3f722023-10-17 19:51:17104}
105
Joe Masonf75bf182023-10-17 22:16:25106#endif // ENABLE_CPU_TESTS
Fabrice de Gans4072fcf2021-08-20 21:35:29107
Joe Masonf4812182024-01-19 01:12:37108// Helper to deal with Mac process launching complexity. On other platforms this
109// is just a thin wrapper around SpawnMultiProcessTestChild.
110class TestChildLauncher {
111 public:
112 TestChildLauncher() = default;
113 ~TestChildLauncher() = default;
114
115 TestChildLauncher(const TestChildLauncher&) = delete;
116 TestChildLauncher& operator=(const TestChildLauncher&) = delete;
117
118 // Returns a reference to the command line for the child process. This can be
119 // used to add extra parameters before calling SpawnChildProcess().
120 CommandLine& command_line() { return command_line_; }
121
122 // Returns a reference to the child process object, which will be invalid
123 // until SpawnChildProcess() is called.
124 Process& child_process() { return child_process_; }
125
126 // Spawns a multiprocess test child to execute the function `procname`.
127 AssertionResult SpawnChildProcess(const std::string& procname);
128
129 // Returns a ProcessMetrics object for the child process created by
130 // SpawnChildProcess().
131 std::unique_ptr<ProcessMetrics> CreateChildProcessMetrics();
132
133 // Terminates the child process created by SpawnChildProcess(). Returns true
134 // if the process successfully terminates within the allowed time.
135 bool TerminateChildProcess();
136
137 // Called from the child process to send data back to the parent if needed.
138 static void NotifyParent();
139
140 private:
141 CommandLine command_line_ = GetMultiProcessTestChildBaseCommandLine();
142 Process child_process_;
143
Dave Tapuska828a495c2024-03-26 17:33:03144#if BUILDFLAG(IS_MAC)
Joe Masonf4812182024-01-19 01:12:37145 class TestChildPortProvider;
146 std::unique_ptr<TestChildPortProvider> port_provider_;
Joe Masonf75bf182023-10-17 22:16:25147#endif
Joe Masonf4812182024-01-19 01:12:37148};
149
Dave Tapuska828a495c2024-03-26 17:33:03150#if BUILDFLAG(IS_MAC)
Joe Masonf4812182024-01-19 01:12:37151
Mark Roweced178d2024-10-08 21:16:09152// Adapted from base/apple/mach_port_rendezvous_unittest.cc and
Joe Masonf4812182024-01-19 01:12:37153// https://mw.foldr.org/posts/computers/macosx/task-info-fun-with-mach/
154
155constexpr MachPortsForRendezvous::key_type kTestChildRendezvousKey = 'test';
156
157// A PortProvider that tracks child processes spawned by TestChildLauncher.
158class TestChildLauncher::TestChildPortProvider final : public PortProvider {
159 public:
160 TestChildPortProvider(ProcessHandle handle, apple::ScopedMachSendRight port)
161 : handle_(handle), port_(std::move(port)) {}
162
163 ~TestChildPortProvider() final = default;
164
165 TestChildPortProvider(const TestChildPortProvider&) = delete;
166 TestChildPortProvider& operator=(const TestChildPortProvider&) = delete;
167
Francois Doray7898890312024-02-05 18:24:26168 mach_port_t TaskForHandle(ProcessHandle process_handle) const final {
169 return process_handle == handle_ ? port_.get() : MACH_PORT_NULL;
Joe Masonf4812182024-01-19 01:12:37170 }
171
172 private:
173 ProcessHandle handle_;
174 apple::ScopedMachSendRight port_;
175};
176
177AssertionResult TestChildLauncher::SpawnChildProcess(
178 const std::string& procname) {
179 // Allocate a port for the parent to receive details from the child process.
180 apple::ScopedMachReceiveRight receive_port;
181 if (!apple::CreateMachPort(&receive_port, nullptr)) {
182 return AssertionFailure() << "Failed to allocate receive port";
183 }
184
185 // Pass the sending end of the port to the child.
186 LaunchOptions options = LaunchOptionsForTest();
187 options.mach_ports_for_rendezvous.emplace(
188 kTestChildRendezvousKey,
189 MachRendezvousPort(receive_port.get(), MACH_MSG_TYPE_MAKE_SEND));
190 child_process_ =
191 SpawnMultiProcessTestChild(procname, command_line_, std::move(options));
192 if (!child_process_.IsValid()) {
193 return AssertionFailure() << "Failed to launch child process.";
194 }
195
196 // Wait for the child to send back its mach_task_self().
197 struct : mach_msg_base_t {
198 mach_msg_port_descriptor_t task_port;
199 mach_msg_trailer_t trailer;
200 } msg{};
201 kern_return_t kr =
202 mach_msg(&msg.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(msg),
203 receive_port.get(),
204 TestTimeouts::action_timeout().InMilliseconds(), MACH_PORT_NULL);
205 if (kr != KERN_SUCCESS) {
206 return AssertionFailure()
207 << "Failed to read mach_task_self from child process: "
208 << mach_error_string(kr);
209 }
210 port_provider_ = std::make_unique<TestChildPortProvider>(
211 child_process_.Handle(), apple::ScopedMachSendRight(msg.task_port.name));
212 return AssertionSuccess();
Joe Masonf75bf182023-10-17 22:16:25213}
214
Joe Masonf4812182024-01-19 01:12:37215std::unique_ptr<ProcessMetrics> TestChildLauncher::CreateChildProcessMetrics() {
Gyuyoung Kimf41383e2024-01-22 14:30:10216#if BUILDFLAG(IS_MAC)
Joe Masonf4812182024-01-19 01:12:37217 return ProcessMetrics::CreateProcessMetrics(child_process_.Handle(),
218 port_provider_.get());
Gyuyoung Kimf41383e2024-01-22 14:30:10219#else
220 return ProcessMetrics::CreateProcessMetrics(child_process_.Handle());
221#endif
Joe Masonf4812182024-01-19 01:12:37222}
223
224bool TestChildLauncher::TerminateChildProcess() {
225 return TerminateMultiProcessTestChild(child_process_, /*exit_code=*/0,
226 /*wait=*/true);
227}
228
229// static
230void TestChildLauncher::NotifyParent() {
231 auto* client = MachPortRendezvousClient::GetInstance();
232 ASSERT_TRUE(client);
233 apple::ScopedMachSendRight send_port =
234 client->TakeSendRight(kTestChildRendezvousKey);
235 ASSERT_TRUE(send_port.is_valid());
236
237 // Send mach_task_self to the parent process so that it can use the port to
238 // create ProcessMetrics.
239 struct : mach_msg_base_t {
240 mach_msg_port_descriptor_t task_port;
241 } msg{};
242 msg.header.msgh_bits =
243 MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND) | MACH_MSGH_BITS_COMPLEX;
244 msg.header.msgh_remote_port = send_port.get();
245 msg.header.msgh_size = sizeof(msg);
246 msg.body.msgh_descriptor_count = 1;
247 msg.task_port.name = mach_task_self();
248 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
249 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
250 kern_return_t kr =
251 mach_msg(&msg.header, MACH_SEND_MSG, msg.header.msgh_size, 0,
252 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
253 MACH_CHECK(kr == KERN_SUCCESS, kr);
254}
255
256#else
257
258AssertionResult TestChildLauncher::SpawnChildProcess(
259 const std::string& procname) {
260 child_process_ = SpawnMultiProcessTestChild(procname, command_line_,
261 LaunchOptionsForTest());
262 return child_process_.IsValid()
263 ? AssertionSuccess()
264 : AssertionFailure() << "Failed to launch child process.";
265}
266
267std::unique_ptr<ProcessMetrics> TestChildLauncher::CreateChildProcessMetrics() {
268 return ProcessMetrics::CreateProcessMetrics(child_process_.Handle());
269}
270
271bool TestChildLauncher::TerminateChildProcess() {
272 [[maybe_unused]] const ProcessHandle child_handle = child_process_.Handle();
273 if (!TerminateMultiProcessTestChild(child_process_, /*exit_code=*/0,
274 /*wait=*/true)) {
275 return false;
276 }
277#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
278 // After the process exits, ProcessMetrics races to read /proc/<pid>/stat
279 // before it's deleted. Wait until it's definitely gone.
280 const auto stat_path = FilePath(FILE_PATH_LITERAL("/proc"))
281 .AppendASCII(NumberToString(child_handle))
282 .Append(FILE_PATH_LITERAL("stat"));
283
284 while (PathExists(stat_path)) {
285 PlatformThread::Sleep(TestTimeouts::tiny_timeout());
286 }
287#endif
288 return true;
289}
290
291// static
292void TestChildLauncher::NotifyParent() {
293 // Do nothing.
294}
295
296#endif // BUILDFLAG(IS_MAC)
297
Joe Masonf75bf182023-10-17 22:16:25298} // namespace
afakhry8c03da072015-12-03 01:26:19299
[email protected]669a09332013-08-30 22:59:14300// Tests for SystemMetrics.
301// Exists as a class so it can be a friend of SystemMetrics.
302class SystemMetricsTest : public testing::Test {
303 public:
Chris Watkinsbb7211c2017-11-29 07:16:38304 SystemMetricsTest() = default;
[email protected]669a09332013-08-30 22:59:14305
Peter Boström75cd3c02021-09-28 15:23:18306 SystemMetricsTest(const SystemMetricsTest&) = delete;
307 SystemMetricsTest& operator=(const SystemMetricsTest&) = delete;
[email protected]669a09332013-08-30 22:59:14308};
309
Xiaohan Wang37e81612022-01-15 18:27:00310#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
[email protected]669a09332013-08-30 22:59:14311TEST_F(SystemMetricsTest, IsValidDiskName) {
Lei Zhang912563e2017-07-20 16:49:58312 const char invalid_input1[] = "";
313 const char invalid_input2[] = "s";
314 const char invalid_input3[] = "sdz+";
315 const char invalid_input4[] = "hda0";
316 const char invalid_input5[] = "mmcbl";
317 const char invalid_input6[] = "mmcblka";
318 const char invalid_input7[] = "mmcblkb";
319 const char invalid_input8[] = "mmmblk0";
[email protected]669a09332013-08-30 22:59:14320
321 EXPECT_FALSE(IsValidDiskName(invalid_input1));
322 EXPECT_FALSE(IsValidDiskName(invalid_input2));
323 EXPECT_FALSE(IsValidDiskName(invalid_input3));
324 EXPECT_FALSE(IsValidDiskName(invalid_input4));
325 EXPECT_FALSE(IsValidDiskName(invalid_input5));
326 EXPECT_FALSE(IsValidDiskName(invalid_input6));
327 EXPECT_FALSE(IsValidDiskName(invalid_input7));
328 EXPECT_FALSE(IsValidDiskName(invalid_input8));
329
Lei Zhang912563e2017-07-20 16:49:58330 const char valid_input1[] = "sda";
331 const char valid_input2[] = "sdaaaa";
332 const char valid_input3[] = "hdz";
333 const char valid_input4[] = "mmcblk0";
334 const char valid_input5[] = "mmcblk999";
[email protected]669a09332013-08-30 22:59:14335
336 EXPECT_TRUE(IsValidDiskName(valid_input1));
337 EXPECT_TRUE(IsValidDiskName(valid_input2));
338 EXPECT_TRUE(IsValidDiskName(valid_input3));
339 EXPECT_TRUE(IsValidDiskName(valid_input4));
340 EXPECT_TRUE(IsValidDiskName(valid_input5));
341}
[email protected]ded8c42b2013-11-05 22:15:03342
343TEST_F(SystemMetricsTest, ParseMeminfo) {
Avi Drissmanc4404ffc2025-08-05 21:48:06344 SystemMemoryInfo meminfo;
Lei Zhang912563e2017-07-20 16:49:58345 const char invalid_input1[] = "abc";
346 const char invalid_input2[] = "MemTotal:";
[email protected]ded8c42b2013-11-05 22:15:03347 // Partial file with no MemTotal
Lei Zhang912563e2017-07-20 16:49:58348 const char invalid_input3[] =
349 "MemFree: 3913968 kB\n"
350 "Buffers: 2348340 kB\n"
351 "Cached: 49071596 kB\n"
352 "SwapCached: 12 kB\n"
353 "Active: 36393900 kB\n"
354 "Inactive: 21221496 kB\n"
355 "Active(anon): 5674352 kB\n"
356 "Inactive(anon): 633992 kB\n";
[email protected]ded8c42b2013-11-05 22:15:03357 EXPECT_FALSE(ParseProcMeminfo(invalid_input1, &meminfo));
358 EXPECT_FALSE(ParseProcMeminfo(invalid_input2, &meminfo));
359 EXPECT_FALSE(ParseProcMeminfo(invalid_input3, &meminfo));
360
Lei Zhang912563e2017-07-20 16:49:58361 const char valid_input1[] =
362 "MemTotal: 3981504 kB\n"
363 "MemFree: 140764 kB\n"
364 "MemAvailable: 535413 kB\n"
365 "Buffers: 116480 kB\n"
366 "Cached: 406160 kB\n"
367 "SwapCached: 21304 kB\n"
368 "Active: 3152040 kB\n"
369 "Inactive: 472856 kB\n"
370 "Active(anon): 2972352 kB\n"
371 "Inactive(anon): 270108 kB\n"
372 "Active(file): 179688 kB\n"
373 "Inactive(file): 202748 kB\n"
374 "Unevictable: 0 kB\n"
375 "Mlocked: 0 kB\n"
376 "SwapTotal: 5832280 kB\n"
377 "SwapFree: 3672368 kB\n"
378 "Dirty: 184 kB\n"
379 "Writeback: 0 kB\n"
380 "AnonPages: 3101224 kB\n"
381 "Mapped: 142296 kB\n"
382 "Shmem: 140204 kB\n"
383 "Slab: 54212 kB\n"
384 "SReclaimable: 30936 kB\n"
385 "SUnreclaim: 23276 kB\n"
386 "KernelStack: 2464 kB\n"
387 "PageTables: 24812 kB\n"
388 "NFS_Unstable: 0 kB\n"
389 "Bounce: 0 kB\n"
390 "WritebackTmp: 0 kB\n"
391 "CommitLimit: 7823032 kB\n"
392 "Committed_AS: 7973536 kB\n"
393 "VmallocTotal: 34359738367 kB\n"
394 "VmallocUsed: 375940 kB\n"
395 "VmallocChunk: 34359361127 kB\n"
396 "DirectMap4k: 72448 kB\n"
397 "DirectMap2M: 4061184 kB\n";
[email protected]ded8c42b2013-11-05 22:15:03398 // output from a much older kernel where the Active and Inactive aren't
399 // broken down into anon and file and Huge Pages are enabled
Lei Zhang912563e2017-07-20 16:49:58400 const char valid_input2[] =
401 "MemTotal: 255908 kB\n"
402 "MemFree: 69936 kB\n"
403 "Buffers: 15812 kB\n"
404 "Cached: 115124 kB\n"
405 "SwapCached: 0 kB\n"
406 "Active: 92700 kB\n"
407 "Inactive: 63792 kB\n"
408 "HighTotal: 0 kB\n"
409 "HighFree: 0 kB\n"
410 "LowTotal: 255908 kB\n"
411 "LowFree: 69936 kB\n"
412 "SwapTotal: 524280 kB\n"
413 "SwapFree: 524200 kB\n"
414 "Dirty: 4 kB\n"
415 "Writeback: 0 kB\n"
416 "Mapped: 42236 kB\n"
417 "Slab: 25912 kB\n"
418 "Committed_AS: 118680 kB\n"
419 "PageTables: 1236 kB\n"
420 "VmallocTotal: 3874808 kB\n"
421 "VmallocUsed: 1416 kB\n"
422 "VmallocChunk: 3872908 kB\n"
423 "HugePages_Total: 0\n"
424 "HugePages_Free: 0\n"
425 "Hugepagesize: 4096 kB\n";
[email protected]ded8c42b2013-11-05 22:15:03426
427 EXPECT_TRUE(ParseProcMeminfo(valid_input1, &meminfo));
Avi Drissmanc4404ffc2025-08-05 21:48:06428 EXPECT_EQ(meminfo.total.InKiB(), 3981504);
429 EXPECT_EQ(meminfo.free.InKiB(), 140764);
430 EXPECT_EQ(meminfo.available.InKiB(), 535413);
431 EXPECT_EQ(meminfo.buffers.InKiB(), 116480);
432 EXPECT_EQ(meminfo.cached.InKiB(), 406160);
433 EXPECT_EQ(meminfo.active_anon.InKiB(), 2972352);
434 EXPECT_EQ(meminfo.active_file.InKiB(), 179688);
435 EXPECT_EQ(meminfo.inactive_anon.InKiB(), 270108);
436 EXPECT_EQ(meminfo.inactive_file.InKiB(), 202748);
437 EXPECT_EQ(meminfo.swap_total.InKiB(), 5832280);
438 EXPECT_EQ(meminfo.swap_free.InKiB(), 3672368);
439 EXPECT_EQ(meminfo.dirty.InKiB(), 184);
440 EXPECT_EQ(meminfo.reclaimable.InKiB(), 30936);
Eric Willigers611cf54e2022-04-28 02:22:14441#if BUILDFLAG(IS_CHROMEOS)
Avi Drissmanc4404ffc2025-08-05 21:48:06442 EXPECT_EQ(meminfo.shmem.InKiB(), 140204);
443 EXPECT_EQ(meminfo.slab.InKiB(), 54212);
[email protected]ded8c42b2013-11-05 22:15:03444#endif
François Doray9cee8042025-08-15 19:02:55445 EXPECT_EQ(355725,
446 base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo).InKiB());
mkolom01ac10b2017-03-22 01:47:29447 // Simulate as if there is no MemAvailable.
Avi Drissmanc4404ffc2025-08-05 21:48:06448 meminfo.available = ByteCount(0);
Peter Kastinga0b914dc2022-07-14 18:43:19449 EXPECT_EQ(374448u,
François Doray9cee8042025-08-15 19:02:55450 base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo).InKiB());
mkolom01ac10b2017-03-22 01:47:29451 meminfo = {};
[email protected]ded8c42b2013-11-05 22:15:03452 EXPECT_TRUE(ParseProcMeminfo(valid_input2, &meminfo));
Avi Drissmanc4404ffc2025-08-05 21:48:06453 EXPECT_EQ(meminfo.total.InKiB(), 255908);
454 EXPECT_EQ(meminfo.free.InKiB(), 69936);
455 EXPECT_EQ(meminfo.available.InKiB(), 0);
456 EXPECT_EQ(meminfo.buffers.InKiB(), 15812);
457 EXPECT_EQ(meminfo.cached.InKiB(), 115124);
458 EXPECT_EQ(meminfo.swap_total.InKiB(), 524280);
459 EXPECT_EQ(meminfo.swap_free.InKiB(), 524200);
460 EXPECT_EQ(meminfo.dirty.InKiB(), 4);
Peter Kastinga0b914dc2022-07-14 18:43:19461 EXPECT_EQ(69936u,
François Doray9cee8042025-08-15 19:02:55462 base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo).InKiB());
Joe Mason87c33f12024-02-09 15:47:04463
464 // output from a system with a large page cache, to catch arithmetic errors
465 // that incorrectly assume free + buffers + cached <= total. (Copied from
Hidehiko Abe89ebba172025-01-30 19:33:29466 // chromeos/ash/experiences/arc/test/data/mem_profile/16G.)
Joe Mason87c33f12024-02-09 15:47:04467 const char large_cache_input[] =
468 "MemTotal: 18025572 kB\n"
469 "MemFree: 13150176 kB\n"
470 "MemAvailable: 15447672 kB\n"
471 "Buffers: 1524852 kB\n"
472 "Cached: 12645260 kB\n"
473 "SwapCached: 0 kB\n"
474 "Active: 2572904 kB\n"
475 "Inactive: 1064976 kB\n"
476 "Active(anon): 1047836 kB\n"
477 "Inactive(anon): 11736 kB\n"
478 "Active(file): 1525068 kB\n"
479 "Inactive(file): 1053240 kB\n"
480 "Unevictable: 611904 kB\n"
481 "Mlocked: 32884 kB\n"
482 "SwapTotal: 11756208 kB\n"
483 "SwapFree: 11756208 kB\n"
484 "Dirty: 4152 kB\n"
485 "Writeback: 0 kB\n"
486 "AnonPages: 1079660 kB\n"
487 "Mapped: 782152 kB\n"
488 "Shmem: 591820 kB\n"
489 "Slab: 366104 kB\n"
490 "SReclaimable: 254356 kB\n"
491 "SUnreclaim: 111748 kB\n"
492 "KernelStack: 22652 kB\n"
493 "PageTables: 41540 kB\n"
494 "NFS_Unstable: 0 kB\n"
495 "Bounce: 0 kB\n"
496 "WritebackTmp: 0 kB\n"
497 "CommitLimit: 15768992 kB\n"
498 "Committed_AS: 36120244 kB\n"
499 "VmallocTotal: 34359738367 kB\n"
500 "VmallocUsed: 0 kB\n"
501 "VmallocChunk: 0 kB\n"
502 "Percpu: 3328 kB\n"
503 "AnonHugePages: 32768 kB\n"
504 "ShmemHugePages: 0 kB\n"
505 "ShmemPmdMapped: 0 kB\n"
506 "DirectMap4k: 293036 kB\n"
507 "DirectMap2M: 6918144 kB\n"
508 "DirectMap1G: 2097152 kB\n";
509
510 meminfo = {};
511 EXPECT_TRUE(ParseProcMeminfo(large_cache_input, &meminfo));
Avi Drissmanc4404ffc2025-08-05 21:48:06512 EXPECT_EQ(meminfo.total.InKiB(), 18025572);
513 EXPECT_EQ(meminfo.free.InKiB(), 13150176);
514 EXPECT_EQ(meminfo.buffers.InKiB(), 1524852);
515 EXPECT_EQ(meminfo.cached.InKiB(), 12645260);
Joe Mason87c33f12024-02-09 15:47:04516 EXPECT_EQ(GetSystemCommitChargeFromMeminfo(meminfo), 0u);
[email protected]ded8c42b2013-11-05 22:15:03517}
518
519TEST_F(SystemMetricsTest, ParseVmstat) {
Kenichi Ishibashi44871522017-10-23 07:12:19520 VmStatInfo vmstat;
Kuo-Hsin Yanga141f592020-09-10 07:09:33521 // Part of vmstat from a 4.19 kernel.
Lei Zhang912563e2017-07-20 16:49:58522 const char valid_input1[] =
Kuo-Hsin Yanga141f592020-09-10 07:09:33523 "pgpgin 2358216\n"
524 "pgpgout 296072\n"
525 "pswpin 345219\n"
526 "pswpout 2605828\n"
527 "pgalloc_dma32 8380235\n"
528 "pgalloc_normal 3384525\n"
Lei Zhang912563e2017-07-20 16:49:58529 "pgalloc_movable 0\n"
Kuo-Hsin Yanga141f592020-09-10 07:09:33530 "allocstall_dma32 0\n"
531 "allocstall_normal 2028\n"
532 "allocstall_movable 32559\n"
533 "pgskip_dma32 0\n"
534 "pgskip_normal 0\n"
535 "pgskip_movable 0\n"
536 "pgfree 11802722\n"
537 "pgactivate 894917\n"
538 "pgdeactivate 3255711\n"
539 "pglazyfree 48\n"
540 "pgfault 10043657\n"
541 "pgmajfault 358901\n"
542 "pgmajfault_s 2100\n"
543 "pgmajfault_a 343211\n"
544 "pgmajfault_f 13590\n"
545 "pglazyfreed 0\n"
546 "pgrefill 3429488\n"
547 "pgsteal_kswapd 1466893\n"
548 "pgsteal_direct 1771759\n"
549 "pgscan_kswapd 1907332\n"
550 "pgscan_direct 2118930\n"
551 "pgscan_direct_throttle 154\n"
552 "pginodesteal 3176\n"
553 "slabs_scanned 293804\n"
554 "kswapd_inodesteal 16753\n"
555 "kswapd_low_wmark_hit_quickly 10\n"
556 "kswapd_high_wmark_hit_quickly 423\n"
557 "pageoutrun 441\n"
558 "pgrotated 1636\n"
559 "drop_pagecache 0\n"
560 "drop_slab 0\n"
561 "oom_kill 18\n";
Lei Zhang912563e2017-07-20 16:49:58562 const char valid_input2[] =
Kuo-Hsin Yanga141f592020-09-10 07:09:33563 "pgpgin 2606135\n"
564 "pgpgout 1359128\n"
565 "pswpin 899959\n"
566 "pswpout 19761244\n"
567 "pgalloc_dma 31\n"
568 "pgalloc_dma32 18139339\n"
569 "pgalloc_normal 44085950\n"
570 "pgalloc_movable 0\n"
571 "allocstall_dma 0\n"
572 "allocstall_dma32 0\n"
573 "allocstall_normal 18881\n"
574 "allocstall_movable 169527\n"
575 "pgskip_dma 0\n"
576 "pgskip_dma32 0\n"
577 "pgskip_normal 0\n"
578 "pgskip_movable 0\n"
579 "pgfree 63060999\n"
580 "pgactivate 1703494\n"
581 "pgdeactivate 20537803\n"
582 "pglazyfree 163\n"
583 "pgfault 45201169\n"
584 "pgmajfault 609626\n"
585 "pgmajfault_s 7488\n"
586 "pgmajfault_a 591793\n"
587 "pgmajfault_f 10345\n"
588 "pglazyfreed 0\n"
589 "pgrefill 20673453\n"
590 "pgsteal_kswapd 11802772\n"
591 "pgsteal_direct 8618160\n"
592 "pgscan_kswapd 12640517\n"
593 "pgscan_direct 9092230\n"
594 "pgscan_direct_throttle 638\n"
595 "pginodesteal 1716\n"
596 "slabs_scanned 2594642\n"
597 "kswapd_inodesteal 67358\n"
598 "kswapd_low_wmark_hit_quickly 52\n"
599 "kswapd_high_wmark_hit_quickly 11\n"
600 "pageoutrun 83\n"
601 "pgrotated 977\n"
602 "drop_pagecache 1\n"
603 "drop_slab 1\n"
604 "oom_kill 1\n"
605 "pgmigrate_success 3202\n"
606 "pgmigrate_fail 795\n";
607 const char valid_input3[] =
Lei Zhang912563e2017-07-20 16:49:58608 "pswpin 12\n"
609 "pswpout 901\n"
Kuo-Hsin Yanga141f592020-09-10 07:09:33610 "pgmajfault 18881\n";
Kenichi Ishibashi44871522017-10-23 07:12:19611 EXPECT_TRUE(ParseProcVmstat(valid_input1, &vmstat));
Kuo-Hsin Yanga141f592020-09-10 07:09:33612 EXPECT_EQ(345219LU, vmstat.pswpin);
613 EXPECT_EQ(2605828LU, vmstat.pswpout);
614 EXPECT_EQ(358901LU, vmstat.pgmajfault);
615 EXPECT_EQ(18LU, vmstat.oom_kill);
Kenichi Ishibashi44871522017-10-23 07:12:19616 EXPECT_TRUE(ParseProcVmstat(valid_input2, &vmstat));
Kuo-Hsin Yanga141f592020-09-10 07:09:33617 EXPECT_EQ(899959LU, vmstat.pswpin);
618 EXPECT_EQ(19761244LU, vmstat.pswpout);
619 EXPECT_EQ(609626LU, vmstat.pgmajfault);
620 EXPECT_EQ(1LU, vmstat.oom_kill);
621 EXPECT_TRUE(ParseProcVmstat(valid_input3, &vmstat));
Kenichi Ishibashi44871522017-10-23 07:12:19622 EXPECT_EQ(12LU, vmstat.pswpin);
623 EXPECT_EQ(901LU, vmstat.pswpout);
Kuo-Hsin Yanga141f592020-09-10 07:09:33624 EXPECT_EQ(18881LU, vmstat.pgmajfault);
625 EXPECT_EQ(0LU, vmstat.oom_kill);
Lei Zhang912563e2017-07-20 16:49:58626
627 const char missing_pgmajfault_input[] =
628 "pswpin 12\n"
629 "pswpout 901\n";
Kenichi Ishibashi44871522017-10-23 07:12:19630 EXPECT_FALSE(ParseProcVmstat(missing_pgmajfault_input, &vmstat));
Lei Zhang912563e2017-07-20 16:49:58631 const char empty_input[] = "";
Kenichi Ishibashi44871522017-10-23 07:12:19632 EXPECT_FALSE(ParseProcVmstat(empty_input, &vmstat));
[email protected]ded8c42b2013-11-05 22:15:03633}
Xiaohan Wang37e81612022-01-15 18:27:00634#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
635 // BUILDFLAG(IS_ANDROID)
[email protected]669a09332013-08-30 22:59:14636
Joe Masonf75bf182023-10-17 22:16:25637#if ENABLE_CPU_TESTS
Wez4ae8f292017-09-11 20:52:03638// Test that ProcessMetrics::GetPlatformIndependentCPUUsage() doesn't return
639// negative values when the number of threads running on the process decreases
640// between two successive calls to it.
afakhry8c03da072015-12-03 01:26:19641TEST_F(SystemMetricsTest, TestNoNegativeCpuUsage) {
Joe Masonf4812182024-01-19 01:12:37642 std::unique_ptr<ProcessMetrics> metrics =
643 ProcessMetrics::CreateCurrentProcessMetrics();
afakhry8c03da072015-12-03 01:26:19644
Joe Mason550eed62024-03-25 18:07:31645 EXPECT_THAT(metrics->GetPlatformIndependentCPUUsage(), ValueIs(Ge(0.0)));
Joe Masonc2c3f722023-10-17 19:51:17646
afakhry8c03da072015-12-03 01:26:19647 Thread thread1("thread1");
648 Thread thread2("thread2");
649 Thread thread3("thread3");
650
651 thread1.StartAndWaitForTesting();
652 thread2.StartAndWaitForTesting();
653 thread3.StartAndWaitForTesting();
654
655 ASSERT_TRUE(thread1.IsRunning());
656 ASSERT_TRUE(thread2.IsRunning());
657 ASSERT_TRUE(thread3.IsRunning());
658
659 std::vector<std::string> vec1;
660 std::vector<std::string> vec2;
661 std::vector<std::string> vec3;
662
tzik92b7a422017-04-11 15:00:44663 thread1.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec1));
664 thread2.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec2));
665 thread3.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec3));
afakhry8c03da072015-12-03 01:26:19666
Joe Masonc2c3f722023-10-17 19:51:17667 TimeDelta prev_cpu_usage = TestCumulativeCPU(metrics.get(), TimeDelta());
afakhry8c03da072015-12-03 01:26:19668
669 thread1.Stop();
Joe Masonc2c3f722023-10-17 19:51:17670 prev_cpu_usage = TestCumulativeCPU(metrics.get(), prev_cpu_usage);
afakhry8c03da072015-12-03 01:26:19671
672 thread2.Stop();
Joe Masonc2c3f722023-10-17 19:51:17673 prev_cpu_usage = TestCumulativeCPU(metrics.get(), prev_cpu_usage);
afakhry8c03da072015-12-03 01:26:19674
675 thread3.Stop();
Joe Masonc2c3f722023-10-17 19:51:17676 prev_cpu_usage = TestCumulativeCPU(metrics.get(), prev_cpu_usage);
afakhry8c03da072015-12-03 01:26:19677}
Joe Masonf4812182024-01-19 01:12:37678
Dave Tapuska828a495c2024-03-26 17:33:03679#if !BUILDFLAG(IS_APPLE)
Joe Masonf4812182024-01-19 01:12:37680
681// Subprocess to test the child CPU usage.
682MULTIPROCESS_TEST_MAIN(CPUUsageChildMain) {
683 TestChildLauncher::NotifyParent();
684 // Busy wait until terminated.
685 while (true) {
686 std::vector<std::string> vec;
687 BusyWork(&vec);
688 }
689}
690
691TEST_F(SystemMetricsTest, MeasureChildCpuUsage) {
692 TestChildLauncher child_launcher;
693 ASSERT_TRUE(child_launcher.SpawnChildProcess("CPUUsageChildMain"));
694 std::unique_ptr<ProcessMetrics> metrics =
695 child_launcher.CreateChildProcessMetrics();
696
697 const TimeDelta cpu_usage1 = TestCumulativeCPU(metrics.get(), TimeDelta());
Joe Masonf4812182024-01-19 01:12:37698
Joe Masonc4ad7dc2024-05-07 17:45:57699 // The child thread does busy work, so it should get some CPU usage. There's a
700 // small chance it won't be scheduled during the delay so loop several times.
701 const auto abort_time =
702 base::TimeTicks::Now() + TestTimeouts::action_max_timeout();
703 TimeDelta cpu_usage2;
704 while (cpu_usage2.is_zero() && !HasFailure() &&
705 base::TimeTicks::Now() < abort_time) {
706 PlatformThread::Sleep(TestTimeouts::tiny_timeout());
707 cpu_usage2 = TestCumulativeCPU(metrics.get(), cpu_usage1);
708 }
Joe Masonf4812182024-01-19 01:12:37709 EXPECT_TRUE(cpu_usage2.is_positive());
710
711 ASSERT_TRUE(child_launcher.TerminateChildProcess());
712
713#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_FUCHSIA)
714 // Windows and Fuchsia return final measurements of a process after it exits.
715 TestCumulativeCPU(metrics.get(), cpu_usage2);
Joe Masonf4812182024-01-19 01:12:37716#else
Joe Masonba145282024-03-12 20:18:19717 // All other platforms return an error.
Joe Mason550eed62024-03-25 18:07:31718 EXPECT_THAT(metrics->GetCumulativeCPUUsage(), ErrorIs(_));
719 EXPECT_THAT(metrics->GetPlatformIndependentCPUUsage(), ErrorIs(_));
Joe Masonf4812182024-01-19 01:12:37720#endif
721}
722
Dave Tapuska828a495c2024-03-26 17:33:03723#endif // !BUILDFLAG(IS_APPLE)
Joe Masonf4812182024-01-19 01:12:37724
Joe Masonf4812182024-01-19 01:12:37725TEST_F(SystemMetricsTest, InvalidProcessCpuUsage) {
726#if BUILDFLAG(IS_MAC)
727 std::unique_ptr<ProcessMetrics> metrics =
728 ProcessMetrics::CreateProcessMetrics(kNullProcessHandle, nullptr);
729#else
730 std::unique_ptr<ProcessMetrics> metrics =
731 ProcessMetrics::CreateProcessMetrics(kNullProcessHandle);
732#endif
Joe Mason550eed62024-03-25 18:07:31733 EXPECT_THAT(metrics->GetCumulativeCPUUsage(), ErrorIs(_));
734 EXPECT_THAT(metrics->GetPlatformIndependentCPUUsage(), ErrorIs(_));
Joe Masonf4812182024-01-19 01:12:37735}
Joe Masonf4812182024-01-19 01:12:37736
Joe Masonf75bf182023-10-17 22:16:25737#endif // ENABLE_CPU_TESTS
afakhry8c03da072015-12-03 01:26:19738
Etienne Pierre-doray490c80f2024-12-05 00:30:14739TEST_F(SystemMetricsTest, TestValidMemoryInfo) {
740 std::unique_ptr<ProcessMetrics> metrics =
741 ProcessMetrics::CreateCurrentProcessMetrics();
742
743 auto memory_info = metrics->GetMemoryInfo();
744 EXPECT_TRUE(memory_info.has_value());
745 EXPECT_GT(memory_info->resident_set_bytes, 0U);
746
747#if BUILDFLAG(IS_APPLE)
748 EXPECT_GT(memory_info->physical_footprint_bytes, 0U);
749 EXPECT_GT(memory_info->internal_bytes, 0U);
750 EXPECT_GE(memory_info->compressed_bytes, 0U);
751#endif // BUILDFLAG(IS_APPLE)
752
753#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
754 BUILDFLAG(IS_FUCHSIA)
755 EXPECT_GT(memory_info->rss_anon_bytes, 0U);
756 EXPECT_GE(memory_info->vm_swap_bytes, 0U);
757#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
758 // BUILDFLAG(IS_ANDROID)
759
760#if BUILDFLAG(IS_WIN)
761 EXPECT_GT(memory_info->private_bytes, 0U);
762#endif // BUILDFLAG(IS_WIN)
763}
764
Eric Willigers611cf54e2022-04-28 02:22:14765#if BUILDFLAG(IS_CHROMEOS)
Chung-Sheng Wu838f843b2017-07-21 04:17:58766TEST_F(SystemMetricsTest, ParseZramMmStat) {
767 SwapInfo swapinfo;
768
769 const char invalid_input1[] = "aaa";
770 const char invalid_input2[] = "1 2 3 4 5 6";
771 const char invalid_input3[] = "a 2 3 4 5 6 7";
772 EXPECT_FALSE(ParseZramMmStat(invalid_input1, &swapinfo));
773 EXPECT_FALSE(ParseZramMmStat(invalid_input2, &swapinfo));
774 EXPECT_FALSE(ParseZramMmStat(invalid_input3, &swapinfo));
775
776 const char valid_input1[] =
777 "17715200 5008166 566062 0 1225715712 127 183842";
778 EXPECT_TRUE(ParseZramMmStat(valid_input1, &swapinfo));
779 EXPECT_EQ(17715200ULL, swapinfo.orig_data_size);
780 EXPECT_EQ(5008166ULL, swapinfo.compr_data_size);
781 EXPECT_EQ(566062ULL, swapinfo.mem_used_total);
782}
783
784TEST_F(SystemMetricsTest, ParseZramStat) {
785 SwapInfo swapinfo;
786
787 const char invalid_input1[] = "aaa";
788 const char invalid_input2[] = "1 2 3 4 5 6 7 8 9 10";
789 const char invalid_input3[] = "a 2 3 4 5 6 7 8 9 10 11";
790 EXPECT_FALSE(ParseZramStat(invalid_input1, &swapinfo));
791 EXPECT_FALSE(ParseZramStat(invalid_input2, &swapinfo));
792 EXPECT_FALSE(ParseZramStat(invalid_input3, &swapinfo));
793
794 const char valid_input1[] =
795 "299 0 2392 0 1 0 8 0 0 0 0";
796 EXPECT_TRUE(ParseZramStat(valid_input1, &swapinfo));
797 EXPECT_EQ(299ULL, swapinfo.num_reads);
798 EXPECT_EQ(1ULL, swapinfo.num_writes);
799}
Eric Willigers611cf54e2022-04-28 02:22:14800#endif // BUILDFLAG(IS_CHROMEOS)
Chung-Sheng Wu838f843b2017-07-21 04:17:58801
Xiaohan Wang37e81612022-01-15 18:27:00802#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) || \
803 BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
Sonny Rao81a33e82020-02-13 19:30:26804TEST(SystemMetrics2Test, GetSystemMemoryInfo) {
Avi Drissmanc4404ffc2025-08-05 21:48:06805 SystemMemoryInfo info;
thestigcf4c85b2015-12-16 08:33:30806 EXPECT_TRUE(GetSystemMemoryInfo(&info));
[email protected]cf46e3752013-12-02 01:01:01807
808 // Ensure each field received a value.
Avi Drissmanc4404ffc2025-08-05 21:48:06809 EXPECT_GT(info.total, ByteCount(0));
Xiaohan Wang37e81612022-01-15 18:27:00810#if BUILDFLAG(IS_WIN)
Avi Drissmanc4404ffc2025-08-05 21:48:06811 EXPECT_GT(info.avail_phys, ByteCount(0));
mkolom01ac10b2017-03-22 01:47:29812#else
Avi Drissmanc4404ffc2025-08-05 21:48:06813 EXPECT_GT(info.free, ByteCount(0));
mkolom01ac10b2017-03-22 01:47:29814#endif
Xiaohan Wang37e81612022-01-15 18:27:00815#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
Avi Drissmanc4404ffc2025-08-05 21:48:06816 EXPECT_GT(info.buffers, ByteCount(0));
817 EXPECT_GT(info.cached, ByteCount(0));
818 EXPECT_GT(info.active_anon + info.inactive_anon, ByteCount(0));
819 EXPECT_GT(info.active_file + info.inactive_file, ByteCount(0));
Xiaohan Wang37e81612022-01-15 18:27:00820#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
821 // BUILDFLAG(IS_ANDROID)
[email protected]cf46e3752013-12-02 01:01:01822
823 // All the values should be less than the total amount of memory.
Xiaohan Wang37e81612022-01-15 18:27:00824#if !BUILDFLAG(IS_WIN) && !BUILDFLAG(IS_IOS)
Alison Gale81f4f2c72024-04-22 19:33:31825 // TODO(crbug.com/40515565): re-enable the following assertion on iOS.
[email protected]cf46e3752013-12-02 01:01:01826 EXPECT_LT(info.free, info.total);
mkolom01ac10b2017-03-22 01:47:29827#endif
Xiaohan Wang37e81612022-01-15 18:27:00828#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
[email protected]cf46e3752013-12-02 01:01:01829 EXPECT_LT(info.buffers, info.total);
830 EXPECT_LT(info.cached, info.total);
831 EXPECT_LT(info.active_anon, info.total);
832 EXPECT_LT(info.inactive_anon, info.total);
833 EXPECT_LT(info.active_file, info.total);
834 EXPECT_LT(info.inactive_file, info.total);
Xiaohan Wang37e81612022-01-15 18:27:00835#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
836 // BUILDFLAG(IS_ANDROID)
[email protected]cf46e3752013-12-02 01:01:01837
Xiaohan Wang37e81612022-01-15 18:27:00838#if BUILDFLAG(IS_APPLE)
Avi Drissmanc4404ffc2025-08-05 21:48:06839 EXPECT_GT(info.file_backed, ByteCount(0));
mkolom01ac10b2017-03-22 01:47:29840#endif
841
Eric Willigers611cf54e2022-04-28 02:22:14842#if BUILDFLAG(IS_CHROMEOS)
[email protected]cf46e3752013-12-02 01:01:01843 // Chrome OS exposes shmem.
Avi Drissmanc4404ffc2025-08-05 21:48:06844 EXPECT_GT(info.shmem, ByteCount(0));
[email protected]cf46e3752013-12-02 01:01:01845 EXPECT_LT(info.shmem, info.total);
[email protected]cf46e3752013-12-02 01:01:01846#endif
847}
Xiaohan Wang37e81612022-01-15 18:27:00848#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) ||
849 // BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
[email protected]cf46e3752013-12-02 01:01:01850
Xiaohan Wang37e81612022-01-15 18:27:00851#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
[email protected]cf46e3752013-12-02 01:01:01852TEST(ProcessMetricsTest, ParseProcStatCPU) {
853 // /proc/self/stat for a process running "top".
Joe Masonf75bf182023-10-17 22:16:25854 const char kTopStat[] =
855 "960 (top) S 16230 960 16230 34818 960 "
[email protected]cf46e3752013-12-02 01:01:01856 "4202496 471 0 0 0 "
857 "12 16 0 0 " // <- These are the goods.
858 "20 0 1 0 121946157 15077376 314 18446744073709551615 4194304 "
859 "4246868 140733983044336 18446744073709551615 140244213071219 "
860 "0 0 0 138047495 0 0 0 17 1 0 0 0 0 0";
thestigcf4c85b2015-12-16 08:33:30861 EXPECT_EQ(12 + 16, ParseProcStatCPU(kTopStat));
[email protected]cf46e3752013-12-02 01:01:01862
863 // cat /proc/self/stat on a random other machine I have.
Joe Masonf75bf182023-10-17 22:16:25864 const char kSelfStat[] =
865 "5364 (cat) R 5354 5364 5354 34819 5364 "
[email protected]cf46e3752013-12-02 01:01:01866 "0 142 0 0 0 "
867 "0 0 0 0 " // <- No CPU, apparently.
868 "16 0 1 0 1676099790 2957312 114 4294967295 134512640 134528148 "
869 "3221224832 3221224344 3086339742 0 0 0 0 0 0 0 17 0 0 0";
870
thestigcf4c85b2015-12-16 08:33:30871 EXPECT_EQ(0, ParseProcStatCPU(kSelfStat));
afakhry597a8512015-02-05 00:51:57872
873 // Some weird long-running process with a weird name that I created for the
874 // purposes of this test.
Joe Masonf75bf182023-10-17 22:16:25875 const char kWeirdNameStat[] =
876 "26115 (Hello) You ())) ) R 24614 26115 24614"
afakhry597a8512015-02-05 00:51:57877 " 34839 26115 4218880 227 0 0 0 "
878 "5186 11 0 0 "
879 "20 0 1 0 36933953 4296704 90 18446744073709551615 4194304 4196116 "
880 "140735857761568 140735857761160 4195644 0 0 0 0 0 0 0 17 14 0 0 0 0 0 "
881 "6295056 6295616 16519168 140735857770710 140735857770737 "
882 "140735857770737 140735857774557 0";
thestigcf4c85b2015-12-16 08:33:30883 EXPECT_EQ(5186 + 11, ParseProcStatCPU(kWeirdNameStat));
[email protected]cf46e3752013-12-02 01:01:01884}
Xiaohan Wang37e81612022-01-15 18:27:00885#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
886 // BUILDFLAG(IS_ANDROID)
[email protected]cf46e3752013-12-02 01:01:01887
888// Disable on Android because base_unittests runs inside a Dalvik VM that
889// starts and stop threads (crbug.com/175563).
Xiaohan Wang37e81612022-01-15 18:27:00890#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
[email protected]9792d382014-08-11 16:12:37891// http://crbug.com/396455
892TEST(ProcessMetricsTest, DISABLED_GetNumberOfThreads) {
thestigcf4c85b2015-12-16 08:33:30893 const ProcessHandle current = GetCurrentProcessHandle();
Peter Kasting25acd5942022-07-07 17:45:15894 const int64_t initial_threads = GetNumberOfThreads(current);
[email protected]cf46e3752013-12-02 01:01:01895 ASSERT_GT(initial_threads, 0);
896 const int kNumAdditionalThreads = 10;
897 {
Arthur Sonzogni0844a992024-12-12 11:36:20898 std::array<std::unique_ptr<Thread>, kNumAdditionalThreads> my_threads;
[email protected]cf46e3752013-12-02 01:01:01899 for (int i = 0; i < kNumAdditionalThreads; ++i) {
Peter Boström6b701822021-04-15 03:53:08900 my_threads[i] = std::make_unique<Thread>("GetNumberOfThreadsTest");
[email protected]cf46e3752013-12-02 01:01:01901 my_threads[i]->Start();
thestigcf4c85b2015-12-16 08:33:30902 ASSERT_EQ(GetNumberOfThreads(current), initial_threads + 1 + i);
[email protected]cf46e3752013-12-02 01:01:01903 }
904 }
905 // The Thread destructor will stop them.
thestigcf4c85b2015-12-16 08:33:30906 ASSERT_EQ(initial_threads, GetNumberOfThreads(current));
907}
Xiaohan Wang37e81612022-01-15 18:27:00908#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
thestigcf4c85b2015-12-16 08:33:30909
Dave Tapuska828a495c2024-03-26 17:33:03910#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
thestigcf4c85b2015-12-16 08:33:30911namespace {
912
Siddhartha5293d8a2017-12-21 01:09:54913// Keep these in sync so the GetChildOpenFdCount test can refer to correct test
914// main.
thestigcf4c85b2015-12-16 08:33:30915#define ChildMain ChildFdCount
916#define ChildMainString "ChildFdCount"
917
918// Command line flag name and file name used for synchronization.
919const char kTempDirFlag[] = "temp-dir";
Robert Sesek3aff3362019-01-23 20:16:16920
921const char kSignalReady[] = "ready";
922const char kSignalReadyAck[] = "ready-ack";
923const char kSignalOpened[] = "opened";
924const char kSignalOpenedAck[] = "opened-ack";
thestigcf4c85b2015-12-16 08:33:30925const char kSignalClosed[] = "closed";
926
Robert Sesek3aff3362019-01-23 20:16:16927const int kChildNumFilesToOpen = 100;
928
thestigcf4c85b2015-12-16 08:33:30929bool SignalEvent(const FilePath& signal_dir, const char* signal_file) {
930 File file(signal_dir.AppendASCII(signal_file),
931 File::FLAG_CREATE | File::FLAG_WRITE);
932 return file.IsValid();
933}
934
935// Check whether an event was signaled.
936bool CheckEvent(const FilePath& signal_dir, const char* signal_file) {
937 File file(signal_dir.AppendASCII(signal_file),
938 File::FLAG_OPEN | File::FLAG_READ);
939 return file.IsValid();
940}
941
942// Busy-wait for an event to be signaled.
943void WaitForEvent(const FilePath& signal_dir, const char* signal_file) {
Joe Masonf75bf182023-10-17 22:16:25944 while (!CheckEvent(signal_dir, signal_file)) {
Peter Kasting53fd6ee2021-10-05 20:40:48945 PlatformThread::Sleep(Milliseconds(10));
Joe Masonf75bf182023-10-17 22:16:25946 }
thestigcf4c85b2015-12-16 08:33:30947}
948
949// Subprocess to test the number of open file descriptors.
950MULTIPROCESS_TEST_MAIN(ChildMain) {
Joe Masonf4812182024-01-19 01:12:37951 TestChildLauncher::NotifyParent();
952
thestigcf4c85b2015-12-16 08:33:30953 CommandLine* command_line = CommandLine::ForCurrentProcess();
954 const FilePath temp_path = command_line->GetSwitchValuePath(kTempDirFlag);
955 CHECK(DirectoryExists(temp_path));
956
Robert Sesek3aff3362019-01-23 20:16:16957 CHECK(SignalEvent(temp_path, kSignalReady));
958 WaitForEvent(temp_path, kSignalReadyAck);
959
960 std::vector<File> files;
961 for (int i = 0; i < kChildNumFilesToOpen; ++i) {
962 files.emplace_back(temp_path.AppendASCII(StringPrintf("file.%d", i)),
963 File::FLAG_CREATE | File::FLAG_WRITE);
964 }
965
966 CHECK(SignalEvent(temp_path, kSignalOpened));
967 WaitForEvent(temp_path, kSignalOpenedAck);
968
969 files.clear();
970
thestigcf4c85b2015-12-16 08:33:30971 CHECK(SignalEvent(temp_path, kSignalClosed));
972
973 // Wait to be terminated.
Joe Masonf75bf182023-10-17 22:16:25974 while (true) {
Peter Kasting53fd6ee2021-10-05 20:40:48975 PlatformThread::Sleep(Seconds(1));
Joe Masonf75bf182023-10-17 22:16:25976 }
thestigcf4c85b2015-12-16 08:33:30977}
978
979} // namespace
980
Siddhartha5293d8a2017-12-21 01:09:54981TEST(ProcessMetricsTest, GetChildOpenFdCount) {
thestigcf4c85b2015-12-16 08:33:30982 ScopedTempDir temp_dir;
983 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
vabr411f4fc2016-09-08 09:26:27984 const FilePath temp_path = temp_dir.GetPath();
Joe Masonf4812182024-01-19 01:12:37985
986 TestChildLauncher child_launcher;
987 child_launcher.command_line().AppendSwitchPath(kTempDirFlag, temp_path);
988 ASSERT_TRUE(child_launcher.SpawnChildProcess(ChildMainString));
Robert Sesek3aff3362019-01-23 20:16:16989
990 WaitForEvent(temp_path, kSignalReady);
991
992 std::unique_ptr<ProcessMetrics> metrics =
Joe Masonf4812182024-01-19 01:12:37993 child_launcher.CreateChildProcessMetrics();
Robert Sesek3aff3362019-01-23 20:16:16994
995 const int fd_count = metrics->GetOpenFdCount();
996 EXPECT_GE(fd_count, 0);
997
998 ASSERT_TRUE(SignalEvent(temp_path, kSignalReadyAck));
999 WaitForEvent(temp_path, kSignalOpened);
1000
1001 EXPECT_EQ(fd_count + kChildNumFilesToOpen, metrics->GetOpenFdCount());
1002 ASSERT_TRUE(SignalEvent(temp_path, kSignalOpenedAck));
1003
thestigcf4c85b2015-12-16 08:33:301004 WaitForEvent(temp_path, kSignalClosed);
1005
Robert Sesek3aff3362019-01-23 20:16:161006 EXPECT_EQ(fd_count, metrics->GetOpenFdCount());
1007
Joe Masonf4812182024-01-19 01:12:371008 ASSERT_TRUE(child_launcher.TerminateChildProcess());
[email protected]cf46e3752013-12-02 01:01:011009}
Siddhartha5293d8a2017-12-21 01:09:541010
1011TEST(ProcessMetricsTest, GetOpenFdCount) {
Joe Masonf4812182024-01-19 01:12:371012 std::unique_ptr<ProcessMetrics> metrics =
1013 ProcessMetrics::CreateCurrentProcessMetrics();
Robert Sesek3aff3362019-01-23 20:16:161014
1015 ScopedTempDir temp_dir;
1016 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1017
Siddhartha5293d8a2017-12-21 01:09:541018 int fd_count = metrics->GetOpenFdCount();
1019 EXPECT_GT(fd_count, 0);
Robert Sesek3aff3362019-01-23 20:16:161020 File file(temp_dir.GetPath().AppendASCII("file"),
1021 File::FLAG_CREATE | File::FLAG_WRITE);
Siddhartha5293d8a2017-12-21 01:09:541022 int new_fd_count = metrics->GetOpenFdCount();
1023 EXPECT_GT(new_fd_count, 0);
1024 EXPECT_EQ(new_fd_count, fd_count + 1);
1025}
Dave Tapuska828a495c2024-03-26 17:33:031026#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
Robert Sesek3aff3362019-01-23 20:16:161027
Xiaohan Wang37e81612022-01-15 18:27:001028#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
Eric Seckler9db213952020-06-12 08:48:191029
Benoit Lize448ee882017-08-31 13:32:121030TEST(ProcessMetricsTestLinux, GetPageFaultCounts) {
Joe Masonf4812182024-01-19 01:12:371031 std::unique_ptr<ProcessMetrics> process_metrics =
1032 ProcessMetrics::CreateCurrentProcessMetrics();
Benoit Lize448ee882017-08-31 13:32:121033
1034 PageFaultCounts counts;
1035 ASSERT_TRUE(process_metrics->GetPageFaultCounts(&counts));
1036 ASSERT_GT(counts.minor, 0);
1037 ASSERT_GE(counts.major, 0);
1038
arthursonzogni38d9bf472019-04-15 13:00:111039 // Allocate and touch memory. Touching it is required to make sure that the
1040 // page fault count goes up, as memory is typically mapped lazily.
Benoit Lize448ee882017-08-31 13:32:121041 {
arthursonzogni38d9bf472019-04-15 13:00:111042 const size_t kMappedSize = 4 << 20; // 4 MiB.
1043
1044 WritableSharedMemoryRegion region =
1045 WritableSharedMemoryRegion::Create(kMappedSize);
1046 ASSERT_TRUE(region.IsValid());
1047
1048 WritableSharedMemoryMapping mapping = region.Map();
1049 ASSERT_TRUE(mapping.IsValid());
1050
1051 memset(mapping.memory(), 42, kMappedSize);
Benoit Lize448ee882017-08-31 13:32:121052 }
1053
1054 PageFaultCounts counts_after;
1055 ASSERT_TRUE(process_metrics->GetPageFaultCounts(&counts_after));
1056 ASSERT_GT(counts_after.minor, counts.minor);
1057 ASSERT_GE(counts_after.major, counts.major);
1058}
Eric Seckler9db213952020-06-12 08:48:191059
1060TEST(ProcessMetricsTestLinux, GetCumulativeCPUUsagePerThread) {
Joe Masonf4812182024-01-19 01:12:371061 std::unique_ptr<ProcessMetrics> metrics =
1062 ProcessMetrics::CreateCurrentProcessMetrics();
Eric Seckler9db213952020-06-12 08:48:191063
1064 Thread thread1("thread1");
1065 thread1.StartAndWaitForTesting();
1066 ASSERT_TRUE(thread1.IsRunning());
1067
1068 std::vector<std::string> vec1;
1069 thread1.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec1));
1070
1071 ProcessMetrics::CPUUsagePerThread prev_thread_times;
1072 EXPECT_TRUE(metrics->GetCumulativeCPUUsagePerThread(prev_thread_times));
1073
1074 // Should have at least the test runner thread and the thread spawned above.
1075 EXPECT_GE(prev_thread_times.size(), 2u);
Peter Kasting025a94252025-01-29 21:28:371076 EXPECT_TRUE(std::ranges::any_of(
Anton Bikineeva61fb572020-10-18 08:54:441077 prev_thread_times,
Eric Seckler9db213952020-06-12 08:48:191078 [&thread1](const std::pair<PlatformThreadId, base::TimeDelta>& entry) {
1079 return entry.first == thread1.GetThreadId();
1080 }));
Peter Kasting025a94252025-01-29 21:28:371081 EXPECT_TRUE(std::ranges::any_of(
Anton Bikineeva61fb572020-10-18 08:54:441082 prev_thread_times,
Eric Seckler9db213952020-06-12 08:48:191083 [](const std::pair<PlatformThreadId, base::TimeDelta>& entry) {
1084 return entry.first == base::PlatformThread::CurrentId();
1085 }));
1086
1087 for (const auto& entry : prev_thread_times) {
1088 EXPECT_GE(entry.second, base::TimeDelta());
1089 }
1090
1091 thread1.Stop();
1092
1093 ProcessMetrics::CPUUsagePerThread current_thread_times;
1094 EXPECT_TRUE(metrics->GetCumulativeCPUUsagePerThread(current_thread_times));
1095
1096 // The stopped thread may still be reported until the kernel cleans it up.
1097 EXPECT_GE(prev_thread_times.size(), 1u);
Peter Kasting025a94252025-01-29 21:28:371098 EXPECT_TRUE(std::ranges::any_of(
Anton Bikineeva61fb572020-10-18 08:54:441099 current_thread_times,
Eric Seckler9db213952020-06-12 08:48:191100 [](const std::pair<PlatformThreadId, base::TimeDelta>& entry) {
1101 return entry.first == base::PlatformThread::CurrentId();
1102 }));
1103
1104 // Reported times should not decrease.
1105 for (const auto& entry : current_thread_times) {
Peter Kasting025a94252025-01-29 21:28:371106 auto prev_it = std::ranges::find_if(
Anton Bikineeva61fb572020-10-18 08:54:441107 prev_thread_times,
Eric Seckler9db213952020-06-12 08:48:191108 [&entry](
1109 const std::pair<PlatformThreadId, base::TimeDelta>& prev_entry) {
1110 return entry.first == prev_entry.first;
1111 });
1112
Joe Masonf75bf182023-10-17 22:16:251113 if (prev_it != prev_thread_times.end()) {
Eric Seckler9db213952020-06-12 08:48:191114 EXPECT_GE(entry.second, prev_it->second);
Joe Masonf75bf182023-10-17 22:16:251115 }
Eric Seckler9db213952020-06-12 08:48:191116 }
1117}
Xiaohan Wang37e81612022-01-15 18:27:001118#endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) ||
1119 // BUILDFLAG(IS_CHROMEOS)
Benoit Lize448ee882017-08-31 13:32:121120
Joe Masonf75bf182023-10-17 22:16:251121} // namespace base::debug