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