Encode method and error message inside LevelDB::Status message
[chromium-blink-merge.git] / base / process_util_linux.cc
blob2c2824fd77db68da521883918bc88b580e99caa2
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());
394 entry_.exe_file_ = GetProcessExecutablePath(pid).BaseName().value();
395 return true;
398 bool NamedProcessIterator::IncludeEntry() {
399 if (executable_name_ != entry().exe_file())
400 return false;
401 return ProcessIterator::IncludeEntry();
405 // static
406 ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
407 return new ProcessMetrics(process);
410 // On linux, we return vsize.
411 size_t ProcessMetrics::GetPagefileUsage() const {
412 return ReadProcStatsAndGetFieldAsSizeT(process_, VM_VSIZE);
415 // On linux, we return the high water mark of vsize.
416 size_t ProcessMetrics::GetPeakPagefileUsage() const {
417 return ReadProcStatusAndGetFieldAsSizeT(process_, "VmPeak") * 1024;
420 // On linux, we return RSS.
421 size_t ProcessMetrics::GetWorkingSetSize() const {
422 return ReadProcStatsAndGetFieldAsSizeT(process_, VM_RSS) * getpagesize();
425 // On linux, we return the high water mark of RSS.
426 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
427 return ReadProcStatusAndGetFieldAsSizeT(process_, "VmHWM") * 1024;
430 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
431 size_t* shared_bytes) {
432 WorkingSetKBytes ws_usage;
433 if (!GetWorkingSetKBytes(&ws_usage))
434 return false;
436 if (private_bytes)
437 *private_bytes = ws_usage.priv * 1024;
439 if (shared_bytes)
440 *shared_bytes = ws_usage.shared * 1024;
442 return true;
445 // Private and Shared working set sizes are obtained from /proc/<pid>/statm.
446 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
447 // Use statm instead of smaps because smaps is:
448 // a) Large and slow to parse.
449 // b) Unavailable in the SUID sandbox.
451 // First we need to get the page size, since everything is measured in pages.
452 // For details, see: man 5 proc.
453 const int page_size_kb = getpagesize() / 1024;
454 if (page_size_kb <= 0)
455 return false;
457 std::string statm;
459 FilePath statm_file = GetProcPidDir(process_).Append("statm");
460 // Synchronously reading files in /proc is safe.
461 ThreadRestrictions::ScopedAllowIO allow_io;
462 bool ret = file_util::ReadFileToString(statm_file, &statm);
463 if (!ret || statm.length() == 0)
464 return false;
467 std::vector<std::string> statm_vec;
468 SplitString(statm, ' ', &statm_vec);
469 if (statm_vec.size() != 7)
470 return false; // Not the format we expect.
472 int statm_rss, statm_shared;
473 StringToInt(statm_vec[1], &statm_rss);
474 StringToInt(statm_vec[2], &statm_shared);
476 ws_usage->priv = (statm_rss - statm_shared) * page_size_kb;
477 ws_usage->shared = statm_shared * page_size_kb;
479 // Sharable is not calculated, as it does not provide interesting data.
480 ws_usage->shareable = 0;
482 return true;
485 double ProcessMetrics::GetCPUUsage() {
486 // This queries the /proc-specific scaling factor which is
487 // conceptually the system hertz. To dump this value on another
488 // system, try
489 // od -t dL /proc/self/auxv
490 // and look for the number after 17 in the output; mine is
491 // 0000040 17 100 3 134512692
492 // which means the answer is 100.
493 // It may be the case that this value is always 100.
494 static const int kHertz = sysconf(_SC_CLK_TCK);
496 struct timeval now;
497 int retval = gettimeofday(&now, NULL);
498 if (retval)
499 return 0;
500 int64 time = TimeValToMicroseconds(now);
502 if (last_time_ == 0) {
503 // First call, just set the last values.
504 last_time_ = time;
505 last_cpu_ = GetProcessCPU(process_);
506 return 0;
509 int64 time_delta = time - last_time_;
510 DCHECK_NE(time_delta, 0);
511 if (time_delta == 0)
512 return 0;
514 int cpu = GetProcessCPU(process_);
516 // We have the number of jiffies in the time period. Convert to percentage.
517 // Note this means we will go *over* 100 in the case where multiple threads
518 // are together adding to more than one CPU's worth.
519 int percentage = 100 * (cpu - last_cpu_) /
520 (kHertz * TimeDelta::FromMicroseconds(time_delta).InSecondsF());
522 last_time_ = time;
523 last_cpu_ = cpu;
525 return percentage;
528 // To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
529 // in your kernel configuration.
530 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
531 // Synchronously reading files in /proc is safe.
532 ThreadRestrictions::ScopedAllowIO allow_io;
534 std::string proc_io_contents;
535 FilePath io_file = GetProcPidDir(process_).Append("io");
536 if (!file_util::ReadFileToString(io_file, &proc_io_contents))
537 return false;
539 (*io_counters).OtherOperationCount = 0;
540 (*io_counters).OtherTransferCount = 0;
542 StringTokenizer tokenizer(proc_io_contents, ": \n");
543 ParsingState state = KEY_NAME;
544 StringPiece last_key_name;
545 while (tokenizer.GetNext()) {
546 switch (state) {
547 case KEY_NAME:
548 last_key_name = tokenizer.token_piece();
549 state = KEY_VALUE;
550 break;
551 case KEY_VALUE:
552 DCHECK(!last_key_name.empty());
553 if (last_key_name == "syscr") {
554 StringToInt64(tokenizer.token_piece(),
555 reinterpret_cast<int64*>(&(*io_counters).ReadOperationCount));
556 } else if (last_key_name == "syscw") {
557 StringToInt64(tokenizer.token_piece(),
558 reinterpret_cast<int64*>(&(*io_counters).WriteOperationCount));
559 } else if (last_key_name == "rchar") {
560 StringToInt64(tokenizer.token_piece(),
561 reinterpret_cast<int64*>(&(*io_counters).ReadTransferCount));
562 } else if (last_key_name == "wchar") {
563 StringToInt64(tokenizer.token_piece(),
564 reinterpret_cast<int64*>(&(*io_counters).WriteTransferCount));
566 state = KEY_NAME;
567 break;
570 return true;
573 ProcessMetrics::ProcessMetrics(ProcessHandle process)
574 : process_(process),
575 last_time_(0),
576 last_system_time_(0),
577 last_cpu_(0) {
578 processor_count_ = SysInfo::NumberOfProcessors();
582 // Exposed for testing.
583 int ParseProcStatCPU(const std::string& input) {
584 std::vector<std::string> proc_stats;
585 if (!ParseProcStats(input, &proc_stats))
586 return -1;
588 if (proc_stats.size() <= VM_STIME)
589 return -1;
590 int utime = GetProcStatsFieldAsInt(proc_stats, VM_UTIME);
591 int stime = GetProcStatsFieldAsInt(proc_stats, VM_STIME);
592 return utime + stime;
595 int GetNumberOfThreads(ProcessHandle process) {
596 return ReadProcStatsAndGetFieldAsInt(process, VM_NUMTHREADS);
599 namespace {
601 // The format of /proc/meminfo is:
603 // MemTotal: 8235324 kB
604 // MemFree: 1628304 kB
605 // Buffers: 429596 kB
606 // Cached: 4728232 kB
607 // ...
608 const size_t kMemTotalIndex = 1;
609 const size_t kMemFreeIndex = 4;
610 const size_t kMemBuffersIndex = 7;
611 const size_t kMemCachedIndex = 10;
612 const size_t kMemActiveAnonIndex = 22;
613 const size_t kMemInactiveAnonIndex = 25;
614 const size_t kMemActiveFileIndex = 28;
615 const size_t kMemInactiveFileIndex = 31;
617 } // namespace
619 SystemMemoryInfoKB::SystemMemoryInfoKB()
620 : total(0),
621 free(0),
622 buffers(0),
623 cached(0),
624 active_anon(0),
625 inactive_anon(0),
626 active_file(0),
627 inactive_file(0),
628 shmem(0),
629 gem_objects(-1),
630 gem_size(-1) {
633 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
634 // Synchronously reading files in /proc is safe.
635 ThreadRestrictions::ScopedAllowIO allow_io;
637 // Used memory is: total - free - buffers - caches
638 FilePath meminfo_file("/proc/meminfo");
639 std::string meminfo_data;
640 if (!file_util::ReadFileToString(meminfo_file, &meminfo_data)) {
641 DLOG(WARNING) << "Failed to open " << meminfo_file.value();
642 return false;
644 std::vector<std::string> meminfo_fields;
645 SplitStringAlongWhitespace(meminfo_data, &meminfo_fields);
647 if (meminfo_fields.size() < kMemCachedIndex) {
648 DLOG(WARNING) << "Failed to parse " << meminfo_file.value()
649 << ". Only found " << meminfo_fields.size() << " fields.";
650 return false;
653 DCHECK_EQ(meminfo_fields[kMemTotalIndex-1], "MemTotal:");
654 DCHECK_EQ(meminfo_fields[kMemFreeIndex-1], "MemFree:");
655 DCHECK_EQ(meminfo_fields[kMemBuffersIndex-1], "Buffers:");
656 DCHECK_EQ(meminfo_fields[kMemCachedIndex-1], "Cached:");
657 DCHECK_EQ(meminfo_fields[kMemActiveAnonIndex-1], "Active(anon):");
658 DCHECK_EQ(meminfo_fields[kMemInactiveAnonIndex-1], "Inactive(anon):");
659 DCHECK_EQ(meminfo_fields[kMemActiveFileIndex-1], "Active(file):");
660 DCHECK_EQ(meminfo_fields[kMemInactiveFileIndex-1], "Inactive(file):");
662 StringToInt(meminfo_fields[kMemTotalIndex], &meminfo->total);
663 StringToInt(meminfo_fields[kMemFreeIndex], &meminfo->free);
664 StringToInt(meminfo_fields[kMemBuffersIndex], &meminfo->buffers);
665 StringToInt(meminfo_fields[kMemCachedIndex], &meminfo->cached);
666 StringToInt(meminfo_fields[kMemActiveAnonIndex], &meminfo->active_anon);
667 StringToInt(meminfo_fields[kMemInactiveAnonIndex],
668 &meminfo->inactive_anon);
669 StringToInt(meminfo_fields[kMemActiveFileIndex], &meminfo->active_file);
670 StringToInt(meminfo_fields[kMemInactiveFileIndex],
671 &meminfo->inactive_file);
672 #if defined(OS_CHROMEOS)
673 // Chrome OS has a tweaked kernel that allows us to query Shmem, which is
674 // usually video memory otherwise invisible to the OS. Unfortunately, the
675 // meminfo format varies on different hardware so we have to search for the
676 // string. It always appears after "Cached:".
677 for (size_t i = kMemCachedIndex+2; i < meminfo_fields.size(); i += 3) {
678 if (meminfo_fields[i] == "Shmem:") {
679 StringToInt(meminfo_fields[i+1], &meminfo->shmem);
680 break;
684 // Report on Chrome OS GEM object graphics memory. /var/run/debugfs_gpu is a
685 // bind mount into /sys/kernel/debug and synchronously reading the in-memory
686 // files in /sys is fast.
687 #if defined(ARCH_CPU_ARM_FAMILY)
688 FilePath geminfo_file("/var/run/debugfs_gpu/exynos_gem_objects");
689 #else
690 FilePath geminfo_file("/var/run/debugfs_gpu/i915_gem_objects");
691 #endif
692 std::string geminfo_data;
693 meminfo->gem_objects = -1;
694 meminfo->gem_size = -1;
695 if (file_util::ReadFileToString(geminfo_file, &geminfo_data)) {
696 int gem_objects = -1;
697 long long gem_size = -1;
698 int num_res = sscanf(geminfo_data.c_str(),
699 "%d objects, %lld bytes",
700 &gem_objects, &gem_size);
701 if (num_res == 2) {
702 meminfo->gem_objects = gem_objects;
703 meminfo->gem_size = gem_size;
707 #if defined(ARCH_CPU_ARM_FAMILY)
708 // Incorporate Mali graphics memory if present.
709 FilePath mali_memory_file("/sys/devices/platform/mali.0/memory");
710 std::string mali_memory_data;
711 if (file_util::ReadFileToString(mali_memory_file, &mali_memory_data)) {
712 long long mali_size = -1;
713 int num_res = sscanf(mali_memory_data.c_str(), "%lld bytes", &mali_size);
714 if (num_res == 1)
715 meminfo->gem_size += mali_size;
717 #endif // defined(ARCH_CPU_ARM_FAMILY)
718 #endif // defined(OS_CHROMEOS)
720 return true;
723 size_t GetSystemCommitCharge() {
724 SystemMemoryInfoKB meminfo;
725 if (!GetSystemMemoryInfo(&meminfo))
726 return 0;
727 return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
730 namespace {
732 void OnNoMemorySize(size_t size) {
733 #if defined(USE_LINUX_BREAKPAD)
734 g_oom_size = size;
735 #endif
737 if (size != 0)
738 LOG(FATAL) << "Out of memory, size = " << size;
739 LOG(FATAL) << "Out of memory.";
742 void OnNoMemory() {
743 OnNoMemorySize(0);
746 } // namespace
748 #if !defined(OS_ANDROID) && !defined(USE_TCMALLOC) && \
749 !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
750 !defined(THREAD_SANITIZER)
752 extern "C" {
753 void* __libc_malloc(size_t size);
754 void* __libc_realloc(void* ptr, size_t size);
755 void* __libc_calloc(size_t nmemb, size_t size);
756 void* __libc_valloc(size_t size);
757 void* __libc_pvalloc(size_t size);
758 void* __libc_memalign(size_t alignment, size_t size);
760 // Overriding the system memory allocation functions:
762 // For security reasons, we want malloc failures to be fatal. Too much code
763 // doesn't check for a NULL return value from malloc and unconditionally uses
764 // the resulting pointer. If the first offset that they try to access is
765 // attacker controlled, then the attacker can direct the code to access any
766 // part of memory.
768 // Thus, we define all the standard malloc functions here and mark them as
769 // visibility 'default'. This means that they replace the malloc functions for
770 // all Chromium code and also for all code in shared libraries. There are tests
771 // for this in process_util_unittest.cc.
773 // If we are using tcmalloc, then the problem is moot since tcmalloc handles
774 // this for us. Thus this code is in a !defined(USE_TCMALLOC) block.
776 // If we are testing the binary with AddressSanitizer, we should not
777 // redefine malloc and let AddressSanitizer do it instead.
779 // We call the real libc functions in this code by using __libc_malloc etc.
780 // Previously we tried using dlsym(RTLD_NEXT, ...) but that failed depending on
781 // the link order. Since ld.so needs calloc during symbol resolution, it
782 // defines its own versions of several of these functions in dl-minimal.c.
783 // Depending on the runtime library order, dlsym ended up giving us those
784 // functions and bad things happened. See crbug.com/31809
786 // This means that any code which calls __libc_* gets the raw libc versions of
787 // these functions.
789 #define DIE_ON_OOM_1(function_name) \
790 void* function_name(size_t) __attribute__ ((visibility("default"))); \
792 void* function_name(size_t size) { \
793 void* ret = __libc_##function_name(size); \
794 if (ret == NULL && size != 0) \
795 OnNoMemorySize(size); \
796 return ret; \
799 #define DIE_ON_OOM_2(function_name, arg1_type) \
800 void* function_name(arg1_type, size_t) \
801 __attribute__ ((visibility("default"))); \
803 void* function_name(arg1_type arg1, size_t size) { \
804 void* ret = __libc_##function_name(arg1, size); \
805 if (ret == NULL && size != 0) \
806 OnNoMemorySize(size); \
807 return ret; \
810 DIE_ON_OOM_1(malloc)
811 DIE_ON_OOM_1(valloc)
812 DIE_ON_OOM_1(pvalloc)
814 DIE_ON_OOM_2(calloc, size_t)
815 DIE_ON_OOM_2(realloc, void*)
816 DIE_ON_OOM_2(memalign, size_t)
818 // posix_memalign has a unique signature and doesn't have a __libc_ variant.
819 int posix_memalign(void** ptr, size_t alignment, size_t size)
820 __attribute__ ((visibility("default")));
822 int posix_memalign(void** ptr, size_t alignment, size_t size) {
823 // This will use the safe version of memalign, above.
824 *ptr = memalign(alignment, size);
825 return 0;
828 } // extern C
829 #endif // ANDROID, TCMALLOC, *_SANITIZER
831 void EnableTerminationOnHeapCorruption() {
832 // On Linux, there nothing to do AFAIK.
835 void EnableTerminationOnOutOfMemory() {
836 #if defined(OS_ANDROID)
837 // Android doesn't support setting a new handler.
838 DLOG(WARNING) << "Not feasible.";
839 #else
840 // Set the new-out of memory handler.
841 std::set_new_handler(&OnNoMemory);
842 // If we're using glibc's allocator, the above functions will override
843 // malloc and friends and make them die on out of memory.
844 #endif
847 // NOTE: This is not the only version of this function in the source:
848 // the setuid sandbox (in process_util_linux.c, in the sandbox source)
849 // also has its own C version.
850 bool AdjustOOMScore(ProcessId process, int score) {
851 if (score < 0 || score > kMaxOomScore)
852 return false;
854 FilePath oom_path(GetProcPidDir(process));
856 // Attempt to write the newer oom_score_adj file first.
857 FilePath oom_file = oom_path.AppendASCII("oom_score_adj");
858 if (file_util::PathExists(oom_file)) {
859 std::string score_str = IntToString(score);
860 DVLOG(1) << "Adjusting oom_score_adj of " << process << " to "
861 << score_str;
862 int score_len = static_cast<int>(score_str.length());
863 return (score_len == file_util::WriteFile(oom_file,
864 score_str.c_str(),
865 score_len));
868 // If the oom_score_adj file doesn't exist, then we write the old
869 // style file and translate the oom_adj score to the range 0-15.
870 oom_file = oom_path.AppendASCII("oom_adj");
871 if (file_util::PathExists(oom_file)) {
872 // Max score for the old oom_adj range. Used for conversion of new
873 // values to old values.
874 const int kMaxOldOomScore = 15;
876 int converted_score = score * kMaxOldOomScore / kMaxOomScore;
877 std::string score_str = IntToString(converted_score);
878 DVLOG(1) << "Adjusting oom_adj of " << process << " to " << score_str;
879 int score_len = static_cast<int>(score_str.length());
880 return (score_len == file_util::WriteFile(oom_file,
881 score_str.c_str(),
882 score_len));
885 return false;
888 } // namespace base