process_metrics_unittest.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/process/process_metrics.h"
  5. #include <stddef.h>
  6. #include <stdint.h>
  7. #include <memory>
  8. #include <sstream>
  9. #include <string>
  10. #include <vector>
  11. #include "base/bind.h"
  12. #include "base/command_line.h"
  13. #include "base/files/file.h"
  14. #include "base/files/file_util.h"
  15. #include "base/files/scoped_temp_dir.h"
  16. #include "base/memory/shared_memory_mapping.h"
  17. #include "base/memory/writable_shared_memory_region.h"
  18. #include "base/ranges/algorithm.h"
  19. #include "base/strings/string_number_conversions.h"
  20. #include "base/strings/string_util.h"
  21. #include "base/strings/stringprintf.h"
  22. #include "base/system/sys_info.h"
  23. #include "base/test/multiprocess_test.h"
  24. #include "base/threading/thread.h"
  25. #include "build/build_config.h"
  26. #include "build/chromeos_buildflags.h"
  27. #include "testing/gtest/include/gtest/gtest.h"
  28. #include "testing/multiprocess_func_list.h"
  29. #if BUILDFLAG(IS_APPLE)
  30. #include <sys/mman.h>
  31. #endif
  32. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  33. #include "base/process/internal_linux.h"
  34. #endif
  35. namespace base {
  36. namespace debug {
  37. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
  38. BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_WIN) || \
  39. BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
  40. namespace {
  41. void BusyWork(std::vector<std::string>* vec) {
  42. int64_t test_value = 0;
  43. for (int i = 0; i < 100000; ++i) {
  44. ++test_value;
  45. vec->push_back(NumberToString(test_value));
  46. }
  47. }
  48. } // namespace
  49. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  50. // BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_WIN) ||
  51. // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
  52. // Tests for SystemMetrics.
  53. // Exists as a class so it can be a friend of SystemMetrics.
  54. class SystemMetricsTest : public testing::Test {
  55. public:
  56. SystemMetricsTest() = default;
  57. SystemMetricsTest(const SystemMetricsTest&) = delete;
  58. SystemMetricsTest& operator=(const SystemMetricsTest&) = delete;
  59. };
  60. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  61. TEST_F(SystemMetricsTest, IsValidDiskName) {
  62. const char invalid_input1[] = "";
  63. const char invalid_input2[] = "s";
  64. const char invalid_input3[] = "sdz+";
  65. const char invalid_input4[] = "hda0";
  66. const char invalid_input5[] = "mmcbl";
  67. const char invalid_input6[] = "mmcblka";
  68. const char invalid_input7[] = "mmcblkb";
  69. const char invalid_input8[] = "mmmblk0";
  70. EXPECT_FALSE(IsValidDiskName(invalid_input1));
  71. EXPECT_FALSE(IsValidDiskName(invalid_input2));
  72. EXPECT_FALSE(IsValidDiskName(invalid_input3));
  73. EXPECT_FALSE(IsValidDiskName(invalid_input4));
  74. EXPECT_FALSE(IsValidDiskName(invalid_input5));
  75. EXPECT_FALSE(IsValidDiskName(invalid_input6));
  76. EXPECT_FALSE(IsValidDiskName(invalid_input7));
  77. EXPECT_FALSE(IsValidDiskName(invalid_input8));
  78. const char valid_input1[] = "sda";
  79. const char valid_input2[] = "sdaaaa";
  80. const char valid_input3[] = "hdz";
  81. const char valid_input4[] = "mmcblk0";
  82. const char valid_input5[] = "mmcblk999";
  83. EXPECT_TRUE(IsValidDiskName(valid_input1));
  84. EXPECT_TRUE(IsValidDiskName(valid_input2));
  85. EXPECT_TRUE(IsValidDiskName(valid_input3));
  86. EXPECT_TRUE(IsValidDiskName(valid_input4));
  87. EXPECT_TRUE(IsValidDiskName(valid_input5));
  88. }
  89. TEST_F(SystemMetricsTest, ParseMeminfo) {
  90. SystemMemoryInfoKB meminfo;
  91. const char invalid_input1[] = "abc";
  92. const char invalid_input2[] = "MemTotal:";
  93. // Partial file with no MemTotal
  94. const char invalid_input3[] =
  95. "MemFree: 3913968 kB\n"
  96. "Buffers: 2348340 kB\n"
  97. "Cached: 49071596 kB\n"
  98. "SwapCached: 12 kB\n"
  99. "Active: 36393900 kB\n"
  100. "Inactive: 21221496 kB\n"
  101. "Active(anon): 5674352 kB\n"
  102. "Inactive(anon): 633992 kB\n";
  103. EXPECT_FALSE(ParseProcMeminfo(invalid_input1, &meminfo));
  104. EXPECT_FALSE(ParseProcMeminfo(invalid_input2, &meminfo));
  105. EXPECT_FALSE(ParseProcMeminfo(invalid_input3, &meminfo));
  106. const char valid_input1[] =
  107. "MemTotal: 3981504 kB\n"
  108. "MemFree: 140764 kB\n"
  109. "MemAvailable: 535413 kB\n"
  110. "Buffers: 116480 kB\n"
  111. "Cached: 406160 kB\n"
  112. "SwapCached: 21304 kB\n"
  113. "Active: 3152040 kB\n"
  114. "Inactive: 472856 kB\n"
  115. "Active(anon): 2972352 kB\n"
  116. "Inactive(anon): 270108 kB\n"
  117. "Active(file): 179688 kB\n"
  118. "Inactive(file): 202748 kB\n"
  119. "Unevictable: 0 kB\n"
  120. "Mlocked: 0 kB\n"
  121. "SwapTotal: 5832280 kB\n"
  122. "SwapFree: 3672368 kB\n"
  123. "Dirty: 184 kB\n"
  124. "Writeback: 0 kB\n"
  125. "AnonPages: 3101224 kB\n"
  126. "Mapped: 142296 kB\n"
  127. "Shmem: 140204 kB\n"
  128. "Slab: 54212 kB\n"
  129. "SReclaimable: 30936 kB\n"
  130. "SUnreclaim: 23276 kB\n"
  131. "KernelStack: 2464 kB\n"
  132. "PageTables: 24812 kB\n"
  133. "NFS_Unstable: 0 kB\n"
  134. "Bounce: 0 kB\n"
  135. "WritebackTmp: 0 kB\n"
  136. "CommitLimit: 7823032 kB\n"
  137. "Committed_AS: 7973536 kB\n"
  138. "VmallocTotal: 34359738367 kB\n"
  139. "VmallocUsed: 375940 kB\n"
  140. "VmallocChunk: 34359361127 kB\n"
  141. "DirectMap4k: 72448 kB\n"
  142. "DirectMap2M: 4061184 kB\n";
  143. // output from a much older kernel where the Active and Inactive aren't
  144. // broken down into anon and file and Huge Pages are enabled
  145. const char valid_input2[] =
  146. "MemTotal: 255908 kB\n"
  147. "MemFree: 69936 kB\n"
  148. "Buffers: 15812 kB\n"
  149. "Cached: 115124 kB\n"
  150. "SwapCached: 0 kB\n"
  151. "Active: 92700 kB\n"
  152. "Inactive: 63792 kB\n"
  153. "HighTotal: 0 kB\n"
  154. "HighFree: 0 kB\n"
  155. "LowTotal: 255908 kB\n"
  156. "LowFree: 69936 kB\n"
  157. "SwapTotal: 524280 kB\n"
  158. "SwapFree: 524200 kB\n"
  159. "Dirty: 4 kB\n"
  160. "Writeback: 0 kB\n"
  161. "Mapped: 42236 kB\n"
  162. "Slab: 25912 kB\n"
  163. "Committed_AS: 118680 kB\n"
  164. "PageTables: 1236 kB\n"
  165. "VmallocTotal: 3874808 kB\n"
  166. "VmallocUsed: 1416 kB\n"
  167. "VmallocChunk: 3872908 kB\n"
  168. "HugePages_Total: 0\n"
  169. "HugePages_Free: 0\n"
  170. "Hugepagesize: 4096 kB\n";
  171. EXPECT_TRUE(ParseProcMeminfo(valid_input1, &meminfo));
  172. EXPECT_EQ(meminfo.total, 3981504);
  173. EXPECT_EQ(meminfo.free, 140764);
  174. EXPECT_EQ(meminfo.available, 535413);
  175. EXPECT_EQ(meminfo.buffers, 116480);
  176. EXPECT_EQ(meminfo.cached, 406160);
  177. EXPECT_EQ(meminfo.active_anon, 2972352);
  178. EXPECT_EQ(meminfo.active_file, 179688);
  179. EXPECT_EQ(meminfo.inactive_anon, 270108);
  180. EXPECT_EQ(meminfo.inactive_file, 202748);
  181. EXPECT_EQ(meminfo.swap_total, 5832280);
  182. EXPECT_EQ(meminfo.swap_free, 3672368);
  183. EXPECT_EQ(meminfo.dirty, 184);
  184. EXPECT_EQ(meminfo.reclaimable, 30936);
  185. #if BUILDFLAG(IS_CHROMEOS)
  186. EXPECT_EQ(meminfo.shmem, 140204);
  187. EXPECT_EQ(meminfo.slab, 54212);
  188. #endif
  189. EXPECT_EQ(355725u,
  190. base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo) / 1024);
  191. // Simulate as if there is no MemAvailable.
  192. meminfo.available = 0;
  193. EXPECT_EQ(374448u,
  194. base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo) / 1024);
  195. meminfo = {};
  196. EXPECT_TRUE(ParseProcMeminfo(valid_input2, &meminfo));
  197. EXPECT_EQ(meminfo.total, 255908);
  198. EXPECT_EQ(meminfo.free, 69936);
  199. EXPECT_EQ(meminfo.available, 0);
  200. EXPECT_EQ(meminfo.buffers, 15812);
  201. EXPECT_EQ(meminfo.cached, 115124);
  202. EXPECT_EQ(meminfo.swap_total, 524280);
  203. EXPECT_EQ(meminfo.swap_free, 524200);
  204. EXPECT_EQ(meminfo.dirty, 4);
  205. EXPECT_EQ(69936u,
  206. base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo) / 1024);
  207. }
  208. TEST_F(SystemMetricsTest, ParseVmstat) {
  209. VmStatInfo vmstat;
  210. // Part of vmstat from a 4.19 kernel.
  211. const char valid_input1[] =
  212. "pgpgin 2358216\n"
  213. "pgpgout 296072\n"
  214. "pswpin 345219\n"
  215. "pswpout 2605828\n"
  216. "pgalloc_dma32 8380235\n"
  217. "pgalloc_normal 3384525\n"
  218. "pgalloc_movable 0\n"
  219. "allocstall_dma32 0\n"
  220. "allocstall_normal 2028\n"
  221. "allocstall_movable 32559\n"
  222. "pgskip_dma32 0\n"
  223. "pgskip_normal 0\n"
  224. "pgskip_movable 0\n"
  225. "pgfree 11802722\n"
  226. "pgactivate 894917\n"
  227. "pgdeactivate 3255711\n"
  228. "pglazyfree 48\n"
  229. "pgfault 10043657\n"
  230. "pgmajfault 358901\n"
  231. "pgmajfault_s 2100\n"
  232. "pgmajfault_a 343211\n"
  233. "pgmajfault_f 13590\n"
  234. "pglazyfreed 0\n"
  235. "pgrefill 3429488\n"
  236. "pgsteal_kswapd 1466893\n"
  237. "pgsteal_direct 1771759\n"
  238. "pgscan_kswapd 1907332\n"
  239. "pgscan_direct 2118930\n"
  240. "pgscan_direct_throttle 154\n"
  241. "pginodesteal 3176\n"
  242. "slabs_scanned 293804\n"
  243. "kswapd_inodesteal 16753\n"
  244. "kswapd_low_wmark_hit_quickly 10\n"
  245. "kswapd_high_wmark_hit_quickly 423\n"
  246. "pageoutrun 441\n"
  247. "pgrotated 1636\n"
  248. "drop_pagecache 0\n"
  249. "drop_slab 0\n"
  250. "oom_kill 18\n";
  251. const char valid_input2[] =
  252. "pgpgin 2606135\n"
  253. "pgpgout 1359128\n"
  254. "pswpin 899959\n"
  255. "pswpout 19761244\n"
  256. "pgalloc_dma 31\n"
  257. "pgalloc_dma32 18139339\n"
  258. "pgalloc_normal 44085950\n"
  259. "pgalloc_movable 0\n"
  260. "allocstall_dma 0\n"
  261. "allocstall_dma32 0\n"
  262. "allocstall_normal 18881\n"
  263. "allocstall_movable 169527\n"
  264. "pgskip_dma 0\n"
  265. "pgskip_dma32 0\n"
  266. "pgskip_normal 0\n"
  267. "pgskip_movable 0\n"
  268. "pgfree 63060999\n"
  269. "pgactivate 1703494\n"
  270. "pgdeactivate 20537803\n"
  271. "pglazyfree 163\n"
  272. "pgfault 45201169\n"
  273. "pgmajfault 609626\n"
  274. "pgmajfault_s 7488\n"
  275. "pgmajfault_a 591793\n"
  276. "pgmajfault_f 10345\n"
  277. "pglazyfreed 0\n"
  278. "pgrefill 20673453\n"
  279. "pgsteal_kswapd 11802772\n"
  280. "pgsteal_direct 8618160\n"
  281. "pgscan_kswapd 12640517\n"
  282. "pgscan_direct 9092230\n"
  283. "pgscan_direct_throttle 638\n"
  284. "pginodesteal 1716\n"
  285. "slabs_scanned 2594642\n"
  286. "kswapd_inodesteal 67358\n"
  287. "kswapd_low_wmark_hit_quickly 52\n"
  288. "kswapd_high_wmark_hit_quickly 11\n"
  289. "pageoutrun 83\n"
  290. "pgrotated 977\n"
  291. "drop_pagecache 1\n"
  292. "drop_slab 1\n"
  293. "oom_kill 1\n"
  294. "pgmigrate_success 3202\n"
  295. "pgmigrate_fail 795\n";
  296. const char valid_input3[] =
  297. "pswpin 12\n"
  298. "pswpout 901\n"
  299. "pgmajfault 18881\n";
  300. EXPECT_TRUE(ParseProcVmstat(valid_input1, &vmstat));
  301. EXPECT_EQ(345219LU, vmstat.pswpin);
  302. EXPECT_EQ(2605828LU, vmstat.pswpout);
  303. EXPECT_EQ(358901LU, vmstat.pgmajfault);
  304. EXPECT_EQ(18LU, vmstat.oom_kill);
  305. EXPECT_TRUE(ParseProcVmstat(valid_input2, &vmstat));
  306. EXPECT_EQ(899959LU, vmstat.pswpin);
  307. EXPECT_EQ(19761244LU, vmstat.pswpout);
  308. EXPECT_EQ(609626LU, vmstat.pgmajfault);
  309. EXPECT_EQ(1LU, vmstat.oom_kill);
  310. EXPECT_TRUE(ParseProcVmstat(valid_input3, &vmstat));
  311. EXPECT_EQ(12LU, vmstat.pswpin);
  312. EXPECT_EQ(901LU, vmstat.pswpout);
  313. EXPECT_EQ(18881LU, vmstat.pgmajfault);
  314. EXPECT_EQ(0LU, vmstat.oom_kill);
  315. const char missing_pgmajfault_input[] =
  316. "pswpin 12\n"
  317. "pswpout 901\n";
  318. EXPECT_FALSE(ParseProcVmstat(missing_pgmajfault_input, &vmstat));
  319. const char empty_input[] = "";
  320. EXPECT_FALSE(ParseProcVmstat(empty_input, &vmstat));
  321. }
  322. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  323. // BUILDFLAG(IS_ANDROID)
  324. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
  325. BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_WIN) || \
  326. BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
  327. // Test that ProcessMetrics::GetPlatformIndependentCPUUsage() doesn't return
  328. // negative values when the number of threads running on the process decreases
  329. // between two successive calls to it.
  330. TEST_F(SystemMetricsTest, TestNoNegativeCpuUsage) {
  331. ProcessHandle handle = GetCurrentProcessHandle();
  332. std::unique_ptr<ProcessMetrics> metrics(
  333. ProcessMetrics::CreateProcessMetrics(handle));
  334. EXPECT_GE(metrics->GetPlatformIndependentCPUUsage(), 0.0);
  335. Thread thread1("thread1");
  336. Thread thread2("thread2");
  337. Thread thread3("thread3");
  338. thread1.StartAndWaitForTesting();
  339. thread2.StartAndWaitForTesting();
  340. thread3.StartAndWaitForTesting();
  341. ASSERT_TRUE(thread1.IsRunning());
  342. ASSERT_TRUE(thread2.IsRunning());
  343. ASSERT_TRUE(thread3.IsRunning());
  344. std::vector<std::string> vec1;
  345. std::vector<std::string> vec2;
  346. std::vector<std::string> vec3;
  347. thread1.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec1));
  348. thread2.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec2));
  349. thread3.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec3));
  350. TimeDelta prev_cpu_usage = metrics->GetCumulativeCPUUsage();
  351. EXPECT_GE(prev_cpu_usage, TimeDelta());
  352. EXPECT_GE(metrics->GetPlatformIndependentCPUUsage(), 0.0);
  353. thread1.Stop();
  354. TimeDelta current_cpu_usage = metrics->GetCumulativeCPUUsage();
  355. EXPECT_GE(current_cpu_usage, prev_cpu_usage);
  356. prev_cpu_usage = current_cpu_usage;
  357. EXPECT_GE(metrics->GetPlatformIndependentCPUUsage(), 0.0);
  358. thread2.Stop();
  359. current_cpu_usage = metrics->GetCumulativeCPUUsage();
  360. EXPECT_GE(current_cpu_usage, prev_cpu_usage);
  361. prev_cpu_usage = current_cpu_usage;
  362. EXPECT_GE(metrics->GetPlatformIndependentCPUUsage(), 0.0);
  363. thread3.Stop();
  364. current_cpu_usage = metrics->GetCumulativeCPUUsage();
  365. EXPECT_GE(current_cpu_usage, prev_cpu_usage);
  366. EXPECT_GE(metrics->GetPlatformIndependentCPUUsage(), 0.0);
  367. }
  368. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  369. // BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_WIN) ||
  370. // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
  371. #if BUILDFLAG(IS_CHROMEOS)
  372. TEST_F(SystemMetricsTest, ParseZramMmStat) {
  373. SwapInfo swapinfo;
  374. const char invalid_input1[] = "aaa";
  375. const char invalid_input2[] = "1 2 3 4 5 6";
  376. const char invalid_input3[] = "a 2 3 4 5 6 7";
  377. EXPECT_FALSE(ParseZramMmStat(invalid_input1, &swapinfo));
  378. EXPECT_FALSE(ParseZramMmStat(invalid_input2, &swapinfo));
  379. EXPECT_FALSE(ParseZramMmStat(invalid_input3, &swapinfo));
  380. const char valid_input1[] =
  381. "17715200 5008166 566062 0 1225715712 127 183842";
  382. EXPECT_TRUE(ParseZramMmStat(valid_input1, &swapinfo));
  383. EXPECT_EQ(17715200ULL, swapinfo.orig_data_size);
  384. EXPECT_EQ(5008166ULL, swapinfo.compr_data_size);
  385. EXPECT_EQ(566062ULL, swapinfo.mem_used_total);
  386. }
  387. TEST_F(SystemMetricsTest, ParseZramStat) {
  388. SwapInfo swapinfo;
  389. const char invalid_input1[] = "aaa";
  390. const char invalid_input2[] = "1 2 3 4 5 6 7 8 9 10";
  391. const char invalid_input3[] = "a 2 3 4 5 6 7 8 9 10 11";
  392. EXPECT_FALSE(ParseZramStat(invalid_input1, &swapinfo));
  393. EXPECT_FALSE(ParseZramStat(invalid_input2, &swapinfo));
  394. EXPECT_FALSE(ParseZramStat(invalid_input3, &swapinfo));
  395. const char valid_input1[] =
  396. "299 0 2392 0 1 0 8 0 0 0 0";
  397. EXPECT_TRUE(ParseZramStat(valid_input1, &swapinfo));
  398. EXPECT_EQ(299ULL, swapinfo.num_reads);
  399. EXPECT_EQ(1ULL, swapinfo.num_writes);
  400. }
  401. #endif // BUILDFLAG(IS_CHROMEOS)
  402. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) || \
  403. BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  404. TEST(SystemMetrics2Test, GetSystemMemoryInfo) {
  405. SystemMemoryInfoKB info;
  406. EXPECT_TRUE(GetSystemMemoryInfo(&info));
  407. // Ensure each field received a value.
  408. EXPECT_GT(info.total, 0);
  409. #if BUILDFLAG(IS_WIN)
  410. EXPECT_GT(info.avail_phys, 0);
  411. #else
  412. EXPECT_GT(info.free, 0);
  413. #endif
  414. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  415. EXPECT_GT(info.buffers, 0);
  416. EXPECT_GT(info.cached, 0);
  417. EXPECT_GT(info.active_anon + info.inactive_anon, 0);
  418. EXPECT_GT(info.active_file + info.inactive_file, 0);
  419. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  420. // BUILDFLAG(IS_ANDROID)
  421. // All the values should be less than the total amount of memory.
  422. #if !BUILDFLAG(IS_WIN) && !BUILDFLAG(IS_IOS)
  423. // TODO(crbug.com/711450): re-enable the following assertion on iOS.
  424. EXPECT_LT(info.free, info.total);
  425. #endif
  426. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  427. EXPECT_LT(info.buffers, info.total);
  428. EXPECT_LT(info.cached, info.total);
  429. EXPECT_LT(info.active_anon, info.total);
  430. EXPECT_LT(info.inactive_anon, info.total);
  431. EXPECT_LT(info.active_file, info.total);
  432. EXPECT_LT(info.inactive_file, info.total);
  433. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  434. // BUILDFLAG(IS_ANDROID)
  435. #if BUILDFLAG(IS_APPLE)
  436. EXPECT_GT(info.file_backed, 0);
  437. #endif
  438. #if BUILDFLAG(IS_CHROMEOS)
  439. // Chrome OS exposes shmem.
  440. EXPECT_GT(info.shmem, 0);
  441. EXPECT_LT(info.shmem, info.total);
  442. #endif
  443. }
  444. #endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) ||
  445. // BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  446. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  447. TEST(ProcessMetricsTest, ParseProcStatCPU) {
  448. // /proc/self/stat for a process running "top".
  449. const char kTopStat[] = "960 (top) S 16230 960 16230 34818 960 "
  450. "4202496 471 0 0 0 "
  451. "12 16 0 0 " // <- These are the goods.
  452. "20 0 1 0 121946157 15077376 314 18446744073709551615 4194304 "
  453. "4246868 140733983044336 18446744073709551615 140244213071219 "
  454. "0 0 0 138047495 0 0 0 17 1 0 0 0 0 0";
  455. EXPECT_EQ(12 + 16, ParseProcStatCPU(kTopStat));
  456. // cat /proc/self/stat on a random other machine I have.
  457. const char kSelfStat[] = "5364 (cat) R 5354 5364 5354 34819 5364 "
  458. "0 142 0 0 0 "
  459. "0 0 0 0 " // <- No CPU, apparently.
  460. "16 0 1 0 1676099790 2957312 114 4294967295 134512640 134528148 "
  461. "3221224832 3221224344 3086339742 0 0 0 0 0 0 0 17 0 0 0";
  462. EXPECT_EQ(0, ParseProcStatCPU(kSelfStat));
  463. // Some weird long-running process with a weird name that I created for the
  464. // purposes of this test.
  465. const char kWeirdNameStat[] = "26115 (Hello) You ())) ) R 24614 26115 24614"
  466. " 34839 26115 4218880 227 0 0 0 "
  467. "5186 11 0 0 "
  468. "20 0 1 0 36933953 4296704 90 18446744073709551615 4194304 4196116 "
  469. "140735857761568 140735857761160 4195644 0 0 0 0 0 0 0 17 14 0 0 0 0 0 "
  470. "6295056 6295616 16519168 140735857770710 140735857770737 "
  471. "140735857770737 140735857774557 0";
  472. EXPECT_EQ(5186 + 11, ParseProcStatCPU(kWeirdNameStat));
  473. }
  474. TEST(ProcessMetricsTest, ParseProcTimeInState) {
  475. ProcessHandle handle = GetCurrentProcessHandle();
  476. std::unique_ptr<ProcessMetrics> metrics(
  477. ProcessMetrics::CreateProcessMetrics(handle));
  478. ProcessMetrics::TimeInStatePerThread time_in_state;
  479. const char kStatThread123[] =
  480. "cpu0\n"
  481. "100000 4\n"
  482. "200000 5\n"
  483. "300000 0\n"
  484. "cpu4\n"
  485. "400000 3\n"
  486. "500000 2\n";
  487. EXPECT_TRUE(
  488. metrics->ParseProcTimeInState(kStatThread123, 123, time_in_state));
  489. // Zero-valued entry should not exist.
  490. ASSERT_EQ(time_in_state.size(), 4u);
  491. EXPECT_EQ(time_in_state[0].thread_id, 123);
  492. EXPECT_EQ(time_in_state[0].cluster_core_index, 0u);
  493. EXPECT_EQ(time_in_state[0].core_frequency_khz, 100000u);
  494. EXPECT_EQ(time_in_state[0].cumulative_cpu_time, base::Milliseconds(40));
  495. EXPECT_EQ(time_in_state[1].thread_id, 123);
  496. EXPECT_EQ(time_in_state[1].cluster_core_index, 0u);
  497. EXPECT_EQ(time_in_state[1].core_frequency_khz, 200000u);
  498. EXPECT_EQ(time_in_state[1].cumulative_cpu_time, base::Milliseconds(50));
  499. EXPECT_EQ(time_in_state[2].thread_id, 123);
  500. EXPECT_EQ(time_in_state[2].cluster_core_index, 4u);
  501. EXPECT_EQ(time_in_state[2].core_frequency_khz, 400000u);
  502. EXPECT_EQ(time_in_state[2].cumulative_cpu_time, base::Milliseconds(30));
  503. EXPECT_EQ(time_in_state[3].thread_id, 123);
  504. EXPECT_EQ(time_in_state[3].cluster_core_index, 4u);
  505. EXPECT_EQ(time_in_state[3].core_frequency_khz, 500000u);
  506. EXPECT_EQ(time_in_state[3].cumulative_cpu_time, base::Milliseconds(20));
  507. // Calling ParseProcTimeInState again adds to the vector.
  508. const char kStatThread456[] =
  509. "cpu0\n"
  510. "\n" // extra empty line is fine.
  511. "1000000 10"; // missing "\n" at end is fine.
  512. EXPECT_TRUE(
  513. metrics->ParseProcTimeInState(kStatThread456, 456, time_in_state));
  514. ASSERT_EQ(time_in_state.size(), 5u);
  515. EXPECT_EQ(time_in_state[4].thread_id, 456);
  516. EXPECT_EQ(time_in_state[4].cluster_core_index, 0u);
  517. EXPECT_EQ(time_in_state[4].core_frequency_khz, 1000000u);
  518. EXPECT_EQ(time_in_state[4].cumulative_cpu_time, base::Milliseconds(100));
  519. // Calling ParseProcTimeInState with invalid data returns false.
  520. EXPECT_FALSE(
  521. metrics->ParseProcTimeInState("100000 5\n" // no header
  522. "200000 6\n",
  523. 123, time_in_state));
  524. EXPECT_FALSE(
  525. metrics->ParseProcTimeInState("cpu0\n"
  526. "100000\n", // no time value
  527. 123, time_in_state));
  528. EXPECT_FALSE(
  529. metrics->ParseProcTimeInState("header0\n" // invalid header / line
  530. "100000 5\n",
  531. 123, time_in_state));
  532. EXPECT_FALSE(
  533. metrics->ParseProcTimeInState("cpu0\n"
  534. "100000 5\n"
  535. "invalid334 4\n", // invalid header / line
  536. 123, time_in_state));
  537. }
  538. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  539. // BUILDFLAG(IS_ANDROID)
  540. // Disable on Android because base_unittests runs inside a Dalvik VM that
  541. // starts and stop threads (crbug.com/175563).
  542. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  543. // http://crbug.com/396455
  544. TEST(ProcessMetricsTest, DISABLED_GetNumberOfThreads) {
  545. const ProcessHandle current = GetCurrentProcessHandle();
  546. const int64_t initial_threads = GetNumberOfThreads(current);
  547. ASSERT_GT(initial_threads, 0);
  548. const int kNumAdditionalThreads = 10;
  549. {
  550. std::unique_ptr<Thread> my_threads[kNumAdditionalThreads];
  551. for (int i = 0; i < kNumAdditionalThreads; ++i) {
  552. my_threads[i] = std::make_unique<Thread>("GetNumberOfThreadsTest");
  553. my_threads[i]->Start();
  554. ASSERT_EQ(GetNumberOfThreads(current), initial_threads + 1 + i);
  555. }
  556. }
  557. // The Thread destructor will stop them.
  558. ASSERT_EQ(initial_threads, GetNumberOfThreads(current));
  559. }
  560. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  561. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
  562. namespace {
  563. // Keep these in sync so the GetChildOpenFdCount test can refer to correct test
  564. // main.
  565. #define ChildMain ChildFdCount
  566. #define ChildMainString "ChildFdCount"
  567. // Command line flag name and file name used for synchronization.
  568. const char kTempDirFlag[] = "temp-dir";
  569. const char kSignalReady[] = "ready";
  570. const char kSignalReadyAck[] = "ready-ack";
  571. const char kSignalOpened[] = "opened";
  572. const char kSignalOpenedAck[] = "opened-ack";
  573. const char kSignalClosed[] = "closed";
  574. const int kChildNumFilesToOpen = 100;
  575. bool SignalEvent(const FilePath& signal_dir, const char* signal_file) {
  576. File file(signal_dir.AppendASCII(signal_file),
  577. File::FLAG_CREATE | File::FLAG_WRITE);
  578. return file.IsValid();
  579. }
  580. // Check whether an event was signaled.
  581. bool CheckEvent(const FilePath& signal_dir, const char* signal_file) {
  582. File file(signal_dir.AppendASCII(signal_file),
  583. File::FLAG_OPEN | File::FLAG_READ);
  584. return file.IsValid();
  585. }
  586. // Busy-wait for an event to be signaled.
  587. void WaitForEvent(const FilePath& signal_dir, const char* signal_file) {
  588. while (!CheckEvent(signal_dir, signal_file))
  589. PlatformThread::Sleep(Milliseconds(10));
  590. }
  591. // Subprocess to test the number of open file descriptors.
  592. MULTIPROCESS_TEST_MAIN(ChildMain) {
  593. CommandLine* command_line = CommandLine::ForCurrentProcess();
  594. const FilePath temp_path = command_line->GetSwitchValuePath(kTempDirFlag);
  595. CHECK(DirectoryExists(temp_path));
  596. CHECK(SignalEvent(temp_path, kSignalReady));
  597. WaitForEvent(temp_path, kSignalReadyAck);
  598. std::vector<File> files;
  599. for (int i = 0; i < kChildNumFilesToOpen; ++i) {
  600. files.emplace_back(temp_path.AppendASCII(StringPrintf("file.%d", i)),
  601. File::FLAG_CREATE | File::FLAG_WRITE);
  602. }
  603. CHECK(SignalEvent(temp_path, kSignalOpened));
  604. WaitForEvent(temp_path, kSignalOpenedAck);
  605. files.clear();
  606. CHECK(SignalEvent(temp_path, kSignalClosed));
  607. // Wait to be terminated.
  608. while (true)
  609. PlatformThread::Sleep(Seconds(1));
  610. }
  611. } // namespace
  612. TEST(ProcessMetricsTest, GetChildOpenFdCount) {
  613. ScopedTempDir temp_dir;
  614. ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  615. const FilePath temp_path = temp_dir.GetPath();
  616. CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
  617. child_command_line.AppendSwitchPath(kTempDirFlag, temp_path);
  618. Process child = SpawnMultiProcessTestChild(
  619. ChildMainString, child_command_line, LaunchOptions());
  620. ASSERT_TRUE(child.IsValid());
  621. WaitForEvent(temp_path, kSignalReady);
  622. std::unique_ptr<ProcessMetrics> metrics =
  623. #if BUILDFLAG(IS_APPLE)
  624. ProcessMetrics::CreateProcessMetrics(child.Handle(), nullptr);
  625. #else
  626. ProcessMetrics::CreateProcessMetrics(child.Handle());
  627. #endif // BUILDFLAG(IS_APPLE)
  628. const int fd_count = metrics->GetOpenFdCount();
  629. EXPECT_GE(fd_count, 0);
  630. ASSERT_TRUE(SignalEvent(temp_path, kSignalReadyAck));
  631. WaitForEvent(temp_path, kSignalOpened);
  632. EXPECT_EQ(fd_count + kChildNumFilesToOpen, metrics->GetOpenFdCount());
  633. ASSERT_TRUE(SignalEvent(temp_path, kSignalOpenedAck));
  634. WaitForEvent(temp_path, kSignalClosed);
  635. EXPECT_EQ(fd_count, metrics->GetOpenFdCount());
  636. ASSERT_TRUE(child.Terminate(0, true));
  637. }
  638. TEST(ProcessMetricsTest, GetOpenFdCount) {
  639. base::ProcessHandle process = base::GetCurrentProcessHandle();
  640. std::unique_ptr<base::ProcessMetrics> metrics =
  641. #if BUILDFLAG(IS_APPLE)
  642. ProcessMetrics::CreateProcessMetrics(process, nullptr);
  643. #else
  644. ProcessMetrics::CreateProcessMetrics(process);
  645. #endif // BUILDFLAG(IS_APPLE)
  646. ScopedTempDir temp_dir;
  647. ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  648. int fd_count = metrics->GetOpenFdCount();
  649. EXPECT_GT(fd_count, 0);
  650. File file(temp_dir.GetPath().AppendASCII("file"),
  651. File::FLAG_CREATE | File::FLAG_WRITE);
  652. int new_fd_count = metrics->GetOpenFdCount();
  653. EXPECT_GT(new_fd_count, 0);
  654. EXPECT_EQ(new_fd_count, fd_count + 1);
  655. }
  656. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
  657. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  658. TEST(ProcessMetricsTestLinux, GetPageFaultCounts) {
  659. std::unique_ptr<base::ProcessMetrics> process_metrics(
  660. base::ProcessMetrics::CreateProcessMetrics(
  661. base::GetCurrentProcessHandle()));
  662. PageFaultCounts counts;
  663. ASSERT_TRUE(process_metrics->GetPageFaultCounts(&counts));
  664. ASSERT_GT(counts.minor, 0);
  665. ASSERT_GE(counts.major, 0);
  666. // Allocate and touch memory. Touching it is required to make sure that the
  667. // page fault count goes up, as memory is typically mapped lazily.
  668. {
  669. const size_t kMappedSize = 4 << 20; // 4 MiB.
  670. WritableSharedMemoryRegion region =
  671. WritableSharedMemoryRegion::Create(kMappedSize);
  672. ASSERT_TRUE(region.IsValid());
  673. WritableSharedMemoryMapping mapping = region.Map();
  674. ASSERT_TRUE(mapping.IsValid());
  675. memset(mapping.memory(), 42, kMappedSize);
  676. }
  677. PageFaultCounts counts_after;
  678. ASSERT_TRUE(process_metrics->GetPageFaultCounts(&counts_after));
  679. ASSERT_GT(counts_after.minor, counts.minor);
  680. ASSERT_GE(counts_after.major, counts.major);
  681. }
  682. TEST(ProcessMetricsTestLinux, GetCumulativeCPUUsagePerThread) {
  683. ProcessHandle handle = GetCurrentProcessHandle();
  684. std::unique_ptr<ProcessMetrics> metrics(
  685. ProcessMetrics::CreateProcessMetrics(handle));
  686. Thread thread1("thread1");
  687. thread1.StartAndWaitForTesting();
  688. ASSERT_TRUE(thread1.IsRunning());
  689. std::vector<std::string> vec1;
  690. thread1.task_runner()->PostTask(FROM_HERE, BindOnce(&BusyWork, &vec1));
  691. ProcessMetrics::CPUUsagePerThread prev_thread_times;
  692. EXPECT_TRUE(metrics->GetCumulativeCPUUsagePerThread(prev_thread_times));
  693. // Should have at least the test runner thread and the thread spawned above.
  694. EXPECT_GE(prev_thread_times.size(), 2u);
  695. EXPECT_TRUE(ranges::any_of(
  696. prev_thread_times,
  697. [&thread1](const std::pair<PlatformThreadId, base::TimeDelta>& entry) {
  698. return entry.first == thread1.GetThreadId();
  699. }));
  700. EXPECT_TRUE(ranges::any_of(
  701. prev_thread_times,
  702. [](const std::pair<PlatformThreadId, base::TimeDelta>& entry) {
  703. return entry.first == base::PlatformThread::CurrentId();
  704. }));
  705. for (const auto& entry : prev_thread_times) {
  706. EXPECT_GE(entry.second, base::TimeDelta());
  707. }
  708. thread1.Stop();
  709. ProcessMetrics::CPUUsagePerThread current_thread_times;
  710. EXPECT_TRUE(metrics->GetCumulativeCPUUsagePerThread(current_thread_times));
  711. // The stopped thread may still be reported until the kernel cleans it up.
  712. EXPECT_GE(prev_thread_times.size(), 1u);
  713. EXPECT_TRUE(ranges::any_of(
  714. current_thread_times,
  715. [](const std::pair<PlatformThreadId, base::TimeDelta>& entry) {
  716. return entry.first == base::PlatformThread::CurrentId();
  717. }));
  718. // Reported times should not decrease.
  719. for (const auto& entry : current_thread_times) {
  720. auto prev_it = ranges::find_if(
  721. prev_thread_times,
  722. [&entry](
  723. const std::pair<PlatformThreadId, base::TimeDelta>& prev_entry) {
  724. return entry.first == prev_entry.first;
  725. });
  726. if (prev_it != prev_thread_times.end())
  727. EXPECT_GE(entry.second, prev_it->second);
  728. }
  729. }
  730. TEST(ProcessMetricsTestLinux, GetPerThreadCumulativeCPUTimeInState) {
  731. ProcessHandle handle = GetCurrentProcessHandle();
  732. std::unique_ptr<ProcessMetrics> metrics(
  733. ProcessMetrics::CreateProcessMetrics(handle));
  734. // Only some test systems will support GetPerThreadCumulativeCPUTimeInState,
  735. // as it relies on /proc/pid/task/tid/time_in_state support in the kernel. In
  736. // Android, this is only supported in newer kernels with a patch such as this:
  737. // https://android-review.googlesource.com/c/kernel/common/+/610460/.
  738. bool expect_success;
  739. std::string contents;
  740. {
  741. FilePath time_in_state_path = FilePath("/proc")
  742. .Append(NumberToString(handle))
  743. .Append("task")
  744. .Append(NumberToString(handle))
  745. .Append("time_in_state");
  746. expect_success = ReadFileToString(time_in_state_path, &contents) &&
  747. StartsWith(contents, "cpu", CompareCase::SENSITIVE);
  748. }
  749. ProcessMetrics::TimeInStatePerThread prev_thread_times;
  750. EXPECT_EQ(metrics->GetPerThreadCumulativeCPUTimeInState(prev_thread_times),
  751. expect_success)
  752. << "time_in_state example contents: \n"
  753. << contents;
  754. // Only non-zero entries are reported.
  755. for (const auto& entry : prev_thread_times) {
  756. EXPECT_NE(entry.thread_id, 0);
  757. EXPECT_GT(entry.cumulative_cpu_time, base::TimeDelta());
  758. }
  759. ProcessMetrics::TimeInStatePerThread current_thread_times;
  760. EXPECT_EQ(metrics->GetPerThreadCumulativeCPUTimeInState(current_thread_times),
  761. expect_success);
  762. // Reported times should not decrease.
  763. for (const auto& entry : current_thread_times) {
  764. auto prev_it = ranges::find_if(
  765. prev_thread_times,
  766. [&entry](const ProcessMetrics::ThreadTimeInState& prev_entry) {
  767. return entry.thread_id == prev_entry.thread_id &&
  768. entry.core_type == prev_entry.core_type &&
  769. entry.core_frequency_khz == prev_entry.core_frequency_khz;
  770. });
  771. if (prev_it != prev_thread_times.end())
  772. EXPECT_GE(entry.cumulative_cpu_time, prev_it->cumulative_cpu_time);
  773. }
  774. }
  775. #endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) ||
  776. // BUILDFLAG(IS_CHROMEOS)
  777. } // namespace debug
  778. } // namespace base