blob: 8b39881d0d3a3a152a72908032bcf5e3212e523e [file] [log] [blame]
Yabin Cui323e9452015-04-20 18:07:17 -07001/*
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
Yabin Cui7d59bb42015-05-04 20:27:57 -070019#include <inttypes.h>
20#include <stdio.h>
Yabin Cui323e9452015-04-20 18:07:17 -070021#include <stdlib.h>
Yabin Cuic8485602015-08-20 15:04:39 -070022
23#include <limits>
Yabin Cuicb4c17e2015-10-26 16:15:29 -070024#include <set>
Yabin Cui7d59bb42015-05-04 20:27:57 -070025#include <unordered_map>
Yabin Cui323e9452015-04-20 18:07:17 -070026#include <vector>
27
Elliott Hughes66dd09e2015-12-04 14:00:57 -080028#include <android-base/file.h>
29#include <android-base/logging.h>
Yabin Cui569f64a2016-02-05 17:32:08 -080030#include <android-base/parseint.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080031#include <android-base/strings.h>
32#include <android-base/stringprintf.h>
Yabin Cui323e9452015-04-20 18:07:17 -070033
Yabin Cui8f622512015-05-05 19:58:07 -070034#include "read_elf.h"
Yabin Cui323e9452015-04-20 18:07:17 -070035#include "utils.h"
36
Yabin Cuiffaa9122016-01-15 15:25:48 -080037class LineReader {
38 public:
39 LineReader(FILE* fp) : fp_(fp), buf_(nullptr), bufsize_(0) {
40 }
41
42 ~LineReader() {
43 free(buf_);
44 fclose(fp_);
45 }
46
47 char* ReadLine() {
48 if (getline(&buf_, &bufsize_, fp_) != -1) {
49 return buf_;
50 }
51 return nullptr;
52 }
53
54 size_t MaxLineSize() {
55 return bufsize_;
56 }
57
58 private:
59 FILE* fp_;
60 char* buf_;
61 size_t bufsize_;
62};
63
Yabin Cui323e9452015-04-20 18:07:17 -070064std::vector<int> GetOnlineCpus() {
65 std::vector<int> result;
66 FILE* fp = fopen("/sys/devices/system/cpu/online", "re");
67 if (fp == nullptr) {
68 PLOG(ERROR) << "can't open online cpu information";
69 return result;
70 }
71
72 LineReader reader(fp);
73 char* line;
74 if ((line = reader.ReadLine()) != nullptr) {
Yabin Cuicb4c17e2015-10-26 16:15:29 -070075 result = GetCpusFromString(line);
Yabin Cui323e9452015-04-20 18:07:17 -070076 }
77 CHECK(!result.empty()) << "can't get online cpu information";
78 return result;
79}
80
Yabin Cuicb4c17e2015-10-26 16:15:29 -070081std::vector<int> GetCpusFromString(const std::string& s) {
82 std::set<int> cpu_set;
Yabin Cui323e9452015-04-20 18:07:17 -070083 bool have_dash = false;
84 const char* p = s.c_str();
85 char* endp;
Yabin Cuicb4c17e2015-10-26 16:15:29 -070086 int last_cpu;
Yabin Cui323e9452015-04-20 18:07:17 -070087 long cpu;
88 // Parse line like: 0,1-3, 5, 7-8
89 while ((cpu = strtol(p, &endp, 10)) != 0 || endp != p) {
Yabin Cuicb4c17e2015-10-26 16:15:29 -070090 if (have_dash && !cpu_set.empty()) {
91 for (int t = last_cpu + 1; t < cpu; ++t) {
92 cpu_set.insert(t);
Yabin Cui323e9452015-04-20 18:07:17 -070093 }
94 }
95 have_dash = false;
Yabin Cuicb4c17e2015-10-26 16:15:29 -070096 cpu_set.insert(cpu);
97 last_cpu = cpu;
Yabin Cui323e9452015-04-20 18:07:17 -070098 p = endp;
99 while (!isdigit(*p) && *p != '\0') {
100 if (*p == '-') {
101 have_dash = true;
102 }
103 ++p;
104 }
105 }
Yabin Cuicb4c17e2015-10-26 16:15:29 -0700106 return std::vector<int>(cpu_set.begin(), cpu_set.end());
Yabin Cui323e9452015-04-20 18:07:17 -0700107}
Yabin Cui7d59bb42015-05-04 20:27:57 -0700108
109bool ProcessKernelSymbols(const std::string& symbol_file,
110 std::function<bool(const KernelSymbol&)> callback) {
111 FILE* fp = fopen(symbol_file.c_str(), "re");
112 if (fp == nullptr) {
113 PLOG(ERROR) << "failed to open file " << symbol_file;
114 return false;
115 }
116 LineReader reader(fp);
117 char* line;
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()];
122 strcpy(module, "");
123
124 KernelSymbol symbol;
125 if (sscanf(line, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module) < 3) {
126 continue;
127 }
128 symbol.name = name;
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];
133 } else {
134 symbol.module = nullptr;
135 }
136
137 if (callback(symbol)) {
138 return true;
139 }
140 }
141 return false;
142}
143
144static bool FindStartOfKernelSymbolCallback(const KernelSymbol& symbol, uint64_t* start_addr) {
145 if (symbol.module == nullptr) {
146 *start_addr = symbol.addr;
147 return true;
148 }
149 return false;
150}
151
152static bool FindStartOfKernelSymbol(const std::string& symbol_file, uint64_t* start_addr) {
153 return ProcessKernelSymbols(
154 symbol_file, std::bind(&FindStartOfKernelSymbolCallback, std::placeholders::_1, start_addr));
155}
156
157static bool FindKernelFunctionSymbolCallback(const KernelSymbol& symbol, const std::string& name,
158 uint64_t* addr) {
159 if ((symbol.type == 'T' || symbol.type == 'W' || symbol.type == 'A') &&
160 symbol.module == nullptr && name == symbol.name) {
161 *addr = symbol.addr;
162 return true;
163 }
164 return false;
165}
166
167static bool FindKernelFunctionSymbol(const std::string& symbol_file, const std::string& name,
168 uint64_t* addr) {
169 return ProcessKernelSymbols(
170 symbol_file, std::bind(&FindKernelFunctionSymbolCallback, std::placeholders::_1, name, addr));
171}
172
173std::vector<ModuleMmap> GetLoadedModules() {
174 std::vector<ModuleMmap> result;
175 FILE* fp = fopen("/proc/modules", "re");
176 if (fp == nullptr) {
177 // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
178 PLOG(DEBUG) << "failed to open file /proc/modules";
179 return result;
180 }
181 LineReader reader(fp);
182 char* line;
183 while ((line = reader.ReadLine()) != nullptr) {
184 // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
185 char name[reader.MaxLineSize()];
186 uint64_t addr;
187 if (sscanf(line, "%s%*lu%*u%*s%*s 0x%" PRIx64, name, &addr) == 2) {
188 ModuleMmap map;
189 map.name = name;
190 map.start_addr = addr;
191 result.push_back(map);
192 }
193 }
194 return result;
195}
196
197static std::string GetLinuxVersion() {
198 std::string content;
199 if (android::base::ReadFileToString("/proc/version", &content)) {
200 char s[content.size() + 1];
201 if (sscanf(content.c_str(), "Linux version %s", s) == 1) {
202 return s;
203 }
204 }
205 PLOG(FATAL) << "can't read linux version";
206 return "";
207}
208
209static void GetAllModuleFiles(const std::string& path,
210 std::unordered_map<std::string, std::string>* module_file_map) {
211 std::vector<std::string> files;
212 std::vector<std::string> subdirs;
213 GetEntriesInDir(path, &files, &subdirs);
214 for (auto& name : files) {
215 if (android::base::EndsWith(name, ".ko")) {
216 std::string module_name = name.substr(0, name.size() - 3);
217 std::replace(module_name.begin(), module_name.end(), '-', '_');
Yabin Cuiec12ed92015-06-08 10:38:10 -0700218 module_file_map->insert(std::make_pair(module_name, path + "/" + name));
Yabin Cui7d59bb42015-05-04 20:27:57 -0700219 }
220 }
221 for (auto& name : subdirs) {
222 GetAllModuleFiles(path + "/" + name, module_file_map);
223 }
224}
225
226static std::vector<ModuleMmap> GetModulesInUse() {
227 // TODO: There is no /proc/modules or /lib/modules on Android, find methods work on it.
228 std::vector<ModuleMmap> module_mmaps = GetLoadedModules();
229 std::string linux_version = GetLinuxVersion();
230 std::string module_dirpath = "/lib/modules/" + linux_version + "/kernel";
231 std::unordered_map<std::string, std::string> module_file_map;
232 GetAllModuleFiles(module_dirpath, &module_file_map);
233 for (auto& module : module_mmaps) {
234 auto it = module_file_map.find(module.name);
235 if (it != module_file_map.end()) {
236 module.filepath = it->second;
237 }
238 }
239 return module_mmaps;
240}
241
242bool GetKernelAndModuleMmaps(KernelMmap* kernel_mmap, std::vector<ModuleMmap>* module_mmaps) {
243 if (!FindStartOfKernelSymbol("/proc/kallsyms", &kernel_mmap->start_addr)) {
244 LOG(DEBUG) << "call FindStartOfKernelSymbol() failed";
245 return false;
246 }
247 if (!FindKernelFunctionSymbol("/proc/kallsyms", "_text", &kernel_mmap->pgoff)) {
248 LOG(DEBUG) << "call FindKernelFunctionSymbol() failed";
249 return false;
250 }
251 kernel_mmap->name = DEFAULT_KERNEL_MMAP_NAME;
252 *module_mmaps = GetModulesInUse();
253 if (module_mmaps->size() == 0) {
Yabin Cuic8485602015-08-20 15:04:39 -0700254 kernel_mmap->len = std::numeric_limits<unsigned long long>::max() - kernel_mmap->start_addr;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700255 } else {
256 std::sort(
257 module_mmaps->begin(), module_mmaps->end(),
258 [](const ModuleMmap& m1, const ModuleMmap& m2) { return m1.start_addr < m2.start_addr; });
259 CHECK_LE(kernel_mmap->start_addr, (*module_mmaps)[0].start_addr);
260 // When not having enough privilege, all addresses are read as 0.
261 if (kernel_mmap->start_addr == (*module_mmaps)[0].start_addr) {
262 kernel_mmap->len = 0;
263 } else {
264 kernel_mmap->len = (*module_mmaps)[0].start_addr - kernel_mmap->start_addr - 1;
265 }
266 for (size_t i = 0; i + 1 < module_mmaps->size(); ++i) {
267 if ((*module_mmaps)[i].start_addr == (*module_mmaps)[i + 1].start_addr) {
268 (*module_mmaps)[i].len = 0;
269 } else {
270 (*module_mmaps)[i].len =
271 (*module_mmaps)[i + 1].start_addr - (*module_mmaps)[i].start_addr - 1;
272 }
273 }
Yabin Cuic8485602015-08-20 15:04:39 -0700274 module_mmaps->back().len =
275 std::numeric_limits<unsigned long long>::max() - module_mmaps->back().start_addr;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700276 }
277 return true;
278}
279
Yabin Cui7d59bb42015-05-04 20:27:57 -0700280static bool ReadThreadNameAndTgid(const std::string& status_file, std::string* comm, pid_t* tgid) {
281 FILE* fp = fopen(status_file.c_str(), "re");
282 if (fp == nullptr) {
283 return false;
284 }
285 bool read_comm = false;
286 bool read_tgid = false;
287 LineReader reader(fp);
288 char* line;
289 while ((line = reader.ReadLine()) != nullptr) {
290 char s[reader.MaxLineSize()];
291 if (sscanf(line, "Name:%s", s) == 1) {
292 *comm = s;
293 read_comm = true;
294 } else if (sscanf(line, "Tgid:%d", tgid) == 1) {
295 read_tgid = true;
296 }
297 if (read_comm && read_tgid) {
298 return true;
299 }
300 }
301 return false;
302}
303
Yabin Cuib032de72015-06-17 21:15:09 -0700304static std::vector<pid_t> GetThreadsInProcess(pid_t pid) {
305 std::vector<pid_t> result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700306 std::string task_dirname = android::base::StringPrintf("/proc/%d/task", pid);
307 std::vector<std::string> subdirs;
308 GetEntriesInDir(task_dirname, nullptr, &subdirs);
Yabin Cui569f64a2016-02-05 17:32:08 -0800309 for (const auto& name : subdirs) {
Yabin Cui38e573e2015-08-06 11:25:09 -0700310 int tid;
Yabin Cui569f64a2016-02-05 17:32:08 -0800311 if (!android::base::ParseInt(name.c_str(), &tid, 0)) {
Yabin Cui7d59bb42015-05-04 20:27:57 -0700312 continue;
313 }
Yabin Cuib032de72015-06-17 21:15:09 -0700314 result.push_back(tid);
315 }
316 return result;
317}
318
319static bool GetThreadComm(pid_t pid, std::vector<ThreadComm>* thread_comms) {
320 std::vector<pid_t> tids = GetThreadsInProcess(pid);
321 for (auto& tid : tids) {
322 std::string status_file = android::base::StringPrintf("/proc/%d/task/%d/status", pid, tid);
Yabin Cui7d59bb42015-05-04 20:27:57 -0700323 std::string comm;
324 pid_t tgid;
Yabin Cuib032de72015-06-17 21:15:09 -0700325 // It is possible that the process or thread exited before we can read its status.
Yabin Cui7d59bb42015-05-04 20:27:57 -0700326 if (!ReadThreadNameAndTgid(status_file, &comm, &tgid)) {
Yabin Cuib032de72015-06-17 21:15:09 -0700327 continue;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700328 }
Yabin Cui41d4ba92015-06-22 12:27:58 -0700329 CHECK_EQ(pid, tgid);
Yabin Cui7d59bb42015-05-04 20:27:57 -0700330 ThreadComm thread;
331 thread.tid = tid;
Yabin Cui41d4ba92015-06-22 12:27:58 -0700332 thread.pid = pid;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700333 thread.comm = comm;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700334 thread_comms->push_back(thread);
335 }
336 return true;
337}
338
339bool GetThreadComms(std::vector<ThreadComm>* thread_comms) {
340 thread_comms->clear();
341 std::vector<std::string> subdirs;
342 GetEntriesInDir("/proc", nullptr, &subdirs);
343 for (auto& name : subdirs) {
Yabin Cui38e573e2015-08-06 11:25:09 -0700344 int pid;
Yabin Cui569f64a2016-02-05 17:32:08 -0800345 if (!android::base::ParseInt(name.c_str(), &pid, 0)) {
Yabin Cui7d59bb42015-05-04 20:27:57 -0700346 continue;
347 }
348 if (!GetThreadComm(pid, thread_comms)) {
349 return false;
350 }
351 }
352 return true;
353}
354
355bool GetThreadMmapsInProcess(pid_t pid, std::vector<ThreadMmap>* thread_mmaps) {
356 std::string map_file = android::base::StringPrintf("/proc/%d/maps", pid);
357 FILE* fp = fopen(map_file.c_str(), "re");
358 if (fp == nullptr) {
359 PLOG(DEBUG) << "can't open file " << map_file;
360 return false;
361 }
362 thread_mmaps->clear();
363 LineReader reader(fp);
364 char* line;
365 while ((line = reader.ReadLine()) != nullptr) {
366 // Parse line like: 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
367 uint64_t start_addr, end_addr, pgoff;
368 char type[reader.MaxLineSize()];
369 char execname[reader.MaxLineSize()];
370 strcpy(execname, "");
371 if (sscanf(line, "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " %*x:%*x %*u %s\n", &start_addr,
372 &end_addr, type, &pgoff, execname) < 4) {
373 continue;
374 }
375 if (strcmp(execname, "") == 0) {
376 strcpy(execname, DEFAULT_EXECNAME_FOR_THREAD_MMAP);
377 }
378 ThreadMmap thread;
379 thread.start_addr = start_addr;
380 thread.len = end_addr - start_addr;
381 thread.pgoff = pgoff;
382 thread.name = execname;
383 thread.executable = (type[2] == 'x');
384 thread_mmaps->push_back(thread);
385 }
386 return true;
387}
Yabin Cui8f622512015-05-05 19:58:07 -0700388
389bool GetKernelBuildId(BuildId* build_id) {
390 return GetBuildIdFromNoteFile("/sys/kernel/notes", build_id);
391}
392
393bool GetModuleBuildId(const std::string& module_name, BuildId* build_id) {
394 std::string notefile = "/sys/module/" + module_name + "/notes/.note.gnu.build-id";
395 return GetBuildIdFromNoteFile(notefile, build_id);
396}
Yabin Cuib032de72015-06-17 21:15:09 -0700397
398bool GetValidThreadsFromProcessString(const std::string& pid_str, std::set<pid_t>* tid_set) {
399 std::vector<std::string> strs = android::base::Split(pid_str, ",");
Yabin Cui569f64a2016-02-05 17:32:08 -0800400 for (const auto& s : strs) {
Yabin Cui38e573e2015-08-06 11:25:09 -0700401 int pid;
Yabin Cui569f64a2016-02-05 17:32:08 -0800402 if (!android::base::ParseInt(s.c_str(), &pid, 0)) {
Yabin Cuib032de72015-06-17 21:15:09 -0700403 LOG(ERROR) << "Invalid pid '" << s << "'";
404 return false;
405 }
406 std::vector<pid_t> tids = GetThreadsInProcess(pid);
407 if (tids.empty()) {
408 LOG(ERROR) << "Non existing process '" << pid << "'";
409 return false;
410 }
411 tid_set->insert(tids.begin(), tids.end());
412 }
413 return true;
414}
415
416bool GetValidThreadsFromThreadString(const std::string& tid_str, std::set<pid_t>* tid_set) {
417 std::vector<std::string> strs = android::base::Split(tid_str, ",");
Yabin Cui569f64a2016-02-05 17:32:08 -0800418 for (const auto& s : strs) {
Yabin Cui38e573e2015-08-06 11:25:09 -0700419 int tid;
Yabin Cui569f64a2016-02-05 17:32:08 -0800420 if (!android::base::ParseInt(s.c_str(), &tid, 0)) {
Yabin Cuib032de72015-06-17 21:15:09 -0700421 LOG(ERROR) << "Invalid tid '" << s << "'";
422 return false;
423 }
424 if (!IsDir(android::base::StringPrintf("/proc/%d", tid))) {
425 LOG(ERROR) << "Non existing thread '" << tid << "'";
426 return false;
427 }
428 tid_set->insert(tid);
429 }
430 return true;
431}
Yabin Cuid713f952015-06-23 18:50:36 -0700432
433bool GetExecPath(std::string* exec_path) {
434 char path[PATH_MAX];
435 ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
436 if (path_len <= 0 || path_len >= static_cast<ssize_t>(sizeof(path))) {
437 PLOG(ERROR) << "readlink failed";
438 return false;
439 }
440 path[path_len] = '\0';
441 *exec_path = path;
442 return true;
443}