OSDN Git Service

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