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