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