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