OSDN Git Service

am f2392997: system/extra: include more of what you use.
[android-x86/system-extras.git] / simpleperf / environment.cpp
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "environment.h"
18
19 #include <inttypes.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <unordered_map>
23 #include <vector>
24
25 #include <base/file.h>
26 #include <base/logging.h>
27 #include <base/strings.h>
28 #include <base/stringprintf.h>
29
30 #include "utils.h"
31
32 std::vector<int> GetOnlineCpus() {
33   std::vector<int> result;
34   FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
35   if (fp == nullptr) {
36     PLOG(ERROR) << "can't open online cpu information";
37     return result;
38   }
39
40   LineReader reader(fp);
41   char* line;
42   if ((line = reader.ReadLine()) != nullptr) {
43     result = GetOnlineCpusFromString(line);
44   }
45   CHECK(!result.empty()) << "can't get online cpu information";
46   return result;
47 }
48
49 std::vector<int> GetOnlineCpusFromString(const std::string& s) {
50   std::vector<int> result;
51   bool have_dash = false;
52   const char* p = s.c_str();
53   char* endp;
54   long cpu;
55   // Parse line like: 0,1-3, 5, 7-8
56   while ((cpu = strtol(p, &endp, 10)) != 0 || endp != p) {
57     if (have_dash && result.size() > 0) {
58       for (int t = result.back() + 1; t < cpu; ++t) {
59         result.push_back(t);
60       }
61     }
62     have_dash = false;
63     result.push_back(cpu);
64     p = endp;
65     while (!isdigit(*p) && *p != '\0') {
66       if (*p == '-') {
67         have_dash = true;
68       }
69       ++p;
70     }
71   }
72   return result;
73 }
74
75 bool ProcessKernelSymbols(const std::string& symbol_file,
76                           std::function<bool(const KernelSymbol&)> callback) {
77   FILE* fp = fopen(symbol_file.c_str(), "re");
78   if (fp == nullptr) {
79     PLOG(ERROR) << "failed to open file " << symbol_file;
80     return false;
81   }
82   LineReader reader(fp);
83   char* line;
84   while ((line = reader.ReadLine()) != nullptr) {
85     // Parse line like: ffffffffa005c4e4 d __warned.41698       [libsas]
86     char name[reader.MaxLineSize()];
87     char module[reader.MaxLineSize()];
88     strcpy(module, "");
89
90     KernelSymbol symbol;
91     if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
92       continue;
93     }
94     symbol.name = name;
95     size_t module_len = strlen(module);
96     if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
97       module[module_len - 1] = '\0';
98       symbol.module = &module[1];
99     } else {
100       symbol.module = nullptr;
101     }
102
103     if (callback(symbol)) {
104       return true;
105     }
106   }
107   return false;
108 }
109
110 static bool FindStartOfKernelSymbolCallback(const KernelSymbol& symbol, uint64_t* start_addr) {
111   if (symbol.module == nullptr) {
112     *start_addr = symbol.addr;
113     return true;
114   }
115   return false;
116 }
117
118 static bool FindStartOfKernelSymbol(const std::string& symbol_file, uint64_t* start_addr) {
119   return ProcessKernelSymbols(
120       symbol_file, std::bind(&FindStartOfKernelSymbolCallback, std::placeholders::_1, start_addr));
121 }
122
123 static bool FindKernelFunctionSymbolCallback(const KernelSymbol& symbol, const std::string& name,
124                                              uint64_t* addr) {
125   if ((symbol.type == 'T' || symbol.type == 'W' || symbol.type == 'A') &&
126       symbol.module == nullptr && name == symbol.name) {
127     *addr = symbol.addr;
128     return true;
129   }
130   return false;
131 }
132
133 static bool FindKernelFunctionSymbol(const std::string& symbol_file, const std::string& name,
134                                      uint64_t* addr) {
135   return ProcessKernelSymbols(
136       symbol_file, std::bind(&FindKernelFunctionSymbolCallback, std::placeholders::_1, name, addr));
137 }
138
139 std::vector<ModuleMmap> GetLoadedModules() {
140   std::vector<ModuleMmap> result;
141   FILE* fp = fopen("/proc/modules", "re");
142   if (fp == nullptr) {
143     // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
144     PLOG(DEBUG) << "failed to open file /proc/modules";
145     return result;
146   }
147   LineReader reader(fp);
148   char* line;
149   while ((line = reader.ReadLine()) != nullptr) {
150     // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
151     char name[reader.MaxLineSize()];
152     uint64_t addr;
153     if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
154       ModuleMmap map;
155       map.name = name;
156       map.start_addr = addr;
157       result.push_back(map);
158     }
159   }
160   return result;
161 }
162
163 static std::string GetLinuxVersion() {
164   std::string content;
165   if (android::base::ReadFileToString("/proc/version", &content)) {
166     char s[content.size() + 1];
167     if (sscanf(content.c_str(), "Linux version %s", s) == 1) {
168       return s;
169     }
170   }
171   PLOG(FATAL) << "can't read linux version";
172   return "";
173 }
174
175 static void GetAllModuleFiles(const std::string& path,
176                               std::unordered_map<std::string, std::string>* module_file_map) {
177   std::vector<std::string> files;
178   std::vector<std::string> subdirs;
179   GetEntriesInDir(path, &files, &subdirs);
180   for (auto& name : files) {
181     if (android::base::EndsWith(name, ".ko")) {
182       std::string module_name = name.substr(0, name.size() - 3);
183       std::replace(module_name.begin(), module_name.end(), '-', '_');
184       module_file_map->insert(std::make_pair(module_name, path + name));
185     }
186   }
187   for (auto& name : subdirs) {
188     GetAllModuleFiles(path + "/" + name, module_file_map);
189   }
190 }
191
192 static std::vector<ModuleMmap> GetModulesInUse() {
193   // TODO: There is no /proc/modules or /lib/modules on Android, find methods work on it.
194   std::vector<ModuleMmap> module_mmaps = GetLoadedModules();
195   std::string linux_version = GetLinuxVersion();
196   std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
197   std::unordered_map<std::string, std::string> module_file_map;
198   GetAllModuleFiles(module_dirpath, &module_file_map);
199   for (auto& module : module_mmaps) {
200     auto it = module_file_map.find(module.name);
201     if (it != module_file_map.end()) {
202       module.filepath = it->second;
203     }
204   }
205   return module_mmaps;
206 }
207
208 bool GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<ModuleMmap>* module_mmaps) {
209   if (!FindStartOfKernelSymbol("/proc/kallsyms", &kernel_mmap->start_addr)) {
210     LOG(DEBUG) << "call FindStartOfKernelSymbol() failed";
211     return false;
212   }
213   if (!FindKernelFunctionSymbol("/proc/kallsyms", "_text", &kernel_mmap->pgoff)) {
214     LOG(DEBUG) << "call FindKernelFunctionSymbol() failed";
215     return false;
216   }
217   kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
218   *module_mmaps = GetModulesInUse();
219   if (module_mmaps->size() == 0) {
220     kernel_mmap->len = ULLONG_MAX - kernel_mmap->start_addr;
221   } else {
222     std::sort(
223         module_mmaps->begin(), module_mmaps->end(),
224         [](const ModuleMmap& m1, const ModuleMmap& m2) { return m1.start_addr < m2.start_addr; });
225     CHECK_LE(kernel_mmap->start_addr, (*module_mmaps)[0].start_addr);
226     // When not having enough privilege, all addresses are read as 0.
227     if (kernel_mmap->start_addr == (*module_mmaps)[0].start_addr) {
228       kernel_mmap->len = 0;
229     } else {
230       kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
231     }
232     for (size_t i = 0; i + 1 < module_mmaps->size(); ++i) {
233       if ((*module_mmaps)[i].start_addr == (*module_mmaps)[i + 1].start_addr) {
234         (*module_mmaps)[i].len = 0;
235       } else {
236         (*module_mmaps)[i].len =
237             (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
238       }
239     }
240     module_mmaps->back().len = ULLONG_MAX - module_mmaps->back().start_addr;
241   }
242   return true;
243 }
244
245 static bool StringToPid(const std::string& s, pid_t* pid) {
246   char* endptr;
247   *pid = static_cast<pid_t>(strtol(s.c_str(), &endptr, 10));
248   return *endptr == '\0';
249 }
250
251 static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
252   FILE* fp = fopen(status_file.c_str(), "re");
253   if (fp == nullptr) {
254     return false;
255   }
256   bool read_comm = false;
257   bool read_tgid = false;
258   LineReader reader(fp);
259   char* line;
260   while ((line = reader.ReadLine()) != nullptr) {
261     char s[reader.MaxLineSize()];
262     if (sscanf(line, "Name:%s", s) == 1) {
263       *comm = s;
264       read_comm = true;
265     } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
266       read_tgid = true;
267     }
268     if (read_comm && read_tgid) {
269       return true;
270     }
271   }
272   return false;
273 }
274
275 static bool GetThreadComm(pid_t pid, std::vector<ThreadComm>* thread_comms) {
276   std::string task_dirname = android::base::StringPrintf("/proc/%d/task", pid);
277   std::vector<std::string> subdirs;
278   GetEntriesInDir(task_dirname, nullptr, &subdirs);
279   for (auto& name : subdirs) {
280     pid_t tid;
281     if (!StringToPid(name, &tid)) {
282       continue;
283     }
284     std::string status_file = task_dirname + "/" + name + "/status";
285     std::string comm;
286     pid_t tgid;
287     if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
288       return false;
289     }
290     ThreadComm thread;
291     thread.tid = tid;
292     thread.tgid = tgid;
293     thread.comm = comm;
294     thread.is_process = (tid == pid);
295     thread_comms->push_back(thread);
296   }
297   return true;
298 }
299
300 bool GetThreadComms(std::vector<ThreadComm>* thread_comms) {
301   thread_comms->clear();
302   std::vector<std::string> subdirs;
303   GetEntriesInDir("/proc", nullptr, &subdirs);
304   for (auto& name : subdirs) {
305     pid_t pid;
306     if (!StringToPid(name, &pid)) {
307       continue;
308     }
309     if (!GetThreadComm(pid, thread_comms)) {
310       return false;
311     }
312   }
313   return true;
314 }
315
316 bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
317   std::string map_file = android::base::StringPrintf("/proc/%d/maps", pid);
318   FILE* fp = fopen(map_file.c_str(), "re");
319   if (fp == nullptr) {
320     PLOG(DEBUG) << "can't open file " << map_file;
321     return false;
322   }
323   thread_mmaps->clear();
324   LineReader reader(fp);
325   char* line;
326   while ((line = reader.ReadLine()) != nullptr) {
327     // Parse line like: 00400000-00409000 r-xp 00000000 fc:00 426998  /usr/lib/gvfs/gvfsd-http
328     uint64_t start_addr, end_addr, pgoff;
329     char type[reader.MaxLineSize()];
330     char execname[reader.MaxLineSize()];
331     strcpy(execname, "");
332     if (sscanf(line, "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " %*x:%*x %*u %s\n", &start_addr,
333                &end_addr, type, &pgoff, execname) < 4) {
334       continue;
335     }
336     if (strcmp(execname, "") == 0) {
337       strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
338     }
339     ThreadMmap thread;
340     thread.start_addr = start_addr;
341     thread.len = end_addr - start_addr;
342     thread.pgoff = pgoff;
343     thread.name = execname;
344     thread.executable = (type[2] == 'x');
345     thread_mmaps->push_back(thread);
346   }
347   return true;
348 }