• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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/notreached.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_split.h"
19 #include "base/strings/string_util.h"
20 #include "base/threading/thread_restrictions.h"
21 #include "base/time/time.h"
22 #include "build/build_config.h"
23 
24 // Not defined on AIX by default.
25 #if BUILDFLAG(IS_AIX)
26 #define NAME_MAX 255
27 #endif
28 
29 namespace base {
30 namespace internal {
31 
32 namespace {
33 
TrimKeyValuePairs(StringPairs * pairs)34 void TrimKeyValuePairs(StringPairs* pairs) {
35   for (auto& pair : *pairs) {
36     TrimWhitespaceASCII(pair.first, TRIM_ALL, &pair.first);
37     TrimWhitespaceASCII(pair.second, TRIM_ALL, &pair.second);
38   }
39 }
40 
41 }  // namespace
42 
43 const char kProcDir[] = "/proc";
44 
45 const char kStatFile[] = "stat";
46 
GetProcPidDir(pid_t pid)47 FilePath GetProcPidDir(pid_t pid) {
48   return FilePath(kProcDir).Append(NumberToString(pid));
49 }
50 
ProcDirSlotToPid(const char * d_name)51 pid_t ProcDirSlotToPid(const char* d_name) {
52   int i;
53   for (i = 0; i < NAME_MAX && d_name[i]; ++i) {
54     if (!IsAsciiDigit(d_name[i])) {
55       return 0;
56     }
57   }
58   if (i == NAME_MAX)
59     return 0;
60 
61   // Read the process's command line.
62   pid_t pid;
63   std::string pid_string(d_name);
64   if (!StringToInt(pid_string, &pid)) {
65     NOTREACHED();
66     return 0;
67   }
68   return pid;
69 }
70 
ReadProcFile(const FilePath & file,std::string * buffer)71 bool ReadProcFile(const FilePath& file, std::string* buffer) {
72   DCHECK(FilePath(kProcDir).IsParent(file));
73   buffer->clear();
74   // Synchronously reading files in /proc is safe.
75   ScopedAllowBlocking scoped_allow_blocking;
76 
77   if (!ReadFileToString(file, buffer)) {
78     DLOG(WARNING) << "Failed to read " << file.MaybeAsASCII();
79     return false;
80   }
81   return !buffer->empty();
82 }
83 
ReadProcFileToTrimmedStringPairs(pid_t pid,StringPiece filename,StringPairs * key_value_pairs)84 bool ReadProcFileToTrimmedStringPairs(pid_t pid,
85                                       StringPiece filename,
86                                       StringPairs* key_value_pairs) {
87   std::string status_data;
88   FilePath status_file = GetProcPidDir(pid).Append(filename);
89   if (!ReadProcFile(status_file, &status_data)) {
90     return false;
91   }
92   SplitStringIntoKeyValuePairs(status_data, ':', '\n', key_value_pairs);
93   TrimKeyValuePairs(key_value_pairs);
94   return true;
95 }
96 
ReadProcStatusAndGetKbFieldAsSizeT(pid_t pid,StringPiece field)97 size_t ReadProcStatusAndGetKbFieldAsSizeT(pid_t pid, StringPiece field) {
98   StringPairs pairs;
99   if (!ReadProcFileToTrimmedStringPairs(pid, "status", &pairs)) {
100     return 0;
101   }
102 
103   for (const auto& pair : pairs) {
104     const std::string& key = pair.first;
105     const std::string& value_str = pair.second;
106     if (key != field) {
107       continue;
108     }
109 
110     std::vector<StringPiece> split_value_str =
111         SplitStringPiece(value_str, " ", TRIM_WHITESPACE, SPLIT_WANT_ALL);
112     if (split_value_str.size() != 2 || split_value_str[1] != "kB") {
113       NOTREACHED();
114       return 0;
115     }
116     size_t value;
117     if (!StringToSizeT(split_value_str[0], &value)) {
118       NOTREACHED();
119       return 0;
120     }
121     return value;
122   }
123   // This can be reached if the process dies when proc is read -- in that case,
124   // the kernel can return missing fields.
125   return 0;
126 }
127 
ReadProcStatusAndGetFieldAsUint64(pid_t pid,StringPiece field,uint64_t * result)128 bool ReadProcStatusAndGetFieldAsUint64(pid_t pid,
129                                        StringPiece field,
130                                        uint64_t* result) {
131   StringPairs pairs;
132   if (!ReadProcFileToTrimmedStringPairs(pid, "status", &pairs)) {
133     return false;
134   }
135 
136   for (const auto& pair : pairs) {
137     const std::string& key = pair.first;
138     const std::string& value_str = pair.second;
139     if (key != field) {
140       continue;
141     }
142 
143     uint64_t value;
144     if (!StringToUint64(value_str, &value)) {
145       return false;
146     }
147     *result = value;
148     return true;
149   }
150   return false;
151 }
152 
ReadProcStats(pid_t pid,std::string * buffer)153 bool ReadProcStats(pid_t pid, std::string* buffer) {
154   FilePath stat_file = internal::GetProcPidDir(pid).Append(kStatFile);
155   return ReadProcFile(stat_file, buffer);
156 }
157 
ParseProcStats(const std::string & stats_data,std::vector<std::string> * proc_stats)158 bool ParseProcStats(const std::string& stats_data,
159                     std::vector<std::string>* proc_stats) {
160   // |stats_data| may be empty if the process disappeared somehow.
161   // e.g. http://crbug.com/145811
162   if (stats_data.empty())
163     return false;
164 
165   // The stat file is formatted as:
166   // pid (process name) data1 data2 .... dataN
167   // Look for the closing paren by scanning backwards, to avoid being fooled by
168   // processes with ')' in the name.
169   size_t open_parens_idx = stats_data.find(" (");
170   size_t close_parens_idx = stats_data.rfind(") ");
171   if (open_parens_idx == std::string::npos ||
172       close_parens_idx == std::string::npos ||
173       open_parens_idx > close_parens_idx) {
174     DLOG(WARNING) << "Failed to find matched parens in '" << stats_data << "'";
175     NOTREACHED();
176     return false;
177   }
178   open_parens_idx++;
179 
180   proc_stats->clear();
181   // PID.
182   proc_stats->push_back(stats_data.substr(0, open_parens_idx));
183   // Process name without parentheses.
184   proc_stats->push_back(
185       stats_data.substr(open_parens_idx + 1,
186                         close_parens_idx - (open_parens_idx + 1)));
187 
188   // Split the rest.
189   std::vector<std::string> other_stats = SplitString(
190       stats_data.substr(close_parens_idx + 2), " ",
191       base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
192   for (const auto& i : other_stats)
193     proc_stats->push_back(i);
194   return true;
195 }
196 
197 typedef std::map<std::string, std::string> ProcStatMap;
ParseProcStat(const std::string & contents,ProcStatMap * output)198 void ParseProcStat(const std::string& contents, ProcStatMap* output) {
199   StringPairs key_value_pairs;
200   SplitStringIntoKeyValuePairs(contents, ' ', '\n', &key_value_pairs);
201   for (auto& i : key_value_pairs) {
202     output->insert(std::move(i));
203   }
204 }
205 
GetProcStatsFieldAsInt64(const std::vector<std::string> & proc_stats,ProcStatsFields field_num)206 int64_t GetProcStatsFieldAsInt64(const std::vector<std::string>& proc_stats,
207                                  ProcStatsFields field_num) {
208   DCHECK_GE(field_num, VM_PPID);
209   CHECK_LT(static_cast<size_t>(field_num), proc_stats.size());
210 
211   int64_t value;
212   return StringToInt64(proc_stats[field_num], &value) ? value : 0;
213 }
214 
GetProcStatsFieldAsSizeT(const std::vector<std::string> & proc_stats,ProcStatsFields field_num)215 size_t GetProcStatsFieldAsSizeT(const std::vector<std::string>& proc_stats,
216                                 ProcStatsFields field_num) {
217   DCHECK_GE(field_num, VM_PPID);
218   CHECK_LT(static_cast<size_t>(field_num), proc_stats.size());
219 
220   size_t value;
221   return StringToSizeT(proc_stats[field_num], &value) ? value : 0;
222 }
223 
ReadStatFileAndGetFieldAsInt64(const FilePath & stat_file,ProcStatsFields field_num)224 int64_t ReadStatFileAndGetFieldAsInt64(const FilePath& stat_file,
225                                        ProcStatsFields field_num) {
226   std::string stats_data;
227   if (!ReadProcFile(stat_file, &stats_data))
228     return 0;
229   std::vector<std::string> proc_stats;
230   if (!ParseProcStats(stats_data, &proc_stats))
231     return 0;
232   return GetProcStatsFieldAsInt64(proc_stats, field_num);
233 }
234 
ReadProcStatsAndGetFieldAsInt64(pid_t pid,ProcStatsFields field_num)235 int64_t ReadProcStatsAndGetFieldAsInt64(pid_t pid, ProcStatsFields field_num) {
236   FilePath stat_file = internal::GetProcPidDir(pid).Append(kStatFile);
237   return ReadStatFileAndGetFieldAsInt64(stat_file, field_num);
238 }
239 
ReadProcSelfStatsAndGetFieldAsInt64(ProcStatsFields field_num)240 int64_t ReadProcSelfStatsAndGetFieldAsInt64(ProcStatsFields field_num) {
241   FilePath stat_file = FilePath(kProcDir).Append("self").Append(kStatFile);
242   return ReadStatFileAndGetFieldAsInt64(stat_file, field_num);
243 }
244 
ReadProcStatsAndGetFieldAsSizeT(pid_t pid,ProcStatsFields field_num)245 size_t ReadProcStatsAndGetFieldAsSizeT(pid_t pid,
246                                        ProcStatsFields field_num) {
247   std::string stats_data;
248   if (!ReadProcStats(pid, &stats_data))
249     return 0;
250   std::vector<std::string> proc_stats;
251   if (!ParseProcStats(stats_data, &proc_stats))
252     return 0;
253   return GetProcStatsFieldAsSizeT(proc_stats, field_num);
254 }
255 
GetBootTime()256 Time GetBootTime() {
257   FilePath path("/proc/stat");
258   std::string contents;
259   if (!ReadProcFile(path, &contents))
260     return Time();
261   ProcStatMap proc_stat;
262   ParseProcStat(contents, &proc_stat);
263   ProcStatMap::const_iterator btime_it = proc_stat.find("btime");
264   if (btime_it == proc_stat.end())
265     return Time();
266   int btime;
267   if (!StringToInt(btime_it->second, &btime))
268     return Time();
269   return Time::FromTimeT(btime);
270 }
271 
GetUserCpuTimeSinceBoot()272 TimeDelta GetUserCpuTimeSinceBoot() {
273   FilePath path("/proc/stat");
274   std::string contents;
275   if (!ReadProcFile(path, &contents))
276     return TimeDelta();
277 
278   ProcStatMap proc_stat;
279   ParseProcStat(contents, &proc_stat);
280   ProcStatMap::const_iterator cpu_it = proc_stat.find("cpu");
281   if (cpu_it == proc_stat.end())
282     return TimeDelta();
283 
284   std::vector<std::string> cpu = SplitString(
285       cpu_it->second, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
286 
287   if (cpu.size() < 2 || cpu[0] != "cpu")
288     return TimeDelta();
289 
290   uint64_t user;
291   uint64_t nice;
292   if (!StringToUint64(cpu[0], &user) || !StringToUint64(cpu[1], &nice))
293     return TimeDelta();
294 
295   return ClockTicksToTimeDelta(checked_cast<int64_t>(user + nice));
296 }
297 
ClockTicksToTimeDelta(int64_t clock_ticks)298 TimeDelta ClockTicksToTimeDelta(int64_t clock_ticks) {
299   // This queries the /proc-specific scaling factor which is
300   // conceptually the system hertz.  To dump this value on another
301   // system, try
302   //   od -t dL /proc/self/auxv
303   // and look for the number after 17 in the output; mine is
304   //   0000040          17         100           3   134512692
305   // which means the answer is 100.
306   // It may be the case that this value is always 100.
307   static const long kHertz = sysconf(_SC_CLK_TCK);
308 
309   return Microseconds(Time::kMicrosecondsPerSecond * clock_ticks / kHertz);
310 }
311 
312 }  // namespace internal
313 }  // namespace base
314