OSDN Git Service

am 3033e307: (-s ours) am 47efd844: Merge "Simpleperf: separate ThreadTree from Sampl...
[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
23 #include <limits>
24 #include <unordered_map>
25 #include <vector>
26
27 #include <base/file.h>
28 #include <base/logging.h>
29 #include <base/strings.h>
30 #include <base/stringprintf.h>
31
32 #include "read_elf.h"
33 #include "utils.h"
34
35 std::vector<int> GetOnlineCpus() {
36   std::vector<int> result;
37   FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
38   if (fp == nullptr) {
39     PLOG(ERROR) << "can't open online cpu information";
40     return result;
41   }
42
43   LineReader reader(fp);
44   char* line;
45   if ((line = reader.ReadLine()) != nullptr) {
46     result = GetOnlineCpusFromString(line);
47   }
48   CHECK(!result.empty()) << "can't get online cpu information";
49   return result;
50 }
51
52 std::vector<int> GetOnlineCpusFromString(const std::string& s) {
53   std::vector<int> result;
54   bool have_dash = false;
55   const char* p = s.c_str();
56   char* endp;
57   long cpu;
58   // Parse line like: 0,1-3, 5, 7-8
59   while ((cpu = strtol(p, &endp, 10)) != 0 || endp != p) {
60     if (have_dash && result.size() > 0) {
61       for (int t = result.back() + 1; t < cpu; ++t) {
62         result.push_back(t);
63       }
64     }
65     have_dash = false;
66     result.push_back(cpu);
67     p = endp;
68     while (!isdigit(*p) && *p != '\0') {
69       if (*p == '-') {
70         have_dash = true;
71       }
72       ++p;
73     }
74   }
75   return result;
76 }
77
78 bool ProcessKernelSymbols(const std::string& symbol_file,
79                           std::function<bool(const KernelSymbol&)> callback) {
80   FILE* fp = fopen(symbol_file.c_str(), "re");
81   if (fp == nullptr) {
82     PLOG(ERROR) << "failed to open file " << symbol_file;
83     return false;
84   }
85   LineReader reader(fp);
86   char* line;
87   while ((line = reader.ReadLine()) != nullptr) {
88     // Parse line like: ffffffffa005c4e4 d __warned.41698       [libsas]
89     char name[reader.MaxLineSize()];
90     char module[reader.MaxLineSize()];
91     strcpy(module, "");
92
93     KernelSymbol symbol;
94     if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
95       continue;
96     }
97     symbol.name = name;
98     size_t module_len = strlen(module);
99     if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
100       module[module_len - 1] = '\0';
101       symbol.module = &module[1];
102     } else {
103       symbol.module = nullptr;
104     }
105
106     if (callback(symbol)) {
107       return true;
108     }
109   }
110   return false;
111 }
112
113 static bool FindStartOfKernelSymbolCallback(const KernelSymbol& symbol, uint64_t* start_addr) {
114   if (symbol.module == nullptr) {
115     *start_addr = symbol.addr;
116     return true;
117   }
118   return false;
119 }
120
121 static bool FindStartOfKernelSymbol(const std::string& symbol_file, uint64_t* start_addr) {
122   return ProcessKernelSymbols(
123       symbol_file, std::bind(&FindStartOfKernelSymbolCallback, std::placeholders::_1, start_addr));
124 }
125
126 static bool FindKernelFunctionSymbolCallback(const KernelSymbol& symbol, const std::string& name,
127                                              uint64_t* addr) {
128   if ((symbol.type == 'T' || symbol.type == 'W' || symbol.type == 'A') &&
129       symbol.module == nullptr && name == symbol.name) {
130     *addr = symbol.addr;
131     return true;
132   }
133   return false;
134 }
135
136 static bool FindKernelFunctionSymbol(const std::string& symbol_file, const std::string& name,
137                                      uint64_t* addr) {
138   return ProcessKernelSymbols(
139       symbol_file, std::bind(&FindKernelFunctionSymbolCallback, std::placeholders::_1, name, addr));
140 }
141
142 std::vector<ModuleMmap> GetLoadedModules() {
143   std::vector<ModuleMmap> result;
144   FILE* fp = fopen("/proc/modules", "re");
145   if (fp == nullptr) {
146     // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
147     PLOG(DEBUG) << "failed to open file /proc/modules";
148     return result;
149   }
150   LineReader reader(fp);
151   char* line;
152   while ((line = reader.ReadLine()) != nullptr) {
153     // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
154     char name[reader.MaxLineSize()];
155     uint64_t addr;
156     if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
157       ModuleMmap map;
158       map.name = name;
159       map.start_addr = addr;
160       result.push_back(map);
161     }
162   }
163   return result;
164 }
165
166 static std::string GetLinuxVersion() {
167   std::string content;
168   if (android::base::ReadFileToString("/proc/version", &content)) {
169     char s[content.size() + 1];
170     if (sscanf(content.c_str(), "Linux version %s", s) == 1) {
171       return s;
172     }
173   }
174   PLOG(FATAL) << "can't read linux version";
175   return "";
176 }
177
178 static void GetAllModuleFiles(const std::string& path,
179                               std::unordered_map<std::string, std::string>* module_file_map) {
180   std::vector<std::string> files;
181   std::vector<std::string> subdirs;
182   GetEntriesInDir(path, &files, &subdirs);
183   for (auto& name : files) {
184     if (android::base::EndsWith(name, ".ko")) {
185       std::string module_name = name.substr(0, name.size() - 3);
186       std::replace(module_name.begin(), module_name.end(), '-', '_');
187       module_file_map->insert(std::make_pair(module_name, path + "/" + name));
188     }
189   }
190   for (auto& name : subdirs) {
191     GetAllModuleFiles(path + "/" + name, module_file_map);
192   }
193 }
194
195 static std::vector<ModuleMmap> GetModulesInUse() {
196   // TODO: There is no /proc/modules or /lib/modules on Android, find methods work on it.
197   std::vector<ModuleMmap> module_mmaps = GetLoadedModules();
198   std::string linux_version = GetLinuxVersion();
199   std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
200   std::unordered_map<std::string, std::string> module_file_map;
201   GetAllModuleFiles(module_dirpath, &module_file_map);
202   for (auto& module : module_mmaps) {
203     auto it = module_file_map.find(module.name);
204     if (it != module_file_map.end()) {
205       module.filepath = it->second;
206     }
207   }
208   return module_mmaps;
209 }
210
211 bool GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<ModuleMmap>* module_mmaps) {
212   if (!FindStartOfKernelSymbol("/proc/kallsyms", &kernel_mmap->start_addr)) {
213     LOG(DEBUG) << "call FindStartOfKernelSymbol() failed";
214     return false;
215   }
216   if (!FindKernelFunctionSymbol("/proc/kallsyms", "_text", &kernel_mmap->pgoff)) {
217     LOG(DEBUG) << "call FindKernelFunctionSymbol() failed";
218     return false;
219   }
220   kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
221   *module_mmaps = GetModulesInUse();
222   if (module_mmaps->size() == 0) {
223     kernel_mmap->len = std::numeric_limits<unsigned long long>::max() - kernel_mmap->start_addr;
224   } else {
225     std::sort(
226         module_mmaps->begin(), module_mmaps->end(),
227         [](const ModuleMmap& m1, const ModuleMmap& m2) { return m1.start_addr < m2.start_addr; });
228     CHECK_LE(kernel_mmap->start_addr, (*module_mmaps)[0].start_addr);
229     // When not having enough privilege, all addresses are read as 0.
230     if (kernel_mmap->start_addr == (*module_mmaps)[0].start_addr) {
231       kernel_mmap->len = 0;
232     } else {
233       kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
234     }
235     for (size_t i = 0; i + 1 < module_mmaps->size(); ++i) {
236       if ((*module_mmaps)[i].start_addr == (*module_mmaps)[i + 1].start_addr) {
237         (*module_mmaps)[i].len = 0;
238       } else {
239         (*module_mmaps)[i].len =
240             (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
241       }
242     }
243     module_mmaps->back().len =
244         std::numeric_limits<unsigned long long>::max() - module_mmaps->back().start_addr;
245   }
246   return true;
247 }
248
249 static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
250   FILE* fp = fopen(status_file.c_str(), "re");
251   if (fp == nullptr) {
252     return false;
253   }
254   bool read_comm = false;
255   bool read_tgid = false;
256   LineReader reader(fp);
257   char* line;
258   while ((line = reader.ReadLine()) != nullptr) {
259     char s[reader.MaxLineSize()];
260     if (sscanf(line, "Name:%s", s) == 1) {
261       *comm = s;
262       read_comm = true;
263     } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
264       read_tgid = true;
265     }
266     if (read_comm && read_tgid) {
267       return true;
268     }
269   }
270   return false;
271 }
272
273 static std::vector<pid_t> GetThreadsInProcess(pid_t pid) {
274   std::vector<pid_t> result;
275   std::string task_dirname = android::base::StringPrintf("/proc/%d/task", pid);
276   std::vector<std::string> subdirs;
277   GetEntriesInDir(task_dirname, nullptr, &subdirs);
278   for (auto& name : subdirs) {
279     int tid;
280     if (!StringToPid(name, &tid)) {
281       continue;
282     }
283     result.push_back(tid);
284   }
285   return result;
286 }
287
288 static bool GetThreadComm(pid_t pid, std::vector<ThreadComm>* thread_comms) {
289   std::vector<pid_t> tids = GetThreadsInProcess(pid);
290   for (auto& tid : tids) {
291     std::string status_file = android::base::StringPrintf("/proc/%d/task/%d/status", pid, tid);
292     std::string comm;
293     pid_t tgid;
294     // It is possible that the process or thread exited before we can read its status.
295     if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
296       continue;
297     }
298     CHECK_EQ(pid, tgid);
299     ThreadComm thread;
300     thread.tid = tid;
301     thread.pid = pid;
302     thread.comm = comm;
303     thread_comms->push_back(thread);
304   }
305   return true;
306 }
307
308 bool GetThreadComms(std::vector<ThreadComm>* thread_comms) {
309   thread_comms->clear();
310   std::vector<std::string> subdirs;
311   GetEntriesInDir("/proc", nullptr, &subdirs);
312   for (auto& name : subdirs) {
313     int pid;
314     if (!StringToPid(name, &pid)) {
315       continue;
316     }
317     if (!GetThreadComm(pid, thread_comms)) {
318       return false;
319     }
320   }
321   return true;
322 }
323
324 bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
325   std::string map_file = android::base::StringPrintf("/proc/%d/maps", pid);
326   FILE* fp = fopen(map_file.c_str(), "re");
327   if (fp == nullptr) {
328     PLOG(DEBUG) << "can't open file " << map_file;
329     return false;
330   }
331   thread_mmaps->clear();
332   LineReader reader(fp);
333   char* line;
334   while ((line = reader.ReadLine()) != nullptr) {
335     // Parse line like: 00400000-00409000 r-xp 00000000 fc:00 426998  /usr/lib/gvfs/gvfsd-http
336     uint64_t start_addr, end_addr, pgoff;
337     char type[reader.MaxLineSize()];
338     char execname[reader.MaxLineSize()];
339     strcpy(execname, "");
340     if (sscanf(line, "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " %*x:%*x %*u %s\n", &start_addr,
341                &end_addr, type, &pgoff, execname) < 4) {
342       continue;
343     }
344     if (strcmp(execname, "") == 0) {
345       strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
346     }
347     ThreadMmap thread;
348     thread.start_addr = start_addr;
349     thread.len = end_addr - start_addr;
350     thread.pgoff = pgoff;
351     thread.name = execname;
352     thread.executable = (type[2] == 'x');
353     thread_mmaps->push_back(thread);
354   }
355   return true;
356 }
357
358 bool GetKernelBuildId(BuildId* build_id) {
359   return GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
360 }
361
362 bool GetModuleBuildId(const std::string& module_name, BuildId* build_id) {
363   std::string notefile = "/sys/module/" + module_name + "/notes/.note.gnu.build-id";
364   return GetBuildIdFromNoteFile(notefile, build_id);
365 }
366
367 bool GetValidThreadsFromProcessString(const std::string& pid_str, std::set<pid_t>* tid_set) {
368   std::vector<std::string> strs = android::base::Split(pid_str, ",");
369   for (auto& s : strs) {
370     int pid;
371     if (!StringToPid(s, &pid)) {
372       LOG(ERROR) << "Invalid pid '" << s << "'";
373       return false;
374     }
375     std::vector<pid_t> tids = GetThreadsInProcess(pid);
376     if (tids.empty()) {
377       LOG(ERROR) << "Non existing process '" << pid << "'";
378       return false;
379     }
380     tid_set->insert(tids.begin(), tids.end());
381   }
382   return true;
383 }
384
385 bool GetValidThreadsFromThreadString(const std::string& tid_str, std::set<pid_t>* tid_set) {
386   std::vector<std::string> strs = android::base::Split(tid_str, ",");
387   for (auto& s : strs) {
388     int tid;
389     if (!StringToPid(s, &tid)) {
390       LOG(ERROR) << "Invalid tid '" << s << "'";
391       return false;
392     }
393     if (!IsDir(android::base::StringPrintf("/proc/%d", tid))) {
394       LOG(ERROR) << "Non existing thread '" << tid << "'";
395       return false;
396     }
397     tid_set->insert(tid);
398   }
399   return true;
400 }
401
402 bool GetExecPath(std::string* exec_path) {
403   char path[PATH_MAX];
404   ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
405   if (path_len <= 0 || path_len >= static_cast<ssize_t>(sizeof(path))) {
406     PLOG(ERROR) << "readlink failed";
407     return false;
408   }
409   path[path_len] = '\0';
410   *exec_path = path;
411   return true;
412 }