OSDN Git Service

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