2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "environment.h"
25 #include <unordered_map>
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/strings.h>
31 #include <android-base/stringprintf.h>
38 LineReader(FILE* fp) : fp_(fp), buf_(nullptr), bufsize_(0) {
47 if (getline(&buf_, &bufsize_, fp_) != -1) {
53 size_t MaxLineSize() {
63 std::vector<int> GetOnlineCpus() {
64 std::vector<int> result;
65 FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
67 PLOG(ERROR) << "can't open online cpu information";
71 LineReader reader(fp);
73 if ((line = reader.ReadLine()) != nullptr) {
74 result = GetCpusFromString(line);
76 CHECK(!result.empty()) << "can't get online cpu information";
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();
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) {
98 while (!isdigit(*p) && *p != '\0') {
105 return std::vector<int>(cpu_set.begin(), cpu_set.end());
108 bool ProcessKernelSymbols(const std::string& symbol_file,
109 std::function<bool(const KernelSymbol&)> callback) {
110 FILE* fp = fopen(symbol_file.c_str(), "re");
112 PLOG(ERROR) << "failed to open file " << symbol_file;
115 LineReader reader(fp);
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()];
124 if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
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];
133 symbol.module = nullptr;
136 if (callback(symbol)) {
143 static bool FindStartOfKernelSymbolCallback(const KernelSymbol& symbol, uint64_t* start_addr) {
144 if (symbol.module == nullptr) {
145 *start_addr = symbol.addr;
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));
156 static bool FindKernelFunctionSymbolCallback(const KernelSymbol& symbol, const std::string& name,
158 if ((symbol.type == 'T' || symbol.type == 'W' || symbol.type == 'A') &&
159 symbol.module == nullptr && name == symbol.name) {
166 static bool FindKernelFunctionSymbol(const std::string& symbol_file, const std::string& name,
168 return ProcessKernelSymbols(
169 symbol_file, std::bind(&FindKernelFunctionSymbolCallback, std::placeholders::_1, name, addr));
172 std::vector<ModuleMmap> GetLoadedModules() {
173 std::vector<ModuleMmap> result;
174 FILE* fp = fopen("/proc/modules", "re");
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";
180 LineReader reader(fp);
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()];
186 if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
189 map.start_addr = addr;
190 result.push_back(map);
196 static std::string GetLinuxVersion() {
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) {
204 PLOG(FATAL) << "can't read linux version";
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));
220 for (auto& name : subdirs) {
221 GetAllModuleFiles(path + "/" + name, module_file_map);
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;
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";
246 if (!FindKernelFunctionSymbol("/proc/kallsyms", "_text", &kernel_mmap->pgoff)) {
247 LOG(DEBUG) << "call FindKernelFunctionSymbol() failed";
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;
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;
263 kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
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;
269 (*module_mmaps)[i].len =
270 (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
273 module_mmaps->back().len =
274 std::numeric_limits<unsigned long long>::max() - module_mmaps->back().start_addr;
279 static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
280 FILE* fp = fopen(status_file.c_str(), "re");
284 bool read_comm = false;
285 bool read_tgid = false;
286 LineReader reader(fp);
288 while ((line = reader.ReadLine()) != nullptr) {
289 char s[reader.MaxLineSize()];
290 if (sscanf(line, "Name:%s", s) == 1) {
293 } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
296 if (read_comm && read_tgid) {
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) {
310 if (!StringToPid(name, &tid)) {
313 result.push_back(tid);
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);
324 // It is possible that the process or thread exited before we can read its status.
325 if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
333 thread_comms->push_back(thread);
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) {
344 if (!StringToPid(name, &pid)) {
347 if (!GetThreadComm(pid, thread_comms)) {
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");
358 PLOG(DEBUG) << "can't open file " << map_file;
361 thread_mmaps->clear();
362 LineReader reader(fp);
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) {
374 if (strcmp(execname, "") == 0) {
375 strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
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);
388 bool GetKernelBuildId(BuildId* build_id) {
389 return GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
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);
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) {
401 if (!StringToPid(s, &pid)) {
402 LOG(ERROR) << "Invalid pid '" << s << "'";
405 std::vector<pid_t> tids = GetThreadsInProcess(pid);
407 LOG(ERROR) << "Non existing process '" << pid << "'";
410 tid_set->insert(tids.begin(), tids.end());
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) {
419 if (!StringToPid(s, &tid)) {
420 LOG(ERROR) << "Invalid tid '" << s << "'";
423 if (!IsDir(android::base::StringPrintf("/proc/%d", tid))) {
424 LOG(ERROR) << "Non existing thread '" << tid << "'";
427 tid_set->insert(tid);
432 bool GetExecPath(std::string* exec_path) {
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";
439 path[path_len] = '\0';