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/parseint.h>
31 #include <android-base/strings.h>
32 #include <android-base/stringprintf.h>
39 LineReader(FILE* fp) : fp_(fp), buf_(nullptr), bufsize_(0) {
48 if (getline(&buf_, &bufsize_, fp_) != -1) {
54 size_t MaxLineSize() {
64 std::vector<int> GetOnlineCpus() {
65 std::vector<int> result;
66 FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
68 PLOG(ERROR) << "can't open online cpu information";
72 LineReader reader(fp);
74 if ((line = reader.ReadLine()) != nullptr) {
75 result = GetCpusFromString(line);
77 CHECK(!result.empty()) << "can't get online cpu information";
81 std::vector<int> GetCpusFromString(const std::string& s) {
82 std::set<int> cpu_set;
83 bool have_dash = false;
84 const char* p = s.c_str();
88 // Parse line like: 0,1-3, 5, 7-8
89 while ((cpu = strtol(p, &endp, 10)) != 0 || endp != p) {
90 if (have_dash && !cpu_set.empty()) {
91 for (int t = last_cpu + 1; t < cpu; ++t) {
99 while (!isdigit(*p) && *p != '\0') {
106 return std::vector<int>(cpu_set.begin(), cpu_set.end());
109 bool ProcessKernelSymbols(const std::string& symbol_file,
110 std::function<bool(const KernelSymbol&)> callback) {
111 FILE* fp = fopen(symbol_file.c_str(), "re");
113 PLOG(ERROR) << "failed to open file " << symbol_file;
116 LineReader reader(fp);
118 while ((line = reader.ReadLine()) != nullptr) {
119 // Parse line like: ffffffffa005c4e4 d __warned.41698 [libsas]
120 char name[reader.MaxLineSize()];
121 char module[reader.MaxLineSize()];
125 if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
129 size_t module_len = strlen(module);
130 if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
131 module[module_len - 1] = '\0';
132 symbol.module = &module[1];
134 symbol.module = nullptr;
137 if (callback(symbol)) {
144 static std::vector<KernelMmap> GetLoadedModules() {
145 std::vector<KernelMmap> result;
146 FILE* fp = fopen("/proc/modules", "re");
148 // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
149 PLOG(DEBUG) << "failed to open file /proc/modules";
152 LineReader reader(fp);
154 while ((line = reader.ReadLine()) != nullptr) {
155 // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
156 char name[reader.MaxLineSize()];
158 if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
161 map.start_addr = addr;
162 result.push_back(map);
168 static std::string GetLinuxVersion() {
170 if (android::base::ReadFileToString("/proc/version", &content)) {
171 char s[content.size() + 1];
172 if (sscanf(content.c_str(), "Linux version %s", s) == 1) {
176 PLOG(FATAL) << "can't read linux version";
180 static void GetAllModuleFiles(const std::string& path,
181 std::unordered_map<std::string, std::string>* module_file_map) {
182 std::vector<std::string> files;
183 std::vector<std::string> subdirs;
184 GetEntriesInDir(path, &files, &subdirs);
185 for (auto& name : files) {
186 if (android::base::EndsWith(name, ".ko")) {
187 std::string module_name = name.substr(0, name.size() - 3);
188 std::replace(module_name.begin(), module_name.end(), '-', '_');
189 module_file_map->insert(std::make_pair(module_name, path + "/" + name));
192 for (auto& name : subdirs) {
193 GetAllModuleFiles(path + "/" + name, module_file_map);
197 static std::vector<KernelMmap> GetModulesInUse() {
198 // TODO: There is no /proc/modules or /lib/modules on Android, find methods work on it.
199 std::vector<KernelMmap> module_mmaps = GetLoadedModules();
200 std::string linux_version = GetLinuxVersion();
201 std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
202 std::unordered_map<std::string, std::string> module_file_map;
203 GetAllModuleFiles(module_dirpath, &module_file_map);
204 for (auto& module : module_mmaps) {
205 auto it = module_file_map.find(module.name);
206 if (it != module_file_map.end()) {
207 module.filepath = it->second;
213 void GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<KernelMmap>* module_mmaps) {
214 kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
215 kernel_mmap->start_addr = 0;
216 kernel_mmap->filepath = kernel_mmap->name;
217 *module_mmaps = GetModulesInUse();
218 for (auto& map : *module_mmaps) {
219 if (map.filepath.empty()) {
220 map.filepath = "[" + map.name + "]";
224 if (module_mmaps->size() == 0) {
225 kernel_mmap->len = std::numeric_limits<unsigned long long>::max() - kernel_mmap->start_addr;
228 module_mmaps->begin(), module_mmaps->end(),
229 [](const KernelMmap& m1, const KernelMmap& m2) { return m1.start_addr < m2.start_addr; });
230 // When not having enough privilege, all addresses are read as 0.
231 if (kernel_mmap->start_addr == (*module_mmaps)[0].start_addr) {
232 kernel_mmap->len = 0;
234 kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
236 for (size_t i = 0; i + 1 < module_mmaps->size(); ++i) {
237 if ((*module_mmaps)[i].start_addr == (*module_mmaps)[i + 1].start_addr) {
238 (*module_mmaps)[i].len = 0;
240 (*module_mmaps)[i].len =
241 (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
244 module_mmaps->back().len =
245 std::numeric_limits<unsigned long long>::max() - module_mmaps->back().start_addr;
249 static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
250 FILE* fp = fopen(status_file.c_str(), "re");
254 bool read_comm = false;
255 bool read_tgid = false;
256 LineReader reader(fp);
258 while ((line = reader.ReadLine()) != nullptr) {
259 char s[reader.MaxLineSize()];
260 if (sscanf(line, "Name:%s", s) == 1) {
263 } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
266 if (read_comm && read_tgid) {
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 (const auto& name : subdirs) {
280 if (!android::base::ParseInt(name.c_str(), &tid, 0)) {
283 result.push_back(tid);
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);
294 // It is possible that the process or thread exited before we can read its status.
295 if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
303 thread_comms->push_back(thread);
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) {
314 if (!android::base::ParseInt(name.c_str(), &pid, 0)) {
317 if (!GetThreadComm(pid, thread_comms)) {
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");
328 PLOG(DEBUG) << "can't open file " << map_file;
331 thread_mmaps->clear();
332 LineReader reader(fp);
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) {
344 if (strcmp(execname, "") == 0) {
345 strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
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);
358 bool GetKernelBuildId(BuildId* build_id) {
359 return GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
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);
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 (const auto& s : strs) {
371 if (!android::base::ParseInt(s.c_str(), &pid, 0)) {
372 LOG(ERROR) << "Invalid pid '" << s << "'";
375 std::vector<pid_t> tids = GetThreadsInProcess(pid);
377 LOG(ERROR) << "Non existing process '" << pid << "'";
380 tid_set->insert(tids.begin(), tids.end());
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 (const auto& s : strs) {
389 if (!android::base::ParseInt(s.c_str(), &tid, 0)) {
390 LOG(ERROR) << "Invalid tid '" << s << "'";
393 if (!IsDir(android::base::StringPrintf("/proc/%d", tid))) {
394 LOG(ERROR) << "Non existing thread '" << tid << "'";
397 tid_set->insert(tid);
402 bool GetExecPath(std::string* exec_path) {
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";
409 path[path_len] = '\0';