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"
22 #include <unordered_map>
25 #include <base/file.h>
26 #include <base/logging.h>
27 #include <base/strings.h>
28 #include <base/stringprintf.h>
32 std::vector<int> GetOnlineCpus() {
33 std::vector<int> result;
34 FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
36 PLOG(ERROR) << "can't open online cpu information";
40 LineReader reader(fp);
42 if ((line = reader.ReadLine()) != nullptr) {
43 result = GetOnlineCpusFromString(line);
45 CHECK(!result.empty()) << "can't get online cpu information";
49 std::vector<int> GetOnlineCpusFromString(const std::string& s) {
50 std::vector<int> result;
51 bool have_dash = false;
52 const char* p = s.c_str();
55 // Parse line like: 0,1-3, 5, 7-8
56 while ((cpu = strtol(p, &endp, 10)) != 0 || endp != p) {
57 if (have_dash && result.size() > 0) {
58 for (int t = result.back() + 1; t < cpu; ++t) {
63 result.push_back(cpu);
65 while (!isdigit(*p) && *p != '\0') {
75 bool ProcessKernelSymbols(const std::string& symbol_file,
76 std::function<bool(const KernelSymbol&)> callback) {
77 FILE* fp = fopen(symbol_file.c_str(), "re");
79 PLOG(ERROR) << "failed to open file " << symbol_file;
82 LineReader reader(fp);
84 while ((line = reader.ReadLine()) != nullptr) {
85 // Parse line like: ffffffffa005c4e4 d __warned.41698 [libsas]
86 char name[reader.MaxLineSize()];
87 char module[reader.MaxLineSize()];
91 if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
95 size_t module_len = strlen(module);
96 if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
97 module[module_len - 1] = '\0';
98 symbol.module = &module[1];
100 symbol.module = nullptr;
103 if (callback(symbol)) {
110 static bool FindStartOfKernelSymbolCallback(const KernelSymbol& symbol, uint64_t* start_addr) {
111 if (symbol.module == nullptr) {
112 *start_addr = symbol.addr;
118 static bool FindStartOfKernelSymbol(const std::string& symbol_file, uint64_t* start_addr) {
119 return ProcessKernelSymbols(
120 symbol_file, std::bind(&FindStartOfKernelSymbolCallback, std::placeholders::_1, start_addr));
123 static bool FindKernelFunctionSymbolCallback(const KernelSymbol& symbol, const std::string& name,
125 if ((symbol.type == 'T' || symbol.type == 'W' || symbol.type == 'A') &&
126 symbol.module == nullptr && name == symbol.name) {
133 static bool FindKernelFunctionSymbol(const std::string& symbol_file, const std::string& name,
135 return ProcessKernelSymbols(
136 symbol_file, std::bind(&FindKernelFunctionSymbolCallback, std::placeholders::_1, name, addr));
139 std::vector<ModuleMmap> GetLoadedModules() {
140 std::vector<ModuleMmap> result;
141 FILE* fp = fopen("/proc/modules", "re");
143 // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
144 PLOG(DEBUG) << "failed to open file /proc/modules";
147 LineReader reader(fp);
149 while ((line = reader.ReadLine()) != nullptr) {
150 // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
151 char name[reader.MaxLineSize()];
153 if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
156 map.start_addr = addr;
157 result.push_back(map);
163 static std::string GetLinuxVersion() {
165 if (android::base::ReadFileToString("/proc/version", &content)) {
166 char s[content.size() + 1];
167 if (sscanf(content.c_str(), "Linux version %s", s) == 1) {
171 PLOG(FATAL) << "can't read linux version";
175 static void GetAllModuleFiles(const std::string& path,
176 std::unordered_map<std::string, std::string>* module_file_map) {
177 std::vector<std::string> files;
178 std::vector<std::string> subdirs;
179 GetEntriesInDir(path, &files, &subdirs);
180 for (auto& name : files) {
181 if (android::base::EndsWith(name, ".ko")) {
182 std::string module_name = name.substr(0, name.size() - 3);
183 std::replace(module_name.begin(), module_name.end(), '-', '_');
184 module_file_map->insert(std::make_pair(module_name, path + name));
187 for (auto& name : subdirs) {
188 GetAllModuleFiles(path + "/" + name, module_file_map);
192 static std::vector<ModuleMmap> GetModulesInUse() {
193 // TODO: There is no /proc/modules or /lib/modules on Android, find methods work on it.
194 std::vector<ModuleMmap> module_mmaps = GetLoadedModules();
195 std::string linux_version = GetLinuxVersion();
196 std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
197 std::unordered_map<std::string, std::string> module_file_map;
198 GetAllModuleFiles(module_dirpath, &module_file_map);
199 for (auto& module : module_mmaps) {
200 auto it = module_file_map.find(module.name);
201 if (it != module_file_map.end()) {
202 module.filepath = it->second;
208 bool GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<ModuleMmap>* module_mmaps) {
209 if (!FindStartOfKernelSymbol("/proc/kallsyms", &kernel_mmap->start_addr)) {
210 LOG(DEBUG) << "call FindStartOfKernelSymbol() failed";
213 if (!FindKernelFunctionSymbol("/proc/kallsyms", "_text", &kernel_mmap->pgoff)) {
214 LOG(DEBUG) << "call FindKernelFunctionSymbol() failed";
217 kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
218 *module_mmaps = GetModulesInUse();
219 if (module_mmaps->size() == 0) {
220 kernel_mmap->len = ULLONG_MAX - kernel_mmap->start_addr;
223 module_mmaps->begin(), module_mmaps->end(),
224 [](const ModuleMmap& m1, const ModuleMmap& m2) { return m1.start_addr < m2.start_addr; });
225 CHECK_LE(kernel_mmap->start_addr, (*module_mmaps)[0].start_addr);
226 // When not having enough privilege, all addresses are read as 0.
227 if (kernel_mmap->start_addr == (*module_mmaps)[0].start_addr) {
228 kernel_mmap->len = 0;
230 kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
232 for (size_t i = 0; i + 1 < module_mmaps->size(); ++i) {
233 if ((*module_mmaps)[i].start_addr == (*module_mmaps)[i + 1].start_addr) {
234 (*module_mmaps)[i].len = 0;
236 (*module_mmaps)[i].len =
237 (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
240 module_mmaps->back().len = ULLONG_MAX - module_mmaps->back().start_addr;
245 static bool StringToPid(const std::string& s, pid_t* pid) {
247 *pid = static_cast<pid_t>(strtol(s.c_str(), &endptr, 10));
248 return *endptr == '\0';
251 static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
252 FILE* fp = fopen(status_file.c_str(), "re");
256 bool read_comm = false;
257 bool read_tgid = false;
258 LineReader reader(fp);
260 while ((line = reader.ReadLine()) != nullptr) {
261 char s[reader.MaxLineSize()];
262 if (sscanf(line, "Name:%s", s) == 1) {
265 } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
268 if (read_comm && read_tgid) {
275 static bool GetThreadComm(pid_t pid, std::vector<ThreadComm>* thread_comms) {
276 std::string task_dirname = android::base::StringPrintf("/proc/%d/task", pid);
277 std::vector<std::string> subdirs;
278 GetEntriesInDir(task_dirname, nullptr, &subdirs);
279 for (auto& name : subdirs) {
281 if (!StringToPid(name, &tid)) {
284 std::string status_file = task_dirname + "/" + name + "/status";
287 if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
294 thread.is_process = (tid == pid);
295 thread_comms->push_back(thread);
300 bool GetThreadComms(std::vector<ThreadComm>* thread_comms) {
301 thread_comms->clear();
302 std::vector<std::string> subdirs;
303 GetEntriesInDir("/proc", nullptr, &subdirs);
304 for (auto& name : subdirs) {
306 if (!StringToPid(name, &pid)) {
309 if (!GetThreadComm(pid, thread_comms)) {
316 bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
317 std::string map_file = android::base::StringPrintf("/proc/%d/maps", pid);
318 FILE* fp = fopen(map_file.c_str(), "re");
320 PLOG(DEBUG) << "can't open file " << map_file;
323 thread_mmaps->clear();
324 LineReader reader(fp);
326 while ((line = reader.ReadLine()) != nullptr) {
327 // Parse line like: 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
328 uint64_t start_addr, end_addr, pgoff;
329 char type[reader.MaxLineSize()];
330 char execname[reader.MaxLineSize()];
331 strcpy(execname, "");
332 if (sscanf(line, "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " %*x:%*x %*u %s\n", &start_addr,
333 &end_addr, type, &pgoff, execname) < 4) {
336 if (strcmp(execname, "") == 0) {
337 strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
340 thread.start_addr = start_addr;
341 thread.len = end_addr - start_addr;
342 thread.pgoff = pgoff;
343 thread.name = execname;
344 thread.executable = (type[2] == 'x');
345 thread_mmaps->push_back(thread);