• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "base/process/internal_linux.h"
6 
7 #include <limits.h>
8 #include <unistd.h>
9 
10 #include <map>
11 #include <string>
12 #include <vector>
13 
14 #include "base/files/file_util.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/threading/thread_restrictions.h"
20 #include "base/time/time.h"
21 
22 // Not defined on AIX by default.
23 #if defined(OS_AIX)
24 #define NAME_MAX 255
25 #endif
26 
27 namespace base {
28 namespace internal {
29 
30 const char kProcDir[] = "/proc";
31 
32 const char kStatFile[] = "stat";
33 
GetProcPidDir(pid_t pid)34 FilePath GetProcPidDir(pid_t pid) {
35   return FilePath(kProcDir).Append(IntToString(pid));
36 }
37 
ProcDirSlotToPid(const char * d_name)38 pid_t ProcDirSlotToPid(const char* d_name) {
39   int i;
40   for (i = 0; i < NAME_MAX && d_name[i]; ++i) {
41     if (!IsAsciiDigit(d_name[i])) {
42       return 0;
43     }
44   }
45   if (i == NAME_MAX)
46     return 0;
47 
48   // Read the process's command line.
49   pid_t pid;
50   std::string pid_string(d_name);
51   if (!StringToInt(pid_string, &pid)) {
52     NOTREACHED();
53     return 0;
54   }
55   return pid;
56 }
57 
ReadProcFile(const FilePath & file,std::string * buffer)58 bool ReadProcFile(const FilePath& file, std::string* buffer) {
59   buffer->clear();
60   // Synchronously reading files in /proc is safe.
61   ThreadRestrictions::ScopedAllowIO allow_io;
62 
63   if (!ReadFileToString(file, buffer)) {
64     DLOG(WARNING) << "Failed to read " << file.MaybeAsASCII();
65     return false;
66   }
67   return !buffer->empty();
68 }
69 
ReadProcStats(pid_t pid,std::string * buffer)70 bool ReadProcStats(pid_t pid, std::string* buffer) {
71   FilePath stat_file = internal::GetProcPidDir(pid).Append(kStatFile);
72   return ReadProcFile(stat_file, buffer);
73 }
74 
ParseProcStats(const std::string & stats_data,std::vector<std::string> * proc_stats)75 bool ParseProcStats(const std::string& stats_data,
76                     std::vector<std::string>* proc_stats) {
77   // |stats_data| may be empty if the process disappeared somehow.
78   // e.g. http://crbug.com/145811
79   if (stats_data.empty())
80     return false;
81 
82   // The stat file is formatted as:
83   // pid (process name) data1 data2 .... dataN
84   // Look for the closing paren by scanning backwards, to avoid being fooled by
85   // processes with ')' in the name.
86   size_t open_parens_idx = stats_data.find(" (");
87   size_t close_parens_idx = stats_data.rfind(") ");
88   if (open_parens_idx == std::string::npos ||
89       close_parens_idx == std::string::npos ||
90       open_parens_idx > close_parens_idx) {
91     DLOG(WARNING) << "Failed to find matched parens in '" << stats_data << "'";
92     NOTREACHED();
93     return false;
94   }
95   open_parens_idx++;
96 
97   proc_stats->clear();
98   // PID.
99   proc_stats->push_back(stats_data.substr(0, open_parens_idx));
100   // Process name without parentheses.
101   proc_stats->push_back(
102       stats_data.substr(open_parens_idx + 1,
103                         close_parens_idx - (open_parens_idx + 1)));
104 
105   // Split the rest.
106   std::vector<std::string> other_stats = SplitString(
107       stats_data.substr(close_parens_idx + 2), " ",
108       base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
109   for (size_t i = 0; i < other_stats.size(); ++i)
110     proc_stats->push_back(other_stats[i]);
111   return true;
112 }
113 
114 typedef std::map<std::string, std::string> ProcStatMap;
ParseProcStat(const std::string & contents,ProcStatMap * output)115 void ParseProcStat(const std::string& contents, ProcStatMap* output) {
116   StringPairs key_value_pairs;
117   SplitStringIntoKeyValuePairs(contents, ' ', '\n', &key_value_pairs);
118   for (size_t i = 0; i < key_value_pairs.size(); ++i) {
119     output->insert(key_value_pairs[i]);
120   }
121 }
122 
GetProcStatsFieldAsInt64(const std::vector<std::string> & proc_stats,ProcStatsFields field_num)123 int64_t GetProcStatsFieldAsInt64(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());
127 
128   int64_t value;
129   return StringToInt64(proc_stats[field_num], &value) ? value : 0;
130 }
131 
GetProcStatsFieldAsSizeT(const std::vector<std::string> & proc_stats,ProcStatsFields field_num)132 size_t GetProcStatsFieldAsSizeT(const std::vector<std::string>& proc_stats,
133                                 ProcStatsFields field_num) {
134   DCHECK_GE(field_num, VM_PPID);
135   CHECK_LT(static_cast<size_t>(field_num), proc_stats.size());
136 
137   size_t value;
138   return StringToSizeT(proc_stats[field_num], &value) ? value : 0;
139 }
140 
ReadStatFileAndGetFieldAsInt64(const FilePath & stat_file,ProcStatsFields field_num)141 int64_t ReadStatFileAndGetFieldAsInt64(const FilePath& stat_file,
142                                        ProcStatsFields field_num) {
143   std::string stats_data;
144   if (!ReadProcFile(stat_file, &stats_data))
145     return 0;
146   std::vector<std::string> proc_stats;
147   if (!ParseProcStats(stats_data, &proc_stats))
148     return 0;
149   return GetProcStatsFieldAsInt64(proc_stats, field_num);
150 }
151 
ReadProcStatsAndGetFieldAsInt64(pid_t pid,ProcStatsFields field_num)152 int64_t ReadProcStatsAndGetFieldAsInt64(pid_t pid, ProcStatsFields field_num) {
153   FilePath stat_file = internal::GetProcPidDir(pid).Append(kStatFile);
154   return ReadStatFileAndGetFieldAsInt64(stat_file, field_num);
155 }
156 
ReadProcSelfStatsAndGetFieldAsInt64(ProcStatsFields field_num)157 int64_t ReadProcSelfStatsAndGetFieldAsInt64(ProcStatsFields field_num) {
158   FilePath stat_file = FilePath(kProcDir).Append("self").Append(kStatFile);
159   return ReadStatFileAndGetFieldAsInt64(stat_file, field_num);
160 }
161 
ReadProcStatsAndGetFieldAsSizeT(pid_t pid,ProcStatsFields field_num)162 size_t ReadProcStatsAndGetFieldAsSizeT(pid_t pid,
163                                        ProcStatsFields field_num) {
164   std::string stats_data;
165   if (!ReadProcStats(pid, &stats_data))
166     return 0;
167   std::vector<std::string> proc_stats;
168   if (!ParseProcStats(stats_data, &proc_stats))
169     return 0;
170   return GetProcStatsFieldAsSizeT(proc_stats, field_num);
171 }
172 
GetBootTime()173 Time GetBootTime() {
174   FilePath path("/proc/stat");
175   std::string contents;
176   if (!ReadProcFile(path, &contents))
177     return Time();
178   ProcStatMap proc_stat;
179   ParseProcStat(contents, &proc_stat);
180   ProcStatMap::const_iterator btime_it = proc_stat.find("btime");
181   if (btime_it == proc_stat.end())
182     return Time();
183   int btime;
184   if (!StringToInt(btime_it->second, &btime))
185     return Time();
186   return Time::FromTimeT(btime);
187 }
188 
GetUserCpuTimeSinceBoot()189 TimeDelta GetUserCpuTimeSinceBoot() {
190   FilePath path("/proc/stat");
191   std::string contents;
192   if (!ReadProcFile(path, &contents))
193     return TimeDelta();
194 
195   ProcStatMap proc_stat;
196   ParseProcStat(contents, &proc_stat);
197   ProcStatMap::const_iterator cpu_it = proc_stat.find("cpu");
198   if (cpu_it == proc_stat.end())
199     return TimeDelta();
200 
201   std::vector<std::string> cpu = SplitString(
202       cpu_it->second, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
203 
204   if (cpu.size() < 2 || cpu[0] != "cpu")
205     return TimeDelta();
206 
207   uint64_t user;
208   uint64_t nice;
209   if (!StringToUint64(cpu[0], &user) || !StringToUint64(cpu[1], &nice))
210     return TimeDelta();
211 
212   return ClockTicksToTimeDelta(user + nice);
213 }
214 
ClockTicksToTimeDelta(int clock_ticks)215 TimeDelta ClockTicksToTimeDelta(int clock_ticks) {
216   // This queries the /proc-specific scaling factor which is
217   // conceptually the system hertz.  To dump this value on another
218   // system, try
219   //   od -t dL /proc/self/auxv
220   // and look for the number after 17 in the output; mine is
221   //   0000040          17         100           3   134512692
222   // which means the answer is 100.
223   // It may be the case that this value is always 100.
224   static const int kHertz = sysconf(_SC_CLK_TCK);
225 
226   return TimeDelta::FromMicroseconds(
227       Time::kMicrosecondsPerSecond * clock_ticks / kHertz);
228 }
229 
230 }  // namespace internal
231 }  // namespace base
232