• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <stddef.h>
10 #include <stdint.h>
11 #include <sys/stat.h>
12 #include <sys/time.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15 #include <utility>
16 
17 #include "base/files/dir_reader_posix.h"
18 #include "base/files/file_util.h"
19 #include "base/logging.h"
20 #include "base/process/internal_linux.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/strings/string_tokenizer.h"
24 #include "base/strings/string_util.h"
25 #include "base/sys_info.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "build/build_config.h"
28 
29 namespace base {
30 
31 namespace {
32 
TrimKeyValuePairs(StringPairs * pairs)33 void TrimKeyValuePairs(StringPairs* pairs) {
34   DCHECK(pairs);
35   StringPairs& p_ref = *pairs;
36   for (size_t i = 0; i < p_ref.size(); ++i) {
37     TrimWhitespaceASCII(p_ref[i].first, TRIM_ALL, &p_ref[i].first);
38     TrimWhitespaceASCII(p_ref[i].second, TRIM_ALL, &p_ref[i].second);
39   }
40 }
41 
42 #if defined(OS_CHROMEOS)
43 // Read a file with a single number string and return the number as a uint64_t.
ReadFileToUint64(const FilePath file)44 static uint64_t ReadFileToUint64(const FilePath file) {
45   std::string file_as_string;
46   if (!ReadFileToString(file, &file_as_string))
47     return 0;
48   TrimWhitespaceASCII(file_as_string, TRIM_ALL, &file_as_string);
49   uint64_t file_as_uint64 = 0;
50   if (!StringToUint64(file_as_string, &file_as_uint64))
51     return 0;
52   return file_as_uint64;
53 }
54 #endif
55 
56 // Read /proc/<pid>/status and return the value for |field|, or 0 on failure.
57 // Only works for fields in the form of "Field: value kB".
ReadProcStatusAndGetFieldAsSizeT(pid_t pid,const std::string & field)58 size_t ReadProcStatusAndGetFieldAsSizeT(pid_t pid, const std::string& field) {
59   std::string status;
60   {
61     // Synchronously reading files in /proc does not hit the disk.
62     ThreadRestrictions::ScopedAllowIO allow_io;
63     FilePath stat_file = internal::GetProcPidDir(pid).Append("status");
64     if (!ReadFileToString(stat_file, &status))
65       return 0;
66   }
67 
68   StringPairs pairs;
69   SplitStringIntoKeyValuePairs(status, ':', '\n', &pairs);
70   TrimKeyValuePairs(&pairs);
71   for (size_t i = 0; i < pairs.size(); ++i) {
72     const std::string& key = pairs[i].first;
73     const std::string& value_str = pairs[i].second;
74     if (key == field) {
75       std::vector<StringPiece> split_value_str = SplitStringPiece(
76           value_str, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
77       if (split_value_str.size() != 2 || split_value_str[1] != "kB") {
78         NOTREACHED();
79         return 0;
80       }
81       size_t value;
82       if (!StringToSizeT(split_value_str[0], &value)) {
83         NOTREACHED();
84         return 0;
85       }
86       return value;
87     }
88   }
89   // This can be reached if the process dies when proc is read -- in that case,
90   // the kernel can return missing fields.
91   return 0;
92 }
93 
94 #if defined(OS_LINUX)
95 // Read /proc/<pid>/sched and look for |field|. On succes, return true and
96 // write the value for |field| into |result|.
97 // Only works for fields in the form of "field    :     uint_value"
ReadProcSchedAndGetFieldAsUint64(pid_t pid,const std::string & field,uint64_t * result)98 bool ReadProcSchedAndGetFieldAsUint64(pid_t pid,
99                                       const std::string& field,
100                                       uint64_t* result) {
101   std::string sched_data;
102   {
103     // Synchronously reading files in /proc does not hit the disk.
104     ThreadRestrictions::ScopedAllowIO allow_io;
105     FilePath sched_file = internal::GetProcPidDir(pid).Append("sched");
106     if (!ReadFileToString(sched_file, &sched_data))
107       return false;
108   }
109 
110   StringPairs pairs;
111   SplitStringIntoKeyValuePairs(sched_data, ':', '\n', &pairs);
112   TrimKeyValuePairs(&pairs);
113   for (size_t i = 0; i < pairs.size(); ++i) {
114     const std::string& key = pairs[i].first;
115     const std::string& value_str = pairs[i].second;
116     if (key == field) {
117       uint64_t value;
118       if (!StringToUint64(value_str, &value))
119         return false;
120       *result = value;
121       return true;
122     }
123   }
124   return false;
125 }
126 #endif  // defined(OS_LINUX)
127 
128 // Get the total CPU of a single process.  Return value is number of jiffies
129 // on success or -1 on error.
GetProcessCPU(pid_t pid)130 int GetProcessCPU(pid_t pid) {
131   // Use /proc/<pid>/task to find all threads and parse their /stat file.
132   FilePath task_path = internal::GetProcPidDir(pid).Append("task");
133 
134   DIR* dir = opendir(task_path.value().c_str());
135   if (!dir) {
136     DPLOG(ERROR) << "opendir(" << task_path.value() << ")";
137     return -1;
138   }
139 
140   int total_cpu = 0;
141   while (struct dirent* ent = readdir(dir)) {
142     pid_t tid = internal::ProcDirSlotToPid(ent->d_name);
143     if (!tid)
144       continue;
145 
146     // Synchronously reading files in /proc does not hit the disk.
147     ThreadRestrictions::ScopedAllowIO allow_io;
148 
149     std::string stat;
150     FilePath stat_path =
151         task_path.Append(ent->d_name).Append(internal::kStatFile);
152     if (ReadFileToString(stat_path, &stat)) {
153       int cpu = ParseProcStatCPU(stat);
154       if (cpu > 0)
155         total_cpu += cpu;
156     }
157   }
158   closedir(dir);
159 
160   return total_cpu;
161 }
162 
163 }  // namespace
164 
165 // static
CreateProcessMetrics(ProcessHandle process)166 ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
167   return new ProcessMetrics(process);
168 }
169 
170 // On linux, we return vsize.
GetPagefileUsage() const171 size_t ProcessMetrics::GetPagefileUsage() const {
172   return internal::ReadProcStatsAndGetFieldAsSizeT(process_,
173                                                    internal::VM_VSIZE);
174 }
175 
176 // On linux, we return the high water mark of vsize.
GetPeakPagefileUsage() const177 size_t ProcessMetrics::GetPeakPagefileUsage() const {
178   return ReadProcStatusAndGetFieldAsSizeT(process_, "VmPeak") * 1024;
179 }
180 
181 // On linux, we return RSS.
GetWorkingSetSize() const182 size_t ProcessMetrics::GetWorkingSetSize() const {
183   return internal::ReadProcStatsAndGetFieldAsSizeT(process_, internal::VM_RSS) *
184       getpagesize();
185 }
186 
187 // On linux, we return the high water mark of RSS.
GetPeakWorkingSetSize() const188 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
189   return ReadProcStatusAndGetFieldAsSizeT(process_, "VmHWM") * 1024;
190 }
191 
GetMemoryBytes(size_t * private_bytes,size_t * shared_bytes)192 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
193                                     size_t* shared_bytes) {
194   WorkingSetKBytes ws_usage;
195   if (!GetWorkingSetKBytes(&ws_usage))
196     return false;
197 
198   if (private_bytes)
199     *private_bytes = ws_usage.priv * 1024;
200 
201   if (shared_bytes)
202     *shared_bytes = ws_usage.shared * 1024;
203 
204   return true;
205 }
206 
GetWorkingSetKBytes(WorkingSetKBytes * ws_usage) const207 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
208 #if defined(OS_CHROMEOS)
209   if (GetWorkingSetKBytesTotmaps(ws_usage))
210     return true;
211 #endif
212   return GetWorkingSetKBytesStatm(ws_usage);
213 }
214 
GetCPUUsage()215 double ProcessMetrics::GetCPUUsage() {
216   TimeTicks time = TimeTicks::Now();
217 
218   if (last_cpu_ == 0) {
219     // First call, just set the last values.
220     last_cpu_time_ = time;
221     last_cpu_ = GetProcessCPU(process_);
222     return 0.0;
223   }
224 
225   TimeDelta time_delta = time - last_cpu_time_;
226   if (time_delta.is_zero()) {
227     NOTREACHED();
228     return 0.0;
229   }
230 
231   int cpu = GetProcessCPU(process_);
232 
233   // We have the number of jiffies in the time period.  Convert to percentage.
234   // Note this means we will go *over* 100 in the case where multiple threads
235   // are together adding to more than one CPU's worth.
236   TimeDelta cpu_time = internal::ClockTicksToTimeDelta(cpu);
237   TimeDelta last_cpu_time = internal::ClockTicksToTimeDelta(last_cpu_);
238 
239   // If the number of threads running in the process has decreased since the
240   // last time this function was called, |last_cpu_time| will be greater than
241   // |cpu_time| which will result in a negative value in the below percentage
242   // calculation. We prevent this by clamping to 0. crbug.com/546565.
243   // This computation is known to be shaky when threads are destroyed between
244   // "last" and "now", but for our current purposes, it's all right.
245   double percentage = 0.0;
246   if (last_cpu_time < cpu_time) {
247     percentage = 100.0 * (cpu_time - last_cpu_time).InSecondsF() /
248         time_delta.InSecondsF();
249   }
250 
251   last_cpu_time_ = time;
252   last_cpu_ = cpu;
253 
254   return percentage;
255 }
256 
257 // To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
258 // in your kernel configuration.
GetIOCounters(IoCounters * io_counters) const259 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
260   // Synchronously reading files in /proc does not hit the disk.
261   ThreadRestrictions::ScopedAllowIO allow_io;
262 
263   std::string proc_io_contents;
264   FilePath io_file = internal::GetProcPidDir(process_).Append("io");
265   if (!ReadFileToString(io_file, &proc_io_contents))
266     return false;
267 
268   io_counters->OtherOperationCount = 0;
269   io_counters->OtherTransferCount = 0;
270 
271   StringPairs pairs;
272   SplitStringIntoKeyValuePairs(proc_io_contents, ':', '\n', &pairs);
273   TrimKeyValuePairs(&pairs);
274   for (size_t i = 0; i < pairs.size(); ++i) {
275     const std::string& key = pairs[i].first;
276     const std::string& value_str = pairs[i].second;
277     uint64_t* target_counter = NULL;
278     if (key == "syscr")
279       target_counter = &io_counters->ReadOperationCount;
280     else if (key == "syscw")
281       target_counter = &io_counters->WriteOperationCount;
282     else if (key == "rchar")
283       target_counter = &io_counters->ReadTransferCount;
284     else if (key == "wchar")
285       target_counter = &io_counters->WriteTransferCount;
286     if (!target_counter)
287       continue;
288     bool converted = StringToUint64(value_str, target_counter);
289     DCHECK(converted);
290   }
291   return true;
292 }
293 
294 #if defined(OS_LINUX)
GetOpenFdCount() const295 int ProcessMetrics::GetOpenFdCount() const {
296   // Use /proc/<pid>/fd to count the number of entries there.
297   FilePath fd_path = internal::GetProcPidDir(process_).Append("fd");
298 
299   DirReaderPosix dir_reader(fd_path.value().c_str());
300   if (!dir_reader.IsValid())
301     return -1;
302 
303   int total_count = 0;
304   for (; dir_reader.Next(); ) {
305     const char* name = dir_reader.name();
306     if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
307       ++total_count;
308   }
309 
310   return total_count;
311 }
312 #endif  // defined(OS_LINUX)
313 
ProcessMetrics(ProcessHandle process)314 ProcessMetrics::ProcessMetrics(ProcessHandle process)
315     : process_(process),
316       last_system_time_(0),
317 #if defined(OS_LINUX)
318       last_absolute_idle_wakeups_(0),
319 #endif
320       last_cpu_(0) {
321   processor_count_ = SysInfo::NumberOfProcessors();
322 }
323 
324 #if defined(OS_CHROMEOS)
325 // Private, Shared and Proportional working set sizes are obtained from
326 // /proc/<pid>/totmaps
GetWorkingSetKBytesTotmaps(WorkingSetKBytes * ws_usage) const327 bool ProcessMetrics::GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage)
328   const {
329   // The format of /proc/<pid>/totmaps is:
330   //
331   // Rss:                6120 kB
332   // Pss:                3335 kB
333   // Shared_Clean:       1008 kB
334   // Shared_Dirty:       4012 kB
335   // Private_Clean:         4 kB
336   // Private_Dirty:      1096 kB
337   // Referenced:          XXX kB
338   // Anonymous:           XXX kB
339   // AnonHugePages:       XXX kB
340   // Swap:                XXX kB
341   // Locked:              XXX kB
342   const size_t kPssIndex = (1 * 3) + 1;
343   const size_t kPrivate_CleanIndex = (4 * 3) + 1;
344   const size_t kPrivate_DirtyIndex = (5 * 3) + 1;
345   const size_t kSwapIndex = (9 * 3) + 1;
346 
347   std::string totmaps_data;
348   {
349     FilePath totmaps_file = internal::GetProcPidDir(process_).Append("totmaps");
350     ThreadRestrictions::ScopedAllowIO allow_io;
351     bool ret = ReadFileToString(totmaps_file, &totmaps_data);
352     if (!ret || totmaps_data.length() == 0)
353       return false;
354   }
355 
356   std::vector<std::string> totmaps_fields = SplitString(
357       totmaps_data, base::kWhitespaceASCII, base::KEEP_WHITESPACE,
358       base::SPLIT_WANT_NONEMPTY);
359 
360   DCHECK_EQ("Pss:", totmaps_fields[kPssIndex-1]);
361   DCHECK_EQ("Private_Clean:", totmaps_fields[kPrivate_CleanIndex - 1]);
362   DCHECK_EQ("Private_Dirty:", totmaps_fields[kPrivate_DirtyIndex - 1]);
363   DCHECK_EQ("Swap:", totmaps_fields[kSwapIndex-1]);
364 
365   int pss = 0;
366   int private_clean = 0;
367   int private_dirty = 0;
368   int swap = 0;
369   bool ret = true;
370   ret &= StringToInt(totmaps_fields[kPssIndex], &pss);
371   ret &= StringToInt(totmaps_fields[kPrivate_CleanIndex], &private_clean);
372   ret &= StringToInt(totmaps_fields[kPrivate_DirtyIndex], &private_dirty);
373   ret &= StringToInt(totmaps_fields[kSwapIndex], &swap);
374 
375   // On ChromeOS swap is to zram. We count this as private / shared, as
376   // increased swap decreases available RAM to user processes, which would
377   // otherwise create surprising results.
378   ws_usage->priv = private_clean + private_dirty + swap;
379   ws_usage->shared = pss + swap;
380   ws_usage->shareable = 0;
381   ws_usage->swapped = swap;
382   return ret;
383 }
384 #endif
385 
386 // Private and Shared working set sizes are obtained from /proc/<pid>/statm.
GetWorkingSetKBytesStatm(WorkingSetKBytes * ws_usage) const387 bool ProcessMetrics::GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage)
388     const {
389   // Use statm instead of smaps because smaps is:
390   // a) Large and slow to parse.
391   // b) Unavailable in the SUID sandbox.
392 
393   // First we need to get the page size, since everything is measured in pages.
394   // For details, see: man 5 proc.
395   const int page_size_kb = getpagesize() / 1024;
396   if (page_size_kb <= 0)
397     return false;
398 
399   std::string statm;
400   {
401     FilePath statm_file = internal::GetProcPidDir(process_).Append("statm");
402     // Synchronously reading files in /proc does not hit the disk.
403     ThreadRestrictions::ScopedAllowIO allow_io;
404     bool ret = ReadFileToString(statm_file, &statm);
405     if (!ret || statm.length() == 0)
406       return false;
407   }
408 
409   std::vector<StringPiece> statm_vec = SplitStringPiece(
410       statm, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
411   if (statm_vec.size() != 7)
412     return false;  // Not the format we expect.
413 
414   int statm_rss, statm_shared;
415   bool ret = true;
416   ret &= StringToInt(statm_vec[1], &statm_rss);
417   ret &= StringToInt(statm_vec[2], &statm_shared);
418 
419   ws_usage->priv = (statm_rss - statm_shared) * page_size_kb;
420   ws_usage->shared = statm_shared * page_size_kb;
421 
422   // Sharable is not calculated, as it does not provide interesting data.
423   ws_usage->shareable = 0;
424 
425 #if defined(OS_CHROMEOS)
426   // Can't get swapped memory from statm.
427   ws_usage->swapped = 0;
428 #endif
429 
430   return ret;
431 }
432 
GetSystemCommitCharge()433 size_t GetSystemCommitCharge() {
434   SystemMemoryInfoKB meminfo;
435   if (!GetSystemMemoryInfo(&meminfo))
436     return 0;
437   return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
438 }
439 
ParseProcStatCPU(const std::string & input)440 int ParseProcStatCPU(const std::string& input) {
441   // |input| may be empty if the process disappeared somehow.
442   // e.g. http://crbug.com/145811.
443   if (input.empty())
444     return -1;
445 
446   size_t start = input.find_last_of(')');
447   if (start == input.npos)
448     return -1;
449 
450   // Number of spaces remaining until reaching utime's index starting after the
451   // last ')'.
452   int num_spaces_remaining = internal::VM_UTIME - 1;
453 
454   size_t i = start;
455   while ((i = input.find(' ', i + 1)) != input.npos) {
456     // Validate the assumption that there aren't any contiguous spaces
457     // in |input| before utime.
458     DCHECK_NE(input[i - 1], ' ');
459     if (--num_spaces_remaining == 0) {
460       int utime = 0;
461       int stime = 0;
462       if (sscanf(&input.data()[i], "%d %d", &utime, &stime) != 2)
463         return -1;
464 
465       return utime + stime;
466     }
467   }
468 
469   return -1;
470 }
471 
472 const char kProcSelfExe[] = "/proc/self/exe";
473 
GetNumberOfThreads(ProcessHandle process)474 int GetNumberOfThreads(ProcessHandle process) {
475   return internal::ReadProcStatsAndGetFieldAsInt64(process,
476                                                    internal::VM_NUMTHREADS);
477 }
478 
479 namespace {
480 
481 // The format of /proc/diskstats is:
482 //  Device major number
483 //  Device minor number
484 //  Device name
485 //  Field  1 -- # of reads completed
486 //      This is the total number of reads completed successfully.
487 //  Field  2 -- # of reads merged, field 6 -- # of writes merged
488 //      Reads and writes which are adjacent to each other may be merged for
489 //      efficiency.  Thus two 4K reads may become one 8K read before it is
490 //      ultimately handed to the disk, and so it will be counted (and queued)
491 //      as only one I/O.  This field lets you know how often this was done.
492 //  Field  3 -- # of sectors read
493 //      This is the total number of sectors read successfully.
494 //  Field  4 -- # of milliseconds spent reading
495 //      This is the total number of milliseconds spent by all reads (as
496 //      measured from __make_request() to end_that_request_last()).
497 //  Field  5 -- # of writes completed
498 //      This is the total number of writes completed successfully.
499 //  Field  6 -- # of writes merged
500 //      See the description of field 2.
501 //  Field  7 -- # of sectors written
502 //      This is the total number of sectors written successfully.
503 //  Field  8 -- # of milliseconds spent writing
504 //      This is the total number of milliseconds spent by all writes (as
505 //      measured from __make_request() to end_that_request_last()).
506 //  Field  9 -- # of I/Os currently in progress
507 //      The only field that should go to zero. Incremented as requests are
508 //      given to appropriate struct request_queue and decremented as they
509 //      finish.
510 //  Field 10 -- # of milliseconds spent doing I/Os
511 //      This field increases so long as field 9 is nonzero.
512 //  Field 11 -- weighted # of milliseconds spent doing I/Os
513 //      This field is incremented at each I/O start, I/O completion, I/O
514 //      merge, or read of these stats by the number of I/Os in progress
515 //      (field 9) times the number of milliseconds spent doing I/O since the
516 //      last update of this field.  This can provide an easy measure of both
517 //      I/O completion time and the backlog that may be accumulating.
518 
519 const size_t kDiskDriveName = 2;
520 const size_t kDiskReads = 3;
521 const size_t kDiskReadsMerged = 4;
522 const size_t kDiskSectorsRead = 5;
523 const size_t kDiskReadTime = 6;
524 const size_t kDiskWrites = 7;
525 const size_t kDiskWritesMerged = 8;
526 const size_t kDiskSectorsWritten = 9;
527 const size_t kDiskWriteTime = 10;
528 const size_t kDiskIO = 11;
529 const size_t kDiskIOTime = 12;
530 const size_t kDiskWeightedIOTime = 13;
531 
532 }  // namespace
533 
SystemMemoryInfoKB()534 SystemMemoryInfoKB::SystemMemoryInfoKB() {
535   total = 0;
536   free = 0;
537 #if defined(OS_LINUX)
538   available = 0;
539 #endif
540   buffers = 0;
541   cached = 0;
542   active_anon = 0;
543   inactive_anon = 0;
544   active_file = 0;
545   inactive_file = 0;
546   swap_total = 0;
547   swap_free = 0;
548   dirty = 0;
549 
550   pswpin = 0;
551   pswpout = 0;
552   pgmajfault = 0;
553 
554 #ifdef OS_CHROMEOS
555   shmem = 0;
556   slab = 0;
557   gem_objects = -1;
558   gem_size = -1;
559 #endif
560 }
561 
562 SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) =
563     default;
564 
ToValue() const565 std::unique_ptr<Value> SystemMemoryInfoKB::ToValue() const {
566   std::unique_ptr<DictionaryValue> res(new DictionaryValue());
567 
568   res->SetInteger("total", total);
569   res->SetInteger("free", free);
570 #if defined(OS_LINUX)
571   res->SetInteger("available", available);
572 #endif
573   res->SetInteger("buffers", buffers);
574   res->SetInteger("cached", cached);
575   res->SetInteger("active_anon", active_anon);
576   res->SetInteger("inactive_anon", inactive_anon);
577   res->SetInteger("active_file", active_file);
578   res->SetInteger("inactive_file", inactive_file);
579   res->SetInteger("swap_total", swap_total);
580   res->SetInteger("swap_free", swap_free);
581   res->SetInteger("swap_used", swap_total - swap_free);
582   res->SetInteger("dirty", dirty);
583   res->SetInteger("pswpin", pswpin);
584   res->SetInteger("pswpout", pswpout);
585   res->SetInteger("pgmajfault", pgmajfault);
586 #ifdef OS_CHROMEOS
587   res->SetInteger("shmem", shmem);
588   res->SetInteger("slab", slab);
589   res->SetInteger("gem_objects", gem_objects);
590   res->SetInteger("gem_size", gem_size);
591 #endif
592 
593   return std::move(res);
594 }
595 
596 // exposed for testing
ParseProcMeminfo(const std::string & meminfo_data,SystemMemoryInfoKB * meminfo)597 bool ParseProcMeminfo(const std::string& meminfo_data,
598                       SystemMemoryInfoKB* meminfo) {
599   // The format of /proc/meminfo is:
600   //
601   // MemTotal:      8235324 kB
602   // MemFree:       1628304 kB
603   // Buffers:        429596 kB
604   // Cached:        4728232 kB
605   // ...
606   // There is no guarantee on the ordering or position
607   // though it doesn't appear to change very often
608 
609   // As a basic sanity check, let's make sure we at least get non-zero
610   // MemTotal value
611   meminfo->total = 0;
612 
613   for (const StringPiece& line : SplitStringPiece(
614            meminfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
615     std::vector<StringPiece> tokens = SplitStringPiece(
616         line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
617     // HugePages_* only has a number and no suffix so we can't rely on
618     // there being exactly 3 tokens.
619     if (tokens.size() <= 1) {
620       DLOG(WARNING) << "meminfo: tokens: " << tokens.size()
621                     << " malformed line: " << line.as_string();
622       continue;
623     }
624 
625     int* target = NULL;
626     if (tokens[0] == "MemTotal:")
627       target = &meminfo->total;
628     else if (tokens[0] == "MemFree:")
629       target = &meminfo->free;
630 #if defined(OS_LINUX)
631     else if (tokens[0] == "MemAvailable:")
632       target = &meminfo->available;
633 #endif
634     else if (tokens[0] == "Buffers:")
635       target = &meminfo->buffers;
636     else if (tokens[0] == "Cached:")
637       target = &meminfo->cached;
638     else if (tokens[0] == "Active(anon):")
639       target = &meminfo->active_anon;
640     else if (tokens[0] == "Inactive(anon):")
641       target = &meminfo->inactive_anon;
642     else if (tokens[0] == "Active(file):")
643       target = &meminfo->active_file;
644     else if (tokens[0] == "Inactive(file):")
645       target = &meminfo->inactive_file;
646     else if (tokens[0] == "SwapTotal:")
647       target = &meminfo->swap_total;
648     else if (tokens[0] == "SwapFree:")
649       target = &meminfo->swap_free;
650     else if (tokens[0] == "Dirty:")
651       target = &meminfo->dirty;
652 #if defined(OS_CHROMEOS)
653     // Chrome OS has a tweaked kernel that allows us to query Shmem, which is
654     // usually video memory otherwise invisible to the OS.
655     else if (tokens[0] == "Shmem:")
656       target = &meminfo->shmem;
657     else if (tokens[0] == "Slab:")
658       target = &meminfo->slab;
659 #endif
660     if (target)
661       StringToInt(tokens[1], target);
662   }
663 
664   // Make sure we got a valid MemTotal.
665   return meminfo->total > 0;
666 }
667 
668 // exposed for testing
ParseProcVmstat(const std::string & vmstat_data,SystemMemoryInfoKB * meminfo)669 bool ParseProcVmstat(const std::string& vmstat_data,
670                      SystemMemoryInfoKB* meminfo) {
671   // The format of /proc/vmstat is:
672   //
673   // nr_free_pages 299878
674   // nr_inactive_anon 239863
675   // nr_active_anon 1318966
676   // nr_inactive_file 2015629
677   // ...
678   //
679   // We iterate through the whole file because the position of the
680   // fields are dependent on the kernel version and configuration.
681 
682   for (const StringPiece& line : SplitStringPiece(
683            vmstat_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
684     std::vector<StringPiece> tokens = SplitStringPiece(
685         line, " ", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
686     if (tokens.size() != 2)
687       continue;
688 
689     if (tokens[0] == "pswpin") {
690       StringToInt(tokens[1], &meminfo->pswpin);
691     } else if (tokens[0] == "pswpout") {
692       StringToInt(tokens[1], &meminfo->pswpout);
693     } else if (tokens[0] == "pgmajfault") {
694       StringToInt(tokens[1], &meminfo->pgmajfault);
695     }
696   }
697 
698   return true;
699 }
700 
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)701 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
702   // Synchronously reading files in /proc and /sys are safe.
703   ThreadRestrictions::ScopedAllowIO allow_io;
704 
705   // Used memory is: total - free - buffers - caches
706   FilePath meminfo_file("/proc/meminfo");
707   std::string meminfo_data;
708   if (!ReadFileToString(meminfo_file, &meminfo_data)) {
709     DLOG(WARNING) << "Failed to open " << meminfo_file.value();
710     return false;
711   }
712 
713   if (!ParseProcMeminfo(meminfo_data, meminfo)) {
714     DLOG(WARNING) << "Failed to parse " << meminfo_file.value();
715     return false;
716   }
717 
718 #if defined(OS_CHROMEOS)
719   // Report on Chrome OS GEM object graphics memory. /run/debugfs_gpu is a
720   // bind mount into /sys/kernel/debug and synchronously reading the in-memory
721   // files in /sys is fast.
722 #if defined(ARCH_CPU_ARM_FAMILY)
723   FilePath geminfo_file("/run/debugfs_gpu/exynos_gem_objects");
724 #else
725   FilePath geminfo_file("/run/debugfs_gpu/i915_gem_objects");
726 #endif
727   std::string geminfo_data;
728   meminfo->gem_objects = -1;
729   meminfo->gem_size = -1;
730   if (ReadFileToString(geminfo_file, &geminfo_data)) {
731     int gem_objects = -1;
732     long long gem_size = -1;
733     int num_res = sscanf(geminfo_data.c_str(),
734                          "%d objects, %lld bytes",
735                          &gem_objects, &gem_size);
736     if (num_res == 2) {
737       meminfo->gem_objects = gem_objects;
738       meminfo->gem_size = gem_size;
739     }
740   }
741 
742 #if defined(ARCH_CPU_ARM_FAMILY)
743   // Incorporate Mali graphics memory if present.
744   FilePath mali_memory_file("/sys/class/misc/mali0/device/memory");
745   std::string mali_memory_data;
746   if (ReadFileToString(mali_memory_file, &mali_memory_data)) {
747     long long mali_size = -1;
748     int num_res = sscanf(mali_memory_data.c_str(), "%lld bytes", &mali_size);
749     if (num_res == 1)
750       meminfo->gem_size += mali_size;
751   }
752 #endif  // defined(ARCH_CPU_ARM_FAMILY)
753 #endif  // defined(OS_CHROMEOS)
754 
755   FilePath vmstat_file("/proc/vmstat");
756   std::string vmstat_data;
757   if (!ReadFileToString(vmstat_file, &vmstat_data)) {
758     DLOG(WARNING) << "Failed to open " << vmstat_file.value();
759     return false;
760   }
761   if (!ParseProcVmstat(vmstat_data, meminfo)) {
762     DLOG(WARNING) << "Failed to parse " << vmstat_file.value();
763     return false;
764   }
765 
766   return true;
767 }
768 
SystemDiskInfo()769 SystemDiskInfo::SystemDiskInfo() {
770   reads = 0;
771   reads_merged = 0;
772   sectors_read = 0;
773   read_time = 0;
774   writes = 0;
775   writes_merged = 0;
776   sectors_written = 0;
777   write_time = 0;
778   io = 0;
779   io_time = 0;
780   weighted_io_time = 0;
781 }
782 
783 SystemDiskInfo::SystemDiskInfo(const SystemDiskInfo& other) = default;
784 
ToValue() const785 std::unique_ptr<Value> SystemDiskInfo::ToValue() const {
786   std::unique_ptr<DictionaryValue> res(new DictionaryValue());
787 
788   // Write out uint64_t variables as doubles.
789   // Note: this may discard some precision, but for JS there's no other option.
790   res->SetDouble("reads", static_cast<double>(reads));
791   res->SetDouble("reads_merged", static_cast<double>(reads_merged));
792   res->SetDouble("sectors_read", static_cast<double>(sectors_read));
793   res->SetDouble("read_time", static_cast<double>(read_time));
794   res->SetDouble("writes", static_cast<double>(writes));
795   res->SetDouble("writes_merged", static_cast<double>(writes_merged));
796   res->SetDouble("sectors_written", static_cast<double>(sectors_written));
797   res->SetDouble("write_time", static_cast<double>(write_time));
798   res->SetDouble("io", static_cast<double>(io));
799   res->SetDouble("io_time", static_cast<double>(io_time));
800   res->SetDouble("weighted_io_time", static_cast<double>(weighted_io_time));
801 
802   return std::move(res);
803 }
804 
IsValidDiskName(const std::string & candidate)805 bool IsValidDiskName(const std::string& candidate) {
806   if (candidate.length() < 3)
807     return false;
808   if (candidate[1] == 'd' &&
809       (candidate[0] == 'h' || candidate[0] == 's' || candidate[0] == 'v')) {
810     // [hsv]d[a-z]+ case
811     for (size_t i = 2; i < candidate.length(); ++i) {
812       if (!islower(candidate[i]))
813         return false;
814     }
815     return true;
816   }
817 
818   const char kMMCName[] = "mmcblk";
819   const size_t kMMCNameLen = strlen(kMMCName);
820   if (candidate.length() < kMMCNameLen + 1)
821     return false;
822   if (candidate.compare(0, kMMCNameLen, kMMCName) != 0)
823     return false;
824 
825   // mmcblk[0-9]+ case
826   for (size_t i = kMMCNameLen; i < candidate.length(); ++i) {
827     if (!isdigit(candidate[i]))
828       return false;
829   }
830   return true;
831 }
832 
GetSystemDiskInfo(SystemDiskInfo * diskinfo)833 bool GetSystemDiskInfo(SystemDiskInfo* diskinfo) {
834   // Synchronously reading files in /proc does not hit the disk.
835   ThreadRestrictions::ScopedAllowIO allow_io;
836 
837   FilePath diskinfo_file("/proc/diskstats");
838   std::string diskinfo_data;
839   if (!ReadFileToString(diskinfo_file, &diskinfo_data)) {
840     DLOG(WARNING) << "Failed to open " << diskinfo_file.value();
841     return false;
842   }
843 
844   std::vector<StringPiece> diskinfo_lines = SplitStringPiece(
845       diskinfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
846   if (diskinfo_lines.size() == 0) {
847     DLOG(WARNING) << "No lines found";
848     return false;
849   }
850 
851   diskinfo->reads = 0;
852   diskinfo->reads_merged = 0;
853   diskinfo->sectors_read = 0;
854   diskinfo->read_time = 0;
855   diskinfo->writes = 0;
856   diskinfo->writes_merged = 0;
857   diskinfo->sectors_written = 0;
858   diskinfo->write_time = 0;
859   diskinfo->io = 0;
860   diskinfo->io_time = 0;
861   diskinfo->weighted_io_time = 0;
862 
863   uint64_t reads = 0;
864   uint64_t reads_merged = 0;
865   uint64_t sectors_read = 0;
866   uint64_t read_time = 0;
867   uint64_t writes = 0;
868   uint64_t writes_merged = 0;
869   uint64_t sectors_written = 0;
870   uint64_t write_time = 0;
871   uint64_t io = 0;
872   uint64_t io_time = 0;
873   uint64_t weighted_io_time = 0;
874 
875   for (const StringPiece& line : diskinfo_lines) {
876     std::vector<StringPiece> disk_fields = SplitStringPiece(
877         line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
878 
879     // Fields may have overflowed and reset to zero.
880     if (IsValidDiskName(disk_fields[kDiskDriveName].as_string())) {
881       StringToUint64(disk_fields[kDiskReads], &reads);
882       StringToUint64(disk_fields[kDiskReadsMerged], &reads_merged);
883       StringToUint64(disk_fields[kDiskSectorsRead], &sectors_read);
884       StringToUint64(disk_fields[kDiskReadTime], &read_time);
885       StringToUint64(disk_fields[kDiskWrites], &writes);
886       StringToUint64(disk_fields[kDiskWritesMerged], &writes_merged);
887       StringToUint64(disk_fields[kDiskSectorsWritten], &sectors_written);
888       StringToUint64(disk_fields[kDiskWriteTime], &write_time);
889       StringToUint64(disk_fields[kDiskIO], &io);
890       StringToUint64(disk_fields[kDiskIOTime], &io_time);
891       StringToUint64(disk_fields[kDiskWeightedIOTime], &weighted_io_time);
892 
893       diskinfo->reads += reads;
894       diskinfo->reads_merged += reads_merged;
895       diskinfo->sectors_read += sectors_read;
896       diskinfo->read_time += read_time;
897       diskinfo->writes += writes;
898       diskinfo->writes_merged += writes_merged;
899       diskinfo->sectors_written += sectors_written;
900       diskinfo->write_time += write_time;
901       diskinfo->io += io;
902       diskinfo->io_time += io_time;
903       diskinfo->weighted_io_time += weighted_io_time;
904     }
905   }
906 
907   return true;
908 }
909 
910 #if defined(OS_CHROMEOS)
ToValue() const911 std::unique_ptr<Value> SwapInfo::ToValue() const {
912   std::unique_ptr<DictionaryValue> res(new DictionaryValue());
913 
914   // Write out uint64_t variables as doubles.
915   // Note: this may discard some precision, but for JS there's no other option.
916   res->SetDouble("num_reads", static_cast<double>(num_reads));
917   res->SetDouble("num_writes", static_cast<double>(num_writes));
918   res->SetDouble("orig_data_size", static_cast<double>(orig_data_size));
919   res->SetDouble("compr_data_size", static_cast<double>(compr_data_size));
920   res->SetDouble("mem_used_total", static_cast<double>(mem_used_total));
921   if (compr_data_size > 0)
922     res->SetDouble("compression_ratio", static_cast<double>(orig_data_size) /
923                                         static_cast<double>(compr_data_size));
924   else
925     res->SetDouble("compression_ratio", 0);
926 
927   return std::move(res);
928 }
929 
GetSwapInfo(SwapInfo * swap_info)930 void GetSwapInfo(SwapInfo* swap_info) {
931   // Synchronously reading files in /sys/block/zram0 does not hit the disk.
932   ThreadRestrictions::ScopedAllowIO allow_io;
933 
934   FilePath zram_path("/sys/block/zram0");
935   uint64_t orig_data_size =
936       ReadFileToUint64(zram_path.Append("orig_data_size"));
937   if (orig_data_size <= 4096) {
938     // A single page is compressed at startup, and has a high compression
939     // ratio. We ignore this as it doesn't indicate any real swapping.
940     swap_info->orig_data_size = 0;
941     swap_info->num_reads = 0;
942     swap_info->num_writes = 0;
943     swap_info->compr_data_size = 0;
944     swap_info->mem_used_total = 0;
945     return;
946   }
947   swap_info->orig_data_size = orig_data_size;
948   swap_info->num_reads = ReadFileToUint64(zram_path.Append("num_reads"));
949   swap_info->num_writes = ReadFileToUint64(zram_path.Append("num_writes"));
950   swap_info->compr_data_size =
951       ReadFileToUint64(zram_path.Append("compr_data_size"));
952   swap_info->mem_used_total =
953       ReadFileToUint64(zram_path.Append("mem_used_total"));
954 }
955 #endif  // defined(OS_CHROMEOS)
956 
957 #if defined(OS_LINUX)
GetIdleWakeupsPerSecond()958 int ProcessMetrics::GetIdleWakeupsPerSecond() {
959   uint64_t wake_ups;
960   const char kWakeupStat[] = "se.statistics.nr_wakeups";
961   return ReadProcSchedAndGetFieldAsUint64(process_, kWakeupStat, &wake_ups) ?
962       CalculateIdleWakeupsPerSecond(wake_ups) : 0;
963 }
964 #endif  // defined(OS_LINUX)
965 
966 }  // namespace base
967