1 // Copyright (c) 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 
5 #include "base/process/process_metrics.h"
6 
7 #include <dirent.h>
8 #include <fcntl.h>
9 #include <inttypes.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <sys/stat.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 
17 #include <utility>
18 
19 #include "base/cpu.h"
20 #include "base/files/dir_reader_posix.h"
21 #include "base/files/file_util.h"
22 #include "base/logging.h"
23 #include "base/memory/ptr_util.h"
24 #include "base/notreached.h"
25 #include "base/optional.h"
26 #include "base/process/internal_linux.h"
27 #include "base/process/process_metrics_iocounters.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_tokenizer.h"
31 #include "base/strings/string_util.h"
32 #include "base/system/sys_info.h"
33 #include "base/threading/thread_restrictions.h"
34 #include "build/build_config.h"
35 
36 namespace base {
37 
38 namespace {
39 
TrimKeyValuePairs(StringPairs * pairs)40 void TrimKeyValuePairs(StringPairs* pairs) {
41   for (auto& pair : *pairs) {
42     TrimWhitespaceASCII(pair.first, TRIM_ALL, &pair.first);
43     TrimWhitespaceASCII(pair.second, TRIM_ALL, &pair.second);
44   }
45 }
46 
47 #if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
48 // Read a file with a single number string and return the number as a uint64_t.
ReadFileToUint64(const FilePath & file)49 uint64_t ReadFileToUint64(const FilePath& file) {
50   std::string file_contents;
51   if (!ReadFileToString(file, &file_contents))
52     return 0;
53   TrimWhitespaceASCII(file_contents, TRIM_ALL, &file_contents);
54   uint64_t file_contents_uint64 = 0;
55   if (!StringToUint64(file_contents, &file_contents_uint64))
56     return 0;
57   return file_contents_uint64;
58 }
59 #endif
60 
61 // Read |filename| in /proc/<pid>/, split the entries into key/value pairs, and
62 // trim the key and value. On success, return true and write the trimmed
63 // key/value pairs into |key_value_pairs|.
ReadProcFileToTrimmedStringPairs(pid_t pid,StringPiece filename,StringPairs * key_value_pairs)64 bool ReadProcFileToTrimmedStringPairs(pid_t pid,
65                                       StringPiece filename,
66                                       StringPairs* key_value_pairs) {
67   std::string status_data;
68   FilePath status_file = internal::GetProcPidDir(pid).Append(filename);
69   if (!internal::ReadProcFile(status_file, &status_data))
70     return false;
71   SplitStringIntoKeyValuePairs(status_data, ':', '\n', key_value_pairs);
72   TrimKeyValuePairs(key_value_pairs);
73   return true;
74 }
75 
76 // Read /proc/<pid>/status and return the value for |field|, or 0 on failure.
77 // Only works for fields in the form of "Field: value kB".
ReadProcStatusAndGetFieldAsSizeT(pid_t pid,StringPiece field)78 size_t ReadProcStatusAndGetFieldAsSizeT(pid_t pid, StringPiece field) {
79   StringPairs pairs;
80   if (!ReadProcFileToTrimmedStringPairs(pid, "status", &pairs))
81     return 0;
82 
83   for (const auto& pair : pairs) {
84     const std::string& key = pair.first;
85     const std::string& value_str = pair.second;
86     if (key != field)
87       continue;
88 
89     std::vector<StringPiece> split_value_str =
90         SplitStringPiece(value_str, " ", TRIM_WHITESPACE, SPLIT_WANT_ALL);
91     if (split_value_str.size() != 2 || split_value_str[1] != "kB") {
92       NOTREACHED();
93       return 0;
94     }
95     size_t value;
96     if (!StringToSizeT(split_value_str[0], &value)) {
97       NOTREACHED();
98       return 0;
99     }
100     return value;
101   }
102   // This can be reached if the process dies when proc is read -- in that case,
103   // the kernel can return missing fields.
104   return 0;
105 }
106 
107 #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
108 // Read /proc/<pid>/status and look for |field|. On success, return true and
109 // write the value for |field| into |result|.
110 // Only works for fields in the form of "field    :     uint_value"
ReadProcStatusAndGetFieldAsUint64(pid_t pid,StringPiece field,uint64_t * result)111 bool ReadProcStatusAndGetFieldAsUint64(pid_t pid,
112                                        StringPiece field,
113                                        uint64_t* result) {
114   StringPairs pairs;
115   if (!ReadProcFileToTrimmedStringPairs(pid, "status", &pairs))
116     return false;
117 
118   for (const auto& pair : pairs) {
119     const std::string& key = pair.first;
120     const std::string& value_str = pair.second;
121     if (key != field)
122       continue;
123 
124     uint64_t value;
125     if (!StringToUint64(value_str, &value))
126       return false;
127     *result = value;
128     return true;
129   }
130   return false;
131 }
132 #endif  // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
133 
134 // Get the total CPU from a proc stat buffer.  Return value is number of jiffies
135 // on success or 0 if parsing failed.
ParseTotalCPUTimeFromStats(const std::vector<std::string> & proc_stats)136 int64_t ParseTotalCPUTimeFromStats(const std::vector<std::string>& proc_stats) {
137   return internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_UTIME) +
138          internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_STIME);
139 }
140 
141 // Get the total CPU of a single process.  Return value is number of jiffies
142 // on success or -1 on error.
GetProcessCPU(pid_t pid)143 int64_t GetProcessCPU(pid_t pid) {
144   std::string buffer;
145   std::vector<std::string> proc_stats;
146   if (!internal::ReadProcStats(pid, &buffer) ||
147       !internal::ParseProcStats(buffer, &proc_stats)) {
148     return -1;
149   }
150 
151   return ParseTotalCPUTimeFromStats(proc_stats);
152 }
153 
SupportsPerTaskTimeInState()154 bool SupportsPerTaskTimeInState() {
155   FilePath time_in_state_path = internal::GetProcPidDir(GetCurrentProcId())
156                                     .Append("task")
157                                     .Append(NumberToString(GetCurrentProcId()))
158                                     .Append("time_in_state");
159   std::string contents;
160   return internal::ReadProcFile(time_in_state_path, &contents) &&
161          StartsWith(contents, "cpu");
162 }
163 
164 }  // namespace
165 
166 // static
CreateProcessMetrics(ProcessHandle process)167 std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
168     ProcessHandle process) {
169   return WrapUnique(new ProcessMetrics(process));
170 }
171 
GetResidentSetSize() const172 size_t ProcessMetrics::GetResidentSetSize() const {
173   return internal::ReadProcStatsAndGetFieldAsSizeT(process_, internal::VM_RSS) *
174       getpagesize();
175 }
176 
GetCumulativeCPUUsage()177 TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
178   return internal::ClockTicksToTimeDelta(GetProcessCPU(process_));
179 }
180 
GetCumulativeCPUUsagePerThread(CPUUsagePerThread & cpu_per_thread)181 bool ProcessMetrics::GetCumulativeCPUUsagePerThread(
182     CPUUsagePerThread& cpu_per_thread) {
183   cpu_per_thread.clear();
184 
185   internal::ForEachProcessTask(
186       process_,
187       [&cpu_per_thread](PlatformThreadId tid, const FilePath& task_path) {
188         FilePath thread_stat_path = task_path.Append("stat");
189 
190         std::string buffer;
191         std::vector<std::string> proc_stats;
192         if (!internal::ReadProcFile(thread_stat_path, &buffer) ||
193             !internal::ParseProcStats(buffer, &proc_stats)) {
194           return;
195         }
196 
197         TimeDelta thread_time = internal::ClockTicksToTimeDelta(
198             ParseTotalCPUTimeFromStats(proc_stats));
199         cpu_per_thread.emplace_back(tid, thread_time);
200       });
201 
202   return !cpu_per_thread.empty();
203 }
204 
GetPerThreadCumulativeCPUTimeInState(TimeInStatePerThread & time_in_state_per_thread)205 bool ProcessMetrics::GetPerThreadCumulativeCPUTimeInState(
206     TimeInStatePerThread& time_in_state_per_thread) {
207   time_in_state_per_thread.clear();
208 
209   // Check for per-pid/tid time_in_state support. If the current process's
210   // time_in_state file doesn't exist or conform to the expected format, there's
211   // no need to iterate the threads. This shouldn't change over the lifetime of
212   // the current process, so we cache it into a static constant.
213   static const bool kSupportsPerPidTimeInState = SupportsPerTaskTimeInState();
214   if (!kSupportsPerPidTimeInState)
215     return false;
216 
217   bool success = false;
218   internal::ForEachProcessTask(
219       process_, [&time_in_state_per_thread, &success, this](
220                     PlatformThreadId tid, const FilePath& task_path) {
221         FilePath time_in_state_path = task_path.Append("time_in_state");
222 
223         std::string buffer;
224         if (!internal::ReadProcFile(time_in_state_path, &buffer))
225           return;
226 
227         success |= ParseProcTimeInState(buffer, tid, time_in_state_per_thread);
228       });
229 
230   return success;
231 }
232 
233 // For the /proc/self/io file to exist, the Linux kernel must have
234 // CONFIG_TASK_IO_ACCOUNTING enabled.
GetIOCounters(IoCounters * io_counters) const235 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
236   StringPairs pairs;
237   if (!ReadProcFileToTrimmedStringPairs(process_, "io", &pairs))
238     return false;
239 
240   io_counters->OtherOperationCount = 0;
241   io_counters->OtherTransferCount = 0;
242 
243   for (const auto& pair : pairs) {
244     const std::string& key = pair.first;
245     const std::string& value_str = pair.second;
246     uint64_t* target_counter = nullptr;
247     if (key == "syscr")
248       target_counter = &io_counters->ReadOperationCount;
249     else if (key == "syscw")
250       target_counter = &io_counters->WriteOperationCount;
251     else if (key == "rchar")
252       target_counter = &io_counters->ReadTransferCount;
253     else if (key == "wchar")
254       target_counter = &io_counters->WriteTransferCount;
255     if (!target_counter)
256       continue;
257     bool converted = StringToUint64(value_str, target_counter);
258     DCHECK(converted);
259   }
260   return true;
261 }
262 
263 #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID)
GetVmSwapBytes() const264 uint64_t ProcessMetrics::GetVmSwapBytes() const {
265   return ReadProcStatusAndGetFieldAsSizeT(process_, "VmSwap") * 1024;
266 }
267 
GetPageFaultCounts(PageFaultCounts * counts) const268 bool ProcessMetrics::GetPageFaultCounts(PageFaultCounts* counts) const {
269   // We are not using internal::ReadStatsFileAndGetFieldAsInt64(), since it
270   // would read the file twice, and return inconsistent numbers.
271   std::string stats_data;
272   if (!internal::ReadProcStats(process_, &stats_data))
273     return false;
274   std::vector<std::string> proc_stats;
275   if (!internal::ParseProcStats(stats_data, &proc_stats))
276     return false;
277 
278   counts->minor =
279       internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_MINFLT);
280   counts->major =
281       internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_MAJFLT);
282   return true;
283 }
284 #endif  // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID)
285 
GetOpenFdCount() const286 int ProcessMetrics::GetOpenFdCount() const {
287   // Use /proc/<pid>/fd to count the number of entries there.
288   FilePath fd_path = internal::GetProcPidDir(process_).Append("fd");
289 
290   DirReaderPosix dir_reader(fd_path.value().c_str());
291   if (!dir_reader.IsValid())
292     return -1;
293 
294   int total_count = 0;
295   for (; dir_reader.Next(); ) {
296     const char* name = dir_reader.name();
297     if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
298       ++total_count;
299   }
300 
301   return total_count;
302 }
303 
GetOpenFdSoftLimit() const304 int ProcessMetrics::GetOpenFdSoftLimit() const {
305   // Use /proc/<pid>/limits to read the open fd limit.
306   FilePath fd_path = internal::GetProcPidDir(process_).Append("limits");
307 
308   std::string limits_contents;
309   if (!ReadFileToStringNonBlocking(fd_path, &limits_contents))
310     return -1;
311 
312   for (const auto& line : SplitStringPiece(
313            limits_contents, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
314     if (!StartsWith(line, "Max open files"))
315       continue;
316 
317     auto tokens =
318         SplitStringPiece(line, " ", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
319     if (tokens.size() > 3) {
320       int limit = -1;
321       if (!StringToInt(tokens[3], &limit))
322         return -1;
323       return limit;
324     }
325   }
326   return -1;
327 }
328 
329 #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
ProcessMetrics(ProcessHandle process)330 ProcessMetrics::ProcessMetrics(ProcessHandle process)
331     : process_(process), last_absolute_idle_wakeups_(0) {}
332 #else
ProcessMetrics(ProcessHandle process)333 ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process) {}
334 #endif
335 
GetSystemCommitCharge()336 size_t GetSystemCommitCharge() {
337   SystemMemoryInfoKB meminfo;
338   if (!GetSystemMemoryInfo(&meminfo))
339     return 0;
340   return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
341 }
342 
ParseProcStatCPU(StringPiece input)343 int ParseProcStatCPU(StringPiece input) {
344   // |input| may be empty if the process disappeared somehow.
345   // e.g. http://crbug.com/145811.
346   if (input.empty())
347     return -1;
348 
349   size_t start = input.find_last_of(')');
350   if (start == input.npos)
351     return -1;
352 
353   // Number of spaces remaining until reaching utime's index starting after the
354   // last ')'.
355   int num_spaces_remaining = internal::VM_UTIME - 1;
356 
357   size_t i = start;
358   while ((i = input.find(' ', i + 1)) != input.npos) {
359     // Validate the assumption that there aren't any contiguous spaces
360     // in |input| before utime.
361     DCHECK_NE(input[i - 1], ' ');
362     if (--num_spaces_remaining == 0) {
363       int utime = 0;
364       int stime = 0;
365       if (sscanf(&input.data()[i], "%d %d", &utime, &stime) != 2)
366         return -1;
367 
368       return utime + stime;
369     }
370   }
371 
372   return -1;
373 }
374 
GetNumberOfThreads(ProcessHandle process)375 int GetNumberOfThreads(ProcessHandle process) {
376   return internal::ReadProcStatsAndGetFieldAsInt64(process,
377                                                    internal::VM_NUMTHREADS);
378 }
379 
ParseProcTimeInState(const std::string & content,PlatformThreadId tid,TimeInStatePerThread & time_in_state_per_thread)380 bool ProcessMetrics::ParseProcTimeInState(
381     const std::string& content,
382     PlatformThreadId tid,
383     TimeInStatePerThread& time_in_state_per_thread) {
384   uint32_t current_core_index = 0;
385   CPU::CoreType current_core_type = CPU::CoreType::kOther;
386   bool header_seen = false;
387 
388   const char* begin = content.data();
389   size_t max_pos = content.size() - 1;
390 
391   // Example time_in_state content:
392   // ---
393   // cpu0
394   // 300000 1
395   // 403200 0
396   // 499200 15
397   // cpu4
398   // 710400 13
399   // 825600 5
400   // 940800 550
401   // ---
402 
403   // Iterate over the individual lines.
404   for (size_t pos = 0; pos <= max_pos;) {
405     const char next_char = content[pos];
406     int num_chars = 0;
407     if (!isdigit(next_char)) {
408       // Header line, which we expect to contain "cpu" followed by the number
409       // of the CPU, e.g. "cpu0" or "cpu24".
410       int matches = sscanf(begin + pos, "cpu%" PRIu32 "\n%n",
411                            &current_core_index, &num_chars);
412       if (matches != 1)
413         return false;
414       current_core_type = GetCoreType(current_core_index);
415       header_seen = true;
416     } else if (header_seen) {
417       // Data line with two integer fields, frequency (kHz) and time (in
418       // jiffies), separated by a space, e.g. "2419200 132".
419       uint64_t frequency;
420       uint64_t time;
421       int matches = sscanf(begin + pos, "%" PRIu64 " %" PRIu64 "\n%n",
422                            &frequency, &time, &num_chars);
423       if (matches != 2)
424         return false;
425 
426       // Skip zero-valued entries in the output list (no time spent at this
427       // frequency).
428       if (time > 0) {
429         time_in_state_per_thread.push_back(
430             {tid, current_core_type, current_core_index, frequency,
431              internal::ClockTicksToTimeDelta(time)});
432       }
433     } else {
434       // Data without a header is not supported.
435       return false;
436     }
437 
438     // Advance line.
439     DCHECK_GT(num_chars, 0);
440     pos += num_chars;
441   }
442 
443   return true;
444 }
445 
GetCoreType(int core_index)446 CPU::CoreType ProcessMetrics::GetCoreType(int core_index) {
447   const std::vector<CPU::CoreType>& core_types = CPU::GetGuessedCoreTypes();
448   if (static_cast<size_t>(core_index) >= core_types.size())
449     return CPU::CoreType::kUnknown;
450   return core_types[static_cast<size_t>(core_index)];
451 }
452 
453 const char kProcSelfExe[] = "/proc/self/exe";
454 
455 namespace {
456 
457 // The format of /proc/diskstats is:
458 //  Device major number
459 //  Device minor number
460 //  Device name
461 //  Field  1 -- # of reads completed
462 //      This is the total number of reads completed successfully.
463 //  Field  2 -- # of reads merged, field 6 -- # of writes merged
464 //      Reads and writes which are adjacent to each other may be merged for
465 //      efficiency.  Thus two 4K reads may become one 8K read before it is
466 //      ultimately handed to the disk, and so it will be counted (and queued)
467 //      as only one I/O.  This field lets you know how often this was done.
468 //  Field  3 -- # of sectors read
469 //      This is the total number of sectors read successfully.
470 //  Field  4 -- # of milliseconds spent reading
471 //      This is the total number of milliseconds spent by all reads (as
472 //      measured from __make_request() to end_that_request_last()).
473 //  Field  5 -- # of writes completed
474 //      This is the total number of writes completed successfully.
475 //  Field  6 -- # of writes merged
476 //      See the description of field 2.
477 //  Field  7 -- # of sectors written
478 //      This is the total number of sectors written successfully.
479 //  Field  8 -- # of milliseconds spent writing
480 //      This is the total number of milliseconds spent by all writes (as
481 //      measured from __make_request() to end_that_request_last()).
482 //  Field  9 -- # of I/Os currently in progress
483 //      The only field that should go to zero. Incremented as requests are
484 //      given to appropriate struct request_queue and decremented as they
485 //      finish.
486 //  Field 10 -- # of milliseconds spent doing I/Os
487 //      This field increases so long as field 9 is nonzero.
488 //  Field 11 -- weighted # of milliseconds spent doing I/Os
489 //      This field is incremented at each I/O start, I/O completion, I/O
490 //      merge, or read of these stats by the number of I/Os in progress
491 //      (field 9) times the number of milliseconds spent doing I/O since the
492 //      last update of this field.  This can provide an easy measure of both
493 //      I/O completion time and the backlog that may be accumulating.
494 
495 const size_t kDiskDriveName = 2;
496 const size_t kDiskReads = 3;
497 const size_t kDiskReadsMerged = 4;
498 const size_t kDiskSectorsRead = 5;
499 const size_t kDiskReadTime = 6;
500 const size_t kDiskWrites = 7;
501 const size_t kDiskWritesMerged = 8;
502 const size_t kDiskSectorsWritten = 9;
503 const size_t kDiskWriteTime = 10;
504 const size_t kDiskIO = 11;
505 const size_t kDiskIOTime = 12;
506 const size_t kDiskWeightedIOTime = 13;
507 
508 }  // namespace
509 
ToValue() const510 std::unique_ptr<DictionaryValue> SystemMemoryInfoKB::ToValue() const {
511   auto res = std::make_unique<DictionaryValue>();
512   res->SetIntKey("total", total);
513   res->SetIntKey("free", free);
514   res->SetIntKey("available", available);
515   res->SetIntKey("buffers", buffers);
516   res->SetIntKey("cached", cached);
517   res->SetIntKey("active_anon", active_anon);
518   res->SetIntKey("inactive_anon", inactive_anon);
519   res->SetIntKey("active_file", active_file);
520   res->SetIntKey("inactive_file", inactive_file);
521   res->SetIntKey("swap_total", swap_total);
522   res->SetIntKey("swap_free", swap_free);
523   res->SetIntKey("swap_used", swap_total - swap_free);
524   res->SetIntKey("dirty", dirty);
525   res->SetIntKey("reclaimable", reclaimable);
526 #if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
527   res->SetIntKey("shmem", shmem);
528   res->SetIntKey("slab", slab);
529 #endif
530 
531   return res;
532 }
533 
ParseProcMeminfo(StringPiece meminfo_data,SystemMemoryInfoKB * meminfo)534 bool ParseProcMeminfo(StringPiece meminfo_data, SystemMemoryInfoKB* meminfo) {
535   // The format of /proc/meminfo is:
536   //
537   // MemTotal:      8235324 kB
538   // MemFree:       1628304 kB
539   // Buffers:        429596 kB
540   // Cached:        4728232 kB
541   // ...
542   // There is no guarantee on the ordering or position
543   // though it doesn't appear to change very often
544 
545   // As a basic sanity check at the end, make sure the MemTotal value will be at
546   // least non-zero. So start off with a zero total.
547   meminfo->total = 0;
548 
549   for (const StringPiece& line : SplitStringPiece(
550            meminfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
551     std::vector<StringPiece> tokens = SplitStringPiece(
552         line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
553     // HugePages_* only has a number and no suffix so there may not be exactly 3
554     // tokens.
555     if (tokens.size() <= 1) {
556       DLOG(WARNING) << "meminfo: tokens: " << tokens.size()
557                     << " malformed line: " << line.as_string();
558       continue;
559     }
560 
561     int* target = nullptr;
562     if (tokens[0] == "MemTotal:")
563       target = &meminfo->total;
564     else if (tokens[0] == "MemFree:")
565       target = &meminfo->free;
566     else if (tokens[0] == "MemAvailable:")
567       target = &meminfo->available;
568     else if (tokens[0] == "Buffers:")
569       target = &meminfo->buffers;
570     else if (tokens[0] == "Cached:")
571       target = &meminfo->cached;
572     else if (tokens[0] == "Active(anon):")
573       target = &meminfo->active_anon;
574     else if (tokens[0] == "Inactive(anon):")
575       target = &meminfo->inactive_anon;
576     else if (tokens[0] == "Active(file):")
577       target = &meminfo->active_file;
578     else if (tokens[0] == "Inactive(file):")
579       target = &meminfo->inactive_file;
580     else if (tokens[0] == "SwapTotal:")
581       target = &meminfo->swap_total;
582     else if (tokens[0] == "SwapFree:")
583       target = &meminfo->swap_free;
584     else if (tokens[0] == "Dirty:")
585       target = &meminfo->dirty;
586     else if (tokens[0] == "SReclaimable:")
587       target = &meminfo->reclaimable;
588 #if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
589     // Chrome OS has a tweaked kernel that allows querying Shmem, which is
590     // usually video memory otherwise invisible to the OS.
591     else if (tokens[0] == "Shmem:")
592       target = &meminfo->shmem;
593     else if (tokens[0] == "Slab:")
594       target = &meminfo->slab;
595 #endif
596     if (target)
597       StringToInt(tokens[1], target);
598   }
599 
600   // Make sure the MemTotal is valid.
601   return meminfo->total > 0;
602 }
603 
ParseProcVmstat(StringPiece vmstat_data,VmStatInfo * vmstat)604 bool ParseProcVmstat(StringPiece vmstat_data, VmStatInfo* vmstat) {
605   // The format of /proc/vmstat is:
606   //
607   // nr_free_pages 299878
608   // nr_inactive_anon 239863
609   // nr_active_anon 1318966
610   // nr_inactive_file 2015629
611   // ...
612   //
613   // Iterate through the whole file because the position of the
614   // fields are dependent on the kernel version and configuration.
615 
616   // Returns true if all of these 3 fields are present.
617   bool has_pswpin = false;
618   bool has_pswpout = false;
619   bool has_pgmajfault = false;
620 
621   // The oom_kill field is optional. The vmstat oom_kill field is available on
622   // upstream kernel 4.13. It's backported to Chrome OS kernel 3.10.
623   bool has_oom_kill = false;
624   vmstat->oom_kill = 0;
625 
626   for (const StringPiece& line : SplitStringPiece(
627            vmstat_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
628     std::vector<StringPiece> tokens = SplitStringPiece(
629         line, " ", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
630     if (tokens.size() != 2)
631       continue;
632 
633     uint64_t val;
634     if (!StringToUint64(tokens[1], &val))
635       continue;
636 
637     if (tokens[0] == "pswpin") {
638       vmstat->pswpin = val;
639       DCHECK(!has_pswpin);
640       has_pswpin = true;
641     } else if (tokens[0] == "pswpout") {
642       vmstat->pswpout = val;
643       DCHECK(!has_pswpout);
644       has_pswpout = true;
645     } else if (tokens[0] == "pgmajfault") {
646       vmstat->pgmajfault = val;
647       DCHECK(!has_pgmajfault);
648       has_pgmajfault = true;
649     } else if (tokens[0] == "oom_kill") {
650       vmstat->oom_kill = val;
651       DCHECK(!has_oom_kill);
652       has_oom_kill = true;
653     }
654   }
655 
656   return has_pswpin && has_pswpout && has_pgmajfault;
657 }
658 
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)659 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
660   // Synchronously reading files in /proc is safe.
661   ThreadRestrictions::ScopedAllowIO allow_io;
662 
663   // Used memory is: total - free - buffers - caches
664   FilePath meminfo_file("/proc/meminfo");
665   std::string meminfo_data;
666   if (!ReadFileToStringNonBlocking(meminfo_file, &meminfo_data)) {
667     DLOG(WARNING) << "Failed to open " << meminfo_file.value();
668     return false;
669   }
670 
671   if (!ParseProcMeminfo(meminfo_data, meminfo)) {
672     DLOG(WARNING) << "Failed to parse " << meminfo_file.value();
673     return false;
674   }
675 
676   return true;
677 }
678 
ToValue() const679 std::unique_ptr<DictionaryValue> VmStatInfo::ToValue() const {
680   auto res = std::make_unique<DictionaryValue>();
681   res->SetIntKey("pswpin", pswpin);
682   res->SetIntKey("pswpout", pswpout);
683   res->SetIntKey("pgmajfault", pgmajfault);
684   return res;
685 }
686 
GetVmStatInfo(VmStatInfo * vmstat)687 bool GetVmStatInfo(VmStatInfo* vmstat) {
688   // Synchronously reading files in /proc is safe.
689   ThreadRestrictions::ScopedAllowIO allow_io;
690 
691   FilePath vmstat_file("/proc/vmstat");
692   std::string vmstat_data;
693   if (!ReadFileToStringNonBlocking(vmstat_file, &vmstat_data)) {
694     DLOG(WARNING) << "Failed to open " << vmstat_file.value();
695     return false;
696   }
697   if (!ParseProcVmstat(vmstat_data, vmstat)) {
698     DLOG(WARNING) << "Failed to parse " << vmstat_file.value();
699     return false;
700   }
701   return true;
702 }
703 
SystemDiskInfo()704 SystemDiskInfo::SystemDiskInfo() {
705   reads = 0;
706   reads_merged = 0;
707   sectors_read = 0;
708   read_time = 0;
709   writes = 0;
710   writes_merged = 0;
711   sectors_written = 0;
712   write_time = 0;
713   io = 0;
714   io_time = 0;
715   weighted_io_time = 0;
716 }
717 
718 SystemDiskInfo::SystemDiskInfo(const SystemDiskInfo& other) = default;
719 
ToValue() const720 std::unique_ptr<Value> SystemDiskInfo::ToValue() const {
721   auto res = std::make_unique<DictionaryValue>();
722 
723   // Write out uint64_t variables as doubles.
724   // Note: this may discard some precision, but for JS there's no other option.
725   res->SetDouble("reads", static_cast<double>(reads));
726   res->SetDouble("reads_merged", static_cast<double>(reads_merged));
727   res->SetDouble("sectors_read", static_cast<double>(sectors_read));
728   res->SetDouble("read_time", static_cast<double>(read_time));
729   res->SetDouble("writes", static_cast<double>(writes));
730   res->SetDouble("writes_merged", static_cast<double>(writes_merged));
731   res->SetDouble("sectors_written", static_cast<double>(sectors_written));
732   res->SetDouble("write_time", static_cast<double>(write_time));
733   res->SetDouble("io", static_cast<double>(io));
734   res->SetDouble("io_time", static_cast<double>(io_time));
735   res->SetDouble("weighted_io_time", static_cast<double>(weighted_io_time));
736 
737   return std::move(res);
738 }
739 
IsValidDiskName(StringPiece candidate)740 bool IsValidDiskName(StringPiece candidate) {
741   if (candidate.length() < 3)
742     return false;
743 
744   if (candidate[1] == 'd' &&
745       (candidate[0] == 'h' || candidate[0] == 's' || candidate[0] == 'v')) {
746     // [hsv]d[a-z]+ case
747     for (size_t i = 2; i < candidate.length(); ++i) {
748       if (!islower(candidate[i]))
749         return false;
750     }
751     return true;
752   }
753 
754   const char kMMCName[] = "mmcblk";
755   if (!StartsWith(candidate, kMMCName))
756     return false;
757 
758   // mmcblk[0-9]+ case
759   for (size_t i = strlen(kMMCName); i < candidate.length(); ++i) {
760     if (!isdigit(candidate[i]))
761       return false;
762   }
763   return true;
764 }
765 
GetSystemDiskInfo(SystemDiskInfo * diskinfo)766 bool GetSystemDiskInfo(SystemDiskInfo* diskinfo) {
767   // Synchronously reading files in /proc does not hit the disk.
768   ThreadRestrictions::ScopedAllowIO allow_io;
769 
770   FilePath diskinfo_file("/proc/diskstats");
771   std::string diskinfo_data;
772   if (!ReadFileToStringNonBlocking(diskinfo_file, &diskinfo_data)) {
773     DLOG(WARNING) << "Failed to open " << diskinfo_file.value();
774     return false;
775   }
776 
777   std::vector<StringPiece> diskinfo_lines = SplitStringPiece(
778       diskinfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
779   if (diskinfo_lines.empty()) {
780     DLOG(WARNING) << "No lines found";
781     return false;
782   }
783 
784   diskinfo->reads = 0;
785   diskinfo->reads_merged = 0;
786   diskinfo->sectors_read = 0;
787   diskinfo->read_time = 0;
788   diskinfo->writes = 0;
789   diskinfo->writes_merged = 0;
790   diskinfo->sectors_written = 0;
791   diskinfo->write_time = 0;
792   diskinfo->io = 0;
793   diskinfo->io_time = 0;
794   diskinfo->weighted_io_time = 0;
795 
796   uint64_t reads = 0;
797   uint64_t reads_merged = 0;
798   uint64_t sectors_read = 0;
799   uint64_t read_time = 0;
800   uint64_t writes = 0;
801   uint64_t writes_merged = 0;
802   uint64_t sectors_written = 0;
803   uint64_t write_time = 0;
804   uint64_t io = 0;
805   uint64_t io_time = 0;
806   uint64_t weighted_io_time = 0;
807 
808   for (const StringPiece& line : diskinfo_lines) {
809     std::vector<StringPiece> disk_fields = SplitStringPiece(
810         line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
811 
812     // Fields may have overflowed and reset to zero.
813     if (!IsValidDiskName(disk_fields[kDiskDriveName].as_string()))
814       continue;
815 
816     StringToUint64(disk_fields[kDiskReads], &reads);
817     StringToUint64(disk_fields[kDiskReadsMerged], &reads_merged);
818     StringToUint64(disk_fields[kDiskSectorsRead], &sectors_read);
819     StringToUint64(disk_fields[kDiskReadTime], &read_time);
820     StringToUint64(disk_fields[kDiskWrites], &writes);
821     StringToUint64(disk_fields[kDiskWritesMerged], &writes_merged);
822     StringToUint64(disk_fields[kDiskSectorsWritten], &sectors_written);
823     StringToUint64(disk_fields[kDiskWriteTime], &write_time);
824     StringToUint64(disk_fields[kDiskIO], &io);
825     StringToUint64(disk_fields[kDiskIOTime], &io_time);
826     StringToUint64(disk_fields[kDiskWeightedIOTime], &weighted_io_time);
827 
828     diskinfo->reads += reads;
829     diskinfo->reads_merged += reads_merged;
830     diskinfo->sectors_read += sectors_read;
831     diskinfo->read_time += read_time;
832     diskinfo->writes += writes;
833     diskinfo->writes_merged += writes_merged;
834     diskinfo->sectors_written += sectors_written;
835     diskinfo->write_time += write_time;
836     diskinfo->io += io;
837     diskinfo->io_time += io_time;
838     diskinfo->weighted_io_time += weighted_io_time;
839   }
840 
841   return true;
842 }
843 
GetUserCpuTimeSinceBoot()844 TimeDelta GetUserCpuTimeSinceBoot() {
845   return internal::GetUserCpuTimeSinceBoot();
846 }
847 
848 #if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
ToValue() const849 std::unique_ptr<Value> SwapInfo::ToValue() const {
850   auto res = std::make_unique<DictionaryValue>();
851 
852   // Write out uint64_t variables as doubles.
853   // Note: this may discard some precision, but for JS there's no other option.
854   res->SetDouble("num_reads", static_cast<double>(num_reads));
855   res->SetDouble("num_writes", static_cast<double>(num_writes));
856   res->SetDouble("orig_data_size", static_cast<double>(orig_data_size));
857   res->SetDouble("compr_data_size", static_cast<double>(compr_data_size));
858   res->SetDouble("mem_used_total", static_cast<double>(mem_used_total));
859   double ratio = compr_data_size ? static_cast<double>(orig_data_size) /
860                                        static_cast<double>(compr_data_size)
861                                  : 0;
862   res->SetDouble("compression_ratio", ratio);
863 
864   return std::move(res);
865 }
866 
ToValue() const867 std::unique_ptr<Value> GraphicsMemoryInfoKB::ToValue() const {
868   auto res = std::make_unique<DictionaryValue>();
869   res->SetIntKey("gpu_objects", gpu_objects);
870   res->SetDouble("gpu_memory_size", static_cast<double>(gpu_memory_size));
871 
872   return std::move(res);
873 }
874 
ParseZramMmStat(StringPiece mm_stat_data,SwapInfo * swap_info)875 bool ParseZramMmStat(StringPiece mm_stat_data, SwapInfo* swap_info) {
876   // There are 7 columns in /sys/block/zram0/mm_stat,
877   // split by several spaces. The first three columns
878   // are orig_data_size, compr_data_size and mem_used_total.
879   // Example:
880   // 17715200 5008166 566062  0 1225715712  127 183842
881   //
882   // For more details:
883   // https://www.kernel.org/doc/Documentation/blockdev/zram.txt
884 
885   std::vector<StringPiece> tokens = SplitStringPiece(
886       mm_stat_data, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
887   if (tokens.size() < 7) {
888     DLOG(WARNING) << "zram mm_stat: tokens: " << tokens.size()
889                   << " malformed line: " << mm_stat_data.as_string();
890     return false;
891   }
892 
893   if (!StringToUint64(tokens[0], &swap_info->orig_data_size))
894     return false;
895   if (!StringToUint64(tokens[1], &swap_info->compr_data_size))
896     return false;
897   if (!StringToUint64(tokens[2], &swap_info->mem_used_total))
898     return false;
899 
900   return true;
901 }
902 
ParseZramStat(StringPiece stat_data,SwapInfo * swap_info)903 bool ParseZramStat(StringPiece stat_data, SwapInfo* swap_info) {
904   // There are 11 columns in /sys/block/zram0/stat,
905   // split by several spaces. The first column is read I/Os
906   // and fifth column is write I/Os.
907   // Example:
908   // 299    0    2392    0    1    0    8    0    0    0    0
909   //
910   // For more details:
911   // https://www.kernel.org/doc/Documentation/blockdev/zram.txt
912 
913   std::vector<StringPiece> tokens = SplitStringPiece(
914       stat_data, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
915   if (tokens.size() < 11) {
916     DLOG(WARNING) << "zram stat: tokens: " << tokens.size()
917                   << " malformed line: " << stat_data.as_string();
918     return false;
919   }
920 
921   if (!StringToUint64(tokens[0], &swap_info->num_reads))
922     return false;
923   if (!StringToUint64(tokens[4], &swap_info->num_writes))
924     return false;
925 
926   return true;
927 }
928 
929 namespace {
930 
IgnoreZramFirstPage(uint64_t orig_data_size,SwapInfo * swap_info)931 bool IgnoreZramFirstPage(uint64_t orig_data_size, SwapInfo* swap_info) {
932   if (orig_data_size <= 4096) {
933     // A single page is compressed at startup, and has a high compression
934     // ratio. Ignore this as it doesn't indicate any real swapping.
935     swap_info->orig_data_size = 0;
936     swap_info->num_reads = 0;
937     swap_info->num_writes = 0;
938     swap_info->compr_data_size = 0;
939     swap_info->mem_used_total = 0;
940     return true;
941   }
942   return false;
943 }
944 
ParseZramPath(SwapInfo * swap_info)945 void ParseZramPath(SwapInfo* swap_info) {
946   FilePath zram_path("/sys/block/zram0");
947   uint64_t orig_data_size =
948       ReadFileToUint64(zram_path.Append("orig_data_size"));
949   if (IgnoreZramFirstPage(orig_data_size, swap_info))
950     return;
951 
952   swap_info->orig_data_size = orig_data_size;
953   swap_info->num_reads = ReadFileToUint64(zram_path.Append("num_reads"));
954   swap_info->num_writes = ReadFileToUint64(zram_path.Append("num_writes"));
955   swap_info->compr_data_size =
956       ReadFileToUint64(zram_path.Append("compr_data_size"));
957   swap_info->mem_used_total =
958       ReadFileToUint64(zram_path.Append("mem_used_total"));
959 }
960 
GetSwapInfoImpl(SwapInfo * swap_info)961 bool GetSwapInfoImpl(SwapInfo* swap_info) {
962   // Synchronously reading files in /sys/block/zram0 does not hit the disk.
963   ThreadRestrictions::ScopedAllowIO allow_io;
964 
965   // Since ZRAM update, it shows the usage data in different places.
966   // If file "/sys/block/zram0/mm_stat" exists, use the new way, otherwise,
967   // use the old way.
968   static Optional<bool> use_new_zram_interface;
969   FilePath zram_mm_stat_file("/sys/block/zram0/mm_stat");
970   if (!use_new_zram_interface.has_value()) {
971     use_new_zram_interface = PathExists(zram_mm_stat_file);
972   }
973 
974   if (!use_new_zram_interface.value()) {
975     ParseZramPath(swap_info);
976     return true;
977   }
978 
979   std::string mm_stat_data;
980   if (!ReadFileToStringNonBlocking(zram_mm_stat_file, &mm_stat_data)) {
981     DLOG(WARNING) << "Failed to open " << zram_mm_stat_file.value();
982     return false;
983   }
984   if (!ParseZramMmStat(mm_stat_data, swap_info)) {
985     DLOG(WARNING) << "Failed to parse " << zram_mm_stat_file.value();
986     return false;
987   }
988   if (IgnoreZramFirstPage(swap_info->orig_data_size, swap_info))
989     return true;
990 
991   FilePath zram_stat_file("/sys/block/zram0/stat");
992   std::string stat_data;
993   if (!ReadFileToStringNonBlocking(zram_stat_file, &stat_data)) {
994     DLOG(WARNING) << "Failed to open " << zram_stat_file.value();
995     return false;
996   }
997   if (!ParseZramStat(stat_data, swap_info)) {
998     DLOG(WARNING) << "Failed to parse " << zram_stat_file.value();
999     return false;
1000   }
1001 
1002   return true;
1003 }
1004 
1005 }  // namespace
1006 
GetSwapInfo(SwapInfo * swap_info)1007 bool GetSwapInfo(SwapInfo* swap_info) {
1008   if (!GetSwapInfoImpl(swap_info)) {
1009     *swap_info = SwapInfo();
1010     return false;
1011   }
1012   return true;
1013 }
1014 
GetGraphicsMemoryInfo(GraphicsMemoryInfoKB * gpu_meminfo)1015 bool GetGraphicsMemoryInfo(GraphicsMemoryInfoKB* gpu_meminfo) {
1016 #if defined(ARCH_CPU_X86_FAMILY)
1017   // Reading i915_gem_objects on intel platform with kernel 5.4 is slow and is
1018   // prohibited.
1019   // TODO(b/170397975): Update if i915_gem_objects reading time is improved.
1020   static bool is_newer_kernel =
1021       base::StartsWith(base::SysInfo::KernelVersion(), "5.");
1022   static bool is_intel_cpu = base::CPU().vendor_name() == "GenuineIntel";
1023   if (is_newer_kernel && is_intel_cpu)
1024     return false;
1025 #endif
1026 
1027 #if defined(ARCH_CPU_ARM_FAMILY)
1028   const FilePath geminfo_path("/run/debugfs_gpu/exynos_gem_objects");
1029 #else
1030   const FilePath geminfo_path("/run/debugfs_gpu/i915_gem_objects");
1031 #endif
1032   std::string geminfo_data;
1033   gpu_meminfo->gpu_objects = -1;
1034   gpu_meminfo->gpu_memory_size = -1;
1035   if (ReadFileToStringNonBlocking(geminfo_path, &geminfo_data)) {
1036     int gpu_objects = -1;
1037     int64_t gpu_memory_size = -1;
1038     int num_res = sscanf(geminfo_data.c_str(), "%d objects, %" SCNd64 " bytes",
1039                          &gpu_objects, &gpu_memory_size);
1040     if (num_res == 2) {
1041       gpu_meminfo->gpu_objects = gpu_objects;
1042       gpu_meminfo->gpu_memory_size = gpu_memory_size;
1043     }
1044   }
1045 
1046 #if defined(ARCH_CPU_ARM_FAMILY)
1047   // Incorporate Mali graphics memory if present.
1048   FilePath mali_memory_file("/sys/class/misc/mali0/device/memory");
1049   std::string mali_memory_data;
1050   if (ReadFileToStringNonBlocking(mali_memory_file, &mali_memory_data)) {
1051     int64_t mali_size = -1;
1052     int num_res =
1053         sscanf(mali_memory_data.c_str(), "%" SCNd64 " bytes", &mali_size);
1054     if (num_res == 1)
1055       gpu_meminfo->gpu_memory_size += mali_size;
1056   }
1057 #endif  // defined(ARCH_CPU_ARM_FAMILY)
1058 
1059   return gpu_meminfo->gpu_memory_size != -1;
1060 }
1061 
1062 #endif  // defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
1063 
1064 #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
GetIdleWakeupsPerSecond()1065 int ProcessMetrics::GetIdleWakeupsPerSecond() {
1066   uint64_t num_switches;
1067   static const char kSwitchStat[] = "voluntary_ctxt_switches";
1068   return ReadProcStatusAndGetFieldAsUint64(process_, kSwitchStat, &num_switches)
1069              ? CalculateIdleWakeupsPerSecond(num_switches)
1070              : 0;
1071 }
1072 #endif  // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
1073 
1074 }  // namespace base
1075