Make certificate viewer a tab-modal dialog.
[chromium-blink-merge.git] / base / process_util_linux.cc
blobe06d99cf599ea3f232a578027cac8fdbdc0a76b9
1 // Copyright (c) 2012 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.
5 #include "base/process_util.h"
7 #include <dirent.h>
8 #include <malloc.h>
9 #include <sys/time.h>
10 #include <sys/types.h>
11 #include <unistd.h>
13 #include "base/file_util.h"
14 #include "base/logging.h"
15 #include "base/string_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_tokenizer.h"
19 #include "base/sys_info.h"
20 #include "base/threading/thread_restrictions.h"
22 namespace base {
24 namespace {
26 enum ParsingState {
27 KEY_NAME,
28 KEY_VALUE
31 const char kProcDir[] = "/proc";
32 const char kStatFile[] = "stat";
34 // Returns a FilePath to "/proc/pid".
35 FilePath GetProcPidDir(pid_t pid) {
36 return FilePath(kProcDir).Append(IntToString(pid));
39 // Fields from /proc/<pid>/stat, 0-based. See man 5 proc.
40 // If the ordering ever changes, carefully review functions that use these
41 // values.
42 enum ProcStatsFields {
43 VM_COMM = 1, // Filename of executable, without parentheses.
44 VM_STATE = 2, // Letter indicating the state of the process.
45 VM_PPID = 3, // PID of the parent.
46 VM_PGRP = 4, // Process group id.
47 VM_UTIME = 13, // Time scheduled in user mode in clock ticks.
48 VM_STIME = 14, // Time scheduled in kernel mode in clock ticks.
49 VM_NUMTHREADS = 19, // Number of threads.
50 VM_VSIZE = 22, // Virtual memory size in bytes.
51 VM_RSS = 23, // Resident Set Size in pages.
54 // Reads /proc/<pid>/stat into |buffer|. Returns true if the file can be read
55 // and is non-empty.
56 bool ReadProcStats(pid_t pid, std::string* buffer) {
57 buffer->clear();
58 // Synchronously reading files in /proc is safe.
59 ThreadRestrictions::ScopedAllowIO allow_io;
61 FilePath stat_file = GetProcPidDir(pid).Append(kStatFile);
62 if (!file_util::ReadFileToString(stat_file, buffer)) {
63 DLOG(WARNING) << "Failed to get process stats.";
64 return false;
66 return !buffer->empty();
69 // Takes |stats_data| and populates |proc_stats| with the values split by
70 // spaces. Taking into account the 2nd field may, in itself, contain spaces.
71 // Returns true if successful.
72 bool ParseProcStats(const std::string& stats_data,
73 std::vector<std::string>* proc_stats) {
74 // |stats_data| may be empty if the process disappeared somehow.
75 // e.g. http://crbug.com/145811
76 if (stats_data.empty())
77 return false;
79 // The stat file is formatted as:
80 // pid (process name) data1 data2 .... dataN
81 // Look for the closing paren by scanning backwards, to avoid being fooled by
82 // processes with ')' in the name.
83 size_t open_parens_idx = stats_data.find(" (");
84 size_t close_parens_idx = stats_data.rfind(") ");
85 if (open_parens_idx == std::string::npos ||
86 close_parens_idx == std::string::npos ||
87 open_parens_idx > close_parens_idx) {
88 DLOG(WARNING) << "Failed to find matched parens in '" << stats_data << "'";
89 NOTREACHED();
90 return false;
92 open_parens_idx++;
94 proc_stats->clear();
95 // PID.
96 proc_stats->push_back(stats_data.substr(0, open_parens_idx));
97 // Process name without parentheses.
98 proc_stats->push_back(
99 stats_data.substr(open_parens_idx + 1,
100 close_parens_idx - (open_parens_idx + 1)));
102 // Split the rest.
103 std::vector<std::string> other_stats;
104 SplitString(stats_data.substr(close_parens_idx + 2), ' ', &other_stats);
105 for (size_t i = 0; i < other_stats.size(); ++i)
106 proc_stats->push_back(other_stats[i]);
107 return true;
110 // Reads the |field_num|th field from |proc_stats|. Returns 0 on failure.
111 // This version does not handle the first 3 values, since the first value is
112 // simply |pid|, and the next two values are strings.
113 int GetProcStatsFieldAsInt(const std::vector<std::string>& proc_stats,
114 ProcStatsFields field_num) {
115 DCHECK_GE(field_num, VM_PPID);
116 CHECK_LT(static_cast<size_t>(field_num), proc_stats.size());
118 int value;
119 return StringToInt(proc_stats[field_num], &value) ? value : 0;
122 // Same as GetProcStatsFieldAsInt(), but for size_t values.
123 size_t GetProcStatsFieldAsSizeT(const std::vector<std::string>& proc_stats,
124 ProcStatsFields field_num) {
125 DCHECK_GE(field_num, VM_PPID);
126 CHECK_LT(static_cast<size_t>(field_num), proc_stats.size());
128 size_t value;
129 return StringToSizeT(proc_stats[field_num], &value) ? value : 0;
132 // Convenience wrapper around GetProcStatsFieldAsInt(), ParseProcStats() and
133 // ReadProcStats(). See GetProcStatsFieldAsInt() for details.
134 int ReadProcStatsAndGetFieldAsInt(pid_t pid, ProcStatsFields field_num) {
135 std::string stats_data;
136 if (!ReadProcStats(pid, &stats_data))
137 return 0;
138 std::vector<std::string> proc_stats;
139 if (!ParseProcStats(stats_data, &proc_stats))
140 return 0;
141 return GetProcStatsFieldAsInt(proc_stats, field_num);
144 // Same as ReadProcStatsAndGetFieldAsInt() but for size_t values.
145 size_t ReadProcStatsAndGetFieldAsSizeT(pid_t pid, ProcStatsFields field_num) {
146 std::string stats_data;
147 if (!ReadProcStats(pid, &stats_data))
148 return 0;
149 std::vector<std::string> proc_stats;
150 if (!ParseProcStats(stats_data, &proc_stats))
151 return 0;
152 return GetProcStatsFieldAsSizeT(proc_stats, field_num);
155 // Reads the |field_num|th field from |proc_stats|.
156 // Returns an empty string on failure.
157 // This version only handles VM_COMM and VM_STATE, which are the only fields
158 // that are strings.
159 std::string GetProcStatsFieldAsString(
160 const std::vector<std::string>& proc_stats,
161 ProcStatsFields field_num) {
162 if (field_num < VM_COMM || field_num > VM_STATE) {
163 NOTREACHED();
164 return std::string();
167 if (proc_stats.size() > static_cast<size_t>(field_num))
168 return proc_stats[field_num];
170 NOTREACHED();
171 return 0;
174 // Reads /proc/<pid>/cmdline and populates |proc_cmd_line_args| with the command
175 // line arguments. Returns true if successful.
176 // Note: /proc/<pid>/cmdline contains command line arguments separated by single
177 // null characters. We tokenize it into a vector of strings using '\0' as a
178 // delimiter.
179 bool GetProcCmdline(pid_t pid, std::vector<std::string>* proc_cmd_line_args) {
180 // Synchronously reading files in /proc is safe.
181 ThreadRestrictions::ScopedAllowIO allow_io;
183 FilePath cmd_line_file = GetProcPidDir(pid).Append("cmdline");
184 std::string cmd_line;
185 if (!file_util::ReadFileToString(cmd_line_file, &cmd_line))
186 return false;
187 std::string delimiters;
188 delimiters.push_back('\0');
189 Tokenize(cmd_line, delimiters, proc_cmd_line_args);
190 return true;
193 // Take a /proc directory entry named |d_name|, and if it is the directory for
194 // a process, convert it to a pid_t.
195 // Returns 0 on failure.
196 // e.g. /proc/self/ will return 0, whereas /proc/1234 will return 1234.
197 pid_t ProcDirSlotToPid(const char* d_name) {
198 int i;
199 for (i = 0; i < NAME_MAX && d_name[i]; ++i) {
200 if (!IsAsciiDigit(d_name[i])) {
201 return 0;
204 if (i == NAME_MAX)
205 return 0;
207 // Read the process's command line.
208 pid_t pid;
209 std::string pid_string(d_name);
210 if (!StringToInt(pid_string, &pid)) {
211 NOTREACHED();
212 return 0;
214 return pid;
217 // Get the total CPU of a single process. Return value is number of jiffies
218 // on success or -1 on error.
219 int GetProcessCPU(pid_t pid) {
220 // Use /proc/<pid>/task to find all threads and parse their /stat file.
221 FilePath task_path = GetProcPidDir(pid).Append("task");
223 DIR* dir = opendir(task_path.value().c_str());
224 if (!dir) {
225 DPLOG(ERROR) << "opendir(" << task_path.value() << ")";
226 return -1;
229 int total_cpu = 0;
230 while (struct dirent* ent = readdir(dir)) {
231 pid_t tid = ProcDirSlotToPid(ent->d_name);
232 if (!tid)
233 continue;
235 // Synchronously reading files in /proc is safe.
236 ThreadRestrictions::ScopedAllowIO allow_io;
238 std::string stat;
239 FilePath stat_path = task_path.Append(ent->d_name).Append(kStatFile);
240 if (file_util::ReadFileToString(stat_path, &stat)) {
241 int cpu = ParseProcStatCPU(stat);
242 if (cpu > 0)
243 total_cpu += cpu;
246 closedir(dir);
248 return total_cpu;
251 // Read /proc/<pid>/status and returns the value for |field|, or 0 on failure.
252 // Only works for fields in the form of "Field: value kB".
253 size_t ReadProcStatusAndGetFieldAsSizeT(pid_t pid, const std::string& field) {
254 FilePath stat_file = GetProcPidDir(pid).Append("status");
255 std::string status;
257 // Synchronously reading files in /proc is safe.
258 ThreadRestrictions::ScopedAllowIO allow_io;
259 if (!file_util::ReadFileToString(stat_file, &status))
260 return 0;
263 StringTokenizer tokenizer(status, ":\n");
264 ParsingState state = KEY_NAME;
265 StringPiece last_key_name;
266 while (tokenizer.GetNext()) {
267 switch (state) {
268 case KEY_NAME:
269 last_key_name = tokenizer.token_piece();
270 state = KEY_VALUE;
271 break;
272 case KEY_VALUE:
273 DCHECK(!last_key_name.empty());
274 if (last_key_name == field) {
275 std::string value_str;
276 tokenizer.token_piece().CopyToString(&value_str);
277 std::string value_str_trimmed;
278 TrimWhitespaceASCII(value_str, TRIM_ALL, &value_str_trimmed);
279 std::vector<std::string> split_value_str;
280 SplitString(value_str_trimmed, ' ', &split_value_str);
281 if (split_value_str.size() != 2 || split_value_str[1] != "kB") {
282 NOTREACHED();
283 return 0;
285 size_t value;
286 if (!StringToSizeT(split_value_str[0], &value)) {
287 NOTREACHED();
288 return 0;
290 return value;
292 state = KEY_NAME;
293 break;
296 NOTREACHED();
297 return 0;
300 } // namespace
302 #if defined(USE_LINUX_BREAKPAD)
303 size_t g_oom_size = 0U;
304 #endif
306 const char kProcSelfExe[] = "/proc/self/exe";
308 ProcessId GetParentProcessId(ProcessHandle process) {
309 ProcessId pid = ReadProcStatsAndGetFieldAsInt(process, VM_PPID);
310 if (pid)
311 return pid;
312 return -1;
315 FilePath GetProcessExecutablePath(ProcessHandle process) {
316 FilePath stat_file = GetProcPidDir(process).Append("exe");
317 FilePath exe_name;
318 if (!file_util::ReadSymbolicLink(stat_file, &exe_name)) {
319 // No such process. Happens frequently in e.g. TerminateAllChromeProcesses
320 return FilePath();
322 return exe_name;
325 ProcessIterator::ProcessIterator(const ProcessFilter* filter)
326 : filter_(filter) {
327 procfs_dir_ = opendir(kProcDir);
330 ProcessIterator::~ProcessIterator() {
331 if (procfs_dir_) {
332 closedir(procfs_dir_);
333 procfs_dir_ = NULL;
337 bool ProcessIterator::CheckForNextProcess() {
338 // TODO(port): skip processes owned by different UID
340 pid_t pid = kNullProcessId;
341 std::vector<std::string> cmd_line_args;
342 std::string stats_data;
343 std::vector<std::string> proc_stats;
345 // Arbitrarily guess that there will never be more than 200 non-process
346 // files in /proc. Hardy has 53 and Lucid has 61.
347 int skipped = 0;
348 const int kSkipLimit = 200;
349 while (skipped < kSkipLimit) {
350 dirent* slot = readdir(procfs_dir_);
351 // all done looking through /proc?
352 if (!slot)
353 return false;
355 // If not a process, keep looking for one.
356 pid = ProcDirSlotToPid(slot->d_name);
357 if (!pid) {
358 skipped++;
359 continue;
362 if (!GetProcCmdline(pid, &cmd_line_args))
363 continue;
365 if (!ReadProcStats(pid, &stats_data))
366 continue;
367 if (!ParseProcStats(stats_data, &proc_stats))
368 continue;
370 std::string runstate = GetProcStatsFieldAsString(proc_stats, VM_STATE);
371 if (runstate.size() != 1) {
372 NOTREACHED();
373 continue;
376 // Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?
377 // Allowed values: D R S T Z
378 if (runstate[0] != 'Z')
379 break;
381 // Nope, it's a zombie; somebody isn't cleaning up after their children.
382 // (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)
383 // There could be a lot of zombies, can't really decrement i here.
385 if (skipped >= kSkipLimit) {
386 NOTREACHED();
387 return false;
390 entry_.pid_ = pid;
391 entry_.ppid_ = GetProcStatsFieldAsInt(proc_stats, VM_PPID);
392 entry_.gid_ = GetProcStatsFieldAsInt(proc_stats, VM_PGRP);
393 entry_.cmd_line_args_.assign(cmd_line_args.begin(), cmd_line_args.end());
395 // TODO(port): read pid's commandline's $0, like killall does. Using the
396 // short name between openparen and closeparen won't work for long names!
397 entry_.exe_file_ = GetProcStatsFieldAsString(proc_stats, VM_COMM);
398 return true;
401 bool NamedProcessIterator::IncludeEntry() {
402 if (executable_name_ != entry().exe_file())
403 return false;
404 return ProcessIterator::IncludeEntry();
408 // static
409 ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
410 return new ProcessMetrics(process);
413 // On linux, we return vsize.
414 size_t ProcessMetrics::GetPagefileUsage() const {
415 return ReadProcStatsAndGetFieldAsSizeT(process_, VM_VSIZE);
418 // On linux, we return the high water mark of vsize.
419 size_t ProcessMetrics::GetPeakPagefileUsage() const {
420 return ReadProcStatusAndGetFieldAsSizeT(process_, "VmPeak") * 1024;
423 // On linux, we return RSS.
424 size_t ProcessMetrics::GetWorkingSetSize() const {
425 return ReadProcStatsAndGetFieldAsSizeT(process_, VM_RSS) * getpagesize();
428 // On linux, we return the high water mark of RSS.
429 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
430 return ReadProcStatusAndGetFieldAsSizeT(process_, "VmHWM") * 1024;
433 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
434 size_t* shared_bytes) {
435 WorkingSetKBytes ws_usage;
436 if (!GetWorkingSetKBytes(&ws_usage))
437 return false;
439 if (private_bytes)
440 *private_bytes = ws_usage.priv * 1024;
442 if (shared_bytes)
443 *shared_bytes = ws_usage.shared * 1024;
445 return true;
448 // Private and Shared working set sizes are obtained from /proc/<pid>/statm.
449 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
450 // Use statm instead of smaps because smaps is:
451 // a) Large and slow to parse.
452 // b) Unavailable in the SUID sandbox.
454 // First we need to get the page size, since everything is measured in pages.
455 // For details, see: man 5 proc.
456 const int page_size_kb = getpagesize() / 1024;
457 if (page_size_kb <= 0)
458 return false;
460 std::string statm;
462 FilePath statm_file = GetProcPidDir(process_).Append("statm");
463 // Synchronously reading files in /proc is safe.
464 ThreadRestrictions::ScopedAllowIO allow_io;
465 bool ret = file_util::ReadFileToString(statm_file, &statm);
466 if (!ret || statm.length() == 0)
467 return false;
470 std::vector<std::string> statm_vec;
471 SplitString(statm, ' ', &statm_vec);
472 if (statm_vec.size() != 7)
473 return false; // Not the format we expect.
475 int statm_rss, statm_shared;
476 StringToInt(statm_vec[1], &statm_rss);
477 StringToInt(statm_vec[2], &statm_shared);
479 ws_usage->priv = (statm_rss - statm_shared) * page_size_kb;
480 ws_usage->shared = statm_shared * page_size_kb;
482 // Sharable is not calculated, as it does not provide interesting data.
483 ws_usage->shareable = 0;
485 return true;
488 double ProcessMetrics::GetCPUUsage() {
489 // This queries the /proc-specific scaling factor which is
490 // conceptually the system hertz. To dump this value on another
491 // system, try
492 // od -t dL /proc/self/auxv
493 // and look for the number after 17 in the output; mine is
494 // 0000040 17 100 3 134512692
495 // which means the answer is 100.
496 // It may be the case that this value is always 100.
497 static const int kHertz = sysconf(_SC_CLK_TCK);
499 struct timeval now;
500 int retval = gettimeofday(&now, NULL);
501 if (retval)
502 return 0;
503 int64 time = TimeValToMicroseconds(now);
505 if (last_time_ == 0) {
506 // First call, just set the last values.
507 last_time_ = time;
508 last_cpu_ = GetProcessCPU(process_);
509 return 0;
512 int64 time_delta = time - last_time_;
513 DCHECK_NE(time_delta, 0);
514 if (time_delta == 0)
515 return 0;
517 int cpu = GetProcessCPU(process_);
519 // We have the number of jiffies in the time period. Convert to percentage.
520 // Note this means we will go *over* 100 in the case where multiple threads
521 // are together adding to more than one CPU's worth.
522 int percentage = 100 * (cpu - last_cpu_) /
523 (kHertz * TimeDelta::FromMicroseconds(time_delta).InSecondsF());
525 last_time_ = time;
526 last_cpu_ = cpu;
528 return percentage;
531 // To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
532 // in your kernel configuration.
533 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
534 // Synchronously reading files in /proc is safe.
535 ThreadRestrictions::ScopedAllowIO allow_io;
537 std::string proc_io_contents;
538 FilePath io_file = GetProcPidDir(process_).Append("io");
539 if (!file_util::ReadFileToString(io_file, &proc_io_contents))
540 return false;
542 (*io_counters).OtherOperationCount = 0;
543 (*io_counters).OtherTransferCount = 0;
545 StringTokenizer tokenizer(proc_io_contents, ": \n");
546 ParsingState state = KEY_NAME;
547 StringPiece last_key_name;
548 while (tokenizer.GetNext()) {
549 switch (state) {
550 case KEY_NAME:
551 last_key_name = tokenizer.token_piece();
552 state = KEY_VALUE;
553 break;
554 case KEY_VALUE:
555 DCHECK(!last_key_name.empty());
556 if (last_key_name == "syscr") {
557 StringToInt64(tokenizer.token_piece(),
558 reinterpret_cast<int64*>(&(*io_counters).ReadOperationCount));
559 } else if (last_key_name == "syscw") {
560 StringToInt64(tokenizer.token_piece(),
561 reinterpret_cast<int64*>(&(*io_counters).WriteOperationCount));
562 } else if (last_key_name == "rchar") {
563 StringToInt64(tokenizer.token_piece(),
564 reinterpret_cast<int64*>(&(*io_counters).ReadTransferCount));
565 } else if (last_key_name == "wchar") {
566 StringToInt64(tokenizer.token_piece(),
567 reinterpret_cast<int64*>(&(*io_counters).WriteTransferCount));
569 state = KEY_NAME;
570 break;
573 return true;
576 ProcessMetrics::ProcessMetrics(ProcessHandle process)
577 : process_(process),
578 last_time_(0),
579 last_system_time_(0),
580 last_cpu_(0) {
581 processor_count_ = SysInfo::NumberOfProcessors();
585 // Exposed for testing.
586 int ParseProcStatCPU(const std::string& input) {
587 std::vector<std::string> proc_stats;
588 if (!ParseProcStats(input, &proc_stats))
589 return -1;
591 if (proc_stats.size() <= VM_STIME)
592 return -1;
593 int utime = GetProcStatsFieldAsInt(proc_stats, VM_UTIME);
594 int stime = GetProcStatsFieldAsInt(proc_stats, VM_STIME);
595 return utime + stime;
598 int GetNumberOfThreads(ProcessHandle process) {
599 return ReadProcStatsAndGetFieldAsInt(process, VM_NUMTHREADS);
602 namespace {
604 // The format of /proc/meminfo is:
606 // MemTotal: 8235324 kB
607 // MemFree: 1628304 kB
608 // Buffers: 429596 kB
609 // Cached: 4728232 kB
610 // ...
611 const size_t kMemTotalIndex = 1;
612 const size_t kMemFreeIndex = 4;
613 const size_t kMemBuffersIndex = 7;
614 const size_t kMemCachedIndex = 10;
615 const size_t kMemActiveAnonIndex = 22;
616 const size_t kMemInactiveAnonIndex = 25;
617 const size_t kMemActiveFileIndex = 28;
618 const size_t kMemInactiveFileIndex = 31;
620 } // namespace
622 SystemMemoryInfoKB::SystemMemoryInfoKB()
623 : total(0),
624 free(0),
625 buffers(0),
626 cached(0),
627 active_anon(0),
628 inactive_anon(0),
629 active_file(0),
630 inactive_file(0),
631 shmem(0),
632 gem_objects(-1),
633 gem_size(-1) {
636 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
637 // Synchronously reading files in /proc is safe.
638 ThreadRestrictions::ScopedAllowIO allow_io;
640 // Used memory is: total - free - buffers - caches
641 FilePath meminfo_file("/proc/meminfo");
642 std::string meminfo_data;
643 if (!file_util::ReadFileToString(meminfo_file, &meminfo_data)) {
644 DLOG(WARNING) << "Failed to open " << meminfo_file.value();
645 return false;
647 std::vector<std::string> meminfo_fields;
648 SplitStringAlongWhitespace(meminfo_data, &meminfo_fields);
650 if (meminfo_fields.size() < kMemCachedIndex) {
651 DLOG(WARNING) << "Failed to parse " << meminfo_file.value()
652 << ". Only found " << meminfo_fields.size() << " fields.";
653 return false;
656 DCHECK_EQ(meminfo_fields[kMemTotalIndex-1], "MemTotal:");
657 DCHECK_EQ(meminfo_fields[kMemFreeIndex-1], "MemFree:");
658 DCHECK_EQ(meminfo_fields[kMemBuffersIndex-1], "Buffers:");
659 DCHECK_EQ(meminfo_fields[kMemCachedIndex-1], "Cached:");
660 DCHECK_EQ(meminfo_fields[kMemActiveAnonIndex-1], "Active(anon):");
661 DCHECK_EQ(meminfo_fields[kMemInactiveAnonIndex-1], "Inactive(anon):");
662 DCHECK_EQ(meminfo_fields[kMemActiveFileIndex-1], "Active(file):");
663 DCHECK_EQ(meminfo_fields[kMemInactiveFileIndex-1], "Inactive(file):");
665 StringToInt(meminfo_fields[kMemTotalIndex], &meminfo->total);
666 StringToInt(meminfo_fields[kMemFreeIndex], &meminfo->free);
667 StringToInt(meminfo_fields[kMemBuffersIndex], &meminfo->buffers);
668 StringToInt(meminfo_fields[kMemCachedIndex], &meminfo->cached);
669 StringToInt(meminfo_fields[kMemActiveAnonIndex], &meminfo->active_anon);
670 StringToInt(meminfo_fields[kMemInactiveAnonIndex],
671 &meminfo->inactive_anon);
672 StringToInt(meminfo_fields[kMemActiveFileIndex], &meminfo->active_file);
673 StringToInt(meminfo_fields[kMemInactiveFileIndex],
674 &meminfo->inactive_file);
675 #if defined(OS_CHROMEOS)
676 // Chrome OS has a tweaked kernel that allows us to query Shmem, which is
677 // usually video memory otherwise invisible to the OS. Unfortunately, the
678 // meminfo format varies on different hardware so we have to search for the
679 // string. It always appears after "Cached:".
680 for (size_t i = kMemCachedIndex+2; i < meminfo_fields.size(); i += 3) {
681 if (meminfo_fields[i] == "Shmem:") {
682 StringToInt(meminfo_fields[i+1], &meminfo->shmem);
683 break;
687 // Report on Chrome OS GEM object graphics memory. /var/run/debugfs_gpu is a
688 // bind mount into /sys/kernel/debug and synchronously reading the in-memory
689 // files in /sys is fast.
690 #if defined(ARCH_CPU_ARM_FAMILY)
691 FilePath geminfo_file("/var/run/debugfs_gpu/exynos_gem_objects");
692 #else
693 FilePath geminfo_file("/var/run/debugfs_gpu/i915_gem_objects");
694 #endif
695 std::string geminfo_data;
696 meminfo->gem_objects = -1;
697 meminfo->gem_size = -1;
698 if (file_util::ReadFileToString(geminfo_file, &geminfo_data)) {
699 int gem_objects = -1;
700 long long gem_size = -1;
701 int num_res = sscanf(geminfo_data.c_str(),
702 "%d objects, %lld bytes",
703 &gem_objects, &gem_size);
704 if (num_res == 2) {
705 meminfo->gem_objects = gem_objects;
706 meminfo->gem_size = gem_size;
710 #if defined(ARCH_CPU_ARM_FAMILY)
711 // Incorporate Mali graphics memory if present.
712 FilePath mali_memory_file("/sys/devices/platform/mali.0/memory");
713 std::string mali_memory_data;
714 if (file_util::ReadFileToString(mali_memory_file, &mali_memory_data)) {
715 long long mali_size = -1;
716 int num_res = sscanf(mali_memory_data.c_str(), "%lld bytes", &mali_size);
717 if (num_res == 1)
718 meminfo->gem_size += mali_size;
720 #endif // defined(ARCH_CPU_ARM_FAMILY)
721 #endif // defined(OS_CHROMEOS)
723 return true;
726 size_t GetSystemCommitCharge() {
727 SystemMemoryInfoKB meminfo;
728 if (!GetSystemMemoryInfo(&meminfo))
729 return 0;
730 return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
733 namespace {
735 void OnNoMemorySize(size_t size) {
736 #if defined(USE_LINUX_BREAKPAD)
737 g_oom_size = size;
738 #endif
740 if (size != 0)
741 LOG(FATAL) << "Out of memory, size = " << size;
742 LOG(FATAL) << "Out of memory.";
745 void OnNoMemory() {
746 OnNoMemorySize(0);
749 } // namespace
751 #if !defined(OS_ANDROID) && !defined(USE_TCMALLOC) && \
752 !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
753 !defined(THREAD_SANITIZER)
755 extern "C" {
756 void* __libc_malloc(size_t size);
757 void* __libc_realloc(void* ptr, size_t size);
758 void* __libc_calloc(size_t nmemb, size_t size);
759 void* __libc_valloc(size_t size);
760 void* __libc_pvalloc(size_t size);
761 void* __libc_memalign(size_t alignment, size_t size);
763 // Overriding the system memory allocation functions:
765 // For security reasons, we want malloc failures to be fatal. Too much code
766 // doesn't check for a NULL return value from malloc and unconditionally uses
767 // the resulting pointer. If the first offset that they try to access is
768 // attacker controlled, then the attacker can direct the code to access any
769 // part of memory.
771 // Thus, we define all the standard malloc functions here and mark them as
772 // visibility 'default'. This means that they replace the malloc functions for
773 // all Chromium code and also for all code in shared libraries. There are tests
774 // for this in process_util_unittest.cc.
776 // If we are using tcmalloc, then the problem is moot since tcmalloc handles
777 // this for us. Thus this code is in a !defined(USE_TCMALLOC) block.
779 // If we are testing the binary with AddressSanitizer, we should not
780 // redefine malloc and let AddressSanitizer do it instead.
782 // We call the real libc functions in this code by using __libc_malloc etc.
783 // Previously we tried using dlsym(RTLD_NEXT, ...) but that failed depending on
784 // the link order. Since ld.so needs calloc during symbol resolution, it
785 // defines its own versions of several of these functions in dl-minimal.c.
786 // Depending on the runtime library order, dlsym ended up giving us those
787 // functions and bad things happened. See crbug.com/31809
789 // This means that any code which calls __libc_* gets the raw libc versions of
790 // these functions.
792 #define DIE_ON_OOM_1(function_name) \
793 void* function_name(size_t) __attribute__ ((visibility("default"))); \
795 void* function_name(size_t size) { \
796 void* ret = __libc_##function_name(size); \
797 if (ret == NULL && size != 0) \
798 OnNoMemorySize(size); \
799 return ret; \
802 #define DIE_ON_OOM_2(function_name, arg1_type) \
803 void* function_name(arg1_type, size_t) \
804 __attribute__ ((visibility("default"))); \
806 void* function_name(arg1_type arg1, size_t size) { \
807 void* ret = __libc_##function_name(arg1, size); \
808 if (ret == NULL && size != 0) \
809 OnNoMemorySize(size); \
810 return ret; \
813 DIE_ON_OOM_1(malloc)
814 DIE_ON_OOM_1(valloc)
815 DIE_ON_OOM_1(pvalloc)
817 DIE_ON_OOM_2(calloc, size_t)
818 DIE_ON_OOM_2(realloc, void*)
819 DIE_ON_OOM_2(memalign, size_t)
821 // posix_memalign has a unique signature and doesn't have a __libc_ variant.
822 int posix_memalign(void** ptr, size_t alignment, size_t size)
823 __attribute__ ((visibility("default")));
825 int posix_memalign(void** ptr, size_t alignment, size_t size) {
826 // This will use the safe version of memalign, above.
827 *ptr = memalign(alignment, size);
828 return 0;
831 } // extern C
832 #endif // ANDROID, TCMALLOC, *_SANITIZER
834 void EnableTerminationOnHeapCorruption() {
835 // On Linux, there nothing to do AFAIK.
838 void EnableTerminationOnOutOfMemory() {
839 #if defined(OS_ANDROID)
840 // Android doesn't support setting a new handler.
841 DLOG(WARNING) << "Not feasible.";
842 #else
843 // Set the new-out of memory handler.
844 std::set_new_handler(&OnNoMemory);
845 // If we're using glibc's allocator, the above functions will override
846 // malloc and friends and make them die on out of memory.
847 #endif
850 // NOTE: This is not the only version of this function in the source:
851 // the setuid sandbox (in process_util_linux.c, in the sandbox source)
852 // also has its own C version.
853 bool AdjustOOMScore(ProcessId process, int score) {
854 if (score < 0 || score > kMaxOomScore)
855 return false;
857 FilePath oom_path(GetProcPidDir(process));
859 // Attempt to write the newer oom_score_adj file first.
860 FilePath oom_file = oom_path.AppendASCII("oom_score_adj");
861 if (file_util::PathExists(oom_file)) {
862 std::string score_str = IntToString(score);
863 DVLOG(1) << "Adjusting oom_score_adj of " << process << " to "
864 << score_str;
865 int score_len = static_cast<int>(score_str.length());
866 return (score_len == file_util::WriteFile(oom_file,
867 score_str.c_str(),
868 score_len));
871 // If the oom_score_adj file doesn't exist, then we write the old
872 // style file and translate the oom_adj score to the range 0-15.
873 oom_file = oom_path.AppendASCII("oom_adj");
874 if (file_util::PathExists(oom_file)) {
875 // Max score for the old oom_adj range. Used for conversion of new
876 // values to old values.
877 const int kMaxOldOomScore = 15;
879 int converted_score = score * kMaxOldOomScore / kMaxOomScore;
880 std::string score_str = IntToString(converted_score);
881 DVLOG(1) << "Adjusting oom_adj of " << process << " to " << score_str;
882 int score_len = static_cast<int>(score_str.length());
883 return (score_len == file_util::WriteFile(oom_file,
884 score_str.c_str(),
885 score_len));
888 return false;
891 } // namespace base